@earlyai/cli 2.16.1 → 2.16.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +171 -19
- 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:j,createCommand:te,createArgument:M,createOption:N,CommanderError:P,InvalidArgumentError:F,InvalidOptionArgumentError:I,Command:L,Argument:ne,Option:R,Help:z}=u(s((e=>{let{Argument:t}=D(),{Command:n}=ee(),{CommanderError:r,InvalidArgumentError:i}=E(),{Help:a}=O(),{Option:o}=k();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 re=`2.16.1`,ie=s((e=>{let t=e=>e!=null,n=e=>typeof e==`object`&&!!e,r=e=>Array.isArray(e),i=e=>e instanceof Map,a=e=>e instanceof Set,o=e=>e instanceof Date,s=e=>typeof e==`number`,c=e=>typeof e==`string`,l=e=>typeof e==`boolean`,u=e=>e instanceof Error,d=e=>t(e)?c(e)||r(e)?e.length===0:i(e)||a(e)?e.size===0:o(e)?!1:n(e)?Object.keys(e).length===0:!1:!0,f=e=>u(e)?e.message:`error is not Instance of Error`,p=(e,t)=>{let n=new Set(e);for(let e of n)t.includes(e)||n.delete(e);return[...n]},m=async(e,t)=>{let n=await Promise.all(e.map(e=>t(e)));return e.filter((e,t)=>n[t])},h=(e,t)=>{let n=[];for(let r of e)n.some(e=>t(r,e))||n.push(r);return n},g=e=>[...new Set(e)],_=async e=>Promise.all(e.map(e=>new Promise((t,n)=>e().then(e=>e?t(e):n(e)).catch(e=>n(e))))).then(()=>!0).catch(e=>{if(!l(e))throw e;return e}),v=e=>e.trim().replaceAll(/([\da-z])([A-Z])/g,`$1-$2`).replaceAll(/([A-Z])([A-Z][\da-z])/g,`$1-$2`).replaceAll(/[\s_]+/g,`-`).toLowerCase(),y=e=>e.replaceAll(/[\s-]+/g,` `).split(` `).map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(``),b=e=>{let t=0;for(let n=0;n<e.length;n++){let r=e.codePointAt(n)??0;t=Math.trunc(t*31+r)}return t>>>0},x=(...e)=>{let n={};for(let r of e)for(let e in r)t(r[e])&&(n[e]=r[e]);return n},S=(e,t)=>r(e)?e.map(e=>S(e,t)):n(e)?Object.fromEntries(Object.entries(e).filter(([e])=>!t.includes(e)).map(([e,n])=>[e,S(n,t)])):e,C=(e,t)=>{let n;return(...r)=>{clearTimeout(n),n=setTimeout(()=>e(...r),t)}},w=(e,t)=>{let n=!1;return(...r)=>{n||(e(...r),n=!0,setTimeout(()=>{n=!1},t))}};var T=class{listeners=[];addListener(e){this.listeners.push(e)}notifyAll(e){for(let t of this.listeners)t(e)}clear(){this.listeners.length=0}},E=class{set=new Set;constructor(e=[]){for(let t of e)this.safeAdd(t)}safeAdd(e){return t(e)?(this.set.add(e),!0):!1}has(e){return t(e)?this.set.has(e):!1}delete(e){return t(e)?this.set.delete(e):!1}clear(){this.set.clear()}get size(){return this.set.size}values(){return this.set.values()}toSet(){return structuredClone(this.set)}[Symbol.iterator](){return this.set[Symbol.iterator]()}concatSet(e){for(let t of e)this.safeAdd(t)}};e.Observer=T,e.SafeSet=E,e.arePromiseFnsTruthy=_,e.debounce=C,e.fastHash=b,e.filterAsync=m,e.getErrorMessage=f,e.intersection=p,e.isArray=r,e.isBoolean=l,e.isDate=o,e.isDefined=t,e.isEmpty=d,e.isError=u,e.isMap=i,e.isNumber=s,e.isObject=n,e.isSet=a,e.isString=c,e.merge=x,e.removeNestedField=S,e.throttle=w,e.toCamelCase=y,e.toKebabCase=v,e.uniq=g,e.uniqWith=h})),B=ie();function V(e,t,n,{key:r=``,prefix:i=`EARLY`,parser:a,def:o,isRequired:s=!1,envName:c}={}){let l=new R(t,n);a&&l.argParser(a),s&&l.makeOptionMandatory(!0);let u=c??(()=>{let n=[];for(let t=e;t&&(0,B.isDefined)(t.name());t=t.parent)t.parent&&n.unshift(t.name());return[i,...n,r||t.split(/[ ,|]/)[1].replace(/^--?/,``)].join(`_`).replaceAll(/[- ]/g,`_`).toUpperCase()})();return l.env(u),(0,B.isDefined)(o)&&l.default(o),e.addOption(l),l}function ae(e){return(typeof e==`object`&&!!e||typeof e==`function`)&&typeof e.then==`function`}function oe(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 se=Symbol.for(`@inversifyjs/common/islazyServiceIdentifier`);var ce=class{[se];#e;constructor(e){this.#e=e,this[se]=!0}static is(e){return typeof e==`object`&&!!e&&!0===e[se]}unwrap(){return this.#e()}};function le(e,t,n){return Reflect.getOwnMetadata(t,e,n)}function ue(e,t,n,r){Reflect.defineMetadata(t,n,e,r)}function de(e,t,n,r,i){let a=r(le(e,t,i)??n());Reflect.defineMetadata(t,a,e,i)}function fe(e){return Object.getPrototypeOf(e.prototype)?.constructor}const pe=`@inversifyjs/container/bindingId`;function me(){let e=le(Object,pe)??0;return e===2**53-1?ue(Object,pe,-(2**53-1)):de(Object,pe,()=>e,e=>e+1),e}const he={Request:`Request`,Singleton:`Singleton`,Transient:`Transient`},ge={ConstantValue:`ConstantValue`,DynamicValue:`DynamicValue`,Factory:`Factory`,Instance:`Instance`,Provider:`Provider`,ResolvedValue:`ResolvedValue`,ServiceRedirection:`ServiceRedirection`};function*_e(...e){for(let t of e)yield*t}var ve=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)}}},ye;(function(e){e.moduleId=`moduleId`,e.serviceId=`serviceId`})(ye||={});var be=class e{#e;#t;constructor(e,t){this.#e=t??new ve({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(ye.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 _e(...t)}removeAllByModuleId(e){this.#e.removeByRelation(ye.moduleId,e)}removeAllByServiceId(e){this.#e.removeByRelation(ye.serviceId,e)}};const xe=`@inversifyjs/core/classMetadataReflectKey`;function Se(){return{constructorArguments:[],lifecycle:{postConstructMethodNames:new Set,preDestroyMethodNames:new Set},properties:new Map,scope:void 0}}const Ce=`@inversifyjs/core/pendingClassMetadataCountReflectKey`,we=Symbol.for(`@inversifyjs/core/InversifyCoreError`);var Te=class e extends Error{[we];kind;constructor(e,t,n){super(t,n),this[we]=!0,this.kind=e}static is(e){return typeof e==`object`&&!!e&&!0===e[we]}static isErrorOfKind(t,n){return e.is(t)&&t.kind===n}},Ee,De,Oe,ke,Ae;function je(e){let t=le(e,xe)??Se();if(!function(e){let t=le(e,Ce);return t!==void 0&&t!==0}(e))return function(e,t){let n=[];if(t.length<e.length)throw new Te(Ee.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 Te(Ee.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!==De.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===De.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 Te(Ee.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 Te(Ee.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:j,createCommand:te,createArgument:M,createOption:N,CommanderError:P,InvalidArgumentError:F,InvalidOptionArgumentError:I,Command:L,Argument:ne,Option:R,Help:z}=u(s((e=>{let{Argument:t}=D(),{Command:n}=ee(),{CommanderError:r,InvalidArgumentError:i}=E(),{Help:a}=O(),{Option:o}=k();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 re=`2.16.3`,ie=s((e=>{let t=e=>e!=null,n=e=>typeof e==`object`&&!!e,r=e=>Array.isArray(e),i=e=>e instanceof Map,a=e=>e instanceof Set,o=e=>e instanceof Date,s=e=>typeof e==`number`,c=e=>typeof e==`string`,l=e=>typeof e==`boolean`,u=e=>e instanceof Error,d=e=>t(e)?c(e)||r(e)?e.length===0:i(e)||a(e)?e.size===0:o(e)?!1:n(e)?Object.keys(e).length===0:!1:!0,f=e=>u(e)?e.message:`error is not Instance of Error`,p=(e,t)=>{let n=new Set(e);for(let e of n)t.includes(e)||n.delete(e);return[...n]},m=async(e,t)=>{let n=await Promise.all(e.map(e=>t(e)));return e.filter((e,t)=>n[t])},h=(e,t)=>{let n=[];for(let r of e)n.some(e=>t(r,e))||n.push(r);return n},g=e=>[...new Set(e)],_=async e=>Promise.all(e.map(e=>new Promise((t,n)=>e().then(e=>e?t(e):n(e)).catch(e=>n(e))))).then(()=>!0).catch(e=>{if(!l(e))throw e;return e}),v=e=>e.trim().replaceAll(/([\da-z])([A-Z])/g,`$1-$2`).replaceAll(/([A-Z])([A-Z][\da-z])/g,`$1-$2`).replaceAll(/[\s_]+/g,`-`).toLowerCase(),y=e=>e.replaceAll(/[\s-]+/g,` `).split(` `).map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(``),b=e=>{let t=0;for(let n=0;n<e.length;n++){let r=e.codePointAt(n)??0;t=Math.trunc(t*31+r)}return t>>>0},x=(...e)=>{let n={};for(let r of e)for(let e in r)t(r[e])&&(n[e]=r[e]);return n},S=(e,t)=>r(e)?e.map(e=>S(e,t)):n(e)?Object.fromEntries(Object.entries(e).filter(([e])=>!t.includes(e)).map(([e,n])=>[e,S(n,t)])):e,C=(e,t)=>{let n;return(...r)=>{clearTimeout(n),n=setTimeout(()=>e(...r),t)}},w=(e,t)=>{let n=!1;return(...r)=>{n||(e(...r),n=!0,setTimeout(()=>{n=!1},t))}};var T=class{listeners=[];addListener(e){this.listeners.push(e)}notifyAll(e){for(let t of this.listeners)t(e)}clear(){this.listeners.length=0}},E=class{set=new Set;constructor(e=[]){for(let t of e)this.safeAdd(t)}safeAdd(e){return t(e)?(this.set.add(e),!0):!1}has(e){return t(e)?this.set.has(e):!1}delete(e){return t(e)?this.set.delete(e):!1}clear(){this.set.clear()}get size(){return this.set.size}values(){return this.set.values()}toSet(){return structuredClone(this.set)}[Symbol.iterator](){return this.set[Symbol.iterator]()}concatSet(e){for(let t of e)this.safeAdd(t)}};e.Observer=T,e.SafeSet=E,e.arePromiseFnsTruthy=_,e.debounce=C,e.fastHash=b,e.filterAsync=m,e.getErrorMessage=f,e.intersection=p,e.isArray=r,e.isBoolean=l,e.isDate=o,e.isDefined=t,e.isEmpty=d,e.isError=u,e.isMap=i,e.isNumber=s,e.isObject=n,e.isSet=a,e.isString=c,e.merge=x,e.removeNestedField=S,e.throttle=w,e.toCamelCase=y,e.toKebabCase=v,e.uniq=g,e.uniqWith=h})),B=ie();function V(e,t,n,{key:r=``,prefix:i=`EARLY`,parser:a,def:o,isRequired:s=!1,envName:c}={}){let l=new R(t,n);a&&l.argParser(a),s&&l.makeOptionMandatory(!0);let u=c??(()=>{let n=[];for(let t=e;t&&(0,B.isDefined)(t.name());t=t.parent)t.parent&&n.unshift(t.name());return[i,...n,r||t.split(/[ ,|]/)[1].replace(/^--?/,``)].join(`_`).replaceAll(/[- ]/g,`_`).toUpperCase()})();return l.env(u),(0,B.isDefined)(o)&&l.default(o),e.addOption(l),l}function ae(e){return(typeof e==`object`&&!!e||typeof e==`function`)&&typeof e.then==`function`}function oe(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 se=Symbol.for(`@inversifyjs/common/islazyServiceIdentifier`);var ce=class{[se];#e;constructor(e){this.#e=e,this[se]=!0}static is(e){return typeof e==`object`&&!!e&&!0===e[se]}unwrap(){return this.#e()}};function le(e,t,n){return Reflect.getOwnMetadata(t,e,n)}function ue(e,t,n,r){Reflect.defineMetadata(t,n,e,r)}function de(e,t,n,r,i){let a=r(le(e,t,i)??n());Reflect.defineMetadata(t,a,e,i)}function fe(e){return Object.getPrototypeOf(e.prototype)?.constructor}const pe=`@inversifyjs/container/bindingId`;function me(){let e=le(Object,pe)??0;return e===2**53-1?ue(Object,pe,-(2**53-1)):de(Object,pe,()=>e,e=>e+1),e}const he={Request:`Request`,Singleton:`Singleton`,Transient:`Transient`},ge={ConstantValue:`ConstantValue`,DynamicValue:`DynamicValue`,Factory:`Factory`,Instance:`Instance`,Provider:`Provider`,ResolvedValue:`ResolvedValue`,ServiceRedirection:`ServiceRedirection`};function*_e(...e){for(let t of e)yield*t}var ve=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)}}},ye;(function(e){e.moduleId=`moduleId`,e.serviceId=`serviceId`})(ye||={});var be=class e{#e;#t;constructor(e,t){this.#e=t??new ve({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(ye.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 _e(...t)}removeAllByModuleId(e){this.#e.removeByRelation(ye.moduleId,e)}removeAllByServiceId(e){this.#e.removeByRelation(ye.serviceId,e)}};const xe=`@inversifyjs/core/classMetadataReflectKey`;function Se(){return{constructorArguments:[],lifecycle:{postConstructMethodNames:new Set,preDestroyMethodNames:new Set},properties:new Map,scope:void 0}}const Ce=`@inversifyjs/core/pendingClassMetadataCountReflectKey`,we=Symbol.for(`@inversifyjs/core/InversifyCoreError`);var Te=class e extends Error{[we];kind;constructor(e,t,n){super(t,n),this[we]=!0,this.kind=e}static is(e){return typeof e==`object`&&!!e&&!0===e[we]}static isErrorOfKind(t,n){return e.is(t)&&t.kind===n}},Ee,De,Oe,ke,Ae;function je(e){let t=le(e,xe)??Se();if(!function(e){let t=le(e,Ce);return t!==void 0&&t!==0}(e))return function(e,t){let n=[];if(t.length<e.length)throw new Te(Ee.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 Te(Ee.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!==De.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===De.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 Te(Ee.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 Te(Ee.missingInjectionDecorator,`Invalid class metadata at type ${e.name}:\n\n${n.join(`
|
|
21
21
|
|
|
22
22
|
`)}`)})(e,t)}function Me(e,t){let n=je(t).scope??e.scope;return{cache:{isRight:!1,value:void 0},id:me(),implementationType:t,isSatisfiedBy:()=>!0,moduleId:void 0,onActivation:void 0,onDeactivation:void 0,scope:n,serviceIdentifier:t,type:ge.Instance}}function Ne(e){return e.isRight?{isRight:!0,value:e.value}:e}function Pe(e){switch(e.type){case ge.ConstantValue:case ge.DynamicValue:return function(e){return{cache:Ne(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 ge.Factory:return function(e){return{cache:Ne(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 ge.Instance:return function(e){return{cache:Ne(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 ge.Provider:return function(e){return{cache:Ne(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 ge.ResolvedValue:return function(e){return{cache:Ne(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 ge.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`})(Ee||={}),function(e){e[e.unknown=32]=`unknown`}(De||={}),function(e){e.id=`id`,e.moduleId=`moduleId`,e.serviceId=`serviceId`}(Oe||={});var Fe=class e extends ve{_buildNewInstance(t){return new e(t)}_cloneModel(e){return Pe(e)}},Ie=class e{#e;#t;#n;constructor(e,t,n){this.#t=n??new Fe({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(Oe.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(Oe.id,e)??this.#n()?.getById(e)}getByModuleId(e){return this.#t.get(Oe.moduleId,e)??this.#n()?.getByModuleId(e)}getNonParentBindings(e){return this.#t.get(Oe.serviceId,e)}getNonParentBoundServices(){return this.#t.getAllKeys(Oe.serviceId)}removeById(e){this.#t.removeByRelation(Oe.id,e)}removeAllByModuleId(e){this.#t.removeByRelation(Oe.moduleId,e)}removeAllByServiceId(e){this.#t.removeByRelation(Oe.serviceId,e)}set(e){let t={[Oe.id]:e.id,[Oe.serviceId]:e.serviceIdentifier};e.moduleId!==void 0&&(t[Oe.moduleId]=e.moduleId),this.#t.add(e,t)}#r(e){if(this.#e===void 0||typeof e!=`function`)return;let t=Me(this.#e,e);return this.set(t),t}};(function(e){e.moduleId=`moduleId`,e.serviceId=`serviceId`})(ke||={});var Le=class e{#e;#t;constructor(e,t){this.#e=t??new ve({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(ke.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 _e(...t)}removeAllByModuleId(e){this.#e.removeByRelation(ke.moduleId,e)}removeAllByServiceId(e){this.#e.removeByRelation(ke.serviceId,e)}};function Re(){return 0}function ze(e){return t=>{t!==void 0&&t.kind===De.unknown&&de(e,Ce,Re,e=>e-1)}}function Be(e,t){return(...n)=>r=>{if(r===void 0)return e(...n);if(r.kind===Ae.unmanaged)throw new Te(Ee.injectionDecoratorConflict,`Unexpected injection found. Multiple @inject, @multiInject or @unmanaged decorators found`);return t(r,...n)}}function Ve(e){if(e.kind!==De.unknown&&!0!==e.isFromTypescriptParamType)throw new Te(Ee.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`})(Ae||={});const H=Be(function(e,t,n){return e===Ae.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 Ve(e),t===Ae.multipleInjection?{...e,chained:r?.chained??!1,kind:t,value:n}:{...e,kind:t,value:n}});function He(e,t){return n=>{let r=n.properties.get(t);return n.properties.set(t,e(r)),n}}var Ue;function We(e,t,n,r){if(Te.isErrorOfKind(r,Ee.injectionDecoratorConflict)){let i=function(e,t,n){if(n===void 0){if(t===void 0)throw new Te(Ee.unknown,`Unexpected undefined property and index values`);return{kind:Ue.property,property:t,targetClass:e.constructor}}return typeof n==`number`?{index:n,kind:Ue.parameter,targetClass:e}:{kind:Ue.method,method:t,targetClass:e}}(e,t,n);throw new Te(Ee.injectionDecoratorConflict,`Unexpected injection error.\n\nCause:\n\n${r.message}\n\nDetails\n\n${function(e){switch(e.kind){case Ue.method:return`[class: "${e.targetClass.name}", method: "${e.method.toString()}"]`;case Ue.parameter:return`[class: "${e.targetClass.name}", index: "${e.index.toString()}"]`;case Ue.property:return`[class: "${e.targetClass.name}", property: "${e.property.toString()}"]`}}(i)}`,{cause:r})}throw r}function Ge(e,t){return(n,r,i)=>{try{i===void 0?function(e,t){let n=Ke(e,t);return(e,t)=>{de(e.constructor,xe,Se,He(n(e),t))}}(e,t)(n,r):typeof i==`number`?function(e,t){let n=Ke(e,t);return(e,t,r)=>{if(!function(e,t){return typeof e==`function`&&t===void 0}(e,t))throw new Te(Ee.injectionDecoratorConflict,`Found an @inject decorator in a non constructor parameter.\nFound @inject decorator at method "${t?.toString()??``}" at class "${e.constructor.name}"`);de(e,xe,Se,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=Ke(e,t);return(e,t,r)=>{if(!function(e){return e.set!==void 0}(r))throw new Te(Ee.injectionDecoratorConflict,`Found an @inject decorator in a non setter property method.\nFound @inject decorator at method "${t.toString()}" at class "${e.constructor.name}"`);de(e.constructor,xe,Se,He(n(e),t))}}(e,t)(n,r,i)}catch(e){We(n,r,i,e)}}}function Ke(e,t){return n=>{let r=t(n);return t=>(r(t),e(t))}}function qe(e){return Ge(H(Ae.singleInjection,e),ze)}(function(e){e[e.method=0]=`method`,e[e.parameter=1]=`parameter`,e[e.property=2]=`property`})(Ue||={});const Je=`@inversifyjs/core/classIsInjectableFlagReflectKey`,Ye=[Array,BigInt,Boolean,Function,Number,Object,String];function Xe(e){let t=le(e,`design:paramtypes`);t!==void 0&&de(e,xe,Se,function(e){return t=>(e.forEach((e,n)=>{var r;t.constructorArguments[n]!==void 0||(r=e,Ye.includes(r))||(t.constructorArguments[n]=function(e){return{isFromTypescriptParamType:!0,kind:Ae.singleInjection,name:void 0,optional:!1,tags:new Map,value:e}}(e))}),t)}(t))}function Ze(e){return t=>{(function(e){if(le(e,Je)!==void 0)throw new Te(Ee.injectionDecoratorConflict,`Cannot apply @injectable decorator multiple times at class "${e.name}"`);ue(e,Je,!0)})(t),Xe(t),e!==void 0&&de(t,xe,Se,t=>({...t,scope:e}))}}function Qe(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 $e(e,t,n){return e?new Set([...t,...n]):n}function et(e,t,n){let r=e.lifecycle?.extendPostConstructMethods??!0,i=$e(e.lifecycle?.extendPreDestroyMethods??!0,t.lifecycle.preDestroyMethodNames,n.lifecycle.preDestroyMethodNames);return{postConstructMethodNames:$e(r,t.lifecycle.postConstructMethodNames,n.lifecycle.postConstructMethodNames),preDestroyMethodNames:i}}function tt(e,t,n){let r;return r=e.extendProperties??!0?new Map(_e(t.properties,n.properties)):n.properties,r}function nt(e){return t=>{de(t,xe,Se,function(e,t){return n=>({constructorArguments:Qe(e,t,n),lifecycle:et(e,t,n),properties:tt(e,t,n),scope:n.scope})}(e,je(e.type)))}}function rt(e){return t=>{let n=fe(t);if(n===void 0)throw new Te(Ee.injectionDecoratorConflict,`Expected base type for type "${t.name}", none found.`);nt({...e,type:n})(t)}}function it(e){return t=>{let n=[],r=fe(t);for(;r!==void 0&&r!==Object;){let e=r;n.push(e),r=fe(e)}n.reverse();for(let r of n)nt({...e,type:r})(t)}}function at(e){return t=>{t===void 0&&de(e,Ce,Re,e=>e+1)}}function ot(e){return t=>{let n=t??{kind:De.unknown,name:void 0,optional:!1,tags:new Map};if(n.kind===Ae.unmanaged)throw new Te(Ee.injectionDecoratorConflict,`Unexpected injection found. Found @unmanaged injection with additional @named, @optional, @tagged or @targetName injections`);return e(n)}}function st(e){if(e.optional)throw new Te(Ee.injectionDecoratorConflict,`Unexpected duplicated optional decorator`);return e.optional=!0,e}function U(){return Ge(ot(st),at)}var ct;function lt(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 ut(e,t){if(lt(t)){let n=function(e){let t=[...e];return t.length===0?`(No dependency trace)`:t.map(oe).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 Te(Ee.planning,`Circular dependency found: ${n}`,{cause:t})}throw t}(function(e){e[e.multipleInjection=0]=`multipleInjection`,e[e.singleInjection=1]=`singleInjection`})(ct||={});const dt=Symbol.for(`@inversifyjs/core/LazyPlanServiceNode`);var ft=class{[dt];_serviceIdentifier;_serviceNode;constructor(e,t){this[dt]=!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[dt]}invalidate(){this._serviceNode=void 0}isExpanded(){return this._serviceNode!==void 0}_getNode(){return this._serviceNode===void 0&&(this._serviceNode=this._buildPlanServiceNode()),this._serviceNode}},pt=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 mt(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=Me(e.autobindOptions,r);e.operations.setBinding(n),n.isSatisfiedBy(t)&&i.push(n)}return i}var ht=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 gt(e){let t=new Map;return e.rootConstraints.tag!==void 0&&t.set(e.rootConstraints.tag.key,e.rootConstraints.tag.value),new ht({elem:{getAncestorsCalled:!1,name:e.rootConstraints.name,serviceIdentifier:e.rootConstraints.serviceIdentifier,tags:t},previous:void 0})}function _t(e){return e.redirections!==void 0}function vt(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: "${oe(a[a.length-1]??n)}".${St(a)}\n\nRegistered bindings:\n\n${e.map(e=>function(e){switch(e.type){case ge.Instance:return`[ type: "${e.type}", serviceIdentifier: "${oe(e.serviceIdentifier)}", scope: "${e.scope}", implementationType: "${e.implementationType.name}" ]`;case ge.ServiceRedirection:return`[ type: "${e.type}", serviceIdentifier: "${oe(e.serviceIdentifier)}", redirection: "${oe(e.targetServiceIdentifier)}" ]`;default:return`[ type: "${e.type}", serviceIdentifier: "${oe(e.serviceIdentifier)}", scope: "${e.scope}" ]`}}(e.binding)).join(`
|
|
23
23
|
`)}\n\nTrying to resolve bindings for "${bt(n,r)}".${xt(i)}`;throw new Te(Ee.planning,t)}t||yt(n,r,i,a)}(e,t,i,a,n.elem,r):function(e,t,n,r,i,a){e!==void 0||t||yt(n,r,i,a)}(e,t,i,a,n.elem,r)}function yt(e,t,n,r){let i=`No bindings found for service: "${oe(r[r.length-1]??e)}".\n\nTrying to resolve bindings for "${bt(e,t)}".${St(r)}${xt(n)}`;throw new Te(Ee.planning,i)}function bt(e,t){return t===void 0?`${oe(e)} (Root service)`:oe(t)}function xt(e){let t=e.tags.size===0?``:`\n- tags:\n - ${[...e.tags.keys()].map(e=>e.toString()).join(`
|
|
@@ -115,11 +115,11 @@ Binding constraints:
|
|
|
115
115
|
To resolve the conflict:`,(0,r.getConflictResolutionRecipe)(i,e))),a=o):n.diag.warn(`A view or instrument with the name `,e.name,` has already been registered and is incompatible with another registered view.
|
|
116
116
|
`,`Details:
|
|
117
117
|
`,(0,r.getIncompatibilityDetails)(i,e),`To resolve the conflict:
|
|
118
|
-
`,(0,r.getConflictResolutionRecipe)(i,e))}return a}}})),AI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MultiMetricStorage=void 0,e.MultiMetricStorage=class{_backingStorages;constructor(e){this._backingStorages=e}record(e,t,n,r){this._backingStorages.forEach(i=>{i.record(e,t,n,r)})}}})),jI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BatchObservableResultImpl=e.ObservableResultImpl=void 0;let t=(Jd(),d(Kd)),n=wI(),r=xI();e.ObservableResultImpl=class{_instrumentName;_valueType;_buffer=new n.AttributeHashMap;constructor(e,t){this._instrumentName=e,this._valueType=t}observe(e,n={}){if(typeof e!=`number`){t.diag.warn(`non-number value provided to metric ${this._instrumentName}: ${e}`);return}this._valueType===t.ValueType.INT&&!Number.isInteger(e)&&(t.diag.warn(`INT value type cannot accept a floating-point value for ${this._instrumentName}, ignoring the fractional digits.`),e=Math.trunc(e),!Number.isInteger(e))||this._buffer.set(n,e)}},e.BatchObservableResultImpl=class{_buffer=new Map;observe(e,i,a={}){if(!(0,r.isObservableInstrument)(e))return;let o=this._buffer.get(e);if(o??(o=new n.AttributeHashMap,this._buffer.set(e,o)),typeof i!=`number`){t.diag.warn(`non-number value provided to metric ${e._descriptor.name}: ${i}`);return}e._descriptor.valueType===t.ValueType.INT&&!Number.isInteger(i)&&(t.diag.warn(`INT value type cannot accept a floating-point value for ${e._descriptor.name}, ignoring the fractional digits.`),i=Math.trunc(i),!Number.isInteger(i))||o.set(a,i)}}})),MI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ObservableRegistry=void 0;let t=(Jd(),d(Kd)),n=xI(),r=jI(),i=ZF();e.ObservableRegistry=class{_callbacks=[];_batchCallbacks=[];addCallback(e,t){this._findCallback(e,t)>=0||this._callbacks.push({callback:e,instrument:t})}removeCallback(e,t){let n=this._findCallback(e,t);n<0||this._callbacks.splice(n,1)}addBatchCallback(e,r){let i=new Set(r.filter(n.isObservableInstrument));if(i.size===0){t.diag.error(`BatchObservableCallback is not associated with valid instruments`,r);return}this._findBatchCallback(e,i)>=0||this._batchCallbacks.push({callback:e,instruments:i})}removeBatchCallback(e,t){let r=new Set(t.filter(n.isObservableInstrument)),i=this._findBatchCallback(e,r);i<0||this._batchCallbacks.splice(i,1)}async observe(e,t){let n=this._observeCallbacks(e,t),r=this._observeBatchCallbacks(e,t);return(await(0,i.PromiseAllSettled)([...n,...r])).filter(i.isPromiseAllSettledRejectionResult).map(e=>e.reason)}_observeCallbacks(e,t){return this._callbacks.map(async({callback:n,instrument:a})=>{let o=new r.ObservableResultImpl(a._descriptor.name,a._descriptor.valueType),s=Promise.resolve(n(o));t!=null&&(s=(0,i.callWithTimeout)(s,t)),await s,a._metricStorages.forEach(t=>{t.record(o._buffer,e)})})}_observeBatchCallbacks(e,t){return this._batchCallbacks.map(async({callback:n,instruments:a})=>{let o=new r.BatchObservableResultImpl,s=Promise.resolve(n(o));t!=null&&(s=(0,i.callWithTimeout)(s,t)),await s,a.forEach(t=>{let n=o._buffer.get(t);n!=null&&t._metricStorages.forEach(t=>{t.record(n,e)})})})}_findCallback(e,t){return this._callbacks.findIndex(n=>n.callback===e&&n.instrument===t)}_findBatchCallback(e,t){return this._batchCallbacks.findIndex(n=>n.callback===e&&(0,i.setEquals)(n.instruments,t))}}})),NI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.SyncMetricStorage=void 0;let t=CI(),n=TI(),r=EI();e.SyncMetricStorage=class extends t.MetricStorage{_attributesProcessor;_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;constructor(e,t,i,a,o){super(e),this._attributesProcessor=i,this._aggregationCardinalityLimit=o,this._deltaMetricStorage=new n.DeltaMetricProcessor(t,this._aggregationCardinalityLimit),this._temporalMetricStorage=new r.TemporalMetricProcessor(t,a)}record(e,t,n,r){t=this._attributesProcessor.process(t,n),this._deltaMetricStorage.record(e,t,n,r)}collect(e,t){let n=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(e,this._instrumentDescriptor,n,t)}}})),PI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.createDenyListAttributesProcessor=e.createAllowListAttributesProcessor=e.createMultiAttributesProcessor=e.createNoopAttributesProcessor=void 0;var t=class{process(e,t){return e}},n=class{_processors;constructor(e){this._processors=e}process(e,t){let n=e;for(let e of this._processors)n=e.process(n,t);return n}},r=class{_allowedAttributeNames;constructor(e){this._allowedAttributeNames=e}process(e,t){let n={};return Object.keys(e).filter(e=>this._allowedAttributeNames.includes(e)).forEach(t=>n[t]=e[t]),n}},i=class{_deniedAttributeNames;constructor(e){this._deniedAttributeNames=e}process(e,t){let n={};return Object.keys(e).filter(e=>!this._deniedAttributeNames.includes(e)).forEach(t=>n[t]=e[t]),n}};function a(){return l}e.createNoopAttributesProcessor=a;function o(e){return new n(e)}e.createMultiAttributesProcessor=o;function s(e){return new r(e)}e.createAllowListAttributesProcessor=s;function c(e){return new i(e)}e.createDenyListAttributesProcessor=c;let l=new t})),FI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MeterSharedState=void 0;let t=bI(),n=SI(),r=ZF(),i=DI(),a=kI(),o=AI(),s=MI(),c=NI(),l=PI();e.MeterSharedState=class{_meterProviderSharedState;_instrumentationScope;metricStorageRegistry=new a.MetricStorageRegistry;observableRegistry=new s.ObservableRegistry;meter;constructor(e,t){this._meterProviderSharedState=e,this._instrumentationScope=t,this.meter=new n.Meter(this)}registerMetricStorage(e){let t=this._registerMetricStorage(e,c.SyncMetricStorage);return t.length===1?t[0]:new o.MultiMetricStorage(t)}registerAsyncMetricStorage(e){return this._registerMetricStorage(e,i.AsyncMetricStorage)}async collect(e,t,n){let i=await this.observableRegistry.observe(t,n?.timeoutMillis),a=this.metricStorageRegistry.getStorages(e);if(a.length===0)return null;let o=a.map(n=>n.collect(e,t)).filter(r.isNotNullish);return o.length===0?{errors:i}:{scopeMetrics:{scope:this._instrumentationScope,metrics:o},errors:i}}_registerMetricStorage(e,n){let r=this._meterProviderSharedState.viewRegistry.findViews(e,this._instrumentationScope).map(r=>{let i=(0,t.createInstrumentDescriptorWithView)(r,e),a=this.metricStorageRegistry.findOrUpdateCompatibleStorage(i);if(a!=null)return a;let o=new n(i,r.aggregation.createAggregator(i),r.attributesProcessor,this._meterProviderSharedState.metricCollectors,r.aggregationCardinalityLimit);return this.metricStorageRegistry.register(o),o});if(r.length===0){let t=this._meterProviderSharedState.selectAggregations(e.type).map(([t,r])=>{let i=this.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(t,e);if(i!=null)return i;let a=r.createAggregator(e),o=t.selectCardinalityLimit(e.type),s=new n(e,a,(0,l.createNoopAttributesProcessor)(),[t],o);return this.metricStorageRegistry.registerForCollector(t,s),s});r=r.concat(t)}return r}}})),II=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MeterProviderSharedState=void 0;let t=ZF(),n=yI(),r=FI(),i=pI();e.MeterProviderSharedState=class{resource;viewRegistry=new n.ViewRegistry;metricCollectors=[];meterSharedStates=new Map;constructor(e){this.resource=e}getMeterSharedState(e){let n=(0,t.instrumentationScopeId)(e),i=this.meterSharedStates.get(n);return i??(i=new r.MeterSharedState(this,e),this.meterSharedStates.set(n,i)),i}selectAggregations(e){let t=[];for(let n of this.metricCollectors)t.push([n,(0,i.toAggregation)(n.selectAggregation(e))]);return t}}})),LI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MetricCollector=void 0;let t=tj();e.MetricCollector=class{_sharedState;_metricReader;constructor(e,t){this._sharedState=e,this._metricReader=t}async collect(e){let n=(0,t.millisToHrTime)(Date.now()),r=[],i=[],a=Array.from(this._sharedState.meterSharedStates.values()).map(async t=>{let a=await t.collect(this,n,e);a?.scopeMetrics!=null&&r.push(a.scopeMetrics),a?.errors!=null&&i.push(...a.errors)});return await Promise.all(a),{resourceMetrics:{resource:this._sharedState.resource,scopeMetrics:r},errors:i}}async forceFlush(e){await this._metricReader.forceFlush(e)}async shutdown(e){await this._metricReader.shutdown(e)}selectAggregationTemporality(e){return this._metricReader.selectAggregationTemporality(e)}selectAggregation(e){return this._metricReader.selectAggregation(e)}selectCardinalityLimit(e){return this._metricReader.selectCardinalityLimit?.(e)??2e3}}})),RI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ExactPredicate=e.PatternPredicate=void 0;let t=/[\^$\\.+?()[\]{}|]/g;e.PatternPredicate=class e{_matchAll;_regexp;constructor(t){t===`*`?(this._matchAll=!0,this._regexp=/.*/):(this._matchAll=!1,this._regexp=new RegExp(e.escapePattern(t)))}match(e){return this._matchAll?!0:this._regexp.test(e)}static escapePattern(e){return`^${e.replace(t,`\\$&`).replace(`*`,`.*`)}$`}static hasWildcard(e){return e.includes(`*`)}},e.ExactPredicate=class{_matchAll;_pattern;constructor(e){this._matchAll=e===void 0,this._pattern=e}match(e){return!!(this._matchAll||e===this._pattern)}}})),aee=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.InstrumentSelector=void 0;let t=RI();e.InstrumentSelector=class{_nameFilter;_type;_unitFilter;constructor(e){this._nameFilter=new t.PatternPredicate(e?.name??`*`),this._type=e?.type,this._unitFilter=new t.ExactPredicate(e?.unit)}getType(){return this._type}getNameFilter(){return this._nameFilter}getUnitFilter(){return this._unitFilter}}})),zI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MeterSelector=void 0;let t=RI();e.MeterSelector=class{_nameFilter;_versionFilter;_schemaUrlFilter;constructor(e){this._nameFilter=new t.ExactPredicate(e?.name),this._versionFilter=new t.ExactPredicate(e?.version),this._schemaUrlFilter=new t.ExactPredicate(e?.schemaUrl)}getNameFilter(){return this._nameFilter}getVersionFilter(){return this._versionFilter}getSchemaUrlFilter(){return this._schemaUrlFilter}}})),BI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.View=void 0;let t=RI(),n=PI(),r=aee(),i=zI(),a=pI();function o(e){return e.instrumentName==null&&e.instrumentType==null&&e.instrumentUnit==null&&e.meterName==null&&e.meterVersion==null&&e.meterSchemaUrl==null}function s(e){if(o(e))throw Error(`Cannot create view with no selector arguments supplied`);if(e.name!=null&&(e?.instrumentName==null||t.PatternPredicate.hasWildcard(e.instrumentName)))throw Error(`Views with a specified name must be declared with an instrument selector that selects at most one instrument per meter.`)}e.View=class{name;description;aggregation;attributesProcessor;instrumentSelector;meterSelector;aggregationCardinalityLimit;constructor(e){s(e),e.attributesProcessors==null?this.attributesProcessor=(0,n.createNoopAttributesProcessor)():this.attributesProcessor=(0,n.createMultiAttributesProcessor)(e.attributesProcessors),this.name=e.name,this.description=e.description,this.aggregation=(0,a.toAggregation)(e.aggregation??{type:a.AggregationType.DEFAULT}),this.instrumentSelector=new r.InstrumentSelector({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new i.MeterSelector({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}}})),VI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MeterProvider=void 0;let t=(Jd(),d(Kd)),n=bj(),r=II(),i=LI(),a=BI();e.MeterProvider=class{_sharedState;_shutdown=!1;constructor(e){if(this._sharedState=new r.MeterProviderSharedState(e?.resource??(0,n.defaultResource)()),e?.views!=null&&e.views.length>0)for(let t of e.views)this._sharedState.viewRegistry.addView(new a.View(t));if(e?.readers!=null&&e.readers.length>0)for(let t of e.readers){let e=new i.MetricCollector(this._sharedState,t);t.setMetricProducer(e),this._sharedState.metricCollectors.push(e)}}getMeter(e,n=``,r={}){return this._shutdown?(t.diag.warn(`A shutdown MeterProvider cannot provide a Meter`),(0,t.createNoopMeter)()):this._sharedState.getMeterSharedState({name:e,version:n,schemaUrl:r.schemaUrl}).meter}async shutdown(e){if(this._shutdown){t.diag.warn(`shutdown may only be called once per MeterProvider`);return}this._shutdown=!0,await Promise.all(this._sharedState.metricCollectors.map(t=>t.shutdown(e)))}async forceFlush(e){if(this._shutdown){t.diag.warn(`invalid attempt to force flush after MeterProvider shutdown`);return}await Promise.all(this._sharedState.metricCollectors.map(t=>t.forceFlush(e)))}}})),HI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.TimeoutError=e.createDenyListAttributesProcessor=e.createAllowListAttributesProcessor=e.AggregationType=e.MeterProvider=e.ConsoleMetricExporter=e.InMemoryMetricExporter=e.PeriodicExportingMetricReader=e.MetricReader=e.InstrumentType=e.DataPointType=e.AggregationTemporality=void 0;var t=YF();Object.defineProperty(e,`AggregationTemporality`,{enumerable:!0,get:function(){return t.AggregationTemporality}});var n=XF();Object.defineProperty(e,`DataPointType`,{enumerable:!0,get:function(){return n.DataPointType}}),Object.defineProperty(e,`InstrumentType`,{enumerable:!0,get:function(){return n.InstrumentType}});var r=hI();Object.defineProperty(e,`MetricReader`,{enumerable:!0,get:function(){return r.MetricReader}});var i=gI();Object.defineProperty(e,`PeriodicExportingMetricReader`,{enumerable:!0,get:function(){return i.PeriodicExportingMetricReader}});var a=_I();Object.defineProperty(e,`InMemoryMetricExporter`,{enumerable:!0,get:function(){return a.InMemoryMetricExporter}});var o=vI();Object.defineProperty(e,`ConsoleMetricExporter`,{enumerable:!0,get:function(){return o.ConsoleMetricExporter}});var s=VI();Object.defineProperty(e,`MeterProvider`,{enumerable:!0,get:function(){return s.MeterProvider}});var c=pI();Object.defineProperty(e,`AggregationType`,{enumerable:!0,get:function(){return c.AggregationType}});var l=PI();Object.defineProperty(e,`createAllowListAttributesProcessor`,{enumerable:!0,get:function(){return l.createAllowListAttributesProcessor}}),Object.defineProperty(e,`createDenyListAttributesProcessor`,{enumerable:!0,get:function(){return l.createDenyListAttributesProcessor}});var u=ZF();Object.defineProperty(e,`TimeoutError`,{enumerable:!0,get:function(){return u.TimeoutError}})})),UI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.StatsbeatFeatureType=e.EU_ENDPOINTS=e.EU_CONNECTION_STRING=e.NON_EU_CONNECTION_STRING=e.AIMS_FORMAT=e.AIMS_API_VERSION=e.AIMS_URI=e.StatsbeatCounter=e.AttachTypeName=e.StatsbeatResourceProvider=e.MAX_STATSBEAT_FAILURES=e.AZURE_MONITOR_AUTO_ATTACH=e.STATSBEAT_LANGUAGE=e.NetworkStatsbeat=void 0,e.isStatsbeatShutdownStatus=i,e.NetworkStatsbeat=class{constructor(e,t){this.endpoint=e,this.host=t,this.totalRequestCount=0,this.totalSuccessfulRequestCount=0,this.totalReadFailureCount=0,this.totalWriteFailureCount=0,this.totalFailedRequestCount=[],this.retryCount=[],this.exceptionCount=[],this.throttleCount=[],this.intervalRequestExecutionTime=0,this.lastIntervalRequestExecutionTime=0,this.lastTime=+new Date,this.lastRequestCount=0,this.averageRequestExecutionTime=0}},e.STATSBEAT_LANGUAGE=`node`,e.AZURE_MONITOR_AUTO_ATTACH=`AZURE_MONITOR_AUTO_ATTACH`,e.MAX_STATSBEAT_FAILURES=3,e.StatsbeatResourceProvider={appsvc:`appsvc`,aks:`aks`,functions:`functions`,vm:`vm`,unknown:`unknown`};var t;(function(e){e.INTEGRATED_AUTO=`IntegratedAuto`,e.MANUAL=`Manual`})(t||(e.AttachTypeName=t={}));var n;(function(e){e.SUCCESS_COUNT=`Request_Success_Count`,e.FAILURE_COUNT=`Request_Failure_Count`,e.RETRY_COUNT=`Retry_Count`,e.THROTTLE_COUNT=`Throttle_Count`,e.EXCEPTION_COUNT=`Exception_Count`,e.AVERAGE_DURATION=`Request_Duration`,e.READ_FAILURE_COUNT=`Read_Failure_Count`,e.WRITE_FAILURE_COUNT=`Write_Failure_Count`,e.ATTACH=`Attach`,e.FEATURE=`Feature`})(n||(e.StatsbeatCounter=n={})),e.AIMS_URI=`http://169.254.169.254/metadata/instance/compute`,e.AIMS_API_VERSION=`api-version=2017-12-01`,e.AIMS_FORMAT=`format=json`,e.NON_EU_CONNECTION_STRING=`InstrumentationKey=c4a29126-a7cb-47e5-b348-11414998b11e;IngestionEndpoint=https://westus-0.in.applicationinsights.azure.com`,e.EU_CONNECTION_STRING=`InstrumentationKey=7dc56bab-3c0c-4e9f-9ebb-d1acadee8d0f;IngestionEndpoint=https://westeurope-5.in.applicationinsights.azure.com`,e.EU_ENDPOINTS=[`westeurope`,`northeurope`,`francecentral`,`francesouth`,`germanywestcentral`,`norwayeast`,`norwaywest`,`swedencentral`,`switzerlandnorth`,`switzerlandwest`,`uksouth`,`ukwest`];var r;(function(e){e[e.FEATURE=0]=`FEATURE`,e[e.INSTRUMENTATION=1]=`INSTRUMENTATION`})(r||(e.StatsbeatFeatureType=r={}));function i(e){return e===401||e===403||e===503}})),WI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.StatsbeatMetrics=void 0;let t=(kM(),d(Gj)),n=DF(),r=(Jd(),d(Kd)),i=UI(),a=t.__importStar(require(`node:os`));e.StatsbeatMetrics=class{constructor(){this.resourceProvider=i.StatsbeatResourceProvider.unknown,this.vmInfo={},this.os=a.type(),this.resourceIdentifier=``}async getResourceProvider(){this.resourceProvider=i.StatsbeatResourceProvider.unknown,process.env.AKS_ARM_NAMESPACE_ID?(this.resourceProvider=i.StatsbeatResourceProvider.aks,this.resourceIdentifier=process.env.AKS_ARM_NAMESPACE_ID):process.env.WEBSITE_SITE_NAME?(this.resourceProvider=i.StatsbeatResourceProvider.appsvc,this.resourceIdentifier=process.env.WEBSITE_SITE_NAME,process.env.WEBSITE_HOME_STAMPNAME&&(this.resourceIdentifier+=`/`+process.env.WEBSITE_HOME_STAMPNAME)):process.env.FUNCTIONS_WORKER_RUNTIME?(this.resourceProvider=i.StatsbeatResourceProvider.functions,process.env.WEBSITE_HOSTNAME&&(this.resourceIdentifier=process.env.WEBSITE_HOSTNAME)):await this.getAzureComputeMetadata()?(this.resourceProvider=i.StatsbeatResourceProvider.vm,this.resourceIdentifier=this.vmInfo.id+`/`+this.vmInfo.subscriptionId,this.vmInfo.osType&&(this.os=this.vmInfo.osType)):this.resourceProvider=i.StatsbeatResourceProvider.unknown}async getAzureComputeMetadata(){let e=(0,n.createDefaultHttpClient)(),t={url:`${i.AIMS_URI}?${i.AIMS_API_VERSION}&${i.AIMS_FORMAT}`,timeout:5e3,method:`GET`,allowInsecureConnection:!0},a=(0,n.createPipelineRequest)(t);return await e.sendRequest(a).then(e=>{if(e.status===200){this.vmInfo.isVM=!0;let t=``;return e.on(`data`,e=>{t+=e}),e.on(`end`,()=>{try{let e=JSON.parse(t);this.vmInfo.id=e.vmId||``,this.vmInfo.subscriptionId=e.subscriptionId||``,this.vmInfo.osType=e.osType||``}catch(e){r.diag.debug(`Failed to parse JSON: `,e)}}),!0}else return!1}).catch(()=>!1),!1}getConnectionString(e){let t=e;for(let e=0;e<i.EU_ENDPOINTS.length;e++)if(t.includes(i.EU_ENDPOINTS[e]))return i.EU_CONNECTION_STRING;return i.NON_EU_CONNECTION_STRING}}})),GI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.resourceMetricsToEnvelope=l,e.isAksAttach=u,e.shouldSendToOtlp=d,e.isStandardMetric=f,e.getAttachType=p;let t=HI(),n=nL(),r=dN(),i=AM(),a=UI(),o=tL(),s=new Map([[r.OTelPerformanceCounterNames.PRIVATE_BYTES,r.BreezePerformanceCounterNames.PRIVATE_BYTES],[r.OTelPerformanceCounterNames.AVAILABLE_BYTES,r.BreezePerformanceCounterNames.AVAILABLE_BYTES],[r.OTelPerformanceCounterNames.PROCESSOR_TIME,r.BreezePerformanceCounterNames.PROCESSOR_TIME],[r.OTelPerformanceCounterNames.PROCESS_TIME_STANDARD,r.BreezePerformanceCounterNames.PROCESS_TIME_STANDARD],[r.OTelPerformanceCounterNames.PROCESS_TIME_NORMALIZED,r.BreezePerformanceCounterNames.PROCESS_TIME_NORMALIZED],[r.OTelPerformanceCounterNames.REQUEST_RATE,r.BreezePerformanceCounterNames.REQUEST_RATE],[r.OTelPerformanceCounterNames.REQUEST_DURATION,r.BreezePerformanceCounterNames.REQUEST_DURATION],[r.OTelPerformanceCounterNames.EXCEPTION_RATE,r.BreezePerformanceCounterNames.EXCEPTION_RATE]]);function c(e){let t={};if(e)for(let n of Object.keys(e))t[n]=e[n];return t}function l(e,r,a){let l=[],p=new Date,m=r,h,g;if(a){g=`Microsoft.ApplicationInsights.Statsbeat`;let e=(0,o.getInstance)();h=Object.assign({},e.tags)}else g=`Microsoft.ApplicationInsights.Metric`,h=(0,n.createTagsFromResource)(e.resource);return e.scopeMetrics.forEach(e=>{e.metrics.forEach(e=>{e.dataPoints.forEach(n=>{let r={metrics:[],version:2,properties:{}};if(r.properties=c(n.attributes),d()&&u()&&!f(n)&&process.env[i.ENV_APPLICATIONINSIGHTS_METRICS_TO_LOGANALYTICS_ENABLED]===`false`&&!a)return;d()&&u()&&!a?r.properties[`_MS.SentToAMW`]=`True`:u()&&!a&&(r.properties[`_MS.SentToAMW`]=`False`);let o;s.has(e.descriptor.name)&&(o=s.get(e.descriptor.name));let _={name:o||e.descriptor.name,value:0,dataPointType:`Aggregation`};e.dataPointType===t.DataPointType.SUM||e.dataPointType===t.DataPointType.GAUGE?(_.value=n.value,_.count=1):(_.value=n.value.sum||0,_.count=n.value.count,_.max=n.value.max,_.min=n.value.min),r.metrics.push(_);let v={name:g,time:p,sampleRate:100,instrumentationKey:m,tags:h,version:1,data:{baseType:`MetricData`,baseData:Object.assign({},r)}};l.push(v)})})}),l}function u(){return!!(process.env[i.ENV_AZURE_MONITOR_AUTO_ATTACH]===`true`&&process.env.AKS_ARM_NAMESPACE_ID)}function d(){return!!(process.env[i.ENV_OTLP_METRICS_ENDPOINT]&&process.env[i.ENV_OTEL_METRICS_EXPORTER]?.includes(`otlp`))}function f(e){return e.attributes?.[`_MS.IsAutocollected`]===`True`}function p(){return process.env[a.AZURE_MONITOR_AUTO_ATTACH]===`true`?a.AttachTypeName.INTEGRATED_AUTO:a.AttachTypeName.MANUAL}})),KI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AzureMonitorStatsbeatExporter=void 0;let t=(Jd(),d(Kd)),n=uN(),r=GI(),i=MM(),a=tL();e.AzureMonitorStatsbeatExporter=class extends i.AzureMonitorBaseExporter{constructor(e){super(e,!0),this._isShutdown=!1,this._sender=new a.HttpSender({endpointUrl:this.endpointUrl,instrumentationKey:this.instrumentationKey,trackStatsbeat:this.trackStatsbeat,exporterOptions:e,isStatsbeatSender:!0})}async export(e,i){if(this._isShutdown){setTimeout(()=>i({code:n.ExportResultCode.FAILED}),0);return}let a=(0,r.resourceMetricsToEnvelope)(e,this.instrumentationKey,!0);t.context.with((0,n.suppressTracing)(t.context.active()),async()=>{i(await this._sender.exportEnvelopes(a))})}async shutdown(){return this._isShutdown=!0,this._sender.shutdown()}async forceFlush(){return Promise.resolve()}}})),qI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.NetworkStatsbeatMetrics=void 0;let t=(kM(),d(Gj)),n=(Jd(),d(Kd)),r=HI(),i=t.__importStar(Uj()),a=WI(),o=UI(),s=KI(),c=AM(),l=GI();var u=class e extends a.StatsbeatMetrics{constructor(e){super(),this.disableNonEssentialStatsbeat=!!process.env[c.ENV_DISABLE_STATSBEAT],this.isInitialized=!1,this.statsCollectionShortInterval=9e5,this.networkStatsbeatCollection=[],this.attach=(0,l.getAttachType)(),this.connectionString=super.getConnectionString(e.endpointUrl);let t={connectionString:this.connectionString};this.networkAzureExporter=new s.AzureMonitorStatsbeatExporter(t);let n={exporter:this.networkAzureExporter,exportIntervalMillis:e.networkCollectionInterval||this.statsCollectionShortInterval};this.networkStatsbeatMeterProvider=new r.MeterProvider({readers:[new r.PeriodicExportingMetricReader(n)]}),this.networkStatsbeatMeter=this.networkStatsbeatMeterProvider.getMeter(`Azure Monitor Network Statsbeat`),this.endpointUrl=e.endpointUrl,this.runtimeVersion=process.version,this.language=o.STATSBEAT_LANGUAGE,this.version=i.packageVersion,this.host=this.getShortHost(e.endpointUrl),this.cikey=e.instrumentationKey,this.successCountGauge=this.networkStatsbeatMeter.createObservableGauge(o.StatsbeatCounter.SUCCESS_COUNT),this.failureCountGauge=this.networkStatsbeatMeter.createObservableGauge(o.StatsbeatCounter.FAILURE_COUNT),this.retryCountGauge=this.networkStatsbeatMeter.createObservableGauge(o.StatsbeatCounter.RETRY_COUNT),this.throttleCountGauge=this.networkStatsbeatMeter.createObservableGauge(o.StatsbeatCounter.THROTTLE_COUNT),this.exceptionCountGauge=this.networkStatsbeatMeter.createObservableGauge(o.StatsbeatCounter.EXCEPTION_COUNT),this.averageDurationGauge=this.networkStatsbeatMeter.createObservableGauge(o.StatsbeatCounter.AVERAGE_DURATION),this.disableNonEssentialStatsbeat||(this.readFailureGauge=this.networkStatsbeatMeter.createObservableGauge(o.StatsbeatCounter.READ_FAILURE_COUNT),this.writeFailureGauge=this.networkStatsbeatMeter.createObservableGauge(o.StatsbeatCounter.WRITE_FAILURE_COUNT)),this.isInitialized=!0,this.initialize(),this.commonProperties={os:this.os,rp:this.resourceProvider,cikey:this.cikey,runtimeVersion:this.runtimeVersion,language:this.language,version:this.version,attach:this.attach},this.networkProperties={endpoint:this.endpointUrl,host:this.host}}shutdown(){return this.networkStatsbeatMeterProvider.shutdown()}async initialize(){var e,t;try{await super.getResourceProvider(),this.successCountGauge.addCallback(this.successCallback.bind(this)),this.networkStatsbeatMeter.addBatchObservableCallback(this.failureCallback.bind(this),[this.failureCountGauge]),this.networkStatsbeatMeter.addBatchObservableCallback(this.retryCallback.bind(this),[this.retryCountGauge]),this.networkStatsbeatMeter.addBatchObservableCallback(this.throttleCallback.bind(this),[this.throttleCountGauge]),this.networkStatsbeatMeter.addBatchObservableCallback(this.exceptionCallback.bind(this),[this.exceptionCountGauge]),this.disableNonEssentialStatsbeat||((e=this.readFailureGauge)==null||e.addCallback(this.readFailureCallback.bind(this)),(t=this.writeFailureGauge)==null||t.addCallback(this.writeFailureCallback.bind(this))),this.averageDurationGauge.addCallback(this.durationCallback.bind(this))}catch{n.diag.debug(`Call to get the resource provider failed.`)}}successCallback(e){let t=this.getNetworkStatsbeatCounter(this.endpointUrl,this.host);if(t.totalSuccessfulRequestCount>0){let n=Object.assign(Object.assign({},this.commonProperties),this.networkProperties);e.observe(t.totalSuccessfulRequestCount,n),t.totalSuccessfulRequestCount=0}}failureCallback(e){let t=this.getNetworkStatsbeatCounter(this.endpointUrl,this.host),n=Object.assign(Object.assign(Object.assign({},this.networkProperties),this.commonProperties),{statusCode:0});for(let r=0;r<t.totalFailedRequestCount.length;r++)t.totalFailedRequestCount[r].count>0&&(n.statusCode=t.totalFailedRequestCount[r].statusCode,e.observe(this.failureCountGauge,t.totalFailedRequestCount[r].count,Object.assign({},n)),t.totalFailedRequestCount[r].count=0)}retryCallback(e){let t=this.getNetworkStatsbeatCounter(this.endpointUrl,this.host),n=Object.assign(Object.assign(Object.assign({},this.networkProperties),this.commonProperties),{statusCode:0});for(let r=0;r<t.retryCount.length;r++)t.retryCount[r].count>0&&(n.statusCode=t.retryCount[r].statusCode,e.observe(this.retryCountGauge,t.retryCount[r].count,Object.assign({},n)),t.retryCount[r].count=0)}throttleCallback(e){let t=this.getNetworkStatsbeatCounter(this.endpointUrl,this.host),n=Object.assign(Object.assign(Object.assign({},this.networkProperties),this.commonProperties),{statusCode:0});for(let r=0;r<t.throttleCount.length;r++)t.throttleCount[r].count>0&&(n.statusCode=t.throttleCount[r].statusCode,e.observe(this.throttleCountGauge,t.throttleCount[r].count,Object.assign({},n)),t.throttleCount[r].count=0)}exceptionCallback(e){let t=this.getNetworkStatsbeatCounter(this.endpointUrl,this.host),n=Object.assign(Object.assign(Object.assign({},this.networkProperties),this.commonProperties),{exceptionType:``});for(let r=0;r<t.exceptionCount.length;r++)t.exceptionCount[r].count>0&&(n.exceptionType=t.exceptionCount[r].exceptionType,e.observe(this.exceptionCountGauge,t.exceptionCount[r].count,Object.assign({},n)),t.exceptionCount[r].count=0)}durationCallback(e){let t=this.getNetworkStatsbeatCounter(this.endpointUrl,this.host),n=Object.assign(Object.assign({},this.networkProperties),this.commonProperties);for(let e=0;e<this.networkStatsbeatCollection.length;e++){let t=this.networkStatsbeatCollection[e];t.time=Number(new Date);let n=t.totalRequestCount-t.lastRequestCount||0;n>0?t.averageRequestExecutionTime=(t.intervalRequestExecutionTime-t.lastIntervalRequestExecutionTime)/n||0:t.averageRequestExecutionTime=0,t.lastIntervalRequestExecutionTime=t.intervalRequestExecutionTime,t.lastRequestCount=t.totalRequestCount,t.lastTime=t.time}t.averageRequestExecutionTime>0&&(e.observe(t.averageRequestExecutionTime,n),t.averageRequestExecutionTime=0)}readFailureCallback(e){let t=this.getNetworkStatsbeatCounter(this.endpointUrl,this.host);if(t.totalReadFailureCount>0){let n=Object.assign(Object.assign({},this.commonProperties),this.networkProperties);e.observe(t.totalReadFailureCount,n),t.totalReadFailureCount=0}}writeFailureCallback(e){let t=this.getNetworkStatsbeatCounter(this.endpointUrl,this.host);if(t.totalWriteFailureCount>0){let n=Object.assign(Object.assign({},this.commonProperties),this.networkProperties);e.observe(t.totalWriteFailureCount,n),t.totalWriteFailureCount=0}}countSuccess(e){if(!this.isInitialized)return;let t=this.getNetworkStatsbeatCounter(this.endpointUrl,this.host);t.totalRequestCount++,t.totalSuccessfulRequestCount++,t.intervalRequestExecutionTime+=e}countFailure(e,t){if(!this.isInitialized)return;let n=this.getNetworkStatsbeatCounter(this.endpointUrl,this.host),r=n.totalFailedRequestCount.find(e=>t===e.statusCode);r?r.count++:n.totalFailedRequestCount.push({statusCode:t,count:1}),n.totalRequestCount++,n.intervalRequestExecutionTime+=e}countRetry(e){if(!this.isInitialized)return;let t=this.getNetworkStatsbeatCounter(this.endpointUrl,this.host),n=t.retryCount.find(t=>e===t.statusCode);n?n.count++:t.retryCount.push({statusCode:e,count:1})}countThrottle(e){if(!this.isInitialized)return;let t=this.getNetworkStatsbeatCounter(this.endpointUrl,this.host),n=t.throttleCount.find(t=>e===t.statusCode);n?n.count++:t.throttleCount.push({statusCode:e,count:1})}countReadFailure(){if(!this.isInitialized||this.disableNonEssentialStatsbeat)return;let e=this.getNetworkStatsbeatCounter(this.endpointUrl,this.host);e.totalReadFailureCount++}countWriteFailure(){if(!this.isInitialized||this.disableNonEssentialStatsbeat)return;let e=this.getNetworkStatsbeatCounter(this.endpointUrl,this.host);e.totalWriteFailureCount++}countException(e){if(!this.isInitialized)return;let t=this.getNetworkStatsbeatCounter(this.endpointUrl,this.host),n=t.exceptionCount.find(t=>e.name===t.exceptionType);n?n.count++:t.exceptionCount.push({exceptionType:e.name,count:1})}getNetworkStatsbeatCounter(e,t){for(let n=0;n<this.networkStatsbeatCollection.length;n++)if(e===this.networkStatsbeatCollection[n].endpoint&&t===this.networkStatsbeatCollection[n].host)return this.networkStatsbeatCollection[n];let n=new o.NetworkStatsbeat(e,t);return this.networkStatsbeatCollection.push(n),n}getShortHost(e){let t=e;try{let n=new RegExp(/^https?:\/\/(?:www\.)?([^/.-]+)/).exec(e);n!==null&&n.length>1&&(t=n[1]),t=t.replace(`.in.applicationinsights.azure.com`,``)}catch{n.diag.debug(`Failed to get the short host name.`)}return t}static getInstance(t){return e.instance||=new e(t),e.instance}};e.NetworkStatsbeatMetrics=u,u.instance=null})),JI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.LongIntervalStatsbeatMetrics=void 0;let t=(kM(),d(Gj)),n=(Jd(),d(Kd)),r=uN(),i=HI(),a=t.__importStar(Uj()),o=WI(),s=UI(),c=KI(),l=GI();var u=class e extends o.StatsbeatMetrics{constructor(e){super(),this.statsCollectionLongInterval=864e5,this.attach=(0,l.getAttachType)(),this.feature=0,this.instrumentation=0,this.isInitialized=!1,this.connectionString=super.getConnectionString(e.endpointUrl);let t={connectionString:this.connectionString,disableOfflineStorage:e.disableOfflineStorage};this.setFeatures(),this.longIntervalAzureExporter=new c.AzureMonitorStatsbeatExporter(t);let n={exporter:this.longIntervalAzureExporter,exportIntervalMillis:Number(process.env.LONG_INTERVAL_EXPORT_MILLIS)||this.statsCollectionLongInterval};this.longIntervalMetricReader=new i.PeriodicExportingMetricReader(n),this.longIntervalStatsbeatMeterProvider=new i.MeterProvider({readers:[this.longIntervalMetricReader]}),this.longIntervalStatsbeatMeter=this.longIntervalStatsbeatMeterProvider.getMeter(`Azure Monitor Long Interval Statsbeat`),this.runtimeVersion=process.version,this.language=s.STATSBEAT_LANGUAGE,this.version=a.packageVersion,this.cikey=e.instrumentationKey,this.featureStatsbeatGauge=this.longIntervalStatsbeatMeter.createObservableGauge(s.StatsbeatCounter.FEATURE),this.attachStatsbeatGauge=this.longIntervalStatsbeatMeter.createObservableGauge(s.StatsbeatCounter.ATTACH),this.isInitialized=!0,this.initialize(),this.commonProperties={os:this.os,rp:this.resourceProvider,cikey:this.cikey,runtimeVersion:this.runtimeVersion,language:this.language,version:this.version,attach:this.attach},this.attachProperties={rpId:this.resourceIdentifier}}async initialize(){try{await this.getResourceProvider(),this.attachStatsbeatGauge.addCallback(this.attachCallback.bind(this)),this.longIntervalStatsbeatMeter.addBatchObservableCallback(this.getEnvironmentStatus.bind(this),[this.featureStatsbeatGauge]),setTimeout(async()=>{try{let e=await this.longIntervalMetricReader.collect();e?this.longIntervalAzureExporter.export(e.resourceMetrics,e=>{e.code!==r.ExportResultCode.SUCCESS&&n.diag.debug(`LongIntervalStatsbeat: metrics export failed (error ${e.error})`)}):n.diag.debug(`LongIntervalStatsbeat: No metrics collected`)}catch(e){n.diag.debug(`LongIntervalStatsbeat: Error collecting metrics: ${e}`)}},15e3)}catch{n.diag.debug(`Call to get the resource provider failed.`)}}getEnvironmentStatus(e){this.setFeatures();let t;this.instrumentation>0&&(t=Object.assign(Object.assign({},this.commonProperties),{feature:this.instrumentation,type:s.StatsbeatFeatureType.INSTRUMENTATION}),e.observe(this.featureStatsbeatGauge,1,Object.assign({},t))),this.feature>0&&(t=Object.assign(Object.assign({},this.commonProperties),{feature:this.feature,type:s.StatsbeatFeatureType.FEATURE}),e.observe(this.featureStatsbeatGauge,1,Object.assign({},t)))}setFeatures(){let e=process.env.AZURE_MONITOR_STATSBEAT_FEATURES;if(e)try{this.feature=JSON.parse(e).feature,this.instrumentation=JSON.parse(e).instrumentation}catch(e){n.diag.debug(`LongIntervalStatsbeat: Failed to parse features/instrumentations (error ${e})`)}}attachCallback(e){let t=Object.assign(Object.assign({},this.commonProperties),this.attachProperties);e.observe(1,t)}shutdown(){return this.longIntervalStatsbeatMeterProvider.shutdown()}static getInstance(t){return e.instance||=new e(t),e.instance}};e.LongIntervalStatsbeatMetrics=u,u.instance=null})),YI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.isRetriable=t,e.msToTimeSpan=n;function t(e){return e===206||e===401||e===403||e===408||e===429||e===439||e===500||e===502||e===503||e===504}function n(e){(isNaN(e)||e<0)&&(e=0);let t=(e/1e3%60).toFixed(7).replace(/0{0,4}$/,``),n=``+Math.floor(e/(1e3*60))%60,r=``+Math.floor(e/(1e3*60*60))%24,i=Math.floor(e/(1e3*60*60*24));return t=t.indexOf(`.`)<2?`0`+t:t,n=n.length<2?`0`+n:n,r=r.length<2?`0`+r:r,(i>0?i+`.`:``)+r+`:`+n+`:`+t}})),XI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BaseSender=void 0;let t=(Jd(),d(Kd)),n=gN(),r=uN(),i=qI(),a=JI(),o=UI(),s=YI(),c=AM();e.BaseSender=class{constructor(e){this.statsbeatFailureCount=0,this.batchSendRetryIntervalMs=6e4,this.numConsecutiveRedirects=0,this.disableOfflineStorage=e.exporterOptions.disableOfflineStorage||!1,this.persister=new n.FileSystemPersist(e.instrumentationKey,e.exporterOptions),e.trackStatsbeat&&(this.networkStatsbeatMetrics=i.NetworkStatsbeatMetrics.getInstance({instrumentationKey:e.instrumentationKey,endpointUrl:e.endpointUrl,disableOfflineStorage:this.disableOfflineStorage}),this.longIntervalStatsbeatMetrics=a.LongIntervalStatsbeatMetrics.getInstance({instrumentationKey:e.instrumentationKey,endpointUrl:e.endpointUrl,disableOfflineStorage:this.disableOfflineStorage})),this.retryTimer=null,this.isStatsbeatSender=e.isStatsbeatSender||!1}async exportEnvelopes(e){var n,i,a,c,l,u,d,f,p,m;if(t.diag.info(`Exporting ${e.length} envelope(s)`),e.length<1)return{code:r.ExportResultCode.SUCCESS};try{let o=new Date().getTime(),{result:d,statusCode:f}=await this.send(e),p=new Date().getTime()-o;if(this.numConsecutiveRedirects=0,f===200)return this.retryTimer||(this.retryTimer=setTimeout(()=>{this.retryTimer=null,this.sendFirstPersistedFile()},this.batchSendRetryIntervalMs),this.retryTimer.unref()),this.isStatsbeatSender||(n=this.networkStatsbeatMetrics)==null||n.countSuccess(p),{code:r.ExportResultCode.SUCCESS};if(f&&(0,s.isRetriable)(f)){if(f===429||f===439)return this.isStatsbeatSender||(i=this.networkStatsbeatMetrics)==null||i.countThrottle(f),{code:r.ExportResultCode.SUCCESS};if(d){t.diag.info(d);let n=JSON.parse(d),i=[];return n.itemsAccepted>0&&f===206&&!this.isStatsbeatSender&&((a=this.networkStatsbeatMetrics)==null||a.countSuccess(p)),n.errors&&n.errors.forEach(t=>{t.statusCode&&(0,s.isRetriable)(t.statusCode)&&i.push(e[t.index])}),i.length>0?(this.isStatsbeatSender||(c=this.networkStatsbeatMetrics)==null||c.countRetry(f),await this.persist(i)):(this.isStatsbeatSender||(l=this.networkStatsbeatMetrics)==null||l.countFailure(p,f),{code:r.ExportResultCode.FAILED})}else return this.isStatsbeatSender||(u=this.networkStatsbeatMetrics)==null||u.countRetry(f),await this.persist(e)}else return this.networkStatsbeatMetrics&&!this.isStatsbeatSender?f&&this.networkStatsbeatMetrics.countFailure(p,f):this.incrementStatsbeatFailure(),{code:r.ExportResultCode.FAILED}}catch(n){let i=n;if(i.statusCode&&(i.statusCode===307||i.statusCode===308))if(this.numConsecutiveRedirects++,this.numConsecutiveRedirects<10){if(i.response&&i.response.headers){let t=i.response.headers.get(`location`);if(t)return this.handlePermanentRedirect(t),this.exportEnvelopes(e)}}else{let e=Error(`Circular redirect`);return this.isStatsbeatSender||(d=this.networkStatsbeatMetrics)==null||d.countException(e),{code:r.ExportResultCode.FAILED,error:e}}else if(i.statusCode&&(0,s.isRetriable)(i.statusCode)&&!this.isStatsbeatSender)return(f=this.networkStatsbeatMetrics)==null||f.countRetry(i.statusCode),this.persist(e);else if(i.statusCode===400&&i.message.includes(`Invalid instrumentation key`))return this.shutdownStatsbeat(),{code:r.ExportResultCode.SUCCESS};else if(i.statusCode&&this.isStatsbeatSender&&(0,o.isStatsbeatShutdownStatus)(i.statusCode))return this.incrementStatsbeatFailure(),{code:r.ExportResultCode.SUCCESS};return this.isRetriableRestError(i)?(i.statusCode&&!this.isStatsbeatSender&&((p=this.networkStatsbeatMetrics)==null||p.countRetry(i.statusCode)),this.isStatsbeatSender||t.diag.error(`Retrying due to transient client side error. Error message:`,i.message),this.persist(e)):(this.isStatsbeatSender||(m=this.networkStatsbeatMetrics)==null||m.countException(i),this.isStatsbeatSender||t.diag.error(`Envelopes could not be exported and are not retriable. Error message:`,i.message),{code:r.ExportResultCode.FAILED,error:i})}}async persist(e){var t;try{return await this.persister.push(e)?{code:r.ExportResultCode.SUCCESS}:{code:r.ExportResultCode.FAILED,error:Error(`Failed to persist envelope in disk.`)}}catch(e){return this.isStatsbeatSender||(t=this.networkStatsbeatMetrics)==null||t.countWriteFailure(),{code:r.ExportResultCode.FAILED,error:e}}}incrementStatsbeatFailure(){this.statsbeatFailureCount++,this.statsbeatFailureCount>o.MAX_STATSBEAT_FAILURES&&this.shutdownStatsbeat()}shutdownStatsbeat(){var e;this.networkStatsbeatMetrics&&this.networkStatsbeatMetrics.shutdown(),(e=this.longIntervalStatsbeatMetrics)==null||e.shutdown(),this.statsbeatFailureCount=0}async sendFirstPersistedFile(){var e;try{let e=await this.persister.shift();e&&await this.send(e)}catch(n){this.isStatsbeatSender||(e=this.networkStatsbeatMetrics)==null||e.countReadFailure(),t.diag.warn(`Failed to fetch persisted file`,n)}}isRetriableRestError(e){let t=Object.values(c.RetriableRestErrorTypes);return!!(e&&e.code&&t.includes(e.code))}}})),ZI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.HttpSender=void 0;let t=(kM(),d(Gj)).__importDefault(require(`node:url`)),n=(Jd(),d(Kd)),r=DF(),i=JF(),a=XI();e.HttpSender=class extends a.BaseSender{constructor(e){super(e),this.appInsightsClientOptions=Object.assign({host:e.endpointUrl},e.exporterOptions),this.appInsightsClientOptions.credential&&(e.aadAudience?this.appInsightsClientOptions.credentialScopes=[e.aadAudience]:this.appInsightsClientOptions.credentialScopes=[`https://monitor.azure.com//.default`]),this.appInsightsClient=new i.ApplicationInsightsClient(this.appInsightsClientOptions),this.appInsightsClient.pipeline.removePolicy({name:r.redirectPolicyName})}async send(e){let t={},n;function r(e,r){n=e,t.onResponse&&t.onResponse(e,r)}return await this.appInsightsClient.track(e,Object.assign(Object.assign({},t),{onResponse:r})),{statusCode:n?.status,result:n?.bodyAsText??``}}async shutdown(){n.diag.info(`HttpSender shutting down`)}handlePermanentRedirect(e){if(e){let n=new t.default.URL(e);n&&n.host&&(this.appInsightsClient.host=`https://`+n.host)}}}})),QI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.Context=void 0,e.getInstance=u;let t=(kM(),d(Gj)),n=t.__importStar(require(`node:os`)),r=uN(),i=(PA(),d(NA)),a=JF(),o=t.__importStar(Uj()),s=AM(),c=null;var l=class e{constructor(){this.tags={},this._loadDeviceContext(),this._loadInternalContext()}_loadDeviceContext(){this.tags[a.KnownContextTagKeys.AiDeviceOsVersion]=n&&`${n.type()} ${n.release()}`}_loadInternalContext(){let{node:t}=process.versions;[e.nodeVersion]=t.split(`.`),e.opentelemetryVersion=r.SDK_INFO[i.ATTR_TELEMETRY_SDK_VERSION],e.sdkVersion=o.packageVersion;let n=process.env[s.ENV_AZURE_MONITOR_PREFIX]?process.env[s.ENV_AZURE_MONITOR_PREFIX]:``,c=this._getVersion(),l=`${n}node${e.nodeVersion}:otel${e.opentelemetryVersion}:${c}`;this.tags[a.KnownContextTagKeys.AiInternalSdkVersion]=l}_getVersion(){return process.env[s.ENV_APPLICATIONINSIGHTS_SHIM_VERSION]?`sha${process.env[s.ENV_APPLICATIONINSIGHTS_SHIM_VERSION]}`:process.env[s.ENV_AZURE_MONITOR_DISTRO_VERSION]?`dst${process.env[s.ENV_AZURE_MONITOR_DISTRO_VERSION]}`:`ext${e.sdkVersion}`}};e.Context=l,l.sdkVersion=null,l.opentelemetryVersion=null,l.nodeVersion=``;function u(){return c||=new l,c}})),$I=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),(kM(),d(Gj)).__exportStar(QI(),e)})),eL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=(kM(),d(Gj));t.__exportStar(fN(),e),t.__exportStar(gN(),e),t.__exportStar(ZI(),e),t.__exportStar($I(),e)})),tL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),(kM(),d(Gj)).__exportStar(eL(),e)})),nL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.hrTimeToDate=l,e.createTagsFromResource=u,e.isSqlDB=m,e.getUrl=h,e.getDependencyTarget=g,e.createResourceMetricEnvelope=_,e.serializeAttribute=v,e.shouldCreateResourceMetric=y,e.isSyntheticSource=b;let t=(kM(),d(Gj)).__importDefault(require(`node:os`)),n=(PA(),d(NA)),r=dN(),i=tL(),a=JF(),o=uN(),s=AM(),c=aL();function l(e){return new Date((0,o.hrTimeToNanoseconds)(e)/1e6)}function u(e){let t=(0,i.getInstance)(),r=Object.assign({},t.tags);return e&&e.attributes&&(r[a.KnownContextTagKeys.AiCloudRole]=f(e),r[a.KnownContextTagKeys.AiCloudRoleInstance]=p(e),e.attributes[n.SEMRESATTRS_DEVICE_ID]&&(r[a.KnownContextTagKeys.AiDeviceId]=String(e.attributes[n.SEMRESATTRS_DEVICE_ID])),e.attributes[n.SEMRESATTRS_DEVICE_MODEL_NAME]&&(r[a.KnownContextTagKeys.AiDeviceModel]=String(e.attributes[n.SEMRESATTRS_DEVICE_MODEL_NAME])),e.attributes[n.SEMRESATTRS_SERVICE_VERSION]&&(r[a.KnownContextTagKeys.AiApplicationVer]=String(e.attributes[n.SEMRESATTRS_SERVICE_VERSION]))),r}function f(e){let t=``,r=e.attributes[n.SEMRESATTRS_SERVICE_NAME],i=e.attributes[n.SEMRESATTRS_SERVICE_NAMESPACE];if(r)if(String(r).startsWith(`unknown_service`))t=i?`${i}.${r}`:String(r);else return i?`${i}.${r}`:String(r);let a=e.attributes[n.SEMRESATTRS_K8S_DEPLOYMENT_NAME];if(a)return String(a);let o=e.attributes[n.SEMRESATTRS_K8S_REPLICASET_NAME];if(o)return String(o);let s=e.attributes[n.SEMRESATTRS_K8S_STATEFULSET_NAME];if(s)return String(s);let c=e.attributes[n.SEMRESATTRS_K8S_JOB_NAME];if(c)return String(c);let l=e.attributes[n.SEMRESATTRS_K8S_CRONJOB_NAME];if(l)return String(l);let u=e.attributes[n.SEMRESATTRS_K8S_DAEMONSET_NAME];return u?String(u):t}function p(e){let r=e.attributes[n.SEMRESATTRS_K8S_POD_NAME];if(r)return String(r);let i=e.attributes[n.SEMRESATTRS_SERVICE_INSTANCE_ID];return i?String(i):t.default&&t.default.hostname()}function m(e){return e===n.DBSYSTEMVALUES_DB2||e===n.DBSYSTEMVALUES_DERBY||e===n.DBSYSTEMVALUES_MARIADB||e===n.DBSYSTEMVALUES_MSSQL||e===n.DBSYSTEMVALUES_ORACLE||e===n.DBSYSTEMVALUES_SQLITE||e===n.DBSYSTEMVALUES_OTHER_SQL||e===n.DBSYSTEMVALUES_HSQLDB||e===n.DBSYSTEMVALUES_H2}function h(e){if(!e)return``;if((0,c.getHttpMethod)(e)){let t=(0,c.getHttpUrl)(e);if(t)return String(t);{let t=(0,c.getHttpScheme)(e),n=(0,c.getHttpTarget)(e);if(t&&n){let r=(0,c.getHttpHost)(e);if(r)return`${t}://${r}${n}`;{let r=(0,c.getNetPeerPort)(e);if(r){let i=(0,c.getNetPeerName)(e);if(i)return`${t}://${i}:${r}${n}`;{let i=(0,c.getPeerIp)(e);if(i)return`${t}://${i}:${r}${n}`}}}}}}return``}function g(e){if(!e)return``;let t=e[n.SEMATTRS_PEER_SERVICE],r=(0,c.getHttpHost)(e),i=(0,c.getHttpUrl)(e),a=(0,c.getNetPeerName)(e),o=(0,c.getPeerIp)(e);return t?String(t):r?String(r):i?String(i):a?String(a):o?String(o):``}function _(e,t){if(e&&e.attributes){let r=u(e),i={};for(let t of Object.keys(e.attributes))t.startsWith(`_MS.`)||t===n.ATTR_TELEMETRY_SDK_VERSION||t===n.ATTR_TELEMETRY_SDK_LANGUAGE||t===n.ATTR_TELEMETRY_SDK_NAME||(i[t]=e.attributes[t]);if(Object.keys(i).length>0){let e={version:2,metrics:[{name:`_OTELRESOURCE_`,value:1}],properties:i};return{name:`Microsoft.ApplicationInsights.Metric`,time:new Date,sampleRate:100,instrumentationKey:t,version:1,data:{baseType:`MetricData`,baseData:e},tags:r}}}}function v(e){if(typeof e==`object`)if(e instanceof Error)try{return JSON.stringify(e,Object.getOwnPropertyNames(e))}catch{return String(e)}else if(e instanceof Uint8Array)return String(e);else try{return JSON.stringify(e)}catch{return String(e)}return String(e)}function y(){return process.env[s.ENV_OPENTELEMETRY_RESOURCE_METRIC_DISABLED]?.toLowerCase()!==`true`}function b(e){return!!e[r.experimentalOpenTelemetryValues.SYNTHETIC_TYPE]}})),rL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MessageBusDestination=e.MicrosoftEventHub=e.AzNamespace=void 0,e.AzNamespace=`az.namespace`,e.MicrosoftEventHub=`Microsoft.EventHub`,e.MessageBusDestination=`message_bus.destination`})),iL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.parseEventHubSpan=void 0;let t=(Jd(),d(Kd)),n=uN(),r=(PA(),d(NA)),i=Uj(),a=rL(),o=e=>{let t=0,r=0,a=(0,n.hrTimeToMilliseconds)(e.startTime);return e.links.forEach(({attributes:e})=>{let n=e?.[i.ENQUEUED_TIME];n&&(t+=1,r+=a-(parseFloat(n.toString())||0))}),Math.max(r/(t||1),0)};e.parseEventHubSpan=(e,n)=>{let s=e.attributes[a.AzNamespace],c=(e.attributes[r.SEMATTRS_NET_PEER_NAME]||e.attributes[`peer.address`]||`unknown`).replace(/\/$/g,``),l=e.attributes[a.MessageBusDestination]||`unknown`;switch(e.kind){case t.SpanKind.CLIENT:n.type=s,n.target=`${c}/${l}`;break;case t.SpanKind.PRODUCER:n.type=`Queue Message | ${s}`,n.target=`${c}/${l}`;break;case t.SpanKind.CONSUMER:n.type=`Queue Message | ${s}`,n.source=`${c}/${l}`,n.measurements=Object.assign(Object.assign({},n.measurements),{[i.TIME_SINCE_ENQUEUED]:o(e)});break;default:}}})),aL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.readableSpanToEnvelope=_,e.spanEventsToEnvelopes=v,e.getPeerIp=y,e.getLocationIp=b,e.getHttpClientIp=x,e.getUserAgent=S,e.getHttpUrl=C,e.getHttpMethod=w,e.getHttpStatusCode=T,e.getHttpScheme=E,e.getHttpTarget=D,e.getHttpHost=O,e.getNetPeerName=k,e.getNetPeerPort=A;let t=uN(),n=(Jd(),d(Kd)),r=(PA(),d(NA)),i=nL(),a=dN(),o=iL(),s=Uj(),c=rL(),l=JF(),u=YI();function f(e){let t=(0,i.createTagsFromResource)(e.resource);t[l.KnownContextTagKeys.AiOperationId]=e.spanContext().traceId,e.parentSpanContext?.spanId&&(t[l.KnownContextTagKeys.AiOperationParentId]=e.parentSpanContext.spanId);let o=e.attributes[r.SEMATTRS_ENDUSER_ID];o&&(t[l.KnownContextTagKeys.AiUserId]=String(o));let s=S(e.attributes);if(s&&(t[`ai.user.userAgent`]=String(s)),(0,i.isSyntheticSource)(e.attributes)&&(t[l.KnownContextTagKeys.AiOperationSyntheticSource]=`True`),e.kind===n.SpanKind.SERVER){let n=w(e.attributes);if(b(t,e.attributes),n){let i=e.attributes[r.ATTR_HTTP_ROUTE],o=C(e.attributes);if(t[l.KnownContextTagKeys.AiOperationName]=e.name,i)t[l.KnownContextTagKeys.AiOperationName]=String(`${n} ${i}`).substring(0,a.MaxPropertyLengths.TEN_BIT);else if(o)try{let e=new URL(String(o));t[l.KnownContextTagKeys.AiOperationName]=String(`${n} ${e.pathname}`).substring(0,a.MaxPropertyLengths.TEN_BIT)}catch{}}else t[l.KnownContextTagKeys.AiOperationName]=e.name}else e.attributes[l.KnownContextTagKeys.AiOperationName]&&(t[l.KnownContextTagKeys.AiOperationName]=e.attributes[l.KnownContextTagKeys.AiOperationName]);return t}function p(e){let t={};if(e)for(let n of Object.keys(e))n.startsWith(`_MS.`)&&!a.internalMicrosoftAttributes.includes(n)||n.startsWith(`microsoft.`)||a.legacySemanticValues.includes(n)||a.httpSemanticValues.includes(n)||n===l.KnownContextTagKeys.AiOperationName||(t[n]=(0,i.serializeAttribute)(e[n]));return t}function m(e){let t=p(e.attributes),n={},r=e.links.map(e=>({operation_Id:e.context.traceId,id:e.context.spanId}));return r.length>0&&(t[s.MS_LINKS]=JSON.stringify(r)),[t,n]}function h(e){let a={name:e.name,id:`${e.spanContext().spanId}`,success:e.status?.code!==n.SpanStatusCode.ERROR,resultCode:`0`,type:`Dependency`,duration:(0,u.msToTimeSpan)((0,t.hrTimeToMilliseconds)(e.duration)),version:2};e.kind===n.SpanKind.PRODUCER&&(a.type=s.DependencyTypes.QueueMessage),e.kind===n.SpanKind.INTERNAL&&e.parentSpanContext&&(a.type=s.DependencyTypes.InProc);let o=w(e.attributes),c=e.attributes[r.SEMATTRS_DB_SYSTEM],l=e.attributes[r.SEMATTRS_RPC_SYSTEM];if(o){let t=C(e.attributes);if(t)try{a.name=`${o} ${new URL(String(t)).pathname}`}catch{}a.type=s.DependencyTypes.Http,a.data=(0,i.getUrl)(e.attributes);let n=T(e.attributes);n&&(a.resultCode=String(n));let r=(0,i.getDependencyTarget)(e.attributes);if(r){try{let e=new RegExp(/(https?)(:\/\/.*)(:\d+)(\S*)/).exec(r);if(e!==null){let t=e[1],n=e[3];(t===`https`&&n===`:443`||t===`http`&&n===`:80`)&&(r=e[1]+e[2]+e[4])}}catch{}a.target=`${r}`}}else if(c){String(c)===r.DBSYSTEMVALUES_MYSQL?a.type=`mysql`:String(c)===r.DBSYSTEMVALUES_POSTGRESQL?a.type=`postgresql`:String(c)===r.DBSYSTEMVALUES_MONGODB?a.type=`mongodb`:String(c)===r.DBSYSTEMVALUES_REDIS?a.type=`redis`:(0,i.isSqlDB)(String(c))?a.type=`SQL`:a.type=String(c);let t=e.attributes[r.SEMATTRS_DB_STATEMENT],n=e.attributes[r.SEMATTRS_DB_OPERATION];t?a.data=String(t):n&&(a.data=String(n));let o=(0,i.getDependencyTarget)(e.attributes),s=e.attributes[r.SEMATTRS_DB_NAME];o?a.target=s?`${o}|${s}`:`${o}`:a.target=s?`${s}`:`${c}`}else if(l){l===s.DependencyTypes.Wcf?a.type=s.DependencyTypes.Wcf:a.type=s.DependencyTypes.Grpc;let t=e.attributes[r.SEMATTRS_RPC_GRPC_STATUS_CODE];t&&(a.resultCode=String(t));let n=(0,i.getDependencyTarget)(e.attributes);n?a.target=`${n}`:l&&(a.target=String(l))}return a}function g(e){let a={id:`${e.spanContext().spanId}`,success:e.status.code!==n.SpanStatusCode.ERROR&&(Number(T(e.attributes))||0)<400,responseCode:`0`,duration:(0,u.msToTimeSpan)((0,t.hrTimeToMilliseconds)(e.duration)),version:2,source:void 0},o=w(e.attributes),s=e.attributes[r.SEMATTRS_RPC_GRPC_STATUS_CODE];if(o){a.url=(0,i.getUrl)(e.attributes);let t=T(e.attributes);t&&(a.responseCode=String(t))}else s&&(a.responseCode=String(s));return a}function _(e,t){let r,u,d,p=(0,i.hrTimeToDate)(e.startTime),_=t,v=f(e),[y,b]=m(e);switch(e.kind){case n.SpanKind.CLIENT:case n.SpanKind.PRODUCER:case n.SpanKind.INTERNAL:r=`Microsoft.ApplicationInsights.RemoteDependency`,u=`RemoteDependencyData`,d=h(e);break;case n.SpanKind.SERVER:case n.SpanKind.CONSUMER:r=`Microsoft.ApplicationInsights.Request`,u=`RequestData`,d=g(e),d.name=v[l.KnownContextTagKeys.AiOperationName];break;default:throw n.diag.error(`Unsupported span kind ${e.kind}`),Error(`Unsupported span kind ${e.kind}`)}let x=100;if(e.attributes[s.AzureMonitorSampleRate]&&(x=Number(e.attributes[s.AzureMonitorSampleRate])),e.attributes[c.AzNamespace]&&(e.kind===n.SpanKind.INTERNAL&&(d.type=`${s.DependencyTypes.InProc} | ${e.attributes[c.AzNamespace]}`),e.attributes[c.AzNamespace]===c.MicrosoftEventHub&&(0,o.parseEventHubSpan)(e,d)),d.id&&=d.id.substring(0,a.MaxPropertyLengths.NINE_BIT),d.name&&=d.name.substring(0,a.MaxPropertyLengths.TEN_BIT),d.resultCode&&=String(d.resultCode).substring(0,a.MaxPropertyLengths.TEN_BIT),d.data&&=String(d.data).substring(0,a.MaxPropertyLengths.THIRTEEN_BIT),d.type&&=String(d.type).substring(0,a.MaxPropertyLengths.TEN_BIT),d.target&&=String(d.target).substring(0,a.MaxPropertyLengths.TEN_BIT),d.properties)for(let e of Object.keys(d.properties))d.properties[e]=d.properties[e].substring(0,a.MaxPropertyLengths.THIRTEEN_BIT);return{name:r,sampleRate:x,time:p,instrumentationKey:_,tags:v,version:1,data:{baseType:u,baseData:Object.assign(Object.assign({},d),{properties:y,measurements:b})}}}function v(e,t){let n=[];return e.events&&e.events.forEach(o=>{let c,u=(0,i.hrTimeToDate)(o.time),d=``,f,m=p(o.attributes),h=(0,i.createTagsFromResource)(e.resource);h[l.KnownContextTagKeys.AiOperationId]=e.spanContext().traceId;let g=e.spanContext().spanId;if(g&&(h[l.KnownContextTagKeys.AiOperationParentId]=g),o.name===`exception`){d=`Microsoft.ApplicationInsights.Exception`,c=`ExceptionData`;let e=``,t=`Exception`,n=``,i=!1;if(o.attributes){e=String(o.attributes[r.SEMATTRS_EXCEPTION_TYPE]),n=String(o.attributes[r.SEMATTRS_EXCEPTION_STACKTRACE]),n&&(i=!0);let a=o.attributes[r.SEMATTRS_EXCEPTION_MESSAGE];a&&(t=String(a));let s=o.attributes[r.SEMATTRS_EXCEPTION_ESCAPED];s!==void 0&&(m[r.SEMATTRS_EXCEPTION_ESCAPED]=String(s))}f={exceptions:[{typeName:e,message:t,stack:n,hasFullStack:i}],version:2,properties:m}}else d=`Microsoft.ApplicationInsights.Message`,c=`MessageData`,f={message:o.name,version:2,properties:m};let _=100;if(e.attributes[s.AzureMonitorSampleRate]&&(_=Number(e.attributes[s.AzureMonitorSampleRate])),f.message&&=String(f.message).substring(0,a.MaxPropertyLengths.FIFTEEN_BIT),f.properties)for(let e of Object.keys(f.properties))f.properties[e]=f.properties[e].substring(0,a.MaxPropertyLengths.THIRTEEN_BIT);let v={name:d,time:u,instrumentationKey:t,version:1,sampleRate:_,data:{baseType:c,baseData:f},tags:h};n.push(v)}),n}function y(e){if(e)return e[r.ATTR_NETWORK_PEER_ADDRESS]||e[r.SEMATTRS_NET_PEER_IP]}function b(e,t){if(t){let n=x(t),r=y(t);n?e[l.KnownContextTagKeys.AiLocationIp]=String(n):r&&(e[l.KnownContextTagKeys.AiLocationIp]=String(r))}}function x(e){if(e)return e[r.ATTR_CLIENT_ADDRESS]||e[r.SEMATTRS_HTTP_CLIENT_IP]}function S(e){if(e)return e[r.ATTR_USER_AGENT_ORIGINAL]||e[r.SEMATTRS_HTTP_USER_AGENT]}function C(e){if(e)return e[r.ATTR_URL_FULL]||e[r.SEMATTRS_HTTP_URL]}function w(e){if(e)return e[r.ATTR_HTTP_REQUEST_METHOD]||e[r.SEMATTRS_HTTP_METHOD]}function T(e){if(e)return e[r.ATTR_HTTP_RESPONSE_STATUS_CODE]||e[r.SEMATTRS_HTTP_STATUS_CODE]}function E(e){if(e)return e[r.ATTR_URL_SCHEME]||e[r.SEMATTRS_HTTP_SCHEME]}function D(e){if(e)return e[r.ATTR_URL_PATH]?e[r.ATTR_URL_PATH]:e[r.ATTR_URL_QUERY]?e[r.ATTR_URL_QUERY]:e[r.SEMATTRS_HTTP_TARGET]}function O(e){if(e)return e[r.ATTR_SERVER_ADDRESS]||e[r.SEMATTRS_HTTP_HOST]}function k(e){if(e)return e[r.ATTR_CLIENT_ADDRESS]||e[r.SEMATTRS_NET_PEER_NAME]}function A(e){if(e)return e[r.ATTR_CLIENT_PORT]||e[r.ATTR_SERVER_PORT]||e[r.SEMATTRS_NET_PEER_PORT]}})),oL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AzureMonitorTraceExporter=void 0;let t=(Jd(),d(Kd)),n=uN(),r=MM(),i=aL(),a=nL(),o=tL();e.AzureMonitorTraceExporter=class extends r.AzureMonitorBaseExporter{constructor(e={}){super(e),this.isShutdown=!1,this.shouldCreateResourceMetric=(0,a.shouldCreateResourceMetric)(),this.sender=new o.HttpSender({endpointUrl:this.endpointUrl,instrumentationKey:this.instrumentationKey,trackStatsbeat:this.trackStatsbeat,exporterOptions:e,aadAudience:this.aadAudience}),t.diag.debug(`AzureMonitorTraceExporter was successfully setup`)}async export(e,r){if(this.isShutdown){t.diag.info(`Exporter shut down. Failed to export spans.`),setTimeout(()=>r({code:n.ExportResultCode.FAILED}),0);return}if(t.diag.info(`Exporting ${e.length} span(s). Converting to envelopes...`),e.length>0){let t=[],n=(0,a.createResourceMetricEnvelope)(e[0].resource,this.instrumentationKey);n&&this.shouldCreateResourceMetric&&t.push(n),e.forEach(e=>{t.push((0,i.readableSpanToEnvelope)(e,this.instrumentationKey));let n=(0,i.spanEventsToEnvelopes)(e,this.instrumentationKey);n.length>0&&t.push(...n)}),r(await this.sender.exportEnvelopes(t))}r({code:n.ExportResultCode.SUCCESS})}async shutdown(){return this.isShutdown=!0,t.diag.info(`AzureMonitorTraceExporter shutting down`),this.sender.shutdown()}}})),sL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AzureMonitorMetricExporter=void 0;let t=(Jd(),d(Kd)),n=HI(),r=uN(),i=MM(),a=GI(),o=tL();e.AzureMonitorMetricExporter=class extends i.AzureMonitorBaseExporter{constructor(e={}){super(e),this._isShutdown=!1,this._sender=new o.HttpSender({endpointUrl:this.endpointUrl,instrumentationKey:this.instrumentationKey,trackStatsbeat:this.trackStatsbeat,exporterOptions:e,aadAudience:this.aadAudience}),t.diag.debug(`AzureMonitorMetricExporter was successfully setup`)}async export(e,n){if(this._isShutdown){t.diag.info(`Exporter shut down. Failed to export spans.`),setTimeout(()=>n({code:r.ExportResultCode.FAILED}),0);return}t.diag.info(`Exporting ${e.scopeMetrics.length} metrics(s). Converting to envelopes...`);let i=(0,a.resourceMetricsToEnvelope)(e,this.instrumentationKey);await t.context.with((0,r.suppressTracing)(t.context.active()),async()=>{n(await this._sender.exportEnvelopes(i))})}async shutdown(){return this._isShutdown=!0,t.diag.info(`AzureMonitorMetricExporter shutting down`),this._sender.shutdown()}selectAggregationTemporality(e){return e===n.InstrumentType.UP_DOWN_COUNTER||e===n.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER?n.AggregationTemporality.CUMULATIVE:n.AggregationTemporality.DELTA}async forceFlush(){return Promise.resolve()}}})),cL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.logToEnvelope=c;let t=JF(),n=nL(),r=(PA(),d(NA)),i=dN(),a=(Jd(),d(Kd)),o=Uj(),s=aL();function c(e,t){let a=(0,n.hrTimeToDate)(e.hrTime),s=t,c=l(e),[d,g]=u(e),_,v,y,b=e.attributes[r.ATTR_EXCEPTION_STACKTRACE],x=e.attributes[r.ATTR_EXCEPTION_TYPE],S=!!(x&&b)||!1,C=!e.attributes[o.ApplicationInsightsBaseType]&&!e.attributes[o.ApplicationInsightsCustomEventName]&&!x;if(S){let t=e.attributes[r.ATTR_EXCEPTION_MESSAGE];_=o.ApplicationInsightsExceptionName,v=o.ApplicationInsightsExceptionBaseType,y={exceptions:[{typeName:String(x),message:String(t),hasFullStack:!!b,stack:String(b)}],severityLevel:String(f(e.severityNumber)),version:2}}else if(e.attributes[o.ApplicationInsightsCustomEventName])_=o.ApplicationInsightsEventName,v=o.ApplicationInsightsEventBaseType,y={name:String(e.attributes[o.ApplicationInsightsCustomEventName]),version:2},g=m(e);else if(C)_=o.ApplicationInsightsMessageName,v=o.ApplicationInsightsMessageBaseType,y={message:String(e.body),severityLevel:String(f(e.severityNumber)),version:2};else if(v=String(e.attributes[o.ApplicationInsightsBaseType]),_=p(e),y=h(e),g=m(e),!y)return;if(y.message&&=String(y.message).substring(0,i.MaxPropertyLengths.FIFTEEN_BIT),d)for(let e of Object.keys(d))d[e]=String(d[e]).substring(0,i.MaxPropertyLengths.THIRTEEN_BIT);return{name:_,sampleRate:100,time:a,instrumentationKey:s,tags:c,version:1,data:{baseType:v,baseData:Object.assign(Object.assign({},y),{properties:d,measurements:g})}}}function l(e){let r=(0,n.createTagsFromResource)(e.resource);return e.spanContext?.traceId&&(r[t.KnownContextTagKeys.AiOperationId]=e.spanContext.traceId),e.spanContext?.spanId&&(r[t.KnownContextTagKeys.AiOperationParentId]=e.spanContext.spanId),e.attributes[t.KnownContextTagKeys.AiOperationName]&&(r[t.KnownContextTagKeys.AiOperationName]=e.attributes[t.KnownContextTagKeys.AiOperationName]),(0,n.isSyntheticSource)(e.attributes)&&(r[t.KnownContextTagKeys.AiOperationSyntheticSource]=`True`),(0,s.getLocationIp)(r,e.attributes),r}function u(e){let r={},a={};if(e.attributes)for(let r of Object.keys(e.attributes))r.startsWith(`_MS.`)||r.startsWith(`microsoft`)||i.legacySemanticValues.includes(r)||i.httpSemanticValues.includes(r)||r===t.KnownContextTagKeys.AiOperationName||(a[r]=(0,n.serializeAttribute)(e.attributes[r]));return[a,r]}function f(e){if(e){if(e>0&&e<9)return t.KnownSeverityLevel.Verbose;if(e>=9&&e<13)return t.KnownSeverityLevel.Information;if(e>=13&&e<17)return t.KnownSeverityLevel.Warning;if(e>=17&&e<21)return t.KnownSeverityLevel.Error;if(e>=21&&e<25)return t.KnownSeverityLevel.Critical}}function p(e){let t=``;switch(e.attributes[o.ApplicationInsightsBaseType]){case o.ApplicationInsightsAvailabilityBaseType:t=o.ApplicationInsightsAvailabilityName;break;case o.ApplicationInsightsExceptionBaseType:t=o.ApplicationInsightsExceptionName;break;case o.ApplicationInsightsMessageBaseType:t=o.ApplicationInsightsMessageName;break;case o.ApplicationInsightsPageViewBaseType:t=o.ApplicationInsightsPageViewName;break;case o.ApplicationInsightsEventBaseType:t=o.ApplicationInsightsEventName;break}return t}function m(e){let t={};return e.body?.measurements&&(t=Object.assign({},e.body.measurements)),t}function h(e){let t={version:2};if(e.body)try{switch(e.attributes[o.ApplicationInsightsBaseType]){case o.ApplicationInsightsAvailabilityBaseType:t=e.body;break;case o.ApplicationInsightsExceptionBaseType:t=e.body;break;case o.ApplicationInsightsMessageBaseType:t=e.body;break;case o.ApplicationInsightsPageViewBaseType:t=e.body;break;case o.ApplicationInsightsEventBaseType:t=e.body;break}typeof t?.message==`object`&&(t.message=JSON.stringify(t.message))}catch{a.diag.error(`AzureMonitorLogExporter failed to parse Application Insights Telemetry`)}return t}})),lL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AzureMonitorLogExporter=void 0;let t=(Jd(),d(Kd)),n=uN(),r=MM(),i=cL(),a=tL();e.AzureMonitorLogExporter=class extends r.AzureMonitorBaseExporter{constructor(e={}){super(e),this._isShutdown=!1,this._sender=new a.HttpSender({endpointUrl:this.endpointUrl,instrumentationKey:this.instrumentationKey,trackStatsbeat:this.trackStatsbeat,exporterOptions:e,aadAudience:this.aadAudience}),t.diag.debug(`AzureMonitorLogExporter was successfully setup`)}async export(e,r){if(this._isShutdown){t.diag.info(`Exporter shut down. Failed to export spans.`),setTimeout(()=>r({code:n.ExportResultCode.FAILED}),0);return}t.diag.info(`Exporting ${e.length} logs(s). Converting to envelopes...`);let a=[];e.forEach(e=>{let t=(0,i.logToEnvelope)(e,this.instrumentationKey);t&&a.push(t)}),await t.context.with((0,n.suppressTracing)(t.context.active()),async()=>{r(await this._sender.exportEnvelopes(a))})}async shutdown(){return this._isShutdown=!0,t.diag.info(`AzureMonitorLogExporter shutting down`),this._sender.shutdown()}}})),uL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AI_OPERATION_NAME=e.ServiceApiVersion=e.AzureMonitorLogExporter=e.AzureMonitorMetricExporter=e.AzureMonitorTraceExporter=e.AzureMonitorBaseExporter=e.ApplicationInsightsSampler=void 0;var t=Wj();Object.defineProperty(e,`ApplicationInsightsSampler`,{enumerable:!0,get:function(){return t.ApplicationInsightsSampler}});var n=MM();Object.defineProperty(e,`AzureMonitorBaseExporter`,{enumerable:!0,get:function(){return n.AzureMonitorBaseExporter}});var r=oL();Object.defineProperty(e,`AzureMonitorTraceExporter`,{enumerable:!0,get:function(){return r.AzureMonitorTraceExporter}});var i=sL();Object.defineProperty(e,`AzureMonitorMetricExporter`,{enumerable:!0,get:function(){return i.AzureMonitorMetricExporter}});var a=lL();Object.defineProperty(e,`AzureMonitorLogExporter`,{enumerable:!0,get:function(){return a.AzureMonitorLogExporter}});var o=AM();Object.defineProperty(e,`ServiceApiVersion`,{enumerable:!0,get:function(){return o.ServiceApiVersion}});var s=AM();Object.defineProperty(e,`AI_OPERATION_NAME`,{enumerable:!0,get:function(){return s.AI_OPERATION_NAME}})})),dL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.isTracingSuppressed=e.unsuppressTracing=e.suppressTracing=void 0;let t=(0,(Jd(),d(Kd)).createContextKey)(`OpenTelemetry SDK Context Key SUPPRESS_TRACING`);function n(e){return e.setValue(t,!0)}e.suppressTracing=n;function r(e){return e.deleteValue(t)}e.unsuppressTracing=r;function i(e){return e.getValue(t)===!0}e.isTracingSuppressed=i})),fL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BAGGAGE_MAX_TOTAL_LENGTH=e.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS=e.BAGGAGE_MAX_NAME_VALUE_PAIRS=e.BAGGAGE_HEADER=e.BAGGAGE_ITEMS_SEPARATOR=e.BAGGAGE_PROPERTIES_SEPARATOR=e.BAGGAGE_KEY_PAIR_SEPARATOR=void 0,e.BAGGAGE_KEY_PAIR_SEPARATOR=`=`,e.BAGGAGE_PROPERTIES_SEPARATOR=`;`,e.BAGGAGE_ITEMS_SEPARATOR=`,`,e.BAGGAGE_HEADER=`baggage`,e.BAGGAGE_MAX_NAME_VALUE_PAIRS=180,e.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS=4096,e.BAGGAGE_MAX_TOTAL_LENGTH=8192})),pL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.parseKeyPairsIntoRecord=e.parsePairKeyValue=e.getKeyPairs=e.serializeKeyPairs=void 0;let t=(Jd(),d(Kd)),n=fL();function r(e){return e.reduce((e,t)=>{let r=`${e}${e===``?``:n.BAGGAGE_ITEMS_SEPARATOR}${t}`;return r.length>n.BAGGAGE_MAX_TOTAL_LENGTH?e:r},``)}e.serializeKeyPairs=r;function i(e){return e.getAllEntries().map(([e,t])=>{let r=`${encodeURIComponent(e)}=${encodeURIComponent(t.value)}`;return t.metadata!==void 0&&(r+=n.BAGGAGE_PROPERTIES_SEPARATOR+t.metadata.toString()),r})}e.getKeyPairs=i;function a(e){let r=e.split(n.BAGGAGE_PROPERTIES_SEPARATOR);if(r.length<=0)return;let i=r.shift();if(!i)return;let a=i.indexOf(n.BAGGAGE_KEY_PAIR_SEPARATOR);if(a<=0)return;let o=decodeURIComponent(i.substring(0,a).trim()),s=decodeURIComponent(i.substring(a+1).trim()),c;return r.length>0&&(c=(0,t.baggageEntryMetadataFromString)(r.join(n.BAGGAGE_PROPERTIES_SEPARATOR))),{key:o,value:s,metadata:c}}e.parsePairKeyValue=a;function o(e){let t={};return typeof e==`string`&&e.length>0&&e.split(n.BAGGAGE_ITEMS_SEPARATOR).forEach(e=>{let n=a(e);n!==void 0&&n.value.length>0&&(t[n.key]=n.value)}),t}e.parseKeyPairsIntoRecord=o})),mL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.W3CBaggagePropagator=void 0;let t=(Jd(),d(Kd)),n=dL(),r=fL(),i=pL();e.W3CBaggagePropagator=class{inject(e,a,o){let s=t.propagation.getBaggage(e);if(!s||(0,n.isTracingSuppressed)(e))return;let c=(0,i.getKeyPairs)(s).filter(e=>e.length<=r.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS).slice(0,r.BAGGAGE_MAX_NAME_VALUE_PAIRS),l=(0,i.serializeKeyPairs)(c);l.length>0&&o.set(a,r.BAGGAGE_HEADER,l)}extract(e,n,a){let o=a.get(n,r.BAGGAGE_HEADER),s=Array.isArray(o)?o.join(r.BAGGAGE_ITEMS_SEPARATOR):o;if(!s)return e;let c={};return s.length===0||(s.split(r.BAGGAGE_ITEMS_SEPARATOR).forEach(e=>{let t=(0,i.parsePairKeyValue)(e);if(t){let e={value:t.value};t.metadata&&(e.metadata=t.metadata),c[t.key]=e}}),Object.entries(c).length===0)?e:t.propagation.setBaggage(e,t.propagation.createBaggage(c))}fields(){return[r.BAGGAGE_HEADER]}}})),hL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AnchoredClock=void 0,e.AnchoredClock=class{_monotonicClock;_epochMillis;_performanceMillis;constructor(e,t){this._monotonicClock=t,this._epochMillis=e.now(),this._performanceMillis=t.now()}now(){let e=this._monotonicClock.now()-this._performanceMillis;return this._epochMillis+e}}})),gL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.isAttributeValue=e.isAttributeKey=e.sanitizeAttributes=void 0;let t=(Jd(),d(Kd));function n(e){let n={};if(typeof e!=`object`||!e)return n;for(let[a,o]of Object.entries(e)){if(!r(a)){t.diag.warn(`Invalid attribute key: ${a}`);continue}if(!i(o)){t.diag.warn(`Invalid attribute value set for key: ${a}`);continue}Array.isArray(o)?n[a]=o.slice():n[a]=o}return n}e.sanitizeAttributes=n;function r(e){return typeof e==`string`&&e.length>0}e.isAttributeKey=r;function i(e){return e==null?!0:Array.isArray(e)?a(e):o(e)}e.isAttributeValue=i;function a(e){let t;for(let n of e)if(n!=null){if(!t){if(o(n)){t=typeof n;continue}return!1}if(typeof n!==t)return!1}return!0}function o(e){switch(typeof e){case`number`:case`boolean`:case`string`:return!0}return!1}})),_L=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.loggingErrorHandler=void 0;let t=(Jd(),d(Kd));function n(){return e=>{t.diag.error(r(e))}}e.loggingErrorHandler=n;function r(e){return typeof e==`string`?e:JSON.stringify(i(e))}function i(e){let t={},n=e;for(;n!==null;)Object.getOwnPropertyNames(n).forEach(e=>{if(t[e])return;let r=n[e];r&&(t[e]=String(r))}),n=Object.getPrototypeOf(n);return t}})),vL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.globalErrorHandler=e.setGlobalErrorHandler=void 0;let t=(0,_L().loggingErrorHandler)();function n(e){t=e}e.setGlobalErrorHandler=n;function r(e){try{t(e)}catch{}}e.globalErrorHandler=r})),oee=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getStringListFromEnv=e.getBooleanFromEnv=e.getStringFromEnv=e.getNumberFromEnv=void 0;let t=(Jd(),d(Kd)),n=require(`util`);function r(e){let r=process.env[e];if(r==null||r.trim()===``)return;let i=Number(r);if(isNaN(i)){t.diag.warn(`Unknown value ${(0,n.inspect)(r)} for ${e}, expected a number, using defaults`);return}return i}e.getNumberFromEnv=r;function i(e){let t=process.env[e];if(!(t==null||t.trim()===``))return t}e.getStringFromEnv=i;function a(e){let r=process.env[e]?.trim().toLowerCase();return r==null||r===``?!1:r===`true`?!0:(r===`false`||t.diag.warn(`Unknown value ${(0,n.inspect)(r)} for ${e}, expected 'true' or 'false', falling back to 'false' (default)`),!1)}e.getBooleanFromEnv=a;function o(e){return i(e)?.split(`,`).map(e=>e.trim()).filter(e=>e!==``)}e.getStringListFromEnv=o})),yL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e._globalThis=void 0,e._globalThis=typeof globalThis==`object`?globalThis:global})),bL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.otperformance=void 0,e.otperformance=require(`perf_hooks`).performance})),xL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.VERSION=void 0,e.VERSION=`2.1.0`})),SL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ATTR_PROCESS_RUNTIME_NAME=void 0,e.ATTR_PROCESS_RUNTIME_NAME=`process.runtime.name`})),CL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.SDK_INFO=void 0;let t=xL(),n=(PA(),d(NA)),r=SL();e.SDK_INFO={[n.ATTR_TELEMETRY_SDK_NAME]:`opentelemetry`,[r.ATTR_PROCESS_RUNTIME_NAME]:`node`,[n.ATTR_TELEMETRY_SDK_LANGUAGE]:n.TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,[n.ATTR_TELEMETRY_SDK_VERSION]:t.VERSION}})),wL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.unrefTimer=void 0;function t(e){e.unref()}e.unrefTimer=t})),TL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.unrefTimer=e.SDK_INFO=e.otperformance=e._globalThis=e.getStringListFromEnv=e.getNumberFromEnv=e.getBooleanFromEnv=e.getStringFromEnv=void 0;var t=oee();Object.defineProperty(e,`getStringFromEnv`,{enumerable:!0,get:function(){return t.getStringFromEnv}}),Object.defineProperty(e,`getBooleanFromEnv`,{enumerable:!0,get:function(){return t.getBooleanFromEnv}}),Object.defineProperty(e,`getNumberFromEnv`,{enumerable:!0,get:function(){return t.getNumberFromEnv}}),Object.defineProperty(e,`getStringListFromEnv`,{enumerable:!0,get:function(){return t.getStringListFromEnv}});var n=yL();Object.defineProperty(e,`_globalThis`,{enumerable:!0,get:function(){return n._globalThis}});var r=bL();Object.defineProperty(e,`otperformance`,{enumerable:!0,get:function(){return r.otperformance}});var i=CL();Object.defineProperty(e,`SDK_INFO`,{enumerable:!0,get:function(){return i.SDK_INFO}});var a=wL();Object.defineProperty(e,`unrefTimer`,{enumerable:!0,get:function(){return a.unrefTimer}})})),EL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getStringListFromEnv=e.getNumberFromEnv=e.getStringFromEnv=e.getBooleanFromEnv=e.unrefTimer=e.otperformance=e._globalThis=e.SDK_INFO=void 0;var t=TL();Object.defineProperty(e,`SDK_INFO`,{enumerable:!0,get:function(){return t.SDK_INFO}}),Object.defineProperty(e,`_globalThis`,{enumerable:!0,get:function(){return t._globalThis}}),Object.defineProperty(e,`otperformance`,{enumerable:!0,get:function(){return t.otperformance}}),Object.defineProperty(e,`unrefTimer`,{enumerable:!0,get:function(){return t.unrefTimer}}),Object.defineProperty(e,`getBooleanFromEnv`,{enumerable:!0,get:function(){return t.getBooleanFromEnv}}),Object.defineProperty(e,`getStringFromEnv`,{enumerable:!0,get:function(){return t.getStringFromEnv}}),Object.defineProperty(e,`getNumberFromEnv`,{enumerable:!0,get:function(){return t.getNumberFromEnv}}),Object.defineProperty(e,`getStringListFromEnv`,{enumerable:!0,get:function(){return t.getStringListFromEnv}})})),DL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.addHrTimes=e.isTimeInput=e.isTimeInputHrTime=e.hrTimeToMicroseconds=e.hrTimeToMilliseconds=e.hrTimeToNanoseconds=e.hrTimeToTimeStamp=e.hrTimeDuration=e.timeInputToHrTime=e.hrTime=e.getTimeOrigin=e.millisToHrTime=void 0;let t=EL(),n=10**6,r=10**9;function i(e){let t=e/1e3;return[Math.trunc(t),Math.round(e%1e3*n)]}e.millisToHrTime=i;function a(){let e=t.otperformance.timeOrigin;if(typeof e!=`number`){let n=t.otperformance;e=n.timing&&n.timing.fetchStart}return e}e.getTimeOrigin=a;function o(e){return h(i(a()),i(typeof e==`number`?e:t.otperformance.now()))}e.hrTime=o;function s(e){if(p(e))return e;if(typeof e==`number`)return e<a()?o(e):i(e);if(e instanceof Date)return i(e.getTime());throw TypeError(`Invalid input type`)}e.timeInputToHrTime=s;function c(e,t){let n=t[0]-e[0],i=t[1]-e[1];return i<0&&(--n,i+=r),[n,i]}e.hrTimeDuration=c;function l(e){let t=`${`0`.repeat(9)}${e[1]}Z`,n=t.substring(t.length-9-1);return new Date(e[0]*1e3).toISOString().replace(`000Z`,n)}e.hrTimeToTimeStamp=l;function u(e){return e[0]*r+e[1]}e.hrTimeToNanoseconds=u;function d(e){return e[0]*1e3+e[1]/1e6}e.hrTimeToMilliseconds=d;function f(e){return e[0]*1e6+e[1]/1e3}e.hrTimeToMicroseconds=f;function p(e){return Array.isArray(e)&&e.length===2&&typeof e[0]==`number`&&typeof e[1]==`number`}e.isTimeInputHrTime=p;function m(e){return p(e)||typeof e==`number`||e instanceof Date}e.isTimeInput=m;function h(e,t){let n=[e[0]+t[0],e[1]+t[1]];return n[1]>=r&&(n[1]-=r,n[0]+=1),n}e.addHrTimes=h})),OL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ExportResultCode=void 0,(function(e){e[e.SUCCESS=0]=`SUCCESS`,e[e.FAILED=1]=`FAILED`})(e.ExportResultCode||={})})),kL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.CompositePropagator=void 0;let t=(Jd(),d(Kd));e.CompositePropagator=class{_propagators;_fields;constructor(e={}){this._propagators=e.propagators??[],this._fields=Array.from(new Set(this._propagators.map(e=>typeof e.fields==`function`?e.fields():[]).reduce((e,t)=>e.concat(t),[])))}inject(e,n,r){for(let i of this._propagators)try{i.inject(e,n,r)}catch(e){t.diag.warn(`Failed to inject with ${i.constructor.name}. Err: ${e.message}`)}}extract(e,n,r){return this._propagators.reduce((e,i)=>{try{return i.extract(e,n,r)}catch(e){t.diag.warn(`Failed to extract with ${i.constructor.name}. Err: ${e.message}`)}return e},e)}fields(){return this._fields.slice()}}})),AL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateValue=e.validateKey=void 0;let t=`[_0-9a-z-*/]`,n=`[a-z]${t}{0,255}`,r=`[a-z0-9]${t}{0,240}@[a-z]${t}{0,13}`,i=RegExp(`^(?:${n}|${r})$`),a=/^[ -~]{0,255}[!-~]$/,o=/,|=/;function s(e){return i.test(e)}e.validateKey=s;function c(e){return a.test(e)&&!o.test(e)}e.validateValue=c})),jL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.TraceState=void 0;let t=AL();e.TraceState=class e{_internalState=new Map;constructor(e){e&&this._parse(e)}set(e,t){let n=this._clone();return n._internalState.has(e)&&n._internalState.delete(e),n._internalState.set(e,t),n}unset(e){let t=this._clone();return t._internalState.delete(e),t}get(e){return this._internalState.get(e)}serialize(){return this._keys().reduce((e,t)=>(e.push(t+`=`+this.get(t)),e),[]).join(`,`)}_parse(e){e.length>512||(this._internalState=e.split(`,`).reverse().reduce((e,n)=>{let r=n.trim(),i=r.indexOf(`=`);if(i!==-1){let a=r.slice(0,i),o=r.slice(i+1,n.length);(0,t.validateKey)(a)&&(0,t.validateValue)(o)&&e.set(a,o)}return e},new Map),this._internalState.size>32&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,32))))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){let t=new e;return t._internalState=new Map(this._internalState),t}}})),ML=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.W3CTraceContextPropagator=e.parseTraceParent=e.TRACE_STATE_HEADER=e.TRACE_PARENT_HEADER=void 0;let t=(Jd(),d(Kd)),n=dL(),r=jL();e.TRACE_PARENT_HEADER=`traceparent`,e.TRACE_STATE_HEADER=`tracestate`;let i=RegExp(`^\\s?((?!ff)[\\da-f]{2})-((?![0]{32})[\\da-f]{32})-((?![0]{16})[\\da-f]{16})-([\\da-f]{2})(-.*)?\\s?$`);function a(e){let t=i.exec(e);return!t||t[1]===`00`&&t[5]?null:{traceId:t[2],spanId:t[3],traceFlags:parseInt(t[4],16)}}e.parseTraceParent=a,e.W3CTraceContextPropagator=class{inject(r,i,a){let o=t.trace.getSpanContext(r);if(!o||(0,n.isTracingSuppressed)(r)||!(0,t.isSpanContextValid)(o))return;let s=`00-${o.traceId}-${o.spanId}-0${Number(o.traceFlags||t.TraceFlags.NONE).toString(16)}`;a.set(i,e.TRACE_PARENT_HEADER,s),o.traceState&&a.set(i,e.TRACE_STATE_HEADER,o.traceState.serialize())}extract(n,i,o){let s=o.get(i,e.TRACE_PARENT_HEADER);if(!s)return n;let c=Array.isArray(s)?s[0]:s;if(typeof c!=`string`)return n;let l=a(c);if(!l)return n;l.isRemote=!0;let u=o.get(i,e.TRACE_STATE_HEADER);if(u){let e=Array.isArray(u)?u.join(`,`):u;l.traceState=new r.TraceState(typeof e==`string`?e:void 0)}return t.trace.setSpanContext(n,l)}fields(){return[e.TRACE_PARENT_HEADER,e.TRACE_STATE_HEADER]}}})),NL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getRPCMetadata=e.deleteRPCMetadata=e.setRPCMetadata=e.RPCType=void 0;let t=(0,(Jd(),d(Kd)).createContextKey)(`OpenTelemetry SDK Context Key RPC_METADATA`);(function(e){e.HTTP=`http`})(e.RPCType||={});function n(e,n){return e.setValue(t,n)}e.setRPCMetadata=n;function r(e){return e.deleteValue(t)}e.deleteRPCMetadata=r;function i(e){return e.getValue(t)}e.getRPCMetadata=i})),PL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.isPlainObject=void 0;let t=Function.prototype.toString,n=t.call(Object),r=Object.getPrototypeOf,i=Object.prototype,a=i.hasOwnProperty,o=Symbol?Symbol.toStringTag:void 0,s=i.toString;function c(e){if(!l(e)||u(e)!==`[object Object]`)return!1;let i=r(e);if(i===null)return!0;let o=a.call(i,`constructor`)&&i.constructor;return typeof o==`function`&&o instanceof o&&t.call(o)===n}e.isPlainObject=c;function l(e){return typeof e==`object`&&!!e}function u(e){return e==null?e===void 0?`[object Undefined]`:`[object Null]`:o&&o in Object(e)?d(e):f(e)}function d(e){let t=a.call(e,o),n=e[o],r=!1;try{e[o]=void 0,r=!0}catch{}let i=s.call(e);return r&&(t?e[o]=n:delete e[o]),i}function f(e){return s.call(e)}})),FL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.merge=void 0;let t=PL();function n(...e){let t=e.shift(),n=new WeakMap;for(;e.length>0;)t=i(t,e.shift(),0,n);return t}e.merge=n;function r(e){return o(e)?e.slice():e}function i(e,t,n=0,d){let f;if(!(n>20)){if(n++,l(e)||l(t)||s(t))f=r(t);else if(o(e)){if(f=e.slice(),o(t))for(let e=0,n=t.length;e<n;e++)f.push(r(t[e]));else if(c(t)){let e=Object.keys(t);for(let n=0,i=e.length;n<i;n++){let i=e[n];f[i]=r(t[i])}}}else if(c(e))if(c(t)){if(!u(e,t))return t;f=Object.assign({},e);let r=Object.keys(t);for(let o=0,s=r.length;o<s;o++){let s=r[o],u=t[s];if(l(u))u===void 0?delete f[s]:f[s]=u;else{let r=f[s],o=u;if(a(e,s,d)||a(t,s,d))delete f[s];else{if(c(r)&&c(o)){let n=d.get(r)||[],i=d.get(o)||[];n.push({obj:e,key:s}),i.push({obj:t,key:s}),d.set(r,n),d.set(o,i)}f[s]=i(f[s],u,n,d)}}}}else f=t;return f}}function a(e,t,n){let r=n.get(e[t])||[];for(let n=0,i=r.length;n<i;n++){let i=r[n];if(i.key===t&&i.obj===e)return!0}return!1}function o(e){return Array.isArray(e)}function s(e){return typeof e==`function`}function c(e){return!l(e)&&!o(e)&&!s(e)&&typeof e==`object`}function l(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`||e===void 0||e instanceof Date||e instanceof RegExp||e===null}function u(e,n){return!(!(0,t.isPlainObject)(e)||!(0,t.isPlainObject)(n))}})),IL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.callWithTimeout=e.TimeoutError=void 0;var t=class e extends Error{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype)}};e.TimeoutError=t;function n(e,n){let r,i=new Promise(function(e,i){r=setTimeout(function(){i(new t(`Operation timed out.`))},n)});return Promise.race([e,i]).then(e=>(clearTimeout(r),e),e=>{throw clearTimeout(r),e})}e.callWithTimeout=n})),LL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.isUrlIgnored=e.urlMatches=void 0;function t(e,t){return typeof t==`string`?e===t:!!e.match(t)}e.urlMatches=t;function n(e,n){if(!n)return!1;for(let r of n)if(t(e,r))return!0;return!1}e.isUrlIgnored=n})),RL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.Deferred=void 0,e.Deferred=class{_promise;_resolve;_reject;constructor(){this._promise=new Promise((e,t)=>{this._resolve=e,this._reject=t})}get promise(){return this._promise}resolve(e){this._resolve(e)}reject(e){this._reject(e)}}})),zL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BindOnceFuture=void 0;let t=RL();e.BindOnceFuture=class{_callback;_that;_isCalled=!1;_deferred=new t.Deferred;constructor(e,t){this._callback=e,this._that=t}get isCalled(){return this._isCalled}get promise(){return this._deferred.promise}call(...e){if(!this._isCalled){this._isCalled=!0;try{Promise.resolve(this._callback.call(this._that,...e)).then(e=>this._deferred.resolve(e),e=>this._deferred.reject(e))}catch(e){this._deferred.reject(e)}}return this._deferred.promise}}})),BL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.diagLogLevelFromString=void 0;let t=(Jd(),d(Kd)),n={ALL:t.DiagLogLevel.ALL,VERBOSE:t.DiagLogLevel.VERBOSE,DEBUG:t.DiagLogLevel.DEBUG,INFO:t.DiagLogLevel.INFO,WARN:t.DiagLogLevel.WARN,ERROR:t.DiagLogLevel.ERROR,NONE:t.DiagLogLevel.NONE};function r(e){return e==null?void 0:n[e.toUpperCase()]??(t.diag.warn(`Unknown log level "${e}", expected one of ${Object.keys(n)}, using default`),t.DiagLogLevel.INFO)}e.diagLogLevelFromString=r})),VL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e._export=void 0;let t=(Jd(),d(Kd)),n=dL();function r(e,r){return new Promise(i=>{t.context.with((0,n.suppressTracing)(t.context.active()),()=>{e.export(r,e=>{i(e)})})})}e._export=r})),HL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.internal=e.diagLogLevelFromString=e.BindOnceFuture=e.urlMatches=e.isUrlIgnored=e.callWithTimeout=e.TimeoutError=e.merge=e.TraceState=e.unsuppressTracing=e.suppressTracing=e.isTracingSuppressed=e.setRPCMetadata=e.getRPCMetadata=e.deleteRPCMetadata=e.RPCType=e.parseTraceParent=e.W3CTraceContextPropagator=e.TRACE_STATE_HEADER=e.TRACE_PARENT_HEADER=e.CompositePropagator=e.unrefTimer=e.otperformance=e.getStringListFromEnv=e.getNumberFromEnv=e.getBooleanFromEnv=e.getStringFromEnv=e._globalThis=e.SDK_INFO=e.parseKeyPairsIntoRecord=e.ExportResultCode=e.timeInputToHrTime=e.millisToHrTime=e.isTimeInputHrTime=e.isTimeInput=e.hrTimeToTimeStamp=e.hrTimeToNanoseconds=e.hrTimeToMilliseconds=e.hrTimeToMicroseconds=e.hrTimeDuration=e.hrTime=e.getTimeOrigin=e.addHrTimes=e.loggingErrorHandler=e.setGlobalErrorHandler=e.globalErrorHandler=e.sanitizeAttributes=e.isAttributeValue=e.AnchoredClock=e.W3CBaggagePropagator=void 0;var t=mL();Object.defineProperty(e,`W3CBaggagePropagator`,{enumerable:!0,get:function(){return t.W3CBaggagePropagator}});var n=hL();Object.defineProperty(e,`AnchoredClock`,{enumerable:!0,get:function(){return n.AnchoredClock}});var r=gL();Object.defineProperty(e,`isAttributeValue`,{enumerable:!0,get:function(){return r.isAttributeValue}}),Object.defineProperty(e,`sanitizeAttributes`,{enumerable:!0,get:function(){return r.sanitizeAttributes}});var i=vL();Object.defineProperty(e,`globalErrorHandler`,{enumerable:!0,get:function(){return i.globalErrorHandler}}),Object.defineProperty(e,`setGlobalErrorHandler`,{enumerable:!0,get:function(){return i.setGlobalErrorHandler}});var a=_L();Object.defineProperty(e,`loggingErrorHandler`,{enumerable:!0,get:function(){return a.loggingErrorHandler}});var o=DL();Object.defineProperty(e,`addHrTimes`,{enumerable:!0,get:function(){return o.addHrTimes}}),Object.defineProperty(e,`getTimeOrigin`,{enumerable:!0,get:function(){return o.getTimeOrigin}}),Object.defineProperty(e,`hrTime`,{enumerable:!0,get:function(){return o.hrTime}}),Object.defineProperty(e,`hrTimeDuration`,{enumerable:!0,get:function(){return o.hrTimeDuration}}),Object.defineProperty(e,`hrTimeToMicroseconds`,{enumerable:!0,get:function(){return o.hrTimeToMicroseconds}}),Object.defineProperty(e,`hrTimeToMilliseconds`,{enumerable:!0,get:function(){return o.hrTimeToMilliseconds}}),Object.defineProperty(e,`hrTimeToNanoseconds`,{enumerable:!0,get:function(){return o.hrTimeToNanoseconds}}),Object.defineProperty(e,`hrTimeToTimeStamp`,{enumerable:!0,get:function(){return o.hrTimeToTimeStamp}}),Object.defineProperty(e,`isTimeInput`,{enumerable:!0,get:function(){return o.isTimeInput}}),Object.defineProperty(e,`isTimeInputHrTime`,{enumerable:!0,get:function(){return o.isTimeInputHrTime}}),Object.defineProperty(e,`millisToHrTime`,{enumerable:!0,get:function(){return o.millisToHrTime}}),Object.defineProperty(e,`timeInputToHrTime`,{enumerable:!0,get:function(){return o.timeInputToHrTime}});var s=OL();Object.defineProperty(e,`ExportResultCode`,{enumerable:!0,get:function(){return s.ExportResultCode}});var c=pL();Object.defineProperty(e,`parseKeyPairsIntoRecord`,{enumerable:!0,get:function(){return c.parseKeyPairsIntoRecord}});var l=EL();Object.defineProperty(e,`SDK_INFO`,{enumerable:!0,get:function(){return l.SDK_INFO}}),Object.defineProperty(e,`_globalThis`,{enumerable:!0,get:function(){return l._globalThis}}),Object.defineProperty(e,`getStringFromEnv`,{enumerable:!0,get:function(){return l.getStringFromEnv}}),Object.defineProperty(e,`getBooleanFromEnv`,{enumerable:!0,get:function(){return l.getBooleanFromEnv}}),Object.defineProperty(e,`getNumberFromEnv`,{enumerable:!0,get:function(){return l.getNumberFromEnv}}),Object.defineProperty(e,`getStringListFromEnv`,{enumerable:!0,get:function(){return l.getStringListFromEnv}}),Object.defineProperty(e,`otperformance`,{enumerable:!0,get:function(){return l.otperformance}}),Object.defineProperty(e,`unrefTimer`,{enumerable:!0,get:function(){return l.unrefTimer}});var u=kL();Object.defineProperty(e,`CompositePropagator`,{enumerable:!0,get:function(){return u.CompositePropagator}});var d=ML();Object.defineProperty(e,`TRACE_PARENT_HEADER`,{enumerable:!0,get:function(){return d.TRACE_PARENT_HEADER}}),Object.defineProperty(e,`TRACE_STATE_HEADER`,{enumerable:!0,get:function(){return d.TRACE_STATE_HEADER}}),Object.defineProperty(e,`W3CTraceContextPropagator`,{enumerable:!0,get:function(){return d.W3CTraceContextPropagator}}),Object.defineProperty(e,`parseTraceParent`,{enumerable:!0,get:function(){return d.parseTraceParent}});var f=NL();Object.defineProperty(e,`RPCType`,{enumerable:!0,get:function(){return f.RPCType}}),Object.defineProperty(e,`deleteRPCMetadata`,{enumerable:!0,get:function(){return f.deleteRPCMetadata}}),Object.defineProperty(e,`getRPCMetadata`,{enumerable:!0,get:function(){return f.getRPCMetadata}}),Object.defineProperty(e,`setRPCMetadata`,{enumerable:!0,get:function(){return f.setRPCMetadata}});var p=dL();Object.defineProperty(e,`isTracingSuppressed`,{enumerable:!0,get:function(){return p.isTracingSuppressed}}),Object.defineProperty(e,`suppressTracing`,{enumerable:!0,get:function(){return p.suppressTracing}}),Object.defineProperty(e,`unsuppressTracing`,{enumerable:!0,get:function(){return p.unsuppressTracing}});var m=jL();Object.defineProperty(e,`TraceState`,{enumerable:!0,get:function(){return m.TraceState}});var h=FL();Object.defineProperty(e,`merge`,{enumerable:!0,get:function(){return h.merge}});var g=IL();Object.defineProperty(e,`TimeoutError`,{enumerable:!0,get:function(){return g.TimeoutError}}),Object.defineProperty(e,`callWithTimeout`,{enumerable:!0,get:function(){return g.callWithTimeout}});var _=LL();Object.defineProperty(e,`isUrlIgnored`,{enumerable:!0,get:function(){return _.isUrlIgnored}}),Object.defineProperty(e,`urlMatches`,{enumerable:!0,get:function(){return _.urlMatches}});var v=zL();Object.defineProperty(e,`BindOnceFuture`,{enumerable:!0,get:function(){return v.BindOnceFuture}});var y=BL();Object.defineProperty(e,`diagLogLevelFromString`,{enumerable:!0,get:function(){return y.diagLogLevelFromString}}),e.internal={_export:VL()._export}})),UL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.defaultServiceName=void 0;function t(){return`unknown_service:${process.argv0}`}e.defaultServiceName=t})),WL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.defaultServiceName=void 0;var t=UL();Object.defineProperty(e,`defaultServiceName`,{enumerable:!0,get:function(){return t.defaultServiceName}})})),GL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.defaultServiceName=void 0;var t=WL();Object.defineProperty(e,`defaultServiceName`,{enumerable:!0,get:function(){return t.defaultServiceName}})})),KL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.identity=e.isPromiseLike=void 0,e.isPromiseLike=e=>typeof e==`object`&&!!e&&typeof e.then==`function`;function t(e){return e}e.identity=t})),qL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.defaultResource=e.emptyResource=e.resourceFromDetectedResource=e.resourceFromAttributes=void 0;let t=(Jd(),d(Kd)),n=HL(),r=(PA(),d(NA)),i=GL(),a=KL();var o=class e{_rawAttributes;_asyncAttributesPending=!1;_schemaUrl;_memoizedAttributes;static FromAttributeList(t,n){let r=new e({},n);return r._rawAttributes=f(t),r._asyncAttributesPending=t.filter(([e,t])=>(0,a.isPromiseLike)(t)).length>0,r}constructor(e,t){let n=e.attributes??{};this._rawAttributes=Object.entries(n).map(([e,t])=>((0,a.isPromiseLike)(t)&&(this._asyncAttributesPending=!0),[e,t])),this._rawAttributes=f(this._rawAttributes),this._schemaUrl=p(t?.schemaUrl)}get asyncAttributesPending(){return this._asyncAttributesPending}async waitForAsyncAttributes(){if(this.asyncAttributesPending){for(let e=0;e<this._rawAttributes.length;e++){let[t,n]=this._rawAttributes[e];this._rawAttributes[e]=[t,(0,a.isPromiseLike)(n)?await n:n]}this._asyncAttributesPending=!1}}get attributes(){if(this.asyncAttributesPending&&t.diag.error(`Accessing resource attributes before async attributes settled`),this._memoizedAttributes)return this._memoizedAttributes;let e={};for(let[n,r]of this._rawAttributes){if((0,a.isPromiseLike)(r)){t.diag.debug(`Unsettled resource attribute ${n} skipped`);continue}r!=null&&(e[n]??=r)}return this._asyncAttributesPending||(this._memoizedAttributes=e),e}getRawAttributes(){return this._rawAttributes}get schemaUrl(){return this._schemaUrl}merge(t){if(t==null)return this;let n=m(this,t),r=n?{schemaUrl:n}:void 0;return e.FromAttributeList([...t.getRawAttributes(),...this.getRawAttributes()],r)}};function s(e,t){return o.FromAttributeList(Object.entries(e),t)}e.resourceFromAttributes=s;function c(e,t){return new o(e,t)}e.resourceFromDetectedResource=c;function l(){return s({})}e.emptyResource=l;function u(){return s({[r.ATTR_SERVICE_NAME]:(0,i.defaultServiceName)(),[r.ATTR_TELEMETRY_SDK_LANGUAGE]:n.SDK_INFO[r.ATTR_TELEMETRY_SDK_LANGUAGE],[r.ATTR_TELEMETRY_SDK_NAME]:n.SDK_INFO[r.ATTR_TELEMETRY_SDK_NAME],[r.ATTR_TELEMETRY_SDK_VERSION]:n.SDK_INFO[r.ATTR_TELEMETRY_SDK_VERSION]})}e.defaultResource=u;function f(e){return e.map(([e,n])=>(0,a.isPromiseLike)(n)?[e,n.catch(n=>{t.diag.debug(`promise rejection for resource attribute: %s - %s`,e,n)})]:[e,n])}function p(e){if(typeof e==`string`||e===void 0)return e;t.diag.warn(`Schema URL must be string or undefined, got %s. Schema URL will be ignored.`,e)}function m(e,n){let r=e?.schemaUrl,i=n?.schemaUrl,a=r===void 0||r===``,o=i===void 0||i===``;if(a)return i;if(o||r===i)return r;t.diag.warn(`Schema URL merge conflict: old resource has "%s", updating resource has "%s". Resulting resource will have undefined Schema URL.`,r,i)}})),JL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.detectResources=void 0;let t=(Jd(),d(Kd)),n=qL();e.detectResources=(e={})=>(e.detectors||[]).map(r=>{try{let i=(0,n.resourceFromDetectedResource)(r.detect(e));return t.diag.debug(`${r.constructor.name} found resource.`,i),i}catch(e){return t.diag.debug(`${r.constructor.name} failed: ${e.message}`),(0,n.emptyResource)()}}).reduce((e,t)=>e.merge(t),(0,n.emptyResource)())})),YL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.envDetector=void 0;let t=(Jd(),d(Kd)),n=(PA(),d(NA)),r=HL();e.envDetector=new class{_MAX_LENGTH=255;_COMMA_SEPARATOR=`,`;_LABEL_KEY_VALUE_SPLITTER=`=`;_ERROR_MESSAGE_INVALID_CHARS=`should be a ASCII string with a length greater than 0 and not exceed `+this._MAX_LENGTH+` characters.`;_ERROR_MESSAGE_INVALID_VALUE=`should be a ASCII string with a length not exceed `+this._MAX_LENGTH+` characters.`;detect(e){let i={},a=(0,r.getStringFromEnv)(`OTEL_RESOURCE_ATTRIBUTES`),o=(0,r.getStringFromEnv)(`OTEL_SERVICE_NAME`);if(a)try{let e=this._parseResourceAttributes(a);Object.assign(i,e)}catch(e){t.diag.debug(`EnvDetector failed: ${e.message}`)}return o&&(i[n.ATTR_SERVICE_NAME]=o),{attributes:i}}_parseResourceAttributes(e){if(!e)return{};let t={},n=e.split(this._COMMA_SEPARATOR,-1);for(let e of n){let n=e.split(this._LABEL_KEY_VALUE_SPLITTER,-1);if(n.length!==2)continue;let[r,i]=n;if(r=r.trim(),i=i.trim().split(/^"|"$/).join(``),!this._isValidAndNotEmpty(r))throw Error(`Attribute key ${this._ERROR_MESSAGE_INVALID_CHARS}`);if(!this._isValid(i))throw Error(`Attribute value ${this._ERROR_MESSAGE_INVALID_VALUE}`);t[r]=decodeURIComponent(i)}return t}_isValid(e){return e.length<=this._MAX_LENGTH&&this._isBaggageOctetString(e)}_isBaggageOctetString(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<33||n===44||n===59||n===92||n>126)return!1}return!0}_isValidAndNotEmpty(e){return e.length>0&&this._isValid(e)}}})),XL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ATTR_WEBENGINE_VERSION=e.ATTR_WEBENGINE_NAME=e.ATTR_WEBENGINE_DESCRIPTION=e.ATTR_SERVICE_NAMESPACE=e.ATTR_SERVICE_INSTANCE_ID=e.ATTR_PROCESS_RUNTIME_VERSION=e.ATTR_PROCESS_RUNTIME_NAME=e.ATTR_PROCESS_RUNTIME_DESCRIPTION=e.ATTR_PROCESS_PID=e.ATTR_PROCESS_OWNER=e.ATTR_PROCESS_EXECUTABLE_PATH=e.ATTR_PROCESS_EXECUTABLE_NAME=e.ATTR_PROCESS_COMMAND_ARGS=e.ATTR_PROCESS_COMMAND=e.ATTR_OS_VERSION=e.ATTR_OS_TYPE=e.ATTR_K8S_POD_NAME=e.ATTR_K8S_NAMESPACE_NAME=e.ATTR_K8S_DEPLOYMENT_NAME=e.ATTR_K8S_CLUSTER_NAME=e.ATTR_HOST_TYPE=e.ATTR_HOST_NAME=e.ATTR_HOST_IMAGE_VERSION=e.ATTR_HOST_IMAGE_NAME=e.ATTR_HOST_IMAGE_ID=e.ATTR_HOST_ID=e.ATTR_HOST_ARCH=e.ATTR_CONTAINER_NAME=e.ATTR_CONTAINER_IMAGE_TAGS=e.ATTR_CONTAINER_IMAGE_NAME=e.ATTR_CONTAINER_ID=e.ATTR_CLOUD_REGION=e.ATTR_CLOUD_PROVIDER=e.ATTR_CLOUD_AVAILABILITY_ZONE=e.ATTR_CLOUD_ACCOUNT_ID=void 0,e.ATTR_CLOUD_ACCOUNT_ID=`cloud.account.id`,e.ATTR_CLOUD_AVAILABILITY_ZONE=`cloud.availability_zone`,e.ATTR_CLOUD_PROVIDER=`cloud.provider`,e.ATTR_CLOUD_REGION=`cloud.region`,e.ATTR_CONTAINER_ID=`container.id`,e.ATTR_CONTAINER_IMAGE_NAME=`container.image.name`,e.ATTR_CONTAINER_IMAGE_TAGS=`container.image.tags`,e.ATTR_CONTAINER_NAME=`container.name`,e.ATTR_HOST_ARCH=`host.arch`,e.ATTR_HOST_ID=`host.id`,e.ATTR_HOST_IMAGE_ID=`host.image.id`,e.ATTR_HOST_IMAGE_NAME=`host.image.name`,e.ATTR_HOST_IMAGE_VERSION=`host.image.version`,e.ATTR_HOST_NAME=`host.name`,e.ATTR_HOST_TYPE=`host.type`,e.ATTR_K8S_CLUSTER_NAME=`k8s.cluster.name`,e.ATTR_K8S_DEPLOYMENT_NAME=`k8s.deployment.name`,e.ATTR_K8S_NAMESPACE_NAME=`k8s.namespace.name`,e.ATTR_K8S_POD_NAME=`k8s.pod.name`,e.ATTR_OS_TYPE=`os.type`,e.ATTR_OS_VERSION=`os.version`,e.ATTR_PROCESS_COMMAND=`process.command`,e.ATTR_PROCESS_COMMAND_ARGS=`process.command_args`,e.ATTR_PROCESS_EXECUTABLE_NAME=`process.executable.name`,e.ATTR_PROCESS_EXECUTABLE_PATH=`process.executable.path`,e.ATTR_PROCESS_OWNER=`process.owner`,e.ATTR_PROCESS_PID=`process.pid`,e.ATTR_PROCESS_RUNTIME_DESCRIPTION=`process.runtime.description`,e.ATTR_PROCESS_RUNTIME_NAME=`process.runtime.name`,e.ATTR_PROCESS_RUNTIME_VERSION=`process.runtime.version`,e.ATTR_SERVICE_INSTANCE_ID=`service.instance.id`,e.ATTR_SERVICE_NAMESPACE=`service.namespace`,e.ATTR_WEBENGINE_DESCRIPTION=`webengine.description`,e.ATTR_WEBENGINE_NAME=`webengine.name`,e.ATTR_WEBENGINE_VERSION=`webengine.version`})),ZL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getMachineId=void 0;let t=require(`process`),n;async function r(){if(!n)switch(t.platform){case`darwin`:n=(await Promise.resolve().then(()=>u(require(`./getMachineId-darwin-qxG7FDMy.cjs`).default))).getMachineId;break;case`linux`:n=(await Promise.resolve().then(()=>u(require(`./getMachineId-linux-Dnsx6XjV.cjs`).default))).getMachineId;break;case`freebsd`:n=(await Promise.resolve().then(()=>u(require(`./getMachineId-bsd-C6vJ2MI6.cjs`).default))).getMachineId;break;case`win32`:n=(await Promise.resolve().then(()=>u(require(`./getMachineId-win-BDuHxVob.cjs`).default))).getMachineId;break;default:n=(await Promise.resolve().then(()=>u(require(`./getMachineId-unsupported-BE5onnLI.cjs`).default))).getMachineId;break}return n()}e.getMachineId=r})),QL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.normalizeType=e.normalizeArch=void 0,e.normalizeArch=e=>{switch(e){case`arm`:return`arm32`;case`ppc`:return`ppc32`;case`x64`:return`amd64`;default:return e}},e.normalizeType=e=>{switch(e){case`sunos`:return`solaris`;case`win32`:return`windows`;default:return e}}})),$L=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.hostDetector=void 0;let t=XL(),n=require(`os`),r=ZL(),i=QL();e.hostDetector=new class{detect(e){return{attributes:{[t.ATTR_HOST_NAME]:(0,n.hostname)(),[t.ATTR_HOST_ARCH]:(0,i.normalizeArch)((0,n.arch)()),[t.ATTR_HOST_ID]:(0,r.getMachineId)()}}}}})),eR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.osDetector=void 0;let t=XL(),n=require(`os`),r=QL();e.osDetector=new class{detect(e){return{attributes:{[t.ATTR_OS_TYPE]:(0,r.normalizeType)((0,n.platform)()),[t.ATTR_OS_VERSION]:(0,n.release)()}}}}})),tR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.processDetector=void 0;let t=(Jd(),d(Kd)),n=XL(),r=require(`os`);e.processDetector=new class{detect(e){let i={[n.ATTR_PROCESS_PID]:process.pid,[n.ATTR_PROCESS_EXECUTABLE_NAME]:process.title,[n.ATTR_PROCESS_EXECUTABLE_PATH]:process.execPath,[n.ATTR_PROCESS_COMMAND_ARGS]:[process.argv[0],...process.execArgv,...process.argv.slice(1)],[n.ATTR_PROCESS_RUNTIME_VERSION]:process.versions.node,[n.ATTR_PROCESS_RUNTIME_NAME]:`nodejs`,[n.ATTR_PROCESS_RUNTIME_DESCRIPTION]:`Node.js`};process.argv.length>1&&(i[n.ATTR_PROCESS_COMMAND]=process.argv[1]);try{let e=r.userInfo();i[n.ATTR_PROCESS_OWNER]=e.username}catch(e){t.diag.debug(`error obtaining process owner: ${e}`)}return{attributes:i}}}})),nR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.serviceInstanceIdDetector=void 0;let t=XL(),n=require(`crypto`);e.serviceInstanceIdDetector=new class{detect(e){return{attributes:{[t.ATTR_SERVICE_INSTANCE_ID]:(0,n.randomUUID)()}}}}})),rR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.serviceInstanceIdDetector=e.processDetector=e.osDetector=e.hostDetector=void 0;var t=$L();Object.defineProperty(e,`hostDetector`,{enumerable:!0,get:function(){return t.hostDetector}});var n=eR();Object.defineProperty(e,`osDetector`,{enumerable:!0,get:function(){return n.osDetector}});var r=tR();Object.defineProperty(e,`processDetector`,{enumerable:!0,get:function(){return r.processDetector}});var i=nR();Object.defineProperty(e,`serviceInstanceIdDetector`,{enumerable:!0,get:function(){return i.serviceInstanceIdDetector}})})),iR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.serviceInstanceIdDetector=e.processDetector=e.osDetector=e.hostDetector=void 0;var t=rR();Object.defineProperty(e,`hostDetector`,{enumerable:!0,get:function(){return t.hostDetector}}),Object.defineProperty(e,`osDetector`,{enumerable:!0,get:function(){return t.osDetector}}),Object.defineProperty(e,`processDetector`,{enumerable:!0,get:function(){return t.processDetector}}),Object.defineProperty(e,`serviceInstanceIdDetector`,{enumerable:!0,get:function(){return t.serviceInstanceIdDetector}})})),aR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.noopDetector=e.NoopDetector=void 0;var t=class{detect(){return{attributes:{}}}};e.NoopDetector=t,e.noopDetector=new t})),oR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.noopDetector=e.serviceInstanceIdDetector=e.processDetector=e.osDetector=e.hostDetector=e.envDetector=void 0;var t=YL();Object.defineProperty(e,`envDetector`,{enumerable:!0,get:function(){return t.envDetector}});var n=iR();Object.defineProperty(e,`hostDetector`,{enumerable:!0,get:function(){return n.hostDetector}}),Object.defineProperty(e,`osDetector`,{enumerable:!0,get:function(){return n.osDetector}}),Object.defineProperty(e,`processDetector`,{enumerable:!0,get:function(){return n.processDetector}}),Object.defineProperty(e,`serviceInstanceIdDetector`,{enumerable:!0,get:function(){return n.serviceInstanceIdDetector}});var r=aR();Object.defineProperty(e,`noopDetector`,{enumerable:!0,get:function(){return r.noopDetector}})})),sR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.defaultServiceName=e.emptyResource=e.defaultResource=e.resourceFromAttributes=e.serviceInstanceIdDetector=e.processDetector=e.osDetector=e.hostDetector=e.envDetector=e.detectResources=void 0;var t=JL();Object.defineProperty(e,`detectResources`,{enumerable:!0,get:function(){return t.detectResources}});var n=oR();Object.defineProperty(e,`envDetector`,{enumerable:!0,get:function(){return n.envDetector}}),Object.defineProperty(e,`hostDetector`,{enumerable:!0,get:function(){return n.hostDetector}}),Object.defineProperty(e,`osDetector`,{enumerable:!0,get:function(){return n.osDetector}}),Object.defineProperty(e,`processDetector`,{enumerable:!0,get:function(){return n.processDetector}}),Object.defineProperty(e,`serviceInstanceIdDetector`,{enumerable:!0,get:function(){return n.serviceInstanceIdDetector}});var r=qL();Object.defineProperty(e,`resourceFromAttributes`,{enumerable:!0,get:function(){return r.resourceFromAttributes}}),Object.defineProperty(e,`defaultResource`,{enumerable:!0,get:function(){return r.defaultResource}}),Object.defineProperty(e,`emptyResource`,{enumerable:!0,get:function(){return r.emptyResource}});var i=GL();Object.defineProperty(e,`defaultServiceName`,{enumerable:!0,get:function(){return i.defaultServiceName}})})),cR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.LogRecordImpl=void 0;let t=(Jd(),d(Kd)),n=HL();e.LogRecordImpl=class{hrTime;hrTimeObserved;spanContext;resource;instrumentationScope;attributes={};_severityText;_severityNumber;_body;_eventName;totalAttributesCount=0;_isReadonly=!1;_logRecordLimits;set severityText(e){this._isLogRecordReadonly()||(this._severityText=e)}get severityText(){return this._severityText}set severityNumber(e){this._isLogRecordReadonly()||(this._severityNumber=e)}get severityNumber(){return this._severityNumber}set body(e){this._isLogRecordReadonly()||(this._body=e)}get body(){return this._body}get eventName(){return this._eventName}set eventName(e){this._isLogRecordReadonly()||(this._eventName=e)}get droppedAttributesCount(){return this.totalAttributesCount-Object.keys(this.attributes).length}constructor(e,r,i){let{timestamp:a,observedTimestamp:o,eventName:s,severityNumber:c,severityText:l,body:u,attributes:d={},context:f}=i,p=Date.now();if(this.hrTime=(0,n.timeInputToHrTime)(a??p),this.hrTimeObserved=(0,n.timeInputToHrTime)(o??p),f){let e=t.trace.getSpanContext(f);e&&t.isSpanContextValid(e)&&(this.spanContext=e)}this.severityNumber=c,this.severityText=l,this.body=u,this.resource=e.resource,this.instrumentationScope=r,this._logRecordLimits=e.logRecordLimits,this._eventName=s,this.setAttributes(d)}setAttribute(e,r){return this._isLogRecordReadonly()||r===null?this:e.length===0?(t.diag.warn(`Invalid attribute key: ${e}`),this):!(0,n.isAttributeValue)(r)&&!(typeof r==`object`&&!Array.isArray(r)&&Object.keys(r).length>0)?(t.diag.warn(`Invalid attribute value set for key: ${e}`),this):(this.totalAttributesCount+=1,Object.keys(this.attributes).length>=this._logRecordLimits.attributeCountLimit&&!Object.prototype.hasOwnProperty.call(this.attributes,e)?(this.droppedAttributesCount===1&&t.diag.warn(`Dropping extra attributes.`),this):((0,n.isAttributeValue)(r)?this.attributes[e]=this._truncateToSize(r):this.attributes[e]=r,this))}setAttributes(e){for(let[t,n]of Object.entries(e))this.setAttribute(t,n);return this}setBody(e){return this.body=e,this}setEventName(e){return this.eventName=e,this}setSeverityNumber(e){return this.severityNumber=e,this}setSeverityText(e){return this.severityText=e,this}_makeReadonly(){this._isReadonly=!0}_truncateToSize(e){let n=this._logRecordLimits.attributeValueLengthLimit;return n<=0?(t.diag.warn(`Attribute value limit must be positive, got ${n}`),e):typeof e==`string`?this._truncateToLimitUtil(e,n):Array.isArray(e)?e.map(e=>typeof e==`string`?this._truncateToLimitUtil(e,n):e):e}_truncateToLimitUtil(e,t){return e.length<=t?e:e.substring(0,t)}_isLogRecordReadonly(){return this._isReadonly&&t.diag.warn(`Can not execute the operation on emitted log record`),this._isReadonly}}})),lR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.Logger=void 0;let t=(Jd(),d(Kd)),n=cR();e.Logger=class{instrumentationScope;_sharedState;constructor(e,t){this.instrumentationScope=e,this._sharedState=t}emit(e){let r=e.context||t.context.active(),i=new n.LogRecordImpl(this._sharedState,this.instrumentationScope,{context:r,...e});this._sharedState.activeProcessor.onEmit(i,r),i._makeReadonly()}}})),uR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.reconfigureLimits=e.loadDefaultConfig=void 0;let t=HL();function n(){return{forceFlushTimeoutMillis:3e4,logRecordLimits:{attributeValueLengthLimit:(0,t.getNumberFromEnv)(`OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT`)??1/0,attributeCountLimit:(0,t.getNumberFromEnv)(`OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT`)??128},includeTraceContext:!0}}e.loadDefaultConfig=n;function r(e){return{attributeCountLimit:e.attributeCountLimit??(0,t.getNumberFromEnv)(`OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT`)??(0,t.getNumberFromEnv)(`OTEL_ATTRIBUTE_COUNT_LIMIT`)??128,attributeValueLengthLimit:e.attributeValueLengthLimit??(0,t.getNumberFromEnv)(`OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT`)??(0,t.getNumberFromEnv)(`OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT`)??1/0}}e.reconfigureLimits=r})),dR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.NoopLogRecordProcessor=void 0,e.NoopLogRecordProcessor=class{forceFlush(){return Promise.resolve()}onEmit(e,t){}shutdown(){return Promise.resolve()}}})),fR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MultiLogRecordProcessor=void 0;let t=HL();e.MultiLogRecordProcessor=class{processors;forceFlushTimeoutMillis;constructor(e,t){this.processors=e,this.forceFlushTimeoutMillis=t}async forceFlush(){let e=this.forceFlushTimeoutMillis;await Promise.all(this.processors.map(n=>(0,t.callWithTimeout)(n.forceFlush(),e)))}onEmit(e,t){this.processors.forEach(n=>n.onEmit(e,t))}async shutdown(){await Promise.all(this.processors.map(e=>e.shutdown()))}}})),pR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.LoggerProviderSharedState=void 0;let t=dR(),n=fR();e.LoggerProviderSharedState=class{resource;forceFlushTimeoutMillis;logRecordLimits;processors;loggers=new Map;activeProcessor;registeredLogRecordProcessors=[];constructor(e,r,i,a){this.resource=e,this.forceFlushTimeoutMillis=r,this.logRecordLimits=i,this.processors=a,a.length>0?(this.registeredLogRecordProcessors=a,this.activeProcessor=new n.MultiLogRecordProcessor(this.registeredLogRecordProcessors,this.forceFlushTimeoutMillis)):this.activeProcessor=new t.NoopLogRecordProcessor}}})),mR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.LoggerProvider=e.DEFAULT_LOGGER_NAME=void 0;let t=(Jd(),d(Kd)),n=Li(),r=sR(),i=HL(),a=lR(),o=uR(),s=pR();e.DEFAULT_LOGGER_NAME=`unknown`,e.LoggerProvider=class{_shutdownOnce;_sharedState;constructor(e={}){let t=(0,i.merge)({},(0,o.loadDefaultConfig)(),e),n=e.resource??(0,r.defaultResource)();this._sharedState=new s.LoggerProviderSharedState(n,t.forceFlushTimeoutMillis,(0,o.reconfigureLimits)(t.logRecordLimits),e?.processors??[]),this._shutdownOnce=new i.BindOnceFuture(this._shutdown,this)}getLogger(r,i,o){if(this._shutdownOnce.isCalled)return t.diag.warn(`A shutdown LoggerProvider cannot provide a Logger`),n.NOOP_LOGGER;r||t.diag.warn(`Logger requested without instrumentation scope name.`);let s=r||e.DEFAULT_LOGGER_NAME,c=`${s}@${i||``}:${o?.schemaUrl||``}`;return this._sharedState.loggers.has(c)||this._sharedState.loggers.set(c,new a.Logger({name:s,version:i,schemaUrl:o?.schemaUrl},this._sharedState)),this._sharedState.loggers.get(c)}forceFlush(){return this._shutdownOnce.isCalled?(t.diag.warn(`invalid attempt to force flush after LoggerProvider shutdown`),this._shutdownOnce.promise):this._sharedState.activeProcessor.forceFlush()}shutdown(){return this._shutdownOnce.isCalled?(t.diag.warn(`shutdown may only be called once per LoggerProvider`),this._shutdownOnce.promise):this._shutdownOnce.call()}_shutdown(){return this._sharedState.activeProcessor.shutdown()}}})),hR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ConsoleLogRecordExporter=void 0;let t=HL();e.ConsoleLogRecordExporter=class{export(e,t){this._sendLogRecords(e,t)}shutdown(){return Promise.resolve()}_exportInfo(e){return{resource:{attributes:e.resource.attributes},instrumentationScope:e.instrumentationScope,timestamp:(0,t.hrTimeToMicroseconds)(e.hrTime),traceId:e.spanContext?.traceId,spanId:e.spanContext?.spanId,traceFlags:e.spanContext?.traceFlags,severityText:e.severityText,severityNumber:e.severityNumber,body:e.body,attributes:e.attributes}}_sendLogRecords(e,n){for(let t of e)console.dir(this._exportInfo(t),{depth:3});n?.({code:t.ExportResultCode.SUCCESS})}}})),see=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.SimpleLogRecordProcessor=void 0;let t=HL();e.SimpleLogRecordProcessor=class{_exporter;_shutdownOnce;_unresolvedExports;constructor(e){this._exporter=e,this._shutdownOnce=new t.BindOnceFuture(this._shutdown,this),this._unresolvedExports=new Set}onEmit(e){if(this._shutdownOnce.isCalled)return;let n=()=>t.internal._export(this._exporter,[e]).then(e=>{e.code!==t.ExportResultCode.SUCCESS&&(0,t.globalErrorHandler)(e.error??Error(`SimpleLogRecordProcessor: log record export failed (status ${e})`))}).catch(t.globalErrorHandler);if(e.resource.asyncAttributesPending){let r=e.resource.waitForAsyncAttributes?.().then(()=>(this._unresolvedExports.delete(r),n()),t.globalErrorHandler);r!=null&&this._unresolvedExports.add(r)}else n()}async forceFlush(){await Promise.all(Array.from(this._unresolvedExports))}shutdown(){return this._shutdownOnce.call()}_shutdown(){return this._exporter.shutdown()}}})),gR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.InMemoryLogRecordExporter=void 0;let t=HL();e.InMemoryLogRecordExporter=class{_finishedLogRecords=[];_stopped=!1;export(e,n){if(this._stopped)return n({code:t.ExportResultCode.FAILED,error:Error(`Exporter has been stopped`)});this._finishedLogRecords.push(...e),n({code:t.ExportResultCode.SUCCESS})}shutdown(){return this._stopped=!0,this.reset(),Promise.resolve()}getFinishedLogRecords(){return this._finishedLogRecords}reset(){this._finishedLogRecords=[]}}})),cee=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BatchLogRecordProcessorBase=void 0;let t=(Jd(),d(Kd)),n=HL();e.BatchLogRecordProcessorBase=class{_exporter;_maxExportBatchSize;_maxQueueSize;_scheduledDelayMillis;_exportTimeoutMillis;_finishedLogRecords=[];_timer;_shutdownOnce;constructor(e,r){this._exporter=e,this._maxExportBatchSize=r?.maxExportBatchSize??(0,n.getNumberFromEnv)(`OTEL_BLRP_MAX_EXPORT_BATCH_SIZE`)??512,this._maxQueueSize=r?.maxQueueSize??(0,n.getNumberFromEnv)(`OTEL_BLRP_MAX_QUEUE_SIZE`)??2048,this._scheduledDelayMillis=r?.scheduledDelayMillis??(0,n.getNumberFromEnv)(`OTEL_BLRP_SCHEDULE_DELAY`)??5e3,this._exportTimeoutMillis=r?.exportTimeoutMillis??(0,n.getNumberFromEnv)(`OTEL_BLRP_EXPORT_TIMEOUT`)??3e4,this._shutdownOnce=new n.BindOnceFuture(this._shutdown,this),this._maxExportBatchSize>this._maxQueueSize&&(t.diag.warn(`BatchLogRecordProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize`),this._maxExportBatchSize=this._maxQueueSize)}onEmit(e){this._shutdownOnce.isCalled||this._addToBuffer(e)}forceFlush(){return this._shutdownOnce.isCalled?this._shutdownOnce.promise:this._flushAll()}shutdown(){return this._shutdownOnce.call()}async _shutdown(){this.onShutdown(),await this._flushAll(),await this._exporter.shutdown()}_addToBuffer(e){this._finishedLogRecords.length>=this._maxQueueSize||(this._finishedLogRecords.push(e),this._maybeStartTimer())}_flushAll(){return new Promise((e,t)=>{let n=[],r=Math.ceil(this._finishedLogRecords.length/this._maxExportBatchSize);for(let e=0;e<r;e++)n.push(this._flushOneBatch());Promise.all(n).then(()=>{e()}).catch(t)})}_flushOneBatch(){return this._clearTimer(),this._finishedLogRecords.length===0?Promise.resolve():new Promise((e,t)=>{(0,n.callWithTimeout)(this._export(this._finishedLogRecords.splice(0,this._maxExportBatchSize)),this._exportTimeoutMillis).then(()=>e()).catch(t)})}_maybeStartTimer(){this._timer===void 0&&(this._timer=setTimeout(()=>{this._flushOneBatch().then(()=>{this._finishedLogRecords.length>0&&(this._clearTimer(),this._maybeStartTimer())}).catch(e=>{(0,n.globalErrorHandler)(e)})},this._scheduledDelayMillis),(0,n.unrefTimer)(this._timer))}_clearTimer(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)}_export(e){let t=()=>n.internal._export(this._exporter,e).then(e=>{e.code!==n.ExportResultCode.SUCCESS&&(0,n.globalErrorHandler)(e.error??Error(`BatchLogRecordProcessor: log record export failed (status ${e})`))}).catch(n.globalErrorHandler),r=e.map(e=>e.resource).filter(e=>e.asyncAttributesPending);return r.length===0?t():Promise.all(r.map(e=>e.waitForAsyncAttributes?.())).then(t,n.globalErrorHandler)}}})),lee=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BatchLogRecordProcessor=void 0;let t=cee();e.BatchLogRecordProcessor=class extends t.BatchLogRecordProcessorBase{onShutdown(){}}})),_R=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BatchLogRecordProcessor=void 0;var t=lee();Object.defineProperty(e,`BatchLogRecordProcessor`,{enumerable:!0,get:function(){return t.BatchLogRecordProcessor}})})),vR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BatchLogRecordProcessor=void 0;var t=_R();Object.defineProperty(e,`BatchLogRecordProcessor`,{enumerable:!0,get:function(){return t.BatchLogRecordProcessor}})})),yR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BatchLogRecordProcessor=e.InMemoryLogRecordExporter=e.SimpleLogRecordProcessor=e.ConsoleLogRecordExporter=e.NoopLogRecordProcessor=e.LoggerProvider=void 0;var t=mR();Object.defineProperty(e,`LoggerProvider`,{enumerable:!0,get:function(){return t.LoggerProvider}});var n=dR();Object.defineProperty(e,`NoopLogRecordProcessor`,{enumerable:!0,get:function(){return n.NoopLogRecordProcessor}});var r=hR();Object.defineProperty(e,`ConsoleLogRecordExporter`,{enumerable:!0,get:function(){return r.ConsoleLogRecordExporter}});var i=see();Object.defineProperty(e,`SimpleLogRecordProcessor`,{enumerable:!0,get:function(){return i.SimpleLogRecordProcessor}});var a=gR();Object.defineProperty(e,`InMemoryLogRecordExporter`,{enumerable:!0,get:function(){return a.InMemoryLogRecordExporter}});var o=vR();Object.defineProperty(e,`BatchLogRecordProcessor`,{enumerable:!0,get:function(){return o.BatchLogRecordProcessor}})})),bR=s((e=>{let t=ur(),n=t.__toESM(Ei()),r=t.__toESM(require(`node:async_hooks`)),i=t.__toESM(ie()),a=t.__toESM(Li()),o=t.__toESM(Fc()),s=t.__toESM(require(`node:process`)),c=t.__toESM(require(`node:os`)),l=t.__toESM(require(`node:tty`)),u=t.__toESM(require(`node:crypto`)),f=t.__toESM(uL()),p=t.__toESM(bj()),m=t.__toESM(yR()),h=t.__toESM((PA(),d(NA))),g={DELETE:`delete`,COMMENT_OUT:`comment out`,KEEP:`keep`,SKIP:`skip`},_={GREEN:`Green`,GREY:`Grey`,RED:`Red`,NA:`NA`},v={GREEN:`Green`,GREY:`Grey`,RUNTIME_ERROR:`RuntimeError`},y=function(e){return e.IDE=`IDE`,e.CLI=`CLI`,e}({}),b=function(e){return e.SIBLING_FOLDER=`siblingFolder`,e.ROOT_FOLDER=`rootFolder`,e}({}),x=function(e){return e.JEST=`jest`,e.MOCHA=`mocha`,e.VITEST=`vitest`,e.PYTEST=`pytest`,e}({}),S=function(e){return e.SPEC=`spec`,e.TEST=`test`,e}({}),C=function(e){return e.CAMEL_CASE=`camelCase`,e.KEBAB_CASE=`kebabCase`,e}({}),w=function(e){return e.NONE=`none`,e.CATEGORIES=`categories`,e}({}),T=function(e){return e.NEW_CODE_FILE=`newCodeFile`,e.OVERRIDE_CODE_FILE=`overrideCodeFile`,e}({}),E=function(e){return e.ON=`on`,e.OFF=`off`,e}({}),D={DEFAULT:0,MIN:0,MAX:100},O={DEFAULT:5,MIN:1,MAX:50};n.z.object({rootPath:n.z.string().default(process.cwd()),testStructure:n.z.enum(b).optional(),testFramework:n.z.enum(x).optional(),testSuffix:n.z.enum(S).optional(),testFileName:n.z.enum(C).optional(),calculateCoverage:n.z.enum(E).optional(),coverageThreshold:n.z.number().min(D.MIN).max(D.MAX).default(D.DEFAULT),requestSource:n.z.enum(y).optional(),concurrency:n.z.number().min(O.MIN).max(O.MAX).default(O.DEFAULT),backendURL:n.z.string().optional(),secretToken:n.z.string().optional(),modelName:n.z.string().optional(),context:n.z.object({git:n.z.object({ref_name:n.z.string(),anchorBranch:n.z.string(),compareBranch:n.z.string(),repository:n.z.string(),owner:n.z.string(),sha:n.z.string(),workflowRunId:n.z.string(),remoteUrl:n.z.string(),topLevel:n.z.string()}).partial().optional()}).optional(),testCommand:n.z.string().optional(),coverageCommand:n.z.string().optional(),lintCommand:n.z.string().optional(),prettierCommand:n.z.string().optional(),disableLintRules:n.z.boolean().optional(),ignoreAsAnyLintErrors:n.z.boolean().optional(),includeEarlyTests:n.z.boolean().optional(),greyTestBehaviour:n.z.enum(g).optional(),redTestBehaviour:n.z.enum(g).optional(),keepErrorTests:n.z.boolean().optional(),keepFailedTests:n.z.boolean().optional(),conditionalKeep:n.z.boolean().optional(),continueOnTestErrors:n.z.boolean().optional(),perFunctionTimeout:n.z.number().positive().optional(),dynamicPromptIterations:n.z.number().min(0).max(10).optional(),removeComments:n.z.boolean().optional(),experimentalAgentSdk:n.z.boolean().optional(),compressOutput:n.z.boolean().optional(),agentSdkModel:n.z.string().optional(),agentSdkBudget:n.z.number().positive().optional(),pluginPath:n.z.string().optional(),catalogId:n.z.string().optional(),label:n.z.string().optional(),debug:n.z.boolean().optional(),verbose:n.z.boolean().optional(),progressLogger:n.z.custom().optional(),onTokenRefresh:n.z.custom().optional()});var k=`@earlyai/ts-agent`,A=`0.94.0`;let ee={VSCODE:`vscode`,GITHUB_ACTION:`github-action`,UNKNOWN:`unknown`},j=`$early_filename`,te=`npx jest ${j} --no-coverage --silent --json --forceExit --maxWorkers=1`,M=`npx --no eslint ${j}`,N=`npx --no prettier ${j} --write`,P={rootPath:process.cwd(),isSiblingFolderStructured:!0,gitURL:`https://github.com/your-owner/your-repo`,testFramework:x.JEST,greyTestBehaviour:g.DELETE,redTestBehaviour:g.DELETE,keepErrorTests:!1,keepFailedTests:!1,conditionalKeep:!1,continueOnTestErrors:!0,generatedTestStructure:w.CATEGORIES,isRootFolderStructured:!1,clientSource:ee.GITHUB_ACTION,backendURL:`https://api.startearly.ai`,requestSource:y.CLI,userPrompt:``,testLocation:`__tests__`,coverageThreshold:D.DEFAULT,concurrency:5,testFileFormat:`ts`,outputType:T.NEW_CODE_FILE,shouldRefreshCoverage:!0,kebabCaseFileName:!1,earlyTestFilenameSuffix:`.early.${S.TEST}`,testSuffix:S.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:M,prettierCommand:N,disableLintRules:!1,ignoreAsAnyLintErrors:!0,allowUndefinedLintErrors:!0,perFunctionTimeout:42e4,removeComments:!0,experimentalAgentSdk:!1,compressOutput:!1,agentSdkModel:void 0,agentSdkBudget:void 0,debug:!1,verbose:!1},F=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.compressOutput.agentSdkModel.agentSdkBudget.pluginPath.label.catalogId.debug.verbose.progressLogger.onTokenRefresh`.split(`.`).reduce((t,n)=>(0,i.isDefined)(e[n])?{...t,[n]:e[n]}:t,{}),n={...(0,i.isDefined)(e.testStructure)&&{isSiblingFolderStructured:e.testStructure===b.SIBLING_FOLDER,isRootFolderStructured:e.testStructure===b.ROOT_FOLDER},...(0,i.isDefined)(e.testFileName)&&{kebabCaseFileName:e.testFileName===C.KEBAB_CASE},...(0,i.isDefined)(e.calculateCoverage)&&{shouldRefreshCoverage:e.calculateCoverage===E.ON},...(0,i.isDefined)(e.modelName)&&{fixTestsLLMModelName:e.modelName,generateTestsLLMModelName:e.modelName},...(0,i.isDefined)(e.testSuffix)&&{earlyTestFilenameSuffix:`.early.${e.testSuffix}`},...(0,i.isDefined)(e.requestSource)&&{clientSource:e.requestSource===y.IDE?ee.VSCODE:ee.GITHUB_ACTION}};return{...t,...n}},I=(e=0)=>t=>`\u001B[${t+e}m`,L=(e=0)=>t=>`\u001B[${38+e};5;${t}m`,ne=(e=0)=>(t,n,r)=>`\u001B[${38+e};2;${t};${n};${r}m`,R={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys(R.modifier);let z=Object.keys(R.color),re=Object.keys(R.bgColor);[...z,...re];function B(){let e=new Map;for(let[t,n]of Object.entries(R)){for(let[t,r]of Object.entries(n))R[t]={open:`\u001B[${r[0]}m`,close:`\u001B[${r[1]}m`},n[t]=R[t],e.set(r[0],r[1]);Object.defineProperty(R,t,{value:n,enumerable:!1})}return Object.defineProperty(R,`codes`,{value:e,enumerable:!1}),R.color.close=`\x1B[39m`,R.bgColor.close=`\x1B[49m`,R.color.ansi=I(),R.color.ansi256=L(),R.color.ansi16m=ne(),R.bgColor.ansi=I(10),R.bgColor.ansi256=L(10),R.bgColor.ansi16m=ne(10),Object.defineProperties(R,{rgbToAnsi256:{value(e,t,n){return e===t&&t===n?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(n/255*5)},enumerable:!1},hexToRgb:{value(e){let t=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!t)return[0,0,0];let[n]=t;n.length===3&&(n=[...n].map(e=>e+e).join(``));let r=Number.parseInt(n,16);return[r>>16&255,r>>8&255,r&255]},enumerable:!1},hexToAnsi256:{value:e=>R.rgbToAnsi256(...R.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return 90+(e-8);let t,n,r;if(e>=232)t=((e-232)*10+8)/255,n=t,r=t;else{e-=16;let i=e%36;t=Math.floor(e/36)/5,n=Math.floor(i/6)/5,r=i%6/5}let i=Math.max(t,n,r)*2;if(i===0)return 30;let a=30+(Math.round(r)<<2|Math.round(n)<<1|Math.round(t));return i===2&&(a+=60),a},enumerable:!1},rgbToAnsi:{value:(e,t,n)=>R.ansi256ToAnsi(R.rgbToAnsi256(e,t,n)),enumerable:!1},hexToAnsi:{value:e=>R.ansi256ToAnsi(R.hexToAnsi256(e)),enumerable:!1}}),R}var V=B();function ae(e,t=globalThis.Deno?globalThis.Deno.args:s.default.argv){let n=e.startsWith(`-`)?``:e.length===1?`-`:`--`,r=t.indexOf(n+e),i=t.indexOf(`--`);return r!==-1&&(i===-1||r<i)}let{env:oe}=s.default,se;ae(`no-color`)||ae(`no-colors`)||ae(`color=false`)||ae(`color=never`)?se=0:(ae(`color`)||ae(`colors`)||ae(`color=true`)||ae(`color=always`))&&(se=1);function ce(){if(`FORCE_COLOR`in oe)return oe.FORCE_COLOR===`true`?1:oe.FORCE_COLOR===`false`?0:oe.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(oe.FORCE_COLOR,10),3)}function le(e){return e===0?!1:{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function ue(e,{streamIsTTY:t,sniffFlags:n=!0}={}){let r=ce();r!==void 0&&(se=r);let i=n?se:r;if(i===0)return 0;if(n){if(ae(`color=16m`)||ae(`color=full`)||ae(`color=truecolor`))return 3;if(ae(`color=256`))return 2}if(`TF_BUILD`in oe&&`AGENT_NAME`in oe)return 1;if(e&&!t&&i===void 0)return 0;let a=i||0;if(oe.TERM===`dumb`)return a;if(s.default.platform===`win32`){let e=c.default.release().split(`.`);return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if(`CI`in oe)return[`GITHUB_ACTIONS`,`GITEA_ACTIONS`,`CIRCLECI`].some(e=>e in oe)?3:[`TRAVIS`,`APPVEYOR`,`GITLAB_CI`,`BUILDKITE`,`DRONE`].some(e=>e in oe)||oe.CI_NAME===`codeship`?1:a;if(`TEAMCITY_VERSION`in oe)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(oe.TEAMCITY_VERSION)?1:0;if(oe.COLORTERM===`truecolor`||oe.TERM===`xterm-kitty`||oe.TERM===`xterm-ghostty`||oe.TERM===`wezterm`)return 3;if(`TERM_PROGRAM`in oe){let e=Number.parseInt((oe.TERM_PROGRAM_VERSION||``).split(`.`)[0],10);switch(oe.TERM_PROGRAM){case`iTerm.app`:return e>=3?3:2;case`Apple_Terminal`:return 2}}return/-256(color)?$/i.test(oe.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(oe.TERM)||`COLORTERM`in oe?1:a}function de(e,t={}){return le(ue(e,{streamIsTTY:e&&e.isTTY,...t}))}var fe={stdout:de({isTTY:l.default.isatty(1)}),stderr:de({isTTY:l.default.isatty(2)})};function pe(e,t,n){let r=e.indexOf(t);if(r===-1)return e;let i=t.length,a=0,o=``;do o+=e.slice(a,r)+t+n,a=r+i,r=e.indexOf(t,a);while(r!==-1);return o+=e.slice(a),o}function me(e,t,n,r){let i=0,a=``;do{let o=e[r-1]===`\r`;a+=e.slice(i,o?r-1:r)+t+(o?`\r
|
|
118
|
+
`,(0,r.getConflictResolutionRecipe)(i,e))}return a}}})),AI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MultiMetricStorage=void 0,e.MultiMetricStorage=class{_backingStorages;constructor(e){this._backingStorages=e}record(e,t,n,r){this._backingStorages.forEach(i=>{i.record(e,t,n,r)})}}})),jI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BatchObservableResultImpl=e.ObservableResultImpl=void 0;let t=(Jd(),d(Kd)),n=wI(),r=xI();e.ObservableResultImpl=class{_instrumentName;_valueType;_buffer=new n.AttributeHashMap;constructor(e,t){this._instrumentName=e,this._valueType=t}observe(e,n={}){if(typeof e!=`number`){t.diag.warn(`non-number value provided to metric ${this._instrumentName}: ${e}`);return}this._valueType===t.ValueType.INT&&!Number.isInteger(e)&&(t.diag.warn(`INT value type cannot accept a floating-point value for ${this._instrumentName}, ignoring the fractional digits.`),e=Math.trunc(e),!Number.isInteger(e))||this._buffer.set(n,e)}},e.BatchObservableResultImpl=class{_buffer=new Map;observe(e,i,a={}){if(!(0,r.isObservableInstrument)(e))return;let o=this._buffer.get(e);if(o??(o=new n.AttributeHashMap,this._buffer.set(e,o)),typeof i!=`number`){t.diag.warn(`non-number value provided to metric ${e._descriptor.name}: ${i}`);return}e._descriptor.valueType===t.ValueType.INT&&!Number.isInteger(i)&&(t.diag.warn(`INT value type cannot accept a floating-point value for ${e._descriptor.name}, ignoring the fractional digits.`),i=Math.trunc(i),!Number.isInteger(i))||o.set(a,i)}}})),MI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ObservableRegistry=void 0;let t=(Jd(),d(Kd)),n=xI(),r=jI(),i=ZF();e.ObservableRegistry=class{_callbacks=[];_batchCallbacks=[];addCallback(e,t){this._findCallback(e,t)>=0||this._callbacks.push({callback:e,instrument:t})}removeCallback(e,t){let n=this._findCallback(e,t);n<0||this._callbacks.splice(n,1)}addBatchCallback(e,r){let i=new Set(r.filter(n.isObservableInstrument));if(i.size===0){t.diag.error(`BatchObservableCallback is not associated with valid instruments`,r);return}this._findBatchCallback(e,i)>=0||this._batchCallbacks.push({callback:e,instruments:i})}removeBatchCallback(e,t){let r=new Set(t.filter(n.isObservableInstrument)),i=this._findBatchCallback(e,r);i<0||this._batchCallbacks.splice(i,1)}async observe(e,t){let n=this._observeCallbacks(e,t),r=this._observeBatchCallbacks(e,t);return(await(0,i.PromiseAllSettled)([...n,...r])).filter(i.isPromiseAllSettledRejectionResult).map(e=>e.reason)}_observeCallbacks(e,t){return this._callbacks.map(async({callback:n,instrument:a})=>{let o=new r.ObservableResultImpl(a._descriptor.name,a._descriptor.valueType),s=Promise.resolve(n(o));t!=null&&(s=(0,i.callWithTimeout)(s,t)),await s,a._metricStorages.forEach(t=>{t.record(o._buffer,e)})})}_observeBatchCallbacks(e,t){return this._batchCallbacks.map(async({callback:n,instruments:a})=>{let o=new r.BatchObservableResultImpl,s=Promise.resolve(n(o));t!=null&&(s=(0,i.callWithTimeout)(s,t)),await s,a.forEach(t=>{let n=o._buffer.get(t);n!=null&&t._metricStorages.forEach(t=>{t.record(n,e)})})})}_findCallback(e,t){return this._callbacks.findIndex(n=>n.callback===e&&n.instrument===t)}_findBatchCallback(e,t){return this._batchCallbacks.findIndex(n=>n.callback===e&&(0,i.setEquals)(n.instruments,t))}}})),NI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.SyncMetricStorage=void 0;let t=CI(),n=TI(),r=EI();e.SyncMetricStorage=class extends t.MetricStorage{_attributesProcessor;_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;constructor(e,t,i,a,o){super(e),this._attributesProcessor=i,this._aggregationCardinalityLimit=o,this._deltaMetricStorage=new n.DeltaMetricProcessor(t,this._aggregationCardinalityLimit),this._temporalMetricStorage=new r.TemporalMetricProcessor(t,a)}record(e,t,n,r){t=this._attributesProcessor.process(t,n),this._deltaMetricStorage.record(e,t,n,r)}collect(e,t){let n=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(e,this._instrumentDescriptor,n,t)}}})),PI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.createDenyListAttributesProcessor=e.createAllowListAttributesProcessor=e.createMultiAttributesProcessor=e.createNoopAttributesProcessor=void 0;var t=class{process(e,t){return e}},n=class{_processors;constructor(e){this._processors=e}process(e,t){let n=e;for(let e of this._processors)n=e.process(n,t);return n}},r=class{_allowedAttributeNames;constructor(e){this._allowedAttributeNames=e}process(e,t){let n={};return Object.keys(e).filter(e=>this._allowedAttributeNames.includes(e)).forEach(t=>n[t]=e[t]),n}},i=class{_deniedAttributeNames;constructor(e){this._deniedAttributeNames=e}process(e,t){let n={};return Object.keys(e).filter(e=>!this._deniedAttributeNames.includes(e)).forEach(t=>n[t]=e[t]),n}};function a(){return l}e.createNoopAttributesProcessor=a;function o(e){return new n(e)}e.createMultiAttributesProcessor=o;function s(e){return new r(e)}e.createAllowListAttributesProcessor=s;function c(e){return new i(e)}e.createDenyListAttributesProcessor=c;let l=new t})),FI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MeterSharedState=void 0;let t=bI(),n=SI(),r=ZF(),i=DI(),a=kI(),o=AI(),s=MI(),c=NI(),l=PI();e.MeterSharedState=class{_meterProviderSharedState;_instrumentationScope;metricStorageRegistry=new a.MetricStorageRegistry;observableRegistry=new s.ObservableRegistry;meter;constructor(e,t){this._meterProviderSharedState=e,this._instrumentationScope=t,this.meter=new n.Meter(this)}registerMetricStorage(e){let t=this._registerMetricStorage(e,c.SyncMetricStorage);return t.length===1?t[0]:new o.MultiMetricStorage(t)}registerAsyncMetricStorage(e){return this._registerMetricStorage(e,i.AsyncMetricStorage)}async collect(e,t,n){let i=await this.observableRegistry.observe(t,n?.timeoutMillis),a=this.metricStorageRegistry.getStorages(e);if(a.length===0)return null;let o=a.map(n=>n.collect(e,t)).filter(r.isNotNullish);return o.length===0?{errors:i}:{scopeMetrics:{scope:this._instrumentationScope,metrics:o},errors:i}}_registerMetricStorage(e,n){let r=this._meterProviderSharedState.viewRegistry.findViews(e,this._instrumentationScope).map(r=>{let i=(0,t.createInstrumentDescriptorWithView)(r,e),a=this.metricStorageRegistry.findOrUpdateCompatibleStorage(i);if(a!=null)return a;let o=new n(i,r.aggregation.createAggregator(i),r.attributesProcessor,this._meterProviderSharedState.metricCollectors,r.aggregationCardinalityLimit);return this.metricStorageRegistry.register(o),o});if(r.length===0){let t=this._meterProviderSharedState.selectAggregations(e.type).map(([t,r])=>{let i=this.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(t,e);if(i!=null)return i;let a=r.createAggregator(e),o=t.selectCardinalityLimit(e.type),s=new n(e,a,(0,l.createNoopAttributesProcessor)(),[t],o);return this.metricStorageRegistry.registerForCollector(t,s),s});r=r.concat(t)}return r}}})),II=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MeterProviderSharedState=void 0;let t=ZF(),n=yI(),r=FI(),i=pI();e.MeterProviderSharedState=class{resource;viewRegistry=new n.ViewRegistry;metricCollectors=[];meterSharedStates=new Map;constructor(e){this.resource=e}getMeterSharedState(e){let n=(0,t.instrumentationScopeId)(e),i=this.meterSharedStates.get(n);return i??(i=new r.MeterSharedState(this,e),this.meterSharedStates.set(n,i)),i}selectAggregations(e){let t=[];for(let n of this.metricCollectors)t.push([n,(0,i.toAggregation)(n.selectAggregation(e))]);return t}}})),LI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MetricCollector=void 0;let t=tj();e.MetricCollector=class{_sharedState;_metricReader;constructor(e,t){this._sharedState=e,this._metricReader=t}async collect(e){let n=(0,t.millisToHrTime)(Date.now()),r=[],i=[],a=Array.from(this._sharedState.meterSharedStates.values()).map(async t=>{let a=await t.collect(this,n,e);a?.scopeMetrics!=null&&r.push(a.scopeMetrics),a?.errors!=null&&i.push(...a.errors)});return await Promise.all(a),{resourceMetrics:{resource:this._sharedState.resource,scopeMetrics:r},errors:i}}async forceFlush(e){await this._metricReader.forceFlush(e)}async shutdown(e){await this._metricReader.shutdown(e)}selectAggregationTemporality(e){return this._metricReader.selectAggregationTemporality(e)}selectAggregation(e){return this._metricReader.selectAggregation(e)}selectCardinalityLimit(e){return this._metricReader.selectCardinalityLimit?.(e)??2e3}}})),RI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ExactPredicate=e.PatternPredicate=void 0;let t=/[\^$\\.+?()[\]{}|]/g;e.PatternPredicate=class e{_matchAll;_regexp;constructor(t){t===`*`?(this._matchAll=!0,this._regexp=/.*/):(this._matchAll=!1,this._regexp=new RegExp(e.escapePattern(t)))}match(e){return this._matchAll?!0:this._regexp.test(e)}static escapePattern(e){return`^${e.replace(t,`\\$&`).replace(`*`,`.*`)}$`}static hasWildcard(e){return e.includes(`*`)}},e.ExactPredicate=class{_matchAll;_pattern;constructor(e){this._matchAll=e===void 0,this._pattern=e}match(e){return!!(this._matchAll||e===this._pattern)}}})),aee=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.InstrumentSelector=void 0;let t=RI();e.InstrumentSelector=class{_nameFilter;_type;_unitFilter;constructor(e){this._nameFilter=new t.PatternPredicate(e?.name??`*`),this._type=e?.type,this._unitFilter=new t.ExactPredicate(e?.unit)}getType(){return this._type}getNameFilter(){return this._nameFilter}getUnitFilter(){return this._unitFilter}}})),zI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MeterSelector=void 0;let t=RI();e.MeterSelector=class{_nameFilter;_versionFilter;_schemaUrlFilter;constructor(e){this._nameFilter=new t.ExactPredicate(e?.name),this._versionFilter=new t.ExactPredicate(e?.version),this._schemaUrlFilter=new t.ExactPredicate(e?.schemaUrl)}getNameFilter(){return this._nameFilter}getVersionFilter(){return this._versionFilter}getSchemaUrlFilter(){return this._schemaUrlFilter}}})),BI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.View=void 0;let t=RI(),n=PI(),r=aee(),i=zI(),a=pI();function o(e){return e.instrumentName==null&&e.instrumentType==null&&e.instrumentUnit==null&&e.meterName==null&&e.meterVersion==null&&e.meterSchemaUrl==null}function s(e){if(o(e))throw Error(`Cannot create view with no selector arguments supplied`);if(e.name!=null&&(e?.instrumentName==null||t.PatternPredicate.hasWildcard(e.instrumentName)))throw Error(`Views with a specified name must be declared with an instrument selector that selects at most one instrument per meter.`)}e.View=class{name;description;aggregation;attributesProcessor;instrumentSelector;meterSelector;aggregationCardinalityLimit;constructor(e){s(e),e.attributesProcessors==null?this.attributesProcessor=(0,n.createNoopAttributesProcessor)():this.attributesProcessor=(0,n.createMultiAttributesProcessor)(e.attributesProcessors),this.name=e.name,this.description=e.description,this.aggregation=(0,a.toAggregation)(e.aggregation??{type:a.AggregationType.DEFAULT}),this.instrumentSelector=new r.InstrumentSelector({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new i.MeterSelector({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}}})),VI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MeterProvider=void 0;let t=(Jd(),d(Kd)),n=bj(),r=II(),i=LI(),a=BI();e.MeterProvider=class{_sharedState;_shutdown=!1;constructor(e){if(this._sharedState=new r.MeterProviderSharedState(e?.resource??(0,n.defaultResource)()),e?.views!=null&&e.views.length>0)for(let t of e.views)this._sharedState.viewRegistry.addView(new a.View(t));if(e?.readers!=null&&e.readers.length>0)for(let t of e.readers){let e=new i.MetricCollector(this._sharedState,t);t.setMetricProducer(e),this._sharedState.metricCollectors.push(e)}}getMeter(e,n=``,r={}){return this._shutdown?(t.diag.warn(`A shutdown MeterProvider cannot provide a Meter`),(0,t.createNoopMeter)()):this._sharedState.getMeterSharedState({name:e,version:n,schemaUrl:r.schemaUrl}).meter}async shutdown(e){if(this._shutdown){t.diag.warn(`shutdown may only be called once per MeterProvider`);return}this._shutdown=!0,await Promise.all(this._sharedState.metricCollectors.map(t=>t.shutdown(e)))}async forceFlush(e){if(this._shutdown){t.diag.warn(`invalid attempt to force flush after MeterProvider shutdown`);return}await Promise.all(this._sharedState.metricCollectors.map(t=>t.forceFlush(e)))}}})),HI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.TimeoutError=e.createDenyListAttributesProcessor=e.createAllowListAttributesProcessor=e.AggregationType=e.MeterProvider=e.ConsoleMetricExporter=e.InMemoryMetricExporter=e.PeriodicExportingMetricReader=e.MetricReader=e.InstrumentType=e.DataPointType=e.AggregationTemporality=void 0;var t=YF();Object.defineProperty(e,`AggregationTemporality`,{enumerable:!0,get:function(){return t.AggregationTemporality}});var n=XF();Object.defineProperty(e,`DataPointType`,{enumerable:!0,get:function(){return n.DataPointType}}),Object.defineProperty(e,`InstrumentType`,{enumerable:!0,get:function(){return n.InstrumentType}});var r=hI();Object.defineProperty(e,`MetricReader`,{enumerable:!0,get:function(){return r.MetricReader}});var i=gI();Object.defineProperty(e,`PeriodicExportingMetricReader`,{enumerable:!0,get:function(){return i.PeriodicExportingMetricReader}});var a=_I();Object.defineProperty(e,`InMemoryMetricExporter`,{enumerable:!0,get:function(){return a.InMemoryMetricExporter}});var o=vI();Object.defineProperty(e,`ConsoleMetricExporter`,{enumerable:!0,get:function(){return o.ConsoleMetricExporter}});var s=VI();Object.defineProperty(e,`MeterProvider`,{enumerable:!0,get:function(){return s.MeterProvider}});var c=pI();Object.defineProperty(e,`AggregationType`,{enumerable:!0,get:function(){return c.AggregationType}});var l=PI();Object.defineProperty(e,`createAllowListAttributesProcessor`,{enumerable:!0,get:function(){return l.createAllowListAttributesProcessor}}),Object.defineProperty(e,`createDenyListAttributesProcessor`,{enumerable:!0,get:function(){return l.createDenyListAttributesProcessor}});var u=ZF();Object.defineProperty(e,`TimeoutError`,{enumerable:!0,get:function(){return u.TimeoutError}})})),UI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.StatsbeatFeatureType=e.EU_ENDPOINTS=e.EU_CONNECTION_STRING=e.NON_EU_CONNECTION_STRING=e.AIMS_FORMAT=e.AIMS_API_VERSION=e.AIMS_URI=e.StatsbeatCounter=e.AttachTypeName=e.StatsbeatResourceProvider=e.MAX_STATSBEAT_FAILURES=e.AZURE_MONITOR_AUTO_ATTACH=e.STATSBEAT_LANGUAGE=e.NetworkStatsbeat=void 0,e.isStatsbeatShutdownStatus=i,e.NetworkStatsbeat=class{constructor(e,t){this.endpoint=e,this.host=t,this.totalRequestCount=0,this.totalSuccessfulRequestCount=0,this.totalReadFailureCount=0,this.totalWriteFailureCount=0,this.totalFailedRequestCount=[],this.retryCount=[],this.exceptionCount=[],this.throttleCount=[],this.intervalRequestExecutionTime=0,this.lastIntervalRequestExecutionTime=0,this.lastTime=+new Date,this.lastRequestCount=0,this.averageRequestExecutionTime=0}},e.STATSBEAT_LANGUAGE=`node`,e.AZURE_MONITOR_AUTO_ATTACH=`AZURE_MONITOR_AUTO_ATTACH`,e.MAX_STATSBEAT_FAILURES=3,e.StatsbeatResourceProvider={appsvc:`appsvc`,aks:`aks`,functions:`functions`,vm:`vm`,unknown:`unknown`};var t;(function(e){e.INTEGRATED_AUTO=`IntegratedAuto`,e.MANUAL=`Manual`})(t||(e.AttachTypeName=t={}));var n;(function(e){e.SUCCESS_COUNT=`Request_Success_Count`,e.FAILURE_COUNT=`Request_Failure_Count`,e.RETRY_COUNT=`Retry_Count`,e.THROTTLE_COUNT=`Throttle_Count`,e.EXCEPTION_COUNT=`Exception_Count`,e.AVERAGE_DURATION=`Request_Duration`,e.READ_FAILURE_COUNT=`Read_Failure_Count`,e.WRITE_FAILURE_COUNT=`Write_Failure_Count`,e.ATTACH=`Attach`,e.FEATURE=`Feature`})(n||(e.StatsbeatCounter=n={})),e.AIMS_URI=`http://169.254.169.254/metadata/instance/compute`,e.AIMS_API_VERSION=`api-version=2017-12-01`,e.AIMS_FORMAT=`format=json`,e.NON_EU_CONNECTION_STRING=`InstrumentationKey=c4a29126-a7cb-47e5-b348-11414998b11e;IngestionEndpoint=https://westus-0.in.applicationinsights.azure.com`,e.EU_CONNECTION_STRING=`InstrumentationKey=7dc56bab-3c0c-4e9f-9ebb-d1acadee8d0f;IngestionEndpoint=https://westeurope-5.in.applicationinsights.azure.com`,e.EU_ENDPOINTS=[`westeurope`,`northeurope`,`francecentral`,`francesouth`,`germanywestcentral`,`norwayeast`,`norwaywest`,`swedencentral`,`switzerlandnorth`,`switzerlandwest`,`uksouth`,`ukwest`];var r;(function(e){e[e.FEATURE=0]=`FEATURE`,e[e.INSTRUMENTATION=1]=`INSTRUMENTATION`})(r||(e.StatsbeatFeatureType=r={}));function i(e){return e===401||e===403||e===503}})),WI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.StatsbeatMetrics=void 0;let t=(kM(),d(Gj)),n=DF(),r=(Jd(),d(Kd)),i=UI(),a=t.__importStar(require(`node:os`));e.StatsbeatMetrics=class{constructor(){this.resourceProvider=i.StatsbeatResourceProvider.unknown,this.vmInfo={},this.os=a.type(),this.resourceIdentifier=``}async getResourceProvider(){this.resourceProvider=i.StatsbeatResourceProvider.unknown,process.env.AKS_ARM_NAMESPACE_ID?(this.resourceProvider=i.StatsbeatResourceProvider.aks,this.resourceIdentifier=process.env.AKS_ARM_NAMESPACE_ID):process.env.WEBSITE_SITE_NAME?(this.resourceProvider=i.StatsbeatResourceProvider.appsvc,this.resourceIdentifier=process.env.WEBSITE_SITE_NAME,process.env.WEBSITE_HOME_STAMPNAME&&(this.resourceIdentifier+=`/`+process.env.WEBSITE_HOME_STAMPNAME)):process.env.FUNCTIONS_WORKER_RUNTIME?(this.resourceProvider=i.StatsbeatResourceProvider.functions,process.env.WEBSITE_HOSTNAME&&(this.resourceIdentifier=process.env.WEBSITE_HOSTNAME)):await this.getAzureComputeMetadata()?(this.resourceProvider=i.StatsbeatResourceProvider.vm,this.resourceIdentifier=this.vmInfo.id+`/`+this.vmInfo.subscriptionId,this.vmInfo.osType&&(this.os=this.vmInfo.osType)):this.resourceProvider=i.StatsbeatResourceProvider.unknown}async getAzureComputeMetadata(){let e=(0,n.createDefaultHttpClient)(),t={url:`${i.AIMS_URI}?${i.AIMS_API_VERSION}&${i.AIMS_FORMAT}`,timeout:5e3,method:`GET`,allowInsecureConnection:!0},a=(0,n.createPipelineRequest)(t);return await e.sendRequest(a).then(e=>{if(e.status===200){this.vmInfo.isVM=!0;let t=``;return e.on(`data`,e=>{t+=e}),e.on(`end`,()=>{try{let e=JSON.parse(t);this.vmInfo.id=e.vmId||``,this.vmInfo.subscriptionId=e.subscriptionId||``,this.vmInfo.osType=e.osType||``}catch(e){r.diag.debug(`Failed to parse JSON: `,e)}}),!0}else return!1}).catch(()=>!1),!1}getConnectionString(e){let t=e;for(let e=0;e<i.EU_ENDPOINTS.length;e++)if(t.includes(i.EU_ENDPOINTS[e]))return i.EU_CONNECTION_STRING;return i.NON_EU_CONNECTION_STRING}}})),GI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.resourceMetricsToEnvelope=l,e.isAksAttach=u,e.shouldSendToOtlp=d,e.isStandardMetric=f,e.getAttachType=p;let t=HI(),n=nL(),r=dN(),i=AM(),a=UI(),o=tL(),s=new Map([[r.OTelPerformanceCounterNames.PRIVATE_BYTES,r.BreezePerformanceCounterNames.PRIVATE_BYTES],[r.OTelPerformanceCounterNames.AVAILABLE_BYTES,r.BreezePerformanceCounterNames.AVAILABLE_BYTES],[r.OTelPerformanceCounterNames.PROCESSOR_TIME,r.BreezePerformanceCounterNames.PROCESSOR_TIME],[r.OTelPerformanceCounterNames.PROCESS_TIME_STANDARD,r.BreezePerformanceCounterNames.PROCESS_TIME_STANDARD],[r.OTelPerformanceCounterNames.PROCESS_TIME_NORMALIZED,r.BreezePerformanceCounterNames.PROCESS_TIME_NORMALIZED],[r.OTelPerformanceCounterNames.REQUEST_RATE,r.BreezePerformanceCounterNames.REQUEST_RATE],[r.OTelPerformanceCounterNames.REQUEST_DURATION,r.BreezePerformanceCounterNames.REQUEST_DURATION],[r.OTelPerformanceCounterNames.EXCEPTION_RATE,r.BreezePerformanceCounterNames.EXCEPTION_RATE]]);function c(e){let t={};if(e)for(let n of Object.keys(e))t[n]=e[n];return t}function l(e,r,a){let l=[],p=new Date,m=r,h,g;if(a){g=`Microsoft.ApplicationInsights.Statsbeat`;let e=(0,o.getInstance)();h=Object.assign({},e.tags)}else g=`Microsoft.ApplicationInsights.Metric`,h=(0,n.createTagsFromResource)(e.resource);return e.scopeMetrics.forEach(e=>{e.metrics.forEach(e=>{e.dataPoints.forEach(n=>{let r={metrics:[],version:2,properties:{}};if(r.properties=c(n.attributes),d()&&u()&&!f(n)&&process.env[i.ENV_APPLICATIONINSIGHTS_METRICS_TO_LOGANALYTICS_ENABLED]===`false`&&!a)return;d()&&u()&&!a?r.properties[`_MS.SentToAMW`]=`True`:u()&&!a&&(r.properties[`_MS.SentToAMW`]=`False`);let o;s.has(e.descriptor.name)&&(o=s.get(e.descriptor.name));let _={name:o||e.descriptor.name,value:0,dataPointType:`Aggregation`};e.dataPointType===t.DataPointType.SUM||e.dataPointType===t.DataPointType.GAUGE?(_.value=n.value,_.count=1):(_.value=n.value.sum||0,_.count=n.value.count,_.max=n.value.max,_.min=n.value.min),r.metrics.push(_);let v={name:g,time:p,sampleRate:100,instrumentationKey:m,tags:h,version:1,data:{baseType:`MetricData`,baseData:Object.assign({},r)}};l.push(v)})})}),l}function u(){return!!(process.env[i.ENV_AZURE_MONITOR_AUTO_ATTACH]===`true`&&process.env.AKS_ARM_NAMESPACE_ID)}function d(){return!!(process.env[i.ENV_OTLP_METRICS_ENDPOINT]&&process.env[i.ENV_OTEL_METRICS_EXPORTER]?.includes(`otlp`))}function f(e){return e.attributes?.[`_MS.IsAutocollected`]===`True`}function p(){return process.env[a.AZURE_MONITOR_AUTO_ATTACH]===`true`?a.AttachTypeName.INTEGRATED_AUTO:a.AttachTypeName.MANUAL}})),KI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AzureMonitorStatsbeatExporter=void 0;let t=(Jd(),d(Kd)),n=uN(),r=GI(),i=MM(),a=tL();e.AzureMonitorStatsbeatExporter=class extends i.AzureMonitorBaseExporter{constructor(e){super(e,!0),this._isShutdown=!1,this._sender=new a.HttpSender({endpointUrl:this.endpointUrl,instrumentationKey:this.instrumentationKey,trackStatsbeat:this.trackStatsbeat,exporterOptions:e,isStatsbeatSender:!0})}async export(e,i){if(this._isShutdown){setTimeout(()=>i({code:n.ExportResultCode.FAILED}),0);return}let a=(0,r.resourceMetricsToEnvelope)(e,this.instrumentationKey,!0);t.context.with((0,n.suppressTracing)(t.context.active()),async()=>{i(await this._sender.exportEnvelopes(a))})}async shutdown(){return this._isShutdown=!0,this._sender.shutdown()}async forceFlush(){return Promise.resolve()}}})),qI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.NetworkStatsbeatMetrics=void 0;let t=(kM(),d(Gj)),n=(Jd(),d(Kd)),r=HI(),i=t.__importStar(Uj()),a=WI(),o=UI(),s=KI(),c=AM(),l=GI();var u=class e extends a.StatsbeatMetrics{constructor(e){super(),this.disableNonEssentialStatsbeat=!!process.env[c.ENV_DISABLE_STATSBEAT],this.isInitialized=!1,this.statsCollectionShortInterval=9e5,this.networkStatsbeatCollection=[],this.attach=(0,l.getAttachType)(),this.connectionString=super.getConnectionString(e.endpointUrl);let t={connectionString:this.connectionString};this.networkAzureExporter=new s.AzureMonitorStatsbeatExporter(t);let n={exporter:this.networkAzureExporter,exportIntervalMillis:e.networkCollectionInterval||this.statsCollectionShortInterval};this.networkStatsbeatMeterProvider=new r.MeterProvider({readers:[new r.PeriodicExportingMetricReader(n)]}),this.networkStatsbeatMeter=this.networkStatsbeatMeterProvider.getMeter(`Azure Monitor Network Statsbeat`),this.endpointUrl=e.endpointUrl,this.runtimeVersion=process.version,this.language=o.STATSBEAT_LANGUAGE,this.version=i.packageVersion,this.host=this.getShortHost(e.endpointUrl),this.cikey=e.instrumentationKey,this.successCountGauge=this.networkStatsbeatMeter.createObservableGauge(o.StatsbeatCounter.SUCCESS_COUNT),this.failureCountGauge=this.networkStatsbeatMeter.createObservableGauge(o.StatsbeatCounter.FAILURE_COUNT),this.retryCountGauge=this.networkStatsbeatMeter.createObservableGauge(o.StatsbeatCounter.RETRY_COUNT),this.throttleCountGauge=this.networkStatsbeatMeter.createObservableGauge(o.StatsbeatCounter.THROTTLE_COUNT),this.exceptionCountGauge=this.networkStatsbeatMeter.createObservableGauge(o.StatsbeatCounter.EXCEPTION_COUNT),this.averageDurationGauge=this.networkStatsbeatMeter.createObservableGauge(o.StatsbeatCounter.AVERAGE_DURATION),this.disableNonEssentialStatsbeat||(this.readFailureGauge=this.networkStatsbeatMeter.createObservableGauge(o.StatsbeatCounter.READ_FAILURE_COUNT),this.writeFailureGauge=this.networkStatsbeatMeter.createObservableGauge(o.StatsbeatCounter.WRITE_FAILURE_COUNT)),this.isInitialized=!0,this.initialize(),this.commonProperties={os:this.os,rp:this.resourceProvider,cikey:this.cikey,runtimeVersion:this.runtimeVersion,language:this.language,version:this.version,attach:this.attach},this.networkProperties={endpoint:this.endpointUrl,host:this.host}}shutdown(){return this.networkStatsbeatMeterProvider.shutdown()}async initialize(){var e,t;try{await super.getResourceProvider(),this.successCountGauge.addCallback(this.successCallback.bind(this)),this.networkStatsbeatMeter.addBatchObservableCallback(this.failureCallback.bind(this),[this.failureCountGauge]),this.networkStatsbeatMeter.addBatchObservableCallback(this.retryCallback.bind(this),[this.retryCountGauge]),this.networkStatsbeatMeter.addBatchObservableCallback(this.throttleCallback.bind(this),[this.throttleCountGauge]),this.networkStatsbeatMeter.addBatchObservableCallback(this.exceptionCallback.bind(this),[this.exceptionCountGauge]),this.disableNonEssentialStatsbeat||((e=this.readFailureGauge)==null||e.addCallback(this.readFailureCallback.bind(this)),(t=this.writeFailureGauge)==null||t.addCallback(this.writeFailureCallback.bind(this))),this.averageDurationGauge.addCallback(this.durationCallback.bind(this))}catch{n.diag.debug(`Call to get the resource provider failed.`)}}successCallback(e){let t=this.getNetworkStatsbeatCounter(this.endpointUrl,this.host);if(t.totalSuccessfulRequestCount>0){let n=Object.assign(Object.assign({},this.commonProperties),this.networkProperties);e.observe(t.totalSuccessfulRequestCount,n),t.totalSuccessfulRequestCount=0}}failureCallback(e){let t=this.getNetworkStatsbeatCounter(this.endpointUrl,this.host),n=Object.assign(Object.assign(Object.assign({},this.networkProperties),this.commonProperties),{statusCode:0});for(let r=0;r<t.totalFailedRequestCount.length;r++)t.totalFailedRequestCount[r].count>0&&(n.statusCode=t.totalFailedRequestCount[r].statusCode,e.observe(this.failureCountGauge,t.totalFailedRequestCount[r].count,Object.assign({},n)),t.totalFailedRequestCount[r].count=0)}retryCallback(e){let t=this.getNetworkStatsbeatCounter(this.endpointUrl,this.host),n=Object.assign(Object.assign(Object.assign({},this.networkProperties),this.commonProperties),{statusCode:0});for(let r=0;r<t.retryCount.length;r++)t.retryCount[r].count>0&&(n.statusCode=t.retryCount[r].statusCode,e.observe(this.retryCountGauge,t.retryCount[r].count,Object.assign({},n)),t.retryCount[r].count=0)}throttleCallback(e){let t=this.getNetworkStatsbeatCounter(this.endpointUrl,this.host),n=Object.assign(Object.assign(Object.assign({},this.networkProperties),this.commonProperties),{statusCode:0});for(let r=0;r<t.throttleCount.length;r++)t.throttleCount[r].count>0&&(n.statusCode=t.throttleCount[r].statusCode,e.observe(this.throttleCountGauge,t.throttleCount[r].count,Object.assign({},n)),t.throttleCount[r].count=0)}exceptionCallback(e){let t=this.getNetworkStatsbeatCounter(this.endpointUrl,this.host),n=Object.assign(Object.assign(Object.assign({},this.networkProperties),this.commonProperties),{exceptionType:``});for(let r=0;r<t.exceptionCount.length;r++)t.exceptionCount[r].count>0&&(n.exceptionType=t.exceptionCount[r].exceptionType,e.observe(this.exceptionCountGauge,t.exceptionCount[r].count,Object.assign({},n)),t.exceptionCount[r].count=0)}durationCallback(e){let t=this.getNetworkStatsbeatCounter(this.endpointUrl,this.host),n=Object.assign(Object.assign({},this.networkProperties),this.commonProperties);for(let e=0;e<this.networkStatsbeatCollection.length;e++){let t=this.networkStatsbeatCollection[e];t.time=Number(new Date);let n=t.totalRequestCount-t.lastRequestCount||0;n>0?t.averageRequestExecutionTime=(t.intervalRequestExecutionTime-t.lastIntervalRequestExecutionTime)/n||0:t.averageRequestExecutionTime=0,t.lastIntervalRequestExecutionTime=t.intervalRequestExecutionTime,t.lastRequestCount=t.totalRequestCount,t.lastTime=t.time}t.averageRequestExecutionTime>0&&(e.observe(t.averageRequestExecutionTime,n),t.averageRequestExecutionTime=0)}readFailureCallback(e){let t=this.getNetworkStatsbeatCounter(this.endpointUrl,this.host);if(t.totalReadFailureCount>0){let n=Object.assign(Object.assign({},this.commonProperties),this.networkProperties);e.observe(t.totalReadFailureCount,n),t.totalReadFailureCount=0}}writeFailureCallback(e){let t=this.getNetworkStatsbeatCounter(this.endpointUrl,this.host);if(t.totalWriteFailureCount>0){let n=Object.assign(Object.assign({},this.commonProperties),this.networkProperties);e.observe(t.totalWriteFailureCount,n),t.totalWriteFailureCount=0}}countSuccess(e){if(!this.isInitialized)return;let t=this.getNetworkStatsbeatCounter(this.endpointUrl,this.host);t.totalRequestCount++,t.totalSuccessfulRequestCount++,t.intervalRequestExecutionTime+=e}countFailure(e,t){if(!this.isInitialized)return;let n=this.getNetworkStatsbeatCounter(this.endpointUrl,this.host),r=n.totalFailedRequestCount.find(e=>t===e.statusCode);r?r.count++:n.totalFailedRequestCount.push({statusCode:t,count:1}),n.totalRequestCount++,n.intervalRequestExecutionTime+=e}countRetry(e){if(!this.isInitialized)return;let t=this.getNetworkStatsbeatCounter(this.endpointUrl,this.host),n=t.retryCount.find(t=>e===t.statusCode);n?n.count++:t.retryCount.push({statusCode:e,count:1})}countThrottle(e){if(!this.isInitialized)return;let t=this.getNetworkStatsbeatCounter(this.endpointUrl,this.host),n=t.throttleCount.find(t=>e===t.statusCode);n?n.count++:t.throttleCount.push({statusCode:e,count:1})}countReadFailure(){if(!this.isInitialized||this.disableNonEssentialStatsbeat)return;let e=this.getNetworkStatsbeatCounter(this.endpointUrl,this.host);e.totalReadFailureCount++}countWriteFailure(){if(!this.isInitialized||this.disableNonEssentialStatsbeat)return;let e=this.getNetworkStatsbeatCounter(this.endpointUrl,this.host);e.totalWriteFailureCount++}countException(e){if(!this.isInitialized)return;let t=this.getNetworkStatsbeatCounter(this.endpointUrl,this.host),n=t.exceptionCount.find(t=>e.name===t.exceptionType);n?n.count++:t.exceptionCount.push({exceptionType:e.name,count:1})}getNetworkStatsbeatCounter(e,t){for(let n=0;n<this.networkStatsbeatCollection.length;n++)if(e===this.networkStatsbeatCollection[n].endpoint&&t===this.networkStatsbeatCollection[n].host)return this.networkStatsbeatCollection[n];let n=new o.NetworkStatsbeat(e,t);return this.networkStatsbeatCollection.push(n),n}getShortHost(e){let t=e;try{let n=new RegExp(/^https?:\/\/(?:www\.)?([^/.-]+)/).exec(e);n!==null&&n.length>1&&(t=n[1]),t=t.replace(`.in.applicationinsights.azure.com`,``)}catch{n.diag.debug(`Failed to get the short host name.`)}return t}static getInstance(t){return e.instance||=new e(t),e.instance}};e.NetworkStatsbeatMetrics=u,u.instance=null})),JI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.LongIntervalStatsbeatMetrics=void 0;let t=(kM(),d(Gj)),n=(Jd(),d(Kd)),r=uN(),i=HI(),a=t.__importStar(Uj()),o=WI(),s=UI(),c=KI(),l=GI();var u=class e extends o.StatsbeatMetrics{constructor(e){super(),this.statsCollectionLongInterval=864e5,this.attach=(0,l.getAttachType)(),this.feature=0,this.instrumentation=0,this.isInitialized=!1,this.connectionString=super.getConnectionString(e.endpointUrl);let t={connectionString:this.connectionString,disableOfflineStorage:e.disableOfflineStorage};this.setFeatures(),this.longIntervalAzureExporter=new c.AzureMonitorStatsbeatExporter(t);let n={exporter:this.longIntervalAzureExporter,exportIntervalMillis:Number(process.env.LONG_INTERVAL_EXPORT_MILLIS)||this.statsCollectionLongInterval};this.longIntervalMetricReader=new i.PeriodicExportingMetricReader(n),this.longIntervalStatsbeatMeterProvider=new i.MeterProvider({readers:[this.longIntervalMetricReader]}),this.longIntervalStatsbeatMeter=this.longIntervalStatsbeatMeterProvider.getMeter(`Azure Monitor Long Interval Statsbeat`),this.runtimeVersion=process.version,this.language=s.STATSBEAT_LANGUAGE,this.version=a.packageVersion,this.cikey=e.instrumentationKey,this.featureStatsbeatGauge=this.longIntervalStatsbeatMeter.createObservableGauge(s.StatsbeatCounter.FEATURE),this.attachStatsbeatGauge=this.longIntervalStatsbeatMeter.createObservableGauge(s.StatsbeatCounter.ATTACH),this.isInitialized=!0,this.initialize(),this.commonProperties={os:this.os,rp:this.resourceProvider,cikey:this.cikey,runtimeVersion:this.runtimeVersion,language:this.language,version:this.version,attach:this.attach},this.attachProperties={rpId:this.resourceIdentifier}}async initialize(){try{await this.getResourceProvider(),this.attachStatsbeatGauge.addCallback(this.attachCallback.bind(this)),this.longIntervalStatsbeatMeter.addBatchObservableCallback(this.getEnvironmentStatus.bind(this),[this.featureStatsbeatGauge]),setTimeout(async()=>{try{let e=await this.longIntervalMetricReader.collect();e?this.longIntervalAzureExporter.export(e.resourceMetrics,e=>{e.code!==r.ExportResultCode.SUCCESS&&n.diag.debug(`LongIntervalStatsbeat: metrics export failed (error ${e.error})`)}):n.diag.debug(`LongIntervalStatsbeat: No metrics collected`)}catch(e){n.diag.debug(`LongIntervalStatsbeat: Error collecting metrics: ${e}`)}},15e3)}catch{n.diag.debug(`Call to get the resource provider failed.`)}}getEnvironmentStatus(e){this.setFeatures();let t;this.instrumentation>0&&(t=Object.assign(Object.assign({},this.commonProperties),{feature:this.instrumentation,type:s.StatsbeatFeatureType.INSTRUMENTATION}),e.observe(this.featureStatsbeatGauge,1,Object.assign({},t))),this.feature>0&&(t=Object.assign(Object.assign({},this.commonProperties),{feature:this.feature,type:s.StatsbeatFeatureType.FEATURE}),e.observe(this.featureStatsbeatGauge,1,Object.assign({},t)))}setFeatures(){let e=process.env.AZURE_MONITOR_STATSBEAT_FEATURES;if(e)try{this.feature=JSON.parse(e).feature,this.instrumentation=JSON.parse(e).instrumentation}catch(e){n.diag.debug(`LongIntervalStatsbeat: Failed to parse features/instrumentations (error ${e})`)}}attachCallback(e){let t=Object.assign(Object.assign({},this.commonProperties),this.attachProperties);e.observe(1,t)}shutdown(){return this.longIntervalStatsbeatMeterProvider.shutdown()}static getInstance(t){return e.instance||=new e(t),e.instance}};e.LongIntervalStatsbeatMetrics=u,u.instance=null})),YI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.isRetriable=t,e.msToTimeSpan=n;function t(e){return e===206||e===401||e===403||e===408||e===429||e===439||e===500||e===502||e===503||e===504}function n(e){(isNaN(e)||e<0)&&(e=0);let t=(e/1e3%60).toFixed(7).replace(/0{0,4}$/,``),n=``+Math.floor(e/(1e3*60))%60,r=``+Math.floor(e/(1e3*60*60))%24,i=Math.floor(e/(1e3*60*60*24));return t=t.indexOf(`.`)<2?`0`+t:t,n=n.length<2?`0`+n:n,r=r.length<2?`0`+r:r,(i>0?i+`.`:``)+r+`:`+n+`:`+t}})),XI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BaseSender=void 0;let t=(Jd(),d(Kd)),n=gN(),r=uN(),i=qI(),a=JI(),o=UI(),s=YI(),c=AM();e.BaseSender=class{constructor(e){this.statsbeatFailureCount=0,this.batchSendRetryIntervalMs=6e4,this.numConsecutiveRedirects=0,this.disableOfflineStorage=e.exporterOptions.disableOfflineStorage||!1,this.persister=new n.FileSystemPersist(e.instrumentationKey,e.exporterOptions),e.trackStatsbeat&&(this.networkStatsbeatMetrics=i.NetworkStatsbeatMetrics.getInstance({instrumentationKey:e.instrumentationKey,endpointUrl:e.endpointUrl,disableOfflineStorage:this.disableOfflineStorage}),this.longIntervalStatsbeatMetrics=a.LongIntervalStatsbeatMetrics.getInstance({instrumentationKey:e.instrumentationKey,endpointUrl:e.endpointUrl,disableOfflineStorage:this.disableOfflineStorage})),this.retryTimer=null,this.isStatsbeatSender=e.isStatsbeatSender||!1}async exportEnvelopes(e){var n,i,a,c,l,u,d,f,p,m;if(t.diag.info(`Exporting ${e.length} envelope(s)`),e.length<1)return{code:r.ExportResultCode.SUCCESS};try{let o=new Date().getTime(),{result:d,statusCode:f}=await this.send(e),p=new Date().getTime()-o;if(this.numConsecutiveRedirects=0,f===200)return this.retryTimer||(this.retryTimer=setTimeout(()=>{this.retryTimer=null,this.sendFirstPersistedFile()},this.batchSendRetryIntervalMs),this.retryTimer.unref()),this.isStatsbeatSender||(n=this.networkStatsbeatMetrics)==null||n.countSuccess(p),{code:r.ExportResultCode.SUCCESS};if(f&&(0,s.isRetriable)(f)){if(f===429||f===439)return this.isStatsbeatSender||(i=this.networkStatsbeatMetrics)==null||i.countThrottle(f),{code:r.ExportResultCode.SUCCESS};if(d){t.diag.info(d);let n=JSON.parse(d),i=[];return n.itemsAccepted>0&&f===206&&!this.isStatsbeatSender&&((a=this.networkStatsbeatMetrics)==null||a.countSuccess(p)),n.errors&&n.errors.forEach(t=>{t.statusCode&&(0,s.isRetriable)(t.statusCode)&&i.push(e[t.index])}),i.length>0?(this.isStatsbeatSender||(c=this.networkStatsbeatMetrics)==null||c.countRetry(f),await this.persist(i)):(this.isStatsbeatSender||(l=this.networkStatsbeatMetrics)==null||l.countFailure(p,f),{code:r.ExportResultCode.FAILED})}else return this.isStatsbeatSender||(u=this.networkStatsbeatMetrics)==null||u.countRetry(f),await this.persist(e)}else return this.networkStatsbeatMetrics&&!this.isStatsbeatSender?f&&this.networkStatsbeatMetrics.countFailure(p,f):this.incrementStatsbeatFailure(),{code:r.ExportResultCode.FAILED}}catch(n){let i=n;if(i.statusCode&&(i.statusCode===307||i.statusCode===308))if(this.numConsecutiveRedirects++,this.numConsecutiveRedirects<10){if(i.response&&i.response.headers){let t=i.response.headers.get(`location`);if(t)return this.handlePermanentRedirect(t),this.exportEnvelopes(e)}}else{let e=Error(`Circular redirect`);return this.isStatsbeatSender||(d=this.networkStatsbeatMetrics)==null||d.countException(e),{code:r.ExportResultCode.FAILED,error:e}}else if(i.statusCode&&(0,s.isRetriable)(i.statusCode)&&!this.isStatsbeatSender)return(f=this.networkStatsbeatMetrics)==null||f.countRetry(i.statusCode),this.persist(e);else if(i.statusCode===400&&i.message.includes(`Invalid instrumentation key`))return this.shutdownStatsbeat(),{code:r.ExportResultCode.SUCCESS};else if(i.statusCode&&this.isStatsbeatSender&&(0,o.isStatsbeatShutdownStatus)(i.statusCode))return this.incrementStatsbeatFailure(),{code:r.ExportResultCode.SUCCESS};return this.isRetriableRestError(i)?(i.statusCode&&!this.isStatsbeatSender&&((p=this.networkStatsbeatMetrics)==null||p.countRetry(i.statusCode)),this.isStatsbeatSender||t.diag.error(`Retrying due to transient client side error. Error message:`,i.message),this.persist(e)):(this.isStatsbeatSender||(m=this.networkStatsbeatMetrics)==null||m.countException(i),this.isStatsbeatSender||t.diag.error(`Envelopes could not be exported and are not retriable. Error message:`,i.message),{code:r.ExportResultCode.FAILED,error:i})}}async persist(e){var t;try{return await this.persister.push(e)?{code:r.ExportResultCode.SUCCESS}:{code:r.ExportResultCode.FAILED,error:Error(`Failed to persist envelope in disk.`)}}catch(e){return this.isStatsbeatSender||(t=this.networkStatsbeatMetrics)==null||t.countWriteFailure(),{code:r.ExportResultCode.FAILED,error:e}}}incrementStatsbeatFailure(){this.statsbeatFailureCount++,this.statsbeatFailureCount>o.MAX_STATSBEAT_FAILURES&&this.shutdownStatsbeat()}shutdownStatsbeat(){var e;this.networkStatsbeatMetrics&&this.networkStatsbeatMetrics.shutdown(),(e=this.longIntervalStatsbeatMetrics)==null||e.shutdown(),this.statsbeatFailureCount=0}async sendFirstPersistedFile(){var e;try{let e=await this.persister.shift();e&&await this.send(e)}catch(n){this.isStatsbeatSender||(e=this.networkStatsbeatMetrics)==null||e.countReadFailure(),t.diag.warn(`Failed to fetch persisted file`,n)}}isRetriableRestError(e){let t=Object.values(c.RetriableRestErrorTypes);return!!(e&&e.code&&t.includes(e.code))}}})),ZI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.HttpSender=void 0;let t=(kM(),d(Gj)).__importDefault(require(`node:url`)),n=(Jd(),d(Kd)),r=DF(),i=JF(),a=XI();e.HttpSender=class extends a.BaseSender{constructor(e){super(e),this.appInsightsClientOptions=Object.assign({host:e.endpointUrl},e.exporterOptions),this.appInsightsClientOptions.credential&&(e.aadAudience?this.appInsightsClientOptions.credentialScopes=[e.aadAudience]:this.appInsightsClientOptions.credentialScopes=[`https://monitor.azure.com//.default`]),this.appInsightsClient=new i.ApplicationInsightsClient(this.appInsightsClientOptions),this.appInsightsClient.pipeline.removePolicy({name:r.redirectPolicyName})}async send(e){let t={},n;function r(e,r){n=e,t.onResponse&&t.onResponse(e,r)}return await this.appInsightsClient.track(e,Object.assign(Object.assign({},t),{onResponse:r})),{statusCode:n?.status,result:n?.bodyAsText??``}}async shutdown(){n.diag.info(`HttpSender shutting down`)}handlePermanentRedirect(e){if(e){let n=new t.default.URL(e);n&&n.host&&(this.appInsightsClient.host=`https://`+n.host)}}}})),QI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.Context=void 0,e.getInstance=u;let t=(kM(),d(Gj)),n=t.__importStar(require(`node:os`)),r=uN(),i=(PA(),d(NA)),a=JF(),o=t.__importStar(Uj()),s=AM(),c=null;var l=class e{constructor(){this.tags={},this._loadDeviceContext(),this._loadInternalContext()}_loadDeviceContext(){this.tags[a.KnownContextTagKeys.AiDeviceOsVersion]=n&&`${n.type()} ${n.release()}`}_loadInternalContext(){let{node:t}=process.versions;[e.nodeVersion]=t.split(`.`),e.opentelemetryVersion=r.SDK_INFO[i.ATTR_TELEMETRY_SDK_VERSION],e.sdkVersion=o.packageVersion;let n=process.env[s.ENV_AZURE_MONITOR_PREFIX]?process.env[s.ENV_AZURE_MONITOR_PREFIX]:``,c=this._getVersion(),l=`${n}node${e.nodeVersion}:otel${e.opentelemetryVersion}:${c}`;this.tags[a.KnownContextTagKeys.AiInternalSdkVersion]=l}_getVersion(){return process.env[s.ENV_APPLICATIONINSIGHTS_SHIM_VERSION]?`sha${process.env[s.ENV_APPLICATIONINSIGHTS_SHIM_VERSION]}`:process.env[s.ENV_AZURE_MONITOR_DISTRO_VERSION]?`dst${process.env[s.ENV_AZURE_MONITOR_DISTRO_VERSION]}`:`ext${e.sdkVersion}`}};e.Context=l,l.sdkVersion=null,l.opentelemetryVersion=null,l.nodeVersion=``;function u(){return c||=new l,c}})),$I=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),(kM(),d(Gj)).__exportStar(QI(),e)})),eL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=(kM(),d(Gj));t.__exportStar(fN(),e),t.__exportStar(gN(),e),t.__exportStar(ZI(),e),t.__exportStar($I(),e)})),tL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),(kM(),d(Gj)).__exportStar(eL(),e)})),nL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.hrTimeToDate=l,e.createTagsFromResource=u,e.isSqlDB=m,e.getUrl=h,e.getDependencyTarget=g,e.createResourceMetricEnvelope=_,e.serializeAttribute=v,e.shouldCreateResourceMetric=y,e.isSyntheticSource=b;let t=(kM(),d(Gj)).__importDefault(require(`node:os`)),n=(PA(),d(NA)),r=dN(),i=tL(),a=JF(),o=uN(),s=AM(),c=aL();function l(e){return new Date((0,o.hrTimeToNanoseconds)(e)/1e6)}function u(e){let t=(0,i.getInstance)(),r=Object.assign({},t.tags);return e&&e.attributes&&(r[a.KnownContextTagKeys.AiCloudRole]=f(e),r[a.KnownContextTagKeys.AiCloudRoleInstance]=p(e),e.attributes[n.SEMRESATTRS_DEVICE_ID]&&(r[a.KnownContextTagKeys.AiDeviceId]=String(e.attributes[n.SEMRESATTRS_DEVICE_ID])),e.attributes[n.SEMRESATTRS_DEVICE_MODEL_NAME]&&(r[a.KnownContextTagKeys.AiDeviceModel]=String(e.attributes[n.SEMRESATTRS_DEVICE_MODEL_NAME])),e.attributes[n.SEMRESATTRS_SERVICE_VERSION]&&(r[a.KnownContextTagKeys.AiApplicationVer]=String(e.attributes[n.SEMRESATTRS_SERVICE_VERSION]))),r}function f(e){let t=``,r=e.attributes[n.SEMRESATTRS_SERVICE_NAME],i=e.attributes[n.SEMRESATTRS_SERVICE_NAMESPACE];if(r)if(String(r).startsWith(`unknown_service`))t=i?`${i}.${r}`:String(r);else return i?`${i}.${r}`:String(r);let a=e.attributes[n.SEMRESATTRS_K8S_DEPLOYMENT_NAME];if(a)return String(a);let o=e.attributes[n.SEMRESATTRS_K8S_REPLICASET_NAME];if(o)return String(o);let s=e.attributes[n.SEMRESATTRS_K8S_STATEFULSET_NAME];if(s)return String(s);let c=e.attributes[n.SEMRESATTRS_K8S_JOB_NAME];if(c)return String(c);let l=e.attributes[n.SEMRESATTRS_K8S_CRONJOB_NAME];if(l)return String(l);let u=e.attributes[n.SEMRESATTRS_K8S_DAEMONSET_NAME];return u?String(u):t}function p(e){let r=e.attributes[n.SEMRESATTRS_K8S_POD_NAME];if(r)return String(r);let i=e.attributes[n.SEMRESATTRS_SERVICE_INSTANCE_ID];return i?String(i):t.default&&t.default.hostname()}function m(e){return e===n.DBSYSTEMVALUES_DB2||e===n.DBSYSTEMVALUES_DERBY||e===n.DBSYSTEMVALUES_MARIADB||e===n.DBSYSTEMVALUES_MSSQL||e===n.DBSYSTEMVALUES_ORACLE||e===n.DBSYSTEMVALUES_SQLITE||e===n.DBSYSTEMVALUES_OTHER_SQL||e===n.DBSYSTEMVALUES_HSQLDB||e===n.DBSYSTEMVALUES_H2}function h(e){if(!e)return``;if((0,c.getHttpMethod)(e)){let t=(0,c.getHttpUrl)(e);if(t)return String(t);{let t=(0,c.getHttpScheme)(e),n=(0,c.getHttpTarget)(e);if(t&&n){let r=(0,c.getHttpHost)(e);if(r)return`${t}://${r}${n}`;{let r=(0,c.getNetPeerPort)(e);if(r){let i=(0,c.getNetPeerName)(e);if(i)return`${t}://${i}:${r}${n}`;{let i=(0,c.getPeerIp)(e);if(i)return`${t}://${i}:${r}${n}`}}}}}}return``}function g(e){if(!e)return``;let t=e[n.SEMATTRS_PEER_SERVICE],r=(0,c.getHttpHost)(e),i=(0,c.getHttpUrl)(e),a=(0,c.getNetPeerName)(e),o=(0,c.getPeerIp)(e);return t?String(t):r?String(r):i?String(i):a?String(a):o?String(o):``}function _(e,t){if(e&&e.attributes){let r=u(e),i={};for(let t of Object.keys(e.attributes))t.startsWith(`_MS.`)||t===n.ATTR_TELEMETRY_SDK_VERSION||t===n.ATTR_TELEMETRY_SDK_LANGUAGE||t===n.ATTR_TELEMETRY_SDK_NAME||(i[t]=e.attributes[t]);if(Object.keys(i).length>0){let e={version:2,metrics:[{name:`_OTELRESOURCE_`,value:1}],properties:i};return{name:`Microsoft.ApplicationInsights.Metric`,time:new Date,sampleRate:100,instrumentationKey:t,version:1,data:{baseType:`MetricData`,baseData:e},tags:r}}}}function v(e){if(typeof e==`object`)if(e instanceof Error)try{return JSON.stringify(e,Object.getOwnPropertyNames(e))}catch{return String(e)}else if(e instanceof Uint8Array)return String(e);else try{return JSON.stringify(e)}catch{return String(e)}return String(e)}function y(){return process.env[s.ENV_OPENTELEMETRY_RESOURCE_METRIC_DISABLED]?.toLowerCase()!==`true`}function b(e){return!!e[r.experimentalOpenTelemetryValues.SYNTHETIC_TYPE]}})),rL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MessageBusDestination=e.MicrosoftEventHub=e.AzNamespace=void 0,e.AzNamespace=`az.namespace`,e.MicrosoftEventHub=`Microsoft.EventHub`,e.MessageBusDestination=`message_bus.destination`})),iL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.parseEventHubSpan=void 0;let t=(Jd(),d(Kd)),n=uN(),r=(PA(),d(NA)),i=Uj(),a=rL(),o=e=>{let t=0,r=0,a=(0,n.hrTimeToMilliseconds)(e.startTime);return e.links.forEach(({attributes:e})=>{let n=e?.[i.ENQUEUED_TIME];n&&(t+=1,r+=a-(parseFloat(n.toString())||0))}),Math.max(r/(t||1),0)};e.parseEventHubSpan=(e,n)=>{let s=e.attributes[a.AzNamespace],c=(e.attributes[r.SEMATTRS_NET_PEER_NAME]||e.attributes[`peer.address`]||`unknown`).replace(/\/$/g,``),l=e.attributes[a.MessageBusDestination]||`unknown`;switch(e.kind){case t.SpanKind.CLIENT:n.type=s,n.target=`${c}/${l}`;break;case t.SpanKind.PRODUCER:n.type=`Queue Message | ${s}`,n.target=`${c}/${l}`;break;case t.SpanKind.CONSUMER:n.type=`Queue Message | ${s}`,n.source=`${c}/${l}`,n.measurements=Object.assign(Object.assign({},n.measurements),{[i.TIME_SINCE_ENQUEUED]:o(e)});break;default:}}})),aL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.readableSpanToEnvelope=_,e.spanEventsToEnvelopes=v,e.getPeerIp=y,e.getLocationIp=b,e.getHttpClientIp=x,e.getUserAgent=S,e.getHttpUrl=C,e.getHttpMethod=w,e.getHttpStatusCode=T,e.getHttpScheme=E,e.getHttpTarget=D,e.getHttpHost=O,e.getNetPeerName=k,e.getNetPeerPort=A;let t=uN(),n=(Jd(),d(Kd)),r=(PA(),d(NA)),i=nL(),a=dN(),o=iL(),s=Uj(),c=rL(),l=JF(),u=YI();function f(e){let t=(0,i.createTagsFromResource)(e.resource);t[l.KnownContextTagKeys.AiOperationId]=e.spanContext().traceId,e.parentSpanContext?.spanId&&(t[l.KnownContextTagKeys.AiOperationParentId]=e.parentSpanContext.spanId);let o=e.attributes[r.SEMATTRS_ENDUSER_ID];o&&(t[l.KnownContextTagKeys.AiUserId]=String(o));let s=S(e.attributes);if(s&&(t[`ai.user.userAgent`]=String(s)),(0,i.isSyntheticSource)(e.attributes)&&(t[l.KnownContextTagKeys.AiOperationSyntheticSource]=`True`),e.kind===n.SpanKind.SERVER){let n=w(e.attributes);if(b(t,e.attributes),n){let i=e.attributes[r.ATTR_HTTP_ROUTE],o=C(e.attributes);if(t[l.KnownContextTagKeys.AiOperationName]=e.name,i)t[l.KnownContextTagKeys.AiOperationName]=String(`${n} ${i}`).substring(0,a.MaxPropertyLengths.TEN_BIT);else if(o)try{let e=new URL(String(o));t[l.KnownContextTagKeys.AiOperationName]=String(`${n} ${e.pathname}`).substring(0,a.MaxPropertyLengths.TEN_BIT)}catch{}}else t[l.KnownContextTagKeys.AiOperationName]=e.name}else e.attributes[l.KnownContextTagKeys.AiOperationName]&&(t[l.KnownContextTagKeys.AiOperationName]=e.attributes[l.KnownContextTagKeys.AiOperationName]);return t}function p(e){let t={};if(e)for(let n of Object.keys(e))n.startsWith(`_MS.`)&&!a.internalMicrosoftAttributes.includes(n)||n.startsWith(`microsoft.`)||a.legacySemanticValues.includes(n)||a.httpSemanticValues.includes(n)||n===l.KnownContextTagKeys.AiOperationName||(t[n]=(0,i.serializeAttribute)(e[n]));return t}function m(e){let t=p(e.attributes),n={},r=e.links.map(e=>({operation_Id:e.context.traceId,id:e.context.spanId}));return r.length>0&&(t[s.MS_LINKS]=JSON.stringify(r)),[t,n]}function h(e){let a={name:e.name,id:`${e.spanContext().spanId}`,success:e.status?.code!==n.SpanStatusCode.ERROR,resultCode:`0`,type:`Dependency`,duration:(0,u.msToTimeSpan)((0,t.hrTimeToMilliseconds)(e.duration)),version:2};e.kind===n.SpanKind.PRODUCER&&(a.type=s.DependencyTypes.QueueMessage),e.kind===n.SpanKind.INTERNAL&&e.parentSpanContext&&(a.type=s.DependencyTypes.InProc);let o=w(e.attributes),c=e.attributes[r.SEMATTRS_DB_SYSTEM],l=e.attributes[r.SEMATTRS_RPC_SYSTEM];if(o){let t=C(e.attributes);if(t)try{a.name=`${o} ${new URL(String(t)).pathname}`}catch{}a.type=s.DependencyTypes.Http,a.data=(0,i.getUrl)(e.attributes);let n=T(e.attributes);n&&(a.resultCode=String(n));let r=(0,i.getDependencyTarget)(e.attributes);if(r){try{let e=new RegExp(/(https?)(:\/\/.*)(:\d+)(\S*)/).exec(r);if(e!==null){let t=e[1],n=e[3];(t===`https`&&n===`:443`||t===`http`&&n===`:80`)&&(r=e[1]+e[2]+e[4])}}catch{}a.target=`${r}`}}else if(c){String(c)===r.DBSYSTEMVALUES_MYSQL?a.type=`mysql`:String(c)===r.DBSYSTEMVALUES_POSTGRESQL?a.type=`postgresql`:String(c)===r.DBSYSTEMVALUES_MONGODB?a.type=`mongodb`:String(c)===r.DBSYSTEMVALUES_REDIS?a.type=`redis`:(0,i.isSqlDB)(String(c))?a.type=`SQL`:a.type=String(c);let t=e.attributes[r.SEMATTRS_DB_STATEMENT],n=e.attributes[r.SEMATTRS_DB_OPERATION];t?a.data=String(t):n&&(a.data=String(n));let o=(0,i.getDependencyTarget)(e.attributes),s=e.attributes[r.SEMATTRS_DB_NAME];o?a.target=s?`${o}|${s}`:`${o}`:a.target=s?`${s}`:`${c}`}else if(l){l===s.DependencyTypes.Wcf?a.type=s.DependencyTypes.Wcf:a.type=s.DependencyTypes.Grpc;let t=e.attributes[r.SEMATTRS_RPC_GRPC_STATUS_CODE];t&&(a.resultCode=String(t));let n=(0,i.getDependencyTarget)(e.attributes);n?a.target=`${n}`:l&&(a.target=String(l))}return a}function g(e){let a={id:`${e.spanContext().spanId}`,success:e.status.code!==n.SpanStatusCode.ERROR&&(Number(T(e.attributes))||0)<400,responseCode:`0`,duration:(0,u.msToTimeSpan)((0,t.hrTimeToMilliseconds)(e.duration)),version:2,source:void 0},o=w(e.attributes),s=e.attributes[r.SEMATTRS_RPC_GRPC_STATUS_CODE];if(o){a.url=(0,i.getUrl)(e.attributes);let t=T(e.attributes);t&&(a.responseCode=String(t))}else s&&(a.responseCode=String(s));return a}function _(e,t){let r,u,d,p=(0,i.hrTimeToDate)(e.startTime),_=t,v=f(e),[y,b]=m(e);switch(e.kind){case n.SpanKind.CLIENT:case n.SpanKind.PRODUCER:case n.SpanKind.INTERNAL:r=`Microsoft.ApplicationInsights.RemoteDependency`,u=`RemoteDependencyData`,d=h(e);break;case n.SpanKind.SERVER:case n.SpanKind.CONSUMER:r=`Microsoft.ApplicationInsights.Request`,u=`RequestData`,d=g(e),d.name=v[l.KnownContextTagKeys.AiOperationName];break;default:throw n.diag.error(`Unsupported span kind ${e.kind}`),Error(`Unsupported span kind ${e.kind}`)}let x=100;if(e.attributes[s.AzureMonitorSampleRate]&&(x=Number(e.attributes[s.AzureMonitorSampleRate])),e.attributes[c.AzNamespace]&&(e.kind===n.SpanKind.INTERNAL&&(d.type=`${s.DependencyTypes.InProc} | ${e.attributes[c.AzNamespace]}`),e.attributes[c.AzNamespace]===c.MicrosoftEventHub&&(0,o.parseEventHubSpan)(e,d)),d.id&&=d.id.substring(0,a.MaxPropertyLengths.NINE_BIT),d.name&&=d.name.substring(0,a.MaxPropertyLengths.TEN_BIT),d.resultCode&&=String(d.resultCode).substring(0,a.MaxPropertyLengths.TEN_BIT),d.data&&=String(d.data).substring(0,a.MaxPropertyLengths.THIRTEEN_BIT),d.type&&=String(d.type).substring(0,a.MaxPropertyLengths.TEN_BIT),d.target&&=String(d.target).substring(0,a.MaxPropertyLengths.TEN_BIT),d.properties)for(let e of Object.keys(d.properties))d.properties[e]=d.properties[e].substring(0,a.MaxPropertyLengths.THIRTEEN_BIT);return{name:r,sampleRate:x,time:p,instrumentationKey:_,tags:v,version:1,data:{baseType:u,baseData:Object.assign(Object.assign({},d),{properties:y,measurements:b})}}}function v(e,t){let n=[];return e.events&&e.events.forEach(o=>{let c,u=(0,i.hrTimeToDate)(o.time),d=``,f,m=p(o.attributes),h=(0,i.createTagsFromResource)(e.resource);h[l.KnownContextTagKeys.AiOperationId]=e.spanContext().traceId;let g=e.spanContext().spanId;if(g&&(h[l.KnownContextTagKeys.AiOperationParentId]=g),o.name===`exception`){d=`Microsoft.ApplicationInsights.Exception`,c=`ExceptionData`;let e=``,t=`Exception`,n=``,i=!1;if(o.attributes){e=String(o.attributes[r.SEMATTRS_EXCEPTION_TYPE]),n=String(o.attributes[r.SEMATTRS_EXCEPTION_STACKTRACE]),n&&(i=!0);let a=o.attributes[r.SEMATTRS_EXCEPTION_MESSAGE];a&&(t=String(a));let s=o.attributes[r.SEMATTRS_EXCEPTION_ESCAPED];s!==void 0&&(m[r.SEMATTRS_EXCEPTION_ESCAPED]=String(s))}f={exceptions:[{typeName:e,message:t,stack:n,hasFullStack:i}],version:2,properties:m}}else d=`Microsoft.ApplicationInsights.Message`,c=`MessageData`,f={message:o.name,version:2,properties:m};let _=100;if(e.attributes[s.AzureMonitorSampleRate]&&(_=Number(e.attributes[s.AzureMonitorSampleRate])),f.message&&=String(f.message).substring(0,a.MaxPropertyLengths.FIFTEEN_BIT),f.properties)for(let e of Object.keys(f.properties))f.properties[e]=f.properties[e].substring(0,a.MaxPropertyLengths.THIRTEEN_BIT);let v={name:d,time:u,instrumentationKey:t,version:1,sampleRate:_,data:{baseType:c,baseData:f},tags:h};n.push(v)}),n}function y(e){if(e)return e[r.ATTR_NETWORK_PEER_ADDRESS]||e[r.SEMATTRS_NET_PEER_IP]}function b(e,t){if(t){let n=x(t),r=y(t);n?e[l.KnownContextTagKeys.AiLocationIp]=String(n):r&&(e[l.KnownContextTagKeys.AiLocationIp]=String(r))}}function x(e){if(e)return e[r.ATTR_CLIENT_ADDRESS]||e[r.SEMATTRS_HTTP_CLIENT_IP]}function S(e){if(e)return e[r.ATTR_USER_AGENT_ORIGINAL]||e[r.SEMATTRS_HTTP_USER_AGENT]}function C(e){if(e)return e[r.ATTR_URL_FULL]||e[r.SEMATTRS_HTTP_URL]}function w(e){if(e)return e[r.ATTR_HTTP_REQUEST_METHOD]||e[r.SEMATTRS_HTTP_METHOD]}function T(e){if(e)return e[r.ATTR_HTTP_RESPONSE_STATUS_CODE]||e[r.SEMATTRS_HTTP_STATUS_CODE]}function E(e){if(e)return e[r.ATTR_URL_SCHEME]||e[r.SEMATTRS_HTTP_SCHEME]}function D(e){if(e)return e[r.ATTR_URL_PATH]?e[r.ATTR_URL_PATH]:e[r.ATTR_URL_QUERY]?e[r.ATTR_URL_QUERY]:e[r.SEMATTRS_HTTP_TARGET]}function O(e){if(e)return e[r.ATTR_SERVER_ADDRESS]||e[r.SEMATTRS_HTTP_HOST]}function k(e){if(e)return e[r.ATTR_CLIENT_ADDRESS]||e[r.SEMATTRS_NET_PEER_NAME]}function A(e){if(e)return e[r.ATTR_CLIENT_PORT]||e[r.ATTR_SERVER_PORT]||e[r.SEMATTRS_NET_PEER_PORT]}})),oL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AzureMonitorTraceExporter=void 0;let t=(Jd(),d(Kd)),n=uN(),r=MM(),i=aL(),a=nL(),o=tL();e.AzureMonitorTraceExporter=class extends r.AzureMonitorBaseExporter{constructor(e={}){super(e),this.isShutdown=!1,this.shouldCreateResourceMetric=(0,a.shouldCreateResourceMetric)(),this.sender=new o.HttpSender({endpointUrl:this.endpointUrl,instrumentationKey:this.instrumentationKey,trackStatsbeat:this.trackStatsbeat,exporterOptions:e,aadAudience:this.aadAudience}),t.diag.debug(`AzureMonitorTraceExporter was successfully setup`)}async export(e,r){if(this.isShutdown){t.diag.info(`Exporter shut down. Failed to export spans.`),setTimeout(()=>r({code:n.ExportResultCode.FAILED}),0);return}if(t.diag.info(`Exporting ${e.length} span(s). Converting to envelopes...`),e.length>0){let t=[],n=(0,a.createResourceMetricEnvelope)(e[0].resource,this.instrumentationKey);n&&this.shouldCreateResourceMetric&&t.push(n),e.forEach(e=>{t.push((0,i.readableSpanToEnvelope)(e,this.instrumentationKey));let n=(0,i.spanEventsToEnvelopes)(e,this.instrumentationKey);n.length>0&&t.push(...n)}),r(await this.sender.exportEnvelopes(t))}r({code:n.ExportResultCode.SUCCESS})}async shutdown(){return this.isShutdown=!0,t.diag.info(`AzureMonitorTraceExporter shutting down`),this.sender.shutdown()}}})),sL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AzureMonitorMetricExporter=void 0;let t=(Jd(),d(Kd)),n=HI(),r=uN(),i=MM(),a=GI(),o=tL();e.AzureMonitorMetricExporter=class extends i.AzureMonitorBaseExporter{constructor(e={}){super(e),this._isShutdown=!1,this._sender=new o.HttpSender({endpointUrl:this.endpointUrl,instrumentationKey:this.instrumentationKey,trackStatsbeat:this.trackStatsbeat,exporterOptions:e,aadAudience:this.aadAudience}),t.diag.debug(`AzureMonitorMetricExporter was successfully setup`)}async export(e,n){if(this._isShutdown){t.diag.info(`Exporter shut down. Failed to export spans.`),setTimeout(()=>n({code:r.ExportResultCode.FAILED}),0);return}t.diag.info(`Exporting ${e.scopeMetrics.length} metrics(s). Converting to envelopes...`);let i=(0,a.resourceMetricsToEnvelope)(e,this.instrumentationKey);await t.context.with((0,r.suppressTracing)(t.context.active()),async()=>{n(await this._sender.exportEnvelopes(i))})}async shutdown(){return this._isShutdown=!0,t.diag.info(`AzureMonitorMetricExporter shutting down`),this._sender.shutdown()}selectAggregationTemporality(e){return e===n.InstrumentType.UP_DOWN_COUNTER||e===n.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER?n.AggregationTemporality.CUMULATIVE:n.AggregationTemporality.DELTA}async forceFlush(){return Promise.resolve()}}})),cL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.logToEnvelope=c;let t=JF(),n=nL(),r=(PA(),d(NA)),i=dN(),a=(Jd(),d(Kd)),o=Uj(),s=aL();function c(e,t){let a=(0,n.hrTimeToDate)(e.hrTime),s=t,c=l(e),[d,g]=u(e),_,v,y,b=e.attributes[r.ATTR_EXCEPTION_STACKTRACE],x=e.attributes[r.ATTR_EXCEPTION_TYPE],S=!!(x&&b)||!1,C=!e.attributes[o.ApplicationInsightsBaseType]&&!e.attributes[o.ApplicationInsightsCustomEventName]&&!x;if(S){let t=e.attributes[r.ATTR_EXCEPTION_MESSAGE];_=o.ApplicationInsightsExceptionName,v=o.ApplicationInsightsExceptionBaseType,y={exceptions:[{typeName:String(x),message:String(t),hasFullStack:!!b,stack:String(b)}],severityLevel:String(f(e.severityNumber)),version:2}}else if(e.attributes[o.ApplicationInsightsCustomEventName])_=o.ApplicationInsightsEventName,v=o.ApplicationInsightsEventBaseType,y={name:String(e.attributes[o.ApplicationInsightsCustomEventName]),version:2},g=m(e);else if(C)_=o.ApplicationInsightsMessageName,v=o.ApplicationInsightsMessageBaseType,y={message:String(e.body),severityLevel:String(f(e.severityNumber)),version:2};else if(v=String(e.attributes[o.ApplicationInsightsBaseType]),_=p(e),y=h(e),g=m(e),!y)return;if(y.message&&=String(y.message).substring(0,i.MaxPropertyLengths.FIFTEEN_BIT),d)for(let e of Object.keys(d))d[e]=String(d[e]).substring(0,i.MaxPropertyLengths.THIRTEEN_BIT);return{name:_,sampleRate:100,time:a,instrumentationKey:s,tags:c,version:1,data:{baseType:v,baseData:Object.assign(Object.assign({},y),{properties:d,measurements:g})}}}function l(e){let r=(0,n.createTagsFromResource)(e.resource);return e.spanContext?.traceId&&(r[t.KnownContextTagKeys.AiOperationId]=e.spanContext.traceId),e.spanContext?.spanId&&(r[t.KnownContextTagKeys.AiOperationParentId]=e.spanContext.spanId),e.attributes[t.KnownContextTagKeys.AiOperationName]&&(r[t.KnownContextTagKeys.AiOperationName]=e.attributes[t.KnownContextTagKeys.AiOperationName]),(0,n.isSyntheticSource)(e.attributes)&&(r[t.KnownContextTagKeys.AiOperationSyntheticSource]=`True`),(0,s.getLocationIp)(r,e.attributes),r}function u(e){let r={},a={};if(e.attributes)for(let r of Object.keys(e.attributes))r.startsWith(`_MS.`)||r.startsWith(`microsoft`)||i.legacySemanticValues.includes(r)||i.httpSemanticValues.includes(r)||r===t.KnownContextTagKeys.AiOperationName||(a[r]=(0,n.serializeAttribute)(e.attributes[r]));return[a,r]}function f(e){if(e){if(e>0&&e<9)return t.KnownSeverityLevel.Verbose;if(e>=9&&e<13)return t.KnownSeverityLevel.Information;if(e>=13&&e<17)return t.KnownSeverityLevel.Warning;if(e>=17&&e<21)return t.KnownSeverityLevel.Error;if(e>=21&&e<25)return t.KnownSeverityLevel.Critical}}function p(e){let t=``;switch(e.attributes[o.ApplicationInsightsBaseType]){case o.ApplicationInsightsAvailabilityBaseType:t=o.ApplicationInsightsAvailabilityName;break;case o.ApplicationInsightsExceptionBaseType:t=o.ApplicationInsightsExceptionName;break;case o.ApplicationInsightsMessageBaseType:t=o.ApplicationInsightsMessageName;break;case o.ApplicationInsightsPageViewBaseType:t=o.ApplicationInsightsPageViewName;break;case o.ApplicationInsightsEventBaseType:t=o.ApplicationInsightsEventName;break}return t}function m(e){let t={};return e.body?.measurements&&(t=Object.assign({},e.body.measurements)),t}function h(e){let t={version:2};if(e.body)try{switch(e.attributes[o.ApplicationInsightsBaseType]){case o.ApplicationInsightsAvailabilityBaseType:t=e.body;break;case o.ApplicationInsightsExceptionBaseType:t=e.body;break;case o.ApplicationInsightsMessageBaseType:t=e.body;break;case o.ApplicationInsightsPageViewBaseType:t=e.body;break;case o.ApplicationInsightsEventBaseType:t=e.body;break}typeof t?.message==`object`&&(t.message=JSON.stringify(t.message))}catch{a.diag.error(`AzureMonitorLogExporter failed to parse Application Insights Telemetry`)}return t}})),lL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AzureMonitorLogExporter=void 0;let t=(Jd(),d(Kd)),n=uN(),r=MM(),i=cL(),a=tL();e.AzureMonitorLogExporter=class extends r.AzureMonitorBaseExporter{constructor(e={}){super(e),this._isShutdown=!1,this._sender=new a.HttpSender({endpointUrl:this.endpointUrl,instrumentationKey:this.instrumentationKey,trackStatsbeat:this.trackStatsbeat,exporterOptions:e,aadAudience:this.aadAudience}),t.diag.debug(`AzureMonitorLogExporter was successfully setup`)}async export(e,r){if(this._isShutdown){t.diag.info(`Exporter shut down. Failed to export spans.`),setTimeout(()=>r({code:n.ExportResultCode.FAILED}),0);return}t.diag.info(`Exporting ${e.length} logs(s). Converting to envelopes...`);let a=[];e.forEach(e=>{let t=(0,i.logToEnvelope)(e,this.instrumentationKey);t&&a.push(t)}),await t.context.with((0,n.suppressTracing)(t.context.active()),async()=>{r(await this._sender.exportEnvelopes(a))})}async shutdown(){return this._isShutdown=!0,t.diag.info(`AzureMonitorLogExporter shutting down`),this._sender.shutdown()}}})),uL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AI_OPERATION_NAME=e.ServiceApiVersion=e.AzureMonitorLogExporter=e.AzureMonitorMetricExporter=e.AzureMonitorTraceExporter=e.AzureMonitorBaseExporter=e.ApplicationInsightsSampler=void 0;var t=Wj();Object.defineProperty(e,`ApplicationInsightsSampler`,{enumerable:!0,get:function(){return t.ApplicationInsightsSampler}});var n=MM();Object.defineProperty(e,`AzureMonitorBaseExporter`,{enumerable:!0,get:function(){return n.AzureMonitorBaseExporter}});var r=oL();Object.defineProperty(e,`AzureMonitorTraceExporter`,{enumerable:!0,get:function(){return r.AzureMonitorTraceExporter}});var i=sL();Object.defineProperty(e,`AzureMonitorMetricExporter`,{enumerable:!0,get:function(){return i.AzureMonitorMetricExporter}});var a=lL();Object.defineProperty(e,`AzureMonitorLogExporter`,{enumerable:!0,get:function(){return a.AzureMonitorLogExporter}});var o=AM();Object.defineProperty(e,`ServiceApiVersion`,{enumerable:!0,get:function(){return o.ServiceApiVersion}});var s=AM();Object.defineProperty(e,`AI_OPERATION_NAME`,{enumerable:!0,get:function(){return s.AI_OPERATION_NAME}})})),dL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.isTracingSuppressed=e.unsuppressTracing=e.suppressTracing=void 0;let t=(0,(Jd(),d(Kd)).createContextKey)(`OpenTelemetry SDK Context Key SUPPRESS_TRACING`);function n(e){return e.setValue(t,!0)}e.suppressTracing=n;function r(e){return e.deleteValue(t)}e.unsuppressTracing=r;function i(e){return e.getValue(t)===!0}e.isTracingSuppressed=i})),fL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BAGGAGE_MAX_TOTAL_LENGTH=e.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS=e.BAGGAGE_MAX_NAME_VALUE_PAIRS=e.BAGGAGE_HEADER=e.BAGGAGE_ITEMS_SEPARATOR=e.BAGGAGE_PROPERTIES_SEPARATOR=e.BAGGAGE_KEY_PAIR_SEPARATOR=void 0,e.BAGGAGE_KEY_PAIR_SEPARATOR=`=`,e.BAGGAGE_PROPERTIES_SEPARATOR=`;`,e.BAGGAGE_ITEMS_SEPARATOR=`,`,e.BAGGAGE_HEADER=`baggage`,e.BAGGAGE_MAX_NAME_VALUE_PAIRS=180,e.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS=4096,e.BAGGAGE_MAX_TOTAL_LENGTH=8192})),pL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.parseKeyPairsIntoRecord=e.parsePairKeyValue=e.getKeyPairs=e.serializeKeyPairs=void 0;let t=(Jd(),d(Kd)),n=fL();function r(e){return e.reduce((e,t)=>{let r=`${e}${e===``?``:n.BAGGAGE_ITEMS_SEPARATOR}${t}`;return r.length>n.BAGGAGE_MAX_TOTAL_LENGTH?e:r},``)}e.serializeKeyPairs=r;function i(e){return e.getAllEntries().map(([e,t])=>{let r=`${encodeURIComponent(e)}=${encodeURIComponent(t.value)}`;return t.metadata!==void 0&&(r+=n.BAGGAGE_PROPERTIES_SEPARATOR+t.metadata.toString()),r})}e.getKeyPairs=i;function a(e){let r=e.split(n.BAGGAGE_PROPERTIES_SEPARATOR);if(r.length<=0)return;let i=r.shift();if(!i)return;let a=i.indexOf(n.BAGGAGE_KEY_PAIR_SEPARATOR);if(a<=0)return;let o=decodeURIComponent(i.substring(0,a).trim()),s=decodeURIComponent(i.substring(a+1).trim()),c;return r.length>0&&(c=(0,t.baggageEntryMetadataFromString)(r.join(n.BAGGAGE_PROPERTIES_SEPARATOR))),{key:o,value:s,metadata:c}}e.parsePairKeyValue=a;function o(e){let t={};return typeof e==`string`&&e.length>0&&e.split(n.BAGGAGE_ITEMS_SEPARATOR).forEach(e=>{let n=a(e);n!==void 0&&n.value.length>0&&(t[n.key]=n.value)}),t}e.parseKeyPairsIntoRecord=o})),mL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.W3CBaggagePropagator=void 0;let t=(Jd(),d(Kd)),n=dL(),r=fL(),i=pL();e.W3CBaggagePropagator=class{inject(e,a,o){let s=t.propagation.getBaggage(e);if(!s||(0,n.isTracingSuppressed)(e))return;let c=(0,i.getKeyPairs)(s).filter(e=>e.length<=r.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS).slice(0,r.BAGGAGE_MAX_NAME_VALUE_PAIRS),l=(0,i.serializeKeyPairs)(c);l.length>0&&o.set(a,r.BAGGAGE_HEADER,l)}extract(e,n,a){let o=a.get(n,r.BAGGAGE_HEADER),s=Array.isArray(o)?o.join(r.BAGGAGE_ITEMS_SEPARATOR):o;if(!s)return e;let c={};return s.length===0||(s.split(r.BAGGAGE_ITEMS_SEPARATOR).forEach(e=>{let t=(0,i.parsePairKeyValue)(e);if(t){let e={value:t.value};t.metadata&&(e.metadata=t.metadata),c[t.key]=e}}),Object.entries(c).length===0)?e:t.propagation.setBaggage(e,t.propagation.createBaggage(c))}fields(){return[r.BAGGAGE_HEADER]}}})),hL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AnchoredClock=void 0,e.AnchoredClock=class{_monotonicClock;_epochMillis;_performanceMillis;constructor(e,t){this._monotonicClock=t,this._epochMillis=e.now(),this._performanceMillis=t.now()}now(){let e=this._monotonicClock.now()-this._performanceMillis;return this._epochMillis+e}}})),gL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.isAttributeValue=e.isAttributeKey=e.sanitizeAttributes=void 0;let t=(Jd(),d(Kd));function n(e){let n={};if(typeof e!=`object`||!e)return n;for(let[a,o]of Object.entries(e)){if(!r(a)){t.diag.warn(`Invalid attribute key: ${a}`);continue}if(!i(o)){t.diag.warn(`Invalid attribute value set for key: ${a}`);continue}Array.isArray(o)?n[a]=o.slice():n[a]=o}return n}e.sanitizeAttributes=n;function r(e){return typeof e==`string`&&e.length>0}e.isAttributeKey=r;function i(e){return e==null?!0:Array.isArray(e)?a(e):o(e)}e.isAttributeValue=i;function a(e){let t;for(let n of e)if(n!=null){if(!t){if(o(n)){t=typeof n;continue}return!1}if(typeof n!==t)return!1}return!0}function o(e){switch(typeof e){case`number`:case`boolean`:case`string`:return!0}return!1}})),_L=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.loggingErrorHandler=void 0;let t=(Jd(),d(Kd));function n(){return e=>{t.diag.error(r(e))}}e.loggingErrorHandler=n;function r(e){return typeof e==`string`?e:JSON.stringify(i(e))}function i(e){let t={},n=e;for(;n!==null;)Object.getOwnPropertyNames(n).forEach(e=>{if(t[e])return;let r=n[e];r&&(t[e]=String(r))}),n=Object.getPrototypeOf(n);return t}})),vL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.globalErrorHandler=e.setGlobalErrorHandler=void 0;let t=(0,_L().loggingErrorHandler)();function n(e){t=e}e.setGlobalErrorHandler=n;function r(e){try{t(e)}catch{}}e.globalErrorHandler=r})),oee=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getStringListFromEnv=e.getBooleanFromEnv=e.getStringFromEnv=e.getNumberFromEnv=void 0;let t=(Jd(),d(Kd)),n=require(`util`);function r(e){let r=process.env[e];if(r==null||r.trim()===``)return;let i=Number(r);if(isNaN(i)){t.diag.warn(`Unknown value ${(0,n.inspect)(r)} for ${e}, expected a number, using defaults`);return}return i}e.getNumberFromEnv=r;function i(e){let t=process.env[e];if(!(t==null||t.trim()===``))return t}e.getStringFromEnv=i;function a(e){let r=process.env[e]?.trim().toLowerCase();return r==null||r===``?!1:r===`true`?!0:(r===`false`||t.diag.warn(`Unknown value ${(0,n.inspect)(r)} for ${e}, expected 'true' or 'false', falling back to 'false' (default)`),!1)}e.getBooleanFromEnv=a;function o(e){return i(e)?.split(`,`).map(e=>e.trim()).filter(e=>e!==``)}e.getStringListFromEnv=o})),yL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e._globalThis=void 0,e._globalThis=typeof globalThis==`object`?globalThis:global})),bL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.otperformance=void 0,e.otperformance=require(`perf_hooks`).performance})),xL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.VERSION=void 0,e.VERSION=`2.1.0`})),SL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ATTR_PROCESS_RUNTIME_NAME=void 0,e.ATTR_PROCESS_RUNTIME_NAME=`process.runtime.name`})),CL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.SDK_INFO=void 0;let t=xL(),n=(PA(),d(NA)),r=SL();e.SDK_INFO={[n.ATTR_TELEMETRY_SDK_NAME]:`opentelemetry`,[r.ATTR_PROCESS_RUNTIME_NAME]:`node`,[n.ATTR_TELEMETRY_SDK_LANGUAGE]:n.TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS,[n.ATTR_TELEMETRY_SDK_VERSION]:t.VERSION}})),wL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.unrefTimer=void 0;function t(e){e.unref()}e.unrefTimer=t})),TL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.unrefTimer=e.SDK_INFO=e.otperformance=e._globalThis=e.getStringListFromEnv=e.getNumberFromEnv=e.getBooleanFromEnv=e.getStringFromEnv=void 0;var t=oee();Object.defineProperty(e,`getStringFromEnv`,{enumerable:!0,get:function(){return t.getStringFromEnv}}),Object.defineProperty(e,`getBooleanFromEnv`,{enumerable:!0,get:function(){return t.getBooleanFromEnv}}),Object.defineProperty(e,`getNumberFromEnv`,{enumerable:!0,get:function(){return t.getNumberFromEnv}}),Object.defineProperty(e,`getStringListFromEnv`,{enumerable:!0,get:function(){return t.getStringListFromEnv}});var n=yL();Object.defineProperty(e,`_globalThis`,{enumerable:!0,get:function(){return n._globalThis}});var r=bL();Object.defineProperty(e,`otperformance`,{enumerable:!0,get:function(){return r.otperformance}});var i=CL();Object.defineProperty(e,`SDK_INFO`,{enumerable:!0,get:function(){return i.SDK_INFO}});var a=wL();Object.defineProperty(e,`unrefTimer`,{enumerable:!0,get:function(){return a.unrefTimer}})})),EL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getStringListFromEnv=e.getNumberFromEnv=e.getStringFromEnv=e.getBooleanFromEnv=e.unrefTimer=e.otperformance=e._globalThis=e.SDK_INFO=void 0;var t=TL();Object.defineProperty(e,`SDK_INFO`,{enumerable:!0,get:function(){return t.SDK_INFO}}),Object.defineProperty(e,`_globalThis`,{enumerable:!0,get:function(){return t._globalThis}}),Object.defineProperty(e,`otperformance`,{enumerable:!0,get:function(){return t.otperformance}}),Object.defineProperty(e,`unrefTimer`,{enumerable:!0,get:function(){return t.unrefTimer}}),Object.defineProperty(e,`getBooleanFromEnv`,{enumerable:!0,get:function(){return t.getBooleanFromEnv}}),Object.defineProperty(e,`getStringFromEnv`,{enumerable:!0,get:function(){return t.getStringFromEnv}}),Object.defineProperty(e,`getNumberFromEnv`,{enumerable:!0,get:function(){return t.getNumberFromEnv}}),Object.defineProperty(e,`getStringListFromEnv`,{enumerable:!0,get:function(){return t.getStringListFromEnv}})})),DL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.addHrTimes=e.isTimeInput=e.isTimeInputHrTime=e.hrTimeToMicroseconds=e.hrTimeToMilliseconds=e.hrTimeToNanoseconds=e.hrTimeToTimeStamp=e.hrTimeDuration=e.timeInputToHrTime=e.hrTime=e.getTimeOrigin=e.millisToHrTime=void 0;let t=EL(),n=10**6,r=10**9;function i(e){let t=e/1e3;return[Math.trunc(t),Math.round(e%1e3*n)]}e.millisToHrTime=i;function a(){let e=t.otperformance.timeOrigin;if(typeof e!=`number`){let n=t.otperformance;e=n.timing&&n.timing.fetchStart}return e}e.getTimeOrigin=a;function o(e){return h(i(a()),i(typeof e==`number`?e:t.otperformance.now()))}e.hrTime=o;function s(e){if(p(e))return e;if(typeof e==`number`)return e<a()?o(e):i(e);if(e instanceof Date)return i(e.getTime());throw TypeError(`Invalid input type`)}e.timeInputToHrTime=s;function c(e,t){let n=t[0]-e[0],i=t[1]-e[1];return i<0&&(--n,i+=r),[n,i]}e.hrTimeDuration=c;function l(e){let t=`${`0`.repeat(9)}${e[1]}Z`,n=t.substring(t.length-9-1);return new Date(e[0]*1e3).toISOString().replace(`000Z`,n)}e.hrTimeToTimeStamp=l;function u(e){return e[0]*r+e[1]}e.hrTimeToNanoseconds=u;function d(e){return e[0]*1e3+e[1]/1e6}e.hrTimeToMilliseconds=d;function f(e){return e[0]*1e6+e[1]/1e3}e.hrTimeToMicroseconds=f;function p(e){return Array.isArray(e)&&e.length===2&&typeof e[0]==`number`&&typeof e[1]==`number`}e.isTimeInputHrTime=p;function m(e){return p(e)||typeof e==`number`||e instanceof Date}e.isTimeInput=m;function h(e,t){let n=[e[0]+t[0],e[1]+t[1]];return n[1]>=r&&(n[1]-=r,n[0]+=1),n}e.addHrTimes=h})),OL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ExportResultCode=void 0,(function(e){e[e.SUCCESS=0]=`SUCCESS`,e[e.FAILED=1]=`FAILED`})(e.ExportResultCode||={})})),kL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.CompositePropagator=void 0;let t=(Jd(),d(Kd));e.CompositePropagator=class{_propagators;_fields;constructor(e={}){this._propagators=e.propagators??[],this._fields=Array.from(new Set(this._propagators.map(e=>typeof e.fields==`function`?e.fields():[]).reduce((e,t)=>e.concat(t),[])))}inject(e,n,r){for(let i of this._propagators)try{i.inject(e,n,r)}catch(e){t.diag.warn(`Failed to inject with ${i.constructor.name}. Err: ${e.message}`)}}extract(e,n,r){return this._propagators.reduce((e,i)=>{try{return i.extract(e,n,r)}catch(e){t.diag.warn(`Failed to extract with ${i.constructor.name}. Err: ${e.message}`)}return e},e)}fields(){return this._fields.slice()}}})),AL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.validateValue=e.validateKey=void 0;let t=`[_0-9a-z-*/]`,n=`[a-z]${t}{0,255}`,r=`[a-z0-9]${t}{0,240}@[a-z]${t}{0,13}`,i=RegExp(`^(?:${n}|${r})$`),a=/^[ -~]{0,255}[!-~]$/,o=/,|=/;function s(e){return i.test(e)}e.validateKey=s;function c(e){return a.test(e)&&!o.test(e)}e.validateValue=c})),jL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.TraceState=void 0;let t=AL();e.TraceState=class e{_internalState=new Map;constructor(e){e&&this._parse(e)}set(e,t){let n=this._clone();return n._internalState.has(e)&&n._internalState.delete(e),n._internalState.set(e,t),n}unset(e){let t=this._clone();return t._internalState.delete(e),t}get(e){return this._internalState.get(e)}serialize(){return this._keys().reduce((e,t)=>(e.push(t+`=`+this.get(t)),e),[]).join(`,`)}_parse(e){e.length>512||(this._internalState=e.split(`,`).reverse().reduce((e,n)=>{let r=n.trim(),i=r.indexOf(`=`);if(i!==-1){let a=r.slice(0,i),o=r.slice(i+1,n.length);(0,t.validateKey)(a)&&(0,t.validateValue)(o)&&e.set(a,o)}return e},new Map),this._internalState.size>32&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,32))))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){let t=new e;return t._internalState=new Map(this._internalState),t}}})),ML=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.W3CTraceContextPropagator=e.parseTraceParent=e.TRACE_STATE_HEADER=e.TRACE_PARENT_HEADER=void 0;let t=(Jd(),d(Kd)),n=dL(),r=jL();e.TRACE_PARENT_HEADER=`traceparent`,e.TRACE_STATE_HEADER=`tracestate`;let i=RegExp(`^\\s?((?!ff)[\\da-f]{2})-((?![0]{32})[\\da-f]{32})-((?![0]{16})[\\da-f]{16})-([\\da-f]{2})(-.*)?\\s?$`);function a(e){let t=i.exec(e);return!t||t[1]===`00`&&t[5]?null:{traceId:t[2],spanId:t[3],traceFlags:parseInt(t[4],16)}}e.parseTraceParent=a,e.W3CTraceContextPropagator=class{inject(r,i,a){let o=t.trace.getSpanContext(r);if(!o||(0,n.isTracingSuppressed)(r)||!(0,t.isSpanContextValid)(o))return;let s=`00-${o.traceId}-${o.spanId}-0${Number(o.traceFlags||t.TraceFlags.NONE).toString(16)}`;a.set(i,e.TRACE_PARENT_HEADER,s),o.traceState&&a.set(i,e.TRACE_STATE_HEADER,o.traceState.serialize())}extract(n,i,o){let s=o.get(i,e.TRACE_PARENT_HEADER);if(!s)return n;let c=Array.isArray(s)?s[0]:s;if(typeof c!=`string`)return n;let l=a(c);if(!l)return n;l.isRemote=!0;let u=o.get(i,e.TRACE_STATE_HEADER);if(u){let e=Array.isArray(u)?u.join(`,`):u;l.traceState=new r.TraceState(typeof e==`string`?e:void 0)}return t.trace.setSpanContext(n,l)}fields(){return[e.TRACE_PARENT_HEADER,e.TRACE_STATE_HEADER]}}})),NL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getRPCMetadata=e.deleteRPCMetadata=e.setRPCMetadata=e.RPCType=void 0;let t=(0,(Jd(),d(Kd)).createContextKey)(`OpenTelemetry SDK Context Key RPC_METADATA`);(function(e){e.HTTP=`http`})(e.RPCType||={});function n(e,n){return e.setValue(t,n)}e.setRPCMetadata=n;function r(e){return e.deleteValue(t)}e.deleteRPCMetadata=r;function i(e){return e.getValue(t)}e.getRPCMetadata=i})),PL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.isPlainObject=void 0;let t=Function.prototype.toString,n=t.call(Object),r=Object.getPrototypeOf,i=Object.prototype,a=i.hasOwnProperty,o=Symbol?Symbol.toStringTag:void 0,s=i.toString;function c(e){if(!l(e)||u(e)!==`[object Object]`)return!1;let i=r(e);if(i===null)return!0;let o=a.call(i,`constructor`)&&i.constructor;return typeof o==`function`&&o instanceof o&&t.call(o)===n}e.isPlainObject=c;function l(e){return typeof e==`object`&&!!e}function u(e){return e==null?e===void 0?`[object Undefined]`:`[object Null]`:o&&o in Object(e)?d(e):f(e)}function d(e){let t=a.call(e,o),n=e[o],r=!1;try{e[o]=void 0,r=!0}catch{}let i=s.call(e);return r&&(t?e[o]=n:delete e[o]),i}function f(e){return s.call(e)}})),FL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.merge=void 0;let t=PL();function n(...e){let t=e.shift(),n=new WeakMap;for(;e.length>0;)t=i(t,e.shift(),0,n);return t}e.merge=n;function r(e){return o(e)?e.slice():e}function i(e,t,n=0,d){let f;if(!(n>20)){if(n++,l(e)||l(t)||s(t))f=r(t);else if(o(e)){if(f=e.slice(),o(t))for(let e=0,n=t.length;e<n;e++)f.push(r(t[e]));else if(c(t)){let e=Object.keys(t);for(let n=0,i=e.length;n<i;n++){let i=e[n];f[i]=r(t[i])}}}else if(c(e))if(c(t)){if(!u(e,t))return t;f=Object.assign({},e);let r=Object.keys(t);for(let o=0,s=r.length;o<s;o++){let s=r[o],u=t[s];if(l(u))u===void 0?delete f[s]:f[s]=u;else{let r=f[s],o=u;if(a(e,s,d)||a(t,s,d))delete f[s];else{if(c(r)&&c(o)){let n=d.get(r)||[],i=d.get(o)||[];n.push({obj:e,key:s}),i.push({obj:t,key:s}),d.set(r,n),d.set(o,i)}f[s]=i(f[s],u,n,d)}}}}else f=t;return f}}function a(e,t,n){let r=n.get(e[t])||[];for(let n=0,i=r.length;n<i;n++){let i=r[n];if(i.key===t&&i.obj===e)return!0}return!1}function o(e){return Array.isArray(e)}function s(e){return typeof e==`function`}function c(e){return!l(e)&&!o(e)&&!s(e)&&typeof e==`object`}function l(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`||e===void 0||e instanceof Date||e instanceof RegExp||e===null}function u(e,n){return!(!(0,t.isPlainObject)(e)||!(0,t.isPlainObject)(n))}})),IL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.callWithTimeout=e.TimeoutError=void 0;var t=class e extends Error{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype)}};e.TimeoutError=t;function n(e,n){let r,i=new Promise(function(e,i){r=setTimeout(function(){i(new t(`Operation timed out.`))},n)});return Promise.race([e,i]).then(e=>(clearTimeout(r),e),e=>{throw clearTimeout(r),e})}e.callWithTimeout=n})),LL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.isUrlIgnored=e.urlMatches=void 0;function t(e,t){return typeof t==`string`?e===t:!!e.match(t)}e.urlMatches=t;function n(e,n){if(!n)return!1;for(let r of n)if(t(e,r))return!0;return!1}e.isUrlIgnored=n})),RL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.Deferred=void 0,e.Deferred=class{_promise;_resolve;_reject;constructor(){this._promise=new Promise((e,t)=>{this._resolve=e,this._reject=t})}get promise(){return this._promise}resolve(e){this._resolve(e)}reject(e){this._reject(e)}}})),zL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BindOnceFuture=void 0;let t=RL();e.BindOnceFuture=class{_callback;_that;_isCalled=!1;_deferred=new t.Deferred;constructor(e,t){this._callback=e,this._that=t}get isCalled(){return this._isCalled}get promise(){return this._deferred.promise}call(...e){if(!this._isCalled){this._isCalled=!0;try{Promise.resolve(this._callback.call(this._that,...e)).then(e=>this._deferred.resolve(e),e=>this._deferred.reject(e))}catch(e){this._deferred.reject(e)}}return this._deferred.promise}}})),BL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.diagLogLevelFromString=void 0;let t=(Jd(),d(Kd)),n={ALL:t.DiagLogLevel.ALL,VERBOSE:t.DiagLogLevel.VERBOSE,DEBUG:t.DiagLogLevel.DEBUG,INFO:t.DiagLogLevel.INFO,WARN:t.DiagLogLevel.WARN,ERROR:t.DiagLogLevel.ERROR,NONE:t.DiagLogLevel.NONE};function r(e){return e==null?void 0:n[e.toUpperCase()]??(t.diag.warn(`Unknown log level "${e}", expected one of ${Object.keys(n)}, using default`),t.DiagLogLevel.INFO)}e.diagLogLevelFromString=r})),VL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e._export=void 0;let t=(Jd(),d(Kd)),n=dL();function r(e,r){return new Promise(i=>{t.context.with((0,n.suppressTracing)(t.context.active()),()=>{e.export(r,e=>{i(e)})})})}e._export=r})),HL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.internal=e.diagLogLevelFromString=e.BindOnceFuture=e.urlMatches=e.isUrlIgnored=e.callWithTimeout=e.TimeoutError=e.merge=e.TraceState=e.unsuppressTracing=e.suppressTracing=e.isTracingSuppressed=e.setRPCMetadata=e.getRPCMetadata=e.deleteRPCMetadata=e.RPCType=e.parseTraceParent=e.W3CTraceContextPropagator=e.TRACE_STATE_HEADER=e.TRACE_PARENT_HEADER=e.CompositePropagator=e.unrefTimer=e.otperformance=e.getStringListFromEnv=e.getNumberFromEnv=e.getBooleanFromEnv=e.getStringFromEnv=e._globalThis=e.SDK_INFO=e.parseKeyPairsIntoRecord=e.ExportResultCode=e.timeInputToHrTime=e.millisToHrTime=e.isTimeInputHrTime=e.isTimeInput=e.hrTimeToTimeStamp=e.hrTimeToNanoseconds=e.hrTimeToMilliseconds=e.hrTimeToMicroseconds=e.hrTimeDuration=e.hrTime=e.getTimeOrigin=e.addHrTimes=e.loggingErrorHandler=e.setGlobalErrorHandler=e.globalErrorHandler=e.sanitizeAttributes=e.isAttributeValue=e.AnchoredClock=e.W3CBaggagePropagator=void 0;var t=mL();Object.defineProperty(e,`W3CBaggagePropagator`,{enumerable:!0,get:function(){return t.W3CBaggagePropagator}});var n=hL();Object.defineProperty(e,`AnchoredClock`,{enumerable:!0,get:function(){return n.AnchoredClock}});var r=gL();Object.defineProperty(e,`isAttributeValue`,{enumerable:!0,get:function(){return r.isAttributeValue}}),Object.defineProperty(e,`sanitizeAttributes`,{enumerable:!0,get:function(){return r.sanitizeAttributes}});var i=vL();Object.defineProperty(e,`globalErrorHandler`,{enumerable:!0,get:function(){return i.globalErrorHandler}}),Object.defineProperty(e,`setGlobalErrorHandler`,{enumerable:!0,get:function(){return i.setGlobalErrorHandler}});var a=_L();Object.defineProperty(e,`loggingErrorHandler`,{enumerable:!0,get:function(){return a.loggingErrorHandler}});var o=DL();Object.defineProperty(e,`addHrTimes`,{enumerable:!0,get:function(){return o.addHrTimes}}),Object.defineProperty(e,`getTimeOrigin`,{enumerable:!0,get:function(){return o.getTimeOrigin}}),Object.defineProperty(e,`hrTime`,{enumerable:!0,get:function(){return o.hrTime}}),Object.defineProperty(e,`hrTimeDuration`,{enumerable:!0,get:function(){return o.hrTimeDuration}}),Object.defineProperty(e,`hrTimeToMicroseconds`,{enumerable:!0,get:function(){return o.hrTimeToMicroseconds}}),Object.defineProperty(e,`hrTimeToMilliseconds`,{enumerable:!0,get:function(){return o.hrTimeToMilliseconds}}),Object.defineProperty(e,`hrTimeToNanoseconds`,{enumerable:!0,get:function(){return o.hrTimeToNanoseconds}}),Object.defineProperty(e,`hrTimeToTimeStamp`,{enumerable:!0,get:function(){return o.hrTimeToTimeStamp}}),Object.defineProperty(e,`isTimeInput`,{enumerable:!0,get:function(){return o.isTimeInput}}),Object.defineProperty(e,`isTimeInputHrTime`,{enumerable:!0,get:function(){return o.isTimeInputHrTime}}),Object.defineProperty(e,`millisToHrTime`,{enumerable:!0,get:function(){return o.millisToHrTime}}),Object.defineProperty(e,`timeInputToHrTime`,{enumerable:!0,get:function(){return o.timeInputToHrTime}});var s=OL();Object.defineProperty(e,`ExportResultCode`,{enumerable:!0,get:function(){return s.ExportResultCode}});var c=pL();Object.defineProperty(e,`parseKeyPairsIntoRecord`,{enumerable:!0,get:function(){return c.parseKeyPairsIntoRecord}});var l=EL();Object.defineProperty(e,`SDK_INFO`,{enumerable:!0,get:function(){return l.SDK_INFO}}),Object.defineProperty(e,`_globalThis`,{enumerable:!0,get:function(){return l._globalThis}}),Object.defineProperty(e,`getStringFromEnv`,{enumerable:!0,get:function(){return l.getStringFromEnv}}),Object.defineProperty(e,`getBooleanFromEnv`,{enumerable:!0,get:function(){return l.getBooleanFromEnv}}),Object.defineProperty(e,`getNumberFromEnv`,{enumerable:!0,get:function(){return l.getNumberFromEnv}}),Object.defineProperty(e,`getStringListFromEnv`,{enumerable:!0,get:function(){return l.getStringListFromEnv}}),Object.defineProperty(e,`otperformance`,{enumerable:!0,get:function(){return l.otperformance}}),Object.defineProperty(e,`unrefTimer`,{enumerable:!0,get:function(){return l.unrefTimer}});var u=kL();Object.defineProperty(e,`CompositePropagator`,{enumerable:!0,get:function(){return u.CompositePropagator}});var d=ML();Object.defineProperty(e,`TRACE_PARENT_HEADER`,{enumerable:!0,get:function(){return d.TRACE_PARENT_HEADER}}),Object.defineProperty(e,`TRACE_STATE_HEADER`,{enumerable:!0,get:function(){return d.TRACE_STATE_HEADER}}),Object.defineProperty(e,`W3CTraceContextPropagator`,{enumerable:!0,get:function(){return d.W3CTraceContextPropagator}}),Object.defineProperty(e,`parseTraceParent`,{enumerable:!0,get:function(){return d.parseTraceParent}});var f=NL();Object.defineProperty(e,`RPCType`,{enumerable:!0,get:function(){return f.RPCType}}),Object.defineProperty(e,`deleteRPCMetadata`,{enumerable:!0,get:function(){return f.deleteRPCMetadata}}),Object.defineProperty(e,`getRPCMetadata`,{enumerable:!0,get:function(){return f.getRPCMetadata}}),Object.defineProperty(e,`setRPCMetadata`,{enumerable:!0,get:function(){return f.setRPCMetadata}});var p=dL();Object.defineProperty(e,`isTracingSuppressed`,{enumerable:!0,get:function(){return p.isTracingSuppressed}}),Object.defineProperty(e,`suppressTracing`,{enumerable:!0,get:function(){return p.suppressTracing}}),Object.defineProperty(e,`unsuppressTracing`,{enumerable:!0,get:function(){return p.unsuppressTracing}});var m=jL();Object.defineProperty(e,`TraceState`,{enumerable:!0,get:function(){return m.TraceState}});var h=FL();Object.defineProperty(e,`merge`,{enumerable:!0,get:function(){return h.merge}});var g=IL();Object.defineProperty(e,`TimeoutError`,{enumerable:!0,get:function(){return g.TimeoutError}}),Object.defineProperty(e,`callWithTimeout`,{enumerable:!0,get:function(){return g.callWithTimeout}});var _=LL();Object.defineProperty(e,`isUrlIgnored`,{enumerable:!0,get:function(){return _.isUrlIgnored}}),Object.defineProperty(e,`urlMatches`,{enumerable:!0,get:function(){return _.urlMatches}});var v=zL();Object.defineProperty(e,`BindOnceFuture`,{enumerable:!0,get:function(){return v.BindOnceFuture}});var y=BL();Object.defineProperty(e,`diagLogLevelFromString`,{enumerable:!0,get:function(){return y.diagLogLevelFromString}}),e.internal={_export:VL()._export}})),UL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.defaultServiceName=void 0;function t(){return`unknown_service:${process.argv0}`}e.defaultServiceName=t})),WL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.defaultServiceName=void 0;var t=UL();Object.defineProperty(e,`defaultServiceName`,{enumerable:!0,get:function(){return t.defaultServiceName}})})),GL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.defaultServiceName=void 0;var t=WL();Object.defineProperty(e,`defaultServiceName`,{enumerable:!0,get:function(){return t.defaultServiceName}})})),KL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.identity=e.isPromiseLike=void 0,e.isPromiseLike=e=>typeof e==`object`&&!!e&&typeof e.then==`function`;function t(e){return e}e.identity=t})),qL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.defaultResource=e.emptyResource=e.resourceFromDetectedResource=e.resourceFromAttributes=void 0;let t=(Jd(),d(Kd)),n=HL(),r=(PA(),d(NA)),i=GL(),a=KL();var o=class e{_rawAttributes;_asyncAttributesPending=!1;_schemaUrl;_memoizedAttributes;static FromAttributeList(t,n){let r=new e({},n);return r._rawAttributes=f(t),r._asyncAttributesPending=t.filter(([e,t])=>(0,a.isPromiseLike)(t)).length>0,r}constructor(e,t){let n=e.attributes??{};this._rawAttributes=Object.entries(n).map(([e,t])=>((0,a.isPromiseLike)(t)&&(this._asyncAttributesPending=!0),[e,t])),this._rawAttributes=f(this._rawAttributes),this._schemaUrl=p(t?.schemaUrl)}get asyncAttributesPending(){return this._asyncAttributesPending}async waitForAsyncAttributes(){if(this.asyncAttributesPending){for(let e=0;e<this._rawAttributes.length;e++){let[t,n]=this._rawAttributes[e];this._rawAttributes[e]=[t,(0,a.isPromiseLike)(n)?await n:n]}this._asyncAttributesPending=!1}}get attributes(){if(this.asyncAttributesPending&&t.diag.error(`Accessing resource attributes before async attributes settled`),this._memoizedAttributes)return this._memoizedAttributes;let e={};for(let[n,r]of this._rawAttributes){if((0,a.isPromiseLike)(r)){t.diag.debug(`Unsettled resource attribute ${n} skipped`);continue}r!=null&&(e[n]??=r)}return this._asyncAttributesPending||(this._memoizedAttributes=e),e}getRawAttributes(){return this._rawAttributes}get schemaUrl(){return this._schemaUrl}merge(t){if(t==null)return this;let n=m(this,t),r=n?{schemaUrl:n}:void 0;return e.FromAttributeList([...t.getRawAttributes(),...this.getRawAttributes()],r)}};function s(e,t){return o.FromAttributeList(Object.entries(e),t)}e.resourceFromAttributes=s;function c(e,t){return new o(e,t)}e.resourceFromDetectedResource=c;function l(){return s({})}e.emptyResource=l;function u(){return s({[r.ATTR_SERVICE_NAME]:(0,i.defaultServiceName)(),[r.ATTR_TELEMETRY_SDK_LANGUAGE]:n.SDK_INFO[r.ATTR_TELEMETRY_SDK_LANGUAGE],[r.ATTR_TELEMETRY_SDK_NAME]:n.SDK_INFO[r.ATTR_TELEMETRY_SDK_NAME],[r.ATTR_TELEMETRY_SDK_VERSION]:n.SDK_INFO[r.ATTR_TELEMETRY_SDK_VERSION]})}e.defaultResource=u;function f(e){return e.map(([e,n])=>(0,a.isPromiseLike)(n)?[e,n.catch(n=>{t.diag.debug(`promise rejection for resource attribute: %s - %s`,e,n)})]:[e,n])}function p(e){if(typeof e==`string`||e===void 0)return e;t.diag.warn(`Schema URL must be string or undefined, got %s. Schema URL will be ignored.`,e)}function m(e,n){let r=e?.schemaUrl,i=n?.schemaUrl,a=r===void 0||r===``,o=i===void 0||i===``;if(a)return i;if(o||r===i)return r;t.diag.warn(`Schema URL merge conflict: old resource has "%s", updating resource has "%s". Resulting resource will have undefined Schema URL.`,r,i)}})),JL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.detectResources=void 0;let t=(Jd(),d(Kd)),n=qL();e.detectResources=(e={})=>(e.detectors||[]).map(r=>{try{let i=(0,n.resourceFromDetectedResource)(r.detect(e));return t.diag.debug(`${r.constructor.name} found resource.`,i),i}catch(e){return t.diag.debug(`${r.constructor.name} failed: ${e.message}`),(0,n.emptyResource)()}}).reduce((e,t)=>e.merge(t),(0,n.emptyResource)())})),YL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.envDetector=void 0;let t=(Jd(),d(Kd)),n=(PA(),d(NA)),r=HL();e.envDetector=new class{_MAX_LENGTH=255;_COMMA_SEPARATOR=`,`;_LABEL_KEY_VALUE_SPLITTER=`=`;_ERROR_MESSAGE_INVALID_CHARS=`should be a ASCII string with a length greater than 0 and not exceed `+this._MAX_LENGTH+` characters.`;_ERROR_MESSAGE_INVALID_VALUE=`should be a ASCII string with a length not exceed `+this._MAX_LENGTH+` characters.`;detect(e){let i={},a=(0,r.getStringFromEnv)(`OTEL_RESOURCE_ATTRIBUTES`),o=(0,r.getStringFromEnv)(`OTEL_SERVICE_NAME`);if(a)try{let e=this._parseResourceAttributes(a);Object.assign(i,e)}catch(e){t.diag.debug(`EnvDetector failed: ${e.message}`)}return o&&(i[n.ATTR_SERVICE_NAME]=o),{attributes:i}}_parseResourceAttributes(e){if(!e)return{};let t={},n=e.split(this._COMMA_SEPARATOR,-1);for(let e of n){let n=e.split(this._LABEL_KEY_VALUE_SPLITTER,-1);if(n.length!==2)continue;let[r,i]=n;if(r=r.trim(),i=i.trim().split(/^"|"$/).join(``),!this._isValidAndNotEmpty(r))throw Error(`Attribute key ${this._ERROR_MESSAGE_INVALID_CHARS}`);if(!this._isValid(i))throw Error(`Attribute value ${this._ERROR_MESSAGE_INVALID_VALUE}`);t[r]=decodeURIComponent(i)}return t}_isValid(e){return e.length<=this._MAX_LENGTH&&this._isBaggageOctetString(e)}_isBaggageOctetString(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<33||n===44||n===59||n===92||n>126)return!1}return!0}_isValidAndNotEmpty(e){return e.length>0&&this._isValid(e)}}})),XL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ATTR_WEBENGINE_VERSION=e.ATTR_WEBENGINE_NAME=e.ATTR_WEBENGINE_DESCRIPTION=e.ATTR_SERVICE_NAMESPACE=e.ATTR_SERVICE_INSTANCE_ID=e.ATTR_PROCESS_RUNTIME_VERSION=e.ATTR_PROCESS_RUNTIME_NAME=e.ATTR_PROCESS_RUNTIME_DESCRIPTION=e.ATTR_PROCESS_PID=e.ATTR_PROCESS_OWNER=e.ATTR_PROCESS_EXECUTABLE_PATH=e.ATTR_PROCESS_EXECUTABLE_NAME=e.ATTR_PROCESS_COMMAND_ARGS=e.ATTR_PROCESS_COMMAND=e.ATTR_OS_VERSION=e.ATTR_OS_TYPE=e.ATTR_K8S_POD_NAME=e.ATTR_K8S_NAMESPACE_NAME=e.ATTR_K8S_DEPLOYMENT_NAME=e.ATTR_K8S_CLUSTER_NAME=e.ATTR_HOST_TYPE=e.ATTR_HOST_NAME=e.ATTR_HOST_IMAGE_VERSION=e.ATTR_HOST_IMAGE_NAME=e.ATTR_HOST_IMAGE_ID=e.ATTR_HOST_ID=e.ATTR_HOST_ARCH=e.ATTR_CONTAINER_NAME=e.ATTR_CONTAINER_IMAGE_TAGS=e.ATTR_CONTAINER_IMAGE_NAME=e.ATTR_CONTAINER_ID=e.ATTR_CLOUD_REGION=e.ATTR_CLOUD_PROVIDER=e.ATTR_CLOUD_AVAILABILITY_ZONE=e.ATTR_CLOUD_ACCOUNT_ID=void 0,e.ATTR_CLOUD_ACCOUNT_ID=`cloud.account.id`,e.ATTR_CLOUD_AVAILABILITY_ZONE=`cloud.availability_zone`,e.ATTR_CLOUD_PROVIDER=`cloud.provider`,e.ATTR_CLOUD_REGION=`cloud.region`,e.ATTR_CONTAINER_ID=`container.id`,e.ATTR_CONTAINER_IMAGE_NAME=`container.image.name`,e.ATTR_CONTAINER_IMAGE_TAGS=`container.image.tags`,e.ATTR_CONTAINER_NAME=`container.name`,e.ATTR_HOST_ARCH=`host.arch`,e.ATTR_HOST_ID=`host.id`,e.ATTR_HOST_IMAGE_ID=`host.image.id`,e.ATTR_HOST_IMAGE_NAME=`host.image.name`,e.ATTR_HOST_IMAGE_VERSION=`host.image.version`,e.ATTR_HOST_NAME=`host.name`,e.ATTR_HOST_TYPE=`host.type`,e.ATTR_K8S_CLUSTER_NAME=`k8s.cluster.name`,e.ATTR_K8S_DEPLOYMENT_NAME=`k8s.deployment.name`,e.ATTR_K8S_NAMESPACE_NAME=`k8s.namespace.name`,e.ATTR_K8S_POD_NAME=`k8s.pod.name`,e.ATTR_OS_TYPE=`os.type`,e.ATTR_OS_VERSION=`os.version`,e.ATTR_PROCESS_COMMAND=`process.command`,e.ATTR_PROCESS_COMMAND_ARGS=`process.command_args`,e.ATTR_PROCESS_EXECUTABLE_NAME=`process.executable.name`,e.ATTR_PROCESS_EXECUTABLE_PATH=`process.executable.path`,e.ATTR_PROCESS_OWNER=`process.owner`,e.ATTR_PROCESS_PID=`process.pid`,e.ATTR_PROCESS_RUNTIME_DESCRIPTION=`process.runtime.description`,e.ATTR_PROCESS_RUNTIME_NAME=`process.runtime.name`,e.ATTR_PROCESS_RUNTIME_VERSION=`process.runtime.version`,e.ATTR_SERVICE_INSTANCE_ID=`service.instance.id`,e.ATTR_SERVICE_NAMESPACE=`service.namespace`,e.ATTR_WEBENGINE_DESCRIPTION=`webengine.description`,e.ATTR_WEBENGINE_NAME=`webengine.name`,e.ATTR_WEBENGINE_VERSION=`webengine.version`})),ZL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getMachineId=void 0;let t=require(`process`),n;async function r(){if(!n)switch(t.platform){case`darwin`:n=(await Promise.resolve().then(()=>u(require(`./getMachineId-darwin-qxG7FDMy.cjs`).default))).getMachineId;break;case`linux`:n=(await Promise.resolve().then(()=>u(require(`./getMachineId-linux-Dnsx6XjV.cjs`).default))).getMachineId;break;case`freebsd`:n=(await Promise.resolve().then(()=>u(require(`./getMachineId-bsd-C6vJ2MI6.cjs`).default))).getMachineId;break;case`win32`:n=(await Promise.resolve().then(()=>u(require(`./getMachineId-win-BDuHxVob.cjs`).default))).getMachineId;break;default:n=(await Promise.resolve().then(()=>u(require(`./getMachineId-unsupported-BE5onnLI.cjs`).default))).getMachineId;break}return n()}e.getMachineId=r})),QL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.normalizeType=e.normalizeArch=void 0,e.normalizeArch=e=>{switch(e){case`arm`:return`arm32`;case`ppc`:return`ppc32`;case`x64`:return`amd64`;default:return e}},e.normalizeType=e=>{switch(e){case`sunos`:return`solaris`;case`win32`:return`windows`;default:return e}}})),$L=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.hostDetector=void 0;let t=XL(),n=require(`os`),r=ZL(),i=QL();e.hostDetector=new class{detect(e){return{attributes:{[t.ATTR_HOST_NAME]:(0,n.hostname)(),[t.ATTR_HOST_ARCH]:(0,i.normalizeArch)((0,n.arch)()),[t.ATTR_HOST_ID]:(0,r.getMachineId)()}}}}})),eR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.osDetector=void 0;let t=XL(),n=require(`os`),r=QL();e.osDetector=new class{detect(e){return{attributes:{[t.ATTR_OS_TYPE]:(0,r.normalizeType)((0,n.platform)()),[t.ATTR_OS_VERSION]:(0,n.release)()}}}}})),tR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.processDetector=void 0;let t=(Jd(),d(Kd)),n=XL(),r=require(`os`);e.processDetector=new class{detect(e){let i={[n.ATTR_PROCESS_PID]:process.pid,[n.ATTR_PROCESS_EXECUTABLE_NAME]:process.title,[n.ATTR_PROCESS_EXECUTABLE_PATH]:process.execPath,[n.ATTR_PROCESS_COMMAND_ARGS]:[process.argv[0],...process.execArgv,...process.argv.slice(1)],[n.ATTR_PROCESS_RUNTIME_VERSION]:process.versions.node,[n.ATTR_PROCESS_RUNTIME_NAME]:`nodejs`,[n.ATTR_PROCESS_RUNTIME_DESCRIPTION]:`Node.js`};process.argv.length>1&&(i[n.ATTR_PROCESS_COMMAND]=process.argv[1]);try{let e=r.userInfo();i[n.ATTR_PROCESS_OWNER]=e.username}catch(e){t.diag.debug(`error obtaining process owner: ${e}`)}return{attributes:i}}}})),nR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.serviceInstanceIdDetector=void 0;let t=XL(),n=require(`crypto`);e.serviceInstanceIdDetector=new class{detect(e){return{attributes:{[t.ATTR_SERVICE_INSTANCE_ID]:(0,n.randomUUID)()}}}}})),rR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.serviceInstanceIdDetector=e.processDetector=e.osDetector=e.hostDetector=void 0;var t=$L();Object.defineProperty(e,`hostDetector`,{enumerable:!0,get:function(){return t.hostDetector}});var n=eR();Object.defineProperty(e,`osDetector`,{enumerable:!0,get:function(){return n.osDetector}});var r=tR();Object.defineProperty(e,`processDetector`,{enumerable:!0,get:function(){return r.processDetector}});var i=nR();Object.defineProperty(e,`serviceInstanceIdDetector`,{enumerable:!0,get:function(){return i.serviceInstanceIdDetector}})})),iR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.serviceInstanceIdDetector=e.processDetector=e.osDetector=e.hostDetector=void 0;var t=rR();Object.defineProperty(e,`hostDetector`,{enumerable:!0,get:function(){return t.hostDetector}}),Object.defineProperty(e,`osDetector`,{enumerable:!0,get:function(){return t.osDetector}}),Object.defineProperty(e,`processDetector`,{enumerable:!0,get:function(){return t.processDetector}}),Object.defineProperty(e,`serviceInstanceIdDetector`,{enumerable:!0,get:function(){return t.serviceInstanceIdDetector}})})),aR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.noopDetector=e.NoopDetector=void 0;var t=class{detect(){return{attributes:{}}}};e.NoopDetector=t,e.noopDetector=new t})),oR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.noopDetector=e.serviceInstanceIdDetector=e.processDetector=e.osDetector=e.hostDetector=e.envDetector=void 0;var t=YL();Object.defineProperty(e,`envDetector`,{enumerable:!0,get:function(){return t.envDetector}});var n=iR();Object.defineProperty(e,`hostDetector`,{enumerable:!0,get:function(){return n.hostDetector}}),Object.defineProperty(e,`osDetector`,{enumerable:!0,get:function(){return n.osDetector}}),Object.defineProperty(e,`processDetector`,{enumerable:!0,get:function(){return n.processDetector}}),Object.defineProperty(e,`serviceInstanceIdDetector`,{enumerable:!0,get:function(){return n.serviceInstanceIdDetector}});var r=aR();Object.defineProperty(e,`noopDetector`,{enumerable:!0,get:function(){return r.noopDetector}})})),sR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.defaultServiceName=e.emptyResource=e.defaultResource=e.resourceFromAttributes=e.serviceInstanceIdDetector=e.processDetector=e.osDetector=e.hostDetector=e.envDetector=e.detectResources=void 0;var t=JL();Object.defineProperty(e,`detectResources`,{enumerable:!0,get:function(){return t.detectResources}});var n=oR();Object.defineProperty(e,`envDetector`,{enumerable:!0,get:function(){return n.envDetector}}),Object.defineProperty(e,`hostDetector`,{enumerable:!0,get:function(){return n.hostDetector}}),Object.defineProperty(e,`osDetector`,{enumerable:!0,get:function(){return n.osDetector}}),Object.defineProperty(e,`processDetector`,{enumerable:!0,get:function(){return n.processDetector}}),Object.defineProperty(e,`serviceInstanceIdDetector`,{enumerable:!0,get:function(){return n.serviceInstanceIdDetector}});var r=qL();Object.defineProperty(e,`resourceFromAttributes`,{enumerable:!0,get:function(){return r.resourceFromAttributes}}),Object.defineProperty(e,`defaultResource`,{enumerable:!0,get:function(){return r.defaultResource}}),Object.defineProperty(e,`emptyResource`,{enumerable:!0,get:function(){return r.emptyResource}});var i=GL();Object.defineProperty(e,`defaultServiceName`,{enumerable:!0,get:function(){return i.defaultServiceName}})})),cR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.LogRecordImpl=void 0;let t=(Jd(),d(Kd)),n=HL();e.LogRecordImpl=class{hrTime;hrTimeObserved;spanContext;resource;instrumentationScope;attributes={};_severityText;_severityNumber;_body;_eventName;totalAttributesCount=0;_isReadonly=!1;_logRecordLimits;set severityText(e){this._isLogRecordReadonly()||(this._severityText=e)}get severityText(){return this._severityText}set severityNumber(e){this._isLogRecordReadonly()||(this._severityNumber=e)}get severityNumber(){return this._severityNumber}set body(e){this._isLogRecordReadonly()||(this._body=e)}get body(){return this._body}get eventName(){return this._eventName}set eventName(e){this._isLogRecordReadonly()||(this._eventName=e)}get droppedAttributesCount(){return this.totalAttributesCount-Object.keys(this.attributes).length}constructor(e,r,i){let{timestamp:a,observedTimestamp:o,eventName:s,severityNumber:c,severityText:l,body:u,attributes:d={},context:f}=i,p=Date.now();if(this.hrTime=(0,n.timeInputToHrTime)(a??p),this.hrTimeObserved=(0,n.timeInputToHrTime)(o??p),f){let e=t.trace.getSpanContext(f);e&&t.isSpanContextValid(e)&&(this.spanContext=e)}this.severityNumber=c,this.severityText=l,this.body=u,this.resource=e.resource,this.instrumentationScope=r,this._logRecordLimits=e.logRecordLimits,this._eventName=s,this.setAttributes(d)}setAttribute(e,r){return this._isLogRecordReadonly()||r===null?this:e.length===0?(t.diag.warn(`Invalid attribute key: ${e}`),this):!(0,n.isAttributeValue)(r)&&!(typeof r==`object`&&!Array.isArray(r)&&Object.keys(r).length>0)?(t.diag.warn(`Invalid attribute value set for key: ${e}`),this):(this.totalAttributesCount+=1,Object.keys(this.attributes).length>=this._logRecordLimits.attributeCountLimit&&!Object.prototype.hasOwnProperty.call(this.attributes,e)?(this.droppedAttributesCount===1&&t.diag.warn(`Dropping extra attributes.`),this):((0,n.isAttributeValue)(r)?this.attributes[e]=this._truncateToSize(r):this.attributes[e]=r,this))}setAttributes(e){for(let[t,n]of Object.entries(e))this.setAttribute(t,n);return this}setBody(e){return this.body=e,this}setEventName(e){return this.eventName=e,this}setSeverityNumber(e){return this.severityNumber=e,this}setSeverityText(e){return this.severityText=e,this}_makeReadonly(){this._isReadonly=!0}_truncateToSize(e){let n=this._logRecordLimits.attributeValueLengthLimit;return n<=0?(t.diag.warn(`Attribute value limit must be positive, got ${n}`),e):typeof e==`string`?this._truncateToLimitUtil(e,n):Array.isArray(e)?e.map(e=>typeof e==`string`?this._truncateToLimitUtil(e,n):e):e}_truncateToLimitUtil(e,t){return e.length<=t?e:e.substring(0,t)}_isLogRecordReadonly(){return this._isReadonly&&t.diag.warn(`Can not execute the operation on emitted log record`),this._isReadonly}}})),lR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.Logger=void 0;let t=(Jd(),d(Kd)),n=cR();e.Logger=class{instrumentationScope;_sharedState;constructor(e,t){this.instrumentationScope=e,this._sharedState=t}emit(e){let r=e.context||t.context.active(),i=new n.LogRecordImpl(this._sharedState,this.instrumentationScope,{context:r,...e});this._sharedState.activeProcessor.onEmit(i,r),i._makeReadonly()}}})),uR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.reconfigureLimits=e.loadDefaultConfig=void 0;let t=HL();function n(){return{forceFlushTimeoutMillis:3e4,logRecordLimits:{attributeValueLengthLimit:(0,t.getNumberFromEnv)(`OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT`)??1/0,attributeCountLimit:(0,t.getNumberFromEnv)(`OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT`)??128},includeTraceContext:!0}}e.loadDefaultConfig=n;function r(e){return{attributeCountLimit:e.attributeCountLimit??(0,t.getNumberFromEnv)(`OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT`)??(0,t.getNumberFromEnv)(`OTEL_ATTRIBUTE_COUNT_LIMIT`)??128,attributeValueLengthLimit:e.attributeValueLengthLimit??(0,t.getNumberFromEnv)(`OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT`)??(0,t.getNumberFromEnv)(`OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT`)??1/0}}e.reconfigureLimits=r})),dR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.NoopLogRecordProcessor=void 0,e.NoopLogRecordProcessor=class{forceFlush(){return Promise.resolve()}onEmit(e,t){}shutdown(){return Promise.resolve()}}})),fR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MultiLogRecordProcessor=void 0;let t=HL();e.MultiLogRecordProcessor=class{processors;forceFlushTimeoutMillis;constructor(e,t){this.processors=e,this.forceFlushTimeoutMillis=t}async forceFlush(){let e=this.forceFlushTimeoutMillis;await Promise.all(this.processors.map(n=>(0,t.callWithTimeout)(n.forceFlush(),e)))}onEmit(e,t){this.processors.forEach(n=>n.onEmit(e,t))}async shutdown(){await Promise.all(this.processors.map(e=>e.shutdown()))}}})),pR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.LoggerProviderSharedState=void 0;let t=dR(),n=fR();e.LoggerProviderSharedState=class{resource;forceFlushTimeoutMillis;logRecordLimits;processors;loggers=new Map;activeProcessor;registeredLogRecordProcessors=[];constructor(e,r,i,a){this.resource=e,this.forceFlushTimeoutMillis=r,this.logRecordLimits=i,this.processors=a,a.length>0?(this.registeredLogRecordProcessors=a,this.activeProcessor=new n.MultiLogRecordProcessor(this.registeredLogRecordProcessors,this.forceFlushTimeoutMillis)):this.activeProcessor=new t.NoopLogRecordProcessor}}})),mR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.LoggerProvider=e.DEFAULT_LOGGER_NAME=void 0;let t=(Jd(),d(Kd)),n=Li(),r=sR(),i=HL(),a=lR(),o=uR(),s=pR();e.DEFAULT_LOGGER_NAME=`unknown`,e.LoggerProvider=class{_shutdownOnce;_sharedState;constructor(e={}){let t=(0,i.merge)({},(0,o.loadDefaultConfig)(),e),n=e.resource??(0,r.defaultResource)();this._sharedState=new s.LoggerProviderSharedState(n,t.forceFlushTimeoutMillis,(0,o.reconfigureLimits)(t.logRecordLimits),e?.processors??[]),this._shutdownOnce=new i.BindOnceFuture(this._shutdown,this)}getLogger(r,i,o){if(this._shutdownOnce.isCalled)return t.diag.warn(`A shutdown LoggerProvider cannot provide a Logger`),n.NOOP_LOGGER;r||t.diag.warn(`Logger requested without instrumentation scope name.`);let s=r||e.DEFAULT_LOGGER_NAME,c=`${s}@${i||``}:${o?.schemaUrl||``}`;return this._sharedState.loggers.has(c)||this._sharedState.loggers.set(c,new a.Logger({name:s,version:i,schemaUrl:o?.schemaUrl},this._sharedState)),this._sharedState.loggers.get(c)}forceFlush(){return this._shutdownOnce.isCalled?(t.diag.warn(`invalid attempt to force flush after LoggerProvider shutdown`),this._shutdownOnce.promise):this._sharedState.activeProcessor.forceFlush()}shutdown(){return this._shutdownOnce.isCalled?(t.diag.warn(`shutdown may only be called once per LoggerProvider`),this._shutdownOnce.promise):this._shutdownOnce.call()}_shutdown(){return this._sharedState.activeProcessor.shutdown()}}})),hR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ConsoleLogRecordExporter=void 0;let t=HL();e.ConsoleLogRecordExporter=class{export(e,t){this._sendLogRecords(e,t)}shutdown(){return Promise.resolve()}_exportInfo(e){return{resource:{attributes:e.resource.attributes},instrumentationScope:e.instrumentationScope,timestamp:(0,t.hrTimeToMicroseconds)(e.hrTime),traceId:e.spanContext?.traceId,spanId:e.spanContext?.spanId,traceFlags:e.spanContext?.traceFlags,severityText:e.severityText,severityNumber:e.severityNumber,body:e.body,attributes:e.attributes}}_sendLogRecords(e,n){for(let t of e)console.dir(this._exportInfo(t),{depth:3});n?.({code:t.ExportResultCode.SUCCESS})}}})),see=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.SimpleLogRecordProcessor=void 0;let t=HL();e.SimpleLogRecordProcessor=class{_exporter;_shutdownOnce;_unresolvedExports;constructor(e){this._exporter=e,this._shutdownOnce=new t.BindOnceFuture(this._shutdown,this),this._unresolvedExports=new Set}onEmit(e){if(this._shutdownOnce.isCalled)return;let n=()=>t.internal._export(this._exporter,[e]).then(e=>{e.code!==t.ExportResultCode.SUCCESS&&(0,t.globalErrorHandler)(e.error??Error(`SimpleLogRecordProcessor: log record export failed (status ${e})`))}).catch(t.globalErrorHandler);if(e.resource.asyncAttributesPending){let r=e.resource.waitForAsyncAttributes?.().then(()=>(this._unresolvedExports.delete(r),n()),t.globalErrorHandler);r!=null&&this._unresolvedExports.add(r)}else n()}async forceFlush(){await Promise.all(Array.from(this._unresolvedExports))}shutdown(){return this._shutdownOnce.call()}_shutdown(){return this._exporter.shutdown()}}})),gR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.InMemoryLogRecordExporter=void 0;let t=HL();e.InMemoryLogRecordExporter=class{_finishedLogRecords=[];_stopped=!1;export(e,n){if(this._stopped)return n({code:t.ExportResultCode.FAILED,error:Error(`Exporter has been stopped`)});this._finishedLogRecords.push(...e),n({code:t.ExportResultCode.SUCCESS})}shutdown(){return this._stopped=!0,this.reset(),Promise.resolve()}getFinishedLogRecords(){return this._finishedLogRecords}reset(){this._finishedLogRecords=[]}}})),cee=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BatchLogRecordProcessorBase=void 0;let t=(Jd(),d(Kd)),n=HL();e.BatchLogRecordProcessorBase=class{_exporter;_maxExportBatchSize;_maxQueueSize;_scheduledDelayMillis;_exportTimeoutMillis;_finishedLogRecords=[];_timer;_shutdownOnce;constructor(e,r){this._exporter=e,this._maxExportBatchSize=r?.maxExportBatchSize??(0,n.getNumberFromEnv)(`OTEL_BLRP_MAX_EXPORT_BATCH_SIZE`)??512,this._maxQueueSize=r?.maxQueueSize??(0,n.getNumberFromEnv)(`OTEL_BLRP_MAX_QUEUE_SIZE`)??2048,this._scheduledDelayMillis=r?.scheduledDelayMillis??(0,n.getNumberFromEnv)(`OTEL_BLRP_SCHEDULE_DELAY`)??5e3,this._exportTimeoutMillis=r?.exportTimeoutMillis??(0,n.getNumberFromEnv)(`OTEL_BLRP_EXPORT_TIMEOUT`)??3e4,this._shutdownOnce=new n.BindOnceFuture(this._shutdown,this),this._maxExportBatchSize>this._maxQueueSize&&(t.diag.warn(`BatchLogRecordProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize`),this._maxExportBatchSize=this._maxQueueSize)}onEmit(e){this._shutdownOnce.isCalled||this._addToBuffer(e)}forceFlush(){return this._shutdownOnce.isCalled?this._shutdownOnce.promise:this._flushAll()}shutdown(){return this._shutdownOnce.call()}async _shutdown(){this.onShutdown(),await this._flushAll(),await this._exporter.shutdown()}_addToBuffer(e){this._finishedLogRecords.length>=this._maxQueueSize||(this._finishedLogRecords.push(e),this._maybeStartTimer())}_flushAll(){return new Promise((e,t)=>{let n=[],r=Math.ceil(this._finishedLogRecords.length/this._maxExportBatchSize);for(let e=0;e<r;e++)n.push(this._flushOneBatch());Promise.all(n).then(()=>{e()}).catch(t)})}_flushOneBatch(){return this._clearTimer(),this._finishedLogRecords.length===0?Promise.resolve():new Promise((e,t)=>{(0,n.callWithTimeout)(this._export(this._finishedLogRecords.splice(0,this._maxExportBatchSize)),this._exportTimeoutMillis).then(()=>e()).catch(t)})}_maybeStartTimer(){this._timer===void 0&&(this._timer=setTimeout(()=>{this._flushOneBatch().then(()=>{this._finishedLogRecords.length>0&&(this._clearTimer(),this._maybeStartTimer())}).catch(e=>{(0,n.globalErrorHandler)(e)})},this._scheduledDelayMillis),(0,n.unrefTimer)(this._timer))}_clearTimer(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)}_export(e){let t=()=>n.internal._export(this._exporter,e).then(e=>{e.code!==n.ExportResultCode.SUCCESS&&(0,n.globalErrorHandler)(e.error??Error(`BatchLogRecordProcessor: log record export failed (status ${e})`))}).catch(n.globalErrorHandler),r=e.map(e=>e.resource).filter(e=>e.asyncAttributesPending);return r.length===0?t():Promise.all(r.map(e=>e.waitForAsyncAttributes?.())).then(t,n.globalErrorHandler)}}})),lee=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BatchLogRecordProcessor=void 0;let t=cee();e.BatchLogRecordProcessor=class extends t.BatchLogRecordProcessorBase{onShutdown(){}}})),_R=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BatchLogRecordProcessor=void 0;var t=lee();Object.defineProperty(e,`BatchLogRecordProcessor`,{enumerable:!0,get:function(){return t.BatchLogRecordProcessor}})})),vR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BatchLogRecordProcessor=void 0;var t=_R();Object.defineProperty(e,`BatchLogRecordProcessor`,{enumerable:!0,get:function(){return t.BatchLogRecordProcessor}})})),yR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BatchLogRecordProcessor=e.InMemoryLogRecordExporter=e.SimpleLogRecordProcessor=e.ConsoleLogRecordExporter=e.NoopLogRecordProcessor=e.LoggerProvider=void 0;var t=mR();Object.defineProperty(e,`LoggerProvider`,{enumerable:!0,get:function(){return t.LoggerProvider}});var n=dR();Object.defineProperty(e,`NoopLogRecordProcessor`,{enumerable:!0,get:function(){return n.NoopLogRecordProcessor}});var r=hR();Object.defineProperty(e,`ConsoleLogRecordExporter`,{enumerable:!0,get:function(){return r.ConsoleLogRecordExporter}});var i=see();Object.defineProperty(e,`SimpleLogRecordProcessor`,{enumerable:!0,get:function(){return i.SimpleLogRecordProcessor}});var a=gR();Object.defineProperty(e,`InMemoryLogRecordExporter`,{enumerable:!0,get:function(){return a.InMemoryLogRecordExporter}});var o=vR();Object.defineProperty(e,`BatchLogRecordProcessor`,{enumerable:!0,get:function(){return o.BatchLogRecordProcessor}})})),bR=s((e=>{let t=ur(),n=t.__toESM(Ei()),r=t.__toESM(require(`node:async_hooks`)),i=t.__toESM(ie()),a=t.__toESM(Li()),o=t.__toESM(Fc()),s=t.__toESM(require(`node:process`)),c=t.__toESM(require(`node:os`)),l=t.__toESM(require(`node:tty`)),u=t.__toESM(require(`node:crypto`)),f=t.__toESM(uL()),p=t.__toESM(bj()),m=t.__toESM(yR()),h=t.__toESM((PA(),d(NA))),g={DELETE:`delete`,COMMENT_OUT:`comment out`,KEEP:`keep`,SKIP:`skip`},_={GREEN:`Green`,GREY:`Grey`,RED:`Red`,NA:`NA`},v={GREEN:`Green`,GREY:`Grey`,RUNTIME_ERROR:`RuntimeError`},y=function(e){return e.IDE=`IDE`,e.CLI=`CLI`,e}({}),b=function(e){return e.SIBLING_FOLDER=`siblingFolder`,e.ROOT_FOLDER=`rootFolder`,e}({}),x=function(e){return e.JEST=`jest`,e.MOCHA=`mocha`,e.VITEST=`vitest`,e.PYTEST=`pytest`,e}({}),S=function(e){return e.SPEC=`spec`,e.TEST=`test`,e}({}),C=function(e){return e.CAMEL_CASE=`camelCase`,e.KEBAB_CASE=`kebabCase`,e}({}),w=function(e){return e.NONE=`none`,e.CATEGORIES=`categories`,e}({}),T=function(e){return e.NEW_CODE_FILE=`newCodeFile`,e.OVERRIDE_CODE_FILE=`overrideCodeFile`,e}({}),E=function(e){return e.ON=`on`,e.OFF=`off`,e}({}),D={DEFAULT:0,MIN:0,MAX:100},O={DEFAULT:5,MIN:1,MAX:50};n.z.object({rootPath:n.z.string().default(process.cwd()),testStructure:n.z.enum(b).optional(),testFramework:n.z.enum(x).optional(),testSuffix:n.z.enum(S).optional(),testFileName:n.z.enum(C).optional(),calculateCoverage:n.z.enum(E).optional(),coverageThreshold:n.z.number().min(D.MIN).max(D.MAX).default(D.DEFAULT),requestSource:n.z.enum(y).optional(),concurrency:n.z.number().min(O.MIN).max(O.MAX).default(O.DEFAULT),backendURL:n.z.string().optional(),secretToken:n.z.string().optional(),modelName:n.z.string().optional(),context:n.z.object({git:n.z.object({ref_name:n.z.string(),anchorBranch:n.z.string(),compareBranch:n.z.string(),repository:n.z.string(),owner:n.z.string(),sha:n.z.string(),workflowRunId:n.z.string(),remoteUrl:n.z.string(),topLevel:n.z.string()}).partial().optional()}).optional(),testCommand:n.z.string().optional(),coverageCommand:n.z.string().optional(),lintCommand:n.z.string().optional(),prettierCommand:n.z.string().optional(),disableLintRules:n.z.boolean().optional(),ignoreAsAnyLintErrors:n.z.boolean().optional(),includeEarlyTests:n.z.boolean().optional(),greyTestBehaviour:n.z.enum(g).optional(),redTestBehaviour:n.z.enum(g).optional(),keepErrorTests:n.z.boolean().optional(),keepFailedTests:n.z.boolean().optional(),conditionalKeep:n.z.boolean().optional(),continueOnTestErrors:n.z.boolean().optional(),perFunctionTimeout:n.z.number().positive().optional(),dynamicPromptIterations:n.z.number().min(0).max(10).optional(),removeComments:n.z.boolean().optional(),experimentalAgentSdk:n.z.boolean().optional(),compressOutput:n.z.boolean().optional(),agentSdkModel:n.z.string().optional(),agentSdkBudget:n.z.number().positive().optional(),pluginPath:n.z.string().optional(),claudeCodeExecutablePath:n.z.string().optional(),catalogId:n.z.string().optional(),label:n.z.string().optional(),debug:n.z.boolean().optional(),verbose:n.z.boolean().optional(),progressLogger:n.z.custom().optional(),onTokenRefresh:n.z.custom().optional()});var k=`@earlyai/ts-agent`,A=`0.97.0`;let ee={VSCODE:`vscode`,GITHUB_ACTION:`github-action`,UNKNOWN:`unknown`},j=`$early_filename`,te=`npx jest ${j} --no-coverage --silent --json --forceExit --maxWorkers=1`,M=`npx --no eslint ${j}`,N=`npx --no prettier ${j} --write`,P={rootPath:process.cwd(),isSiblingFolderStructured:!0,gitURL:`https://github.com/your-owner/your-repo`,testFramework:x.JEST,greyTestBehaviour:g.DELETE,redTestBehaviour:g.DELETE,keepErrorTests:!1,keepFailedTests:!1,conditionalKeep:!1,continueOnTestErrors:!0,generatedTestStructure:w.CATEGORIES,isRootFolderStructured:!1,clientSource:ee.GITHUB_ACTION,backendURL:`https://api.startearly.ai`,requestSource:y.CLI,userPrompt:``,testLocation:`__tests__`,coverageThreshold:D.DEFAULT,concurrency:5,testFileFormat:`ts`,outputType:T.NEW_CODE_FILE,shouldRefreshCoverage:!0,kebabCaseFileName:!1,earlyTestFilenameSuffix:`.early.${S.TEST}`,testSuffix:S.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:M,prettierCommand:N,disableLintRules:!1,ignoreAsAnyLintErrors:!0,allowUndefinedLintErrors:!0,perFunctionTimeout:42e4,removeComments:!0,experimentalAgentSdk:!1,compressOutput:!1,agentSdkModel:void 0,agentSdkBudget:void 0,debug:!1,verbose:!1},F=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.compressOutput.agentSdkModel.agentSdkBudget.pluginPath.claudeCodeExecutablePath.label.catalogId.debug.verbose.progressLogger.onTokenRefresh`.split(`.`).reduce((t,n)=>(0,i.isDefined)(e[n])?{...t,[n]:e[n]}:t,{}),n={...(0,i.isDefined)(e.testStructure)&&{isSiblingFolderStructured:e.testStructure===b.SIBLING_FOLDER,isRootFolderStructured:e.testStructure===b.ROOT_FOLDER},...(0,i.isDefined)(e.testFileName)&&{kebabCaseFileName:e.testFileName===C.KEBAB_CASE},...(0,i.isDefined)(e.calculateCoverage)&&{shouldRefreshCoverage:e.calculateCoverage===E.ON},...(0,i.isDefined)(e.modelName)&&{fixTestsLLMModelName:e.modelName,generateTestsLLMModelName:e.modelName},...(0,i.isDefined)(e.testSuffix)&&{earlyTestFilenameSuffix:`.early.${e.testSuffix}`},...(0,i.isDefined)(e.requestSource)&&{clientSource:e.requestSource===y.IDE?ee.VSCODE:ee.GITHUB_ACTION}};return{...t,...n}},I=(e=0)=>t=>`\u001B[${t+e}m`,L=(e=0)=>t=>`\u001B[${38+e};5;${t}m`,ne=(e=0)=>(t,n,r)=>`\u001B[${38+e};2;${t};${n};${r}m`,R={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys(R.modifier);let z=Object.keys(R.color),re=Object.keys(R.bgColor);[...z,...re];function B(){let e=new Map;for(let[t,n]of Object.entries(R)){for(let[t,r]of Object.entries(n))R[t]={open:`\u001B[${r[0]}m`,close:`\u001B[${r[1]}m`},n[t]=R[t],e.set(r[0],r[1]);Object.defineProperty(R,t,{value:n,enumerable:!1})}return Object.defineProperty(R,`codes`,{value:e,enumerable:!1}),R.color.close=`\x1B[39m`,R.bgColor.close=`\x1B[49m`,R.color.ansi=I(),R.color.ansi256=L(),R.color.ansi16m=ne(),R.bgColor.ansi=I(10),R.bgColor.ansi256=L(10),R.bgColor.ansi16m=ne(10),Object.defineProperties(R,{rgbToAnsi256:{value(e,t,n){return e===t&&t===n?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(n/255*5)},enumerable:!1},hexToRgb:{value(e){let t=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!t)return[0,0,0];let[n]=t;n.length===3&&(n=[...n].map(e=>e+e).join(``));let r=Number.parseInt(n,16);return[r>>16&255,r>>8&255,r&255]},enumerable:!1},hexToAnsi256:{value:e=>R.rgbToAnsi256(...R.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return 90+(e-8);let t,n,r;if(e>=232)t=((e-232)*10+8)/255,n=t,r=t;else{e-=16;let i=e%36;t=Math.floor(e/36)/5,n=Math.floor(i/6)/5,r=i%6/5}let i=Math.max(t,n,r)*2;if(i===0)return 30;let a=30+(Math.round(r)<<2|Math.round(n)<<1|Math.round(t));return i===2&&(a+=60),a},enumerable:!1},rgbToAnsi:{value:(e,t,n)=>R.ansi256ToAnsi(R.rgbToAnsi256(e,t,n)),enumerable:!1},hexToAnsi:{value:e=>R.ansi256ToAnsi(R.hexToAnsi256(e)),enumerable:!1}}),R}var V=B();function ae(e,t=globalThis.Deno?globalThis.Deno.args:s.default.argv){let n=e.startsWith(`-`)?``:e.length===1?`-`:`--`,r=t.indexOf(n+e),i=t.indexOf(`--`);return r!==-1&&(i===-1||r<i)}let{env:oe}=s.default,se;ae(`no-color`)||ae(`no-colors`)||ae(`color=false`)||ae(`color=never`)?se=0:(ae(`color`)||ae(`colors`)||ae(`color=true`)||ae(`color=always`))&&(se=1);function ce(){if(`FORCE_COLOR`in oe)return oe.FORCE_COLOR===`true`?1:oe.FORCE_COLOR===`false`?0:oe.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(oe.FORCE_COLOR,10),3)}function le(e){return e===0?!1:{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function ue(e,{streamIsTTY:t,sniffFlags:n=!0}={}){let r=ce();r!==void 0&&(se=r);let i=n?se:r;if(i===0)return 0;if(n){if(ae(`color=16m`)||ae(`color=full`)||ae(`color=truecolor`))return 3;if(ae(`color=256`))return 2}if(`TF_BUILD`in oe&&`AGENT_NAME`in oe)return 1;if(e&&!t&&i===void 0)return 0;let a=i||0;if(oe.TERM===`dumb`)return a;if(s.default.platform===`win32`){let e=c.default.release().split(`.`);return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if(`CI`in oe)return[`GITHUB_ACTIONS`,`GITEA_ACTIONS`,`CIRCLECI`].some(e=>e in oe)?3:[`TRAVIS`,`APPVEYOR`,`GITLAB_CI`,`BUILDKITE`,`DRONE`].some(e=>e in oe)||oe.CI_NAME===`codeship`?1:a;if(`TEAMCITY_VERSION`in oe)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(oe.TEAMCITY_VERSION)?1:0;if(oe.COLORTERM===`truecolor`||oe.TERM===`xterm-kitty`||oe.TERM===`xterm-ghostty`||oe.TERM===`wezterm`)return 3;if(`TERM_PROGRAM`in oe){let e=Number.parseInt((oe.TERM_PROGRAM_VERSION||``).split(`.`)[0],10);switch(oe.TERM_PROGRAM){case`iTerm.app`:return e>=3?3:2;case`Apple_Terminal`:return 2}}return/-256(color)?$/i.test(oe.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(oe.TERM)||`COLORTERM`in oe?1:a}function de(e,t={}){return le(ue(e,{streamIsTTY:e&&e.isTTY,...t}))}var fe={stdout:de({isTTY:l.default.isatty(1)}),stderr:de({isTTY:l.default.isatty(2)})};function pe(e,t,n){let r=e.indexOf(t);if(r===-1)return e;let i=t.length,a=0,o=``;do o+=e.slice(a,r)+t+n,a=r+i,r=e.indexOf(t,a);while(r!==-1);return o+=e.slice(a),o}function me(e,t,n,r){let i=0,a=``;do{let o=e[r-1]===`\r`;a+=e.slice(i,o?r-1:r)+t+(o?`\r
|
|
119
119
|
`:`
|
|
120
120
|
`)+n,i=r+1,r=e.indexOf(`
|
|
121
121
|
`,i)}while(r!==-1);return a+=e.slice(i),a}let{stdout:he,stderr:ge}=fe,_e=Symbol(`GENERATOR`),ve=Symbol(`STYLER`),ye=Symbol(`IS_EMPTY`),be=[`ansi`,`ansi`,`ansi256`,`ansi16m`],xe=Object.create(null),Se=(e,t={})=>{if(t.level&&!(Number.isInteger(t.level)&&t.level>=0&&t.level<=3))throw Error("The `level` option should be an integer from 0 to 3");let n=he?he.level:0;e.level=t.level===void 0?n:t.level},Ce=e=>{let t=(...e)=>e.join(` `);return Se(t,e),Object.setPrototypeOf(t,we.prototype),t};function we(e){return Ce(e)}Object.setPrototypeOf(we.prototype,Function.prototype);for(let[e,t]of Object.entries(V))xe[e]={get(){let n=Oe(this,De(t.open,t.close,this[ve]),this[ye]);return Object.defineProperty(this,e,{value:n}),n}};xe.visible={get(){let e=Oe(this,this[ve],!0);return Object.defineProperty(this,`visible`,{value:e}),e}};let Te=(e,t,n,...r)=>e===`rgb`?t===`ansi16m`?V[n].ansi16m(...r):t===`ansi256`?V[n].ansi256(V.rgbToAnsi256(...r)):V[n].ansi(V.rgbToAnsi(...r)):e===`hex`?Te(`rgb`,t,n,...V.hexToRgb(...r)):V[n][e](...r);for(let e of[`rgb`,`hex`,`ansi256`]){xe[e]={get(){let{level:t}=this;return function(...n){let r=De(Te(e,be[t],`color`,...n),V.color.close,this[ve]);return Oe(this,r,this[ye])}}};let t=`bg`+e[0].toUpperCase()+e.slice(1);xe[t]={get(){let{level:t}=this;return function(...n){let r=De(Te(e,be[t],`bgColor`,...n),V.bgColor.close,this[ve]);return Oe(this,r,this[ye])}}}}let Ee=Object.defineProperties(()=>{},{...xe,level:{enumerable:!0,get(){return this[_e].level},set(e){this[_e].level=e}}}),De=(e,t,n)=>{let r,i;return n===void 0?(r=e,i=t):(r=n.openAll+e,i=t+n.closeAll),{open:e,close:t,openAll:r,closeAll:i,parent:n}},Oe=(e,t,n)=>{let r=(...e)=>ke(r,e.length===1?``+e[0]:e.join(` `));return Object.setPrototypeOf(r,Ee),r[_e]=e,r[ve]=t,r[ye]=n,r},ke=(e,t)=>{if(e.level<=0||!t)return e[ye]?``:t;let n=e[ve];if(n===void 0)return t;let{openAll:r,closeAll:i}=n;if(t.includes(`\x1B`))for(;n!==void 0;)t=pe(t,n.close,n.open),n=n.parent;let a=t.indexOf(`
|
|
122
|
-
`);return a!==-1&&(t=me(t,i,r,a)),r+t+i};Object.defineProperties(we.prototype,xe);let Ae=we();we({level:ge?ge.level:0});var je=Ae;let Me=()=>{},Ne={info:Me,verbose:Me,debug:Me},Pe=[je.cyan,je.magenta,je.green,je.blue,je.redBright,je.cyanBright,je.magentaBright,je.greenBright];function Fe(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.codePointAt(n)??0,t=Math.imul(t,16777619);return Pe[Math.abs(t)%Pe.length]}function Ie(e,t){let n=(0,i.isDefined)(t.parentName)?`${t.parentName}.${t.methodName}`:t.methodName,r=Fe(n)(`[${n}]`);return{info:(...t)=>e.info(r,...t),verbose:(...t)=>e.verbose(r,...t),debug:(...t)=>e.debug(r,...t)}}var Le=t.__commonJSMin(((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})),Re=t.__commonJSMin(((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})),ze=t.__toESM(Le()),Be=t.__toESM(Re()),Ve,H;let He=class{config;constructor(e,t={}){if(!(0,i.isDefined)(e)){this.config=P;return}let n=F(e);this.config=(0,i.merge)(P,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;shouldCompressOutput=()=>this.config.compressOutput;getAgentSdkModel=()=>this.config.agentSdkModel;getAgentSdkBudget=()=>this.config.agentSdkBudget;getPluginPath=()=>this.config.pluginPath;getLabel=()=>this.config.label;getCatalogId=()=>this.config.catalogId;updateContext=e=>{this.config.context=(0,i.merge)(this.config.context??{},e??{})};updateRootPath=e=>{this.config.rootPath=e};isDebug=()=>this.config.debug??!1;isVerbose=()=>this.config.verbose??!1;getOnTokenRefresh=()=>this.config.onTokenRefresh;getProgressLogger=e=>{let t=this.config.progressLogger??Ne;return(0,i.isDefined)(e)?Ie(t,e):t}};He=(0,Be.default)([(0,o.injectable)(`Singleton`),(0,ze.default)(`design:paramtypes`,[typeof(Ve=typeof Partial<`u`&&Partial)==`function`?Ve:Object,typeof(H=typeof Partial<`u`&&Partial)==`function`?H:Object])],He);var Ue=new o.Container({autobind:!0,defaultScope:`Singleton`});let We=()=>Ue.get(He);var Ge=class{storage=new r.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,i.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,i.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 Ke=function(e){return e.DEFAULT=`default`,e.VERBOSE=`verbose`,e.DEBUG=`debug`,e}({}),qe=function(e){return e.INFO=`info`,e.WARN=`warn`,e}({});function Je(){return(0,u.randomUUID)()}function Ye(){let e=``;for(let t=0;t<8;t++)e+=`abcdefghijklmnopqrstuvwxyz0123456789`.charAt(Math.floor(Math.random()*36));return e}var Xe=t.__toESM(Le()),Ze=t.__toESM(Re()),Qe=class{export(e,t){for(let t of e){let e=t.body;if((0,i.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 $e=class{loggerProvider;config;constructor(e){this.config=e,this.loggerProvider=new m.LoggerProvider({resource:(0,p.resourceFromAttributes)({[h.ATTR_SERVICE_NAME]:k,[h.ATTR_SERVICE_VERSION]:A})}),this.initializeExporters(),this.setGlobalLoggerProvider()}getLogger(e){return this.loggerProvider.getLogger(e)}initializeExporters(){let e=[];if(this.config.consoleEnabled){let t=new Qe;e.push(new m.SimpleLogRecordProcessor(t))}if(this.config.azureEnabled&&(0,i.isDefined)(this.config.azureConnectionString)){let t=new f.AzureMonitorLogExporter({connectionString:this.config.azureConnectionString});e.push(new m.BatchLogRecordProcessor(t))}this.loggerProvider=new m.LoggerProvider({processors:e})}setGlobalLoggerProvider(){a.logs.setGlobalLoggerProvider(this.loggerProvider)}};$e=(0,Ze.default)([(0,o.injectable)(),(0,Xe.default)(`design:paramtypes`,[Object])],$e),t.__toESM(Le()),t.__toESM(Re());let et=new class{storage;otelService;otelLogger;isConsoleEnabled;printBuffer;default=this.createLogObject(Ke.DEFAULT);verbose=this.createLogObject(Ke.VERBOSE);constructor(e){this.storage=new r.AsyncLocalStorage,this.otelService=new $e(e),this.otelLogger=this.otelService.getLogger(`ts-agent`),this.isConsoleEnabled=e.consoleEnabled,this.printBuffer=new Ge(e.consoleEnabled)}resetPrintOrder(){this.printBuffer.resetOrder()}async withBufferedPrinting(e,t){return this.printBuffer.withBufferedPrinting(e,t)}info={startLog:(e,...t)=>this.log(a.SeverityNumber.INFO,`Start ${e}`,...t),endLog:(e,...t)=>this.log(a.SeverityNumber.INFO,`End ${e}`,...t),failedLog:(e,...t)=>this.log(a.SeverityNumber.INFO,`Failed ${e}`,...t),defaultLog:(e,...t)=>this.log(a.SeverityNumber.INFO,e,...t)};debug={startLog:(e,...t)=>this.log(a.SeverityNumber.DEBUG,`Start ${e}`,...t),endLog:(e,...t)=>this.log(a.SeverityNumber.DEBUG,`End ${e}`,...t),failedLog:(e,...t)=>this.log(a.SeverityNumber.DEBUG,`Failed ${e}`,...t),defaultLog:(e,...t)=>this.log(a.SeverityNumber.DEBUG,e,...t)};error(e,t,...n){let r=t instanceof Error?`${e} ${t.message} ${t.stack}`:`${e} ${JSON.stringify(t)}`;this.log(a.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(Ke.DEBUG))&&console.info(r)}logToOpenTelemetry(e,t){let n=this.storage.getStore(),r={service:k,version:A};(0,i.isDefined)(n)&&((0,i.isDefined)(n.traceId)&&(r.traceId=n.traceId),(0,i.isDefined)(n.requestId)&&(r.requestId=n.requestId),(0,i.isDefined)(n.category)&&(r.category=n.category),(0,i.isDefined)(n.subCategory)&&(r.subCategory=n.subCategory),(0,i.isDefined)(n.testedMethodClass)&&(r.testedMethodClass=n.testedMethodClass),(0,i.isDefined)(n.testedFunction)&&(r.testedFunction=n.testedFunction),(0,i.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 a.SeverityNumber.TRACE:return`TRACE`;case a.SeverityNumber.DEBUG:return`DEBUG`;case a.SeverityNumber.INFO:return`INFO`;case a.SeverityNumber.WARN:return`WARN`;case a.SeverityNumber.ERROR:return`ERROR`;case a.SeverityNumber.FATAL:return`FATAL`;default:return`INFO`}}formatMessage(e,...t){let n=this.formatPrefix(),r=(0,i.isDefined)(n)?`${n} ${e}`:e;return this.formatPrint(r,...t)}formatPrint(e,...t){return(0,i.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:Ye(),requestId:Je()};return i.run(n,()=>r.apply(this,e))},n};addContext(e){let t=this.storage.getStore();(0,i.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:Je()}}:void 0}async runWithContext(e,t){return(0,i.isDefined)(e)?this.storage.run(e,t):t()}isLevelEnabled(e){switch(e){case Ke.DEFAULT:return!0;case Ke.VERBOSE:return We().isVerbose()||We().isDebug();case Ke.DEBUG:return We().isDebug()}}createLogObject(e){return{info:(t,...n)=>{this.isLevelEnabled(e)&&this.printOrBuffer(qe.INFO,this.formatPrint(t,...n))},warn:(t,...n)=>{this.isLevelEnabled(e)&&this.printOrBuffer(qe.WARN,this.formatPrint(t,...n))}}}printOrBuffer(e,t){this.printBuffer.printOrBuffer(e,t)}formatPrefix(){let e=this.storage.getStore();if(!(0,i.isDefined)(e))return``;let t=[];return(0,i.isDefined)(e.traceId)&&t.push(`[${e.traceId}]`),(0,i.isDefined)(e.requestId)&&t.push(`[${e.requestId}]`),(0,i.isDefined)(e.category)&&t.push(`[${e.category}]`),(0,i.isDefined)(e.subCategory)&&t.push(`[${e.subCategory}]`),(0,i.isDefined)(e.testedMethodClass)&&t.push(`[${e.testedMethodClass}]`),(0,i.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,i.isDefined)(e)&&et.addContext(e),et.withContext(t,n,r)}}let nt={type:`object`,additionalProperties:!1,required:[`flows`,`projectSummary`,`projectType`,`detectedEntryCount`],properties:{flows:{type:`array`,items:{type:`object`}},projectSummary:{type:`string`},projectType:{type:`string`},detectedEntryCount:{type:`number`}}},rt={type:`object`,additionalProperties:!1,required:[`sourceFiles`],properties:{sourceFiles:{type:`array`,items:{type:`string`}}}},it={type:`object`,additionalProperties:!1,required:[`techChanges`,`productChanges`],properties:{techChanges:{type:`array`,items:{type:`object`}},productChanges:{type:`array`,items:{type:`object`}},affectedSteps:{type:`array`,items:{type:`object`}}}},at={type:`object`,additionalProperties:!1,required:[`fileFlowMapping`],properties:{fileFlowMapping:{type:`array`,items:{type:`object`}}}},ot={type:`object`,additionalProperties:!1,required:[`calledModules`],properties:{calledModules:{type:`array`,items:{type:`string`}}}};Object.defineProperty(e,`CATALOG_OUTPUT_SCHEMA`,{enumerable:!0,get:function(){return nt}}),Object.defineProperty(e,`CONCURRENCY`,{enumerable:!0,get:function(){return O}}),Object.defineProperty(e,`COVERAGE_THRESHOLD`,{enumerable:!0,get:function(){return D}}),Object.defineProperty(e,`CalculateCoverageOption`,{enumerable:!0,get:function(){return E}}),Object.defineProperty(e,`DEFAULT_LINT_COMMAND`,{enumerable:!0,get:function(){return M}}),Object.defineProperty(e,`DEFAULT_PRETTIER_COMMAND`,{enumerable:!0,get:function(){return N}}),Object.defineProperty(e,`DEFAULT_TEST_COMMAND`,{enumerable:!0,get:function(){return te}}),Object.defineProperty(e,`DEPENDENCY_TRACER_OUTPUT_SCHEMA`,{enumerable:!0,get:function(){return ot}}),Object.defineProperty(e,`DESCRIBE_STATUS`,{enumerable:!0,get:function(){return v}}),Object.defineProperty(e,`EARLY_COVERAGE_DIR`,{enumerable:!0,get:function(){return`$early_coverage_dir`}}),Object.defineProperty(e,`EARLY_FILENAME_VAR`,{enumerable:!0,get:function(){return j}}),Object.defineProperty(e,`EARLY_TEST_FILES_VAR`,{enumerable:!0,get:function(){return`$early_test_files`}}),Object.defineProperty(e,`FILE_FLOW_MAPPING_OUTPUT_SCHEMA`,{enumerable:!0,get:function(){return at}}),Object.defineProperty(e,`GenerateTestsOutputType`,{enumerable:!0,get:function(){return T}}),Object.defineProperty(e,`GeneratedTestStructure`,{enumerable:!0,get:function(){return w}}),Object.defineProperty(e,`GlobalConfigService`,{enumerable:!0,get:function(){return He}}),Object.defineProperty(e,`NOOP_PROGRESS_LOGGER`,{enumerable:!0,get:function(){return Ne}}),Object.defineProperty(e,`PRE_FILTER_OUTPUT_SCHEMA`,{enumerable:!0,get:function(){return rt}}),Object.defineProperty(e,`REGRESSION_CATALOG_MAX_BUDGET_USD`,{enumerable:!0,get:function(){return 4}}),Object.defineProperty(e,`REGRESSION_CATALOG_MAX_TURNS`,{enumerable:!0,get:function(){return 100}}),Object.defineProperty(e,`REGRESSION_CATALOG_MODEL`,{enumerable:!0,get:function(){return`claude-sonnet-4-6`}}),Object.defineProperty(e,`REGRESSION_CATALOG_TARGET_COUNT`,{enumerable:!0,get:function(){return 20}}),Object.defineProperty(e,`REGRESSION_IMPACT_AGENTIC_MAX_BUDGET_USD`,{enumerable:!0,get:function(){return 2}}),Object.defineProperty(e,`REGRESSION_IMPACT_AGENTIC_MAX_TURNS`,{enumerable:!0,get:function(){return 30}}),Object.defineProperty(e,`REGRESSION_IMPACT_COMPARE_BRANCH`,{enumerable:!0,get:function(){return``}}),Object.defineProperty(e,`REGRESSION_IMPACT_DEEP_MAX_BUDGET_USD`,{enumerable:!0,get:function(){return 1}}),Object.defineProperty(e,`REGRESSION_IMPACT_DEEP_MAX_TURNS`,{enumerable:!0,get:function(){return 25}}),Object.defineProperty(e,`REGRESSION_IMPACT_DEEP_MODEL`,{enumerable:!0,get:function(){return`claude-sonnet-4-6`}}),Object.defineProperty(e,`REGRESSION_IMPACT_HAIKU_MODEL`,{enumerable:!0,get:function(){return`claude-haiku-4-5-20251001`}}),Object.defineProperty(e,`REGRESSION_IMPACT_MAPPING_BATCH_SIZE`,{enumerable:!0,get:function(){return 10}}),Object.defineProperty(e,`REGRESSION_IMPACT_MAPPING_CONCURRENCY`,{enumerable:!0,get:function(){return 5}}),Object.defineProperty(e,`REGRESSION_IMPACT_SONNET_MODEL`,{enumerable:!0,get:function(){return`claude-sonnet-4-6`}}),Object.defineProperty(e,`REGRESSION_LOG_COST`,{enumerable:!0,get:function(){return!1}}),Object.defineProperty(e,`REGRESSION_PERMISSION_MODE`,{enumerable:!0,get:function(){return`bypassPermissions`}}),Object.defineProperty(e,`REGRESSION_SAVE_REPORT_FILES`,{enumerable:!0,get:function(){return!1}}),Object.defineProperty(e,`REGRESSION_TRACER_CONCURRENCY`,{enumerable:!0,get:function(){return 5}}),Object.defineProperty(e,`REGRESSION_TRACER_ENABLED`,{enumerable:!0,get:function(){return!1}}),Object.defineProperty(e,`REGRESSION_TRACER_MAX_BUDGET_USD`,{enumerable:!0,get:function(){return .5}}),Object.defineProperty(e,`REGRESSION_TRACER_MAX_TURNS`,{enumerable:!0,get:function(){return 30}}),Object.defineProperty(e,`REGRESSION_TRACER_MODEL`,{enumerable:!0,get:function(){return`claude-haiku-4-5-20251001`}}),Object.defineProperty(e,`RequestSource`,{enumerable:!0,get:function(){return y}}),Object.defineProperty(e,`SONNET_DEEP_OUTPUT_SCHEMA`,{enumerable:!0,get:function(){return it}}),Object.defineProperty(e,`TEST_BEHAVIOR`,{enumerable:!0,get:function(){return g}}),Object.defineProperty(e,`TEST_STATUS`,{enumerable:!0,get:function(){return _}}),Object.defineProperty(e,`TestFileName`,{enumerable:!0,get:function(){return C}}),Object.defineProperty(e,`TestFramework`,{enumerable:!0,get:function(){return x}}),Object.defineProperty(e,`TestStructureVariant`,{enumerable:!0,get:function(){return b}}),Object.defineProperty(e,`TestSuffix`,{enumerable:!0,get:function(){return S}}),Object.defineProperty(e,`WithLoggerContext`,{enumerable:!0,get:function(){return tt}}),Object.defineProperty(e,`getGlobalConfig`,{enumerable:!0,get:function(){return We}}),Object.defineProperty(e,`inversify_default`,{enumerable:!0,get:function(){return Ue}}),Object.defineProperty(e,`logger`,{enumerable:!0,get:function(){return et}}),Object.defineProperty(e,`require_decorate`,{enumerable:!0,get:function(){return Re}}),Object.defineProperty(e,`require_decorateMetadata`,{enumerable:!0,get:function(){return Le}}),Object.defineProperty(e,`version`,{enumerable:!0,get:function(){return A}})})),xR=s((e=>{ur().__toESM(require(`@anthropic-ai/claude-agent-sdk`));function t(e){return e.hook_event_name===`PreToolUse`}function n(e){return e.hook_event_name===`PostToolUse`}function r(e){return e.type===`result`}function i(e){return e.subtype!==`success`}function a(e){let t=e.tool_input?.file_path;return typeof t==`string`?t:``}function o(e){let t=e.tool_input?.command;return typeof t==`string`?t:``}let s=/(\u009B|\u001B\[)[0-?]*[ -/]*[@-~]/g;function c(e){return e.replaceAll(s,``)}function l(e){let t=e;return c(((t.stdout??``)+(t.stderr??``)).trim())}function u(e){let t=e;return Array.isArray(t.message?.content)?t.message.content:void 0}function d(e){return e}Object.defineProperty(e,`getExecOutput`,{enumerable:!0,get:function(){return l}}),Object.defineProperty(e,`getMessageContentBlocks`,{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,`getSystemInitData`,{enumerable:!0,get:function(){return d}}),Object.defineProperty(e,`getToolInputCommand`,{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,`getToolInputFilePath`,{enumerable:!0,get:function(){return a}}),Object.defineProperty(e,`isErrorResult`,{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,`isPostToolUseInput`,{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,`isPreToolUseInput`,{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,`isResultMessage`,{enumerable:!0,get:function(){return r}}),Object.defineProperty(e,`stripAnsi`,{enumerable:!0,get:function(){return c}})})),SR=s((e=>{function t(e){return`You are a senior software engineer mapping changed files to the critical flows they affect by tracing import chains. The project type is: ${e}.
|
|
122
|
+
`);return a!==-1&&(t=me(t,i,r,a)),r+t+i};Object.defineProperties(we.prototype,xe);let Ae=we();we({level:ge?ge.level:0});var je=Ae;let Me=()=>{},Ne={info:Me,verbose:Me,debug:Me},Pe=[je.cyan,je.magenta,je.green,je.blue,je.redBright,je.cyanBright,je.magentaBright,je.greenBright];function Fe(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.codePointAt(n)??0,t=Math.imul(t,16777619);return Pe[Math.abs(t)%Pe.length]}function Ie(e,t){let n=(0,i.isDefined)(t.parentName)?`${t.parentName}.${t.methodName}`:t.methodName,r=Fe(n)(`[${n}]`);return{info:(...t)=>e.info(r,...t),verbose:(...t)=>e.verbose(r,...t),debug:(...t)=>e.debug(r,...t)}}var Le=t.__commonJSMin(((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})),Re=t.__commonJSMin(((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})),ze=t.__toESM(Le()),Be=t.__toESM(Re()),Ve,H;let He=class{config;constructor(e,t={}){if(!(0,i.isDefined)(e)){this.config=P;return}let n=F(e);this.config=(0,i.merge)(P,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;shouldCompressOutput=()=>this.config.compressOutput;getAgentSdkModel=()=>this.config.agentSdkModel;getAgentSdkBudget=()=>this.config.agentSdkBudget;getPluginPath=()=>this.config.pluginPath;getClaudeCodeExecutablePath=()=>this.config.claudeCodeExecutablePath;getLabel=()=>this.config.label;getCatalogId=()=>this.config.catalogId;updateContext=e=>{this.config.context=(0,i.merge)(this.config.context??{},e??{})};updateRootPath=e=>{this.config.rootPath=e};isDebug=()=>this.config.debug??!1;isVerbose=()=>this.config.verbose??!1;getOnTokenRefresh=()=>this.config.onTokenRefresh;getProgressLogger=e=>{let t=this.config.progressLogger??Ne;return(0,i.isDefined)(e)?Ie(t,e):t}};He=(0,Be.default)([(0,o.injectable)(`Singleton`),(0,ze.default)(`design:paramtypes`,[typeof(Ve=typeof Partial<`u`&&Partial)==`function`?Ve:Object,typeof(H=typeof Partial<`u`&&Partial)==`function`?H:Object])],He);var Ue=new o.Container({autobind:!0,defaultScope:`Singleton`});let We=()=>Ue.get(He);var Ge=class{storage=new r.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,i.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,i.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 Ke=function(e){return e.DEFAULT=`default`,e.VERBOSE=`verbose`,e.DEBUG=`debug`,e}({}),qe=function(e){return e.INFO=`info`,e.WARN=`warn`,e}({});function Je(){return(0,u.randomUUID)()}function Ye(){let e=``;for(let t=0;t<8;t++)e+=`abcdefghijklmnopqrstuvwxyz0123456789`.charAt(Math.floor(Math.random()*36));return e}var Xe=t.__toESM(Le()),Ze=t.__toESM(Re()),Qe=class{export(e,t){for(let t of e){let e=t.body;if((0,i.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 $e=class{loggerProvider;config;constructor(e){this.config=e,this.loggerProvider=new m.LoggerProvider({resource:(0,p.resourceFromAttributes)({[h.ATTR_SERVICE_NAME]:k,[h.ATTR_SERVICE_VERSION]:A})}),this.initializeExporters(),this.setGlobalLoggerProvider()}getLogger(e){return this.loggerProvider.getLogger(e)}initializeExporters(){let e=[];if(this.config.consoleEnabled){let t=new Qe;e.push(new m.SimpleLogRecordProcessor(t))}if(this.config.azureEnabled&&(0,i.isDefined)(this.config.azureConnectionString)){let t=new f.AzureMonitorLogExporter({connectionString:this.config.azureConnectionString});e.push(new m.BatchLogRecordProcessor(t))}this.loggerProvider=new m.LoggerProvider({processors:e})}setGlobalLoggerProvider(){a.logs.setGlobalLoggerProvider(this.loggerProvider)}};$e=(0,Ze.default)([(0,o.injectable)(),(0,Xe.default)(`design:paramtypes`,[Object])],$e),t.__toESM(Le()),t.__toESM(Re());let et=new class{storage;otelService;otelLogger;isConsoleEnabled;printBuffer;default=this.createLogObject(Ke.DEFAULT);verbose=this.createLogObject(Ke.VERBOSE);constructor(e){this.storage=new r.AsyncLocalStorage,this.otelService=new $e(e),this.otelLogger=this.otelService.getLogger(`ts-agent`),this.isConsoleEnabled=e.consoleEnabled,this.printBuffer=new Ge(e.consoleEnabled)}resetPrintOrder(){this.printBuffer.resetOrder()}async withBufferedPrinting(e,t){return this.printBuffer.withBufferedPrinting(e,t)}info={startLog:(e,...t)=>this.log(a.SeverityNumber.INFO,`Start ${e}`,...t),endLog:(e,...t)=>this.log(a.SeverityNumber.INFO,`End ${e}`,...t),failedLog:(e,...t)=>this.log(a.SeverityNumber.INFO,`Failed ${e}`,...t),defaultLog:(e,...t)=>this.log(a.SeverityNumber.INFO,e,...t)};debug={startLog:(e,...t)=>this.log(a.SeverityNumber.DEBUG,`Start ${e}`,...t),endLog:(e,...t)=>this.log(a.SeverityNumber.DEBUG,`End ${e}`,...t),failedLog:(e,...t)=>this.log(a.SeverityNumber.DEBUG,`Failed ${e}`,...t),defaultLog:(e,...t)=>this.log(a.SeverityNumber.DEBUG,e,...t)};error(e,t,...n){let r=t instanceof Error?`${e} ${t.message} ${t.stack}`:`${e} ${JSON.stringify(t)}`;this.log(a.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(Ke.DEBUG))&&console.info(r)}logToOpenTelemetry(e,t){let n=this.storage.getStore(),r={service:k,version:A};(0,i.isDefined)(n)&&((0,i.isDefined)(n.traceId)&&(r.traceId=n.traceId),(0,i.isDefined)(n.requestId)&&(r.requestId=n.requestId),(0,i.isDefined)(n.category)&&(r.category=n.category),(0,i.isDefined)(n.subCategory)&&(r.subCategory=n.subCategory),(0,i.isDefined)(n.testedMethodClass)&&(r.testedMethodClass=n.testedMethodClass),(0,i.isDefined)(n.testedFunction)&&(r.testedFunction=n.testedFunction),(0,i.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 a.SeverityNumber.TRACE:return`TRACE`;case a.SeverityNumber.DEBUG:return`DEBUG`;case a.SeverityNumber.INFO:return`INFO`;case a.SeverityNumber.WARN:return`WARN`;case a.SeverityNumber.ERROR:return`ERROR`;case a.SeverityNumber.FATAL:return`FATAL`;default:return`INFO`}}formatMessage(e,...t){let n=this.formatPrefix(),r=(0,i.isDefined)(n)?`${n} ${e}`:e;return this.formatPrint(r,...t)}formatPrint(e,...t){return(0,i.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:Ye(),requestId:Je()};return i.run(n,()=>r.apply(this,e))},n};addContext(e){let t=this.storage.getStore();(0,i.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:Je()}}:void 0}async runWithContext(e,t){return(0,i.isDefined)(e)?this.storage.run(e,t):t()}isLevelEnabled(e){switch(e){case Ke.DEFAULT:return!0;case Ke.VERBOSE:return We().isVerbose()||We().isDebug();case Ke.DEBUG:return We().isDebug()}}createLogObject(e){return{info:(t,...n)=>{this.isLevelEnabled(e)&&this.printOrBuffer(qe.INFO,this.formatPrint(t,...n))},warn:(t,...n)=>{this.isLevelEnabled(e)&&this.printOrBuffer(qe.WARN,this.formatPrint(t,...n))}}}printOrBuffer(e,t){this.printBuffer.printOrBuffer(e,t)}formatPrefix(){let e=this.storage.getStore();if(!(0,i.isDefined)(e))return``;let t=[];return(0,i.isDefined)(e.traceId)&&t.push(`[${e.traceId}]`),(0,i.isDefined)(e.requestId)&&t.push(`[${e.requestId}]`),(0,i.isDefined)(e.category)&&t.push(`[${e.category}]`),(0,i.isDefined)(e.subCategory)&&t.push(`[${e.subCategory}]`),(0,i.isDefined)(e.testedMethodClass)&&t.push(`[${e.testedMethodClass}]`),(0,i.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,i.isDefined)(e)&&et.addContext(e),et.withContext(t,n,r)}}let nt={type:`object`,additionalProperties:!1,required:[`flows`,`projectSummary`,`projectType`,`detectedEntryCount`],properties:{flows:{type:`array`,items:{type:`object`}},projectSummary:{type:`string`},projectType:{type:`string`},detectedEntryCount:{type:`number`}}},rt={type:`object`,additionalProperties:!1,required:[`sourceFiles`],properties:{sourceFiles:{type:`array`,items:{type:`string`}}}},it={type:`object`,additionalProperties:!1,required:[`techChanges`,`productChanges`],properties:{techChanges:{type:`array`,items:{type:`object`}},productChanges:{type:`array`,items:{type:`object`}},affectedSteps:{type:`array`,items:{type:`object`}}}},at={type:`object`,additionalProperties:!1,required:[`fileFlowMapping`],properties:{fileFlowMapping:{type:`array`,items:{type:`object`}}}},ot={type:`object`,additionalProperties:!1,required:[`score`,`reasoning`],properties:{score:{type:`integer`,minimum:1,maximum:10},reasoning:{type:`string`},criticalOverride:{type:`boolean`},signalsThatFired:{type:`object`,properties:{bug:{type:`array`,items:{type:`integer`}},intentional:{type:`array`,items:{type:`integer`}}}},changeFromOriginal:{type:`object`,properties:{changed:{type:`boolean`},delta:{type:`integer`},reason:{type:`string`}}}}},st={type:`object`,additionalProperties:!1,required:[`calledModules`],properties:{calledModules:{type:`array`,items:{type:`string`}}}};Object.defineProperty(e,`CATALOG_OUTPUT_SCHEMA`,{enumerable:!0,get:function(){return nt}}),Object.defineProperty(e,`CONCURRENCY`,{enumerable:!0,get:function(){return O}}),Object.defineProperty(e,`COVERAGE_THRESHOLD`,{enumerable:!0,get:function(){return D}}),Object.defineProperty(e,`CalculateCoverageOption`,{enumerable:!0,get:function(){return E}}),Object.defineProperty(e,`DEFAULT_LINT_COMMAND`,{enumerable:!0,get:function(){return M}}),Object.defineProperty(e,`DEFAULT_PRETTIER_COMMAND`,{enumerable:!0,get:function(){return N}}),Object.defineProperty(e,`DEFAULT_TEST_COMMAND`,{enumerable:!0,get:function(){return te}}),Object.defineProperty(e,`DEPENDENCY_TRACER_OUTPUT_SCHEMA`,{enumerable:!0,get:function(){return st}}),Object.defineProperty(e,`DESCRIBE_STATUS`,{enumerable:!0,get:function(){return v}}),Object.defineProperty(e,`EARLY_COVERAGE_DIR`,{enumerable:!0,get:function(){return`$early_coverage_dir`}}),Object.defineProperty(e,`EARLY_FILENAME_VAR`,{enumerable:!0,get:function(){return j}}),Object.defineProperty(e,`EARLY_TEST_FILES_VAR`,{enumerable:!0,get:function(){return`$early_test_files`}}),Object.defineProperty(e,`FILE_FLOW_MAPPING_OUTPUT_SCHEMA`,{enumerable:!0,get:function(){return at}}),Object.defineProperty(e,`GenerateTestsOutputType`,{enumerable:!0,get:function(){return T}}),Object.defineProperty(e,`GeneratedTestStructure`,{enumerable:!0,get:function(){return w}}),Object.defineProperty(e,`GlobalConfigService`,{enumerable:!0,get:function(){return He}}),Object.defineProperty(e,`NOOP_PROGRESS_LOGGER`,{enumerable:!0,get:function(){return Ne}}),Object.defineProperty(e,`PRE_FILTER_OUTPUT_SCHEMA`,{enumerable:!0,get:function(){return rt}}),Object.defineProperty(e,`REGRESSION_CATALOG_MAX_BUDGET_USD`,{enumerable:!0,get:function(){return 4}}),Object.defineProperty(e,`REGRESSION_CATALOG_MAX_TURNS`,{enumerable:!0,get:function(){return 100}}),Object.defineProperty(e,`REGRESSION_CATALOG_MODEL`,{enumerable:!0,get:function(){return`claude-sonnet-4-6`}}),Object.defineProperty(e,`REGRESSION_CATALOG_TARGET_COUNT`,{enumerable:!0,get:function(){return 20}}),Object.defineProperty(e,`REGRESSION_IMPACT_AGENTIC_MAX_BUDGET_USD`,{enumerable:!0,get:function(){return 2}}),Object.defineProperty(e,`REGRESSION_IMPACT_AGENTIC_MAX_TURNS`,{enumerable:!0,get:function(){return 30}}),Object.defineProperty(e,`REGRESSION_IMPACT_CALIBRATION_ENABLED`,{enumerable:!0,get:function(){return!1}}),Object.defineProperty(e,`REGRESSION_IMPACT_CALIBRATION_RANGE_MAX`,{enumerable:!0,get:function(){return 8}}),Object.defineProperty(e,`REGRESSION_IMPACT_CALIBRATION_RANGE_MIN`,{enumerable:!0,get:function(){return 5}}),Object.defineProperty(e,`REGRESSION_IMPACT_CALIBRATOR_CONCURRENCY`,{enumerable:!0,get:function(){return 8}}),Object.defineProperty(e,`REGRESSION_IMPACT_CALIBRATOR_MAX_BUDGET_USD`,{enumerable:!0,get:function(){return .3}}),Object.defineProperty(e,`REGRESSION_IMPACT_CALIBRATOR_MAX_TURNS`,{enumerable:!0,get:function(){return 5}}),Object.defineProperty(e,`REGRESSION_IMPACT_CALIBRATOR_MODEL`,{enumerable:!0,get:function(){return`claude-sonnet-4-6`}}),Object.defineProperty(e,`REGRESSION_IMPACT_DEEP_MAX_BUDGET_USD`,{enumerable:!0,get:function(){return 1}}),Object.defineProperty(e,`REGRESSION_IMPACT_DEEP_MAX_TURNS`,{enumerable:!0,get:function(){return 25}}),Object.defineProperty(e,`REGRESSION_IMPACT_DEEP_MODEL`,{enumerable:!0,get:function(){return`claude-sonnet-4-6`}}),Object.defineProperty(e,`REGRESSION_IMPACT_HAIKU_MODEL`,{enumerable:!0,get:function(){return`claude-haiku-4-5-20251001`}}),Object.defineProperty(e,`REGRESSION_IMPACT_MAPPING_BATCH_SIZE`,{enumerable:!0,get:function(){return 10}}),Object.defineProperty(e,`REGRESSION_IMPACT_MAPPING_CONCURRENCY`,{enumerable:!0,get:function(){return 5}}),Object.defineProperty(e,`REGRESSION_IMPACT_SONNET_MODEL`,{enumerable:!0,get:function(){return`claude-sonnet-4-6`}}),Object.defineProperty(e,`REGRESSION_LOG_COST`,{enumerable:!0,get:function(){return!1}}),Object.defineProperty(e,`REGRESSION_PERMISSION_MODE`,{enumerable:!0,get:function(){return`bypassPermissions`}}),Object.defineProperty(e,`REGRESSION_SAVE_REPORT_FILES`,{enumerable:!0,get:function(){return!1}}),Object.defineProperty(e,`REGRESSION_TRACER_CONCURRENCY`,{enumerable:!0,get:function(){return 5}}),Object.defineProperty(e,`REGRESSION_TRACER_ENABLED`,{enumerable:!0,get:function(){return!1}}),Object.defineProperty(e,`REGRESSION_TRACER_MAX_BUDGET_USD`,{enumerable:!0,get:function(){return .5}}),Object.defineProperty(e,`REGRESSION_TRACER_MAX_TURNS`,{enumerable:!0,get:function(){return 30}}),Object.defineProperty(e,`REGRESSION_TRACER_MODEL`,{enumerable:!0,get:function(){return`claude-haiku-4-5-20251001`}}),Object.defineProperty(e,`RequestSource`,{enumerable:!0,get:function(){return y}}),Object.defineProperty(e,`SONNET_DEEP_OUTPUT_SCHEMA`,{enumerable:!0,get:function(){return it}}),Object.defineProperty(e,`TEST_BEHAVIOR`,{enumerable:!0,get:function(){return g}}),Object.defineProperty(e,`TEST_STATUS`,{enumerable:!0,get:function(){return _}}),Object.defineProperty(e,`TestFileName`,{enumerable:!0,get:function(){return C}}),Object.defineProperty(e,`TestFramework`,{enumerable:!0,get:function(){return x}}),Object.defineProperty(e,`TestStructureVariant`,{enumerable:!0,get:function(){return b}}),Object.defineProperty(e,`TestSuffix`,{enumerable:!0,get:function(){return S}}),Object.defineProperty(e,`VERDICT_CALIBRATOR_OUTPUT_SCHEMA`,{enumerable:!0,get:function(){return ot}}),Object.defineProperty(e,`WithLoggerContext`,{enumerable:!0,get:function(){return tt}}),Object.defineProperty(e,`getGlobalConfig`,{enumerable:!0,get:function(){return We}}),Object.defineProperty(e,`inversify_default`,{enumerable:!0,get:function(){return Ue}}),Object.defineProperty(e,`logger`,{enumerable:!0,get:function(){return et}}),Object.defineProperty(e,`require_decorate`,{enumerable:!0,get:function(){return Re}}),Object.defineProperty(e,`require_decorateMetadata`,{enumerable:!0,get:function(){return Le}}),Object.defineProperty(e,`version`,{enumerable:!0,get:function(){return A}})})),xR=s((e=>{ur().__toESM(require(`@anthropic-ai/claude-agent-sdk`));function t(e){return e.hook_event_name===`PreToolUse`}function n(e){return e.hook_event_name===`PostToolUse`}function r(e){return e.type===`result`}function i(e){return e.subtype!==`success`}function a(e){let t=e.tool_input?.file_path;return typeof t==`string`?t:``}function o(e){let t=e.tool_input?.command;return typeof t==`string`?t:``}let s=/(\u009B|\u001B\[)[0-?]*[ -/]*[@-~]/g;function c(e){return e.replaceAll(s,``)}function l(e){let t=e;return c(((t.stdout??``)+(t.stderr??``)).trim())}function u(e){let t=e;return Array.isArray(t.message?.content)?t.message.content:void 0}function d(e){return e}Object.defineProperty(e,`getExecOutput`,{enumerable:!0,get:function(){return l}}),Object.defineProperty(e,`getMessageContentBlocks`,{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,`getSystemInitData`,{enumerable:!0,get:function(){return d}}),Object.defineProperty(e,`getToolInputCommand`,{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,`getToolInputFilePath`,{enumerable:!0,get:function(){return a}}),Object.defineProperty(e,`isErrorResult`,{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,`isPostToolUseInput`,{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,`isPreToolUseInput`,{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,`isResultMessage`,{enumerable:!0,get:function(){return r}}),Object.defineProperty(e,`stripAnsi`,{enumerable:!0,get:function(){return c}})})),SR=s((e=>{function t(e){return`You are a senior software engineer mapping changed files to the critical flows they affect by tracing import chains. The project type is: ${e}.
|
|
123
123
|
|
|
124
124
|
## Your task:
|
|
125
125
|
For each changed file, determine which flows it belongs to by tracing the import chain from the file UP to each flow's entry files.
|
|
@@ -194,7 +194,7 @@ ${a}`}function r(){return`You are a senior software engineer tracing how a code
|
|
|
194
194
|
- "score": 1–10 — 1 = certainly expected/intentional, 10 = certainly a bug. Use the FULL scale:
|
|
195
195
|
- 1–2: clearly intentional — commit message matches diff, tests updated, focused single-module change
|
|
196
196
|
- 3–4: likely intentional but touching sensitive code, no tests added, or small uncertainty about side effects
|
|
197
|
-
- 5–6: uncertain — change is plausible but
|
|
197
|
+
- 5–6: uncertain — change is plausible but signals are evenly split or ambiguous
|
|
198
198
|
- 7–8: suspicious — logic changed in a non-obvious way, author unfamiliar with file, risky area
|
|
199
199
|
- 9–10: very likely a bug — wrong operator, off-by-one, inverted condition, removed guard
|
|
200
200
|
|
|
@@ -203,10 +203,17 @@ ${a}`}function r(){return`You are a senior software engineer tracing how a code
|
|
|
203
203
|
2. every commit uses \`chore:\`/\`refactor:\` yet behavior visibly changes → 7–8
|
|
204
204
|
|
|
205
205
|
**Diff signals:**
|
|
206
|
-
3. Tests added/updated alongside source change → 1–2
|
|
206
|
+
3. Tests added/updated alongside source change → 1–2. Only fires when the tests actually exercise the changed behavior (new branches, edge cases, error paths). Snapshot updates, formatting changes, or unrelated test edits do NOT count.
|
|
207
207
|
4. Diff matches exactly what commit message describes → 1–2
|
|
208
208
|
5. Diff does more than commit message claims → 7–8
|
|
209
|
-
6. Obvious bug pattern
|
|
209
|
+
6. Obvious bug pattern → 9–10. Specifically look for any of:
|
|
210
|
+
- Empty catch blocks (absolutely forbidden)
|
|
211
|
+
- Catch blocks that only log and continue
|
|
212
|
+
- Returning null/undefined/default values on error without logging
|
|
213
|
+
- Using optional chaining (?.) to silently skip operations that might fail
|
|
214
|
+
- Fallback chains that try multiple approaches without explaining why
|
|
215
|
+
- Retry logic that exhausts attempts without informing the user
|
|
216
|
+
- Wrong operator, off-by-one, missing guard, removed condition, inverted condition
|
|
210
217
|
7. Change reverts a previous change → 1–2
|
|
211
218
|
8. Changed default values, timeout values, retry counts, or config constants → 7–8
|
|
212
219
|
9. Public function signature changed (parameters or return type) → 7–8
|
|
@@ -219,15 +226,22 @@ ${a}`}function r(){return`You are a senior software engineer tracing how a code
|
|
|
219
226
|
14. 3+ fix: commits on this file in 90d (unstable area) → 7–8
|
|
220
227
|
15. Revert commits on this file in 90d (risky area) → 7–8
|
|
221
228
|
|
|
222
|
-
**Product contract signals** (when ## Product Flow Steps section is present):
|
|
223
|
-
|
|
229
|
+
**Product contract signals** (when ## Product Flow Steps section is present) — fire AT MOST ONE of 16a, 16b, 17:
|
|
230
|
+
16a. productAfter fundamentally changes what the flow achieves AND code signals clearly indicate intent (feat: commit, tests updated, signature change matched by caller updates) → 1–2 (intentional product evolution)
|
|
231
|
+
16b. productAfter fundamentally changes what the flow achieves AND no code signal explains the intent → 7–8
|
|
224
232
|
17. productAfter refines how the flow works (timing, limits, format) without changing what it achieves → 1–2
|
|
225
233
|
|
|
226
234
|
**Code comment signals:**
|
|
227
|
-
18. Changed code contradicts an inline comment (// IMPORTANT, // WARNING, // NOTE, // HACK, // TODO) that describes expected behavior
|
|
235
|
+
18. Changed code contradicts an inline comment (// IMPORTANT, // WARNING, // NOTE, // HACK, // TODO) that describes expected behavior, AND the comment was not also updated → 9–10. Specifically look for any of:
|
|
236
|
+
- Function signatures no longer match documented parameters and return types
|
|
237
|
+
- Edge cases mentioned in the comment are no longer handled in the code
|
|
238
|
+
- Examples in the comment don't match the current implementation
|
|
239
|
+
- TODOs or FIXMEs that may have already been addressed
|
|
240
|
+
- Outdated references to refactored code
|
|
241
|
+
- Assumptions stated in the comment that may no longer hold true
|
|
228
242
|
|
|
229
243
|
**Caller compatibility signals:**
|
|
230
|
-
19. Callers of the changed method
|
|
244
|
+
19. Callers of the changed method assume old behavior and are incompatible with new, AND the diff does NOT update those callers in the same change → 8–10
|
|
231
245
|
|
|
232
246
|
- "reason": one sentence explaining the score
|
|
233
247
|
- productChanges are independent of techChanges — one tech change may produce zero or multiple product changes; multiple tech changes may combine into one product change
|
|
@@ -319,7 +333,140 @@ ${l}
|
|
|
319
333
|
${t.map(e=>`- ${e}`).join(`
|
|
320
334
|
`)}
|
|
321
335
|
|
|
322
|
-
${c}`}
|
|
336
|
+
${c}`}function a(){return`You are a strict verdict calibrator for code-change "is this a bug?" scoring.
|
|
337
|
+
|
|
338
|
+
Another agent (Sonnet deep) has already analyzed a code change and produced a productChange with an initial verdict score (1-10). You only see productChanges scored 5-8 — the "uncertain" range where Sonnet tends to hedge.
|
|
339
|
+
|
|
340
|
+
Your single job: re-score the verdict using strict signal-based arithmetic. Push the score to the correct end of the scale. Force commitment, do not hedge.
|
|
341
|
+
|
|
342
|
+
## Verdict scale
|
|
343
|
+
|
|
344
|
+
- 1-2: certainly intentional — commit message matches diff, tests added, focused single-module change
|
|
345
|
+
- 3-4: likely intentional but touching sensitive code, no tests added, or small uncertainty about side effects
|
|
346
|
+
- 5-6: genuinely uncertain — change is plausible but signals are evenly split. Use sparingly.
|
|
347
|
+
- 7-8: suspicious — logic changed in a non-obvious way, author unfamiliar with file, risky area
|
|
348
|
+
- 9-10: very likely a bug — wrong operator, off-by-one, inverted condition, removed guard
|
|
349
|
+
|
|
350
|
+
## Signals (the same 19 used by Sonnet deep)
|
|
351
|
+
|
|
352
|
+
**Commit message signals:**
|
|
353
|
+
1. at least one commit has \`fix:\`/\`feat:\` prefix → 1–2
|
|
354
|
+
2. every commit uses \`chore:\`/\`refactor:\` yet behavior visibly changes → 7–8
|
|
355
|
+
|
|
356
|
+
**Diff signals:**
|
|
357
|
+
3. Tests added/updated alongside source change → 1–2
|
|
358
|
+
4. Diff matches exactly what commit message describes → 1–2
|
|
359
|
+
5. Diff does more than commit message claims → 7–8
|
|
360
|
+
6. Obvious bug pattern (wrong operator, off-by-one, missing guard, removed condition) → 9–10
|
|
361
|
+
7. Change reverts a previous change → 7–8 (reverts usually roll back broken code)
|
|
362
|
+
8. Changed default values, timeout values, retry counts, or config constants → contextual: if a rationale appears in a commit message or comment treat as 1–2 (intentional tune), otherwise 7–8
|
|
363
|
+
9. Public function signature changed (parameters or return type) → 1–2 (signature changes break compilation; virtually always deliberate API evolution)
|
|
364
|
+
10. Changes scattered across 5+ unrelated modules → neutral; do not auto-fire on file count alone, only fire when there is independent evidence the diff is incoherent
|
|
365
|
+
11. All changes in one focused module → 2–3
|
|
366
|
+
|
|
367
|
+
**Git history signals** (when ## Git signals section is present):
|
|
368
|
+
12. File untouched 180+ days → 5–6 (mild suspicion — stable code rarely needs to change reactively, but combine with other signals before scoring higher)
|
|
369
|
+
13. Author has 0 commits on this file in 90d (unfamiliar) → 7–8
|
|
370
|
+
14. 3+ fix: commits on this file in 90d (unstable area) → 7–8
|
|
371
|
+
15. Revert commits on this file in 90d (risky area) → 7–8
|
|
372
|
+
|
|
373
|
+
**Product contract signals** — fire AT MOST ONE of 16a, 16b, 17:
|
|
374
|
+
16a. productAfter fundamentally changes what the flow achieves AND code signals clearly indicate intent (feat: commit, tests updated, signature change matched by caller updates) → 1–2 (intentional product evolution)
|
|
375
|
+
16b. productAfter fundamentally changes what the flow achieves AND no code signal explains the intent → 7–8
|
|
376
|
+
17. productAfter refines how the flow works (timing, limits, format) without changing what it achieves → 1–2
|
|
377
|
+
|
|
378
|
+
**Code comment signals:**
|
|
379
|
+
18. Changed code contradicts an inline comment that describes expected behavior, AND the comment was not also updated → 9–10
|
|
380
|
+
|
|
381
|
+
**Caller compatibility signals:**
|
|
382
|
+
19. Callers of the changed method assume old behavior and are incompatible with new, AND the diff does NOT update those callers in the same change → 7–8 (missed-work signal — deliberate breaking changes update their callers; not updating them suggests the developer missed the impact)
|
|
383
|
+
|
|
384
|
+
## Strict scoring rules
|
|
385
|
+
|
|
386
|
+
1. List the bug signals that fire (signal numbers).
|
|
387
|
+
2. List the intentional signals that fire (signal numbers).
|
|
388
|
+
3. Compute net = bug_count − intentional_count.
|
|
389
|
+
4. Apply CRITICAL OVERRIDE patterns. ANY of these forces score ≥ 8:
|
|
390
|
+
- Removed null check / guard / validation on data that flows to a caller
|
|
391
|
+
- Inverted condition operator AND no test was added or updated for the inverted branch
|
|
392
|
+
- Code contradicts an inline comment that was not also updated (signal 18 fires)
|
|
393
|
+
- Caller incompatibility AND callers not updated in same diff (signal 19 fires) — shipping a breaking change without updating callers is a smoking-gun missed-work pattern
|
|
394
|
+
5. Map net to score (when no critical override):
|
|
395
|
+
- net ≥ 2 → 8-10
|
|
396
|
+
- net = 1 → 7
|
|
397
|
+
- net = 0 → 5-6
|
|
398
|
+
- net = -1 → 4
|
|
399
|
+
- net ≤ -2 → 1-3
|
|
400
|
+
6. Within each band, pick the specific number based on signal strength. Don't always pick the middle.
|
|
401
|
+
|
|
402
|
+
## What NOT to do
|
|
403
|
+
|
|
404
|
+
- Don't downgrade a clear bug just because the commit message says "feat:". The diff itself is stronger evidence than the message.
|
|
405
|
+
- Don't retreat to 7 because you're "not sure." If signals split evenly, the right answer is 5-6, not 7.
|
|
406
|
+
- Don't soften a 9 to an 8 just because it feels harsh. The scale exists; commit to it.
|
|
407
|
+
- Don't invent signals not in the list. Use only the 19 above.
|
|
408
|
+
- Don't second-guess Sonnet's productBefore/After or severity — those are given. Your job is the score, not the narrative.
|
|
409
|
+
|
|
410
|
+
## Output (JSON, no prose outside)
|
|
411
|
+
|
|
412
|
+
{
|
|
413
|
+
"score": <integer 1-10>,
|
|
414
|
+
"reasoning": "<one sentence: signals X,Y fired (bug); signal Z fired (intentional); net=N; critical override [yes/no, which]; → score W>",
|
|
415
|
+
"criticalOverride": <boolean>,
|
|
416
|
+
"signalsThatFired": { "bug": [<numbers>], "intentional": [<numbers>] },
|
|
417
|
+
"changeFromOriginal": {
|
|
418
|
+
"changed": <boolean — true if score differs from the input verdict>,
|
|
419
|
+
"delta": <integer — newScore - originalScore; 0 if unchanged>,
|
|
420
|
+
"reason": "<one sentence explaining what changed and why; empty if changed=false>"
|
|
421
|
+
}
|
|
422
|
+
}`}function o(e){if(e===void 0||e.owner===void 0||e.repo===void 0)return``;let t=t=>`https://github.com/${e.owner}/${e.repo}/commit/${t}`,n=e.anchorSha===void 0?``:` (${t(e.anchorSha)})`,r=e.headSha===void 0?``:` (${t(e.headSha)})`,i=[`## Repository & Analysis Context`,``,`Repository: ${e.owner}/${e.repo}`,`Base: ${e.anchorBranch??`(unknown)`}${n}`,`Head: ${e.branch??`(unknown)`}${r}`],a=e.branch?.match(/#(\d+)|^(\d+)$/),o=a?.[1]??a?.[2],s=o===void 0?void 0:`Possible PR: https://github.com/${e.owner}/${e.repo}/pull/${o} (may not be exact)`,c=`Analysis date: ${new Date().toLocaleDateString(`en-US`,{month:`short`,day:`numeric`,year:`numeric`})}`,l=[];return s!==void 0&&l.push(s),e.runType!==void 0&&l.push(`Run type: ${e.runType}`),l.push(c,``),[...i,...l].join(`
|
|
423
|
+
`)}function s(e,t){if(e===void 0||e.steps.length===0)return``;let n=new Map((t??[]).map(e=>[e.stepId,e.reason])),r=e.steps.map((e,t)=>{let r=n.get(e.stepId),i=r===void 0?``:`\n 🔥 Affected by this change: ${r}`;return`${t+1}. [${e.stepId}] ${e.actor} → ${e.action} ⇒ ${e.outcome}${i}`}).join(`
|
|
424
|
+
`);return`## Product Flow
|
|
425
|
+
|
|
426
|
+
${e.trigger===void 0?``:`Trigger: ${e.trigger}\n`}${r}${e.outcome===void 0?``:`\nOutcome: ${e.outcome}`}
|
|
427
|
+
|
|
428
|
+
`}function c(e){if(e===void 0||!(e.entryFiles.length>0||e.entrySymbols.length>0||e.calledModules.length>0))return``;let t=[`## Code Trace`,``];return e.entryFiles.length>0&&t.push(`Entry files: ${e.entryFiles.join(`, `)}`),e.entrySymbols.length>0&&t.push(`Entry symbols: ${e.entrySymbols.join(`, `)}`),e.calledModules.length>0&&t.push(`Called modules: ${e.calledModules.join(`, `)}`),t.push(``),t.join(`
|
|
429
|
+
`)}function l(e){let{productChange:t,techChanges:n,originalVerdict:r,flow:i,commitMessages:a,gitSignalsBlock:l,runContext:u,affectedSteps:d}=e,f=n.map(e=>`### ${e.file}
|
|
430
|
+
techBefore: ${e.techBefore}
|
|
431
|
+
techAfter: ${e.techAfter}
|
|
432
|
+
confidence: ${e.confidence}`).join(`
|
|
433
|
+
|
|
434
|
+
`),p=a.length>0?a.map((e,t)=>`${t+1}. ${e}`).join(`
|
|
435
|
+
`):`(none)`,m=o(u),h=s(i.productFlow,d),g=c(i.trace);return`${m}## Flow context
|
|
436
|
+
|
|
437
|
+
Flow: ${i.name} (rank ${i.rank})
|
|
438
|
+
Importance: ${i.importance??`—`}
|
|
439
|
+
Why this flow matters: ${i.importanceReason}
|
|
440
|
+
|
|
441
|
+
${h}${g}## ProductChange to recalibrate
|
|
442
|
+
|
|
443
|
+
Title: ${t.title??`(no title)`}
|
|
444
|
+
Severity: ${t.severity}
|
|
445
|
+
severityReason: ${t.severityReason??`(none)`}
|
|
446
|
+
|
|
447
|
+
productBefore: ${t.productBefore}
|
|
448
|
+
productAfter: ${t.productAfter}
|
|
449
|
+
|
|
450
|
+
## Sonnet's initial verdict (this is what you are reviewing)
|
|
451
|
+
|
|
452
|
+
Score: ${r.score}
|
|
453
|
+
Reason: ${r.reason??`(none)`}
|
|
454
|
+
|
|
455
|
+
## Tech changes (the diff hunks Sonnet identified for this finding)
|
|
456
|
+
|
|
457
|
+
${f||`(no techChanges)`}
|
|
458
|
+
|
|
459
|
+
## Commit messages (newest first)
|
|
460
|
+
|
|
461
|
+
${p}
|
|
462
|
+
|
|
463
|
+
${l}
|
|
464
|
+
|
|
465
|
+
## Your task
|
|
466
|
+
|
|
467
|
+
Apply the strict scoring rules from the system prompt. Re-score this productChange. The current score (${r.score}) is in the 5-8 range, which means Sonnet was uncertain. Your job is to commit to the correct number.
|
|
468
|
+
|
|
469
|
+
Output the JSON described in the system prompt. No prose outside the JSON.`}Object.defineProperty(e,`PRE_FILTER_SYSTEM_PROMPT`,{enumerable:!0,get:function(){return`You classify file paths as SOURCE or NON_SOURCE.
|
|
323
470
|
|
|
324
471
|
NON_SOURCE: tests, test helpers, test fixtures, config files, migration files, lock files, documentation, build artifacts, IDE settings, CI configs.
|
|
325
472
|
SOURCE: everything else — application code, services, controllers, models, utilities, types, DTOs.
|
|
@@ -327,7 +474,7 @@ SOURCE: everything else — application code, services, controllers, models, uti
|
|
|
327
474
|
Output a JSON object with a single "sourceFiles" array containing ONLY the SOURCE file paths.
|
|
328
475
|
|
|
329
476
|
Example:
|
|
330
|
-
{"sourceFiles": ["src/auth/auth.service.ts", "src/payments/payments.controller.ts"]}`}}),Object.defineProperty(e,`buildFileToFlowMappingPrompt`,{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,`buildFileToFlowMappingSystemPrompt`,{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,`buildSonnetDeepPrompt`,{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,`buildSonnetDeepSystemPrompt`,{enumerable:!0,get:function(){return r}})})),CR=s((e=>{var t=`2.0.1`,n,r,i,a,o,s,c,l,u,d,f,p=[].slice,m=[].indexOf||function(e){for(var t=0,n=this.length;t<n;t++)if(t in this&&this[t]===e)return t;return-1},h={}.hasOwnProperty;for(l in c=require(`path`),i=function(e){return typeof e==`function`},a=function(e){return typeof e==`string`||!!e&&typeof e==`object`&&Object.prototype.toString.call(e)===`[object String]`},f=e,f.VERSION=t??`NO-VERSION`,d=function(e){return e=e.replace(/\\/g,`/`),e=e.replace(/(?<!^)\/+/g,`/`),e},c)u=c[l],i(u)?f[l]=function(e){return function(){var t=1<=arguments.length?p.call(arguments,0):[],n;return t=t.map(function(e){return a(e)?d(e):e}),n=c[e].apply(c,t),a(n)?d(n):n}}(l):f[l]=u;for(s in f.sep=`/`,r={toUnix:d,normalizeSafe:function(e){var t;return e=d(e),t=f.normalize(e),e.startsWith(`./`)&&!t.startsWith(`./`)&&!t.startsWith(`..`)?t=`./`+t:e.startsWith(`//`)&&!t.startsWith(`//`)&&(t=e.startsWith(`//./`)?`//.`+t:`/`+t),t},normalizeTrim:function(e){return e=f.normalizeSafe(e),e.endsWith(`/`)?e.slice(0,+(e.length-2)+1||9e9):e},joinSafe:function(){var e=1<=arguments.length?p.call(arguments,0):[],t,n=f.join.apply(null,e);return e.length>0&&(t=d(e[0]),t.startsWith(`./`)&&!n.startsWith(`./`)&&!n.startsWith(`..`)?n=`./`+n:t.startsWith(`//`)&&!n.startsWith(`//`)&&(n=t.startsWith(`//./`)?`//.`+n:`/`+n)),n},addExt:function(e,t){return t?(t[0]!==`.`&&(t=`.`+t),e+(e.endsWith(t)?``:t)):e},trimExt:function(e,t,n){var r;return n??=7,r=f.extname(e),o(r,t,n)?e.slice(0,+(e.length-r.length-1)+1||9e9):e},removeExt:function(e,t){return t?(t=t[0]===`.`?t:`.`+t,f.extname(e)===t?f.trimExt(e,[],t.length):e):e},changeExt:function(e,t,n,r){return r??=7,f.trimExt(e,n,r)+(t?t[0]===`.`?t:`.`+t:``)},defaultExt:function(e,t,n,r){var i;return r??=7,i=f.extname(e),o(i,n,r)?e:f.addExt(e,t)}},o=function(e,t,n){return t??=[],e&&e.length<=n&&m.call(t.map(function(e){return(e&&e[0]!==`.`?`.`:``)+e}),e)<0},r)if(h.call(r,s)){if(n=r[s],f[s]!==void 0)throw Error(`path.`+s+` already exists.`);f[s]=n}})),wR=s(((e,t)=>{
|
|
477
|
+
{"sourceFiles": ["src/auth/auth.service.ts", "src/payments/payments.controller.ts"]}`}}),Object.defineProperty(e,`buildFileToFlowMappingPrompt`,{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,`buildFileToFlowMappingSystemPrompt`,{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,`buildSonnetDeepPrompt`,{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,`buildSonnetDeepSystemPrompt`,{enumerable:!0,get:function(){return r}}),Object.defineProperty(e,`buildVerdictCalibratorPrompt`,{enumerable:!0,get:function(){return l}}),Object.defineProperty(e,`buildVerdictCalibratorSystemPrompt`,{enumerable:!0,get:function(){return a}})})),CR=s((e=>{var t=`2.0.1`,n,r,i,a,o,s,c,l,u,d,f,p=[].slice,m=[].indexOf||function(e){for(var t=0,n=this.length;t<n;t++)if(t in this&&this[t]===e)return t;return-1},h={}.hasOwnProperty;for(l in c=require(`path`),i=function(e){return typeof e==`function`},a=function(e){return typeof e==`string`||!!e&&typeof e==`object`&&Object.prototype.toString.call(e)===`[object String]`},f=e,f.VERSION=t??`NO-VERSION`,d=function(e){return e=e.replace(/\\/g,`/`),e=e.replace(/(?<!^)\/+/g,`/`),e},c)u=c[l],i(u)?f[l]=function(e){return function(){var t=1<=arguments.length?p.call(arguments,0):[],n;return t=t.map(function(e){return a(e)?d(e):e}),n=c[e].apply(c,t),a(n)?d(n):n}}(l):f[l]=u;for(s in f.sep=`/`,r={toUnix:d,normalizeSafe:function(e){var t;return e=d(e),t=f.normalize(e),e.startsWith(`./`)&&!t.startsWith(`./`)&&!t.startsWith(`..`)?t=`./`+t:e.startsWith(`//`)&&!t.startsWith(`//`)&&(t=e.startsWith(`//./`)?`//.`+t:`/`+t),t},normalizeTrim:function(e){return e=f.normalizeSafe(e),e.endsWith(`/`)?e.slice(0,+(e.length-2)+1||9e9):e},joinSafe:function(){var e=1<=arguments.length?p.call(arguments,0):[],t,n=f.join.apply(null,e);return e.length>0&&(t=d(e[0]),t.startsWith(`./`)&&!n.startsWith(`./`)&&!n.startsWith(`..`)?n=`./`+n:t.startsWith(`//`)&&!n.startsWith(`//`)&&(n=t.startsWith(`//./`)?`//.`+n:`/`+n)),n},addExt:function(e,t){return t?(t[0]!==`.`&&(t=`.`+t),e+(e.endsWith(t)?``:t)):e},trimExt:function(e,t,n){var r;return n??=7,r=f.extname(e),o(r,t,n)?e.slice(0,+(e.length-r.length-1)+1||9e9):e},removeExt:function(e,t){return t?(t=t[0]===`.`?t:`.`+t,f.extname(e)===t?f.trimExt(e,[],t.length):e):e},changeExt:function(e,t,n,r){return r??=7,f.trimExt(e,n,r)+(t?t[0]===`.`?t:`.`+t:``)},defaultExt:function(e,t,n,r){var i;return r??=7,i=f.extname(e),o(i,n,r)?e:f.addExt(e,t)}},o=function(e,t,n){return t??=[],e&&e.length<=n&&m.call(t.map(function(e){return(e&&e[0]!==`.`?`.`:``)+e}),e)<0},r)if(h.call(r,s)){if(n=r[s],f[s]!==void 0)throw Error(`path.`+s+` already exists.`);f[s]=n}})),wR=s(((e,t)=>{
|
|
331
478
|
/*!
|
|
332
479
|
* is-extglob <https://github.com/jonschlinkert/is-extglob>
|
|
333
480
|
*
|
|
@@ -32210,7 +32357,7 @@ https://www.w3ctech.com/topic/2226`));let i=t(...r);return i.postcssPlugin=e,i.p
|
|
|
32210
32357
|
`);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=z(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=re(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=z(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=z(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=re(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 I(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 L=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 ne(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 R(e,t,n,r){return!(!t||!t.has(r))||!(!e||!e.has(n))}function z(e,t,n,r){let i=e.indexOf(t,n);if(i===-1)throw Error(r);return i+t.length-1}function re(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 ie(e,t,n){let r=n,i=1;for(;n<e.length;n++)if(e[n]===`<`)if(e[n+1]===`/`){let a=z(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=z(e,`?>`,n+1,`StopNode is not closed.`);else if(e.substr(n+1,3)===`!--`)n=z(e,`-->`,n+3,`StopNode is not closed.`);else if(e.substr(n+1,2)===`![`)n=z(e,`]]>`,n,`StopNode is not closed.`)-2;else{let r=re(e,n,`>`);r&&((r&&r.tagName)===t&&r.tagExp[r.tagExp.length-1]!==`/`&&i++,n=r.closeIndex)}}function B(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 V=x.getMetaDataSymbol();function ae(e,t){return oe(e,t)}function oe(e,t,n){let r,i={};for(let a=0;a<e.length;a++){let o=e[a],s=se(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=oe(o[s],t,c),n=le(e,t);o[V]!==void 0&&(e[V]=o[V]),o[`:@`]?ce(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 se(e){let t=Object.keys(e);for(let e=0;e<t.length;e++){let n=t[e];if(n!==`:@`)return n}}function ce(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 le(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 ue{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:ae(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 '
'`);if(t===`&`)throw Error(`An entity with value '&' is not permitted`);this.externalEntities[e]=t}static getMetaDataSymbol(){return x.getMetaDataSymbol()}}function de(e,t){let n=``;return t.format&&t.indentBy.length>0&&(n=`
|
|
32211
32358
|
`),fe(e,t,``,n)}function fe(e,t,n,r){let i=``,a=!1;for(let o=0;o<e.length;o++){let s=e[o],c=pe(s);if(c===void 0)continue;let l=``;if(l=n.length===0?c:`${n}.${c}`,c===t.textNodeName){let e=s[c];he(l,t)||(e=t.tagValueProcessor(c,e),e=ge(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=me(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}${me(s[`:@`],t)}`,f=fe(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 pe(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 me(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=ge(i,t),!0===i&&t.suppressBooleanAttributes?n+=` ${r.substr(t.attributeNamePrefix.length)}`:n+=` ${r.substr(t.attributeNamePrefix.length)}="${i}"`}return n}function he(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 ge(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 _e={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:`&`},{regex:RegExp(`>`,`g`),val:`>`},{regex:RegExp(`<`,`g`),val:`<`},{regex:RegExp(`'`,`g`),val:`'`},{regex:RegExp(`"`,`g`),val:`"`}],processEntities:!0,stopNodes:[],oneListGroup:!1};function ve(e){this.options=Object.assign({},_e,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=xe),this.processTextOrObjNode=ye,this.options.format?(this.indentate=be,this.tagEndChar=`>
|
|
32212
32359
|
`,this.newLine=`
|
|
32213
|
-
`):(this.indentate=function(){return``},this.tagEndChar=`>`,this.newLine=``)}function ye(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 be(e){return this.options.indentBy.repeat(e)}function xe(e){return!(!e.startsWith(this.options.attributeNamePrefix)||e===this.options.textNodeName)&&e.substr(this.attrPrefixLen)}ve.prototype.build=function(e){return this.options.preserveOrder?de(e,this.options):(Array.isArray(e)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(e={[this.options.arrayNodeName]:e}),this.j2x(e,0,[]).val)},ve.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}},ve.prototype.buildAttrPairStr=function(e,t){return t=this.options.attributeValueProcessor(e,``+t),t=this.replaceEntitiesValue(t),this.options.suppressBooleanAttributes&&t===`true`?` `+e:` `+e+`="`+t+`"`},ve.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}},ve.prototype.closeTag=function(e){let t=``;return this.options.unpairedTags.indexOf(e)===-1?t=this.options.suppressEmptyNode?`/`:`></${e}`:this.options.suppressUnpairedNode||(t=`/`),t},ve.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}},ve.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 Se={validate:s};t.exports=n})()})),wU=s((e=>{let t=ur(),n=xR(),r=t.__toESM(require(`@anthropic-ai/claude-agent-sdk`));e.getMessageContentBlocks=n.getMessageContentBlocks,e.isErrorResult=n.isErrorResult,e.isResultMessage=n.isResultMessage,Object.defineProperty(e,`query`,{enumerable:!0,get:function(){return r.query}})})),TU=s((e=>{let t=SR();e.buildFileToFlowMappingPrompt=t.buildFileToFlowMappingPrompt,e.buildFileToFlowMappingSystemPrompt=t.buildFileToFlowMappingSystemPrompt})),jee=s((e=>{let t=ur(),n=bR(),r=t.__toESM(require(`node:crypto`));function i(e){if(typeof e!=`object`||!e)return;let t=e;if(Array.isArray(t.fileFlowMapping))return{fileFlowMapping:t.fileFlowMapping}}async function a(e,t,a,o,s,c,l,u){let{query:d,isResultMessage:f,isErrorResult:p}=await Promise.resolve().then(()=>wU()),{buildFileToFlowMappingSystemPrompt:m,buildFileToFlowMappingPrompt:h}=await Promise.resolve().then(()=>TU()),g=d({prompt:h(e,t,a,o,s),options:{model:n.REGRESSION_IMPACT_SONNET_MODEL,systemPrompt:m(u),allowedTools:[`Read`,`Grep`,`Glob`,`Bash`],permissionMode:n.REGRESSION_PERMISSION_MODE,allowDangerouslySkipPermissions:!0,maxBudgetUsd:n.REGRESSION_IMPACT_AGENTIC_MAX_BUDGET_USD,maxTurns:n.REGRESSION_IMPACT_AGENTIC_MAX_TURNS,cwd:a,sessionId:(0,r.randomUUID)(),outputFormat:{type:`json_schema`,schema:n.FILE_FLOW_MAPPING_OUTPUT_SCHEMA},env:{...process.env,ANTHROPIC_BASE_URL:l,ANTHROPIC_AUTH_TOKEN:c??``}}});for await(let e of g){if(!f(e))continue;if(p(e))return n.logger.info.defaultLog(`[regression-impact] File-to-flow mapping error: ${String(e.subtype)}`),{mappings:[],costUsd:0,turns:0,maxTurnsHit:!1};let r=e.total_cost_usd,a=e.num_turns,o=a>=n.REGRESSION_IMPACT_AGENTIC_MAX_TURNS,s=i(e.structured_output);return n.REGRESSION_LOG_COST&&n.logger.info.defaultLog(`[regression-impact] Batch (${t.length} files) cost: $${r.toFixed(4)}`),{mappings:s?.fileFlowMapping??[],costUsd:r,turns:a,maxTurnsHit:o}}return{mappings:[],costUsd:0,turns:0,maxTurnsHit:!1}}async function o(e,t,r,i,o,s,c,l){let u=[];for(let e=0;e<t.length;e+=n.REGRESSION_IMPACT_MAPPING_BATCH_SIZE)u.push(t.slice(e,e+n.REGRESSION_IMPACT_MAPPING_BATCH_SIZE));let d=u.length;n.logger.info.defaultLog(`[regression-impact] File-to-flow mapping: ${t.length} file(s) in ${d} batch(es) against ${e.length} flow(s)...`);let f=[],p=0,m=0,h=!1;for(let t=0;t<u.length;t+=n.REGRESSION_IMPACT_MAPPING_CONCURRENCY){let d=u.slice(t,t+n.REGRESSION_IMPACT_MAPPING_CONCURRENCY),g=await Promise.all(d.map(t=>a(e,t,r,i,o,s,c,l)));for(let e of g){for(let t of e.mappings){let e=t.flowIds.length>0?t.flowIds.join(`, `):`no flows`;n.logger.info.defaultLog(`[regression-impact] ${t.file} → ${e}`)}f.push(...e.mappings),p+=e.costUsd,m+=e.turns,h||=e.maxTurnsHit}}return{mappings:f,costUsd:p,turns:m,maxTurnsHit:h}}e.runFileToFlowMapping=o})),EU=s((e=>{let t=ur(),n=bR(),r=xR(),i=SR(),a=t.__toESM(CR()),o=t.__toESM(require(`node:fs/promises`)),s=t.__toESM(require(`node:async_hooks`)),c=t.__toESM(ie()),l=t.__toESM(Fc()),u=t.__toESM(require(`node:process`)),d=t.__toESM(require(`node:os`));t.__toESM(require(`node:tty`));let f=t.__toESM(require(`node:crypto`)),p=t.__toESM(require(`node:fs`)),m=t.__toESM(ez()),h=t.__toESM(vB()),g=t.__toESM(require(`node:child_process`)),_=t.__toESM(require(`node:util`)),v=t.__toESM(require(`@prisma/internals`)),y=t.__toESM(gB()),b=t.__toESM(require(`node:zlib`)),x=t.__toESM(xV()),S=t.__toESM(CV()),C=t.__toESM(kV()),w=t.__toESM(PV()),T=t.__toESM(require(`node:events`)),E=t.__toESM(OH()),D=t.__toESM(mU()),O=t.__toESM(xU()),k=t.__toESM(SU()),A=t.__toESM(CU()),ee=t.__toESM(kH());t.__toESM(require(`node:readline`));let j=t.__toESM(require(`node:path`)),te=t.__toESM(require(`node:module`)),M=t.__toESM(require(`@anthropic-ai/claude-agent-sdk`));var N=class e{rootPath;absolutePath;static EARLY_FILENAME_VAR=`$early_filename`;constructor(e){this.rootPath=a.default.normalizeTrim(n.getGlobalConfig().getRootPath());let t=a.default.normalizeTrim(e),r=a.default.normalizeTrim(this.rootPath);if(t===r||t.startsWith(r+a.default.sep))this.absolutePath=t;else{let e=t.replace(/^\//,``);this.absolutePath=a.default.resolve(this.rootPath,e)}}static fromSourceFile(t){let r=a.default.normalizeTrim(t.getFilePath());return new e(a.default.relative(a.default.normalizeTrim(n.getGlobalConfig().getRootPath()),r))}static fromAbsolutePath(t){let r=a.default.normalizeTrim(t);return new e(a.default.relative(a.default.normalizeTrim(n.getGlobalConfig().getRootPath()),r))}static fromRelativePath(t){return new e(t)}getRelativeFilePath(){return a.default.relative(this.rootPath,this.absolutePath)}getAbsoluteFilePath(){return this.absolutePath}async isFileExists(){try{return(await o.default.stat(this.absolutePath)).isFile()}catch{return!1}}async isDirectoryExists(){try{return(await o.default.stat(this.absolutePath)).isDirectory()}catch{return!1}}async createDirectory(e){await o.default.mkdir(this.absolutePath,{recursive:e?.recursive??!0})}async getText(){try{return await o.default.readFile(this.absolutePath,`utf8`)}catch{return``}}async upsert(e){let t=a.default.dirname(this.absolutePath);await o.default.mkdir(t,{recursive:!0}),await(await this.isFileExists()?o.default.appendFile(this.absolutePath,e):o.default.writeFile(this.absolutePath,e)),n.logger.info.defaultLog(`Upserted file`,{path:this.getRelativeFilePath()})}async replace(e){let t=a.default.dirname(this.absolutePath);await o.default.mkdir(t,{recursive:!0}),await o.default.writeFile(this.absolutePath,e),n.logger.info.defaultLog(`Replaced file`,{path:this.getRelativeFilePath()})}async delete(){try{await o.default.unlink(this.absolutePath),n.logger.info.defaultLog(`Deleted file`,{path:this.getRelativeFilePath()})}catch{}}};let P={WIN32:`win32`,DARWIN:`darwin`,LINUX:`linux`},F={JAVASCRIPT:`javascript`,TYPESCRIPT:`typescript`,PYTHON:`python`},I=e=>{let t=n.getGlobalConfig().getRootPath();return a.default.resolve(t,e)},L=e=>{let t=n.getGlobalConfig().getRootPath(),r=a.default.normalize(e);return a.default.relative(t,r)},ne=e=>({".js":`javascript`,".mjs":`javascript`,".cjs":`javascript`,".jsx":`javascript`,".ts":`typescript`,".tsx":`typescript`,".py":`python`})[e.toLowerCase()]??`javascript`;function R(e){return ne((0,a.extname)(e))}function z(e){return ne((0,a.extname)(e))===`typescript`}function re(e){return ne((0,a.extname)(e))===F.PYTHON}function B(e){let t=n.getGlobalConfig().getRootPath();if(!(0,c.isDefined)(t))throw Error(`Workspace root path is not defined`);if((0,c.isEmpty)(e))return a.default.normalize(t);let r=a.default.normalize(t),i=a.default.normalize(e);if(process.platform===P.WIN32){let t=r.split(`:`)[0].toUpperCase(),n=i.split(`:`)[0].toUpperCase();if(t!==n&&!n.startsWith(t))return e}return a.default.relative(r,i)}function V(e){return e.startsWith(`../`)?`../${e}`:e.startsWith(`./`)?`.${e}`:e}function ae(e){let t=a.default.normalize(I(e)),n=a.default.normalize((0,m.default)([`package.json`,`project.json`],{cwd:t})??``);if(!n)return``;let r=L((0,a.dirname)(n));return r.startsWith(`/`)?r.slice(1):r}function oe(e,t,n){if(!ce(e))return e;let r=n===``?t:t.replace(n,``),i=n===``?ue(r):le(r),o=r.split(`/`).slice(0,-1),s=se(e,`../`),c=s>0?o.slice(0,-s).join(`/`):(0,a.dirname)(r),l=e.replaceAll(`../`,``).replaceAll(`./`,``);return a.default.join(i,c,l)}function se(e,t){return e.split(t).length-1}function ce(e){return e.startsWith(`../`)||e.startsWith(`./`)}function le(e){let t=se(e,`/`);return`../`.repeat(t-1)}function ue(e){let t=se(e,`/`);return`../`.repeat(t+1)}function de(e){return e?.includes(`node_modules/`)}let fe=e=>e.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`),pe=e=>process.platform===`win32`?`"${e.replaceAll(`"`,String.raw`\"`)}"`:`'${e.replaceAll(`'`,`'"'"'`)}'`;function me(e,t){let n=a.default.isAbsolute(e)?e:I(e);return(0,m.default)(t,{cwd:n})}function he(e,t){let n=me(e,t);if(!(0,c.isDefined)(n))return;let r=p.readFileSync(n,`utf8`);return JSON.parse(r)}function ge(e){return he(e,`package.json`)}function _e(e,t){let{dependencies:n={},devDependencies:r={}}=e;return Object.keys({...r,...n}).includes(t)}let ve=[{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}],ye=[`@typescript-eslint/no-undefined`,`unicorn/no-useless-undefined`,`no-undefined`];async function be(e){for(let{path:t,isFlat:n}of ve){let r=a.default.join(e,t);if(await N.fromAbsolutePath(r).isFileExists())return{path:r,isFlat:n}}return ge(e)?.eslint?{path:me(e,`package.json`),isFlat:!1}:{path:null,isFlat:!1}}let xe={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`,REGRESSION_IMPACT:`regression-impact`,REGRESSION_CATALOG:`regression-catalog`},Se={CODE_EXTRACTOR:`code-extractor`,CODE_REFINEMENT:`code-refinement`,TEST_MANAGEMENT:`test-management`,TEST_VALIDATOR:`test-validator`,CONFIG_FILE:`config-file`,COMMAND_EXECUTION:`command-execution`},Ce=[`.jsx`,`.tsx`],we=[`it`,`test`,`it.each`,`test.each`],Te=function(e){return e.Default=`default`,e.ObjectDefault=`object-default`,e.Named=`named`,e.Unknown=`unknown`,e.NotExported=`not-exported`,e}({}),Ee=function(e){return e.PRIVATE=`private`,e.PROTECTED=`protected`,e.PUBLIC=`public`,e}({}),De=function(e){return e.REACT=`react`,e.ANGULAR=`angular`,e}({}),Oe=`unknown`,ke=`tests`,Ae=(0,_.promisify)(g.default.exec);async function je(e,{cwd:t=n.getGlobalConfig().getRootPath(),timeout:r=1e4}={}){return(await Ae(e,{cwd:t,maxBuffer:500*1024,timeout:r}))?.stdout?.toString()??``}let Me=e=>{let t=I(e);return(0,m.default)(`jest.config.+(js|ts|mjs|cjs|json)`,{cwd:t})},Ne=e=>(0,c.isObject)(e)&&(0,c.isString)(e.rootDir),Pe=async e=>{let t;if(n.logger.addContext({subCategory:Se.CONFIG_FILE}),(0,c.isDefined)(e)){let n=Me(e);n!==null&&(t=(0,a.dirname)(n))}t??=n.getGlobalConfig().getRootPath();let r;try{if(r=await je(`npx jest --showConfig`,{cwd:t}),!(0,c.isString)(r))throw n.logger.info.defaultLog(`Jest config return is not a string`,r),Error(`Jest config return is not a string`);let e=JSON.parse(r);if((0,c.isObject)(e)&&(0,c.isArray)(e.configs)&&e.configs.every(e=>Ne(e)))return{projectConfigs:e.configs,globalConfig:e.globalConfig,configs:e.configs}}catch(e){n.logger.info.defaultLog(`Cannot read jest config`,(0,c.getErrorMessage)(e)),n.logger.info.defaultLog(`Failed reading jest config`,e,(0,c.getErrorMessage)(e));return}n.logger.info.defaultLog(`Invalid jest config or config in not supported format`)},Fe=async()=>{let e=[n.getGlobalConfig().getRootPath()],t=a.default.join(`node_modules`,`.prisma`,`client`,`index.d.ts`),r=e.map(e=>a.default.join(e,t)).map(e=>N.fromAbsolutePath(e));return(await(0,c.filterAsync)(r,e=>e.isFileExists())).map(e=>e.getAbsoluteFilePath())},Ie=async()=>{try{let e=n.getGlobalConfig().getRootPath();if(!(0,c.isDefined)(e))return[];let t=await(0,v.getSchemaWithPathOptional)(``,``,{cwd:e});if(!(0,c.isDefined)(t))return[];let r=t.schemas.map(e=>e[1]),i=new Set;for(let e of r){let n=(await(0,v.getConfig)({datamodel:e,ignoreEnvVarErrors:!0})).generators;for(let e of n)if((0,c.isDefined)(e.output?.value)){let n=a.default.join(a.default.resolve(t.schemaRootDir,e.output.value),`index.d.ts`);await N.fromAbsolutePath(n).isFileExists()&&i.add(n)}}return[...i]}catch(e){return n.logger.error(`Failed to get prisma typings paths`,e),[]}},Le=async()=>(await Promise.all([Fe(),Ie()])).flat(),Re=async(e,t=!1,r)=>{let i=`!**/node_modules/**`;if(t)return new h.Project({useInMemoryFileSystem:!0,compilerOptions:r});let o=z(e),s=ze((0,a.dirname)(I(e)),n.getGlobalConfig().isSiblingFolderStructured());if(!o&&!(0,c.isDefined)(s)){let t=await Ve(e);if(!(0,c.isDefined)(t)||(0,c.isEmpty)(t))throw Error(`Cannot find source code path in jest config`);let n=new h.Project({compilerOptions:{allowJs:!0,maxNodeModuleJsDepth:0},useInMemoryFileSystem:!1});return n.addSourceFilesAtPaths([...t,i]),n}if(!o&&(0,c.isDefined)(s)){let t=new h.Project({tsConfigFilePath:s,compilerOptions:{allowJs:!0,maxNodeModuleJsDepth:0}}),n=await Ve(e);return t.addSourceFilesAtPaths([...n,i]),t}let l={maxNodeModuleJsDepth:0};if(n.getGlobalConfig().isRootFolderStructured()){let e=n.getGlobalConfig().getRootPath();l.rootDirs=[a.default.resolve(e,`src`),a.default.resolve(e,ke)]}let u=new h.Project({tsConfigFilePath:s,compilerOptions:l}),d=await Le();for(let e of d)u.addSourceFileAtPath(e);return u},ze=(e,t)=>{let n;try{n=Be(e)}catch{t&&(n=Be((0,a.dirname)(e)))}return n},Be=e=>{let t=e,n=/^(tsconfig|jsconfig).*\.json$/;for(;t!==(0,a.dirname)(t);){let e=(0,a.join)(t,`tsconfig.json`),r=(0,a.join)(t,`jsconfig.json`);if(!(0,p.existsSync)(t))return Be((0,a.dirname)(t));if((0,p.existsSync)(e))return e;if((0,p.existsSync)(r))return r;let i=(0,p.readdirSync)(t);for(let e of i)if(n.test(e))return(0,a.join)(t,e);t=(0,a.dirname)(t)}},Ve=async e=>{let t=await Pe(e);if((0,c.isDefined)(t)){let e=t?.configs[0].roots.map(e=>a.default.join(e,`**/*.{ts,js,tsx,jsx}`));if(!(0,c.isEmpty)(e))return e}return[I(ae(e))]};var H=t.__toESM(n.require_decorateMetadata()),He=t.__toESM(n.require_decorate());let Ue=`The ts-morph project is not initialized.`,We=new class{storage=new s.AsyncLocalStorage;_project;clear(){this._project=void 0}async init(e,t,n){let r=I(e);if((0,c.isDefined)(this._project))return this._project.addSourceFileAtPathIfExists(r);this._project=await Re(e,t,n);let i=this.storage.getStore();if((0,c.isDefined)(i))return this._project.addSourceFileAtPathIfExists(r)}add(e,t){let n=I(e),r=this.storage.getStore()?.getProject();if(!(0,c.isDefined)(r))throw Error(Ue);return r.createSourceFile(n,t,{overwrite:!0})}update(e,t){let n=this.get(e);return n.replaceWithText(t),n}addFile(e){(0,c.isDefined)(this._project)&&this._project.addSourceFileAtPathIfExists(e)}removeFile(e){if(!(0,c.isDefined)(this._project))return;let t=this._project.getSourceFile(e);(0,c.isDefined)(t)&&this._project.removeSourceFile(t)}async refreshFromFileSystem(e){if(!(0,c.isDefined)(this._project))return;let t=I(e),n=this._project?.getSourceFile(e)??this._project?.getSourceFile(t);if((0,c.isDefined)(n)){let e=n.getFilePath();this._project.removeSourceFile(n),this._project.addSourceFileAtPath(e)}}get(e){let t=I(e),n=this.storage.getStore()?.getProject();if(!(0,c.isDefined)(n))throw Error(Ue+` store`);let r=n.getSourceFile(t);if(!(0,c.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=I(e);return this._project?.getSourceFile(t)}withContext=(e,t,n)=>{let r=n.value,i=this.storage;if((0,c.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}},Ge=We.withContext,Ke=async e=>{class t{async fn(){return e()}}(0,He.default)([Ge,(0,H.default)(`design:type`,Function),(0,H.default)(`design:paramtypes`,[]),(0,H.default)(`design:returntype`,Promise)],t.prototype,`fn`,null),await new t().fn()},qe=e=>{let t=e?.asKind(h.SyntaxKind.ExpressionStatement)?.getExpression();if(!(0,c.isDefined)(t))return;let n=t.asKind(h.SyntaxKind.CallExpression)?.getArguments()?.at(-1),r=n?.asKind(h.SyntaxKind.ArrowFunction)?.getBody(),i=n?.asKind(h.SyntaxKind.FunctionExpression)?.getBody();return r?.asKind(h.SyntaxKind.Block)??i?.asKind(h.SyntaxKind.Block)},Je=e=>h.Node.isExpressionStatement(e)&&e.getFirstChildByKind(h.SyntaxKind.CallExpression)?.getFirstChildByKind(h.SyntaxKind.Identifier)?.getText()===`describe`,Ye=e=>e.getStatements().filter(e=>Je(e)),Xe=e=>{let t=e.getExpression().getFirstChild()?.getText();return!(0,c.isDefined)(t)||(0,c.isEmpty)(t)?!1:we.some(e=>t.startsWith(e))},Ze=e=>{let t=qe(e);return(0,c.isDefined)(t)?t.getChildrenOfKind(h.SyntaxKind.ExpressionStatement).some(e=>Xe(e)):!1},Qe=e=>{let t=qe(e);return(0,c.isDefined)(t)?t.getChildrenOfKind(h.SyntaxKind.ExpressionStatement).filter(e=>Je(e)&&Ze(e)):[]},$e=e=>{let t=qe(e);if((0,c.isDefined)(t))return t.getChildrenOfKind(h.SyntaxKind.ExpressionStatement).find(e=>Je(e)&&Ze(e))},et=e=>{let t=$e(e);return(0,c.isDefined)(t)},tt=e=>{let t=qe(e);if(!(0,c.isDefined)(t))return!0;let n=t.getChildrenOfKind(h.SyntaxKind.ExpressionStatement);if((0,c.isEmpty)(n))return!0;let r=new Set([`beforeEach`,`afterEach`,`beforeAll`,`afterAll`]);return n.every(e=>{let t=e.getExpressionIfKind(h.SyntaxKind.CallExpression)?.getExpressionIfKind(h.SyntaxKind.Identifier);return(0,c.isDefined)(t)?r.has(t.getText()):!1})},nt=e=>{if(e.isNamedExport?.())return Te.Named;if(e.isDefaultExport?.())return Te.Default;let t=e?.getParent();if((0,c.isDefined)(t)){if(t.isNamedExport?.())return Te.Named;if(t.isDefaultExport?.())return Te.Default}return e.isExportDefaultObject?.()??it(e.getSourceFile(),e.getName?.())?Te.ObjectDefault:Te.NotExported},rt=(e,t)=>(0,c.isDefined)(e)?nt(e):(0,c.isDefined)(t)?t.isNamedImport?Te.Named:Te.Default:Te.Unknown;function it(e,t){let[n]=e.getExportAssignments()??[];return n?.getDescendantsOfKind(h.SyntaxKind.Identifier).some(e=>(e.getSymbol()?.getEscapedName()??e.getText())===t)}function at(e,t){let n=Ye(We.get(e)),r=n.find(e=>e.getText().includes(t))??n[0],i=Qe(r),a=[],o=(0,c.isEmpty)(i)?[r]:i;for(let e of o){let t=qe(e);(0,c.isDefined)(t)&&a.push(...t.getChildrenOfKind(h.SyntaxKind.ExpressionStatement).filter(e=>Xe(e)))}return a}let ot=e=>e.getFirstDescendantByKind(h.SyntaxKind.StringLiteral)?.getLiteralValue(),st=e=>ot(e),U=e=>ot(e),ct=(e,t)=>{let n=e.getFullText().slice(0,Math.max(0,t)).split(`
|
|
32360
|
+
`):(this.indentate=function(){return``},this.tagEndChar=`>`,this.newLine=``)}function ye(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 be(e){return this.options.indentBy.repeat(e)}function xe(e){return!(!e.startsWith(this.options.attributeNamePrefix)||e===this.options.textNodeName)&&e.substr(this.attrPrefixLen)}ve.prototype.build=function(e){return this.options.preserveOrder?de(e,this.options):(Array.isArray(e)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(e={[this.options.arrayNodeName]:e}),this.j2x(e,0,[]).val)},ve.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}},ve.prototype.buildAttrPairStr=function(e,t){return t=this.options.attributeValueProcessor(e,``+t),t=this.replaceEntitiesValue(t),this.options.suppressBooleanAttributes&&t===`true`?` `+e:` `+e+`="`+t+`"`},ve.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}},ve.prototype.closeTag=function(e){let t=``;return this.options.unpairedTags.indexOf(e)===-1?t=this.options.suppressEmptyNode?`/`:`></${e}`:this.options.suppressUnpairedNode||(t=`/`),t},ve.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}},ve.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 Se={validate:s};t.exports=n})()})),wU=s((e=>{let t=ur(),n=xR(),r=t.__toESM(require(`@anthropic-ai/claude-agent-sdk`));e.getMessageContentBlocks=n.getMessageContentBlocks,e.isErrorResult=n.isErrorResult,e.isResultMessage=n.isResultMessage,Object.defineProperty(e,`query`,{enumerable:!0,get:function(){return r.query}})})),TU=s((e=>{let t=SR();e.buildFileToFlowMappingPrompt=t.buildFileToFlowMappingPrompt,e.buildFileToFlowMappingSystemPrompt=t.buildFileToFlowMappingSystemPrompt})),jee=s((e=>{let t=ur(),n=bR(),r=t.__toESM(require(`node:crypto`)),i=t.__toESM(PV());function a(e){if(typeof e!=`object`||!e)return;let t=e;if(Array.isArray(t.fileFlowMapping))return{fileFlowMapping:t.fileFlowMapping}}async function o(e,t,i,o,s,c,l,u){let{query:d,isResultMessage:f,isErrorResult:p}=await Promise.resolve().then(()=>wU()),{buildFileToFlowMappingSystemPrompt:m,buildFileToFlowMappingPrompt:h}=await Promise.resolve().then(()=>TU()),g=d({prompt:h(e,t,i,o,s),options:{model:n.REGRESSION_IMPACT_SONNET_MODEL,systemPrompt:m(u),allowedTools:[`Read`,`Grep`,`Glob`,`Bash`],permissionMode:n.REGRESSION_PERMISSION_MODE,allowDangerouslySkipPermissions:!0,maxBudgetUsd:n.REGRESSION_IMPACT_AGENTIC_MAX_BUDGET_USD,maxTurns:n.REGRESSION_IMPACT_AGENTIC_MAX_TURNS,cwd:i,sessionId:(0,r.randomUUID)(),outputFormat:{type:`json_schema`,schema:n.FILE_FLOW_MAPPING_OUTPUT_SCHEMA},env:{...process.env,ANTHROPIC_BASE_URL:l,ANTHROPIC_AUTH_TOKEN:c??``}}});for await(let e of g){if(!f(e))continue;if(p(e))return n.logger.info.defaultLog(`[regression-impact] File-to-flow mapping error: ${String(e.subtype)}`),{mappings:[],costUsd:0,turns:0,maxTurnsHit:!1};let r=e.total_cost_usd,i=e.num_turns,o=i>=n.REGRESSION_IMPACT_AGENTIC_MAX_TURNS,s=a(e.structured_output);return n.REGRESSION_LOG_COST&&n.logger.info.defaultLog(`[regression-impact] Batch (${t.length} files) cost: $${r.toFixed(4)}`),{mappings:s?.fileFlowMapping??[],costUsd:r,turns:i,maxTurnsHit:o}}return{mappings:[],costUsd:0,turns:0,maxTurnsHit:!1}}async function s(e,t,r,a,s,c,l,u){let d=[];for(let e=0;e<t.length;e+=n.REGRESSION_IMPACT_MAPPING_BATCH_SIZE)d.push(t.slice(e,e+n.REGRESSION_IMPACT_MAPPING_BATCH_SIZE));let f=d.length,p=0;n.logger.info.defaultLog(`[regression-impact] File-to-flow mapping: ${t.length} file(s) in ${f} batch(es) against ${e.length} flow(s)...`);let m=[],h=0,g=0,_=!1,v=new i.default({concurrency:n.REGRESSION_IMPACT_MAPPING_CONCURRENCY});for(let t of d)v.add(async()=>{try{let i=await o(e,t,r,a,s,c,l,u);for(let e of i.mappings){let t=e.flowIds.length>0?e.flowIds.join(`, `):`no flows`;p+=1,n.logger.info.defaultLog(`[regression-impact] ${p} - ${e.file} → ${t}`)}m.push(...i.mappings),h+=i.costUsd,g+=i.turns,_||=i.maxTurnsHit}catch(e){n.logger.info.defaultLog(`[regression-impact] File-to-flow mapping batch crashed (${t.length} file(s)): ${String(e)}`)}});return await v.onIdle(),{mappings:m,costUsd:h,turns:g,maxTurnsHit:_}}e.runFileToFlowMapping=s})),EU=s((e=>{let t=ur(),n=bR(),r=xR(),i=SR(),a=t.__toESM(CR()),o=t.__toESM(require(`node:fs/promises`)),s=t.__toESM(require(`node:async_hooks`)),c=t.__toESM(ie()),l=t.__toESM(Fc()),u=t.__toESM(require(`node:process`)),d=t.__toESM(require(`node:os`));t.__toESM(require(`node:tty`));let f=t.__toESM(require(`node:crypto`)),p=t.__toESM(require(`node:fs`)),m=t.__toESM(ez()),h=t.__toESM(vB()),g=t.__toESM(require(`node:child_process`)),_=t.__toESM(require(`node:util`)),v=t.__toESM(require(`@prisma/internals`)),y=t.__toESM(gB()),b=t.__toESM(require(`node:zlib`)),x=t.__toESM(xV()),S=t.__toESM(CV()),C=t.__toESM(kV()),w=t.__toESM(PV()),T=t.__toESM(require(`node:events`)),E=t.__toESM(OH()),D=t.__toESM(mU()),O=t.__toESM(xU()),k=t.__toESM(SU()),A=t.__toESM(CU()),ee=t.__toESM(kH());t.__toESM(require(`node:readline`));let j=t.__toESM(require(`node:path`)),te=t.__toESM(require(`node:module`)),M=t.__toESM(require(`@anthropic-ai/claude-agent-sdk`));var N=class e{rootPath;absolutePath;static EARLY_FILENAME_VAR=`$early_filename`;constructor(e){this.rootPath=a.default.normalizeTrim(n.getGlobalConfig().getRootPath());let t=a.default.normalizeTrim(e),r=a.default.normalizeTrim(this.rootPath);if(t===r||t.startsWith(r+a.default.sep))this.absolutePath=t;else{let e=t.replace(/^\//,``);this.absolutePath=a.default.resolve(this.rootPath,e)}}static fromSourceFile(t){let r=a.default.normalizeTrim(t.getFilePath());return new e(a.default.relative(a.default.normalizeTrim(n.getGlobalConfig().getRootPath()),r))}static fromAbsolutePath(t){let r=a.default.normalizeTrim(t);return new e(a.default.relative(a.default.normalizeTrim(n.getGlobalConfig().getRootPath()),r))}static fromRelativePath(t){return new e(t)}getRelativeFilePath(){return a.default.relative(this.rootPath,this.absolutePath)}getAbsoluteFilePath(){return this.absolutePath}async isFileExists(){try{return(await o.default.stat(this.absolutePath)).isFile()}catch{return!1}}async isDirectoryExists(){try{return(await o.default.stat(this.absolutePath)).isDirectory()}catch{return!1}}async createDirectory(e){await o.default.mkdir(this.absolutePath,{recursive:e?.recursive??!0})}async getText(){try{return await o.default.readFile(this.absolutePath,`utf8`)}catch{return``}}async upsert(e){let t=a.default.dirname(this.absolutePath);await o.default.mkdir(t,{recursive:!0}),await(await this.isFileExists()?o.default.appendFile(this.absolutePath,e):o.default.writeFile(this.absolutePath,e)),n.logger.info.defaultLog(`Upserted file`,{path:this.getRelativeFilePath()})}async replace(e){let t=a.default.dirname(this.absolutePath);await o.default.mkdir(t,{recursive:!0}),await o.default.writeFile(this.absolutePath,e),n.logger.info.defaultLog(`Replaced file`,{path:this.getRelativeFilePath()})}async delete(){try{await o.default.unlink(this.absolutePath),n.logger.info.defaultLog(`Deleted file`,{path:this.getRelativeFilePath()})}catch{}}};let P={WIN32:`win32`,DARWIN:`darwin`,LINUX:`linux`},F={JAVASCRIPT:`javascript`,TYPESCRIPT:`typescript`,PYTHON:`python`},I=e=>{let t=n.getGlobalConfig().getRootPath();return a.default.resolve(t,e)},L=e=>{let t=n.getGlobalConfig().getRootPath(),r=a.default.normalize(e);return a.default.relative(t,r)},ne=e=>({".js":`javascript`,".mjs":`javascript`,".cjs":`javascript`,".jsx":`javascript`,".ts":`typescript`,".tsx":`typescript`,".py":`python`})[e.toLowerCase()]??`javascript`;function R(e){return ne((0,a.extname)(e))}function z(e){return ne((0,a.extname)(e))===`typescript`}function re(e){return ne((0,a.extname)(e))===F.PYTHON}function B(e){let t=n.getGlobalConfig().getRootPath();if(!(0,c.isDefined)(t))throw Error(`Workspace root path is not defined`);if((0,c.isEmpty)(e))return a.default.normalize(t);let r=a.default.normalize(t),i=a.default.normalize(e);if(process.platform===P.WIN32){let t=r.split(`:`)[0].toUpperCase(),n=i.split(`:`)[0].toUpperCase();if(t!==n&&!n.startsWith(t))return e}return a.default.relative(r,i)}function V(e){return e.startsWith(`../`)?`../${e}`:e.startsWith(`./`)?`.${e}`:e}function ae(e){let t=a.default.normalize(I(e)),n=a.default.normalize((0,m.default)([`package.json`,`project.json`],{cwd:t})??``);if(!n)return``;let r=L((0,a.dirname)(n));return r.startsWith(`/`)?r.slice(1):r}function oe(e,t,n){if(!ce(e))return e;let r=n===``?t:t.replace(n,``),i=n===``?ue(r):le(r),o=r.split(`/`).slice(0,-1),s=se(e,`../`),c=s>0?o.slice(0,-s).join(`/`):(0,a.dirname)(r),l=e.replaceAll(`../`,``).replaceAll(`./`,``);return a.default.join(i,c,l)}function se(e,t){return e.split(t).length-1}function ce(e){return e.startsWith(`../`)||e.startsWith(`./`)}function le(e){let t=se(e,`/`);return`../`.repeat(t-1)}function ue(e){let t=se(e,`/`);return`../`.repeat(t+1)}function de(e){return e?.includes(`node_modules/`)}let fe=e=>e.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`),pe=e=>process.platform===`win32`?`"${e.replaceAll(`"`,String.raw`\"`)}"`:`'${e.replaceAll(`'`,`'"'"'`)}'`;function me(e,t){let n=a.default.isAbsolute(e)?e:I(e);return(0,m.default)(t,{cwd:n})}function he(e,t){let n=me(e,t);if(!(0,c.isDefined)(n))return;let r=p.readFileSync(n,`utf8`);return JSON.parse(r)}function ge(e){return he(e,`package.json`)}function _e(e,t){let{dependencies:n={},devDependencies:r={}}=e;return Object.keys({...r,...n}).includes(t)}let ve=[{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}],ye=[`@typescript-eslint/no-undefined`,`unicorn/no-useless-undefined`,`no-undefined`];async function be(e){for(let{path:t,isFlat:n}of ve){let r=a.default.join(e,t);if(await N.fromAbsolutePath(r).isFileExists())return{path:r,isFlat:n}}return ge(e)?.eslint?{path:me(e,`package.json`),isFlat:!1}:{path:null,isFlat:!1}}let xe={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`,REGRESSION_IMPACT:`regression-impact`,REGRESSION_CATALOG:`regression-catalog`},Se={CODE_EXTRACTOR:`code-extractor`,CODE_REFINEMENT:`code-refinement`,TEST_MANAGEMENT:`test-management`,TEST_VALIDATOR:`test-validator`,CONFIG_FILE:`config-file`,COMMAND_EXECUTION:`command-execution`},Ce=[`.jsx`,`.tsx`],we=[`it`,`test`,`it.each`,`test.each`],Te=function(e){return e.Default=`default`,e.ObjectDefault=`object-default`,e.Named=`named`,e.Unknown=`unknown`,e.NotExported=`not-exported`,e}({}),Ee=function(e){return e.PRIVATE=`private`,e.PROTECTED=`protected`,e.PUBLIC=`public`,e}({}),De=function(e){return e.REACT=`react`,e.ANGULAR=`angular`,e}({}),Oe=`unknown`,ke=`tests`,Ae=(0,_.promisify)(g.default.exec);async function je(e,{cwd:t=n.getGlobalConfig().getRootPath(),timeout:r=1e4}={}){return(await Ae(e,{cwd:t,maxBuffer:500*1024,timeout:r}))?.stdout?.toString()??``}let Me=e=>{let t=I(e);return(0,m.default)(`jest.config.+(js|ts|mjs|cjs|json)`,{cwd:t})},Ne=e=>(0,c.isObject)(e)&&(0,c.isString)(e.rootDir),Pe=async e=>{let t;if(n.logger.addContext({subCategory:Se.CONFIG_FILE}),(0,c.isDefined)(e)){let n=Me(e);n!==null&&(t=(0,a.dirname)(n))}t??=n.getGlobalConfig().getRootPath();let r;try{if(r=await je(`npx jest --showConfig`,{cwd:t}),!(0,c.isString)(r))throw n.logger.info.defaultLog(`Jest config return is not a string`,r),Error(`Jest config return is not a string`);let e=JSON.parse(r);if((0,c.isObject)(e)&&(0,c.isArray)(e.configs)&&e.configs.every(e=>Ne(e)))return{projectConfigs:e.configs,globalConfig:e.globalConfig,configs:e.configs}}catch(e){n.logger.info.defaultLog(`Cannot read jest config`,(0,c.getErrorMessage)(e)),n.logger.info.defaultLog(`Failed reading jest config`,e,(0,c.getErrorMessage)(e));return}n.logger.info.defaultLog(`Invalid jest config or config in not supported format`)},Fe=async()=>{let e=[n.getGlobalConfig().getRootPath()],t=a.default.join(`node_modules`,`.prisma`,`client`,`index.d.ts`),r=e.map(e=>a.default.join(e,t)).map(e=>N.fromAbsolutePath(e));return(await(0,c.filterAsync)(r,e=>e.isFileExists())).map(e=>e.getAbsoluteFilePath())},Ie=async()=>{try{let e=n.getGlobalConfig().getRootPath();if(!(0,c.isDefined)(e))return[];let t=await(0,v.getSchemaWithPathOptional)(``,``,{cwd:e});if(!(0,c.isDefined)(t))return[];let r=t.schemas.map(e=>e[1]),i=new Set;for(let e of r){let n=(await(0,v.getConfig)({datamodel:e,ignoreEnvVarErrors:!0})).generators;for(let e of n)if((0,c.isDefined)(e.output?.value)){let n=a.default.join(a.default.resolve(t.schemaRootDir,e.output.value),`index.d.ts`);await N.fromAbsolutePath(n).isFileExists()&&i.add(n)}}return[...i]}catch(e){return n.logger.error(`Failed to get prisma typings paths`,e),[]}},Le=async()=>(await Promise.all([Fe(),Ie()])).flat(),Re=async(e,t=!1,r)=>{let i=`!**/node_modules/**`;if(t)return new h.Project({useInMemoryFileSystem:!0,compilerOptions:r});let o=z(e),s=ze((0,a.dirname)(I(e)),n.getGlobalConfig().isSiblingFolderStructured());if(!o&&!(0,c.isDefined)(s)){let t=await Ve(e);if(!(0,c.isDefined)(t)||(0,c.isEmpty)(t))throw Error(`Cannot find source code path in jest config`);let n=new h.Project({compilerOptions:{allowJs:!0,maxNodeModuleJsDepth:0},useInMemoryFileSystem:!1});return n.addSourceFilesAtPaths([...t,i]),n}if(!o&&(0,c.isDefined)(s)){let t=new h.Project({tsConfigFilePath:s,compilerOptions:{allowJs:!0,maxNodeModuleJsDepth:0}}),n=await Ve(e);return t.addSourceFilesAtPaths([...n,i]),t}let l={maxNodeModuleJsDepth:0};if(n.getGlobalConfig().isRootFolderStructured()){let e=n.getGlobalConfig().getRootPath();l.rootDirs=[a.default.resolve(e,`src`),a.default.resolve(e,ke)]}let u=new h.Project({tsConfigFilePath:s,compilerOptions:l}),d=await Le();for(let e of d)u.addSourceFileAtPath(e);return u},ze=(e,t)=>{let n;try{n=Be(e)}catch{t&&(n=Be((0,a.dirname)(e)))}return n},Be=e=>{let t=e,n=/^(tsconfig|jsconfig).*\.json$/;for(;t!==(0,a.dirname)(t);){let e=(0,a.join)(t,`tsconfig.json`),r=(0,a.join)(t,`jsconfig.json`);if(!(0,p.existsSync)(t))return Be((0,a.dirname)(t));if((0,p.existsSync)(e))return e;if((0,p.existsSync)(r))return r;let i=(0,p.readdirSync)(t);for(let e of i)if(n.test(e))return(0,a.join)(t,e);t=(0,a.dirname)(t)}},Ve=async e=>{let t=await Pe(e);if((0,c.isDefined)(t)){let e=t?.configs[0].roots.map(e=>a.default.join(e,`**/*.{ts,js,tsx,jsx}`));if(!(0,c.isEmpty)(e))return e}return[I(ae(e))]};var H=t.__toESM(n.require_decorateMetadata()),He=t.__toESM(n.require_decorate());let Ue=`The ts-morph project is not initialized.`,We=new class{storage=new s.AsyncLocalStorage;_project;clear(){this._project=void 0}async init(e,t,n){let r=I(e);if((0,c.isDefined)(this._project))return this._project.addSourceFileAtPathIfExists(r);this._project=await Re(e,t,n);let i=this.storage.getStore();if((0,c.isDefined)(i))return this._project.addSourceFileAtPathIfExists(r)}add(e,t){let n=I(e),r=this.storage.getStore()?.getProject();if(!(0,c.isDefined)(r))throw Error(Ue);return r.createSourceFile(n,t,{overwrite:!0})}update(e,t){let n=this.get(e);return n.replaceWithText(t),n}addFile(e){(0,c.isDefined)(this._project)&&this._project.addSourceFileAtPathIfExists(e)}removeFile(e){if(!(0,c.isDefined)(this._project))return;let t=this._project.getSourceFile(e);(0,c.isDefined)(t)&&this._project.removeSourceFile(t)}async refreshFromFileSystem(e){if(!(0,c.isDefined)(this._project))return;let t=I(e),n=this._project?.getSourceFile(e)??this._project?.getSourceFile(t);if((0,c.isDefined)(n)){let e=n.getFilePath();this._project.removeSourceFile(n),this._project.addSourceFileAtPath(e)}}get(e){let t=I(e),n=this.storage.getStore()?.getProject();if(!(0,c.isDefined)(n))throw Error(Ue+` store`);let r=n.getSourceFile(t);if(!(0,c.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=I(e);return this._project?.getSourceFile(t)}withContext=(e,t,n)=>{let r=n.value,i=this.storage;if((0,c.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}},Ge=We.withContext,Ke=async e=>{class t{async fn(){return e()}}(0,He.default)([Ge,(0,H.default)(`design:type`,Function),(0,H.default)(`design:paramtypes`,[]),(0,H.default)(`design:returntype`,Promise)],t.prototype,`fn`,null),await new t().fn()},qe=e=>{let t=e?.asKind(h.SyntaxKind.ExpressionStatement)?.getExpression();if(!(0,c.isDefined)(t))return;let n=t.asKind(h.SyntaxKind.CallExpression)?.getArguments()?.at(-1),r=n?.asKind(h.SyntaxKind.ArrowFunction)?.getBody(),i=n?.asKind(h.SyntaxKind.FunctionExpression)?.getBody();return r?.asKind(h.SyntaxKind.Block)??i?.asKind(h.SyntaxKind.Block)},Je=e=>h.Node.isExpressionStatement(e)&&e.getFirstChildByKind(h.SyntaxKind.CallExpression)?.getFirstChildByKind(h.SyntaxKind.Identifier)?.getText()===`describe`,Ye=e=>e.getStatements().filter(e=>Je(e)),Xe=e=>{let t=e.getExpression().getFirstChild()?.getText();return!(0,c.isDefined)(t)||(0,c.isEmpty)(t)?!1:we.some(e=>t.startsWith(e))},Ze=e=>{let t=qe(e);return(0,c.isDefined)(t)?t.getChildrenOfKind(h.SyntaxKind.ExpressionStatement).some(e=>Xe(e)):!1},Qe=e=>{let t=qe(e);return(0,c.isDefined)(t)?t.getChildrenOfKind(h.SyntaxKind.ExpressionStatement).filter(e=>Je(e)&&Ze(e)):[]},$e=e=>{let t=qe(e);if((0,c.isDefined)(t))return t.getChildrenOfKind(h.SyntaxKind.ExpressionStatement).find(e=>Je(e)&&Ze(e))},et=e=>{let t=$e(e);return(0,c.isDefined)(t)},tt=e=>{let t=qe(e);if(!(0,c.isDefined)(t))return!0;let n=t.getChildrenOfKind(h.SyntaxKind.ExpressionStatement);if((0,c.isEmpty)(n))return!0;let r=new Set([`beforeEach`,`afterEach`,`beforeAll`,`afterAll`]);return n.every(e=>{let t=e.getExpressionIfKind(h.SyntaxKind.CallExpression)?.getExpressionIfKind(h.SyntaxKind.Identifier);return(0,c.isDefined)(t)?r.has(t.getText()):!1})},nt=e=>{if(e.isNamedExport?.())return Te.Named;if(e.isDefaultExport?.())return Te.Default;let t=e?.getParent();if((0,c.isDefined)(t)){if(t.isNamedExport?.())return Te.Named;if(t.isDefaultExport?.())return Te.Default}return e.isExportDefaultObject?.()??it(e.getSourceFile(),e.getName?.())?Te.ObjectDefault:Te.NotExported},rt=(e,t)=>(0,c.isDefined)(e)?nt(e):(0,c.isDefined)(t)?t.isNamedImport?Te.Named:Te.Default:Te.Unknown;function it(e,t){let[n]=e.getExportAssignments()??[];return n?.getDescendantsOfKind(h.SyntaxKind.Identifier).some(e=>(e.getSymbol()?.getEscapedName()??e.getText())===t)}function at(e,t){let n=Ye(We.get(e)),r=n.find(e=>e.getText().includes(t))??n[0],i=Qe(r),a=[],o=(0,c.isEmpty)(i)?[r]:i;for(let e of o){let t=qe(e);(0,c.isDefined)(t)&&a.push(...t.getChildrenOfKind(h.SyntaxKind.ExpressionStatement).filter(e=>Xe(e)))}return a}let ot=e=>e.getFirstDescendantByKind(h.SyntaxKind.StringLiteral)?.getLiteralValue(),st=e=>ot(e),U=e=>ot(e),ct=(e,t)=>{let n=e.getFullText().slice(0,Math.max(0,t)).split(`
|
|
32214
32361
|
`);return{line:n.length,column:(n.at(-1)?.length??0)+1}},lt=(e,t)=>{let n=t.getStart(),r=t.getEnd(),{line:i,column:a}=ct(e,n),{line:o,column:s}=ct(e,r);return{startLine:i,startColumn:a,startIndex:n,endLine:o,endColumn:s,endIndex:r}},ut=e=>e.getDescendantsOfKind(h.SyntaxKind.ExpressionStatement).filter(e=>Xe(e)),dt=(e,t,n,r)=>{let i=r?`.tsx`:`.ts`,a=t+Date.now()+(0,f.randomUUID)()+i;return e.createSourceFile(a,n)},ft=e=>e.getDescendantsOfKind(h.SyntaxKind.CallExpression).reduce((e,t)=>{let n=t.getExpression(),r=n.getParentIfKind(h.SyntaxKind.VariableDeclaration);return(0,c.isDefined)(r)&&n.getText()===`require`&&e.push(r),e},[]),pt=e=>{let t=e.getFirstChildByKind(h.SyntaxKind.CallExpression);if(!(0,c.isDefined)(t))return;let[n]=t.getArguments();if(!(!(0,c.isDefined)(n)||n.getKind()!==h.SyntaxKind.StringLiteral))return n.getText().slice(1,-1)},mt=e=>{let t=[`${n.getGlobalConfig().getEarlyTestFilenameSuffix()}.ts`,`.test.ts`,`.spec.ts`,`.test.tsx`,`.spec.tsx`,`.test.js`,`.spec.js`,`.test.jsx`,`.spec.jsx`],r=e.getFilePath(),i=`_`+(0,f.randomUUID)()+`_temp`;for(let e of t)if(r.endsWith(e))return r.slice(0,-e.length)+i+e;let a=r.split(`.`);return a[a.length-2]+=i,a.join(`.`)},ht=(e,t=e.getFullText())=>{let n=mt(e);return e.getProject().createSourceFile(n,t)},gt=e=>e.getSymbol()?.getDeclarations()?.[0]?.getSourceFile()??e.getAliasSymbol()?.getDeclarations()?.[0]?.getSourceFile(),_t=(e,t)=>{let n=e.getRelativePathTo(t.getFilePath());n=n.replaceAll(`\\`,`/`);let r=a.default.extname(n);return n=n.replaceAll(r,``),n.startsWith(`.`)||(n=`./`+n),n},vt=[h.SyntaxKind.JsxElement,h.SyntaxKind.JsxOpeningElement,h.SyntaxKind.JsxClosingElement,h.SyntaxKind.JsxExpression,h.SyntaxKind.JsxSelfClosingElement,h.SyntaxKind.JsxAttributes,h.SyntaxKind.JsxAttribute,h.SyntaxKind.JsxFragment,h.SyntaxKind.JsxOpeningFragment,h.SyntaxKind.JsxClosingFragment,h.SyntaxKind.JsxNamespacedName,h.SyntaxKind.JsxSpreadAttribute,h.SyntaxKind.JsxText,h.SyntaxKind.JsxTextAllWhiteSpaces],yt=e=>vt.some(t=>(0,c.isDefined)(e.getFirstDescendantByKind(t))),bt=e=>vt.some(t=>(0,c.isDefined)(e.getParentIfKind(t))),xt=e=>{let t=e.compilerType;if(`id`in t&&(0,c.isNumber)(t.id)){let e=t.id;return e===0?null:e}return null},St=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(`.`)),Ct=`anonymousFunction`;var wt=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,c.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(h.SyntaxKind.CallExpression),n=t?.getFirstDescendantByKind(h.SyntaxKind.PropertyAccessExpression),r=t?.getFirstDescendantByKind(h.SyntaxKind.Identifier);return[n?.getText(),r?.getText()].some(e=>(0,c.isDefined)(e)?[...St.values()].some(t=>e.includes(t)):!1)}).map(e=>{let t=e.getFirstDescendantByKind(h.SyntaxKind.VariableDeclaration)?.getFirstChildByKind(h.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()??Ct,n=this.isEntityExported(t)||e.isExported();return{...this.getLocationPivot(e),name:t,type:`function`,node:e,canCreateTests:n}})}getFunctionsExpressions(){return this.sourceFile.getDescendantsOfKind(h.SyntaxKind.FunctionExpression).filter(e=>e.getParentIfKind(h.SyntaxKind.ExportAssignment)?.isExportEquals()??!(this.isCallbackFunction(e)||this.isInnerFunction(e)||this.isJSXFunction(e))).map(e=>{let t=e.getName()??this.getArrowFunctionName(e)??Ct,n=this.isEntityExported(t);return{...this.getLocationPivot(e),name:t,type:`function`,node:e,canCreateTests:n}})}getArrowFunctionsExpressions(){return this.sourceFile.getDescendantsOfKind(h.SyntaxKind.ArrowFunction).filter(e=>e.getParentIfKind(h.SyntaxKind.ExportAssignment)?.isExportEquals()??!(this.isCallbackFunction(e)||this.isInnerFunction(e)||this.isJSXFunction(e))).map(e=>{let t=this.getArrowFunctionName(e)??Ct,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()===h.SyntaxKind.CallExpression}isJSXFunction(e){return bt(e)}isInnerFunction(e){let t=e.getParent(),n=0;for(;(0,c.isDefined)(t)&&t.getKind()!==h.SyntaxKind.SourceFile&&n<20;){if(t.getKind()===h.SyntaxKind.ArrowFunction)return!0;t=t.getParent(),n++}return!1}getArrowFunctionName(e){let t=e.getParent();if(t?.getKind()===h.SyntaxKind.BinaryExpression&&t?.getFirstChild()?.getKind()===h.SyntaxKind.PropertyAccessExpression)return e.getParent()?.getFirstChildByKind(h.SyntaxKind.PropertyAccessExpression)?.getName();let n=e.getFirstAncestorByKind(h.SyntaxKind.VariableDeclaration);if((0,c.isDefined)(n))return n.getName();let r=e.getFirstAncestorByKind(h.SyntaxKind.PropertyAssignment);if((0,c.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(h.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(h.SyntaxKind.BinaryExpression).map(e=>e.getRight()).filter(e=>h.Node.isObjectLiteralExpression(e)),t=this.sourceFile.getExportAssignments().map(e=>e.getExpression()).filter(e=>h.Node.isObjectLiteralExpression(e));return[...e,...t].flatMap(e=>e.getProperties()).filter(e=>h.Node.isMethodDeclaration(e)).map(e=>({...this.getLocationPivot(e),type:`object-method`,node:e,name:e.getName(),canCreateTests:!0}))}getLocationPivot(e){return lt(this.sourceFile,e)}isEntityExported(e){return(0,c.isDefined)(e)&&!(0,c.isEmpty)(e)?this.exportedDeclarations.includes(e):!1}isEntityExportedWithThis(e){let t=e.getParent()?.getChildren()??[];return t[0]?.getFirstChild()?.getKind()===h.SyntaxKind.ThisKeyword&&t[1]?.getKind()===h.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 Tt=`default`;var Et=class{constructor(e,t){this.sourceFile=e,this.isUsingJSX=t}getImports(){return[...this.getESMImportsNodes(),...this.getCJSImportsNodes()].map(e=>({name:`Import`,location:lt(this.sourceFile,e),node:e,type:`import`,sourceValue:(h.Node.isImportDeclaration(e)?e.getModuleSpecifierValue():e.getFirstDescendantByKind(h.SyntaxKind.StringLiteral)?.getLiteralValue())??``}))}getCJSImportsNodes(){return this.sourceFile.getVariableStatements().filter(e=>(e.getFirstDescendantByKind(h.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(h.SyntaxKind.ExportAssignment).length>0;return e||t||n}getCJSExports(){let e=[],t=``,n=`module.exports`,r=`exports`;for(let i of this.sourceFile.getDescendantsOfKind(h.SyntaxKind.ExpressionStatement)){let a=i.getExpression(),o=a.getText().trim(),s=a.asKind(h.SyntaxKind.BinaryExpression);if(!o.startsWith(n)&&!o.startsWith(r)||!(0,c.isDefined)(s))continue;let l=s.getLeft(),u=l.getText(),d=l.asKind(h.SyntaxKind.PropertyAccessExpression),f=d?.getName()??``,p=l.getKind()===h.SyntaxKind.PropertyAccessExpression,m=s.getRight(),g=p&&d?.getExpression().getText()===n,_=p&&d?.getExpression().getText()===r;if(g&&f===Tt){t=m.getText();continue}if(g||_){e.push(f);continue}if(u!==n)continue;let v=t=>{let n=t.asKind(h.SyntaxKind.ObjectLiteralExpression);if((0,c.isDefined)(n))for(let t of n.getProperties()){if(t.getKind()===h.SyntaxKind.PropertyAssignment||t.getKind()===h.SyntaxKind.ShorthandPropertyAssignment||t.getKind()===h.SyntaxKind.MethodDeclaration){let n=t.getName();e.push(n)}if(t.getKind()===h.SyntaxKind.PropertyAssignment){let e=t.getInitializer();(0,c.isDefined)(e)&&v(e)}}},y=t=>{let n=t.asKind(h.SyntaxKind.FunctionDeclaration)?.getBody()?.asKind(h.SyntaxKind.Block);if((0,c.isDefined)(n))for(let t of n.getStatements()){let n=((t.asKind(h.SyntaxKind.ExpressionStatement)?.getExpression())?.asKind(h.SyntaxKind.BinaryExpression)?.getLeft())?.asKind(h.SyntaxKind.PropertyAccessExpression);n?.getExpression().getKind()===h.SyntaxKind.ThisKeyword&&e.push(n.getName())}},b=t=>{let n=t.asKind(h.SyntaxKind.FunctionDeclaration)?.getName();if((0,c.isDefined)(n))for(let t of this.sourceFile.getStatements()){let r=((t.asKind(h.SyntaxKind.ExpressionStatement)?.getExpression())?.asKind(h.SyntaxKind.BinaryExpression)?.getLeft())?.asKind(h.SyntaxKind.PropertyAccessExpression);r?.getExpression().getText()===`${n}.prototype`&&e.push(r.getName())}};if(m.getKind()===h.SyntaxKind.ObjectLiteralExpression){v(m);continue}if(m.getKind()===h.SyntaxKind.Identifier){let t=m.asKind(h.SyntaxKind.Identifier),n=t?.findReferences().map(e=>e.getDefinition().getNode().getParent()).filter(e=>(0,c.isDefined)(e)).filter(e=>e.getKind()===h.SyntaxKind.VariableDeclaration);if(!(0,c.isDefined)(n))continue;for(let t of n){let n=t.getInitializer()?.asKind(h.SyntaxKind.ObjectLiteralExpression);if((0,c.isDefined)(n)){for(let t of n.getProperties())if(t.getKind()===h.SyntaxKind.PropertyAssignment||t.getKind()===h.SyntaxKind.ShorthandPropertyAssignment){let n=t.getName();e.push(n)}}}let r=t?.findReferences().map(e=>e.getDefinition().getNode().getParent()).filter(e=>e?.getKind()===h.SyntaxKind.FunctionDeclaration);if(!(0,c.isDefined)(r))continue;for(let e of r)y(e),b(e)}if(m.isKind(h.SyntaxKind.NewExpression)){let e=m.asKind(h.SyntaxKind.NewExpression);(0,c.isDefined)(e)&&(t=e.getExpression().getText());continue}t=m.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()===h.SyntaxKind.Identifier){e=i.getText();continue}let a=r.getFirstChildByKind(h.SyntaxKind.ObjectLiteralExpression);if((0,c.isDefined)(a)){for(let e of a.getProperties())if(e.getKind()===h.SyntaxKind.PropertyAssignment||e.getKind()===h.SyntaxKind.ShorthandPropertyAssignment||e.getKind()===h.SyntaxKind.MethodDeclaration){let n=e.getName();t.push(n)}}}let r=this.sourceFile.getExportedDeclarations();if(!(n&&r.size===1&&[...r.keys()][0]===Tt))for(let[n,i]of r)if(n===Tt){let t=(i[0]?.getFirstChildByKind(h.SyntaxKind.Identifier))?.getText()?.trim()??Ct;(0,c.isDefined)(t)&&(e=t)}else t.push(n);return{defaultExport:e,namedExports:t}}hasRequire(){return this.sourceFile.getDescendantsOfKind(h.SyntaxKind.CallExpression).some(e=>e.getExpression().getText()===`require`)}transformRequiresToImports(){let e=dt(this.sourceFile.getProject(),`transformRequiresToImports`,this.sourceFile.getFullText(),this.isUsingJSX),t;try{let n=e.getVariableStatements();for(let e of n){let t=e.getFirstDescendantByKind(h.SyntaxKind.CallExpression),n=t?.getExpression();if(!(0,c.isDefined)(t)||!(0,c.isDefined)(n)||n.getText()!==`require`)continue;let r=t.getFirstDescendantByKind(h.SyntaxKind.StringLiteral)?.getLiteralValue();if(!(0,c.isDefined)(r))continue;let i=e.getDeclarations()?.[0]?.getNameNode()?.getText();if(!(0,c.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()}},Dt=class{tests;constructor(e){this.sourceFile=e}getDescribes(){return Ye(this.sourceFile).map(e=>{let t=st(e);return(0,c.isDefined)(t)?{node:e,name:t,location:lt(this.sourceFile,e),type:`describe`}:null}).filter(e=>(0,c.isDefined)(e))}getTests(){return(0,c.isDefined)(this.tests)||(this.tests=ut(this.sourceFile).map(e=>{let t=lt(this.sourceFile,e),n=U(e);return(0,c.isDefined)(n)?{node:e,name:n,location:t,type:`test`}:null}).filter(e=>(0,c.isDefined)(e))),this.tests}getDescribeTests(e){return ut(e.node).map(e=>{let t=U(e);return(0,c.isDefined)(t)?{node:e,name:t,location:lt(this.sourceFile,e),type:`test`}:null}).filter(e=>(0,c.isDefined)(e))}},Ot=class{sourceFile;tests;testables;moduleInfo;constructor(e,t){this.filePath=t;let n=!0;try{let t=new h.Project({useInMemoryFileSystem:!0,skipAddingFilesFromTsConfig:!0,skipFileDependencyResolution:!0,skipLoadingLibFiles:!0}),r=dt(t,`ast`,e,!0);yt(r)?this.sourceFile=r:(t.removeSourceFile(r),this.sourceFile=dt(t,`ast`,e,!1),n=!1)}catch{throw Error(`Cannot parse file content`)}this.moduleInfo=new Et(this.sourceFile,n),this.testables=new wt(this.sourceFile,this.moduleInfo),this.tests=new Dt(this.sourceFile)}isReactFile(){let e=(0,a.extname)(this.filePath??this.sourceFile.getFilePath());return Ce.includes(e)||this.isFileContainsImport(`react`)}isFileContainsImport(e){return this.moduleInfo.getImports().some(t=>t.sourceValue.includes(e))}checkIsJSDoc(e,t,n){return t===h.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,c.isEmpty)(r.slice(t,e.start).trim())&&(0,c.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 kt=e=>{let{node:t,parent:n,...r}=e;return r};var At=class{GITIGNORE_FILE_NAME=`.gitignore`;gitignorePath;constructor(e){this.gitignorePath=(0,a.join)(e,this.GITIGNORE_FILE_NAME)}async add(e){try{let t=await o.default.readFile(this.gitignorePath,`utf8`);t.includes(e)||await o.default.writeFile(this.gitignorePath,`${t}\n${e}`)}catch(e){let t=e instanceof Error?e.message:`Unknown error`;n.logger.info.defaultLog(`Error reading gitignore file`,{message:t})}}};let jt=`.early.coverage`;var Mt=class{getCoverageDirectoryPath(){let e=n.getGlobalConfig().getRootPath();return a.default.join(e,jt,`v8`)}getCoverageDirectoryForCommand(){return this.getCoverageDirectoryPath()}getExecutionCwd(){return n.getGlobalConfig().getRootPath()}},Nt=class extends Mt{getCoverageDirectoryForCommand(){let e=n.getGlobalConfig().getGitTopLevel(),t=n.getGlobalConfig().getRootPath(),r=a.default.relative(e,t);return a.default.join(r,jt,`v8`)}};function Pt(){let e=n.getGlobalConfig().getCoverageCommand()?.split(/\s+/).includes(`nx`)??!1;return n.logger.info.defaultLog(`Coverage path strategy: `+(e?`nx`:`standard`)),e?new Nt:new Mt}var Ft=class{report={};constructor(e,t){for(let[n,r]of Object.entries(e)){let e=a.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,c.isDefined)(r))return null;let i=this.findFunctionDefinition(t,r.fnMap,n);if(!(0,c.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,c.isDefined)(t)&&t>0&&a++}return{percentage:this.toPercentage(a,o),totalStatements:o,coveredStatements:a}}getStatsForFile(e){let t=this.report[e];if(!(0,c.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,c.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,c.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,c.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=a.default.relative(e,t);return(0,c.isDefined)(n)?!n.startsWith(`..`)&&!a.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 It(e){let t=n.getGlobalConfig().getRootPath(),r=[];try{let e=new N(`.gitignore`);await e.isFileExists()&&(r=(await e.getText()).split(`
|
|
32215
32362
|
`).map(e=>e.trim()).filter(e=>(0,c.isDefined)(e)&&!e.startsWith(`#`)))}catch{}let i=[`node_modules`,`*.config.ts`,`**/*.mock.ts`,`**/*.mocks.ts`,`**/*.test.ts`,`**/*.spec.ts`,...r];return(await(0,y.default)(e,{cwd:t,absolute:!0,ignore:i})).map(e=>`/${a.default.relative(t,e)}`)}var Lt=class{nextSource=null;setNext(e){return this.nextSource=e,e}async getFromNext(e){return this.nextSource?this.nextSource.getFiles(e):[]}},Rt=class extends Lt{async getFiles(e){return It(`**/*.{js,ts,jsx,tsx}`)}};let zt=/\.[jt]sx?$/;var Bt=class extends Lt{async getFiles(e){let t=Object.keys(e).filter(e=>zt.test(e));return t.length>0?t:this.getFromNext(e)}};function Vt(){let e=new Bt,t=new Rt;return e.setNext(t),e}let Ht=String.raw`.*\.early\.(spec|test)\.[tj]sx?$`;var Ut=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=Pt()}getCoverageDirectoryPath(){if(!(0,c.isDefined)(this.pathStrategy))throw Error(`Provider not initialized. Call init() first.`);return this.pathStrategy.getCoverageDirectoryPath()}getCoverageDirectoryForCommand(){if(!(0,c.isDefined)(this.pathStrategy))throw Error(`Provider not initialized. Call init() first.`);return this.pathStrategy.getCoverageDirectoryForCommand()}getExecutionCwd(){if(!(0,c.isDefined)(this.pathStrategy))throw Error(`Provider not initialized. Call init() first.`);return this.pathStrategy.getExecutionCwd()}getCoverageReportPath(){return a.default.join(this.getCoverageDirectoryPath(),this.COVERAGE_REPORT_FILE_NAME)}async getCommand(e){let t=n.getGlobalConfig().getCoverageCommand(),r=(0,c.isDefined)(e)&&e.length>0?this.formatTestFiles(e):``;if((0,c.isDefined)(t)){let e=t.replaceAll(n.EARLY_COVERAGE_DIR,this.getCoverageDirectoryForCommand()).replaceAll(n.EARLY_TEST_FILES_VAR,r);return!t.includes(n.EARLY_TEST_FILES_VAR)&&r&&(e=`${e} ${r}`),e}return(await this.buildJestCoverageCommand(e)).replaceAll(n.EARLY_COVERAGE_DIR,this.getCoverageDirectoryForCommand())}async isReportExists(){try{return await o.default.access(this.getCoverageReportPath(),o.constants.R_OK),!0}catch{return!1}}async removeReport(){try{let e=N.fromAbsolutePath(this.getCoverageReportPath());await e.isFileExists()&&await e.delete()}catch(e){n.logger.error(`Error removing coverage report`,e)}}async getReport(){try{let e=await N.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){n.logger.info.defaultLog(`Coverage: generation started`),await this.removeReport();let t=await this.getCommand(e);n.logger.info.defaultLog(`Coverage command: ${t}`);try{await Ae(t,{cwd:this.getExecutionCwd(),timeout:this.EXEC_TIMEOUT_IN_MS,maxBuffer:this.MAX_BUFFER_SIZE}),n.logger.info.defaultLog(`Coverage command generation success`)}catch(e){let r=e instanceof Error&&`code`in e?{code:e.code,signal:e.signal,killed:e.killed}:{code:`UNKNOWN_ERROR`};throw n.logger.info.defaultLog(`Coverage generation exited with error: "${t}".`,r),Error(`Failed to generate coverage report: ${e.message}`)}finally{await new At(n.getGlobalConfig().getGitTopLevel()).add(this.COVERAGE_ROOT_DIRECTORY_NAME)}}calculateCoverage(e){let t=new Ft(e,a.default.normalize(n.getGlobalConfig().getRootPath()).toLowerCase()),r=new Map;for(let[e,n]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(!r.has(e)){let n=t.getStatsForDirectory(e);r.set(e,{percentage:n.percentage,totalStatements:n.totalStatements,coveredStatements:n.coveredStatements})}a.pop()}let o=[];for(let{name:r}of Object.values(n.fnMap)){let n=t.getStatsForTestable(e,r);o.push({name:r,percentage:n?.percentage??null,totalStatements:n?.totalStatements??null,coveredStatements:n?.coveredStatements??null})}r.set(e,{percentage:i.percentage,totalStatements:i.totalStatements,coveredStatements:i.coveredStatements,testables:o})}return Object.fromEntries(r.entries())}async hasJestConfig(){let e=Me(n.getGlobalConfig().getRootPath());return(0,c.isDefined)(e)}async buildJestCoverageCommand(e){let t=[`node_modules`,`dist`];n.getGlobalConfig().getIncludeEarlyTests()||t.push(Ht);let r=t.map(e=>`"${e}"`).join(` `),i=n.getGlobalConfig().getRootPath(),a=await this.hasJestConfig(),o=(0,c.isDefined)(e)&&e.length>0?` ${this.formatTestFiles(e)}`:``;return a?`npx jest --coverage --coverageProvider=v8 --coveragePathIgnorePatterns ${r} --coverageReporters=json --coverageDirectory=${pe(n.EARLY_COVERAGE_DIR)} --silent --passWithNoTests --maxWorkers=2 ${o}`:`npx jest --coverage --coverageProvider=v8 --coveragePathIgnorePatterns ${r} --coverageReporters=json --coverageDirectory=${pe(n.EARLY_COVERAGE_DIR)} --rootDir=${pe(i)} --silent --passWithNoTests --maxWorkers=2 ${o}`}async getCoverageTree(e){let t=await Vt().getFiles(e),n=new Map;for(let r of t){let t=new Ot(await new N(r).getText(),`getCoverageTree`).testables.getAllTestables(),i=r.split(`/`).slice(0,-1);for(;!(0,c.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=>kt(e)),s=e[r];for(let e of o){let{name:t}=e;if(!(0,c.isDefined)(t))continue;let n=e.type===`method`?e.parentName:void 0,r=s?.testables?.find(e=>e.name===t),i={name:t,...(0,c.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=>pe(e)).join(` `)}toPercentage(e,t,n=0){if(t===0)return null;let r=e/t;return Number(Math.round(r*100).toFixed(n))}},Wt=class extends Ft{constructor(e,t){super(e,t)}findFunctionDefinition(e,t,n){for(let r of Object.values(t))if(r.name===e||(0,c.isDefined)(n)&&r.name.startsWith(`(anonymous`)&&r.loc.start.line===n)return r;return null}};let Gt=`npx vitest run --coverage.enabled --coverage.exclude="${Ht}" --coverage.reportsDirectory=${n.EARLY_COVERAGE_DIR} --coverage.reportOnFailure=true --coverage.reporter=json --maxWorkers=2 --passWithNoTests`;var Kt=class extends Ut{async init(){await super.init()}async getCommand(e){let t=n.getGlobalConfig().getCoverageCommand(),r=(0,c.isDefined)(e)&&e.length>0?this.formatTestFiles(e):``;if((0,c.isDefined)(t)){let e=t.replaceAll(n.EARLY_COVERAGE_DIR,this.getCoverageDirectoryForCommand()).replaceAll(n.EARLY_TEST_FILES_VAR,r);return!t.includes(n.EARLY_TEST_FILES_VAR)&&r&&(e=`${e} ${r}`),e}let i=Gt.replaceAll(n.EARLY_COVERAGE_DIR,this.getCoverageDirectoryForCommand());return r?`${i} ${r}`:i}async getReport(){try{let e=await N.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=a.default.normalize(n.getGlobalConfig().getRootPath()).toLowerCase(),r=new Wt(e,t),i=this.buildAbsolutePathMap(e,t),o=[...r.getEntries()];return this.processEntries(o,r,i)}buildAbsolutePathMap(e,t){let n=new Map;for(let r of Object.keys(e)){let e=a.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,c.isDefined)(a))return;let o=await this.readFileText(a);if(!(0,c.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 N.fromAbsolutePath(e).getText()}catch{return null}}extractTestables(e,t,n){let r=new Ot(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,c.isDefined)(a)&&{parentName:a},percentage:o?.percentage??null,totalStatements:o?.totalStatements??null,coveredStatements:o?.coveredStatements??null})}return i}},qt=function(e){return e.JEST=`jest`,e.VITEST=`vitest`,e}(qt||{}),Jt=class{provider=null;async create(){let e=await this.detectProjectType();return n.logger.info.defaultLog(`Coverage: project type`,e),e===qt.JEST?this.provider=new Ut:e===qt.VITEST&&(this.provider=new Kt),this.provider&&await this.provider.init(),n.logger.info.defaultLog(`Coverage Provider: `+(e??`null`)),this.provider}async detectProjectType(){return await this.checkFileExists([`vitest.config.ts`,`vitest.config.js`])?qt.VITEST:await this.checkFileExists([`package.json`,`jest.config.js`,`jest.config.ts`,`tsconfig.json`])?qt.JEST:null}async checkFileExists(e){n.logger.info.defaultLog(`Coverage: checking files`,e);for(let t of e)if(await new N(t).isFileExists())return!0;return!1}};let Yt={};var Xt=class{provider=null;coverage=null;async init(){(0,c.isDefined)(this.provider)||(this.provider=await new Jt().create())}async consumeReport(){if((0,c.isDefined)(this.provider))try{this.coverage=await this.provider.getReport(),await this.provider.removeReport()}catch(e){n.logger.info.defaultLog(`Error reading coverage report`,{error:e})}}async generateCoverage(e){if(!(0,c.isDefined)(this.provider))return Yt;try{await this.provider.generateReport(e)}catch(e){let t=await this.provider.isReportExists();if(!n.getGlobalConfig().shouldContinueOnTestErrors()||!t)throw e;n.logger.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,c.isDefined)(this.coverage))throw(0,c.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,c.isDefined)(this.provider)||!(0,c.isDefined)(this.coverage)?Yt:this.provider.getCoverageTree(this.coverage)}setCoverage(e){this.coverage=e}getCoverageForFiles(e){if(!(0,c.isDefined)(this.provider))throw Error(`Coverage provider not initialized`);if(!(0,c.isDefined)(this.coverage))throw Error(`Coverage report not available`);return this.provider.getCoverageForFiles(e,this.coverage)}},Zt=t.__toESM(n.require_decorateMetadata()),Qt=t.__toESM(n.require_decorate());let $t=class{coverageService=new Xt;async generateCoverage(e){try{await this.coverageService.init(),await this.coverageService.generateCoverage(e)}catch(e){throw n.logger.info.failedLog(`Failed to generate coverage`,e),e}}async setCoverage(e){try{await this.coverageService.init(),await this.coverageService.setCoverage(e)}catch(e){throw n.logger.info.failedLog(`Failed to set coverage`,e),e}}async getCoverageTree(){try{await this.coverageService.init(),n.logger.info.startLog(`Getting coverage tree`);let e=await this.coverageService.getCoverageTree();return n.logger.info.endLog(`Getting coverage tree`),e??null}catch(e){throw n.logger.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 n.logger.info.failedLog(`Failed to get coverage for files`,e),e}}};(0,Qt.default)([n.WithLoggerContext({category:xe.GENERATE_COVERAGE}),(0,Zt.default)(`design:type`,Function),(0,Zt.default)(`design:paramtypes`,[Array]),(0,Zt.default)(`design:returntype`,Promise)],$t.prototype,`generateCoverage`,null),(0,Qt.default)([n.WithLoggerContext({category:xe.SET_COVERAGE}),(0,Zt.default)(`design:type`,Function),(0,Zt.default)(`design:paramtypes`,[Object]),(0,Zt.default)(`design:returntype`,Promise)],$t.prototype,`setCoverage`,null),(0,Qt.default)([n.WithLoggerContext({category:xe.GET_COVERAGE}),(0,Zt.default)(`design:type`,Function),(0,Zt.default)(`design:paramtypes`,[]),(0,Zt.default)(`design:returntype`,Promise)],$t.prototype,`getCoverageTree`,null),(0,Qt.default)([n.WithLoggerContext({category:xe.GET_COVERAGE}),(0,Zt.default)(`design:type`,Function),(0,Zt.default)(`design:paramtypes`,[Array]),(0,Zt.default)(`design:returntype`,Promise)],$t.prototype,`getCoverageForFiles`,null),$t=(0,Qt.default)([(0,l.injectable)()],$t);let en=new class{safeTrackEvent(e,t){}},tn={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`},nn={[tn.EMPTY_TEST]:`Oops! No tests were generated for "{{methodName}}". Code:{{code}} - We're on it!`,[tn.DESCRIBE_NOT_FOUND]:`Oops! Test suite not found for "{{methodName}}". Code:{{code}} - We're on it!`,[tn.TESTED_CODE_DATA_SOURCE_ERROR]:`Cannot get testable data for "{{methodName}}". Code:{{code}} - We're on it!`,[tn.GENERATING_TESTS_REQUEST_ERROR]:`Generating tests for method "{{methodName}}" - failed: "{{errorMessage}}". Code:{{code}} - We're on it!`,[tn.PREPARATIONS_FOR_GENERATING_TEST_DTO_ERROR]:`Generating tests for method "{{methodName}}" - failed: "{{errorMessage}}". Code:{{code}} - We're on it!`,[tn.GET_VERSION_REQUEST_ERROR]:`Failed to make request. Code:{{code}} - We're on it!`,[tn.GENERATING_HELPER_REQUEST_ERROR]:`Generating helpers for method "{{methodName}}" - failed: "{{errorMessage}}". Code:{{code}} - We're on it!`,[tn.ENHANCE_TESTS_REQUEST_ERROR]:`Enhance tests for method "{{methodName}}" - failed: "{{errorMessage}}". Code:{{code}} - We're on it!`,[tn.EMPTY_FIXED_TESTS]:`Oops! We got an empty API response for "{{methodName}}" test fixes. Code:{{code}} - We're on it!`,[tn.TESTABLE_NOT_FOUND]:`Oops! Testable code not found for "{{methodName}}". Code:{{code}} - We're on it!`,[tn.TESTED_CODE_FILE_PATH_NOT_FOUND]:`Oops! Testable code file path not found for "{{methodName}}". Code:{{code}}`,[tn.PREEN_TESTS_ERROR]:`Encountered a problem while processing "{{methodName}}". Code:{{code}} - We're on it!`,[tn.ORGANIZE_IMPORTS_ERROR]:`There was an issue with the processing "{{methodName}}". Code:{{code}} - We're on it!`,[tn.NOT_ENOUGH_BALANCE_ERROR]:`Usage test generation limit reached.`,[tn.UNSUPPORTED_MODEL_ERROR]:`We do not support this model at the moment.`,[tn.TOO_MANY_USERS_ERROR]:`Users limit reached. Please contact support.`,[tn.PAYLOAD_TOO_LARGE_ERROR]:`We could not generate tests due to code size.`,[tn.TEST_SUMMARY_DB_REQUEST_ERROR]:`We could not save test summary to database.`,[tn.TEST_SUMMARY_INVALID_CREATED_BY_ERROR]:`Invalid created by field.`,[tn.TEST_SUMMARY_INVALID_GIT_REMOTE_ERROR]:`Invalid git remote.`,[tn.TEST_SUMMARY_INVALID_GIT_BRANCH_ERROR]:`Invalid git branch.`,[tn.GITHUB_ACTION_TEST_SUMMARY_DB_REQUEST_ERROR]:`We could not save test summary to database.`,[tn.GITHUB_ACTION_TEST_SUMMARY_READ_CONF_FILE]:`Failed to read github action config file.`,[tn.GITHUB_ACTION_TEST_SUMMARY_INVALID_GIT_REMOTE_ERROR]:`Invalid git remote.`,[tn.GITHUB_ACTION_TEST_SUMMARY_INVALID_GIT_BRANCH_ERROR]:`Invalid git branch.`,[tn.GITHUB_ACTION_TEST_SUMMARY_READ_CONF_FILE_EMPTY_OPTIONS]:`Failed to parse options from github action conf file.`,[tn.GITHUB_ACTION_TEST_SUMMARY_NO_COVERAGE_FOUND]:`No coverage found. Please run coverage first.`,[tn.WS_DYNAMIC_PROMPT_GENERAL_ERROR]:`Failed initializing dynamic prompt.`,[tn.WS_DYNAMIC_PROMPT_AUTH_ERROR]:`Failed authorizing dynamic prompt.`,[tn.PREPARATIONS_FOR_DYNAMIC_PROMPT_ERROR]:`Failed preparing init dynamic prompt.`,[tn.WS_DYNAMIC_PROMPT_VALIDATION_FAILED_ERROR]:`Failed validating dynamic prompt dto.`,[tn.WS_DYNAMIC_PROMPT_TIMEOUT_ERROR]:`Dynamic prompt operation timed out.`};var rn=class extends Error{constructor(e,t){let n=an(e,t);super(n),this.code=e}};let an=(e,t)=>{let n=nn[e];for(let[r,i]of Object.entries({...t,code:e}))n=n.replace(`{{${r}}}`,i);return n},on=`x-request-id`;var sn=class extends Error{constructor(){super(`Not authorized`)}};new TextEncoder;let cn=new TextDecoder;function ln(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 un(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof e==`string`?e:cn.decode(e),{alphabet:`base64url`});let t=e;t instanceof Uint8Array&&(t=cn.decode(t)),t=t.replace(/-/g,`+`).replace(/_/g,`/`);try{return ln(t)}catch{throw TypeError(`The input to be decoded is not correctly encoded.`)}}var dn=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)}},W=class extends dn{static code=`ERR_JWT_INVALID`;code=`ERR_JWT_INVALID`};let fn=e=>typeof e==`object`&&!!e;function pn(e){if(!fn(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 mn(e){if(typeof e!=`string`)throw new W(`JWTs must use Compact JWS serialization, JWT must be a string`);let{1:t,length:n}=e.split(`.`);if(n===5)throw new W(`Only JWTs using Compact JWS serialization can be decoded`);if(n!==3)throw new W(`Invalid JWT`);if(!t)throw new W(`JWTs must contain a payload`);let r;try{r=un(t)}catch{throw new W(`Failed to base64url decode the payload`)}let i;try{i=JSON.parse(cn.decode(r))}catch{throw new W(`Failed to parse the decoded payload as JSON`)}if(!pn(i))throw new W(`Invalid JWT Claims Set`);return i}let hn=e=>{let t=mn(e).exp;return(0,c.isDefined)(t)?t*1e3:null},gn=e=>{if(!(0,c.isDefined)(e))return!0;let t=hn(e);return(0,c.isDefined)(t)?t<Date.now():!0};var _n=t.__toESM(n.require_decorate());let vn=class{jwtToken=null;refreshTokenCallback=null;observer=new c.Observer;refreshTokenMutex=new C.Mutex;setJWTToken(e){this.jwtToken=e,this.observer.notifyAll(e)}async getJWTToken(){return(0,c.isDefined)(this.jwtToken)?(this.isTokenValid()||await this.refreshTokenMutex.runExclusive(async()=>{if((0,c.isDefined)(this.refreshTokenCallback))return await this.refreshTokenCallback(),this.jwtToken}),this.jwtToken):null}async getJWTTokenOrThrow(){let e=await this.getJWTToken();if(!(0,c.isDefined)(e))throw new sn;return e}onJWTTokenSave(e){this.observer.addListener(e)}isTokenValid(){return!gn(this.jwtToken)}setRefreshTokenCallback(e){this.refreshTokenCallback=e}};vn=(0,_n.default)([(0,l.injectable)(`Singleton`)],vn);var yn=t.__commonJSMin(((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})),bn=t.__toESM(n.require_decorateMetadata()),xn=t.__toESM(yn()),Sn=t.__toESM(n.require_decorate()),Cn,wn;let G=class{axiosInstance;constructor(e,t){this.authStorage=e,this.globalConfigService=t,this.axiosInstance=x.default.create({baseURL:this.globalConfigService.getBackendURL(),headers:{"x-client-name":`ts-agent`,"x-client-version":n.version,"Content-Type":`application/json`,"Content-Encoding":`gzip`},transformRequest:[e=>{if((0,c.isDefined)(e)){let t=b.default.createGzip();return t.write(JSON.stringify(e)),t.end(),t}else return e}]}),(0,S.default)(this.axiosInstance)}async apiCall({url:e,method:t,data:n,config:r}){let i=new x.AxiosHeaders({"x-request-source":this.globalConfigService.getRequestSource(),...r?.headers});if(!r?.ignoreAuth){let e=await this.authStorage.getJWTToken();(0,c.isDefined)(e)&&!(0,c.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(x.default.isAxiosError(t))if((0,c.isDefined)(t.response)){let{status:e,statusText:n,data:r}=t.response;throw e===x.HttpStatusCode.PaymentRequired?new rn(tn.NOT_ENOUGH_BALANCE_ERROR):Error(`API request failed: ${e} ${n} - ${JSON.stringify(r)}`)}else if((0,c.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,c.isDefined)(t)&&e()})}};G=(0,Sn.default)([(0,l.injectable)(),(0,xn.default)(0,(0,l.inject)(vn)),(0,xn.default)(1,(0,l.inject)(n.GlobalConfigService)),(0,bn.default)(`design:paramtypes`,[typeof(Cn=vn!==void 0&&vn)==`function`?Cn:Object,typeof(wn=n.GlobalConfigService!==void 0&&n.GlobalConfigService)==`function`?wn:Object])],G);let Tn={SUPER_ADMIN:1,ADMIN:2,USER:3},En=[Tn.ADMIN,Tn.SUPER_ADMIN];var Dn=t.__toESM(n.require_decorateMetadata()),On=t.__toESM(yn()),kn=t.__toESM(n.require_decorate()),An;let jn=class{mutex=new C.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,n.logger.addContext({userId:e.id})}async getUser(){return(0,c.isDefined)(this.user)?this.user:await this.mutex.runExclusive(async()=>await this.fetchUser())}async isAdminUser(){let e=await this.getUser();return(0,c.isDefined)(e)?En.includes(e?.role):!1}async isInOrganization(){let e=await this.getUser();return(0,c.isDefined)(e?.organization)}};jn=(0,kn.default)([(0,l.injectable)(),(0,On.default)(0,(0,l.inject)(G)),(0,Dn.default)(`design:paramtypes`,[typeof(An=G!==void 0&&G)==`function`?An:Object])],jn);let Mn=e=>(0,f.createHash)(`md5`).update(String(e)).digest(`hex`),Nn=e=>({...Pn(e),testFrameworkReceived:(0,c.isDefined)(e.testFrameworkReceived)?Mn(e.testFrameworkReceived):void 0,testFrameworkExpected:(0,c.isDefined)(e.testFrameworkExpected)?Mn(e.testFrameworkExpected):void 0}),Pn=e=>({errorCode:e.errorCode,shortDescription:Mn(e.shortDescription),fullDescription:Mn(e.fullDescription)}),Fn=e=>({name:Mn(e.name),code:Mn(e.code),status:e.status,errors:e.errors?.map(e=>Nn(e)),lintErrors:e.lintErrors?.map(e=>In(e))??null}),In=e=>({errorCode:e.errorCode,fullDescription:Mn(e.fullDescription),shortDescription:Mn(e.shortDescription),severity:e.severity,exactCode:Mn(e.exactCode)}),Ln=({describe:e,stdout:t})=>({describe:{path:e.path,code:Mn(e.code),fullCode:Mn(e.fullCode),status:e.status,errors:e.errors?.map(e=>Pn(e)),tests:e.tests.map(e=>Fn(e)),lintErrors:e.lintErrors?.map(e=>In(e))??null},stdout:t});var Rn=t.__toESM(n.require_decorateMetadata()),zn=t.__toESM(yn()),Bn=t.__toESM(n.require_decorate()),Vn,Hn,Un;let Wn=class{constructor(e,t,n){this.apiService=e,this.userService=t,this.globalConfigService=n}async saveTestMetrics({requestId:e,timeElapsed:t,validationReport:r,...i}){try{let a={timeElapsed:t,...r,...i};await this.userService.isInOrganization()&&(n.logger.debug.defaultLog(`Filtering private data for B2B user`),a.testResult=(0,c.isDefined)(r?.testResult)?Ln(r.testResult):void 0),n.logger.debug.startLog(`Sending metrics with request id ${e}`),await this.postWithRequestId(`/api/v1/tests/update-operation-metrics`,a,e),n.logger.debug.defaultLog(`Test metrics have been saved`)}catch(e){n.logger.error(`Test metrics cannot be saved`,e)}n.logger.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=ge(e);if(!(0,c.isDefined)(t))return;await this.updateRepositoryPackageJson(t)}catch(e){n.logger.info.defaultLog(`Failed to log package dependencies.`,e);return}}async saveOperationMetricsTrace(e){let{parentRequestId:t,llmModel:r,testResultIteration:i=0,toolsOutput:a,testFileContent:o}=e;try{n.logger.debug.startLog(`Sending operation metrics trace for testResultIteration ${i}`),await this.postWithRequestId(`/api/v1/tests/operation-metrics-trace`,{parentRequestId:t,iteration:i,llmModel:r,toolsOutput:a,testFileContent:o},t),n.logger.debug.defaultLog(`Operation metrics trace saved for testResultIteration ${i}`)}catch(e){n.logger.error(`Failed to save operation metrics trace for testResultIteration ${i}`,e)}n.logger.debug.endLog(`Sending operation metrics trace for testResultIteration ${i}`)}async postWithRequestId(e,t,n){await this.apiService.post(e,t,{headers:{[on]:n}})}async updateRepositoryPackageJson(e){try{let t=this.globalConfigService.getContext();if(!(0,c.isDefined)(t?.git?.owner)||!(0,c.isDefined)(t?.git?.repository)){n.logger.debug.defaultLog(`No git context available, skipping package.json update`);return}let r={owner:t.git.owner,repo:t.git.repository,packageJson:JSON.stringify(e)};await this.apiService.patch(`/api/v1/github-repos/package-json`,r),n.logger.debug.defaultLog(`Successfully updated repository package.json`)}catch(e){n.logger.info.defaultLog(`Failed to update repository package.json`,e)}}};Wn=(0,Bn.default)([(0,l.injectable)(),(0,zn.default)(0,(0,l.inject)(G)),(0,zn.default)(1,(0,l.inject)(jn)),(0,zn.default)(2,(0,l.inject)(n.GlobalConfigService)),(0,Rn.default)(`design:paramtypes`,[typeof(Vn=G!==void 0&&G)==`function`?Vn:Object,typeof(Hn=jn!==void 0&&jn)==`function`?Hn:Object,typeof(Un=n.GlobalConfigService!==void 0&&n.GlobalConfigService)==`function`?Un:Object])],Wn);var Gn=class{queue;activeProcesses=[];itemAddedObserver=new c.Observer;itemExecutedObserver=new c.Observer;itemAbortedObserver=new c.Observer;abortControllers=new Map;getItemKey;constructor({concurrency:e,getItemKey:t}){this.queue=new w.default({concurrency:e}),this.getItemKey=t}async add(e,t){let r=this.getItemKey(e);if(this.activeProcesses.includes(r))return;let i=new AbortController,a=n.logger.captureContext({withNewRequestId:!0});return this.abortControllers.set(r,i),this.activeProcesses.push(r),this.itemAddedObserver.notifyAll(r),this.queue.add(async()=>{await n.logger.runWithContext(a,async()=>{await t(i.signal)})},{signal:i.signal}).then(()=>{this.itemExecutedObserver.notifyAll(r)}).finally(()=>{this.activeProcesses=this.activeProcesses.filter(e=>e!==r),this.abortControllers.delete(r)})}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)}clearDoneListeners(){this.itemExecutedObserver.clear()}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,c.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,c.isDefined)(e)&&(e.abort(),this.abortControllers.delete(t)),this.itemAbortedObserver.notifyAll(t)}this.activeProcesses=this.getProcessing()}getIdlePromise(){return this.queue.onIdle()}};let Kn=`npx jest ${n.EARLY_FILENAME_VAR} --coverage=false --verbose=false --watchAll=false --silent --json --forceExit --testPathIgnorePatterns=// --maxWorkers=1`;var qn=class{fulfill(e){if(n.getGlobalConfig().getTestFramework()!==n.TestFramework.JEST)return!1;let t=e,r=null,i=0;for(;i<25;){i++;let e=me(t,`package.json`);if(!(0,c.isDefined)(e)||e===r)return!1;let n=ge(t);if((0,c.isDefined)(n)&&_e(n,`jest`))return!0;r=e,t=a.default.dirname(a.default.dirname(e))}return!1}getTestCommand(){return{command:n.getGlobalConfig().getTestCommand()??Kn,framework:n.TestFramework.JEST}}};let Jn=`npx vitest run ${n.EARLY_FILENAME_VAR} --reporter=junit --silent --pool=threads --maxWorkers=1 --coverage.enabled=false`,Yn=new class{constructor(e){this.providers=e}getTestCommand(e){let t=this.getProvider(e);if(!(0,c.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(n.getGlobalConfig().getTestFramework()!==n.TestFramework.VITEST)return!1;let t=e,r=null,i=0;for(;i<25;){i++;let e=me(t,`package.json`);if(!(0,c.isDefined)(e)||e===r)return!1;let n=ge(t);if((0,c.isDefined)(n)&&_e(n,`vitest`))return!0;r=e,t=a.default.dirname(a.default.dirname(e))}return!1}getTestCommand(){return{command:n.getGlobalConfig().getTestCommand()??Jn,framework:n.TestFramework.VITEST}}},new qn]);var Xn=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 Zn=`validate-tests`,Qn=e=>e instanceof Error&&`code`in e&&typeof e.code==`number`;var $n=class e{constructor(e){this.relativePath=e}async runCommandOnFile(e,t=Xn.success,r=!1){let i=r?fe(a.default.normalize(this.relativePath)):a.default.normalize(this.relativePath),o=e.replaceAll(n.EARLY_FILENAME_VAR,pe(i));try{n.logger.debug.startLog(`Command been executed on test-file ${this.relativePath} ${e}`),n.logger.info.defaultLog(`Running command on file ${this.relativePath}`,{renderedCommand:o});let{stdout:t,stderr:r}=await Ae(o,{cwd:n.getGlobalConfig().getRootPath(),timeout:3e5}),i=t||r;return n.logger.debug.endLog(`Command been executed on test-file ${this.relativePath} ${e}: ${i}`),i}catch(r){if(!(Qn(r)&&(0,c.isDefined)(r.code)&&t.allow(r.code))){let t=`Failed run command "${e}" on file ${this.relativePath}`;throw n.logger.error(t,r),r}let i=r.stdout||r.stderr;return n.logger.debug.endLog(`Command been executed on test-file ${this.relativePath} ${e}: ${i}`),i}}getTempFileName(e,t,r){if(t){let t=a.default.join(d.default.tmpdir(),`early`),n=`${e}-${(0,f.randomUUID)()}`;return a.default.join(t,n)}let i=(0,c.isDefined)(r)&&!(0,c.isEmpty)(r),o=i&&a.default.isAbsolute(r)?a.default.dirname(r):a.default.join(n.getGlobalConfig().getRootPath(),a.default.dirname(r??``));if(!(0,c.isDefined)(o))throw Error(`Workspace root path is not defined`);let s=`.${e}-${(0,f.randomUUID)()}-${i?a.default.basename(r):`.ts`}`;return a.default.join(o,s)}async runCommandWithContent(t,r,i,s=!1){n.logger.addContext({subCategory:Se.COMMAND_EXECUTION});let l={filePrefix:`generated-content`,useTemporaryOSFolder:!(0,c.isDefined)(i?.predefinedPath),validExitCodes:Xn.success,...i},u=this.getTempFileName(l.filePrefix,l.useTemporaryOSFolder,l.predefinedPath);try{n.logger.info.defaultLog(`Creating temp file ${u}`),await o.default.mkdir(a.default.dirname(u),{recursive:!0}),await o.default.writeFile(u,t);let i=new e(u);return n.logger.info.defaultLog(`Running command "${r}" on temp file`),await i.runCommandOnFile(r,l.validExitCodes,s)}catch(e){return n.logger.error(`Failed running command "${r}" on temp file`,e),``}finally{try{await o.default.unlink(u)}catch(e){n.logger.info.defaultLog(`Failed removing temp file`,e)}}}async runTestCommand(){n.logger.addContext({subCategory:Se.COMMAND_EXECUTION});let e;try{e=Yn.getTestCommand(this.relativePath)}catch(e){return e instanceof Error?e.message:`Framework is not supported yet`}return await this.runCommandOnFile(e.command,Xn.suppress_1,!0)}async runTestCommandOnTempFile(e){n.logger.addContext({subCategory:Se.COMMAND_EXECUTION});let t;try{t=Yn.getTestCommand(this.relativePath)}catch(e){return e instanceof Error?e.message:`Framework is not supported yet`}return await this.runCommandWithContent(e,t.command,{validExitCodes:Xn.suppress_1,filePrefix:Zn,predefinedPath:this.relativePath},!0)}async runFormatCommand(){n.logger.addContext({subCategory:Se.COMMAND_EXECUTION});let e=n.getGlobalConfig().getPrettierCommand();n.logger.debug.startLog(`format command: ${e}`);let t=await this.runCommandOnFile(e,Xn.all);return n.logger.debug.endLog(`format command: ${e}`),t}async runLintCommand(e=[]){n.logger.addContext({subCategory:Se.COMMAND_EXECUTION});let t=n.getGlobalConfig().getLintCommand(),r=e.length>0?t+` `+e.join(` `):t;n.logger.debug.startLog(`lint command: ${r}`);let i=await this.runCommandOnFile(r,Xn.all);return n.logger.debug.endLog(`lint command: ${r}`),i}};let er=e=>{let t=e.name??``,n=e.type;return{methodType:n,methodName:t,parentName:n===`method`?e.parentName:void 0}};async function tr(e,{methodType:t,methodName:n,parentName:r}){let i=new Ot(await new N(e).getText()).testables.findTestable(t,n,r);if(!(0,c.isDefined)(i))throw new rn(tn.TESTABLE_NOT_FOUND,{methodName:n});return i}function nr(e,t){return(0,c.isDefined)(t)&&!(0,c.isEmpty)(t)?`${t}.${e}`:e}function rr(e){if(!e||e.trim()===``)return[];let t=e.indexOf(`[`),r=e.lastIndexOf(`]`),i=t!==-1&&r!==-1&&r>t?e.slice(t,r+1):e;try{return JSON.parse(i)}catch(e){return n.logger.error(`Failed to parse eslint JSON output`,e),null}}var ir=t.__toESM(n.require_decorate());let ar=class{contentCache=new Map;filePathIndex=new Map;computeContentHash(e){return Mn(e)}getContentCacheKey(e,t){return`${e}:${t?`fix`:`nofix`}`}evictOldest(){let e=this.contentCache.keys().next().value;(0,c.isDefined)(e)&&(this.contentCache.delete(e),n.logger.debug.defaultLog(`Lint cache evicted oldest entry (FIFO)`))}get(e,t,r){let i=this.computeContentHash(t),a=this.getContentCacheKey(i,r),o=this.contentCache.get(a);return(0,c.isDefined)(o)?(n.logger.debug.defaultLog(`Lint cache hit for ${e}`),o.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,c.isDefined)(t))return;let r=this.getContentCacheKey(t,!0),i=this.getContentCacheKey(t,!1),a=this.contentCache.delete(r),o=this.contentCache.delete(i);this.filePathIndex.delete(e),(a||o)&&n.logger.debug.defaultLog(`Lint cache invalidated for ${e}`)}invalidateAll(){let e=this.contentCache.size;this.contentCache.clear(),this.filePathIndex.clear(),e>0&&n.logger.debug.defaultLog(`Lint cache cleared: ${e} entries removed`)}};ar=(0,ir.default)([(0,l.injectable)()],ar);let or=function(e){return e[e.ERROR=2]=`ERROR`,e[e.WARN=1]=`WARN`,e[e.OFF=0]=`OFF`,e}({});var sr=t.__toESM(n.require_decorateMetadata()),cr=t.__toESM(yn()),lr=t.__toESM(n.require_decorate()),dr,fr;let pr=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()?ye:[]].filter(c.isDefined);this.globalConfigService.shouldDisableLintRules()?await this.disableAllLintRules(e):(0,c.isEmpty)(t)||await this.disableLintRules(e,t),await We.refreshFromFileSystem(e)}async disableAllLintRules(e){let t=await this.getRulesToDisable(e);if((0,c.isDefined)(t)){if((0,c.isEmpty)(t)){n.logger.info.defaultLog(`No lint rules needed to be disabled`);return}await this.addDisableComment(e,t),n.logger.info.defaultLog(`Added eslint-disable comment for rules: ${t.join(`, `)}`)}}async lintFiles(e,t){let n=N.fromRelativePath(e),r=await n.getText(),i=this.lintCacheService.get(e,r,t);if((0,c.isDefined)(i))return i;let a=t?[`--format`,`json`,`--fix`]:[`--format`,`json`],o=rr(await new $n(e).runLintCommand(a));if(!(0,c.isDefined)(o))return null;if(t){await We.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 n.logger.error(`Failed to get lint results:`,e),null}}async fixLint(e){try{return await this.lint(e,!0)}catch(e){return n.logger.error(`Failed to fix lint:`,e),null}}async getLintResults(e){try{return await this.lint(e,!1)}catch(e){return n.logger.error(`Failed to get lint results:`,e),null}}async getRulesToDisable(e){let t=await this.getLintResults(e);if(!(0,c.isDefined)(t))return null;let n=(t[0]?.messages??[]).filter(e=>e.severity===or.ERROR);return[...new Set(n.map(e=>e.ruleId).filter(c.isDefined))]}async addDisableComment(e,t){let n=N.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(`
|
|
32216
32363
|
`);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 r=N.fromRelativePath(e),i=await r.getText();if(this.hasDisableCommentForRules(i,t))return;let a=await this.getLintResults(e);if(!(0,c.isDefined)(a)){n.logger.info.defaultLog(`No lint results returned`);return}let o=a[0]?.messages??[],s=t.filter(e=>o.some(t=>t.severity===or.ERROR&&t.ruleId===e));if((0,c.isEmpty)(s))return;let l=`/* eslint-disable ${s.join(`, `)} */\n\n`;await r.replace(l+i),this.lintCacheService.invalidate(e),n.logger.info.defaultLog(`Added eslint-disable comment for ${s.join(`, `)} in ${e}`)}};pr=(0,lr.default)([(0,l.injectable)(),(0,cr.default)(0,(0,l.inject)(n.GlobalConfigService)),(0,cr.default)(1,(0,l.inject)(ar)),(0,sr.default)(`design:paramtypes`,[typeof(dr=n.GlobalConfigService!==void 0&&n.GlobalConfigService)==`function`?dr:Object,typeof(fr=ar!==void 0&&ar)==`function`?fr:Object])],pr);let mr="${methodName}";`${mr}`,`${mr}`;function hr(e,t,n){let r=e.split(`
|
|
@@ -32588,7 +32735,7 @@ Start the workflow now with Phase 0 (read the provided project commands), then p
|
|
|
32588
32735
|
`)).filter(e=>e.length>0);return{files:[...new Set(n)],description:`uncommitted (unstaged + staged + untracked)`}}function Xm(e,t,n,r,i=!1){if(e.length===0)return``;let a={cwd:t,encoding:`utf8`,timeout:3e4},o=e.join(` `);try{if(i)return[(0,g.execSync)(`git diff -- ${o}`,a).trim(),(0,g.execSync)(`git diff --cached -- ${o}`,a).trim()].filter(Boolean).join(`
|
|
32589
32736
|
`)||`(diff unavailable)`;let e=qm(t,n);return(0,g.execSync)(`git diff ${r}...${e} -- ${o}`,a).trim()}catch{return`(diff unavailable)`}}function Zm(e,t){let n={cwd:e,encoding:`utf8`,timeout:1e4};try{let e=(0,g.execSync)(`git log ${t}..HEAD --format=%s`,n).trim();return e.length>0?e.split(`
|
|
32590
32737
|
`).filter(e=>e.length>0):[]}catch{return[]}}function Qm(e,t,n){let r={cwd:e,encoding:`utf8`,timeout:1e4};try{return n?(0,g.execSync)(`git config user.email`,r).trim():(0,g.execSync)(`git log -1 --format=%ae ${t}`,r).trim()}catch{return``}}function $m(e,t,n){let r={cwd:e,encoding:`utf8`,timeout:1e4};try{let e=(0,g.execSync)(`git log -1 --format=%ci ${n} -- "${t}"`,r).trim();return e.length===0?0:Math.floor((Date.now()-new Date(e).getTime())/(1e3*60*60*24))}catch{return 0}}function eh(e,t,n,r){let i={cwd:e,encoding:`utf8`,timeout:1e4};try{let e=(0,g.execSync)(`git log --oneline --since="90 days ago" ${n} ${r} -- "${t}"`,i).trim();return e.length===0?0:e.split(`
|
|
32591
|
-
`).length}catch{return 0}}function th(e,t,
|
|
32738
|
+
`).length}catch{return 0}}function th(e,t,r,i,a){let o=i!==void 0&&i.length>0,s=o?i:a;o||n.logger.info.defaultLog(`[regression-impact] anchorSha missing — git signals computed against branch '${a}' (may include commits past catalog snapshot)`);let c={};for(let n of t){let t=r.length>0?`--author="${r}"`:``;c[n]={fileAgeDays:$m(e,n,s),authorCommits:r.length>0?eh(e,n,s,t):0,bugFixCommits:eh(e,n,s,`--grep="fix:"`),revertCommits:eh(e,n,s,`--grep="revert"`)}}return c}function nh(e,t){let{name:n,flowType:r,entryPoints:i,importanceReason:a,description:o,trace:s,scoring:c}=e,l=c===void 0?[]:[``,`**Scoring:**`,`- Risk Score: ${c.riskScore} — ${c.riskReason}`,`- Blast Radius: ${c.blastRadius} — ${c.blastReason}`,`- Final Score: ${c.finalScore}`],u=e.productFlow===void 0?[]:[``,`**Product Flow:**`,`- **Trigger:** ${e.productFlow.trigger}`,...e.productFlow.steps.map((e,t)=>`- ${t+1}. **${e.actor}** → ${e.action} → _${e.outcome}_`),`- **Outcome:** ${e.productFlow.outcome}`];return[`### ${t+1}. ${n} (${r})`,`**Entry points:** ${i.join(`, `)||`none`}`,`**Why important:** ${a}`,`**Description:** ${o}`,...u,``,`**Trace:**`,`- Entry files: ${s.entryFiles.join(`, `)||`none`}`,`- Entry symbols: ${s.entrySymbols.join(`, `)||`none`}`,`- Called modules: ${s.calledModules.join(`, `)||`none`}`,...l,``,`**Code snippet:**`,"```",s.codeSnippet??`(empty)`,"```"].join(`
|
|
32592
32739
|
`)}function rh(e){return[`## Flow Identity Reconciliation`,``,`| Category | Count | Flow IDs |`,`|---|---|---|`,`| ✅ Kept | ${e.kept.length} | ${e.kept.join(`, `)||`—`} |`,`| 🔁 Revived | ${e.revived.length} | ${e.revived.join(`, `)||`—`} |`,`| 🆕 Added | ${e.added.length} | ${e.added.join(`, `)||`—`} |`,`| ❌ Gone | ${e.gone.length} | ${e.gone.join(`, `)||`—`} |`].join(`
|
|
32593
32740
|
`)}function ih(e,t,r,i,a,o,s){(0,p.mkdirSync)(e,{recursive:!0});let l=new Date().toISOString().replaceAll(/[:.]/g,`-`),u=j.default.basename(t),d=`${l}-${u}.md`,f=j.default.join(e,d),m=i.flows.map((e,t)=>nh(e,t)).join(`
|
|
32594
32741
|
|
|
@@ -32847,7 +32994,12 @@ ${n.length>0?n.map(e=>`- ${e}`).join(`
|
|
|
32847
32994
|
`):`(none)`}
|
|
32848
32995
|
|
|
32849
32996
|
Trace all local imports reachable from the entry files and return any NEW files not already in the known list.`}var wh=t.__toESM(n.require_decorateMetadata()),Th=t.__toESM(yn()),Eh=t.__toESM(n.require_decorate()),Dh;function Oh(e){if(typeof e!=`object`||!e)return;let t=e;if(Array.isArray(t.calledModules))return{calledModules:t.calledModules.filter(e=>typeof e==`string`)}}let kh=class{constructor(e,t){this.globalConfigService=e,this.authStorage=t}async run(e,t){n.logger.info.defaultLog(`[regression-tracer] Tracing dependencies for ${e.flows.length} flows in parallel...`);let r=await this.authStorage.getJWTToken(),i=this.globalConfigService.getAnthropicProxyUrl(),a=[...e.flows],o=0;for(let e=0;e<a.length;e+=n.REGRESSION_TRACER_CONCURRENCY){let s=a.slice(e,e+n.REGRESSION_TRACER_CONCURRENCY);await Promise.all(s.map(async e=>{let{newModules:a,costUsd:s}=await this.traceFlow(e,t,r,i);o+=s,a.length>0&&(e.trace.calledModules=[...new Set([...e.trace.calledModules,...a])],n.logger.info.defaultLog(`[regression-tracer] ${e.name}: +${a.length} modules (total: ${e.trace.calledModules.length})`))}))}return n.REGRESSION_LOG_COST&&n.logger.info.defaultLog(`[regression-tracer] Done. Total cost: $${o.toFixed(4)}`),{result:{...e,flows:a},costUsd:o}}async traceFlow(e,t,r,i){if(e.trace.entryFiles.length===0)return{newModules:[],costUsd:0};let{query:a,isResultMessage:o,isErrorResult:s}=await Promise.resolve().then(()=>wU()),c=a({prompt:Ch(t,e.trace.entryFiles,e.trace.calledModules),options:{model:n.REGRESSION_TRACER_MODEL,systemPrompt:Sh(),allowedTools:[`Read`,`Glob`],permissionMode:n.REGRESSION_PERMISSION_MODE,allowDangerouslySkipPermissions:!0,maxBudgetUsd:n.REGRESSION_TRACER_MAX_BUDGET_USD,maxTurns:n.REGRESSION_TRACER_MAX_TURNS,cwd:t,sessionId:(0,f.randomUUID)(),env:{...process.env,ANTHROPIC_BASE_URL:i,ANTHROPIC_AUTH_TOKEN:r??``},outputFormat:{type:`json_schema`,schema:n.DEPENDENCY_TRACER_OUTPUT_SCHEMA}}}),l=0;for await(let t of c){if(!o(t))continue;if(s(t))return n.logger.info.defaultLog(`[regression-tracer] ${e.name}: agent error — keeping original calledModules`),{newModules:[],costUsd:0};l=t.total_cost_usd;let r=Oh(t.structured_output),i=new Set(e.trace.calledModules);return{newModules:(r?.calledModules??[]).filter(e=>typeof e==`string`&&!i.has(e)),costUsd:l}}return{newModules:[],costUsd:0}}};kh=(0,Eh.default)([(0,l.injectable)(),(0,Th.default)(0,(0,l.inject)(n.GlobalConfigService)),(0,Th.default)(1,(0,l.inject)(vn)),(0,wh.default)(`design:paramtypes`,[Object,typeof(Dh=vn!==void 0&&vn)==`function`?Dh:Object])],kh);var Ah=t.__toESM(n.require_decorateMetadata()),jh=t.__toESM(yn()),Mh=t.__toESM(n.require_decorate()),Nh,Ph,Fh;let Ih=class{constructor(e,t,n,r){this.runner=e,this.tracer=t,this.apiService=n,this.globalConfigService=r}async run(){let e=this.globalConfigService.getRootPath(),t=this.globalConfigService.getContext()?.git?.anchorBranch?.trim()??``,n=t.length>0?t:`master`;return lh(``,this.runner,this.tracer,e,n,this.apiService,this.globalConfigService)}};Ih=(0,Mh.default)([(0,l.injectable)(),(0,jh.default)(0,(0,l.inject)(bh)),(0,jh.default)(1,(0,l.inject)(kh)),(0,jh.default)(2,(0,l.inject)(G)),(0,jh.default)(3,(0,l.inject)(n.GlobalConfigService)),(0,Ah.default)(`design:paramtypes`,[typeof(Nh=bh!==void 0&&bh)==`function`?Nh:Object,typeof(Ph=kh!==void 0&&kh)==`function`?Ph:Object,typeof(Fh=G!==void 0&&G)==`function`?Fh:Object,Object])],Ih);function Lh(e){if(typeof e!=`object`||!e)return;let t=e;if(Array.isArray(t.sourceFiles))return{sourceFiles:t.sourceFiles.filter(e=>typeof e==`string`)}}async function Rh(e,t,r,a){let{query:o,isResultMessage:s,isErrorResult:c}=await Promise.resolve().then(()=>wU()),l=`Changed files:\n${e.map((e,t)=>`${t+1}. ${e}`).join(`
|
|
32850
|
-
`)}`;n.logger.info.defaultLog(`[regression-impact] Pre-filter: classifying ${e.length} files (source vs non-source)`);let u=o({prompt:l,options:{model:n.REGRESSION_IMPACT_HAIKU_MODEL,systemPrompt:i.PRE_FILTER_SYSTEM_PROMPT,allowedTools:[],permissionMode:n.REGRESSION_PERMISSION_MODE,allowDangerouslySkipPermissions:!0,maxBudgetUsd:.1,maxTurns:5,cwd:a,sessionId:(0,f.randomUUID)(),outputFormat:{type:`json_schema`,schema:n.PRE_FILTER_OUTPUT_SCHEMA},env:{...process.env,ANTHROPIC_BASE_URL:r,ANTHROPIC_AUTH_TOKEN:t??``}}});for await(let t of u){if(!s(t))continue;if(c(t))return n.logger.info.defaultLog(`[regression-impact] Pre-filter error: ${t.subtype}`),{sourceFiles:e,costUsd:0,turns:0,maxTurnsHit:!1};let r=t.total_cost_usd,i=t.num_turns,a=i>=5,o=Lh(t.structured_output);if(o===void 0)return{sourceFiles:e,costUsd:r,turns:i,maxTurnsHit:a};let l=o.sourceFiles.filter(t=>e.includes(t));return n.logger.info.defaultLog(`[regression-impact] Pre-filter: ${e.length} → ${l.length} source files (${e.length-l.length} non-source filtered out)`),{sourceFiles:l,costUsd:r,turns:i,maxTurnsHit:a}}return{sourceFiles:e,costUsd:0,turns:0,maxTurnsHit:!1}}let zh=[`NONE`,`LOW`,`MEDIUM`,`HIGH`,`CRITICAL`];function Bh(e){return e.length===0?`NONE`:e.reduce((e,t)=>zh.indexOf(t.severity)>zh.indexOf(e)?t.severity:e,`NONE`)}function Vh(e){if(typeof e!=`object`||!e)return;let t=e;if(!(!Array.isArray(t.techChanges)||!Array.isArray(t.productChanges)))return{techChanges:t.techChanges,productChanges:t.productChanges,affectedSteps:Array.isArray(t.affectedSteps)?t.affectedSteps:[]}}async function Hh(e,t,r,a,o,s,c,l=!1,u=[],d){let{query:p,isResultMessage:m,isErrorResult:h}=await Promise.resolve().then(()=>wU()),g=Xm(t,r,a,o,l),_=p({prompt:i.buildSonnetDeepPrompt(e,t,g,a,o,u,d),options:{model:n.REGRESSION_IMPACT_DEEP_MODEL,systemPrompt:i.buildSonnetDeepSystemPrompt(),allowedTools:[`Read`,`Grep`,`Glob`,`Bash`],permissionMode:n.REGRESSION_PERMISSION_MODE,allowDangerouslySkipPermissions:!0,maxBudgetUsd:n.REGRESSION_IMPACT_DEEP_MAX_BUDGET_USD,maxTurns:n.REGRESSION_IMPACT_DEEP_MAX_TURNS,cwd:r,sessionId:(0,f.randomUUID)(),outputFormat:{type:`json_schema`,schema:n.SONNET_DEEP_OUTPUT_SCHEMA},env:{...process.env,ANTHROPIC_BASE_URL:c,ANTHROPIC_AUTH_TOKEN:s??``}}}),v=0;for await(let t of _){if(!m(t))continue;if(h(t))return n.logger.info.defaultLog(`[regression-impact] Sonnet deep analysis error: ${t.subtype}`),null;v=t.total_cost_usd;let r=t.num_turns,i=r>=n.REGRESSION_IMPACT_DEEP_MAX_TURNS,a=Vh(t.structured_output);if(a===void 0)return n.logger.info.defaultLog(`[regression-impact] Sonnet deep: missing or invalid structured_output (flow: ${e.name})`),null;let o=a.techChanges.map(e=>({file:e.file,confidence:e.confidence,techBefore:e.techBefore,techAfter:e.techAfter})),s=a.productChanges.map(e=>({...e.title===void 0?{}:{title:e.title},productBefore:e.productBefore,productAfter:e.productAfter,confidence:e.confidence,severity:e.severity,...e.severityReason===void 0?{}:{severityReason:e.severityReason},...e.importance===void 0?{}:{importance:e.importance},...e.importanceReason===void 0?{}:{importanceReason:e.importanceReason},...e.priority===void 0?{}:{priority:e.priority},...e.verdict===void 0?{}:{verdictScore:e.verdict.score,...e.verdict.reason===void 0?{}:{verdictReason:e.verdict.reason}}}));return{severity:Bh(s),techChanges:o,productChanges:s,affectedSteps:a.affectedSteps??[],costUsd:v,turns:r,maxTurnsHit:i}}return null}function Uh(e
|
|
32997
|
+
`)}`;n.logger.info.defaultLog(`[regression-impact] Pre-filter: classifying ${e.length} files (source vs non-source)`);let u=o({prompt:l,options:{model:n.REGRESSION_IMPACT_HAIKU_MODEL,systemPrompt:i.PRE_FILTER_SYSTEM_PROMPT,allowedTools:[],permissionMode:n.REGRESSION_PERMISSION_MODE,allowDangerouslySkipPermissions:!0,maxBudgetUsd:.1,maxTurns:5,cwd:a,sessionId:(0,f.randomUUID)(),outputFormat:{type:`json_schema`,schema:n.PRE_FILTER_OUTPUT_SCHEMA},env:{...process.env,ANTHROPIC_BASE_URL:r,ANTHROPIC_AUTH_TOKEN:t??``}}});for await(let t of u){if(!s(t))continue;if(c(t))return n.logger.info.defaultLog(`[regression-impact] Pre-filter error: ${t.subtype}`),{sourceFiles:e,costUsd:0,turns:0,maxTurnsHit:!1};let r=t.total_cost_usd,i=t.num_turns,a=i>=5,o=Lh(t.structured_output);if(o===void 0)return{sourceFiles:e,costUsd:r,turns:i,maxTurnsHit:a};let l=o.sourceFiles.filter(t=>e.includes(t));return n.logger.info.defaultLog(`[regression-impact] Pre-filter: ${e.length} → ${l.length} source files (${e.length-l.length} non-source filtered out)`),{sourceFiles:l,costUsd:r,turns:i,maxTurnsHit:a}}return{sourceFiles:e,costUsd:0,turns:0,maxTurnsHit:!1}}let zh=[`NONE`,`LOW`,`MEDIUM`,`HIGH`,`CRITICAL`];function Bh(e){return e.length===0?`NONE`:e.reduce((e,t)=>zh.indexOf(t.severity)>zh.indexOf(e)?t.severity:e,`NONE`)}function Vh(e){if(typeof e!=`object`||!e)return;let t=e;if(!(!Array.isArray(t.techChanges)||!Array.isArray(t.productChanges)))return{techChanges:t.techChanges,productChanges:t.productChanges,affectedSteps:Array.isArray(t.affectedSteps)?t.affectedSteps:[]}}async function Hh(e,t,r,a,o,s,c,l=!1,u=[],d){let{query:p,isResultMessage:m,isErrorResult:h}=await Promise.resolve().then(()=>wU()),g=Xm(t,r,a,o,l),_=p({prompt:i.buildSonnetDeepPrompt(e,t,g,a,o,u,d),options:{model:n.REGRESSION_IMPACT_DEEP_MODEL,systemPrompt:i.buildSonnetDeepSystemPrompt(),allowedTools:[`Read`,`Grep`,`Glob`,`Bash`],permissionMode:n.REGRESSION_PERMISSION_MODE,allowDangerouslySkipPermissions:!0,maxBudgetUsd:n.REGRESSION_IMPACT_DEEP_MAX_BUDGET_USD,maxTurns:n.REGRESSION_IMPACT_DEEP_MAX_TURNS,cwd:r,sessionId:(0,f.randomUUID)(),outputFormat:{type:`json_schema`,schema:n.SONNET_DEEP_OUTPUT_SCHEMA},env:{...process.env,ANTHROPIC_BASE_URL:c,ANTHROPIC_AUTH_TOKEN:s??``}}}),v=0;for await(let t of _){if(!m(t))continue;if(h(t))return n.logger.info.defaultLog(`[regression-impact] Sonnet deep analysis error: ${t.subtype}`),null;v=t.total_cost_usd;let r=t.num_turns,i=r>=n.REGRESSION_IMPACT_DEEP_MAX_TURNS,a=Vh(t.structured_output);if(a===void 0)return n.logger.info.defaultLog(`[regression-impact] Sonnet deep: missing or invalid structured_output (flow: ${e.name})`),null;let o=a.techChanges.map(e=>({file:e.file,confidence:e.confidence,techBefore:e.techBefore,techAfter:e.techAfter})),s=a.productChanges.map(e=>({...e.title===void 0?{}:{title:e.title},productBefore:e.productBefore,productAfter:e.productAfter,confidence:e.confidence,severity:e.severity,...e.severityReason===void 0?{}:{severityReason:e.severityReason},...e.importance===void 0?{}:{importance:e.importance},...e.importanceReason===void 0?{}:{importanceReason:e.importanceReason},...e.priority===void 0?{}:{priority:e.priority},...e.verdict===void 0?{}:{verdictScore:e.verdict.score,...e.verdict.reason===void 0?{}:{verdictReason:e.verdict.reason}}}));return{severity:Bh(s),techChanges:o,productChanges:s,affectedSteps:a.affectedSteps??[],costUsd:v,turns:r,maxTurnsHit:i}}return null}function Uh(e){if(typeof e!=`object`||!e)return;let t=e;if(!(typeof t.score!=`number`||t.score<1||t.score>10||!Number.isInteger(t.score)||typeof t.reasoning!=`string`))return t}function Wh(e,t){if(e===void 0)return``;let n=Object.entries(e).filter(([e])=>t.includes(e)).map(([e,t])=>`| ${e} | ${t.fileAgeDays===0?`new/unknown`:`${t.fileAgeDays}d ago`} | ${t.authorCommits} | ${t.bugFixCommits} | ${t.revertCommits} |`);return n.length===0?``:`## Git signals (pre-computed):
|
|
32998
|
+
| File | Last touched | Author commits (90d) | Fix commits (90d) | Revert commits (90d) |
|
|
32999
|
+
|---|---|---|---|---|
|
|
33000
|
+
${n.join(`
|
|
33001
|
+
`)}
|
|
33002
|
+
`}async function Gh(e){let{productChange:t,techChanges:r,flow:a,commitMessages:o,gitSignals:s,runContext:c,affectedSteps:l,jwtToken:u,anthropicBaseUrl:d,rootPath:p}=e,m=t.verdictScore,h=t.verdictReason;if(m===void 0)return{verdict:null,costUsd:0,turns:0,maxTurnsHit:!1};let{query:g,isResultMessage:_,isErrorResult:v}=await Promise.resolve().then(()=>wU()),y=Wh(s,r.map(e=>e.file)),b=i.buildVerdictCalibratorSystemPrompt(),x=g({prompt:i.buildVerdictCalibratorPrompt({productChange:{title:t.title,severity:t.severity,severityReason:t.severityReason,productBefore:t.productBefore,productAfter:t.productAfter},techChanges:r.map(e=>({file:e.file,techBefore:e.techBefore,techAfter:e.techAfter,confidence:e.confidence})),originalVerdict:{score:m,reason:h},flow:{name:a.name,rank:a.rank,importance:void 0,importanceReason:a.importanceReason,trace:a.trace,productFlow:a.productFlow},commitMessages:o,gitSignalsBlock:y,runContext:c,affectedSteps:l}),options:{model:n.REGRESSION_IMPACT_CALIBRATOR_MODEL,systemPrompt:b,allowedTools:[],permissionMode:n.REGRESSION_PERMISSION_MODE,allowDangerouslySkipPermissions:!0,maxBudgetUsd:n.REGRESSION_IMPACT_CALIBRATOR_MAX_BUDGET_USD,maxTurns:n.REGRESSION_IMPACT_CALIBRATOR_MAX_TURNS,cwd:p,sessionId:(0,f.randomUUID)(),outputFormat:{type:`json_schema`,schema:n.VERDICT_CALIBRATOR_OUTPUT_SCHEMA},env:{...process.env,ANTHROPIC_BASE_URL:d,ANTHROPIC_AUTH_TOKEN:u??``}}});for await(let e of x){if(!_(e))continue;let r=e.total_cost_usd??0,i=e.total_cost_usd?.toFixed(4)??`N/A`,a=e.num_turns,o=a>=n.REGRESSION_IMPACT_CALIBRATOR_MAX_TURNS;if(v(e))return n.logger.info.defaultLog(`[regression-impact] Verdict calibrator error for "${t.title??`(untitled)`}": ${e.subtype} (cost: $${i})`),{verdict:null,costUsd:r,turns:a,maxTurnsHit:o};let s=Uh(e.structured_output);if(s===void 0)return n.logger.info.defaultLog(`[regression-impact] Verdict calibrator: invalid structured output for "${t.title??`(untitled)`}" (cost: $${i})`),{verdict:null,costUsd:r,turns:a,maxTurnsHit:o};let c=s.score,l=c!==m;return{verdict:{score:c,reason:s.reasoning,changed:l},costUsd:r,turns:a,maxTurnsHit:o}}return n.logger.info.defaultLog(`[regression-impact] Verdict calibrator stream ended with no result message for "${t.title??`(untitled)`}" — partial API cost unrecoverable`),{verdict:null,costUsd:0,turns:0,maxTurnsHit:!1,streamEnded:!0}}function Kh(e,t,r,i){if(i)return t;if((0,c.isDefined)(r)&&r.length>0)try{return Wm(e,r),r}catch{n.logger.info.defaultLog(`[regression-impact] anchorSha ${r} not found locally, falling back to branch`)}return Km(e,t)}async function qh(e,t){try{let r=t.getCatalogId(),i=(0,c.isDefined)(r)&&r.length>0?`/api/v1/regression/catalogs/${r}`:Jh(t);if(i===null)return null;n.logger.info.defaultLog(`[regression-impact] Loading catalog from: ${i}`);let a=await e.get(i);n.logger.info.defaultLog(`[regression-impact] Loaded catalog id: ${a.id??`unknown`}`);let o=a.flows.filter(e=>e.status!==`DEPRECATED`);return{catalogId:a.id,rootPath:a.rootPath,projectType:a.projectType,anchorBranch:a.anchorBranch,anchorSha:a.anchorSha??void 0,flows:o}}catch(e){return n.logger.info.defaultLog(`[regression-impact] Could not load catalog from backend: ${String(e)}`),null}}function Jh(e){let t=e.getContext();if(!(0,c.isDefined)(t?.git?.owner)||!(0,c.isDefined)(t?.git?.repository))return null;let{owner:n,repository:r}=t.git,i=t.git.anchorBranch?.trim()??``;return i.length===0?null:`/api/v1/regression/catalogs?owner=${n}&repo=${r}&anchorBranch=${i}`}function Yh(e,t,n){if((n??``).length>0)return n;let r=t.getContext()?.git?.compareBranch?.trim();return(0,c.isDefined)(r)&&r.length>0?r:Hm(e)}async function Xh(e,t,n,r,i,a,o){let s=Yh(e,r,o),{files:c,description:l}=n===`LOCAL`?Ym(e):Jm(e,s,t),u=await Rh(c,i,a,e);return{branch:s,changedFiles:u.sourceFiles,compareDescription:l,preFilterCostUsd:u.costUsd,preFilterTurns:u.turns,preFilterMaxTurnsHit:u.maxTurnsHit}}async function Zh(e,t,r,i,a,o,s,c){let{runFileToFlowMapping:l}=await Promise.resolve().then(()=>jee()),{mappings:u,costUsd:d,turns:f,maxTurnsHit:p}=await l(e,t,r,i,a,o,s,c),m=new Map;for(let e of u)for(let t of e.flowIds)m.has(t)||m.set(t,new Set),m.get(t)?.add(e.file);let h=e.filter(e=>(m.get(e.flowId)?.size??0)>0).length;return n.logger.info.defaultLog(`[regression-impact] File-to-flow mapping: ${h} affected, ${e.length-h} not affected`),{flowFileMap:m,costUsd:d,turns:f,maxTurnsHit:p}}function Qh(e,t){return e.map(e=>{let n=t.get(e.flowId),r=(n?.size??0)>0;return{flow:e,affected:r,changedFiles:r?[...n]:[],severity:r?`MEDIUM`:`NONE`}})}function $h(e,t){if(e.productFlow==null)return[];let n=new Map(e.productFlow.steps.map(e=>[e.stepId,e]));return t.filter(e=>n.has(e.stepId)).map(e=>{let t=n.get(e.stepId);if((0,c.isDefined)(t))return{stepId:e.stepId,actor:t.actor,action:t.action,reason:e.reason}}).filter(c.isDefined)}async function eg(e,t,r,i,a,o,s,c,l){let u=e.filter(e=>e.affected&&e.severity!==`NONE`&&e.severity!==void 0),d=e.filter(e=>e.uncertain===!0),f=[...u,...d.filter(e=>!u.includes(e))],p=0;if(n.logger.info.defaultLog(`[regression-impact] Sonnet deep analysis for ${f.length} flow(s) (${u.length} affected, ${d.length} uncertain) in parallel...`),f.length===0)return{costUsd:0,turns:0,maxTurnsHit:!1};let m=th(t,[...new Set(f.flatMap(e=>e.changedFiles))],Qm(t,r,s),l,i),h=0,g=0,_=!1,v=new w.default({concurrency:6});for(let e of f)v.add(async()=>{try{p+=1,n.logger.info.defaultLog(`[regression-impact] ${p} - Sonnet deep analysis: ${e.flow.name} (${e.changedFiles.length} file(s))`);let l=await Hh(e.flow,e.changedFiles,t,r,i,a,o,s,c,m);if(l===null){n.logger.info.defaultLog(`[regression-impact] Sonnet deep returned null for flow "${e.flow.name}" — keeping default severity "${e.severity}" with no techChanges/productChanges`);return}h+=l.costUsd,g+=l.turns,_||=l.maxTurnsHit,ng(e,l)}catch(t){n.logger.info.defaultLog(`[regression-impact] Sonnet deep crashed for flow "${e.flow.name}": ${String(t)}`)}});return await v.onIdle(),{costUsd:h,turns:g,maxTurnsHit:_}}async function tg(e,t,r,i,a,o,s,c,l,u){let d=[];for(let t of e)if(t.productChanges!==void 0)for(let e of t.productChanges){let r=e.verdictScore;r!==void 0&&r>=n.REGRESSION_IMPACT_CALIBRATION_RANGE_MIN&&r<=n.REGRESSION_IMPACT_CALIBRATION_RANGE_MAX&&d.push({fi:t,pc:e})}if(d.length===0)return{costUsd:0,turns:0,maxTurnsHit:!1,calibratedCount:0,changedCount:0,failedCount:0,crashedCount:0};n.logger.info.defaultLog(`[regression-impact] Verdict calibration for ${d.length} borderline productChange(s)...`);let f=th(t,[...new Set(d.flatMap(({fi:e})=>(e.techChanges??[]).map(e=>e.file)))],Qm(t,r,s),l,i),p=0,m=0,h=!1,g=0,_=0,v=0,y=new w.default({concurrency:n.REGRESSION_IMPACT_CALIBRATOR_CONCURRENCY});for(let e of d)y.add(async()=>{try{let r=e.fi.affectedSteps??[],i=await Gh({productChange:e.pc,techChanges:e.fi.techChanges??[],flow:e.fi.flow,commitMessages:c,gitSignals:f,runContext:u,affectedSteps:r,jwtToken:a,anthropicBaseUrl:o,rootPath:t});if(p+=i.costUsd,m+=i.turns,h||=i.maxTurnsHit,i.streamEnded===!0&&(v+=1),i.verdict===null){i.streamEnded!==!0&&(_+=1),n.logger.info.defaultLog(`[regression-impact] Verdict calibrator returned no verdict for "${e.pc.title??`(untitled)`}" — keeping original score ${e.pc.verdictScore??`?`}`);return}let s=e.pc.verdictScore,l=e.pc.verdictReason;e.pc.originalVerdictScore=s,e.pc.originalVerdictReason=l,i.verdict.changed?(e.pc.calibrationReason=`Calibrated ${s} → ${i.verdict.score}: ${i.verdict.reason}`,e.pc.verdictScore=i.verdict.score,e.pc.verdictReason=i.verdict.reason,g+=1,n.logger.info.defaultLog(`[regression-impact] Verdict calibrated for "${e.pc.title??`(untitled)`}": ${s} → ${i.verdict.score}`)):e.pc.calibrationReason=`Calibrator confirmed score ${s}: ${i.verdict.reason}`}catch(t){v+=1,n.logger.info.defaultLog(`[regression-impact] Verdict calibrator crashed for "${e.pc.title??`(untitled)`}" — partial API cost unrecoverable: ${String(t)}`)}});return await y.onIdle(),v>0&&n.logger.info.defaultLog(`[regression-impact] Verdict calibration: ${v}/${d.length} call(s) crashed — totalCost ($${p.toFixed(4)}) does not include their partial spend`),{costUsd:p,turns:m,maxTurnsHit:h,calibratedCount:d.length,changedCount:g,failedCount:_,crashedCount:v}}function ng(e,t){e.severity=t.severity,e.severityReason=t.productChanges.find(e=>e.severity===t.severity)?.severityReason,e.techChanges=t.techChanges,e.productChanges=t.productChanges,t.affectedSteps&&(e.affectedSteps=$h(e.flow,t.affectedSteps)),e.uncertain===!0&&(e.affected=t.severity!==`NONE`,e.uncertain=!1)}function rg(e,t){(0,p.mkdirSync)(t,{recursive:!0});let r=new Date().toISOString().replaceAll(/[:.]/g,`-`),i=j.default.basename(e.rootPath),a=j.default.join(t,`${r}-${i}-${e.branch}-vs-${e.anchorBranch}.impact.md`),o=e.flowImpacts.map(({flow:e,affected:t,severity:n,severityReason:r,techChanges:i,productChanges:a})=>{let o=t?`AFFECTED`:`NOT AFFECTED`,s=n!==void 0&&n.length>0?` — Severity: **${n}**`:``,c=r!==void 0&&r.length>0?`\n**Reason:** ${r}`:``,l=(i??[]).length>0?`
|
|
32851
33003
|
|
|
32852
33004
|
**Technical changes:**
|
|
32853
33005
|
`+(i??[]).map(e=>{let t=e.confidence===`low`?` (low confidence)`:``;return`- \`${e.file}\`${t}\n - Before: ${e.techBefore}\n - After: ${e.techAfter}`}).join(`
|
|
@@ -32881,10 +33033,10 @@ ${o}
|
|
|
32881
33033
|
|---|---|---|---|---|
|
|
32882
33034
|
${e.flowImpacts.map(e=>{let t=e.haikuSeverity??`—`,n=e.haikuConfidence??`—`,r=(0,c.isDefined)(e.techChanges)?e.severity??`—`:`skipped`,i=e.affected?`**${e.severity??`AFFECTED`}**`:`NOT AFFECTED`;return`| ${e.flow.name} | ${t} | ${n} | ${r} | ${i} |`}).join(`
|
|
32883
33035
|
`)}
|
|
32884
|
-
`;(0,p.writeFileSync)(a,l,`utf8`),n.logger.info.defaultLog(`[regression-impact] Impact report saved to: ${a}`)}function eg(e){n.logger.info.defaultLog(`[regression-impact] Regression Impact Check`),n.logger.info.defaultLog(`[regression-impact] Branch: ${e.branch} vs ${e.anchorBranch}`),n.logger.info.defaultLog(`[regression-impact] Run type: ${e.runType}`),n.logger.info.defaultLog(`[regression-impact] Changed files: ${e.changedFiles.length}`);let t=e.flowImpacts.filter(e=>e.affected||e.uncertain===!0||(0,c.isDefined)(e.techChanges)),r=e.flowImpacts.filter(e=>!e.affected&&e.uncertain!==!0&&!(0,c.isDefined)(e.techChanges)),i=t.filter(e=>e.affected&&e.severity!==`NONE`),a=t.filter(e=>!e.affected||e.severity===`NONE`);if(i.length>0){n.logger.info.defaultLog(`[regression-impact] Affected flows:`);for(let e of i)n.logger.info.defaultLog(`[regression-impact] ${e.flow.name} — ${e.severity}`)}a.length>0&&n.logger.info.defaultLog(`[regression-impact] Cleared by Sonnet deep: ${a.map(e=>e.flow.name).join(`, `)}`),r.length>0&&n.logger.info.defaultLog(`[regression-impact] ${r.length} flow(s) not affected (resolved by filter)`);let o=i.length,s=r.length,l=t.length;n.logger.info.defaultLog(`[regression-impact] Summary: ${o} of ${e.flowImpacts.length} flows affected (${s} resolved by filter, ${l} analyzed by Sonnet deep)`)}async function tg(e,t,r){try{let r=e.flowImpacts.filter(e=>e.affected&&e.severity!==void 0&&e.severity!==`NONE`).map(e=>{let t=(e.techChanges??[]).map(e=>({file:e.file,confidence:e.confidence,techBefore:e.techBefore,techAfter:e.techAfter})),n=(e.productChanges??[]).map(e=>({...e.title===void 0?{}:{title:e.title},productBefore:e.productBefore,productAfter:e.productAfter,confidence:e.confidence,severity:e.severity,severityReason:e.severityReason,...e.importance===void 0?{}:{importance:e.importance},...e.importanceReason===void 0?{}:{importanceReason:e.importanceReason},...e.priority===void 0?{}:{priority:e.priority},...e.verdictScore===void 0?{}:{verdict:{score:e.verdictScore,...e.verdictReason===void 0?{}:{reason:e.verdictReason}}}})),r=(e.affectedSteps??[]).map(e=>({stepId:e.stepId,actor:e.actor,action:e.action,reason:e.reason}));return{flowId:e.flow.flowId,techChanges:t,productChanges:n,affectedSteps:r}}),i={catalogId:e.catalogId,runType:e.runType,branch:e.branch,headSha:e.headSha,anchorSha:e.anchorSha,changedFiles:e.changedFiles,stepsMetrics:e.stepsMetrics??[],flowImpacts:r,agentVersion:Bm},a=await t.post(`/api/v1/regression/runs`,i);return n.logger.info.defaultLog(`[regression-impact] Run posted to backend. runId: ${a.runId}`),a}catch(e){return n.logger.info.defaultLog(`[regression-impact] Failed to post run to backend: ${String(e)}`),null}}function ng(e,t,n,r,i){return{stepName:e,costUsd:t,durationSeconds:(Date.now()-n)/1e3,turns:r,maxTurnsHit:i}}function rg(e){if(n.REGRESSION_LOG_COST)for(let t of e){let e=t.maxTurnsHit===!0?` ⚠️ cap`:``,r=t.turns===void 0?``:`, ${t.turns} turns${e}`;n.logger.info.defaultLog(`[regression-impact] ${t.stepName}: $${t.costUsd.toFixed(4)} (${t.durationSeconds.toFixed(1)}s${r})`)}}async function ig(e,t,r,i,a,o,s){let l=Date.now(),u=t===`LOCAL`,d=await Wh(a,o);if(!d)throw Error(`[regression-impact] Could not load catalog from backend. Run catalog sync first.`);let{catalogId:f,anchorBranch:p,anchorSha:m,flows:h,projectType:g}=d,_=o.getRootPath()??d.rootPath,v=Uh(_,p,m,u),y=Zm(_,v),b=(0,c.isDefined)(m)?`, sha: ${m}`:``;n.logger.info.defaultLog(`[regression-impact] Loaded catalog for: ${_}`),n.logger.info.defaultLog(`[regression-impact] Anchor: ${p} (resolved: ${v}${b})`),n.logger.info.defaultLog(`[regression-impact] ${h.length} flows in catalog`);let x=[],S=Date.now(),{branch:C,changedFiles:w,compareDescription:T,preFilterCostUsd:E,preFilterTurns:D,preFilterMaxTurnsHit:O}=await qh(_,v,t,o,r,i,s);x.push(ng(`preFilter`,E,S,D,O)),n.logger.info.defaultLog(`[regression-impact] Compare: ${T}`);let k=o.getLabel()?.trim(),A=(0,c.isDefined)(k)&&k.length>0?k:void 0,ee;if(!u)try{ee=Wm(_,C)}catch{n.logger.info.defaultLog(`[regression-impact] Could not resolve headSha for '${C}'`)}if(n.logger.info.defaultLog(`[regression-impact] Label: ${A??`(not set, using branch)`}, headSha: ${ee??`(none)`}`),w.length===0)return ag(h,f,_,A??C,ee,p,m,t,e,a,o);n.logger.info.defaultLog(`[regression-impact] ${w.length} changed files`);let j=Date.now(),{flowFileMap:te,costUsd:M,turns:N,maxTurnsHit:P}=await Jh(h,w,_,C,v,r,i,g);x.push(ng(`fileToFlowMapping`,M,j,N,P));let F=Yh(h,te),I=Date.now(),{costUsd:L,turns:ne,maxTurnsHit:R}=await Zh(F,_,C,v,r,i,u,y,m??``);x.push(ng(`deepAnalysis`,L,I,ne,R)),rg(x);let z={flowImpacts:F,catalogId:f,rootPath:_,changedFiles:w,branch:A??C,headSha:ee,anchorBranch:p,anchorSha:m,runType:t,stepsMetrics:x,durationSeconds:(Date.now()-l)/1e3};return n.REGRESSION_SAVE_REPORT_FILES&&$h(z,e),eg(z),await tg(z,a,o),z}async function ag(e,t,r,i,a,o,s,c,l,u,d){n.logger.info.defaultLog(`[regression-impact] No changes detected`);let f={flowImpacts:e.map(e=>({flow:e,affected:!1,changedFiles:[]})),catalogId:t,rootPath:r,changedFiles:[],branch:i,headSha:a,anchorBranch:o,anchorSha:s,runType:c};return n.REGRESSION_SAVE_REPORT_FILES&&$h(f,l),eg(f),await tg(f,u,d),f}var og=t.__toESM(n.require_decorateMetadata()),sg=t.__toESM(yn()),cg=t.__toESM(n.require_decorate()),lg,ug;let dg=class{constructor(e,t,n){this.globalConfigService=e,this.apiService=t,this.authStorage=n}async run(e){let t=await this.authStorage.getJWTToken();return ig(e.reportsDir,e.runType,t,this.globalConfigService.getAnthropicProxyUrl(),this.apiService,this.globalConfigService,e.compareBranch)}};dg=(0,cg.default)([(0,l.injectable)(),(0,sg.default)(0,(0,l.inject)(n.GlobalConfigService)),(0,sg.default)(1,(0,l.inject)(G)),(0,sg.default)(2,(0,l.inject)(vn)),(0,og.default)(`design:paramtypes`,[Object,typeof(lg=G!==void 0&&G)==`function`?lg:Object,typeof(ug=vn!==void 0&&vn)==`function`?ug:Object])],dg);let fg=`claude-haiku-4-5-20251001`,pg=`Read,Write,Edit,Bash(npm *),Bash(npx *),Bash(yarn *),Bash(pnpm *),Bash(bun *),Bash(node *),Bash(python *),Bash(python3 *),Bash(uv *),Bash(uvx *),Bash(pytest *),Bash(pylint *),Bash(ruff *),Bash(black *),Bash(mypy *),Bash(pyright *),Bash(isort *),Bash(flake8 *),Bash(autopep8 *),Bash(eslint *),Bash(prettier *),Bash(biome *),Bash(tsc *),Bash(vue-tsc *),Bash(svelte-check *),Bash(.venv/bin/* *),Bash(venv/bin/* *),Bash(.venv/Scripts/* *),Bash(venv/Scripts/* *),Bash(PYTHONPATH=* python *),Bash(PYTHONPATH=* python3 *),Bash(PYTHONPATH=* .venv/bin/* *),Bash(PYTHONPATH=* venv/bin/* *),Bash(PYTHONPATH=* .venv/Scripts/* *),Bash(PYTHONPATH=* venv/Scripts/* *),Bash(true),Glob,Grep,Skill`.split(`,`),mg={type:`object`,additionalProperties:!1,required:[`status`],properties:{status:{type:`string`,enum:[`generated`,`skipped`,`aborted`,`no-viable-tests`],description:"`generated` when green tests were shipped; `skipped` when the skill triaged the method as trivial; `aborted` for unresolvable inputs; `no-viable-tests` when every drafted test had to be removed (the file is left in place for inspection)."},reason:{type:`string`,description:"Short human-readable explanation. Required when status is not `generated`."},testCount:{type:`integer`,minimum:0,description:"Number of tests shipped. Only meaningful when status is `generated`."}}};var hg=t.__toESM(n.require_decorateMetadata()),gg=t.__toESM(yn()),_g=t.__toESM(n.require_decorate()),vg,yg,bg,xg;function Sg(){try{let e=(0,te.createRequire)(__filename)?.resolve?.(`@anthropic-ai/claude-agent-sdk`);if(e)return a.default.join(a.default.dirname(e),`cli.js`)}catch{}return a.default.join(__dirname,`..`,`..`,`node_modules`,`@anthropic-ai`,`claude-agent-sdk`,`cli.js`)}function Cg(){return a.default.join(__dirname,`..`,`plugin`)}let wg=class{constructor(e,t,n,r,i){this.globalConfigService=e,this.authStorage=t,this.apiService=n,this.metricReportService=r,this.testResultCounterService=i}async run(e){let t=this.globalConfigService.getPluginPath()??Cg(),i=this.globalConfigService.getBackendURL(),o=Date.now(),s=()=>Date.now()-o;if(!i)return{outcome:`error`,success:!1,error:`backendURL is not configured`,durationMs:s()};let l=e.requestId??n.logger.getRequestId(),u=new AbortController;(0,c.isDefined)(e.abortSignal)&&(e.abortSignal.aborted?u.abort():e.abortSignal.addEventListener(`abort`,()=>u.abort(),{once:!0}));let d=await this.authStorage.getJWTToken()??``,p=Sg(),m=R(e.filePath),h=re(e.filePath)?n.TestFramework.PYTEST:this.globalConfigService.getTestFramework();try{await this.apiService.post(`/api/v1/tests/generate-prompt`,{testedCodeDataSource:{filePath:e.filePath,relativePathToTestFile:``,testFramework:h,language:m,testedMethod:{name:e.methodName,isAsync:!1,isStatic:!1,parameters:[],imports:[],decorators:[],code:``,exportType:`named`,accessModifierType:`public`,signature:e.methodName,kind:`function`},missingDependencies:[],codeDependencies:[],usages:[],libraries:[],gitUrl:null},llmConfig:{},clientSource:this.globalConfigService.getClientSource()},{headers:{[on]:l}})}catch(e){if(e instanceof rn&&e.code===tn.NOT_ENOUGH_BALANCE_ERROR)return{outcome:`error`,success:!1,error:e.message,errorCode:e.code,durationMs:s()};n.logger.info.defaultLog(`[plugin-agent] generate-prompt side-effect failed: ${e}`)}let g=(0,c.isDefined)(e.testFilePath)?new Pr(e.testFilePath):Pr.fromTestablePath(e.filePath,e.methodName,e.workingDirectory),_=await g.isFileExists(),v=(_?await g.getText():``).trim().length>0,y=e.preserveExistingContent===!0&&v;e.preserveExistingContent===!0&&!v&&n.logger.default.warn(`[plugin-agent] preserveExistingContent was requested but the target file is empty — falling back to generate mode.`),(!_||!y)&&await g.replace(`
|
|
32885
|
-
`);let
|
|
32886
|
-
`)
|
|
32887
|
-
`)},hooks:{PreToolUse:[{matcher:`Write|Edit`,hooks:[O]},{matcher:`Read`,hooks:[bd]},{matcher:`Bash`,hooks:[yd,Wu]}]}}}),A=0;for await(let t of k){A+=1,await D.processMessage(t);let i=t.type;if(T.debug(`[plugin-agent] stream message #${A} type=${i??`unknown`}`),i===`assistant`){let e=t.message?.content,r=Array.isArray(e)?e:[],i=r.filter(e=>e.type===`tool_use`).map(e=>e.name),a=r.some(e=>e.type===`text`);i.length>0?n.logger.info.defaultLog(`[plugin-agent] Tool calls: ${i.join(`, `)}`):a&&n.logger.info.defaultLog(`[plugin-agent] Agent thinking...`)}if(r.isResultMessage(t)){await D.flush();let i=s();if(r.isErrorResult(t))return n.logger.default.warn(`[plugin-agent] Agent error: ${t.subtype}`),{outcome:`error`,success:!1,costUsd:t.total_cost_usd,error:t.subtype,durationMs:i};n.logger.info.defaultLog(`[plugin-agent] Agent completed. Cost: $${t.total_cost_usd.toFixed(4)} — ${i}ms`);let a=Tg(t.structured_output),o=a?.status,l=a?.reason;if(o===`skipped`||o===`aborted`||o===`no-viable-tests`){let e=(0,c.isDefined)(l)?`${o}: ${l}`:o;return n.logger.info.defaultLog(`[plugin-agent] ${o} by skill: ${l??`no reason given`}`),this.metricReportService.saveTestMetrics({requestId:E,timeElapsed:i,errorCause:e}),o===`skipped`?{outcome:`skipped`,success:!0,skipped:!0,skipReason:l??`trivial`,costUsd:t.total_cost_usd,durationMs:i}:{outcome:o,success:!1,costUsd:t.total_cost_usd,error:e,durationMs:i}}if(o!==`generated`)return n.logger.default.warn(`[plugin-agent] Missing or invalid structured_output — treating as error.`),{outcome:`error`,success:!1,costUsd:t.total_cost_usd,error:`invalid_structured_output`,durationMs:i};let u=await g.getText(),d=await this.testResultCounterService.getValidationReport(b,e.methodName).catch(()=>void 0),f=D.getLatestTestResult(),p=f?.passed??d?.greenTestsCount,m=f?.failed??d?.redTestsCount;return this.metricReportService.saveTestMetrics({requestId:E,timeElapsed:i,validationReport:d}),u!==``&&this.metricReportService.saveOperationMetricsTrace({parentRequestId:E,llmModel:fg,testFileContent:u}),{outcome:`generated`,success:!0,costUsd:t.total_cost_usd,testFilePath:x,durationMs:i,greenTestsCount:p,redTestsCount:m}}}return await D.flush(),{outcome:`error`,success:!1,error:`stream_ended_without_result`,durationMs:s()}}};wg=(0,_g.default)([(0,l.injectable)(),(0,gg.default)(0,(0,l.inject)(n.GlobalConfigService)),(0,gg.default)(1,(0,l.inject)(vn)),(0,gg.default)(2,(0,l.inject)(G)),(0,gg.default)(3,(0,l.inject)(Wn)),(0,gg.default)(4,(0,l.inject)(Kl)),(0,hg.default)(`design:paramtypes`,[Object,typeof(vg=vn!==void 0&&vn)==`function`?vg:Object,typeof(yg=G!==void 0&&G)==`function`?yg:Object,typeof(bg=Wn!==void 0&&Wn)==`function`?bg:Object,typeof(xg=Kl!==void 0&&Kl)==`function`?xg:Object])],wg);function Tg(e){if(!(0,c.isDefined)(e)||typeof e!=`object`)return;let t=e,n=t.status;if(!(n!==`generated`&&n!==`skipped`&&n!==`aborted`&&n!==`no-viable-tests`))return{status:n,reason:typeof t.reason==`string`?t.reason:void 0,testCount:typeof t.testCount==`number`?t.testCount:void 0}}var Eg=t.__toESM(n.require_decorateMetadata()),Dg=t.__toESM(yn()),Og=t.__toESM(n.require_decorate()),kg,Ag,jg,Mg,Ng,Pg,Fg,Ig,Lg,Rg,zg,Bg,Vg;let Hg=class{constructor(e,t,n,r,i,a,o,s,c,l,u,d){this.testablesController=e,this.coverageController=t,this.generateTestController=n,this.authService=r,this.globalConfigService=i,this.testResultCounterService=a,this.testableContextService=o,this.dynamicPromptService=s,this.testValidatorService=c,this.regressionImpactManager=l,this.regressionCatalogManager=u,this.pluginAgentRunner=d}async init(e){await this.authService.authorize(e)}async getTestables(e){return this.testablesController.getTestables(e)}async getAllMethodsCount(e){return this.testablesController.getAllMethodsCount(e)}async resolveEarlyTestFile(e){return this.testablesController.resolveEarlyTestFile(e)}async getTestableFileMap(e){return this.testablesController.getTestableFileMap(e)}async generateCoverage(e){return this.coverageController.generateCoverage(e)}async setCoverage(e){return this.coverageController.setCoverage(e)}async getCoverageTree(){return this.coverageController.getCoverageTree()}async getCoverageForFiles(e){return this.coverageController.getCoverageForFiles(e)}async generateTests(e,t){return this.generateTestController.addGenerationToQueue({filePath:e,testable:t})}async bulkGenerateTests(e,t,n,r){return this.generateTestController.bulkGenerateTests(e,t,n,r)}updateContext(e){this.globalConfigService.updateContext(e)}updateRootPath(e){this.globalConfigService.updateRootPath(e)}async getValidationReport(e,t){return this.testResultCounterService.getValidationReport(e,t)}async getTestedCodeDataSource(e,t,n){return this.testableContextService.getTestedCodeDataSource(e,t,n)}async runDynamicPrompt(e,t,n){return(await this.dynamicPromptService.initDynamicPrompt(e,t,0,n))?.validationReport??null}async validateTestsByCode(e,t){return this.testValidatorService.validateTestsByCode(e,t)}async runRegressionImpact(e){return this.regressionImpactManager.run(e)}async runRegressionCatalog(){return this.regressionCatalogManager.run()}async runPluginAgent(e){let t=this.globalConfigService.getRootPath();return this.pluginAgentRunner.run({...e,workingDirectory:t})}};(0,Og.default)([n.WithLoggerContext({category:xe.INITIALIZATION}),(0,Eg.default)(`design:type`,Function),(0,Eg.default)(`design:paramtypes`,[String]),(0,Eg.default)(`design:returntype`,Promise)],Hg.prototype,`init`,null),(0,Og.default)([n.WithLoggerContext({category:xe.GET_TESTABLES}),(0,Eg.default)(`design:type`,Function),(0,Eg.default)(`design:paramtypes`,[String]),(0,Eg.default)(`design:returntype`,Promise)],Hg.prototype,`getTestables`,null),(0,Og.default)([n.WithLoggerContext({category:xe.GET_TESTABLES}),(0,Eg.default)(`design:type`,Function),(0,Eg.default)(`design:paramtypes`,[String]),(0,Eg.default)(`design:returntype`,Promise)],Hg.prototype,`getAllMethodsCount`,null),(0,Og.default)([n.WithLoggerContext({category:xe.GET_TESTABLES}),(0,Eg.default)(`design:type`,Function),(0,Eg.default)(`design:paramtypes`,[Object]),(0,Eg.default)(`design:returntype`,Promise)],Hg.prototype,`resolveEarlyTestFile`,null),(0,Og.default)([n.WithLoggerContext({category:xe.GET_TESTABLES}),(0,Eg.default)(`design:type`,Function),(0,Eg.default)(`design:paramtypes`,[Array]),(0,Eg.default)(`design:returntype`,Promise)],Hg.prototype,`getTestableFileMap`,null),(0,Og.default)([n.WithLoggerContext({category:xe.GENERATE_COVERAGE}),(0,Eg.default)(`design:type`,Function),(0,Eg.default)(`design:paramtypes`,[Array]),(0,Eg.default)(`design:returntype`,Promise)],Hg.prototype,`generateCoverage`,null),(0,Og.default)([n.WithLoggerContext({category:xe.SET_COVERAGE}),(0,Eg.default)(`design:type`,Function),(0,Eg.default)(`design:paramtypes`,[Object]),(0,Eg.default)(`design:returntype`,Promise)],Hg.prototype,`setCoverage`,null),(0,Og.default)([n.WithLoggerContext({category:xe.GET_COVERAGE}),(0,Eg.default)(`design:type`,Function),(0,Eg.default)(`design:paramtypes`,[]),(0,Eg.default)(`design:returntype`,Promise)],Hg.prototype,`getCoverageTree`,null),(0,Og.default)([n.WithLoggerContext({category:xe.GET_COVERAGE}),(0,Eg.default)(`design:type`,Function),(0,Eg.default)(`design:paramtypes`,[Array]),(0,Eg.default)(`design:returntype`,Promise)],Hg.prototype,`getCoverageForFiles`,null),(0,Og.default)([n.WithLoggerContext({category:xe.GENERATE_TESTS}),(0,Eg.default)(`design:type`,Function),(0,Eg.default)(`design:paramtypes`,[String,Object]),(0,Eg.default)(`design:returntype`,Promise)],Hg.prototype,`generateTests`,null),(0,Og.default)([n.WithLoggerContext({category:xe.GENERATE_TESTS}),(0,Eg.default)(`design:type`,Function),(0,Eg.default)(`design:paramtypes`,[Array,Object,String,typeof(Vg=c.Fn!==void 0&&c.Fn)==`function`?Vg:Object]),(0,Eg.default)(`design:returntype`,Promise)],Hg.prototype,`bulkGenerateTests`,null),(0,Og.default)([n.WithLoggerContext({category:xe.GENERATE_TESTS}),(0,Eg.default)(`design:type`,Function),(0,Eg.default)(`design:paramtypes`,[String,String]),(0,Eg.default)(`design:returntype`,Promise)],Hg.prototype,`getValidationReport`,null),(0,Og.default)([n.WithLoggerContext({category:xe.GET_TESTED_CODE_DATA_SOURCE}),(0,Eg.default)(`design:type`,Function),(0,Eg.default)(`design:paramtypes`,[String,Object,String]),(0,Eg.default)(`design:returntype`,Promise)],Hg.prototype,`getTestedCodeDataSource`,null),(0,Og.default)([n.WithLoggerContext({category:xe.DYNAMIC_PROMPT}),(0,Eg.default)(`design:type`,Function),(0,Eg.default)(`design:paramtypes`,[String,Object,String]),(0,Eg.default)(`design:returntype`,Promise)],Hg.prototype,`runDynamicPrompt`,null),(0,Og.default)([n.WithLoggerContext({category:xe.TEST_VALIDATION}),(0,Eg.default)(`design:type`,Function),(0,Eg.default)(`design:paramtypes`,[String,String]),(0,Eg.default)(`design:returntype`,Promise)],Hg.prototype,`validateTestsByCode`,null),(0,Og.default)([n.WithLoggerContext({category:xe.REGRESSION_IMPACT}),(0,Eg.default)(`design:type`,Function),(0,Eg.default)(`design:paramtypes`,[Object]),(0,Eg.default)(`design:returntype`,Promise)],Hg.prototype,`runRegressionImpact`,null),(0,Og.default)([n.WithLoggerContext({category:xe.REGRESSION_CATALOG}),(0,Eg.default)(`design:type`,Function),(0,Eg.default)(`design:paramtypes`,[]),(0,Eg.default)(`design:returntype`,Promise)],Hg.prototype,`runRegressionCatalog`,null),(0,Og.default)([n.WithLoggerContext({category:xe.GENERATE_TESTS}),(0,Eg.default)(`design:type`,Function),(0,Eg.default)(`design:paramtypes`,[Object]),(0,Eg.default)(`design:returntype`,Promise)],Hg.prototype,`runPluginAgent`,null),Hg=(0,Og.default)([(0,l.injectable)(),(0,Dg.default)(0,(0,l.inject)(zm)),(0,Dg.default)(1,(0,l.inject)($t)),(0,Dg.default)(2,(0,l.inject)(km)),(0,Dg.default)(3,(0,l.inject)(us)),(0,Dg.default)(4,(0,l.inject)(n.GlobalConfigService)),(0,Dg.default)(5,(0,l.inject)(Kl)),(0,Dg.default)(6,(0,l.inject)(Zp)),(0,Dg.default)(7,(0,l.inject)(uu)),(0,Dg.default)(8,(0,l.inject)(kl)),(0,Dg.default)(9,(0,l.inject)(dg)),(0,Dg.default)(10,(0,l.inject)(Ih)),(0,Dg.default)(11,(0,l.inject)(wg)),(0,Eg.default)(`design:paramtypes`,[typeof(kg=zm!==void 0&&zm)==`function`?kg:Object,typeof(Ag=$t!==void 0&&$t)==`function`?Ag:Object,typeof(jg=km!==void 0&&km)==`function`?jg:Object,typeof(Mg=us!==void 0&&us)==`function`?Mg:Object,typeof(Ng=n.GlobalConfigService!==void 0&&n.GlobalConfigService)==`function`?Ng:Object,typeof(Pg=Kl!==void 0&&Kl)==`function`?Pg:Object,typeof(Fg=Zp!==void 0&&Zp)==`function`?Fg:Object,typeof(Ig=uu!==void 0&&uu)==`function`?Ig:Object,typeof(Lg=kl!==void 0&&kl)==`function`?Lg:Object,typeof(Rg=dg!==void 0&&dg)==`function`?Rg:Object,typeof(zg=Ih!==void 0&&Ih)==`function`?zg:Object,typeof(Bg=wg!==void 0&&wg)==`function`?Bg:Object])],Hg);let Ug=!1;e.AST=Ot,e.AccessModifierType=Ee,e.AstModuleInfo=Et,e.CONCURRENCY=n.CONCURRENCY,e.COVERAGE_THRESHOLD=n.COVERAGE_THRESHOLD,e.CalculateCoverageOption=n.CalculateCoverageOption,e.DEFAULT_TYPE_KIND=Oe,e.ExportType=Te,e.GenerateTestsOutputType=n.GenerateTestsOutputType,e.GeneratedTestStructure=n.GeneratedTestStructure,e.LibraryName=De,e.RequestSource=n.RequestSource,Object.defineProperty(e,`TSAgent`,{enumerable:!0,get:function(){return Hg}}),e.TestFileName=n.TestFileName,e.TestFramework=n.TestFramework,e.TestStructureVariant=n.TestStructureVariant,e.TestSuffix=n.TestSuffix,e.WithTsMorphManager=Ge,e.createTSAgent=(e={})=>((Ug?n.inversify_default.rebindSync(n.GlobalConfigService):n.inversify_default.bind(n.GlobalConfigService)).toDynamicValue(()=>new n.GlobalConfigService(e)).inSingletonScope(),Ug=!0,n.inversify_default.get(Hg)),e.findLintConfigPath=be,e.getUnitTests=at,e.tsMorphManager=We}))();const DU={TSAgent:Symbol.for(`TSAgent`),CliOptions:Symbol.for(`CliOptions`),SCMHostService:Symbol.for(`SCMHostService`)};var OU=u(CR());let kU=function(e){return e.PR=`generate-for-pr`,e.COMMIT=`generate-for-commit`,e.PROJECT=`generate-for-project`,e.COVERAGE=`generate-coverage`,e.GATHER_STATS=`gather-stats`,e.REGRESSION_IMPACT=`generate-impact`,e.REGRESSION_CATALOG=`generate-catalog`,e}({});const AU=Object.freeze({status:`aborted`});function jU(e,t,n){function r(n,r){var i;Object.defineProperty(n,`_zod`,{value:n._zod??{},enumerable:!1}),(i=n._zod).traits??(i.traits=new Set),n._zod.traits.add(e),t(n,r);for(let e in o.prototype)e in n||Object.defineProperty(n,e,{value:o.prototype[e].bind(n)});n._zod.constr=o,n._zod.def=r}let i=n?.Parent??Object;class a extends i{}Object.defineProperty(a,`name`,{value:e});function o(e){var t;let i=n?.Parent?new a:this;r(i,e),(t=i._zod).deferred??(t.deferred=[]);for(let e of i._zod.deferred)e();return i}return Object.defineProperty(o,`init`,{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:t=>n?.Parent&&t instanceof n.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(o,`name`,{value:e}),o}var MU=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},NU=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};const PU={};function FU(e){return e&&Object.assign(PU,e),PU}function Mee(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function IU(e,t){return typeof t==`bigint`?t.toString():t}function LU(e){return{get value(){{let t=e();return Object.defineProperty(this,`value`,{value:t}),t}throw Error(`cached value already set`)}}}function RU(e){return e==null}function zU(e){let t=e.startsWith(`^`)?1:0,n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function BU(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=t.toString(),i=(r.split(`.`)[1]||``).length;if(i===0&&/\d?e-\d?/.test(r)){let e=r.match(/\d?e-(\d?)/);e?.[1]&&(i=Number.parseInt(e[1]))}let a=n>i?n:i;return Number.parseInt(e.toFixed(a).replace(`.`,``))%Number.parseInt(t.toFixed(a).replace(`.`,``))/10**a}const VU=Symbol(`evaluating`);function HU(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==VU)return r===void 0&&(r=VU,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function UU(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function WU(...e){let t={};for(let n of e){let e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function GU(e){return JSON.stringify(e)}const KU=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function qU(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const JU=LU(()=>{if(typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function YU(e){if(qU(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(qU(n)===!1||Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)===!1)}function XU(e){return YU(e)?{...e}:Array.isArray(e)?[...e]:e}const ZU=new Set([`string`,`number`,`symbol`]);function QU(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function $U(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function eW(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function Nee(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}const Pee={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function tW(e,t){let n=e._zod.def;return $U(e,WU(e._zod.def,{get shape(){let e={};for(let r in t){if(!(r in n.shape))throw Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return UU(this,`shape`,e),e},checks:[]}))}function nW(e,t){let n=e._zod.def;return $U(e,WU(e._zod.def,{get shape(){let r={...e._zod.def.shape};for(let e in t){if(!(e in n.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return UU(this,`shape`,r),r},checks:[]}))}function rW(e,t){if(!YU(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0)throw Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");return $U(e,WU(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return UU(this,`shape`,n),n},checks:[]}))}function iW(e,t){if(!YU(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return $U(e,{...e._zod.def,get shape(){let n={...e._zod.def.shape,...t};return UU(this,`shape`,n),n},checks:e._zod.def.checks})}function aW(e,t){return $U(e,WU(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return UU(this,`shape`,n),n},get catchall(){return t._zod.def.catchall},checks:[]}))}function oW(e,t,n){return $U(t,WU(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in r))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t])}else for(let t in r)i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t];return UU(this,`shape`,i),i},checks:[]}))}function sW(e,t,n){return $U(t,WU(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in i))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=new e({type:`nonoptional`,innerType:r[t]}))}else for(let t in r)i[t]=new e({type:`nonoptional`,innerType:r[t]});return UU(this,`shape`,i),i},checks:[]}))}function cW(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function lW(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function uW(e){return typeof e==`string`?e:e?.message}function dW(e,t,n){let r={...e,path:e.path??[]};return e.message||(r.message=uW(e.inst?._zod.def?.error?.(e))??uW(t?.error?.(e))??uW(n.customError?.(e))??uW(n.localeError?.(e))??`Invalid input`),delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function fW(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function pW(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}const mW=(e,t)=>{e.name=`$ZodError`,Object.defineProperty(e,`_zod`,{value:e._zod,enumerable:!1}),Object.defineProperty(e,`issues`,{value:t,enumerable:!1}),e.message=JSON.stringify(t,IU,2),Object.defineProperty(e,`toString`,{value:()=>e.message,enumerable:!1})},hW=jU(`$ZodError`,mW),gW=jU(`$ZodError`,mW,{Parent:Error});function _W(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function vW(e,t){let n=t||function(e){return e.message},r={_errors:[]},i=e=>{for(let t of e.issues)if(t.code===`invalid_union`&&t.errors.length)t.errors.map(e=>i({issues:e}));else if(t.code===`invalid_key`)i({issues:t.issues});else if(t.code===`invalid_element`)i({issues:t.issues});else if(t.path.length===0)r._errors.push(n(t));else{let e=r,i=0;for(;i<t.path.length;){let r=t.path[i];i===t.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(n(t))):e[r]=e[r]||{_errors:[]},e=e[r],i++}}};return i(e),r}const yW=e=>(t,n,r,i)=>{let a=r?Object.assign(r,{async:!1}):{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new MU;if(o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>dW(e,a,FU())));throw KU(t,i?.callee),t}return o.value},bW=e=>async(t,n,r,i)=>{let a=r?Object.assign(r,{async:!0}):{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>dW(e,a,FU())));throw KU(t,i?.callee),t}return o.value},xW=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new MU;return a.issues.length?{success:!1,error:new(e??hW)(a.issues.map(e=>dW(e,i,FU())))}:{success:!0,data:a.value}},SW=xW(gW),CW=e=>async(t,n,r)=>{let i=r?Object.assign(r,{async:!0}):{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>dW(e,i,FU())))}:{success:!0,data:a.value}},wW=CW(gW),TW=e=>(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return yW(e)(t,n,i)},EW=e=>(t,n,r)=>yW(e)(t,n,r),Fee=e=>async(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return bW(e)(t,n,i)},DW=e=>async(t,n,r)=>bW(e)(t,n,r),OW=e=>(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return xW(e)(t,n,i)},kW=e=>(t,n,r)=>xW(e)(t,n,r),AW=e=>async(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return CW(e)(t,n,i)},jW=e=>async(t,n,r)=>CW(e)(t,n,r),MW=/^[cC][^\s-]{8,}$/,NW=/^[0-9a-z]+$/,PW=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,FW=/^[0-9a-vA-V]{20}$/,Iee=/^[A-Za-z0-9]{27}$/,Lee=/^[a-zA-Z0-9_-]{21}$/,IW=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Ree=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,LW=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,RW=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function zW(){return RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)}const BW=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,VW=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,HW=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,UW=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,WW=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,GW=/^[A-Za-z0-9_-]*$/,KW=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,qW=/^\+(?:[0-9]){6,14}[0-9]$/,JW=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`,YW=RegExp(`^${JW}$`);function XW(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function ZW(e){return RegExp(`^${XW(e)}$`)}function QW(e){let t=XW({precision:e.precision}),n=[`Z`];e.local&&n.push(``),e.offset&&n.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let r=`${t}(?:${n.join(`|`)})`;return RegExp(`^${JW}T(?:${r})$`)}const $W=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},eG=/^-?\d+$/,tG=/^-?\d+(?:\.\d+)?/,nG=/^[^A-Z]*$/,rG=/^[^a-z]*$/,iG=jU(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),aG={number:`number`,bigint:`bigint`,object:`date`},oG=jU(`$ZodCheckLessThan`,(e,t)=>{iG.init(e,t);let n=aG[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??1/0;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:`too_big`,maximum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),sG=jU(`$ZodCheckGreaterThan`,(e,t)=>{iG.init(e,t);let n=aG[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??-1/0;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:`too_small`,minimum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),cG=jU(`$ZodCheckMultipleOf`,(e,t)=>{iG.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?n.value%t.value===BigInt(0):BU(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),lG=jU(`$ZodCheckNumberFormat`,(e,t)=>{iG.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=Pee[t.format];e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=a,n&&(r.pattern=eG)}),e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,continue:!t.abort});return}}s<i&&o.issues.push({origin:`number`,input:s,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inst:e})}}),uG=jU(`$ZodCheckMaxLength`,(e,t)=>{var n;iG.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!RU(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let r=n.value;if(r.length<=t.maximum)return;let i=fW(r);n.issues.push({origin:i,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),dG=jU(`$ZodCheckMinLength`,(e,t)=>{var n;iG.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!RU(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value;if(r.length>=t.minimum)return;let i=fW(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),fG=jU(`$ZodCheckLengthEquals`,(e,t)=>{var n;iG.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!RU(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{let r=n.value,i=r.length;if(i===t.length)return;let a=fW(r),o=i>t.length;n.issues.push({origin:a,...o?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),pG=jU(`$ZodCheckStringFormat`,(e,t)=>{var n,r;iG.init(e,t),e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??=new Set,n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),mG=jU(`$ZodCheckRegex`,(e,t)=>{pG.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),hG=jU(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=nG,pG.init(e,t)}),gG=jU(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=rG,pG.init(e,t)}),_G=jU(`$ZodCheckIncludes`,(e,t)=>{iG.init(e,t);let n=QU(t.includes),r=new RegExp(typeof t.position==`number`?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),vG=jU(`$ZodCheckStartsWith`,(e,t)=>{iG.init(e,t);let n=RegExp(`^${QU(t.prefix)}.*`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),yG=jU(`$ZodCheckEndsWith`,(e,t)=>{iG.init(e,t);let n=RegExp(`.*${QU(t.suffix)}$`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),bG=jU(`$ZodCheckOverwrite`,(e,t)=>{iG.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});var xG=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),--this.indent}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(`
|
|
33036
|
+
`;(0,p.writeFileSync)(a,l,`utf8`),n.logger.info.defaultLog(`[regression-impact] Impact report saved to: ${a}`)}function ig(e){n.logger.info.defaultLog(`[regression-impact] Regression Impact Check`),n.logger.info.defaultLog(`[regression-impact] Branch: ${e.branch} vs ${e.anchorBranch}`),n.logger.info.defaultLog(`[regression-impact] Run type: ${e.runType}`),n.logger.info.defaultLog(`[regression-impact] Changed files: ${e.changedFiles.length}`);let t=e.flowImpacts.filter(e=>e.affected||e.uncertain===!0||(0,c.isDefined)(e.techChanges)),r=e.flowImpacts.filter(e=>!e.affected&&e.uncertain!==!0&&!(0,c.isDefined)(e.techChanges)),i=t.filter(e=>e.affected&&e.severity!==`NONE`),a=t.filter(e=>!e.affected||e.severity===`NONE`);if(i.length>0){n.logger.info.defaultLog(`[regression-impact] Affected flows:`);for(let e of i)n.logger.info.defaultLog(`[regression-impact] ${e.flow.name} — ${e.severity}`)}a.length>0&&n.logger.info.defaultLog(`[regression-impact] Cleared by Sonnet deep: ${a.map(e=>e.flow.name).join(`, `)}`),r.length>0&&n.logger.info.defaultLog(`[regression-impact] ${r.length} flow(s) not affected (resolved by filter)`);let o=i.length,s=r.length,l=t.length;n.logger.info.defaultLog(`[regression-impact] Summary: ${o} of ${e.flowImpacts.length} flows affected (${s} resolved by filter, ${l} analyzed by Sonnet deep)`)}async function ag(e,t,r){try{let r=e.flowImpacts.filter(e=>e.affected&&e.severity!==void 0&&e.severity!==`NONE`).map(e=>{let t=(e.techChanges??[]).map(e=>({file:e.file,confidence:e.confidence,techBefore:e.techBefore,techAfter:e.techAfter})),n=(e.productChanges??[]).map(e=>({...e.title===void 0?{}:{title:e.title},productBefore:e.productBefore,productAfter:e.productAfter,confidence:e.confidence,severity:e.severity,severityReason:e.severityReason,...e.importance===void 0?{}:{importance:e.importance},...e.importanceReason===void 0?{}:{importanceReason:e.importanceReason},...e.priority===void 0?{}:{priority:e.priority},...e.verdictScore===void 0?{}:{verdict:{score:e.verdictScore,...e.verdictReason===void 0?{}:{reason:e.verdictReason},...e.originalVerdictScore===void 0?{}:{originalScore:e.originalVerdictScore},...e.originalVerdictReason===void 0?{}:{originalReason:e.originalVerdictReason},...e.calibrationReason===void 0?{}:{calibrationReason:e.calibrationReason}}}})),r=(e.affectedSteps??[]).map(e=>({stepId:e.stepId,actor:e.actor,action:e.action,reason:e.reason}));return{flowId:e.flow.flowId,techChanges:t,productChanges:n,affectedSteps:r}}),i={catalogId:e.catalogId,runType:e.runType,branch:e.branch,headSha:e.headSha,anchorSha:e.anchorSha,changedFiles:e.changedFiles,stepsMetrics:e.stepsMetrics??[],flowImpacts:r,agentVersion:Bm},a=await t.post(`/api/v1/regression/runs`,i);return n.logger.info.defaultLog(`[regression-impact] Run posted to backend. runId: ${a.runId}`),a}catch(e){return n.logger.info.defaultLog(`[regression-impact] Failed to post run to backend: ${String(e)}`),null}}function og(e,t,n,r,i){return{stepName:e,costUsd:t,durationSeconds:(Date.now()-n)/1e3,turns:r,maxTurnsHit:i}}function sg(e){if(n.REGRESSION_LOG_COST)for(let t of e){let e=t.maxTurnsHit===!0?` ⚠️ cap`:``,r=t.turns===void 0?``:`, ${t.turns} turns${e}`;n.logger.info.defaultLog(`[regression-impact] ${t.stepName}: $${t.costUsd.toFixed(4)} (${t.durationSeconds.toFixed(1)}s${r})`)}}async function cg(e,t,r,i,a,o,s){let l=Date.now(),u=t===`LOCAL`,d=await qh(a,o);if(!d)throw Error(`[regression-impact] Could not load catalog from backend. Run catalog sync first.`);let{catalogId:f,anchorBranch:p,anchorSha:m,flows:h,projectType:g}=d,_=o.getRootPath()??d.rootPath,v=Kh(_,p,m,u),y=Zm(_,v),b=(0,c.isDefined)(m)?`, sha: ${m}`:``;n.logger.info.defaultLog(`[regression-impact] Loaded catalog for: ${_}`),n.logger.info.defaultLog(`[regression-impact] Anchor: ${p} (resolved: ${v}${b})`),n.logger.info.defaultLog(`[regression-impact] ${h.length} flows in catalog`);let x=[],S=Date.now(),{branch:C,changedFiles:w,compareDescription:T,preFilterCostUsd:E,preFilterTurns:D,preFilterMaxTurnsHit:O}=await Xh(_,v,t,o,r,i,s);x.push(og(`preFilter`,E,S,D,O)),n.logger.info.defaultLog(`[regression-impact] Compare: ${T}`);let k=o.getLabel()?.trim(),A=(0,c.isDefined)(k)&&k.length>0?k:void 0,ee;if(!u)try{ee=Wm(_,C)}catch{n.logger.info.defaultLog(`[regression-impact] Could not resolve headSha for '${C}'`)}if(n.logger.info.defaultLog(`[regression-impact] Label: ${A??`(not set, using branch)`}, headSha: ${ee??`(none)`}`),w.length===0)return lg(h,f,_,A??C,ee,p,m,t,e,a,o);n.logger.info.defaultLog(`[regression-impact] ${w.length} changed files`);let j=Date.now(),{flowFileMap:te,costUsd:M,turns:N,maxTurnsHit:P}=await Zh(h,w,_,C,v,r,i,g);x.push(og(`fileToFlowMapping`,M,j,N,P));let F=Qh(h,te),I=Date.now(),{costUsd:L,turns:ne,maxTurnsHit:R}=await eg(F,_,C,v,r,i,u,y,m);if(x.push(og(`deepAnalysis`,L,I,ne,R)),n.REGRESSION_IMPACT_CALIBRATION_ENABLED){let e=Date.now(),a=o.getContext()?.git,s=await tg(F,_,C,v,r,i,u,y,m,{owner:a?.owner,repo:a?.repository,anchorBranch:p,anchorSha:m,branch:A??C,headSha:ee,runType:t});if(x.push(og(`verdictCalibration`,s.costUsd,e,s.turns,s.maxTurnsHit)),s.calibratedCount>0){let{calibratedCount:e,changedCount:t,failedCount:r,crashedCount:i}=s,a=e-t-r-i;n.logger.info.defaultLog(`[regression-impact] Verdict calibration: ${t} changed, ${a} confirmed, ${r} failed (no verdict), ${i} crashed (out of ${e})`)}}else n.logger.info.defaultLog(`[regression-impact] Verdict calibration: skipped (REGRESSION_IMPACT_CALIBRATION_ENABLED=false)`);sg(x);let z={flowImpacts:F,catalogId:f,rootPath:_,changedFiles:w,branch:A??C,headSha:ee,anchorBranch:p,anchorSha:m,runType:t,stepsMetrics:x,durationSeconds:(Date.now()-l)/1e3};return n.REGRESSION_SAVE_REPORT_FILES&&rg(z,e),ig(z),await ag(z,a,o),z}async function lg(e,t,r,i,a,o,s,c,l,u,d){n.logger.info.defaultLog(`[regression-impact] No changes detected`);let f={flowImpacts:e.map(e=>({flow:e,affected:!1,changedFiles:[]})),catalogId:t,rootPath:r,changedFiles:[],branch:i,headSha:a,anchorBranch:o,anchorSha:s,runType:c};return n.REGRESSION_SAVE_REPORT_FILES&&rg(f,l),ig(f),await ag(f,u,d),f}var ug=t.__toESM(n.require_decorateMetadata()),dg=t.__toESM(yn()),fg=t.__toESM(n.require_decorate()),pg,mg;let hg=class{constructor(e,t,n){this.globalConfigService=e,this.apiService=t,this.authStorage=n}async run(e){let t=await this.authStorage.getJWTToken();return cg(e.reportsDir,e.runType,t,this.globalConfigService.getAnthropicProxyUrl(),this.apiService,this.globalConfigService,e.compareBranch)}};hg=(0,fg.default)([(0,l.injectable)(),(0,dg.default)(0,(0,l.inject)(n.GlobalConfigService)),(0,dg.default)(1,(0,l.inject)(G)),(0,dg.default)(2,(0,l.inject)(vn)),(0,ug.default)(`design:paramtypes`,[Object,typeof(pg=G!==void 0&&G)==`function`?pg:Object,typeof(mg=vn!==void 0&&vn)==`function`?mg:Object])],hg);let gg=`claude-haiku-4-5-20251001`,_g=`Read,Write,Edit,Bash(npm *),Bash(npx *),Bash(yarn *),Bash(pnpm *),Bash(bun *),Bash(node *),Bash(python *),Bash(python3 *),Bash(uv *),Bash(uvx *),Bash(pytest *),Bash(pylint *),Bash(ruff *),Bash(black *),Bash(mypy *),Bash(pyright *),Bash(isort *),Bash(flake8 *),Bash(autopep8 *),Bash(eslint *),Bash(prettier *),Bash(biome *),Bash(tsc *),Bash(vue-tsc *),Bash(svelte-check *),Bash(.venv/bin/* *),Bash(venv/bin/* *),Bash(.venv/Scripts/* *),Bash(venv/Scripts/* *),Bash(PYTHONPATH=* python *),Bash(PYTHONPATH=* python3 *),Bash(PYTHONPATH=* .venv/bin/* *),Bash(PYTHONPATH=* venv/bin/* *),Bash(PYTHONPATH=* .venv/Scripts/* *),Bash(PYTHONPATH=* venv/Scripts/* *),Bash(true),Glob,Grep`.split(`,`),vg={type:`object`,additionalProperties:!1,required:[`status`],properties:{status:{type:`string`,enum:[`generated`,`skipped`,`aborted`,`no-viable-tests`],description:"`generated` when green tests were shipped; `skipped` when the skill triaged the method as trivial; `aborted` for unresolvable inputs; `no-viable-tests` when every drafted test had to be removed (the file is left in place for inspection)."},reason:{type:`string`,description:"Short human-readable explanation. Required when status is not `generated`."},testCount:{type:`integer`,minimum:0,description:"Total number of tests shipped. Only meaningful when status is `generated`."},passedCount:{type:`integer`,minimum:0,description:"Number of passing tests. Only meaningful when status is `generated`."},failedCount:{type:`integer`,minimum:0,description:"Number of failing tests. Only meaningful when status is `generated`."}}};var yg=t.__toESM(n.require_decorateMetadata()),bg=t.__toESM(yn()),xg=t.__toESM(n.require_decorate()),Sg,Cg,wg,Tg;function Eg(e){if((0,c.isDefined)(e))return e;try{let e=(0,te.createRequire)(__filename)?.resolve?.(`@anthropic-ai/claude-agent-sdk`);if(e)return a.default.join(a.default.dirname(e),`cli.js`)}catch{}return a.default.join(__dirname,`..`,`..`,`node_modules`,`@anthropic-ai`,`claude-agent-sdk`,`cli.js`)}function Dg(){return a.default.join(__dirname,`..`,`plugin`)}function Og(e,t){return new Promise(n=>{if(t.aborted){n();return}let r=setTimeout(n,e);t.addEventListener(`abort`,()=>{clearTimeout(r),n()},{once:!0})})}function kg(e,t){return{type:`user`,message:{role:`user`,content:e},parent_tool_use_id:null,session_id:t}}async function*Ag(e,t,n,r,i){yield kg(e,t),await Og(3e4,n),!n.aborted&&(await r.flush(),i.debug(`[plugin-agent] Phase transition: recon → draft`),yield kg(`<system-reminder>Recon time is over. Move to Phase 3 — draft the test file now.</system-reminder>`,t),await Og(3e4,n),!n.aborted&&(await r.flush(),i.debug(`[plugin-agent] Phase transition: draft → validate`),yield kg(`<system-reminder>Draft time is over. Move to Phase 4 — run test, lint, and format gates now.</system-reminder>`,t),await Og(15e3,n),!n.aborted&&(await r.flush(),i.debug(`[plugin-agent] Phase transition: validate → stop`),yield kg(`<system-reminder>Time is up. Stop all work. Exit with your structured output now.</system-reminder>`,t))))}let jg=class{constructor(e,t,n,r,i){this.globalConfigService=e,this.authStorage=t,this.apiService=n,this.metricReportService=r,this.testResultCounterService=i}async run(e){let t=this.globalConfigService.getPluginPath()??Dg(),i=a.default.join(t,`skills`,`early-generate-unit-tests`,`references`),s=this.globalConfigService.getBackendURL(),l=Date.now(),u=()=>Date.now()-l;if(!s)return{outcome:`error`,success:!1,error:`backendURL is not configured`,durationMs:u()};let d=e.requestId??n.logger.getRequestId(),p=new AbortController;(0,c.isDefined)(e.abortSignal)&&(e.abortSignal.aborted?p.abort():e.abortSignal.addEventListener(`abort`,()=>p.abort(),{once:!0}));let m=await this.authStorage.getJWTToken()??``,h=Eg(this.globalConfigService.getClaudeCodeExecutablePath()),g=R(e.filePath),_=re(e.filePath)?n.TestFramework.PYTEST:this.globalConfigService.getTestFramework();try{await this.apiService.post(`/api/v1/tests/generate-prompt`,{testedCodeDataSource:{filePath:e.filePath,relativePathToTestFile:``,testFramework:_,language:g,testedMethod:{name:e.methodName,isAsync:!1,isStatic:!1,parameters:[],imports:[],decorators:[],code:``,exportType:`named`,accessModifierType:`public`,signature:e.methodName,kind:`function`},missingDependencies:[],codeDependencies:[],usages:[],libraries:[],gitUrl:null},llmConfig:{},clientSource:this.globalConfigService.getClientSource()},{headers:{[on]:d}})}catch(e){if(e instanceof rn&&e.code===tn.NOT_ENOUGH_BALANCE_ERROR)return{outcome:`error`,success:!1,error:e.message,errorCode:e.code,durationMs:u()};n.logger.info.defaultLog(`[plugin-agent] generate-prompt side-effect failed: ${e}`)}let v=(0,c.isDefined)(e.testFilePath)?new Pr(e.testFilePath):await Pr.getNextTestFile(e.filePath,e.methodName,e.workingDirectory);if(e.preserveExistingContent===!0&&!(0,c.isDefined)(e.testFilePath)){let t=await Pr.getLatestTestFile(e.filePath,e.methodName);if((0,c.isDefined)(t)){let e=await new Pr(B(t)).getText();e.trim().length>0&&await v.replace(e)}}let y=(await v.isFileExists()?await v.getText():``).trim().length>0,b=e.preserveExistingContent===!0&&y;if(e.preserveExistingContent===!0&&!y&&n.logger.default.warn(`[plugin-agent] preserveExistingContent was requested but the target file is empty — falling back to generate mode.`),!b){let t=re(e.filePath)?`#`:`//`;await v.replace(`${t} early-test-generation-in-progress`)}let x=v.getAbsoluteFilePath(),S=v.getFilePath(),C=a.default.relative(e.workingDirectory,x),w=a.default.join(i,`framework`,`${_}.md`),T=a.default.join(i,`${g}.md`),E=e=>(0,o.readFile)(e,`utf8`).catch(()=>(n.logger.default.warn(`[plugin-agent] Reference file not found: ${e}`),``)),[D,O]=await Promise.all([E(w),E(T)]),k=[`Generate unit tests for method \`${e.methodName}\` in: ${e.filePath}`,`Framework: ${_}`,`Working directory: ${a.default.normalize(e.workingDirectory)}`,`testFilePath: ${a.default.normalize(C)}`];b&&k.push(``,`ENHANCE MODE: The testFilePath already contains existing tests. Read the file first, then improve the tests according to the user's request below. Keep passing tests intact unless the request says otherwise; add, edit, or delete individual tests as the request requires. Do NOT start from an empty file.`),(0,c.isDefined)(e.userPrompt)&&e.userPrompt.trim()!==``&&k.push(``,e.userPrompt),D!==``&&k.push(``,`---`,`## Framework Reference`,D),O!==``&&k.push(``,`---`,`## Language Reference`,O);let A=k.join(`
|
|
33037
|
+
`),ee=this.globalConfigService.getProgressLogger({methodName:e.methodName});n.logger.info.defaultLog(`[plugin-agent] Starting plugin agent for file: ${e.filePath}, testFile: ${C}`);let j=d,te=new mf(this.metricReportService,j,gg,x,e.workingDirectory),N=xd(x,e.workingDirectory),P=(0,f.randomUUID)(),F=(0,M.query)({prompt:Ag(A,P,p.signal,te,ee),options:{systemPrompt:{type:`preset`,preset:`claude_code`,append:[`## Workflow`,``,`You generate unit tests in phases. Each phase transition is signaled by a user message.`,``,`### Phase 1 — Triage`,`Read the test and source file, locate the method.`,``,`Trivial shapes → exit {"status":"skipped","reason":"<shape>"}:`,`- Pure delegation / pass-through`,`- Delegation + a single guard throw`,`- Getters, setters, constant returns, stubs, framework no-ops`,`- One-line wrappers where the only logic is the dependency call`,``,`If unresolvable → exit {"status":"aborted","reason":"..."}`,``,`### Phase 2 — Recon`,`Gather in parallel:`,`1. Manifest (package.json, pyproject.toml, etc.)`,`2. Lint config (eslint.config.*, .eslintrc.*, ruff.toml, biome.json, etc.)`,`3. tsconfig.json for path aliases and baseUrl`,`4. Grep type definitions referenced by the method`,`5. Identify deps to mock`,``,`Compute exact import statements from testFilePath's directory to each dependency.`,``,`### Phase 3 — Draft & Edit`,`Read the test file and Put the test code into it using the Edit tool. Rules:`,`- AAA shape, one test per branch`,`- Use computed imports — do not guess paths`,`- Mock external deps, never mock the method under test`,`- No shared mutable state between tests`,`- Cap: ≤ 9 tests`,``,`### Phase 4 — Validate & Fix`,`Run in parallel: test, lint (autofix mode), format (fix mode).`,`If lint/format failed, fix and re-run only the failed gate.`,`Do NOT chase green tests — red tests exercising real behavior are fine.`,`Report pass/fail counts.`,``,`Exit {"status":"generated","testCount":N,"passedCount":P,"failedCount":F} or {"status":"no-viable-tests","reason":"..."}`,``,`## Import Resolution`,``,`The test file and source file are in DIFFERENT directories.`,`Compute every import path relative to the test file's directory, not the source file's.`,`- If the project uses path aliases and the source uses them, the test should too`,`- If using relative paths: path.relative(dirname(testFilePath), sourceFile)`,`- Example: source at src/services/foo.ts, test at src/services/foo.early.test/bar.early.test.ts → import from '../foo'`,`- The .early.test/ subdirectory means tests are always one level deeper than the source`].join(`
|
|
33038
|
+
`)},model:gg,pathToClaudeCodeExecutable:h,allowedTools:[..._g],permissionMode:`dontAsk`,maxBudgetUsd:2,cwd:e.workingDirectory,abortController:p,outputFormat:{type:`json_schema`,schema:vg},sessionId:P,env:{...process.env,ANTHROPIC_BASE_URL:this.globalConfigService.getAnthropicProxyUrl(),ANTHROPIC_AUTH_TOKEN:m,ANTHROPIC_CUSTOM_HEADERS:[`x-request-id: `+d].join(`
|
|
33039
|
+
`)},hooks:{PreToolUse:[{matcher:`Write|Edit`,hooks:[N]},{matcher:`Read`,hooks:[bd]},{matcher:`Bash`,hooks:[yd,Wu]}]}}}),I=0;try{for await(let t of F){I+=1,await te.processMessage(t);let i=t.type;if(ee.debug(`[plugin-agent] stream message #${I} type=${i??`unknown`}`),i===`assistant`){let e=t.message?.content,r=Array.isArray(e)?e:[],i=r.filter(e=>e.type===`tool_use`).map(e=>e.name),a=r.some(e=>e.type===`text`);i.length>0?n.logger.info.defaultLog(`[plugin-agent] Tool calls: ${i.join(`, `)}`):a&&n.logger.info.defaultLog(`[plugin-agent] Agent thinking...`)}if(r.isResultMessage(t)){await te.flush();let i=u();if(r.isErrorResult(t))return n.logger.default.warn(`[plugin-agent] Agent error: ${t.subtype}`),{outcome:`error`,success:!1,costUsd:t.total_cost_usd,error:t.subtype,durationMs:i};n.logger.info.defaultLog(`[plugin-agent] Agent completed. Cost: $${t.total_cost_usd.toFixed(4)} — ${i}ms`);let a=Mg(t.structured_output),o=a?.status,s=a?.reason;if(o===`skipped`||o===`aborted`||o===`no-viable-tests`){let e=(0,c.isDefined)(s)?`${o}: ${s}`:o;return n.logger.info.defaultLog(`[plugin-agent] ${o} by skill: ${s??`no reason given`}`),this.metricReportService.saveTestMetrics({requestId:j,timeElapsed:i,errorCause:e}),o===`skipped`?{outcome:`skipped`,success:!0,skipped:!0,skipReason:s??`trivial`,costUsd:t.total_cost_usd,durationMs:i}:{outcome:o,success:!1,costUsd:t.total_cost_usd,error:e,durationMs:i}}if(o!==`generated`)return n.logger.default.warn(`[plugin-agent] Missing or invalid structured_output — treating as error.`),{outcome:`error`,success:!1,costUsd:t.total_cost_usd,error:`invalid_structured_output`,durationMs:i};let l=await v.getText(),d=await this.testResultCounterService.getValidationReport(x,e.methodName).catch(()=>void 0),f=te.getLatestTestResult(),p=a?.passedCount??f?.passed??d?.greenTestsCount,m=a?.failedCount??f?.failed??d?.redTestsCount;return this.metricReportService.saveTestMetrics({requestId:j,timeElapsed:i,validationReport:d}),l!==``&&this.metricReportService.saveOperationMetricsTrace({parentRequestId:j,llmModel:gg,testFileContent:l}),{outcome:`generated`,success:!0,costUsd:t.total_cost_usd,testFilePath:S,durationMs:i,greenTestsCount:p,redTestsCount:m}}}return await te.flush(),{outcome:`error`,success:!1,error:`stream_ended_without_result`,durationMs:u()}}finally{p.abort()}}};jg=(0,xg.default)([(0,l.injectable)(),(0,bg.default)(0,(0,l.inject)(n.GlobalConfigService)),(0,bg.default)(1,(0,l.inject)(vn)),(0,bg.default)(2,(0,l.inject)(G)),(0,bg.default)(3,(0,l.inject)(Wn)),(0,bg.default)(4,(0,l.inject)(Kl)),(0,yg.default)(`design:paramtypes`,[Object,typeof(Sg=vn!==void 0&&vn)==`function`?Sg:Object,typeof(Cg=G!==void 0&&G)==`function`?Cg:Object,typeof(wg=Wn!==void 0&&Wn)==`function`?wg:Object,typeof(Tg=Kl!==void 0&&Kl)==`function`?Tg:Object])],jg);function Mg(e){if(!(0,c.isDefined)(e)||typeof e!=`object`)return;let t=e,n=t.status;if(!(n!==`generated`&&n!==`skipped`&&n!==`aborted`&&n!==`no-viable-tests`))return{status:n,reason:typeof t.reason==`string`?t.reason:void 0,testCount:typeof t.testCount==`number`?t.testCount:void 0,passedCount:typeof t.passedCount==`number`?t.passedCount:void 0,failedCount:typeof t.failedCount==`number`?t.failedCount:void 0}}var Ng=t.__toESM(n.require_decorateMetadata()),Pg=t.__toESM(yn()),Fg=t.__toESM(n.require_decorate()),Ig,Lg,Rg,zg,Bg,Vg,Hg,Ug,Wg,Gg,Kg,qg,Jg;let Yg=class{constructor(e,t,n,r,i,a,o,s,c,l,u,d){this.testablesController=e,this.coverageController=t,this.generateTestController=n,this.authService=r,this.globalConfigService=i,this.testResultCounterService=a,this.testableContextService=o,this.dynamicPromptService=s,this.testValidatorService=c,this.regressionImpactManager=l,this.regressionCatalogManager=u,this.pluginAgentRunner=d}async init(e){await this.authService.authorize(e)}async getTestables(e){return this.testablesController.getTestables(e)}async getAllMethodsCount(e){return this.testablesController.getAllMethodsCount(e)}async resolveEarlyTestFile(e){return this.testablesController.resolveEarlyTestFile(e)}async getTestableFileMap(e){return this.testablesController.getTestableFileMap(e)}async generateCoverage(e){return this.coverageController.generateCoverage(e)}async setCoverage(e){return this.coverageController.setCoverage(e)}async getCoverageTree(){return this.coverageController.getCoverageTree()}async getCoverageForFiles(e){return this.coverageController.getCoverageForFiles(e)}async generateTests(e,t){return this.generateTestController.addGenerationToQueue({filePath:e,testable:t})}async bulkGenerateTests(e,t,n,r){return this.generateTestController.bulkGenerateTests(e,t,n,r)}updateContext(e){this.globalConfigService.updateContext(e)}updateRootPath(e){this.globalConfigService.updateRootPath(e)}async getValidationReport(e,t){return this.testResultCounterService.getValidationReport(e,t)}async getTestedCodeDataSource(e,t,n){return this.testableContextService.getTestedCodeDataSource(e,t,n)}async runDynamicPrompt(e,t,n){return(await this.dynamicPromptService.initDynamicPrompt(e,t,0,n))?.validationReport??null}async validateTestsByCode(e,t){return this.testValidatorService.validateTestsByCode(e,t)}async runRegressionImpact(e){return this.regressionImpactManager.run(e)}async runRegressionCatalog(){return this.regressionCatalogManager.run()}async runPluginAgent(e){let t=this.globalConfigService.getRootPath();return this.pluginAgentRunner.run({...e,workingDirectory:t})}};(0,Fg.default)([n.WithLoggerContext({category:xe.INITIALIZATION}),(0,Ng.default)(`design:type`,Function),(0,Ng.default)(`design:paramtypes`,[String]),(0,Ng.default)(`design:returntype`,Promise)],Yg.prototype,`init`,null),(0,Fg.default)([n.WithLoggerContext({category:xe.GET_TESTABLES}),(0,Ng.default)(`design:type`,Function),(0,Ng.default)(`design:paramtypes`,[String]),(0,Ng.default)(`design:returntype`,Promise)],Yg.prototype,`getTestables`,null),(0,Fg.default)([n.WithLoggerContext({category:xe.GET_TESTABLES}),(0,Ng.default)(`design:type`,Function),(0,Ng.default)(`design:paramtypes`,[String]),(0,Ng.default)(`design:returntype`,Promise)],Yg.prototype,`getAllMethodsCount`,null),(0,Fg.default)([n.WithLoggerContext({category:xe.GET_TESTABLES}),(0,Ng.default)(`design:type`,Function),(0,Ng.default)(`design:paramtypes`,[Object]),(0,Ng.default)(`design:returntype`,Promise)],Yg.prototype,`resolveEarlyTestFile`,null),(0,Fg.default)([n.WithLoggerContext({category:xe.GET_TESTABLES}),(0,Ng.default)(`design:type`,Function),(0,Ng.default)(`design:paramtypes`,[Array]),(0,Ng.default)(`design:returntype`,Promise)],Yg.prototype,`getTestableFileMap`,null),(0,Fg.default)([n.WithLoggerContext({category:xe.GENERATE_COVERAGE}),(0,Ng.default)(`design:type`,Function),(0,Ng.default)(`design:paramtypes`,[Array]),(0,Ng.default)(`design:returntype`,Promise)],Yg.prototype,`generateCoverage`,null),(0,Fg.default)([n.WithLoggerContext({category:xe.SET_COVERAGE}),(0,Ng.default)(`design:type`,Function),(0,Ng.default)(`design:paramtypes`,[Object]),(0,Ng.default)(`design:returntype`,Promise)],Yg.prototype,`setCoverage`,null),(0,Fg.default)([n.WithLoggerContext({category:xe.GET_COVERAGE}),(0,Ng.default)(`design:type`,Function),(0,Ng.default)(`design:paramtypes`,[]),(0,Ng.default)(`design:returntype`,Promise)],Yg.prototype,`getCoverageTree`,null),(0,Fg.default)([n.WithLoggerContext({category:xe.GET_COVERAGE}),(0,Ng.default)(`design:type`,Function),(0,Ng.default)(`design:paramtypes`,[Array]),(0,Ng.default)(`design:returntype`,Promise)],Yg.prototype,`getCoverageForFiles`,null),(0,Fg.default)([n.WithLoggerContext({category:xe.GENERATE_TESTS}),(0,Ng.default)(`design:type`,Function),(0,Ng.default)(`design:paramtypes`,[String,Object]),(0,Ng.default)(`design:returntype`,Promise)],Yg.prototype,`generateTests`,null),(0,Fg.default)([n.WithLoggerContext({category:xe.GENERATE_TESTS}),(0,Ng.default)(`design:type`,Function),(0,Ng.default)(`design:paramtypes`,[Array,Object,String,typeof(Jg=c.Fn!==void 0&&c.Fn)==`function`?Jg:Object]),(0,Ng.default)(`design:returntype`,Promise)],Yg.prototype,`bulkGenerateTests`,null),(0,Fg.default)([n.WithLoggerContext({category:xe.GENERATE_TESTS}),(0,Ng.default)(`design:type`,Function),(0,Ng.default)(`design:paramtypes`,[String,String]),(0,Ng.default)(`design:returntype`,Promise)],Yg.prototype,`getValidationReport`,null),(0,Fg.default)([n.WithLoggerContext({category:xe.GET_TESTED_CODE_DATA_SOURCE}),(0,Ng.default)(`design:type`,Function),(0,Ng.default)(`design:paramtypes`,[String,Object,String]),(0,Ng.default)(`design:returntype`,Promise)],Yg.prototype,`getTestedCodeDataSource`,null),(0,Fg.default)([n.WithLoggerContext({category:xe.DYNAMIC_PROMPT}),(0,Ng.default)(`design:type`,Function),(0,Ng.default)(`design:paramtypes`,[String,Object,String]),(0,Ng.default)(`design:returntype`,Promise)],Yg.prototype,`runDynamicPrompt`,null),(0,Fg.default)([n.WithLoggerContext({category:xe.TEST_VALIDATION}),(0,Ng.default)(`design:type`,Function),(0,Ng.default)(`design:paramtypes`,[String,String]),(0,Ng.default)(`design:returntype`,Promise)],Yg.prototype,`validateTestsByCode`,null),(0,Fg.default)([n.WithLoggerContext({category:xe.REGRESSION_IMPACT}),(0,Ng.default)(`design:type`,Function),(0,Ng.default)(`design:paramtypes`,[Object]),(0,Ng.default)(`design:returntype`,Promise)],Yg.prototype,`runRegressionImpact`,null),(0,Fg.default)([n.WithLoggerContext({category:xe.REGRESSION_CATALOG}),(0,Ng.default)(`design:type`,Function),(0,Ng.default)(`design:paramtypes`,[]),(0,Ng.default)(`design:returntype`,Promise)],Yg.prototype,`runRegressionCatalog`,null),(0,Fg.default)([n.WithLoggerContext({category:xe.GENERATE_TESTS}),(0,Ng.default)(`design:type`,Function),(0,Ng.default)(`design:paramtypes`,[Object]),(0,Ng.default)(`design:returntype`,Promise)],Yg.prototype,`runPluginAgent`,null),Yg=(0,Fg.default)([(0,l.injectable)(),(0,Pg.default)(0,(0,l.inject)(zm)),(0,Pg.default)(1,(0,l.inject)($t)),(0,Pg.default)(2,(0,l.inject)(km)),(0,Pg.default)(3,(0,l.inject)(us)),(0,Pg.default)(4,(0,l.inject)(n.GlobalConfigService)),(0,Pg.default)(5,(0,l.inject)(Kl)),(0,Pg.default)(6,(0,l.inject)(Zp)),(0,Pg.default)(7,(0,l.inject)(uu)),(0,Pg.default)(8,(0,l.inject)(kl)),(0,Pg.default)(9,(0,l.inject)(hg)),(0,Pg.default)(10,(0,l.inject)(Ih)),(0,Pg.default)(11,(0,l.inject)(jg)),(0,Ng.default)(`design:paramtypes`,[typeof(Ig=zm!==void 0&&zm)==`function`?Ig:Object,typeof(Lg=$t!==void 0&&$t)==`function`?Lg:Object,typeof(Rg=km!==void 0&&km)==`function`?Rg:Object,typeof(zg=us!==void 0&&us)==`function`?zg:Object,typeof(Bg=n.GlobalConfigService!==void 0&&n.GlobalConfigService)==`function`?Bg:Object,typeof(Vg=Kl!==void 0&&Kl)==`function`?Vg:Object,typeof(Hg=Zp!==void 0&&Zp)==`function`?Hg:Object,typeof(Ug=uu!==void 0&&uu)==`function`?Ug:Object,typeof(Wg=kl!==void 0&&kl)==`function`?Wg:Object,typeof(Gg=hg!==void 0&&hg)==`function`?Gg:Object,typeof(Kg=Ih!==void 0&&Ih)==`function`?Kg:Object,typeof(qg=jg!==void 0&&jg)==`function`?qg:Object])],Yg);let Xg=!1;e.AST=Ot,e.AccessModifierType=Ee,e.AstModuleInfo=Et,e.CONCURRENCY=n.CONCURRENCY,e.COVERAGE_THRESHOLD=n.COVERAGE_THRESHOLD,e.CalculateCoverageOption=n.CalculateCoverageOption,e.DEFAULT_TYPE_KIND=Oe,e.ExportType=Te,e.GenerateTestsOutputType=n.GenerateTestsOutputType,e.GeneratedTestStructure=n.GeneratedTestStructure,e.LibraryName=De,e.RequestSource=n.RequestSource,Object.defineProperty(e,`TSAgent`,{enumerable:!0,get:function(){return Yg}}),e.TestFileName=n.TestFileName,e.TestFramework=n.TestFramework,e.TestStructureVariant=n.TestStructureVariant,e.TestSuffix=n.TestSuffix,e.WithTsMorphManager=Ge,e.createTSAgent=(e={})=>((Xg?n.inversify_default.rebindSync(n.GlobalConfigService):n.inversify_default.bind(n.GlobalConfigService)).toDynamicValue(()=>new n.GlobalConfigService(e)).inSingletonScope(),Xg=!0,n.inversify_default.get(Yg)),e.findLintConfigPath=be,e.getUnitTests=at,e.tsMorphManager=We}))();const DU={TSAgent:Symbol.for(`TSAgent`),CliOptions:Symbol.for(`CliOptions`),SCMHostService:Symbol.for(`SCMHostService`)};var OU=u(CR());let kU=function(e){return e.PR=`generate-for-pr`,e.COMMIT=`generate-for-commit`,e.PROJECT=`generate-for-project`,e.COVERAGE=`generate-coverage`,e.GATHER_STATS=`gather-stats`,e.REGRESSION_IMPACT=`generate-impact`,e.REGRESSION_CATALOG=`generate-catalog`,e}({});const AU=Object.freeze({status:`aborted`});function jU(e,t,n){function r(n,r){var i;Object.defineProperty(n,`_zod`,{value:n._zod??{},enumerable:!1}),(i=n._zod).traits??(i.traits=new Set),n._zod.traits.add(e),t(n,r);for(let e in o.prototype)e in n||Object.defineProperty(n,e,{value:o.prototype[e].bind(n)});n._zod.constr=o,n._zod.def=r}let i=n?.Parent??Object;class a extends i{}Object.defineProperty(a,`name`,{value:e});function o(e){var t;let i=n?.Parent?new a:this;r(i,e),(t=i._zod).deferred??(t.deferred=[]);for(let e of i._zod.deferred)e();return i}return Object.defineProperty(o,`init`,{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:t=>n?.Parent&&t instanceof n.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(o,`name`,{value:e}),o}var MU=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},NU=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};const PU={};function FU(e){return e&&Object.assign(PU,e),PU}function Mee(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function IU(e,t){return typeof t==`bigint`?t.toString():t}function LU(e){return{get value(){{let t=e();return Object.defineProperty(this,`value`,{value:t}),t}throw Error(`cached value already set`)}}}function RU(e){return e==null}function zU(e){let t=e.startsWith(`^`)?1:0,n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function BU(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=t.toString(),i=(r.split(`.`)[1]||``).length;if(i===0&&/\d?e-\d?/.test(r)){let e=r.match(/\d?e-(\d?)/);e?.[1]&&(i=Number.parseInt(e[1]))}let a=n>i?n:i;return Number.parseInt(e.toFixed(a).replace(`.`,``))%Number.parseInt(t.toFixed(a).replace(`.`,``))/10**a}const VU=Symbol(`evaluating`);function HU(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==VU)return r===void 0&&(r=VU,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function UU(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function WU(...e){let t={};for(let n of e){let e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function GU(e){return JSON.stringify(e)}const KU=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function qU(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const JU=LU(()=>{if(typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function YU(e){if(qU(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(qU(n)===!1||Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)===!1)}function XU(e){return YU(e)?{...e}:Array.isArray(e)?[...e]:e}const ZU=new Set([`string`,`number`,`symbol`]);function QU(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function $U(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function eW(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function Nee(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}const Pee={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function tW(e,t){let n=e._zod.def;return $U(e,WU(e._zod.def,{get shape(){let e={};for(let r in t){if(!(r in n.shape))throw Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return UU(this,`shape`,e),e},checks:[]}))}function nW(e,t){let n=e._zod.def;return $U(e,WU(e._zod.def,{get shape(){let r={...e._zod.def.shape};for(let e in t){if(!(e in n.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return UU(this,`shape`,r),r},checks:[]}))}function rW(e,t){if(!YU(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0)throw Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");return $U(e,WU(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return UU(this,`shape`,n),n},checks:[]}))}function iW(e,t){if(!YU(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return $U(e,{...e._zod.def,get shape(){let n={...e._zod.def.shape,...t};return UU(this,`shape`,n),n},checks:e._zod.def.checks})}function aW(e,t){return $U(e,WU(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return UU(this,`shape`,n),n},get catchall(){return t._zod.def.catchall},checks:[]}))}function oW(e,t,n){return $U(t,WU(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in r))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t])}else for(let t in r)i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t];return UU(this,`shape`,i),i},checks:[]}))}function sW(e,t,n){return $U(t,WU(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in i))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=new e({type:`nonoptional`,innerType:r[t]}))}else for(let t in r)i[t]=new e({type:`nonoptional`,innerType:r[t]});return UU(this,`shape`,i),i},checks:[]}))}function cW(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function lW(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function uW(e){return typeof e==`string`?e:e?.message}function dW(e,t,n){let r={...e,path:e.path??[]};return e.message||(r.message=uW(e.inst?._zod.def?.error?.(e))??uW(t?.error?.(e))??uW(n.customError?.(e))??uW(n.localeError?.(e))??`Invalid input`),delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function fW(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function pW(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}const mW=(e,t)=>{e.name=`$ZodError`,Object.defineProperty(e,`_zod`,{value:e._zod,enumerable:!1}),Object.defineProperty(e,`issues`,{value:t,enumerable:!1}),e.message=JSON.stringify(t,IU,2),Object.defineProperty(e,`toString`,{value:()=>e.message,enumerable:!1})},hW=jU(`$ZodError`,mW),gW=jU(`$ZodError`,mW,{Parent:Error});function _W(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function vW(e,t){let n=t||function(e){return e.message},r={_errors:[]},i=e=>{for(let t of e.issues)if(t.code===`invalid_union`&&t.errors.length)t.errors.map(e=>i({issues:e}));else if(t.code===`invalid_key`)i({issues:t.issues});else if(t.code===`invalid_element`)i({issues:t.issues});else if(t.path.length===0)r._errors.push(n(t));else{let e=r,i=0;for(;i<t.path.length;){let r=t.path[i];i===t.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(n(t))):e[r]=e[r]||{_errors:[]},e=e[r],i++}}};return i(e),r}const yW=e=>(t,n,r,i)=>{let a=r?Object.assign(r,{async:!1}):{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new MU;if(o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>dW(e,a,FU())));throw KU(t,i?.callee),t}return o.value},bW=e=>async(t,n,r,i)=>{let a=r?Object.assign(r,{async:!0}):{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>dW(e,a,FU())));throw KU(t,i?.callee),t}return o.value},xW=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new MU;return a.issues.length?{success:!1,error:new(e??hW)(a.issues.map(e=>dW(e,i,FU())))}:{success:!0,data:a.value}},SW=xW(gW),CW=e=>async(t,n,r)=>{let i=r?Object.assign(r,{async:!0}):{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>dW(e,i,FU())))}:{success:!0,data:a.value}},wW=CW(gW),TW=e=>(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return yW(e)(t,n,i)},EW=e=>(t,n,r)=>yW(e)(t,n,r),Fee=e=>async(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return bW(e)(t,n,i)},DW=e=>async(t,n,r)=>bW(e)(t,n,r),OW=e=>(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return xW(e)(t,n,i)},kW=e=>(t,n,r)=>xW(e)(t,n,r),AW=e=>async(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return CW(e)(t,n,i)},jW=e=>async(t,n,r)=>CW(e)(t,n,r),MW=/^[cC][^\s-]{8,}$/,NW=/^[0-9a-z]+$/,PW=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,FW=/^[0-9a-vA-V]{20}$/,Iee=/^[A-Za-z0-9]{27}$/,Lee=/^[a-zA-Z0-9_-]{21}$/,IW=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Ree=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,LW=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,RW=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function zW(){return RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)}const BW=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,VW=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,HW=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,UW=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,WW=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,GW=/^[A-Za-z0-9_-]*$/,KW=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,qW=/^\+(?:[0-9]){6,14}[0-9]$/,JW=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`,YW=RegExp(`^${JW}$`);function XW(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function ZW(e){return RegExp(`^${XW(e)}$`)}function QW(e){let t=XW({precision:e.precision}),n=[`Z`];e.local&&n.push(``),e.offset&&n.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let r=`${t}(?:${n.join(`|`)})`;return RegExp(`^${JW}T(?:${r})$`)}const $W=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},eG=/^-?\d+$/,tG=/^-?\d+(?:\.\d+)?/,nG=/^[^A-Z]*$/,rG=/^[^a-z]*$/,iG=jU(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),aG={number:`number`,bigint:`bigint`,object:`date`},oG=jU(`$ZodCheckLessThan`,(e,t)=>{iG.init(e,t);let n=aG[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??1/0;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:`too_big`,maximum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),sG=jU(`$ZodCheckGreaterThan`,(e,t)=>{iG.init(e,t);let n=aG[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??-1/0;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:`too_small`,minimum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),cG=jU(`$ZodCheckMultipleOf`,(e,t)=>{iG.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?n.value%t.value===BigInt(0):BU(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),lG=jU(`$ZodCheckNumberFormat`,(e,t)=>{iG.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=Pee[t.format];e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=a,n&&(r.pattern=eG)}),e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,continue:!t.abort});return}}s<i&&o.issues.push({origin:`number`,input:s,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inst:e})}}),uG=jU(`$ZodCheckMaxLength`,(e,t)=>{var n;iG.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!RU(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let r=n.value;if(r.length<=t.maximum)return;let i=fW(r);n.issues.push({origin:i,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),dG=jU(`$ZodCheckMinLength`,(e,t)=>{var n;iG.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!RU(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value;if(r.length>=t.minimum)return;let i=fW(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),fG=jU(`$ZodCheckLengthEquals`,(e,t)=>{var n;iG.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!RU(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{let r=n.value,i=r.length;if(i===t.length)return;let a=fW(r),o=i>t.length;n.issues.push({origin:a,...o?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),pG=jU(`$ZodCheckStringFormat`,(e,t)=>{var n,r;iG.init(e,t),e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??=new Set,n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),mG=jU(`$ZodCheckRegex`,(e,t)=>{pG.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),hG=jU(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=nG,pG.init(e,t)}),gG=jU(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=rG,pG.init(e,t)}),_G=jU(`$ZodCheckIncludes`,(e,t)=>{iG.init(e,t);let n=QU(t.includes),r=new RegExp(typeof t.position==`number`?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),vG=jU(`$ZodCheckStartsWith`,(e,t)=>{iG.init(e,t);let n=RegExp(`^${QU(t.prefix)}.*`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),yG=jU(`$ZodCheckEndsWith`,(e,t)=>{iG.init(e,t);let n=RegExp(`.*${QU(t.suffix)}$`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),bG=jU(`$ZodCheckOverwrite`,(e,t)=>{iG.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});var xG=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),--this.indent}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(`
|
|
32888
33040
|
`).filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>` `.repeat(this.indent*2)+e);for(let e of r)this.content.push(e)}compile(){let e=Function,t=this?.args,n=[...(this?.content??[``]).map(e=>` ${e}`)];return new e(...t,n.join(`
|
|
32889
33041
|
`))}};const zee={major:4,minor:1,patch:11},SG=jU(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=zee;let r=[...e._zod.def.checks??[]];e._zod.traits.has(`$ZodCheck`)&&r.unshift(e);for(let t of r)for(let n of t._zod.onattach)n(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,n)=>{let r=cW(e),i;for(let a of t){if(a._zod.def.when){if(!a._zod.def.when(e))continue}else if(r)continue;let t=e.issues.length,o=a._zod.check(e);if(o instanceof Promise&&n?.async===!1)throw new MU;if(i||o instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await o,e.issues.length!==t&&(r||=cW(e,t))});else{if(e.issues.length===t)continue;r||=cW(e,t)}}return i?i.then(()=>e):e},n=(n,i,a)=>{if(cW(n))return n.aborted=!0,n;let o=t(i,r,a);if(o instanceof Promise){if(a.async===!1)throw new MU;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(i,a)=>{if(a.skipChecks)return e._zod.parse(i,a);if(a.direction===`backward`){let t=e._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,i,a)):n(t,i,a)}let o=e._zod.parse(i,a);if(o instanceof Promise){if(a.async===!1)throw new MU;return o.then(e=>t(e,r,a))}return t(o,r,a)}}e[`~standard`]={validate:t=>{try{let n=SW(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch{return wW(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:`zod`,version:1}}),CG=jU(`$ZodString`,(e,t)=>{SG.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??$W(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),wG=jU(`$ZodStringFormat`,(e,t)=>{pG.init(e,t),CG.init(e,t)}),Bee=jU(`$ZodGUID`,(e,t)=>{t.pattern??=Ree,wG.init(e,t)}),Vee=jU(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=LW(e)}else t.pattern??=LW();wG.init(e,t)}),TG=jU(`$ZodEmail`,(e,t)=>{t.pattern??=RW,wG.init(e,t)}),EG=jU(`$ZodURL`,(e,t)=>{wG.init(e,t),e._zod.check=n=>{try{let r=n.value.trim(),i=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:KW.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(`:`)?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=i.href:n.value=r;return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),DG=jU(`$ZodEmoji`,(e,t)=>{t.pattern??=zW(),wG.init(e,t)}),Hee=jU(`$ZodNanoID`,(e,t)=>{t.pattern??=Lee,wG.init(e,t)}),Uee=jU(`$ZodCUID`,(e,t)=>{t.pattern??=MW,wG.init(e,t)}),OG=jU(`$ZodCUID2`,(e,t)=>{t.pattern??=NW,wG.init(e,t)}),kG=jU(`$ZodULID`,(e,t)=>{t.pattern??=PW,wG.init(e,t)}),AG=jU(`$ZodXID`,(e,t)=>{t.pattern??=FW,wG.init(e,t)}),Wee=jU(`$ZodKSUID`,(e,t)=>{t.pattern??=Iee,wG.init(e,t)}),jG=jU(`$ZodISODateTime`,(e,t)=>{t.pattern??=QW(t),wG.init(e,t)}),MG=jU(`$ZodISODate`,(e,t)=>{t.pattern??=YW,wG.init(e,t)}),NG=jU(`$ZodISOTime`,(e,t)=>{t.pattern??=ZW(t),wG.init(e,t)}),PG=jU(`$ZodISODuration`,(e,t)=>{t.pattern??=IW,wG.init(e,t)}),FG=jU(`$ZodIPv4`,(e,t)=>{t.pattern??=BW,wG.init(e,t),e._zod.onattach.push(e=>{let t=e._zod.bag;t.format=`ipv4`})}),IG=jU(`$ZodIPv6`,(e,t)=>{t.pattern??=VW,wG.init(e,t),e._zod.onattach.push(e=>{let t=e._zod.bag;t.format=`ipv6`}),e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}}),LG=jU(`$ZodCIDRv4`,(e,t)=>{t.pattern??=HW,wG.init(e,t)}),RG=jU(`$ZodCIDRv6`,(e,t)=>{t.pattern??=UW,wG.init(e,t),e._zod.check=n=>{let r=n.value.split(`/`);try{if(r.length!==2)throw Error();let[e,t]=r;if(!t)throw Error();let n=Number(t);if(`${n}`!==t||n<0||n>128)throw Error();new URL(`http://[${e}]`)}catch{n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}}});function zG(e){if(e===``)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const BG=jU(`$ZodBase64`,(e,t)=>{t.pattern??=WW,wG.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.contentEncoding=`base64`}),e._zod.check=n=>{zG(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}});function VG(e){if(!GW.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return zG(t.padEnd(Math.ceil(t.length/4)*4,`=`))}const HG=jU(`$ZodBase64URL`,(e,t)=>{t.pattern??=GW,wG.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.contentEncoding=`base64url`}),e._zod.check=n=>{VG(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),UG=jU(`$ZodE164`,(e,t)=>{t.pattern??=qW,wG.init(e,t)});function WG(e,t=null){try{let n=e.split(`.`);if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!(`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&(!(`alg`in i)||i.alg!==t))}catch{return!1}}const GG=jU(`$ZodJWT`,(e,t)=>{wG.init(e,t),e._zod.check=n=>{WG(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),KG=jU(`$ZodNumber`,(e,t)=>{SG.init(e,t),e._zod.pattern=e._zod.bag.pattern??tG,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:`Infinity`:void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),qG=jU(`$ZodNumber`,(e,t)=>{lG.init(e,t),KG.init(e,t)}),JG=jU(`$ZodUnknown`,(e,t)=>{SG.init(e,t),e._zod.parse=e=>e}),YG=jU(`$ZodNever`,(e,t)=>{SG.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function XG(e,t,n){e.issues.length&&t.issues.push(...lW(n,e.issues)),t.value[n]=e.value}const ZG=jU(`$ZodArray`,(e,t)=>{SG.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:`array`,code:`invalid_type`,input:i,inst:e}),n;n.value=Array(i.length);let a=[];for(let e=0;e<i.length;e++){let o=i[e],s=t.element._zod.run({value:o,issues:[]},r);s instanceof Promise?a.push(s.then(t=>XG(t,n,e))):XG(s,n,e)}return a.length?Promise.all(a).then(()=>n):n}});function QG(e,t,n,r){e.issues.length&&t.issues.push(...lW(n,e.issues)),e.value===void 0?n in r&&(t.value[n]=void 0):t.value[n]=e.value}function $G(e){let t=Object.keys(e.shape);for(let n of t)if(!e.shape?.[n]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${n}": expected a Zod schema`);let n=Nee(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function eK(e,t,n,r,i,a){let o=[],s=i.keySet,c=i.catchall._zod,l=c.def.type;for(let i of Object.keys(t)){if(s.has(i))continue;if(l===`never`){o.push(i);continue}let a=c.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>QG(e,n,i,t))):QG(a,n,i,t)}return o.length&&n.issues.push({code:`unrecognized_keys`,keys:o,input:t,inst:a}),e.length?Promise.all(e).then(()=>n):n}const tK=jU(`$ZodObject`,(e,t)=>{if(SG.init(e,t),!Object.getOwnPropertyDescriptor(t,`shape`)?.get){let e=t.shape;Object.defineProperty(t,`shape`,{get:()=>{let n={...e};return Object.defineProperty(t,`shape`,{value:n}),n}})}let n=LU(()=>$G(t));HU(e._zod,`propValues`,()=>{let e=t.shape,n={};for(let t in e){let r=e[t]._zod;if(r.values){n[t]??(n[t]=new Set);for(let e of r.values)n[t].add(e)}}return n});let r=qU,i=t.catchall,a;e._zod.parse=(t,o)=>{a??=n.value;let s=t.value;if(!r(s))return t.issues.push({expected:`object`,code:`invalid_type`,input:s,inst:e}),t;t.value={};let c=[],l=a.shape;for(let e of a.keys){let n=l[e]._zod.run({value:s[e],issues:[]},o);n instanceof Promise?c.push(n.then(n=>QG(n,t,e,s))):QG(n,t,e,s)}return i?eK(c,s,t,o,n.value,e):c.length?Promise.all(c).then(()=>t):t}}),nK=jU(`$ZodObjectJIT`,(e,t)=>{tK.init(e,t);let n=e._zod.parse,r=LU(()=>$G(t)),i=e=>{let t=new xG([`shape`,`payload`,`ctx`]),n=r.value,i=e=>{let t=GU(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write(`const input = payload.value;`);let a=Object.create(null),o=0;for(let e of n.keys)a[e]=`key_${o++}`;t.write(`const newResult = {};`);for(let e of n.keys){let n=a[e],r=GU(e);t.write(`const ${n} = ${i(e)};`),t.write(`
|
|
32890
33042
|
if (${n}.issues.length) {
|