@earlyai/cli 2.21.13 → 2.21.14
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 +59 -59
- 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:M,createCommand:ee,createArgument:N,createOption:te,CommanderError:P,InvalidArgumentError:F,InvalidOptionArgumentError:I,Command:L,Argument:ne,Option:R,Help:z}=u(s((e=>{let{Argument:t}=D(),{Command:n}=j(),{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.21.13`,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:M,createCommand:ee,createArgument:N,createOption:te,CommanderError:P,InvalidArgumentError:F,InvalidOptionArgumentError:I,Command:L,Argument:ne,Option:R,Help:z}=u(s((e=>{let{Argument:t}=D(),{Command:n}=j(),{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.21.14`,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,7 +115,7 @@ 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}}})),kI=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)})}}})),AI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BatchObservableResultImpl=e.ObservableResultImpl=void 0;let t=(Jd(),d(Kd)),n=CI(),r=bI();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)}}})),jI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ObservableRegistry=void 0;let t=(Jd(),d(Kd)),n=bI(),r=AI(),i=XF();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))}}})),MI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.SyncMetricStorage=void 0;let t=SI(),n=wI(),r=TI();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)}}})),NI=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})),PI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MeterSharedState=void 0;let t=yI(),n=xI(),r=XF(),i=EI(),a=OI(),o=kI(),s=jI(),c=MI(),l=NI();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}}})),FI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MeterProviderSharedState=void 0;let t=XF(),n=vI(),r=PI(),i=fI();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}}})),II=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}}})),LI=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)}}})),oee=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.InstrumentSelector=void 0;let t=LI();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}}})),RI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MeterSelector=void 0;let t=LI();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}}})),zI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.View=void 0;let t=LI(),n=NI(),r=oee(),i=RI(),a=fI();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}}})),BI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MeterProvider=void 0;let t=(Jd(),d(Kd)),n=bj(),r=FI(),i=II(),a=zI();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)))}}})),VI=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=JF();Object.defineProperty(e,`AggregationTemporality`,{enumerable:!0,get:function(){return t.AggregationTemporality}});var n=YF();Object.defineProperty(e,`DataPointType`,{enumerable:!0,get:function(){return n.DataPointType}}),Object.defineProperty(e,`InstrumentType`,{enumerable:!0,get:function(){return n.InstrumentType}});var r=mI();Object.defineProperty(e,`MetricReader`,{enumerable:!0,get:function(){return r.MetricReader}});var i=hI();Object.defineProperty(e,`PeriodicExportingMetricReader`,{enumerable:!0,get:function(){return i.PeriodicExportingMetricReader}});var a=gI();Object.defineProperty(e,`InMemoryMetricExporter`,{enumerable:!0,get:function(){return a.InMemoryMetricExporter}});var o=_I();Object.defineProperty(e,`ConsoleMetricExporter`,{enumerable:!0,get:function(){return o.ConsoleMetricExporter}});var s=BI();Object.defineProperty(e,`MeterProvider`,{enumerable:!0,get:function(){return s.MeterProvider}});var c=fI();Object.defineProperty(e,`AggregationType`,{enumerable:!0,get:function(){return c.AggregationType}});var l=NI();Object.defineProperty(e,`createAllowListAttributesProcessor`,{enumerable:!0,get:function(){return l.createAllowListAttributesProcessor}}),Object.defineProperty(e,`createDenyListAttributesProcessor`,{enumerable:!0,get:function(){return l.createDenyListAttributesProcessor}});var u=XF();Object.defineProperty(e,`TimeoutError`,{enumerable:!0,get:function(){return u.TimeoutError}})})),HI=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}})),UI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.StatsbeatMetrics=void 0;let t=(kM(),d(Gj)),n=EF(),r=(Jd(),d(Kd)),i=HI(),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}}})),WI=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=VI(),n=tL(),r=dN(),i=AM(),a=HI(),o=eL(),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}})),GI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AzureMonitorStatsbeatExporter=void 0;let t=(Jd(),d(Kd)),n=uN(),r=WI(),i=MM(),a=eL();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()}}})),KI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.NetworkStatsbeatMetrics=void 0;let t=(kM(),d(Gj)),n=(Jd(),d(Kd)),r=VI(),i=t.__importStar(Uj()),a=UI(),o=HI(),s=GI(),c=AM(),l=WI();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})),qI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.LongIntervalStatsbeatMetrics=void 0;let t=(kM(),d(Gj)),n=(Jd(),d(Kd)),r=uN(),i=VI(),a=t.__importStar(Uj()),o=UI(),s=HI(),c=GI(),l=WI();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})),JI=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}})),YI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BaseSender=void 0;let t=(Jd(),d(Kd)),n=gN(),r=uN(),i=KI(),a=qI(),o=HI(),s=JI(),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))}}})),XI=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=EF(),i=qF(),a=YI();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)}}}})),ZI=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=qF(),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}})),QI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),(kM(),d(Gj)).__exportStar(ZI(),e)})),$I=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=(kM(),d(Gj));t.__exportStar(fN(),e),t.__exportStar(gN(),e),t.__exportStar(XI(),e),t.__exportStar(QI(),e)})),eL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),(kM(),d(Gj)).__exportStar($I(),e)})),tL=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=eL(),a=qF(),o=uN(),s=AM(),c=iL();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]}})),nL=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`})),rL=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=nL(),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:}}})),iL=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=tL(),a=dN(),o=rL(),s=Uj(),c=nL(),l=qF(),u=JI();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]}})),aL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AzureMonitorTraceExporter=void 0;let t=(Jd(),d(Kd)),n=uN(),r=MM(),i=iL(),a=tL(),o=eL();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()}}})),oL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AzureMonitorMetricExporter=void 0;let t=(Jd(),d(Kd)),n=VI(),r=uN(),i=MM(),a=WI(),o=eL();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()}}})),sL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.logToEnvelope=c;let t=qF(),n=tL(),r=(PA(),d(NA)),i=dN(),a=(Jd(),d(Kd)),o=Uj(),s=iL();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}})),cL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AzureMonitorLogExporter=void 0;let t=(Jd(),d(Kd)),n=uN(),r=MM(),i=sL(),a=eL();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()}}})),lL=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=aL();Object.defineProperty(e,`AzureMonitorTraceExporter`,{enumerable:!0,get:function(){return r.AzureMonitorTraceExporter}});var i=oL();Object.defineProperty(e,`AzureMonitorMetricExporter`,{enumerable:!0,get:function(){return i.AzureMonitorMetricExporter}});var a=cL();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}})})),uL=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})),dL=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})),fL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.parseKeyPairsIntoRecord=e.parsePairKeyValue=e.getKeyPairs=e.serializeKeyPairs=void 0;let t=(Jd(),d(Kd)),n=dL();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})),pL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.W3CBaggagePropagator=void 0;let t=(Jd(),d(Kd)),n=uL(),r=dL(),i=fL();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]}}})),mL=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}}})),hL=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}})),gL=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}})),_L=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.globalErrorHandler=e.setGlobalErrorHandler=void 0;let t=(0,gL().loggingErrorHandler)();function n(e){t=e}e.setGlobalErrorHandler=n;function r(e){try{t(e)}catch{}}e.globalErrorHandler=r})),see=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})),vL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e._globalThis=void 0,e._globalThis=typeof globalThis==`object`?globalThis:global})),yL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.otperformance=void 0,e.otperformance=require(`perf_hooks`).performance})),bL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.VERSION=void 0,e.VERSION=`2.1.0`})),xL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ATTR_PROCESS_RUNTIME_NAME=void 0,e.ATTR_PROCESS_RUNTIME_NAME=`process.runtime.name`})),SL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.SDK_INFO=void 0;let t=bL(),n=(PA(),d(NA)),r=xL();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}})),CL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.unrefTimer=void 0;function t(e){e.unref()}e.unrefTimer=t})),wL=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=see();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=vL();Object.defineProperty(e,`_globalThis`,{enumerable:!0,get:function(){return n._globalThis}});var r=yL();Object.defineProperty(e,`otperformance`,{enumerable:!0,get:function(){return r.otperformance}});var i=SL();Object.defineProperty(e,`SDK_INFO`,{enumerable:!0,get:function(){return i.SDK_INFO}});var a=CL();Object.defineProperty(e,`unrefTimer`,{enumerable:!0,get:function(){return a.unrefTimer}})})),TL=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=wL();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}})})),EL=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=TL(),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})),DL=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||={})})),OL=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()}}})),kL=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})),AL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.TraceState=void 0;let t=kL();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}}})),cee=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=uL(),r=AL();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]}}})),jL=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})),lee=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)}})),ML=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.merge=void 0;let t=lee();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))}})),NL=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})),PL=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})),FL=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)}}})),IL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BindOnceFuture=void 0;let t=FL();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}}})),LL=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})),RL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e._export=void 0;let t=(Jd(),d(Kd)),n=uL();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})),zL=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=pL();Object.defineProperty(e,`W3CBaggagePropagator`,{enumerable:!0,get:function(){return t.W3CBaggagePropagator}});var n=mL();Object.defineProperty(e,`AnchoredClock`,{enumerable:!0,get:function(){return n.AnchoredClock}});var r=hL();Object.defineProperty(e,`isAttributeValue`,{enumerable:!0,get:function(){return r.isAttributeValue}}),Object.defineProperty(e,`sanitizeAttributes`,{enumerable:!0,get:function(){return r.sanitizeAttributes}});var i=_L();Object.defineProperty(e,`globalErrorHandler`,{enumerable:!0,get:function(){return i.globalErrorHandler}}),Object.defineProperty(e,`setGlobalErrorHandler`,{enumerable:!0,get:function(){return i.setGlobalErrorHandler}});var a=gL();Object.defineProperty(e,`loggingErrorHandler`,{enumerable:!0,get:function(){return a.loggingErrorHandler}});var o=EL();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=DL();Object.defineProperty(e,`ExportResultCode`,{enumerable:!0,get:function(){return s.ExportResultCode}});var c=fL();Object.defineProperty(e,`parseKeyPairsIntoRecord`,{enumerable:!0,get:function(){return c.parseKeyPairsIntoRecord}});var l=TL();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=OL();Object.defineProperty(e,`CompositePropagator`,{enumerable:!0,get:function(){return u.CompositePropagator}});var d=cee();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=jL();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=uL();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=AL();Object.defineProperty(e,`TraceState`,{enumerable:!0,get:function(){return m.TraceState}});var h=ML();Object.defineProperty(e,`merge`,{enumerable:!0,get:function(){return h.merge}});var g=NL();Object.defineProperty(e,`TimeoutError`,{enumerable:!0,get:function(){return g.TimeoutError}}),Object.defineProperty(e,`callWithTimeout`,{enumerable:!0,get:function(){return g.callWithTimeout}});var _=PL();Object.defineProperty(e,`isUrlIgnored`,{enumerable:!0,get:function(){return _.isUrlIgnored}}),Object.defineProperty(e,`urlMatches`,{enumerable:!0,get:function(){return _.urlMatches}});var v=IL();Object.defineProperty(e,`BindOnceFuture`,{enumerable:!0,get:function(){return v.BindOnceFuture}});var y=LL();Object.defineProperty(e,`diagLogLevelFromString`,{enumerable:!0,get:function(){return y.diagLogLevelFromString}}),e.internal={_export:RL()._export}})),BL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.defaultServiceName=void 0;function t(){return`unknown_service:${process.argv0}`}e.defaultServiceName=t})),VL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.defaultServiceName=void 0;var t=BL();Object.defineProperty(e,`defaultServiceName`,{enumerable:!0,get:function(){return t.defaultServiceName}})})),HL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.defaultServiceName=void 0;var t=VL();Object.defineProperty(e,`defaultServiceName`,{enumerable:!0,get:function(){return t.defaultServiceName}})})),UL=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})),WL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.defaultResource=e.emptyResource=e.resourceFromDetectedResource=e.resourceFromAttributes=void 0;let t=(Jd(),d(Kd)),n=zL(),r=(PA(),d(NA)),i=HL(),a=UL();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)}})),GL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.detectResources=void 0;let t=(Jd(),d(Kd)),n=WL();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)())})),KL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.envDetector=void 0;let t=(Jd(),d(Kd)),n=(PA(),d(NA)),r=zL();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)}}})),qL=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`})),JL=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})),YL=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}}})),XL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.hostDetector=void 0;let t=qL(),n=require(`os`),r=JL(),i=YL();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)()}}}}})),ZL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.osDetector=void 0;let t=qL(),n=require(`os`),r=YL();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)()}}}}})),QL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.processDetector=void 0;let t=(Jd(),d(Kd)),n=qL(),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}}}})),$L=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.serviceInstanceIdDetector=void 0;let t=qL(),n=require(`crypto`);e.serviceInstanceIdDetector=new class{detect(e){return{attributes:{[t.ATTR_SERVICE_INSTANCE_ID]:(0,n.randomUUID)()}}}}})),eR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.serviceInstanceIdDetector=e.processDetector=e.osDetector=e.hostDetector=void 0;var t=XL();Object.defineProperty(e,`hostDetector`,{enumerable:!0,get:function(){return t.hostDetector}});var n=ZL();Object.defineProperty(e,`osDetector`,{enumerable:!0,get:function(){return n.osDetector}});var r=QL();Object.defineProperty(e,`processDetector`,{enumerable:!0,get:function(){return r.processDetector}});var i=$L();Object.defineProperty(e,`serviceInstanceIdDetector`,{enumerable:!0,get:function(){return i.serviceInstanceIdDetector}})})),tR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.serviceInstanceIdDetector=e.processDetector=e.osDetector=e.hostDetector=void 0;var t=eR();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}})})),nR=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})),rR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.noopDetector=e.serviceInstanceIdDetector=e.processDetector=e.osDetector=e.hostDetector=e.envDetector=void 0;var t=KL();Object.defineProperty(e,`envDetector`,{enumerable:!0,get:function(){return t.envDetector}});var n=tR();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=nR();Object.defineProperty(e,`noopDetector`,{enumerable:!0,get:function(){return r.noopDetector}})})),iR=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=GL();Object.defineProperty(e,`detectResources`,{enumerable:!0,get:function(){return t.detectResources}});var n=rR();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=WL();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=HL();Object.defineProperty(e,`defaultServiceName`,{enumerable:!0,get:function(){return i.defaultServiceName}})})),aR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.LogRecordImpl=void 0;let t=(Jd(),d(Kd)),n=zL();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}}})),oR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.Logger=void 0;let t=(Jd(),d(Kd)),n=aR();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()}}})),sR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.reconfigureLimits=e.loadDefaultConfig=void 0;let t=zL();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})),cR=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()}}})),lR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MultiLogRecordProcessor=void 0;let t=zL();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()))}}})),uR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.LoggerProviderSharedState=void 0;let t=cR(),n=lR();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}}})),dR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.LoggerProvider=e.DEFAULT_LOGGER_NAME=void 0;let t=(Jd(),d(Kd)),n=Li(),r=iR(),i=zL(),a=oR(),o=sR(),s=uR();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()}}})),fR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ConsoleLogRecordExporter=void 0;let t=zL();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})}}})),uee=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.SimpleLogRecordProcessor=void 0;let t=zL();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()}}})),pR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.InMemoryLogRecordExporter=void 0;let t=zL();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=[]}}})),dee=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BatchLogRecordProcessorBase=void 0;let t=(Jd(),d(Kd)),n=zL();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)}}})),fee=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BatchLogRecordProcessor=void 0;let t=dee();e.BatchLogRecordProcessor=class extends t.BatchLogRecordProcessorBase{onShutdown(){}}})),mR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BatchLogRecordProcessor=void 0;var t=fee();Object.defineProperty(e,`BatchLogRecordProcessor`,{enumerable:!0,get:function(){return t.BatchLogRecordProcessor}})})),hR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BatchLogRecordProcessor=void 0;var t=mR();Object.defineProperty(e,`BatchLogRecordProcessor`,{enumerable:!0,get:function(){return t.BatchLogRecordProcessor}})})),gR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BatchLogRecordProcessor=e.InMemoryLogRecordExporter=e.SimpleLogRecordProcessor=e.ConsoleLogRecordExporter=e.NoopLogRecordProcessor=e.LoggerProvider=void 0;var t=dR();Object.defineProperty(e,`LoggerProvider`,{enumerable:!0,get:function(){return t.LoggerProvider}});var n=cR();Object.defineProperty(e,`NoopLogRecordProcessor`,{enumerable:!0,get:function(){return n.NoopLogRecordProcessor}});var r=fR();Object.defineProperty(e,`ConsoleLogRecordExporter`,{enumerable:!0,get:function(){return r.ConsoleLogRecordExporter}});var i=uee();Object.defineProperty(e,`SimpleLogRecordProcessor`,{enumerable:!0,get:function(){return i.SimpleLogRecordProcessor}});var a=pR();Object.defineProperty(e,`InMemoryLogRecordExporter`,{enumerable:!0,get:function(){return a.InMemoryLogRecordExporter}});var o=hR();Object.defineProperty(e,`BatchLogRecordProcessor`,{enumerable:!0,get:function(){return o.BatchLogRecordProcessor}})})),_R=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(lL()),p=t.__toESM(bj()),m=t.__toESM(gR()),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(),projectId:n.z.string().optional(),e2eCatalogIds:n.z.array(n.z.string()).optional(),e2eProjectIds:n.z.array(n.z.string()).optional(),jobId: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.133.0`;let j={VSCODE:`vscode`,GITHUB_ACTION:`github-action`,UNKNOWN:`unknown`},M=`$early_filename`,ee=`npx jest ${M} --no-coverage --silent --json --forceExit --maxWorkers=1`,N=`npx --no eslint ${M}`,te=`npx --no prettier ${M} --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:j.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:N,prettierCommand:te,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.jobId.label.projectId.e2eCatalogIds.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?j.VSCODE:j.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}}})),kI=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)})}}})),AI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BatchObservableResultImpl=e.ObservableResultImpl=void 0;let t=(Jd(),d(Kd)),n=CI(),r=bI();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)}}})),jI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ObservableRegistry=void 0;let t=(Jd(),d(Kd)),n=bI(),r=AI(),i=XF();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))}}})),MI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.SyncMetricStorage=void 0;let t=SI(),n=wI(),r=TI();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)}}})),NI=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})),PI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MeterSharedState=void 0;let t=yI(),n=xI(),r=XF(),i=EI(),a=OI(),o=kI(),s=jI(),c=MI(),l=NI();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}}})),FI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MeterProviderSharedState=void 0;let t=XF(),n=vI(),r=PI(),i=fI();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}}})),II=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}}})),LI=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)}}})),oee=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.InstrumentSelector=void 0;let t=LI();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}}})),RI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MeterSelector=void 0;let t=LI();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}}})),zI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.View=void 0;let t=LI(),n=NI(),r=oee(),i=RI(),a=fI();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}}})),BI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MeterProvider=void 0;let t=(Jd(),d(Kd)),n=bj(),r=FI(),i=II(),a=zI();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)))}}})),VI=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=JF();Object.defineProperty(e,`AggregationTemporality`,{enumerable:!0,get:function(){return t.AggregationTemporality}});var n=YF();Object.defineProperty(e,`DataPointType`,{enumerable:!0,get:function(){return n.DataPointType}}),Object.defineProperty(e,`InstrumentType`,{enumerable:!0,get:function(){return n.InstrumentType}});var r=mI();Object.defineProperty(e,`MetricReader`,{enumerable:!0,get:function(){return r.MetricReader}});var i=hI();Object.defineProperty(e,`PeriodicExportingMetricReader`,{enumerable:!0,get:function(){return i.PeriodicExportingMetricReader}});var a=gI();Object.defineProperty(e,`InMemoryMetricExporter`,{enumerable:!0,get:function(){return a.InMemoryMetricExporter}});var o=_I();Object.defineProperty(e,`ConsoleMetricExporter`,{enumerable:!0,get:function(){return o.ConsoleMetricExporter}});var s=BI();Object.defineProperty(e,`MeterProvider`,{enumerable:!0,get:function(){return s.MeterProvider}});var c=fI();Object.defineProperty(e,`AggregationType`,{enumerable:!0,get:function(){return c.AggregationType}});var l=NI();Object.defineProperty(e,`createAllowListAttributesProcessor`,{enumerable:!0,get:function(){return l.createAllowListAttributesProcessor}}),Object.defineProperty(e,`createDenyListAttributesProcessor`,{enumerable:!0,get:function(){return l.createDenyListAttributesProcessor}});var u=XF();Object.defineProperty(e,`TimeoutError`,{enumerable:!0,get:function(){return u.TimeoutError}})})),HI=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}})),UI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.StatsbeatMetrics=void 0;let t=(kM(),d(Gj)),n=EF(),r=(Jd(),d(Kd)),i=HI(),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}}})),WI=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=VI(),n=tL(),r=dN(),i=AM(),a=HI(),o=eL(),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}})),GI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AzureMonitorStatsbeatExporter=void 0;let t=(Jd(),d(Kd)),n=uN(),r=WI(),i=MM(),a=eL();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()}}})),KI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.NetworkStatsbeatMetrics=void 0;let t=(kM(),d(Gj)),n=(Jd(),d(Kd)),r=VI(),i=t.__importStar(Uj()),a=UI(),o=HI(),s=GI(),c=AM(),l=WI();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})),qI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.LongIntervalStatsbeatMetrics=void 0;let t=(kM(),d(Gj)),n=(Jd(),d(Kd)),r=uN(),i=VI(),a=t.__importStar(Uj()),o=UI(),s=HI(),c=GI(),l=WI();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})),JI=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}})),YI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BaseSender=void 0;let t=(Jd(),d(Kd)),n=gN(),r=uN(),i=KI(),a=qI(),o=HI(),s=JI(),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))}}})),XI=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=EF(),i=qF(),a=YI();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)}}}})),ZI=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=qF(),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}})),QI=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),(kM(),d(Gj)).__exportStar(ZI(),e)})),$I=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=(kM(),d(Gj));t.__exportStar(fN(),e),t.__exportStar(gN(),e),t.__exportStar(XI(),e),t.__exportStar(QI(),e)})),eL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),(kM(),d(Gj)).__exportStar($I(),e)})),tL=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=eL(),a=qF(),o=uN(),s=AM(),c=iL();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]}})),nL=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`})),rL=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=nL(),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:}}})),iL=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=tL(),a=dN(),o=rL(),s=Uj(),c=nL(),l=qF(),u=JI();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]}})),aL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AzureMonitorTraceExporter=void 0;let t=(Jd(),d(Kd)),n=uN(),r=MM(),i=iL(),a=tL(),o=eL();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()}}})),oL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AzureMonitorMetricExporter=void 0;let t=(Jd(),d(Kd)),n=VI(),r=uN(),i=MM(),a=WI(),o=eL();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()}}})),sL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.logToEnvelope=c;let t=qF(),n=tL(),r=(PA(),d(NA)),i=dN(),a=(Jd(),d(Kd)),o=Uj(),s=iL();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}})),cL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.AzureMonitorLogExporter=void 0;let t=(Jd(),d(Kd)),n=uN(),r=MM(),i=sL(),a=eL();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()}}})),lL=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=aL();Object.defineProperty(e,`AzureMonitorTraceExporter`,{enumerable:!0,get:function(){return r.AzureMonitorTraceExporter}});var i=oL();Object.defineProperty(e,`AzureMonitorMetricExporter`,{enumerable:!0,get:function(){return i.AzureMonitorMetricExporter}});var a=cL();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}})})),uL=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})),dL=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})),fL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.parseKeyPairsIntoRecord=e.parsePairKeyValue=e.getKeyPairs=e.serializeKeyPairs=void 0;let t=(Jd(),d(Kd)),n=dL();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})),pL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.W3CBaggagePropagator=void 0;let t=(Jd(),d(Kd)),n=uL(),r=dL(),i=fL();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]}}})),mL=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}}})),hL=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}})),gL=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}})),_L=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.globalErrorHandler=e.setGlobalErrorHandler=void 0;let t=(0,gL().loggingErrorHandler)();function n(e){t=e}e.setGlobalErrorHandler=n;function r(e){try{t(e)}catch{}}e.globalErrorHandler=r})),see=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})),vL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e._globalThis=void 0,e._globalThis=typeof globalThis==`object`?globalThis:global})),yL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.otperformance=void 0,e.otperformance=require(`perf_hooks`).performance})),bL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.VERSION=void 0,e.VERSION=`2.1.0`})),xL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ATTR_PROCESS_RUNTIME_NAME=void 0,e.ATTR_PROCESS_RUNTIME_NAME=`process.runtime.name`})),SL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.SDK_INFO=void 0;let t=bL(),n=(PA(),d(NA)),r=xL();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}})),CL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.unrefTimer=void 0;function t(e){e.unref()}e.unrefTimer=t})),wL=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=see();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=vL();Object.defineProperty(e,`_globalThis`,{enumerable:!0,get:function(){return n._globalThis}});var r=yL();Object.defineProperty(e,`otperformance`,{enumerable:!0,get:function(){return r.otperformance}});var i=SL();Object.defineProperty(e,`SDK_INFO`,{enumerable:!0,get:function(){return i.SDK_INFO}});var a=CL();Object.defineProperty(e,`unrefTimer`,{enumerable:!0,get:function(){return a.unrefTimer}})})),TL=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=wL();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}})})),EL=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=TL(),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})),DL=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||={})})),OL=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()}}})),kL=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})),AL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.TraceState=void 0;let t=kL();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}}})),cee=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=uL(),r=AL();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]}}})),jL=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})),lee=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)}})),ML=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.merge=void 0;let t=lee();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))}})),NL=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})),PL=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})),FL=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)}}})),IL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BindOnceFuture=void 0;let t=FL();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}}})),LL=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})),RL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e._export=void 0;let t=(Jd(),d(Kd)),n=uL();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})),zL=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=pL();Object.defineProperty(e,`W3CBaggagePropagator`,{enumerable:!0,get:function(){return t.W3CBaggagePropagator}});var n=mL();Object.defineProperty(e,`AnchoredClock`,{enumerable:!0,get:function(){return n.AnchoredClock}});var r=hL();Object.defineProperty(e,`isAttributeValue`,{enumerable:!0,get:function(){return r.isAttributeValue}}),Object.defineProperty(e,`sanitizeAttributes`,{enumerable:!0,get:function(){return r.sanitizeAttributes}});var i=_L();Object.defineProperty(e,`globalErrorHandler`,{enumerable:!0,get:function(){return i.globalErrorHandler}}),Object.defineProperty(e,`setGlobalErrorHandler`,{enumerable:!0,get:function(){return i.setGlobalErrorHandler}});var a=gL();Object.defineProperty(e,`loggingErrorHandler`,{enumerable:!0,get:function(){return a.loggingErrorHandler}});var o=EL();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=DL();Object.defineProperty(e,`ExportResultCode`,{enumerable:!0,get:function(){return s.ExportResultCode}});var c=fL();Object.defineProperty(e,`parseKeyPairsIntoRecord`,{enumerable:!0,get:function(){return c.parseKeyPairsIntoRecord}});var l=TL();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=OL();Object.defineProperty(e,`CompositePropagator`,{enumerable:!0,get:function(){return u.CompositePropagator}});var d=cee();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=jL();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=uL();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=AL();Object.defineProperty(e,`TraceState`,{enumerable:!0,get:function(){return m.TraceState}});var h=ML();Object.defineProperty(e,`merge`,{enumerable:!0,get:function(){return h.merge}});var g=NL();Object.defineProperty(e,`TimeoutError`,{enumerable:!0,get:function(){return g.TimeoutError}}),Object.defineProperty(e,`callWithTimeout`,{enumerable:!0,get:function(){return g.callWithTimeout}});var _=PL();Object.defineProperty(e,`isUrlIgnored`,{enumerable:!0,get:function(){return _.isUrlIgnored}}),Object.defineProperty(e,`urlMatches`,{enumerable:!0,get:function(){return _.urlMatches}});var v=IL();Object.defineProperty(e,`BindOnceFuture`,{enumerable:!0,get:function(){return v.BindOnceFuture}});var y=LL();Object.defineProperty(e,`diagLogLevelFromString`,{enumerable:!0,get:function(){return y.diagLogLevelFromString}}),e.internal={_export:RL()._export}})),BL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.defaultServiceName=void 0;function t(){return`unknown_service:${process.argv0}`}e.defaultServiceName=t})),VL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.defaultServiceName=void 0;var t=BL();Object.defineProperty(e,`defaultServiceName`,{enumerable:!0,get:function(){return t.defaultServiceName}})})),HL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.defaultServiceName=void 0;var t=VL();Object.defineProperty(e,`defaultServiceName`,{enumerable:!0,get:function(){return t.defaultServiceName}})})),UL=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})),WL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.defaultResource=e.emptyResource=e.resourceFromDetectedResource=e.resourceFromAttributes=void 0;let t=(Jd(),d(Kd)),n=zL(),r=(PA(),d(NA)),i=HL(),a=UL();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)}})),GL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.detectResources=void 0;let t=(Jd(),d(Kd)),n=WL();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)())})),KL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.envDetector=void 0;let t=(Jd(),d(Kd)),n=(PA(),d(NA)),r=zL();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)}}})),qL=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`})),JL=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})),YL=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}}})),XL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.hostDetector=void 0;let t=qL(),n=require(`os`),r=JL(),i=YL();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)()}}}}})),ZL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.osDetector=void 0;let t=qL(),n=require(`os`),r=YL();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)()}}}}})),QL=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.processDetector=void 0;let t=(Jd(),d(Kd)),n=qL(),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}}}})),$L=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.serviceInstanceIdDetector=void 0;let t=qL(),n=require(`crypto`);e.serviceInstanceIdDetector=new class{detect(e){return{attributes:{[t.ATTR_SERVICE_INSTANCE_ID]:(0,n.randomUUID)()}}}}})),eR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.serviceInstanceIdDetector=e.processDetector=e.osDetector=e.hostDetector=void 0;var t=XL();Object.defineProperty(e,`hostDetector`,{enumerable:!0,get:function(){return t.hostDetector}});var n=ZL();Object.defineProperty(e,`osDetector`,{enumerable:!0,get:function(){return n.osDetector}});var r=QL();Object.defineProperty(e,`processDetector`,{enumerable:!0,get:function(){return r.processDetector}});var i=$L();Object.defineProperty(e,`serviceInstanceIdDetector`,{enumerable:!0,get:function(){return i.serviceInstanceIdDetector}})})),tR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.serviceInstanceIdDetector=e.processDetector=e.osDetector=e.hostDetector=void 0;var t=eR();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}})})),nR=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})),rR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.noopDetector=e.serviceInstanceIdDetector=e.processDetector=e.osDetector=e.hostDetector=e.envDetector=void 0;var t=KL();Object.defineProperty(e,`envDetector`,{enumerable:!0,get:function(){return t.envDetector}});var n=tR();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=nR();Object.defineProperty(e,`noopDetector`,{enumerable:!0,get:function(){return r.noopDetector}})})),iR=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=GL();Object.defineProperty(e,`detectResources`,{enumerable:!0,get:function(){return t.detectResources}});var n=rR();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=WL();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=HL();Object.defineProperty(e,`defaultServiceName`,{enumerable:!0,get:function(){return i.defaultServiceName}})})),aR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.LogRecordImpl=void 0;let t=(Jd(),d(Kd)),n=zL();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}}})),oR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.Logger=void 0;let t=(Jd(),d(Kd)),n=aR();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()}}})),sR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.reconfigureLimits=e.loadDefaultConfig=void 0;let t=zL();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})),cR=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()}}})),lR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.MultiLogRecordProcessor=void 0;let t=zL();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()))}}})),uR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.LoggerProviderSharedState=void 0;let t=cR(),n=lR();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}}})),dR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.LoggerProvider=e.DEFAULT_LOGGER_NAME=void 0;let t=(Jd(),d(Kd)),n=Li(),r=iR(),i=zL(),a=oR(),o=sR(),s=uR();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()}}})),fR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ConsoleLogRecordExporter=void 0;let t=zL();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})}}})),uee=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.SimpleLogRecordProcessor=void 0;let t=zL();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()}}})),pR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.InMemoryLogRecordExporter=void 0;let t=zL();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=[]}}})),dee=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BatchLogRecordProcessorBase=void 0;let t=(Jd(),d(Kd)),n=zL();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)}}})),fee=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BatchLogRecordProcessor=void 0;let t=dee();e.BatchLogRecordProcessor=class extends t.BatchLogRecordProcessorBase{onShutdown(){}}})),mR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BatchLogRecordProcessor=void 0;var t=fee();Object.defineProperty(e,`BatchLogRecordProcessor`,{enumerable:!0,get:function(){return t.BatchLogRecordProcessor}})})),hR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BatchLogRecordProcessor=void 0;var t=mR();Object.defineProperty(e,`BatchLogRecordProcessor`,{enumerable:!0,get:function(){return t.BatchLogRecordProcessor}})})),gR=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.BatchLogRecordProcessor=e.InMemoryLogRecordExporter=e.SimpleLogRecordProcessor=e.ConsoleLogRecordExporter=e.NoopLogRecordProcessor=e.LoggerProvider=void 0;var t=dR();Object.defineProperty(e,`LoggerProvider`,{enumerable:!0,get:function(){return t.LoggerProvider}});var n=cR();Object.defineProperty(e,`NoopLogRecordProcessor`,{enumerable:!0,get:function(){return n.NoopLogRecordProcessor}});var r=fR();Object.defineProperty(e,`ConsoleLogRecordExporter`,{enumerable:!0,get:function(){return r.ConsoleLogRecordExporter}});var i=uee();Object.defineProperty(e,`SimpleLogRecordProcessor`,{enumerable:!0,get:function(){return i.SimpleLogRecordProcessor}});var a=pR();Object.defineProperty(e,`InMemoryLogRecordExporter`,{enumerable:!0,get:function(){return a.InMemoryLogRecordExporter}});var o=hR();Object.defineProperty(e,`BatchLogRecordProcessor`,{enumerable:!0,get:function(){return o.BatchLogRecordProcessor}})})),_R=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(lL()),p=t.__toESM(bj()),m=t.__toESM(gR()),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(),projectId:n.z.string().optional(),e2eCatalogIds:n.z.array(n.z.string()).optional(),e2eProjectIds:n.z.array(n.z.string()).optional(),jobId: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.134.0`;let j={VSCODE:`vscode`,GITHUB_ACTION:`github-action`,UNKNOWN:`unknown`},M=`$early_filename`,ee=`npx jest ${M} --no-coverage --silent --json --forceExit --maxWorkers=1`,N=`npx --no eslint ${M}`,te=`npx --no prettier ${M} --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:j.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:N,prettierCommand:te,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.jobId.label.projectId.e2eCatalogIds.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?j.VSCODE:j.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(`
|
|
@@ -152,21 +152,21 @@ var n=CR(),r=require(`path`);t.exports=function(e){var t=n();return e.charCodeAt
|
|
|
152
152
|
* Released under the MIT License.
|
|
153
153
|
*/
|
|
154
154
|
(function(n){e&&typeof e==`object`&&t!==void 0?t.exports=n():typeof define==`function`&&define.amd?define([],n):typeof window<`u`?window.isWindows=n():typeof global<`u`?global.isWindows=n():typeof self<`u`?self.isWindows=n():this.isWindows=n()})(function(){"use strict";return function(){return process&&(process.platform===`win32`||/^(msys|cygwin)$/.test(process.env.OSTYPE))}})})),DR=s(((e,t)=>{t.exports=a,a.sync=o;var n=require(`fs`);function r(e,t){var n=t.pathExt===void 0?process.env.PATHEXT:t.pathExt;if(!n||(n=n.split(`;`),n.indexOf(``)!==-1))return!0;for(var r=0;r<n.length;r++){var i=n[r].toLowerCase();if(i&&e.substr(-i.length).toLowerCase()===i)return!0}return!1}function i(e,t,n){return!e.isSymbolicLink()&&!e.isFile()?!1:r(t,n)}function a(e,t,r){n.stat(e,function(n,a){r(n,n?!1:i(a,e,t))})}function o(e,t){return i(n.statSync(e),e,t)}})),OR=s(((e,t)=>{t.exports=r,r.sync=i;var n=require(`fs`);function r(e,t,r){n.stat(e,function(e,n){r(e,e?!1:a(n,t))})}function i(e,t){return a(n.statSync(e),t)}function a(e,t){return e.isFile()&&o(e,t)}function o(e,t){var n=e.mode,r=e.uid,i=e.gid,a=t.uid===void 0?process.getuid&&process.getuid():t.uid,o=t.gid===void 0?process.getgid&&process.getgid():t.gid,s=64,c=8,l=1,u=s|c;return n&l||n&c&&i===o||n&s&&r===a||n&u&&a===0}})),kR=s(((e,t)=>{require(`fs`);var n=process.platform===`win32`||global.TESTING_WINDOWS?DR():OR();t.exports=r,r.sync=i;function r(e,t,i){if(typeof t==`function`&&(i=t,t={}),!i){if(typeof Promise!=`function`)throw TypeError(`callback not provided`);return new Promise(function(n,i){r(e,t||{},function(e,t){e?i(e):n(t)})})}n(e,t||{},function(e,n){e&&(e.code===`EACCES`||t&&t.ignoreErrors)&&(e=null,n=!1),i(e,n)})}function i(e,t){try{return n.sync(e,t||{})}catch(e){if(t&&t.ignoreErrors||e.code===`EACCES`)return!1;throw e}}})),AR=s(((e,t)=>{t.exports=c,c.sync=l;var n=process.platform===`win32`||process.env.OSTYPE===`cygwin`||process.env.OSTYPE===`msys`,r=require(`path`),i=n?`;`:`:`,a=kR();function o(e){var t=Error(`not found: `+e);return t.code=`ENOENT`,t}function s(e,t){var r=t.colon||i,a=t.path||process.env.PATH||``,o=[``];a=a.split(r);var s=``;return n&&(a.unshift(process.cwd()),s=t.pathExt||process.env.PATHEXT||`.EXE;.CMD;.BAT;.COM`,o=s.split(r),e.indexOf(`.`)!==-1&&o[0]!==``&&o.unshift(``)),(e.match(/\//)||n&&e.match(/\\/))&&(a=[``]),{env:a,ext:o,extExe:s}}function c(e,t,n){typeof t==`function`&&(n=t,t={});var i=s(e,t),c=i.env,l=i.ext,u=i.extExe,d=[];(function i(s,f){if(s===f)return t.all&&d.length?n(null,d):n(o(e));var p=c[s];p.charAt(0)===`"`&&p.slice(-1)===`"`&&(p=p.slice(1,-1));var m=r.join(p,e);!p&&/^\.[\\\/]/.test(e)&&(m=e.slice(0,2)+m),(function e(r,o){if(r===o)return i(s+1,f);var c=l[r];a(m+c,{pathExt:u},function(i,a){if(!i&&a)if(t.all)d.push(m+c);else return n(null,m+c);return e(r+1,o)})})(0,l.length)})(0,c.length)}function l(e,t){t||={};for(var n=s(e,t),i=n.env,c=n.ext,l=n.extExe,u=[],d=0,f=i.length;d<f;d++){var p=i[d];p.charAt(0)===`"`&&p.slice(-1)===`"`&&(p=p.slice(1,-1));var m=r.join(p,e);!p&&/^\.[\\\/]/.test(e)&&(m=e.slice(0,2)+m);for(var h=0,g=c.length;h<g;h++){var _=m+c[h],v;try{if(v=a.sync(_,{pathExt:l}),v)if(t.all)u.push(_);else return _}catch{}}}if(t.all&&u.length)return u;if(t.nothrow)return null;throw o(e)}})),jR=s(((e,t)=>{var n=require(`fs`),r=require(`path`),i=wR(),a=CR(),o=TR(),s;function c(){if(process.env.PREFIX)s=process.env.PREFIX;else{var e=a();if(e&&(s=d(r.resolve(e,`.npmrc`))),!s){var t=u();t&&(s=d(r.resolve(t,`..`,`..`,`npmrc`)),s&&=d(r.resolve(s,`etc`,`npmrc`))||s),s||l()}}if(s)return i(s)}function l(){ER()()?s=process.env.APPDATA?r.join(process.env.APPDATA,`npm`):r.dirname(process.execPath):(s=r.dirname(r.dirname(process.execPath)),process.env.DESTDIR&&(s=r.join(process.env.DESTDIR,s)))}function u(){try{return n.realpathSync(AR().sync(`npm`))}catch{}return null}function d(e){try{var t=n.readFileSync(e,`utf-8`),r=o.parse(t);if(r.prefix)return r.prefix}catch{}return null}Object.defineProperty(t,`exports`,{enumerable:!0,get:function(){return s||=c()}})})),MR=s(((e,t)=>{var n=require(`path`),r=jR(),i=ER(),a;function o(){return i()?n.resolve(r,`node_modules`):n.resolve(r,`lib/node_modules`)}Object.defineProperty(t,`exports`,{enumerable:!0,get:function(){return a||=o()}})})),NR=s(((e,t)=>{var n=require(`path`),r=wR(),i=MR();t.exports=function(e){return e.charAt(0)===`~`&&(e=r(e)),e.charAt(0)===`@`&&(e=n.join(i,e.slice(1))),e}})),PR=s(((e,t)=>{var n=require(`fs`),r=require(`path`);t.exports=function(e,t){return!e||typeof e!=`string`?null:n.existsSync(e)?r.resolve(e):(t||={},t.nocase===!0?i(e):null)};function i(e){e=r.resolve(e);var t=a(e);if(t===null)return null;if(t.path===e)return t.path;for(var n=e.toUpperCase(),i=t.files.length,o=-1;++o<i;){var s=r.resolve(t.path,t.files[o]);if(e===s||n===s)return s;var c=s.toUpperCase();if(e===c||n===c)return s}return null}function a(e){var t={path:e,files:[]};try{return t.files=n.readdirSync(e),t}catch{}try{return t.path=r.dirname(e),t.files=n.readdirSync(t.path),t}catch{}return null}})),FR=s((e=>{e.isInteger=e=>typeof e==`number`?Number.isInteger(e):typeof e==`string`&&e.trim()!==``?Number.isInteger(Number(e)):!1,e.find=(e,t)=>e.nodes.find(e=>e.type===t),e.exceedsLimit=(t,n,r=1,i)=>i===!1||!e.isInteger(t)||!e.isInteger(n)?!1:(Number(n)-Number(t))/Number(r)>=i,e.escapeNode=(e,t=0,n)=>{let r=e.nodes[t];r&&(n&&r.type===n||r.type===`open`||r.type===`close`)&&r.escaped!==!0&&(r.value=`\\`+r.value,r.escaped=!0)},e.encloseBrace=e=>e.type===`brace`?e.commas>>0+e.ranges>>0?!1:(e.invalid=!0,!0):!1,e.isInvalidBrace=e=>e.type===`brace`?e.invalid===!0||e.dollar?!0:!(e.commas>>0+e.ranges>>0)||e.open!==!0||e.close!==!0?(e.invalid=!0,!0):!1:!1,e.isOpenOrClose=e=>e.type===`open`||e.type===`close`?!0:e.open===!0||e.close===!0,e.reduce=e=>e.reduce((e,t)=>(t.type===`text`&&e.push(t.value),t.type===`range`&&(t.type=`text`),e),[]),e.flatten=(...e)=>{let t=[],n=e=>{for(let r=0;r<e.length;r++){let i=e[r];if(Array.isArray(i)){n(i);continue}i!==void 0&&t.push(i)}return t};return n(e),t}})),IR=s(((e,t)=>{let n=FR();t.exports=(e,t={})=>{let r=(e,i={})=>{let a=t.escapeInvalid&&n.isInvalidBrace(i),o=e.invalid===!0&&t.escapeInvalid===!0,s=``;if(e.value)return(a||o)&&n.isOpenOrClose(e)?`\\`+e.value:e.value;if(e.value)return e.value;if(e.nodes)for(let t of e.nodes)s+=r(t);return s};return r(e)}})),LR=s(((e,t)=>{t.exports=function(e){return typeof e==`number`?e-e===0:typeof e==`string`&&e.trim()!==``?Number.isFinite?Number.isFinite(+e):isFinite(+e):!1}})),RR=s(((e,t)=>{let n=LR(),r=(e,t,a)=>{if(n(e)===!1)throw TypeError(`toRegexRange: expected the first argument to be a number`);if(t===void 0||e===t)return String(e);if(n(t)===!1)throw TypeError(`toRegexRange: expected the second argument to be a number.`);let o={relaxZeros:!0,...a};typeof o.strictZeros==`boolean`&&(o.relaxZeros=o.strictZeros===!1);let c=String(o.relaxZeros),l=String(o.shorthand),u=String(o.capture),d=String(o.wrap),f=e+`:`+t+`=`+c+l+u+d;if(r.cache.hasOwnProperty(f))return r.cache[f].result;let p=Math.min(e,t),m=Math.max(e,t);if(Math.abs(p-m)===1){let n=e+`|`+t;return o.capture?`(${n})`:o.wrap===!1?n:`(?:${n})`}let h=g(e)||g(t),_={min:e,max:t,a:p,b:m},v=[],y=[];return h&&(_.isPadded=h,_.maxLen=String(_.max).length),p<0&&(y=s(m<0?Math.abs(m):1,Math.abs(p),_,o),p=_.a=0),m>=0&&(v=s(p,m,_,o)),_.negatives=y,_.positives=v,_.result=i(y,v,o),o.capture===!0?_.result=`(${_.result})`:o.wrap!==!1&&v.length+y.length>1&&(_.result=`(?:${_.result})`),r.cache[f]=_,_.result};function i(e,t,n){let r=c(e,t,`-`,!1,n)||[],i=c(t,e,``,!1,n)||[],a=c(e,t,`-?`,!0,n)||[];return r.concat(a).concat(i).join(`|`)}function a(e,t){let n=1,r=1,i=f(e,n),a=new Set([t]);for(;e<=i&&i<=t;)a.add(i),n+=1,i=f(e,n);for(i=p(t+1,r)-1;e<i&&i<=t;)a.add(i),r+=1,i=p(t+1,r)-1;return a=[...a],a.sort(u),a}function o(e,t,n){if(e===t)return{pattern:e,count:[],digits:0};let r=l(e,t),i=r.length,a=``,o=0;for(let e=0;e<i;e++){let[t,i]=r[e];t===i?a+=t:t!==`0`||i!==`9`?a+=h(t,i,n):o++}return o&&(a+=n.shorthand===!0?`\\d`:`[0-9]`),{pattern:a,count:[o],digits:i}}function s(e,t,n,r){let i=a(e,t),s=[],c=e,l;for(let e=0;e<i.length;e++){let t=i[e],a=o(String(c),String(t),r),u=``;if(!n.isPadded&&l&&l.pattern===a.pattern){l.count.length>1&&l.count.pop(),l.count.push(a.count[0]),l.string=l.pattern+m(l.count),c=t+1;continue}n.isPadded&&(u=_(t,n,r)),a.string=u+a.pattern+m(a.count),s.push(a),c=t+1,l=a}return s}function c(e,t,n,r,i){let a=[];for(let i of e){let{string:e}=i;!r&&!d(t,`string`,e)&&a.push(n+e),r&&d(t,`string`,e)&&a.push(n+e)}return a}function l(e,t){let n=[];for(let r=0;r<e.length;r++)n.push([e[r],t[r]]);return n}function u(e,t){return e>t?1:t>e?-1:0}function d(e,t,n){return e.some(e=>e[t]===n)}function f(e,t){return Number(String(e).slice(0,-t)+`9`.repeat(t))}function p(e,t){return e-e%10**t}function m(e){let[t=0,n=``]=e;return n||t>1?`{${t+(n?`,`+n:``)}}`:``}function h(e,t,n){return`[${e}${t-e===1?``:`-`}${t}]`}function g(e){return/^-?(0+)\d/.test(e)}function _(e,t,n){if(!t.isPadded)return e;let r=Math.abs(t.maxLen-String(e).length),i=n.relaxZeros!==!1;switch(r){case 0:return``;case 1:return i?`0?`:`0`;case 2:return i?`0{0,2}`:`00`;default:return i?`0{0,${r}}`:`0{${r}}`}}r.cache={},r.clearCache=()=>r.cache={},t.exports=r})),zR=s(((e,t)=>{let n=require(`util`),r=RR(),i=e=>typeof e==`object`&&!!e&&!Array.isArray(e),a=e=>t=>e===!0?Number(t):String(t),o=e=>typeof e==`number`||typeof e==`string`&&e!==``,s=e=>Number.isInteger(+e),c=e=>{let t=`${e}`,n=-1;if(t[0]===`-`&&(t=t.slice(1)),t===`0`)return!1;for(;t[++n]===`0`;);return n>0},l=(e,t,n)=>typeof e==`string`||typeof t==`string`?!0:n.stringify===!0,u=(e,t,n)=>{if(t>0){let n=e[0]===`-`?`-`:``;n&&(e=e.slice(1)),e=n+e.padStart(n?t-1:t,`0`)}return n===!1?String(e):e},d=(e,t)=>{let n=e[0]===`-`?`-`:``;for(n&&(e=e.slice(1),t--);e.length<t;)e=`0`+e;return n?`-`+e:e},f=(e,t,n)=>{e.negatives.sort((e,t)=>e<t?-1:e>t?1:0),e.positives.sort((e,t)=>e<t?-1:e>t?1:0);let r=t.capture?``:`?:`,i=``,a=``,o;return e.positives.length&&(i=e.positives.map(e=>d(String(e),n)).join(`|`)),e.negatives.length&&(a=`-(${r}${e.negatives.map(e=>d(String(e),n)).join(`|`)})`),o=i&&a?`${i}|${a}`:i||a,t.wrap?`(${r}${o})`:o},p=(e,t,n,i)=>{if(n)return r(e,t,{wrap:!1,...i});let a=String.fromCharCode(e);return e===t?a:`[${a}-${String.fromCharCode(t)}]`},m=(e,t,n)=>{if(Array.isArray(e)){let t=n.wrap===!0,r=n.capture?``:`?:`;return t?`(${r}${e.join(`|`)})`:e.join(`|`)}return r(e,t,n)},h=(...e)=>RangeError(`Invalid range arguments: `+n.inspect(...e)),g=(e,t,n)=>{if(n.strictRanges===!0)throw h([e,t]);return[]},_=(e,t)=>{if(t.strictRanges===!0)throw TypeError(`Expected step "${e}" to be a number`);return[]},v=(e,t,n=1,r={})=>{let i=Number(e),o=Number(t);if(!Number.isInteger(i)||!Number.isInteger(o)){if(r.strictRanges===!0)throw h([e,t]);return[]}i===0&&(i=0),o===0&&(o=0);let s=i>o,g=String(e),_=String(t),v=String(n);n=Math.max(Math.abs(n),1);let y=c(g)||c(_)||c(v),b=y?Math.max(g.length,_.length,v.length):0,x=y===!1&&l(e,t,r)===!1,S=r.transform||a(x);if(r.toRegex&&n===1)return p(d(e,b),d(t,b),!0,r);let C={negatives:[],positives:[]},w=e=>C[e<0?`negatives`:`positives`].push(Math.abs(e)),T=[],E=0;for(;s?i>=o:i<=o;)r.toRegex===!0&&n>1?w(i):T.push(u(S(i,E),b,x)),i=s?i-n:i+n,E++;return r.toRegex===!0?n>1?f(C,r,b):m(T,null,{wrap:!1,...r}):T},y=(e,t,n=1,r={})=>{if(!s(e)&&e.length>1||!s(t)&&t.length>1)return g(e,t,r);let i=r.transform||(e=>String.fromCharCode(e)),a=`${e}`.charCodeAt(0),o=`${t}`.charCodeAt(0),c=a>o,l=Math.min(a,o),u=Math.max(a,o);if(r.toRegex&&n===1)return p(l,u,!1,r);let d=[],f=0;for(;c?a>=o:a<=o;)d.push(i(a,f)),a=c?a-n:a+n,f++;return r.toRegex===!0?m(d,null,{wrap:!1,options:r}):d},b=(e,t,n,r={})=>{if(t==null&&o(e))return[e];if(!o(e)||!o(t))return g(e,t,r);if(typeof n==`function`)return b(e,t,1,{transform:n});if(i(n))return b(e,t,0,n);let a={...r};return a.capture===!0&&(a.wrap=!0),n=n||a.step||1,s(n)?s(e)&&s(t)?v(e,t,n,a):y(e,t,Math.max(Math.abs(n),1),a):n!=null&&!i(n)?_(n,a):b(e,t,1,n)};t.exports=b})),pee=s(((e,t)=>{let n=zR(),r=FR();t.exports=(e,t={})=>{let i=(e,a={})=>{let o=r.isInvalidBrace(a),s=e.invalid===!0&&t.escapeInvalid===!0,c=o===!0||s===!0,l=t.escapeInvalid===!0?`\\`:``,u=``;if(e.isOpen===!0)return l+e.value;if(e.isClose===!0)return console.log(`node.isClose`,l,e.value),l+e.value;if(e.type===`open`)return c?l+e.value:`(`;if(e.type===`close`)return c?l+e.value:`)`;if(e.type===`comma`)return e.prev.type===`comma`?``:c?e.value:`|`;if(e.value)return e.value;if(e.nodes&&e.ranges>0){let i=r.reduce(e.nodes),a=n(...i,{...t,wrap:!1,toRegex:!0,strictZeros:!0});if(a.length!==0)return i.length>1&&a.length>1?`(${a})`:a}if(e.nodes)for(let t of e.nodes)u+=i(t,e);return u};return i(e)}})),mee=s(((e,t)=>{let n=zR(),r=IR(),i=FR(),a=(e=``,t=``,n=!1)=>{let r=[];if(e=[].concat(e),t=[].concat(t),!t.length)return e;if(!e.length)return n?i.flatten(t).map(e=>`{${e}}`):t;for(let i of e)if(Array.isArray(i))for(let e of i)r.push(a(e,t,n));else for(let e of t)n===!0&&typeof e==`string`&&(e=`{${e}}`),r.push(Array.isArray(e)?a(i,e,n):i+e);return i.flatten(r)};t.exports=(e,t={})=>{let o=t.rangeLimit===void 0?1e3:t.rangeLimit,s=(e,c={})=>{e.queue=[];let l=c,u=c.queue;for(;l.type!==`brace`&&l.type!==`root`&&l.parent;)l=l.parent,u=l.queue;if(e.invalid||e.dollar){u.push(a(u.pop(),r(e,t)));return}if(e.type===`brace`&&e.invalid!==!0&&e.nodes.length===2){u.push(a(u.pop(),[`{}`]));return}if(e.nodes&&e.ranges>0){let s=i.reduce(e.nodes);if(i.exceedsLimit(...s,t.step,o))throw RangeError(`expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.`);let c=n(...s,t);c.length===0&&(c=r(e,t)),u.push(a(u.pop(),c)),e.nodes=[];return}let d=i.encloseBrace(e),f=e.queue,p=e;for(;p.type!==`brace`&&p.type!==`root`&&p.parent;)p=p.parent,f=p.queue;for(let t=0;t<e.nodes.length;t++){let n=e.nodes[t];if(n.type===`comma`&&e.type===`brace`){t===1&&f.push(``),f.push(``);continue}if(n.type===`close`){u.push(a(u.pop(),f,d));continue}if(n.value&&n.type!==`open`){f.push(a(f.pop(),n.value));continue}n.nodes&&s(n,e)}return f};return i.flatten(s(e))}})),BR=s(((e,t)=>{t.exports={MAX_LENGTH:1e4,CHAR_0:`0`,CHAR_9:`9`,CHAR_UPPERCASE_A:`A`,CHAR_LOWERCASE_A:`a`,CHAR_UPPERCASE_Z:`Z`,CHAR_LOWERCASE_Z:`z`,CHAR_LEFT_PARENTHESES:`(`,CHAR_RIGHT_PARENTHESES:`)`,CHAR_ASTERISK:`*`,CHAR_AMPERSAND:`&`,CHAR_AT:`@`,CHAR_BACKSLASH:`\\`,CHAR_BACKTICK:"`",CHAR_CARRIAGE_RETURN:`\r`,CHAR_CIRCUMFLEX_ACCENT:`^`,CHAR_COLON:`:`,CHAR_COMMA:`,`,CHAR_DOLLAR:`$`,CHAR_DOT:`.`,CHAR_DOUBLE_QUOTE:`"`,CHAR_EQUAL:`=`,CHAR_EXCLAMATION_MARK:`!`,CHAR_FORM_FEED:`\f`,CHAR_FORWARD_SLASH:`/`,CHAR_HASH:`#`,CHAR_HYPHEN_MINUS:`-`,CHAR_LEFT_ANGLE_BRACKET:`<`,CHAR_LEFT_CURLY_BRACE:`{`,CHAR_LEFT_SQUARE_BRACKET:`[`,CHAR_LINE_FEED:`
|
|
155
|
-
`,CHAR_NO_BREAK_SPACE:`\xA0`,CHAR_PERCENT:`%`,CHAR_PLUS:`+`,CHAR_QUESTION_MARK:`?`,CHAR_RIGHT_ANGLE_BRACKET:`>`,CHAR_RIGHT_CURLY_BRACE:`}`,CHAR_RIGHT_SQUARE_BRACKET:`]`,CHAR_SEMICOLON:`;`,CHAR_SINGLE_QUOTE:`'`,CHAR_SPACE:` `,CHAR_TAB:` `,CHAR_UNDERSCORE:`_`,CHAR_VERTICAL_LINE:`|`,CHAR_ZERO_WIDTH_NOBREAK_SPACE:``}})),VR=s(((e,t)=>{let n=IR(),{MAX_LENGTH:r,CHAR_BACKSLASH:i,CHAR_BACKTICK:a,CHAR_COMMA:o,CHAR_DOT:s,CHAR_LEFT_PARENTHESES:c,CHAR_RIGHT_PARENTHESES:l,CHAR_LEFT_CURLY_BRACE:u,CHAR_RIGHT_CURLY_BRACE:d,CHAR_LEFT_SQUARE_BRACKET:f,CHAR_RIGHT_SQUARE_BRACKET:p,CHAR_DOUBLE_QUOTE:m,CHAR_SINGLE_QUOTE:h,CHAR_NO_BREAK_SPACE:g,CHAR_ZERO_WIDTH_NOBREAK_SPACE:_}=BR();t.exports=(e,t={})=>{if(typeof e!=`string`)throw TypeError(`Expected a string`);let v=t||{},y=typeof v.maxLength==`number`?Math.min(r,v.maxLength):r;if(e.length>y)throw SyntaxError(`Input length (${e.length}), exceeds max characters (${y})`);let b={type:`root`,input:e,nodes:[]},x=[b],S=b,C=b,w=0,T=e.length,E=0,D=0,O,k=()=>e[E++],A=e=>{if(e.type===`text`&&C.type===`dot`&&(C.type=`text`),C&&C.type===`text`&&e.type===`text`){C.value+=e.value;return}return S.nodes.push(e),e.parent=S,e.prev=C,C=e,e};for(A({type:`bos`});E<T;)if(S=x[x.length-1],O=k(),!(O===_||O===g)){if(O===i){A({type:`text`,value:(t.keepEscaping?O:``)+k()});continue}if(O===p){A({type:`text`,value:`\\`+O});continue}if(O===f){w++;let e;for(;E<T&&(e=k());){if(O+=e,e===f){w++;continue}if(e===i){O+=k();continue}if(e===p&&(w--,w===0))break}A({type:`text`,value:O});continue}if(O===c){S=A({type:`paren`,nodes:[]}),x.push(S),A({type:`text`,value:O});continue}if(O===l){if(S.type!==`paren`){A({type:`text`,value:O});continue}S=x.pop(),A({type:`text`,value:O}),S=x[x.length-1];continue}if(O===m||O===h||O===a){let e=O,n;for(t.keepQuotes!==!0&&(O=``);E<T&&(n=k());){if(n===i){O+=n+k();continue}if(n===e){t.keepQuotes===!0&&(O+=n);break}O+=n}A({type:`text`,value:O});continue}if(O===u){D++,S=A({type:`brace`,open:!0,close:!1,dollar:C.value&&C.value.slice(-1)===`$`||S.dollar===!0,depth:D,commas:0,ranges:0,nodes:[]}),x.push(S),A({type:`open`,value:O});continue}if(O===d){if(S.type!==`brace`){A({type:`text`,value:O});continue}S=x.pop(),S.close=!0,A({type:`close`,value:O}),D--,S=x[x.length-1];continue}if(O===o&&D>0){if(S.ranges>0){S.ranges=0;let e=S.nodes.shift();S.nodes=[e,{type:`text`,value:n(S)}]}A({type:`comma`,value:O}),S.commas++;continue}if(O===s&&D>0&&S.commas===0){let e=S.nodes;if(D===0||e.length===0){A({type:`text`,value:O});continue}if(C.type===`dot`){if(S.range=[],C.value+=O,C.type=`range`,S.nodes.length!==3&&S.nodes.length!==5){S.invalid=!0,S.ranges=0,C.type=`text`;continue}S.ranges++,S.args=[];continue}if(C.type===`range`){e.pop();let t=e[e.length-1];t.value+=C.value+O,C=t,S.ranges--;continue}A({type:`dot`,value:O});continue}A({type:`text`,value:O})}do if(S=x.pop(),S.type!==`root`){S.nodes.forEach(e=>{e.nodes||(e.type===`open`&&(e.isOpen=!0),e.type===`close`&&(e.isClose=!0),e.nodes||(e.type=`text`),e.invalid=!0)});let e=x[x.length-1],t=e.nodes.indexOf(S);e.nodes.splice(t,1,...S.nodes)}while(x.length>0);return A({type:`eos`}),b}})),HR=s(((e,t)=>{let n=IR(),r=pee(),i=mee(),a=VR(),o=(e,t={})=>{let n=[];if(Array.isArray(e))for(let r of e){let e=o.create(r,t);Array.isArray(e)?n.push(...e):n.push(e)}else n=[].concat(o.create(e,t));return t&&t.expand===!0&&t.nodupes===!0&&(n=[...new Set(n)]),n};o.parse=(e,t={})=>a(e,t),o.stringify=(e,t={})=>n(typeof e==`string`?o.parse(e,t):e,t),o.compile=(e,t={})=>(typeof e==`string`&&(e=o.parse(e,t)),r(e,t)),o.expand=(e,t={})=>{typeof e==`string`&&(e=o.parse(e,t));let n=i(e,t);return t.noempty===!0&&(n=n.filter(Boolean)),t.nodupes===!0&&(n=[...new Set(n)]),n},o.create=(e,t={})=>e===``||e.length<3?[e]:t.expand===!0?o.expand(e,t):o.compile(e,t),t.exports=o})),UR=s(((e,t)=>{let n=require(`path`),r=`[^\\\\/]`,i=`[^/]`,a=`(?:\\/|$)`,o=`(?:^|\\/)`,s=`\\.{1,2}${a}`,c={DOT_LITERAL:`\\.`,PLUS_LITERAL:`\\+`,QMARK_LITERAL:`\\?`,SLASH_LITERAL:`\\/`,ONE_CHAR:`(?=.)`,QMARK:i,END_ANCHOR:a,DOTS_SLASH:s,NO_DOT:`(?!\\.)`,NO_DOTS:`(?!${o}${s})`,NO_DOT_SLASH:`(?!\\.{0,1}${a})`,NO_DOTS_SLASH:`(?!${s})`,QMARK_NO_DOT:`[^.\\/]`,STAR:`${i}*?`,START_ANCHOR:o},l={...c,SLASH_LITERAL:`[\\\\/]`,QMARK:r,STAR:`${r}*?`,DOTS_SLASH:`\\.{1,2}(?:[\\\\/]|$)`,NO_DOT:`(?!\\.)`,NO_DOTS:`(?!(?:^|[\\\\/])\\.{1,2}(?:[\\\\/]|$))`,NO_DOT_SLASH:`(?!\\.{0,1}(?:[\\\\/]|$))`,NO_DOTS_SLASH:`(?!\\.{1,2}(?:[\\\\/]|$))`,QMARK_NO_DOT:`[^.\\\\/]`,START_ANCHOR:`(?:^|[\\\\/])`,END_ANCHOR:`(?:[\\\\/]|$)`};t.exports={MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:{alnum:`a-zA-Z0-9`,alpha:`a-zA-Z`,ascii:`\\x00-\\x7F`,blank:` \\t`,cntrl:`\\x00-\\x1F\\x7F`,digit:`0-9`,graph:`\\x21-\\x7E`,lower:`a-z`,print:`\\x20-\\x7E `,punct:`\\-!"#$%&'()\\*+,./:;<=>?@[\\]^_\`{|}~`,space:` \\t\\r\\n\\v\\f`,upper:`A-Z`,word:`A-Za-z0-9_`,xdigit:`A-Fa-f0-9`},REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{"***":`*`,"**/**":`**`,"**/**/**":`**`},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,SEP:n.sep,extglobChars(e){return{"!":{type:`negate`,open:`(?:(?!(?:`,close:`))${e.STAR})`},"?":{type:`qmark`,open:`(?:`,close:`)?`},"+":{type:`plus`,open:`(?:`,close:`)+`},"*":{type:`star`,open:`(?:`,close:`)*`},"@":{type:`at`,open:`(?:`,close:`)`}}},globChars(e){return e===!0?l:c}}})),WR=s((e=>{let t=require(`path`),n=process.platform===`win32`,{REGEX_BACKSLASH:r,REGEX_REMOVE_BACKSLASH:i,REGEX_SPECIAL_CHARS:a,REGEX_SPECIAL_CHARS_GLOBAL:o}=UR();e.isObject=e=>typeof e==`object`&&!!e&&!Array.isArray(e),e.hasRegexChars=e=>a.test(e),e.isRegexChar=t=>t.length===1&&e.hasRegexChars(t),e.escapeRegex=e=>e.replace(o,`\\$1`),e.toPosixSlashes=e=>e.replace(r,`/`),e.removeBackslashes=e=>e.replace(i,e=>e===`\\`?``:e),e.supportsLookbehinds=()=>{let e=process.version.slice(1).split(`.`).map(Number);return e.length===3&&e[0]>=9||e[0]===8&&e[1]>=10},e.isWindows=e=>e&&typeof e.windows==`boolean`?e.windows:n===!0||t.sep===`\\`,e.escapeLast=(t,n,r)=>{let i=t.lastIndexOf(n,r);return i===-1?t:t[i-1]===`\\`?e.escapeLast(t,n,i-1):`${t.slice(0,i)}\\${t.slice(i)}`},e.removePrefix=(e,t={})=>{let n=e;return n.startsWith(`./`)&&(n=n.slice(2),t.prefix=`./`),n},e.wrapOutput=(e,t={},n={})=>{let r=`${n.contains?``:`^`}(?:${e})${n.contains?``:`$`}`;return t.negated===!0&&(r=`(?:^(?!${r}).*$)`),r}})),GR=s(((e,t)=>{let n=WR(),{CHAR_ASTERISK:r,CHAR_AT:i,CHAR_BACKWARD_SLASH:a,CHAR_COMMA:o,CHAR_DOT:s,CHAR_EXCLAMATION_MARK:c,CHAR_FORWARD_SLASH:l,CHAR_LEFT_CURLY_BRACE:u,CHAR_LEFT_PARENTHESES:d,CHAR_LEFT_SQUARE_BRACKET:f,CHAR_PLUS:p,CHAR_QUESTION_MARK:m,CHAR_RIGHT_CURLY_BRACE:h,CHAR_RIGHT_PARENTHESES:g,CHAR_RIGHT_SQUARE_BRACKET:_}=UR(),v=e=>e===l||e===a,y=e=>{e.isPrefix!==!0&&(e.depth=e.isGlobstar?1/0:1)};t.exports=(e,t)=>{let b=t||{},x=e.length-1,S=b.parts===!0||b.scanToEnd===!0,C=[],w=[],T=[],E=e,D=-1,O=0,k=0,A=!1,j=!1,M=!1,ee=!1,N=!1,te=!1,P=!1,F=!1,I=!1,L=!1,ne=0,R,z,re={value:``,depth:0,isGlob:!1},ie=()=>D>=x,B=()=>E.charCodeAt(D+1),V=()=>(R=z,E.charCodeAt(++D));for(;D<x;){z=V();let e;if(z===a){P=re.backslashes=!0,z=V(),z===u&&(te=!0);continue}if(te===!0||z===u){for(ne++;ie()!==!0&&(z=V());){if(z===a){P=re.backslashes=!0,V();continue}if(z===u){ne++;continue}if(te!==!0&&z===s&&(z=V())===s){if(A=re.isBrace=!0,M=re.isGlob=!0,L=!0,S===!0)continue;break}if(te!==!0&&z===o){if(A=re.isBrace=!0,M=re.isGlob=!0,L=!0,S===!0)continue;break}if(z===h&&(ne--,ne===0)){te=!1,A=re.isBrace=!0,L=!0;break}}if(S===!0)continue;break}if(z===l){if(C.push(D),w.push(re),re={value:``,depth:0,isGlob:!1},L===!0)continue;if(R===s&&D===O+1){O+=2;continue}k=D+1;continue}if(b.noext!==!0&&(z===p||z===i||z===r||z===m||z===c)&&B()===d){if(M=re.isGlob=!0,ee=re.isExtglob=!0,L=!0,z===c&&D===O&&(I=!0),S===!0){for(;ie()!==!0&&(z=V());){if(z===a){P=re.backslashes=!0,z=V();continue}if(z===g){M=re.isGlob=!0,L=!0;break}}continue}break}if(z===r){if(R===r&&(N=re.isGlobstar=!0),M=re.isGlob=!0,L=!0,S===!0)continue;break}if(z===m){if(M=re.isGlob=!0,L=!0,S===!0)continue;break}if(z===f){for(;ie()!==!0&&(e=V());){if(e===a){P=re.backslashes=!0,V();continue}if(e===_){j=re.isBracket=!0,M=re.isGlob=!0,L=!0;break}}if(S===!0)continue;break}if(b.nonegate!==!0&&z===c&&D===O){F=re.negated=!0,O++;continue}if(b.noparen!==!0&&z===d){if(M=re.isGlob=!0,S===!0){for(;ie()!==!0&&(z=V());){if(z===d){P=re.backslashes=!0,z=V();continue}if(z===g){L=!0;break}}continue}break}if(M===!0){if(L=!0,S===!0)continue;break}}b.noext===!0&&(ee=!1,M=!1);let ae=E,oe=``,se=``;O>0&&(oe=E.slice(0,O),E=E.slice(O),k-=O),ae&&M===!0&&k>0?(ae=E.slice(0,k),se=E.slice(k)):M===!0?(ae=``,se=E):ae=E,ae&&ae!==``&&ae!==`/`&&ae!==E&&v(ae.charCodeAt(ae.length-1))&&(ae=ae.slice(0,-1)),b.unescape===!0&&(se&&=n.removeBackslashes(se),ae&&P===!0&&(ae=n.removeBackslashes(ae)));let ce={prefix:oe,input:e,start:O,base:ae,glob:se,isBrace:A,isBracket:j,isGlob:M,isExtglob:ee,isGlobstar:N,negated:F,negatedExtglob:I};if(b.tokens===!0&&(ce.maxDepth=0,v(z)||w.push(re),ce.tokens=w),b.parts===!0||b.tokens===!0){let t;for(let n=0;n<C.length;n++){let r=t?t+1:O,i=C[n],a=e.slice(r,i);b.tokens&&(n===0&&O!==0?(w[n].isPrefix=!0,w[n].value=oe):w[n].value=a,y(w[n]),ce.maxDepth+=w[n].depth),(n!==0||a!==``)&&T.push(a),t=i}if(t&&t+1<e.length){let n=e.slice(t+1);T.push(n),b.tokens&&(w[w.length-1].value=n,y(w[w.length-1]),ce.maxDepth+=w[w.length-1].depth)}ce.slashes=C,ce.parts=T}return ce}})),KR=s(((e,t)=>{let n=UR(),r=WR(),{MAX_LENGTH:i,POSIX_REGEX_SOURCE:a,REGEX_NON_SPECIAL_CHARS:o,REGEX_SPECIAL_CHARS_BACKREF:s,REPLACEMENTS:c}=n,l=(e,t)=>{if(typeof t.expandRange==`function`)return t.expandRange(...e,t);e.sort();let n=`[${e.join(`-`)}]`;try{new RegExp(n)}catch{return e.map(e=>r.escapeRegex(e)).join(`..`)}return n},u=(e,t)=>`Missing ${e}: "${t}" - use "\\\\${t}" to match literal characters`,d=(e,t)=>{if(typeof e!=`string`)throw TypeError(`Expected a string`);e=c[e]||e;let f={...t},p=typeof f.maxLength==`number`?Math.min(i,f.maxLength):i,m=e.length;if(m>p)throw SyntaxError(`Input length: ${m}, exceeds maximum allowed length: ${p}`);let h={type:`bos`,value:``,output:f.prepend||``},g=[h],_=f.capture?``:`?:`,v=r.isWindows(t),y=n.globChars(v),b=n.extglobChars(y),{DOT_LITERAL:x,PLUS_LITERAL:S,SLASH_LITERAL:C,ONE_CHAR:w,DOTS_SLASH:T,NO_DOT:E,NO_DOT_SLASH:D,NO_DOTS_SLASH:O,QMARK:k,QMARK_NO_DOT:A,STAR:j,START_ANCHOR:M}=y,ee=e=>`(${_}(?:(?!${M}${e.dot?T:x}).)*?)`,N=f.dot?``:E,te=f.dot?k:A,P=f.bash===!0?ee(f):j;f.capture&&(P=`(${P})`),typeof f.noext==`boolean`&&(f.noextglob=f.noext);let F={input:e,index:-1,start:0,dot:f.dot===!0,consumed:``,output:``,prefix:``,backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens:g};e=r.removePrefix(e,F),m=e.length;let I=[],L=[],ne=[],R=h,z,re=()=>F.index===m-1,ie=F.peek=(t=1)=>e[F.index+t],B=F.advance=()=>e[++F.index]||``,V=()=>e.slice(F.index+1),ae=(e=``,t=0)=>{F.consumed+=e,F.index+=t},oe=e=>{F.output+=e.output==null?e.value:e.output,ae(e.value)},se=()=>{let e=1;for(;ie()===`!`&&(ie(2)!==`(`||ie(3)===`?`);)B(),F.start++,e++;return e%2==0?!1:(F.negated=!0,F.start++,!0)},ce=e=>{F[e]++,ne.push(e)},le=e=>{F[e]--,ne.pop()},ue=e=>{if(R.type===`globstar`){let t=F.braces>0&&(e.type===`comma`||e.type===`brace`),n=e.extglob===!0||I.length&&(e.type===`pipe`||e.type===`paren`);e.type!==`slash`&&e.type!==`paren`&&!t&&!n&&(F.output=F.output.slice(0,-R.output.length),R.type=`star`,R.value=`*`,R.output=P,F.output+=R.output)}if(I.length&&e.type!==`paren`&&(I[I.length-1].inner+=e.value),(e.value||e.output)&&oe(e),R&&R.type===`text`&&e.type===`text`){R.value+=e.value,R.output=(R.output||``)+e.value;return}e.prev=R,g.push(e),R=e},de=(e,t)=>{let n={...b[t],conditions:1,inner:``};n.prev=R,n.parens=F.parens,n.output=F.output;let r=(f.capture?`(`:``)+n.open;ce(`parens`),ue({type:e,value:t,output:F.output?``:w}),ue({type:`paren`,extglob:!0,value:B(),output:r}),I.push(n)},fe=e=>{let n=e.close+(f.capture?`)`:``),r;if(e.type===`negate`){let i=P;e.inner&&e.inner.length>1&&e.inner.includes(`/`)&&(i=ee(f)),(i!==P||re()||/^\)+$/.test(V()))&&(n=e.close=`)$))${i}`),e.inner.includes(`*`)&&(r=V())&&/^\.[^\\/.]+$/.test(r)&&(n=e.close=`)${d(r,{...t,fastpaths:!1}).output})${i})`),e.prev.type===`bos`&&(F.negatedExtglob=!0)}ue({type:`paren`,extglob:!0,value:z,output:n}),le(`parens`)};if(f.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(e)){let n=!1,i=e.replace(s,(e,t,r,i,a,o)=>i===`\\`?(n=!0,e):i===`?`?t?t+i+(a?k.repeat(a.length):``):o===0?te+(a?k.repeat(a.length):``):k.repeat(r.length):i===`.`?x.repeat(r.length):i===`*`?t?t+i+(a?P:``):P:t?e:`\\${e}`);return n===!0&&(i=f.unescape===!0?i.replace(/\\/g,``):i.replace(/\\+/g,e=>e.length%2==0?`\\\\`:e?`\\`:``)),i===e&&f.contains===!0?(F.output=e,F):(F.output=r.wrapOutput(i,F,t),F)}for(;!re();){if(z=B(),z===`\0`)continue;if(z===`\\`){let e=ie();if(e===`/`&&f.bash!==!0||e===`.`||e===`;`)continue;if(!e){z+=`\\`,ue({type:`text`,value:z});continue}let t=/^\\+/.exec(V()),n=0;if(t&&t[0].length>2&&(n=t[0].length,F.index+=n,n%2!=0&&(z+=`\\`)),f.unescape===!0?z=B():z+=B(),F.brackets===0){ue({type:`text`,value:z});continue}}if(F.brackets>0&&(z!==`]`||R.value===`[`||R.value===`[^`)){if(f.posix!==!1&&z===`:`){let e=R.value.slice(1);if(e.includes(`[`)&&(R.posix=!0,e.includes(`:`))){let e=R.value.lastIndexOf(`[`),t=R.value.slice(0,e),n=a[R.value.slice(e+2)];if(n){R.value=t+n,F.backtrack=!0,B(),!h.output&&g.indexOf(R)===1&&(h.output=w);continue}}}(z===`[`&&ie()!==`:`||z===`-`&&ie()===`]`)&&(z=`\\${z}`),z===`]`&&(R.value===`[`||R.value===`[^`)&&(z=`\\${z}`),f.posix===!0&&z===`!`&&R.value===`[`&&(z=`^`),R.value+=z,oe({value:z});continue}if(F.quotes===1&&z!==`"`){z=r.escapeRegex(z),R.value+=z,oe({value:z});continue}if(z===`"`){F.quotes=F.quotes===1?0:1,f.keepQuotes===!0&&ue({type:`text`,value:z});continue}if(z===`(`){ce(`parens`),ue({type:`paren`,value:z});continue}if(z===`)`){if(F.parens===0&&f.strictBrackets===!0)throw SyntaxError(u(`opening`,`(`));let e=I[I.length-1];if(e&&F.parens===e.parens+1){fe(I.pop());continue}ue({type:`paren`,value:z,output:F.parens?`)`:`\\)`}),le(`parens`);continue}if(z===`[`){if(f.nobracket===!0||!V().includes(`]`)){if(f.nobracket!==!0&&f.strictBrackets===!0)throw SyntaxError(u(`closing`,`]`));z=`\\${z}`}else ce(`brackets`);ue({type:`bracket`,value:z});continue}if(z===`]`){if(f.nobracket===!0||R&&R.type===`bracket`&&R.value.length===1){ue({type:`text`,value:z,output:`\\${z}`});continue}if(F.brackets===0){if(f.strictBrackets===!0)throw SyntaxError(u(`opening`,`[`));ue({type:`text`,value:z,output:`\\${z}`});continue}le(`brackets`);let e=R.value.slice(1);if(R.posix!==!0&&e[0]===`^`&&!e.includes(`/`)&&(z=`/${z}`),R.value+=z,oe({value:z}),f.literalBrackets===!1||r.hasRegexChars(e))continue;let t=r.escapeRegex(R.value);if(F.output=F.output.slice(0,-R.value.length),f.literalBrackets===!0){F.output+=t,R.value=t;continue}R.value=`(${_}${t}|${R.value})`,F.output+=R.value;continue}if(z===`{`&&f.nobrace!==!0){ce(`braces`);let e={type:`brace`,value:z,output:`(`,outputIndex:F.output.length,tokensIndex:F.tokens.length};L.push(e),ue(e);continue}if(z===`}`){let e=L[L.length-1];if(f.nobrace===!0||!e){ue({type:`text`,value:z,output:z});continue}let t=`)`;if(e.dots===!0){let e=g.slice(),n=[];for(let t=e.length-1;t>=0&&(g.pop(),e[t].type!==`brace`);t--)e[t].type!==`dots`&&n.unshift(e[t].value);t=l(n,f),F.backtrack=!0}if(e.comma!==!0&&e.dots!==!0){let n=F.output.slice(0,e.outputIndex),r=F.tokens.slice(e.tokensIndex);e.value=e.output=`\\{`,z=t=`\\}`,F.output=n;for(let e of r)F.output+=e.output||e.value}ue({type:`brace`,value:z,output:t}),le(`braces`),L.pop();continue}if(z===`|`){I.length>0&&I[I.length-1].conditions++,ue({type:`text`,value:z});continue}if(z===`,`){let e=z,t=L[L.length-1];t&&ne[ne.length-1]===`braces`&&(t.comma=!0,e=`|`),ue({type:`comma`,value:z,output:e});continue}if(z===`/`){if(R.type===`dot`&&F.index===F.start+1){F.start=F.index+1,F.consumed=``,F.output=``,g.pop(),R=h;continue}ue({type:`slash`,value:z,output:C});continue}if(z===`.`){if(F.braces>0&&R.type===`dot`){R.value===`.`&&(R.output=x);let e=L[L.length-1];R.type=`dots`,R.output+=z,R.value+=z,e.dots=!0;continue}if(F.braces+F.parens===0&&R.type!==`bos`&&R.type!==`slash`){ue({type:`text`,value:z,output:x});continue}ue({type:`dot`,value:z,output:x});continue}if(z===`?`){if(!(R&&R.value===`(`)&&f.noextglob!==!0&&ie()===`(`&&ie(2)!==`?`){de(`qmark`,z);continue}if(R&&R.type===`paren`){let e=ie(),t=z;if(e===`<`&&!r.supportsLookbehinds())throw Error(`Node.js v10 or higher is required for regex lookbehinds`);(R.value===`(`&&!/[!=<:]/.test(e)||e===`<`&&!/<([!=]|\w+>)/.test(V()))&&(t=`\\${z}`),ue({type:`text`,value:z,output:t});continue}if(f.dot!==!0&&(R.type===`slash`||R.type===`bos`)){ue({type:`qmark`,value:z,output:A});continue}ue({type:`qmark`,value:z,output:k});continue}if(z===`!`){if(f.noextglob!==!0&&ie()===`(`&&(ie(2)!==`?`||!/[!=<:]/.test(ie(3)))){de(`negate`,z);continue}if(f.nonegate!==!0&&F.index===0){se();continue}}if(z===`+`){if(f.noextglob!==!0&&ie()===`(`&&ie(2)!==`?`){de(`plus`,z);continue}if(R&&R.value===`(`||f.regex===!1){ue({type:`plus`,value:z,output:S});continue}if(R&&(R.type===`bracket`||R.type===`paren`||R.type===`brace`)||F.parens>0){ue({type:`plus`,value:z});continue}ue({type:`plus`,value:S});continue}if(z===`@`){if(f.noextglob!==!0&&ie()===`(`&&ie(2)!==`?`){ue({type:`at`,extglob:!0,value:z,output:``});continue}ue({type:`text`,value:z});continue}if(z!==`*`){(z===`$`||z===`^`)&&(z=`\\${z}`);let e=o.exec(V());e&&(z+=e[0],F.index+=e[0].length),ue({type:`text`,value:z});continue}if(R&&(R.type===`globstar`||R.star===!0)){R.type=`star`,R.star=!0,R.value+=z,R.output=P,F.backtrack=!0,F.globstar=!0,ae(z);continue}let t=V();if(f.noextglob!==!0&&/^\([^?]/.test(t)){de(`star`,z);continue}if(R.type===`star`){if(f.noglobstar===!0){ae(z);continue}let n=R.prev,r=n.prev,i=n.type===`slash`||n.type===`bos`,a=r&&(r.type===`star`||r.type===`globstar`);if(f.bash===!0&&(!i||t[0]&&t[0]!==`/`)){ue({type:`star`,value:z,output:``});continue}let o=F.braces>0&&(n.type===`comma`||n.type===`brace`),s=I.length&&(n.type===`pipe`||n.type===`paren`);if(!i&&n.type!==`paren`&&!o&&!s){ue({type:`star`,value:z,output:``});continue}for(;t.slice(0,3)===`/**`;){let n=e[F.index+4];if(n&&n!==`/`)break;t=t.slice(3),ae(`/**`,3)}if(n.type===`bos`&&re()){R.type=`globstar`,R.value+=z,R.output=ee(f),F.output=R.output,F.globstar=!0,ae(z);continue}if(n.type===`slash`&&n.prev.type!==`bos`&&!a&&re()){F.output=F.output.slice(0,-(n.output+R.output).length),n.output=`(?:${n.output}`,R.type=`globstar`,R.output=ee(f)+(f.strictSlashes?`)`:`|$)`),R.value+=z,F.globstar=!0,F.output+=n.output+R.output,ae(z);continue}if(n.type===`slash`&&n.prev.type!==`bos`&&t[0]===`/`){let e=t[1]===void 0?``:`|$`;F.output=F.output.slice(0,-(n.output+R.output).length),n.output=`(?:${n.output}`,R.type=`globstar`,R.output=`${ee(f)}${C}|${C}${e})`,R.value+=z,F.output+=n.output+R.output,F.globstar=!0,ae(z+B()),ue({type:`slash`,value:`/`,output:``});continue}if(n.type===`bos`&&t[0]===`/`){R.type=`globstar`,R.value+=z,R.output=`(?:^|${C}|${ee(f)}${C})`,F.output=R.output,F.globstar=!0,ae(z+B()),ue({type:`slash`,value:`/`,output:``});continue}F.output=F.output.slice(0,-R.output.length),R.type=`globstar`,R.output=ee(f),R.value+=z,F.output+=R.output,F.globstar=!0,ae(z);continue}let n={type:`star`,value:z,output:P};if(f.bash===!0){n.output=`.*?`,(R.type===`bos`||R.type===`slash`)&&(n.output=N+n.output),ue(n);continue}if(R&&(R.type===`bracket`||R.type===`paren`)&&f.regex===!0){n.output=z,ue(n);continue}(F.index===F.start||R.type===`slash`||R.type===`dot`)&&(R.type===`dot`?(F.output+=D,R.output+=D):f.dot===!0?(F.output+=O,R.output+=O):(F.output+=N,R.output+=N),ie()!==`*`&&(F.output+=w,R.output+=w)),ue(n)}for(;F.brackets>0;){if(f.strictBrackets===!0)throw SyntaxError(u(`closing`,`]`));F.output=r.escapeLast(F.output,`[`),le(`brackets`)}for(;F.parens>0;){if(f.strictBrackets===!0)throw SyntaxError(u(`closing`,`)`));F.output=r.escapeLast(F.output,`(`),le(`parens`)}for(;F.braces>0;){if(f.strictBrackets===!0)throw SyntaxError(u(`closing`,`}`));F.output=r.escapeLast(F.output,`{`),le(`braces`)}if(f.strictSlashes!==!0&&(R.type===`star`||R.type===`bracket`)&&ue({type:`maybe_slash`,value:``,output:`${C}?`}),F.backtrack===!0){F.output=``;for(let e of F.tokens)F.output+=e.output==null?e.value:e.output,e.suffix&&(F.output+=e.suffix)}return F};d.fastpaths=(e,t)=>{let a={...t},o=typeof a.maxLength==`number`?Math.min(i,a.maxLength):i,s=e.length;if(s>o)throw SyntaxError(`Input length: ${s}, exceeds maximum allowed length: ${o}`);e=c[e]||e;let l=r.isWindows(t),{DOT_LITERAL:u,SLASH_LITERAL:d,ONE_CHAR:f,DOTS_SLASH:p,NO_DOT:m,NO_DOTS:h,NO_DOTS_SLASH:g,STAR:_,START_ANCHOR:v}=n.globChars(l),y=a.dot?h:m,b=a.dot?g:m,x=a.capture?``:`?:`,S={negated:!1,prefix:``},C=a.bash===!0?`.*?`:_;a.capture&&(C=`(${C})`);let w=e=>e.noglobstar===!0?C:`(${x}(?:(?!${v}${e.dot?p:u}).)*?)`,T=e=>{switch(e){case`*`:return`${y}${f}${C}`;case`.*`:return`${u}${f}${C}`;case`*.*`:return`${y}${C}${u}${f}${C}`;case`*/*`:return`${y}${C}${d}${f}${b}${C}`;case`**`:return y+w(a);case`**/*`:return`(?:${y}${w(a)}${d})?${b}${f}${C}`;case`**/*.*`:return`(?:${y}${w(a)}${d})?${b}${C}${u}${f}${C}`;case`**/.*`:return`(?:${y}${w(a)}${d})?${u}${f}${C}`;default:{let t=/^(.*?)\.(\w+)$/.exec(e);if(!t)return;let n=T(t[1]);return n?n+u+t[2]:void 0}}},E=T(r.removePrefix(e,S));return E&&a.strictSlashes!==!0&&(E+=`${d}?`),E},t.exports=d})),qR=s(((e,t)=>{let n=require(`path`),r=GR(),i=KR(),a=WR(),o=UR(),s=e=>e&&typeof e==`object`&&!Array.isArray(e),c=(e,t,n=!1)=>{if(Array.isArray(e)){let r=e.map(e=>c(e,t,n));return e=>{for(let t of r){let n=t(e);if(n)return n}return!1}}let r=s(e)&&e.tokens&&e.input;if(e===``||typeof e!=`string`&&!r)throw TypeError(`Expected pattern to be a non-empty string`);let i=t||{},o=a.isWindows(t),l=r?c.compileRe(e,t):c.makeRe(e,t,!1,!0),u=l.state;delete l.state;let d=()=>!1;if(i.ignore){let e={...t,ignore:null,onMatch:null,onResult:null};d=c(i.ignore,e,n)}let f=(n,r=!1)=>{let{isMatch:a,match:s,output:f}=c.test(n,l,t,{glob:e,posix:o}),p={glob:e,state:u,regex:l,posix:o,input:n,output:f,match:s,isMatch:a};return typeof i.onResult==`function`&&i.onResult(p),a===!1?(p.isMatch=!1,r?p:!1):d(n)?(typeof i.onIgnore==`function`&&i.onIgnore(p),p.isMatch=!1,r?p:!1):(typeof i.onMatch==`function`&&i.onMatch(p),r?p:!0)};return n&&(f.state=u),f};c.test=(e,t,n,{glob:r,posix:i}={})=>{if(typeof e!=`string`)throw TypeError(`Expected input to be a string`);if(e===``)return{isMatch:!1,output:``};let o=n||{},s=o.format||(i?a.toPosixSlashes:null),l=e===r,u=l&&s?s(e):e;return l===!1&&(u=s?s(e):e,l=u===r),(l===!1||o.capture===!0)&&(l=o.matchBase===!0||o.basename===!0?c.matchBase(e,t,n,i):t.exec(u)),{isMatch:!!l,match:l,output:u}},c.matchBase=(e,t,r,i=a.isWindows(r))=>(t instanceof RegExp?t:c.makeRe(t,r)).test(n.basename(e)),c.isMatch=(e,t,n)=>c(t,n)(e),c.parse=(e,t)=>Array.isArray(e)?e.map(e=>c.parse(e,t)):i(e,{...t,fastpaths:!1}),c.scan=(e,t)=>r(e,t),c.compileRe=(e,t,n=!1,r=!1)=>{if(n===!0)return e.output;let i=t||{},a=i.contains?``:`^`,o=i.contains?``:`$`,s=`${a}(?:${e.output})${o}`;e&&e.negated===!0&&(s=`^(?!${s}).*$`);let l=c.toRegex(s,t);return r===!0&&(l.state=e),l},c.makeRe=(e,t={},n=!1,r=!1)=>{if(!e||typeof e!=`string`)throw TypeError(`Expected a non-empty string`);let a={negated:!1,fastpaths:!0};return t.fastpaths!==!1&&(e[0]===`.`||e[0]===`*`)&&(a.output=i.fastpaths(e,t)),a.output||(a=i(e,t)),c.compileRe(a,t,n,r)},c.toRegex=(e,t)=>{try{let n=t||{};return new RegExp(e,n.flags||(n.nocase?`i`:``))}catch(e){if(t&&t.debug===!0)throw e;return/$^/}},c.constants=o,t.exports=c})),JR=s(((e,t)=>{t.exports=qR()})),YR=s(((e,t)=>{let n=require(`util`),r=HR(),i=JR(),a=WR(),o=e=>e===``||e===`./`,s=e=>{let t=e.indexOf(`{`);return t>-1&&e.indexOf(`}`,t)>-1},c=(e,t,n)=>{t=[].concat(t),e=[].concat(e);let r=new Set,a=new Set,o=new Set,s=0,c=e=>{o.add(e.output),n&&n.onResult&&n.onResult(e)};for(let o=0;o<t.length;o++){let l=i(String(t[o]),{...n,onResult:c},!0),u=l.state.negated||l.state.negatedExtglob;u&&s++;for(let t of e){let e=l(t,!0);(u?!e.isMatch:e.isMatch)&&(u?r.add(e.output):(r.delete(e.output),a.add(e.output)))}}let l=(s===t.length?[...o]:[...a]).filter(e=>!r.has(e));if(n&&l.length===0){if(n.failglob===!0)throw Error(`No matches found for "${t.join(`, `)}"`);if(n.nonull===!0||n.nullglob===!0)return n.unescape?t.map(e=>e.replace(/\\/g,``)):t}return l};c.match=c,c.matcher=(e,t)=>i(e,t),c.isMatch=(e,t,n)=>i(t,n)(e),c.any=c.isMatch,c.not=(e,t,n={})=>{t=[].concat(t).map(String);let r=new Set,i=[],a=e=>{n.onResult&&n.onResult(e),i.push(e.output)},o=new Set(c(e,t,{...n,onResult:a}));for(let e of i)o.has(e)||r.add(e);return[...r]},c.contains=(e,t,r)=>{if(typeof e!=`string`)throw TypeError(`Expected a string: "${n.inspect(e)}"`);if(Array.isArray(t))return t.some(t=>c.contains(e,t,r));if(typeof t==`string`){if(o(e)||o(t))return!1;if(e.includes(t)||e.startsWith(`./`)&&e.slice(2).includes(t))return!0}return c.isMatch(e,t,{...r,contains:!0})},c.matchKeys=(e,t,n)=>{if(!a.isObject(e))throw TypeError(`Expected the first argument to be an object`);let r=c(Object.keys(e),t,n),i={};for(let t of r)i[t]=e[t];return i},c.some=(e,t,n)=>{let r=[].concat(e);for(let e of[].concat(t)){let t=i(String(e),n);if(r.some(e=>t(e)))return!0}return!1},c.every=(e,t,n)=>{let r=[].concat(e);for(let e of[].concat(t)){let t=i(String(e),n);if(!r.every(e=>t(e)))return!1}return!0},c.all=(e,t,r)=>{if(typeof e!=`string`)throw TypeError(`Expected a string: "${n.inspect(e)}"`);return[].concat(t).every(t=>i(t,r)(e))},c.capture=(e,t,n)=>{let r=a.isWindows(n),o=i.makeRe(String(e),{...n,capture:!0}).exec(r?a.toPosixSlashes(t):t);if(o)return o.slice(1).map(e=>e===void 0?``:e)},c.makeRe=(...e)=>i.makeRe(...e),c.scan=(...e)=>i.scan(...e),c.parse=(e,t)=>{let n=[];for(let a of[].concat(e||[]))for(let e of r(String(a),t))n.push(i.parse(e,t));return n},c.braces=(e,t)=>{if(typeof e!=`string`)throw TypeError(`Expected a string`);return t&&t.nobrace===!0||!s(e)?[e]:r(e,t)},c.braceExpand=(e,t)=>{if(typeof e!=`string`)throw TypeError(`Expected a string`);return c.braces(e,{...t,expand:!0})},c.hasBraces=s,t.exports=c})),XR=s(((e,t)=>{var n=require(`fs`),r=require(`path`),i=bR(),a=NR(),o=PR(),s=YR();t.exports=function(e,t){t||={};var n=r.resolve(a(t.cwd||``));if(typeof e==`string`)return c(n,[e],t);if(!Array.isArray(e))throw TypeError(`findup-sync expects a string or array as the first argument.`);return c(n,e,t)};function c(e,t,n){for(var a=t.length,o=-1,s;++o<a;)if(s=i(t[o])?l(e,t[o],n):u(e,t[o],n),s)return s;var d=r.dirname(e);return d===e?null:c(d,t,n)}function l(e,t,n){for(var i=s.matcher(t,n),a=d(e),o=a.length,c=-1;++c<o;){var l=a[c],u=r.join(e,l);if(i(l)||i(u))return u}return null}function u(e,t,n){return o(r.resolve(e,t),n)}function d(e){try{return n.readdirSync(e)}catch{}return[]}})),ZR=s((e=>{let t=ur(),n=_R(),r=t.__toESM(vR()),i=t.__toESM(ie()),a=t.__toESM(require(`node:fs`)),o=t.__toESM(XR()),s={WIN32:`win32`,DARWIN:`darwin`,LINUX:`linux`},c={JAVASCRIPT:`javascript`,TYPESCRIPT:`typescript`,PYTHON:`python`},l=e=>{let t=n.getGlobalConfig().getRootPath();return r.default.resolve(t,e)},u=e=>{let t=n.getGlobalConfig().getRootPath(),i=r.default.normalize(e);return r.default.relative(t,i)},d=e=>({".js":`javascript`,".mjs":`javascript`,".cjs":`javascript`,".jsx":`javascript`,".ts":`typescript`,".tsx":`typescript`,".py":`python`})[e.toLowerCase()]??`javascript`;function f(e){return d((0,r.extname)(e))}function p(e){return d((0,r.extname)(e))===`typescript`}function m(e){return d((0,r.extname)(e))===c.PYTHON}function h(e){let t=n.getGlobalConfig().getRootPath();if(!(0,i.isDefined)(t))throw Error(`Workspace root path is not defined`);if((0,i.isEmpty)(e))return r.default.normalize(t);let a=r.default.normalize(t),o=r.default.normalize(e);if(process.platform===s.WIN32){let t=a.split(`:`)[0].toUpperCase(),n=o.split(`:`)[0].toUpperCase();if(t!==n&&!n.startsWith(t))return e}return r.default.relative(a,o)}function g(e){return e.startsWith(`../`)?`../${e}`:e.startsWith(`./`)?`.${e}`:e}function _(e){let t=r.default.normalize(l(e)),n=r.default.normalize((0,o.default)([`package.json`,`project.json`],{cwd:t})??``);if(!n)return``;let i=u((0,r.dirname)(n));return i.startsWith(`/`)?i.slice(1):i}function v(e,t,n){if(!b(e))return e;let i=n===``?t:t.replace(n,``),a=n===``?S(i):x(i),o=i.split(`/`).slice(0,-1),s=y(e,`../`),c=s>0?o.slice(0,-s).join(`/`):(0,r.dirname)(i),l=e.replaceAll(`../`,``).replaceAll(`./`,``);return r.default.join(a,c,l)}function y(e,t){return e.split(t).length-1}function b(e){return e.startsWith(`../`)||e.startsWith(`./`)}function x(e){let t=y(e,`/`);return`../`.repeat(t-1)}function S(e){let t=y(e,`/`);return`../`.repeat(t+1)}function C(e){return e?.includes(`node_modules/`)}let w=e=>e.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`),T=e=>process.platform===`win32`?`"${e.replaceAll(`"`,String.raw`\"`)}"`:`'${e.replaceAll(`'`,`'"'"'`)}'`;function E(e,t){let n=r.default.relative(e,t);return!!n&&!n.startsWith(`..`)&&!r.default.isAbsolute(n)}function D(e,t){let n=r.default.isAbsolute(e)?e:l(e);return(0,o.default)(t,{cwd:n})}function O(e,t){let n=D(e,t);if(!(0,i.isDefined)(n))return;let r=a.readFileSync(n,`utf8`);return JSON.parse(r)}function k(e){return O(e,`package.json`)}function A(e,t){let{dependencies:n={},devDependencies:r={}}=e;return Object.keys({...r,...n}).includes(t)}function j(e){return/\.(?:early\.)?(?:test|spec)\.[cm]?[jt]sx?$/.test(e)}var M=class{provider;repoRoot;constructor(e,t){this.provider=e,this.repoRoot=r.default.normalize(r.default.resolve(t))}findPaths(e,t){let n=this.indexEntries(e);return t.map(e=>({file:e,flows:this.pathsForFile(this.toAbsolute(e),n)}))}indexEntries(e){let t=new Map;for(let n of e)for(let e of n.entryFiles){let r=this.toAbsolute(e),i=t.get(r)??[];i.push(n.flowId),t.set(r,i)}return t}pathsForFile(e,t){let n=new Map,r=new Set([e]),i=[e],a=new Map;for(;i.length>0;){let o=i.shift();o!==e&&t.has(o)&&this.recordEntryHit(o,n,e,t,a),this.enqueueImporters(o,r,n,i)}return[...a].map(([e,t])=>({flowId:e,via:t}))}recordEntryHit(e,t,n,r,i){let a=this.reconstruct(t,n,e);for(let t of r.get(e)??[])i.has(t)||i.set(t,a)}enqueueImporters(e,t,n,r){for(let i of this.provider.getImporters(e))!t.has(i)&&!j(i)&&(t.add(i),n.set(i,e),r.push(i))}reconstruct(e,t,n){let r=[],i=n;for(;i!==t;)r.push(this.toRelative(i)),i=e.get(i);return r.toReversed()}toAbsolute(e){return r.default.isAbsolute(e)?r.default.normalize(e):r.default.normalize(r.default.resolve(this.repoRoot,e))}toRelative(e){return r.default.normalize(e).replace(`${this.repoRoot}/`,``)}};Object.defineProperty(e,`ReachabilityPathFinder`,{enumerable:!0,get:function(){return M}}),Object.defineProperty(e,`absoluteToRelativePath`,{enumerable:!0,get:function(){return h}}),Object.defineProperty(e,`absoluteToRelativeUri`,{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,`addFolderHierarchyToPathIfNeeded`,{enumerable:!0,get:function(){return g}}),Object.defineProperty(e,`changePathToTests`,{enumerable:!0,get:function(){return v}}),Object.defineProperty(e,`escapeRegexPath`,{enumerable:!0,get:function(){return w}}),Object.defineProperty(e,`fileExtensionToLanguage`,{enumerable:!0,get:function(){return d}}),Object.defineProperty(e,`findPackageJson`,{enumerable:!0,get:function(){return k}}),Object.defineProperty(e,`findRepoRoot`,{enumerable:!0,get:function(){return _}}),Object.defineProperty(e,`findupFile`,{enumerable:!0,get:function(){return D}}),Object.defineProperty(e,`getFileLanguage`,{enumerable:!0,get:function(){return f}}),Object.defineProperty(e,`isExistDependency`,{enumerable:!0,get:function(){return A}}),Object.defineProperty(e,`isPathInNodeModules`,{enumerable:!0,get:function(){return C}}),Object.defineProperty(e,`isPathInside`,{enumerable:!0,get:function(){return E}}),Object.defineProperty(e,`isPythonFile`,{enumerable:!0,get:function(){return m}}),Object.defineProperty(e,`isRelativePath`,{enumerable:!0,get:function(){return b}}),Object.defineProperty(e,`isTestFile`,{enumerable:!0,get:function(){return j}}),Object.defineProperty(e,`isTypescriptFile`,{enumerable:!0,get:function(){return p}}),Object.defineProperty(e,`relativePathToAbsoluteUri`,{enumerable:!0,get:function(){return l}}),Object.defineProperty(e,`relativeToRoot`,{enumerable:!0,get:function(){return S}}),Object.defineProperty(e,`shellEscapePath`,{enumerable:!0,get:function(){return T}})})),QR=s((e=>{let t=ur(),n=_R(),r=t.__toESM(require(`node:child_process`)),i=process.env.EARLY_DIAGNOSTICS_LOGS===`true`,a=i;function o(e){let t=[],n=/^diff --git a\/.+? b\/(.+)$/gm,r;for(;(r=n.exec(e))!==null;)t.push(r[1]);return t}function s(e,t){if(e.length<=t)return e;let n=e.length-t,r=e.slice(0,t),i=e.slice(t),a=new Set(o(r)),s=o(i).filter(e=>!a.has(e)),c=o(r).at(-1),l=/^diff --git a\//m.test(i.slice(0,200))?void 0:c,u=l===void 0?``:`\nPARTIALLY SHOWN (diff cut mid-file — re-read this file's FULL diff): ${l}`,d=s.length>0?`\nOMITTED FILES (${s.length}) — not shown at all, read each directly if a finding could depend on it: ${s.join(`, `)}`:``;return`${r}
|
|
156
|
-
… [DIFF TRUNCATED — ${n.toLocaleString()} of ${e.length.toLocaleString()} chars omitted because the full diff exceeds the model context. The changes below the cut are NOT shown here. If you need a truncated/omitted file, read it directly with your tools (e.g. \`git --no-pager diff <anchor> <compare> -- <path>\` or Read the file at the compare ref). Do NOT assume the omitted region is inert — flag that coverage was truncated if a finding could depend on it.${
|
|
157
|
-
`),c=Math.max(1,r-a),l=Math.min(s.length,i+a),u=String(l).length,d=[];for(let e=c;e<=l;e++)d.push(`${String(e).padStart(u,` `)}| ${s[e-1]??``}`);let
|
|
158
|
-
`)}${
|
|
159
|
-
`),o=a.some(e=>e.endsWith(`\trefs/heads/${t}`)),s=a.some(e=>e.endsWith(`\trefs/tags/${t}`));if(o)return(0,r.execFileSync)(`git`,[`fetch`,`origin`,`+refs/heads/${t}:refs/remotes/origin/${t}`],n),{kind:`branch`,ref:`origin/${t}`};if(s)return(0,r.execFileSync)(`git`,[`fetch`,`origin`,`+refs/tags/${t}:refs/tags/${t}`],n),{kind:`tag`,ref:`refs/tags/${t}`};throw Error(`[regression-impact] Unable to classify '${t}' from ls-remote output.`)}function
|
|
160
|
-
`).filter(e=>e.length>0);return{files:[...new Set(o)],description:`${a} vs ${n}`}}function
|
|
161
|
-
`)).filter(e=>e.length>0);return{files:[...new Set(n)],description:`uncommitted (unstaged + staged + untracked)`}}function
|
|
162
|
-
`)||`(diff unavailable)`;let s=
|
|
163
|
-
`).filter(e=>e.length>0):[]}return(0,r.execFileSync)(`git`,[`log`,`${t}..HEAD`,`--format=%h%n%s%n%b`],i).trim().split(``).map(e=>
|
|
155
|
+
`,CHAR_NO_BREAK_SPACE:`\xA0`,CHAR_PERCENT:`%`,CHAR_PLUS:`+`,CHAR_QUESTION_MARK:`?`,CHAR_RIGHT_ANGLE_BRACKET:`>`,CHAR_RIGHT_CURLY_BRACE:`}`,CHAR_RIGHT_SQUARE_BRACKET:`]`,CHAR_SEMICOLON:`;`,CHAR_SINGLE_QUOTE:`'`,CHAR_SPACE:` `,CHAR_TAB:` `,CHAR_UNDERSCORE:`_`,CHAR_VERTICAL_LINE:`|`,CHAR_ZERO_WIDTH_NOBREAK_SPACE:``}})),VR=s(((e,t)=>{let n=IR(),{MAX_LENGTH:r,CHAR_BACKSLASH:i,CHAR_BACKTICK:a,CHAR_COMMA:o,CHAR_DOT:s,CHAR_LEFT_PARENTHESES:c,CHAR_RIGHT_PARENTHESES:l,CHAR_LEFT_CURLY_BRACE:u,CHAR_RIGHT_CURLY_BRACE:d,CHAR_LEFT_SQUARE_BRACKET:f,CHAR_RIGHT_SQUARE_BRACKET:p,CHAR_DOUBLE_QUOTE:m,CHAR_SINGLE_QUOTE:h,CHAR_NO_BREAK_SPACE:g,CHAR_ZERO_WIDTH_NOBREAK_SPACE:_}=BR();t.exports=(e,t={})=>{if(typeof e!=`string`)throw TypeError(`Expected a string`);let v=t||{},y=typeof v.maxLength==`number`?Math.min(r,v.maxLength):r;if(e.length>y)throw SyntaxError(`Input length (${e.length}), exceeds max characters (${y})`);let b={type:`root`,input:e,nodes:[]},x=[b],S=b,C=b,w=0,T=e.length,E=0,D=0,O,k=()=>e[E++],A=e=>{if(e.type===`text`&&C.type===`dot`&&(C.type=`text`),C&&C.type===`text`&&e.type===`text`){C.value+=e.value;return}return S.nodes.push(e),e.parent=S,e.prev=C,C=e,e};for(A({type:`bos`});E<T;)if(S=x[x.length-1],O=k(),!(O===_||O===g)){if(O===i){A({type:`text`,value:(t.keepEscaping?O:``)+k()});continue}if(O===p){A({type:`text`,value:`\\`+O});continue}if(O===f){w++;let e;for(;E<T&&(e=k());){if(O+=e,e===f){w++;continue}if(e===i){O+=k();continue}if(e===p&&(w--,w===0))break}A({type:`text`,value:O});continue}if(O===c){S=A({type:`paren`,nodes:[]}),x.push(S),A({type:`text`,value:O});continue}if(O===l){if(S.type!==`paren`){A({type:`text`,value:O});continue}S=x.pop(),A({type:`text`,value:O}),S=x[x.length-1];continue}if(O===m||O===h||O===a){let e=O,n;for(t.keepQuotes!==!0&&(O=``);E<T&&(n=k());){if(n===i){O+=n+k();continue}if(n===e){t.keepQuotes===!0&&(O+=n);break}O+=n}A({type:`text`,value:O});continue}if(O===u){D++,S=A({type:`brace`,open:!0,close:!1,dollar:C.value&&C.value.slice(-1)===`$`||S.dollar===!0,depth:D,commas:0,ranges:0,nodes:[]}),x.push(S),A({type:`open`,value:O});continue}if(O===d){if(S.type!==`brace`){A({type:`text`,value:O});continue}S=x.pop(),S.close=!0,A({type:`close`,value:O}),D--,S=x[x.length-1];continue}if(O===o&&D>0){if(S.ranges>0){S.ranges=0;let e=S.nodes.shift();S.nodes=[e,{type:`text`,value:n(S)}]}A({type:`comma`,value:O}),S.commas++;continue}if(O===s&&D>0&&S.commas===0){let e=S.nodes;if(D===0||e.length===0){A({type:`text`,value:O});continue}if(C.type===`dot`){if(S.range=[],C.value+=O,C.type=`range`,S.nodes.length!==3&&S.nodes.length!==5){S.invalid=!0,S.ranges=0,C.type=`text`;continue}S.ranges++,S.args=[];continue}if(C.type===`range`){e.pop();let t=e[e.length-1];t.value+=C.value+O,C=t,S.ranges--;continue}A({type:`dot`,value:O});continue}A({type:`text`,value:O})}do if(S=x.pop(),S.type!==`root`){S.nodes.forEach(e=>{e.nodes||(e.type===`open`&&(e.isOpen=!0),e.type===`close`&&(e.isClose=!0),e.nodes||(e.type=`text`),e.invalid=!0)});let e=x[x.length-1],t=e.nodes.indexOf(S);e.nodes.splice(t,1,...S.nodes)}while(x.length>0);return A({type:`eos`}),b}})),HR=s(((e,t)=>{let n=IR(),r=pee(),i=mee(),a=VR(),o=(e,t={})=>{let n=[];if(Array.isArray(e))for(let r of e){let e=o.create(r,t);Array.isArray(e)?n.push(...e):n.push(e)}else n=[].concat(o.create(e,t));return t&&t.expand===!0&&t.nodupes===!0&&(n=[...new Set(n)]),n};o.parse=(e,t={})=>a(e,t),o.stringify=(e,t={})=>n(typeof e==`string`?o.parse(e,t):e,t),o.compile=(e,t={})=>(typeof e==`string`&&(e=o.parse(e,t)),r(e,t)),o.expand=(e,t={})=>{typeof e==`string`&&(e=o.parse(e,t));let n=i(e,t);return t.noempty===!0&&(n=n.filter(Boolean)),t.nodupes===!0&&(n=[...new Set(n)]),n},o.create=(e,t={})=>e===``||e.length<3?[e]:t.expand===!0?o.expand(e,t):o.compile(e,t),t.exports=o})),UR=s(((e,t)=>{let n=require(`path`),r=`[^\\\\/]`,i=`[^/]`,a=`(?:\\/|$)`,o=`(?:^|\\/)`,s=`\\.{1,2}${a}`,c={DOT_LITERAL:`\\.`,PLUS_LITERAL:`\\+`,QMARK_LITERAL:`\\?`,SLASH_LITERAL:`\\/`,ONE_CHAR:`(?=.)`,QMARK:i,END_ANCHOR:a,DOTS_SLASH:s,NO_DOT:`(?!\\.)`,NO_DOTS:`(?!${o}${s})`,NO_DOT_SLASH:`(?!\\.{0,1}${a})`,NO_DOTS_SLASH:`(?!${s})`,QMARK_NO_DOT:`[^.\\/]`,STAR:`${i}*?`,START_ANCHOR:o},l={...c,SLASH_LITERAL:`[\\\\/]`,QMARK:r,STAR:`${r}*?`,DOTS_SLASH:`\\.{1,2}(?:[\\\\/]|$)`,NO_DOT:`(?!\\.)`,NO_DOTS:`(?!(?:^|[\\\\/])\\.{1,2}(?:[\\\\/]|$))`,NO_DOT_SLASH:`(?!\\.{0,1}(?:[\\\\/]|$))`,NO_DOTS_SLASH:`(?!\\.{1,2}(?:[\\\\/]|$))`,QMARK_NO_DOT:`[^.\\\\/]`,START_ANCHOR:`(?:^|[\\\\/])`,END_ANCHOR:`(?:[\\\\/]|$)`};t.exports={MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:{alnum:`a-zA-Z0-9`,alpha:`a-zA-Z`,ascii:`\\x00-\\x7F`,blank:` \\t`,cntrl:`\\x00-\\x1F\\x7F`,digit:`0-9`,graph:`\\x21-\\x7E`,lower:`a-z`,print:`\\x20-\\x7E `,punct:`\\-!"#$%&'()\\*+,./:;<=>?@[\\]^_\`{|}~`,space:` \\t\\r\\n\\v\\f`,upper:`A-Z`,word:`A-Za-z0-9_`,xdigit:`A-Fa-f0-9`},REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{"***":`*`,"**/**":`**`,"**/**/**":`**`},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,SEP:n.sep,extglobChars(e){return{"!":{type:`negate`,open:`(?:(?!(?:`,close:`))${e.STAR})`},"?":{type:`qmark`,open:`(?:`,close:`)?`},"+":{type:`plus`,open:`(?:`,close:`)+`},"*":{type:`star`,open:`(?:`,close:`)*`},"@":{type:`at`,open:`(?:`,close:`)`}}},globChars(e){return e===!0?l:c}}})),WR=s((e=>{let t=require(`path`),n=process.platform===`win32`,{REGEX_BACKSLASH:r,REGEX_REMOVE_BACKSLASH:i,REGEX_SPECIAL_CHARS:a,REGEX_SPECIAL_CHARS_GLOBAL:o}=UR();e.isObject=e=>typeof e==`object`&&!!e&&!Array.isArray(e),e.hasRegexChars=e=>a.test(e),e.isRegexChar=t=>t.length===1&&e.hasRegexChars(t),e.escapeRegex=e=>e.replace(o,`\\$1`),e.toPosixSlashes=e=>e.replace(r,`/`),e.removeBackslashes=e=>e.replace(i,e=>e===`\\`?``:e),e.supportsLookbehinds=()=>{let e=process.version.slice(1).split(`.`).map(Number);return e.length===3&&e[0]>=9||e[0]===8&&e[1]>=10},e.isWindows=e=>e&&typeof e.windows==`boolean`?e.windows:n===!0||t.sep===`\\`,e.escapeLast=(t,n,r)=>{let i=t.lastIndexOf(n,r);return i===-1?t:t[i-1]===`\\`?e.escapeLast(t,n,i-1):`${t.slice(0,i)}\\${t.slice(i)}`},e.removePrefix=(e,t={})=>{let n=e;return n.startsWith(`./`)&&(n=n.slice(2),t.prefix=`./`),n},e.wrapOutput=(e,t={},n={})=>{let r=`${n.contains?``:`^`}(?:${e})${n.contains?``:`$`}`;return t.negated===!0&&(r=`(?:^(?!${r}).*$)`),r}})),GR=s(((e,t)=>{let n=WR(),{CHAR_ASTERISK:r,CHAR_AT:i,CHAR_BACKWARD_SLASH:a,CHAR_COMMA:o,CHAR_DOT:s,CHAR_EXCLAMATION_MARK:c,CHAR_FORWARD_SLASH:l,CHAR_LEFT_CURLY_BRACE:u,CHAR_LEFT_PARENTHESES:d,CHAR_LEFT_SQUARE_BRACKET:f,CHAR_PLUS:p,CHAR_QUESTION_MARK:m,CHAR_RIGHT_CURLY_BRACE:h,CHAR_RIGHT_PARENTHESES:g,CHAR_RIGHT_SQUARE_BRACKET:_}=UR(),v=e=>e===l||e===a,y=e=>{e.isPrefix!==!0&&(e.depth=e.isGlobstar?1/0:1)};t.exports=(e,t)=>{let b=t||{},x=e.length-1,S=b.parts===!0||b.scanToEnd===!0,C=[],w=[],T=[],E=e,D=-1,O=0,k=0,A=!1,j=!1,M=!1,ee=!1,N=!1,te=!1,P=!1,F=!1,I=!1,L=!1,ne=0,R,z,re={value:``,depth:0,isGlob:!1},ie=()=>D>=x,B=()=>E.charCodeAt(D+1),V=()=>(R=z,E.charCodeAt(++D));for(;D<x;){z=V();let e;if(z===a){P=re.backslashes=!0,z=V(),z===u&&(te=!0);continue}if(te===!0||z===u){for(ne++;ie()!==!0&&(z=V());){if(z===a){P=re.backslashes=!0,V();continue}if(z===u){ne++;continue}if(te!==!0&&z===s&&(z=V())===s){if(A=re.isBrace=!0,M=re.isGlob=!0,L=!0,S===!0)continue;break}if(te!==!0&&z===o){if(A=re.isBrace=!0,M=re.isGlob=!0,L=!0,S===!0)continue;break}if(z===h&&(ne--,ne===0)){te=!1,A=re.isBrace=!0,L=!0;break}}if(S===!0)continue;break}if(z===l){if(C.push(D),w.push(re),re={value:``,depth:0,isGlob:!1},L===!0)continue;if(R===s&&D===O+1){O+=2;continue}k=D+1;continue}if(b.noext!==!0&&(z===p||z===i||z===r||z===m||z===c)&&B()===d){if(M=re.isGlob=!0,ee=re.isExtglob=!0,L=!0,z===c&&D===O&&(I=!0),S===!0){for(;ie()!==!0&&(z=V());){if(z===a){P=re.backslashes=!0,z=V();continue}if(z===g){M=re.isGlob=!0,L=!0;break}}continue}break}if(z===r){if(R===r&&(N=re.isGlobstar=!0),M=re.isGlob=!0,L=!0,S===!0)continue;break}if(z===m){if(M=re.isGlob=!0,L=!0,S===!0)continue;break}if(z===f){for(;ie()!==!0&&(e=V());){if(e===a){P=re.backslashes=!0,V();continue}if(e===_){j=re.isBracket=!0,M=re.isGlob=!0,L=!0;break}}if(S===!0)continue;break}if(b.nonegate!==!0&&z===c&&D===O){F=re.negated=!0,O++;continue}if(b.noparen!==!0&&z===d){if(M=re.isGlob=!0,S===!0){for(;ie()!==!0&&(z=V());){if(z===d){P=re.backslashes=!0,z=V();continue}if(z===g){L=!0;break}}continue}break}if(M===!0){if(L=!0,S===!0)continue;break}}b.noext===!0&&(ee=!1,M=!1);let ae=E,oe=``,se=``;O>0&&(oe=E.slice(0,O),E=E.slice(O),k-=O),ae&&M===!0&&k>0?(ae=E.slice(0,k),se=E.slice(k)):M===!0?(ae=``,se=E):ae=E,ae&&ae!==``&&ae!==`/`&&ae!==E&&v(ae.charCodeAt(ae.length-1))&&(ae=ae.slice(0,-1)),b.unescape===!0&&(se&&=n.removeBackslashes(se),ae&&P===!0&&(ae=n.removeBackslashes(ae)));let ce={prefix:oe,input:e,start:O,base:ae,glob:se,isBrace:A,isBracket:j,isGlob:M,isExtglob:ee,isGlobstar:N,negated:F,negatedExtglob:I};if(b.tokens===!0&&(ce.maxDepth=0,v(z)||w.push(re),ce.tokens=w),b.parts===!0||b.tokens===!0){let t;for(let n=0;n<C.length;n++){let r=t?t+1:O,i=C[n],a=e.slice(r,i);b.tokens&&(n===0&&O!==0?(w[n].isPrefix=!0,w[n].value=oe):w[n].value=a,y(w[n]),ce.maxDepth+=w[n].depth),(n!==0||a!==``)&&T.push(a),t=i}if(t&&t+1<e.length){let n=e.slice(t+1);T.push(n),b.tokens&&(w[w.length-1].value=n,y(w[w.length-1]),ce.maxDepth+=w[w.length-1].depth)}ce.slashes=C,ce.parts=T}return ce}})),KR=s(((e,t)=>{let n=UR(),r=WR(),{MAX_LENGTH:i,POSIX_REGEX_SOURCE:a,REGEX_NON_SPECIAL_CHARS:o,REGEX_SPECIAL_CHARS_BACKREF:s,REPLACEMENTS:c}=n,l=(e,t)=>{if(typeof t.expandRange==`function`)return t.expandRange(...e,t);e.sort();let n=`[${e.join(`-`)}]`;try{new RegExp(n)}catch{return e.map(e=>r.escapeRegex(e)).join(`..`)}return n},u=(e,t)=>`Missing ${e}: "${t}" - use "\\\\${t}" to match literal characters`,d=(e,t)=>{if(typeof e!=`string`)throw TypeError(`Expected a string`);e=c[e]||e;let f={...t},p=typeof f.maxLength==`number`?Math.min(i,f.maxLength):i,m=e.length;if(m>p)throw SyntaxError(`Input length: ${m}, exceeds maximum allowed length: ${p}`);let h={type:`bos`,value:``,output:f.prepend||``},g=[h],_=f.capture?``:`?:`,v=r.isWindows(t),y=n.globChars(v),b=n.extglobChars(y),{DOT_LITERAL:x,PLUS_LITERAL:S,SLASH_LITERAL:C,ONE_CHAR:w,DOTS_SLASH:T,NO_DOT:E,NO_DOT_SLASH:D,NO_DOTS_SLASH:O,QMARK:k,QMARK_NO_DOT:A,STAR:j,START_ANCHOR:M}=y,ee=e=>`(${_}(?:(?!${M}${e.dot?T:x}).)*?)`,N=f.dot?``:E,te=f.dot?k:A,P=f.bash===!0?ee(f):j;f.capture&&(P=`(${P})`),typeof f.noext==`boolean`&&(f.noextglob=f.noext);let F={input:e,index:-1,start:0,dot:f.dot===!0,consumed:``,output:``,prefix:``,backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens:g};e=r.removePrefix(e,F),m=e.length;let I=[],L=[],ne=[],R=h,z,re=()=>F.index===m-1,ie=F.peek=(t=1)=>e[F.index+t],B=F.advance=()=>e[++F.index]||``,V=()=>e.slice(F.index+1),ae=(e=``,t=0)=>{F.consumed+=e,F.index+=t},oe=e=>{F.output+=e.output==null?e.value:e.output,ae(e.value)},se=()=>{let e=1;for(;ie()===`!`&&(ie(2)!==`(`||ie(3)===`?`);)B(),F.start++,e++;return e%2==0?!1:(F.negated=!0,F.start++,!0)},ce=e=>{F[e]++,ne.push(e)},le=e=>{F[e]--,ne.pop()},ue=e=>{if(R.type===`globstar`){let t=F.braces>0&&(e.type===`comma`||e.type===`brace`),n=e.extglob===!0||I.length&&(e.type===`pipe`||e.type===`paren`);e.type!==`slash`&&e.type!==`paren`&&!t&&!n&&(F.output=F.output.slice(0,-R.output.length),R.type=`star`,R.value=`*`,R.output=P,F.output+=R.output)}if(I.length&&e.type!==`paren`&&(I[I.length-1].inner+=e.value),(e.value||e.output)&&oe(e),R&&R.type===`text`&&e.type===`text`){R.value+=e.value,R.output=(R.output||``)+e.value;return}e.prev=R,g.push(e),R=e},de=(e,t)=>{let n={...b[t],conditions:1,inner:``};n.prev=R,n.parens=F.parens,n.output=F.output;let r=(f.capture?`(`:``)+n.open;ce(`parens`),ue({type:e,value:t,output:F.output?``:w}),ue({type:`paren`,extglob:!0,value:B(),output:r}),I.push(n)},fe=e=>{let n=e.close+(f.capture?`)`:``),r;if(e.type===`negate`){let i=P;e.inner&&e.inner.length>1&&e.inner.includes(`/`)&&(i=ee(f)),(i!==P||re()||/^\)+$/.test(V()))&&(n=e.close=`)$))${i}`),e.inner.includes(`*`)&&(r=V())&&/^\.[^\\/.]+$/.test(r)&&(n=e.close=`)${d(r,{...t,fastpaths:!1}).output})${i})`),e.prev.type===`bos`&&(F.negatedExtglob=!0)}ue({type:`paren`,extglob:!0,value:z,output:n}),le(`parens`)};if(f.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(e)){let n=!1,i=e.replace(s,(e,t,r,i,a,o)=>i===`\\`?(n=!0,e):i===`?`?t?t+i+(a?k.repeat(a.length):``):o===0?te+(a?k.repeat(a.length):``):k.repeat(r.length):i===`.`?x.repeat(r.length):i===`*`?t?t+i+(a?P:``):P:t?e:`\\${e}`);return n===!0&&(i=f.unescape===!0?i.replace(/\\/g,``):i.replace(/\\+/g,e=>e.length%2==0?`\\\\`:e?`\\`:``)),i===e&&f.contains===!0?(F.output=e,F):(F.output=r.wrapOutput(i,F,t),F)}for(;!re();){if(z=B(),z===`\0`)continue;if(z===`\\`){let e=ie();if(e===`/`&&f.bash!==!0||e===`.`||e===`;`)continue;if(!e){z+=`\\`,ue({type:`text`,value:z});continue}let t=/^\\+/.exec(V()),n=0;if(t&&t[0].length>2&&(n=t[0].length,F.index+=n,n%2!=0&&(z+=`\\`)),f.unescape===!0?z=B():z+=B(),F.brackets===0){ue({type:`text`,value:z});continue}}if(F.brackets>0&&(z!==`]`||R.value===`[`||R.value===`[^`)){if(f.posix!==!1&&z===`:`){let e=R.value.slice(1);if(e.includes(`[`)&&(R.posix=!0,e.includes(`:`))){let e=R.value.lastIndexOf(`[`),t=R.value.slice(0,e),n=a[R.value.slice(e+2)];if(n){R.value=t+n,F.backtrack=!0,B(),!h.output&&g.indexOf(R)===1&&(h.output=w);continue}}}(z===`[`&&ie()!==`:`||z===`-`&&ie()===`]`)&&(z=`\\${z}`),z===`]`&&(R.value===`[`||R.value===`[^`)&&(z=`\\${z}`),f.posix===!0&&z===`!`&&R.value===`[`&&(z=`^`),R.value+=z,oe({value:z});continue}if(F.quotes===1&&z!==`"`){z=r.escapeRegex(z),R.value+=z,oe({value:z});continue}if(z===`"`){F.quotes=F.quotes===1?0:1,f.keepQuotes===!0&&ue({type:`text`,value:z});continue}if(z===`(`){ce(`parens`),ue({type:`paren`,value:z});continue}if(z===`)`){if(F.parens===0&&f.strictBrackets===!0)throw SyntaxError(u(`opening`,`(`));let e=I[I.length-1];if(e&&F.parens===e.parens+1){fe(I.pop());continue}ue({type:`paren`,value:z,output:F.parens?`)`:`\\)`}),le(`parens`);continue}if(z===`[`){if(f.nobracket===!0||!V().includes(`]`)){if(f.nobracket!==!0&&f.strictBrackets===!0)throw SyntaxError(u(`closing`,`]`));z=`\\${z}`}else ce(`brackets`);ue({type:`bracket`,value:z});continue}if(z===`]`){if(f.nobracket===!0||R&&R.type===`bracket`&&R.value.length===1){ue({type:`text`,value:z,output:`\\${z}`});continue}if(F.brackets===0){if(f.strictBrackets===!0)throw SyntaxError(u(`opening`,`[`));ue({type:`text`,value:z,output:`\\${z}`});continue}le(`brackets`);let e=R.value.slice(1);if(R.posix!==!0&&e[0]===`^`&&!e.includes(`/`)&&(z=`/${z}`),R.value+=z,oe({value:z}),f.literalBrackets===!1||r.hasRegexChars(e))continue;let t=r.escapeRegex(R.value);if(F.output=F.output.slice(0,-R.value.length),f.literalBrackets===!0){F.output+=t,R.value=t;continue}R.value=`(${_}${t}|${R.value})`,F.output+=R.value;continue}if(z===`{`&&f.nobrace!==!0){ce(`braces`);let e={type:`brace`,value:z,output:`(`,outputIndex:F.output.length,tokensIndex:F.tokens.length};L.push(e),ue(e);continue}if(z===`}`){let e=L[L.length-1];if(f.nobrace===!0||!e){ue({type:`text`,value:z,output:z});continue}let t=`)`;if(e.dots===!0){let e=g.slice(),n=[];for(let t=e.length-1;t>=0&&(g.pop(),e[t].type!==`brace`);t--)e[t].type!==`dots`&&n.unshift(e[t].value);t=l(n,f),F.backtrack=!0}if(e.comma!==!0&&e.dots!==!0){let n=F.output.slice(0,e.outputIndex),r=F.tokens.slice(e.tokensIndex);e.value=e.output=`\\{`,z=t=`\\}`,F.output=n;for(let e of r)F.output+=e.output||e.value}ue({type:`brace`,value:z,output:t}),le(`braces`),L.pop();continue}if(z===`|`){I.length>0&&I[I.length-1].conditions++,ue({type:`text`,value:z});continue}if(z===`,`){let e=z,t=L[L.length-1];t&&ne[ne.length-1]===`braces`&&(t.comma=!0,e=`|`),ue({type:`comma`,value:z,output:e});continue}if(z===`/`){if(R.type===`dot`&&F.index===F.start+1){F.start=F.index+1,F.consumed=``,F.output=``,g.pop(),R=h;continue}ue({type:`slash`,value:z,output:C});continue}if(z===`.`){if(F.braces>0&&R.type===`dot`){R.value===`.`&&(R.output=x);let e=L[L.length-1];R.type=`dots`,R.output+=z,R.value+=z,e.dots=!0;continue}if(F.braces+F.parens===0&&R.type!==`bos`&&R.type!==`slash`){ue({type:`text`,value:z,output:x});continue}ue({type:`dot`,value:z,output:x});continue}if(z===`?`){if(!(R&&R.value===`(`)&&f.noextglob!==!0&&ie()===`(`&&ie(2)!==`?`){de(`qmark`,z);continue}if(R&&R.type===`paren`){let e=ie(),t=z;if(e===`<`&&!r.supportsLookbehinds())throw Error(`Node.js v10 or higher is required for regex lookbehinds`);(R.value===`(`&&!/[!=<:]/.test(e)||e===`<`&&!/<([!=]|\w+>)/.test(V()))&&(t=`\\${z}`),ue({type:`text`,value:z,output:t});continue}if(f.dot!==!0&&(R.type===`slash`||R.type===`bos`)){ue({type:`qmark`,value:z,output:A});continue}ue({type:`qmark`,value:z,output:k});continue}if(z===`!`){if(f.noextglob!==!0&&ie()===`(`&&(ie(2)!==`?`||!/[!=<:]/.test(ie(3)))){de(`negate`,z);continue}if(f.nonegate!==!0&&F.index===0){se();continue}}if(z===`+`){if(f.noextglob!==!0&&ie()===`(`&&ie(2)!==`?`){de(`plus`,z);continue}if(R&&R.value===`(`||f.regex===!1){ue({type:`plus`,value:z,output:S});continue}if(R&&(R.type===`bracket`||R.type===`paren`||R.type===`brace`)||F.parens>0){ue({type:`plus`,value:z});continue}ue({type:`plus`,value:S});continue}if(z===`@`){if(f.noextglob!==!0&&ie()===`(`&&ie(2)!==`?`){ue({type:`at`,extglob:!0,value:z,output:``});continue}ue({type:`text`,value:z});continue}if(z!==`*`){(z===`$`||z===`^`)&&(z=`\\${z}`);let e=o.exec(V());e&&(z+=e[0],F.index+=e[0].length),ue({type:`text`,value:z});continue}if(R&&(R.type===`globstar`||R.star===!0)){R.type=`star`,R.star=!0,R.value+=z,R.output=P,F.backtrack=!0,F.globstar=!0,ae(z);continue}let t=V();if(f.noextglob!==!0&&/^\([^?]/.test(t)){de(`star`,z);continue}if(R.type===`star`){if(f.noglobstar===!0){ae(z);continue}let n=R.prev,r=n.prev,i=n.type===`slash`||n.type===`bos`,a=r&&(r.type===`star`||r.type===`globstar`);if(f.bash===!0&&(!i||t[0]&&t[0]!==`/`)){ue({type:`star`,value:z,output:``});continue}let o=F.braces>0&&(n.type===`comma`||n.type===`brace`),s=I.length&&(n.type===`pipe`||n.type===`paren`);if(!i&&n.type!==`paren`&&!o&&!s){ue({type:`star`,value:z,output:``});continue}for(;t.slice(0,3)===`/**`;){let n=e[F.index+4];if(n&&n!==`/`)break;t=t.slice(3),ae(`/**`,3)}if(n.type===`bos`&&re()){R.type=`globstar`,R.value+=z,R.output=ee(f),F.output=R.output,F.globstar=!0,ae(z);continue}if(n.type===`slash`&&n.prev.type!==`bos`&&!a&&re()){F.output=F.output.slice(0,-(n.output+R.output).length),n.output=`(?:${n.output}`,R.type=`globstar`,R.output=ee(f)+(f.strictSlashes?`)`:`|$)`),R.value+=z,F.globstar=!0,F.output+=n.output+R.output,ae(z);continue}if(n.type===`slash`&&n.prev.type!==`bos`&&t[0]===`/`){let e=t[1]===void 0?``:`|$`;F.output=F.output.slice(0,-(n.output+R.output).length),n.output=`(?:${n.output}`,R.type=`globstar`,R.output=`${ee(f)}${C}|${C}${e})`,R.value+=z,F.output+=n.output+R.output,F.globstar=!0,ae(z+B()),ue({type:`slash`,value:`/`,output:``});continue}if(n.type===`bos`&&t[0]===`/`){R.type=`globstar`,R.value+=z,R.output=`(?:^|${C}|${ee(f)}${C})`,F.output=R.output,F.globstar=!0,ae(z+B()),ue({type:`slash`,value:`/`,output:``});continue}F.output=F.output.slice(0,-R.output.length),R.type=`globstar`,R.output=ee(f),R.value+=z,F.output+=R.output,F.globstar=!0,ae(z);continue}let n={type:`star`,value:z,output:P};if(f.bash===!0){n.output=`.*?`,(R.type===`bos`||R.type===`slash`)&&(n.output=N+n.output),ue(n);continue}if(R&&(R.type===`bracket`||R.type===`paren`)&&f.regex===!0){n.output=z,ue(n);continue}(F.index===F.start||R.type===`slash`||R.type===`dot`)&&(R.type===`dot`?(F.output+=D,R.output+=D):f.dot===!0?(F.output+=O,R.output+=O):(F.output+=N,R.output+=N),ie()!==`*`&&(F.output+=w,R.output+=w)),ue(n)}for(;F.brackets>0;){if(f.strictBrackets===!0)throw SyntaxError(u(`closing`,`]`));F.output=r.escapeLast(F.output,`[`),le(`brackets`)}for(;F.parens>0;){if(f.strictBrackets===!0)throw SyntaxError(u(`closing`,`)`));F.output=r.escapeLast(F.output,`(`),le(`parens`)}for(;F.braces>0;){if(f.strictBrackets===!0)throw SyntaxError(u(`closing`,`}`));F.output=r.escapeLast(F.output,`{`),le(`braces`)}if(f.strictSlashes!==!0&&(R.type===`star`||R.type===`bracket`)&&ue({type:`maybe_slash`,value:``,output:`${C}?`}),F.backtrack===!0){F.output=``;for(let e of F.tokens)F.output+=e.output==null?e.value:e.output,e.suffix&&(F.output+=e.suffix)}return F};d.fastpaths=(e,t)=>{let a={...t},o=typeof a.maxLength==`number`?Math.min(i,a.maxLength):i,s=e.length;if(s>o)throw SyntaxError(`Input length: ${s}, exceeds maximum allowed length: ${o}`);e=c[e]||e;let l=r.isWindows(t),{DOT_LITERAL:u,SLASH_LITERAL:d,ONE_CHAR:f,DOTS_SLASH:p,NO_DOT:m,NO_DOTS:h,NO_DOTS_SLASH:g,STAR:_,START_ANCHOR:v}=n.globChars(l),y=a.dot?h:m,b=a.dot?g:m,x=a.capture?``:`?:`,S={negated:!1,prefix:``},C=a.bash===!0?`.*?`:_;a.capture&&(C=`(${C})`);let w=e=>e.noglobstar===!0?C:`(${x}(?:(?!${v}${e.dot?p:u}).)*?)`,T=e=>{switch(e){case`*`:return`${y}${f}${C}`;case`.*`:return`${u}${f}${C}`;case`*.*`:return`${y}${C}${u}${f}${C}`;case`*/*`:return`${y}${C}${d}${f}${b}${C}`;case`**`:return y+w(a);case`**/*`:return`(?:${y}${w(a)}${d})?${b}${f}${C}`;case`**/*.*`:return`(?:${y}${w(a)}${d})?${b}${C}${u}${f}${C}`;case`**/.*`:return`(?:${y}${w(a)}${d})?${u}${f}${C}`;default:{let t=/^(.*?)\.(\w+)$/.exec(e);if(!t)return;let n=T(t[1]);return n?n+u+t[2]:void 0}}},E=T(r.removePrefix(e,S));return E&&a.strictSlashes!==!0&&(E+=`${d}?`),E},t.exports=d})),qR=s(((e,t)=>{let n=require(`path`),r=GR(),i=KR(),a=WR(),o=UR(),s=e=>e&&typeof e==`object`&&!Array.isArray(e),c=(e,t,n=!1)=>{if(Array.isArray(e)){let r=e.map(e=>c(e,t,n));return e=>{for(let t of r){let n=t(e);if(n)return n}return!1}}let r=s(e)&&e.tokens&&e.input;if(e===``||typeof e!=`string`&&!r)throw TypeError(`Expected pattern to be a non-empty string`);let i=t||{},o=a.isWindows(t),l=r?c.compileRe(e,t):c.makeRe(e,t,!1,!0),u=l.state;delete l.state;let d=()=>!1;if(i.ignore){let e={...t,ignore:null,onMatch:null,onResult:null};d=c(i.ignore,e,n)}let f=(n,r=!1)=>{let{isMatch:a,match:s,output:f}=c.test(n,l,t,{glob:e,posix:o}),p={glob:e,state:u,regex:l,posix:o,input:n,output:f,match:s,isMatch:a};return typeof i.onResult==`function`&&i.onResult(p),a===!1?(p.isMatch=!1,r?p:!1):d(n)?(typeof i.onIgnore==`function`&&i.onIgnore(p),p.isMatch=!1,r?p:!1):(typeof i.onMatch==`function`&&i.onMatch(p),r?p:!0)};return n&&(f.state=u),f};c.test=(e,t,n,{glob:r,posix:i}={})=>{if(typeof e!=`string`)throw TypeError(`Expected input to be a string`);if(e===``)return{isMatch:!1,output:``};let o=n||{},s=o.format||(i?a.toPosixSlashes:null),l=e===r,u=l&&s?s(e):e;return l===!1&&(u=s?s(e):e,l=u===r),(l===!1||o.capture===!0)&&(l=o.matchBase===!0||o.basename===!0?c.matchBase(e,t,n,i):t.exec(u)),{isMatch:!!l,match:l,output:u}},c.matchBase=(e,t,r,i=a.isWindows(r))=>(t instanceof RegExp?t:c.makeRe(t,r)).test(n.basename(e)),c.isMatch=(e,t,n)=>c(t,n)(e),c.parse=(e,t)=>Array.isArray(e)?e.map(e=>c.parse(e,t)):i(e,{...t,fastpaths:!1}),c.scan=(e,t)=>r(e,t),c.compileRe=(e,t,n=!1,r=!1)=>{if(n===!0)return e.output;let i=t||{},a=i.contains?``:`^`,o=i.contains?``:`$`,s=`${a}(?:${e.output})${o}`;e&&e.negated===!0&&(s=`^(?!${s}).*$`);let l=c.toRegex(s,t);return r===!0&&(l.state=e),l},c.makeRe=(e,t={},n=!1,r=!1)=>{if(!e||typeof e!=`string`)throw TypeError(`Expected a non-empty string`);let a={negated:!1,fastpaths:!0};return t.fastpaths!==!1&&(e[0]===`.`||e[0]===`*`)&&(a.output=i.fastpaths(e,t)),a.output||(a=i(e,t)),c.compileRe(a,t,n,r)},c.toRegex=(e,t)=>{try{let n=t||{};return new RegExp(e,n.flags||(n.nocase?`i`:``))}catch(e){if(t&&t.debug===!0)throw e;return/$^/}},c.constants=o,t.exports=c})),JR=s(((e,t)=>{t.exports=qR()})),YR=s(((e,t)=>{let n=require(`util`),r=HR(),i=JR(),a=WR(),o=e=>e===``||e===`./`,s=e=>{let t=e.indexOf(`{`);return t>-1&&e.indexOf(`}`,t)>-1},c=(e,t,n)=>{t=[].concat(t),e=[].concat(e);let r=new Set,a=new Set,o=new Set,s=0,c=e=>{o.add(e.output),n&&n.onResult&&n.onResult(e)};for(let o=0;o<t.length;o++){let l=i(String(t[o]),{...n,onResult:c},!0),u=l.state.negated||l.state.negatedExtglob;u&&s++;for(let t of e){let e=l(t,!0);(u?!e.isMatch:e.isMatch)&&(u?r.add(e.output):(r.delete(e.output),a.add(e.output)))}}let l=(s===t.length?[...o]:[...a]).filter(e=>!r.has(e));if(n&&l.length===0){if(n.failglob===!0)throw Error(`No matches found for "${t.join(`, `)}"`);if(n.nonull===!0||n.nullglob===!0)return n.unescape?t.map(e=>e.replace(/\\/g,``)):t}return l};c.match=c,c.matcher=(e,t)=>i(e,t),c.isMatch=(e,t,n)=>i(t,n)(e),c.any=c.isMatch,c.not=(e,t,n={})=>{t=[].concat(t).map(String);let r=new Set,i=[],a=e=>{n.onResult&&n.onResult(e),i.push(e.output)},o=new Set(c(e,t,{...n,onResult:a}));for(let e of i)o.has(e)||r.add(e);return[...r]},c.contains=(e,t,r)=>{if(typeof e!=`string`)throw TypeError(`Expected a string: "${n.inspect(e)}"`);if(Array.isArray(t))return t.some(t=>c.contains(e,t,r));if(typeof t==`string`){if(o(e)||o(t))return!1;if(e.includes(t)||e.startsWith(`./`)&&e.slice(2).includes(t))return!0}return c.isMatch(e,t,{...r,contains:!0})},c.matchKeys=(e,t,n)=>{if(!a.isObject(e))throw TypeError(`Expected the first argument to be an object`);let r=c(Object.keys(e),t,n),i={};for(let t of r)i[t]=e[t];return i},c.some=(e,t,n)=>{let r=[].concat(e);for(let e of[].concat(t)){let t=i(String(e),n);if(r.some(e=>t(e)))return!0}return!1},c.every=(e,t,n)=>{let r=[].concat(e);for(let e of[].concat(t)){let t=i(String(e),n);if(!r.every(e=>t(e)))return!1}return!0},c.all=(e,t,r)=>{if(typeof e!=`string`)throw TypeError(`Expected a string: "${n.inspect(e)}"`);return[].concat(t).every(t=>i(t,r)(e))},c.capture=(e,t,n)=>{let r=a.isWindows(n),o=i.makeRe(String(e),{...n,capture:!0}).exec(r?a.toPosixSlashes(t):t);if(o)return o.slice(1).map(e=>e===void 0?``:e)},c.makeRe=(...e)=>i.makeRe(...e),c.scan=(...e)=>i.scan(...e),c.parse=(e,t)=>{let n=[];for(let a of[].concat(e||[]))for(let e of r(String(a),t))n.push(i.parse(e,t));return n},c.braces=(e,t)=>{if(typeof e!=`string`)throw TypeError(`Expected a string`);return t&&t.nobrace===!0||!s(e)?[e]:r(e,t)},c.braceExpand=(e,t)=>{if(typeof e!=`string`)throw TypeError(`Expected a string`);return c.braces(e,{...t,expand:!0})},c.hasBraces=s,t.exports=c})),XR=s(((e,t)=>{var n=require(`fs`),r=require(`path`),i=bR(),a=NR(),o=PR(),s=YR();t.exports=function(e,t){t||={};var n=r.resolve(a(t.cwd||``));if(typeof e==`string`)return c(n,[e],t);if(!Array.isArray(e))throw TypeError(`findup-sync expects a string or array as the first argument.`);return c(n,e,t)};function c(e,t,n){for(var a=t.length,o=-1,s;++o<a;)if(s=i(t[o])?l(e,t[o],n):u(e,t[o],n),s)return s;var d=r.dirname(e);return d===e?null:c(d,t,n)}function l(e,t,n){for(var i=s.matcher(t,n),a=d(e),o=a.length,c=-1;++c<o;){var l=a[c],u=r.join(e,l);if(i(l)||i(u))return u}return null}function u(e,t,n){return o(r.resolve(e,t),n)}function d(e){try{return n.readdirSync(e)}catch{}return[]}})),ZR=s((e=>{let t=ur(),n=_R(),r=t.__toESM(vR()),i=t.__toESM(ie()),a=t.__toESM(require(`node:fs`)),o=t.__toESM(XR()),s={WIN32:`win32`,DARWIN:`darwin`,LINUX:`linux`},c={JAVASCRIPT:`javascript`,TYPESCRIPT:`typescript`,PYTHON:`python`},l=e=>{let t=n.getGlobalConfig().getRootPath();return r.default.resolve(t,e)},u=e=>{let t=n.getGlobalConfig().getRootPath(),i=r.default.normalize(e);return r.default.relative(t,i)},d=e=>({".js":`javascript`,".mjs":`javascript`,".cjs":`javascript`,".jsx":`javascript`,".ts":`typescript`,".tsx":`typescript`,".py":`python`})[e.toLowerCase()]??`javascript`;function f(e){return d((0,r.extname)(e))}function p(e){return d((0,r.extname)(e))===`typescript`}function m(e){return d((0,r.extname)(e))===c.PYTHON}function h(e){let t=n.getGlobalConfig().getRootPath();if(!(0,i.isDefined)(t))throw Error(`Workspace root path is not defined`);if((0,i.isEmpty)(e))return r.default.normalize(t);let a=r.default.normalize(t),o=r.default.normalize(e);if(process.platform===s.WIN32){let t=a.split(`:`)[0].toUpperCase(),n=o.split(`:`)[0].toUpperCase();if(t!==n&&!n.startsWith(t))return e}return r.default.relative(a,o)}function g(e){return e.startsWith(`../`)?`../${e}`:e.startsWith(`./`)?`.${e}`:e}function _(e){let t=r.default.normalize(l(e)),n=r.default.normalize((0,o.default)([`package.json`,`project.json`],{cwd:t})??``);if(!n)return``;let i=u((0,r.dirname)(n));return i.startsWith(`/`)?i.slice(1):i}function v(e,t,n){if(!b(e))return e;let i=n===``?t:t.replace(n,``),a=n===``?S(i):x(i),o=i.split(`/`).slice(0,-1),s=y(e,`../`),c=s>0?o.slice(0,-s).join(`/`):(0,r.dirname)(i),l=e.replaceAll(`../`,``).replaceAll(`./`,``);return r.default.join(a,c,l)}function y(e,t){return e.split(t).length-1}function b(e){return e.startsWith(`../`)||e.startsWith(`./`)}function x(e){let t=y(e,`/`);return`../`.repeat(t-1)}function S(e){let t=y(e,`/`);return`../`.repeat(t+1)}function C(e){return e?.includes(`node_modules/`)}let w=e=>e.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`),T=e=>process.platform===`win32`?`"${e.replaceAll(`"`,String.raw`\"`)}"`:`'${e.replaceAll(`'`,`'"'"'`)}'`;function E(e,t){let n=r.default.relative(e,t);return!!n&&!n.startsWith(`..`)&&!r.default.isAbsolute(n)}function D(e,t){let n=r.default.isAbsolute(e)?e:l(e);return(0,o.default)(t,{cwd:n})}function O(e,t){let n=D(e,t);if(!(0,i.isDefined)(n))return;let r=a.readFileSync(n,`utf8`);return JSON.parse(r)}function k(e){return O(e,`package.json`)}function A(e,t){let{dependencies:n={},devDependencies:r={}}=e;return Object.keys({...r,...n}).includes(t)}function j(e){return/\.(?:early\.)?(?:test|spec)\.[cm]?[jt]sx?$/.test(e)}var M=class{provider;repoRoot;constructor(e,t){this.provider=e,this.repoRoot=r.default.normalize(r.default.resolve(t))}findPaths(e,t){let n=this.indexEntries(e);return t.map(e=>({file:e,flows:this.pathsForFile(this.toAbsolute(e),n)}))}indexEntries(e){let t=new Map;for(let n of e)for(let e of n.entryFiles){let r=this.toAbsolute(e),i=t.get(r)??[];i.push(n.flowId),t.set(r,i)}return t}pathsForFile(e,t){let n=new Map,r=new Set([e]),i=[e],a=new Map;for(;i.length>0;){let o=i.shift();o!==e&&t.has(o)&&this.recordEntryHit(o,n,e,t,a),this.enqueueImporters(o,r,n,i)}return[...a].map(([e,t])=>({flowId:e,via:t}))}recordEntryHit(e,t,n,r,i){let a=this.reconstruct(t,n,e);for(let t of r.get(e)??[])i.has(t)||i.set(t,a)}enqueueImporters(e,t,n,r){for(let i of this.provider.getImporters(e))!t.has(i)&&!j(i)&&(t.add(i),n.set(i,e),r.push(i))}reconstruct(e,t,n){let r=[],i=n;for(;i!==t;)r.push(this.toRelative(i)),i=e.get(i);return r.toReversed()}toAbsolute(e){return r.default.isAbsolute(e)?r.default.normalize(e):r.default.normalize(r.default.resolve(this.repoRoot,e))}toRelative(e){return r.default.normalize(e).replace(`${this.repoRoot}/`,``)}};Object.defineProperty(e,`ReachabilityPathFinder`,{enumerable:!0,get:function(){return M}}),Object.defineProperty(e,`absoluteToRelativePath`,{enumerable:!0,get:function(){return h}}),Object.defineProperty(e,`absoluteToRelativeUri`,{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,`addFolderHierarchyToPathIfNeeded`,{enumerable:!0,get:function(){return g}}),Object.defineProperty(e,`changePathToTests`,{enumerable:!0,get:function(){return v}}),Object.defineProperty(e,`escapeRegexPath`,{enumerable:!0,get:function(){return w}}),Object.defineProperty(e,`fileExtensionToLanguage`,{enumerable:!0,get:function(){return d}}),Object.defineProperty(e,`findPackageJson`,{enumerable:!0,get:function(){return k}}),Object.defineProperty(e,`findRepoRoot`,{enumerable:!0,get:function(){return _}}),Object.defineProperty(e,`findupFile`,{enumerable:!0,get:function(){return D}}),Object.defineProperty(e,`getFileLanguage`,{enumerable:!0,get:function(){return f}}),Object.defineProperty(e,`isExistDependency`,{enumerable:!0,get:function(){return A}}),Object.defineProperty(e,`isPathInNodeModules`,{enumerable:!0,get:function(){return C}}),Object.defineProperty(e,`isPathInside`,{enumerable:!0,get:function(){return E}}),Object.defineProperty(e,`isPythonFile`,{enumerable:!0,get:function(){return m}}),Object.defineProperty(e,`isRelativePath`,{enumerable:!0,get:function(){return b}}),Object.defineProperty(e,`isTestFile`,{enumerable:!0,get:function(){return j}}),Object.defineProperty(e,`isTypescriptFile`,{enumerable:!0,get:function(){return p}}),Object.defineProperty(e,`relativePathToAbsoluteUri`,{enumerable:!0,get:function(){return l}}),Object.defineProperty(e,`relativeToRoot`,{enumerable:!0,get:function(){return S}}),Object.defineProperty(e,`shellEscapePath`,{enumerable:!0,get:function(){return T}})})),QR=s((e=>{let t=ur(),n=_R(),r=t.__toESM(require(`node:child_process`)),i=[`low`,`medium`,`high`,`xhigh`,`max`];function a(e){let t=process.env.EARLY_REGRESSION_EFFORT;if(t===void 0||t===``)return e;let n=i.find(e=>e===t);return n===void 0?(console.error(`[regression] Ignoring EARLY_REGRESSION_EFFORT="${t}" — not one of ${i.join(`, `)}. Falling back to "${e}".`),e):n}let o=a(`high`),s={thinking:{type:`adaptive`},effort:o},c={thinking:{type:`adaptive`},effort:o},l={},u=process.env.EARLY_DIAGNOSTICS_LOGS===`true`,d=u;function f(e){let t=[],n=/^diff --git a\/.+? b\/(.+)$/gm,r;for(;(r=n.exec(e))!==null;)t.push(r[1]);return t}function p(e,t){if(e.length<=t)return e;let n=e.length-t,r=e.slice(0,t),i=e.slice(t),a=new Set(f(r)),o=f(i).filter(e=>!a.has(e)),s=f(r).at(-1),c=/^diff --git a\//m.test(i.slice(0,200))?void 0:s,l=c===void 0?``:`\nPARTIALLY SHOWN (diff cut mid-file — re-read this file's FULL diff): ${c}`,u=o.length>0?`\nOMITTED FILES (${o.length}) — not shown at all, read each directly if a finding could depend on it: ${o.join(`, `)}`:``;return`${r}
|
|
156
|
+
… [DIFF TRUNCATED — ${n.toLocaleString()} of ${e.length.toLocaleString()} chars omitted because the full diff exceeds the model context. The changes below the cut are NOT shown here. If you need a truncated/omitted file, read it directly with your tools (e.g. \`git --no-pager diff <anchor> <compare> -- <path>\` or Read the file at the compare ref). Do NOT assume the omitted region is inert — flag that coverage was truncated if a finding could depend on it.${l}${u}]`}function m(e){let t={cwd:e,encoding:`utf8`,timeout:1e4};return(0,r.execSync)(`git rev-parse --abbrev-ref HEAD`,t).trim()}function h(e){let t={cwd:e,encoding:`utf8`,timeout:1e4};return(0,r.execSync)(`git rev-parse HEAD`,t).trim()}function g(e){let t={cwd:e,encoding:`utf8`,timeout:1e4};return(0,r.execSync)(`git rev-parse --show-toplevel`,t).trim()}function _(e,t){let n={cwd:e,encoding:`utf8`,timeout:1e4};return(0,r.execFileSync)(`git`,[`rev-parse`,t],n).trim()}function v(e,t,n,i=0){let a={cwd:e,encoding:`utf8`,timeout:15e3,maxBuffer:2e7};try{let e=(0,r.execFileSync)(`git`,[`--no-pager`,`show`,`${t}:${n}`],a);return i>0&&e.length>i?`${e.slice(0,i)}\n… [truncated at ${i} chars — read the file with your tools for the rest]`:e}catch{return``}}function y(e,t,n,r,i,a=60){let o=v(e,t,n);if(o===``)return``;let s=o.split(`
|
|
157
|
+
`),c=Math.max(1,r-a),l=Math.min(s.length,i+a),u=String(l).length,d=[];for(let e=c;e<=l;e++)d.push(`${String(e).padStart(u,` `)}| ${s[e-1]??``}`);let f=c>1?`… (lines 1-${c-1} omitted)\n`:``,p=l<s.length?`\n… (lines ${l+1}-${s.length} omitted)`:``;return`${f}${d.join(`
|
|
158
|
+
`)}${p}`}function b(e,t){let n={cwd:e,encoding:`utf8`,timeout:3e4},i=(0,r.execFileSync)(`git`,[`ls-remote`,`--heads`,`--tags`,`origin`,t],n).trim();if(i.length===0)throw Error(`[regression-impact] Ref '${t}' not found on origin as branch or tag.`);let a=i.split(`
|
|
159
|
+
`),o=a.some(e=>e.endsWith(`\trefs/heads/${t}`)),s=a.some(e=>e.endsWith(`\trefs/tags/${t}`));if(o)return(0,r.execFileSync)(`git`,[`fetch`,`origin`,`+refs/heads/${t}:refs/remotes/origin/${t}`],n),{kind:`branch`,ref:`origin/${t}`};if(s)return(0,r.execFileSync)(`git`,[`fetch`,`origin`,`+refs/tags/${t}:refs/tags/${t}`],n),{kind:`tag`,ref:`refs/tags/${t}`};throw Error(`[regression-impact] Unable to classify '${t}' from ls-remote output.`)}function x(e,t){try{return b(e,t).ref}catch(e){throw Error(`[regression-impact] Failed to resolve anchor '${t}'. Ensure the branch or tag exists on origin and the remote is reachable.\nCause: ${String(e)}`,{cause:e})}}function S(e,t){let n={cwd:e,encoding:`utf8`,timeout:3e4};try{return(0,r.execFileSync)(`git`,[`rev-parse`,`--verify`,t],n),t}catch{}try{return b(e,t).ref}catch(e){throw Error(`[regression-impact] Compare ref '${t}' not found locally or on origin. Ensure the branch or tag exists before running regression analysis.\nCause: ${String(e)}`,{cause:e})}}function C(e,t,n){let i={cwd:e,encoding:`utf8`,timeout:3e4,maxBuffer:5242880},a=S(e,t),o=(0,r.execFileSync)(`git`,[`diff`,`--name-only`,`${n}...${a}`],i).trim().split(`
|
|
160
|
+
`).filter(e=>e.length>0);return{files:[...new Set(o)],description:`${a} vs ${n}`}}function w(e){let t={cwd:e,encoding:`utf8`,timeout:3e4},n=[(0,r.execSync)(`git diff --name-only`,t).trim(),(0,r.execSync)(`git diff --name-only --cached`,t).trim(),(0,r.execSync)(`git ls-files --others --exclude-standard`,t).trim()].flatMap(e=>e.split(`
|
|
161
|
+
`)).filter(e=>e.length>0);return{files:[...new Set(n)],description:`uncommitted (unstaged + staged + untracked)`}}function T(e,t,n,i,a=!1){if(e.length===0)return``;let o={cwd:g(t),encoding:`utf8`,timeout:3e4};try{if(a)return[(0,r.execFileSync)(`git`,[`diff`,`--`,...e],o).trim(),(0,r.execFileSync)(`git`,[`diff`,`--cached`,`--`,...e],o).trim()].filter(Boolean).join(`
|
|
162
|
+
`)||`(diff unavailable)`;let s=S(t,n);return(0,r.execFileSync)(`git`,[`diff`,`${i}...${s}`,`--`,...e],o).trim()}catch{return`(diff unavailable)`}}function E(e,t,n,r,i){return Object.fromEntries(e.map(e=>[e,T([e],t,n,r,i)]))}function D(e,t,n=!1){let i={cwd:e,encoding:`utf8`,timeout:1e4};try{if(n){let e=(0,r.execFileSync)(`git`,[`log`,`${t}..HEAD`,`--format=%s`],i).trim();return e.length>0?e.split(`
|
|
163
|
+
`).filter(e=>e.length>0):[]}return(0,r.execFileSync)(`git`,[`log`,`${t}..HEAD`,`--format=%h%n%s%n%b`],i).trim().split(``).map(e=>O(e)).filter(e=>e.length>0)}catch{return[]}}function O(e){let t=e.trim();if(t.length===0)return``;let n=t.indexOf(`
|
|
164
164
|
`),r=n===-1?t:t.slice(0,n).trim(),i=n===-1?``:t.slice(n+1),a=i.indexOf(`
|
|
165
|
-
`),o=a===-1?i.trim():i.slice(0,a).trim(),s=a===-1?``:i.slice(a+1).trim();return s.length===0?o:s.length<=800?`${o}\n${s}`:`${o}\n${s.slice(0,800)}\n… (commit message truncated — run \`git show -s --format=%B ${r}\` to read the full message)`}function
|
|
165
|
+
`),o=a===-1?i.trim():i.slice(0,a).trim(),s=a===-1?``:i.slice(a+1).trim();return s.length===0?o:s.length<=800?`${o}\n${s}`:`${o}\n${s.slice(0,800)}\n… (commit message truncated — run \`git show -s --format=%B ${r}\` to read the full message)`}function k(e){return e.length===0?`(none)`:e.map((e,t)=>{let[n,...r]=e.split(`
|
|
166
166
|
`),i=r.map(e=>` ${e}`).join(`
|
|
167
167
|
`),a=r.length>0?`\n${i}`:``;return`${t+1}. ${n}${a}`}).join(`
|
|
168
|
-
`)}function
|
|
169
|
-
`).length}catch{return 0}}function D(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:T(e,n,s),authorCommits:r.length>0?E(e,n,s,t):0,bugFixCommits:E(e,n,s,`--grep="fix:"`),revertCommits:E(e,n,s,`--grep="revert"`)}}return c}function O(e){let t=/(\d+) insertion/.exec(e),n=/(\d+) deletion/.exec(e);return(t===null?0:Number.parseInt(t[1],10))+(n===null?0:Number.parseInt(n[1],10))}function k(e,t,n,i){let a={cwd:e,encoding:`utf8`,timeout:3e4,maxBuffer:5242880};try{if(i){let e=(0,r.execFileSync)(`git`,[`diff`,`--shortstat`],a).trim(),t=(0,r.execFileSync)(`git`,[`diff`,`--shortstat`,`--cached`],a).trim();return O(e)+O(t)}let o=g(e,t);return O((0,r.execFileSync)(`git`,[`diff`,`--shortstat`,`${n}...${o}`],a).trim())}catch{return 0}}Object.defineProperty(e,`BEHAVIOR_REGRESSION_SCORE_THRESHOLD`,{enumerable:!0,get:function(){return 7}}),Object.defineProperty(e,`COMPOSE_VERIFY_MAX_BUDGET_USD`,{enumerable:!0,get:function(){return 1}}),Object.defineProperty(e,`COMPOSE_VERIFY_MAX_TURNS`,{enumerable:!0,get:function(){return 30}}),Object.defineProperty(e,`COMPOSE_VERIFY_MODEL`,{enumerable:!0,get:function(){return`claude-sonnet-4-6`}}),Object.defineProperty(e,`CROSS_COMPONENT_CONSUMER_MAX_BUDGET_USD`,{enumerable:!0,get:function(){return 6}}),Object.defineProperty(e,`CROSS_COMPONENT_CONSUMER_MAX_TURNS`,{enumerable:!0,get:function(){return 80}}),Object.defineProperty(e,`CROSS_COMPONENT_MAX_BUDGET_USD`,{enumerable:!0,get:function(){return 4}}),Object.defineProperty(e,`CROSS_COMPONENT_MAX_TURNS`,{enumerable:!0,get:function(){return 60}}),Object.defineProperty(e,`CROSS_COMPONENT_MODEL`,{enumerable:!0,get:function(){return`claude-sonnet-4-6`}}),Object.defineProperty(e,`CROSS_COMPONENT_REGRESSION_SCORE_THRESHOLD`,{enumerable:!0,get:function(){return 7}}),Object.defineProperty(e,`HUNT_FIRST_BLAST_RADIUS_MAX_SYMBOL_LOOKUPS`,{enumerable:!0,get:function(){return 200}}),Object.defineProperty(e,`HUNT_FIRST_HUNTER_CONCURRENCY`,{enumerable:!0,get:function(){return 4}}),Object.defineProperty(e,`HUNT_FIRST_HUNTER_MAX_BUDGET_USD`,{enumerable:!0,get:function(){return 4}}),Object.defineProperty(e,`HUNT_FIRST_HUNTER_MAX_TURNS`,{enumerable:!0,get:function(){return 40}}),Object.defineProperty(e,`HUNT_FIRST_HUNTER_MODEL`,{enumerable:!0,get:function(){return`claude-sonnet-4-6`}}),Object.defineProperty(e,`HUNT_FIRST_PANEL_FILE_THRESHOLD`,{enumerable:!0,get:function(){return 8}}),Object.defineProperty(e,`HUNT_FIRST_PANEL_LINE_THRESHOLD`,{enumerable:!0,get:function(){return 300}}),Object.defineProperty(e,`HUNT_FIRST_SCORING_MAX_BUDGET_USD`,{enumerable:!0,get:function(){return 2}}),Object.defineProperty(e,`HUNT_FIRST_SCORING_MAX_TURNS`,{enumerable:!0,get:function(){return 15}}),Object.defineProperty(e,`HUNT_FIRST_SENTINEL_FLOW_ID`,{enumerable:!0,get:function(){return`uncatalogued`}}),Object.defineProperty(e,`HUNT_FIRST_SENTINEL_FLOW_NAME`,{enumerable:!0,get:function(){return`Uncatalogued`}}),Object.defineProperty(e,`REGRESSION_ADJ_MAX_BUDGET_USD`,{enumerable:!0,get:function(){return 4}}),Object.defineProperty(e,`REGRESSION_ADJ_MAX_TURNS`,{enumerable:!0,get:function(){return 35}}),Object.defineProperty(e,`REGRESSION_CATALOG_LOG_PROMPT`,{enumerable:!0,get:function(){return!1}}),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_DEV_ARTIFACT_DIR`,{enumerable:!0,get:function(){return``}}),Object.defineProperty(e,`REGRESSION_E2E_CATALOG_MAX_BUDGET_USD`,{enumerable:!0,get:function(){return 4}}),Object.defineProperty(e,`REGRESSION_E2E_CATALOG_MAX_TURNS`,{enumerable:!0,get:function(){return 100}}),Object.defineProperty(e,`REGRESSION_E2E_CATALOG_MODEL`,{enumerable:!0,get:function(){return`claude-sonnet-4-6`}}),Object.defineProperty(e,`REGRESSION_E2E_CATALOG_SAVE_REPORT_FILES`,{enumerable:!0,get:function(){return!1}}),Object.defineProperty(e,`REGRESSION_E2E_CATALOG_TARGET_COUNT`,{enumerable:!0,get:function(){return 20}}),Object.defineProperty(e,`REGRESSION_E2E_CONNECTION_MAX_BUDGET_USD`,{enumerable:!0,get:function(){return 2}}),Object.defineProperty(e,`REGRESSION_E2E_CONNECTION_MAX_TURNS`,{enumerable:!0,get:function(){return 10}}),Object.defineProperty(e,`REGRESSION_FIRST_CATEGORY_MAX_TURNS`,{enumerable:!0,get:function(){return 30}}),Object.defineProperty(e,`REGRESSION_FIRST_DIFF_MAX_CHARS`,{enumerable:!0,get:function(){return 4e5}}),Object.defineProperty(e,`REGRESSION_FIRST_GENERALIST_MAX_TURNS`,{enumerable:!0,get:function(){return 45}}),Object.defineProperty(e,`REGRESSION_FIRST_LOG_SUBAGENTS`,{enumerable:!0,get:function(){return!1}}),Object.defineProperty(e,`REGRESSION_FIRST_MAX_BUDGET_USD`,{enumerable:!0,get:function(){return 14}}),Object.defineProperty(e,`REGRESSION_FIRST_MAX_TURNS`,{enumerable:!0,get:function(){return 60}}),Object.defineProperty(e,`REGRESSION_FIRST_MODEL`,{enumerable:!0,get:function(){return`claude-sonnet-4-6`}}),Object.defineProperty(e,`REGRESSION_FIRST_POST_EXPERIMENTAL`,{enumerable:!0,get:function(){return!1}}),Object.defineProperty(e,`REGRESSION_FIRST_PRODUCT_INTENT_MAX_TURNS`,{enumerable:!0,get:function(){return 45}}),Object.defineProperty(e,`REGRESSION_FIRST_SENTINEL_FLOW_ID`,{enumerable:!0,get:function(){return`regression-first--uncatalogued`}}),Object.defineProperty(e,`REGRESSION_FIRST_SENTINEL_FLOW_NAME`,{enumerable:!0,get:function(){return`Uncatalogued (regression-first)`}}),Object.defineProperty(e,`REGRESSION_FIRST_SINGLE_PANEL_DIFF_MAX_CHARS`,{enumerable:!0,get:function(){return 12e4}}),Object.defineProperty(e,`REGRESSION_FIRST_UI_MAX_TURNS`,{enumerable:!0,get:function(){return 45}}),Object.defineProperty(e,`REGRESSION_FIRST_UI_SAMPLES`,{enumerable:!0,get:function(){return 3}}),Object.defineProperty(e,`REGRESSION_FIRST_WRITE_DETECT_FILE`,{enumerable:!0,get:function(){return!1}}),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 50}}),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_CONTRACT_MODE`,{enumerable:!0,get:function(){return!0}}),Object.defineProperty(e,`REGRESSION_IMPACT_DEEP_MAX_BUDGET_USD`,{enumerable:!0,get:function(){return 2}}),Object.defineProperty(e,`REGRESSION_IMPACT_DEEP_MAX_TURNS`,{enumerable:!0,get:function(){return 40}}),Object.defineProperty(e,`REGRESSION_IMPACT_DEEP_MODE`,{enumerable:!0,get:function(){return`dedup`}}),Object.defineProperty(e,`REGRESSION_IMPACT_DEEP_MODEL`,{enumerable:!0,get:function(){return`claude-sonnet-4-6`}}),Object.defineProperty(e,`REGRESSION_IMPACT_DEEP_PASS1_BATCH_SIZE`,{enumerable:!0,get:function(){return 10}}),Object.defineProperty(e,`REGRESSION_IMPACT_DEEP_PASS1_CONCURRENCY`,{enumerable:!0,get:function(){return 5}}),Object.defineProperty(e,`REGRESSION_IMPACT_DEEP_PASS2_CONCURRENCY`,{enumerable:!0,get:function(){return 10}}),Object.defineProperty(e,`REGRESSION_IMPACT_DEV_MAPPING_SNAPSHOT`,{enumerable:!0,get:function(){return!1}}),Object.defineProperty(e,`REGRESSION_IMPACT_HAIKU_MODEL`,{enumerable:!0,get:function(){return`claude-haiku-4-5-20251001`}}),Object.defineProperty(e,`REGRESSION_IMPACT_LOG_DEEP_PROMPT`,{enumerable:!0,get:function(){return!1}}),Object.defineProperty(e,`REGRESSION_IMPACT_LOG_MAPPING_PROMPT`,{enumerable:!0,get:function(){return!1}}),Object.defineProperty(e,`REGRESSION_IMPACT_MAPPING_BATCH_SIZE`,{enumerable:!0,get:function(){return 5}}),Object.defineProperty(e,`REGRESSION_IMPACT_MAPPING_CONCURRENCY`,{enumerable:!0,get:function(){return 10}}),Object.defineProperty(e,`REGRESSION_IMPACT_MAPPING_FILE_DIFF_MAX_CHARS`,{enumerable:!0,get:function(){return 8e3}}),Object.defineProperty(e,`REGRESSION_IMPACT_MAPPING_STRATEGY`,{enumerable:!0,get:function(){return`shallow`}}),Object.defineProperty(e,`REGRESSION_IMPACT_MAPPING_SYMBOL_TRACING`,{enumerable:!0,get:function(){return!0}}),Object.defineProperty(e,`REGRESSION_IMPACT_MAPPING_TRACING_BUDGET`,{enumerable:!0,get:function(){return!0}}),Object.defineProperty(e,`REGRESSION_IMPACT_PASS2_GROUPED`,{enumerable:!0,get:function(){return!0}}),Object.defineProperty(e,`REGRESSION_IMPACT_PASS2_GROUP_DIFF_MAX_CHARS`,{enumerable:!0,get:function(){return 12e4}}),Object.defineProperty(e,`REGRESSION_IMPACT_PASS2_MAX_GROUP_SIZE`,{enumerable:!0,get:function(){return 5}}),Object.defineProperty(e,`REGRESSION_IMPACT_PASS2_MAX_SUBGROUPS`,{enumerable:!0,get:function(){return 8}}),Object.defineProperty(e,`REGRESSION_IMPACT_PASS2_MIN_OVERLAP`,{enumerable:!0,get:function(){return .4}}),Object.defineProperty(e,`REGRESSION_IMPACT_RESIDUAL_BATCH_SIZE`,{enumerable:!0,get:function(){return 5}}),Object.defineProperty(e,`REGRESSION_IMPACT_RESIDUAL_CONCURRENCY`,{enumerable:!0,get:function(){return 10}}),Object.defineProperty(e,`REGRESSION_IMPACT_RESIDUAL_ROUGH_MAP`,{enumerable:!0,get:function(){return!0}}),Object.defineProperty(e,`REGRESSION_IMPACT_ROUGH_MAP_CAP`,{enumerable:!0,get:function(){return 4}}),Object.defineProperty(e,`REGRESSION_IMPACT_SHALLOW_DIFF_MAX_CHARS`,{enumerable:!0,get:function(){return 2e4}}),Object.defineProperty(e,`REGRESSION_IMPACT_SKIP_PASS1`,{enumerable:!0,get:function(){return!0}}),Object.defineProperty(e,`REGRESSION_IMPACT_SONNET_MODEL`,{enumerable:!0,get:function(){return`claude-sonnet-4-6`}}),Object.defineProperty(e,`REGRESSION_IMPACT_STOP_AFTER_MAPPING`,{enumerable:!0,get:function(){return!1}}),Object.defineProperty(e,`REGRESSION_IMPACT_STOP_AFTER_PASS1`,{enumerable:!0,get:function(){return!1}}),Object.defineProperty(e,`REGRESSION_LOG_COST`,{enumerable:!0,get:function(){return a}}),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,`capDiffForEmbed`,{enumerable:!0,get:function(){return s}}),Object.defineProperty(e,`ensureAnchorRef`,{enumerable:!0,get:function(){return h}}),Object.defineProperty(e,`ensureCompareBranchRef`,{enumerable:!0,get:function(){return g}}),Object.defineProperty(e,`formatCommitMessagesBlock`,{enumerable:!0,get:function(){return C}}),Object.defineProperty(e,`getAuthorEmail`,{enumerable:!0,get:function(){return w}}),Object.defineProperty(e,`getChangedFiles`,{enumerable:!0,get:function(){return _}}),Object.defineProperty(e,`getChangedLineCount`,{enumerable:!0,get:function(){return k}}),Object.defineProperty(e,`getCommitMessages`,{enumerable:!0,get:function(){return x}}),Object.defineProperty(e,`getCurrentBranch`,{enumerable:!0,get:function(){return c}}),Object.defineProperty(e,`getDiffForFiles`,{enumerable:!0,get:function(){return y}}),Object.defineProperty(e,`getGitSignalsForFiles`,{enumerable:!0,get:function(){return D}}),Object.defineProperty(e,`getHeadSha`,{enumerable:!0,get:function(){return l}}),Object.defineProperty(e,`getPerFileDiffs`,{enumerable:!0,get:function(){return b}}),Object.defineProperty(e,`getRepoRoot`,{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,`getUncommittedFiles`,{enumerable:!0,get:function(){return v}}),Object.defineProperty(e,`resolveRefSha`,{enumerable:!0,get:function(){return d}}),Object.defineProperty(e,`shouldLogDiagnostics`,{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,`showFileAtRef`,{enumerable:!0,get:function(){return f}}),Object.defineProperty(e,`showFileRangeAtRef`,{enumerable:!0,get:function(){return p}})})),$R=s((e=>{let t=_R(),n=QR();function r(){return process.env.ANTHROPIC_TRANSPORT===`direct`?`direct`:`proxy`}function i(e){let t=`x-request-id: `+e.requestId;return r()===`direct`?{ANTHROPIC_BASE_URL:void 0,ANTHROPIC_AUTH_TOKEN:void 0,ANTHROPIC_CUSTOM_HEADERS:t}:{ANTHROPIC_BASE_URL:e.proxyUrl,ANTHROPIC_AUTH_TOKEN:e.jwtToken,ANTHROPIC_CUSTOM_HEADERS:t}}let a=!1;function o(e){a=e}function s(){return new Date().toISOString()}function c(e){return typeof e==`string`?e:Array.isArray(e)?e.map(e=>{let t=e;return typeof t.text==`string`?t.text:JSON.stringify(t)}).join(` | `):e===void 0?``:JSON.stringify(e)}function l(e,t){let n=e.replaceAll(/\r\n|[\n\r]/g,` `);return n.length>t?`${n.slice(0,t)}...`:n}function u(e,n){a&&t.logger.info.defaultLog(`[${s()}] [agent-log] [${e}] cwd (rootPath): ${n}`)}function d(e){let t=String(e.name??``),n=e.input;return`tool: ${t} ${l(n===void 0?``:JSON.stringify(n),200)}`}function f(e){return typeof e.text==`string`&&e.text.trim().length>0?`text (${e.text.length} chars): ${l(e.text,200)}`:null}function p(e){let t=typeof e.thinking==`string`?e.thinking:``;return`thinking (${t.length} chars): ${l(t,200)}`}function m(e){let t=e.is_error===!0?`ERROR`:`ok`,n=c(e.content);return`tool_result: ${t} (${n.length} chars): ${l(n,200)}`}function h(e){switch(String(e.type??``)){case`tool_use`:return d(e);case`text`:return f(e);case`thinking`:return p(e);case`tool_result`:return m(e);default:return null}}function g(e,n,r){if(!(!a||r===void 0||r.length===0))for(let i of r){let r=h(i);r!==null&&t.logger.info.defaultLog(`[${s()}] [agent-log] [${e}] Turn ${n} — ${r}`)}}function _(e){return e.map(e=>`${e.name} (${e.flowId})`).join(` | `)}function v(e,n,r){if(a){t.logger.info.defaultLog(`[${s()}] [agent-log] [${e}] split BEFORE: ${n.flows.length} flow(s), ${n.diffChars} diff chars (over cap) — [${_(n.flows)}]`);for(let[n,i]of r.entries()){let a=i.isTruncated?` (TRUNCATED — irreducible/hard-stop fallback)`:``;t.logger.info.defaultLog(`[${s()}] [agent-log] [${e}] split AFTER sub-group ${n+1}/${r.length}: ${i.flows.length} flow(s), ${i.diffChars} diff chars${a} — [${_(i.flows)}]`)}}}let y={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`}}},b={type:`object`,additionalProperties:!1,required:[`flows`,`projectSummary`,`projectType`,`detectedFlowCount`],properties:{flows:{type:`array`,items:{type:`object`,required:[`name`,`description`,`importance`,`importanceReason`,`composedOf`,`scoring`,`productFlow`],properties:{flowId:{type:`string`},name:{type:`string`},description:{type:`string`},importance:{type:`string`,enum:[`CRITICAL`,`HIGH`,`MEDIUM`,`LOW`]},importanceReason:{type:`string`},rank:{type:`number`},scoring:{type:`object`,required:[`riskScore`,`riskReason`,`blastRadius`,`blastReason`,`finalScore`],properties:{riskScore:{type:`number`},riskReason:{type:`string`},blastRadius:{type:`number`},blastReason:{type:`string`},finalScore:{type:`number`}}},productFlow:{type:`object`,required:[`trigger`,`steps`,`outcome`],properties:{trigger:{type:`string`},outcome:{type:`string`},steps:{type:`array`,items:{type:`object`,required:[`actor`,`action`,`outcome`],properties:{actor:{type:`string`},action:{type:`string`},outcome:{type:`string`}}}}}},composedOf:{type:`array`,items:{type:`object`,additionalProperties:!1,required:[`catalogId`,`repoSlug`,`perRepoFlowId`,`perRepoFlowName`],properties:{catalogId:{type:`string`},repoSlug:{type:`string`},perRepoFlowId:{type:`string`},perRepoFlowName:{type:`string`}}}}}}},projectSummary:{type:`string`},projectType:{type:`string`},detectedFlowCount:{type:`number`}}},x={type:`object`,additionalProperties:!1,required:[`guesses`],properties:{guesses:{type:`array`,items:{type:`object`}}}},S={type:`object`,additionalProperties:!1,required:[`sourceFiles`],properties:{sourceFiles:{type:`array`,items:{type:`string`}}}},C={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`}}}},w={type:`object`,additionalProperties:!1,required:[`flows`],properties:{flows:{type:`array`,items:{type:`object`}}}},T={type:`object`,additionalProperties:!1,required:[`fileFlowMapping`],properties:{fileFlowMapping:{type:`array`,items:{type:`object`}}}},E={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`}}}}},D={type:`object`,additionalProperties:!1,required:[`calledModules`],properties:{calledModules:{type:`array`,items:{type:`string`}}}},O={type:`object`,additionalProperties:!1,required:[`findings`],properties:{findings:{type:`array`,items:{type:`object`,additionalProperties:!1,required:[`title`,`file`,`hunkExcerpt`,`behaviorBefore`,`behaviorAfter`,`confidence`,`rationale`,`category`],properties:{title:{type:`string`},file:{type:`string`},hunkExcerpt:{type:`string`},behaviorBefore:{type:`string`},behaviorAfter:{type:`string`},confidence:{type:`string`,enum:[`high`,`low`]},rationale:{type:`string`},category:{type:`string`}}}}}},k={type:`object`,additionalProperties:!1,required:[`scores`],properties:{scores:{type:`array`,items:{type:`object`,additionalProperties:!1,required:[`index`,`severity`,`verdictScore`,`verdictReason`],properties:{index:{type:`number`},severity:{type:`string`,enum:[`NONE`,`LOW`,`MEDIUM`,`HIGH`,`CRITICAL`]},verdictScore:{type:`number`},verdictReason:{type:`string`}}}}}},A={cacheReadTokens:0,cacheCreationTokens:0,inputTokens:0,outputTokens:0};function j(e){let t=0,n=0,r=0,i=0;if(typeof e!=`object`||!e)return{cacheReadTokens:t,cacheCreationTokens:n,inputTokens:r,outputTokens:i};let a=e.modelUsage;if(typeof a!=`object`||!a)return{cacheReadTokens:t,cacheCreationTokens:n,inputTokens:r,outputTokens:i};for(let e of Object.values(a)){if(typeof e!=`object`||!e)continue;let a=e;t+=typeof a.cacheReadInputTokens==`number`?a.cacheReadInputTokens:0,n+=typeof a.cacheCreationInputTokens==`number`?a.cacheCreationInputTokens:0,r+=typeof a.inputTokens==`number`?a.inputTokens:0,i+=typeof a.outputTokens==`number`?a.outputTokens:0}return{cacheReadTokens:t,cacheCreationTokens:n,inputTokens:r,outputTokens:i}}function M(e,r){if(!n.shouldLogDiagnostics)return;let i=r.cacheReadTokens+r.cacheCreationTokens+r.inputTokens,a=i>0?r.cacheReadTokens/i*100:0;t.logger.info.defaultLog(`[regression-impact] ${e} tokens: cache_read=${r.cacheReadTokens} cache_creation=${r.cacheCreationTokens} input_uncached=${r.inputTokens} output=${r.outputTokens} cache_hit=${a.toFixed(1)}%`)}function ee(e,t){let n=j(t);return M(e,n),n}Object.defineProperty(e,`CATALOG_OUTPUT_SCHEMA`,{enumerable:!0,get:function(){return y}}),Object.defineProperty(e,`DEPENDENCY_TRACER_OUTPUT_SCHEMA`,{enumerable:!0,get:function(){return D}}),Object.defineProperty(e,`E2E_CATALOG_OUTPUT_SCHEMA`,{enumerable:!0,get:function(){return b}}),Object.defineProperty(e,`FILE_FLOW_MAPPING_OUTPUT_SCHEMA`,{enumerable:!0,get:function(){return T}}),Object.defineProperty(e,`HUNT_FINDING_OUTPUT_SCHEMA`,{enumerable:!0,get:function(){return O}}),Object.defineProperty(e,`HUNT_SCORING_OUTPUT_SCHEMA`,{enumerable:!0,get:function(){return k}}),Object.defineProperty(e,`PRE_FILTER_OUTPUT_SCHEMA`,{enumerable:!0,get:function(){return S}}),Object.defineProperty(e,`RESIDUAL_ROUGH_MAP_OUTPUT_SCHEMA`,{enumerable:!0,get:function(){return x}}),Object.defineProperty(e,`SONNET_DEEP_GROUPED_OUTPUT_SCHEMA`,{enumerable:!0,get:function(){return w}}),Object.defineProperty(e,`SONNET_DEEP_OUTPUT_SCHEMA`,{enumerable:!0,get:function(){return C}}),Object.defineProperty(e,`VERDICT_CALIBRATOR_OUTPUT_SCHEMA`,{enumerable:!0,get:function(){return E}}),Object.defineProperty(e,`ZERO_TOKENS`,{enumerable:!0,get:function(){return A}}),Object.defineProperty(e,`buildAnthropicSdkEnv`,{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,`extractCacheTokens`,{enumerable:!0,get:function(){return j}}),Object.defineProperty(e,`logAgentActivity`,{enumerable:!0,get:function(){return g}}),Object.defineProperty(e,`logAgentCwd`,{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,`logAgentGroupSplit`,{enumerable:!0,get:function(){return v}}),Object.defineProperty(e,`logCacheTokens`,{enumerable:!0,get:function(){return M}}),Object.defineProperty(e,`logCacheTokensFromMessage`,{enumerable:!0,get:function(){return ee}}),Object.defineProperty(e,`setAgentLogEnabled`,{enumerable:!0,get:function(){return o}})})),ez=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.type===`system`&&e.subtype===`api_retry`}function a(e){return e.type===`system`&&e.subtype===`model_refusal_fallback`}function o(e){return e.subtype!==`success`}function s(e){let t=e.tool_input?.file_path;return typeof t==`string`?t:``}function c(e){let t=e.tool_input?.command;return typeof t==`string`?t:``}let l=/(\u009B|\u001B\[)[0-?]*[ -/]*[@-~]/g;function u(e){return e.replaceAll(l,``)}function d(e){let t=e;return u(((t.stdout??``)+(t.stderr??``)).trim())}function f(e){let t=e;return Array.isArray(t.message?.content)?t.message.content:void 0}function p(e){return e}Object.defineProperty(e,`getExecOutput`,{enumerable:!0,get:function(){return d}}),Object.defineProperty(e,`getMessageContentBlocks`,{enumerable:!0,get:function(){return f}}),Object.defineProperty(e,`getSystemInitData`,{enumerable:!0,get:function(){return p}}),Object.defineProperty(e,`getToolInputCommand`,{enumerable:!0,get:function(){return c}}),Object.defineProperty(e,`getToolInputFilePath`,{enumerable:!0,get:function(){return s}}),Object.defineProperty(e,`isApiRetryMessage`,{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,`isErrorResult`,{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,`isModelRefusalFallbackMessage`,{enumerable:!0,get:function(){return a}}),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 u}})})),tz=s((e=>{let t=`catalog_emit`,n=`emit_catalog_flow`,r=`emit_catalog_summary`,i=`mcp__${t}__${n}`,a=`mcp__${t}__${r}`;var o=class{flows=[];projectSummary=``;projectType=`unknown`;detectedEntryCount=0;addFlow(e){let t=typeof e.name==`string`?e.name.trim().toLowerCase():``,n=t.length>0?this.flows.findIndex(e=>(typeof e.name==`string`?e.name.trim().toLowerCase():``)===t):-1;return n>=0?this.flows[n]=e:this.flows.push(e),this.flows.length}setSummary(e,t,n){this.projectSummary=e,this.projectType=t,this.detectedEntryCount=n}};function s(e,t){let n;try{n=JSON.parse(t)}catch{return{accepted:!1,error:`flow was not valid JSON — re-send a single flow object as a JSON string`}}return typeof n!=`object`||!n||Array.isArray(n)?{accepted:!1,error:`flow must be a single JSON object, not an array or scalar`}:{accepted:!0,count:e.addFlow(n)}}Object.defineProperty(e,`CATALOG_EMIT_MCP_SERVER_NAME`,{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,`CatalogEmitCollector`,{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,`EMIT_FLOW_TOOL`,{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,`EMIT_SUMMARY_TOOL`,{enumerable:!0,get:function(){return r}}),Object.defineProperty(e,`MCP_EMIT_FLOW_TOOL`,{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,`MCP_EMIT_SUMMARY_TOOL`,{enumerable:!0,get:function(){return a}}),Object.defineProperty(e,`acceptEmittedFlow`,{enumerable:!0,get:function(){return s}})})),nz=s((e=>{let t=ur(),n=QR(),r=t.__toESM(ie()),i=`## Dependency roots (multi-root projects)
|
|
168
|
+
`)}function A(e,t,n){let i={cwd:e,encoding:`utf8`,timeout:1e4};try{return n?(0,r.execSync)(`git config user.email`,i).trim():(0,r.execSync)(`git log -1 --format=%ae ${t}`,i).trim()}catch{return``}}function j(e,t,n){let i={cwd:e,encoding:`utf8`,timeout:1e4};try{let e=(0,r.execSync)(`git log -1 --format=%ci ${n} -- "${t}"`,i).trim();return e.length===0?0:Math.floor((Date.now()-new Date(e).getTime())/(1e3*60*60*24))}catch{return 0}}function M(e,t,n,i){let a={cwd:e,encoding:`utf8`,timeout:1e4};try{let e=(0,r.execSync)(`git log --oneline --since="90 days ago" ${n} ${i} -- "${t}"`,a).trim();return e.length===0?0:e.split(`
|
|
169
|
+
`).length}catch{return 0}}function ee(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:j(e,n,s),authorCommits:r.length>0?M(e,n,s,t):0,bugFixCommits:M(e,n,s,`--grep="fix:"`),revertCommits:M(e,n,s,`--grep="revert"`)}}return c}function N(e){let t=/(\d+) insertion/.exec(e),n=/(\d+) deletion/.exec(e);return(t===null?0:Number.parseInt(t[1],10))+(n===null?0:Number.parseInt(n[1],10))}function te(e,t,n,i){let a={cwd:e,encoding:`utf8`,timeout:3e4,maxBuffer:5242880};try{if(i){let e=(0,r.execFileSync)(`git`,[`diff`,`--shortstat`],a).trim(),t=(0,r.execFileSync)(`git`,[`diff`,`--shortstat`,`--cached`],a).trim();return N(e)+N(t)}let o=S(e,t);return N((0,r.execFileSync)(`git`,[`diff`,`--shortstat`,`${n}...${o}`],a).trim())}catch{return 0}}Object.defineProperty(e,`BEHAVIOR_REGRESSION_SCORE_THRESHOLD`,{enumerable:!0,get:function(){return 7}}),Object.defineProperty(e,`COMPOSE_VERIFY_MAX_BUDGET_USD`,{enumerable:!0,get:function(){return 1}}),Object.defineProperty(e,`COMPOSE_VERIFY_MAX_TURNS`,{enumerable:!0,get:function(){return 30}}),Object.defineProperty(e,`COMPOSE_VERIFY_MODEL`,{enumerable:!0,get:function(){return`claude-sonnet-4-6`}}),Object.defineProperty(e,`CROSS_COMPONENT_CONSUMER_MAX_BUDGET_USD`,{enumerable:!0,get:function(){return 6}}),Object.defineProperty(e,`CROSS_COMPONENT_CONSUMER_MAX_TURNS`,{enumerable:!0,get:function(){return 80}}),Object.defineProperty(e,`CROSS_COMPONENT_MAX_BUDGET_USD`,{enumerable:!0,get:function(){return 4}}),Object.defineProperty(e,`CROSS_COMPONENT_MAX_TURNS`,{enumerable:!0,get:function(){return 60}}),Object.defineProperty(e,`CROSS_COMPONENT_MODEL`,{enumerable:!0,get:function(){return`claude-sonnet-4-6`}}),Object.defineProperty(e,`CROSS_COMPONENT_REGRESSION_SCORE_THRESHOLD`,{enumerable:!0,get:function(){return 7}}),Object.defineProperty(e,`HUNT_FIRST_BLAST_RADIUS_MAX_SYMBOL_LOOKUPS`,{enumerable:!0,get:function(){return 200}}),Object.defineProperty(e,`HUNT_FIRST_HUNTER_CONCURRENCY`,{enumerable:!0,get:function(){return 4}}),Object.defineProperty(e,`HUNT_FIRST_HUNTER_MAX_BUDGET_USD`,{enumerable:!0,get:function(){return 4}}),Object.defineProperty(e,`HUNT_FIRST_HUNTER_MAX_TURNS`,{enumerable:!0,get:function(){return 40}}),Object.defineProperty(e,`HUNT_FIRST_HUNTER_MODEL`,{enumerable:!0,get:function(){return`claude-sonnet-4-6`}}),Object.defineProperty(e,`HUNT_FIRST_PANEL_FILE_THRESHOLD`,{enumerable:!0,get:function(){return 8}}),Object.defineProperty(e,`HUNT_FIRST_PANEL_LINE_THRESHOLD`,{enumerable:!0,get:function(){return 300}}),Object.defineProperty(e,`HUNT_FIRST_SCORING_MAX_BUDGET_USD`,{enumerable:!0,get:function(){return 2}}),Object.defineProperty(e,`HUNT_FIRST_SCORING_MAX_TURNS`,{enumerable:!0,get:function(){return 15}}),Object.defineProperty(e,`HUNT_FIRST_SENTINEL_FLOW_ID`,{enumerable:!0,get:function(){return`uncatalogued`}}),Object.defineProperty(e,`HUNT_FIRST_SENTINEL_FLOW_NAME`,{enumerable:!0,get:function(){return`Uncatalogued`}}),Object.defineProperty(e,`REGRESSION_ADJ_MAX_BUDGET_USD`,{enumerable:!0,get:function(){return 4}}),Object.defineProperty(e,`REGRESSION_ADJ_MAX_TURNS`,{enumerable:!0,get:function(){return 35}}),Object.defineProperty(e,`REGRESSION_CATALOG_LOG_PROMPT`,{enumerable:!0,get:function(){return!1}}),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_DEV_ARTIFACT_DIR`,{enumerable:!0,get:function(){return``}}),Object.defineProperty(e,`REGRESSION_E2E_CATALOG_MAX_BUDGET_USD`,{enumerable:!0,get:function(){return 4}}),Object.defineProperty(e,`REGRESSION_E2E_CATALOG_MAX_TURNS`,{enumerable:!0,get:function(){return 100}}),Object.defineProperty(e,`REGRESSION_E2E_CATALOG_MODEL`,{enumerable:!0,get:function(){return`claude-sonnet-4-6`}}),Object.defineProperty(e,`REGRESSION_E2E_CATALOG_SAVE_REPORT_FILES`,{enumerable:!0,get:function(){return!1}}),Object.defineProperty(e,`REGRESSION_E2E_CATALOG_TARGET_COUNT`,{enumerable:!0,get:function(){return 20}}),Object.defineProperty(e,`REGRESSION_E2E_CONNECTION_MAX_BUDGET_USD`,{enumerable:!0,get:function(){return 2}}),Object.defineProperty(e,`REGRESSION_E2E_CONNECTION_MAX_TURNS`,{enumerable:!0,get:function(){return 10}}),Object.defineProperty(e,`REGRESSION_FIRST_CATEGORY_MAX_TURNS`,{enumerable:!0,get:function(){return 30}}),Object.defineProperty(e,`REGRESSION_FIRST_DIFF_MAX_CHARS`,{enumerable:!0,get:function(){return 4e5}}),Object.defineProperty(e,`REGRESSION_FIRST_GENERALIST_MAX_TURNS`,{enumerable:!0,get:function(){return 45}}),Object.defineProperty(e,`REGRESSION_FIRST_LOG_SUBAGENTS`,{enumerable:!0,get:function(){return!1}}),Object.defineProperty(e,`REGRESSION_FIRST_MAX_BUDGET_USD`,{enumerable:!0,get:function(){return 14}}),Object.defineProperty(e,`REGRESSION_FIRST_MAX_TURNS`,{enumerable:!0,get:function(){return 60}}),Object.defineProperty(e,`REGRESSION_FIRST_MODEL`,{enumerable:!0,get:function(){return`claude-sonnet-4-6`}}),Object.defineProperty(e,`REGRESSION_FIRST_POST_EXPERIMENTAL`,{enumerable:!0,get:function(){return!1}}),Object.defineProperty(e,`REGRESSION_FIRST_PRODUCT_INTENT_MAX_TURNS`,{enumerable:!0,get:function(){return 45}}),Object.defineProperty(e,`REGRESSION_FIRST_SENTINEL_FLOW_ID`,{enumerable:!0,get:function(){return`regression-first--uncatalogued`}}),Object.defineProperty(e,`REGRESSION_FIRST_SENTINEL_FLOW_NAME`,{enumerable:!0,get:function(){return`Uncatalogued (regression-first)`}}),Object.defineProperty(e,`REGRESSION_FIRST_SINGLE_PANEL_DIFF_MAX_CHARS`,{enumerable:!0,get:function(){return 12e4}}),Object.defineProperty(e,`REGRESSION_FIRST_UI_MAX_TURNS`,{enumerable:!0,get:function(){return 45}}),Object.defineProperty(e,`REGRESSION_FIRST_UI_SAMPLES`,{enumerable:!0,get:function(){return 3}}),Object.defineProperty(e,`REGRESSION_FIRST_WRITE_DETECT_FILE`,{enumerable:!0,get:function(){return!1}}),Object.defineProperty(e,`REGRESSION_HAIKU_REASONING`,{enumerable:!0,get:function(){return l}}),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 50}}),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_CONTRACT_MODE`,{enumerable:!0,get:function(){return!0}}),Object.defineProperty(e,`REGRESSION_IMPACT_DEEP_MAX_BUDGET_USD`,{enumerable:!0,get:function(){return 2}}),Object.defineProperty(e,`REGRESSION_IMPACT_DEEP_MAX_TURNS`,{enumerable:!0,get:function(){return 40}}),Object.defineProperty(e,`REGRESSION_IMPACT_DEEP_MODE`,{enumerable:!0,get:function(){return`dedup`}}),Object.defineProperty(e,`REGRESSION_IMPACT_DEEP_MODEL`,{enumerable:!0,get:function(){return`claude-sonnet-4-6`}}),Object.defineProperty(e,`REGRESSION_IMPACT_DEEP_PASS1_BATCH_SIZE`,{enumerable:!0,get:function(){return 10}}),Object.defineProperty(e,`REGRESSION_IMPACT_DEEP_PASS1_CONCURRENCY`,{enumerable:!0,get:function(){return 5}}),Object.defineProperty(e,`REGRESSION_IMPACT_DEEP_PASS2_CONCURRENCY`,{enumerable:!0,get:function(){return 10}}),Object.defineProperty(e,`REGRESSION_IMPACT_DEV_MAPPING_SNAPSHOT`,{enumerable:!0,get:function(){return!1}}),Object.defineProperty(e,`REGRESSION_IMPACT_HAIKU_MODEL`,{enumerable:!0,get:function(){return`claude-haiku-4-5-20251001`}}),Object.defineProperty(e,`REGRESSION_IMPACT_LOG_DEEP_PROMPT`,{enumerable:!0,get:function(){return!1}}),Object.defineProperty(e,`REGRESSION_IMPACT_LOG_MAPPING_PROMPT`,{enumerable:!0,get:function(){return!1}}),Object.defineProperty(e,`REGRESSION_IMPACT_MAPPING_BATCH_SIZE`,{enumerable:!0,get:function(){return 5}}),Object.defineProperty(e,`REGRESSION_IMPACT_MAPPING_CONCURRENCY`,{enumerable:!0,get:function(){return 10}}),Object.defineProperty(e,`REGRESSION_IMPACT_MAPPING_FILE_DIFF_MAX_CHARS`,{enumerable:!0,get:function(){return 8e3}}),Object.defineProperty(e,`REGRESSION_IMPACT_MAPPING_STRATEGY`,{enumerable:!0,get:function(){return`shallow`}}),Object.defineProperty(e,`REGRESSION_IMPACT_MAPPING_SYMBOL_TRACING`,{enumerable:!0,get:function(){return!0}}),Object.defineProperty(e,`REGRESSION_IMPACT_MAPPING_TRACING_BUDGET`,{enumerable:!0,get:function(){return!0}}),Object.defineProperty(e,`REGRESSION_IMPACT_PASS2_GROUPED`,{enumerable:!0,get:function(){return!0}}),Object.defineProperty(e,`REGRESSION_IMPACT_PASS2_GROUP_DIFF_MAX_CHARS`,{enumerable:!0,get:function(){return 12e4}}),Object.defineProperty(e,`REGRESSION_IMPACT_PASS2_MAX_GROUP_SIZE`,{enumerable:!0,get:function(){return 5}}),Object.defineProperty(e,`REGRESSION_IMPACT_PASS2_MAX_SUBGROUPS`,{enumerable:!0,get:function(){return 8}}),Object.defineProperty(e,`REGRESSION_IMPACT_PASS2_MIN_OVERLAP`,{enumerable:!0,get:function(){return .4}}),Object.defineProperty(e,`REGRESSION_IMPACT_RESIDUAL_BATCH_SIZE`,{enumerable:!0,get:function(){return 5}}),Object.defineProperty(e,`REGRESSION_IMPACT_RESIDUAL_CONCURRENCY`,{enumerable:!0,get:function(){return 10}}),Object.defineProperty(e,`REGRESSION_IMPACT_RESIDUAL_ROUGH_MAP`,{enumerable:!0,get:function(){return!0}}),Object.defineProperty(e,`REGRESSION_IMPACT_ROUGH_MAP_CAP`,{enumerable:!0,get:function(){return 4}}),Object.defineProperty(e,`REGRESSION_IMPACT_SHALLOW_DIFF_MAX_CHARS`,{enumerable:!0,get:function(){return 2e4}}),Object.defineProperty(e,`REGRESSION_IMPACT_SKIP_PASS1`,{enumerable:!0,get:function(){return!0}}),Object.defineProperty(e,`REGRESSION_IMPACT_SONNET_MODEL`,{enumerable:!0,get:function(){return`claude-sonnet-4-6`}}),Object.defineProperty(e,`REGRESSION_IMPACT_STOP_AFTER_MAPPING`,{enumerable:!0,get:function(){return!1}}),Object.defineProperty(e,`REGRESSION_IMPACT_STOP_AFTER_PASS1`,{enumerable:!0,get:function(){return!1}}),Object.defineProperty(e,`REGRESSION_LOG_COST`,{enumerable:!0,get:function(){return d}}),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_SONNET_ANALYZER_REASONING`,{enumerable:!0,get:function(){return s}}),Object.defineProperty(e,`REGRESSION_SONNET_SCORER_REASONING`,{enumerable:!0,get:function(){return c}}),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,`capDiffForEmbed`,{enumerable:!0,get:function(){return p}}),Object.defineProperty(e,`ensureAnchorRef`,{enumerable:!0,get:function(){return x}}),Object.defineProperty(e,`ensureCompareBranchRef`,{enumerable:!0,get:function(){return S}}),Object.defineProperty(e,`formatCommitMessagesBlock`,{enumerable:!0,get:function(){return k}}),Object.defineProperty(e,`getAuthorEmail`,{enumerable:!0,get:function(){return A}}),Object.defineProperty(e,`getChangedFiles`,{enumerable:!0,get:function(){return C}}),Object.defineProperty(e,`getChangedLineCount`,{enumerable:!0,get:function(){return te}}),Object.defineProperty(e,`getCommitMessages`,{enumerable:!0,get:function(){return D}}),Object.defineProperty(e,`getCurrentBranch`,{enumerable:!0,get:function(){return m}}),Object.defineProperty(e,`getDiffForFiles`,{enumerable:!0,get:function(){return T}}),Object.defineProperty(e,`getGitSignalsForFiles`,{enumerable:!0,get:function(){return ee}}),Object.defineProperty(e,`getHeadSha`,{enumerable:!0,get:function(){return h}}),Object.defineProperty(e,`getPerFileDiffs`,{enumerable:!0,get:function(){return E}}),Object.defineProperty(e,`getRepoRoot`,{enumerable:!0,get:function(){return g}}),Object.defineProperty(e,`getUncommittedFiles`,{enumerable:!0,get:function(){return w}}),Object.defineProperty(e,`resolveRefSha`,{enumerable:!0,get:function(){return _}}),Object.defineProperty(e,`shouldLogDiagnostics`,{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,`showFileAtRef`,{enumerable:!0,get:function(){return v}}),Object.defineProperty(e,`showFileRangeAtRef`,{enumerable:!0,get:function(){return y}})})),$R=s((e=>{let t=_R(),n=QR();function r(){return process.env.ANTHROPIC_TRANSPORT===`direct`?`direct`:`proxy`}function i(e){let t=`x-request-id: `+e.requestId;return r()===`direct`?{ANTHROPIC_BASE_URL:void 0,ANTHROPIC_AUTH_TOKEN:void 0,ANTHROPIC_CUSTOM_HEADERS:t}:{ANTHROPIC_BASE_URL:e.proxyUrl,ANTHROPIC_AUTH_TOKEN:e.jwtToken,ANTHROPIC_CUSTOM_HEADERS:t}}let a=!1;function o(e){a=e}function s(){return new Date().toISOString()}function c(e){return typeof e==`string`?e:Array.isArray(e)?e.map(e=>{let t=e;return typeof t.text==`string`?t.text:JSON.stringify(t)}).join(` | `):e===void 0?``:JSON.stringify(e)}function l(e,t){let n=e.replaceAll(/\r\n|[\n\r]/g,` `);return n.length>t?`${n.slice(0,t)}...`:n}function u(e,n){a&&t.logger.info.defaultLog(`[${s()}] [agent-log] [${e}] cwd (rootPath): ${n}`)}function d(e){let t=String(e.name??``),n=e.input;return`tool: ${t} ${l(n===void 0?``:JSON.stringify(n),200)}`}function f(e){return typeof e.text==`string`&&e.text.trim().length>0?`text (${e.text.length} chars): ${l(e.text,200)}`:null}function p(e){let t=typeof e.thinking==`string`?e.thinking:``;return`thinking (${t.length} chars): ${l(t,200)}`}function m(e){let t=e.is_error===!0?`ERROR`:`ok`,n=c(e.content);return`tool_result: ${t} (${n.length} chars): ${l(n,200)}`}function h(e){switch(String(e.type??``)){case`tool_use`:return d(e);case`text`:return f(e);case`thinking`:return p(e);case`tool_result`:return m(e);default:return null}}function g(e,n,r){if(!(!a||r===void 0||r.length===0))for(let i of r){let r=h(i);r!==null&&t.logger.info.defaultLog(`[${s()}] [agent-log] [${e}] Turn ${n} — ${r}`)}}function _(e){return e.map(e=>`${e.name} (${e.flowId})`).join(` | `)}function v(e,n,r){if(a){t.logger.info.defaultLog(`[${s()}] [agent-log] [${e}] split BEFORE: ${n.flows.length} flow(s), ${n.diffChars} diff chars (over cap) — [${_(n.flows)}]`);for(let[n,i]of r.entries()){let a=i.isTruncated?` (TRUNCATED — irreducible/hard-stop fallback)`:``;t.logger.info.defaultLog(`[${s()}] [agent-log] [${e}] split AFTER sub-group ${n+1}/${r.length}: ${i.flows.length} flow(s), ${i.diffChars} diff chars${a} — [${_(i.flows)}]`)}}}let y={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`}}},b={type:`object`,additionalProperties:!1,required:[`flows`,`projectSummary`,`projectType`,`detectedFlowCount`],properties:{flows:{type:`array`,items:{type:`object`,required:[`name`,`description`,`importance`,`importanceReason`,`composedOf`,`scoring`,`productFlow`],properties:{flowId:{type:`string`},name:{type:`string`},description:{type:`string`},importance:{type:`string`,enum:[`CRITICAL`,`HIGH`,`MEDIUM`,`LOW`]},importanceReason:{type:`string`},rank:{type:`number`},scoring:{type:`object`,required:[`riskScore`,`riskReason`,`blastRadius`,`blastReason`,`finalScore`],properties:{riskScore:{type:`number`},riskReason:{type:`string`},blastRadius:{type:`number`},blastReason:{type:`string`},finalScore:{type:`number`}}},productFlow:{type:`object`,required:[`trigger`,`steps`,`outcome`],properties:{trigger:{type:`string`},outcome:{type:`string`},steps:{type:`array`,items:{type:`object`,required:[`actor`,`action`,`outcome`],properties:{actor:{type:`string`},action:{type:`string`},outcome:{type:`string`}}}}}},composedOf:{type:`array`,items:{type:`object`,additionalProperties:!1,required:[`catalogId`,`repoSlug`,`perRepoFlowId`,`perRepoFlowName`],properties:{catalogId:{type:`string`},repoSlug:{type:`string`},perRepoFlowId:{type:`string`},perRepoFlowName:{type:`string`}}}}}}},projectSummary:{type:`string`},projectType:{type:`string`},detectedFlowCount:{type:`number`}}},x={type:`object`,additionalProperties:!1,required:[`guesses`],properties:{guesses:{type:`array`,items:{type:`object`}}}},S={type:`object`,additionalProperties:!1,required:[`sourceFiles`],properties:{sourceFiles:{type:`array`,items:{type:`string`}}}},C={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`}}}},w={type:`object`,additionalProperties:!1,required:[`flows`],properties:{flows:{type:`array`,items:{type:`object`}}}},T={type:`object`,additionalProperties:!1,required:[`fileFlowMapping`],properties:{fileFlowMapping:{type:`array`,items:{type:`object`}}}},E={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`}}}}},D={type:`object`,additionalProperties:!1,required:[`calledModules`],properties:{calledModules:{type:`array`,items:{type:`string`}}}},O={type:`object`,additionalProperties:!1,required:[`findings`],properties:{findings:{type:`array`,items:{type:`object`,additionalProperties:!1,required:[`title`,`file`,`hunkExcerpt`,`behaviorBefore`,`behaviorAfter`,`confidence`,`rationale`,`category`],properties:{title:{type:`string`},file:{type:`string`},hunkExcerpt:{type:`string`},behaviorBefore:{type:`string`},behaviorAfter:{type:`string`},confidence:{type:`string`,enum:[`high`,`low`]},rationale:{type:`string`},category:{type:`string`}}}}}},k={type:`object`,additionalProperties:!1,required:[`scores`],properties:{scores:{type:`array`,items:{type:`object`,additionalProperties:!1,required:[`index`,`severity`,`verdictScore`,`verdictReason`],properties:{index:{type:`number`},severity:{type:`string`,enum:[`NONE`,`LOW`,`MEDIUM`,`HIGH`,`CRITICAL`]},verdictScore:{type:`number`},verdictReason:{type:`string`}}}}}},A={cacheReadTokens:0,cacheCreationTokens:0,inputTokens:0,outputTokens:0};function j(e){let t=0,n=0,r=0,i=0;if(typeof e!=`object`||!e)return{cacheReadTokens:t,cacheCreationTokens:n,inputTokens:r,outputTokens:i};let a=e.modelUsage;if(typeof a!=`object`||!a)return{cacheReadTokens:t,cacheCreationTokens:n,inputTokens:r,outputTokens:i};for(let e of Object.values(a)){if(typeof e!=`object`||!e)continue;let a=e;t+=typeof a.cacheReadInputTokens==`number`?a.cacheReadInputTokens:0,n+=typeof a.cacheCreationInputTokens==`number`?a.cacheCreationInputTokens:0,r+=typeof a.inputTokens==`number`?a.inputTokens:0,i+=typeof a.outputTokens==`number`?a.outputTokens:0}return{cacheReadTokens:t,cacheCreationTokens:n,inputTokens:r,outputTokens:i}}function M(e,r){if(!n.shouldLogDiagnostics)return;let i=r.cacheReadTokens+r.cacheCreationTokens+r.inputTokens,a=i>0?r.cacheReadTokens/i*100:0;t.logger.info.defaultLog(`[regression-impact] ${e} tokens: cache_read=${r.cacheReadTokens} cache_creation=${r.cacheCreationTokens} input_uncached=${r.inputTokens} output=${r.outputTokens} cache_hit=${a.toFixed(1)}%`)}function ee(e,t){let n=j(t);return M(e,n),n}Object.defineProperty(e,`CATALOG_OUTPUT_SCHEMA`,{enumerable:!0,get:function(){return y}}),Object.defineProperty(e,`DEPENDENCY_TRACER_OUTPUT_SCHEMA`,{enumerable:!0,get:function(){return D}}),Object.defineProperty(e,`E2E_CATALOG_OUTPUT_SCHEMA`,{enumerable:!0,get:function(){return b}}),Object.defineProperty(e,`FILE_FLOW_MAPPING_OUTPUT_SCHEMA`,{enumerable:!0,get:function(){return T}}),Object.defineProperty(e,`HUNT_FINDING_OUTPUT_SCHEMA`,{enumerable:!0,get:function(){return O}}),Object.defineProperty(e,`HUNT_SCORING_OUTPUT_SCHEMA`,{enumerable:!0,get:function(){return k}}),Object.defineProperty(e,`PRE_FILTER_OUTPUT_SCHEMA`,{enumerable:!0,get:function(){return S}}),Object.defineProperty(e,`RESIDUAL_ROUGH_MAP_OUTPUT_SCHEMA`,{enumerable:!0,get:function(){return x}}),Object.defineProperty(e,`SONNET_DEEP_GROUPED_OUTPUT_SCHEMA`,{enumerable:!0,get:function(){return w}}),Object.defineProperty(e,`SONNET_DEEP_OUTPUT_SCHEMA`,{enumerable:!0,get:function(){return C}}),Object.defineProperty(e,`VERDICT_CALIBRATOR_OUTPUT_SCHEMA`,{enumerable:!0,get:function(){return E}}),Object.defineProperty(e,`ZERO_TOKENS`,{enumerable:!0,get:function(){return A}}),Object.defineProperty(e,`buildAnthropicSdkEnv`,{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,`extractCacheTokens`,{enumerable:!0,get:function(){return j}}),Object.defineProperty(e,`logAgentActivity`,{enumerable:!0,get:function(){return g}}),Object.defineProperty(e,`logAgentCwd`,{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,`logAgentGroupSplit`,{enumerable:!0,get:function(){return v}}),Object.defineProperty(e,`logCacheTokens`,{enumerable:!0,get:function(){return M}}),Object.defineProperty(e,`logCacheTokensFromMessage`,{enumerable:!0,get:function(){return ee}}),Object.defineProperty(e,`setAgentLogEnabled`,{enumerable:!0,get:function(){return o}})})),ez=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.type===`system`&&e.subtype===`api_retry`}function a(e){return e.type===`system`&&e.subtype===`model_refusal_fallback`}function o(e){return e.subtype!==`success`}function s(e){let t=e.tool_input?.file_path;return typeof t==`string`?t:``}function c(e){let t=e.tool_input?.command;return typeof t==`string`?t:``}let l=/(\u009B|\u001B\[)[0-?]*[ -/]*[@-~]/g;function u(e){return e.replaceAll(l,``)}function d(e){let t=e;return u(((t.stdout??``)+(t.stderr??``)).trim())}function f(e){let t=e;return Array.isArray(t.message?.content)?t.message.content:void 0}function p(e){return e}Object.defineProperty(e,`getExecOutput`,{enumerable:!0,get:function(){return d}}),Object.defineProperty(e,`getMessageContentBlocks`,{enumerable:!0,get:function(){return f}}),Object.defineProperty(e,`getSystemInitData`,{enumerable:!0,get:function(){return p}}),Object.defineProperty(e,`getToolInputCommand`,{enumerable:!0,get:function(){return c}}),Object.defineProperty(e,`getToolInputFilePath`,{enumerable:!0,get:function(){return s}}),Object.defineProperty(e,`isApiRetryMessage`,{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,`isErrorResult`,{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,`isModelRefusalFallbackMessage`,{enumerable:!0,get:function(){return a}}),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 u}})})),tz=s((e=>{let t=`catalog_emit`,n=`emit_catalog_flow`,r=`emit_catalog_summary`,i=`mcp__${t}__${n}`,a=`mcp__${t}__${r}`;var o=class{flows=[];projectSummary=``;projectType=`unknown`;detectedEntryCount=0;addFlow(e){let t=typeof e.name==`string`?e.name.trim().toLowerCase():``,n=t.length>0?this.flows.findIndex(e=>(typeof e.name==`string`?e.name.trim().toLowerCase():``)===t):-1;return n>=0?this.flows[n]=e:this.flows.push(e),this.flows.length}setSummary(e,t,n){this.projectSummary=e,this.projectType=t,this.detectedEntryCount=n}};function s(e,t){let n;try{n=JSON.parse(t)}catch{return{accepted:!1,error:`flow was not valid JSON — re-send a single flow object as a JSON string`}}return typeof n!=`object`||!n||Array.isArray(n)?{accepted:!1,error:`flow must be a single JSON object, not an array or scalar`}:{accepted:!0,count:e.addFlow(n)}}Object.defineProperty(e,`CATALOG_EMIT_MCP_SERVER_NAME`,{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,`CatalogEmitCollector`,{enumerable:!0,get:function(){return o}}),Object.defineProperty(e,`EMIT_FLOW_TOOL`,{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,`EMIT_SUMMARY_TOOL`,{enumerable:!0,get:function(){return r}}),Object.defineProperty(e,`MCP_EMIT_FLOW_TOOL`,{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,`MCP_EMIT_SUMMARY_TOOL`,{enumerable:!0,get:function(){return a}}),Object.defineProperty(e,`acceptEmittedFlow`,{enumerable:!0,get:function(){return s}})})),nz=s((e=>{let t=ur(),n=QR(),r=t.__toESM(ie()),i=`## Dependency roots (multi-root projects)
|
|
170
170
|
|
|
171
171
|
Some projects span a PRIMARY project plus one or more DEPENDENCY ROOTS (sibling
|
|
172
172
|
directories in the same repo — e.g. \`common/\`, \`contracts/\`, shared packages).
|
|
@@ -718,7 +718,7 @@ ${t.map(e=>`- ${e}`).join(`
|
|
|
718
718
|
${s}
|
|
719
719
|
|
|
720
720
|
## Flows to choose from:
|
|
721
|
-
${o}`}Object.defineProperty(e,`PRE_FILTER_SYSTEM_PROMPT`,{enumerable:!0,get:function(){return'You classify file paths as SOURCE or NON_SOURCE.\n\nDO NOT use any tools. Do not call Read, Bash, Grep, Glob, WebSearch, or any other tool. You have no tool access and must not attempt to use one. Classify based ONLY on the file paths in the user\'s prompt and your knowledge of file naming conventions. Respond with the JSON object directly in a single turn.\n\nNON_SOURCE — exclude these. A file is NON_SOURCE if ANY of the following match its path:\n- Tests: filename contains `.spec.`, `.test.`, `_test.`, `-test.`, `.e2e`, `.e2e-spec.`, ends in `_test.<ext>`/`Test.<ext>`/`Tests.<ext>`, or sits under a `test/`, `tests/`, `__tests__/`, `__mocks__/`, `spec/`, or `e2e/` directory. (e.g. `src/rounding/rounding.service.spec.ts` is NON_SOURCE.)\n- Test helpers / fixtures / mocks / stubs / factories used only by tests.\n- Config: `*.config.*`, `*.conf`, `.eslintrc*`, `.prettierrc*`, `tsconfig*.json`, `jest.config.*`, `vite*.config.*`, `babel.config.*`, dotfiles, `.env*`.\n- Migrations, seeds, lock files (`*-lock.json`, `*.lock`, `yarn.lock`, `pnpm-lock.yaml`).\n- Documentation (`*.md`, `*.mdx`, `*.txt`), build artifacts (`dist/`, `build/`, `*.min.*`), IDE settings (`.vscode/`, `.idea/`), CI configs (`.github/`, `.gitlab-ci*`, `*.yml`/`*.yaml` pipelines).\n\nSOURCE: everything else — application code in any language (handlers, controllers, services, models, modules, utilities, types, data structures, headers, etc.).\n\nOnly exclude a file when it CLEARLY matches one of the NON_SOURCE rules above (e.g. an unambiguous `.spec.`/`.test.` test file, a lock file, a migration). When you are UNSURE whether a file is source or non-source, KEEP it — include it as SOURCE. Excluding a real source file would hide a regression, which is far worse than analyzing one extra file. Bias toward inclusion on any doubt.\n\nOutput a JSON object with a single "sourceFiles" array containing ONLY the SOURCE file paths.\n\nExample (paths are illustrative — use this project\'s actual paths and file extensions):\n{"sourceFiles": ["<path/to/auth/service.ext>", "<path/to/payments/handler.ext>"]}'}}),Object.defineProperty(e,`buildFileToFlowMappingPrompt`,{enumerable:!0,get:function(){return l}}),Object.defineProperty(e,`buildFileToFlowMappingSystemPrompt`,{enumerable:!0,get:function(){return a}}),Object.defineProperty(e,`buildResidualRoughMapPrompt`,{enumerable:!0,get:function(){return v}}),Object.defineProperty(e,`buildResidualRoughMapSystemPrompt`,{enumerable:!0,get:function(){return _}}),Object.defineProperty(e,`buildShallowMapPrompt`,{enumerable:!0,get:function(){return b}}),Object.defineProperty(e,`buildShallowMapSystemPrompt`,{enumerable:!0,get:function(){return y}}),Object.defineProperty(e,`buildSonnetDeepPrompt`,{enumerable:!0,get:function(){return d}}),Object.defineProperty(e,`buildSonnetDeepSystemPrompt`,{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,`buildVerdictCalibratorPrompt`,{enumerable:!0,get:function(){return g}}),Object.defineProperty(e,`buildVerdictCalibratorSystemPrompt`,{enumerable:!0,get:function(){return f}})})),rz=s((e=>{function t(e){let t=new Map;for(let n of e)for(let e of n.flowIds)t.has(e)||t.set(e,new Set),t.get(e)?.add(n.file);return t}function n(e){let t={directMappedFiles:0,guessedMappedFiles:0,guessedNoFlowFiles:0,noFlowFiles:0};for(let n of e){let e=n.confidence===`low`,r=n.flowIds.length>0;e&&r?t.guessedMappedFiles+=1:e?t.guessedNoFlowFiles+=1:r?t.directMappedFiles+=1:t.noFlowFiles+=1}return t}function r(e){let t={directMappedFiles:[],guessedMappedFiles:[],guessedNoFlowFiles:[],noFlowFiles:[]};for(let n of e){let e=n.confidence===`low`,r=n.flowIds.length>0;e&&r?t.guessedMappedFiles.push(n.file):e?t.guessedNoFlowFiles.push(n.file):r?t.directMappedFiles.push(n.file):t.noFlowFiles.push(n.file)}return t}function i(e){let t=new Set,n=new Set;for(let r of e){let e=r.confidence===`low`;for(let i of r.flowIds)e?n.add(i):t.add(i)}let r=new Set;for(let e of n)t.has(e)||r.add(e);return r}function a(e){let t=new Map;for(let n of e)if(n.reason.length!==0)for(let e of n.flowIds)t.has(e)||t.set(e,new Map),t.get(e)?.set(n.file,n.reason);return t}Object.defineProperty(e,`buildFlowFileMap`,{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,`buildFlowFileReasons`,{enumerable:!0,get:function(){return a}}),Object.defineProperty(e,`buildLowConfidenceFlowIds`,{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,`buildMappingBreakdown`,{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,`buildMappingBreakdownFiles`,{enumerable:!0,get:function(){return r}})})),iz=s(((e,t)=>{var n=Object.prototype.hasOwnProperty,r=`~`;function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(r=!1));function a(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function o(e,t,n,i,o){if(typeof n!=`function`)throw TypeError(`The listener must be a function`);var s=new a(n,i||e,o),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],s]:e._events[c].push(s):(e._events[c]=s,e._eventsCount++),e}function s(e,t){--e._eventsCount===0?e._events=new i:delete e._events[t]}function c(){this._events=new i,this._eventsCount=0}c.prototype.eventNames=function(){var e=[],t,i;if(this._eventsCount===0)return e;for(i in t=this._events)n.call(t,i)&&e.push(r?i.slice(1):i);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e},c.prototype.listeners=function(e){var t=r?r+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,a=n.length,o=Array(a);i<a;i++)o[i]=n[i].fn;return o},c.prototype.listenerCount=function(e){var t=r?r+e:e,n=this._events[t];return n?n.fn?1:n.length:0},c.prototype.emit=function(e,t,n,i,a,o){var s=r?r+e:e;if(!this._events[s])return!1;var c=this._events[s],l=arguments.length,u,d;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,i),!0;case 5:return c.fn.call(c.context,t,n,i,a),!0;case 6:return c.fn.call(c.context,t,n,i,a,o),!0}for(d=1,u=Array(l-1);d<l;d++)u[d-1]=arguments[d];c.fn.apply(c.context,u)}else{var f=c.length,p;for(d=0;d<f;d++)switch(c[d].once&&this.removeListener(e,c[d].fn,void 0,!0),l){case 1:c[d].fn.call(c[d].context);break;case 2:c[d].fn.call(c[d].context,t);break;case 3:c[d].fn.call(c[d].context,t,n);break;case 4:c[d].fn.call(c[d].context,t,n,i);break;default:if(!u)for(p=1,u=Array(l-1);p<l;p++)u[p-1]=arguments[p];c[d].fn.apply(c[d].context,u)}}return!0},c.prototype.on=function(e,t,n){return o(this,e,t,n,!1)},c.prototype.once=function(e,t,n){return o(this,e,t,n,!0)},c.prototype.removeListener=function(e,t,n,i){var a=r?r+e:e;if(!this._events[a])return this;if(!t)return s(this,a),this;var o=this._events[a];if(o.fn)o.fn===t&&(!i||o.once)&&(!n||o.context===n)&&s(this,a);else{for(var c=0,l=[],u=o.length;c<u;c++)(o[c].fn!==t||i&&!o[c].once||n&&o[c].context!==n)&&l.push(o[c]);l.length?this._events[a]=l.length===1?l[0]:l:s(this,a)}return this},c.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&s(this,t)):(this._events=new i,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=r,c.EventEmitter=c,t!==void 0&&(t.exports=c)})),az=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.TimeoutError=void 0,e.default=r;var t=class e extends Error{name=`TimeoutError`;constructor(t,n){var r;super(t,n),(r=Error.captureStackTrace)==null||r.call(Error,this,e)}};e.TimeoutError=t;let n=e=>e.reason??new DOMException(`This operation was aborted.`,`AbortError`);function r(e,r){let{milliseconds:i,fallback:a,message:o,customTimers:s={setTimeout,clearTimeout},signal:c}=r,l,u,d=new Promise((r,d)=>{if(typeof i!=`number`||Math.sign(i)!==1)throw TypeError(`Expected \`milliseconds\` to be a positive number, got \`${i}\``);if(c!=null&&c.aborted){d(n(c));return}if(c&&(u=()=>{d(n(c))},c.addEventListener(`abort`,u,{once:!0})),e.then(r,d),i===1/0)return;let f=new t;l=s.setTimeout.call(void 0,()=>{if(a){try{r(a())}catch(e){d(e)}return}typeof e.cancel==`function`&&e.cancel(),o===!1?r():o instanceof Error?d(o):(f.message=o??`Promise timed out after ${i} milliseconds`,d(f))},i)}).finally(()=>{d.clear(),u&&c&&c.removeEventListener(`abort`,u)});return d.clear=()=>{s.clearTimeout.call(void 0,l),l=void 0},d}})),oz=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default=t;function t(e,t,n){let r=0,i=e.length;for(;i>0;){let a=Math.trunc(i/2),o=r+a;n(e[o],t)<=0?(r=++o,i-=a+1):i=a}return r}})),sz=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default=void 0;var t=n(oz());function n(e){return e&&e.__esModule?e:{default:e}}e.default=class{#e=[];enqueue(e,n){let{priority:r=0,id:i}=n??{},a={priority:r,id:i,run:e};if(this.size===0||this.#e[this.size-1].priority>=r){this.#e.push(a);return}let o=(0,t.default)(this.#e,a,(e,t)=>t.priority-e.priority);this.#e.splice(o,0,a)}setPriority(e,t){let n=this.#e.findIndex(t=>t.id===e);if(n===-1)throw ReferenceError(`No promise function with the id "${e}" exists in the queue.`);let[r]=this.#e.splice(n,1);this.enqueue(r.run,{priority:t,id:e})}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(t=>t.priority===e.priority).map(e=>e.run)}get size(){return this.#e.length}}})),cz=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),Object.defineProperty(e,`TimeoutError`,{enumerable:!0,get:function(){return n.TimeoutError}}),e.default=void 0;var t=iz(),n=a(az()),r=i(sz());function i(e){return e&&e.__esModule?e:{default:e}}function a(e,t){if(typeof WeakMap==`function`)var n=new WeakMap,r=new WeakMap;return(a=function(e,t){if(!t&&e&&e.__esModule)return e;var i,a,o={__proto__:null,default:e};if(e===null||typeof e!=`object`&&typeof e!=`function`)return o;if(i=t?r:n){if(i.has(e))return i.get(e);i.set(e,o)}for(let t in e)t!==`default`&&{}.hasOwnProperty.call(e,t)&&((a=(i=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,t))&&(a.get||a.set)?i(o,t,a):o[t]=e[t]);return o})(e,t)}function o(e,t){d(e,t),t.add(e)}function s(e,t,n){return(t=c(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function c(e){var t=l(e,`string`);return typeof t==`symbol`?t:t+``}function l(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function u(e,t,n){d(e,t),t.set(e,n)}function d(e,t){if(t.has(e))throw TypeError(`Cannot initialize the same private elements twice on an object`)}function f(e,t,n){return n(h(e,t))}function p(e,t){return e.get(h(e,t))}function m(e,t,n){return e.set(h(e,t),n),n}function h(e,t,n){if(typeof e==`function`?e===t:e.has(t))return arguments.length<3?t:n;throw TypeError(`Private element is not present on this object`)}var g=new WeakMap,_=new WeakMap,v=new WeakMap,y=new WeakMap,b=new WeakMap,x=new WeakMap,S=new WeakMap,C=new WeakMap,w=new WeakMap,T=new WeakMap,E=new WeakMap,D=new WeakMap,O=new WeakMap,k=new WeakMap,A=new WeakMap,j=new WeakMap,M=new WeakMap,ee=new WeakMap,N=new WeakSet;e.default=class extends t.EventEmitter{constructor(e){if(super(),o(this,N),u(this,g,void 0),u(this,_,void 0),u(this,v,0),u(this,y,void 0),u(this,b,!1),u(this,x,!1),u(this,S,void 0),u(this,C,0),u(this,w,0),u(this,T,void 0),u(this,E,void 0),u(this,D,void 0),u(this,O,void 0),u(this,k,0),u(this,A,void 0),u(this,j,void 0),u(this,M,1n),u(this,ee,new Map),s(this,`timeout`,void 0),e={carryoverIntervalCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:r.default,...e},!(typeof e.intervalCap==`number`&&e.intervalCap>=1))throw TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??``}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??``}\` (${typeof e.interval})`);if(m(g,this,e.carryoverIntervalCount??e.carryoverConcurrencyCount??!1),m(_,this,e.intervalCap===1/0||e.interval===0),m(y,this,e.intervalCap),m(S,this,e.interval),m(D,this,new e.queueClass),m(O,this,e.queueClass),this.concurrency=e.concurrency,e.timeout!==void 0&&!(Number.isFinite(e.timeout)&&e.timeout>0))throw TypeError(`Expected \`timeout\` to be a positive finite number, got \`${e.timeout}\` (${typeof e.timeout})`);this.timeout=e.timeout,m(j,this,e.autoStart===!1),h(N,this,se).call(this)}get concurrency(){return p(A,this)}set concurrency(e){if(!(typeof e==`number`&&e>=1))throw TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);m(A,this,e),h(N,this,V).call(this)}setPriority(e,t){if(typeof t!=`number`||!Number.isFinite(t))throw TypeError(`Expected \`priority\` to be a finite number, got \`${t}\` (${typeof t})`);p(D,this).setPriority(e,t)}async add(e,t={}){var r,i,a;return(a=t).id??(a.id=(m(M,this,(r=p(M,this),i=r++,r)),i).toString()),t={timeout:this.timeout,...t},new Promise((r,i)=>{let a=Symbol(`task-${t.id}`);p(D,this).enqueue(async()=>{var o;m(k,this,(o=p(k,this),o++,o)),p(ee,this).set(a,{id:t.id,priority:t.priority??0,startTime:Date.now(),timeout:t.timeout});try{try{var s;(s=t.signal)==null||s.throwIfAborted()}catch(e){if(!p(_,this)){var c;m(v,this,(c=p(v,this),c--,c))}throw p(ee,this).delete(a),e}let i=e({signal:t.signal});t.timeout&&(i=(0,n.default)(Promise.resolve(i),{milliseconds:t.timeout,message:`Task timed out after ${t.timeout}ms (queue has ${p(k,this)} running, ${p(D,this).size} waiting)`})),t.signal&&(i=Promise.race([i,h(N,this,ae).call(this,t.signal)]));let o=await i;r(o),this.emit(`completed`,o)}catch(e){i(e),this.emit(`error`,e)}finally{p(ee,this).delete(a),queueMicrotask(()=>{h(N,this,F).call(this)})}},t),this.emit(`add`),h(N,this,re).call(this)})}async addAll(e,t){return Promise.all(e.map(async e=>this.add(e,t)))}start(){return p(j,this)?(m(j,this,!1),h(N,this,V).call(this),this):this}pause(){m(j,this,!0)}clear(){m(D,this,new(p(O,this))),h(N,this,le).call(this)}async onEmpty(){p(D,this).size!==0&&await h(N,this,oe).call(this,`empty`)}async onSizeLessThan(e){p(D,this).size<e||await h(N,this,oe).call(this,`next`,()=>p(D,this).size<e)}async onIdle(){p(k,this)===0&&p(D,this).size===0||await h(N,this,oe).call(this,`idle`)}async onPendingZero(){p(k,this)!==0&&await h(N,this,oe).call(this,`pendingZero`)}async onRateLimit(){this.isRateLimited||await h(N,this,oe).call(this,`rateLimit`)}async onRateLimitCleared(){this.isRateLimited&&await h(N,this,oe).call(this,`rateLimitCleared`)}async onError(){return new Promise((e,t)=>{let n=e=>{this.off(`error`,n),t(e)};this.on(`error`,n)})}get size(){return p(D,this).size}sizeBy(e){return p(D,this).filter(e).length}get pending(){return p(k,this)}get isPaused(){return p(j,this)}get isRateLimited(){return p(b,this)}get isSaturated(){return p(k,this)===p(A,this)&&p(D,this).size>0||this.isRateLimited&&p(D,this).size>0}get runningTasks(){return[...p(ee,this).values()].map(e=>({...e}))}};function te(e){return p(_,e)||p(v,e)<p(y,e)}function P(e){return p(k,e)<p(A,e)}function F(){var e;m(k,this,(e=p(k,this),e--,e)),p(k,this)===0&&this.emit(`pendingZero`),h(N,this,re).call(this),this.emit(`next`)}function I(){h(N,this,B).call(this),h(N,this,ie).call(this),m(E,this,void 0)}function L(e){let t=Date.now();if(p(T,e)===void 0){let n=p(C,e)-t;if(n<0){if(p(w,e)>0){let n=t-p(w,e);if(n<p(S,e))return h(N,e,ne).call(e,p(S,e)-n),!0}m(v,e,p(g,e)?p(k,e):0)}else return h(N,e,ne).call(e,n),!0}return!1}function ne(e){p(E,this)===void 0&&m(E,this,setTimeout(()=>{h(N,this,I).call(this)},e))}function R(){p(T,this)&&(clearInterval(p(T,this)),m(T,this,void 0))}function z(){p(E,this)&&(clearTimeout(p(E,this)),m(E,this,void 0))}function re(){if(p(D,this).size===0)return h(N,this,R).call(this),this.emit(`empty`),p(k,this)===0&&(h(N,this,z).call(this),this.emit(`idle`)),!1;let e=!1;if(!p(j,this)){let n=!f(N,this,L);if(f(N,this,te)&&f(N,this,P)){let r=p(D,this).dequeue();if(!p(_,this)){var t;m(v,this,(t=p(v,this),t++,t)),h(N,this,ce).call(this)}this.emit(`active`),m(w,this,Date.now()),r(),n&&h(N,this,ie).call(this),e=!0}}return e}function ie(){p(_,this)||p(T,this)!==void 0||(m(T,this,setInterval(()=>{h(N,this,B).call(this)},p(S,this))),m(C,this,Date.now()+p(S,this)))}function B(){p(v,this)===0&&p(k,this)===0&&p(T,this)&&h(N,this,R).call(this),m(v,this,p(g,this)?p(k,this):0),h(N,this,V).call(this),h(N,this,ce).call(this)}function V(){for(;h(N,this,re).call(this););}async function ae(e){return new Promise((t,n)=>{e.addEventListener(`abort`,()=>{n(e.reason)},{once:!0})})}async function oe(e,t){return new Promise(n=>{let r=()=>{t&&!t()||(this.off(e,r),n())};this.on(e,r)})}function se(){p(_,this)||(this.on(`add`,()=>{p(D,this).size>0&&h(N,this,ce).call(this)}),this.on(`next`,()=>{h(N,this,ce).call(this)}))}function ce(){p(_,this)||p(x,this)||(m(x,this,!0),queueMicrotask(()=>{m(x,this,!1),h(N,this,le).call(this)}))}function le(){let e=p(b,this),t=!p(_,this)&&p(v,this)>=p(y,this)&&p(D,this).size>0;t!==e&&(m(b,this,t),this.emit(t?`rateLimit`:`rateLimitCleared`))}})),lz=s((e=>{let t=ur(),n=ez(),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}})})),uz=s((e=>{_R(),QR();let t=nz();e.buildFileToFlowMappingPrompt=t.buildFileToFlowMappingPrompt,e.buildFileToFlowMappingSystemPrompt=t.buildFileToFlowMappingSystemPrompt})),dz=s((e=>{let t=ur(),n=_R(),r=$R(),i=QR(),a=rz(),o=t.__toESM(require(`node:crypto`)),s=t.__toESM(require(`node:fs`)),c=t.__toESM(cz()),l=t.__toESM(require(`node:path`));function u(e){if(typeof e!=`object`||!e)return;let t=e;if(Array.isArray(t.fileFlowMapping))return{fileFlowMapping:t.fileFlowMapping}}function d(e){let t=`"fileFlowMapping"`,n;for(let r=e.indexOf(t);r!==-1;r=e.indexOf(t,r+17)){let t=e.lastIndexOf(`{`,r),i=t===-1?-1:f(e,t);if(i===-1)continue;let a=p(e.slice(t,i+1));a!==void 0&&(n=a)}return n}function f(e,t){let n=0;for(let r=t;r<e.length;r+=1)if(e[r]===`{`)n+=1;else if(e[r]===`}`&&--n===0)return r;return-1}function p(e){try{return u(JSON.parse(e))}catch{return}}function m(e,t,r,i){try{let a=l.default.join(t,`reports`,`mapping-prompts`);(0,s.mkdirSync)(a,{recursive:!0});let o=new Date().toISOString().replaceAll(/[:.]/g,`-`),c=l.default.join(a,`${o}-batch-${e}.prompt.log`),u=`# SYSTEM PROMPT\n\n${r}\n\n# USER PROMPT\n\n${i}\n`;(0,s.writeFileSync)(c,u,`utf8`),n.logger.info.defaultLog(`[regression-impact] Mapping prompt (batch ${e}) written to ${c}`)}catch(t){n.logger.info.defaultLog(`[regression-impact] Failed to write mapping prompt (batch ${e}): ${String(t)}`)}}function h(e,t){let n=t;for(let t of e??[])if(t.type===`text`&&typeof t.text==`string`){let e=d(t.text);e!==void 0&&(n=e.fileFlowMapping)}return n}function g(e,t,r,a,o){let s=new Set(a.map(e=>e.file)),c=t.filter(e=>!s.has(e)),l=i.shouldLogDiagnostics?` after ${e.num_turns} turns / $${e.total_cost_usd.toFixed(4)}`:``;return n.logger.info.defaultLog(`[regression-impact] File-to-flow mapping batch #${r} aborted (${e.subtype})${l} — salvaged ${a.length} mapping(s), ${c.length} file(s) INCOMPLETE`),{mappings:a,costUsd:e.total_cost_usd,turns:e.num_turns,maxTurnsHit:e.subtype===`error_max_turns`,maxBudgetHit:e.subtype===`error_max_budget_usd`,incompleteFiles:c,tokens:o}}async function _(e,t,a,s,c,l,d,f,p,_,v,y){let{query:b,isResultMessage:x,isErrorResult:S,getMessageContentBlocks:C}=await Promise.resolve().then(()=>lz()),{buildFileToFlowMappingSystemPrompt:w,buildFileToFlowMappingPrompt:T}=await Promise.resolve().then(()=>uz()),E=`mapping batch #${_}`,D=v?.(t),O=T(e,t,a,s,c,D,y),k=w(f,D!==void 0);i.REGRESSION_IMPACT_LOG_MAPPING_PROMPT&&m(_,a,k,O);let A=b({prompt:O,options:{model:i.REGRESSION_IMPACT_SONNET_MODEL,systemPrompt:k,allowedTools:[`Read`,`Grep`,`Glob`,`Bash`],permissionMode:i.REGRESSION_PERMISSION_MODE,allowDangerouslySkipPermissions:!0,maxBudgetUsd:i.REGRESSION_IMPACT_AGENTIC_MAX_BUDGET_USD,maxTurns:p,cwd:a,sessionId:(0,o.randomUUID)(),outputFormat:{type:`json_schema`,schema:r.FILE_FLOW_MAPPING_OUTPUT_SCHEMA},env:{...process.env,...r.buildAnthropicSdkEnv({proxyUrl:d,jwtToken:l??``,requestId:n.logger.getRequestId()})}}}),j={cacheReadTokens:0,cacheCreationTokens:0,inputTokens:0,outputTokens:0},M=[];r.logAgentCwd(E,a);let ee=0;for await(let e of A){if(!x(e)){let t=C(e);t!==void 0&&t.length>0&&(ee++,r.logAgentActivity(E,ee,t)),M=h(t,M);continue}if(S(e))return g(e,t,_,M,j);let a=e.total_cost_usd,o=e.num_turns,s=o>=p,c=r.logCacheTokensFromMessage(`mapping batch #${_}`,e),l=u(e.structured_output);return i.REGRESSION_LOG_COST&&n.logger.info.defaultLog(`[regression-impact] Batch (${t.length} files) cost: $${a.toFixed(4)}`),{mappings:l?.fileFlowMapping??[],costUsd:a,turns:o,maxTurnsHit:s,maxBudgetHit:!1,incompleteFiles:[],tokens:c}}return{mappings:[],costUsd:0,turns:0,maxTurnsHit:!1,maxBudgetHit:!1,incompleteFiles:[],tokens:j}}async function v(e,t,o,s,l,u,d,f,p,m,h){let g=m??i.REGRESSION_IMPACT_AGENTIC_MAX_TURNS,v=[];for(let e=0;e<t.length;e+=i.REGRESSION_IMPACT_MAPPING_BATCH_SIZE)v.push(t.slice(e,e+i.REGRESSION_IMPACT_MAPPING_BATCH_SIZE));let y=v.length,b=0;n.logger.info.defaultLog(`[regression-impact] File-to-flow mapping: ${t.length} file(s) in ${y} batch(es) against ${e.length} flow(s)...`);let x=new c.default({concurrency:i.REGRESSION_IMPACT_MAPPING_CONCURRENCY}),S=[...await Promise.all([...v.entries()].map(([t,r])=>x.add(async()=>{try{return{batchIndex:t,batch:r,result:await _(e,r,o,s,l,u,d,f,g,t+1,p,h)}}catch(e){return n.logger.info.defaultLog(`[regression-impact] File-to-flow mapping batch crashed (${r.length} file(s)): ${String(e)}`),{batchIndex:t,batch:r,crashed:!0}}})))].sort((e,t)=>e.batchIndex-t.batchIndex),C=[],w=[],T=[],E=0,D=0,O=!1,k=!1,A=0,j=0,M=0,ee=0;for(let e of S){if(`crashed`in e){w.push(...e.batch);continue}let{result:t,batch:r,batchIndex:i}=e;for(let e of t.mappings){let t=e.flowIds.length>0?e.flowIds.join(`, `):`no flows`,r=e.confidence===`low`;b+=1,n.logger.info.defaultLog(`[regression-impact] ${b} - ${e.file} → ${t}${r?` [SMART GUESS — tracing budget hit, low confidence → uncertain]`:``}`)}C.push(...t.mappings),w.push(...t.incompleteFiles),E+=t.costUsd,D+=t.turns,O||=t.maxTurnsHit,k||=t.maxBudgetHit,A+=t.tokens.cacheReadTokens,j+=t.tokens.cacheCreationTokens,M+=t.tokens.inputTokens,ee+=t.tokens.outputTokens,T.push({label:`batch-${i+1}`,totalFiles:r.length,costUsd:t.costUsd,turns:t.turns,maxTurnsHit:t.maxTurnsHit,maxBudgetHit:t.maxBudgetHit,tokens:{inputTokens:t.tokens.inputTokens,outputTokens:t.tokens.outputTokens,cacheReadTokens:t.tokens.cacheReadTokens,cacheCreationTokens:t.tokens.cacheCreationTokens},mappingBreakdown:a.buildMappingBreakdown(t.mappings)})}return r.logCacheTokens(`mapping totals`,{cacheReadTokens:A,cacheCreationTokens:j,inputTokens:M,outputTokens:ee}),w.length>0&&n.logger.info.defaultLog(`[regression-impact] File-to-flow mapping INCOMPLETE for ${w.length} file(s) (batch aborted before mapping) — coverage for these is partial/missing: ${w.join(`, `)}`),{mappings:C,costUsd:E,turns:D,maxTurnsHit:O,maxBudgetHit:k,incompleteFiles:w,batchMetrics:T}}var y=class{context;astReachability;constructor(e,t){this.context=e,this.astReachability=t}async run(e,t){let{rootPath:r,branch:i,resolvedAnchorBranch:o,jwtToken:s,anthropicBaseUrl:c,projectType:l,mappingMaxTurns:u,fileDiffs:d}=this.context,{mappings:f,costUsd:p,turns:m,maxTurnsHit:h,maxBudgetHit:g,incompleteFiles:_,batchMetrics:y}=await v(e,t,r,i,o,s,c,l,this.astReachability,u,d),b=a.buildLowConfidenceFlowIds(f);if(b.size>0){let e=f.filter(e=>e.confidence===`low`).map(e=>e.file);n.logger.info.defaultLog(`[regression-impact] tracing-budget fallback: ${e.length} file(s) placed by a smart guess (${e.join(`, `)}) → ${b.size} flow(s) marked uncertain for deep verification`)}return{flowFileMap:a.buildFlowFileMap(f),flowFileReasons:a.buildFlowFileReasons(f),costUsd:p,turns:m,maxTurnsHit:h,maxBudgetHit:g,incompleteFiles:_,batchMetrics:y,mappingBreakdown:a.buildMappingBreakdown(f),mappingBreakdownFiles:a.buildMappingBreakdownFiles(f),...b.size>0?{lowConfidenceFlowIds:b}:{}}}};Object.defineProperty(e,`AgenticImpactMapper`,{enumerable:!0,get:function(){return y}})})),hee=s((e=>{var t=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`.split(``);e.encode=function(e){if(0<=e&&e<t.length)return t[e];throw TypeError(`Must be between 0 and 63: `+e)},e.decode=function(e){var t=65,n=90,r=97,i=122,a=48;return t<=e&&e<=n?e-t:r<=e&&e<=i?e-r+26:a<=e&&e<=57?e-a+52:e==43?62:e==47?63:-1}})),fz=s((e=>{var t=hee(),n=5,r=1<<n,i=r-1,a=r;function o(e){return e<0?(-e<<1)+1:(e<<1)+0}function s(e){var t=(e&1)==1,n=e>>1;return t?-n:n}e.encode=function(e){var r=``,s,c=o(e);do s=c&i,c>>>=n,c>0&&(s|=a),r+=t.encode(s);while(c>0);return r},e.decode=function(e,r,o){var c=e.length,l=0,u=0,d,f;do{if(r>=c)throw Error(`Expected more digits in base 64 VLQ value.`);if(f=t.decode(e.charCodeAt(r++)),f===-1)throw Error(`Invalid base64 digit: `+e.charAt(r-1));d=!!(f&a),f&=i,l+=f<<u,u+=n}while(d);o.value=s(l),o.rest=r}})),pz=s((e=>{function t(e,t,n){if(t in e)return e[t];if(arguments.length===3)return n;throw Error(`"`+t+`" is a required argument.`)}e.getArg=t;var n=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/,r=/^data:.+\,.+$/;function i(e){var t=e.match(n);return t?{scheme:t[1],auth:t[2],host:t[3],port:t[4],path:t[5]}:null}e.urlParse=i;function a(e){var t=``;return e.scheme&&(t+=e.scheme+`:`),t+=`//`,e.auth&&(t+=e.auth+`@`),e.host&&(t+=e.host),e.port&&(t+=`:`+e.port),e.path&&(t+=e.path),t}e.urlGenerate=a;function o(t){var n=t,r=i(t);if(r){if(!r.path)return t;n=r.path}for(var o=e.isAbsolute(n),s=n.split(/\/+/),c,l=0,u=s.length-1;u>=0;u--)c=s[u],c===`.`?s.splice(u,1):c===`..`?l++:l>0&&(c===``?(s.splice(u+1,l),l=0):(s.splice(u,2),l--));return n=s.join(`/`),n===``&&(n=o?`/`:`.`),r?(r.path=n,a(r)):n}e.normalize=o;function s(e,t){e===``&&(e=`.`),t===``&&(t=`.`);var n=i(t),s=i(e);if(s&&(e=s.path||`/`),n&&!n.scheme)return s&&(n.scheme=s.scheme),a(n);if(n||t.match(r))return t;if(s&&!s.host&&!s.path)return s.host=t,a(s);var c=t.charAt(0)===`/`?t:o(e.replace(/\/+$/,``)+`/`+t);return s?(s.path=c,a(s)):c}e.join=s,e.isAbsolute=function(e){return e.charAt(0)===`/`||n.test(e)};function c(e,t){e===``&&(e=`.`),e=e.replace(/\/$/,``);for(var n=0;t.indexOf(e+`/`)!==0;){var r=e.lastIndexOf(`/`);if(r<0||(e=e.slice(0,r),e.match(/^([^\/]+:\/)?\/*$/)))return t;++n}return Array(n+1).join(`../`)+t.substr(e.length+1)}e.relative=c;var l=function(){return!(`__proto__`in Object.create(null))}();function u(e){return e}function d(e){return p(e)?`$`+e:e}e.toSetString=l?u:d;function f(e){return p(e)?e.slice(1):e}e.fromSetString=l?u:f;function p(e){if(!e)return!1;var t=e.length;if(t<9||e.charCodeAt(t-1)!==95||e.charCodeAt(t-2)!==95||e.charCodeAt(t-3)!==111||e.charCodeAt(t-4)!==116||e.charCodeAt(t-5)!==111||e.charCodeAt(t-6)!==114||e.charCodeAt(t-7)!==112||e.charCodeAt(t-8)!==95||e.charCodeAt(t-9)!==95)return!1;for(var n=t-10;n>=0;n--)if(e.charCodeAt(n)!==36)return!1;return!0}function m(e,t,n){var r=g(e.source,t.source);return r!==0||(r=e.originalLine-t.originalLine,r!==0)||(r=e.originalColumn-t.originalColumn,r!==0||n)||(r=e.generatedColumn-t.generatedColumn,r!==0)||(r=e.generatedLine-t.generatedLine,r!==0)?r:g(e.name,t.name)}e.compareByOriginalPositions=m;function h(e,t,n){var r=e.generatedLine-t.generatedLine;return r!==0||(r=e.generatedColumn-t.generatedColumn,r!==0||n)||(r=g(e.source,t.source),r!==0)||(r=e.originalLine-t.originalLine,r!==0)||(r=e.originalColumn-t.originalColumn,r!==0)?r:g(e.name,t.name)}e.compareByGeneratedPositionsDeflated=h;function g(e,t){return e===t?0:e===null?1:t===null?-1:e>t?1:-1}function _(e,t){var n=e.generatedLine-t.generatedLine;return n!==0||(n=e.generatedColumn-t.generatedColumn,n!==0)||(n=g(e.source,t.source),n!==0)||(n=e.originalLine-t.originalLine,n!==0)||(n=e.originalColumn-t.originalColumn,n!==0)?n:g(e.name,t.name)}e.compareByGeneratedPositionsInflated=_;function v(e){return JSON.parse(e.replace(/^\)]}'[^\n]*\n/,``))}e.parseSourceMapInput=v;function y(e,t,n){if(t||=``,e&&(e[e.length-1]!==`/`&&t[0]!==`/`&&(e+=`/`),t=e+t),n){var r=i(n);if(!r)throw Error(`sourceMapURL could not be parsed`);if(r.path){var c=r.path.lastIndexOf(`/`);c>=0&&(r.path=r.path.substring(0,c+1))}t=s(a(r),t)}return o(t)}e.computeSourceURL=y})),mz=s((e=>{var t=pz(),n=Object.prototype.hasOwnProperty,r=typeof Map<`u`;function i(){this._array=[],this._set=r?new Map:Object.create(null)}i.fromArray=function(e,t){for(var n=new i,r=0,a=e.length;r<a;r++)n.add(e[r],t);return n},i.prototype.size=function(){return r?this._set.size:Object.getOwnPropertyNames(this._set).length},i.prototype.add=function(e,i){var a=r?e:t.toSetString(e),o=r?this.has(e):n.call(this._set,a),s=this._array.length;(!o||i)&&this._array.push(e),o||(r?this._set.set(e,s):this._set[a]=s)},i.prototype.has=function(e){if(r)return this._set.has(e);var i=t.toSetString(e);return n.call(this._set,i)},i.prototype.indexOf=function(e){if(r){var i=this._set.get(e);if(i>=0)return i}else{var a=t.toSetString(e);if(n.call(this._set,a))return this._set[a]}throw Error(`"`+e+`" is not in the set.`)},i.prototype.at=function(e){if(e>=0&&e<this._array.length)return this._array[e];throw Error(`No element indexed by `+e)},i.prototype.toArray=function(){return this._array.slice()},e.ArraySet=i})),hz=s((e=>{var t=pz();function n(e,n){var r=e.generatedLine,i=n.generatedLine,a=e.generatedColumn,o=n.generatedColumn;return i>r||i==r&&o>=a||t.compareByGeneratedPositionsInflated(e,n)<=0}function r(){this._array=[],this._sorted=!0,this._last={generatedLine:-1,generatedColumn:0}}r.prototype.unsortedForEach=function(e,t){this._array.forEach(e,t)},r.prototype.add=function(e){n(this._last,e)?(this._last=e,this._array.push(e)):(this._sorted=!1,this._array.push(e))},r.prototype.toArray=function(){return this._sorted||=(this._array.sort(t.compareByGeneratedPositionsInflated),!0),this._array},e.MappingList=r})),gz=s((e=>{var t=fz(),n=pz(),r=mz().ArraySet,i=hz().MappingList;function a(e){e||={},this._file=n.getArg(e,`file`,null),this._sourceRoot=n.getArg(e,`sourceRoot`,null),this._skipValidation=n.getArg(e,`skipValidation`,!1),this._sources=new r,this._names=new r,this._mappings=new i,this._sourcesContents=null}a.prototype._version=3,a.fromSourceMap=function(e){var t=e.sourceRoot,r=new a({file:e.file,sourceRoot:t});return e.eachMapping(function(e){var i={generated:{line:e.generatedLine,column:e.generatedColumn}};e.source!=null&&(i.source=e.source,t!=null&&(i.source=n.relative(t,i.source)),i.original={line:e.originalLine,column:e.originalColumn},e.name!=null&&(i.name=e.name)),r.addMapping(i)}),e.sources.forEach(function(i){var a=i;t!==null&&(a=n.relative(t,i)),r._sources.has(a)||r._sources.add(a);var o=e.sourceContentFor(i);o!=null&&r.setSourceContent(i,o)}),r},a.prototype.addMapping=function(e){var t=n.getArg(e,`generated`),r=n.getArg(e,`original`,null),i=n.getArg(e,`source`,null),a=n.getArg(e,`name`,null);this._skipValidation||this._validateMapping(t,r,i,a),i!=null&&(i=String(i),this._sources.has(i)||this._sources.add(i)),a!=null&&(a=String(a),this._names.has(a)||this._names.add(a)),this._mappings.add({generatedLine:t.line,generatedColumn:t.column,originalLine:r!=null&&r.line,originalColumn:r!=null&&r.column,source:i,name:a})},a.prototype.setSourceContent=function(e,t){var r=e;this._sourceRoot!=null&&(r=n.relative(this._sourceRoot,r)),t==null?this._sourcesContents&&(delete this._sourcesContents[n.toSetString(r)],Object.keys(this._sourcesContents).length===0&&(this._sourcesContents=null)):(this._sourcesContents||=Object.create(null),this._sourcesContents[n.toSetString(r)]=t)},a.prototype.applySourceMap=function(e,t,i){var a=t;if(t==null){if(e.file==null)throw Error(`SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map's "file" property. Both were omitted.`);a=e.file}var o=this._sourceRoot;o!=null&&(a=n.relative(o,a));var s=new r,c=new r;this._mappings.unsortedForEach(function(t){if(t.source===a&&t.originalLine!=null){var r=e.originalPositionFor({line:t.originalLine,column:t.originalColumn});r.source!=null&&(t.source=r.source,i!=null&&(t.source=n.join(i,t.source)),o!=null&&(t.source=n.relative(o,t.source)),t.originalLine=r.line,t.originalColumn=r.column,r.name!=null&&(t.name=r.name))}var l=t.source;l!=null&&!s.has(l)&&s.add(l);var u=t.name;u!=null&&!c.has(u)&&c.add(u)},this),this._sources=s,this._names=c,e.sources.forEach(function(t){var r=e.sourceContentFor(t);r!=null&&(i!=null&&(t=n.join(i,t)),o!=null&&(t=n.relative(o,t)),this.setSourceContent(t,r))},this)},a.prototype._validateMapping=function(e,t,n,r){if(t&&typeof t.line!=`number`&&typeof t.column!=`number`)throw Error(`original.line and original.column are not numbers -- you probably meant to omit the original mapping entirely and only map the generated position. If so, pass null for the original mapping instead of an object with empty or null values.`);if(!(e&&`line`in e&&`column`in e&&e.line>0&&e.column>=0&&!t&&!n&&!r)&&!(e&&`line`in e&&`column`in e&&t&&`line`in t&&`column`in t&&e.line>0&&e.column>=0&&t.line>0&&t.column>=0&&n))throw Error(`Invalid mapping: `+JSON.stringify({generated:e,source:n,original:t,name:r}))},a.prototype._serializeMappings=function(){for(var e=0,r=1,i=0,a=0,o=0,s=0,c=``,l,u,d,f,p=this._mappings.toArray(),m=0,h=p.length;m<h;m++){if(u=p[m],l=``,u.generatedLine!==r)for(e=0;u.generatedLine!==r;)l+=`;`,r++;else if(m>0){if(!n.compareByGeneratedPositionsInflated(u,p[m-1]))continue;l+=`,`}l+=t.encode(u.generatedColumn-e),e=u.generatedColumn,u.source!=null&&(f=this._sources.indexOf(u.source),l+=t.encode(f-s),s=f,l+=t.encode(u.originalLine-1-a),a=u.originalLine-1,l+=t.encode(u.originalColumn-i),i=u.originalColumn,u.name!=null&&(d=this._names.indexOf(u.name),l+=t.encode(d-o),o=d)),c+=l}return c},a.prototype._generateSourcesContent=function(e,t){return e.map(function(e){if(!this._sourcesContents)return null;t!=null&&(e=n.relative(t,e));var r=n.toSetString(e);return Object.prototype.hasOwnProperty.call(this._sourcesContents,r)?this._sourcesContents[r]:null},this)},a.prototype.toJSON=function(){var e={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};return this._file!=null&&(e.file=this._file),this._sourceRoot!=null&&(e.sourceRoot=this._sourceRoot),this._sourcesContents&&(e.sourcesContent=this._generateSourcesContent(e.sources,e.sourceRoot)),e},a.prototype.toString=function(){return JSON.stringify(this.toJSON())},e.SourceMapGenerator=a})),_z=s((e=>{e.GREATEST_LOWER_BOUND=1,e.LEAST_UPPER_BOUND=2;function t(n,r,i,a,o,s){var c=Math.floor((r-n)/2)+n,l=o(i,a[c],!0);return l===0?c:l>0?r-c>1?t(c,r,i,a,o,s):s==e.LEAST_UPPER_BOUND?r<a.length?r:-1:c:c-n>1?t(n,c,i,a,o,s):s==e.LEAST_UPPER_BOUND?c:n<0?-1:n}e.search=function(n,r,i,a){if(r.length===0)return-1;var o=t(-1,r.length,n,r,i,a||e.GREATEST_LOWER_BOUND);if(o<0)return-1;for(;o-1>=0&&i(r[o],r[o-1],!0)===0;)--o;return o}})),vz=s((e=>{function t(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function n(e,t){return Math.round(e+Math.random()*(t-e))}function r(e,i,a,o){if(a<o){var s=n(a,o),c=a-1;t(e,s,o);for(var l=e[o],u=a;u<o;u++)i(e[u],l)<=0&&(c+=1,t(e,c,u));t(e,c+1,u);var d=c+1;r(e,i,a,d-1),r(e,i,d+1,o)}}e.quickSort=function(e,t){r(e,t,0,e.length-1)}})),yz=s((e=>{var t=pz(),n=_z(),r=mz().ArraySet,i=fz(),a=vz().quickSort;function o(e,n){var r=e;return typeof e==`string`&&(r=t.parseSourceMapInput(e)),r.sections==null?new s(r,n):new l(r,n)}o.fromSourceMap=function(e,t){return s.fromSourceMap(e,t)},o.prototype._version=3,o.prototype.__generatedMappings=null,Object.defineProperty(o.prototype,`_generatedMappings`,{configurable:!0,enumerable:!0,get:function(){return this.__generatedMappings||this._parseMappings(this._mappings,this.sourceRoot),this.__generatedMappings}}),o.prototype.__originalMappings=null,Object.defineProperty(o.prototype,`_originalMappings`,{configurable:!0,enumerable:!0,get:function(){return this.__originalMappings||this._parseMappings(this._mappings,this.sourceRoot),this.__originalMappings}}),o.prototype._charIsMappingSeparator=function(e,t){var n=e.charAt(t);return n===`;`||n===`,`},o.prototype._parseMappings=function(e,t){throw Error(`Subclasses must implement _parseMappings`)},o.GENERATED_ORDER=1,o.ORIGINAL_ORDER=2,o.GREATEST_LOWER_BOUND=1,o.LEAST_UPPER_BOUND=2,o.prototype.eachMapping=function(e,n,r){var i=n||null,a=r||o.GENERATED_ORDER,s;switch(a){case o.GENERATED_ORDER:s=this._generatedMappings;break;case o.ORIGINAL_ORDER:s=this._originalMappings;break;default:throw Error(`Unknown order of iteration.`)}var c=this.sourceRoot;s.map(function(e){var n=e.source===null?null:this._sources.at(e.source);return n=t.computeSourceURL(c,n,this._sourceMapURL),{source:n,generatedLine:e.generatedLine,generatedColumn:e.generatedColumn,originalLine:e.originalLine,originalColumn:e.originalColumn,name:e.name===null?null:this._names.at(e.name)}},this).forEach(e,i)},o.prototype.allGeneratedPositionsFor=function(e){var r=t.getArg(e,`line`),i={source:t.getArg(e,`source`),originalLine:r,originalColumn:t.getArg(e,`column`,0)};if(i.source=this._findSourceIndex(i.source),i.source<0)return[];var a=[],o=this._findMapping(i,this._originalMappings,`originalLine`,`originalColumn`,t.compareByOriginalPositions,n.LEAST_UPPER_BOUND);if(o>=0){var s=this._originalMappings[o];if(e.column===void 0)for(var c=s.originalLine;s&&s.originalLine===c;)a.push({line:t.getArg(s,`generatedLine`,null),column:t.getArg(s,`generatedColumn`,null),lastColumn:t.getArg(s,`lastGeneratedColumn`,null)}),s=this._originalMappings[++o];else for(var l=s.originalColumn;s&&s.originalLine===r&&s.originalColumn==l;)a.push({line:t.getArg(s,`generatedLine`,null),column:t.getArg(s,`generatedColumn`,null),lastColumn:t.getArg(s,`lastGeneratedColumn`,null)}),s=this._originalMappings[++o]}return a},e.SourceMapConsumer=o;function s(e,n){var i=e;typeof e==`string`&&(i=t.parseSourceMapInput(e));var a=t.getArg(i,`version`),o=t.getArg(i,`sources`),s=t.getArg(i,`names`,[]),c=t.getArg(i,`sourceRoot`,null),l=t.getArg(i,`sourcesContent`,null),u=t.getArg(i,`mappings`),d=t.getArg(i,`file`,null);if(a!=this._version)throw Error(`Unsupported version: `+a);c&&=t.normalize(c),o=o.map(String).map(t.normalize).map(function(e){return c&&t.isAbsolute(c)&&t.isAbsolute(e)?t.relative(c,e):e}),this._names=r.fromArray(s.map(String),!0),this._sources=r.fromArray(o,!0),this._absoluteSources=this._sources.toArray().map(function(e){return t.computeSourceURL(c,e,n)}),this.sourceRoot=c,this.sourcesContent=l,this._mappings=u,this._sourceMapURL=n,this.file=d}s.prototype=Object.create(o.prototype),s.prototype.consumer=o,s.prototype._findSourceIndex=function(e){var n=e;if(this.sourceRoot!=null&&(n=t.relative(this.sourceRoot,n)),this._sources.has(n))return this._sources.indexOf(n);var r;for(r=0;r<this._absoluteSources.length;++r)if(this._absoluteSources[r]==e)return r;return-1},s.fromSourceMap=function(e,n){var i=Object.create(s.prototype),o=i._names=r.fromArray(e._names.toArray(),!0),l=i._sources=r.fromArray(e._sources.toArray(),!0);i.sourceRoot=e._sourceRoot,i.sourcesContent=e._generateSourcesContent(i._sources.toArray(),i.sourceRoot),i.file=e._file,i._sourceMapURL=n,i._absoluteSources=i._sources.toArray().map(function(e){return t.computeSourceURL(i.sourceRoot,e,n)});for(var u=e._mappings.toArray().slice(),d=i.__generatedMappings=[],f=i.__originalMappings=[],p=0,m=u.length;p<m;p++){var h=u[p],g=new c;g.generatedLine=h.generatedLine,g.generatedColumn=h.generatedColumn,h.source&&(g.source=l.indexOf(h.source),g.originalLine=h.originalLine,g.originalColumn=h.originalColumn,h.name&&(g.name=o.indexOf(h.name)),f.push(g)),d.push(g)}return a(i.__originalMappings,t.compareByOriginalPositions),i},s.prototype._version=3,Object.defineProperty(s.prototype,`sources`,{get:function(){return this._absoluteSources.slice()}});function c(){this.generatedLine=0,this.generatedColumn=0,this.source=null,this.originalLine=null,this.originalColumn=null,this.name=null}s.prototype._parseMappings=function(e,n){for(var r=1,o=0,s=0,l=0,u=0,d=0,f=e.length,p=0,m={},h={},g=[],_=[],v,y,b,x,S;p<f;)if(e.charAt(p)===`;`)r++,p++,o=0;else if(e.charAt(p)===`,`)p++;else{for(v=new c,v.generatedLine=r,x=p;x<f&&!this._charIsMappingSeparator(e,x);x++);if(y=e.slice(p,x),b=m[y],b)p+=y.length;else{for(b=[];p<x;)i.decode(e,p,h),S=h.value,p=h.rest,b.push(S);if(b.length===2)throw Error(`Found a source, but no line and column`);if(b.length===3)throw Error(`Found a source and line, but no column`);m[y]=b}v.generatedColumn=o+b[0],o=v.generatedColumn,b.length>1&&(v.source=u+b[1],u+=b[1],v.originalLine=s+b[2],s=v.originalLine,v.originalLine+=1,v.originalColumn=l+b[3],l=v.originalColumn,b.length>4&&(v.name=d+b[4],d+=b[4])),_.push(v),typeof v.originalLine==`number`&&g.push(v)}a(_,t.compareByGeneratedPositionsDeflated),this.__generatedMappings=_,a(g,t.compareByOriginalPositions),this.__originalMappings=g},s.prototype._findMapping=function(e,t,r,i,a,o){if(e[r]<=0)throw TypeError(`Line must be greater than or equal to 1, got `+e[r]);if(e[i]<0)throw TypeError(`Column must be greater than or equal to 0, got `+e[i]);return n.search(e,t,a,o)},s.prototype.computeColumnSpans=function(){for(var e=0;e<this._generatedMappings.length;++e){var t=this._generatedMappings[e];if(e+1<this._generatedMappings.length){var n=this._generatedMappings[e+1];if(t.generatedLine===n.generatedLine){t.lastGeneratedColumn=n.generatedColumn-1;continue}}t.lastGeneratedColumn=1/0}},s.prototype.originalPositionFor=function(e){var n={generatedLine:t.getArg(e,`line`),generatedColumn:t.getArg(e,`column`)},r=this._findMapping(n,this._generatedMappings,`generatedLine`,`generatedColumn`,t.compareByGeneratedPositionsDeflated,t.getArg(e,`bias`,o.GREATEST_LOWER_BOUND));if(r>=0){var i=this._generatedMappings[r];if(i.generatedLine===n.generatedLine){var a=t.getArg(i,`source`,null);a!==null&&(a=this._sources.at(a),a=t.computeSourceURL(this.sourceRoot,a,this._sourceMapURL));var s=t.getArg(i,`name`,null);return s!==null&&(s=this._names.at(s)),{source:a,line:t.getArg(i,`originalLine`,null),column:t.getArg(i,`originalColumn`,null),name:s}}}return{source:null,line:null,column:null,name:null}},s.prototype.hasContentsOfAllSources=function(){return this.sourcesContent?this.sourcesContent.length>=this._sources.size()&&!this.sourcesContent.some(function(e){return e==null}):!1},s.prototype.sourceContentFor=function(e,n){if(!this.sourcesContent)return null;var r=this._findSourceIndex(e);if(r>=0)return this.sourcesContent[r];var i=e;this.sourceRoot!=null&&(i=t.relative(this.sourceRoot,i));var a;if(this.sourceRoot!=null&&(a=t.urlParse(this.sourceRoot))){var o=i.replace(/^file:\/\//,``);if(a.scheme==`file`&&this._sources.has(o))return this.sourcesContent[this._sources.indexOf(o)];if((!a.path||a.path==`/`)&&this._sources.has(`/`+i))return this.sourcesContent[this._sources.indexOf(`/`+i)]}if(n)return null;throw Error(`"`+i+`" is not in the SourceMap.`)},s.prototype.generatedPositionFor=function(e){var n=t.getArg(e,`source`);if(n=this._findSourceIndex(n),n<0)return{line:null,column:null,lastColumn:null};var r={source:n,originalLine:t.getArg(e,`line`),originalColumn:t.getArg(e,`column`)},i=this._findMapping(r,this._originalMappings,`originalLine`,`originalColumn`,t.compareByOriginalPositions,t.getArg(e,`bias`,o.GREATEST_LOWER_BOUND));if(i>=0){var a=this._originalMappings[i];if(a.source===r.source)return{line:t.getArg(a,`generatedLine`,null),column:t.getArg(a,`generatedColumn`,null),lastColumn:t.getArg(a,`lastGeneratedColumn`,null)}}return{line:null,column:null,lastColumn:null}},e.BasicSourceMapConsumer=s;function l(e,n){var i=e;typeof e==`string`&&(i=t.parseSourceMapInput(e));var a=t.getArg(i,`version`),s=t.getArg(i,`sections`);if(a!=this._version)throw Error(`Unsupported version: `+a);this._sources=new r,this._names=new r;var c={line:-1,column:0};this._sections=s.map(function(e){if(e.url)throw Error(`Support for url field in sections not implemented.`);var r=t.getArg(e,`offset`),i=t.getArg(r,`line`),a=t.getArg(r,`column`);if(i<c.line||i===c.line&&a<c.column)throw Error(`Section offsets must be ordered and non-overlapping.`);return c=r,{generatedOffset:{generatedLine:i+1,generatedColumn:a+1},consumer:new o(t.getArg(e,`map`),n)}})}l.prototype=Object.create(o.prototype),l.prototype.constructor=o,l.prototype._version=3,Object.defineProperty(l.prototype,`sources`,{get:function(){for(var e=[],t=0;t<this._sections.length;t++)for(var n=0;n<this._sections[t].consumer.sources.length;n++)e.push(this._sections[t].consumer.sources[n]);return e}}),l.prototype.originalPositionFor=function(e){var r={generatedLine:t.getArg(e,`line`),generatedColumn:t.getArg(e,`column`)},i=n.search(r,this._sections,function(e,t){return e.generatedLine-t.generatedOffset.generatedLine||e.generatedColumn-t.generatedOffset.generatedColumn}),a=this._sections[i];return a?a.consumer.originalPositionFor({line:r.generatedLine-(a.generatedOffset.generatedLine-1),column:r.generatedColumn-(a.generatedOffset.generatedLine===r.generatedLine?a.generatedOffset.generatedColumn-1:0),bias:e.bias}):{source:null,line:null,column:null,name:null}},l.prototype.hasContentsOfAllSources=function(){return this._sections.every(function(e){return e.consumer.hasContentsOfAllSources()})},l.prototype.sourceContentFor=function(e,t){for(var n=0;n<this._sections.length;n++){var r=this._sections[n].consumer.sourceContentFor(e,!0);if(r)return r}if(t)return null;throw Error(`"`+e+`" is not in the SourceMap.`)},l.prototype.generatedPositionFor=function(e){for(var n=0;n<this._sections.length;n++){var r=this._sections[n];if(r.consumer._findSourceIndex(t.getArg(e,`source`))!==-1){var i=r.consumer.generatedPositionFor(e);if(i)return{line:i.line+(r.generatedOffset.generatedLine-1),column:i.column+(r.generatedOffset.generatedLine===i.line?r.generatedOffset.generatedColumn-1:0)}}}return{line:null,column:null}},l.prototype._parseMappings=function(e,n){this.__generatedMappings=[],this.__originalMappings=[];for(var r=0;r<this._sections.length;r++)for(var i=this._sections[r],o=i.consumer._generatedMappings,s=0;s<o.length;s++){var c=o[s],l=i.consumer._sources.at(c.source);l=t.computeSourceURL(i.consumer.sourceRoot,l,this._sourceMapURL),this._sources.add(l),l=this._sources.indexOf(l);var u=null;c.name&&(u=i.consumer._names.at(c.name),this._names.add(u),u=this._names.indexOf(u));var d={source:l,generatedLine:c.generatedLine+(i.generatedOffset.generatedLine-1),generatedColumn:c.generatedColumn+(i.generatedOffset.generatedLine===c.generatedLine?i.generatedOffset.generatedColumn-1:0),originalLine:c.originalLine,originalColumn:c.originalColumn,name:u};this.__generatedMappings.push(d),typeof d.originalLine==`number`&&this.__originalMappings.push(d)}a(this.__generatedMappings,t.compareByGeneratedPositionsDeflated),a(this.__originalMappings,t.compareByOriginalPositions)},e.IndexedSourceMapConsumer=l})),bz=s((e=>{var t=gz().SourceMapGenerator,n=pz(),r=/(\r?\n)/,i=10,a=`$$$isSourceNode$$$`;function o(e,t,n,r,i){this.children=[],this.sourceContents={},this.line=e??null,this.column=t??null,this.source=n??null,this.name=i??null,this[a]=!0,r!=null&&this.add(r)}o.fromStringWithSourceMap=function(e,t,i){var a=new o,s=e.split(r),c=0,l=function(){return e()+(e()||``);function e(){return c<s.length?s[c++]:void 0}},u=1,d=0,f=null;return t.eachMapping(function(e){if(f!==null)if(u<e.generatedLine)p(f,l()),u++,d=0;else{var t=s[c]||``,n=t.substr(0,e.generatedColumn-d);s[c]=t.substr(e.generatedColumn-d),d=e.generatedColumn,p(f,n),f=e;return}for(;u<e.generatedLine;)a.add(l()),u++;if(d<e.generatedColumn){var t=s[c]||``;a.add(t.substr(0,e.generatedColumn)),s[c]=t.substr(e.generatedColumn),d=e.generatedColumn}f=e},this),c<s.length&&(f&&p(f,l()),a.add(s.splice(c).join(``))),t.sources.forEach(function(e){var r=t.sourceContentFor(e);r!=null&&(i!=null&&(e=n.join(i,e)),a.setSourceContent(e,r))}),a;function p(e,t){if(e===null||e.source===void 0)a.add(t);else{var r=i?n.join(i,e.source):e.source;a.add(new o(e.originalLine,e.originalColumn,r,t,e.name))}}},o.prototype.add=function(e){if(Array.isArray(e))e.forEach(function(e){this.add(e)},this);else if(e[a]||typeof e==`string`)e&&this.children.push(e);else throw TypeError(`Expected a SourceNode, string, or an array of SourceNodes and strings. Got `+e);return this},o.prototype.prepend=function(e){if(Array.isArray(e))for(var t=e.length-1;t>=0;t--)this.prepend(e[t]);else if(e[a]||typeof e==`string`)this.children.unshift(e);else throw TypeError(`Expected a SourceNode, string, or an array of SourceNodes and strings. Got `+e);return this},o.prototype.walk=function(e){for(var t,n=0,r=this.children.length;n<r;n++)t=this.children[n],t[a]?t.walk(e):t!==``&&e(t,{source:this.source,line:this.line,column:this.column,name:this.name})},o.prototype.join=function(e){var t,n,r=this.children.length;if(r>0){for(t=[],n=0;n<r-1;n++)t.push(this.children[n]),t.push(e);t.push(this.children[n]),this.children=t}return this},o.prototype.replaceRight=function(e,t){var n=this.children[this.children.length-1];return n[a]?n.replaceRight(e,t):typeof n==`string`?this.children[this.children.length-1]=n.replace(e,t):this.children.push(``.replace(e,t)),this},o.prototype.setSourceContent=function(e,t){this.sourceContents[n.toSetString(e)]=t},o.prototype.walkSourceContents=function(e){for(var t=0,r=this.children.length;t<r;t++)this.children[t][a]&&this.children[t].walkSourceContents(e);for(var i=Object.keys(this.sourceContents),t=0,r=i.length;t<r;t++)e(n.fromSetString(i[t]),this.sourceContents[i[t]])},o.prototype.toString=function(){var e=``;return this.walk(function(t){e+=t}),e},o.prototype.toStringWithSourceMap=function(e){var n={code:``,line:1,column:0},r=new t(e),a=!1,o=null,s=null,c=null,l=null;return this.walk(function(e,t){n.code+=e,t.source!==null&&t.line!==null&&t.column!==null?((o!==t.source||s!==t.line||c!==t.column||l!==t.name)&&r.addMapping({source:t.source,original:{line:t.line,column:t.column},generated:{line:n.line,column:n.column},name:t.name}),o=t.source,s=t.line,c=t.column,l=t.name,a=!0):a&&=(r.addMapping({generated:{line:n.line,column:n.column}}),o=null,!1);for(var u=0,d=e.length;u<d;u++)e.charCodeAt(u)===i?(n.line++,n.column=0,u+1===d?(o=null,a=!1):a&&r.addMapping({source:t.source,original:{line:t.line,column:t.column},generated:{line:n.line,column:n.column},name:t.name})):n.column++}),this.walkSourceContents(function(e,t){r.setSourceContent(e,t)}),{code:n.code,map:r}},e.SourceNode=o})),xz=s((e=>{e.SourceMapGenerator=gz().SourceMapGenerator,e.SourceMapConsumer=yz().SourceMapConsumer,e.SourceNode=bz().SourceNode})),Sz=s(((e,t)=>{var n=Object.prototype.toString,r=typeof Buffer<`u`&&typeof Buffer.alloc==`function`&&typeof Buffer.allocUnsafe==`function`&&typeof Buffer.from==`function`;function i(e){return n.call(e).slice(8,-1)===`ArrayBuffer`}function a(e,t,n){t>>>=0;var i=e.byteLength-t;if(i<0)throw RangeError(`'offset' is out of bounds`);if(n===void 0)n=i;else if(n>>>=0,n>i)throw RangeError(`'length' is out of bounds`);return r?Buffer.from(e.slice(t,t+n)):new Buffer(new Uint8Array(e.slice(t,t+n)))}function o(e,t){if((typeof t!=`string`||t===``)&&(t=`utf8`),!Buffer.isEncoding(t))throw TypeError(`"encoding" must be a valid string encoding`);return r?Buffer.from(e,t):new Buffer(e,t)}function s(e,t,n){if(typeof e==`number`)throw TypeError(`"value" argument must not be a number`);return i(e)?a(e,t,n):typeof e==`string`?o(e,t):r?Buffer.from(e):new Buffer(e)}t.exports=s})),Cz=s(((e,t)=>{var n=xz().SourceMapConsumer,r=require(`path`),i;try{i=require(`fs`),(!i.existsSync||!i.readFileSync)&&(i=null)}catch{}var a=Sz();function o(e,t){return e.require(t)}var s=!1,c=!1,l=!1,u=`auto`,d={},f={},p=/^data:application\/json[^,]+base64,/,m=[],h=[];function g(){return u===`browser`?!0:u===`node`?!1:typeof window<`u`&&typeof XMLHttpRequest==`function`&&!(window.require&&window.module&&window.process&&window.process.type===`renderer`)}function _(){return typeof process==`object`&&process!==null&&typeof process.on==`function`}function v(){return typeof process==`object`&&process!==null?process.version:``}function y(){if(typeof process==`object`&&process!==null)return process.stderr}function b(e){if(typeof process==`object`&&process!==null&&typeof process.exit==`function`)return process.exit(e)}function x(e){return function(t){for(var n=0;n<e.length;n++){var r=e[n](t);if(r)return r}return null}}var S=x(m);m.push(function(e){if(e=e.trim(),/^file:/.test(e)&&(e=e.replace(/file:\/\/\/(\w:)?/,function(e,t){return t?``:`/`})),e in d)return d[e];var t=``;try{if(i)i.existsSync(e)&&(t=i.readFileSync(e,`utf8`));else{var n=new XMLHttpRequest;n.open(`GET`,e,!1),n.send(null),n.readyState===4&&n.status===200&&(t=n.responseText)}}catch{}return d[e]=t});function C(e,t){if(!e)return t;var n=r.dirname(e),i=/^\w+:\/\/[^\/]*/.exec(n),a=i?i[0]:``,o=n.slice(a.length);return a&&/^\/\w\:/.test(o)?(a+=`/`,a+r.resolve(n.slice(a.length),t).replace(/\\/g,`/`)):a+r.resolve(n.slice(a.length),t)}function w(e){var t;if(g())try{var n=new XMLHttpRequest;n.open(`GET`,e,!1),n.send(null),t=n.readyState===4?n.responseText:null;var r=n.getResponseHeader(`SourceMap`)||n.getResponseHeader(`X-SourceMap`);if(r)return r}catch{}t=S(e);for(var i=/(?:\/\/[@#][\s]*sourceMappingURL=([^\s'"]+)[\s]*$)|(?:\/\*[@#][\s]*sourceMappingURL=([^\s*'"]+)[\s]*(?:\*\/)[\s]*$)/gm,a,o;o=i.exec(t);)a=o;return a?a[1]:null}var T=x(h);h.push(function(e){var t=w(e);if(!t)return null;var n;return p.test(t)?(n=a(t.slice(t.indexOf(`,`)+1),`base64`).toString(),t=e):(t=C(e,t),n=S(t)),n?{url:t,map:n}:null});function E(e){var t=f[e.source];if(!t){var r=T(e.source);r?(t=f[e.source]={url:r.url,map:new n(r.map)},t.map.sourcesContent&&t.map.sources.forEach(function(e,n){var r=t.map.sourcesContent[n];if(r){var i=C(t.url,e);d[i]=r}})):t=f[e.source]={url:null,map:null}}if(t&&t.map&&typeof t.map.originalPositionFor==`function`){var i=t.map.originalPositionFor(e);if(i.source!==null)return i.source=C(t.url,i.source),i}return e}function D(e){var t=/^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(e);if(t){var n=E({source:t[2],line:+t[3],column:t[4]-1});return`eval at `+t[1]+` (`+n.source+`:`+n.line+`:`+(n.column+1)+`)`}return t=/^eval at ([^(]+) \((.+)\)$/.exec(e),t?`eval at `+t[1]+` (`+D(t[2])+`)`:e}function O(){var e,t=``;if(this.isNative())t=`native`;else{e=this.getScriptNameOrSourceURL(),!e&&this.isEval()&&(t=this.getEvalOrigin(),t+=`, `),e?t+=e:t+=`<anonymous>`;var n=this.getLineNumber();if(n!=null){t+=`:`+n;var r=this.getColumnNumber();r&&(t+=`:`+r)}}var i=``,a=this.getFunctionName(),o=!0,s=this.isConstructor();if(this.isToplevel()||s)s?i+=`new `+(a||`<anonymous>`):a?i+=a:(i+=t,o=!1);else{var c=this.getTypeName();c===`[object Object]`&&(c=`null`);var l=this.getMethodName();a?(c&&a.indexOf(c)!=0&&(i+=c+`.`),i+=a,l&&a.indexOf(`.`+l)!=a.length-l.length-1&&(i+=` [as `+l+`]`)):i+=c+`.`+(l||`<anonymous>`)}return o&&(i+=` (`+t+`)`),i}function k(e){var t={};return Object.getOwnPropertyNames(Object.getPrototypeOf(e)).forEach(function(n){t[n]=/^(?:is|get)/.test(n)?function(){return e[n].call(e)}:e[n]}),t.toString=O,t}function A(e,t){if(t===void 0&&(t={nextPosition:null,curPosition:null}),e.isNative())return t.curPosition=null,e;var n=e.getFileName()||e.getScriptNameOrSourceURL();if(n){var r=e.getLineNumber(),i=e.getColumnNumber()-1,a=/^v(10\.1[6-9]|10\.[2-9][0-9]|10\.[0-9]{3,}|1[2-9]\d*|[2-9]\d|\d{3,}|11\.11)/.test(v())?0:62;r===1&&i>a&&!g()&&!e.isEval()&&(i-=a);var o=E({source:n,line:r,column:i});t.curPosition=o,e=k(e);var s=e.getFunctionName;return e.getFunctionName=function(){return t.nextPosition==null?s():t.nextPosition.name||s()},e.getFileName=function(){return o.source},e.getLineNumber=function(){return o.line},e.getColumnNumber=function(){return o.column+1},e.getScriptNameOrSourceURL=function(){return o.source},e}var c=e.isEval()&&e.getEvalOrigin();return c?(c=D(c),e=k(e),e.getEvalOrigin=function(){return c},e):e}function j(e,t){l&&(d={},f={});for(var n=e.name||`Error`,r=e.message||``,i=n+`: `+r,a={nextPosition:null,curPosition:null},o=[],s=t.length-1;s>=0;s--)o.push(`
|
|
721
|
+
${o}`}Object.defineProperty(e,`PRE_FILTER_SYSTEM_PROMPT`,{enumerable:!0,get:function(){return'You classify file paths as SOURCE or NON_SOURCE.\n\nDO NOT use any tools. Do not call Read, Bash, Grep, Glob, WebSearch, or any other tool. You have no tool access and must not attempt to use one. Classify based ONLY on the file paths in the user\'s prompt and your knowledge of file naming conventions. Respond with the JSON object directly in a single turn.\n\nNON_SOURCE — exclude these. A file is NON_SOURCE if ANY of the following match its path:\n- Tests: filename contains `.spec.`, `.test.`, `_test.`, `-test.`, `.e2e`, `.e2e-spec.`, ends in `_test.<ext>`/`Test.<ext>`/`Tests.<ext>`, or sits under a `test/`, `tests/`, `__tests__/`, `__mocks__/`, `spec/`, or `e2e/` directory. (e.g. `src/rounding/rounding.service.spec.ts` is NON_SOURCE.)\n- Test helpers / fixtures / mocks / stubs / factories used only by tests.\n- Config: `*.config.*`, `*.conf`, `.eslintrc*`, `.prettierrc*`, `tsconfig*.json`, `jest.config.*`, `vite*.config.*`, `babel.config.*`, dotfiles, `.env*`.\n- Migrations, seeds, lock files (`*-lock.json`, `*.lock`, `yarn.lock`, `pnpm-lock.yaml`).\n- Documentation (`*.md`, `*.mdx`, `*.txt`), build artifacts (`dist/`, `build/`, `*.min.*`), IDE settings (`.vscode/`, `.idea/`), CI configs (`.github/`, `.gitlab-ci*`, `*.yml`/`*.yaml` pipelines).\n\nSOURCE: everything else — application code in any language (handlers, controllers, services, models, modules, utilities, types, data structures, headers, etc.).\n\nOnly exclude a file when it CLEARLY matches one of the NON_SOURCE rules above (e.g. an unambiguous `.spec.`/`.test.` test file, a lock file, a migration). When you are UNSURE whether a file is source or non-source, KEEP it — include it as SOURCE. Excluding a real source file would hide a regression, which is far worse than analyzing one extra file. Bias toward inclusion on any doubt.\n\nOutput a JSON object with a single "sourceFiles" array containing ONLY the SOURCE file paths.\n\nExample (paths are illustrative — use this project\'s actual paths and file extensions):\n{"sourceFiles": ["<path/to/auth/service.ext>", "<path/to/payments/handler.ext>"]}'}}),Object.defineProperty(e,`buildFileToFlowMappingPrompt`,{enumerable:!0,get:function(){return l}}),Object.defineProperty(e,`buildFileToFlowMappingSystemPrompt`,{enumerable:!0,get:function(){return a}}),Object.defineProperty(e,`buildResidualRoughMapPrompt`,{enumerable:!0,get:function(){return v}}),Object.defineProperty(e,`buildResidualRoughMapSystemPrompt`,{enumerable:!0,get:function(){return _}}),Object.defineProperty(e,`buildShallowMapPrompt`,{enumerable:!0,get:function(){return b}}),Object.defineProperty(e,`buildShallowMapSystemPrompt`,{enumerable:!0,get:function(){return y}}),Object.defineProperty(e,`buildSonnetDeepPrompt`,{enumerable:!0,get:function(){return d}}),Object.defineProperty(e,`buildSonnetDeepSystemPrompt`,{enumerable:!0,get:function(){return u}}),Object.defineProperty(e,`buildVerdictCalibratorPrompt`,{enumerable:!0,get:function(){return g}}),Object.defineProperty(e,`buildVerdictCalibratorSystemPrompt`,{enumerable:!0,get:function(){return f}})})),rz=s((e=>{function t(e){let t=new Map;for(let n of e)for(let e of n.flowIds)t.has(e)||t.set(e,new Set),t.get(e)?.add(n.file);return t}function n(e){let t={directMappedFiles:0,guessedMappedFiles:0,guessedNoFlowFiles:0,noFlowFiles:0};for(let n of e){let e=n.confidence===`low`,r=n.flowIds.length>0;e&&r?t.guessedMappedFiles+=1:e?t.guessedNoFlowFiles+=1:r?t.directMappedFiles+=1:t.noFlowFiles+=1}return t}function r(e){let t={directMappedFiles:[],guessedMappedFiles:[],guessedNoFlowFiles:[],noFlowFiles:[]};for(let n of e){let e=n.confidence===`low`,r=n.flowIds.length>0;e&&r?t.guessedMappedFiles.push(n.file):e?t.guessedNoFlowFiles.push(n.file):r?t.directMappedFiles.push(n.file):t.noFlowFiles.push(n.file)}return t}function i(e){let t=new Set,n=new Set;for(let r of e){let e=r.confidence===`low`;for(let i of r.flowIds)e?n.add(i):t.add(i)}let r=new Set;for(let e of n)t.has(e)||r.add(e);return r}function a(e){let t=new Map;for(let n of e)if(n.reason.length!==0)for(let e of n.flowIds)t.has(e)||t.set(e,new Map),t.get(e)?.set(n.file,n.reason);return t}Object.defineProperty(e,`buildFlowFileMap`,{enumerable:!0,get:function(){return t}}),Object.defineProperty(e,`buildFlowFileReasons`,{enumerable:!0,get:function(){return a}}),Object.defineProperty(e,`buildLowConfidenceFlowIds`,{enumerable:!0,get:function(){return i}}),Object.defineProperty(e,`buildMappingBreakdown`,{enumerable:!0,get:function(){return n}}),Object.defineProperty(e,`buildMappingBreakdownFiles`,{enumerable:!0,get:function(){return r}})})),iz=s(((e,t)=>{var n=Object.prototype.hasOwnProperty,r=`~`;function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(r=!1));function a(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function o(e,t,n,i,o){if(typeof n!=`function`)throw TypeError(`The listener must be a function`);var s=new a(n,i||e,o),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],s]:e._events[c].push(s):(e._events[c]=s,e._eventsCount++),e}function s(e,t){--e._eventsCount===0?e._events=new i:delete e._events[t]}function c(){this._events=new i,this._eventsCount=0}c.prototype.eventNames=function(){var e=[],t,i;if(this._eventsCount===0)return e;for(i in t=this._events)n.call(t,i)&&e.push(r?i.slice(1):i);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e},c.prototype.listeners=function(e){var t=r?r+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,a=n.length,o=Array(a);i<a;i++)o[i]=n[i].fn;return o},c.prototype.listenerCount=function(e){var t=r?r+e:e,n=this._events[t];return n?n.fn?1:n.length:0},c.prototype.emit=function(e,t,n,i,a,o){var s=r?r+e:e;if(!this._events[s])return!1;var c=this._events[s],l=arguments.length,u,d;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,i),!0;case 5:return c.fn.call(c.context,t,n,i,a),!0;case 6:return c.fn.call(c.context,t,n,i,a,o),!0}for(d=1,u=Array(l-1);d<l;d++)u[d-1]=arguments[d];c.fn.apply(c.context,u)}else{var f=c.length,p;for(d=0;d<f;d++)switch(c[d].once&&this.removeListener(e,c[d].fn,void 0,!0),l){case 1:c[d].fn.call(c[d].context);break;case 2:c[d].fn.call(c[d].context,t);break;case 3:c[d].fn.call(c[d].context,t,n);break;case 4:c[d].fn.call(c[d].context,t,n,i);break;default:if(!u)for(p=1,u=Array(l-1);p<l;p++)u[p-1]=arguments[p];c[d].fn.apply(c[d].context,u)}}return!0},c.prototype.on=function(e,t,n){return o(this,e,t,n,!1)},c.prototype.once=function(e,t,n){return o(this,e,t,n,!0)},c.prototype.removeListener=function(e,t,n,i){var a=r?r+e:e;if(!this._events[a])return this;if(!t)return s(this,a),this;var o=this._events[a];if(o.fn)o.fn===t&&(!i||o.once)&&(!n||o.context===n)&&s(this,a);else{for(var c=0,l=[],u=o.length;c<u;c++)(o[c].fn!==t||i&&!o[c].once||n&&o[c].context!==n)&&l.push(o[c]);l.length?this._events[a]=l.length===1?l[0]:l:s(this,a)}return this},c.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&s(this,t)):(this._events=new i,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=r,c.EventEmitter=c,t!==void 0&&(t.exports=c)})),az=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.TimeoutError=void 0,e.default=r;var t=class e extends Error{name=`TimeoutError`;constructor(t,n){var r;super(t,n),(r=Error.captureStackTrace)==null||r.call(Error,this,e)}};e.TimeoutError=t;let n=e=>e.reason??new DOMException(`This operation was aborted.`,`AbortError`);function r(e,r){let{milliseconds:i,fallback:a,message:o,customTimers:s={setTimeout,clearTimeout},signal:c}=r,l,u,d=new Promise((r,d)=>{if(typeof i!=`number`||Math.sign(i)!==1)throw TypeError(`Expected \`milliseconds\` to be a positive number, got \`${i}\``);if(c!=null&&c.aborted){d(n(c));return}if(c&&(u=()=>{d(n(c))},c.addEventListener(`abort`,u,{once:!0})),e.then(r,d),i===1/0)return;let f=new t;l=s.setTimeout.call(void 0,()=>{if(a){try{r(a())}catch(e){d(e)}return}typeof e.cancel==`function`&&e.cancel(),o===!1?r():o instanceof Error?d(o):(f.message=o??`Promise timed out after ${i} milliseconds`,d(f))},i)}).finally(()=>{d.clear(),u&&c&&c.removeEventListener(`abort`,u)});return d.clear=()=>{s.clearTimeout.call(void 0,l),l=void 0},d}})),oz=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default=t;function t(e,t,n){let r=0,i=e.length;for(;i>0;){let a=Math.trunc(i/2),o=r+a;n(e[o],t)<=0?(r=++o,i-=a+1):i=a}return r}})),sz=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default=void 0;var t=n(oz());function n(e){return e&&e.__esModule?e:{default:e}}e.default=class{#e=[];enqueue(e,n){let{priority:r=0,id:i}=n??{},a={priority:r,id:i,run:e};if(this.size===0||this.#e[this.size-1].priority>=r){this.#e.push(a);return}let o=(0,t.default)(this.#e,a,(e,t)=>t.priority-e.priority);this.#e.splice(o,0,a)}setPriority(e,t){let n=this.#e.findIndex(t=>t.id===e);if(n===-1)throw ReferenceError(`No promise function with the id "${e}" exists in the queue.`);let[r]=this.#e.splice(n,1);this.enqueue(r.run,{priority:t,id:e})}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(t=>t.priority===e.priority).map(e=>e.run)}get size(){return this.#e.length}}})),cz=s((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),Object.defineProperty(e,`TimeoutError`,{enumerable:!0,get:function(){return n.TimeoutError}}),e.default=void 0;var t=iz(),n=a(az()),r=i(sz());function i(e){return e&&e.__esModule?e:{default:e}}function a(e,t){if(typeof WeakMap==`function`)var n=new WeakMap,r=new WeakMap;return(a=function(e,t){if(!t&&e&&e.__esModule)return e;var i,a,o={__proto__:null,default:e};if(e===null||typeof e!=`object`&&typeof e!=`function`)return o;if(i=t?r:n){if(i.has(e))return i.get(e);i.set(e,o)}for(let t in e)t!==`default`&&{}.hasOwnProperty.call(e,t)&&((a=(i=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,t))&&(a.get||a.set)?i(o,t,a):o[t]=e[t]);return o})(e,t)}function o(e,t){d(e,t),t.add(e)}function s(e,t,n){return(t=c(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function c(e){var t=l(e,`string`);return typeof t==`symbol`?t:t+``}function l(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function u(e,t,n){d(e,t),t.set(e,n)}function d(e,t){if(t.has(e))throw TypeError(`Cannot initialize the same private elements twice on an object`)}function f(e,t,n){return n(h(e,t))}function p(e,t){return e.get(h(e,t))}function m(e,t,n){return e.set(h(e,t),n),n}function h(e,t,n){if(typeof e==`function`?e===t:e.has(t))return arguments.length<3?t:n;throw TypeError(`Private element is not present on this object`)}var g=new WeakMap,_=new WeakMap,v=new WeakMap,y=new WeakMap,b=new WeakMap,x=new WeakMap,S=new WeakMap,C=new WeakMap,w=new WeakMap,T=new WeakMap,E=new WeakMap,D=new WeakMap,O=new WeakMap,k=new WeakMap,A=new WeakMap,j=new WeakMap,M=new WeakMap,ee=new WeakMap,N=new WeakSet;e.default=class extends t.EventEmitter{constructor(e){if(super(),o(this,N),u(this,g,void 0),u(this,_,void 0),u(this,v,0),u(this,y,void 0),u(this,b,!1),u(this,x,!1),u(this,S,void 0),u(this,C,0),u(this,w,0),u(this,T,void 0),u(this,E,void 0),u(this,D,void 0),u(this,O,void 0),u(this,k,0),u(this,A,void 0),u(this,j,void 0),u(this,M,1n),u(this,ee,new Map),s(this,`timeout`,void 0),e={carryoverIntervalCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:r.default,...e},!(typeof e.intervalCap==`number`&&e.intervalCap>=1))throw TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??``}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??``}\` (${typeof e.interval})`);if(m(g,this,e.carryoverIntervalCount??e.carryoverConcurrencyCount??!1),m(_,this,e.intervalCap===1/0||e.interval===0),m(y,this,e.intervalCap),m(S,this,e.interval),m(D,this,new e.queueClass),m(O,this,e.queueClass),this.concurrency=e.concurrency,e.timeout!==void 0&&!(Number.isFinite(e.timeout)&&e.timeout>0))throw TypeError(`Expected \`timeout\` to be a positive finite number, got \`${e.timeout}\` (${typeof e.timeout})`);this.timeout=e.timeout,m(j,this,e.autoStart===!1),h(N,this,se).call(this)}get concurrency(){return p(A,this)}set concurrency(e){if(!(typeof e==`number`&&e>=1))throw TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);m(A,this,e),h(N,this,V).call(this)}setPriority(e,t){if(typeof t!=`number`||!Number.isFinite(t))throw TypeError(`Expected \`priority\` to be a finite number, got \`${t}\` (${typeof t})`);p(D,this).setPriority(e,t)}async add(e,t={}){var r,i,a;return(a=t).id??(a.id=(m(M,this,(r=p(M,this),i=r++,r)),i).toString()),t={timeout:this.timeout,...t},new Promise((r,i)=>{let a=Symbol(`task-${t.id}`);p(D,this).enqueue(async()=>{var o;m(k,this,(o=p(k,this),o++,o)),p(ee,this).set(a,{id:t.id,priority:t.priority??0,startTime:Date.now(),timeout:t.timeout});try{try{var s;(s=t.signal)==null||s.throwIfAborted()}catch(e){if(!p(_,this)){var c;m(v,this,(c=p(v,this),c--,c))}throw p(ee,this).delete(a),e}let i=e({signal:t.signal});t.timeout&&(i=(0,n.default)(Promise.resolve(i),{milliseconds:t.timeout,message:`Task timed out after ${t.timeout}ms (queue has ${p(k,this)} running, ${p(D,this).size} waiting)`})),t.signal&&(i=Promise.race([i,h(N,this,ae).call(this,t.signal)]));let o=await i;r(o),this.emit(`completed`,o)}catch(e){i(e),this.emit(`error`,e)}finally{p(ee,this).delete(a),queueMicrotask(()=>{h(N,this,F).call(this)})}},t),this.emit(`add`),h(N,this,re).call(this)})}async addAll(e,t){return Promise.all(e.map(async e=>this.add(e,t)))}start(){return p(j,this)?(m(j,this,!1),h(N,this,V).call(this),this):this}pause(){m(j,this,!0)}clear(){m(D,this,new(p(O,this))),h(N,this,le).call(this)}async onEmpty(){p(D,this).size!==0&&await h(N,this,oe).call(this,`empty`)}async onSizeLessThan(e){p(D,this).size<e||await h(N,this,oe).call(this,`next`,()=>p(D,this).size<e)}async onIdle(){p(k,this)===0&&p(D,this).size===0||await h(N,this,oe).call(this,`idle`)}async onPendingZero(){p(k,this)!==0&&await h(N,this,oe).call(this,`pendingZero`)}async onRateLimit(){this.isRateLimited||await h(N,this,oe).call(this,`rateLimit`)}async onRateLimitCleared(){this.isRateLimited&&await h(N,this,oe).call(this,`rateLimitCleared`)}async onError(){return new Promise((e,t)=>{let n=e=>{this.off(`error`,n),t(e)};this.on(`error`,n)})}get size(){return p(D,this).size}sizeBy(e){return p(D,this).filter(e).length}get pending(){return p(k,this)}get isPaused(){return p(j,this)}get isRateLimited(){return p(b,this)}get isSaturated(){return p(k,this)===p(A,this)&&p(D,this).size>0||this.isRateLimited&&p(D,this).size>0}get runningTasks(){return[...p(ee,this).values()].map(e=>({...e}))}};function te(e){return p(_,e)||p(v,e)<p(y,e)}function P(e){return p(k,e)<p(A,e)}function F(){var e;m(k,this,(e=p(k,this),e--,e)),p(k,this)===0&&this.emit(`pendingZero`),h(N,this,re).call(this),this.emit(`next`)}function I(){h(N,this,B).call(this),h(N,this,ie).call(this),m(E,this,void 0)}function L(e){let t=Date.now();if(p(T,e)===void 0){let n=p(C,e)-t;if(n<0){if(p(w,e)>0){let n=t-p(w,e);if(n<p(S,e))return h(N,e,ne).call(e,p(S,e)-n),!0}m(v,e,p(g,e)?p(k,e):0)}else return h(N,e,ne).call(e,n),!0}return!1}function ne(e){p(E,this)===void 0&&m(E,this,setTimeout(()=>{h(N,this,I).call(this)},e))}function R(){p(T,this)&&(clearInterval(p(T,this)),m(T,this,void 0))}function z(){p(E,this)&&(clearTimeout(p(E,this)),m(E,this,void 0))}function re(){if(p(D,this).size===0)return h(N,this,R).call(this),this.emit(`empty`),p(k,this)===0&&(h(N,this,z).call(this),this.emit(`idle`)),!1;let e=!1;if(!p(j,this)){let n=!f(N,this,L);if(f(N,this,te)&&f(N,this,P)){let r=p(D,this).dequeue();if(!p(_,this)){var t;m(v,this,(t=p(v,this),t++,t)),h(N,this,ce).call(this)}this.emit(`active`),m(w,this,Date.now()),r(),n&&h(N,this,ie).call(this),e=!0}}return e}function ie(){p(_,this)||p(T,this)!==void 0||(m(T,this,setInterval(()=>{h(N,this,B).call(this)},p(S,this))),m(C,this,Date.now()+p(S,this)))}function B(){p(v,this)===0&&p(k,this)===0&&p(T,this)&&h(N,this,R).call(this),m(v,this,p(g,this)?p(k,this):0),h(N,this,V).call(this),h(N,this,ce).call(this)}function V(){for(;h(N,this,re).call(this););}async function ae(e){return new Promise((t,n)=>{e.addEventListener(`abort`,()=>{n(e.reason)},{once:!0})})}async function oe(e,t){return new Promise(n=>{let r=()=>{t&&!t()||(this.off(e,r),n())};this.on(e,r)})}function se(){p(_,this)||(this.on(`add`,()=>{p(D,this).size>0&&h(N,this,ce).call(this)}),this.on(`next`,()=>{h(N,this,ce).call(this)}))}function ce(){p(_,this)||p(x,this)||(m(x,this,!0),queueMicrotask(()=>{m(x,this,!1),h(N,this,le).call(this)}))}function le(){let e=p(b,this),t=!p(_,this)&&p(v,this)>=p(y,this)&&p(D,this).size>0;t!==e&&(m(b,this,t),this.emit(t?`rateLimit`:`rateLimitCleared`))}})),lz=s((e=>{let t=ur(),n=ez(),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}})})),uz=s((e=>{_R(),QR();let t=nz();e.buildFileToFlowMappingPrompt=t.buildFileToFlowMappingPrompt,e.buildFileToFlowMappingSystemPrompt=t.buildFileToFlowMappingSystemPrompt})),dz=s((e=>{let t=ur(),n=_R(),r=$R(),i=QR(),a=rz(),o=t.__toESM(require(`node:crypto`)),s=t.__toESM(require(`node:fs`)),c=t.__toESM(cz()),l=t.__toESM(require(`node:path`));function u(e){if(typeof e!=`object`||!e)return;let t=e;if(Array.isArray(t.fileFlowMapping))return{fileFlowMapping:t.fileFlowMapping}}function d(e){let t=`"fileFlowMapping"`,n;for(let r=e.indexOf(t);r!==-1;r=e.indexOf(t,r+17)){let t=e.lastIndexOf(`{`,r),i=t===-1?-1:f(e,t);if(i===-1)continue;let a=p(e.slice(t,i+1));a!==void 0&&(n=a)}return n}function f(e,t){let n=0;for(let r=t;r<e.length;r+=1)if(e[r]===`{`)n+=1;else if(e[r]===`}`&&--n===0)return r;return-1}function p(e){try{return u(JSON.parse(e))}catch{return}}function m(e,t,r,i){try{let a=l.default.join(t,`reports`,`mapping-prompts`);(0,s.mkdirSync)(a,{recursive:!0});let o=new Date().toISOString().replaceAll(/[:.]/g,`-`),c=l.default.join(a,`${o}-batch-${e}.prompt.log`),u=`# SYSTEM PROMPT\n\n${r}\n\n# USER PROMPT\n\n${i}\n`;(0,s.writeFileSync)(c,u,`utf8`),n.logger.info.defaultLog(`[regression-impact] Mapping prompt (batch ${e}) written to ${c}`)}catch(t){n.logger.info.defaultLog(`[regression-impact] Failed to write mapping prompt (batch ${e}): ${String(t)}`)}}function h(e,t){let n=t;for(let t of e??[])if(t.type===`text`&&typeof t.text==`string`){let e=d(t.text);e!==void 0&&(n=e.fileFlowMapping)}return n}function g(e,t,r,a,o){let s=new Set(a.map(e=>e.file)),c=t.filter(e=>!s.has(e)),l=i.shouldLogDiagnostics?` after ${e.num_turns} turns / $${e.total_cost_usd.toFixed(4)}`:``;return n.logger.info.defaultLog(`[regression-impact] File-to-flow mapping batch #${r} aborted (${e.subtype})${l} — salvaged ${a.length} mapping(s), ${c.length} file(s) INCOMPLETE`),{mappings:a,costUsd:e.total_cost_usd,turns:e.num_turns,maxTurnsHit:e.subtype===`error_max_turns`,maxBudgetHit:e.subtype===`error_max_budget_usd`,incompleteFiles:c,tokens:o}}async function _(e,t,a,s,c,l,d,f,p,_,v,y){let{query:b,isResultMessage:x,isErrorResult:S,getMessageContentBlocks:C}=await Promise.resolve().then(()=>lz()),{buildFileToFlowMappingSystemPrompt:w,buildFileToFlowMappingPrompt:T}=await Promise.resolve().then(()=>uz()),E=`mapping batch #${_}`,D=v?.(t),O=T(e,t,a,s,c,D,y),k=w(f,D!==void 0);i.REGRESSION_IMPACT_LOG_MAPPING_PROMPT&&m(_,a,k,O);let A=b({prompt:O,options:{model:i.REGRESSION_IMPACT_SONNET_MODEL,...i.REGRESSION_SONNET_ANALYZER_REASONING,systemPrompt:k,allowedTools:[`Read`,`Grep`,`Glob`,`Bash`],permissionMode:i.REGRESSION_PERMISSION_MODE,allowDangerouslySkipPermissions:!0,maxBudgetUsd:i.REGRESSION_IMPACT_AGENTIC_MAX_BUDGET_USD,maxTurns:p,cwd:a,sessionId:(0,o.randomUUID)(),outputFormat:{type:`json_schema`,schema:r.FILE_FLOW_MAPPING_OUTPUT_SCHEMA},env:{...process.env,...r.buildAnthropicSdkEnv({proxyUrl:d,jwtToken:l??``,requestId:n.logger.getRequestId()})}}}),j={cacheReadTokens:0,cacheCreationTokens:0,inputTokens:0,outputTokens:0},M=[];r.logAgentCwd(E,a);let ee=0;for await(let e of A){if(!x(e)){let t=C(e);t!==void 0&&t.length>0&&(ee++,r.logAgentActivity(E,ee,t)),M=h(t,M);continue}if(S(e))return g(e,t,_,M,j);let a=e.total_cost_usd,o=e.num_turns,s=o>=p,c=r.logCacheTokensFromMessage(`mapping batch #${_}`,e),l=u(e.structured_output);return i.REGRESSION_LOG_COST&&n.logger.info.defaultLog(`[regression-impact] Batch (${t.length} files) cost: $${a.toFixed(4)}`),{mappings:l?.fileFlowMapping??[],costUsd:a,turns:o,maxTurnsHit:s,maxBudgetHit:!1,incompleteFiles:[],tokens:c}}return{mappings:[],costUsd:0,turns:0,maxTurnsHit:!1,maxBudgetHit:!1,incompleteFiles:[],tokens:j}}async function v(e,t,o,s,l,u,d,f,p,m,h){let g=m??i.REGRESSION_IMPACT_AGENTIC_MAX_TURNS,v=[];for(let e=0;e<t.length;e+=i.REGRESSION_IMPACT_MAPPING_BATCH_SIZE)v.push(t.slice(e,e+i.REGRESSION_IMPACT_MAPPING_BATCH_SIZE));let y=v.length,b=0;n.logger.info.defaultLog(`[regression-impact] File-to-flow mapping: ${t.length} file(s) in ${y} batch(es) against ${e.length} flow(s)...`);let x=new c.default({concurrency:i.REGRESSION_IMPACT_MAPPING_CONCURRENCY}),S=[...await Promise.all([...v.entries()].map(([t,r])=>x.add(async()=>{try{return{batchIndex:t,batch:r,result:await _(e,r,o,s,l,u,d,f,g,t+1,p,h)}}catch(e){return n.logger.info.defaultLog(`[regression-impact] File-to-flow mapping batch crashed (${r.length} file(s)): ${String(e)}`),{batchIndex:t,batch:r,crashed:!0}}})))].sort((e,t)=>e.batchIndex-t.batchIndex),C=[],w=[],T=[],E=0,D=0,O=!1,k=!1,A=0,j=0,M=0,ee=0;for(let e of S){if(`crashed`in e){w.push(...e.batch);continue}let{result:t,batch:r,batchIndex:i}=e;for(let e of t.mappings){let t=e.flowIds.length>0?e.flowIds.join(`, `):`no flows`,r=e.confidence===`low`;b+=1,n.logger.info.defaultLog(`[regression-impact] ${b} - ${e.file} → ${t}${r?` [SMART GUESS — tracing budget hit, low confidence → uncertain]`:``}`)}C.push(...t.mappings),w.push(...t.incompleteFiles),E+=t.costUsd,D+=t.turns,O||=t.maxTurnsHit,k||=t.maxBudgetHit,A+=t.tokens.cacheReadTokens,j+=t.tokens.cacheCreationTokens,M+=t.tokens.inputTokens,ee+=t.tokens.outputTokens,T.push({label:`batch-${i+1}`,totalFiles:r.length,costUsd:t.costUsd,turns:t.turns,maxTurnsHit:t.maxTurnsHit,maxBudgetHit:t.maxBudgetHit,tokens:{inputTokens:t.tokens.inputTokens,outputTokens:t.tokens.outputTokens,cacheReadTokens:t.tokens.cacheReadTokens,cacheCreationTokens:t.tokens.cacheCreationTokens},mappingBreakdown:a.buildMappingBreakdown(t.mappings)})}return r.logCacheTokens(`mapping totals`,{cacheReadTokens:A,cacheCreationTokens:j,inputTokens:M,outputTokens:ee}),w.length>0&&n.logger.info.defaultLog(`[regression-impact] File-to-flow mapping INCOMPLETE for ${w.length} file(s) (batch aborted before mapping) — coverage for these is partial/missing: ${w.join(`, `)}`),{mappings:C,costUsd:E,turns:D,maxTurnsHit:O,maxBudgetHit:k,incompleteFiles:w,batchMetrics:T}}var y=class{context;astReachability;constructor(e,t){this.context=e,this.astReachability=t}async run(e,t){let{rootPath:r,branch:i,resolvedAnchorBranch:o,jwtToken:s,anthropicBaseUrl:c,projectType:l,mappingMaxTurns:u,fileDiffs:d}=this.context,{mappings:f,costUsd:p,turns:m,maxTurnsHit:h,maxBudgetHit:g,incompleteFiles:_,batchMetrics:y}=await v(e,t,r,i,o,s,c,l,this.astReachability,u,d),b=a.buildLowConfidenceFlowIds(f);if(b.size>0){let e=f.filter(e=>e.confidence===`low`).map(e=>e.file);n.logger.info.defaultLog(`[regression-impact] tracing-budget fallback: ${e.length} file(s) placed by a smart guess (${e.join(`, `)}) → ${b.size} flow(s) marked uncertain for deep verification`)}return{flowFileMap:a.buildFlowFileMap(f),flowFileReasons:a.buildFlowFileReasons(f),costUsd:p,turns:m,maxTurnsHit:h,maxBudgetHit:g,incompleteFiles:_,batchMetrics:y,mappingBreakdown:a.buildMappingBreakdown(f),mappingBreakdownFiles:a.buildMappingBreakdownFiles(f),...b.size>0?{lowConfidenceFlowIds:b}:{}}}};Object.defineProperty(e,`AgenticImpactMapper`,{enumerable:!0,get:function(){return y}})})),hee=s((e=>{var t=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`.split(``);e.encode=function(e){if(0<=e&&e<t.length)return t[e];throw TypeError(`Must be between 0 and 63: `+e)},e.decode=function(e){var t=65,n=90,r=97,i=122,a=48;return t<=e&&e<=n?e-t:r<=e&&e<=i?e-r+26:a<=e&&e<=57?e-a+52:e==43?62:e==47?63:-1}})),fz=s((e=>{var t=hee(),n=5,r=1<<n,i=r-1,a=r;function o(e){return e<0?(-e<<1)+1:(e<<1)+0}function s(e){var t=(e&1)==1,n=e>>1;return t?-n:n}e.encode=function(e){var r=``,s,c=o(e);do s=c&i,c>>>=n,c>0&&(s|=a),r+=t.encode(s);while(c>0);return r},e.decode=function(e,r,o){var c=e.length,l=0,u=0,d,f;do{if(r>=c)throw Error(`Expected more digits in base 64 VLQ value.`);if(f=t.decode(e.charCodeAt(r++)),f===-1)throw Error(`Invalid base64 digit: `+e.charAt(r-1));d=!!(f&a),f&=i,l+=f<<u,u+=n}while(d);o.value=s(l),o.rest=r}})),pz=s((e=>{function t(e,t,n){if(t in e)return e[t];if(arguments.length===3)return n;throw Error(`"`+t+`" is a required argument.`)}e.getArg=t;var n=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/,r=/^data:.+\,.+$/;function i(e){var t=e.match(n);return t?{scheme:t[1],auth:t[2],host:t[3],port:t[4],path:t[5]}:null}e.urlParse=i;function a(e){var t=``;return e.scheme&&(t+=e.scheme+`:`),t+=`//`,e.auth&&(t+=e.auth+`@`),e.host&&(t+=e.host),e.port&&(t+=`:`+e.port),e.path&&(t+=e.path),t}e.urlGenerate=a;function o(t){var n=t,r=i(t);if(r){if(!r.path)return t;n=r.path}for(var o=e.isAbsolute(n),s=n.split(/\/+/),c,l=0,u=s.length-1;u>=0;u--)c=s[u],c===`.`?s.splice(u,1):c===`..`?l++:l>0&&(c===``?(s.splice(u+1,l),l=0):(s.splice(u,2),l--));return n=s.join(`/`),n===``&&(n=o?`/`:`.`),r?(r.path=n,a(r)):n}e.normalize=o;function s(e,t){e===``&&(e=`.`),t===``&&(t=`.`);var n=i(t),s=i(e);if(s&&(e=s.path||`/`),n&&!n.scheme)return s&&(n.scheme=s.scheme),a(n);if(n||t.match(r))return t;if(s&&!s.host&&!s.path)return s.host=t,a(s);var c=t.charAt(0)===`/`?t:o(e.replace(/\/+$/,``)+`/`+t);return s?(s.path=c,a(s)):c}e.join=s,e.isAbsolute=function(e){return e.charAt(0)===`/`||n.test(e)};function c(e,t){e===``&&(e=`.`),e=e.replace(/\/$/,``);for(var n=0;t.indexOf(e+`/`)!==0;){var r=e.lastIndexOf(`/`);if(r<0||(e=e.slice(0,r),e.match(/^([^\/]+:\/)?\/*$/)))return t;++n}return Array(n+1).join(`../`)+t.substr(e.length+1)}e.relative=c;var l=function(){return!(`__proto__`in Object.create(null))}();function u(e){return e}function d(e){return p(e)?`$`+e:e}e.toSetString=l?u:d;function f(e){return p(e)?e.slice(1):e}e.fromSetString=l?u:f;function p(e){if(!e)return!1;var t=e.length;if(t<9||e.charCodeAt(t-1)!==95||e.charCodeAt(t-2)!==95||e.charCodeAt(t-3)!==111||e.charCodeAt(t-4)!==116||e.charCodeAt(t-5)!==111||e.charCodeAt(t-6)!==114||e.charCodeAt(t-7)!==112||e.charCodeAt(t-8)!==95||e.charCodeAt(t-9)!==95)return!1;for(var n=t-10;n>=0;n--)if(e.charCodeAt(n)!==36)return!1;return!0}function m(e,t,n){var r=g(e.source,t.source);return r!==0||(r=e.originalLine-t.originalLine,r!==0)||(r=e.originalColumn-t.originalColumn,r!==0||n)||(r=e.generatedColumn-t.generatedColumn,r!==0)||(r=e.generatedLine-t.generatedLine,r!==0)?r:g(e.name,t.name)}e.compareByOriginalPositions=m;function h(e,t,n){var r=e.generatedLine-t.generatedLine;return r!==0||(r=e.generatedColumn-t.generatedColumn,r!==0||n)||(r=g(e.source,t.source),r!==0)||(r=e.originalLine-t.originalLine,r!==0)||(r=e.originalColumn-t.originalColumn,r!==0)?r:g(e.name,t.name)}e.compareByGeneratedPositionsDeflated=h;function g(e,t){return e===t?0:e===null?1:t===null?-1:e>t?1:-1}function _(e,t){var n=e.generatedLine-t.generatedLine;return n!==0||(n=e.generatedColumn-t.generatedColumn,n!==0)||(n=g(e.source,t.source),n!==0)||(n=e.originalLine-t.originalLine,n!==0)||(n=e.originalColumn-t.originalColumn,n!==0)?n:g(e.name,t.name)}e.compareByGeneratedPositionsInflated=_;function v(e){return JSON.parse(e.replace(/^\)]}'[^\n]*\n/,``))}e.parseSourceMapInput=v;function y(e,t,n){if(t||=``,e&&(e[e.length-1]!==`/`&&t[0]!==`/`&&(e+=`/`),t=e+t),n){var r=i(n);if(!r)throw Error(`sourceMapURL could not be parsed`);if(r.path){var c=r.path.lastIndexOf(`/`);c>=0&&(r.path=r.path.substring(0,c+1))}t=s(a(r),t)}return o(t)}e.computeSourceURL=y})),mz=s((e=>{var t=pz(),n=Object.prototype.hasOwnProperty,r=typeof Map<`u`;function i(){this._array=[],this._set=r?new Map:Object.create(null)}i.fromArray=function(e,t){for(var n=new i,r=0,a=e.length;r<a;r++)n.add(e[r],t);return n},i.prototype.size=function(){return r?this._set.size:Object.getOwnPropertyNames(this._set).length},i.prototype.add=function(e,i){var a=r?e:t.toSetString(e),o=r?this.has(e):n.call(this._set,a),s=this._array.length;(!o||i)&&this._array.push(e),o||(r?this._set.set(e,s):this._set[a]=s)},i.prototype.has=function(e){if(r)return this._set.has(e);var i=t.toSetString(e);return n.call(this._set,i)},i.prototype.indexOf=function(e){if(r){var i=this._set.get(e);if(i>=0)return i}else{var a=t.toSetString(e);if(n.call(this._set,a))return this._set[a]}throw Error(`"`+e+`" is not in the set.`)},i.prototype.at=function(e){if(e>=0&&e<this._array.length)return this._array[e];throw Error(`No element indexed by `+e)},i.prototype.toArray=function(){return this._array.slice()},e.ArraySet=i})),hz=s((e=>{var t=pz();function n(e,n){var r=e.generatedLine,i=n.generatedLine,a=e.generatedColumn,o=n.generatedColumn;return i>r||i==r&&o>=a||t.compareByGeneratedPositionsInflated(e,n)<=0}function r(){this._array=[],this._sorted=!0,this._last={generatedLine:-1,generatedColumn:0}}r.prototype.unsortedForEach=function(e,t){this._array.forEach(e,t)},r.prototype.add=function(e){n(this._last,e)?(this._last=e,this._array.push(e)):(this._sorted=!1,this._array.push(e))},r.prototype.toArray=function(){return this._sorted||=(this._array.sort(t.compareByGeneratedPositionsInflated),!0),this._array},e.MappingList=r})),gz=s((e=>{var t=fz(),n=pz(),r=mz().ArraySet,i=hz().MappingList;function a(e){e||={},this._file=n.getArg(e,`file`,null),this._sourceRoot=n.getArg(e,`sourceRoot`,null),this._skipValidation=n.getArg(e,`skipValidation`,!1),this._sources=new r,this._names=new r,this._mappings=new i,this._sourcesContents=null}a.prototype._version=3,a.fromSourceMap=function(e){var t=e.sourceRoot,r=new a({file:e.file,sourceRoot:t});return e.eachMapping(function(e){var i={generated:{line:e.generatedLine,column:e.generatedColumn}};e.source!=null&&(i.source=e.source,t!=null&&(i.source=n.relative(t,i.source)),i.original={line:e.originalLine,column:e.originalColumn},e.name!=null&&(i.name=e.name)),r.addMapping(i)}),e.sources.forEach(function(i){var a=i;t!==null&&(a=n.relative(t,i)),r._sources.has(a)||r._sources.add(a);var o=e.sourceContentFor(i);o!=null&&r.setSourceContent(i,o)}),r},a.prototype.addMapping=function(e){var t=n.getArg(e,`generated`),r=n.getArg(e,`original`,null),i=n.getArg(e,`source`,null),a=n.getArg(e,`name`,null);this._skipValidation||this._validateMapping(t,r,i,a),i!=null&&(i=String(i),this._sources.has(i)||this._sources.add(i)),a!=null&&(a=String(a),this._names.has(a)||this._names.add(a)),this._mappings.add({generatedLine:t.line,generatedColumn:t.column,originalLine:r!=null&&r.line,originalColumn:r!=null&&r.column,source:i,name:a})},a.prototype.setSourceContent=function(e,t){var r=e;this._sourceRoot!=null&&(r=n.relative(this._sourceRoot,r)),t==null?this._sourcesContents&&(delete this._sourcesContents[n.toSetString(r)],Object.keys(this._sourcesContents).length===0&&(this._sourcesContents=null)):(this._sourcesContents||=Object.create(null),this._sourcesContents[n.toSetString(r)]=t)},a.prototype.applySourceMap=function(e,t,i){var a=t;if(t==null){if(e.file==null)throw Error(`SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map's "file" property. Both were omitted.`);a=e.file}var o=this._sourceRoot;o!=null&&(a=n.relative(o,a));var s=new r,c=new r;this._mappings.unsortedForEach(function(t){if(t.source===a&&t.originalLine!=null){var r=e.originalPositionFor({line:t.originalLine,column:t.originalColumn});r.source!=null&&(t.source=r.source,i!=null&&(t.source=n.join(i,t.source)),o!=null&&(t.source=n.relative(o,t.source)),t.originalLine=r.line,t.originalColumn=r.column,r.name!=null&&(t.name=r.name))}var l=t.source;l!=null&&!s.has(l)&&s.add(l);var u=t.name;u!=null&&!c.has(u)&&c.add(u)},this),this._sources=s,this._names=c,e.sources.forEach(function(t){var r=e.sourceContentFor(t);r!=null&&(i!=null&&(t=n.join(i,t)),o!=null&&(t=n.relative(o,t)),this.setSourceContent(t,r))},this)},a.prototype._validateMapping=function(e,t,n,r){if(t&&typeof t.line!=`number`&&typeof t.column!=`number`)throw Error(`original.line and original.column are not numbers -- you probably meant to omit the original mapping entirely and only map the generated position. If so, pass null for the original mapping instead of an object with empty or null values.`);if(!(e&&`line`in e&&`column`in e&&e.line>0&&e.column>=0&&!t&&!n&&!r)&&!(e&&`line`in e&&`column`in e&&t&&`line`in t&&`column`in t&&e.line>0&&e.column>=0&&t.line>0&&t.column>=0&&n))throw Error(`Invalid mapping: `+JSON.stringify({generated:e,source:n,original:t,name:r}))},a.prototype._serializeMappings=function(){for(var e=0,r=1,i=0,a=0,o=0,s=0,c=``,l,u,d,f,p=this._mappings.toArray(),m=0,h=p.length;m<h;m++){if(u=p[m],l=``,u.generatedLine!==r)for(e=0;u.generatedLine!==r;)l+=`;`,r++;else if(m>0){if(!n.compareByGeneratedPositionsInflated(u,p[m-1]))continue;l+=`,`}l+=t.encode(u.generatedColumn-e),e=u.generatedColumn,u.source!=null&&(f=this._sources.indexOf(u.source),l+=t.encode(f-s),s=f,l+=t.encode(u.originalLine-1-a),a=u.originalLine-1,l+=t.encode(u.originalColumn-i),i=u.originalColumn,u.name!=null&&(d=this._names.indexOf(u.name),l+=t.encode(d-o),o=d)),c+=l}return c},a.prototype._generateSourcesContent=function(e,t){return e.map(function(e){if(!this._sourcesContents)return null;t!=null&&(e=n.relative(t,e));var r=n.toSetString(e);return Object.prototype.hasOwnProperty.call(this._sourcesContents,r)?this._sourcesContents[r]:null},this)},a.prototype.toJSON=function(){var e={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};return this._file!=null&&(e.file=this._file),this._sourceRoot!=null&&(e.sourceRoot=this._sourceRoot),this._sourcesContents&&(e.sourcesContent=this._generateSourcesContent(e.sources,e.sourceRoot)),e},a.prototype.toString=function(){return JSON.stringify(this.toJSON())},e.SourceMapGenerator=a})),_z=s((e=>{e.GREATEST_LOWER_BOUND=1,e.LEAST_UPPER_BOUND=2;function t(n,r,i,a,o,s){var c=Math.floor((r-n)/2)+n,l=o(i,a[c],!0);return l===0?c:l>0?r-c>1?t(c,r,i,a,o,s):s==e.LEAST_UPPER_BOUND?r<a.length?r:-1:c:c-n>1?t(n,c,i,a,o,s):s==e.LEAST_UPPER_BOUND?c:n<0?-1:n}e.search=function(n,r,i,a){if(r.length===0)return-1;var o=t(-1,r.length,n,r,i,a||e.GREATEST_LOWER_BOUND);if(o<0)return-1;for(;o-1>=0&&i(r[o],r[o-1],!0)===0;)--o;return o}})),vz=s((e=>{function t(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function n(e,t){return Math.round(e+Math.random()*(t-e))}function r(e,i,a,o){if(a<o){var s=n(a,o),c=a-1;t(e,s,o);for(var l=e[o],u=a;u<o;u++)i(e[u],l)<=0&&(c+=1,t(e,c,u));t(e,c+1,u);var d=c+1;r(e,i,a,d-1),r(e,i,d+1,o)}}e.quickSort=function(e,t){r(e,t,0,e.length-1)}})),yz=s((e=>{var t=pz(),n=_z(),r=mz().ArraySet,i=fz(),a=vz().quickSort;function o(e,n){var r=e;return typeof e==`string`&&(r=t.parseSourceMapInput(e)),r.sections==null?new s(r,n):new l(r,n)}o.fromSourceMap=function(e,t){return s.fromSourceMap(e,t)},o.prototype._version=3,o.prototype.__generatedMappings=null,Object.defineProperty(o.prototype,`_generatedMappings`,{configurable:!0,enumerable:!0,get:function(){return this.__generatedMappings||this._parseMappings(this._mappings,this.sourceRoot),this.__generatedMappings}}),o.prototype.__originalMappings=null,Object.defineProperty(o.prototype,`_originalMappings`,{configurable:!0,enumerable:!0,get:function(){return this.__originalMappings||this._parseMappings(this._mappings,this.sourceRoot),this.__originalMappings}}),o.prototype._charIsMappingSeparator=function(e,t){var n=e.charAt(t);return n===`;`||n===`,`},o.prototype._parseMappings=function(e,t){throw Error(`Subclasses must implement _parseMappings`)},o.GENERATED_ORDER=1,o.ORIGINAL_ORDER=2,o.GREATEST_LOWER_BOUND=1,o.LEAST_UPPER_BOUND=2,o.prototype.eachMapping=function(e,n,r){var i=n||null,a=r||o.GENERATED_ORDER,s;switch(a){case o.GENERATED_ORDER:s=this._generatedMappings;break;case o.ORIGINAL_ORDER:s=this._originalMappings;break;default:throw Error(`Unknown order of iteration.`)}var c=this.sourceRoot;s.map(function(e){var n=e.source===null?null:this._sources.at(e.source);return n=t.computeSourceURL(c,n,this._sourceMapURL),{source:n,generatedLine:e.generatedLine,generatedColumn:e.generatedColumn,originalLine:e.originalLine,originalColumn:e.originalColumn,name:e.name===null?null:this._names.at(e.name)}},this).forEach(e,i)},o.prototype.allGeneratedPositionsFor=function(e){var r=t.getArg(e,`line`),i={source:t.getArg(e,`source`),originalLine:r,originalColumn:t.getArg(e,`column`,0)};if(i.source=this._findSourceIndex(i.source),i.source<0)return[];var a=[],o=this._findMapping(i,this._originalMappings,`originalLine`,`originalColumn`,t.compareByOriginalPositions,n.LEAST_UPPER_BOUND);if(o>=0){var s=this._originalMappings[o];if(e.column===void 0)for(var c=s.originalLine;s&&s.originalLine===c;)a.push({line:t.getArg(s,`generatedLine`,null),column:t.getArg(s,`generatedColumn`,null),lastColumn:t.getArg(s,`lastGeneratedColumn`,null)}),s=this._originalMappings[++o];else for(var l=s.originalColumn;s&&s.originalLine===r&&s.originalColumn==l;)a.push({line:t.getArg(s,`generatedLine`,null),column:t.getArg(s,`generatedColumn`,null),lastColumn:t.getArg(s,`lastGeneratedColumn`,null)}),s=this._originalMappings[++o]}return a},e.SourceMapConsumer=o;function s(e,n){var i=e;typeof e==`string`&&(i=t.parseSourceMapInput(e));var a=t.getArg(i,`version`),o=t.getArg(i,`sources`),s=t.getArg(i,`names`,[]),c=t.getArg(i,`sourceRoot`,null),l=t.getArg(i,`sourcesContent`,null),u=t.getArg(i,`mappings`),d=t.getArg(i,`file`,null);if(a!=this._version)throw Error(`Unsupported version: `+a);c&&=t.normalize(c),o=o.map(String).map(t.normalize).map(function(e){return c&&t.isAbsolute(c)&&t.isAbsolute(e)?t.relative(c,e):e}),this._names=r.fromArray(s.map(String),!0),this._sources=r.fromArray(o,!0),this._absoluteSources=this._sources.toArray().map(function(e){return t.computeSourceURL(c,e,n)}),this.sourceRoot=c,this.sourcesContent=l,this._mappings=u,this._sourceMapURL=n,this.file=d}s.prototype=Object.create(o.prototype),s.prototype.consumer=o,s.prototype._findSourceIndex=function(e){var n=e;if(this.sourceRoot!=null&&(n=t.relative(this.sourceRoot,n)),this._sources.has(n))return this._sources.indexOf(n);var r;for(r=0;r<this._absoluteSources.length;++r)if(this._absoluteSources[r]==e)return r;return-1},s.fromSourceMap=function(e,n){var i=Object.create(s.prototype),o=i._names=r.fromArray(e._names.toArray(),!0),l=i._sources=r.fromArray(e._sources.toArray(),!0);i.sourceRoot=e._sourceRoot,i.sourcesContent=e._generateSourcesContent(i._sources.toArray(),i.sourceRoot),i.file=e._file,i._sourceMapURL=n,i._absoluteSources=i._sources.toArray().map(function(e){return t.computeSourceURL(i.sourceRoot,e,n)});for(var u=e._mappings.toArray().slice(),d=i.__generatedMappings=[],f=i.__originalMappings=[],p=0,m=u.length;p<m;p++){var h=u[p],g=new c;g.generatedLine=h.generatedLine,g.generatedColumn=h.generatedColumn,h.source&&(g.source=l.indexOf(h.source),g.originalLine=h.originalLine,g.originalColumn=h.originalColumn,h.name&&(g.name=o.indexOf(h.name)),f.push(g)),d.push(g)}return a(i.__originalMappings,t.compareByOriginalPositions),i},s.prototype._version=3,Object.defineProperty(s.prototype,`sources`,{get:function(){return this._absoluteSources.slice()}});function c(){this.generatedLine=0,this.generatedColumn=0,this.source=null,this.originalLine=null,this.originalColumn=null,this.name=null}s.prototype._parseMappings=function(e,n){for(var r=1,o=0,s=0,l=0,u=0,d=0,f=e.length,p=0,m={},h={},g=[],_=[],v,y,b,x,S;p<f;)if(e.charAt(p)===`;`)r++,p++,o=0;else if(e.charAt(p)===`,`)p++;else{for(v=new c,v.generatedLine=r,x=p;x<f&&!this._charIsMappingSeparator(e,x);x++);if(y=e.slice(p,x),b=m[y],b)p+=y.length;else{for(b=[];p<x;)i.decode(e,p,h),S=h.value,p=h.rest,b.push(S);if(b.length===2)throw Error(`Found a source, but no line and column`);if(b.length===3)throw Error(`Found a source and line, but no column`);m[y]=b}v.generatedColumn=o+b[0],o=v.generatedColumn,b.length>1&&(v.source=u+b[1],u+=b[1],v.originalLine=s+b[2],s=v.originalLine,v.originalLine+=1,v.originalColumn=l+b[3],l=v.originalColumn,b.length>4&&(v.name=d+b[4],d+=b[4])),_.push(v),typeof v.originalLine==`number`&&g.push(v)}a(_,t.compareByGeneratedPositionsDeflated),this.__generatedMappings=_,a(g,t.compareByOriginalPositions),this.__originalMappings=g},s.prototype._findMapping=function(e,t,r,i,a,o){if(e[r]<=0)throw TypeError(`Line must be greater than or equal to 1, got `+e[r]);if(e[i]<0)throw TypeError(`Column must be greater than or equal to 0, got `+e[i]);return n.search(e,t,a,o)},s.prototype.computeColumnSpans=function(){for(var e=0;e<this._generatedMappings.length;++e){var t=this._generatedMappings[e];if(e+1<this._generatedMappings.length){var n=this._generatedMappings[e+1];if(t.generatedLine===n.generatedLine){t.lastGeneratedColumn=n.generatedColumn-1;continue}}t.lastGeneratedColumn=1/0}},s.prototype.originalPositionFor=function(e){var n={generatedLine:t.getArg(e,`line`),generatedColumn:t.getArg(e,`column`)},r=this._findMapping(n,this._generatedMappings,`generatedLine`,`generatedColumn`,t.compareByGeneratedPositionsDeflated,t.getArg(e,`bias`,o.GREATEST_LOWER_BOUND));if(r>=0){var i=this._generatedMappings[r];if(i.generatedLine===n.generatedLine){var a=t.getArg(i,`source`,null);a!==null&&(a=this._sources.at(a),a=t.computeSourceURL(this.sourceRoot,a,this._sourceMapURL));var s=t.getArg(i,`name`,null);return s!==null&&(s=this._names.at(s)),{source:a,line:t.getArg(i,`originalLine`,null),column:t.getArg(i,`originalColumn`,null),name:s}}}return{source:null,line:null,column:null,name:null}},s.prototype.hasContentsOfAllSources=function(){return this.sourcesContent?this.sourcesContent.length>=this._sources.size()&&!this.sourcesContent.some(function(e){return e==null}):!1},s.prototype.sourceContentFor=function(e,n){if(!this.sourcesContent)return null;var r=this._findSourceIndex(e);if(r>=0)return this.sourcesContent[r];var i=e;this.sourceRoot!=null&&(i=t.relative(this.sourceRoot,i));var a;if(this.sourceRoot!=null&&(a=t.urlParse(this.sourceRoot))){var o=i.replace(/^file:\/\//,``);if(a.scheme==`file`&&this._sources.has(o))return this.sourcesContent[this._sources.indexOf(o)];if((!a.path||a.path==`/`)&&this._sources.has(`/`+i))return this.sourcesContent[this._sources.indexOf(`/`+i)]}if(n)return null;throw Error(`"`+i+`" is not in the SourceMap.`)},s.prototype.generatedPositionFor=function(e){var n=t.getArg(e,`source`);if(n=this._findSourceIndex(n),n<0)return{line:null,column:null,lastColumn:null};var r={source:n,originalLine:t.getArg(e,`line`),originalColumn:t.getArg(e,`column`)},i=this._findMapping(r,this._originalMappings,`originalLine`,`originalColumn`,t.compareByOriginalPositions,t.getArg(e,`bias`,o.GREATEST_LOWER_BOUND));if(i>=0){var a=this._originalMappings[i];if(a.source===r.source)return{line:t.getArg(a,`generatedLine`,null),column:t.getArg(a,`generatedColumn`,null),lastColumn:t.getArg(a,`lastGeneratedColumn`,null)}}return{line:null,column:null,lastColumn:null}},e.BasicSourceMapConsumer=s;function l(e,n){var i=e;typeof e==`string`&&(i=t.parseSourceMapInput(e));var a=t.getArg(i,`version`),s=t.getArg(i,`sections`);if(a!=this._version)throw Error(`Unsupported version: `+a);this._sources=new r,this._names=new r;var c={line:-1,column:0};this._sections=s.map(function(e){if(e.url)throw Error(`Support for url field in sections not implemented.`);var r=t.getArg(e,`offset`),i=t.getArg(r,`line`),a=t.getArg(r,`column`);if(i<c.line||i===c.line&&a<c.column)throw Error(`Section offsets must be ordered and non-overlapping.`);return c=r,{generatedOffset:{generatedLine:i+1,generatedColumn:a+1},consumer:new o(t.getArg(e,`map`),n)}})}l.prototype=Object.create(o.prototype),l.prototype.constructor=o,l.prototype._version=3,Object.defineProperty(l.prototype,`sources`,{get:function(){for(var e=[],t=0;t<this._sections.length;t++)for(var n=0;n<this._sections[t].consumer.sources.length;n++)e.push(this._sections[t].consumer.sources[n]);return e}}),l.prototype.originalPositionFor=function(e){var r={generatedLine:t.getArg(e,`line`),generatedColumn:t.getArg(e,`column`)},i=n.search(r,this._sections,function(e,t){return e.generatedLine-t.generatedOffset.generatedLine||e.generatedColumn-t.generatedOffset.generatedColumn}),a=this._sections[i];return a?a.consumer.originalPositionFor({line:r.generatedLine-(a.generatedOffset.generatedLine-1),column:r.generatedColumn-(a.generatedOffset.generatedLine===r.generatedLine?a.generatedOffset.generatedColumn-1:0),bias:e.bias}):{source:null,line:null,column:null,name:null}},l.prototype.hasContentsOfAllSources=function(){return this._sections.every(function(e){return e.consumer.hasContentsOfAllSources()})},l.prototype.sourceContentFor=function(e,t){for(var n=0;n<this._sections.length;n++){var r=this._sections[n].consumer.sourceContentFor(e,!0);if(r)return r}if(t)return null;throw Error(`"`+e+`" is not in the SourceMap.`)},l.prototype.generatedPositionFor=function(e){for(var n=0;n<this._sections.length;n++){var r=this._sections[n];if(r.consumer._findSourceIndex(t.getArg(e,`source`))!==-1){var i=r.consumer.generatedPositionFor(e);if(i)return{line:i.line+(r.generatedOffset.generatedLine-1),column:i.column+(r.generatedOffset.generatedLine===i.line?r.generatedOffset.generatedColumn-1:0)}}}return{line:null,column:null}},l.prototype._parseMappings=function(e,n){this.__generatedMappings=[],this.__originalMappings=[];for(var r=0;r<this._sections.length;r++)for(var i=this._sections[r],o=i.consumer._generatedMappings,s=0;s<o.length;s++){var c=o[s],l=i.consumer._sources.at(c.source);l=t.computeSourceURL(i.consumer.sourceRoot,l,this._sourceMapURL),this._sources.add(l),l=this._sources.indexOf(l);var u=null;c.name&&(u=i.consumer._names.at(c.name),this._names.add(u),u=this._names.indexOf(u));var d={source:l,generatedLine:c.generatedLine+(i.generatedOffset.generatedLine-1),generatedColumn:c.generatedColumn+(i.generatedOffset.generatedLine===c.generatedLine?i.generatedOffset.generatedColumn-1:0),originalLine:c.originalLine,originalColumn:c.originalColumn,name:u};this.__generatedMappings.push(d),typeof d.originalLine==`number`&&this.__originalMappings.push(d)}a(this.__generatedMappings,t.compareByGeneratedPositionsDeflated),a(this.__originalMappings,t.compareByOriginalPositions)},e.IndexedSourceMapConsumer=l})),bz=s((e=>{var t=gz().SourceMapGenerator,n=pz(),r=/(\r?\n)/,i=10,a=`$$$isSourceNode$$$`;function o(e,t,n,r,i){this.children=[],this.sourceContents={},this.line=e??null,this.column=t??null,this.source=n??null,this.name=i??null,this[a]=!0,r!=null&&this.add(r)}o.fromStringWithSourceMap=function(e,t,i){var a=new o,s=e.split(r),c=0,l=function(){return e()+(e()||``);function e(){return c<s.length?s[c++]:void 0}},u=1,d=0,f=null;return t.eachMapping(function(e){if(f!==null)if(u<e.generatedLine)p(f,l()),u++,d=0;else{var t=s[c]||``,n=t.substr(0,e.generatedColumn-d);s[c]=t.substr(e.generatedColumn-d),d=e.generatedColumn,p(f,n),f=e;return}for(;u<e.generatedLine;)a.add(l()),u++;if(d<e.generatedColumn){var t=s[c]||``;a.add(t.substr(0,e.generatedColumn)),s[c]=t.substr(e.generatedColumn),d=e.generatedColumn}f=e},this),c<s.length&&(f&&p(f,l()),a.add(s.splice(c).join(``))),t.sources.forEach(function(e){var r=t.sourceContentFor(e);r!=null&&(i!=null&&(e=n.join(i,e)),a.setSourceContent(e,r))}),a;function p(e,t){if(e===null||e.source===void 0)a.add(t);else{var r=i?n.join(i,e.source):e.source;a.add(new o(e.originalLine,e.originalColumn,r,t,e.name))}}},o.prototype.add=function(e){if(Array.isArray(e))e.forEach(function(e){this.add(e)},this);else if(e[a]||typeof e==`string`)e&&this.children.push(e);else throw TypeError(`Expected a SourceNode, string, or an array of SourceNodes and strings. Got `+e);return this},o.prototype.prepend=function(e){if(Array.isArray(e))for(var t=e.length-1;t>=0;t--)this.prepend(e[t]);else if(e[a]||typeof e==`string`)this.children.unshift(e);else throw TypeError(`Expected a SourceNode, string, or an array of SourceNodes and strings. Got `+e);return this},o.prototype.walk=function(e){for(var t,n=0,r=this.children.length;n<r;n++)t=this.children[n],t[a]?t.walk(e):t!==``&&e(t,{source:this.source,line:this.line,column:this.column,name:this.name})},o.prototype.join=function(e){var t,n,r=this.children.length;if(r>0){for(t=[],n=0;n<r-1;n++)t.push(this.children[n]),t.push(e);t.push(this.children[n]),this.children=t}return this},o.prototype.replaceRight=function(e,t){var n=this.children[this.children.length-1];return n[a]?n.replaceRight(e,t):typeof n==`string`?this.children[this.children.length-1]=n.replace(e,t):this.children.push(``.replace(e,t)),this},o.prototype.setSourceContent=function(e,t){this.sourceContents[n.toSetString(e)]=t},o.prototype.walkSourceContents=function(e){for(var t=0,r=this.children.length;t<r;t++)this.children[t][a]&&this.children[t].walkSourceContents(e);for(var i=Object.keys(this.sourceContents),t=0,r=i.length;t<r;t++)e(n.fromSetString(i[t]),this.sourceContents[i[t]])},o.prototype.toString=function(){var e=``;return this.walk(function(t){e+=t}),e},o.prototype.toStringWithSourceMap=function(e){var n={code:``,line:1,column:0},r=new t(e),a=!1,o=null,s=null,c=null,l=null;return this.walk(function(e,t){n.code+=e,t.source!==null&&t.line!==null&&t.column!==null?((o!==t.source||s!==t.line||c!==t.column||l!==t.name)&&r.addMapping({source:t.source,original:{line:t.line,column:t.column},generated:{line:n.line,column:n.column},name:t.name}),o=t.source,s=t.line,c=t.column,l=t.name,a=!0):a&&=(r.addMapping({generated:{line:n.line,column:n.column}}),o=null,!1);for(var u=0,d=e.length;u<d;u++)e.charCodeAt(u)===i?(n.line++,n.column=0,u+1===d?(o=null,a=!1):a&&r.addMapping({source:t.source,original:{line:t.line,column:t.column},generated:{line:n.line,column:n.column},name:t.name})):n.column++}),this.walkSourceContents(function(e,t){r.setSourceContent(e,t)}),{code:n.code,map:r}},e.SourceNode=o})),xz=s((e=>{e.SourceMapGenerator=gz().SourceMapGenerator,e.SourceMapConsumer=yz().SourceMapConsumer,e.SourceNode=bz().SourceNode})),Sz=s(((e,t)=>{var n=Object.prototype.toString,r=typeof Buffer<`u`&&typeof Buffer.alloc==`function`&&typeof Buffer.allocUnsafe==`function`&&typeof Buffer.from==`function`;function i(e){return n.call(e).slice(8,-1)===`ArrayBuffer`}function a(e,t,n){t>>>=0;var i=e.byteLength-t;if(i<0)throw RangeError(`'offset' is out of bounds`);if(n===void 0)n=i;else if(n>>>=0,n>i)throw RangeError(`'length' is out of bounds`);return r?Buffer.from(e.slice(t,t+n)):new Buffer(new Uint8Array(e.slice(t,t+n)))}function o(e,t){if((typeof t!=`string`||t===``)&&(t=`utf8`),!Buffer.isEncoding(t))throw TypeError(`"encoding" must be a valid string encoding`);return r?Buffer.from(e,t):new Buffer(e,t)}function s(e,t,n){if(typeof e==`number`)throw TypeError(`"value" argument must not be a number`);return i(e)?a(e,t,n):typeof e==`string`?o(e,t):r?Buffer.from(e):new Buffer(e)}t.exports=s})),Cz=s(((e,t)=>{var n=xz().SourceMapConsumer,r=require(`path`),i;try{i=require(`fs`),(!i.existsSync||!i.readFileSync)&&(i=null)}catch{}var a=Sz();function o(e,t){return e.require(t)}var s=!1,c=!1,l=!1,u=`auto`,d={},f={},p=/^data:application\/json[^,]+base64,/,m=[],h=[];function g(){return u===`browser`?!0:u===`node`?!1:typeof window<`u`&&typeof XMLHttpRequest==`function`&&!(window.require&&window.module&&window.process&&window.process.type===`renderer`)}function _(){return typeof process==`object`&&process!==null&&typeof process.on==`function`}function v(){return typeof process==`object`&&process!==null?process.version:``}function y(){if(typeof process==`object`&&process!==null)return process.stderr}function b(e){if(typeof process==`object`&&process!==null&&typeof process.exit==`function`)return process.exit(e)}function x(e){return function(t){for(var n=0;n<e.length;n++){var r=e[n](t);if(r)return r}return null}}var S=x(m);m.push(function(e){if(e=e.trim(),/^file:/.test(e)&&(e=e.replace(/file:\/\/\/(\w:)?/,function(e,t){return t?``:`/`})),e in d)return d[e];var t=``;try{if(i)i.existsSync(e)&&(t=i.readFileSync(e,`utf8`));else{var n=new XMLHttpRequest;n.open(`GET`,e,!1),n.send(null),n.readyState===4&&n.status===200&&(t=n.responseText)}}catch{}return d[e]=t});function C(e,t){if(!e)return t;var n=r.dirname(e),i=/^\w+:\/\/[^\/]*/.exec(n),a=i?i[0]:``,o=n.slice(a.length);return a&&/^\/\w\:/.test(o)?(a+=`/`,a+r.resolve(n.slice(a.length),t).replace(/\\/g,`/`)):a+r.resolve(n.slice(a.length),t)}function w(e){var t;if(g())try{var n=new XMLHttpRequest;n.open(`GET`,e,!1),n.send(null),t=n.readyState===4?n.responseText:null;var r=n.getResponseHeader(`SourceMap`)||n.getResponseHeader(`X-SourceMap`);if(r)return r}catch{}t=S(e);for(var i=/(?:\/\/[@#][\s]*sourceMappingURL=([^\s'"]+)[\s]*$)|(?:\/\*[@#][\s]*sourceMappingURL=([^\s*'"]+)[\s]*(?:\*\/)[\s]*$)/gm,a,o;o=i.exec(t);)a=o;return a?a[1]:null}var T=x(h);h.push(function(e){var t=w(e);if(!t)return null;var n;return p.test(t)?(n=a(t.slice(t.indexOf(`,`)+1),`base64`).toString(),t=e):(t=C(e,t),n=S(t)),n?{url:t,map:n}:null});function E(e){var t=f[e.source];if(!t){var r=T(e.source);r?(t=f[e.source]={url:r.url,map:new n(r.map)},t.map.sourcesContent&&t.map.sources.forEach(function(e,n){var r=t.map.sourcesContent[n];if(r){var i=C(t.url,e);d[i]=r}})):t=f[e.source]={url:null,map:null}}if(t&&t.map&&typeof t.map.originalPositionFor==`function`){var i=t.map.originalPositionFor(e);if(i.source!==null)return i.source=C(t.url,i.source),i}return e}function D(e){var t=/^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(e);if(t){var n=E({source:t[2],line:+t[3],column:t[4]-1});return`eval at `+t[1]+` (`+n.source+`:`+n.line+`:`+(n.column+1)+`)`}return t=/^eval at ([^(]+) \((.+)\)$/.exec(e),t?`eval at `+t[1]+` (`+D(t[2])+`)`:e}function O(){var e,t=``;if(this.isNative())t=`native`;else{e=this.getScriptNameOrSourceURL(),!e&&this.isEval()&&(t=this.getEvalOrigin(),t+=`, `),e?t+=e:t+=`<anonymous>`;var n=this.getLineNumber();if(n!=null){t+=`:`+n;var r=this.getColumnNumber();r&&(t+=`:`+r)}}var i=``,a=this.getFunctionName(),o=!0,s=this.isConstructor();if(this.isToplevel()||s)s?i+=`new `+(a||`<anonymous>`):a?i+=a:(i+=t,o=!1);else{var c=this.getTypeName();c===`[object Object]`&&(c=`null`);var l=this.getMethodName();a?(c&&a.indexOf(c)!=0&&(i+=c+`.`),i+=a,l&&a.indexOf(`.`+l)!=a.length-l.length-1&&(i+=` [as `+l+`]`)):i+=c+`.`+(l||`<anonymous>`)}return o&&(i+=` (`+t+`)`),i}function k(e){var t={};return Object.getOwnPropertyNames(Object.getPrototypeOf(e)).forEach(function(n){t[n]=/^(?:is|get)/.test(n)?function(){return e[n].call(e)}:e[n]}),t.toString=O,t}function A(e,t){if(t===void 0&&(t={nextPosition:null,curPosition:null}),e.isNative())return t.curPosition=null,e;var n=e.getFileName()||e.getScriptNameOrSourceURL();if(n){var r=e.getLineNumber(),i=e.getColumnNumber()-1,a=/^v(10\.1[6-9]|10\.[2-9][0-9]|10\.[0-9]{3,}|1[2-9]\d*|[2-9]\d|\d{3,}|11\.11)/.test(v())?0:62;r===1&&i>a&&!g()&&!e.isEval()&&(i-=a);var o=E({source:n,line:r,column:i});t.curPosition=o,e=k(e);var s=e.getFunctionName;return e.getFunctionName=function(){return t.nextPosition==null?s():t.nextPosition.name||s()},e.getFileName=function(){return o.source},e.getLineNumber=function(){return o.line},e.getColumnNumber=function(){return o.column+1},e.getScriptNameOrSourceURL=function(){return o.source},e}var c=e.isEval()&&e.getEvalOrigin();return c?(c=D(c),e=k(e),e.getEvalOrigin=function(){return c},e):e}function j(e,t){l&&(d={},f={});for(var n=e.name||`Error`,r=e.message||``,i=n+`: `+r,a={nextPosition:null,curPosition:null},o=[],s=t.length-1;s>=0;s--)o.push(`
|
|
722
722
|
at `+A(t[s],a)),a.nextPosition=a.curPosition;return a.curPosition=a.nextPosition=null,i+o.reverse().join(``)}function M(e){var t=/\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(e.stack);if(t){var n=t[1],r=+t[2],a=+t[3],o=d[n];if(!o&&i&&i.existsSync(n))try{o=i.readFileSync(n,`utf8`)}catch{o=``}if(o){var s=o.split(/(?:\r\n|\r|\n)/)[r-1];if(s)return n+`:`+r+`
|
|
723
723
|
`+s+`
|
|
724
724
|
`+Array(a).join(` `)+`^`}}return null}function ee(e){var t=M(e),n=y();n&&n._handle&&n._handle.setBlocking&&n._handle.setBlocking(!0),t&&(console.error(),console.error(t)),console.error(e.stack),b(1)}function N(){var e=process.emit;process.emit=function(t){if(t===`uncaughtException`){var n=arguments[1]&&arguments[1].stack,r=this.listeners(t).length>0;if(n&&!r)return ee(arguments[1])}return e.apply(this,arguments)}}var te=m.slice(0),P=h.slice(0);e.wrapCallSite=A,e.getErrorSource=M,e.mapSourcePosition=E,e.retrieveSourceMap=T,e.install=function(e){if(e||={},e.environment&&(u=e.environment,[`node`,`browser`,`auto`].indexOf(u)===-1))throw Error(`environment `+u+` was unknown. Available options are {auto, browser, node}`);if(e.retrieveFile&&(e.overrideRetrieveFile&&(m.length=0),m.unshift(e.retrieveFile)),e.retrieveSourceMap&&(e.overrideRetrieveSourceMap&&(h.length=0),h.unshift(e.retrieveSourceMap)),e.hookRequire&&!g()){var n=o(t,`module`),r=n.prototype._compile;r.__sourceMapSupport||(n.prototype._compile=function(e,t){return d[t]=e,f[t]=void 0,r.call(this,e,t)},n.prototype._compile.__sourceMapSupport=!0)}if(l||=`emptyCacheBetweenOperations`in e?e.emptyCacheBetweenOperations:!1,s||(s=!0,Error.prepareStackTrace=j),!c){var i=`handleUncaughtExceptions`in e?e.handleUncaughtExceptions:!0;try{o(t,`worker_threads`).isMainThread===!1&&(i=!1)}catch{}i&&_()&&(c=!0,N())}},e.resetRetrieveHandlers=function(){m.length=0,h.length=0,m=te.slice(0),h=P.slice(0),T=x(h),S=x(m)}})),wz=s(((e,t)=>{
|
|
@@ -32588,7 +32588,7 @@ How to read it:
|
|
|
32588
32588
|
|
|
32589
32589
|
${e.map(e=>f(e,t)).join(`
|
|
32590
32590
|
|
|
32591
|
-
`)}`}let m=[`node_modules`,`dist`,`.next`,`.cache`],h=[`build`,`out`,`coverage`];function g(e,t){return m.some(e=>t.includes(`/${e}/`))?!0:h.some(n=>t.startsWith(`${e}/${n}/`))}var _=class{rootPath;pathScope;project;preloadMsValue=0;constructor(e,t){this.rootPath=a.default.normalize(a.default.resolve(e)),this.pathScope=t}init(){let e=r.findupFile(this.rootPath,`tsconfig.json`)??void 0,t=Date.now();this.project=new s.Project({...(0,o.isDefined)(e)?{tsConfigFilePath:e}:{},skipAddingFilesFromTsConfig:!0,compilerOptions:{allowJs:!1}});let n=m.map(e=>`!${this.rootPath}/**/${e}/**`),i=h.map(e=>`!${this.rootPath}/${e}/**`);this.project.addSourceFilesAtPaths([`${this.rootPath}/**/*.{ts,tsx,mts,cts}`,...n,...i]),this.preloadMsValue=Date.now()-t}getImporters(e){let t=this.requireProject().getSourceFile(a.default.normalize(a.default.resolve(e)));return(0,o.isDefined)(t)?t.getReferencingSourceFiles().map(e=>a.default.normalize(e.getFilePath())).filter(e=>this.pathScope.isInside(e)&&!g(this.rootPath,e)):[]}hasFile(e){return this.project?.getSourceFile(a.default.normalize(a.default.resolve(e)))!==void 0}loadedFileCount(){return this.project?.getSourceFiles().length??0}initDurationMs(){return this.preloadMsValue}requireProject(){if(!(0,o.isDefined)(this.project))throw Error(`[ast-mapping] TsProjectLoader.init() must be called before querying importers`);return this.project}},v=class{mapper;constructor(e){this.mapper=e}run(e,t){let r=e.map(e=>({flowId:e.flowId,entryFiles:e.trace.entryFiles})),a=this.mapper.mapFiles(r,t);if(n.logger.info.defaultLog(`[regression-impact] File-to-flow mapping (AST): preloaded ${a.stats.filesLoaded} file(s) in ${a.stats.preloadMs}ms`),a.residual.length>0&&n.logger.info.defaultLog(`[regression-impact] File-to-flow mapping (AST): ${a.residual.length} changed file(s) reached no flow entry`),a.staleEntryFlowIds.length>0){let t=new Map(e.map(e=>[e.flowId,e]));n.logger.info.defaultLog(`[regression-impact] File-to-flow mapping (AST): ${a.staleEntryFlowIds.length} flow(s) have stale entry files (would go to LLM in hybrid):`);for(let e of a.staleEntryFlowIds){let r=t.get(e),i=r?.trace.entryFiles.join(`, `)??`(unknown)`;n.logger.info.defaultLog(`[regression-impact] ${r?.name??e} [${e}] — entries: ${i}`)}}return Promise.resolve({flowFileMap:i.buildFlowFileMap(a.resolved),costUsd:0,turns:0,maxTurnsHit:!1})}};function y(e,t){return new l(new _(e,new u(e)),t)}function b(e,t){return new v(y(e,t))}function x(e,t,i,a){let o=new _(e,new u(e));o.init();let s=new r.ReachabilityPathFinder(o,t),c=i.map(e=>({flowId:e.flowId,entryFiles:e.trace.entryFiles})),l=new Map(s.findPaths(c,a).map(e=>[e.file,e])),d=new Map(i.map(e=>[e.flowId,e.name]));return n.logger.info.defaultLog(`[regression-impact] File-to-flow mapping (agentic-ast): preloaded ${o.loadedFileCount()} file(s) in ${o.initDurationMs()}ms; static paths ready for ${l.size} changed file(s)`),e=>p(e.map(e=>l.get(e)).filter(e=>e!==void 0),e=>d.get(e))}e.createAgenticAstReachabilityProvider=x,e.createAstFileFlowMapper=y,e.createAstImpactMapper=b})),jU=s((e=>{let t=_R(),n=rz();e.HybridImpactMapper=class{astMapper;agenticMapper;constructor(e,t){this.astMapper=e,this.agenticMapper=t}async run(e,r){let i=e.map(e=>({flowId:e.flowId,entryFiles:e.trace.entryFiles})),a=this.astMapper.mapFiles(i,r),o=n.buildFlowFileMap(a.resolved);if(t.logger.info.defaultLog(`[regression-impact] Hybrid: AST attributed ${a.resolved.length} file(s) across ${o.size} flow(s); ${a.staleEntryFlowIds.length} flow(s) have stale entries → LLM re-check`),a.staleEntryFlowIds.length===0)return t.logger.info.defaultLog(`[regression-impact] Hybrid: no stale-entry flows — LLM skipped entirely.`),{flowFileMap:o,costUsd:0,turns:0,maxTurnsHit:!1};let s=new Set(a.staleEntryFlowIds),c=e.filter(e=>s.has(e.flowId));t.logger.info.defaultLog(`[regression-impact] Hybrid: ${c.length} stale-entry flow(s) → LLM (${r.length} changed file(s)):`);for(let e of c)t.logger.info.defaultLog(`[regression-impact] ${e.name} [${e.flowId}] — entries: ${e.trace.entryFiles.join(`, `)}`);let l=await this.agenticMapper.run(c,r),u=new Map(o);for(let[e,t]of l.flowFileMap)u.set(e,t);return{flowFileMap:u,flowFileReasons:l.flowFileReasons,costUsd:l.costUsd,turns:l.turns,maxTurnsHit:l.maxTurnsHit}}}})),Pee=s((e=>{let t=ur(),n=_R(),r=$R(),i=QR(),a=nz(),o=t.__toESM(require(`node:crypto`)),s=t.__toESM(cz()),c=[`Read`,`Grep`,`Glob`];function l(e,t){let n=[];for(let r=0;r<e.length;r+=Math.max(1,t))n.push(e.slice(r,r+Math.max(1,t)));return n}function u(e,t){let n=e;return n===void 0||!Array.isArray(n.guesses)?[]:n.guesses.map(e=>({file:e.file,flowIds:(Array.isArray(e.flowIds)?e.flowIds:[]).filter(e=>t.has(e)),reason:e.reason}))}async function d(e,t,s,l,d){let{query:f,isResultMessage:p,isErrorResult:m,getMessageContentBlocks:h}=await Promise.resolve().then(()=>lz()),g=`shallow-map batch #${l}`,_={guesses:[],costUsd:0,turns:0,maxTurnsHit:!1,metric:{label:`shallow-batch-${l}`,totalFiles:t.length,costUsd:0,turns:0,maxTurnsHit:!1,maxBudgetHit:!1,tokens:{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0}},failedFiles:[...t]},v=i.getPerFileDiffs(t,d.rootPath,d.branch,d.resolvedAnchorBranch,d.isUncommitted),y=f({prompt:a.buildShallowMapPrompt(e,t,v,d.branch,d.resolvedAnchorBranch,i.REGRESSION_IMPACT_SHALLOW_DIFF_MAX_CHARS),options:{model:i.REGRESSION_IMPACT_SONNET_MODEL,systemPrompt:a.buildShallowMapSystemPrompt(),allowedTools:c,permissionMode:i.REGRESSION_PERMISSION_MODE,allowDangerouslySkipPermissions:!0,maxBudgetUsd:i.REGRESSION_IMPACT_AGENTIC_MAX_BUDGET_USD,maxTurns:25,cwd:d.rootPath,sessionId:(0,o.randomUUID)(),outputFormat:{type:`json_schema`,schema:r.RESIDUAL_ROUGH_MAP_OUTPUT_SCHEMA},env:{...process.env,...r.buildAnthropicSdkEnv({proxyUrl:d.anthropicBaseUrl,jwtToken:d.jwtToken??``,requestId:n.logger.getRequestId()})}}});r.logAgentCwd(g,d.rootPath);let b=0;for await(let e of y){if(!p(e)){let t=h(e);t!==void 0&&t.length>0&&(b++,r.logAgentActivity(g,b,t));continue}if(m(e))return n.logger.info.defaultLog(`[regression-impact] Shallow mapping ${g} error: ${e.subtype} — its files map to no flow`),_;let i=e.num_turns,a=r.logCacheTokensFromMessage(g,e);return{guesses:u(e.structured_output,s),costUsd:e.total_cost_usd,turns:i,maxTurnsHit:i>=25,metric:{label:`shallow-batch-${l}`,totalFiles:t.length,costUsd:e.total_cost_usd,turns:i,maxTurnsHit:i>=25,maxBudgetHit:!1,tokens:a},failedFiles:[]}}return _}e.ShallowImpactMapper=class{constructor(e){this.context=e}async run(e,t){let r=new Set(e.map(e=>e.flowId)),a=l(t,i.REGRESSION_IMPACT_RESIDUAL_BATCH_SIZE);n.logger.info.defaultLog(`[regression-impact] Shallow mapping: ${t.length} changed file(s) in ${a.length} batch(es) (path + diff, Read/Grep/Glob)`);let o=new s.default({concurrency:i.REGRESSION_IMPACT_RESIDUAL_CONCURRENCY}),c=(await Promise.all([...a.entries()].map(([t,i])=>o.add(async()=>{try{return await d(e,i,r,t+1,this.context)}catch(e){return n.logger.info.defaultLog(`[regression-impact] Shallow mapping batch #${t+1} crashed (${i.length} file(s)): ${String(e)}`),{guesses:[],costUsd:0,turns:0,maxTurnsHit:!1,metric:{label:`shallow-batch-${t+1}`,totalFiles:i.length,costUsd:0,turns:0,maxTurnsHit:!1,maxBudgetHit:!1,tokens:{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0}},failedFiles:[...i]}}})))).filter(e=>e!==void 0),u=new Map,f=new Map,p=new Set,m=0,h=0,g=!1,_=[],v=[];for(let e of c){m+=e.costUsd,h+=e.turns,g||=e.maxTurnsHit,_.push(e.metric),v.push(...e.failedFiles);for(let t of e.guesses){if(t.flowIds.length===0)continue;let e=t.reason??`shallow map: guessed from path + diff`;for(let n of t.flowIds){let r=u.get(n)??new Set;r.add(t.file),u.set(n,r),p.add(n);let i=f.get(n)??new Map;i.set(t.file,`shallow (low confidence): ${e}`),f.set(n,i)}}}return{flowFileMap:u,flowFileReasons:f,costUsd:m,turns:h,maxTurnsHit:g,incompleteFiles:v,batchMetrics:_,lowConfidenceFlowIds:p}}}})),MU=s((e=>{_R(),$R();let t=QR();rz();let n=dz();var r=class{context;repoRoot;constructor(e,t){this.context=e,this.repoRoot=t}async run(e,t){let{createAgenticAstReachabilityProvider:r}=await Promise.resolve().then(()=>AU()),i=r(this.context.rootPath,this.repoRoot,e,t);return new n.AgenticImpactMapper(this.context,i).run(e,t)}};async function i(e){if(e.strategy===`ast`){let{createAstImpactMapper:n}=await Promise.resolve().then(()=>AU()),r=t.getRepoRoot(e.rootPath);return n(e.rootPath,r)}if(e.strategy===`hybrid`){let{createAstFileFlowMapper:r}=await Promise.resolve().then(()=>AU()),{HybridImpactMapper:i}=await Promise.resolve().then(()=>jU()),a=t.getRepoRoot(e.rootPath);return new i(r(e.rootPath,a),new n.AgenticImpactMapper(e))}if(e.strategy===`agentic-ast`)return new r(e,t.getRepoRoot(e.rootPath));if(e.strategy===`shallow`){let{ShallowImpactMapper:t}=await Promise.resolve().then(()=>Pee());return new t({rootPath:e.rootPath,branch:e.branch,resolvedAnchorBranch:e.resolvedAnchorBranch,jwtToken:e.jwtToken,anthropicBaseUrl:e.anthropicBaseUrl,isUncommitted:e.isUncommitted??!1})}return new n.AgenticImpactMapper(e)}e.createImpactMapper=i})),NU=s((e=>{let t=ur(),n=_R(),r=ZR(),i=$R(),a=ez(),o=QR(),s=tz(),c=nz();rz();let l=dz(),u=t.__toESM(Ei()),d=t.__toESM(vR()),f=t.__toESM(require(`node:fs/promises`)),p=t.__toESM(require(`node:async_hooks`)),m=t.__toESM(ie()),h=t.__toESM(Fc()),g=t.__toESM(require(`node:process`)),_=t.__toESM(require(`node:os`));t.__toESM(require(`node:tty`));let v=t.__toESM(require(`node:crypto`)),y=t.__toESM(require(`node:fs`)),b=t.__toESM(XR()),x=t.__toESM(MB()),S=t.__toESM(require(`node:child_process`)),C=t.__toESM(require(`node:util`)),w=t.__toESM(require(`@prisma/internals`)),T=t.__toESM(OB()),E=t.__toESM(require(`node:zlib`)),D=t.__toESM(PV()),O=t.__toESM(IV()),k=t.__toESM(VV()),A=t.__toESM(cz()),j=t.__toESM(require(`node:events`)),M=t.__toESM(FH()),ee=t.__toESM(SU()),N=t.__toESM(Nee()),te=t.__toESM(DU()),P=t.__toESM(OU()),F=t.__toESM(IH());t.__toESM(require(`node:readline`));let I=t.__toESM(require(`node:path`)),L=t.__toESM(require(`node:module`)),ne=t.__toESM(require(`@anthropic-ai/claude-agent-sdk`));var R=class e{rootPath;absolutePath;static EARLY_FILENAME_VAR=`$early_filename`;constructor(e){this.rootPath=d.default.normalizeTrim(n.getGlobalConfig().getRootPath());let t=d.default.normalizeTrim(e),r=d.default.normalizeTrim(this.rootPath);if(t===r||t.startsWith(r+d.default.sep))this.absolutePath=t;else{let e=t.replace(/^\//,``);this.absolutePath=d.default.resolve(this.rootPath,e)}}static fromSourceFile(t){let r=d.default.normalizeTrim(t.getFilePath());return new e(d.default.relative(d.default.normalizeTrim(n.getGlobalConfig().getRootPath()),r))}static fromAbsolutePath(t){let r=d.default.normalizeTrim(t);return new e(d.default.relative(d.default.normalizeTrim(n.getGlobalConfig().getRootPath()),r))}static fromRelativePath(t){return new e(t)}getRelativeFilePath(){return d.default.relative(this.rootPath,this.absolutePath)}getAbsoluteFilePath(){return this.absolutePath}async isFileExists(){try{return(await f.default.stat(this.absolutePath)).isFile()}catch{return!1}}async isDirectoryExists(){try{return(await f.default.stat(this.absolutePath)).isDirectory()}catch{return!1}}async createDirectory(e){await f.default.mkdir(this.absolutePath,{recursive:e?.recursive??!0})}async getText(){try{return await f.default.readFile(this.absolutePath,`utf8`)}catch{return``}}async upsert(e){let t=d.default.dirname(this.absolutePath);await f.default.mkdir(t,{recursive:!0}),await(await this.isFileExists()?f.default.appendFile(this.absolutePath,e):f.default.writeFile(this.absolutePath,e)),n.logger.info.defaultLog(`Upserted file`,{path:this.getRelativeFilePath()})}async replace(e){let t=d.default.dirname(this.absolutePath);await f.default.mkdir(t,{recursive:!0}),await f.default.writeFile(this.absolutePath,e),n.logger.info.defaultLog(`Replaced file`,{path:this.getRelativeFilePath()})}async delete(){try{await f.default.unlink(this.absolutePath),n.logger.info.defaultLog(`Deleted file`,{path:this.getRelativeFilePath()})}catch{}}};let z=[{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}],re=[`@typescript-eslint/no-undefined`,`unicorn/no-useless-undefined`,`no-undefined`];async function B(e){for(let{path:t,isFlat:n}of z){let r=d.default.join(e,t);if(await R.fromAbsolutePath(r).isFileExists())return{path:r,isFlat:n}}return r.findPackageJson(e)?.eslint?{path:r.findupFile(e,`package.json`),isFlat:!1}:{path:null,isFlat:!1}}let V={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`},ae={CODE_EXTRACTOR:`code-extractor`,CODE_REFINEMENT:`code-refinement`,TEST_MANAGEMENT:`test-management`,TEST_VALIDATOR:`test-validator`,CONFIG_FILE:`config-file`,COMMAND_EXECUTION:`command-execution`},oe=[`.jsx`,`.tsx`],se=[`it`,`test`,`it.each`,`test.each`],ce=function(e){return e.Default=`default`,e.ObjectDefault=`object-default`,e.Named=`named`,e.Unknown=`unknown`,e.NotExported=`not-exported`,e}({}),le=function(e){return e.PRIVATE=`private`,e.PROTECTED=`protected`,e.PUBLIC=`public`,e}({}),ue=function(e){return e.REACT=`react`,e.ANGULAR=`angular`,e}({}),de=`unknown`,fe=`tests`,pe=(0,C.promisify)(S.default.exec);async function me(e,{cwd:t=n.getGlobalConfig().getRootPath(),timeout:r=1e4}={}){return(await pe(e,{cwd:t,maxBuffer:500*1024,timeout:r}))?.stdout?.toString()??``}let he=e=>{let t=r.relativePathToAbsoluteUri(e);return(0,b.default)(`jest.config.+(js|ts|mjs|cjs|json)`,{cwd:t})},ge=e=>(0,m.isObject)(e)&&(0,m.isString)(e.rootDir),_e=async e=>{let t;if(n.logger.addContext({subCategory:ae.CONFIG_FILE}),(0,m.isDefined)(e)){let n=he(e);n!==null&&(t=(0,d.dirname)(n))}t??=n.getGlobalConfig().getRootPath();let r;try{if(r=await me(`npx jest --showConfig`,{cwd:t}),!(0,m.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,m.isObject)(e)&&(0,m.isArray)(e.configs)&&e.configs.every(e=>ge(e)))return{projectConfigs:e.configs,globalConfig:e.globalConfig,configs:e.configs}}catch(e){n.logger.info.defaultLog(`Cannot read jest config`,(0,m.getErrorMessage)(e)),n.logger.info.defaultLog(`Failed reading jest config`,e,(0,m.getErrorMessage)(e));return}n.logger.info.defaultLog(`Invalid jest config or config in not supported format`)},ve=async()=>{let e=[n.getGlobalConfig().getRootPath()],t=d.default.join(`node_modules`,`.prisma`,`client`,`index.d.ts`),r=e.map(e=>d.default.join(e,t)).map(e=>R.fromAbsolutePath(e));return(await(0,m.filterAsync)(r,e=>e.isFileExists())).map(e=>e.getAbsoluteFilePath())},ye=async()=>{try{let e=n.getGlobalConfig().getRootPath();if(!(0,m.isDefined)(e))return[];let t=await(0,w.getSchemaWithPathOptional)(``,``,{cwd:e});if(!(0,m.isDefined)(t))return[];let r=t.schemas.map(e=>e[1]),i=new Set;for(let e of r){let n=(await(0,w.getConfig)({datamodel:e,ignoreEnvVarErrors:!0})).generators;for(let e of n)if((0,m.isDefined)(e.output?.value)){let n=d.default.join(d.default.resolve(t.schemaRootDir,e.output.value),`index.d.ts`);await R.fromAbsolutePath(n).isFileExists()&&i.add(n)}}return[...i]}catch(e){return n.logger.error(`Failed to get prisma typings paths`,e),[]}},be=async()=>(await Promise.all([ve(),ye()])).flat(),xe=async(e,t=!1,i)=>{let a=`!**/node_modules/**`;if(t)return new x.Project({useInMemoryFileSystem:!0,compilerOptions:i});let o=r.isTypescriptFile(e),s=Se((0,d.dirname)(r.relativePathToAbsoluteUri(e)),n.getGlobalConfig().isSiblingFolderStructured());if(!o&&!(0,m.isDefined)(s)){let t=await we(e);if(!(0,m.isDefined)(t)||(0,m.isEmpty)(t))throw Error(`Cannot find source code path in jest config`);let n=new x.Project({compilerOptions:{allowJs:!0,maxNodeModuleJsDepth:0},useInMemoryFileSystem:!1});return n.addSourceFilesAtPaths([...t,a]),n}if(!o&&(0,m.isDefined)(s)){let t=new x.Project({tsConfigFilePath:s,compilerOptions:{allowJs:!0,maxNodeModuleJsDepth:0}}),n=await we(e);return t.addSourceFilesAtPaths([...n,a]),t}let c={maxNodeModuleJsDepth:0};if(n.getGlobalConfig().isRootFolderStructured()){let e=n.getGlobalConfig().getRootPath();c.rootDirs=[d.default.resolve(e,`src`),d.default.resolve(e,fe)]}let l=new x.Project({tsConfigFilePath:s,compilerOptions:c}),u=await be();for(let e of u)l.addSourceFileAtPath(e);return l},Se=(e,t)=>{let n;try{n=Ce(e)}catch{t&&(n=Ce((0,d.dirname)(e)))}return n},Ce=e=>{let t=e,n=/^(tsconfig|jsconfig).*\.json$/;for(;t!==(0,d.dirname)(t);){let e=(0,d.join)(t,`tsconfig.json`),r=(0,d.join)(t,`jsconfig.json`);if(!(0,y.existsSync)(t))return Ce((0,d.dirname)(t));if((0,y.existsSync)(e))return e;if((0,y.existsSync)(r))return r;let i=(0,y.readdirSync)(t);for(let e of i)if(n.test(e))return(0,d.join)(t,e);t=(0,d.dirname)(t)}},we=async e=>{let t=await _e(e);if((0,m.isDefined)(t)){let e=t?.configs[0].roots.map(e=>d.default.join(e,`**/*.{ts,js,tsx,jsx}`));if(!(0,m.isEmpty)(e))return e}return[r.relativePathToAbsoluteUri(r.findRepoRoot(e))]};var Te=t.__toESM(n.require_decorateMetadata()),Ee=t.__toESM(n.require_decorate());let De=`The ts-morph project is not initialized.`,Oe=new class{storage=new p.AsyncLocalStorage;_project;clear(){this._project=void 0}async init(e,t,n){let i=r.relativePathToAbsoluteUri(e);if((0,m.isDefined)(this._project))return this._project.addSourceFileAtPathIfExists(i);this._project=await xe(e,t,n);let a=this.storage.getStore();if((0,m.isDefined)(a))return this._project.addSourceFileAtPathIfExists(i)}add(e,t){let n=r.relativePathToAbsoluteUri(e),i=this.storage.getStore()?.getProject();if(!(0,m.isDefined)(i))throw Error(De);return i.createSourceFile(n,t,{overwrite:!0})}update(e,t){let n=this.get(e);return n.replaceWithText(t),n}addFile(e){(0,m.isDefined)(this._project)&&this._project.addSourceFileAtPathIfExists(e)}removeFile(e){if(!(0,m.isDefined)(this._project))return;let t=this._project.getSourceFile(e);(0,m.isDefined)(t)&&this._project.removeSourceFile(t)}async refreshFromFileSystem(e){if(!(0,m.isDefined)(this._project))return;let t=r.relativePathToAbsoluteUri(e),n=this._project?.getSourceFile(e)??this._project?.getSourceFile(t);if((0,m.isDefined)(n)){let e=n.getFilePath();this._project.removeSourceFile(n),this._project.addSourceFileAtPath(e)}}get(e){let t=r.relativePathToAbsoluteUri(e),n=this.storage.getStore()?.getProject();if(!(0,m.isDefined)(n))throw Error(De+` store`);let i=n.getSourceFile(t);if(!(0,m.isDefined)(i))throw Error(`The source file is absent. ${e}`);return i}async save(e){await this.get(e).save()}async delete(e){await this.get(e).deleteImmediately()}getOrUndefined(e){let t=r.relativePathToAbsoluteUri(e);return this._project?.getSourceFile(t)}withContext=(e,t,n)=>{let r=n.value,i=this.storage;if((0,m.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}},ke=Oe.withContext,Ae=async e=>{class t{async fn(){return e()}}(0,Ee.default)([ke,(0,Te.default)(`design:type`,Function),(0,Te.default)(`design:paramtypes`,[]),(0,Te.default)(`design:returntype`,Promise)],t.prototype,`fn`,null),await new t().fn()},je=e=>{let t=e?.asKind(x.SyntaxKind.ExpressionStatement)?.getExpression();if(!(0,m.isDefined)(t))return;let n=t.asKind(x.SyntaxKind.CallExpression)?.getArguments()?.at(-1),r=n?.asKind(x.SyntaxKind.ArrowFunction)?.getBody(),i=n?.asKind(x.SyntaxKind.FunctionExpression)?.getBody();return r?.asKind(x.SyntaxKind.Block)??i?.asKind(x.SyntaxKind.Block)},Me=e=>x.Node.isExpressionStatement(e)&&e.getFirstChildByKind(x.SyntaxKind.CallExpression)?.getFirstChildByKind(x.SyntaxKind.Identifier)?.getText()===`describe`,Ne=e=>e.getStatements().filter(e=>Me(e)),Pe=e=>{let t=e.getExpression().getFirstChild()?.getText();return!(0,m.isDefined)(t)||(0,m.isEmpty)(t)?!1:se.some(e=>t.startsWith(e))},Fe=e=>{let t=je(e);return(0,m.isDefined)(t)?t.getChildrenOfKind(x.SyntaxKind.ExpressionStatement).some(e=>Pe(e)):!1},Ie=e=>{let t=je(e);return(0,m.isDefined)(t)?t.getChildrenOfKind(x.SyntaxKind.ExpressionStatement).filter(e=>Me(e)&&Fe(e)):[]},Le=e=>{let t=je(e);if((0,m.isDefined)(t))return t.getChildrenOfKind(x.SyntaxKind.ExpressionStatement).find(e=>Me(e)&&Fe(e))},Re=e=>{let t=Le(e);return(0,m.isDefined)(t)},ze=e=>{let t=je(e);if(!(0,m.isDefined)(t))return!0;let n=t.getChildrenOfKind(x.SyntaxKind.ExpressionStatement);if((0,m.isEmpty)(n))return!0;let r=new Set([`beforeEach`,`afterEach`,`beforeAll`,`afterAll`]);return n.every(e=>{let t=e.getExpressionIfKind(x.SyntaxKind.CallExpression)?.getExpressionIfKind(x.SyntaxKind.Identifier);return(0,m.isDefined)(t)?r.has(t.getText()):!1})},Be=e=>{if(e.isNamedExport?.())return ce.Named;if(e.isDefaultExport?.())return ce.Default;let t=e?.getParent();if((0,m.isDefined)(t)){if(t.isNamedExport?.())return ce.Named;if(t.isDefaultExport?.())return ce.Default}return e.isExportDefaultObject?.()??H(e.getSourceFile(),e.getName?.())?ce.ObjectDefault:ce.NotExported},Ve=(e,t)=>(0,m.isDefined)(e)?Be(e):(0,m.isDefined)(t)?t.isNamedImport?ce.Named:ce.Default:ce.Unknown;function H(e,t){let[n]=e.getExportAssignments()??[];return n?.getDescendantsOfKind(x.SyntaxKind.Identifier).some(e=>(e.getSymbol()?.getEscapedName()??e.getText())===t)}function He(e,t){let n=Ne(Oe.get(e)),r=n.find(e=>e.getText().includes(t))??n[0],i=Ie(r),a=[],o=(0,m.isEmpty)(i)?[r]:i;for(let e of o){let t=je(e);(0,m.isDefined)(t)&&a.push(...t.getChildrenOfKind(x.SyntaxKind.ExpressionStatement).filter(e=>Pe(e)))}return a}let Ue=e=>e.getFirstDescendantByKind(x.SyntaxKind.StringLiteral)?.getLiteralValue(),We=e=>Ue(e),Ge=e=>Ue(e),Ke=(e,t)=>{let n=e.getFullText().slice(0,Math.max(0,t)).split(`
|
|
32591
|
+
`)}`}let m=[`node_modules`,`dist`,`.next`,`.cache`],h=[`build`,`out`,`coverage`];function g(e,t){return m.some(e=>t.includes(`/${e}/`))?!0:h.some(n=>t.startsWith(`${e}/${n}/`))}var _=class{rootPath;pathScope;project;preloadMsValue=0;constructor(e,t){this.rootPath=a.default.normalize(a.default.resolve(e)),this.pathScope=t}init(){let e=r.findupFile(this.rootPath,`tsconfig.json`)??void 0,t=Date.now();this.project=new s.Project({...(0,o.isDefined)(e)?{tsConfigFilePath:e}:{},skipAddingFilesFromTsConfig:!0,compilerOptions:{allowJs:!1}});let n=m.map(e=>`!${this.rootPath}/**/${e}/**`),i=h.map(e=>`!${this.rootPath}/${e}/**`);this.project.addSourceFilesAtPaths([`${this.rootPath}/**/*.{ts,tsx,mts,cts}`,...n,...i]),this.preloadMsValue=Date.now()-t}getImporters(e){let t=this.requireProject().getSourceFile(a.default.normalize(a.default.resolve(e)));return(0,o.isDefined)(t)?t.getReferencingSourceFiles().map(e=>a.default.normalize(e.getFilePath())).filter(e=>this.pathScope.isInside(e)&&!g(this.rootPath,e)):[]}hasFile(e){return this.project?.getSourceFile(a.default.normalize(a.default.resolve(e)))!==void 0}loadedFileCount(){return this.project?.getSourceFiles().length??0}initDurationMs(){return this.preloadMsValue}requireProject(){if(!(0,o.isDefined)(this.project))throw Error(`[ast-mapping] TsProjectLoader.init() must be called before querying importers`);return this.project}},v=class{mapper;constructor(e){this.mapper=e}run(e,t){let r=e.map(e=>({flowId:e.flowId,entryFiles:e.trace.entryFiles})),a=this.mapper.mapFiles(r,t);if(n.logger.info.defaultLog(`[regression-impact] File-to-flow mapping (AST): preloaded ${a.stats.filesLoaded} file(s) in ${a.stats.preloadMs}ms`),a.residual.length>0&&n.logger.info.defaultLog(`[regression-impact] File-to-flow mapping (AST): ${a.residual.length} changed file(s) reached no flow entry`),a.staleEntryFlowIds.length>0){let t=new Map(e.map(e=>[e.flowId,e]));n.logger.info.defaultLog(`[regression-impact] File-to-flow mapping (AST): ${a.staleEntryFlowIds.length} flow(s) have stale entry files (would go to LLM in hybrid):`);for(let e of a.staleEntryFlowIds){let r=t.get(e),i=r?.trace.entryFiles.join(`, `)??`(unknown)`;n.logger.info.defaultLog(`[regression-impact] ${r?.name??e} [${e}] — entries: ${i}`)}}return Promise.resolve({flowFileMap:i.buildFlowFileMap(a.resolved),costUsd:0,turns:0,maxTurnsHit:!1})}};function y(e,t){return new l(new _(e,new u(e)),t)}function b(e,t){return new v(y(e,t))}function x(e,t,i,a){let o=new _(e,new u(e));o.init();let s=new r.ReachabilityPathFinder(o,t),c=i.map(e=>({flowId:e.flowId,entryFiles:e.trace.entryFiles})),l=new Map(s.findPaths(c,a).map(e=>[e.file,e])),d=new Map(i.map(e=>[e.flowId,e.name]));return n.logger.info.defaultLog(`[regression-impact] File-to-flow mapping (agentic-ast): preloaded ${o.loadedFileCount()} file(s) in ${o.initDurationMs()}ms; static paths ready for ${l.size} changed file(s)`),e=>p(e.map(e=>l.get(e)).filter(e=>e!==void 0),e=>d.get(e))}e.createAgenticAstReachabilityProvider=x,e.createAstFileFlowMapper=y,e.createAstImpactMapper=b})),jU=s((e=>{let t=_R(),n=rz();e.HybridImpactMapper=class{astMapper;agenticMapper;constructor(e,t){this.astMapper=e,this.agenticMapper=t}async run(e,r){let i=e.map(e=>({flowId:e.flowId,entryFiles:e.trace.entryFiles})),a=this.astMapper.mapFiles(i,r),o=n.buildFlowFileMap(a.resolved);if(t.logger.info.defaultLog(`[regression-impact] Hybrid: AST attributed ${a.resolved.length} file(s) across ${o.size} flow(s); ${a.staleEntryFlowIds.length} flow(s) have stale entries → LLM re-check`),a.staleEntryFlowIds.length===0)return t.logger.info.defaultLog(`[regression-impact] Hybrid: no stale-entry flows — LLM skipped entirely.`),{flowFileMap:o,costUsd:0,turns:0,maxTurnsHit:!1};let s=new Set(a.staleEntryFlowIds),c=e.filter(e=>s.has(e.flowId));t.logger.info.defaultLog(`[regression-impact] Hybrid: ${c.length} stale-entry flow(s) → LLM (${r.length} changed file(s)):`);for(let e of c)t.logger.info.defaultLog(`[regression-impact] ${e.name} [${e.flowId}] — entries: ${e.trace.entryFiles.join(`, `)}`);let l=await this.agenticMapper.run(c,r),u=new Map(o);for(let[e,t]of l.flowFileMap)u.set(e,t);return{flowFileMap:u,flowFileReasons:l.flowFileReasons,costUsd:l.costUsd,turns:l.turns,maxTurnsHit:l.maxTurnsHit}}}})),Pee=s((e=>{let t=ur(),n=_R(),r=$R(),i=QR(),a=nz(),o=t.__toESM(require(`node:crypto`)),s=t.__toESM(cz()),c=[`Read`,`Grep`,`Glob`];function l(e,t){let n=[];for(let r=0;r<e.length;r+=Math.max(1,t))n.push(e.slice(r,r+Math.max(1,t)));return n}function u(e,t){let n=e;return n===void 0||!Array.isArray(n.guesses)?[]:n.guesses.map(e=>({file:e.file,flowIds:(Array.isArray(e.flowIds)?e.flowIds:[]).filter(e=>t.has(e)),reason:e.reason}))}async function d(e,t,s,l,d){let{query:f,isResultMessage:p,isErrorResult:m,getMessageContentBlocks:h}=await Promise.resolve().then(()=>lz()),g=`shallow-map batch #${l}`,_={guesses:[],costUsd:0,turns:0,maxTurnsHit:!1,metric:{label:`shallow-batch-${l}`,totalFiles:t.length,costUsd:0,turns:0,maxTurnsHit:!1,maxBudgetHit:!1,tokens:{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0}},failedFiles:[...t]},v=i.getPerFileDiffs(t,d.rootPath,d.branch,d.resolvedAnchorBranch,d.isUncommitted),y=f({prompt:a.buildShallowMapPrompt(e,t,v,d.branch,d.resolvedAnchorBranch,i.REGRESSION_IMPACT_SHALLOW_DIFF_MAX_CHARS),options:{model:i.REGRESSION_IMPACT_SONNET_MODEL,...i.REGRESSION_SONNET_ANALYZER_REASONING,systemPrompt:a.buildShallowMapSystemPrompt(),allowedTools:c,permissionMode:i.REGRESSION_PERMISSION_MODE,allowDangerouslySkipPermissions:!0,maxBudgetUsd:i.REGRESSION_IMPACT_AGENTIC_MAX_BUDGET_USD,maxTurns:25,cwd:d.rootPath,sessionId:(0,o.randomUUID)(),outputFormat:{type:`json_schema`,schema:r.RESIDUAL_ROUGH_MAP_OUTPUT_SCHEMA},env:{...process.env,...r.buildAnthropicSdkEnv({proxyUrl:d.anthropicBaseUrl,jwtToken:d.jwtToken??``,requestId:n.logger.getRequestId()})}}});r.logAgentCwd(g,d.rootPath);let b=0;for await(let e of y){if(!p(e)){let t=h(e);t!==void 0&&t.length>0&&(b++,r.logAgentActivity(g,b,t));continue}if(m(e))return n.logger.info.defaultLog(`[regression-impact] Shallow mapping ${g} error: ${e.subtype} — its files map to no flow`),_;let i=e.num_turns,a=r.logCacheTokensFromMessage(g,e);return{guesses:u(e.structured_output,s),costUsd:e.total_cost_usd,turns:i,maxTurnsHit:i>=25,metric:{label:`shallow-batch-${l}`,totalFiles:t.length,costUsd:e.total_cost_usd,turns:i,maxTurnsHit:i>=25,maxBudgetHit:!1,tokens:a},failedFiles:[]}}return _}e.ShallowImpactMapper=class{constructor(e){this.context=e}async run(e,t){let r=new Set(e.map(e=>e.flowId)),a=l(t,i.REGRESSION_IMPACT_RESIDUAL_BATCH_SIZE);n.logger.info.defaultLog(`[regression-impact] Shallow mapping: ${t.length} changed file(s) in ${a.length} batch(es) (path + diff, Read/Grep/Glob)`);let o=new s.default({concurrency:i.REGRESSION_IMPACT_RESIDUAL_CONCURRENCY}),c=(await Promise.all([...a.entries()].map(([t,i])=>o.add(async()=>{try{return await d(e,i,r,t+1,this.context)}catch(e){return n.logger.info.defaultLog(`[regression-impact] Shallow mapping batch #${t+1} crashed (${i.length} file(s)): ${String(e)}`),{guesses:[],costUsd:0,turns:0,maxTurnsHit:!1,metric:{label:`shallow-batch-${t+1}`,totalFiles:i.length,costUsd:0,turns:0,maxTurnsHit:!1,maxBudgetHit:!1,tokens:{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0}},failedFiles:[...i]}}})))).filter(e=>e!==void 0),u=new Map,f=new Map,p=new Set,m=0,h=0,g=!1,_=[],v=[];for(let e of c){m+=e.costUsd,h+=e.turns,g||=e.maxTurnsHit,_.push(e.metric),v.push(...e.failedFiles);for(let t of e.guesses){if(t.flowIds.length===0)continue;let e=t.reason??`shallow map: guessed from path + diff`;for(let n of t.flowIds){let r=u.get(n)??new Set;r.add(t.file),u.set(n,r),p.add(n);let i=f.get(n)??new Map;i.set(t.file,`shallow (low confidence): ${e}`),f.set(n,i)}}}return{flowFileMap:u,flowFileReasons:f,costUsd:m,turns:h,maxTurnsHit:g,incompleteFiles:v,batchMetrics:_,lowConfidenceFlowIds:p}}}})),MU=s((e=>{_R(),$R();let t=QR();rz();let n=dz();var r=class{context;repoRoot;constructor(e,t){this.context=e,this.repoRoot=t}async run(e,t){let{createAgenticAstReachabilityProvider:r}=await Promise.resolve().then(()=>AU()),i=r(this.context.rootPath,this.repoRoot,e,t);return new n.AgenticImpactMapper(this.context,i).run(e,t)}};async function i(e){if(e.strategy===`ast`){let{createAstImpactMapper:n}=await Promise.resolve().then(()=>AU()),r=t.getRepoRoot(e.rootPath);return n(e.rootPath,r)}if(e.strategy===`hybrid`){let{createAstFileFlowMapper:r}=await Promise.resolve().then(()=>AU()),{HybridImpactMapper:i}=await Promise.resolve().then(()=>jU()),a=t.getRepoRoot(e.rootPath);return new i(r(e.rootPath,a),new n.AgenticImpactMapper(e))}if(e.strategy===`agentic-ast`)return new r(e,t.getRepoRoot(e.rootPath));if(e.strategy===`shallow`){let{ShallowImpactMapper:t}=await Promise.resolve().then(()=>Pee());return new t({rootPath:e.rootPath,branch:e.branch,resolvedAnchorBranch:e.resolvedAnchorBranch,jwtToken:e.jwtToken,anthropicBaseUrl:e.anthropicBaseUrl,isUncommitted:e.isUncommitted??!1})}return new n.AgenticImpactMapper(e)}e.createImpactMapper=i})),NU=s((e=>{let t=ur(),n=_R(),r=ZR(),i=$R(),a=ez(),o=QR(),s=tz(),c=nz();rz();let l=dz(),u=t.__toESM(Ei()),d=t.__toESM(vR()),f=t.__toESM(require(`node:fs/promises`)),p=t.__toESM(require(`node:async_hooks`)),m=t.__toESM(ie()),h=t.__toESM(Fc()),g=t.__toESM(require(`node:process`)),_=t.__toESM(require(`node:os`));t.__toESM(require(`node:tty`));let v=t.__toESM(require(`node:crypto`)),y=t.__toESM(require(`node:fs`)),b=t.__toESM(XR()),x=t.__toESM(MB()),S=t.__toESM(require(`node:child_process`)),C=t.__toESM(require(`node:util`)),w=t.__toESM(require(`@prisma/internals`)),T=t.__toESM(OB()),E=t.__toESM(require(`node:zlib`)),D=t.__toESM(PV()),O=t.__toESM(IV()),k=t.__toESM(VV()),A=t.__toESM(cz()),j=t.__toESM(require(`node:events`)),M=t.__toESM(FH()),ee=t.__toESM(SU()),N=t.__toESM(Nee()),te=t.__toESM(DU()),P=t.__toESM(OU()),F=t.__toESM(IH());t.__toESM(require(`node:readline`));let I=t.__toESM(require(`node:path`)),L=t.__toESM(require(`node:module`)),ne=t.__toESM(require(`@anthropic-ai/claude-agent-sdk`));var R=class e{rootPath;absolutePath;static EARLY_FILENAME_VAR=`$early_filename`;constructor(e){this.rootPath=d.default.normalizeTrim(n.getGlobalConfig().getRootPath());let t=d.default.normalizeTrim(e),r=d.default.normalizeTrim(this.rootPath);if(t===r||t.startsWith(r+d.default.sep))this.absolutePath=t;else{let e=t.replace(/^\//,``);this.absolutePath=d.default.resolve(this.rootPath,e)}}static fromSourceFile(t){let r=d.default.normalizeTrim(t.getFilePath());return new e(d.default.relative(d.default.normalizeTrim(n.getGlobalConfig().getRootPath()),r))}static fromAbsolutePath(t){let r=d.default.normalizeTrim(t);return new e(d.default.relative(d.default.normalizeTrim(n.getGlobalConfig().getRootPath()),r))}static fromRelativePath(t){return new e(t)}getRelativeFilePath(){return d.default.relative(this.rootPath,this.absolutePath)}getAbsoluteFilePath(){return this.absolutePath}async isFileExists(){try{return(await f.default.stat(this.absolutePath)).isFile()}catch{return!1}}async isDirectoryExists(){try{return(await f.default.stat(this.absolutePath)).isDirectory()}catch{return!1}}async createDirectory(e){await f.default.mkdir(this.absolutePath,{recursive:e?.recursive??!0})}async getText(){try{return await f.default.readFile(this.absolutePath,`utf8`)}catch{return``}}async upsert(e){let t=d.default.dirname(this.absolutePath);await f.default.mkdir(t,{recursive:!0}),await(await this.isFileExists()?f.default.appendFile(this.absolutePath,e):f.default.writeFile(this.absolutePath,e)),n.logger.info.defaultLog(`Upserted file`,{path:this.getRelativeFilePath()})}async replace(e){let t=d.default.dirname(this.absolutePath);await f.default.mkdir(t,{recursive:!0}),await f.default.writeFile(this.absolutePath,e),n.logger.info.defaultLog(`Replaced file`,{path:this.getRelativeFilePath()})}async delete(){try{await f.default.unlink(this.absolutePath),n.logger.info.defaultLog(`Deleted file`,{path:this.getRelativeFilePath()})}catch{}}};let z=[{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}],re=[`@typescript-eslint/no-undefined`,`unicorn/no-useless-undefined`,`no-undefined`];async function B(e){for(let{path:t,isFlat:n}of z){let r=d.default.join(e,t);if(await R.fromAbsolutePath(r).isFileExists())return{path:r,isFlat:n}}return r.findPackageJson(e)?.eslint?{path:r.findupFile(e,`package.json`),isFlat:!1}:{path:null,isFlat:!1}}let V={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`},ae={CODE_EXTRACTOR:`code-extractor`,CODE_REFINEMENT:`code-refinement`,TEST_MANAGEMENT:`test-management`,TEST_VALIDATOR:`test-validator`,CONFIG_FILE:`config-file`,COMMAND_EXECUTION:`command-execution`},oe=[`.jsx`,`.tsx`],se=[`it`,`test`,`it.each`,`test.each`],ce=function(e){return e.Default=`default`,e.ObjectDefault=`object-default`,e.Named=`named`,e.Unknown=`unknown`,e.NotExported=`not-exported`,e}({}),le=function(e){return e.PRIVATE=`private`,e.PROTECTED=`protected`,e.PUBLIC=`public`,e}({}),ue=function(e){return e.REACT=`react`,e.ANGULAR=`angular`,e}({}),de=`unknown`,fe=`tests`,pe=(0,C.promisify)(S.default.exec);async function me(e,{cwd:t=n.getGlobalConfig().getRootPath(),timeout:r=1e4}={}){return(await pe(e,{cwd:t,maxBuffer:500*1024,timeout:r}))?.stdout?.toString()??``}let he=e=>{let t=r.relativePathToAbsoluteUri(e);return(0,b.default)(`jest.config.+(js|ts|mjs|cjs|json)`,{cwd:t})},ge=e=>(0,m.isObject)(e)&&(0,m.isString)(e.rootDir),_e=async e=>{let t;if(n.logger.addContext({subCategory:ae.CONFIG_FILE}),(0,m.isDefined)(e)){let n=he(e);n!==null&&(t=(0,d.dirname)(n))}t??=n.getGlobalConfig().getRootPath();let r;try{if(r=await me(`npx jest --showConfig`,{cwd:t}),!(0,m.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,m.isObject)(e)&&(0,m.isArray)(e.configs)&&e.configs.every(e=>ge(e)))return{projectConfigs:e.configs,globalConfig:e.globalConfig,configs:e.configs}}catch(e){n.logger.info.defaultLog(`Cannot read jest config`,(0,m.getErrorMessage)(e)),n.logger.info.defaultLog(`Failed reading jest config`,e,(0,m.getErrorMessage)(e));return}n.logger.info.defaultLog(`Invalid jest config or config in not supported format`)},ve=async()=>{let e=[n.getGlobalConfig().getRootPath()],t=d.default.join(`node_modules`,`.prisma`,`client`,`index.d.ts`),r=e.map(e=>d.default.join(e,t)).map(e=>R.fromAbsolutePath(e));return(await(0,m.filterAsync)(r,e=>e.isFileExists())).map(e=>e.getAbsoluteFilePath())},ye=async()=>{try{let e=n.getGlobalConfig().getRootPath();if(!(0,m.isDefined)(e))return[];let t=await(0,w.getSchemaWithPathOptional)(``,``,{cwd:e});if(!(0,m.isDefined)(t))return[];let r=t.schemas.map(e=>e[1]),i=new Set;for(let e of r){let n=(await(0,w.getConfig)({datamodel:e,ignoreEnvVarErrors:!0})).generators;for(let e of n)if((0,m.isDefined)(e.output?.value)){let n=d.default.join(d.default.resolve(t.schemaRootDir,e.output.value),`index.d.ts`);await R.fromAbsolutePath(n).isFileExists()&&i.add(n)}}return[...i]}catch(e){return n.logger.error(`Failed to get prisma typings paths`,e),[]}},be=async()=>(await Promise.all([ve(),ye()])).flat(),xe=async(e,t=!1,i)=>{let a=`!**/node_modules/**`;if(t)return new x.Project({useInMemoryFileSystem:!0,compilerOptions:i});let o=r.isTypescriptFile(e),s=Se((0,d.dirname)(r.relativePathToAbsoluteUri(e)),n.getGlobalConfig().isSiblingFolderStructured());if(!o&&!(0,m.isDefined)(s)){let t=await we(e);if(!(0,m.isDefined)(t)||(0,m.isEmpty)(t))throw Error(`Cannot find source code path in jest config`);let n=new x.Project({compilerOptions:{allowJs:!0,maxNodeModuleJsDepth:0},useInMemoryFileSystem:!1});return n.addSourceFilesAtPaths([...t,a]),n}if(!o&&(0,m.isDefined)(s)){let t=new x.Project({tsConfigFilePath:s,compilerOptions:{allowJs:!0,maxNodeModuleJsDepth:0}}),n=await we(e);return t.addSourceFilesAtPaths([...n,a]),t}let c={maxNodeModuleJsDepth:0};if(n.getGlobalConfig().isRootFolderStructured()){let e=n.getGlobalConfig().getRootPath();c.rootDirs=[d.default.resolve(e,`src`),d.default.resolve(e,fe)]}let l=new x.Project({tsConfigFilePath:s,compilerOptions:c}),u=await be();for(let e of u)l.addSourceFileAtPath(e);return l},Se=(e,t)=>{let n;try{n=Ce(e)}catch{t&&(n=Ce((0,d.dirname)(e)))}return n},Ce=e=>{let t=e,n=/^(tsconfig|jsconfig).*\.json$/;for(;t!==(0,d.dirname)(t);){let e=(0,d.join)(t,`tsconfig.json`),r=(0,d.join)(t,`jsconfig.json`);if(!(0,y.existsSync)(t))return Ce((0,d.dirname)(t));if((0,y.existsSync)(e))return e;if((0,y.existsSync)(r))return r;let i=(0,y.readdirSync)(t);for(let e of i)if(n.test(e))return(0,d.join)(t,e);t=(0,d.dirname)(t)}},we=async e=>{let t=await _e(e);if((0,m.isDefined)(t)){let e=t?.configs[0].roots.map(e=>d.default.join(e,`**/*.{ts,js,tsx,jsx}`));if(!(0,m.isEmpty)(e))return e}return[r.relativePathToAbsoluteUri(r.findRepoRoot(e))]};var Te=t.__toESM(n.require_decorateMetadata()),Ee=t.__toESM(n.require_decorate());let De=`The ts-morph project is not initialized.`,Oe=new class{storage=new p.AsyncLocalStorage;_project;clear(){this._project=void 0}async init(e,t,n){let i=r.relativePathToAbsoluteUri(e);if((0,m.isDefined)(this._project))return this._project.addSourceFileAtPathIfExists(i);this._project=await xe(e,t,n);let a=this.storage.getStore();if((0,m.isDefined)(a))return this._project.addSourceFileAtPathIfExists(i)}add(e,t){let n=r.relativePathToAbsoluteUri(e),i=this.storage.getStore()?.getProject();if(!(0,m.isDefined)(i))throw Error(De);return i.createSourceFile(n,t,{overwrite:!0})}update(e,t){let n=this.get(e);return n.replaceWithText(t),n}addFile(e){(0,m.isDefined)(this._project)&&this._project.addSourceFileAtPathIfExists(e)}removeFile(e){if(!(0,m.isDefined)(this._project))return;let t=this._project.getSourceFile(e);(0,m.isDefined)(t)&&this._project.removeSourceFile(t)}async refreshFromFileSystem(e){if(!(0,m.isDefined)(this._project))return;let t=r.relativePathToAbsoluteUri(e),n=this._project?.getSourceFile(e)??this._project?.getSourceFile(t);if((0,m.isDefined)(n)){let e=n.getFilePath();this._project.removeSourceFile(n),this._project.addSourceFileAtPath(e)}}get(e){let t=r.relativePathToAbsoluteUri(e),n=this.storage.getStore()?.getProject();if(!(0,m.isDefined)(n))throw Error(De+` store`);let i=n.getSourceFile(t);if(!(0,m.isDefined)(i))throw Error(`The source file is absent. ${e}`);return i}async save(e){await this.get(e).save()}async delete(e){await this.get(e).deleteImmediately()}getOrUndefined(e){let t=r.relativePathToAbsoluteUri(e);return this._project?.getSourceFile(t)}withContext=(e,t,n)=>{let r=n.value,i=this.storage;if((0,m.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}},ke=Oe.withContext,Ae=async e=>{class t{async fn(){return e()}}(0,Ee.default)([ke,(0,Te.default)(`design:type`,Function),(0,Te.default)(`design:paramtypes`,[]),(0,Te.default)(`design:returntype`,Promise)],t.prototype,`fn`,null),await new t().fn()},je=e=>{let t=e?.asKind(x.SyntaxKind.ExpressionStatement)?.getExpression();if(!(0,m.isDefined)(t))return;let n=t.asKind(x.SyntaxKind.CallExpression)?.getArguments()?.at(-1),r=n?.asKind(x.SyntaxKind.ArrowFunction)?.getBody(),i=n?.asKind(x.SyntaxKind.FunctionExpression)?.getBody();return r?.asKind(x.SyntaxKind.Block)??i?.asKind(x.SyntaxKind.Block)},Me=e=>x.Node.isExpressionStatement(e)&&e.getFirstChildByKind(x.SyntaxKind.CallExpression)?.getFirstChildByKind(x.SyntaxKind.Identifier)?.getText()===`describe`,Ne=e=>e.getStatements().filter(e=>Me(e)),Pe=e=>{let t=e.getExpression().getFirstChild()?.getText();return!(0,m.isDefined)(t)||(0,m.isEmpty)(t)?!1:se.some(e=>t.startsWith(e))},Fe=e=>{let t=je(e);return(0,m.isDefined)(t)?t.getChildrenOfKind(x.SyntaxKind.ExpressionStatement).some(e=>Pe(e)):!1},Ie=e=>{let t=je(e);return(0,m.isDefined)(t)?t.getChildrenOfKind(x.SyntaxKind.ExpressionStatement).filter(e=>Me(e)&&Fe(e)):[]},Le=e=>{let t=je(e);if((0,m.isDefined)(t))return t.getChildrenOfKind(x.SyntaxKind.ExpressionStatement).find(e=>Me(e)&&Fe(e))},Re=e=>{let t=Le(e);return(0,m.isDefined)(t)},ze=e=>{let t=je(e);if(!(0,m.isDefined)(t))return!0;let n=t.getChildrenOfKind(x.SyntaxKind.ExpressionStatement);if((0,m.isEmpty)(n))return!0;let r=new Set([`beforeEach`,`afterEach`,`beforeAll`,`afterAll`]);return n.every(e=>{let t=e.getExpressionIfKind(x.SyntaxKind.CallExpression)?.getExpressionIfKind(x.SyntaxKind.Identifier);return(0,m.isDefined)(t)?r.has(t.getText()):!1})},Be=e=>{if(e.isNamedExport?.())return ce.Named;if(e.isDefaultExport?.())return ce.Default;let t=e?.getParent();if((0,m.isDefined)(t)){if(t.isNamedExport?.())return ce.Named;if(t.isDefaultExport?.())return ce.Default}return e.isExportDefaultObject?.()??H(e.getSourceFile(),e.getName?.())?ce.ObjectDefault:ce.NotExported},Ve=(e,t)=>(0,m.isDefined)(e)?Be(e):(0,m.isDefined)(t)?t.isNamedImport?ce.Named:ce.Default:ce.Unknown;function H(e,t){let[n]=e.getExportAssignments()??[];return n?.getDescendantsOfKind(x.SyntaxKind.Identifier).some(e=>(e.getSymbol()?.getEscapedName()??e.getText())===t)}function He(e,t){let n=Ne(Oe.get(e)),r=n.find(e=>e.getText().includes(t))??n[0],i=Ie(r),a=[],o=(0,m.isEmpty)(i)?[r]:i;for(let e of o){let t=je(e);(0,m.isDefined)(t)&&a.push(...t.getChildrenOfKind(x.SyntaxKind.ExpressionStatement).filter(e=>Pe(e)))}return a}let Ue=e=>e.getFirstDescendantByKind(x.SyntaxKind.StringLiteral)?.getLiteralValue(),We=e=>Ue(e),Ge=e=>Ue(e),Ke=(e,t)=>{let n=e.getFullText().slice(0,Math.max(0,t)).split(`
|
|
32592
32592
|
`);return{line:n.length,column:(n.at(-1)?.length??0)+1}},qe=(e,t)=>{let n=t.getStart(),r=t.getEnd(),{line:i,column:a}=Ke(e,n),{line:o,column:s}=Ke(e,r);return{startLine:i,startColumn:a,startIndex:n,endLine:o,endColumn:s,endIndex:r}},Je=e=>e.getDescendantsOfKind(x.SyntaxKind.ExpressionStatement).filter(e=>Pe(e)),Ye=(e,t,n,r)=>{let i=r?`.tsx`:`.ts`,a=t+Date.now()+(0,v.randomUUID)()+i;return e.createSourceFile(a,n)},Xe=e=>e.getDescendantsOfKind(x.SyntaxKind.CallExpression).reduce((e,t)=>{let n=t.getExpression(),r=n.getParentIfKind(x.SyntaxKind.VariableDeclaration);return(0,m.isDefined)(r)&&n.getText()===`require`&&e.push(r),e},[]),Ze=e=>{let t=e.getFirstChildByKind(x.SyntaxKind.CallExpression);if(!(0,m.isDefined)(t))return;let[n]=t.getArguments();if(!(!(0,m.isDefined)(n)||n.getKind()!==x.SyntaxKind.StringLiteral))return n.getText().slice(1,-1)},Qe=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,v.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(`.`)},$e=(e,t=e.getFullText())=>{let n=Qe(e);return e.getProject().createSourceFile(n,t)},et=e=>e.getSymbol()?.getDeclarations()?.[0]?.getSourceFile()??e.getAliasSymbol()?.getDeclarations()?.[0]?.getSourceFile(),tt=(e,t)=>{let n=e.getRelativePathTo(t.getFilePath());n=n.replaceAll(`\\`,`/`);let r=d.default.extname(n);return n=n.replaceAll(r,``),n.startsWith(`.`)||(n=`./`+n),n},nt=[x.SyntaxKind.JsxElement,x.SyntaxKind.JsxOpeningElement,x.SyntaxKind.JsxClosingElement,x.SyntaxKind.JsxExpression,x.SyntaxKind.JsxSelfClosingElement,x.SyntaxKind.JsxAttributes,x.SyntaxKind.JsxAttribute,x.SyntaxKind.JsxFragment,x.SyntaxKind.JsxOpeningFragment,x.SyntaxKind.JsxClosingFragment,x.SyntaxKind.JsxNamespacedName,x.SyntaxKind.JsxSpreadAttribute,x.SyntaxKind.JsxText,x.SyntaxKind.JsxTextAllWhiteSpaces],rt=e=>nt.some(t=>(0,m.isDefined)(e.getFirstDescendantByKind(t))),it=e=>nt.some(t=>(0,m.isDefined)(e.getParentIfKind(t))),at=e=>{let t=e.compilerType;if(`id`in t&&(0,m.isNumber)(t.id)){let e=t.id;return e===0?null:e}return null},ot=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(`.`)),st=`anonymousFunction`;var U=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,m.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(x.SyntaxKind.CallExpression),n=t?.getFirstDescendantByKind(x.SyntaxKind.PropertyAccessExpression),r=t?.getFirstDescendantByKind(x.SyntaxKind.Identifier);return[n?.getText(),r?.getText()].some(e=>(0,m.isDefined)(e)?[...ot.values()].some(t=>e.includes(t)):!1)}).map(e=>{let t=e.getFirstDescendantByKind(x.SyntaxKind.VariableDeclaration)?.getFirstChildByKind(x.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()??st,n=this.isEntityExported(t)||e.isExported();return{...this.getLocationPivot(e),name:t,type:`function`,node:e,canCreateTests:n}})}getFunctionsExpressions(){return this.sourceFile.getDescendantsOfKind(x.SyntaxKind.FunctionExpression).filter(e=>e.getParentIfKind(x.SyntaxKind.ExportAssignment)?.isExportEquals()??!(this.isCallbackFunction(e)||this.isInnerFunction(e)||this.isJSXFunction(e))).map(e=>{let t=e.getName()??this.getArrowFunctionName(e)??st,n=this.isEntityExported(t);return{...this.getLocationPivot(e),name:t,type:`function`,node:e,canCreateTests:n}})}getArrowFunctionsExpressions(){return this.sourceFile.getDescendantsOfKind(x.SyntaxKind.ArrowFunction).filter(e=>e.getParentIfKind(x.SyntaxKind.ExportAssignment)?.isExportEquals()??!(this.isCallbackFunction(e)||this.isInnerFunction(e)||this.isJSXFunction(e))).map(e=>{let t=this.getArrowFunctionName(e)??st,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()===x.SyntaxKind.CallExpression}isJSXFunction(e){return it(e)}isInnerFunction(e){let t=e.getParent(),n=0;for(;(0,m.isDefined)(t)&&t.getKind()!==x.SyntaxKind.SourceFile&&n<20;){if(t.getKind()===x.SyntaxKind.ArrowFunction)return!0;t=t.getParent(),n++}return!1}getArrowFunctionName(e){let t=e.getParent();if(t?.getKind()===x.SyntaxKind.BinaryExpression&&t?.getFirstChild()?.getKind()===x.SyntaxKind.PropertyAccessExpression)return e.getParent()?.getFirstChildByKind(x.SyntaxKind.PropertyAccessExpression)?.getName();let n=e.getFirstAncestorByKind(x.SyntaxKind.VariableDeclaration);if((0,m.isDefined)(n))return n.getName();let r=e.getFirstAncestorByKind(x.SyntaxKind.PropertyAssignment);if((0,m.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(x.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(x.SyntaxKind.BinaryExpression).map(e=>e.getRight()).filter(e=>x.Node.isObjectLiteralExpression(e)),t=this.sourceFile.getExportAssignments().map(e=>e.getExpression()).filter(e=>x.Node.isObjectLiteralExpression(e));return[...e,...t].flatMap(e=>e.getProperties()).filter(e=>x.Node.isMethodDeclaration(e)).map(e=>({...this.getLocationPivot(e),type:`object-method`,node:e,name:e.getName(),canCreateTests:!0}))}getLocationPivot(e){return qe(this.sourceFile,e)}isEntityExported(e){return(0,m.isDefined)(e)&&!(0,m.isEmpty)(e)?this.exportedDeclarations.includes(e):!1}isEntityExportedWithThis(e){let t=e.getParent()?.getChildren()??[];return t[0]?.getFirstChild()?.getKind()===x.SyntaxKind.ThisKeyword&&t[1]?.getKind()===x.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 ct=`default`;var lt=class{constructor(e,t){this.sourceFile=e,this.isUsingJSX=t}getImports(){return[...this.getESMImportsNodes(),...this.getCJSImportsNodes()].map(e=>({name:`Import`,location:qe(this.sourceFile,e),node:e,type:`import`,sourceValue:(x.Node.isImportDeclaration(e)?e.getModuleSpecifierValue():e.getFirstDescendantByKind(x.SyntaxKind.StringLiteral)?.getLiteralValue())??``}))}getCJSImportsNodes(){return this.sourceFile.getVariableStatements().filter(e=>(e.getFirstDescendantByKind(x.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(x.SyntaxKind.ExportAssignment).length>0;return e||t||n}getCJSExports(){let e=[],t=``,n=`module.exports`,r=`exports`;for(let i of this.sourceFile.getDescendantsOfKind(x.SyntaxKind.ExpressionStatement)){let a=i.getExpression(),o=a.getText().trim(),s=a.asKind(x.SyntaxKind.BinaryExpression);if(!o.startsWith(n)&&!o.startsWith(r)||!(0,m.isDefined)(s))continue;let c=s.getLeft(),l=c.getText(),u=c.asKind(x.SyntaxKind.PropertyAccessExpression),d=u?.getName()??``,f=c.getKind()===x.SyntaxKind.PropertyAccessExpression,p=s.getRight(),h=f&&u?.getExpression().getText()===n,g=f&&u?.getExpression().getText()===r;if(h&&d===ct){t=p.getText();continue}if(h||g){e.push(d);continue}if(l!==n)continue;let _=t=>{let n=t.asKind(x.SyntaxKind.ObjectLiteralExpression);if((0,m.isDefined)(n))for(let t of n.getProperties()){if(t.getKind()===x.SyntaxKind.PropertyAssignment||t.getKind()===x.SyntaxKind.ShorthandPropertyAssignment||t.getKind()===x.SyntaxKind.MethodDeclaration){let n=t.getName();e.push(n)}if(t.getKind()===x.SyntaxKind.PropertyAssignment){let e=t.getInitializer();(0,m.isDefined)(e)&&_(e)}}},v=t=>{let n=t.asKind(x.SyntaxKind.FunctionDeclaration)?.getBody()?.asKind(x.SyntaxKind.Block);if((0,m.isDefined)(n))for(let t of n.getStatements()){let n=((t.asKind(x.SyntaxKind.ExpressionStatement)?.getExpression())?.asKind(x.SyntaxKind.BinaryExpression)?.getLeft())?.asKind(x.SyntaxKind.PropertyAccessExpression);n?.getExpression().getKind()===x.SyntaxKind.ThisKeyword&&e.push(n.getName())}},y=t=>{let n=t.asKind(x.SyntaxKind.FunctionDeclaration)?.getName();if((0,m.isDefined)(n))for(let t of this.sourceFile.getStatements()){let r=((t.asKind(x.SyntaxKind.ExpressionStatement)?.getExpression())?.asKind(x.SyntaxKind.BinaryExpression)?.getLeft())?.asKind(x.SyntaxKind.PropertyAccessExpression);r?.getExpression().getText()===`${n}.prototype`&&e.push(r.getName())}};if(p.getKind()===x.SyntaxKind.ObjectLiteralExpression){_(p);continue}if(p.getKind()===x.SyntaxKind.Identifier){let t=p.asKind(x.SyntaxKind.Identifier),n=t?.findReferences().map(e=>e.getDefinition().getNode().getParent()).filter(e=>(0,m.isDefined)(e)).filter(e=>e.getKind()===x.SyntaxKind.VariableDeclaration);if(!(0,m.isDefined)(n))continue;for(let t of n){let n=t.getInitializer()?.asKind(x.SyntaxKind.ObjectLiteralExpression);if((0,m.isDefined)(n)){for(let t of n.getProperties())if(t.getKind()===x.SyntaxKind.PropertyAssignment||t.getKind()===x.SyntaxKind.ShorthandPropertyAssignment){let n=t.getName();e.push(n)}}}let r=t?.findReferences().map(e=>e.getDefinition().getNode().getParent()).filter(e=>e?.getKind()===x.SyntaxKind.FunctionDeclaration);if(!(0,m.isDefined)(r))continue;for(let e of r)v(e),y(e)}if(p.isKind(x.SyntaxKind.NewExpression)){let e=p.asKind(x.SyntaxKind.NewExpression);(0,m.isDefined)(e)&&(t=e.getExpression().getText());continue}t=p.getText()}return{namedExports:e,defaultExport:t}}getESMExports(){let e=``,t=[],n=!1;for(let r of this.sourceFile.getExportAssignments()){r.isExportEquals()||(n=!0);let i=r.getExpression();if(i.getKind()===x.SyntaxKind.Identifier){e=i.getText();continue}let a=r.getFirstChildByKind(x.SyntaxKind.ObjectLiteralExpression);if((0,m.isDefined)(a)){for(let e of a.getProperties())if(e.getKind()===x.SyntaxKind.PropertyAssignment||e.getKind()===x.SyntaxKind.ShorthandPropertyAssignment||e.getKind()===x.SyntaxKind.MethodDeclaration){let n=e.getName();t.push(n)}}}let r=this.sourceFile.getExportedDeclarations();if(!(n&&r.size===1&&[...r.keys()][0]===ct))for(let[n,i]of r)if(n===ct){let t=(i[0]?.getFirstChildByKind(x.SyntaxKind.Identifier))?.getText()?.trim()??st;(0,m.isDefined)(t)&&(e=t)}else t.push(n);return{defaultExport:e,namedExports:t}}hasRequire(){return this.sourceFile.getDescendantsOfKind(x.SyntaxKind.CallExpression).some(e=>e.getExpression().getText()===`require`)}transformRequiresToImports(){let e=Ye(this.sourceFile.getProject(),`transformRequiresToImports`,this.sourceFile.getFullText(),this.isUsingJSX),t;try{let n=e.getVariableStatements();for(let e of n){let t=e.getFirstDescendantByKind(x.SyntaxKind.CallExpression),n=t?.getExpression();if(!(0,m.isDefined)(t)||!(0,m.isDefined)(n)||n.getText()!==`require`)continue;let r=t.getFirstDescendantByKind(x.SyntaxKind.StringLiteral)?.getLiteralValue();if(!(0,m.isDefined)(r))continue;let i=e.getDeclarations()?.[0]?.getNameNode()?.getText();if(!(0,m.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()}},ut=class{tests;constructor(e){this.sourceFile=e}getDescribes(){return Ne(this.sourceFile).map(e=>{let t=We(e);return(0,m.isDefined)(t)?{node:e,name:t,location:qe(this.sourceFile,e),type:`describe`}:null}).filter(e=>(0,m.isDefined)(e))}getTests(){return(0,m.isDefined)(this.tests)||(this.tests=Je(this.sourceFile).map(e=>{let t=qe(this.sourceFile,e),n=Ge(e);return(0,m.isDefined)(n)?{node:e,name:n,location:t,type:`test`}:null}).filter(e=>(0,m.isDefined)(e))),this.tests}getDescribeTests(e){return Je(e.node).map(e=>{let t=Ge(e);return(0,m.isDefined)(t)?{node:e,name:t,location:qe(this.sourceFile,e),type:`test`}:null}).filter(e=>(0,m.isDefined)(e))}},dt=class{sourceFile;tests;testables;moduleInfo;constructor(e,t){this.filePath=t;let n=!0;try{let t=new x.Project({useInMemoryFileSystem:!0,skipAddingFilesFromTsConfig:!0,skipFileDependencyResolution:!0,skipLoadingLibFiles:!0}),r=Ye(t,`ast`,e,!0);rt(r)?this.sourceFile=r:(t.removeSourceFile(r),this.sourceFile=Ye(t,`ast`,e,!1),n=!1)}catch{throw Error(`Cannot parse file content`)}this.moduleInfo=new lt(this.sourceFile,n),this.testables=new U(this.sourceFile,this.moduleInfo),this.tests=new ut(this.sourceFile)}isReactFile(){let e=(0,d.extname)(this.filePath??this.sourceFile.getFilePath());return oe.includes(e)||this.isFileContainsImport(`react`)}isFileContainsImport(e){return this.moduleInfo.getImports().some(t=>t.sourceValue.includes(e))}checkIsJSDoc(e,t,n){return t===x.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,m.isEmpty)(r.slice(t,e.start).trim())&&(0,m.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 ft=e=>{let{node:t,parent:n,...r}=e;return r};var pt=class{GITIGNORE_FILE_NAME=`.gitignore`;gitignorePath;constructor(e){this.gitignorePath=(0,d.join)(e,this.GITIGNORE_FILE_NAME)}async add(e){try{let t=await f.default.readFile(this.gitignorePath,`utf8`);t.includes(e)||await f.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 mt=`.early.coverage`;var ht=class{getCoverageDirectoryPath(){let e=n.getGlobalConfig().getRootPath();return d.default.join(e,mt,`v8`)}getCoverageDirectoryForCommand(){return this.getCoverageDirectoryPath()}getExecutionCwd(){return n.getGlobalConfig().getRootPath()}},gt=class extends ht{getCoverageDirectoryForCommand(){let e=n.getGlobalConfig().getGitTopLevel(),t=n.getGlobalConfig().getRootPath(),r=d.default.relative(e,t);return d.default.join(r,mt,`v8`)}};function _t(){let e=n.getGlobalConfig().getCoverageCommand()?.split(/\s+/).includes(`nx`)??!1;return n.logger.info.defaultLog(`Coverage path strategy: `+(e?`nx`:`standard`)),e?new gt:new ht}var vt=class{report={};constructor(e,t){for(let[n,r]of Object.entries(e)){let e=d.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,m.isDefined)(r))return null;let i=this.findFunctionDefinition(t,r.fnMap,n);if(!(0,m.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,m.isDefined)(t)&&t>0&&a++}return{percentage:this.toPercentage(a,o),totalStatements:o,coveredStatements:a}}getStatsForFile(e){let t=this.report[e];if(!(0,m.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,m.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,m.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,m.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=d.default.relative(e,t);return(0,m.isDefined)(n)?!n.startsWith(`..`)&&!d.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 yt(e){let t=n.getGlobalConfig().getRootPath(),r=[];try{let e=new R(`.gitignore`);await e.isFileExists()&&(r=(await e.getText()).split(`
|
|
32593
32593
|
`).map(e=>e.trim()).filter(e=>(0,m.isDefined)(e)&&!e.startsWith(`#`)))}catch{}let i=[`node_modules`,`*.config.ts`,`**/*.mock.ts`,`**/*.mocks.ts`,`**/*.test.ts`,`**/*.spec.ts`,...r];return(await(0,T.default)(e,{cwd:t,absolute:!0,ignore:i})).map(e=>`/${d.default.relative(t,e)}`)}var bt=class{nextSource=null;setNext(e){return this.nextSource=e,e}async getFromNext(e){return this.nextSource?this.nextSource.getFiles(e):[]}},xt=class extends bt{async getFiles(e){return yt(`**/*.{js,ts,jsx,tsx}`)}};let St=/\.[jt]sx?$/;var Ct=class extends bt{async getFiles(e){let t=Object.keys(e).filter(e=>St.test(e));return t.length>0?t:this.getFromNext(e)}};function wt(){let e=new Ct,t=new xt;return e.setNext(t),e}let Tt=String.raw`.*\.early\.(spec|test)\.[tj]sx?$`;var Et=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=_t()}getCoverageDirectoryPath(){if(!(0,m.isDefined)(this.pathStrategy))throw Error(`Provider not initialized. Call init() first.`);return this.pathStrategy.getCoverageDirectoryPath()}getCoverageDirectoryForCommand(){if(!(0,m.isDefined)(this.pathStrategy))throw Error(`Provider not initialized. Call init() first.`);return this.pathStrategy.getCoverageDirectoryForCommand()}getExecutionCwd(){if(!(0,m.isDefined)(this.pathStrategy))throw Error(`Provider not initialized. Call init() first.`);return this.pathStrategy.getExecutionCwd()}getCoverageReportPath(){return d.default.join(this.getCoverageDirectoryPath(),this.COVERAGE_REPORT_FILE_NAME)}async getCommand(e){let t=n.getGlobalConfig().getCoverageCommand(),r=(0,m.isDefined)(e)&&e.length>0?this.formatTestFiles(e):``;if((0,m.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 f.default.access(this.getCoverageReportPath(),f.constants.R_OK),!0}catch{return!1}}async removeReport(){try{let e=R.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 R.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 pe(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 pt(n.getGlobalConfig().getGitTopLevel()).add(this.COVERAGE_ROOT_DIRECTORY_NAME)}}calculateCoverage(e){let t=new vt(e,d.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=he(n.getGlobalConfig().getRootPath());return(0,m.isDefined)(e)}async buildJestCoverageCommand(e){let t=[`node_modules`,`dist`];n.getGlobalConfig().getIncludeEarlyTests()||t.push(Tt);let i=t.map(e=>`"${e}"`).join(` `),a=n.getGlobalConfig().getRootPath(),o=await this.hasJestConfig(),s=(0,m.isDefined)(e)&&e.length>0?` ${this.formatTestFiles(e)}`:``;return o?`npx jest --coverage --coverageProvider=v8 --coveragePathIgnorePatterns ${i} --coverageReporters=json --coverageDirectory=${r.shellEscapePath(n.EARLY_COVERAGE_DIR)} --silent --passWithNoTests --maxWorkers=2 ${s}`:`npx jest --coverage --coverageProvider=v8 --coveragePathIgnorePatterns ${i} --coverageReporters=json --coverageDirectory=${r.shellEscapePath(n.EARLY_COVERAGE_DIR)} --rootDir=${r.shellEscapePath(a)} --silent --passWithNoTests --maxWorkers=2 ${s}`}async getCoverageTree(e){let t=await wt().getFiles(e),n=new Map;for(let r of t){let t=new dt(await new R(r).getText(),`getCoverageTree`).testables.getAllTestables(),i=r.split(`/`).slice(0,-1);for(;!(0,m.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=>ft(e)),s=e[r];for(let e of o){let{name:t}=e;if(!(0,m.isDefined)(t))continue;let n=e.type===`method`?e.parentName:void 0,r=s?.testables?.find(e=>e.name===t),i={name:t,...(0,m.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=>r.shellEscapePath(e)).join(` `)}toPercentage(e,t,n=0){if(t===0)return null;let r=e/t;return Number(Math.round(r*100).toFixed(n))}},Dt=class extends vt{constructor(e,t){super(e,t)}findFunctionDefinition(e,t,n){for(let r of Object.values(t))if(r.name===e||(0,m.isDefined)(n)&&r.name.startsWith(`(anonymous`)&&r.loc.start.line===n)return r;return null}};let Ot=`npx vitest run --coverage.enabled --coverage.exclude="${Tt}" --coverage.reportsDirectory=${n.EARLY_COVERAGE_DIR} --coverage.reportOnFailure=true --coverage.reporter=json --maxWorkers=2 --passWithNoTests`;var kt=class extends Et{async init(){await super.init()}async getCommand(e){let t=n.getGlobalConfig().getCoverageCommand(),r=(0,m.isDefined)(e)&&e.length>0?this.formatTestFiles(e):``;if((0,m.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=Ot.replaceAll(n.EARLY_COVERAGE_DIR,this.getCoverageDirectoryForCommand());return r?`${i} ${r}`:i}async getReport(){try{let e=await R.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=d.default.normalize(n.getGlobalConfig().getRootPath()).toLowerCase(),r=new Dt(e,t),i=this.buildAbsolutePathMap(e,t),a=[...r.getEntries()];return this.processEntries(a,r,i)}buildAbsolutePathMap(e,t){let n=new Map;for(let r of Object.keys(e)){let e=d.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,m.isDefined)(a))return;let o=await this.readFileText(a);if(!(0,m.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 R.fromAbsolutePath(e).getText()}catch{return null}}extractTestables(e,t,n){let r=new dt(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,m.isDefined)(a)&&{parentName:a},percentage:o?.percentage??null,totalStatements:o?.totalStatements??null,coveredStatements:o?.coveredStatements??null})}return i}},At=function(e){return e.JEST=`jest`,e.VITEST=`vitest`,e}(At||{}),jt=class{provider=null;async create(){let e=await this.detectProjectType();return n.logger.info.defaultLog(`Coverage: project type`,e),e===At.JEST?this.provider=new Et:e===At.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`])?At.VITEST:await this.checkFileExists([`package.json`,`jest.config.js`,`jest.config.ts`,`tsconfig.json`])?At.JEST:null}async checkFileExists(e){n.logger.info.defaultLog(`Coverage: checking files`,e);for(let t of e)if(await new R(t).isFileExists())return!0;return!1}};let Mt={};var Nt=class{provider=null;coverage=null;async init(){(0,m.isDefined)(this.provider)||(this.provider=await new jt().create())}async consumeReport(){if((0,m.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,m.isDefined)(this.provider))return Mt;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,m.isDefined)(this.coverage))throw(0,m.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,m.isDefined)(this.provider)||!(0,m.isDefined)(this.coverage)?Mt:this.provider.getCoverageTree(this.coverage)}setCoverage(e){this.coverage=e}getCoverageForFiles(e){if(!(0,m.isDefined)(this.provider))throw Error(`Coverage provider not initialized`);if(!(0,m.isDefined)(this.coverage))throw Error(`Coverage report not available`);return this.provider.getCoverageForFiles(e,this.coverage)}},Pt=t.__toESM(n.require_decorateMetadata()),Ft=t.__toESM(n.require_decorate());let It=class{coverageService=new Nt;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,Ft.default)([n.WithLoggerContext({category:V.GENERATE_COVERAGE}),(0,Pt.default)(`design:type`,Function),(0,Pt.default)(`design:paramtypes`,[Array]),(0,Pt.default)(`design:returntype`,Promise)],It.prototype,`generateCoverage`,null),(0,Ft.default)([n.WithLoggerContext({category:V.SET_COVERAGE}),(0,Pt.default)(`design:type`,Function),(0,Pt.default)(`design:paramtypes`,[Object]),(0,Pt.default)(`design:returntype`,Promise)],It.prototype,`setCoverage`,null),(0,Ft.default)([n.WithLoggerContext({category:V.GET_COVERAGE}),(0,Pt.default)(`design:type`,Function),(0,Pt.default)(`design:paramtypes`,[]),(0,Pt.default)(`design:returntype`,Promise)],It.prototype,`getCoverageTree`,null),(0,Ft.default)([n.WithLoggerContext({category:V.GET_COVERAGE}),(0,Pt.default)(`design:type`,Function),(0,Pt.default)(`design:paramtypes`,[Array]),(0,Pt.default)(`design:returntype`,Promise)],It.prototype,`getCoverageForFiles`,null),It=(0,Ft.default)([(0,h.injectable)()],It);let Lt=new class{safeTrackEvent(e,t){}},Rt={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`},zt={[Rt.EMPTY_TEST]:`Oops! No tests were generated for "{{methodName}}". Code:{{code}} - We're on it!`,[Rt.DESCRIBE_NOT_FOUND]:`Oops! Test suite not found for "{{methodName}}". Code:{{code}} - We're on it!`,[Rt.TESTED_CODE_DATA_SOURCE_ERROR]:`Cannot get testable data for "{{methodName}}". Code:{{code}} - We're on it!`,[Rt.GENERATING_TESTS_REQUEST_ERROR]:`Generating tests for method "{{methodName}}" - failed: "{{errorMessage}}". Code:{{code}} - We're on it!`,[Rt.PREPARATIONS_FOR_GENERATING_TEST_DTO_ERROR]:`Generating tests for method "{{methodName}}" - failed: "{{errorMessage}}". Code:{{code}} - We're on it!`,[Rt.GET_VERSION_REQUEST_ERROR]:`Failed to make request. Code:{{code}} - We're on it!`,[Rt.GENERATING_HELPER_REQUEST_ERROR]:`Generating helpers for method "{{methodName}}" - failed: "{{errorMessage}}". Code:{{code}} - We're on it!`,[Rt.ENHANCE_TESTS_REQUEST_ERROR]:`Enhance tests for method "{{methodName}}" - failed: "{{errorMessage}}". Code:{{code}} - We're on it!`,[Rt.EMPTY_FIXED_TESTS]:`Oops! We got an empty API response for "{{methodName}}" test fixes. Code:{{code}} - We're on it!`,[Rt.TESTABLE_NOT_FOUND]:`Oops! Testable code not found for "{{methodName}}". Code:{{code}} - We're on it!`,[Rt.TESTED_CODE_FILE_PATH_NOT_FOUND]:`Oops! Testable code file path not found for "{{methodName}}". Code:{{code}}`,[Rt.PREEN_TESTS_ERROR]:`Encountered a problem while processing "{{methodName}}". Code:{{code}} - We're on it!`,[Rt.ORGANIZE_IMPORTS_ERROR]:`There was an issue with the processing "{{methodName}}". Code:{{code}} - We're on it!`,[Rt.NOT_ENOUGH_BALANCE_ERROR]:`Usage test generation limit reached.`,[Rt.UNSUPPORTED_MODEL_ERROR]:`We do not support this model at the moment.`,[Rt.TOO_MANY_USERS_ERROR]:`Users limit reached. Please contact support.`,[Rt.PAYLOAD_TOO_LARGE_ERROR]:`We could not generate tests due to code size.`,[Rt.TEST_SUMMARY_DB_REQUEST_ERROR]:`We could not save test summary to database.`,[Rt.TEST_SUMMARY_INVALID_CREATED_BY_ERROR]:`Invalid created by field.`,[Rt.TEST_SUMMARY_INVALID_GIT_REMOTE_ERROR]:`Invalid git remote.`,[Rt.TEST_SUMMARY_INVALID_GIT_BRANCH_ERROR]:`Invalid git branch.`,[Rt.GITHUB_ACTION_TEST_SUMMARY_DB_REQUEST_ERROR]:`We could not save test summary to database.`,[Rt.GITHUB_ACTION_TEST_SUMMARY_READ_CONF_FILE]:`Failed to read github action config file.`,[Rt.GITHUB_ACTION_TEST_SUMMARY_INVALID_GIT_REMOTE_ERROR]:`Invalid git remote.`,[Rt.GITHUB_ACTION_TEST_SUMMARY_INVALID_GIT_BRANCH_ERROR]:`Invalid git branch.`,[Rt.GITHUB_ACTION_TEST_SUMMARY_READ_CONF_FILE_EMPTY_OPTIONS]:`Failed to parse options from github action conf file.`,[Rt.GITHUB_ACTION_TEST_SUMMARY_NO_COVERAGE_FOUND]:`No coverage found. Please run coverage first.`,[Rt.WS_DYNAMIC_PROMPT_GENERAL_ERROR]:`Failed initializing dynamic prompt.`,[Rt.WS_DYNAMIC_PROMPT_AUTH_ERROR]:`Failed authorizing dynamic prompt.`,[Rt.PREPARATIONS_FOR_DYNAMIC_PROMPT_ERROR]:`Failed preparing init dynamic prompt.`,[Rt.WS_DYNAMIC_PROMPT_VALIDATION_FAILED_ERROR]:`Failed validating dynamic prompt dto.`,[Rt.WS_DYNAMIC_PROMPT_TIMEOUT_ERROR]:`Dynamic prompt operation timed out.`};var Bt=class extends Error{constructor(e,t){let n=Vt(e,t);super(n),this.code=e}};let Vt=(e,t)=>{let n=zt[e];for(let[r,i]of Object.entries({...t,code:e}))n=n.replace(`{{${r}}}`,i);return n},Ht=`x-request-id`;var Ut=class extends Error{constructor(){super(`Not authorized`)}};new TextEncoder;let Wt=new TextDecoder;function Gt(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 Kt(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof e==`string`?e:Wt.decode(e),{alphabet:`base64url`});let t=e;t instanceof Uint8Array&&(t=Wt.decode(t)),t=t.replace(/-/g,`+`).replace(/_/g,`/`);try{return Gt(t)}catch{throw TypeError(`The input to be decoded is not correctly encoded.`)}}var qt=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)}},Jt=class extends qt{static code=`ERR_JWT_INVALID`;code=`ERR_JWT_INVALID`};let Yt=e=>typeof e==`object`&&!!e;function Xt(e){if(!Yt(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 Zt(e){if(typeof e!=`string`)throw new Jt(`JWTs must use Compact JWS serialization, JWT must be a string`);let{1:t,length:n}=e.split(`.`);if(n===5)throw new Jt(`Only JWTs using Compact JWS serialization can be decoded`);if(n!==3)throw new Jt(`Invalid JWT`);if(!t)throw new Jt(`JWTs must contain a payload`);let r;try{r=Kt(t)}catch{throw new Jt(`Failed to base64url decode the payload`)}let i;try{i=JSON.parse(Wt.decode(r))}catch{throw new Jt(`Failed to parse the decoded payload as JSON`)}if(!Xt(i))throw new Jt(`Invalid JWT Claims Set`);return i}let Qt=e=>{let t=Zt(e).exp;return(0,m.isDefined)(t)?t*1e3:null},$t=e=>{if(!(0,m.isDefined)(e))return!0;let t=Qt(e);return(0,m.isDefined)(t)?t<Date.now():!0};var en=t.__toESM(n.require_decorate());let tn=class{jwtToken=null;refreshTokenCallback=null;observer=new m.Observer;refreshTokenMutex=new k.Mutex;setJWTToken(e){this.jwtToken=e,this.observer.notifyAll(e)}async getJWTToken(){return(0,m.isDefined)(this.jwtToken)?(this.isTokenValid()||await this.refreshTokenMutex.runExclusive(async()=>{if((0,m.isDefined)(this.refreshTokenCallback))return await this.refreshTokenCallback(),this.jwtToken}),this.jwtToken):null}async getJWTTokenWithMinLifetime(e){return this.hasAtLeastLifetime(e)?this.jwtToken:(await this.refreshTokenMutex.runExclusive(async()=>{if(!this.hasAtLeastLifetime(e)&&(0,m.isDefined)(this.refreshTokenCallback))try{await this.refreshTokenCallback()}catch(e){n.logger.info.defaultLog(`JWT refresh failed in getJWTTokenWithMinLifetime: ${e}`)}}),this.hasAtLeastLifetime(e)||n.logger.info.defaultLog(`JWT still has less than ${e}ms of life after refresh attempt (no refresh callback, or refresh produced a short-lived token); a long session may 401`),this.jwtToken)}hasAtLeastLifetime(e){if(!(0,m.isDefined)(this.jwtToken))return!1;let t=Qt(this.jwtToken);return(0,m.isDefined)(t)&&t-Date.now()>=e}async getJWTTokenOrThrow(){let e=await this.getJWTToken();if(!(0,m.isDefined)(e))throw new Ut;return e}onJWTTokenSave(e){this.observer.addListener(e)}isTokenValid(){return!$t(this.jwtToken)}setRefreshTokenCallback(e){this.refreshTokenCallback=e}};tn=(0,en.default)([(0,h.injectable)(`Singleton`)],tn);var nn=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})),rn=t.__toESM(n.require_decorateMetadata()),an=t.__toESM(nn()),on=t.__toESM(n.require_decorate()),sn,cn;let ln=class{axiosInstance;constructor(e,t){this.authStorage=e,this.globalConfigService=t,this.axiosInstance=D.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,m.isDefined)(e)){let t=E.default.createGzip();return t.write(JSON.stringify(e)),t.end(),t}else return e}]}),(0,O.default)(this.axiosInstance)}async apiCall({url:e,method:t,data:n,config:r}){let i=new D.AxiosHeaders({"x-request-source":this.globalConfigService.getRequestSource(),...r?.headers});if(!r?.ignoreAuth){let e=await this.authStorage.getJWTToken();(0,m.isDefined)(e)&&!(0,m.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(D.default.isAxiosError(t))if((0,m.isDefined)(t.response)){let{status:e,statusText:n,data:r}=t.response;throw e===D.HttpStatusCode.PaymentRequired?new Bt(Rt.NOT_ENOUGH_BALANCE_ERROR):Error(`API request failed: ${e} ${n} - ${JSON.stringify(r)}`)}else if((0,m.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,m.isDefined)(t)&&e()})}};ln=(0,on.default)([(0,h.injectable)(),(0,an.default)(0,(0,h.inject)(tn)),(0,an.default)(1,(0,h.inject)(n.GlobalConfigService)),(0,rn.default)(`design:paramtypes`,[typeof(sn=tn!==void 0&&tn)==`function`?sn:Object,typeof(cn=n.GlobalConfigService!==void 0&&n.GlobalConfigService)==`function`?cn:Object])],ln);let un={SUPER_ADMIN:1,ADMIN:2,USER:3},dn=[un.ADMIN,un.SUPER_ADMIN];var W=t.__toESM(n.require_decorateMetadata()),fn=t.__toESM(nn()),pn=t.__toESM(n.require_decorate()),mn;let hn=class{mutex=new k.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,m.isDefined)(this.user)?this.user:await this.mutex.runExclusive(async()=>await this.fetchUser())}async isAdminUser(){let e=await this.getUser();return(0,m.isDefined)(e)?dn.includes(e?.role):!1}async isInOrganization(){let e=await this.getUser();return(0,m.isDefined)(e?.organization)}};hn=(0,pn.default)([(0,h.injectable)(),(0,fn.default)(0,(0,h.inject)(ln)),(0,W.default)(`design:paramtypes`,[typeof(mn=ln!==void 0&&ln)==`function`?mn:Object])],hn);let gn=e=>(0,v.createHash)(`md5`).update(String(e)).digest(`hex`),_n=e=>({...vn(e),testFrameworkReceived:(0,m.isDefined)(e.testFrameworkReceived)?gn(e.testFrameworkReceived):void 0,testFrameworkExpected:(0,m.isDefined)(e.testFrameworkExpected)?gn(e.testFrameworkExpected):void 0}),vn=e=>({errorCode:e.errorCode,shortDescription:gn(e.shortDescription),fullDescription:gn(e.fullDescription)}),yn=e=>({name:gn(e.name),code:gn(e.code),status:e.status,errors:e.errors?.map(e=>_n(e)),lintErrors:e.lintErrors?.map(e=>bn(e))??null}),bn=e=>({errorCode:e.errorCode,fullDescription:gn(e.fullDescription),shortDescription:gn(e.shortDescription),severity:e.severity,exactCode:gn(e.exactCode)}),xn=({describe:e,stdout:t})=>({describe:{path:e.path,code:gn(e.code),fullCode:gn(e.fullCode),status:e.status,errors:e.errors?.map(e=>vn(e)),tests:e.tests.map(e=>yn(e)),lintErrors:e.lintErrors?.map(e=>bn(e))??null},stdout:t});var Sn=t.__toESM(n.require_decorateMetadata()),Cn=t.__toESM(nn()),wn=t.__toESM(n.require_decorate()),G,Tn,En;let Dn=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,m.isDefined)(r?.testResult)?xn(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=r.findPackageJson(e);if(!(0,m.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:{[Ht]:n}})}async updateRepositoryPackageJson(e){try{let t=this.globalConfigService.getContext();if(!(0,m.isDefined)(t?.git?.owner)||!(0,m.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)}}};Dn=(0,wn.default)([(0,h.injectable)(),(0,Cn.default)(0,(0,h.inject)(ln)),(0,Cn.default)(1,(0,h.inject)(hn)),(0,Cn.default)(2,(0,h.inject)(n.GlobalConfigService)),(0,Sn.default)(`design:paramtypes`,[typeof(G=ln!==void 0&&ln)==`function`?G:Object,typeof(Tn=hn!==void 0&&hn)==`function`?Tn:Object,typeof(En=n.GlobalConfigService!==void 0&&n.GlobalConfigService)==`function`?En:Object])],Dn);var On=class{queue;activeProcesses=[];itemAddedObserver=new m.Observer;itemExecutedObserver=new m.Observer;itemAbortedObserver=new m.Observer;abortControllers=new Map;getItemKey;constructor({concurrency:e,getItemKey:t}){this.queue=new A.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,m.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,m.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 An=class{fulfill(e){if(n.getGlobalConfig().getTestFramework()!==n.TestFramework.JEST)return!1;let t=e,i=null,a=0;for(;a<25;){a++;let e=r.findupFile(t,`package.json`);if(!(0,m.isDefined)(e)||e===i)return!1;let n=r.findPackageJson(t);if((0,m.isDefined)(n)&&r.isExistDependency(n,`jest`))return!0;i=e,t=d.default.dirname(d.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`,Mn=new class{constructor(e){this.providers=e}getTestCommand(e){let t=this.getProvider(e);if(!(0,m.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,i=null,a=0;for(;a<25;){a++;let e=r.findupFile(t,`package.json`);if(!(0,m.isDefined)(e)||e===i)return!1;let n=r.findPackageJson(t);if((0,m.isDefined)(n)&&r.isExistDependency(n,`vitest`))return!0;i=e,t=d.default.dirname(d.default.dirname(e))}return!1}getTestCommand(){return{command:n.getGlobalConfig().getTestCommand()??jn,framework:n.TestFramework.VITEST}}},new An]);var Nn=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 Pn=`validate-tests`,Fn=e=>e instanceof Error&&`code`in e&&typeof e.code==`number`;var In=class e{constructor(e){this.relativePath=e}async runCommandOnFile(e,t=Nn.success,i=!1){let a=i?r.escapeRegexPath(d.default.normalize(this.relativePath)):d.default.normalize(this.relativePath),o=e.replaceAll(n.EARLY_FILENAME_VAR,r.shellEscapePath(a));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 pe(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(!(Fn(r)&&(0,m.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=d.default.join(_.default.tmpdir(),`early`),n=`${e}-${(0,v.randomUUID)()}`;return d.default.join(t,n)}let i=(0,m.isDefined)(r)&&!(0,m.isEmpty)(r),a=i&&d.default.isAbsolute(r)?d.default.dirname(r):d.default.join(n.getGlobalConfig().getRootPath(),d.default.dirname(r??``));if(!(0,m.isDefined)(a))throw Error(`Workspace root path is not defined`);let o=`.${e}-${(0,v.randomUUID)()}-${i?d.default.basename(r):`.ts`}`;return d.default.join(a,o)}async runCommandWithContent(t,r,i,a=!1){n.logger.addContext({subCategory:ae.COMMAND_EXECUTION});let o={filePrefix:`generated-content`,useTemporaryOSFolder:!(0,m.isDefined)(i?.predefinedPath),validExitCodes:Nn.success,...i},s=this.getTempFileName(o.filePrefix,o.useTemporaryOSFolder,o.predefinedPath);try{n.logger.info.defaultLog(`Creating temp file ${s}`),await f.default.mkdir(d.default.dirname(s),{recursive:!0}),await f.default.writeFile(s,t);let i=new e(s);return n.logger.info.defaultLog(`Running command "${r}" on temp file`),await i.runCommandOnFile(r,o.validExitCodes,a)}catch(e){return n.logger.error(`Failed running command "${r}" on temp file`,e),``}finally{try{await f.default.unlink(s)}catch(e){n.logger.info.defaultLog(`Failed removing temp file`,e)}}}async runTestCommand(){n.logger.addContext({subCategory:ae.COMMAND_EXECUTION});let e;try{e=Mn.getTestCommand(this.relativePath)}catch(e){return e instanceof Error?e.message:`Framework is not supported yet`}return await this.runCommandOnFile(e.command,Nn.suppress_1,!0)}async runTestCommandOnTempFile(e){n.logger.addContext({subCategory:ae.COMMAND_EXECUTION});let t;try{t=Mn.getTestCommand(this.relativePath)}catch(e){return e instanceof Error?e.message:`Framework is not supported yet`}return await this.runCommandWithContent(e,t.command,{validExitCodes:Nn.suppress_1,filePrefix:Pn,predefinedPath:this.relativePath},!0)}async runFormatCommand(){n.logger.addContext({subCategory:ae.COMMAND_EXECUTION});let e=n.getGlobalConfig().getPrettierCommand();n.logger.debug.startLog(`format command: ${e}`);let t=await this.runCommandOnFile(e,Nn.all);return n.logger.debug.endLog(`format command: ${e}`),t}async runLintCommand(e=[]){n.logger.addContext({subCategory:ae.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,Nn.all);return n.logger.debug.endLog(`lint command: ${r}`),i}};let Ln=e=>{let t=e.name??``,n=e.type;return{methodType:n,methodName:t,parentName:n===`method`?e.parentName:void 0}};async function Rn(e,{methodType:t,methodName:n,parentName:r}){let i=new dt(await new R(e).getText()).testables.findTestable(t,n,r);if(!(0,m.isDefined)(i))throw new Bt(Rt.TESTABLE_NOT_FOUND,{methodName:n});return i}function zn(e,t){return(0,m.isDefined)(t)&&!(0,m.isEmpty)(t)?`${t}.${e}`:e}function Bn(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 Vn=t.__toESM(n.require_decorate());let Hn=class{contentCache=new Map;filePathIndex=new Map;computeContentHash(e){return gn(e)}getContentCacheKey(e,t){return`${e}:${t?`fix`:`nofix`}`}evictOldest(){let e=this.contentCache.keys().next().value;(0,m.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,m.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,m.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`)}};Hn=(0,Vn.default)([(0,h.injectable)()],Hn);let Un=function(e){return e[e.ERROR=2]=`ERROR`,e[e.WARN=1]=`WARN`,e[e.OFF=0]=`OFF`,e}({});var Wn=t.__toESM(n.require_decorateMetadata()),Gn=t.__toESM(nn()),Kn=t.__toESM(n.require_decorate()),qn,Jn;let Yn=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()?re:[]].filter(m.isDefined);this.globalConfigService.shouldDisableLintRules()?await this.disableAllLintRules(e):(0,m.isEmpty)(t)||await this.disableLintRules(e,t),await Oe.refreshFromFileSystem(e)}async disableAllLintRules(e){let t=await this.getRulesToDisable(e);if((0,m.isDefined)(t)){if((0,m.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=R.fromRelativePath(e),r=await n.getText(),i=this.lintCacheService.get(e,r,t);if((0,m.isDefined)(i))return i;let a=t?[`--format`,`json`,`--fix`]:[`--format`,`json`],o=Bn(await new In(e).runLintCommand(a));if(!(0,m.isDefined)(o))return null;if(t){await Oe.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,m.isDefined)(t))return null;let n=(t[0]?.messages??[]).filter(e=>e.severity===Un.ERROR);return[...new Set(n.map(e=>e.ruleId).filter(m.isDefined))]}async addDisableComment(e,t){let n=R.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(`
|
|
32594
32594
|
`);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=R.fromRelativePath(e),i=await r.getText();if(this.hasDisableCommentForRules(i,t))return;let a=await this.getLintResults(e);if(!(0,m.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===Un.ERROR&&t.ruleId===e));if((0,m.isEmpty)(s))return;let c=`/* eslint-disable ${s.join(`, `)} */\n\n`;await r.replace(c+i),this.lintCacheService.invalidate(e),n.logger.info.defaultLog(`Added eslint-disable comment for ${s.join(`, `)} in ${e}`)}};Yn=(0,Kn.default)([(0,h.injectable)(),(0,Gn.default)(0,(0,h.inject)(n.GlobalConfigService)),(0,Gn.default)(1,(0,h.inject)(Hn)),(0,Wn.default)(`design:paramtypes`,[typeof(qn=n.GlobalConfigService!==void 0&&n.GlobalConfigService)==`function`?qn:Object,typeof(Jn=Hn!==void 0&&Hn)==`function`?Jn:Object])],Yn);let Xn="${methodName}";`${Xn}`,`${Xn}`;function Zn(e,t,n){let r=e.split(`
|
|
@@ -33244,7 +33244,7 @@ RULES (two-tier boundary):
|
|
|
33244
33244
|
- Write \`trace.calledModules\` paths relative to the WORKING DIRECTORY \`${e}\` (e.g. \`${r[0]?.name??`dep`}/src/...\` for dependency files, and the primary's own called files as usual). This keeps dependency files matchable when they change. (Only \`trace.entryFiles\` is primary-relative; \`calledModules\` is working-directory-relative so it can name files in either the primary or a dependency.)`}let Qm=e=>e.replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`);function $m(e){return e.length===0?``:[`<flow-library>`,` <!--`,` Persistent flow library for this (repo, anchor_branch). The values you see`,` here are already merged (user overrides shadow LLM proposals).`,``,` Rules:`,` - REUSE the listed flowId when you re-identify the same flow (do not invent`,` a new id for an existing flow).`,` - userOwnedFields lists fields the user has locked. Do NOT propose values`,` that conflict with what the user set; backend will ignore conflicting`,` proposals for these fields. Pick non-overlapping rank values where rank`,` is locked. Respect user-set importance unless you have a strong reason`,` and even then know your proposal will not stick.`,` - Flows you don't re-emit this run remain in the library with their prior`,` values — that's expected, not an error. Only emit the flows you'd put`,` in your top-${o.REGRESSION_CATALOG_TARGET_COUNT}.`,` -->`,e.map(e=>{let t=e.userOverride===void 0?[]:Object.keys(e.userOverride),n=t.length>0?t.map(e=>Qm(e)).join(`, `):`(none)`,r=e.userOverride?.name??e.name,i=e.userOverride?.description??e.description,a=e.userOverride?.importance??e.importance,o=e.userOverride?.importanceReason??e.importanceReason,s=e.userOverride?.rank??e.rank,c=i===null?``:` <description>${Qm(i)}</description>`,l=o===null?``:` <importanceReason>${Qm(o)}</importanceReason>`;return[` <flow>`,` <flowId>${Qm(e.flowId)}</flowId>`,` <name>${Qm(r)}</name>`,c,` <rank>${s}</rank>`,` <importance>${Qm(a)}</importance>`,l,` <origin>${e.origin}</origin>`,` <userOwnedFields>${n}</userOwnedFields>`,` </flow>`].filter(Boolean).join(`
|
|
33245
33245
|
`)}).join(`
|
|
33246
33246
|
`),`</flow-library>`].join(`
|
|
33247
|
-
`)}var eh=t.__toESM(n.require_decorateMetadata()),th=t.__toESM(nn()),nh=t.__toESM(n.require_decorate()),rh;let ih=[`Read`,`Glob`,`Grep`,`Bash`];function ah(e,t,r){try{let i=I.default.join(e,`reports`,`catalog-prompts`);(0,y.mkdirSync)(i,{recursive:!0});let a=new Date().toISOString().replaceAll(/[:.]/g,`-`),o=I.default.join(i,`${a}-catalog.prompt.log`),s=`# SYSTEM PROMPT\n\n${t}\n\n# USER PROMPT\n\n${r}\n`;(0,y.writeFileSync)(o,s,`utf8`),n.logger.info.defaultLog(`[regression-agent] Catalog prompt written to ${o}`)}catch(e){n.logger.info.defaultLog(`[regression-agent] Failed to write catalog prompt: ${String(e)}`)}}function oh(e){let t=e.toLowerCase().trim().replaceAll(/\s+/g,`-`).replaceAll(/[^a-z0-9-]/g,``).replaceAll(/-+/g,`-`).replaceAll(/^-/g,``).replaceAll(/-$/g,``);return t.length>0?t:`flow`}let sh=class{constructor(e,t){this.globalConfigService=e,this.authStorage=t}agenticToolLog=[];async run(e){let{rootPath:t,anchorBranch:r,primarySource:a,dependencyRoots:c}=e,l=e.agentLog??!1;i.setAgentLogEnabled(l);let u=await this.authStorage.getJWTToken();n.logger.info.defaultLog(`[regression-agent] Starting catalog sync for ${t} on branch "${r}"`);let{query:d,getMessageContentBlocks:f,isResultMessage:p,isErrorResult:m}=await Promise.resolve().then(()=>lz()),h=e.incrementalEmit??!1;n.logger.info.defaultLog(`[regression-agent] Catalog output mode: ${h?`incremental per-flow emit (emit_catalog_flow)`:`single StructuredOutput`}`);let g=Xm(c.length>0,h),_=Zm(t,r,a,c),y=e.libraryFlows&&e.libraryFlows.length>0?$m(e.libraryFlows):``,b=y?`${y}\n\n${_}`:_;n.logger.info.defaultLog(`[regression-agent] Catalog SDK cwd (rootPath): ${t}`),i.logAgentCwd(`catalog`,t),o.REGRESSION_CATALOG_LOG_PROMPT&&!h&&ah(t,g,b);let x=h?new s.CatalogEmitCollector:void 0,S;if(x!==void 0){let{createCatalogEmitServer:e}=await Promise.resolve().then(()=>kU());S=e(x)}let C=d({prompt:b,options:{model:o.REGRESSION_CATALOG_MODEL,systemPrompt:g,allowedTools:h?[...ih,s.MCP_EMIT_FLOW_TOOL,s.MCP_EMIT_SUMMARY_TOOL]:[...ih],permissionMode:o.REGRESSION_PERMISSION_MODE,allowDangerouslySkipPermissions:!0,maxBudgetUsd:o.REGRESSION_CATALOG_MAX_BUDGET_USD,maxTurns:o.REGRESSION_CATALOG_MAX_TURNS,...h?{}:{outputFormat:{type:`json_schema`,schema:i.CATALOG_OUTPUT_SCHEMA}},...S&&{mcpServers:{catalog_emit:S}},cwd:t,sessionId:(0,v.randomUUID)(),env:{...process.env,...i.buildAnthropicSdkEnv({proxyUrl:this.globalConfigService.getAnthropicProxyUrl(),jwtToken:u??``,requestId:n.logger.getRequestId()})}}}),w,T,E=0,D,O=Date.now();for await(let e of C){let t=Date.now(),r=t-O;O=t;let i=String(e.type??``),a=e.error,s=a===void 0?``:` ⚠ error=${String(a)}`;l&&n.logger.info.defaultLog(`[regression-agent] [${new Date(t).toISOString()}] [catalog-debug] SDK message (type: ${i}) — ${(r/1e3).toFixed(1)}s since previous${s}`);let c=f(e);if(c!==void 0&&c.length>0&&(E++,this.logAgenticTurn(E,c)),p(e)){if(m(e))throw new cf(e.subtype,e.errors,e.total_cost_usd);if(w=e.total_cost_usd,typeof e.duration_ms==`number`&&(T=Math.round(e.duration_ms/1e3)),l){let t=e.duration_ms??0,r=e.duration_api_ms??0,i=e.num_turns;n.logger.info.defaultLog(`[regression-agent] [catalog-debug] timing — total=${(t/1e3).toFixed(1)}s api=${(r/1e3).toFixed(1)}s non-api=${((t-r)/1e3).toFixed(1)}s turns=${String(i??`—`)}`)}x!==void 0&&x.flows.length>0?(D=ch({flows:x.flows,projectSummary:x.projectSummary,projectType:x.projectType,detectedEntryCount:x.detectedEntryCount}),n.logger.info.defaultLog(`[regression-agent] Catalog incremental emit: collected ${x.flows.length} flow(s) via emit_catalog_flow`)):(x!==void 0&&n.logger.info.defaultLog(`[regression-agent] Catalog incremental emit: 0 flows emitted — falling back to StructuredOutput blob`),D=ch(e.structured_output)),o.REGRESSION_LOG_COST&&n.logger.info.defaultLog(`[regression-agent] Result received. Cost: $${w?.toFixed(4)} Duration: ${T??`—`}s`);break}}o.REGRESSION_LOG_COST&&n.logger.info.defaultLog(`[regression-agent] Catalog sync done. ${E} turns. Cost: $${w?.toFixed(4)} Duration: ${T??`—`}s`);let k=D?{flows:D.flows,projectSummary:D.projectSummary,projectType:D.projectType,detectedEntryCount:D.detectedEntryCount}:{flows:[],projectSummary:``,projectType:`unknown`,detectedEntryCount:0};return this.normalizeFlowTypes(k.flows),this.normalizeFlowIds(k.flows),this.assignStepIds(k.flows),this.assignRanks(k.flows),o.REGRESSION_LOG_COST&&n.logger.info.defaultLog(`[regression-agent] Done. ${k.flows.length} flows found. Cost: $${w?.toFixed(4)}`),{result:k,costUsd:w,durationSeconds:T,generatedPrompt:b}}getAgenticToolLog(){return this.agenticToolLog}logAgenticTurn(e,t){i.logAgentActivity(`catalog`,e,t);for(let n of t){let t=n,r=String(t.type??``);if(r===`tool_use`){let n=String(t.name??``),r=t.input,i=r===void 0?``:JSON.stringify(r);this.agenticToolLog.push(`[Turn ${e}] TOOL: ${n}\n Input: ${i.slice(0,500)}`)}else if(r===`tool_result`){let e=typeof t.content==`string`?t.content:JSON.stringify(t.content??``),n=e.slice(0,300).replaceAll(`
|
|
33247
|
+
`)}var eh=t.__toESM(n.require_decorateMetadata()),th=t.__toESM(nn()),nh=t.__toESM(n.require_decorate()),rh;let ih=[`Read`,`Glob`,`Grep`,`Bash`];function ah(e,t,r){try{let i=I.default.join(e,`reports`,`catalog-prompts`);(0,y.mkdirSync)(i,{recursive:!0});let a=new Date().toISOString().replaceAll(/[:.]/g,`-`),o=I.default.join(i,`${a}-catalog.prompt.log`),s=`# SYSTEM PROMPT\n\n${t}\n\n# USER PROMPT\n\n${r}\n`;(0,y.writeFileSync)(o,s,`utf8`),n.logger.info.defaultLog(`[regression-agent] Catalog prompt written to ${o}`)}catch(e){n.logger.info.defaultLog(`[regression-agent] Failed to write catalog prompt: ${String(e)}`)}}function oh(e){let t=e.toLowerCase().trim().replaceAll(/\s+/g,`-`).replaceAll(/[^a-z0-9-]/g,``).replaceAll(/-+/g,`-`).replaceAll(/^-/g,``).replaceAll(/-$/g,``);return t.length>0?t:`flow`}let sh=class{constructor(e,t){this.globalConfigService=e,this.authStorage=t}agenticToolLog=[];async run(e){let{rootPath:t,anchorBranch:r,primarySource:a,dependencyRoots:c}=e,l=e.agentLog??!1;i.setAgentLogEnabled(l);let u=await this.authStorage.getJWTToken();n.logger.info.defaultLog(`[regression-agent] Starting catalog sync for ${t} on branch "${r}"`);let{query:d,getMessageContentBlocks:f,isResultMessage:p,isErrorResult:m}=await Promise.resolve().then(()=>lz()),h=e.incrementalEmit??!1;n.logger.info.defaultLog(`[regression-agent] Catalog output mode: ${h?`incremental per-flow emit (emit_catalog_flow)`:`single StructuredOutput`}`);let g=Xm(c.length>0,h),_=Zm(t,r,a,c),y=e.libraryFlows&&e.libraryFlows.length>0?$m(e.libraryFlows):``,b=y?`${y}\n\n${_}`:_;n.logger.info.defaultLog(`[regression-agent] Catalog SDK cwd (rootPath): ${t}`),i.logAgentCwd(`catalog`,t),o.REGRESSION_CATALOG_LOG_PROMPT&&!h&&ah(t,g,b);let x=h?new s.CatalogEmitCollector:void 0,S;if(x!==void 0){let{createCatalogEmitServer:e}=await Promise.resolve().then(()=>kU());S=e(x)}let C=d({prompt:b,options:{model:o.REGRESSION_CATALOG_MODEL,...o.REGRESSION_SONNET_ANALYZER_REASONING,systemPrompt:g,allowedTools:h?[...ih,s.MCP_EMIT_FLOW_TOOL,s.MCP_EMIT_SUMMARY_TOOL]:[...ih],permissionMode:o.REGRESSION_PERMISSION_MODE,allowDangerouslySkipPermissions:!0,maxBudgetUsd:o.REGRESSION_CATALOG_MAX_BUDGET_USD,maxTurns:o.REGRESSION_CATALOG_MAX_TURNS,...h?{}:{outputFormat:{type:`json_schema`,schema:i.CATALOG_OUTPUT_SCHEMA}},...S&&{mcpServers:{catalog_emit:S}},cwd:t,sessionId:(0,v.randomUUID)(),env:{...process.env,...i.buildAnthropicSdkEnv({proxyUrl:this.globalConfigService.getAnthropicProxyUrl(),jwtToken:u??``,requestId:n.logger.getRequestId()})}}}),w,T,E=0,D,O=Date.now();for await(let e of C){let t=Date.now(),r=t-O;O=t;let i=String(e.type??``),a=e.error,s=a===void 0?``:` ⚠ error=${String(a)}`;l&&n.logger.info.defaultLog(`[regression-agent] [${new Date(t).toISOString()}] [catalog-debug] SDK message (type: ${i}) — ${(r/1e3).toFixed(1)}s since previous${s}`);let c=f(e);if(c!==void 0&&c.length>0&&(E++,this.logAgenticTurn(E,c)),p(e)){if(m(e))throw new cf(e.subtype,e.errors,e.total_cost_usd);if(w=e.total_cost_usd,typeof e.duration_ms==`number`&&(T=Math.round(e.duration_ms/1e3)),l){let t=e.duration_ms??0,r=e.duration_api_ms??0,i=e.num_turns;n.logger.info.defaultLog(`[regression-agent] [catalog-debug] timing — total=${(t/1e3).toFixed(1)}s api=${(r/1e3).toFixed(1)}s non-api=${((t-r)/1e3).toFixed(1)}s turns=${String(i??`—`)}`)}x!==void 0&&x.flows.length>0?(D=ch({flows:x.flows,projectSummary:x.projectSummary,projectType:x.projectType,detectedEntryCount:x.detectedEntryCount}),n.logger.info.defaultLog(`[regression-agent] Catalog incremental emit: collected ${x.flows.length} flow(s) via emit_catalog_flow`)):(x!==void 0&&n.logger.info.defaultLog(`[regression-agent] Catalog incremental emit: 0 flows emitted — falling back to StructuredOutput blob`),D=ch(e.structured_output)),o.REGRESSION_LOG_COST&&n.logger.info.defaultLog(`[regression-agent] Result received. Cost: $${w?.toFixed(4)} Duration: ${T??`—`}s`);break}}o.REGRESSION_LOG_COST&&n.logger.info.defaultLog(`[regression-agent] Catalog sync done. ${E} turns. Cost: $${w?.toFixed(4)} Duration: ${T??`—`}s`);let k=D?{flows:D.flows,projectSummary:D.projectSummary,projectType:D.projectType,detectedEntryCount:D.detectedEntryCount}:{flows:[],projectSummary:``,projectType:`unknown`,detectedEntryCount:0};return this.normalizeFlowTypes(k.flows),this.normalizeFlowIds(k.flows),this.assignStepIds(k.flows),this.assignRanks(k.flows),o.REGRESSION_LOG_COST&&n.logger.info.defaultLog(`[regression-agent] Done. ${k.flows.length} flows found. Cost: $${w?.toFixed(4)}`),{result:k,costUsd:w,durationSeconds:T,generatedPrompt:b}}getAgenticToolLog(){return this.agenticToolLog}logAgenticTurn(e,t){i.logAgentActivity(`catalog`,e,t);for(let n of t){let t=n,r=String(t.type??``);if(r===`tool_use`){let n=String(t.name??``),r=t.input,i=r===void 0?``:JSON.stringify(r);this.agenticToolLog.push(`[Turn ${e}] TOOL: ${n}\n Input: ${i.slice(0,500)}`)}else if(r===`tool_result`){let e=typeof t.content==`string`?t.content:JSON.stringify(t.content??``),n=e.slice(0,300).replaceAll(`
|
|
33248
33248
|
`,` `);this.agenticToolLog.push(` Result: ${n}${e.length>300?`...`:``}`)}else if(r===`text`&&typeof t.text==`string`){let n=t.text.slice(0,200).replaceAll(`
|
|
33249
33249
|
`,` `);this.agenticToolLog.push(`[Turn ${e}] TEXT: ${n}${t.text.length>200?`...`:``}`)}}}normalizeFlowTypes(e){let t=new Set([`ENDPOINT`,`COMMAND`,`PAGE`,`EXPORT`,`HANDLER`,`JOB`,`JOURNEY`,`OTHER`]),n={endpoint:`ENDPOINT`,"api-endpoint":`ENDPOINT`,"api-group":`ENDPOINT`,"rest-api":`ENDPOINT`,api:`ENDPOINT`,route:`ENDPOINT`,http:`ENDPOINT`,rest:`ENDPOINT`,command:`COMMAND`,"cli-command":`COMMAND`,cli:`COMMAND`,cmd:`COMMAND`,page:`PAGE`,"web-page":`PAGE`,screen:`PAGE`,view:`PAGE`,export:`EXPORT`,"library-export":`EXPORT`,"public-api":`EXPORT`,handler:`HANDLER`,"event-handler":`HANDLER`,"real-time-stream":`HANDLER`,"real-time":`HANDLER`,webhook:`HANDLER`,event:`HANDLER`,stream:`HANDLER`,job:`JOB`,"background-job":`JOB`,cron:`JOB`,scheduled:`JOB`,worker:`JOB`,task:`JOB`,queue:`JOB`,journey:`JOURNEY`,"user-journey":`JOURNEY`,"business-process":`JOURNEY`,workflow:`JOURNEY`,pipeline:`JOURNEY`,process:`JOURNEY`};for(let r of e){let e=String(r.flowType??``).trim(),i=e.toUpperCase();t.has(i)?r.flowType=i:r.flowType=n[e.toLowerCase()]??`OTHER`}}normalizeFlowIds(e){let t=new Set;for(let n of e){let e=n,r;typeof e.flowId==`string`&&e.flowId.length>0?r=e.flowId:typeof e.flow_id==`string`&&e.flow_id.length>0&&(r=e.flow_id);let i=r??oh(n.name);t.has(i)&&(i=`${i}-${n.rank}`),t.add(i),n.flowId=i}}assignStepIds(e){for(let t of e)if(t.productFlow!==void 0)for(let e of t.productFlow.steps)e.stepId=(0,v.randomUUID)().slice(0,8)}assignRanks(e){e.sort((e,t)=>{let n=e.scoring?.finalScore??0;return(t.scoring?.finalScore??0)-n});for(let[t,n]of e.entries())n.rank=t+1}};sh=(0,nh.default)([(0,h.injectable)(),(0,th.default)(0,(0,h.inject)(n.GlobalConfigService)),(0,th.default)(1,(0,h.inject)(tn)),(0,eh.default)(`design:paramtypes`,[Object,typeof(rh=tn!==void 0&&tn)==`function`?rh:Object])],sh);function ch(e){if(typeof e!=`object`||!e)return;let t=e;if(Array.isArray(t.flows))return{flows:t.flows,projectSummary:typeof t.projectSummary==`string`?t.projectSummary:``,projectType:typeof t.projectType==`string`?t.projectType:`unknown`,detectedEntryCount:typeof t.detectedEntryCount==`number`?t.detectedEntryCount:0}}function lh(){return`You are a dependency tracer. Your only job is to find all local source files reachable from a set of entry files by following the project's dependency / reference chains. Be language- and framework-agnostic — adapt to whatever ecosystem this project uses.
|
|
33250
33250
|
|
|
@@ -33290,7 +33290,7 @@ Already known calledModules (do NOT re-include these):
|
|
|
33290
33290
|
${n.length>0?n.map(e=>`- ${e}`).join(`
|
|
33291
33291
|
`):`(none)`}
|
|
33292
33292
|
|
|
33293
|
-
Trace all local imports reachable from the entry files and return any NEW files not already in the known list.`}var dh=t.__toESM(n.require_decorateMetadata()),fh=t.__toESM(nn()),ph=t.__toESM(n.require_decorate()),mh;function hh(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 gh=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],s=0;for(let e=0;e<a.length;e+=o.REGRESSION_TRACER_CONCURRENCY){let c=a.slice(e,e+o.REGRESSION_TRACER_CONCURRENCY);await Promise.all(c.map(async e=>{let{newModules:a,costUsd:o}=await this.traceFlow(e,t,r,i);s+=o,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 o.REGRESSION_LOG_COST&&n.logger.info.defaultLog(`[regression-tracer] Done. Total cost: $${s.toFixed(4)}`),{result:{...e,flows:a},costUsd:s}}async traceFlow(e,t,r,a){if(e.trace.entryFiles.length===0)return{newModules:[],costUsd:0};let{query:s,isResultMessage:c,isErrorResult:l}=await Promise.resolve().then(()=>lz()),u=s({prompt:uh(t,e.trace.entryFiles,e.trace.calledModules),options:{model:o.REGRESSION_TRACER_MODEL,systemPrompt:lh(),allowedTools:[`Read`,`Glob`],permissionMode:o.REGRESSION_PERMISSION_MODE,allowDangerouslySkipPermissions:!0,maxBudgetUsd:o.REGRESSION_TRACER_MAX_BUDGET_USD,maxTurns:o.REGRESSION_TRACER_MAX_TURNS,cwd:t,sessionId:(0,v.randomUUID)(),env:{...process.env,...i.buildAnthropicSdkEnv({proxyUrl:a,jwtToken:r??``,requestId:n.logger.getRequestId()})},outputFormat:{type:`json_schema`,schema:i.DEPENDENCY_TRACER_OUTPUT_SCHEMA}}}),d=0;for await(let t of u){if(!c(t))continue;if(l(t))return n.logger.info.defaultLog(`[regression-tracer] ${e.name}: agent error — keeping original calledModules`),{newModules:[],costUsd:0};d=t.total_cost_usd;let r=hh(t.structured_output),i=new Set(e.trace.calledModules);return{newModules:(r?.calledModules??[]).filter(e=>typeof e==`string`&&!i.has(e)),costUsd:d}}return{newModules:[],costUsd:0}}};gh=(0,ph.default)([(0,h.injectable)(),(0,fh.default)(0,(0,h.inject)(n.GlobalConfigService)),(0,fh.default)(1,(0,h.inject)(tn)),(0,dh.default)(`design:paramtypes`,[Object,typeof(mh=tn!==void 0&&tn)==`function`?mh:Object])],gh);let _h=u.z.object({name:u.z.string().optional(),sourcePath:u.z.string(),rootPath:u.z.string().optional()}).passthrough(),vh=_h.extend({dependencies:u.z.array(_h).optional().default([])}),yh=u.z.object({jobId:u.z.string().optional(),command:u.z.string(),anchorBranch:u.z.string(),anchorSha:u.z.string(),compareBranch:u.z.string().optional().default(``),compareSha:u.z.string().optional().default(``),catalogId:u.z.string().optional().default(``),projectId:u.z.string(),projectRootPath:u.z.string().optional().default(``),label:u.z.string().optional().default(``),primary:vh.optional(),projectRootPaths:vh.optional(),agentLog:u.z.boolean().optional().default(!1),catalogIncrementalEmit:u.z.boolean().optional().default(!1),analysisMode:u.z.enum([`perflow`,`grouping`,`divergence`,`regression-first`,`regression-first-2`,`regression-first-3`,`regression-first-2-adj`,`regression-first-single`,`regression-first-mono`,`regression-first-experiment`,`hunterImpact`]).optional().catch(void 0),impactMappingMaxTurns:u.z.number().int().positive().optional(),fileMappingMode:u.z.enum([`shallow`,`agentic`,`agentic-ast`]).optional().catch(void 0),baselineFromAnalysisId:u.z.string().optional().default(``),crossComponent:u.z.object({changedSide:u.z.enum([`consumer`,`provider`]).optional().default(`provider`),providerRunId:u.z.string().optional(),providerProjectId:u.z.string(),providerSha:u.z.string().optional(),providerRef:u.z.string().optional(),providerRepo:u.z.object({owner:u.z.string(),repo:u.z.string(),rootPath:u.z.string().optional().default(``)}).optional(),consumerRunId:u.z.string().optional(),consumerIsReleasing:u.z.boolean().optional().default(!1)}).optional()}).transform(e=>({...e,primary:e.primary??e.projectRootPaths}));async function bh(e,t,r,i=`regression`){let a=t.getJobId();if(!(0,m.isDefined)(a)||a.length===0)return null;try{n.logger.info.defaultLog(`[${i}] Fetching job input for jobId: ${a}`);let t=await e.get(`/api/v1/regression/jobs/${a}/input`);return r.parse(t)}catch(e){return n.logger.info.defaultLog(`[${i}] Failed to fetch job input for jobId ${a}: ${String(e)}`),null}}async function xh(e,t){let r=await bh(e,t,yh,`regression`);return r!==null&&n.logger.info.defaultLog(`[regression] Job input loaded: command=${r.command}`),r}var Sh=t.__toESM(n.require_decorateMetadata()),Ch=t.__toESM(nn()),wh=t.__toESM(n.require_decorate()),Th,Eh,Dh;let Oh=class{constructor(e,t,n,r){this.runner=e,this.tracer=t,this.apiService=n,this.globalConfigService=r}async run(){let e=await xh(this.apiService,this.globalConfigService);if(e===null){let e=Error(`[regression-catalog] jobInput is required — no global config fallback is allowed`);throw n.logger.error(e.message,e),e}let t=Rm(e);if((e.primary?.sourcePath??e.projectRootPath??``).trim().length===0){let e=Error(`[regression-catalog] no source path — provide primary.sourcePath or projectRootPath in the job input`);throw n.logger.error(e.message,e),e}let r=kh(e,`anchorBranch`),i=t.dependencyRoots.filter(e=>(0,y.existsSync)(e.sourcePath)),a=t.dependencyRoots.length-i.length;a>0&&n.logger.info.defaultLog(`[regression-catalog] Skipped ${a} dependency root(s) missing on disk.`);let o=t;return i.length!==t.dependencyRoots.length&&e.primary&&(o=Rm({...e,primary:{...e.primary,dependencies:i.map(e=>({sourcePath:e.sourcePath,name:e.name}))}})),Ym(``,this.runner,this.tracer,o.cwd,r,this.apiService,this.globalConfigService,e,o)}};Oh=(0,wh.default)([(0,h.injectable)(),(0,Ch.default)(0,(0,h.inject)(sh)),(0,Ch.default)(1,(0,h.inject)(gh)),(0,Ch.default)(2,(0,h.inject)(ln)),(0,Ch.default)(3,(0,h.inject)(n.GlobalConfigService)),(0,Sh.default)(`design:paramtypes`,[typeof(Th=sh!==void 0&&sh)==`function`?Th:Object,typeof(Eh=gh!==void 0&&gh)==`function`?Eh:Object,typeof(Dh=ln!==void 0&&ln)==`function`?Dh:Object,Object])],Oh);function kh(e,t){let r=e[t]?.trim();if(!(0,m.isDefined)(r)||r.length===0){let e=Error(`[regression-catalog] ${t} is missing from job input`);throw n.logger.error(e.message,e),e}return r}let Ah=function(e){return e.Continue=`continue`,e.Halt=`halt`,e}({}),jh={costUsd:0};var Mh=class{constructor(e){this.steps=e}describe(){return this.steps.map(e=>e.name).join(` -> `)}async run(e){n.logger.info.defaultLog(`[regression-e2e-catalog] Pipeline: ${this.describe()}`);let t=!1;for(let[r,i]of this.steps.entries()){let a=`${r+1}/${this.steps.length}`;if(t&&i.isTerminal!==!0){n.logger.info.defaultLog(`[regression-e2e-catalog] Step ${a} "${i.name}" — SKIPPED (pipeline halted)`);continue}n.logger.info.defaultLog(`[regression-e2e-catalog] Step ${a} "${i.name}" — START`);let s=Date.now(),c=await i.execute(e),l=(Date.now()-s)/1e3;e.totalCostUsd=(e.totalCostUsd??0)+c.costUsd,e.stepMetrics.push({stepName:i.name,costUsd:c.costUsd,durationSeconds:l,turns:c.turns??0,...c.maxTurnsHit===!0&&{maxTurnsHit:!0},...c.tokens!==void 0&&{tokens:c.tokens}});let u=c.status===Ah.Halt?` — HALT`:``,d=o.shouldLogDiagnostics?`${c.turns??0} turns / ${l.toFixed(2)}s`:`${l.toFixed(2)}s`;n.logger.info.defaultLog(`[regression-e2e-catalog] Step ${a} "${i.name}" — END (${d})${u}`),c.status===Ah.Halt&&(t=!0)}return e}};function Nh(e,t,n){if(e===void 0)throw Error(`[e2e-catalog-pipeline] ctx.${t} is unset — ${n} must run before this step`);return e}function Ph(e){return Nh(e.perRepoCatalogs,`perRepoCatalogs`,`LoadProjectsStep`)}function Fh(e){return Nh(e.connectionMap,`connectionMap`,`DiscoverConnectionsStep`)}function Ih(e){return Nh(e.traceData,`traceData`,`BuildTraceDataStep`)}var Lh=class{name=`buildTraceData`;execute(e){let t=Fh(e),r=Ph(e),i=Zh(t);return n.logger.info.defaultLog(`[regression-e2e-catalog] Loaded ${r.length} project flow-lib(s); derived ${i.traces.length} connection(s) → trace(s)`),$h(i,r),e.traceData=i,Promise.resolve(jh)}},Rh=class{name=`capPrimary`;execute(e){let t=Ph(e)[0];if((0,m.isDefined)(t)&&t.flows.length>o.REGRESSION_E2E_CATALOG_TARGET_COUNT){let e=[...t.flows].sort((e,t)=>(typeof e.rank==`number`?e.rank:2**53-1)-(typeof t.rank==`number`?t.rank:2**53-1));n.logger.info.defaultLog(`[regression-e2e-catalog] Primary project "${t.repoSlug}": capping ${t.flows.length} → top ${o.REGRESSION_E2E_CATALOG_TARGET_COUNT} flows`),t.flows=e.slice(0,o.REGRESSION_E2E_CATALOG_TARGET_COUNT)}return Promise.resolve(jh)}},zh=class{name=`discoverConnections`;async execute(e){let t=Ph(e),{map:n,costUsd:r,turns:i,tokens:a}=await e.connectionRunner.run({perRepoCatalogs:t,primaryProjectId:e.projectIds[0]??``});return e.connectionMap=n,{costUsd:r??0,turns:i,tokens:a}}};let Bh=e=>e.replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`);async function Vh(e,t){if(!(0,m.isDefined)(t)||t.length===0)return[];try{return(await e.get(`/api/v1/regression/e2e-catalogs/for-agent`,{params:{releaseCandidateId:t,includeInactive:`true`}}))?.flows??[]}catch(e){return n.logger.info.defaultLog(`[regression-e2e-catalog] Could not fetch E2E flow library for RC ${t} (proceeding with no prior library): ${String(e)}`),[]}}function Hh(e){let t=e.userOverride===void 0?[]:Object.keys(e.userOverride),n=t.length>0?t.map(e=>Bh(e)).join(`, `):`(none)`,r=e.userOverride?.name??e.name,i=e.userOverride?.description??e.description,a=e.userOverride?.importance??e.importance,o=e.userOverride?.importanceReason??e.importanceReason,s=e.userOverride?.rank??e.rank,c=(0,m.isDefined)(i)?` <description>${Bh(i)}</description>`:``,l=(0,m.isDefined)(o)?` <importanceReason>${Bh(o)}</importanceReason>`:``;return[` <flow>`,` <flowId>${Bh(e.flowId)}</flowId>`,` <name>${Bh(r)}</name>`,c,` <rank>${s}</rank>`,` <importance>${Bh(a)}</importance>`,l,` <origin>${e.origin}</origin>`,` <active>${e.active}</active>`,` <userOwnedFields>${n}</userOwnedFields>`,` </flow>`].filter(Boolean).join(`
|
|
33293
|
+
Trace all local imports reachable from the entry files and return any NEW files not already in the known list.`}var dh=t.__toESM(n.require_decorateMetadata()),fh=t.__toESM(nn()),ph=t.__toESM(n.require_decorate()),mh;function hh(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 gh=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],s=0;for(let e=0;e<a.length;e+=o.REGRESSION_TRACER_CONCURRENCY){let c=a.slice(e,e+o.REGRESSION_TRACER_CONCURRENCY);await Promise.all(c.map(async e=>{let{newModules:a,costUsd:o}=await this.traceFlow(e,t,r,i);s+=o,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 o.REGRESSION_LOG_COST&&n.logger.info.defaultLog(`[regression-tracer] Done. Total cost: $${s.toFixed(4)}`),{result:{...e,flows:a},costUsd:s}}async traceFlow(e,t,r,a){if(e.trace.entryFiles.length===0)return{newModules:[],costUsd:0};let{query:s,isResultMessage:c,isErrorResult:l}=await Promise.resolve().then(()=>lz()),u=s({prompt:uh(t,e.trace.entryFiles,e.trace.calledModules),options:{model:o.REGRESSION_TRACER_MODEL,...o.REGRESSION_HAIKU_REASONING,systemPrompt:lh(),allowedTools:[`Read`,`Glob`],permissionMode:o.REGRESSION_PERMISSION_MODE,allowDangerouslySkipPermissions:!0,maxBudgetUsd:o.REGRESSION_TRACER_MAX_BUDGET_USD,maxTurns:o.REGRESSION_TRACER_MAX_TURNS,cwd:t,sessionId:(0,v.randomUUID)(),env:{...process.env,...i.buildAnthropicSdkEnv({proxyUrl:a,jwtToken:r??``,requestId:n.logger.getRequestId()})},outputFormat:{type:`json_schema`,schema:i.DEPENDENCY_TRACER_OUTPUT_SCHEMA}}}),d=0;for await(let t of u){if(!c(t))continue;if(l(t))return n.logger.info.defaultLog(`[regression-tracer] ${e.name}: agent error — keeping original calledModules`),{newModules:[],costUsd:0};d=t.total_cost_usd;let r=hh(t.structured_output),i=new Set(e.trace.calledModules);return{newModules:(r?.calledModules??[]).filter(e=>typeof e==`string`&&!i.has(e)),costUsd:d}}return{newModules:[],costUsd:0}}};gh=(0,ph.default)([(0,h.injectable)(),(0,fh.default)(0,(0,h.inject)(n.GlobalConfigService)),(0,fh.default)(1,(0,h.inject)(tn)),(0,dh.default)(`design:paramtypes`,[Object,typeof(mh=tn!==void 0&&tn)==`function`?mh:Object])],gh);let _h=u.z.object({name:u.z.string().optional(),sourcePath:u.z.string(),rootPath:u.z.string().optional()}).passthrough(),vh=_h.extend({dependencies:u.z.array(_h).optional().default([])}),yh=u.z.object({jobId:u.z.string().optional(),command:u.z.string(),anchorBranch:u.z.string(),anchorSha:u.z.string(),compareBranch:u.z.string().optional().default(``),compareSha:u.z.string().optional().default(``),catalogId:u.z.string().optional().default(``),projectId:u.z.string(),projectRootPath:u.z.string().optional().default(``),label:u.z.string().optional().default(``),primary:vh.optional(),projectRootPaths:vh.optional(),agentLog:u.z.boolean().optional().default(!1),catalogIncrementalEmit:u.z.boolean().optional().default(!1),analysisMode:u.z.enum([`perflow`,`grouping`,`divergence`,`regression-first`,`regression-first-2`,`regression-first-3`,`regression-first-2-adj`,`regression-first-single`,`regression-first-mono`,`regression-first-experiment`,`hunterImpact`]).optional().catch(void 0),impactMappingMaxTurns:u.z.number().int().positive().optional(),fileMappingMode:u.z.enum([`shallow`,`agentic`,`agentic-ast`]).optional().catch(void 0),baselineFromAnalysisId:u.z.string().optional().default(``),crossComponent:u.z.object({changedSide:u.z.enum([`consumer`,`provider`]).optional().default(`provider`),providerRunId:u.z.string().optional(),providerProjectId:u.z.string(),providerSha:u.z.string().optional(),providerRef:u.z.string().optional(),providerRepo:u.z.object({owner:u.z.string(),repo:u.z.string(),rootPath:u.z.string().optional().default(``)}).optional(),consumerRunId:u.z.string().optional(),consumerIsReleasing:u.z.boolean().optional().default(!1)}).optional()}).transform(e=>({...e,primary:e.primary??e.projectRootPaths}));async function bh(e,t,r,i=`regression`){let a=t.getJobId();if(!(0,m.isDefined)(a)||a.length===0)return null;try{n.logger.info.defaultLog(`[${i}] Fetching job input for jobId: ${a}`);let t=await e.get(`/api/v1/regression/jobs/${a}/input`);return r.parse(t)}catch(e){return n.logger.info.defaultLog(`[${i}] Failed to fetch job input for jobId ${a}: ${String(e)}`),null}}async function xh(e,t){let r=await bh(e,t,yh,`regression`);return r!==null&&n.logger.info.defaultLog(`[regression] Job input loaded: command=${r.command}`),r}var Sh=t.__toESM(n.require_decorateMetadata()),Ch=t.__toESM(nn()),wh=t.__toESM(n.require_decorate()),Th,Eh,Dh;let Oh=class{constructor(e,t,n,r){this.runner=e,this.tracer=t,this.apiService=n,this.globalConfigService=r}async run(){let e=await xh(this.apiService,this.globalConfigService);if(e===null){let e=Error(`[regression-catalog] jobInput is required — no global config fallback is allowed`);throw n.logger.error(e.message,e),e}let t=Rm(e);if((e.primary?.sourcePath??e.projectRootPath??``).trim().length===0){let e=Error(`[regression-catalog] no source path — provide primary.sourcePath or projectRootPath in the job input`);throw n.logger.error(e.message,e),e}let r=kh(e,`anchorBranch`),i=t.dependencyRoots.filter(e=>(0,y.existsSync)(e.sourcePath)),a=t.dependencyRoots.length-i.length;a>0&&n.logger.info.defaultLog(`[regression-catalog] Skipped ${a} dependency root(s) missing on disk.`);let o=t;return i.length!==t.dependencyRoots.length&&e.primary&&(o=Rm({...e,primary:{...e.primary,dependencies:i.map(e=>({sourcePath:e.sourcePath,name:e.name}))}})),Ym(``,this.runner,this.tracer,o.cwd,r,this.apiService,this.globalConfigService,e,o)}};Oh=(0,wh.default)([(0,h.injectable)(),(0,Ch.default)(0,(0,h.inject)(sh)),(0,Ch.default)(1,(0,h.inject)(gh)),(0,Ch.default)(2,(0,h.inject)(ln)),(0,Ch.default)(3,(0,h.inject)(n.GlobalConfigService)),(0,Sh.default)(`design:paramtypes`,[typeof(Th=sh!==void 0&&sh)==`function`?Th:Object,typeof(Eh=gh!==void 0&&gh)==`function`?Eh:Object,typeof(Dh=ln!==void 0&&ln)==`function`?Dh:Object,Object])],Oh);function kh(e,t){let r=e[t]?.trim();if(!(0,m.isDefined)(r)||r.length===0){let e=Error(`[regression-catalog] ${t} is missing from job input`);throw n.logger.error(e.message,e),e}return r}let Ah=function(e){return e.Continue=`continue`,e.Halt=`halt`,e}({}),jh={costUsd:0};var Mh=class{constructor(e){this.steps=e}describe(){return this.steps.map(e=>e.name).join(` -> `)}async run(e){n.logger.info.defaultLog(`[regression-e2e-catalog] Pipeline: ${this.describe()}`);let t=!1;for(let[r,i]of this.steps.entries()){let a=`${r+1}/${this.steps.length}`;if(t&&i.isTerminal!==!0){n.logger.info.defaultLog(`[regression-e2e-catalog] Step ${a} "${i.name}" — SKIPPED (pipeline halted)`);continue}n.logger.info.defaultLog(`[regression-e2e-catalog] Step ${a} "${i.name}" — START`);let s=Date.now(),c=await i.execute(e),l=(Date.now()-s)/1e3;e.totalCostUsd=(e.totalCostUsd??0)+c.costUsd,e.stepMetrics.push({stepName:i.name,costUsd:c.costUsd,durationSeconds:l,turns:c.turns??0,...c.maxTurnsHit===!0&&{maxTurnsHit:!0},...c.tokens!==void 0&&{tokens:c.tokens}});let u=c.status===Ah.Halt?` — HALT`:``,d=o.shouldLogDiagnostics?`${c.turns??0} turns / ${l.toFixed(2)}s`:`${l.toFixed(2)}s`;n.logger.info.defaultLog(`[regression-e2e-catalog] Step ${a} "${i.name}" — END (${d})${u}`),c.status===Ah.Halt&&(t=!0)}return e}};function Nh(e,t,n){if(e===void 0)throw Error(`[e2e-catalog-pipeline] ctx.${t} is unset — ${n} must run before this step`);return e}function Ph(e){return Nh(e.perRepoCatalogs,`perRepoCatalogs`,`LoadProjectsStep`)}function Fh(e){return Nh(e.connectionMap,`connectionMap`,`DiscoverConnectionsStep`)}function Ih(e){return Nh(e.traceData,`traceData`,`BuildTraceDataStep`)}var Lh=class{name=`buildTraceData`;execute(e){let t=Fh(e),r=Ph(e),i=Zh(t);return n.logger.info.defaultLog(`[regression-e2e-catalog] Loaded ${r.length} project flow-lib(s); derived ${i.traces.length} connection(s) → trace(s)`),$h(i,r),e.traceData=i,Promise.resolve(jh)}},Rh=class{name=`capPrimary`;execute(e){let t=Ph(e)[0];if((0,m.isDefined)(t)&&t.flows.length>o.REGRESSION_E2E_CATALOG_TARGET_COUNT){let e=[...t.flows].sort((e,t)=>(typeof e.rank==`number`?e.rank:2**53-1)-(typeof t.rank==`number`?t.rank:2**53-1));n.logger.info.defaultLog(`[regression-e2e-catalog] Primary project "${t.repoSlug}": capping ${t.flows.length} → top ${o.REGRESSION_E2E_CATALOG_TARGET_COUNT} flows`),t.flows=e.slice(0,o.REGRESSION_E2E_CATALOG_TARGET_COUNT)}return Promise.resolve(jh)}},zh=class{name=`discoverConnections`;async execute(e){let t=Ph(e),{map:n,costUsd:r,turns:i,tokens:a}=await e.connectionRunner.run({perRepoCatalogs:t,primaryProjectId:e.projectIds[0]??``});return e.connectionMap=n,{costUsd:r??0,turns:i,tokens:a}}};let Bh=e=>e.replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`);async function Vh(e,t){if(!(0,m.isDefined)(t)||t.length===0)return[];try{return(await e.get(`/api/v1/regression/e2e-catalogs/for-agent`,{params:{releaseCandidateId:t,includeInactive:`true`}}))?.flows??[]}catch(e){return n.logger.info.defaultLog(`[regression-e2e-catalog] Could not fetch E2E flow library for RC ${t} (proceeding with no prior library): ${String(e)}`),[]}}function Hh(e){let t=e.userOverride===void 0?[]:Object.keys(e.userOverride),n=t.length>0?t.map(e=>Bh(e)).join(`, `):`(none)`,r=e.userOverride?.name??e.name,i=e.userOverride?.description??e.description,a=e.userOverride?.importance??e.importance,o=e.userOverride?.importanceReason??e.importanceReason,s=e.userOverride?.rank??e.rank,c=(0,m.isDefined)(i)?` <description>${Bh(i)}</description>`:``,l=(0,m.isDefined)(o)?` <importanceReason>${Bh(o)}</importanceReason>`:``;return[` <flow>`,` <flowId>${Bh(e.flowId)}</flowId>`,` <name>${Bh(r)}</name>`,c,` <rank>${s}</rank>`,` <importance>${Bh(a)}</importance>`,l,` <origin>${e.origin}</origin>`,` <active>${e.active}</active>`,` <userOwnedFields>${n}</userOwnedFields>`,` </flow>`].filter(Boolean).join(`
|
|
33294
33294
|
`)}function Uh(e){return e.length===0?``:[`<flow-library>`,` <!--`,` Persistent E2E flow library for this release candidate. Values shown are`,` already merged (user overrides shadow LLM proposals).`,``,` Rules:`,` - REUSE the listed flowId when you re-identify the same end-to-end flow`,` (do not invent a new id for an existing flow).`,` - userOwnedFields lists fields the user has locked. Do NOT propose values`,` that conflict — the backend ignores conflicting proposals for those.`,` - RE-EMIT every flow that is still a real journey (reuse its flowId). The`,` library is a persistent catalog, not a per-run top-N. Do NOT drop a flow`,` for being marginal — only drop it if its journey is genuinely gone.`,` - <active>false</active> = retired in a prior run. If its journey is still`,` real, RE-EMIT it (reuse its flowId) to REVIVE it. Inactive is not a`,` reason to skip it.`,` - A flow you don't re-emit gets DEACTIVATED — correct only when the journey`,` is truly gone, never as a side effect of trimming.`,` -->`,e.map(Hh).join(`
|
|
33295
33295
|
`),`</flow-library>`].join(`
|
|
33296
33296
|
`)}var Wh=class{name=`loadProjects`;async execute(e){n.logger.info.defaultLog(`[regression-e2e-catalog] Project IDs (primary first): ${e.projectIds.join(`, `)}`);let{perRepoCatalogs:t,sourceShas:r}=await tg(e.apiService,e.projectIds);e.perRepoCatalogs=t,e.sourceShas=r;let i=await Vh(e.apiService,e.releaseCandidateId);return e.libraryFlows=i,n.logger.info.defaultLog(`[regression-e2e-catalog] Prior E2E library: ${i.length} flow(s)${e.releaseCandidateId===void 0?` (no releaseCandidateId)`:``}`),jh}},Gh=class{name=`post`;isTerminal=!0;async execute(e){let t=e.result,r=e.perRepoCatalogs;if(t===void 0||r===void 0)return n.logger.info.defaultLog(`[regression-e2e-catalog] PostStep — no result/projects on context (pipeline halted before synthesis); skipping backend sync.`),jh;let i=e.releaseCandidateId;return i===void 0||i.length===0?(n.logger.info.defaultLog(`[regression-e2e-catalog] No releaseCandidateId — skipping backend sync (the RC is the catalog's identity). Local report (when enabled) is authoritative.`),jh):(e.e2eCatalogId=await ag({perRepoCatalogIds:r.map(e=>e.catalogId).filter(e=>e.length>0),result:t,costUsd:e.totalCostUsd,durationSeconds:e.durationSeconds,stepMetrics:e.stepMetrics,releaseCandidateId:i,reconciliation:e.reconciliation,connectionMap:e.connectionMap,sourceShas:e.sourceShas},e.apiService),jh)}},Kh=class{name=`report`;isTerminal=!0;execute(e){if(!o.REGRESSION_E2E_CATALOG_SAVE_REPORT_FILES)return n.logger.info.defaultLog(`[regression-e2e-catalog] REGRESSION_E2E_CATALOG_SAVE_REPORT_FILES=false — skipping report file. Set to true in regression-agent.const.ts to inspect output.`),Promise.resolve(jh);let t=e.result,r=e.perRepoCatalogs,i=e.traceData;return t===void 0||r===void 0||i===void 0?(n.logger.info.defaultLog(`[regression-e2e-catalog] ReportStep — incomplete context (pipeline halted before synthesis); skipping report file.`),Promise.resolve(jh)):(ig(e.reportsDir,{e2eName:e.e2eName,e2eDescription:e.e2eDescription,catalogIds:r.map(e=>e.catalogId),perRepoCatalogs:r,traceCount:i.traces.length,result:t,costUsd:e.totalCostUsd,durationSeconds:e.durationSeconds,stepMetrics:e.stepMetrics,reconciliation:e.reconciliation,generatedPrompt:e.generatedPrompt??``}),Promise.resolve(jh))}};function qh(e,t){let n=new Set(e),r=new Set(t);return{kept:t.filter(e=>n.has(e)),added:t.filter(e=>!n.has(e)),gone:e.filter(e=>!r.has(e))}}var Jh=class{name=`runCatalogAgent`;async execute(e){let t=Ph(e),r=Ih(e),{result:i,costUsd:a,durationSeconds:o,turns:s,tokens:c,generatedPrompt:l}=await e.runner.run({e2eName:e.e2eName,e2eDescription:e.e2eDescription,perRepoCatalogs:t,traceData:r,libraryFlows:e.libraryFlows});e.result=i,e.generatedPrompt=l,e.durationSeconds=o;let u=qh((e.libraryFlows??[]).map(e=>e.flowId),i.flows.map(e=>e.flowId));return e.reconciliation=u,n.logger.info.defaultLog(`[regression-e2e-catalog] Reconciliation vs prior library: ${u.kept.length} kept, ${u.added.length} added, ${u.gone.length} gone`),{costUsd:a??0,turns:s,tokens:c}}},Yh=class{name=`writeConnectionMap`;execute(e){let t=Fh(e);return Qh(e.reportsDir,e.e2eName,t),Promise.resolve(jh)}};let Xh={create(){return new Mh([new Wh,new Rh,new zh,new Yh,new Lh,new Jh,new Kh,new Gh])}};function Zh(e){let t=new Map;for(let n of e.connections){let e=t.get(n.fromFlowId);e===void 0?t.set(n.fromFlowId,[n]):e.push(n)}let n=[];for(let[e,r]of t){let[t]=r,i={repo:t.fromRepo,endpoint:`${t.fromFlowName} (${e})`},a=[];for(let e of r){if(e.calls.length===0){a.push({from:i,to:{repo:e.toRepo,endpoint:`${e.toFlowName} (${e.toFlowId})`},kind:`http`});continue}for(let t of e.calls)a.push({from:i,to:{repo:e.toRepo,endpoint:`${t.method} ${t.route}`},kind:`http`})}n.push({id:e,hops:a})}return{traces:n}}function Qh(e,t,r){if(!o.REGRESSION_E2E_CATALOG_SAVE_REPORT_FILES)return;(0,y.mkdirSync)(e,{recursive:!0});let i=new Date().toISOString().replaceAll(/[:.]/g,`-`),a=t.toLowerCase().replaceAll(/[^a-z0-9-]+/g,`-`).slice(0,60),s=I.default.join(e,`${i}-${a}.connections.json`);(0,y.writeFileSync)(s,JSON.stringify(r,null,2),`utf8`),n.logger.info.defaultLog(`[regression-e2e-catalog] Connection map (${r.connections.length} link(s)) saved to: ${s}`)}function $h(e,t){let r=new Set(t.map(e=>e.repoSlug)),i=new Set;for(let t of e.traces)for(let e of t.hops)r.has(e.from.repo)||i.add(e.from.repo),r.has(e.to.repo)||i.add(e.to.repo);i.size>0&&n.logger.info.defaultLog(`[regression-e2e-catalog] WARNING: trace data references ${i.size} repo(s) not in loaded catalogs: ${[...i].join(`, `)} — agent will still proceed`)}async function eg(e,t,r){if(r===void 0)return`<missing>`;try{return(await e.get(`/api/v1/regression/catalogs/${encodeURIComponent(r)}`))?.repository?.repo??`<missing>`}catch(e){return n.logger.info.defaultLog(`[regression-e2e-catalog] WARNING: could not resolve repo slug for project ${t} (catalog ${r}): ${String(e)}`),`<missing>`}}async function tg(e,t){if(t.length===0)throw Error(`loadPerRepoCatalogsByProject: no projectIds provided`);let r=[],i=[];for(let[a,o]of t.entries()){let t=a===0?`primary`:`dependency`;n.logger.info.defaultLog(`[regression-e2e-catalog] Loading flow library for ${t} project: ${o}`);let s=`/api/v1/regression/flow-library/for-agent?projectId=${encodeURIComponent(o)}`,c;try{c=await e.get(s)}catch(e){throw Error(`Failed to fetch flow library for project ${o}: ${String(e)}`)}if(!(0,m.isDefined)(c)||!(0,m.isDefined)(c.project))throw Error(`Flow library not found for project: ${o}`);let l=c.project.latestCatalogId??void 0,u=await eg(e,o,l),d=c.project.anchorSha??void 0;d===void 0?n.logger.info.defaultLog(`[regression-e2e-catalog] WARNING: project ${o} has no anchorSha (no catalog yet?) — omitted from sourceShas`):i.push({projectId:o,sha:d});let f=(c.flows??[]).filter(e=>e.active!==!1);r.push({catalogId:l??``,repoSlug:u,anchorBranch:c.project.anchorBranch??`<missing>`,projectType:c.project.projectType??`<missing>`,projectSummary:c.project.projectSummary??``,flows:f})}return n.logger.info.defaultLog(`[regression-e2e-catalog] Loaded ${r.length} project flow-lib(s); primary repo: ${r[0]?.repoSlug}`),r.filter(e=>e.catalogId.length>0).length===0&&n.logger.info.defaultLog(`[regression-e2e-catalog] WARNING: none of the ${t.length} project(s) has a catalog yet — the E2E build will NOT be persisted to the backend (no real perRepoCatalogIds). Run a per-repo catalog for these projects first.`),{perRepoCatalogs:r,sourceShas:i}}function ng(e,t){let{name:n,importance:r,description:i,importanceReason:a,scoring:o,productFlow:s,composedOf:c}=e,l=o===void 0?[]:[``,`**Scoring:**`,`- Risk Score: ${o.riskScore} — ${o.riskReason}`,`- Blast Radius: ${o.blastRadius} — ${o.blastReason}`,`- Final Score: ${o.finalScore}`],u=s===void 0?[]:[``,`**Product Flow:**`,`- **Trigger:** ${s.trigger}`,...s.steps.map((e,t)=>`- ${t+1}. **${e.actor}** → ${e.action} → _${e.outcome}_`),`- **Outcome:** ${s.outcome}`],d=c.length===0?[``,`**Composed of:** _(none declared — composition data missing)_`]:[``,`**Composed of per-repo flows (in order):**`,...c.map((e,t)=>`- ${t+1}. \`${e.repoSlug}\` — \`${e.perRepoFlowId}\` _(${e.perRepoFlowName})_ — catalog \`${e.catalogId}\``)];return[`### ${t+1}. ${n} (${r})`,`**Why important:** ${a}`,`**Description:** ${i}`,...u,...d,...l].join(`
|
|
@@ -33542,7 +33542,7 @@ Notes:
|
|
|
33542
33542
|
`),r=e.perRepoCatalogs.filter(e=>e.repoSlug===`<missing>`||e.anchorBranch===`<missing>`||e.projectType===`<missing>`);return[t,r.length>0?[`<warnings>`,...r.map(e=>` <warning>Per-repo catalog ${hg(e.catalogId)} has incomplete metadata (repoSlug="${hg(e.repoSlug)}", anchorBranch="${hg(e.anchorBranch)}", projectType="${hg(e.projectType)}"). Treat "<missing>" as an absent field, not a real value. Hop matching against this catalog may be less reliable; proceed but flag uncertainty in importanceReason if it affects an E2E flow.</warning>`),`</warnings>`].join(`
|
|
33543
33543
|
`):``,n,yg(e.traceData)].filter(e=>e.length>0).join(`
|
|
33544
33544
|
|
|
33545
|
-
`)}var xg=t.__toESM(n.require_decorateMetadata()),Sg=t.__toESM(nn()),Cg=t.__toESM(n.require_decorate()),wg;function Tg(e,t,n){let r=e.toLowerCase().trim().replaceAll(/\s+/g,`-`).replaceAll(/[^a-z0-9-]/g,``).replaceAll(/-+/g,`-`).replaceAll(/(?:^-)|(?:-$)/g,``);if(r.length>0)return r;let[i]=t,[a]=n;return i??a??`unnamed-flow`}function Eg(e){if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`){let t=Number(e);return Number.isFinite(t)?t:void 0}}function Dg(e){let t=0;return(typeof e.name!=`string`||e.name.length===0)&&(e.name=`(unnamed)`,t++),typeof e.description!=`string`&&(e.description=``,t++),typeof e.importanceReason!=`string`&&(e.importanceReason=``,t++),Array.isArray(e.composedOf)||(e.composedOf=[],t++),t}function Og(e){if(e.scoring===void 0)return 0;let t=e.scoring,n=0;for(let r of[`riskScore`,`blastRadius`,`finalScore`]){let i=Eg(t[r]);i!==void 0&&typeof t[r]!=`number`&&(e.scoring[r]=i,n++)}return n}function kg(e){let t=typeof e.duration_ms==`number`?Math.round(e.duration_ms/1e3):void 0,n=typeof e.num_turns==`number`?e.num_turns:void 0,r=e.structured_output;return{costUsd:e.total_cost_usd,durationSeconds:t,turnCount:n,tokens:i.extractCacheTokens(e),structuredOutput:jg(r)}}let Ag=class{constructor(e,t){this.globalConfigService=e,this.authStorage=t}agenticToolLog=[];async run(e){this.agenticToolLog=[];let t=await this.authStorage.getJWTToken();n.logger.info.defaultLog(`[regression-e2e-catalog] Starting E2E catalog for "${e.e2eName}" across ${e.perRepoCatalogs.length} repo(s) with ${e.traceData.traces.length} trace(s)`);let{query:r,getMessageContentBlocks:a,isResultMessage:s,isErrorResult:c}=await Promise.resolve().then(()=>lz()),l=gg(),u=bg({e2eName:e.e2eName,e2eDescription:e.e2eDescription,perRepoCatalogs:e.perRepoCatalogs,traceData:e.traceData}),d=e.libraryFlows&&e.libraryFlows.length>0?Uh(e.libraryFlows):``,f=d?`${d}\n\n${u}`:u,p=r({prompt:f,options:{model:o.REGRESSION_E2E_CATALOG_MODEL,systemPrompt:l,allowedTools:[],permissionMode:o.REGRESSION_PERMISSION_MODE,allowDangerouslySkipPermissions:!0,maxBudgetUsd:o.REGRESSION_E2E_CATALOG_MAX_BUDGET_USD,maxTurns:o.REGRESSION_E2E_CATALOG_MAX_TURNS,outputFormat:{type:`json_schema`,schema:i.E2E_CATALOG_OUTPUT_SCHEMA},sessionId:(0,v.randomUUID)(),env:{...process.env,...i.buildAnthropicSdkEnv({proxyUrl:this.globalConfigService.getAnthropicProxyUrl(),jwtToken:t??``,requestId:n.logger.getRequestId()})},stderr:e=>{n.logger.info.defaultLog(`[regression-e2e-catalog] STDERR: ${e}`)}}}),{costUsd:m,durationSeconds:h,turnCount:g,tokens:_,structuredOutput:y}=await this.consumeMessageStream(p,a,s,c);if(o.REGRESSION_LOG_COST&&n.logger.info.defaultLog(`[regression-e2e-catalog] E2E catalog done. ${g} turns. Cost: $${m?.toFixed(4)} Duration: ${h??`—`}s`),y===void 0)throw new cf(`no_structured_output`,[`E2E catalog runner: SDK result message contained no structured_output. Likely a schema rejection or protocol error.`],m??0);let b=e.traceData.traces.map(e=>e.id),x={flows:y.flows,projectSummary:y.projectSummary,projectType:y.projectType,detectedFlowCount:y.detectedFlowCount};return x.flows.length===0&&n.logger.info.defaultLog(`[regression-e2e-catalog] WARNING: agent returned 0 flows — verify trace data + per-repo catalogs contain meaningful inputs`),this.coerceFlowDefaults(x.flows),this.normalizeImportance(x.flows),this.assignFlowIds(x.flows,b),this.assignStepIds(x.flows),this.assignRanks(x.flows),this.validateComposedOf(x.flows,e.perRepoCatalogs),o.REGRESSION_LOG_COST&&n.logger.info.defaultLog(`[regression-e2e-catalog] Done. ${x.flows.length} E2E flow(s). Cost: $${m?.toFixed(4)} Duration: ${h??`—`}s`),{result:x,costUsd:m,durationSeconds:h,turns:g,tokens:_===void 0?void 0:{inputTokens:_.inputTokens,outputTokens:_.outputTokens,cacheReadTokens:_.cacheReadTokens,cacheCreationTokens:_.cacheCreationTokens},generatedPrompt:f}}getAgenticToolLog(){return this.agenticToolLog}async consumeMessageStream(e,t,r,i){let a,s,c=0,l,u;try{for await(let d of e){let e=t(d);if(e!==void 0&&e.length>0&&(c++,this.logAgenticTurn(c,e)),!r(d))continue;if(i(d))throw new cf(d.subtype,d.errors,d.total_cost_usd);let f=kg(d);a=f.costUsd,s=f.durationSeconds,l=f.tokens,u=f.structuredOutput,f.turnCount!==void 0&&(c=f.turnCount),o.REGRESSION_LOG_COST&&n.logger.info.defaultLog(`[regression-e2e-catalog] Result received. Cost: $${a?.toFixed(4)} Duration: ${s??`—`}s`);break}}catch(e){throw e instanceof cf?e:new cf(`stream_error`,[`E2E catalog stream interrupted: ${String(e)}`],a??0)}return{costUsd:a,durationSeconds:s,turnCount:c,tokens:l,structuredOutput:u}}logAgenticTurn(e,t){for(let r of t){let t=r;if(String(t.type??``)===`text`&&typeof t.text==`string`){let r=t.text.slice(0,200).replaceAll(`
|
|
33545
|
+
`)}var xg=t.__toESM(n.require_decorateMetadata()),Sg=t.__toESM(nn()),Cg=t.__toESM(n.require_decorate()),wg;function Tg(e,t,n){let r=e.toLowerCase().trim().replaceAll(/\s+/g,`-`).replaceAll(/[^a-z0-9-]/g,``).replaceAll(/-+/g,`-`).replaceAll(/(?:^-)|(?:-$)/g,``);if(r.length>0)return r;let[i]=t,[a]=n;return i??a??`unnamed-flow`}function Eg(e){if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`){let t=Number(e);return Number.isFinite(t)?t:void 0}}function Dg(e){let t=0;return(typeof e.name!=`string`||e.name.length===0)&&(e.name=`(unnamed)`,t++),typeof e.description!=`string`&&(e.description=``,t++),typeof e.importanceReason!=`string`&&(e.importanceReason=``,t++),Array.isArray(e.composedOf)||(e.composedOf=[],t++),t}function Og(e){if(e.scoring===void 0)return 0;let t=e.scoring,n=0;for(let r of[`riskScore`,`blastRadius`,`finalScore`]){let i=Eg(t[r]);i!==void 0&&typeof t[r]!=`number`&&(e.scoring[r]=i,n++)}return n}function kg(e){let t=typeof e.duration_ms==`number`?Math.round(e.duration_ms/1e3):void 0,n=typeof e.num_turns==`number`?e.num_turns:void 0,r=e.structured_output;return{costUsd:e.total_cost_usd,durationSeconds:t,turnCount:n,tokens:i.extractCacheTokens(e),structuredOutput:jg(r)}}let Ag=class{constructor(e,t){this.globalConfigService=e,this.authStorage=t}agenticToolLog=[];async run(e){this.agenticToolLog=[];let t=await this.authStorage.getJWTToken();n.logger.info.defaultLog(`[regression-e2e-catalog] Starting E2E catalog for "${e.e2eName}" across ${e.perRepoCatalogs.length} repo(s) with ${e.traceData.traces.length} trace(s)`);let{query:r,getMessageContentBlocks:a,isResultMessage:s,isErrorResult:c}=await Promise.resolve().then(()=>lz()),l=gg(),u=bg({e2eName:e.e2eName,e2eDescription:e.e2eDescription,perRepoCatalogs:e.perRepoCatalogs,traceData:e.traceData}),d=e.libraryFlows&&e.libraryFlows.length>0?Uh(e.libraryFlows):``,f=d?`${d}\n\n${u}`:u,p=r({prompt:f,options:{model:o.REGRESSION_E2E_CATALOG_MODEL,...o.REGRESSION_SONNET_ANALYZER_REASONING,systemPrompt:l,allowedTools:[],permissionMode:o.REGRESSION_PERMISSION_MODE,allowDangerouslySkipPermissions:!0,maxBudgetUsd:o.REGRESSION_E2E_CATALOG_MAX_BUDGET_USD,maxTurns:o.REGRESSION_E2E_CATALOG_MAX_TURNS,outputFormat:{type:`json_schema`,schema:i.E2E_CATALOG_OUTPUT_SCHEMA},sessionId:(0,v.randomUUID)(),env:{...process.env,...i.buildAnthropicSdkEnv({proxyUrl:this.globalConfigService.getAnthropicProxyUrl(),jwtToken:t??``,requestId:n.logger.getRequestId()})},stderr:e=>{n.logger.info.defaultLog(`[regression-e2e-catalog] STDERR: ${e}`)}}}),{costUsd:m,durationSeconds:h,turnCount:g,tokens:_,structuredOutput:y}=await this.consumeMessageStream(p,a,s,c);if(o.REGRESSION_LOG_COST&&n.logger.info.defaultLog(`[regression-e2e-catalog] E2E catalog done. ${g} turns. Cost: $${m?.toFixed(4)} Duration: ${h??`—`}s`),y===void 0)throw new cf(`no_structured_output`,[`E2E catalog runner: SDK result message contained no structured_output. Likely a schema rejection or protocol error.`],m??0);let b=e.traceData.traces.map(e=>e.id),x={flows:y.flows,projectSummary:y.projectSummary,projectType:y.projectType,detectedFlowCount:y.detectedFlowCount};return x.flows.length===0&&n.logger.info.defaultLog(`[regression-e2e-catalog] WARNING: agent returned 0 flows — verify trace data + per-repo catalogs contain meaningful inputs`),this.coerceFlowDefaults(x.flows),this.normalizeImportance(x.flows),this.assignFlowIds(x.flows,b),this.assignStepIds(x.flows),this.assignRanks(x.flows),this.validateComposedOf(x.flows,e.perRepoCatalogs),o.REGRESSION_LOG_COST&&n.logger.info.defaultLog(`[regression-e2e-catalog] Done. ${x.flows.length} E2E flow(s). Cost: $${m?.toFixed(4)} Duration: ${h??`—`}s`),{result:x,costUsd:m,durationSeconds:h,turns:g,tokens:_===void 0?void 0:{inputTokens:_.inputTokens,outputTokens:_.outputTokens,cacheReadTokens:_.cacheReadTokens,cacheCreationTokens:_.cacheCreationTokens},generatedPrompt:f}}getAgenticToolLog(){return this.agenticToolLog}async consumeMessageStream(e,t,r,i){let a,s,c=0,l,u;try{for await(let d of e){let e=t(d);if(e!==void 0&&e.length>0&&(c++,this.logAgenticTurn(c,e)),!r(d))continue;if(i(d))throw new cf(d.subtype,d.errors,d.total_cost_usd);let f=kg(d);a=f.costUsd,s=f.durationSeconds,l=f.tokens,u=f.structuredOutput,f.turnCount!==void 0&&(c=f.turnCount),o.REGRESSION_LOG_COST&&n.logger.info.defaultLog(`[regression-e2e-catalog] Result received. Cost: $${a?.toFixed(4)} Duration: ${s??`—`}s`);break}}catch(e){throw e instanceof cf?e:new cf(`stream_error`,[`E2E catalog stream interrupted: ${String(e)}`],a??0)}return{costUsd:a,durationSeconds:s,turnCount:c,tokens:l,structuredOutput:u}}logAgenticTurn(e,t){for(let r of t){let t=r;if(String(t.type??``)===`text`&&typeof t.text==`string`){let r=t.text.slice(0,200).replaceAll(`
|
|
33546
33546
|
`,` `);n.logger.info.defaultLog(`[regression-e2e-catalog] Turn ${e} — text: ${r}`),this.agenticToolLog.push(`[Turn ${e}] TEXT: ${r}${t.text.length>200?`...`:``}`)}}}coerceFlowDefaults(e){let t=0;for(let n of e)t+=Dg(n),t+=Og(n);t>0&&n.logger.info.defaultLog(`[regression-e2e-catalog] WARNING: coerceFlowDefaults filled ${t} missing/invalid field(s) on agent output`)}normalizeImportance(e){let t=new Set([`CRITICAL`,`HIGH`,`MEDIUM`,`LOW`]),r=0;for(let n of e){let e=String(n.importance??``).trim().toUpperCase();t.has(e)?n.importance=e:(n.importance=`MEDIUM`,r++)}r>0&&n.logger.info.defaultLog(`[regression-e2e-catalog] normalizeImportance: coerced ${r} invalid importance value(s) to MEDIUM`)}validateComposedOf(e,t){let r=new Map;for(let e of t)r.set(e.catalogId,new Set(e.flows.map(e=>e.flowId)));let i=0;for(let t of e){let e=t.composedOf;if(e.length===0){n.logger.info.defaultLog(`[regression-e2e-catalog] WARNING: E2E flow "${t.name}" has empty composedOf — agent should declare its per-repo constituents`);continue}for(let a of e){let e=r.get(a.catalogId);if(e===void 0){i++,n.logger.info.defaultLog(`[regression-e2e-catalog] WARNING: E2E flow "${t.name}" references unknown catalogId "${a.catalogId}" (repoSlug="${a.repoSlug}", perRepoFlowId="${a.perRepoFlowId}")`);continue}e.has(a.perRepoFlowId)||(i++,n.logger.info.defaultLog(`[regression-e2e-catalog] WARNING: E2E flow "${t.name}" references unknown perRepoFlowId "${a.perRepoFlowId}" in catalog "${a.catalogId}" (repoSlug="${a.repoSlug}") — possible LLM hallucination`))}}i>0&&n.logger.info.defaultLog(`[regression-e2e-catalog] composedOf validation: ${i} unknown reference(s) across all E2E flows`)}assignFlowIds(e,t){let n=new Set;for(let[r,i]of e.entries()){let e=i,a;typeof e.flowId==`string`&&e.flowId.trim().length>0?a=e.flowId.trim():typeof e.flow_id==`string`&&e.flow_id.trim().length>0&&(a=e.flow_id.trim());let o=(i.composedOf??[]).map(e=>e.perRepoFlowId),s=a??Tg(i.name,o,t);if(n.has(s)){let e=r;for(;n.has(`${s}-${e}`);)e++;s=`${s}-${e}`}n.add(s),i.flowId=s}}assignStepIds(e){for(let t of e)if(t.productFlow!==void 0)for(let e of t.productFlow.steps)e.stepId=(0,v.randomUUID)().slice(0,8)}assignRanks(e){let t=e.filter(e=>e.scoring===void 0).map(e=>e.name);t.length>0&&n.logger.info.defaultLog(`[regression-e2e-catalog] WARNING: assignRanks: ${t.length} flow(s) are missing scoring and will rank last: ${t.join(`, `)}`),e.sort((e,t)=>{let n=e.scoring?.finalScore??0;return(t.scoring?.finalScore??0)-n});for(let[t,n]of e.entries())n.rank=t+1}};Ag=(0,Cg.default)([(0,h.injectable)(),(0,Sg.default)(0,(0,h.inject)(n.GlobalConfigService)),(0,Sg.default)(1,(0,h.inject)(tn)),(0,xg.default)(`design:paramtypes`,[Object,typeof(wg=tn!==void 0&&tn)==`function`?wg:Object])],Ag);function jg(e){if(typeof e!=`object`||!e)return;let t=e;if(!Array.isArray(t.flows))return;let r=[],i=[];for(let[e,n]of t.flows.entries())typeof n==`object`&&n&&!Array.isArray(n)?r.push(n):i.push(e);return i.length>0&&n.logger.info.defaultLog(`[regression-e2e-catalog] WARNING: parser dropped ${i.length} non-object element(s) at indices [${i.join(`, `)}] from agent output`),{flows:r,projectSummary:typeof t.projectSummary==`string`?t.projectSummary:``,projectType:typeof t.projectType==`string`?t.projectType:`unknown`,detectedFlowCount:typeof t.detectedFlowCount==`number`?t.detectedFlowCount:0}}let Mg={type:`object`,additionalProperties:!1,required:[`connections`],properties:{connections:{type:`array`,items:{type:`object`}}}},Ng=e=>e.replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`);function Pg(){return`You are a staff engineer mapping the CROSS-REPO call graph of a multi-service product, using only each repo's catalog of flows (no source code, no traces).
|
|
33547
33547
|
|
|
33548
33548
|
You are given a PRIMARY project's flows and one or more DEPENDENCY projects' flows. Each flow has: name, description, flowType, entryPoints, and calledModules. Your job: for each PRIMARY flow, find which DEPENDENCY flow(s) it connects to — i.e. which dependency flow the primary flow CALLS or DEPENDS ON as part of its behavior.
|
|
@@ -33592,8 +33592,8 @@ ${e.length===0?``:Ig(`primary`,t)}
|
|
|
33592
33592
|
<dependencyProjects>
|
|
33593
33593
|
${n.map(e=>Ig(`dependency`,e)).join(`
|
|
33594
33594
|
`)}
|
|
33595
|
-
</dependencyProjects>`}var Rg=t.__toESM(n.require_decorateMetadata()),zg=t.__toESM(nn()),Bg=t.__toESM(n.require_decorate()),Vg;function Hg(e){let t=String(e??``).toLowerCase();return t===`high`||t===`medium`||t===`low`?t:`low`}function Ug(e){if(!Array.isArray(e))return[];let t=[];for(let[n,r]of e.entries()){let e=typeof r.route==`string`?r.route.trim():``;if(e.length===0)continue;let i=typeof r.method==`string`&&r.method.trim().length>0?r.method.trim().toUpperCase():`GET`,a=typeof r.order==`number`&&Number.isFinite(r.order)?r.order:n+1;t.push({method:i,route:e,order:a})}return t.sort((e,t)=>e.order-t.order)}function Wg(e,t,r){let i=new Set(t.flows.map(e=>e.flowId).filter(Boolean)),a=new Map;for(let e of r.slice(1))a.set(e.repoSlug,new Set(e.flows.map(e=>e.flowId).filter(Boolean)));let o=[],s=0;for(let n of e){let e=n.fromRepo===t.repoSlug&&i.has(n.fromFlowId),r=a.get(n.toRepo),c=r!==void 0&&r.has(n.toFlowId);if(!e||!c){s++;continue}o.push({fromRepo:n.fromRepo,fromFlowId:n.fromFlowId,fromFlowName:typeof n.fromFlowName==`string`?n.fromFlowName:n.fromFlowId,toRepo:n.toRepo,toFlowId:n.toFlowId,toFlowName:typeof n.toFlowName==`string`?n.toFlowName:n.toFlowId,calls:Ug(n.calls),reason:typeof n.reason==`string`?n.reason:``,confidence:Hg(n.confidence)})}return s>0&&n.logger.info.defaultLog(`[regression-e2e-connection] Dropped ${s} invalid connection(s) (unknown flowId or not primary→dependency)`),n.logger.info.defaultLog(`[regression-e2e-connection] Derived ${o.length} cross-repo connection(s)`),o}let Gg=class{constructor(e,t){this.globalConfigService=e,this.authStorage=t}async run(e){if(e.perRepoCatalogs.length===0)throw Error(`E2E connection discovery: no primary project provided`);let[t]=e.perRepoCatalogs;if(e.perRepoCatalogs.length<2)return n.logger.info.defaultLog(`[regression-e2e-connection] WARNING: only ${e.perRepoCatalogs.length} project provided — an E2E catalog needs a primary + at least one dependency. No cross-repo connections will be discovered and the resulting catalog will be degenerate/empty. Provide dependency projectIds.`),{map:{primaryRepoSlug:t.repoSlug,primaryProjectId:e.primaryProjectId,connections:[]},generatedPrompt:``};let r=await this.authStorage.getJWTToken(),{query:a,isResultMessage:s,isErrorResult:c}=await Promise.resolve().then(()=>lz()),l=Pg(),u=Lg(e.perRepoCatalogs);n.logger.info.defaultLog(`[regression-e2e-connection] Discovering connections: primary "${t.repoSlug}" (${t.flows.length} flows) → ${e.perRepoCatalogs.length-1} dependency project(s)`);let d=a({prompt:u,options:{model:o.REGRESSION_E2E_CATALOG_MODEL,systemPrompt:l,allowedTools:[],permissionMode:o.REGRESSION_PERMISSION_MODE,allowDangerouslySkipPermissions:!0,maxBudgetUsd:o.REGRESSION_E2E_CONNECTION_MAX_BUDGET_USD,maxTurns:o.REGRESSION_E2E_CONNECTION_MAX_TURNS,outputFormat:{type:`json_schema`,schema:Mg},sessionId:(0,v.randomUUID)(),env:{...process.env,...i.buildAnthropicSdkEnv({proxyUrl:this.globalConfigService.getAnthropicProxyUrl(),jwtToken:r??``,requestId:n.logger.getRequestId()})}}}),f,p,m,h;for await(let e of d)if(s(e)){if(c(e))throw new cf(e.subtype,e.errors,e.total_cost_usd);f=e.total_cost_usd,typeof e.num_turns==`number`&&(p=e.num_turns),m=i.extractCacheTokens(e),h=e.structured_output;break}let g=Wg(Array.isArray(h?.connections)?h.connections:[],t,e.perRepoCatalogs);return{map:{primaryRepoSlug:t.repoSlug,primaryProjectId:e.primaryProjectId,connections:g},costUsd:f,turns:p,tokens:m===void 0?void 0:{inputTokens:m.inputTokens,outputTokens:m.outputTokens,cacheReadTokens:m.cacheReadTokens,cacheCreationTokens:m.cacheCreationTokens},generatedPrompt:u}}};Gg=(0,Bg.default)([(0,h.injectable)(),(0,zg.default)(0,(0,h.inject)(n.GlobalConfigService)),(0,zg.default)(1,(0,h.inject)(tn)),(0,Rg.default)(`design:paramtypes`,[Object,typeof(Vg=tn!==void 0&&tn)==`function`?Vg:Object])],Gg);var Kg=t.__toESM(n.require_decorateMetadata()),qg=t.__toESM(nn()),Jg=t.__toESM(n.require_decorate()),Yg,Xg,Zg,Qg;let $g=class{constructor(e,t,n,r,i){this.runner=e,this.connectionRunner=t,this.jobInputProvider=n,this.apiService=r,this.globalConfigService=i}async run(){let e=await mg(this.apiService,this.globalConfigService)??await this.jobInputProvider.getE2eCatalogJobInput(),t=fg(e);if(t.length===0){let e=Error(`[regression-e2e-catalog] no projectIds in the job input — cannot build E2E catalog`);throw n.logger.error(e.message,e),e}return n.logger.info.defaultLog(`[regression-e2e-catalog] Manager: building "${e.e2eName}" — ${t.length} project(s), RC ${e.releaseCandidateId??`(none)`}`),og(`regression-e2e-catalog-reports`,this.runner,this.connectionRunner,{e2eName:e.e2eName,e2eDescription:e.e2eDescription,projectIds:t,releaseCandidateId:e.releaseCandidateId},this.apiService)}};$g=(0,Jg.default)([(0,h.injectable)(),(0,qg.default)(0,(0,h.inject)(Ag)),(0,qg.default)(1,(0,h.inject)(Gg)),(0,qg.default)(2,(0,h.inject)(pg)),(0,qg.default)(3,(0,h.inject)(ln)),(0,qg.default)(4,(0,h.inject)(n.GlobalConfigService)),(0,Kg.default)(`design:paramtypes`,[typeof(Yg=Ag!==void 0&&Ag)==`function`?Yg:Object,typeof(Xg=Gg!==void 0&&Gg)==`function`?Xg:Object,typeof(Zg=pg!==void 0&&pg)==`function`?Zg:Object,typeof(Qg=ln!==void 0&&ln)==`function`?Qg:Object,Object])],$g);function e_(e){if(typeof e!=`object`||!e)return;let t=e;if(Array.isArray(t.sourceFiles))return{sourceFiles:t.sourceFiles.filter(e=>typeof e==`string`)}}let t_=new Set([`svg`,`woff`,`woff2`,`ttf`,`eot`,`otf`,`ico`,`png`,`jpg`,`jpeg`,`gif`,`webp`]);function n_(e){let t=e.slice(e.lastIndexOf(`/`)+1),n=t.lastIndexOf(`.`);return n>0?t.slice(n+1).toLowerCase():``}function r_(e){if(e.length===0)return`0`;let t=new Map;for(let n of e){let e=n.slice(n.lastIndexOf(`/`)+1),r=e.lastIndexOf(`.`),i=r>0?e.slice(r+1).toLowerCase():`(none)`;t.set(i,(t.get(i)??0)+1)}return[...t.entries()].sort((e,t)=>t[1]-e[1]||e[0].localeCompare(t[0])).map(([e,t])=>`${t} ${e}`).join(`, `)}async function i_(e,t,r,a){let{query:s,isResultMessage:l,isErrorResult:u,getMessageContentBlocks:d}=await Promise.resolve().then(()=>lz()),f=`haiku-prefilter`,p=`Changed files:\n${e.map((e,t)=>`${t+1}. ${e}`).join(`
|
|
33596
|
-
`)}`;n.logger.info.defaultLog(`[regression-impact] Pre-filter: classifying ${e.length} files (source vs non-source)`);let m=s({prompt:p,options:{model:o.REGRESSION_IMPACT_HAIKU_MODEL,systemPrompt:c.PRE_FILTER_SYSTEM_PROMPT,tools:[],permissionMode:o.REGRESSION_PERMISSION_MODE,allowDangerouslySkipPermissions:!0,maxBudgetUsd:1,maxTurns:10,cwd:a,sessionId:(0,v.randomUUID)(),outputFormat:{type:`json_schema`,schema:i.PRE_FILTER_OUTPUT_SCHEMA},env:{...process.env,...i.buildAnthropicSdkEnv({proxyUrl:r,jwtToken:t??``,requestId:n.logger.getRequestId()})}}});i.logAgentCwd(f,a);let h=0;for await(let t of m){if(!l(t)){let e=d(t);e!==void 0&&e.length>0&&(h++,i.logAgentActivity(f,h,e));continue}if(u(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,a=t.num_turns,o=a>=10;i.logCacheTokensFromMessage(`pre-filter`,t);let s=e_(t.structured_output);if(s===void 0)return{sourceFiles:e,costUsd:r,turns:a,maxTurnsHit:o};let c=s.sourceFiles.filter(t=>e.includes(t)&&!t_.has(n_(t))),p=e.filter(e=>!c.includes(e));return n.logger.info.defaultLog(`[regression-impact] Pre-filter: ${e.length} → ${c.length} source files (${p.length} non-source filtered out)`),n.logger.info.defaultLog(`[regression-impact] Pre-filter by extension — pass: ${r_(c)} | filtered out: ${r_(p)}`),p.length>0?n.logger.info.defaultLog(`[regression-impact] Pre-filter dropped (non-source): ${p.join(`, `)}`):n.logger.info.defaultLog(`[regression-impact] Pre-filter kept all as source: ${c.join(`, `)}`),{sourceFiles:c,costUsd:r,turns:a,maxTurnsHit:o}}return{sourceFiles:e,costUsd:0,turns:0,maxTurnsHit:!1}}let a_=[`NONE`,`LOW`,`MEDIUM`,`HIGH`,`CRITICAL`];function o_(e){return e.length===0?`NONE`:e.reduce((e,t)=>a_.indexOf(t.severity)>a_.indexOf(e)?t.severity:e,`NONE`)}function s_(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 c_(e,t,r,a,s,l,u,d=!1,f=[],p,m){let{query:h,getMessageContentBlocks:g,isResultMessage:_,isErrorResult:y}=await Promise.resolve().then(()=>lz()),b=`sonnet-deep (${e.name})`;i.logAgentCwd(b,r);let x=o.getDiffForFiles(t,r,a,s,d),S=m!==void 0&&m.size>0,C=h({prompt:c.buildSonnetDeepPrompt(e,t,x,a,s,f,p,m),options:{model:o.REGRESSION_IMPACT_DEEP_MODEL,systemPrompt:c.buildSonnetDeepSystemPrompt(S),allowedTools:[`Read`,`Grep`,`Glob`,`Bash`],permissionMode:o.REGRESSION_PERMISSION_MODE,allowDangerouslySkipPermissions:!0,maxBudgetUsd:o.REGRESSION_IMPACT_DEEP_MAX_BUDGET_USD,maxTurns:o.REGRESSION_IMPACT_DEEP_MAX_TURNS,cwd:r,sessionId:(0,v.randomUUID)(),outputFormat:{type:`json_schema`,schema:i.SONNET_DEEP_OUTPUT_SCHEMA},env:{...process.env,...i.buildAnthropicSdkEnv({proxyUrl:u,jwtToken:l??``,requestId:n.logger.getRequestId()})}}}),w=0,T=0;for await(let t of C){if(!_(t)){let e=g(t);e!==void 0&&e.length>0&&(T++,i.logAgentActivity(b,T,e));continue}if(y(t))return n.logger.info.defaultLog(`[regression-impact] Sonnet deep analysis error: ${t.subtype}`),null;w=t.total_cost_usd;let r=t.num_turns,a=r>=o.REGRESSION_IMPACT_DEEP_MAX_TURNS;i.logCacheTokensFromMessage(`per-flow deep (${e.name})`,t);let s=s_(t.structured_output);if(s===void 0)return n.logger.info.defaultLog(`[regression-impact] Sonnet deep: missing or invalid structured_output (flow: ${e.name})`),null;let c=s.techChanges.map(e=>({file:e.file,confidence:e.confidence,techBefore:e.techBefore,techAfter:e.techAfter})),l=s.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:o_(l),techChanges:c,productChanges:l,affectedSteps:s.affectedSteps??[],costUsd:w,turns:r,maxTurnsHit:a}}return null}let l_=function(e){return e.Continue=`continue`,e.Halt=`halt`,e}({}),u_={costUsd:0,turns:0,maxTurnsHit:!1};function d_(e,t,n,r,i,a,o,s=!1,c,l,u){return{stepName:e,costUsd:t,durationSeconds:(Date.now()-n)/1e3,turns:r,maxTurnsHit:i,...s&&{maxBudgetHit:!0},...a!==void 0&&{tokens:a},...o!==void 0&&o.length>0&&{batches:o},...c!==void 0&&{totalFiles:c},...l!==void 0&&{mappedFiles:l},...u!==void 0&&{mappingBreakdown:u}}}var f_=class{constructor(e){this.steps=e}describe(){return this.steps.map(e=>e.name).join(` -> `)}async run(e){n.logger.info.defaultLog(`[cross-component] Pipeline: ${this.describe()}`);let t=!1;for(let[r,i]of this.steps.entries()){let a=`${r+1}/${this.steps.length}`;if(t&&i.isTerminal!==!0){n.logger.info.defaultLog(`[cross-component] Step ${a} "${i.name}" — SKIPPED (pipeline halted)`);continue}n.logger.info.defaultLog(`[cross-component] Step ${a} "${i.name}" — START`);let s=Date.now(),c=await i.execute(e),l=(Date.now()-s)/1e3;e.stepMetrics.push(d_(i.name,c.costUsd,s,c.turns,c.maxTurnsHit,c.tokens,c.batches,c.maxBudgetHit??!1,c.totalFiles,c.mappedFiles,c.mappingBreakdown));let u=c.status===l_.Halt?` — HALT`:``,d=c.maxTurnsHit?` / maxTurnsHit`:``,f=o.shouldLogDiagnostics?`$${c.costUsd.toFixed(4)} / ${c.turns} turns / ${l.toFixed(2)}s${d}`:`${l.toFixed(2)}s`;n.logger.info.defaultLog(`[cross-component] Step ${a} "${i.name}" — END (${f})${u}`),c.status===l_.Halt&&(t=!0)}return e}};function p_(e,t,n){if(e===void 0)throw Error(`[cross-component] ctx.${t} is unset — ${n} must run before this step`);return e}function m_(e){return p_(e.providerChanges,`providerChanges`,`LoadProviderChangesStep`)}function h_(e){return p_(e.consumerChanges,`consumerChanges`,`LoadConsumerChangesStep`)}function g_(e){return p_(e.findings,`findings`,`CrossContractHuntStep`)}function __(e){return p_(e.result,`result`,`CrossComponentReportStep`)}async function v_(e,t,r){try{if(e.consumerProjectId.length===0)return n.logger.info.defaultLog(`[cross-component] No consumerProjectId — cannot post run`),null;let i=e.findings.map(e=>({severity:e.severity,verdictScore:e.verdictScore,...(0,m.isDefined)(e.verdictReason)?{verdictReason:e.verdictReason}:{},title:e.title,consumerBefore:e.consumerBefore,consumerAfter:e.consumerAfter,...(0,m.isDefined)(e.consumerFile)?{consumerFile:e.consumerFile}:{},...(0,m.isDefined)(e.consumerExcerpt)?{consumerExcerpt:e.consumerExcerpt}:{},...(0,m.isDefined)(e.providerContract)?{providerContract:e.providerContract}:{},...(0,m.isDefined)(e.providerProductChangeId)?{providerProductChangeId:e.providerProductChangeId}:{},...(0,m.isDefined)(e.affectedFlow)?{affectedFlow:e.affectedFlow}:{},...(0,m.isDefined)(e.howToVerify)?{howToVerify:e.howToVerify}:{},...(0,m.isDefined)(e.technicalRootCause)?{technicalRootCause:e.technicalRootCause}:{}})),a={changedSide:e.changedSide,consumerProjectId:e.consumerProjectId,providerProjectId:e.providerProjectId,...(0,m.isDefined)(e.providerRunId)?{providerRunId:e.providerRunId}:{},...(0,m.isDefined)(e.providerSha)?{providerSha:e.providerSha}:{},...(0,m.isDefined)(e.providerRef)?{providerRef:e.providerRef}:{},...(0,m.isDefined)(e.consumerRunId)?{consumerRunId:e.consumerRunId}:{},consumerSha:e.consumerSha,consumerIsReleasing:e.consumerIsReleasing,findings:i,costUsd:e.costUsd,agentVersion:Nm,...(0,m.isDefined)(e.turns)?{turns:e.turns}:{},...(0,m.isDefined)(e.maxTurnsHit)?{maxTurnsHit:e.maxTurnsHit}:{},...(0,m.isDefined)(e.durationSeconds)?{durationSeconds:e.durationSeconds}:{},jobId:r.getJobId()},o=await t.post(`/api/v1/regression/cross-component-runs`,a);return n.logger.info.defaultLog(`[cross-component] Run posted to backend. runId: ${o.runId}`),o}catch(e){return n.logger.info.defaultLog(`[cross-component] Failed to post run to backend: ${String(e)}`),null}}var y_=class{name=`crossComponentPost`;isTerminal=!0;async execute(e){let t=await v_(__(e),e.apiService,e.globalConfigService);if(t===null)throw Error(`[cross-component] Failed to persist the cross-component run to the backend — see the preceding log for the underlying error.`);return e.runId=t.runId,u_}},b_=class{name=`crossComponentReport`;isTerminal=!0;async execute(e){let t=g_(e),r=e.jobInput.crossComponent;if(r===void 0)throw Error(`[cross-component] CrossComponentReportStep requires jobInput.crossComponent`);let a=t.filter(e=>e.verdictScore>=o.CROSS_COMPONENT_REGRESSION_SCORE_THRESHOLD).length,s={findings:t,findingCount:t.length,breakingCount:a,costUsd:e.huntCostUsd??0,turns:e.huntTurns,maxTurnsHit:e.huntMaxTurnsHit,durationSeconds:(Date.now()-e.startTime)/1e3,tokens:e.huntTokens??i.ZERO_TOKENS,changedSide:r.changedSide??`provider`,providerRunId:r.providerRunId,providerSha:r.providerSha,providerRef:r.providerRef,consumerRunId:r.consumerRunId,providerProjectId:r.providerProjectId,consumerProjectId:e.jobInput.projectId,consumerSha:e.jobInput.compareSha,consumerIsReleasing:r.consumerIsReleasing??!1,createdAt:new Date().toISOString()};return n.logger.info.defaultLog(`[cross-component] Done. ${s.findingCount} finding(s), ${s.breakingCount} breaking (score >= ${o.CROSS_COMPONENT_REGRESSION_SCORE_THRESHOLD}), ${((Date.now()-e.startTime)/1e3).toFixed(2)}s`),o.REGRESSION_SAVE_REPORT_FILES&&x_(e.reportsDir,s),e.result=s,u_}};function x_(e,t){(0,y.mkdirSync)(e,{recursive:!0});let r=t.createdAt.replaceAll(/[:.]/g,`-`),i=(t.providerRunId??t.consumerRunId??`unknown`).slice(0,8),a=I.default.join(e,`${r}-cross-component-${i}.json`);(0,y.writeFileSync)(a,JSON.stringify(t,null,2),`utf8`),n.logger.info.defaultLog(`[cross-component] Result written to: ${a}`)}let S_={type:`object`,additionalProperties:!1,required:[`findings`],properties:{findings:{type:`array`,items:{type:`object`,required:[`title`,`severity`,`consumerBefore`,`consumerAfter`,`affectedFlow`,`howToVerify`,`technicalRootCause`,`verdict`],properties:{title:{type:`string`},severity:{type:`string`},consumerBefore:{type:`string`},consumerAfter:{type:`string`},affectedFlow:{type:`string`},howToVerify:{type:`string`},technicalRootCause:{type:`string`},verdict:{type:`object`,required:[`score`],properties:{score:{type:`number`},reason:{type:`string`}}}}}}}},C_=e=>e.replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`),w_=`## Severity (cross-component, product-level)
|
|
33595
|
+
</dependencyProjects>`}var Rg=t.__toESM(n.require_decorateMetadata()),zg=t.__toESM(nn()),Bg=t.__toESM(n.require_decorate()),Vg;function Hg(e){let t=String(e??``).toLowerCase();return t===`high`||t===`medium`||t===`low`?t:`low`}function Ug(e){if(!Array.isArray(e))return[];let t=[];for(let[n,r]of e.entries()){let e=typeof r.route==`string`?r.route.trim():``;if(e.length===0)continue;let i=typeof r.method==`string`&&r.method.trim().length>0?r.method.trim().toUpperCase():`GET`,a=typeof r.order==`number`&&Number.isFinite(r.order)?r.order:n+1;t.push({method:i,route:e,order:a})}return t.sort((e,t)=>e.order-t.order)}function Wg(e,t,r){let i=new Set(t.flows.map(e=>e.flowId).filter(Boolean)),a=new Map;for(let e of r.slice(1))a.set(e.repoSlug,new Set(e.flows.map(e=>e.flowId).filter(Boolean)));let o=[],s=0;for(let n of e){let e=n.fromRepo===t.repoSlug&&i.has(n.fromFlowId),r=a.get(n.toRepo),c=r!==void 0&&r.has(n.toFlowId);if(!e||!c){s++;continue}o.push({fromRepo:n.fromRepo,fromFlowId:n.fromFlowId,fromFlowName:typeof n.fromFlowName==`string`?n.fromFlowName:n.fromFlowId,toRepo:n.toRepo,toFlowId:n.toFlowId,toFlowName:typeof n.toFlowName==`string`?n.toFlowName:n.toFlowId,calls:Ug(n.calls),reason:typeof n.reason==`string`?n.reason:``,confidence:Hg(n.confidence)})}return s>0&&n.logger.info.defaultLog(`[regression-e2e-connection] Dropped ${s} invalid connection(s) (unknown flowId or not primary→dependency)`),n.logger.info.defaultLog(`[regression-e2e-connection] Derived ${o.length} cross-repo connection(s)`),o}let Gg=class{constructor(e,t){this.globalConfigService=e,this.authStorage=t}async run(e){if(e.perRepoCatalogs.length===0)throw Error(`E2E connection discovery: no primary project provided`);let[t]=e.perRepoCatalogs;if(e.perRepoCatalogs.length<2)return n.logger.info.defaultLog(`[regression-e2e-connection] WARNING: only ${e.perRepoCatalogs.length} project provided — an E2E catalog needs a primary + at least one dependency. No cross-repo connections will be discovered and the resulting catalog will be degenerate/empty. Provide dependency projectIds.`),{map:{primaryRepoSlug:t.repoSlug,primaryProjectId:e.primaryProjectId,connections:[]},generatedPrompt:``};let r=await this.authStorage.getJWTToken(),{query:a,isResultMessage:s,isErrorResult:c}=await Promise.resolve().then(()=>lz()),l=Pg(),u=Lg(e.perRepoCatalogs);n.logger.info.defaultLog(`[regression-e2e-connection] Discovering connections: primary "${t.repoSlug}" (${t.flows.length} flows) → ${e.perRepoCatalogs.length-1} dependency project(s)`);let d=a({prompt:u,options:{model:o.REGRESSION_E2E_CATALOG_MODEL,...o.REGRESSION_SONNET_SCORER_REASONING,systemPrompt:l,allowedTools:[],permissionMode:o.REGRESSION_PERMISSION_MODE,allowDangerouslySkipPermissions:!0,maxBudgetUsd:o.REGRESSION_E2E_CONNECTION_MAX_BUDGET_USD,maxTurns:o.REGRESSION_E2E_CONNECTION_MAX_TURNS,outputFormat:{type:`json_schema`,schema:Mg},sessionId:(0,v.randomUUID)(),env:{...process.env,...i.buildAnthropicSdkEnv({proxyUrl:this.globalConfigService.getAnthropicProxyUrl(),jwtToken:r??``,requestId:n.logger.getRequestId()})}}}),f,p,m,h;for await(let e of d)if(s(e)){if(c(e))throw new cf(e.subtype,e.errors,e.total_cost_usd);f=e.total_cost_usd,typeof e.num_turns==`number`&&(p=e.num_turns),m=i.extractCacheTokens(e),h=e.structured_output;break}let g=Wg(Array.isArray(h?.connections)?h.connections:[],t,e.perRepoCatalogs);return{map:{primaryRepoSlug:t.repoSlug,primaryProjectId:e.primaryProjectId,connections:g},costUsd:f,turns:p,tokens:m===void 0?void 0:{inputTokens:m.inputTokens,outputTokens:m.outputTokens,cacheReadTokens:m.cacheReadTokens,cacheCreationTokens:m.cacheCreationTokens},generatedPrompt:u}}};Gg=(0,Bg.default)([(0,h.injectable)(),(0,zg.default)(0,(0,h.inject)(n.GlobalConfigService)),(0,zg.default)(1,(0,h.inject)(tn)),(0,Rg.default)(`design:paramtypes`,[Object,typeof(Vg=tn!==void 0&&tn)==`function`?Vg:Object])],Gg);var Kg=t.__toESM(n.require_decorateMetadata()),qg=t.__toESM(nn()),Jg=t.__toESM(n.require_decorate()),Yg,Xg,Zg,Qg;let $g=class{constructor(e,t,n,r,i){this.runner=e,this.connectionRunner=t,this.jobInputProvider=n,this.apiService=r,this.globalConfigService=i}async run(){let e=await mg(this.apiService,this.globalConfigService)??await this.jobInputProvider.getE2eCatalogJobInput(),t=fg(e);if(t.length===0){let e=Error(`[regression-e2e-catalog] no projectIds in the job input — cannot build E2E catalog`);throw n.logger.error(e.message,e),e}return n.logger.info.defaultLog(`[regression-e2e-catalog] Manager: building "${e.e2eName}" — ${t.length} project(s), RC ${e.releaseCandidateId??`(none)`}`),og(`regression-e2e-catalog-reports`,this.runner,this.connectionRunner,{e2eName:e.e2eName,e2eDescription:e.e2eDescription,projectIds:t,releaseCandidateId:e.releaseCandidateId},this.apiService)}};$g=(0,Jg.default)([(0,h.injectable)(),(0,qg.default)(0,(0,h.inject)(Ag)),(0,qg.default)(1,(0,h.inject)(Gg)),(0,qg.default)(2,(0,h.inject)(pg)),(0,qg.default)(3,(0,h.inject)(ln)),(0,qg.default)(4,(0,h.inject)(n.GlobalConfigService)),(0,Kg.default)(`design:paramtypes`,[typeof(Yg=Ag!==void 0&&Ag)==`function`?Yg:Object,typeof(Xg=Gg!==void 0&&Gg)==`function`?Xg:Object,typeof(Zg=pg!==void 0&&pg)==`function`?Zg:Object,typeof(Qg=ln!==void 0&&ln)==`function`?Qg:Object,Object])],$g);function e_(e){if(typeof e!=`object`||!e)return;let t=e;if(Array.isArray(t.sourceFiles))return{sourceFiles:t.sourceFiles.filter(e=>typeof e==`string`)}}let t_=new Set([`svg`,`woff`,`woff2`,`ttf`,`eot`,`otf`,`ico`,`png`,`jpg`,`jpeg`,`gif`,`webp`]);function n_(e){let t=e.slice(e.lastIndexOf(`/`)+1),n=t.lastIndexOf(`.`);return n>0?t.slice(n+1).toLowerCase():``}function r_(e){if(e.length===0)return`0`;let t=new Map;for(let n of e){let e=n.slice(n.lastIndexOf(`/`)+1),r=e.lastIndexOf(`.`),i=r>0?e.slice(r+1).toLowerCase():`(none)`;t.set(i,(t.get(i)??0)+1)}return[...t.entries()].sort((e,t)=>t[1]-e[1]||e[0].localeCompare(t[0])).map(([e,t])=>`${t} ${e}`).join(`, `)}async function i_(e,t,r,a){let{query:s,isResultMessage:l,isErrorResult:u,getMessageContentBlocks:d}=await Promise.resolve().then(()=>lz()),f=`haiku-prefilter`,p=`Changed files:\n${e.map((e,t)=>`${t+1}. ${e}`).join(`
|
|
33596
|
+
`)}`;n.logger.info.defaultLog(`[regression-impact] Pre-filter: classifying ${e.length} files (source vs non-source)`);let m=s({prompt:p,options:{model:o.REGRESSION_IMPACT_HAIKU_MODEL,...o.REGRESSION_HAIKU_REASONING,systemPrompt:c.PRE_FILTER_SYSTEM_PROMPT,tools:[],permissionMode:o.REGRESSION_PERMISSION_MODE,allowDangerouslySkipPermissions:!0,maxBudgetUsd:1,maxTurns:10,cwd:a,sessionId:(0,v.randomUUID)(),outputFormat:{type:`json_schema`,schema:i.PRE_FILTER_OUTPUT_SCHEMA},env:{...process.env,...i.buildAnthropicSdkEnv({proxyUrl:r,jwtToken:t??``,requestId:n.logger.getRequestId()})}}});i.logAgentCwd(f,a);let h=0;for await(let t of m){if(!l(t)){let e=d(t);e!==void 0&&e.length>0&&(h++,i.logAgentActivity(f,h,e));continue}if(u(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,a=t.num_turns,o=a>=10;i.logCacheTokensFromMessage(`pre-filter`,t);let s=e_(t.structured_output);if(s===void 0)return{sourceFiles:e,costUsd:r,turns:a,maxTurnsHit:o};let c=s.sourceFiles.filter(t=>e.includes(t)&&!t_.has(n_(t))),p=e.filter(e=>!c.includes(e));return n.logger.info.defaultLog(`[regression-impact] Pre-filter: ${e.length} → ${c.length} source files (${p.length} non-source filtered out)`),n.logger.info.defaultLog(`[regression-impact] Pre-filter by extension — pass: ${r_(c)} | filtered out: ${r_(p)}`),p.length>0?n.logger.info.defaultLog(`[regression-impact] Pre-filter dropped (non-source): ${p.join(`, `)}`):n.logger.info.defaultLog(`[regression-impact] Pre-filter kept all as source: ${c.join(`, `)}`),{sourceFiles:c,costUsd:r,turns:a,maxTurnsHit:o}}return{sourceFiles:e,costUsd:0,turns:0,maxTurnsHit:!1}}let a_=[`NONE`,`LOW`,`MEDIUM`,`HIGH`,`CRITICAL`];function o_(e){return e.length===0?`NONE`:e.reduce((e,t)=>a_.indexOf(t.severity)>a_.indexOf(e)?t.severity:e,`NONE`)}function s_(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 c_(e,t,r,a,s,l,u,d=!1,f=[],p,m){let{query:h,getMessageContentBlocks:g,isResultMessage:_,isErrorResult:y}=await Promise.resolve().then(()=>lz()),b=`sonnet-deep (${e.name})`;i.logAgentCwd(b,r);let x=o.getDiffForFiles(t,r,a,s,d),S=m!==void 0&&m.size>0,C=h({prompt:c.buildSonnetDeepPrompt(e,t,x,a,s,f,p,m),options:{model:o.REGRESSION_IMPACT_DEEP_MODEL,...o.REGRESSION_SONNET_ANALYZER_REASONING,systemPrompt:c.buildSonnetDeepSystemPrompt(S),allowedTools:[`Read`,`Grep`,`Glob`,`Bash`],permissionMode:o.REGRESSION_PERMISSION_MODE,allowDangerouslySkipPermissions:!0,maxBudgetUsd:o.REGRESSION_IMPACT_DEEP_MAX_BUDGET_USD,maxTurns:o.REGRESSION_IMPACT_DEEP_MAX_TURNS,cwd:r,sessionId:(0,v.randomUUID)(),outputFormat:{type:`json_schema`,schema:i.SONNET_DEEP_OUTPUT_SCHEMA},env:{...process.env,...i.buildAnthropicSdkEnv({proxyUrl:u,jwtToken:l??``,requestId:n.logger.getRequestId()})}}}),w=0,T=0;for await(let t of C){if(!_(t)){let e=g(t);e!==void 0&&e.length>0&&(T++,i.logAgentActivity(b,T,e));continue}if(y(t))return n.logger.info.defaultLog(`[regression-impact] Sonnet deep analysis error: ${t.subtype}`),null;w=t.total_cost_usd;let r=t.num_turns,a=r>=o.REGRESSION_IMPACT_DEEP_MAX_TURNS;i.logCacheTokensFromMessage(`per-flow deep (${e.name})`,t);let s=s_(t.structured_output);if(s===void 0)return n.logger.info.defaultLog(`[regression-impact] Sonnet deep: missing or invalid structured_output (flow: ${e.name})`),null;let c=s.techChanges.map(e=>({file:e.file,confidence:e.confidence,techBefore:e.techBefore,techAfter:e.techAfter})),l=s.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:o_(l),techChanges:c,productChanges:l,affectedSteps:s.affectedSteps??[],costUsd:w,turns:r,maxTurnsHit:a}}return null}let l_=function(e){return e.Continue=`continue`,e.Halt=`halt`,e}({}),u_={costUsd:0,turns:0,maxTurnsHit:!1};function d_(e,t,n,r,i,a,o,s=!1,c,l,u){return{stepName:e,costUsd:t,durationSeconds:(Date.now()-n)/1e3,turns:r,maxTurnsHit:i,...s&&{maxBudgetHit:!0},...a!==void 0&&{tokens:a},...o!==void 0&&o.length>0&&{batches:o},...c!==void 0&&{totalFiles:c},...l!==void 0&&{mappedFiles:l},...u!==void 0&&{mappingBreakdown:u}}}var f_=class{constructor(e){this.steps=e}describe(){return this.steps.map(e=>e.name).join(` -> `)}async run(e){n.logger.info.defaultLog(`[cross-component] Pipeline: ${this.describe()}`);let t=!1;for(let[r,i]of this.steps.entries()){let a=`${r+1}/${this.steps.length}`;if(t&&i.isTerminal!==!0){n.logger.info.defaultLog(`[cross-component] Step ${a} "${i.name}" — SKIPPED (pipeline halted)`);continue}n.logger.info.defaultLog(`[cross-component] Step ${a} "${i.name}" — START`);let s=Date.now(),c=await i.execute(e),l=(Date.now()-s)/1e3;e.stepMetrics.push(d_(i.name,c.costUsd,s,c.turns,c.maxTurnsHit,c.tokens,c.batches,c.maxBudgetHit??!1,c.totalFiles,c.mappedFiles,c.mappingBreakdown));let u=c.status===l_.Halt?` — HALT`:``,d=c.maxTurnsHit?` / maxTurnsHit`:``,f=o.shouldLogDiagnostics?`$${c.costUsd.toFixed(4)} / ${c.turns} turns / ${l.toFixed(2)}s${d}`:`${l.toFixed(2)}s`;n.logger.info.defaultLog(`[cross-component] Step ${a} "${i.name}" — END (${f})${u}`),c.status===l_.Halt&&(t=!0)}return e}};function p_(e,t,n){if(e===void 0)throw Error(`[cross-component] ctx.${t} is unset — ${n} must run before this step`);return e}function m_(e){return p_(e.providerChanges,`providerChanges`,`LoadProviderChangesStep`)}function h_(e){return p_(e.consumerChanges,`consumerChanges`,`LoadConsumerChangesStep`)}function g_(e){return p_(e.findings,`findings`,`CrossContractHuntStep`)}function __(e){return p_(e.result,`result`,`CrossComponentReportStep`)}async function v_(e,t,r){try{if(e.consumerProjectId.length===0)return n.logger.info.defaultLog(`[cross-component] No consumerProjectId — cannot post run`),null;let i=e.findings.map(e=>({severity:e.severity,verdictScore:e.verdictScore,...(0,m.isDefined)(e.verdictReason)?{verdictReason:e.verdictReason}:{},title:e.title,consumerBefore:e.consumerBefore,consumerAfter:e.consumerAfter,...(0,m.isDefined)(e.consumerFile)?{consumerFile:e.consumerFile}:{},...(0,m.isDefined)(e.consumerExcerpt)?{consumerExcerpt:e.consumerExcerpt}:{},...(0,m.isDefined)(e.providerContract)?{providerContract:e.providerContract}:{},...(0,m.isDefined)(e.providerProductChangeId)?{providerProductChangeId:e.providerProductChangeId}:{},...(0,m.isDefined)(e.affectedFlow)?{affectedFlow:e.affectedFlow}:{},...(0,m.isDefined)(e.howToVerify)?{howToVerify:e.howToVerify}:{},...(0,m.isDefined)(e.technicalRootCause)?{technicalRootCause:e.technicalRootCause}:{}})),a={changedSide:e.changedSide,consumerProjectId:e.consumerProjectId,providerProjectId:e.providerProjectId,...(0,m.isDefined)(e.providerRunId)?{providerRunId:e.providerRunId}:{},...(0,m.isDefined)(e.providerSha)?{providerSha:e.providerSha}:{},...(0,m.isDefined)(e.providerRef)?{providerRef:e.providerRef}:{},...(0,m.isDefined)(e.consumerRunId)?{consumerRunId:e.consumerRunId}:{},consumerSha:e.consumerSha,consumerIsReleasing:e.consumerIsReleasing,findings:i,costUsd:e.costUsd,agentVersion:Nm,...(0,m.isDefined)(e.turns)?{turns:e.turns}:{},...(0,m.isDefined)(e.maxTurnsHit)?{maxTurnsHit:e.maxTurnsHit}:{},...(0,m.isDefined)(e.durationSeconds)?{durationSeconds:e.durationSeconds}:{},jobId:r.getJobId()},o=await t.post(`/api/v1/regression/cross-component-runs`,a);return n.logger.info.defaultLog(`[cross-component] Run posted to backend. runId: ${o.runId}`),o}catch(e){return n.logger.info.defaultLog(`[cross-component] Failed to post run to backend: ${String(e)}`),null}}var y_=class{name=`crossComponentPost`;isTerminal=!0;async execute(e){let t=await v_(__(e),e.apiService,e.globalConfigService);if(t===null)throw Error(`[cross-component] Failed to persist the cross-component run to the backend — see the preceding log for the underlying error.`);return e.runId=t.runId,u_}},b_=class{name=`crossComponentReport`;isTerminal=!0;async execute(e){let t=g_(e),r=e.jobInput.crossComponent;if(r===void 0)throw Error(`[cross-component] CrossComponentReportStep requires jobInput.crossComponent`);let a=t.filter(e=>e.verdictScore>=o.CROSS_COMPONENT_REGRESSION_SCORE_THRESHOLD).length,s={findings:t,findingCount:t.length,breakingCount:a,costUsd:e.huntCostUsd??0,turns:e.huntTurns,maxTurnsHit:e.huntMaxTurnsHit,durationSeconds:(Date.now()-e.startTime)/1e3,tokens:e.huntTokens??i.ZERO_TOKENS,changedSide:r.changedSide??`provider`,providerRunId:r.providerRunId,providerSha:r.providerSha,providerRef:r.providerRef,consumerRunId:r.consumerRunId,providerProjectId:r.providerProjectId,consumerProjectId:e.jobInput.projectId,consumerSha:e.jobInput.compareSha,consumerIsReleasing:r.consumerIsReleasing??!1,createdAt:new Date().toISOString()};return n.logger.info.defaultLog(`[cross-component] Done. ${s.findingCount} finding(s), ${s.breakingCount} breaking (score >= ${o.CROSS_COMPONENT_REGRESSION_SCORE_THRESHOLD}), ${((Date.now()-e.startTime)/1e3).toFixed(2)}s`),o.REGRESSION_SAVE_REPORT_FILES&&x_(e.reportsDir,s),e.result=s,u_}};function x_(e,t){(0,y.mkdirSync)(e,{recursive:!0});let r=t.createdAt.replaceAll(/[:.]/g,`-`),i=(t.providerRunId??t.consumerRunId??`unknown`).slice(0,8),a=I.default.join(e,`${r}-cross-component-${i}.json`);(0,y.writeFileSync)(a,JSON.stringify(t,null,2),`utf8`),n.logger.info.defaultLog(`[cross-component] Result written to: ${a}`)}let S_={type:`object`,additionalProperties:!1,required:[`findings`],properties:{findings:{type:`array`,items:{type:`object`,required:[`title`,`severity`,`consumerBefore`,`consumerAfter`,`affectedFlow`,`howToVerify`,`technicalRootCause`,`verdict`],properties:{title:{type:`string`},severity:{type:`string`},consumerBefore:{type:`string`},consumerAfter:{type:`string`},affectedFlow:{type:`string`},howToVerify:{type:`string`},technicalRootCause:{type:`string`},verdict:{type:`object`,required:[`score`],properties:{score:{type:`number`},reason:{type:`string`}}}}}}}},C_=e=>e.replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`),w_=`## Severity (cross-component, product-level)
|
|
33597
33597
|
|
|
33598
33598
|
- CRITICAL: the consumer is broken for users (page crashes / blank, auth fails, a core action cannot complete, data not shown).
|
|
33599
33599
|
- HIGH: a major part of the consumer degrades, or a breaking-shape change the consumer very likely depends on.
|
|
@@ -33705,7 +33705,7 @@ The consumer changed the following (scored against the consumer ALONE — NONE-s
|
|
|
33705
33705
|
${a}
|
|
33706
33706
|
</consumerChanges>
|
|
33707
33707
|
|
|
33708
|
-
For each change above, find whether the consumer's changed call to the provider still works against the provider's actual contract. Emit the structured findings[]. Do not emit findings for consumer changes that still match the provider's real contract.`}let j_=[`NONE`,`LOW`,`MEDIUM`,`HIGH`,`CRITICAL`];function M_(e){let t=String(e??``).toUpperCase();return j_.includes(t)?t:`NONE`}function N_(e){let t=typeof e==`number`&&Number.isFinite(e)?e:0;return Math.max(0,Math.min(10,Math.round(t)))}function P_(e){return typeof e==`string`&&e.length>0?e:void 0}function F_(e){let t=Array.isArray(e?.findings)?e.findings:[],r=0,i=t.map(e=>{typeof e.verdict?.score==`number`&&Number.isFinite(e.verdict.score)||r++;let t=N_(e.verdict?.score);return{title:typeof e.title==`string`?e.title:`(untitled)`,severity:M_(e.severity),verdictScore:t,verdictReason:P_(e.verdict?.reason),consumerBefore:typeof e.consumerBefore==`string`?e.consumerBefore:``,consumerAfter:typeof e.consumerAfter==`string`?e.consumerAfter:``,consumerFile:P_(e.consumerFile),consumerExcerpt:P_(e.consumerExcerpt),providerContract:P_(e.providerContract),providerProductChangeId:P_(e.providerProductChangeId),affectedFlow:P_(e.affectedFlow),howToVerify:t>=o.CROSS_COMPONENT_REGRESSION_SCORE_THRESHOLD?P_(e.howToVerify):void 0,technicalRootCause:P_(e.technicalRootCause)}});return r>0&&n.logger.info.defaultLog(`[cross-component] ${r} of ${i.length} finding(s) had a missing/malformed verdict score — defaulted to 0 (non-breaking). Model output may be degraded.`),i}async function I_(e){let{query:t,getMessageContentBlocks:r,isResultMessage:a,isErrorResult:s}=await Promise.resolve().then(()=>lz()),c=e.changedSide===`consumer`?O_():T_(),l=t({prompt:e.changedSide===`consumer`?A_({rootPath:e.rootPath,providerRootPath:e.providerRootPath,providerProjectId:e.providerProjectId,consumerChanges:e.consumerChanges}):D_({rootPath:e.rootPath,providerProjectId:e.providerProjectId,providerRunId:e.providerRunId,providerChanges:e.providerChanges}),options:{model:o.CROSS_COMPONENT_MODEL,systemPrompt:c,allowedTools:[`Read`,`Grep`,`Glob`,`Bash`],permissionMode:`bypassPermissions`,allowDangerouslySkipPermissions:!0,maxBudgetUsd:e.maxBudgetUsd,maxTurns:e.maxTurns,cwd:e.rootPath,sessionId:(0,v.randomUUID)(),outputFormat:{type:`json_schema`,schema:S_},env:{...process.env,...i.buildAnthropicSdkEnv({proxyUrl:e.anthropicBaseUrl,jwtToken:e.jwtToken??``,requestId:n.logger.getRequestId()})}}}),u=0;for await(let t of l){if(!a(t)){let e=r(t);e!==void 0&&e.length>0&&(u++,i.logAgentActivity(`cross-component-hunter`,u,e));continue}if(s(t))throw Error(`[cross-component] Hunter error: ${t.subtype}`);let o=t.structured_output;if(o===void 0){let r=(t.result??``).slice(0,300);return n.logger.info.defaultLog(`[cross-component] Hunter returned no structured_output — treating as zero findings. stop_reason=${String(t.stop_reason)} result="${r}"`),{findings:[],costUsd:t.total_cost_usd,turns:t.num_turns,maxTurnsHit:t.num_turns>=e.maxTurns,tokens:i.ZERO_TOKENS,degraded:!0}}let c=F_(o);return n.logger.info.defaultLog(`[cross-component] Hunter completed: costUsd=${t.total_cost_usd} turns=${t.num_turns} findings=${c.length}`),{findings:c,costUsd:t.total_cost_usd,turns:t.num_turns,maxTurnsHit:t.num_turns>=e.maxTurns,tokens:i.extractCacheTokens(t),degraded:!1}}throw Error(`[cross-component] Hunter stream ended without a result message`)}var L_=class{name=`crossContractHunt`;async execute(e){let t=e.jobInput.crossComponent;if(t===void 0)throw Error(`[cross-component] CrossContractHuntStep requires jobInput.crossComponent`);let r=t.changedSide??`provider`,{changeCount:a,dispatchArgs:o}=this.buildDispatch(e,t,r);if(a===0)return n.logger.info.defaultLog(`[cross-component] No ${r}-side contract changes to check — skipping hunter (halt)`),e.findings=[],e.huntCostUsd=0,e.huntTokens=i.ZERO_TOKENS,e.huntTurns=0,e.huntMaxTurnsHit=!1,{costUsd:0,turns:0,maxTurnsHit:!1,tokens:i.ZERO_TOKENS,status:l_.Halt};let s=await I_(o);return e.findings=s.findings,e.huntCostUsd=s.costUsd,e.huntTokens=s.tokens,e.huntTurns=s.turns,e.huntMaxTurnsHit=s.maxTurnsHit,{costUsd:s.costUsd,turns:s.turns,maxTurnsHit:s.maxTurnsHit,tokens:s.tokens}}buildDispatch(e,t,n){let r={rootPath:e.rootPath,providerProjectId:t.providerProjectId,jwtToken:e.jwtToken,anthropicBaseUrl:e.anthropicBaseUrl};if(n===`consumer`){let t=h_(e);if(e.providerRootPath===void 0)throw Error(`[cross-component] consumer-direction hunt requires context.providerRootPath`);return{changeCount:t.length,dispatchArgs:{...r,changedSide:`consumer`,providerRootPath:e.providerRootPath,consumerChanges:t,maxTurns:o.CROSS_COMPONENT_CONSUMER_MAX_TURNS,maxBudgetUsd:o.CROSS_COMPONENT_CONSUMER_MAX_BUDGET_USD}}}let i=m_(e),a=t.providerRunId??``;if(a.length===0)throw Error(`[cross-component] provider-direction hunt requires a non-empty providerRunId`);return{changeCount:i.length,dispatchArgs:{...r,changedSide:`provider`,providerRunId:a,providerChanges:i,maxTurns:o.CROSS_COMPONENT_MAX_TURNS,maxBudgetUsd:o.CROSS_COMPONENT_MAX_BUDGET_USD}}}};let R_=e=>typeof e==`string`&&e.length>0?e:void 0;function z_(e,t){let n=String(e.severity??`NONE`).toUpperCase();if(n!==`NONE`)return{productChangeId:R_(e.id),title:typeof e.title==`string`?e.title:`(untitled)`,severity:n,productBefore:typeof e.productBefore==`string`?e.productBefore:``,productAfter:typeof e.productAfter==`string`?e.productAfter:``,verdict:e.verdict!==void 0&&typeof e.verdict.score==`number`?{score:e.verdict.score,reason:e.verdict.reason}:void 0,sourceFlowName:t,file:R_(e.file),hunkExcerpt:R_(e.hunkExcerpt)}}async function B_(e,t,r){let i=`/api/v1/regression/runs/${t}/full`,a=await e.get(i);if(!(0,m.isDefined)(a))throw Error(`[cross-component] ${r} run ${t} not found`);let o=[];for(let e of a.impacts??[]){let t=e.flow?.name??e.flow?.flowId??`(unknown flow)`;for(let n of e.productChanges??[]){let e=z_(n,t);e!==void 0&&o.push(e)}}return n.logger.info.defaultLog(`[cross-component] Loaded ${r} run ${t}: ${o.length} contract change(s) after dropping NONE-severity`),o}async function V_(e,t){return B_(e,t,`provider`)}async function H_(e,t){return B_(e,t,`consumer`)}var U_=class{name=`loadConsumerChanges`;async execute(e){let t=e.jobInput.crossComponent?.consumerRunId??``;if(t.length===0)throw Error(`[cross-component] LoadConsumerChangesStep requires jobInput.crossComponent.consumerRunId`);if(e.providerRootPath===void 0||e.providerRootPath.length===0){let n=e.jobInput.crossComponent?.providerSha??`<none>`;throw Error(`[cross-component] consumer direction requires a provider checkout, but none was provisioned (PROVIDER_CHECKOUT_DIR=${process.env.PROVIDER_CHECKOUT_DIR??`<unset>`}, providerSha=${n}, consumerRunId=${t})`)}return e.consumerChanges=await H_(e.apiService,t),u_}},W_=class{name=`loadProviderChanges`;async execute(e){let t=e.jobInput.crossComponent?.providerRunId??``;if(t.length===0)throw Error(`[cross-component] LoadProviderChangesStep requires jobInput.crossComponent.providerRunId`);return e.providerChanges=await V_(e.apiService,t),u_}};let G_={create(e){return new f_([e===`consumer`?new U_:new W_,new L_,new b_,new y_])}};function K_(e){let t=e.primary?.sourcePath;return(0,m.isDefined)(t)&&t.length>0?t:process.cwd()}function q_(e){if(e.crossComponent?.changedSide!==`consumer`)return;let t=process.env.PROVIDER_CHECKOUT_DIR;if(!(0,m.isDefined)(t)||t.length===0)return;let n=e.crossComponent.providerRepo?.rootPath??``;return n.length>0?I.default.join(t,n):t}async function J_(e,t,r,a,o,s,c){let l=Date.now();if(i.setAgentLogEnabled(s.agentLog??!1),s.compareSha.length===0)throw Error(`[cross-component] jobInput.compareSha (the consumer checkout SHA) is empty — the dispatch did not resolve a consumer SHA; aborting.`);let u=K_(s),d=s.crossComponent?.changedSide??`provider`,f=q_(s),p=s.crossComponent?.providerRepo,m=p===void 0?`<none>`:`${p.owner}/${p.repo}`;n.logger.info.defaultLog(`[cross-component] Starting (${d} direction): consumerProjectId=${s.projectId} providerRunId=${s.crossComponent?.providerRunId??`<none>`} providerRepo=${m} providerSha=${s.crossComponent?.providerSha??`<none>`} rootPath=${u} providerRootPath=${f??`<none>`}`);let h={reportsDir:e,rootPath:u,jwtToken:t,anthropicBaseUrl:r,apiService:a,globalConfigService:o,jobInput:s,compareBranch:c,startTime:l,providerRootPath:f,stepMetrics:[]};if(await G_.create(d).run(h),h.result===void 0)throw Error(`[cross-component] pipeline finished without producing a result (CrossComponentReportStep did not run)`);return{flowImpacts:[],catalogId:null,rootPath:u,changedFiles:[],branch:s.compareBranch.length>0?s.compareBranch:c??s.anchorBranch,headSha:s.compareSha.length>0?s.compareSha:void 0,anchorBranch:s.anchorBranch,anchorSha:s.anchorSha.length>0?s.anchorSha:void 0,runType:`PR`,stepsMetrics:h.stepMetrics,durationSeconds:(Date.now()-l)/1e3}}var Y_=class{constructor(e){this.steps=e}describe(){return this.steps.map(e=>e.name).join(` -> `)}async run(e){n.logger.info.defaultLog(`[regression-impact] Pipeline: ${this.describe()}`);let t=!1;for(let[r,i]of this.steps.entries()){let a=`${r+1}/${this.steps.length}`;if(t&&i.isTerminal!==!0){n.logger.info.defaultLog(`[regression-impact] Step ${a} "${i.name}" — SKIPPED (pipeline halted)`);continue}n.logger.info.defaultLog(`[regression-impact] Step ${a} "${i.name}" — START`);let s=Date.now(),c=await i.execute(e),l=(Date.now()-s)/1e3;e.stepMetrics.push(d_(i.name,c.costUsd,s,c.turns,c.maxTurnsHit,c.tokens,c.batches,c.maxBudgetHit??!1,c.totalFiles,c.mappedFiles,c.mappingBreakdown));let u=c.status===l_.Halt?` — HALT`:``,d=c.maxTurnsHit?` / maxTurnsHit`:``,f=o.shouldLogDiagnostics?`$${c.costUsd.toFixed(4)} / ${c.turns} turns / ${l.toFixed(2)}s${d}`:`${l.toFixed(2)}s`;n.logger.info.defaultLog(`[regression-impact] Step ${a} "${i.name}" — END (${f})${u}`),c.status===l_.Halt&&(t=!0)}return e}};function X_(e,t=20){return e.length<=t?e:[...e].sort((e,t)=>{let n=e.userOverride?.rank??1/0,r=t.userOverride?.rank??1/0;return n===r?e.rank-t.rank:n-r}).slice(0,t)}function Z_(e,t,r,i){if(i)return t;if((0,m.isDefined)(r)&&r.length>0)try{return o.resolveRefSha(e,r),r}catch{n.logger.info.defaultLog(`[regression-impact] anchorSha ${r} not found locally, falling back to branch`)}return o.ensureAnchorRef(e,t)}async function Q_(e,t,r){let i=r?.projectId??t.getProjectId();if(!(0,m.isDefined)(i)||i.length===0)return n.logger.info.defaultLog(`[regression-impact] No projectId — cannot load flow library`),null;try{n.logger.info.defaultLog(`[regression-impact] Loading flow library for projectId: ${i}`);let t=await e.get(`/api/v1/regression/flow-library/for-agent`,{params:{projectId:i,includeInactive:`false`}});return n.logger.info.defaultLog(`[regression-impact] Loaded library: ${t.flows.length} flows, latestCatalogId=${t.project.latestCatalogId??`(none)`}`),{project:t.project,flows:t.flows}}catch(e){return n.logger.info.defaultLog(`[regression-impact] Could not load flow library from backend: ${String(e)}`),null}}function $_(e){return{flowId:e.flowId,rank:e.rank,name:e.name,flowType:e.flowType??`OTHER`,entryPoints:Array.isArray(e.entryPoints)?e.entryPoints:[],description:e.description??``,importanceReason:e.importanceReason??``,trace:e.trace??{entryFiles:[],entrySymbols:[],calledModules:[],codeSnippet:``},scoring:e.scoring,productFlow:e.productFlow}}async function ev(e,t,n){let r=await Q_(e,t,n);if(!r)throw Error(`[regression-impact] Could not load flow library from backend. Ensure projectId is set and the project has flows.`);return tv(r,n)}function tv(e,t){if(t===null){let e=Error(`[regression-impact] jobInput is required — no global config fallback is allowed`);throw n.logger.error(e.message,e),e}let r=iv(t,`anchorBranch`),i=iv(t,`projectRootPath`),a=iv(t,`anchorSha`),o=X_(e.flows).map($_);return n.logger.info.defaultLog(`[regression-impact] Loaded library for project: ${e.project.projectId}`),n.logger.info.defaultLog(`[regression-impact] ${e.flows.length} active flows in library, analyzing top ${o.length}`),{bundle:e,anchorBranch:r,anchorSha:a,catalogId:e.project.latestCatalogId,projectType:e.project.projectType??`(unknown)`,flows:o,rootPath:i}}async function nv(e,t){n.logger.info.defaultLog(`[regression-impact] Loading library baseline from prior run: ${t}`);let r;try{r=await e.get(`/api/v1/regression/runs/${encodeURIComponent(t)}/library-baseline`)}catch(e){throw Error(`[regression-impact] Could not load library baseline for prior run ${t}. Ensure the run id is valid and belongs to this team. (${String(e)})`,{cause:e})}return n.logger.info.defaultLog(`[regression-impact] Loaded baseline: ${r.flows.length} flows, latestCatalogId=${r.project.latestCatalogId??`(none)`}`),{project:r.project,flows:r.flows}}async function rv(e,t,n){return tv(await nv(e,n),t)}function iv(e,t){let r=e[t]?.trim();if(!(0,m.isDefined)(r)||r.length===0){let e=Error(`[regression-impact] ${t} is missing from job input`);throw n.logger.error(e.message,e),e}return r}var av=class{name=`loadLibrary`;async execute(e){let{bundle:t,anchorBranch:r,anchorSha:i,catalogId:a,projectType:s,flows:c}=await ev(e.apiService,e.globalConfigService,e.jobInput);if(e.jobInput===null)throw Error(`[impact-pipeline] jobInput is required to resolve catalog roots`);let l;try{l=Rm(e.jobInput)}catch(e){throw Error(`[impact-pipeline] failed to resolve catalog roots: ${String(e)}`,{cause:e})}let u=l.cwd,d=Z_(u,r,i,e.isUncommitted),f=o.getCommitMessages(u,d),p=(0,m.isDefined)(i)?`, sha: ${i}`:``;return n.logger.info.defaultLog(`[regression-impact] Anchor: ${r} (resolved: ${d}${p})`),e.bundle=t,e.flows=c,e.catalogId=a,e.projectType=s,e.anchorBranch=r,e.anchorSha=i,e.resolvedAnchorBranch=d,e.rootPath=u,e.primarySource=l.primarySource,e.dependencyRoots=l.dependencyRoots,e.commitMessages=f,u_}};function ov(e){return{version:1,source:`library`,capturedAt:new Date().toISOString(),project:e.project,flows:e.flows}}async function sv(e,t,r,i,a){try{let o=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}}},...e.file===void 0?{}:{file:e.file},...e.hunkExcerpt===void 0?{}:{hunkExcerpt:e.hunkExcerpt},...e.hunterTypes===void 0?{}:{hunterTypes:e.hunterTypes},...e.needsConsumerVerification===!0?{needsConsumerVerification:!0}:{},...e.needsConsumerVerification===!0&&e.consumerVerificationReason!==void 0?{consumerVerificationReason:e.consumerVerificationReason}:{},...e.howToVerify===void 0?{}:{howToVerify:e.howToVerify}})),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}}),s=a?.projectId??i.getProjectId();if(!(0,m.isDefined)(s)||s.length===0)return n.logger.info.defaultLog(`[regression-impact] No projectId — cannot post run`),null;let c=ov(t),l=a?.baselineFromAnalysisId?.trim(),u={projectId:s,catalogId:t.project.latestCatalogId,libraryBaseline:c,...(0,m.isDefined)(l)&&l.length>0?{baselineFromAnalysisId:l}:{},anchorBranch:e.anchorBranch,runType:e.runType,branch:e.branch,headSha:e.headSha,anchorSha:e.anchorSha,changedFiles:e.changedFiles,stepsMetrics:e.stepsMetrics??[],flowImpacts:o,agentVersion:Nm,jobId:i.getJobId()},d=await r.post(`/api/v1/regression/runs`,u);return n.logger.info.defaultLog(`[regression-impact] Run posted to backend. runId: ${d.runId}`),d}catch(e){return n.logger.info.defaultLog(`[regression-impact] Failed to post run to backend: ${String(e)}`),null}}var cv=class{name=`post`;isTerminal=!0;async execute(e){if(e.result===void 0)throw Error(`[impact-pipeline] PostStep requires ctx.result — ReportStep must run before this step`);if(e.bundle===void 0)throw Error(`[impact-pipeline] PostStep requires ctx.bundle — LoadLibraryStep must run before this step`);let t=await sv(e.result,e.bundle,e.apiService,e.globalConfigService,e.jobInput);return t!==null&&(e.runId=t.runId),u_}};function lv(e,t,n){if(e===void 0)throw Error(`[impact-pipeline] ctx.${t} is unset — ${n} must run before this step`);return e}function uv(e){return lv(e.flows,`flows`,`LoadLibraryStep`)}function dv(e){return lv(e.rootPath,`rootPath`,`LoadLibraryStep`)}function fv(e){return lv(e.changedFiles,`changedFiles`,`PreFilterStep or MappingSnapshotReadStep`)}function pv(e){return lv(e.mappingResult,`mappingResult`,`MappingStep`)}function mv(e){return lv(e.flowImpacts,`flowImpacts`,`BuildImpactsStep`)}function hv(e,t){(0,y.mkdirSync)(t,{recursive:!0});let r=new Date().toISOString().replaceAll(/[:.]/g,`-`),i=I.default.basename(e.rootPath),a=I.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?`
|
|
33708
|
+
For each change above, find whether the consumer's changed call to the provider still works against the provider's actual contract. Emit the structured findings[]. Do not emit findings for consumer changes that still match the provider's real contract.`}let j_=[`NONE`,`LOW`,`MEDIUM`,`HIGH`,`CRITICAL`];function M_(e){let t=String(e??``).toUpperCase();return j_.includes(t)?t:`NONE`}function N_(e){let t=typeof e==`number`&&Number.isFinite(e)?e:0;return Math.max(0,Math.min(10,Math.round(t)))}function P_(e){return typeof e==`string`&&e.length>0?e:void 0}function F_(e){let t=Array.isArray(e?.findings)?e.findings:[],r=0,i=t.map(e=>{typeof e.verdict?.score==`number`&&Number.isFinite(e.verdict.score)||r++;let t=N_(e.verdict?.score);return{title:typeof e.title==`string`?e.title:`(untitled)`,severity:M_(e.severity),verdictScore:t,verdictReason:P_(e.verdict?.reason),consumerBefore:typeof e.consumerBefore==`string`?e.consumerBefore:``,consumerAfter:typeof e.consumerAfter==`string`?e.consumerAfter:``,consumerFile:P_(e.consumerFile),consumerExcerpt:P_(e.consumerExcerpt),providerContract:P_(e.providerContract),providerProductChangeId:P_(e.providerProductChangeId),affectedFlow:P_(e.affectedFlow),howToVerify:t>=o.CROSS_COMPONENT_REGRESSION_SCORE_THRESHOLD?P_(e.howToVerify):void 0,technicalRootCause:P_(e.technicalRootCause)}});return r>0&&n.logger.info.defaultLog(`[cross-component] ${r} of ${i.length} finding(s) had a missing/malformed verdict score — defaulted to 0 (non-breaking). Model output may be degraded.`),i}async function I_(e){let{query:t,getMessageContentBlocks:r,isResultMessage:a,isErrorResult:s}=await Promise.resolve().then(()=>lz()),c=e.changedSide===`consumer`?O_():T_(),l=t({prompt:e.changedSide===`consumer`?A_({rootPath:e.rootPath,providerRootPath:e.providerRootPath,providerProjectId:e.providerProjectId,consumerChanges:e.consumerChanges}):D_({rootPath:e.rootPath,providerProjectId:e.providerProjectId,providerRunId:e.providerRunId,providerChanges:e.providerChanges}),options:{model:o.CROSS_COMPONENT_MODEL,...o.REGRESSION_SONNET_ANALYZER_REASONING,systemPrompt:c,allowedTools:[`Read`,`Grep`,`Glob`,`Bash`],permissionMode:`bypassPermissions`,allowDangerouslySkipPermissions:!0,maxBudgetUsd:e.maxBudgetUsd,maxTurns:e.maxTurns,cwd:e.rootPath,sessionId:(0,v.randomUUID)(),outputFormat:{type:`json_schema`,schema:S_},env:{...process.env,...i.buildAnthropicSdkEnv({proxyUrl:e.anthropicBaseUrl,jwtToken:e.jwtToken??``,requestId:n.logger.getRequestId()})}}}),u=0;for await(let t of l){if(!a(t)){let e=r(t);e!==void 0&&e.length>0&&(u++,i.logAgentActivity(`cross-component-hunter`,u,e));continue}if(s(t))throw Error(`[cross-component] Hunter error: ${t.subtype}`);let o=t.structured_output;if(o===void 0){let r=(t.result??``).slice(0,300);return n.logger.info.defaultLog(`[cross-component] Hunter returned no structured_output — treating as zero findings. stop_reason=${String(t.stop_reason)} result="${r}"`),{findings:[],costUsd:t.total_cost_usd,turns:t.num_turns,maxTurnsHit:t.num_turns>=e.maxTurns,tokens:i.ZERO_TOKENS,degraded:!0}}let c=F_(o);return n.logger.info.defaultLog(`[cross-component] Hunter completed: costUsd=${t.total_cost_usd} turns=${t.num_turns} findings=${c.length}`),{findings:c,costUsd:t.total_cost_usd,turns:t.num_turns,maxTurnsHit:t.num_turns>=e.maxTurns,tokens:i.extractCacheTokens(t),degraded:!1}}throw Error(`[cross-component] Hunter stream ended without a result message`)}var L_=class{name=`crossContractHunt`;async execute(e){let t=e.jobInput.crossComponent;if(t===void 0)throw Error(`[cross-component] CrossContractHuntStep requires jobInput.crossComponent`);let r=t.changedSide??`provider`,{changeCount:a,dispatchArgs:o}=this.buildDispatch(e,t,r);if(a===0)return n.logger.info.defaultLog(`[cross-component] No ${r}-side contract changes to check — skipping hunter (halt)`),e.findings=[],e.huntCostUsd=0,e.huntTokens=i.ZERO_TOKENS,e.huntTurns=0,e.huntMaxTurnsHit=!1,{costUsd:0,turns:0,maxTurnsHit:!1,tokens:i.ZERO_TOKENS,status:l_.Halt};let s=await I_(o);return e.findings=s.findings,e.huntCostUsd=s.costUsd,e.huntTokens=s.tokens,e.huntTurns=s.turns,e.huntMaxTurnsHit=s.maxTurnsHit,{costUsd:s.costUsd,turns:s.turns,maxTurnsHit:s.maxTurnsHit,tokens:s.tokens}}buildDispatch(e,t,n){let r={rootPath:e.rootPath,providerProjectId:t.providerProjectId,jwtToken:e.jwtToken,anthropicBaseUrl:e.anthropicBaseUrl};if(n===`consumer`){let t=h_(e);if(e.providerRootPath===void 0)throw Error(`[cross-component] consumer-direction hunt requires context.providerRootPath`);return{changeCount:t.length,dispatchArgs:{...r,changedSide:`consumer`,providerRootPath:e.providerRootPath,consumerChanges:t,maxTurns:o.CROSS_COMPONENT_CONSUMER_MAX_TURNS,maxBudgetUsd:o.CROSS_COMPONENT_CONSUMER_MAX_BUDGET_USD}}}let i=m_(e),a=t.providerRunId??``;if(a.length===0)throw Error(`[cross-component] provider-direction hunt requires a non-empty providerRunId`);return{changeCount:i.length,dispatchArgs:{...r,changedSide:`provider`,providerRunId:a,providerChanges:i,maxTurns:o.CROSS_COMPONENT_MAX_TURNS,maxBudgetUsd:o.CROSS_COMPONENT_MAX_BUDGET_USD}}}};let R_=e=>typeof e==`string`&&e.length>0?e:void 0;function z_(e,t){let n=String(e.severity??`NONE`).toUpperCase();if(n!==`NONE`)return{productChangeId:R_(e.id),title:typeof e.title==`string`?e.title:`(untitled)`,severity:n,productBefore:typeof e.productBefore==`string`?e.productBefore:``,productAfter:typeof e.productAfter==`string`?e.productAfter:``,verdict:e.verdict!==void 0&&typeof e.verdict.score==`number`?{score:e.verdict.score,reason:e.verdict.reason}:void 0,sourceFlowName:t,file:R_(e.file),hunkExcerpt:R_(e.hunkExcerpt)}}async function B_(e,t,r){let i=`/api/v1/regression/runs/${t}/full`,a=await e.get(i);if(!(0,m.isDefined)(a))throw Error(`[cross-component] ${r} run ${t} not found`);let o=[];for(let e of a.impacts??[]){let t=e.flow?.name??e.flow?.flowId??`(unknown flow)`;for(let n of e.productChanges??[]){let e=z_(n,t);e!==void 0&&o.push(e)}}return n.logger.info.defaultLog(`[cross-component] Loaded ${r} run ${t}: ${o.length} contract change(s) after dropping NONE-severity`),o}async function V_(e,t){return B_(e,t,`provider`)}async function H_(e,t){return B_(e,t,`consumer`)}var U_=class{name=`loadConsumerChanges`;async execute(e){let t=e.jobInput.crossComponent?.consumerRunId??``;if(t.length===0)throw Error(`[cross-component] LoadConsumerChangesStep requires jobInput.crossComponent.consumerRunId`);if(e.providerRootPath===void 0||e.providerRootPath.length===0){let n=e.jobInput.crossComponent?.providerSha??`<none>`;throw Error(`[cross-component] consumer direction requires a provider checkout, but none was provisioned (PROVIDER_CHECKOUT_DIR=${process.env.PROVIDER_CHECKOUT_DIR??`<unset>`}, providerSha=${n}, consumerRunId=${t})`)}return e.consumerChanges=await H_(e.apiService,t),u_}},W_=class{name=`loadProviderChanges`;async execute(e){let t=e.jobInput.crossComponent?.providerRunId??``;if(t.length===0)throw Error(`[cross-component] LoadProviderChangesStep requires jobInput.crossComponent.providerRunId`);return e.providerChanges=await V_(e.apiService,t),u_}};let G_={create(e){return new f_([e===`consumer`?new U_:new W_,new L_,new b_,new y_])}};function K_(e){let t=e.primary?.sourcePath;return(0,m.isDefined)(t)&&t.length>0?t:process.cwd()}function q_(e){if(e.crossComponent?.changedSide!==`consumer`)return;let t=process.env.PROVIDER_CHECKOUT_DIR;if(!(0,m.isDefined)(t)||t.length===0)return;let n=e.crossComponent.providerRepo?.rootPath??``;return n.length>0?I.default.join(t,n):t}async function J_(e,t,r,a,o,s,c){let l=Date.now();if(i.setAgentLogEnabled(s.agentLog??!1),s.compareSha.length===0)throw Error(`[cross-component] jobInput.compareSha (the consumer checkout SHA) is empty — the dispatch did not resolve a consumer SHA; aborting.`);let u=K_(s),d=s.crossComponent?.changedSide??`provider`,f=q_(s),p=s.crossComponent?.providerRepo,m=p===void 0?`<none>`:`${p.owner}/${p.repo}`;n.logger.info.defaultLog(`[cross-component] Starting (${d} direction): consumerProjectId=${s.projectId} providerRunId=${s.crossComponent?.providerRunId??`<none>`} providerRepo=${m} providerSha=${s.crossComponent?.providerSha??`<none>`} rootPath=${u} providerRootPath=${f??`<none>`}`);let h={reportsDir:e,rootPath:u,jwtToken:t,anthropicBaseUrl:r,apiService:a,globalConfigService:o,jobInput:s,compareBranch:c,startTime:l,providerRootPath:f,stepMetrics:[]};if(await G_.create(d).run(h),h.result===void 0)throw Error(`[cross-component] pipeline finished without producing a result (CrossComponentReportStep did not run)`);return{flowImpacts:[],catalogId:null,rootPath:u,changedFiles:[],branch:s.compareBranch.length>0?s.compareBranch:c??s.anchorBranch,headSha:s.compareSha.length>0?s.compareSha:void 0,anchorBranch:s.anchorBranch,anchorSha:s.anchorSha.length>0?s.anchorSha:void 0,runType:`PR`,stepsMetrics:h.stepMetrics,durationSeconds:(Date.now()-l)/1e3}}var Y_=class{constructor(e){this.steps=e}describe(){return this.steps.map(e=>e.name).join(` -> `)}async run(e){n.logger.info.defaultLog(`[regression-impact] Pipeline: ${this.describe()}`);let t=!1;for(let[r,i]of this.steps.entries()){let a=`${r+1}/${this.steps.length}`;if(t&&i.isTerminal!==!0){n.logger.info.defaultLog(`[regression-impact] Step ${a} "${i.name}" — SKIPPED (pipeline halted)`);continue}n.logger.info.defaultLog(`[regression-impact] Step ${a} "${i.name}" — START`);let s=Date.now(),c=await i.execute(e),l=(Date.now()-s)/1e3;e.stepMetrics.push(d_(i.name,c.costUsd,s,c.turns,c.maxTurnsHit,c.tokens,c.batches,c.maxBudgetHit??!1,c.totalFiles,c.mappedFiles,c.mappingBreakdown));let u=c.status===l_.Halt?` — HALT`:``,d=c.maxTurnsHit?` / maxTurnsHit`:``,f=o.shouldLogDiagnostics?`$${c.costUsd.toFixed(4)} / ${c.turns} turns / ${l.toFixed(2)}s${d}`:`${l.toFixed(2)}s`;n.logger.info.defaultLog(`[regression-impact] Step ${a} "${i.name}" — END (${f})${u}`),c.status===l_.Halt&&(t=!0)}return e}};function X_(e,t=20){return e.length<=t?e:[...e].sort((e,t)=>{let n=e.userOverride?.rank??1/0,r=t.userOverride?.rank??1/0;return n===r?e.rank-t.rank:n-r}).slice(0,t)}function Z_(e,t,r,i){if(i)return t;if((0,m.isDefined)(r)&&r.length>0)try{return o.resolveRefSha(e,r),r}catch{n.logger.info.defaultLog(`[regression-impact] anchorSha ${r} not found locally, falling back to branch`)}return o.ensureAnchorRef(e,t)}async function Q_(e,t,r){let i=r?.projectId??t.getProjectId();if(!(0,m.isDefined)(i)||i.length===0)return n.logger.info.defaultLog(`[regression-impact] No projectId — cannot load flow library`),null;try{n.logger.info.defaultLog(`[regression-impact] Loading flow library for projectId: ${i}`);let t=await e.get(`/api/v1/regression/flow-library/for-agent`,{params:{projectId:i,includeInactive:`false`}});return n.logger.info.defaultLog(`[regression-impact] Loaded library: ${t.flows.length} flows, latestCatalogId=${t.project.latestCatalogId??`(none)`}`),{project:t.project,flows:t.flows}}catch(e){return n.logger.info.defaultLog(`[regression-impact] Could not load flow library from backend: ${String(e)}`),null}}function $_(e){return{flowId:e.flowId,rank:e.rank,name:e.name,flowType:e.flowType??`OTHER`,entryPoints:Array.isArray(e.entryPoints)?e.entryPoints:[],description:e.description??``,importanceReason:e.importanceReason??``,trace:e.trace??{entryFiles:[],entrySymbols:[],calledModules:[],codeSnippet:``},scoring:e.scoring,productFlow:e.productFlow}}async function ev(e,t,n){let r=await Q_(e,t,n);if(!r)throw Error(`[regression-impact] Could not load flow library from backend. Ensure projectId is set and the project has flows.`);return tv(r,n)}function tv(e,t){if(t===null){let e=Error(`[regression-impact] jobInput is required — no global config fallback is allowed`);throw n.logger.error(e.message,e),e}let r=iv(t,`anchorBranch`),i=iv(t,`projectRootPath`),a=iv(t,`anchorSha`),o=X_(e.flows).map($_);return n.logger.info.defaultLog(`[regression-impact] Loaded library for project: ${e.project.projectId}`),n.logger.info.defaultLog(`[regression-impact] ${e.flows.length} active flows in library, analyzing top ${o.length}`),{bundle:e,anchorBranch:r,anchorSha:a,catalogId:e.project.latestCatalogId,projectType:e.project.projectType??`(unknown)`,flows:o,rootPath:i}}async function nv(e,t){n.logger.info.defaultLog(`[regression-impact] Loading library baseline from prior run: ${t}`);let r;try{r=await e.get(`/api/v1/regression/runs/${encodeURIComponent(t)}/library-baseline`)}catch(e){throw Error(`[regression-impact] Could not load library baseline for prior run ${t}. Ensure the run id is valid and belongs to this team. (${String(e)})`,{cause:e})}return n.logger.info.defaultLog(`[regression-impact] Loaded baseline: ${r.flows.length} flows, latestCatalogId=${r.project.latestCatalogId??`(none)`}`),{project:r.project,flows:r.flows}}async function rv(e,t,n){return tv(await nv(e,n),t)}function iv(e,t){let r=e[t]?.trim();if(!(0,m.isDefined)(r)||r.length===0){let e=Error(`[regression-impact] ${t} is missing from job input`);throw n.logger.error(e.message,e),e}return r}var av=class{name=`loadLibrary`;async execute(e){let{bundle:t,anchorBranch:r,anchorSha:i,catalogId:a,projectType:s,flows:c}=await ev(e.apiService,e.globalConfigService,e.jobInput);if(e.jobInput===null)throw Error(`[impact-pipeline] jobInput is required to resolve catalog roots`);let l;try{l=Rm(e.jobInput)}catch(e){throw Error(`[impact-pipeline] failed to resolve catalog roots: ${String(e)}`,{cause:e})}let u=l.cwd,d=Z_(u,r,i,e.isUncommitted),f=o.getCommitMessages(u,d),p=(0,m.isDefined)(i)?`, sha: ${i}`:``;return n.logger.info.defaultLog(`[regression-impact] Anchor: ${r} (resolved: ${d}${p})`),e.bundle=t,e.flows=c,e.catalogId=a,e.projectType=s,e.anchorBranch=r,e.anchorSha=i,e.resolvedAnchorBranch=d,e.rootPath=u,e.primarySource=l.primarySource,e.dependencyRoots=l.dependencyRoots,e.commitMessages=f,u_}};function ov(e){return{version:1,source:`library`,capturedAt:new Date().toISOString(),project:e.project,flows:e.flows}}async function sv(e,t,r,i,a){try{let o=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}}},...e.file===void 0?{}:{file:e.file},...e.hunkExcerpt===void 0?{}:{hunkExcerpt:e.hunkExcerpt},...e.hunterTypes===void 0?{}:{hunterTypes:e.hunterTypes},...e.needsConsumerVerification===!0?{needsConsumerVerification:!0}:{},...e.needsConsumerVerification===!0&&e.consumerVerificationReason!==void 0?{consumerVerificationReason:e.consumerVerificationReason}:{},...e.howToVerify===void 0?{}:{howToVerify:e.howToVerify}})),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}}),s=a?.projectId??i.getProjectId();if(!(0,m.isDefined)(s)||s.length===0)return n.logger.info.defaultLog(`[regression-impact] No projectId — cannot post run`),null;let c=ov(t),l=a?.baselineFromAnalysisId?.trim(),u={projectId:s,catalogId:t.project.latestCatalogId,libraryBaseline:c,...(0,m.isDefined)(l)&&l.length>0?{baselineFromAnalysisId:l}:{},anchorBranch:e.anchorBranch,runType:e.runType,branch:e.branch,headSha:e.headSha,anchorSha:e.anchorSha,changedFiles:e.changedFiles,...e.changeDetection===void 0?{}:{changeDetection:e.changeDetection},stepsMetrics:e.stepsMetrics??[],flowImpacts:o,agentVersion:Nm,jobId:i.getJobId()},d=await r.post(`/api/v1/regression/runs`,u);return n.logger.info.defaultLog(`[regression-impact] Run posted to backend. runId: ${d.runId}`),d}catch(e){return n.logger.info.defaultLog(`[regression-impact] Failed to post run to backend: ${String(e)}`),null}}var cv=class{name=`post`;isTerminal=!0;async execute(e){if(e.result===void 0)throw Error(`[impact-pipeline] PostStep requires ctx.result — ReportStep must run before this step`);if(e.bundle===void 0)throw Error(`[impact-pipeline] PostStep requires ctx.bundle — LoadLibraryStep must run before this step`);let t=await sv(e.result,e.bundle,e.apiService,e.globalConfigService,e.jobInput);return t!==null&&(e.runId=t.runId),u_}};function lv(e,t,n){if(e===void 0)throw Error(`[impact-pipeline] ctx.${t} is unset — ${n} must run before this step`);return e}function uv(e){return lv(e.flows,`flows`,`LoadLibraryStep`)}function dv(e){return lv(e.rootPath,`rootPath`,`LoadLibraryStep`)}function fv(e){return lv(e.changedFiles,`changedFiles`,`PreFilterStep or MappingSnapshotReadStep`)}function pv(e){return lv(e.mappingResult,`mappingResult`,`MappingStep`)}function mv(e){return lv(e.flowImpacts,`flowImpacts`,`BuildImpactsStep`)}function hv(e,t){(0,y.mkdirSync)(t,{recursive:!0});let r=new Date().toISOString().replaceAll(/[:.]/g,`-`),i=I.default.basename(e.rootPath),a=I.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?`
|
|
33709
33709
|
|
|
33710
33710
|
**Technical changes:**
|
|
33711
33711
|
`+(i??[]).map(e=>{let t=e.confidence===`low`?` (low confidence)`:``;return`- \`${e.file}\`${t}\n - Before: ${e.techBefore}\n - After: ${e.techAfter}`}).join(`
|
|
@@ -33739,7 +33739,7 @@ ${o}
|
|
|
33739
33739
|
|---|---|---|---|---|
|
|
33740
33740
|
${e.flowImpacts.map(e=>{let t=e.haikuSeverity??`—`,n=e.haikuConfidence??`—`,r=(0,m.isDefined)(e.techChanges)?e.severity??`—`:`skipped`,i=e.affected?`**${e.severity??`AFFECTED`}**`:`NOT AFFECTED`;return`| ${e.flow.name} | ${t} | ${n} | ${r} | ${i} |`}).join(`
|
|
33741
33741
|
`)}
|
|
33742
|
-
`;(0,y.writeFileSync)(a,c,`utf8`),n.logger.info.defaultLog(`[regression-impact] Impact report saved to: ${a}`)}function gv(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,m.isDefined)(e.techChanges)),r=e.flowImpacts.filter(e=>!e.affected&&e.uncertain!==!0&&!(0,m.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)`),(0,m.isDefined)(e.incompleteFiles)&&e.incompleteFiles.length>0&&n.logger.info.defaultLog(`[regression-impact] ⚠ INCOMPLETE mapping for ${e.incompleteFiles.length} file(s) (batch aborted, e.g. max turns) — flow attribution is PARTIAL for: ${e.incompleteFiles.join(`, `)}`);let o=i.length,s=r.length,c=t.length;n.logger.info.defaultLog(`[regression-impact] Summary: ${o} of ${e.flowImpacts.length} flows affected (${s} resolved by filter, ${c} analyzed by Sonnet deep)`)}function _v(e){if(o.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})`)}}var vv=class{name=`report`;isTerminal=!0;async execute(e){let t=dv(e),n=fv(e),r=e.flowImpacts??uv(e).map(e=>({flow:e,affected:!1,changedFiles:[]}));if(e.branch===void 0||e.anchorBranch===void 0)throw Error(`[impact-pipeline] ReportStep requires branch/anchorBranch from prior steps`);_v(e.stepMetrics);let i={flowImpacts:r,catalogId:e.catalogId??null,rootPath:t,changedFiles:n,branch:e.jobInput?.compareBranch??e.compareBranch??e.branch,headSha:e.headSha,anchorBranch:e.anchorBranch,anchorSha:e.anchorSha,runType:e.runType,stepsMetrics:e.stepMetrics,durationSeconds:(Date.now()-e.startTime)/1e3,incompleteFiles:e.mappingResult?.incompleteFiles};return o.REGRESSION_SAVE_REPORT_FILES&&hv(i,e.reportsDir),gv(i),e.result=i,u_}};function yv(e,t,r,i){let a=r?.compareSha?.trim();if((0,m.isDefined)(a)&&a.length>0)return n.logger.info.defaultLog(`[regression-impact] Compare ref resolved from jobInput.compareSha: ${a}`),a;if((i??``).length>0)return n.logger.info.defaultLog(`[regression-impact] Compare ref resolved from compareBranch arg: ${i}`),i;let s=r?.compareBranch?.trim();if((0,m.isDefined)(s)&&s.length>0)return n.logger.info.defaultLog(`[regression-impact] Compare ref resolved from jobInput.compareBranch: ${s}`),s;let c=t.getContext()?.git?.compareBranch?.trim();if((0,m.isDefined)(c)&&c.length>0)return n.logger.info.defaultLog(`[regression-impact] Compare ref resolved from config git.compareBranch: ${c}`),c;let l=o.getCurrentBranch(e);return n.logger.info.defaultLog(`[regression-impact] Compare ref resolved from current branch (HEAD): ${l}`),l}function bv(e,t){let n=I.default.resolve(t),r=n.endsWith(I.default.sep)?n:n+I.default.sep;return e===n||e.startsWith(r)}function xv(e,t,n){let r=[],i=[];for(let a of e){let e=I.default.resolve(n,a);t.some(t=>bv(e,t))?r.push(a):i.push(a)}return{kept:r,dropped:i}}async function Sv(e,t,r,i,a,s,c=[e]){let{files:l,description:u}=i===`LOCAL`?o.getUncommittedFiles(e):o.getChangedFiles(e,t,r),{kept:d,dropped:f}=xv(l,c,o.getRepoRoot(e));if(f.length>0){let t=f.slice(0,3).join(`, `),r=f.length>3?`, ... (${f.length-3} more)`:``;n.logger.info.defaultLog(`[regression-impact] Dropped ${f.length} out-of-root file(s) (rootPath: ${e}): ${t}${r}`)}d.length===0&&l.length>0&&n.logger.info.defaultLog(`[regression-impact] All ${l.length} changed files are outside rootPath (${e}) — nothing to analyze.`);let p=await i_(d,a,s,e);return{changedFiles:p.sourceFiles,compareDescription:u,preFilterCostUsd:p.costUsd,preFilterTurns:p.turns,preFilterMaxTurnsHit:p.maxTurnsHit}}var Cv=class{name=`resolveCompare`;execute(e){let t=dv(e),r=yv(t,e.globalConfigService,e.jobInput,e.compareBranch),i=e.jobInput?.label?.trim()??e.globalConfigService.getLabel()?.trim(),a=(0,m.isDefined)(i)&&i.length>0?i:void 0,s;if(!e.isUncommitted)try{s=o.resolveRefSha(t,r)}catch{n.logger.info.defaultLog(`[regression-impact] Could not resolve headSha for '${r}'`)}return n.logger.info.defaultLog(`[regression-impact] Compare branch: ${r}, label: ${a??`(not set, using branch)`}, headSha: ${s??`(none)`}`),e.branch=r,e.label=a,e.headSha=s,Promise.resolve(u_)}};let wv=/^[+-]\s*(?:export\s+)?(?:default\s+)?(?:async\s+)?(?:function|class|const|let)\s+([A-Za-z_]\w*)/;function Tv(e){let t=new Set;for(let n of e.split(`
|
|
33742
|
+
`;(0,y.writeFileSync)(a,c,`utf8`),n.logger.info.defaultLog(`[regression-impact] Impact report saved to: ${a}`)}function gv(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,m.isDefined)(e.techChanges)),r=e.flowImpacts.filter(e=>!e.affected&&e.uncertain!==!0&&!(0,m.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)`),(0,m.isDefined)(e.incompleteFiles)&&e.incompleteFiles.length>0&&n.logger.info.defaultLog(`[regression-impact] ⚠ INCOMPLETE mapping for ${e.incompleteFiles.length} file(s) (batch aborted, e.g. max turns) — flow attribution is PARTIAL for: ${e.incompleteFiles.join(`, `)}`);let o=i.length,s=r.length,c=t.length;n.logger.info.defaultLog(`[regression-impact] Summary: ${o} of ${e.flowImpacts.length} flows affected (${s} resolved by filter, ${c} analyzed by Sonnet deep)`)}function _v(e){if(o.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})`)}}var vv=class{name=`report`;isTerminal=!0;async execute(e){let t=dv(e),n=fv(e),r=e.flowImpacts??uv(e).map(e=>({flow:e,affected:!1,changedFiles:[]}));if(e.branch===void 0||e.anchorBranch===void 0)throw Error(`[impact-pipeline] ReportStep requires branch/anchorBranch from prior steps`);_v(e.stepMetrics);let i={flowImpacts:r,catalogId:e.catalogId??null,rootPath:t,changedFiles:n,changeDetection:e.changeDetection??{detected:n.length,droppedOutOfRoot:0,droppedByPreFilter:0},branch:e.jobInput?.compareBranch??e.compareBranch??e.branch,headSha:e.headSha,anchorBranch:e.anchorBranch,anchorSha:e.anchorSha,runType:e.runType,stepsMetrics:e.stepMetrics,durationSeconds:(Date.now()-e.startTime)/1e3,incompleteFiles:e.mappingResult?.incompleteFiles};return o.REGRESSION_SAVE_REPORT_FILES&&hv(i,e.reportsDir),gv(i),e.result=i,u_}};function yv(e,t,r,i){let a=r?.compareSha?.trim();if((0,m.isDefined)(a)&&a.length>0)return n.logger.info.defaultLog(`[regression-impact] Compare ref resolved from jobInput.compareSha: ${a}`),a;if((i??``).length>0)return n.logger.info.defaultLog(`[regression-impact] Compare ref resolved from compareBranch arg: ${i}`),i;let s=r?.compareBranch?.trim();if((0,m.isDefined)(s)&&s.length>0)return n.logger.info.defaultLog(`[regression-impact] Compare ref resolved from jobInput.compareBranch: ${s}`),s;let c=t.getContext()?.git?.compareBranch?.trim();if((0,m.isDefined)(c)&&c.length>0)return n.logger.info.defaultLog(`[regression-impact] Compare ref resolved from config git.compareBranch: ${c}`),c;let l=o.getCurrentBranch(e);return n.logger.info.defaultLog(`[regression-impact] Compare ref resolved from current branch (HEAD): ${l}`),l}function bv(e,t){let n=I.default.resolve(t),r=n.endsWith(I.default.sep)?n:n+I.default.sep;return e===n||e.startsWith(r)}function xv(e,t,n){let r=[],i=[];for(let a of e){let e=I.default.resolve(n,a);t.some(t=>bv(e,t))?r.push(a):i.push(a)}return{kept:r,dropped:i}}async function Sv(e,t,r,i,a,s,c=[e]){let{files:l,description:u}=i===`LOCAL`?o.getUncommittedFiles(e):o.getChangedFiles(e,t,r),{kept:d,dropped:f}=xv(l,c,o.getRepoRoot(e));if(f.length>0){let t=f.slice(0,3).join(`, `),r=f.length>3?`, ... (${f.length-3} more)`:``;n.logger.info.defaultLog(`[regression-impact] Dropped ${f.length} out-of-root file(s) (rootPath: ${e}): ${t}${r}`)}d.length===0&&l.length>0&&n.logger.info.defaultLog(`[regression-impact] All ${l.length} changed files are outside rootPath (${e}) — nothing to analyze.`);let p=await i_(d,a,s,e);return{changedFiles:p.sourceFiles,compareDescription:u,changeDetection:{detected:l.length,droppedOutOfRoot:f.length,droppedByPreFilter:Math.max(0,d.length-p.sourceFiles.length)},preFilterCostUsd:p.costUsd,preFilterTurns:p.turns,preFilterMaxTurnsHit:p.maxTurnsHit}}var Cv=class{name=`resolveCompare`;execute(e){let t=dv(e),r=yv(t,e.globalConfigService,e.jobInput,e.compareBranch),i=e.jobInput?.label?.trim()??e.globalConfigService.getLabel()?.trim(),a=(0,m.isDefined)(i)&&i.length>0?i:void 0,s;if(!e.isUncommitted)try{s=o.resolveRefSha(t,r)}catch{n.logger.info.defaultLog(`[regression-impact] Could not resolve headSha for '${r}'`)}return n.logger.info.defaultLog(`[regression-impact] Compare branch: ${r}, label: ${a??`(not set, using branch)`}, headSha: ${s??`(none)`}`),e.branch=r,e.label=a,e.headSha=s,Promise.resolve(u_)}};let wv=/^[+-]\s*(?:export\s+)?(?:default\s+)?(?:async\s+)?(?:function|class|const|let)\s+([A-Za-z_]\w*)/;function Tv(e){let t=new Set;for(let n of e.split(`
|
|
33743
33743
|
`)){let e=wv.exec(n);e&&t.add(e[1])}return[...t]}function Ev(e,t,n,r,i,a){return i?[(0,S.execFileSync)(`git`,[`diff`,`--`,e],a),(0,S.execFileSync)(`git`,[`diff`,`--cached`,`--`,e],a)].filter(e=>e.length>0).join(`
|
|
33744
33744
|
`):(0,S.execFileSync)(`git`,[`diff`,`${r}...${n}`,`--`,e],a)}function Dv(e,t,n,r){let i;try{i=(0,S.execFileSync)(`git`,[`grep`,`-n`,`-w`,e,`--`,`*.ts`,`*.tsx`,`*.js`,`*.jsx`],r)}catch{return[]}let a=[];for(let r of i.split(`
|
|
33745
33745
|
`)){if(r.length===0)continue;let i=r.split(`:`);if(i.length<3)continue;let[o,s]=i;n.has(o)||a.push({symbol:e,changedFile:t,callerFile:o,callerLine:Number.parseInt(s,10)})}return a}function Ov(e,t,r,i,a){let s;try{s=o.getRepoRoot(t)}catch{return[]}let c=r;if(!a)try{c=o.ensureCompareBranchRef(t,r)}catch{return[]}let l={cwd:s,encoding:`utf8`,timeout:3e4,maxBuffer:5242880},u=new Set(e),d=[],f=0;for(let r of e){if(f>=o.HUNT_FIRST_BLAST_RADIUS_MAX_SYMBOL_LOOKUPS)break;let e;try{e=Ev(r,t,c,i,a,l)}catch{continue}let s=Tv(e);for(let e of s){if(f>=o.HUNT_FIRST_BLAST_RADIUS_MAX_SYMBOL_LOOKUPS){n.logger.info.defaultLog(`[regression-impact] Blast-radius sweep hit its symbol-lookup cap (${o.HUNT_FIRST_BLAST_RADIUS_MAX_SYMBOL_LOOKUPS}) — returning a partial sweep, not every changed symbol was checked for external callers.`);break}f++,d.push(...Dv(e,r,u,l))}}return d}var kv=class{name=`blastRadiusSweep`;async execute(e){let t=dv(e);if(e.branch===void 0||e.resolvedAnchorBranch===void 0)throw Error(`[impact-pipeline] BlastRadiusSweepStep requires branch/resolvedAnchorBranch`);let{files:n,description:r}=e.isUncommitted?o.getUncommittedFiles(t):o.getChangedFiles(t,e.branch,e.resolvedAnchorBranch);return e.changedFiles=n,e.compareDescription=r,e.blastRadiusFindings=n.length===0?[]:Ov(n,t,e.branch,e.resolvedAnchorBranch,e.isUncommitted),u_}};let Av=[`NONE`,`LOW`,`MEDIUM`,`HIGH`,`CRITICAL`];function jv(e){return e.severity===`NONE`&&e.verdictScore===void 0}function Mv(e){if(e.length===0)return;let t=e.reduce((e,t)=>Av.indexOf(t.severity)>Av.indexOf(e)?t.severity:e,`NONE`);return t===`NONE`&&e.some(e=>jv(e))?`LOW`:t}function Nv(){return{flowId:o.HUNT_FIRST_SENTINEL_FLOW_ID,rank:1,name:o.HUNT_FIRST_SENTINEL_FLOW_NAME,flowType:`OTHER`,entryPoints:[],description:`Findings from the hunt-first impact-analysis command that aren't attributed to any cataloged flow.`,trace:{entryFiles:[],entrySymbols:[],calledModules:[],codeSnippet:``},importanceReason:`Sentinel bucket — importance reflects the underlying findings, not this row itself.`}}function Pv(e){return{title:e.title,productBefore:e.behaviorBefore,productAfter:e.behaviorAfter,confidence:e.confidence,severity:e.severity,...e.verdictScore===void 0?{}:{verdictScore:e.verdictScore},...e.verdictReason===void 0?{}:{verdictReason:e.verdictReason},file:e.file,hunkExcerpt:e.hunkExcerpt,hunterTypes:e.hunterTypes}}var Fv=class{name=`buildSentinelImpact`;async execute(e){if(e.sentinelFlowId===void 0)throw Error(`[impact-pipeline] BuildSentinelImpactStep requires ctx.sentinelFlowId — EnsureSentinelFlowStep must run before this step`);let t=e.scoredHuntFindings??[],n=t.map(Pv);return e.flowImpacts=[{flow:Nv(),affected:t.length>0,severity:Mv(t),changedFiles:e.changedFiles??[],productChanges:n,techChanges:[]}],u_}};let Iv=/^API request failed: 409\b/;function Lv(e){return e instanceof Error&&Iv.test(e.message)}async function Rv(e,t,r){try{await e.post(`/api/v1/regression/flow-library`,{projectId:r,flowId:o.HUNT_FIRST_SENTINEL_FLOW_ID,name:o.HUNT_FIRST_SENTINEL_FLOW_NAME,description:`Findings from the hunt-first impact-analysis command that aren't attributed to any cataloged flow.`,importance:`MEDIUM`,importanceReason:`Sentinel bucket — importance reflects the underlying findings, not this row itself.`,rank:1}),n.logger.info.defaultLog(`[regression-impact] Created sentinel flow "${o.HUNT_FIRST_SENTINEL_FLOW_ID}" for project ${r}`)}catch(e){if(Lv(e)){n.logger.info.defaultLog(`[regression-impact] Sentinel flow "${o.HUNT_FIRST_SENTINEL_FLOW_ID}" already exists for project ${r}`);return}throw e}}var zv=class{name=`ensureSentinelFlow`;async execute(e){let t=e.jobInput?.projectId??e.globalConfigService.getProjectId();if(t===void 0||t.length===0)throw Error(`[impact-pipeline] EnsureSentinelFlowStep requires a projectId`);await Rv(e.apiService,e.globalConfigService,t),e.sentinelFlowId=o.HUNT_FIRST_SENTINEL_FLOW_ID;let r=e.bundle;if(r!==void 0&&!r.flows.some(e=>e.flowId===o.HUNT_FIRST_SENTINEL_FLOW_ID)){let t=(await Q_(e.apiService,e.globalConfigService,e.jobInput))?.flows.find(e=>e.flowId===o.HUNT_FIRST_SENTINEL_FLOW_ID);t===void 0?n.logger.info.defaultLog(`[regression-impact] Sentinel flow "${o.HUNT_FIRST_SENTINEL_FLOW_ID}" still missing from the flow library after ensureSentinelFlow — this run's findings may not display on the web UI`):r.flows.push(t)}return u_}};let Bv=[`security`,`performance`,`data-integrity`,`mechanical-correctness`];if(o.HUNT_FIRST_HUNTER_CONCURRENCY!==Bv.length)throw Error(`[hunt-first] HUNT_FIRST_HUNTER_CONCURRENCY (${o.HUNT_FIRST_HUNTER_CONCURRENCY}) must equal HUNT_FIRST_HUNTER_TYPES.length (${Bv.length})`);function Vv(e,t){return e>o.HUNT_FIRST_PANEL_FILE_THRESHOLD||t>o.HUNT_FIRST_PANEL_LINE_THRESHOLD}let Hv={security:`Focus on SECURITY regressions: removed or weakened auth/authz checks, newly
|
|
@@ -33814,7 +33814,7 @@ External callers of changed symbols found outside the changed files
|
|
|
33814
33814
|
${r}
|
|
33815
33815
|
|
|
33816
33816
|
Report every regression you find using the schema described in your
|
|
33817
|
-
instructions.`}function Gv(e){return e===void 0?0:typeof e==`string`?e.length:e.reduce((e,t)=>{let n=t.text;return e+(typeof n==`string`?n.length:0)},0)}var Kv=class{toolNameByCallId=new Map;totalChars=0;largestChars=0;largestToolName=``;observe(e){for(let t of e)if(t.type===`tool_use`&&t.id!==void 0&&t.name!==void 0)this.toolNameByCallId.set(t.id,t.name);else if(t.type===`tool_result`&&t.tool_use_id!==void 0){let e=Gv(t.content),r=this.toolNameByCallId.get(t.tool_use_id);r===void 0&&n.logger.info.defaultLog(`[regression-impact] tool_result for unknown tool_use_id ${t.tool_use_id} — SDK message ordering may be unexpected`),this.totalChars+=e,e>this.largestChars&&(this.largestChars=e,this.largestToolName=r??`unknown`)}}summary(){return this.totalChars===0?`no tool output observed before failing`:`total_tool_output_chars=${this.totalChars} largest_tool_result_chars=${this.largestChars}(${this.largestToolName})`}};async function qv(e){let{query:t,getMessageContentBlocks:a,isResultMessage:s,isErrorResult:c}=await Promise.resolve().then(()=>lz()),l=Wv({rootPath:e.rootPath,branch:e.branch,resolvedAnchorBranch:e.resolvedAnchorBranch,changedFiles:e.changedFiles,blastRadiusFindings:e.blastRadiusFindings,isUncommitted:e.isUncommitted}),u=hd({rootPath:e.rootPath,anchorRef:e.resolvedAnchorBranch,testFilePaths:e.changedFiles.filter(e=>r.isTestFile(e))}),d=t({prompt:l,options:{model:o.HUNT_FIRST_HUNTER_MODEL,systemPrompt:Uv(e.hunterType),allowedTools:[`Read`,`Grep`,`Glob`,`Bash`],permissionMode:`bypassPermissions`,allowDangerouslySkipPermissions:!0,maxBudgetUsd:o.HUNT_FIRST_HUNTER_MAX_BUDGET_USD,maxTurns:o.HUNT_FIRST_HUNTER_MAX_TURNS,cwd:e.rootPath,sessionId:(0,v.randomUUID)(),outputFormat:{type:`json_schema`,schema:i.HUNT_FINDING_OUTPUT_SCHEMA},env:{...process.env,...i.buildAnthropicSdkEnv({proxyUrl:e.anthropicBaseUrl,jwtToken:e.jwtToken??``,requestId:n.logger.getRequestId()})},hooks:{PreToolUse:[{matcher:`Read|Grep|Bash`,hooks:[u]}]}}}),f=`hunt-panel (${e.hunterType})`,p=0,m=new Kv;for await(let t of d){if(!s(t)){let e=a(t);e!==void 0&&e.length>0&&(p++,i.logAgentActivity(f,p,e),m.observe(e));continue}if(c(t))throw Error(`[regression-impact] Hunter (${e.hunterType}) error: ${t.subtype}`);let r=t.structured_output;if(r===void 0){let r=(t.result??``).slice(0,300),a=`stop_reason=${String(t.stop_reason)} permission_denials=${t.permission_denials?.length??0} result="${r}" ${m.summary()}`;return n.logger.info.defaultLog(`[regression-impact] Hunter (${e.hunterType}) returned no structured_output — treating as zero findings. ${a}`),{findings:[],costUsd:t.total_cost_usd,turns:t.num_turns,maxTurnsHit:t.num_turns>=o.HUNT_FIRST_HUNTER_MAX_TURNS,tokens:i.extractCacheTokens(t),degraded:!0,degradedReason:a}}let l=i.extractCacheTokens(t);return n.logger.info.defaultLog(`[regression-impact] Hunter (${e.hunterType}) completed: costUsd=${t.total_cost_usd} turns=${t.num_turns} findings=${r.findings.length}`),{findings:r.findings,costUsd:t.total_cost_usd,turns:t.num_turns,maxTurnsHit:t.num_turns>=o.HUNT_FIRST_HUNTER_MAX_TURNS,tokens:l,degraded:!1}}throw Error(`[regression-impact] Hunter (${e.hunterType}) stream ended without a result message`)}async function Jv(e){let t=Vv(e.filesChanged,e.linesChanged),r=t?[...Bv]:[`generalist`],i=t?`panel mode (${Bv.length} lenses)`:`single generalist hunter`;n.logger.info.defaultLog(`[regression-impact] Hunt panel: ${i} (${e.filesChanged} files, ${e.linesChanged} lines)`);let a=new A.default({concurrency:o.HUNT_FIRST_HUNTER_CONCURRENCY}),s=[],c=[],l=[],u=[],d=0,f=0,p=!1,m=0,h=0,g=0,_=0;return await Promise.all(r.map(t=>a.add(async()=>{try{let n=await qv({hunterType:t,rootPath:e.rootPath,branch:e.branch,resolvedAnchorBranch:e.resolvedAnchorBranch,changedFiles:e.changedFiles,blastRadiusFindings:e.blastRadiusFindings,jwtToken:e.jwtToken,anthropicBaseUrl:e.anthropicBaseUrl,isUncommitted:e.isUncommitted});d+=n.costUsd,f+=n.turns,p||=n.maxTurnsHit,m+=n.tokens.inputTokens,h+=n.tokens.outputTokens,g+=n.tokens.cacheReadTokens,_+=n.tokens.cacheCreationTokens,n.degraded&&l.push({hunterType:t,costUsd:n.costUsd,turns:n.turns,maxTurnsHit:n.maxTurnsHit,tokens:n.tokens,reason:n.degradedReason??`unknown`}),u.push({hunterType:t,costUsd:n.costUsd,turns:n.turns,maxTurnsHit:n.maxTurnsHit,tokens:n.tokens,degraded:n.degraded});let r=t===`generalist`?[]:[t];s.push(...n.findings.map(e=>({...e,hunterTypes:r})))}catch(e){n.logger.info.defaultLog(`[regression-impact] Hunter (${t}) crashed: ${String(e)}`),c.push(t)}}))),{findings:s,costUsd:d,turns:f,maxTurnsHit:p,failedHunterTypes:c,degradedHunters:l,tokens:{inputTokens:m,outputTokens:h,cacheReadTokens:g,cacheCreationTokens:_},hunterMetrics:u}}function Yv(e,t,n){let r=e.map(e=>({label:`hunter (${e}) — CRASHED`,costUsd:0,turns:0,maxTurnsHit:!1,maxBudgetHit:!1,tokens:i.ZERO_TOKENS})),a=t.map(e=>({label:`hunter (${e.hunterType}) — DEGRADED (no structured_output, treated as zero findings): ${e.reason}`,costUsd:e.costUsd,turns:e.turns,maxTurnsHit:e.maxTurnsHit,maxBudgetHit:!1,tokens:e.tokens})),o=n.map(e=>({label:`hunter (${e.hunterType}) — SUCCESS`,costUsd:e.costUsd,turns:e.turns,maxTurnsHit:e.maxTurnsHit,maxBudgetHit:!1,tokens:e.tokens}));return[...r,...a,...o]}var Xv=class{name=`huntPanel`;async execute(e){let t=dv(e),n=fv(e);if(e.branch===void 0||e.resolvedAnchorBranch===void 0)throw Error(`[impact-pipeline] HuntPanelStep requires branch/resolvedAnchorBranch`);let r=e.isUncommitted?e.branch:o.ensureCompareBranchRef(t,e.branch),i=o.getChangedLineCount(t,r,e.resolvedAnchorBranch,e.isUncommitted),a=await Jv({rootPath:t,branch:r,resolvedAnchorBranch:e.resolvedAnchorBranch,changedFiles:n,blastRadiusFindings:e.blastRadiusFindings??[],filesChanged:n.length,linesChanged:i,jwtToken:e.jwtToken,anthropicBaseUrl:e.anthropicBaseUrl,isUncommitted:e.isUncommitted});e.rawHuntFindings=a.findings;let s=Yv(a.failedHunterTypes,a.degradedHunters,a.hunterMetrics.filter(e=>!e.degraded));return{costUsd:a.costUsd,turns:a.turns,maxTurnsHit:a.maxTurnsHit,tokens:a.tokens,...s.length>0?{batches:s}:{}}}};let Zv=/@@\s+-\d+(?:,\d+)?\s+\+(\d+)(?:,(\d+))?\s+@@/;function Qv(e){let t=Zv.exec(e);if(t===null)return;let n=Number.parseInt(t[1],10),r=t.at(2),i=r===void 0?1:Number.parseInt(r,10);return{start:n,end:n+Math.max(i,1)-1}}function $v(e,t){return e.start-2<=t.end&&t.start-2<=e.end}function ey(e){return`${e.file}::${e.hunkExcerpt}`}function ty(e,t){return e.finding.file===t.finding.file?e.range!==void 0&&t.range!==void 0?$v(e.range,t.range):ey(e.finding)===ey(t.finding):!1}function ny(e){let t=e.map(e=>({finding:e,range:Qv(e.hunkExcerpt)})),n=[];for(let e of t){let t=n.find(t=>t.some(t=>ty(t,e)));t===void 0?n.push([e]):t.push(e)}return n.map(e=>e.map(e=>e.finding))}function ry(e){let[t]=e,n=[...new Set(e.flatMap(e=>e.hunterTypes))];return{...t,hunterTypes:n}}function iy(e){return ny(e).map(ry)}var ay=class{name=`mergeFindings`;execute(e){return e.mergedHuntFindings=iy(e.rawHuntFindings??[]),Promise.resolve(u_)}},oy=class{name=`requireResolvedShas`;async execute(e){if(e.anchorSha===void 0)throw Error(`[impact-pipeline] RequireResolvedShasStep: anchorSha did not resolve — cannot hunt without a diff`);if(!e.isUncommitted&&e.headSha===void 0)throw Error(`[impact-pipeline] RequireResolvedShasStep: headSha did not resolve — cannot hunt without a diff`);return u_}};function sy(e){let t=e.map((e,t)=>`[${t}] file: ${e.file}\n before: ${e.behaviorBefore}\n after: ${e.behaviorAfter}\n category: ${e.category}\n hunter confidence: ${e.confidence}\n rationale: ${e.rationale}`).join(`
|
|
33817
|
+
instructions.`}function Gv(e){return e===void 0?0:typeof e==`string`?e.length:e.reduce((e,t)=>{let n=t.text;return e+(typeof n==`string`?n.length:0)},0)}var Kv=class{toolNameByCallId=new Map;totalChars=0;largestChars=0;largestToolName=``;observe(e){for(let t of e)if(t.type===`tool_use`&&t.id!==void 0&&t.name!==void 0)this.toolNameByCallId.set(t.id,t.name);else if(t.type===`tool_result`&&t.tool_use_id!==void 0){let e=Gv(t.content),r=this.toolNameByCallId.get(t.tool_use_id);r===void 0&&n.logger.info.defaultLog(`[regression-impact] tool_result for unknown tool_use_id ${t.tool_use_id} — SDK message ordering may be unexpected`),this.totalChars+=e,e>this.largestChars&&(this.largestChars=e,this.largestToolName=r??`unknown`)}}summary(){return this.totalChars===0?`no tool output observed before failing`:`total_tool_output_chars=${this.totalChars} largest_tool_result_chars=${this.largestChars}(${this.largestToolName})`}};async function qv(e){let{query:t,getMessageContentBlocks:a,isResultMessage:s,isErrorResult:c}=await Promise.resolve().then(()=>lz()),l=Wv({rootPath:e.rootPath,branch:e.branch,resolvedAnchorBranch:e.resolvedAnchorBranch,changedFiles:e.changedFiles,blastRadiusFindings:e.blastRadiusFindings,isUncommitted:e.isUncommitted}),u=hd({rootPath:e.rootPath,anchorRef:e.resolvedAnchorBranch,testFilePaths:e.changedFiles.filter(e=>r.isTestFile(e))}),d=t({prompt:l,options:{model:o.HUNT_FIRST_HUNTER_MODEL,...o.REGRESSION_SONNET_ANALYZER_REASONING,systemPrompt:Uv(e.hunterType),allowedTools:[`Read`,`Grep`,`Glob`,`Bash`],permissionMode:`bypassPermissions`,allowDangerouslySkipPermissions:!0,maxBudgetUsd:o.HUNT_FIRST_HUNTER_MAX_BUDGET_USD,maxTurns:o.HUNT_FIRST_HUNTER_MAX_TURNS,cwd:e.rootPath,sessionId:(0,v.randomUUID)(),outputFormat:{type:`json_schema`,schema:i.HUNT_FINDING_OUTPUT_SCHEMA},env:{...process.env,...i.buildAnthropicSdkEnv({proxyUrl:e.anthropicBaseUrl,jwtToken:e.jwtToken??``,requestId:n.logger.getRequestId()})},hooks:{PreToolUse:[{matcher:`Read|Grep|Bash`,hooks:[u]}]}}}),f=`hunt-panel (${e.hunterType})`,p=0,m=new Kv;for await(let t of d){if(!s(t)){let e=a(t);e!==void 0&&e.length>0&&(p++,i.logAgentActivity(f,p,e),m.observe(e));continue}if(c(t))throw Error(`[regression-impact] Hunter (${e.hunterType}) error: ${t.subtype}`);let r=t.structured_output;if(r===void 0){let r=(t.result??``).slice(0,300),a=`stop_reason=${String(t.stop_reason)} permission_denials=${t.permission_denials?.length??0} result="${r}" ${m.summary()}`;return n.logger.info.defaultLog(`[regression-impact] Hunter (${e.hunterType}) returned no structured_output — treating as zero findings. ${a}`),{findings:[],costUsd:t.total_cost_usd,turns:t.num_turns,maxTurnsHit:t.num_turns>=o.HUNT_FIRST_HUNTER_MAX_TURNS,tokens:i.extractCacheTokens(t),degraded:!0,degradedReason:a}}let l=i.extractCacheTokens(t);return n.logger.info.defaultLog(`[regression-impact] Hunter (${e.hunterType}) completed: costUsd=${t.total_cost_usd} turns=${t.num_turns} findings=${r.findings.length}`),{findings:r.findings,costUsd:t.total_cost_usd,turns:t.num_turns,maxTurnsHit:t.num_turns>=o.HUNT_FIRST_HUNTER_MAX_TURNS,tokens:l,degraded:!1}}throw Error(`[regression-impact] Hunter (${e.hunterType}) stream ended without a result message`)}async function Jv(e){let t=Vv(e.filesChanged,e.linesChanged),r=t?[...Bv]:[`generalist`],i=t?`panel mode (${Bv.length} lenses)`:`single generalist hunter`;n.logger.info.defaultLog(`[regression-impact] Hunt panel: ${i} (${e.filesChanged} files, ${e.linesChanged} lines)`);let a=new A.default({concurrency:o.HUNT_FIRST_HUNTER_CONCURRENCY}),s=[],c=[],l=[],u=[],d=0,f=0,p=!1,m=0,h=0,g=0,_=0;return await Promise.all(r.map(t=>a.add(async()=>{try{let n=await qv({hunterType:t,rootPath:e.rootPath,branch:e.branch,resolvedAnchorBranch:e.resolvedAnchorBranch,changedFiles:e.changedFiles,blastRadiusFindings:e.blastRadiusFindings,jwtToken:e.jwtToken,anthropicBaseUrl:e.anthropicBaseUrl,isUncommitted:e.isUncommitted});d+=n.costUsd,f+=n.turns,p||=n.maxTurnsHit,m+=n.tokens.inputTokens,h+=n.tokens.outputTokens,g+=n.tokens.cacheReadTokens,_+=n.tokens.cacheCreationTokens,n.degraded&&l.push({hunterType:t,costUsd:n.costUsd,turns:n.turns,maxTurnsHit:n.maxTurnsHit,tokens:n.tokens,reason:n.degradedReason??`unknown`}),u.push({hunterType:t,costUsd:n.costUsd,turns:n.turns,maxTurnsHit:n.maxTurnsHit,tokens:n.tokens,degraded:n.degraded});let r=t===`generalist`?[]:[t];s.push(...n.findings.map(e=>({...e,hunterTypes:r})))}catch(e){n.logger.info.defaultLog(`[regression-impact] Hunter (${t}) crashed: ${String(e)}`),c.push(t)}}))),{findings:s,costUsd:d,turns:f,maxTurnsHit:p,failedHunterTypes:c,degradedHunters:l,tokens:{inputTokens:m,outputTokens:h,cacheReadTokens:g,cacheCreationTokens:_},hunterMetrics:u}}function Yv(e,t,n){let r=e.map(e=>({label:`hunter (${e}) — CRASHED`,costUsd:0,turns:0,maxTurnsHit:!1,maxBudgetHit:!1,tokens:i.ZERO_TOKENS})),a=t.map(e=>({label:`hunter (${e.hunterType}) — DEGRADED (no structured_output, treated as zero findings): ${e.reason}`,costUsd:e.costUsd,turns:e.turns,maxTurnsHit:e.maxTurnsHit,maxBudgetHit:!1,tokens:e.tokens})),o=n.map(e=>({label:`hunter (${e.hunterType}) — SUCCESS`,costUsd:e.costUsd,turns:e.turns,maxTurnsHit:e.maxTurnsHit,maxBudgetHit:!1,tokens:e.tokens}));return[...r,...a,...o]}var Xv=class{name=`huntPanel`;async execute(e){let t=dv(e),n=fv(e);if(e.branch===void 0||e.resolvedAnchorBranch===void 0)throw Error(`[impact-pipeline] HuntPanelStep requires branch/resolvedAnchorBranch`);let r=e.isUncommitted?e.branch:o.ensureCompareBranchRef(t,e.branch),i=o.getChangedLineCount(t,r,e.resolvedAnchorBranch,e.isUncommitted),a=await Jv({rootPath:t,branch:r,resolvedAnchorBranch:e.resolvedAnchorBranch,changedFiles:n,blastRadiusFindings:e.blastRadiusFindings??[],filesChanged:n.length,linesChanged:i,jwtToken:e.jwtToken,anthropicBaseUrl:e.anthropicBaseUrl,isUncommitted:e.isUncommitted});e.rawHuntFindings=a.findings;let s=Yv(a.failedHunterTypes,a.degradedHunters,a.hunterMetrics.filter(e=>!e.degraded));return{costUsd:a.costUsd,turns:a.turns,maxTurnsHit:a.maxTurnsHit,tokens:a.tokens,...s.length>0?{batches:s}:{}}}};let Zv=/@@\s+-\d+(?:,\d+)?\s+\+(\d+)(?:,(\d+))?\s+@@/;function Qv(e){let t=Zv.exec(e);if(t===null)return;let n=Number.parseInt(t[1],10),r=t.at(2),i=r===void 0?1:Number.parseInt(r,10);return{start:n,end:n+Math.max(i,1)-1}}function $v(e,t){return e.start-2<=t.end&&t.start-2<=e.end}function ey(e){return`${e.file}::${e.hunkExcerpt}`}function ty(e,t){return e.finding.file===t.finding.file?e.range!==void 0&&t.range!==void 0?$v(e.range,t.range):ey(e.finding)===ey(t.finding):!1}function ny(e){let t=e.map(e=>({finding:e,range:Qv(e.hunkExcerpt)})),n=[];for(let e of t){let t=n.find(t=>t.some(t=>ty(t,e)));t===void 0?n.push([e]):t.push(e)}return n.map(e=>e.map(e=>e.finding))}function ry(e){let[t]=e,n=[...new Set(e.flatMap(e=>e.hunterTypes))];return{...t,hunterTypes:n}}function iy(e){return ny(e).map(ry)}var ay=class{name=`mergeFindings`;execute(e){return e.mergedHuntFindings=iy(e.rawHuntFindings??[]),Promise.resolve(u_)}},oy=class{name=`requireResolvedShas`;async execute(e){if(e.anchorSha===void 0)throw Error(`[impact-pipeline] RequireResolvedShasStep: anchorSha did not resolve — cannot hunt without a diff`);if(!e.isUncommitted&&e.headSha===void 0)throw Error(`[impact-pipeline] RequireResolvedShasStep: headSha did not resolve — cannot hunt without a diff`);return u_}};function sy(e){let t=e.map((e,t)=>`[${t}] file: ${e.file}\n before: ${e.behaviorBefore}\n after: ${e.behaviorAfter}\n category: ${e.category}\n hunter confidence: ${e.confidence}\n rationale: ${e.rationale}`).join(`
|
|
33818
33818
|
|
|
33819
33819
|
`);return`Score each of the following ${e.length} regression findings from an
|
|
33820
33820
|
independent code review. For EACH finding (by its [index]), assign:
|
|
@@ -33836,7 +33836,7 @@ Findings:
|
|
|
33836
33836
|
|
|
33837
33837
|
${t}
|
|
33838
33838
|
|
|
33839
|
-
Return one score entry per finding, using the same index.`}async function cy(e,t){let{query:r,isResultMessage:a,isErrorResult:s}=await Promise.resolve().then(()=>lz()),c=r({prompt:sy(e),options:{model:o.HUNT_FIRST_HUNTER_MODEL,systemPrompt:`You are a calibrated severity scorer for a batch of already-identified code regressions.`,allowedTools:[],permissionMode:`bypassPermissions`,allowDangerouslySkipPermissions:!0,maxBudgetUsd:o.HUNT_FIRST_SCORING_MAX_BUDGET_USD,maxTurns:o.HUNT_FIRST_SCORING_MAX_TURNS,cwd:t.rootPath,sessionId:(0,v.randomUUID)(),outputFormat:{type:`json_schema`,schema:i.HUNT_SCORING_OUTPUT_SCHEMA},env:{...process.env,...i.buildAnthropicSdkEnv({proxyUrl:t.anthropicBaseUrl,jwtToken:t.jwtToken??``,requestId:n.logger.getRequestId()})}}});for await(let e of c){if(!a(e))continue;if(s(e))throw Error(`[regression-impact] Scoring error: ${e.subtype}`);let t=e.structured_output;if(t===void 0)throw Error(`[regression-impact] Scoring returned no structured_output`);return{scores:t.scores,costUsd:e.total_cost_usd,turns:e.num_turns,maxTurnsHit:e.num_turns>=o.HUNT_FIRST_SCORING_MAX_TURNS,tokens:i.extractCacheTokens(e)}}throw Error(`[regression-impact] Scoring stream ended without a result message`)}async function ly(e,t){if(e.length===0)return{scored:[],costUsd:0,turns:0,maxTurnsHit:!1,isScoringFailed:!1,tokens:i.ZERO_TOKENS};let r,a=!1;try{r=await cy(e,t)}catch(i){n.logger.info.defaultLog(`[regression-impact] Scoring call failed, retrying once: ${String(i)}`);try{r=await cy(e,t)}catch(e){a=!0,n.logger.info.defaultLog(`[regression-impact] Scoring retry also failed, falling back to NONE for all findings: ${String(e)}`)}}let o=new Map((r?.scores??[]).map(e=>[e.index,e]));return{scored:e.map((e,t)=>{let n=o.get(t);return n===void 0?{...e,severity:`NONE`}:{...e,severity:n.severity,verdictScore:n.verdictScore,verdictReason:n.verdictReason}}),costUsd:r?.costUsd??0,turns:r?.turns??0,maxTurnsHit:r?.maxTurnsHit??!1,isScoringFailed:a,tokens:r?.tokens??i.ZERO_TOKENS}}function uy(e){return e?[{label:`scoring — FAILED (all findings floored to NONE)`,costUsd:0,turns:0,maxTurnsHit:!1,maxBudgetHit:!1,tokens:i.ZERO_TOKENS}]:[]}var dy=class{name=`scoreFindings`;async execute(e){let t=dv(e),n=await ly(e.mergedHuntFindings??[],{rootPath:t,jwtToken:e.jwtToken,anthropicBaseUrl:e.anthropicBaseUrl});e.scoredHuntFindings=n.scored;let r=uy(n.isScoringFailed);return{costUsd:n.costUsd,turns:n.turns,maxTurnsHit:n.maxTurnsHit,tokens:n.tokens,...r.length>0?{batches:r}:{}}}};let fy={create(){return new Y_([new av,new Cv,new oy,new zv,new kv,new Xv,new ay,new dy,new Fv,new vv,new cv])}};async function py(e,t,n,r,a,o,s,c){let l=Date.now(),u=t===`LOCAL`;i.setAgentLogEnabled(s?.agentLog??!1);let d={reportsDir:e,runType:t,isUncommitted:u,jwtToken:n,anthropicBaseUrl:r,apiService:a,globalConfigService:o,jobInput:s,compareBranch:c,startTime:l,stepMetrics:[]};if(await fy.create().run(d),d.result===void 0)throw Error(`[hunt-first-impact] pipeline finished without producing a result (ReportStep did not run)`);return d.result}function my(e){return I.default.join(e,`reports`,`mapping-cache`,`latest.mapping.json`)}function hy(e){return(0,y.existsSync)(my(e))}function gy(e){let t={};for(let[n,r]of e)t[n]=[...r];return t}function _y(e){return new Map(Object.entries(e).map(([e,t])=>[e,new Set(t)]))}function vy(e){let t={};if(e===void 0)return t;for(let[n,r]of e)t[n]=Object.fromEntries(r);return t}function yy(e){return new Map(Object.entries(e).map(([e,t])=>[e,new Map(Object.entries(t))]))}function by(e){let t=my(e);if((0,y.existsSync)(t))try{let e=JSON.parse((0,y.readFileSync)(t,`utf8`));if(e.version!==1){n.logger.info.defaultLog(`[regression-impact] Mapping cache at ${t} has unexpected version — ignoring.`);return}return n.logger.info.defaultLog(`[regression-impact] Mapping cache HIT — skipping mapping, loaded from ${t}`+(o.shouldLogDiagnostics?` (original mapping cost was $${e.costUsd.toFixed(4)} / ${e.turns} turns)`:``)),{flowFileMap:_y(e.flowFileMap),flowFileReasons:yy(e.flowFileReasons),costUsd:0,turns:0,maxTurnsHit:!1}}catch(e){n.logger.info.defaultLog(`[regression-impact] Failed to read mapping cache ${t}: ${String(e)}`);return}}function xy(e,t,r){let i=my(e);try{(0,y.mkdirSync)(I.default.dirname(i),{recursive:!0});let e={version:1,inputs:t,flowFileMap:gy(r.flowFileMap),flowFileReasons:vy(r.flowFileReasons),costUsd:r.costUsd,turns:r.turns,maxTurnsHit:r.maxTurnsHit};(0,y.writeFileSync)(i,JSON.stringify(e,null,2),`utf8`),n.logger.info.defaultLog(`[regression-impact] Mapping result cached → ${i}`)}catch(e){n.logger.info.defaultLog(`[regression-impact] Failed to write mapping cache ${i}: ${String(e)}`)}}function Sy(e){let t=[e.isRegressionFirst&&`regression-first`,e.isRegressionFirstV2&&`regression-first-2`,e.isRegressionFirstV3&&`regression-first-3`,e.isRegressionFirstV2Adj&&`regression-first-2-adj`,e.isRegressionFirstSingle&&`regression-first-single`,e.isRegressionFirstMono&&`regression-first-mono`,e.isRegressionFirstExperiment&&`regression-first-experiment`].filter(e=>e!==!1);if(t.length>1)throw Error(`[impact-pipeline] regression-first variants are mutually exclusive but ${t.length} were set: ${t.join(`, `)}`)}function Cy(e,t,n,r,i,a=!1,s=!1,c=!1,l=!1,u=!1,d=!1,f=!1){let p=[`agentic`,`agentic-ast`,`shallow`];if(i!==void 0&&!p.includes(i))throw Error(`[impact-pipeline] unsupported mapping strategy override "${i}" — only ${p.join(`, `)} are wired`);let m=o.REGRESSION_IMPACT_DEV_MAPPING_SNAPSHOT,h=m&&e!==void 0?hy(e):!1;Sy({isRegressionFirst:a,isRegressionFirstV2:s,isRegressionFirstV3:c,isRegressionFirstV2Adj:l,isRegressionFirstSingle:u,isRegressionFirstMono:d,isRegressionFirstExperiment:f});let g=n?.trim();return{baselineFromAnalysisId:g!==void 0&&g.length>0?g:void 0,mappingStrategy:i??o.REGRESSION_IMPACT_MAPPING_STRATEGY,deepMode:t??o.REGRESSION_IMPACT_DEEP_MODE,contractMode:r,pass2Grouped:o.REGRESSION_IMPACT_PASS2_GROUPED,skipPass1:o.REGRESSION_IMPACT_SKIP_PASS1,calibrationEnabled:o.REGRESSION_IMPACT_CALIBRATION_ENABLED,stopAfterMapping:o.REGRESSION_IMPACT_STOP_AFTER_MAPPING,stopAfterPass1:o.REGRESSION_IMPACT_STOP_AFTER_PASS1,residualRoughMap:o.REGRESSION_IMPACT_RESIDUAL_ROUGH_MAP,devMappingSnapshotResume:m&&h,devMappingSnapshotWrite:m&&!h,regressionFirst:a,regressionFirstV2:s,regressionFirstV3:c,regressionFirstV2Adj:l,regressionFirstSingle:u,regressionFirstMono:d,regressionFirstExperiment:f}}function wy(e,t){if(e===null)return{primarySource:t,dependencyRoots:[]};try{let t=Rm(e);return{primarySource:t.primarySource,dependencyRoots:t.dependencyRoots}}catch(e){return n.logger.info.defaultLog(`[regression-first] could not resolve project scope from job input — falling back to rootPath (${t}): ${String(e)}`),{primarySource:t,dependencyRoots:[]}}}function Ty(e,t){return t.length===0?`## Relevant boundary
|
|
33839
|
+
Return one score entry per finding, using the same index.`}async function cy(e,t){let{query:r,isResultMessage:a,isErrorResult:s}=await Promise.resolve().then(()=>lz()),c=r({prompt:sy(e),options:{model:o.HUNT_FIRST_HUNTER_MODEL,...o.REGRESSION_SONNET_SCORER_REASONING,systemPrompt:`You are a calibrated severity scorer for a batch of already-identified code regressions.`,allowedTools:[],permissionMode:`bypassPermissions`,allowDangerouslySkipPermissions:!0,maxBudgetUsd:o.HUNT_FIRST_SCORING_MAX_BUDGET_USD,maxTurns:o.HUNT_FIRST_SCORING_MAX_TURNS,cwd:t.rootPath,sessionId:(0,v.randomUUID)(),outputFormat:{type:`json_schema`,schema:i.HUNT_SCORING_OUTPUT_SCHEMA},env:{...process.env,...i.buildAnthropicSdkEnv({proxyUrl:t.anthropicBaseUrl,jwtToken:t.jwtToken??``,requestId:n.logger.getRequestId()})}}});for await(let e of c){if(!a(e))continue;if(s(e))throw Error(`[regression-impact] Scoring error: ${e.subtype}`);let t=e.structured_output;if(t===void 0)throw Error(`[regression-impact] Scoring returned no structured_output`);return{scores:t.scores,costUsd:e.total_cost_usd,turns:e.num_turns,maxTurnsHit:e.num_turns>=o.HUNT_FIRST_SCORING_MAX_TURNS,tokens:i.extractCacheTokens(e)}}throw Error(`[regression-impact] Scoring stream ended without a result message`)}async function ly(e,t){if(e.length===0)return{scored:[],costUsd:0,turns:0,maxTurnsHit:!1,isScoringFailed:!1,tokens:i.ZERO_TOKENS};let r,a=!1;try{r=await cy(e,t)}catch(i){n.logger.info.defaultLog(`[regression-impact] Scoring call failed, retrying once: ${String(i)}`);try{r=await cy(e,t)}catch(e){a=!0,n.logger.info.defaultLog(`[regression-impact] Scoring retry also failed, falling back to NONE for all findings: ${String(e)}`)}}let o=new Map((r?.scores??[]).map(e=>[e.index,e]));return{scored:e.map((e,t)=>{let n=o.get(t);return n===void 0?{...e,severity:`NONE`}:{...e,severity:n.severity,verdictScore:n.verdictScore,verdictReason:n.verdictReason}}),costUsd:r?.costUsd??0,turns:r?.turns??0,maxTurnsHit:r?.maxTurnsHit??!1,isScoringFailed:a,tokens:r?.tokens??i.ZERO_TOKENS}}function uy(e){return e?[{label:`scoring — FAILED (all findings floored to NONE)`,costUsd:0,turns:0,maxTurnsHit:!1,maxBudgetHit:!1,tokens:i.ZERO_TOKENS}]:[]}var dy=class{name=`scoreFindings`;async execute(e){let t=dv(e),n=await ly(e.mergedHuntFindings??[],{rootPath:t,jwtToken:e.jwtToken,anthropicBaseUrl:e.anthropicBaseUrl});e.scoredHuntFindings=n.scored;let r=uy(n.isScoringFailed);return{costUsd:n.costUsd,turns:n.turns,maxTurnsHit:n.maxTurnsHit,tokens:n.tokens,...r.length>0?{batches:r}:{}}}};let fy={create(){return new Y_([new av,new Cv,new oy,new zv,new kv,new Xv,new ay,new dy,new Fv,new vv,new cv])}};async function py(e,t,n,r,a,o,s,c){let l=Date.now(),u=t===`LOCAL`;i.setAgentLogEnabled(s?.agentLog??!1);let d={reportsDir:e,runType:t,isUncommitted:u,jwtToken:n,anthropicBaseUrl:r,apiService:a,globalConfigService:o,jobInput:s,compareBranch:c,startTime:l,stepMetrics:[]};if(await fy.create().run(d),d.result===void 0)throw Error(`[hunt-first-impact] pipeline finished without producing a result (ReportStep did not run)`);return d.result}function my(e){return I.default.join(e,`reports`,`mapping-cache`,`latest.mapping.json`)}function hy(e){return(0,y.existsSync)(my(e))}function gy(e){let t={};for(let[n,r]of e)t[n]=[...r];return t}function _y(e){return new Map(Object.entries(e).map(([e,t])=>[e,new Set(t)]))}function vy(e){let t={};if(e===void 0)return t;for(let[n,r]of e)t[n]=Object.fromEntries(r);return t}function yy(e){return new Map(Object.entries(e).map(([e,t])=>[e,new Map(Object.entries(t))]))}function by(e){let t=my(e);if((0,y.existsSync)(t))try{let e=JSON.parse((0,y.readFileSync)(t,`utf8`));if(e.version!==1){n.logger.info.defaultLog(`[regression-impact] Mapping cache at ${t} has unexpected version — ignoring.`);return}return n.logger.info.defaultLog(`[regression-impact] Mapping cache HIT — skipping mapping, loaded from ${t}`+(o.shouldLogDiagnostics?` (original mapping cost was $${e.costUsd.toFixed(4)} / ${e.turns} turns)`:``)),{flowFileMap:_y(e.flowFileMap),flowFileReasons:yy(e.flowFileReasons),costUsd:0,turns:0,maxTurnsHit:!1}}catch(e){n.logger.info.defaultLog(`[regression-impact] Failed to read mapping cache ${t}: ${String(e)}`);return}}function xy(e,t,r){let i=my(e);try{(0,y.mkdirSync)(I.default.dirname(i),{recursive:!0});let e={version:1,inputs:t,flowFileMap:gy(r.flowFileMap),flowFileReasons:vy(r.flowFileReasons),costUsd:r.costUsd,turns:r.turns,maxTurnsHit:r.maxTurnsHit};(0,y.writeFileSync)(i,JSON.stringify(e,null,2),`utf8`),n.logger.info.defaultLog(`[regression-impact] Mapping result cached → ${i}`)}catch(e){n.logger.info.defaultLog(`[regression-impact] Failed to write mapping cache ${i}: ${String(e)}`)}}function Sy(e){let t=[e.isRegressionFirst&&`regression-first`,e.isRegressionFirstV2&&`regression-first-2`,e.isRegressionFirstV3&&`regression-first-3`,e.isRegressionFirstV2Adj&&`regression-first-2-adj`,e.isRegressionFirstSingle&&`regression-first-single`,e.isRegressionFirstMono&&`regression-first-mono`,e.isRegressionFirstExperiment&&`regression-first-experiment`].filter(e=>e!==!1);if(t.length>1)throw Error(`[impact-pipeline] regression-first variants are mutually exclusive but ${t.length} were set: ${t.join(`, `)}`)}function Cy(e,t,n,r,i,a=!1,s=!1,c=!1,l=!1,u=!1,d=!1,f=!1){let p=[`agentic`,`agentic-ast`,`shallow`];if(i!==void 0&&!p.includes(i))throw Error(`[impact-pipeline] unsupported mapping strategy override "${i}" — only ${p.join(`, `)} are wired`);let m=o.REGRESSION_IMPACT_DEV_MAPPING_SNAPSHOT,h=m&&e!==void 0?hy(e):!1;Sy({isRegressionFirst:a,isRegressionFirstV2:s,isRegressionFirstV3:c,isRegressionFirstV2Adj:l,isRegressionFirstSingle:u,isRegressionFirstMono:d,isRegressionFirstExperiment:f});let g=n?.trim();return{baselineFromAnalysisId:g!==void 0&&g.length>0?g:void 0,mappingStrategy:i??o.REGRESSION_IMPACT_MAPPING_STRATEGY,deepMode:t??o.REGRESSION_IMPACT_DEEP_MODE,contractMode:r,pass2Grouped:o.REGRESSION_IMPACT_PASS2_GROUPED,skipPass1:o.REGRESSION_IMPACT_SKIP_PASS1,calibrationEnabled:o.REGRESSION_IMPACT_CALIBRATION_ENABLED,stopAfterMapping:o.REGRESSION_IMPACT_STOP_AFTER_MAPPING,stopAfterPass1:o.REGRESSION_IMPACT_STOP_AFTER_PASS1,residualRoughMap:o.REGRESSION_IMPACT_RESIDUAL_ROUGH_MAP,devMappingSnapshotResume:m&&h,devMappingSnapshotWrite:m&&!h,regressionFirst:a,regressionFirstV2:s,regressionFirstV3:c,regressionFirstV2Adj:l,regressionFirstSingle:u,regressionFirstMono:d,regressionFirstExperiment:f}}function wy(e,t){if(e===null)return{primarySource:t,dependencyRoots:[]};try{let t=Rm(e);return{primarySource:t.primarySource,dependencyRoots:t.dependencyRoots}}catch(e){return n.logger.info.defaultLog(`[regression-first] could not resolve project scope from job input — falling back to rootPath (${t}): ${String(e)}`),{primarySource:t,dependencyRoots:[]}}}function Ty(e,t){return t.length===0?`## Relevant boundary
|
|
33840
33840
|
Primary source code (the project whose behavior you are judging): ${e}
|
|
33841
33841
|
Focus your reading on this path as the scope of the source code. Use your judgment on whether you need to look beyond it — e.g. to understand the project type, framework, or a library it depends on — to confirm a finding.`:`## Relevant boundary
|
|
33842
33842
|
Primary source code (the project whose behavior you are judging): ${e}
|
|
@@ -33920,7 +33920,7 @@ ${s}
|
|
|
33920
33920
|
|
|
33921
33921
|
${Oy(e,r,i)}
|
|
33922
33922
|
|
|
33923
|
-
${c}`,tools:a?[`Read`,`Grep`,`Glob`,`Bash`]:[`Read`,`Grep`,`Glob`,`Bash`,`Agent`],model:o.REGRESSION_FIRST_MODEL,maxTurns:e.maxTurns??o.REGRESSION_FIRST_CATEGORY_MAX_TURNS}}let Ay=[{name:`api-contract`,focus:`API/interface CONTRACT changes: a request/response shape, a route/endpoint, an HTTP status code, a function/method SIGNATURE, or a public return type changed in a way a caller or client could observe. Examples of the KIND to hunt: a 207 becomes 200; a required response field dropped; a param added/removed/reordered; a return type widened/narrowed. Focus ONLY on contract-level changes callers/clients depend on.`},{name:`schema-drift`,focus:`SCHEMA / data-shape DRIFT: a field made optional/required, a type widened or narrowed, nullability flipped, an enum case added/removed, a validation constraint loosened/tightened, a serialization shape changed (DTO / model / API schema). Focus ONLY on data-shape/validation drift and whether a consumer still copes with the new shape.`},{name:`auth-guard`,focus:`AUTH / SECURITY / GUARD changes: an authentication or authorization check removed or weakened, a permission/role gate dropped, a validation/guard the flow relied on removed, a security-relevant condition inverted, a fail-closed path turned fail-open. Focus ONLY on guards/gates and access control. A removed or fail-open guard is high severity.`},{name:`behavior-logic`,focus:'BEHAVIOR / LOGIC changes: a default value flipped (e.g. `?? false` → `?? true`), a conditional or operator changed, branch logic altered, a side-effect added/removed/reordered, a "mark done/success" that now runs before the operation that justifies it. Focus ONLY on control-flow / value / sequencing logic changes and their observable outcome.'},{name:`data-integrity`,focus:`DATA-INTEGRITY / ATOMICITY changes: two or more writes that must all succeed but are no longer atomic, a "done means persisted" guarantee broken, a race/ordering hazard introduced, a partial-failure now hidden as success, a persisted state that can now diverge from reported state. Focus ONLY on integrity/atomicity/persistence guarantees.`},{name:`other-behavior`,focus:`CATCH-ALL: any REAL behavior change that does NOT squarely fit api-contract, schema-drift, auth-guard, behavior-logic, or data-integrity. Your job is the recall backstop — report a genuine behavior change here rather than let it fall between categories. Pure no-ops (rename/reformat/import-reorder/log-reword with identical behavior) still get reported, at score 1-2 per the shared rubric.`}],jy={name:`product-intent`,maxTurns:o.REGRESSION_FIRST_PRODUCT_INTENT_MAX_TURNS,focus:`INTENT-SCOPE regressions: a change that is technically correct AND matches its commit, but whose ACTUAL reach is WIDER than the intent the commit describes — so it silently alters behavior for callers/flows the author never mentioned. You are NOT checking whether the code is correct or crashes (the other specialists do that). You ASSUME the diff is technically sound and does exactly what its commit says. Your ONE job: decide whether the change's real reach exceeds its stated scope, and whether the new behavior is APPROPRIATE at every reach point — not just the one the commit names. Classic shape: "feat: X for flow A" that also changes shared code flow B depends on, silently altering B.`,extraDirective:`## YOUR PROCEDURE — this is different from the other agents; follow it exactly
|
|
33923
|
+
${c}`,tools:a?[`Read`,`Grep`,`Glob`,`Bash`]:[`Read`,`Grep`,`Glob`,`Bash`,`Agent`],model:o.REGRESSION_FIRST_MODEL,effort:o.REGRESSION_SONNET_ANALYZER_REASONING.effort,maxTurns:e.maxTurns??o.REGRESSION_FIRST_CATEGORY_MAX_TURNS}}let Ay=[{name:`api-contract`,focus:`API/interface CONTRACT changes: a request/response shape, a route/endpoint, an HTTP status code, a function/method SIGNATURE, or a public return type changed in a way a caller or client could observe. Examples of the KIND to hunt: a 207 becomes 200; a required response field dropped; a param added/removed/reordered; a return type widened/narrowed. Focus ONLY on contract-level changes callers/clients depend on.`},{name:`schema-drift`,focus:`SCHEMA / data-shape DRIFT: a field made optional/required, a type widened or narrowed, nullability flipped, an enum case added/removed, a validation constraint loosened/tightened, a serialization shape changed (DTO / model / API schema). Focus ONLY on data-shape/validation drift and whether a consumer still copes with the new shape.`},{name:`auth-guard`,focus:`AUTH / SECURITY / GUARD changes: an authentication or authorization check removed or weakened, a permission/role gate dropped, a validation/guard the flow relied on removed, a security-relevant condition inverted, a fail-closed path turned fail-open. Focus ONLY on guards/gates and access control. A removed or fail-open guard is high severity.`},{name:`behavior-logic`,focus:'BEHAVIOR / LOGIC changes: a default value flipped (e.g. `?? false` → `?? true`), a conditional or operator changed, branch logic altered, a side-effect added/removed/reordered, a "mark done/success" that now runs before the operation that justifies it. Focus ONLY on control-flow / value / sequencing logic changes and their observable outcome.'},{name:`data-integrity`,focus:`DATA-INTEGRITY / ATOMICITY changes: two or more writes that must all succeed but are no longer atomic, a "done means persisted" guarantee broken, a race/ordering hazard introduced, a partial-failure now hidden as success, a persisted state that can now diverge from reported state. Focus ONLY on integrity/atomicity/persistence guarantees.`},{name:`other-behavior`,focus:`CATCH-ALL: any REAL behavior change that does NOT squarely fit api-contract, schema-drift, auth-guard, behavior-logic, or data-integrity. Your job is the recall backstop — report a genuine behavior change here rather than let it fall between categories. Pure no-ops (rename/reformat/import-reorder/log-reword with identical behavior) still get reported, at score 1-2 per the shared rubric.`}],jy={name:`product-intent`,maxTurns:o.REGRESSION_FIRST_PRODUCT_INTENT_MAX_TURNS,focus:`INTENT-SCOPE regressions: a change that is technically correct AND matches its commit, but whose ACTUAL reach is WIDER than the intent the commit describes — so it silently alters behavior for callers/flows the author never mentioned. You are NOT checking whether the code is correct or crashes (the other specialists do that). You ASSUME the diff is technically sound and does exactly what its commit says. Your ONE job: decide whether the change's real reach exceeds its stated scope, and whether the new behavior is APPROPRIATE at every reach point — not just the one the commit names. Classic shape: "feat: X for flow A" that also changes shared code flow B depends on, silently altering B.`,extraDirective:`## YOUR PROCEDURE — this is different from the other agents; follow it exactly
|
|
33924
33924
|
For each changed function / method / exported symbol in the diff:
|
|
33925
33925
|
1. ENUMERATE CALLERS (upstream fan-out). Grep every caller of the changed symbol across the repo (\`grep -rn "<symbol>" src\`). If a direct caller is itself a shared dispatcher, follow ONE level further up. List each DISTINCT entry point / product flow that reaches the changed line. You MUST do this before scoring — a change to a shared/exported symbol may NOT be scored until its callers are enumerated. Spend your budget going UPSTREAM to callers, NOT downstream to the effect (the other agents cover downstream).
|
|
33926
33926
|
2. READ THE STATED SCOPE. What does the commit message / inline comment claim the change is FOR (e.g. "manual runs", "the generate flow")?
|
|
@@ -34058,7 +34058,7 @@ You are catalog-blind — do not reason about product flows.
|
|
|
34058
34058
|
"priority": 1, "score": 8, "needsConsumerVerification": false, "consumerVerificationReason": "", "reason": "..." }
|
|
34059
34059
|
]
|
|
34060
34060
|
}
|
|
34061
|
-
Output JSON only.`}function eb(e,t){if(typeof t!=`object`||!t)return;let n=t;if(n.type!==`assistant`)return;let r=n.subagent_type;if(typeof r!=`string`||r.length===0)return;let i=e.get(r)??{turns:0,cacheReadTokens:0,cacheCreationTokens:0,inputTokens:0,outputTokens:0};i.turns+=1;let a=n.message?.usage;if(typeof a==`object`&&a){let e=a;i.cacheReadTokens+=typeof e.cache_read_input_tokens==`number`?e.cache_read_input_tokens:0,i.cacheCreationTokens+=typeof e.cache_creation_input_tokens==`number`?e.cache_creation_input_tokens:0,i.inputTokens+=typeof e.input_tokens==`number`?e.input_tokens:0,i.outputTokens+=typeof e.output_tokens==`number`?e.output_tokens:0}e.set(r,i)}function
|
|
34061
|
+
Output JSON only.`}function eb(e,t){if(typeof t!=`object`||!t)return e;let n=t.subagent_type;return typeof n==`string`&&n.length>0?`${e}:${n}`:e}function tb(e,t){if(typeof t!=`object`||!t)return;let n=t;if(n.type!==`assistant`)return;let r=n.subagent_type;if(typeof r!=`string`||r.length===0)return;let i=e.get(r)??{turns:0,cacheReadTokens:0,cacheCreationTokens:0,inputTokens:0,outputTokens:0};i.turns+=1;let a=n.message?.usage;if(typeof a==`object`&&a){let e=a;i.cacheReadTokens+=typeof e.cache_read_input_tokens==`number`?e.cache_read_input_tokens:0,i.cacheCreationTokens+=typeof e.cache_creation_input_tokens==`number`?e.cache_creation_input_tokens:0,i.inputTokens+=typeof e.input_tokens==`number`?e.input_tokens:0,i.outputTokens+=typeof e.output_tokens==`number`?e.output_tokens:0}e.set(r,i)}function nb(e){return[...e.entries()].map(([e,t])=>({label:e,costUsd:0,turns:t.turns,maxTurnsHit:!1,maxBudgetHit:!1,tokens:{cacheReadTokens:t.cacheReadTokens,cacheCreationTokens:t.cacheCreationTokens,inputTokens:t.inputTokens,outputTokens:t.outputTokens}}))}let rb=[`ui`,`generalist`,`product-intent`];function ib(e){return e===void 0||e.length===0?`<orchestrator>`:rb.some(t=>e===t||e.startsWith(`${t}-`))?`seat:${e}`:`helper:${e}`}function ab(e,t,n){if(n!==`experiment`||typeof t!=`object`||!t)return;let r=t;if(r.type!==`assistant`)return;let i=ib(typeof r.subagent_type==`string`?r.subagent_type:void 0),a=e.get(i)??{turns:0,outputTokens:0,cacheCreationTokens:0,cacheReadTokens:0};a.turns+=1;let o=r.message?.usage;typeof o?.output_tokens==`number`&&(a.outputTokens+=o.output_tokens),typeof o?.cache_creation_input_tokens==`number`&&(a.cacheCreationTokens+=o.cache_creation_input_tokens),typeof o?.cache_read_input_tokens==`number`&&(a.cacheReadTokens+=o.cache_read_input_tokens),e.set(i,a)}function ob(e,t){if(t!==`experiment`)return;let r=[...e.entries()].sort(([,e],[,t])=>t.cacheCreationTokens-e.cacheCreationTokens);for(let[e,t]of r)n.logger.info.defaultLog(`[regression-first][ATTR] ${e}: turns=${t.turns} cache_creation=${t.cacheCreationTokens} cache_read=${t.cacheReadTokens} output=${t.outputTokens}`)}function sb(e){return`Run a catalog-blind regression review by delegating to these specialist agents:
|
|
34062
34062
|
${e.map(e=>`- ${e.name}`).join(`
|
|
34063
34063
|
`)}
|
|
34064
34064
|
|
|
@@ -34066,9 +34066,9 @@ Each agent ALREADY HAS THE FULL DIFF embedded in its own instructions. Do NOT gi
|
|
|
34066
34066
|
|
|
34067
34067
|
"Review the diff in your instructions and return your category's regressions as JSON."
|
|
34068
34068
|
|
|
34069
|
-
Then reconcile ALL their findings into one list and JUDGE each score: include every distinct finding (group only exact same-change duplicates), and for each, weigh the agents' reasons to assign the single most defensible score — do not just take the highest. Emit the judged list.`}function
|
|
34069
|
+
Then reconcile ALL their findings into one list and JUDGE each score: include every distinct finding (group only exact same-change duplicates), and for each, weigh the agents' reasons to assign the single most defensible score — do not just take the highest. Emit the judged list.`}function cb(e,t){let n=t===`experiment`?Math.max(1,o.REGRESSION_FIRST_UI_SAMPLES):1,r=[];for(let t of e){let e=t.name===`ui`?n:1;for(let n=0;n<e;n++)r.push({name:n===0?t.name:`${t.name}-${n+1}`,definition:t})}return r}function lb(e,t,n,r,i){let a={};for(let o of e)a[o.name]=ky(o.definition,t,n,r,i);return a}async function ub(e){let t=e.variant??`v1`;return Uy(Zy(e.compareRef,t)),t===`v2`?db(e,My,`v2`):t===`experiment`?db(e,Ly,`experiment`):t===`mono`?db(e,Ly,`mono`):t===`single`?db(e,Iy,`single`):db(e,Ay,`v1`)}async function db(e,t,r){let{query:a,isResultMessage:s,isErrorResult:c,getMessageContentBlocks:l}=await Promise.resolve().then(()=>lz()),u=`regression-detect-orchestrator`,d=cb(t,r);if(n.logger.info.defaultLog(`[regression-first] Detect (${r}): orchestrator spawning ${d.length} category sub-agents (${t.length} lenses) over ${e.anchorRef}...${e.compareRef}`),r===`experiment`){let e=d.filter(e=>e.definition.name===`ui`).length;n.logger.info.defaultLog(`[regression-first] Detect experiment: multi ui agents (UI seat sampled ×${e})`)}let f=lb(d,e.diffText,e.commitMessagesBlock,e.primarySource,e.dependencyRoots),p=$y(d,r,e.primarySource,e.dependencyRoots),m=sb(d);Gy(`orchestrator`,`${p}\n\n----- USER PROMPT -----\n${m}`);for(let[e,t]of Object.entries(f))Gy(e,t.prompt);let h=a({prompt:m,options:{model:o.REGRESSION_FIRST_MODEL,...o.REGRESSION_SONNET_ANALYZER_REASONING,systemPrompt:p,agents:f,allowedTools:[`Agent`,`Task`],permissionMode:o.REGRESSION_PERMISSION_MODE,allowDangerouslySkipPermissions:!0,maxBudgetUsd:o.REGRESSION_FIRST_MAX_BUDGET_USD,maxTurns:o.REGRESSION_FIRST_MAX_TURNS,cwd:e.rootPath,sessionId:(0,v.randomUUID)(),outputFormat:{type:`json_schema`,schema:Qy},env:{...process.env,...i.buildAnthropicSdkEnv({proxyUrl:e.anthropicBaseUrl,jwtToken:e.jwtToken??``,requestId:n.logger.getRequestId()}),CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH:`2`}}});i.logAgentCwd(u,e.rootPath);let g=0,_=new Map,y=new Map;for await(let e of h){if(!s(e)){let t=l(e);t!==void 0&&t.length>0&&(g++,i.logAgentActivity(eb(u,e),g,t),Yy(e,t)),tb(_,e),ab(y,e,r);continue}if(c(e))return n.logger.info.defaultLog(`[regression-first] detect orchestrator error: ${e.subtype} — cost=$${e.total_cost_usd.toFixed(4)}, turns=${e.num_turns}`),ob(y,r),{regressions:[],costUsd:e.total_cost_usd,turns:g,maxTurnsHit:e.subtype===`error_max_turns`,tokens:i.extractCacheTokens(e),errorSubtype:e.subtype,subAgentMetrics:nb(_)};let t=Dy(e.structured_output),a=i.extractCacheTokens(e);return n.logger.info.defaultLog(`[regression-first] Detect done: ${t.length} finding(s) after aggregation`),ob(y,r),{regressions:t,costUsd:e.total_cost_usd,turns:g,maxTurnsHit:e.num_turns>=o.REGRESSION_FIRST_MAX_TURNS,tokens:a,subAgentMetrics:nb(_)}}return{regressions:[],costUsd:0,turns:0,maxTurnsHit:!1,tokens:{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0}}}function fb(e){return e.map((e,t)=>{let n=e.lines===void 0?e.file:`${e.file}:${e.lines}`;return`${t+1}. [score ${e.score}] ${n} — ${e.title}\n before: ${e.productBefore}\n after: ${e.productAfter}\n reason: ${e.reason}`}).join(`
|
|
34070
34070
|
|
|
34071
|
-
`)}function
|
|
34071
|
+
`)}function pb(e,t){return`You are the product-intent adjudicator — the FINAL stage of a catalog-blind regression review. Six specialist agents already reviewed the diff and produced the JUDGED findings you are given. Your job is TWO things, both via CALLER FAN-OUT:
|
|
34072
34072
|
|
|
34073
34073
|
${Ty(e,t)}
|
|
34074
34074
|
|
|
@@ -34089,7 +34089,7 @@ ${Ty(e,t)}
|
|
|
34089
34089
|
|
|
34090
34090
|
## Output
|
|
34091
34091
|
{ "regressions": [ { "file": "path", "lines": "L120", "title": "3-6 words", "productBefore": "X", "productAfter": "Y", "confidence": "high|low", "severity": "LOW|MEDIUM|HIGH|CRITICAL", "severityReason": "one sentence", "importance": "LOW|MEDIUM|HIGH|CRITICAL", "importanceReason": "one sentence", "priority": 1, "score": 8, "needsConsumerVerification": false, "consumerVerificationReason": "", "reason": "the caller evidence you found and how it set the score" } ] }
|
|
34092
|
-
Output JSON only.`}function
|
|
34092
|
+
Output JSON only.`}function mb(e,t,n,r){return`Verify + extend the regression findings below by checking the ACTUAL CALLERS of the changed code.
|
|
34093
34093
|
|
|
34094
34094
|
- anchor: ${e}
|
|
34095
34095
|
- compare: ${t}
|
|
@@ -34103,9 +34103,9 @@ git --no-pager diff ${e}...${t}
|
|
|
34103
34103
|
${n}
|
|
34104
34104
|
|
|
34105
34105
|
## The six agents' judged findings (verify each; adjust score with caller evidence)
|
|
34106
|
-
${
|
|
34106
|
+
${fb(r)}
|
|
34107
34107
|
|
|
34108
|
-
For each finding whose grade depends on consumers, grep for the callers of the changed symbol/endpoint/field and read them. Confirm, downgrade, or leave-unverified with a cited reason. Then add any cross-caller regressions the six missed. Emit the FINAL merged JSON list (drop 1-2 no-ops).`}function
|
|
34108
|
+
For each finding whose grade depends on consumers, grep for the callers of the changed symbol/endpoint/field and read them. Confirm, downgrade, or leave-unverified with a cited reason. Then add any cross-caller regressions the six missed. Emit the FINAL merged JSON list (drop 1-2 no-ops).`}function hb(e,t,n){let r=t.findIndex((t,r)=>!n.has(r)&&t.file===e.file&&(t.lines??``)===(e.lines??``));if(r!==-1)return{index:r,finding:t[r]};let i=t.map((e,t)=>({p:e,i:t})).filter(({p:t,i:r})=>!n.has(r)&&t.file===e.file);if(i.length===1)return{index:i[0].i,finding:i[0].p}}function gb(e,t,r=`product-intent`){let i=new Set,a=0,o=0,s=0,c=0;n.logger.info.defaultLog(`[regression-first] Verdict calibration (${r} over ${e.length} finding(s)):`);for(let r of t){let t=hb(r,e,i),l=r.lines===void 0?r.file:`${r.file}:${r.lines}`;if(t===void 0){c++,n.logger.info.defaultLog(`[regression-first] DISCOVERED ${r.score} ${l} — ${r.title}`);continue}i.add(t.index);let u=t.finding.score;r.score>u?(a++,n.logger.info.defaultLog(`[regression-first] RAISED ${u} → ${r.score} ${l} — ${r.title}`)):r.score<u?(o++,n.logger.info.defaultLog(`[regression-first] LOWERED ${u} → ${r.score} ${l} — ${r.title}`)):(s++,n.logger.info.defaultLog(`[regression-first] unchanged ${r.score} ${l} — ${r.title}`))}let l=0;for(let[t,r]of e.entries()){if(i.has(t))continue;l++;let e=r.lines===void 0?r.file:`${r.file}:${r.lines}`;n.logger.info.defaultLog(`[regression-first] DROPPED ${r.score} ${e} — ${r.title}`)}n.logger.info.defaultLog(`[regression-first] Calibration summary: ${a} raised, ${o} lowered, ${s} unchanged, ${c} discovered, ${l} dropped`)}async function _b(e,t){let{query:r,isResultMessage:a,isErrorResult:s,getMessageContentBlocks:c}=await Promise.resolve().then(()=>lz()),l=`regression-detect-product-intent-verify`,u=pb(e.primarySource,e.dependencyRoots),d=mb(e.anchorRef,e.compareRef,e.commitMessagesBlock,t);n.logger.info.defaultLog(`[regression-first] Detect (v3): product-intent verify pass over ${t.length} phase-1 finding(s)`),Gy(`product-intent-verify`,`${u}\n\n----- USER PROMPT -----\n${d}`);let f=r({prompt:d,options:{model:o.REGRESSION_FIRST_MODEL,...o.REGRESSION_SONNET_ANALYZER_REASONING,systemPrompt:u,allowedTools:[`Read`,`Grep`,`Glob`,`Bash`],permissionMode:o.REGRESSION_PERMISSION_MODE,allowDangerouslySkipPermissions:!0,maxBudgetUsd:o.REGRESSION_FIRST_MAX_BUDGET_USD,maxTurns:o.REGRESSION_FIRST_MAX_TURNS,cwd:e.rootPath,sessionId:(0,v.randomUUID)(),outputFormat:{type:`json_schema`,schema:Qy},env:{...process.env,...i.buildAnthropicSdkEnv({proxyUrl:e.anthropicBaseUrl,jwtToken:e.jwtToken??``,requestId:n.logger.getRequestId()})}}});i.logAgentCwd(l,e.rootPath);let p=0;for await(let e of f){if(!a(e)){let t=c(e);t!==void 0&&t.length>0&&(p++,i.logAgentActivity(l,p,t),Yy(e,t));continue}if(s(e))return n.logger.info.defaultLog(`[regression-first] product-intent verify error: ${e.subtype} — keeping phase-1 findings`),{regressions:t.filter(e=>e.score>=3),costUsd:e.total_cost_usd,turns:p,maxTurnsHit:e.subtype===`error_max_turns`,tokens:i.extractCacheTokens(e)};let r=Dy(e.structured_output),u=(r.length>0?r:t).filter(e=>e.score>=3);return r.length>0&&gb(t,u),n.logger.info.defaultLog(`[regression-first] Detect done (v3): ${u.length} finding(s) after product-intent verify`),{regressions:u,costUsd:e.total_cost_usd,turns:p,maxTurnsHit:e.num_turns>=o.REGRESSION_FIRST_MAX_TURNS,tokens:i.extractCacheTokens(e)}}return{regressions:t.filter(e=>e.score>=3),costUsd:0,turns:0,maxTurnsHit:!1,tokens:{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0}}}function vb(e){return e>=7&&e<=10}function yb(e,t){return`You are the ADJUDICATOR — a focused second pass over a catalog-blind regression review. A first pass of specialist agents scored every change, but they were FORBIDDEN to read the anchor — they saw only the diff, so they scored the MECHANISM they could see, not the NET effect against the previous code. You are given ONLY the findings they scored HIGH (7-10 — "likely" or "near-certain" regressions). Your job: re-score each on the NET observable effect vs the anchor — confirm the ones that are truly regressions, and deflate the ones where the first pass over-called a mechanism that harms no one.
|
|
34109
34109
|
|
|
34110
34110
|
${Ty(e,t)}
|
|
34111
34111
|
|
|
@@ -34155,10 +34155,10 @@ A passing test, an assertion that matches the new behavior, or a comment/docstri
|
|
|
34155
34155
|
|
|
34156
34156
|
## Output
|
|
34157
34157
|
{ "regressions": [ { "file": "path", "lines": "L120", "title": "3-6 words", "productBefore": "X", "productAfter": "Y", "confidence": "high|low", "severity": "LOW|MEDIUM|HIGH|CRITICAL", "severityReason": "one sentence", "importance": "LOW|MEDIUM|HIGH|CRITICAL", "importanceReason": "one sentence", "priority": 1, "score": 4, "needsConsumerVerification": false, "consumerVerificationReason": "", "reason": "the anchor-vs-compare net-effect evidence and how it set the score" } ] }
|
|
34158
|
-
Output JSON only.`}function
|
|
34158
|
+
Output JSON only.`}function bb(e){if(e===void 0)return;let t=[...e.matchAll(/\d+/g)].map(e=>Number(e[0])).filter(e=>Number.isFinite(e)&&e>0);if(t.length!==0)return{start:Math.min(...t),end:Math.max(...t)}}function xb(e){let t=new Map;for(let n of e){let e=t.get(n.file)??{locs:[],range:void 0,wholeFile:!1},r=n.lines===void 0?n.file:`${n.file}:${n.lines}`;e.locs.push(`${r} — ${n.title}`);let i=bb(n.lines);i===void 0?(e.wholeFile=!0,e.range=void 0):e.wholeFile||(e.range=e.range===void 0?i:{start:Math.min(e.range.start,i.start),end:Math.max(e.range.end,i.end)}),t.set(n.file,e)}return t}function Sb(e,t,n,r){return[...xb(r).entries()].map(([r,{locs:i,range:a}])=>{let s=a===void 0?o.showFileAtRef(e,t,r,12e3):o.showFileRangeAtRef(e,t,r,a.start,a.end,60),c=a===void 0?o.showFileAtRef(e,n,r,12e3):o.showFileRangeAtRef(e,n,r,a.start,a.end,60);return`### ${i.join(`
|
|
34159
34159
|
### `)}\n----- ANCHOR (${t.slice(0,8)}) -----\n${s||`(absent at anchor)`}\n----- COMPARE (${n.slice(0,8)}) -----\n${c||`(absent at compare)`}`}).join(`
|
|
34160
34160
|
|
|
34161
|
-
`)}function
|
|
34161
|
+
`)}function Cb(e,t,n,r){return`Adjudicate the findings below, each scored HIGH (7-10) by the first pass (which could not read the anchor).
|
|
34162
34162
|
|
|
34163
34163
|
- anchor: ${e}
|
|
34164
34164
|
- compare: ${t}
|
|
@@ -34168,17 +34168,17 @@ Each block below is the code window (the finding's line range ± context) at the
|
|
|
34168
34168
|
${r}
|
|
34169
34169
|
|
|
34170
34170
|
## The findings to re-score (7-10 band — confirm or deflate)
|
|
34171
|
-
${
|
|
34171
|
+
${fb(n)}
|
|
34172
34172
|
|
|
34173
|
-
For each: net the anchor-vs-compare source above, check only the specific callers you still need, and return the resolved JSON list per your instructions. Emit exactly these findings, re-scored — do not add or drop any.`}async function Cb(e,t){let r={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0},a=t.filter(e=>!_b(e.score)),s=t.filter(e=>_b(e.score));if(s.length===0)return{regressions:t,costUsd:0,turns:0,maxTurnsHit:!1,tokens:r};let{query:c,isResultMessage:l,isErrorResult:u,getMessageContentBlocks:d}=await Promise.resolve().then(()=>lz()),f=`regression-detect-adjudicate-uncertain`,p=vb(e.primarySource,e.dependencyRoots),m=xb(e.rootPath,e.anchorRef,e.compareRef,s),h=Sb(e.anchorRef,e.compareRef,s,m);n.logger.info.defaultLog(`[regression-first] Adjudicate (v2-adj): ${s.length} finding(s) entered stage 2 (score 7-10); ${a.length} passed through untouched (<=6)`);for(let e of s){let t=e.lines===void 0?e.file:`${e.file}:${e.lines}`;n.logger.info.defaultLog(`[regression-first] → stage2 [${e.score}] ${t} — ${e.title}`)}Gy(`adjudicate-uncertain`,`${p}\n\n----- USER PROMPT -----\n${h}`);let g=c({prompt:h,options:{model:o.REGRESSION_FIRST_MODEL,systemPrompt:p,allowedTools:[`Read`,`Grep`,`Glob`,`Bash`],permissionMode:o.REGRESSION_PERMISSION_MODE,allowDangerouslySkipPermissions:!0,maxBudgetUsd:o.REGRESSION_ADJ_MAX_BUDGET_USD,maxTurns:o.REGRESSION_ADJ_MAX_TURNS,cwd:e.rootPath,sessionId:(0,v.randomUUID)(),outputFormat:{type:`json_schema`,schema:Qy},env:{...process.env,...i.buildAnthropicSdkEnv({proxyUrl:e.anthropicBaseUrl,jwtToken:e.jwtToken??``,requestId:n.logger.getRequestId()})}}});i.logAgentCwd(f,e.rootPath);let _=0;for await(let e of g){if(!l(e)){let t=d(e);t!==void 0&&t.length>0&&(_++,i.logAgentActivity(f,_,t),Yy(e,t));continue}return Tb(e,u,{allFindings:t,untouched:a,uncertain:s})}return{regressions:t,costUsd:0,turns:0,maxTurnsHit:!1,tokens:r}}function wb(e,t){let n=e=>`${e.file}|${e.lines??``}|${e.title}`,r=new Map;for(let e of t){let t=n(e),i=r.get(t);r.set(t,{flagged:(i?.flagged??!1)||e.needsConsumerVerification,reason:i?.reason??(e.needsConsumerVerification?e.consumerVerificationReason:void 0)})}for(let t of e){let e=r.get(n(t));e===void 0||!e.flagged||(t.needsConsumerVerification=!0,(t.consumerVerificationReason===void 0||t.consumerVerificationReason.length===0)&&e.reason!==void 0&&(t.consumerVerificationReason=e.reason))}}function Tb(e,t,r){let a=i.extractCacheTokens(e);if(t(e))return n.logger.info.defaultLog(`[regression-first] adjudicate-uncertain error: ${e.subtype} — keeping all original findings`),{regressions:r.allFindings,costUsd:e.total_cost_usd,turns:e.num_turns,maxTurnsHit:e.subtype===`error_max_turns`,tokens:a};let s=Dy(e.structured_output);wb(s,r.uncertain);let c=s.length>0?s:r.uncertain,l=[...r.untouched,...c].filter(e=>e.score>=3);return s.length>0&&hb(r.uncertain,c,`uncertainty-adjudicator`),n.logger.info.defaultLog(`[regression-first] Adjudicate done (v2-adj): ${l.length} finding(s) after uncertainty adjudication`),{regressions:l,costUsd:e.total_cost_usd,turns:e.num_turns,maxTurnsHit:e.num_turns>=o.REGRESSION_ADJ_MAX_TURNS,tokens:a}}var Eb=class{name=`adjudicateUncertain`;async execute(e){let t=e.detectedRegressions??[];if(!t.some(e=>_b(e.score)))return u_;let n=dv(e);if(e.branch===void 0||e.resolvedAnchorBranch===void 0)throw Error(`[impact-pipeline] AdjudicateUncertainStep requires branch/resolvedAnchorBranch from ResolveCompare`);let r=e.changedFiles??[],i=o.getDiffForFiles(r,n,e.branch,e.resolvedAnchorBranch,e.isUncommitted),a=o.formatCommitMessagesBlock(e.commitMessages??[]),s=wy(e.jobInput,n),c=await Cb({anchorRef:e.resolvedAnchorBranch,compareRef:e.branch,rootPath:n,diffText:i,commitMessagesBlock:a,jwtToken:e.jwtToken,anthropicBaseUrl:e.anthropicBaseUrl,primarySource:s.primarySource,dependencyRoots:s.dependencyRoots},t);e.detectedRegressions=c.regressions,e.detectVariant=`v2-adj`,Wy(Zy(e.branch,`v2-adj`)),e.detectCostUsd=(e.detectCostUsd??0)+c.costUsd,e.detectTurns=(e.detectTurns??0)+c.turns;let l=e.detectTokens;return e.detectTokens=l===void 0?c.tokens:{inputTokens:(l.inputTokens??0)+(c.tokens.inputTokens??0),outputTokens:(l.outputTokens??0)+(c.tokens.outputTokens??0),cacheReadTokens:(l.cacheReadTokens??0)+(c.tokens.cacheReadTokens??0),cacheCreationTokens:(l.cacheCreationTokens??0)+(c.tokens.cacheCreationTokens??0)},{costUsd:c.costUsd,turns:c.turns,maxTurnsHit:c.maxTurnsHit,totalFiles:c.regressions.length,tokens:c.tokens}}};async function Db(e,t,n){if(e===`agentic`)return new l.AgenticImpactMapper(t);let{createImpactMapper:r}=await Promise.resolve().then(()=>MU());return r({...t,strategy:e,isUncommitted:n})}async function Ob(e,t=`agentic`){let r=uv(e),i=fv(e),a=dv(e);if(e.branch===void 0||e.resolvedAnchorBranch===void 0||e.projectType===void 0)throw Error(`[impact-pipeline] mapping step requires branch/resolvedAnchorBranch/projectType from prior steps`);let s=o.REGRESSION_IMPACT_MAPPING_SYMBOL_TRACING?new Map(Object.entries(o.getPerFileDiffs(i,a,e.branch,e.resolvedAnchorBranch,e.isUncommitted))):void 0,c=await(await Db(t,{rootPath:a,branch:e.branch,resolvedAnchorBranch:e.resolvedAnchorBranch,jwtToken:e.jwtToken,anthropicBaseUrl:e.anthropicBaseUrl,projectType:e.projectType,mappingMaxTurns:e.jobInput?.impactMappingMaxTurns,fileDiffs:s},e.isUncommitted)).run(r,i),l=r.filter(e=>(c.flowFileMap.get(e.flowId)?.size??0)>0).length,u=i.length,d=new Set;for(let e of c.flowFileMap.values())for(let t of e)d.add(t);let f=d.size;n.logger.info.defaultLog(`[regression-impact] File-to-flow mapping: ${l} affected, ${r.length-l} not affected (${f}/${u} files mapped to >= 1 flow)`);let p=new Set(c.incompleteFiles??[]),m=i.filter(e=>d.has(e)),h=i.filter(e=>p.has(e)),g=i.filter(e=>!d.has(e)&&!p.has(e));n.logger.info.defaultLog(`[regression-impact] File-to-flow mapping summary (${u} files):`),n.logger.info.defaultLog(`[regression-impact] → mapped to flows (${m.length}): ${m.length>0?m.join(`, `):`(none)`}`),n.logger.info.defaultLog(`[regression-impact] → no flows (${g.length}): ${g.length>0?g.join(`, `):`(none)`}`),n.logger.info.defaultLog(`[regression-impact] → INCOMPLETE/unmapped (${h.length}): ${h.length>0?h.join(`, `):`(none)`}`);let _=c.mappingBreakdown,v=c.mappingBreakdownFiles;if(_!==void 0&&v!==void 0){let e=e=>e.length>0?e.join(`, `):`(none)`;n.logger.info.defaultLog(`[regression-impact] File-to-flow mapping attribution breakdown:`),n.logger.info.defaultLog(`[regression-impact] → confirmed + found flow (${_.directMappedFiles}): ${e(v.directMappedFiles)}`),n.logger.info.defaultLog(`[regression-impact] → guessed + found flow (${_.guessedMappedFiles}): ${e(v.guessedMappedFiles)}`),n.logger.info.defaultLog(`[regression-impact] → guessed + NO flow (${_.guessedNoFlowFiles}): ${e(v.guessedNoFlowFiles)}`),n.logger.info.defaultLog(`[regression-impact] → confirmed + NO flow (${_.noFlowFiles}): ${e(v.noFlowFiles)}`)}e.mappingResult=c,e.flowFileReasons=c.flowFileReasons;let y=c.batchMetrics??[],b=y.reduce((e,t)=>({inputTokens:e.inputTokens+t.tokens.inputTokens,outputTokens:e.outputTokens+t.tokens.outputTokens,cacheReadTokens:e.cacheReadTokens+t.tokens.cacheReadTokens,cacheCreationTokens:e.cacheCreationTokens+t.tokens.cacheCreationTokens}),{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0});return{costUsd:c.costUsd,turns:c.turns,maxTurnsHit:c.maxTurnsHit,maxBudgetHit:c.maxBudgetHit??!1,tokens:y.length>0?b:void 0,batches:y.length>0?y:void 0,totalFiles:u,mappedFiles:f,..._!==void 0&&{mappingBreakdown:_}}}var kb=class{name;constructor(e=`agentic`){this.strategy=e,this.name=e===`agentic`?`fileToFlowMapping`:`fileToFlowMapping:${e}`}async execute(e){return Ob(e,this.strategy)}};function Ab(e,t,n,r){return e.map(e=>{let i=t.get(e.flowId),a=(i?.size??0)>0,o=n?.has(e.flowId)===!0,s=r?.has(e.flowId)===!0;return{flow:e,affected:a,...a&&(o||s)?{uncertain:!0}:{},changedFiles:a?[...i]:[],severity:a?`MEDIUM`:`NONE`}})}var jb=class{name=`buildImpacts`;async execute(e){let t=uv(e),n=pv(e);return e.flowImpacts=Ab(t,n.flowFileMap,e.roughGuessedFlowIds,n.lowConfidenceFlowIds),u_}};let Mb=[`NONE`,`LOW`,`MEDIUM`,`HIGH`,`CRITICAL`];function Nb(e){if(e.length!==0)return e.reduce((e,t)=>Mb.indexOf(t.severity)>Mb.indexOf(e)?t.severity:e,`NONE`)}function Pb(){return{flowId:o.REGRESSION_FIRST_SENTINEL_FLOW_ID,rank:1,name:o.REGRESSION_FIRST_SENTINEL_FLOW_NAME,flowType:`OTHER`,entryPoints:[],description:`Findings from the regression-first (regression-locator) command that aren't attributed to any cataloged flow.`,trace:{entryFiles:[],entrySymbols:[],calledModules:[],codeSnippet:``},importanceReason:`Sentinel bucket — importance reflects the underlying findings, not this row itself.`}}function Fb(e){return{title:e.title,productBefore:e.productBefore,productAfter:e.productAfter,confidence:e.confidence,severity:e.severity,severityReason:e.severityReason,verdictScore:e.score,verdictReason:e.reason,importance:e.importance,importanceReason:e.importanceReason,...e.priority===void 0?{}:{priority:e.priority},file:e.file,needsConsumerVerification:e.needsConsumerVerification,...e.consumerVerificationReason===void 0?{}:{consumerVerificationReason:e.consumerVerificationReason},...e.howToVerify===void 0?{}:{howToVerify:e.howToVerify}}}var Ib=class{name=`buildRegFirstSentinelImpact`;async execute(e){if(e.sentinelFlowId===void 0)throw Error(`[regression-first] BuildRegFirstSentinelImpactStep requires ctx.sentinelFlowId — EnsureRegFirstSentinelFlowStep must run before this step`);let t=e.detectedRegressions??[],n=t.map(Fb);return e.flowImpacts=[{flow:Pb(),affected:t.length>0,severity:Nb(t),changedFiles:e.changedFiles??[],productChanges:n,techChanges:[]}],u_}};function Lb(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 Rb(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):
|
|
34173
|
+
For each: net the anchor-vs-compare source above, check only the specific callers you still need, and return the resolved JSON list per your instructions. Emit exactly these findings, re-scored — do not add or drop any.`}async function wb(e,t){let r={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0},a=t.filter(e=>!vb(e.score)),s=t.filter(e=>vb(e.score));if(s.length===0)return{regressions:t,costUsd:0,turns:0,maxTurnsHit:!1,tokens:r};let{query:c,isResultMessage:l,isErrorResult:u,getMessageContentBlocks:d}=await Promise.resolve().then(()=>lz()),f=`regression-detect-adjudicate-uncertain`,p=yb(e.primarySource,e.dependencyRoots),m=Sb(e.rootPath,e.anchorRef,e.compareRef,s),h=Cb(e.anchorRef,e.compareRef,s,m);n.logger.info.defaultLog(`[regression-first] Adjudicate (v2-adj): ${s.length} finding(s) entered stage 2 (score 7-10); ${a.length} passed through untouched (<=6)`);for(let e of s){let t=e.lines===void 0?e.file:`${e.file}:${e.lines}`;n.logger.info.defaultLog(`[regression-first] → stage2 [${e.score}] ${t} — ${e.title}`)}Gy(`adjudicate-uncertain`,`${p}\n\n----- USER PROMPT -----\n${h}`);let g=c({prompt:h,options:{model:o.REGRESSION_FIRST_MODEL,...o.REGRESSION_SONNET_ANALYZER_REASONING,systemPrompt:p,allowedTools:[`Read`,`Grep`,`Glob`,`Bash`],permissionMode:o.REGRESSION_PERMISSION_MODE,allowDangerouslySkipPermissions:!0,maxBudgetUsd:o.REGRESSION_ADJ_MAX_BUDGET_USD,maxTurns:o.REGRESSION_ADJ_MAX_TURNS,cwd:e.rootPath,sessionId:(0,v.randomUUID)(),outputFormat:{type:`json_schema`,schema:Qy},env:{...process.env,...i.buildAnthropicSdkEnv({proxyUrl:e.anthropicBaseUrl,jwtToken:e.jwtToken??``,requestId:n.logger.getRequestId()})}}});i.logAgentCwd(f,e.rootPath);let _=0;for await(let e of g){if(!l(e)){let t=d(e);t!==void 0&&t.length>0&&(_++,i.logAgentActivity(f,_,t),Yy(e,t));continue}return Eb(e,u,{allFindings:t,untouched:a,uncertain:s})}return{regressions:t,costUsd:0,turns:0,maxTurnsHit:!1,tokens:r}}function Tb(e,t){let n=e=>`${e.file}|${e.lines??``}|${e.title}`,r=new Map;for(let e of t){let t=n(e),i=r.get(t);r.set(t,{flagged:(i?.flagged??!1)||e.needsConsumerVerification,reason:i?.reason??(e.needsConsumerVerification?e.consumerVerificationReason:void 0)})}for(let t of e){let e=r.get(n(t));e===void 0||!e.flagged||(t.needsConsumerVerification=!0,(t.consumerVerificationReason===void 0||t.consumerVerificationReason.length===0)&&e.reason!==void 0&&(t.consumerVerificationReason=e.reason))}}function Eb(e,t,r){let a=i.extractCacheTokens(e);if(t(e))return n.logger.info.defaultLog(`[regression-first] adjudicate-uncertain error: ${e.subtype} — keeping all original findings`),{regressions:r.allFindings,costUsd:e.total_cost_usd,turns:e.num_turns,maxTurnsHit:e.subtype===`error_max_turns`,tokens:a};let s=Dy(e.structured_output);Tb(s,r.uncertain);let c=s.length>0?s:r.uncertain,l=[...r.untouched,...c].filter(e=>e.score>=3);return s.length>0&&gb(r.uncertain,c,`uncertainty-adjudicator`),n.logger.info.defaultLog(`[regression-first] Adjudicate done (v2-adj): ${l.length} finding(s) after uncertainty adjudication`),{regressions:l,costUsd:e.total_cost_usd,turns:e.num_turns,maxTurnsHit:e.num_turns>=o.REGRESSION_ADJ_MAX_TURNS,tokens:a}}var Db=class{name=`adjudicateUncertain`;async execute(e){let t=e.detectedRegressions??[];if(!t.some(e=>vb(e.score)))return u_;let n=dv(e);if(e.branch===void 0||e.resolvedAnchorBranch===void 0)throw Error(`[impact-pipeline] AdjudicateUncertainStep requires branch/resolvedAnchorBranch from ResolveCompare`);let r=e.changedFiles??[],i=o.getDiffForFiles(r,n,e.branch,e.resolvedAnchorBranch,e.isUncommitted),a=o.formatCommitMessagesBlock(e.commitMessages??[]),s=wy(e.jobInput,n),c=await wb({anchorRef:e.resolvedAnchorBranch,compareRef:e.branch,rootPath:n,diffText:i,commitMessagesBlock:a,jwtToken:e.jwtToken,anthropicBaseUrl:e.anthropicBaseUrl,primarySource:s.primarySource,dependencyRoots:s.dependencyRoots},t);e.detectedRegressions=c.regressions,e.detectVariant=`v2-adj`,Wy(Zy(e.branch,`v2-adj`)),e.detectCostUsd=(e.detectCostUsd??0)+c.costUsd,e.detectTurns=(e.detectTurns??0)+c.turns;let l=e.detectTokens;return e.detectTokens=l===void 0?c.tokens:{inputTokens:(l.inputTokens??0)+(c.tokens.inputTokens??0),outputTokens:(l.outputTokens??0)+(c.tokens.outputTokens??0),cacheReadTokens:(l.cacheReadTokens??0)+(c.tokens.cacheReadTokens??0),cacheCreationTokens:(l.cacheCreationTokens??0)+(c.tokens.cacheCreationTokens??0)},{costUsd:c.costUsd,turns:c.turns,maxTurnsHit:c.maxTurnsHit,totalFiles:c.regressions.length,tokens:c.tokens}}};async function Ob(e,t,n){if(e===`agentic`)return new l.AgenticImpactMapper(t);let{createImpactMapper:r}=await Promise.resolve().then(()=>MU());return r({...t,strategy:e,isUncommitted:n})}async function kb(e,t=`agentic`){let r=uv(e),i=fv(e),a=dv(e);if(e.branch===void 0||e.resolvedAnchorBranch===void 0||e.projectType===void 0)throw Error(`[impact-pipeline] mapping step requires branch/resolvedAnchorBranch/projectType from prior steps`);let s=o.REGRESSION_IMPACT_MAPPING_SYMBOL_TRACING?new Map(Object.entries(o.getPerFileDiffs(i,a,e.branch,e.resolvedAnchorBranch,e.isUncommitted))):void 0,c=await(await Ob(t,{rootPath:a,branch:e.branch,resolvedAnchorBranch:e.resolvedAnchorBranch,jwtToken:e.jwtToken,anthropicBaseUrl:e.anthropicBaseUrl,projectType:e.projectType,mappingMaxTurns:e.jobInput?.impactMappingMaxTurns,fileDiffs:s},e.isUncommitted)).run(r,i),l=r.filter(e=>(c.flowFileMap.get(e.flowId)?.size??0)>0).length,u=i.length,d=new Set;for(let e of c.flowFileMap.values())for(let t of e)d.add(t);let f=d.size;n.logger.info.defaultLog(`[regression-impact] File-to-flow mapping: ${l} affected, ${r.length-l} not affected (${f}/${u} files mapped to >= 1 flow)`);let p=new Set(c.incompleteFiles??[]),m=i.filter(e=>d.has(e)),h=i.filter(e=>p.has(e)),g=i.filter(e=>!d.has(e)&&!p.has(e));n.logger.info.defaultLog(`[regression-impact] File-to-flow mapping summary (${u} files):`),n.logger.info.defaultLog(`[regression-impact] → mapped to flows (${m.length}): ${m.length>0?m.join(`, `):`(none)`}`),n.logger.info.defaultLog(`[regression-impact] → no flows (${g.length}): ${g.length>0?g.join(`, `):`(none)`}`),n.logger.info.defaultLog(`[regression-impact] → INCOMPLETE/unmapped (${h.length}): ${h.length>0?h.join(`, `):`(none)`}`);let _=c.mappingBreakdown,v=c.mappingBreakdownFiles;if(_!==void 0&&v!==void 0){let e=e=>e.length>0?e.join(`, `):`(none)`;n.logger.info.defaultLog(`[regression-impact] File-to-flow mapping attribution breakdown:`),n.logger.info.defaultLog(`[regression-impact] → confirmed + found flow (${_.directMappedFiles}): ${e(v.directMappedFiles)}`),n.logger.info.defaultLog(`[regression-impact] → guessed + found flow (${_.guessedMappedFiles}): ${e(v.guessedMappedFiles)}`),n.logger.info.defaultLog(`[regression-impact] → guessed + NO flow (${_.guessedNoFlowFiles}): ${e(v.guessedNoFlowFiles)}`),n.logger.info.defaultLog(`[regression-impact] → confirmed + NO flow (${_.noFlowFiles}): ${e(v.noFlowFiles)}`)}e.mappingResult=c,e.flowFileReasons=c.flowFileReasons;let y=c.batchMetrics??[],b=y.reduce((e,t)=>({inputTokens:e.inputTokens+t.tokens.inputTokens,outputTokens:e.outputTokens+t.tokens.outputTokens,cacheReadTokens:e.cacheReadTokens+t.tokens.cacheReadTokens,cacheCreationTokens:e.cacheCreationTokens+t.tokens.cacheCreationTokens}),{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0});return{costUsd:c.costUsd,turns:c.turns,maxTurnsHit:c.maxTurnsHit,maxBudgetHit:c.maxBudgetHit??!1,tokens:y.length>0?b:void 0,batches:y.length>0?y:void 0,totalFiles:u,mappedFiles:f,..._!==void 0&&{mappingBreakdown:_}}}var Ab=class{name;constructor(e=`agentic`){this.strategy=e,this.name=e===`agentic`?`fileToFlowMapping`:`fileToFlowMapping:${e}`}async execute(e){return kb(e,this.strategy)}};function jb(e,t,n,r){return e.map(e=>{let i=t.get(e.flowId),a=(i?.size??0)>0,o=n?.has(e.flowId)===!0,s=r?.has(e.flowId)===!0;return{flow:e,affected:a,...a&&(o||s)?{uncertain:!0}:{},changedFiles:a?[...i]:[],severity:a?`MEDIUM`:`NONE`}})}var Mb=class{name=`buildImpacts`;async execute(e){let t=uv(e),n=pv(e);return e.flowImpacts=jb(t,n.flowFileMap,e.roughGuessedFlowIds,n.lowConfidenceFlowIds),u_}};let Nb=[`NONE`,`LOW`,`MEDIUM`,`HIGH`,`CRITICAL`];function Pb(e){if(e.length!==0)return e.reduce((e,t)=>Nb.indexOf(t.severity)>Nb.indexOf(e)?t.severity:e,`NONE`)}function Fb(){return{flowId:o.REGRESSION_FIRST_SENTINEL_FLOW_ID,rank:1,name:o.REGRESSION_FIRST_SENTINEL_FLOW_NAME,flowType:`OTHER`,entryPoints:[],description:`Findings from the regression-first (regression-locator) command that aren't attributed to any cataloged flow.`,trace:{entryFiles:[],entrySymbols:[],calledModules:[],codeSnippet:``},importanceReason:`Sentinel bucket — importance reflects the underlying findings, not this row itself.`}}function Ib(e){return{title:e.title,productBefore:e.productBefore,productAfter:e.productAfter,confidence:e.confidence,severity:e.severity,severityReason:e.severityReason,verdictScore:e.score,verdictReason:e.reason,importance:e.importance,importanceReason:e.importanceReason,...e.priority===void 0?{}:{priority:e.priority},file:e.file,needsConsumerVerification:e.needsConsumerVerification,...e.consumerVerificationReason===void 0?{}:{consumerVerificationReason:e.consumerVerificationReason},...e.howToVerify===void 0?{}:{howToVerify:e.howToVerify}}}var Lb=class{name=`buildRegFirstSentinelImpact`;async execute(e){if(e.sentinelFlowId===void 0)throw Error(`[regression-first] BuildRegFirstSentinelImpactStep requires ctx.sentinelFlowId — EnsureRegFirstSentinelFlowStep must run before this step`);let t=e.detectedRegressions??[],n=t.map(Ib);return e.flowImpacts=[{flow:Fb(),affected:t.length>0,severity:Pb(t),changedFiles:e.changedFiles??[],productChanges:n,techChanges:[]}],u_}};function Rb(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 zb(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):
|
|
34174
34174
|
| File | Last touched | Author commits (90d) | Fix commits (90d) | Revert commits (90d) |
|
|
34175
34175
|
|---|---|---|---|---|
|
|
34176
34176
|
${n.join(`
|
|
34177
34177
|
`)}
|
|
34178
|
-
`}async function
|
|
34179
|
-
`)}function
|
|
34180
|
-
`)})).filter(e=>Number.isInteger(e.index)&&e.howToVerify.length>0)}function
|
|
34181
|
-
`)}async function
|
|
34178
|
+
`}async function Bb(e){let{productChange:t,techChanges:r,flow:a,commitMessages:s,gitSignals:l,runContext:u,affectedSteps:d,jwtToken:f,anthropicBaseUrl:p,rootPath:m}=e,h=t.verdictScore,g=t.verdictReason;if(h===void 0)return{verdict:null,costUsd:0,turns:0,maxTurnsHit:!1};let{query:_,isResultMessage:y,isErrorResult:b,getMessageContentBlocks:x}=await Promise.resolve().then(()=>lz()),S=`verdict-calibrator`,C=zb(l,r.map(e=>e.file)),w=c.buildVerdictCalibratorSystemPrompt(),T=_({prompt:c.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:h,reason:g},flow:{name:a.name,rank:a.rank,importance:void 0,importanceReason:a.importanceReason,trace:a.trace,productFlow:a.productFlow},commitMessages:s,gitSignalsBlock:C,runContext:u,affectedSteps:d}),options:{model:o.REGRESSION_IMPACT_CALIBRATOR_MODEL,...o.REGRESSION_SONNET_SCORER_REASONING,systemPrompt:w,allowedTools:[],permissionMode:o.REGRESSION_PERMISSION_MODE,allowDangerouslySkipPermissions:!0,maxBudgetUsd:o.REGRESSION_IMPACT_CALIBRATOR_MAX_BUDGET_USD,maxTurns:o.REGRESSION_IMPACT_CALIBRATOR_MAX_TURNS,cwd:m,sessionId:(0,v.randomUUID)(),outputFormat:{type:`json_schema`,schema:i.VERDICT_CALIBRATOR_OUTPUT_SCHEMA},env:{...process.env,...i.buildAnthropicSdkEnv({proxyUrl:p,jwtToken:f??``,requestId:n.logger.getRequestId()})}}});i.logAgentCwd(S,m);let E=0;for await(let e of T){if(!y(e)){let t=x(e);t!==void 0&&t.length>0&&(E++,i.logAgentActivity(S,E,t));continue}let r=e.total_cost_usd??0,a=o.shouldLogDiagnostics?e.total_cost_usd?.toFixed(4)??`N/A`:`hidden`,s=e.num_turns,c=s>=o.REGRESSION_IMPACT_CALIBRATOR_MAX_TURNS;if(b(e))return n.logger.info.defaultLog(`[regression-impact] Verdict calibrator error for "${t.title??`(untitled)`}": ${e.subtype} (cost: $${a})`),{verdict:null,costUsd:r,turns:s,maxTurnsHit:c};let l=Rb(e.structured_output);if(l===void 0)return n.logger.info.defaultLog(`[regression-impact] Verdict calibrator: invalid structured output for "${t.title??`(untitled)`}" (cost: $${a})`),{verdict:null,costUsd:r,turns:s,maxTurnsHit:c};let u=l.score,d=u!==h;return{verdict:{score:u,reason:l.reasoning,changed:d},costUsd:r,turns:s,maxTurnsHit:c}}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}}async function Vb(e,t,r,i,a,s,c,l,u,d){let f=[];for(let t of e)if(t.productChanges!==void 0)for(let e of t.productChanges){let n=e.verdictScore;n!==void 0&&n>=o.REGRESSION_IMPACT_CALIBRATION_RANGE_MIN&&n<=o.REGRESSION_IMPACT_CALIBRATION_RANGE_MAX&&f.push({fi:t,pc:e})}if(f.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 ${f.length} borderline productChange(s)...`);let p=[...new Set(f.flatMap(({fi:e})=>(e.techChanges??[]).map(e=>e.file)))],m=o.getAuthorEmail(t,r,c),h=o.getGitSignalsForFiles(t,p,m,u,i),g=0,_=0,v=!1,y=0,b=0,x=0,S=new A.default({concurrency:o.REGRESSION_IMPACT_CALIBRATOR_CONCURRENCY});for(let e of f)S.add(async()=>{try{let r=e.fi.affectedSteps??[],i=await Bb({productChange:e.pc,techChanges:e.fi.techChanges??[],flow:e.fi.flow,commitMessages:l,gitSignals:h,runContext:d,affectedSteps:r,jwtToken:a,anthropicBaseUrl:s,rootPath:t});if(g+=i.costUsd,_+=i.turns,v||=i.maxTurnsHit,i.streamEnded===!0&&(x+=1),i.verdict===null){i.streamEnded!==!0&&(b+=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 o=e.pc.verdictScore,c=e.pc.verdictReason;e.pc.originalVerdictScore=o,e.pc.originalVerdictReason=c,i.verdict.changed?(e.pc.calibrationReason=`Calibrated ${o} → ${i.verdict.score}: ${i.verdict.reason}`,e.pc.verdictScore=i.verdict.score,e.pc.verdictReason=i.verdict.reason,y+=1,n.logger.info.defaultLog(`[regression-impact] Verdict calibrated for "${e.pc.title??`(untitled)`}": ${o} → ${i.verdict.score}`)):e.pc.calibrationReason=`Calibrator confirmed score ${o}: ${i.verdict.reason}`}catch(t){x+=1,n.logger.info.defaultLog(`[regression-impact] Verdict calibrator crashed for "${e.pc.title??`(untitled)`}" — partial API cost unrecoverable: ${String(t)}`)}});if(await S.onIdle(),x>0){let e=o.shouldLogDiagnostics?` — totalCost ($${g.toFixed(4)}) does not include their partial spend`:``;n.logger.info.defaultLog(`[regression-impact] Verdict calibration: ${x}/${f.length} call(s) crashed${e}`)}return{costUsd:g,turns:_,maxTurnsHit:v,calibratedCount:f.length,changedCount:y,failedCount:b,crashedCount:x}}var Hb=class{name=`verdictCalibration`;async execute(e){let t=mv(e),r=dv(e);if(e.branch===void 0||e.resolvedAnchorBranch===void 0||e.commitMessages===void 0||e.anchorBranch===void 0)throw Error(`[impact-pipeline] CalibrationStep requires branch/resolvedAnchorBranch/commitMessages/anchorBranch`);let i=e.globalConfigService.getContext()?.git,a=await Vb(t,r,e.branch,e.resolvedAnchorBranch,e.jwtToken,e.anthropicBaseUrl,e.isUncommitted,e.commitMessages,e.anchorSha,{owner:i?.owner,repo:i?.repository,anchorBranch:e.anchorBranch,anchorSha:e.anchorSha,branch:e.jobInput?.compareBranch??e.compareBranch??e.branch,headSha:e.headSha,runType:e.runType});if(a.calibratedCount>0){let{calibratedCount:e,changedCount:t,failedCount:r,crashedCount:i}=a,o=e-t-r-i;n.logger.info.defaultLog(`[regression-impact] Verdict calibration: ${t} changed, ${o} confirmed, ${r} failed (no verdict), ${i} crashed (out of ${e})`)}return{costUsd:a.costUsd,turns:a.turns,maxTurnsHit:a.maxTurnsHit}}};let Ub={type:`object`,additionalProperties:!1,required:[`steps`],properties:{steps:{type:`array`,items:{type:`object`,additionalProperties:!1,required:[`index`,`howToVerifySteps`],properties:{index:{type:`number`},howToVerifySteps:{type:`array`,items:{type:`string`}}}}}}};function Wb(){return["You write `howToVerify` for regressions already found in this repository. You do NOT re-judge the findings — for every finding you are given, your only job is the reproduction steps.",``,`**QA reader** — a QA engineer who verifies this in the running product and reports it. They do not read code. Write the way they think: about what they see and do in the product, not how it is built. **Every word counts** — no filler, no preamble, no restating the finding.`,``,`howToVerifySteps: the steps to reproduce the finding in the product, as an ARRAY with ONE STEP PER ELEMENT. Each element is ONE imperative action ("Open …", "Click …", "Re-run …"). The LAST element is the observable check — what they should see vs what they see now. These are actions to take; do not restate the finding's before/after.`,``,String.raw`Do NOT number the elements and do NOT put newlines inside one. Numbering and line breaks are added when the steps are stored and rendered — so ["Open the team page.", "Click Save.", "Confirm the member list shows the new name."], not ["1. Open the team page.\n2. Click Save."].`,``,`**Ground every step in the real product.** Use Read/Grep/Glob to confirm the screens, routes, labels, CLI commands, and API endpoints you name exist in this repo — start from each finding's file. Never invent navigation or UI that is not in the code; if you cannot ground a step, name the closest real surface you verified instead.`,``,`## No self-narration — in EVERY field`,`Never narrate your own investigation: no "Confirmed by reading…", "a grep of…", "I verified…". Emit only the actions the QA engineer takes.`,``,`## Output`,"Emit steps[] with exactly one entry per finding, carrying the finding's `index` unchanged. **Every finding you were given MUST get an entry** — a finding without reproduction steps is unusable to QA."].join(`
|
|
34179
|
+
`)}function Gb(e){return(Array.isArray(e.steps)?e.steps:[]).map(e=>({index:Number(e.index),howToVerify:(Array.isArray(e.howToVerifySteps)?e.howToVerifySteps:[]).map(e=>String(e??``).trim()).filter(e=>e.length>0).join(`
|
|
34180
|
+
`)})).filter(e=>Number.isInteger(e.index)&&e.howToVerify.length>0)}function Kb(e,t){let n=[`Repository checkout: ${e}`,``,`Compose howToVerify for the following ${t.length} regression(s):`,``];for(let[e,r]of t.entries()){let t=r.lines===void 0?``:` (${r.lines})`;n.push(`### index ${e}: ${r.title}`,`- file: ${r.file}${t}`,`- before: ${r.productBefore}`,`- after: ${r.productAfter}`,``)}return n.join(`
|
|
34181
|
+
`)}async function qb(e){let{query:t,getMessageContentBlocks:r,isResultMessage:a,isErrorResult:s}=await Promise.resolve().then(()=>lz()),c=t({prompt:Kb(e.rootPath,e.findings),options:{model:o.COMPOSE_VERIFY_MODEL,...o.REGRESSION_SONNET_SCORER_REASONING,systemPrompt:Wb(),allowedTools:[`Read`,`Grep`,`Glob`],permissionMode:`bypassPermissions`,allowDangerouslySkipPermissions:!0,maxBudgetUsd:e.maxBudgetUsd,maxTurns:e.maxTurns,cwd:e.rootPath,sessionId:(0,v.randomUUID)(),outputFormat:{type:`json_schema`,schema:Ub},env:{...process.env,...i.buildAnthropicSdkEnv({proxyUrl:e.anthropicBaseUrl,jwtToken:e.jwtToken??``,requestId:n.logger.getRequestId()})}}}),l=0;for await(let t of c){if(!a(t)){let e=r(t);e!==void 0&&e.length>0&&(l++,i.logAgentActivity(`compose-verify-steps`,l,e));continue}if(s(t))throw Error(`[compose-verify] Composer error: ${t.subtype}`);let o=t.structured_output;if(o===void 0){let r=(t.result??``).slice(0,300);return n.logger.info.defaultLog(`[compose-verify] Composer returned no structured_output — findings ship without howToVerify. stop_reason=${String(t.stop_reason)} result="${r}"`),{steps:[],costUsd:t.total_cost_usd,turns:t.num_turns,maxTurnsHit:t.num_turns>=e.maxTurns,tokens:i.ZERO_TOKENS,degraded:!0}}let c=Gb(o);return n.logger.info.defaultLog(`[compose-verify] Composer completed: costUsd=${t.total_cost_usd} turns=${t.num_turns} steps=${c.length}/${e.findings.length}`),{steps:c,costUsd:t.total_cost_usd,turns:t.num_turns,maxTurnsHit:t.num_turns>=e.maxTurns,tokens:i.extractCacheTokens(t),degraded:!1}}throw Error(`[compose-verify] Composer stream ended without a result message`)}let Jb={maxBudgetUsd:o.COMPOSE_VERIFY_MAX_BUDGET_USD,maxTurns:o.COMPOSE_VERIFY_MAX_TURNS};var Yb=class{name=`composeVerifySteps`;async execute(e){let t=(e.detectedRegressions??[]).filter(e=>e.score>=o.BEHAVIOR_REGRESSION_SCORE_THRESHOLD);if(t.length===0)return u_;if(e.rootPath===void 0)return n.logger.info.defaultLog(`[compose-verify] No rootPath on context — skipping howToVerify for ${t.length} regression(s).`),u_;try{let r=await qb({rootPath:e.rootPath,findings:t,maxBudgetUsd:Jb.maxBudgetUsd,maxTurns:Jb.maxTurns,jwtToken:e.jwtToken,anthropicBaseUrl:e.anthropicBaseUrl}),i=0;for(let e of r.steps)e.index<0||e.index>=t.length||(t[e.index].howToVerify=e.howToVerify,i++);return i<t.length&&n.logger.info.defaultLog(`[compose-verify] Composed howToVerify for ${i}/${t.length} regression(s); the rest ship without steps.`),{costUsd:r.costUsd,turns:r.turns,maxTurnsHit:r.maxTurnsHit,tokens:r.tokens}}catch(e){return n.logger.error(`[compose-verify] Compose failed — ${t.length} regression(s) ship without howToVerify`,e instanceof Error?e:Error(String(e))),u_}}},Xb=class{name=`consumerUncertainty`;async execute(e){let t=e.detectedRegressions??[],r=0;for(let e of t){if(!e.needsConsumerVerification||e.score<=5)continue;let t=e.score;e.score=5,e.reason=`${e.reason} [score set to 5 — uncertain: correctness depends on a consumer outside this repo, pending a cross-component check (was ${t})]`,r++}return r>0&&n.logger.info.defaultLog(`[consumer-uncertainty] set ${r} consumer-dependent finding(s) to score 5 (uncertain)`),u_}},Zb=class{name=`detectRegressions`;variant=`v1`;runDetect(e){return ub(e)}async execute(e){let t=dv(e);if(e.branch===void 0||e.resolvedAnchorBranch===void 0)throw Error(`[impact-pipeline] DetectRegressionsStep requires branch/resolvedAnchorBranch from ResolveCompare`);let r=e.changedFiles??[],i=o.getDiffForFiles(r,t,e.branch,e.resolvedAnchorBranch,e.isUncommitted),a=o.formatCommitMessagesBlock(e.commitMessages??[]),s=wy(e.jobInput,t),c=await this.runDetect({anchorRef:e.resolvedAnchorBranch,compareRef:e.branch,rootPath:t,diffText:i,commitMessagesBlock:a,jwtToken:e.jwtToken,anthropicBaseUrl:e.anthropicBaseUrl,primarySource:s.primarySource,dependencyRoots:s.dependencyRoots});if(c.errorSubtype!==void 0){let e=`[regression-first] detection did NOT complete (${c.errorSubtype}) after $${c.costUsd.toFixed(2)} / ${c.turns} turns — results are NOT trustworthy, NOT a clean diff. Raise REGRESSION_FIRST_MAX_BUDGET_USD for large diffs or reduce the changed-file set.`;throw n.logger.error(e,Error(c.errorSubtype)),Error(`Operation failed`)}let l=c.regressions.filter(Xy).length;if(l>0&&l===c.regressions.length){let e=`[regression-first] detection FAILED — all ${l} specialist agent(s) returned no parseable output (no real findings, only failure markers) after $${c.costUsd.toFixed(2)} / ${c.turns} turns. This is NOT a clean diff — likely the diff is too large to embed (agents hit "Prompt is too long") or otherwise unanalyzable. Results are NOT trustworthy. Reduce the changed-file set or rerun.`;throw n.logger.error(e,Error(`no-parseable-output`)),Error(`Operation failed`)}let u=c.regressions;return e.detectedRegressions=u,e.detectVariant=this.variant,e.detectCostUsd=c.costUsd,e.detectTurns=c.turns,e.detectTokens=c.tokens,{costUsd:c.costUsd,turns:c.turns,maxTurnsHit:c.maxTurnsHit,totalFiles:u.length,tokens:c.tokens,batches:c.subAgentMetrics}}},Qb=class extends Zb{name=`detectRegressionsExperiment`;variant=`experiment`;runDetect(e){return ub({...e,variant:`experiment`})}},$b=class extends Zb{name=`detectRegressionsMono`;variant=`mono`;runDetect(e){return ub({...e,variant:`mono`})}},ex=class extends Zb{name=`detectRegressionsSingle`;variant=`single`;runDetect(e){return ub({...e,variant:`single`})}},tx=class extends Zb{name=`detectRegressionsV2`;variant=`v2`;runDetect(e){return ub({...e,variant:`v2`})}},nx=class extends Zb{name=`detectRegressionsV3`;variant=`v3`;runDetect(e){return ub({...e,variant:`v3`})}};let rx=/^API request failed: 409\b/;function ix(e){return e instanceof Error&&rx.test(e.message)}async function ax(e,t){try{await e.post(`/api/v1/regression/flow-library`,{projectId:t,flowId:o.REGRESSION_FIRST_SENTINEL_FLOW_ID,name:o.REGRESSION_FIRST_SENTINEL_FLOW_NAME,description:`Findings from the regression-first (regression-locator) command that aren't attributed to any cataloged flow.`,importance:`MEDIUM`,importanceReason:`Sentinel bucket — importance reflects the underlying findings, not this row itself.`,rank:1}),n.logger.info.defaultLog(`[regression-first] Created sentinel flow "${o.REGRESSION_FIRST_SENTINEL_FLOW_ID}" for project ${t}`)}catch(e){if(ix(e)){n.logger.info.defaultLog(`[regression-first] Sentinel flow "${o.REGRESSION_FIRST_SENTINEL_FLOW_ID}" already exists for project ${t}`);return}throw e}}var ox=class{name=`ensureRegFirstSentinelFlow`;async execute(e){let t=e.jobInput?.projectId??e.globalConfigService.getProjectId();if(t===void 0||t.length===0)throw Error(`[regression-first] EnsureRegFirstSentinelFlowStep requires a projectId`);await ax(e.apiService,t),e.sentinelFlowId=o.REGRESSION_FIRST_SENTINEL_FLOW_ID;let r=e.bundle;if(r!==void 0&&!r.flows.some(e=>e.flowId===o.REGRESSION_FIRST_SENTINEL_FLOW_ID)){let t=(await Q_(e.apiService,e.globalConfigService,e.jobInput))?.flows.find(e=>e.flowId===o.REGRESSION_FIRST_SENTINEL_FLOW_ID);t===void 0?n.logger.info.defaultLog(`[regression-first] Sentinel flow "${o.REGRESSION_FIRST_SENTINEL_FLOW_ID}" still missing from the flow library after ensure — this run's findings may not display on the web UI`):r.flows.push(t)}return u_}};let sx='- A commit message in the "Commit messages" section may be truncated (it ends with "… (commit message truncated — run `git show …`)"). If that commit\'s intent is relevant to your verdict, RUN the provided `git show -s --format=%B <hash>` command via Bash to read the full message. Bash is allowed ONLY for read-only `git show`/`git diff` lookups — never for cat/find/writes.',cx='\n- The diff below may be BUDGETED: large changes are packed whole up to a size limit and the rest are listed under an "── OMITTED ──" footer with the exact `git diff` command for each. If a file relevant to a flow is in that OMITTED list (or you otherwise need a change the diff does not show), RUN the provided `git diff … -- <file>` command via Bash to read its real diff. Bash is allowed ONLY for these read-only `git diff`/`git show` lookups — never for cat/find/writes.',lx=`## Dependency roots (multi-root projects)
|
|
34182
34182
|
|
|
34183
34183
|
A flow may CALL INTO a dependency root (a sibling dir in the same repo, e.g.
|
|
34184
34184
|
\`common/\`, \`contracts/\`, a shared package) that lives outside the primary
|
|
@@ -34188,7 +34188,7 @@ change the flow's behavior — judge it as in-scope, not as "outside the project
|
|
|
34188
34188
|
\`entryFiles\` are relative to the primary project; \`calledModules\` may be
|
|
34189
34189
|
relative to the working directory (the common ancestor spanning the primary
|
|
34190
34190
|
project and its dependency roots) — resolve both consistently, and Read/Grep to
|
|
34191
|
-
confirm a real connection when the paths don't line up textually.`;function
|
|
34191
|
+
confirm a real connection when the paths don't line up textually.`;function ux(){return`You are a senior software engineer reading a batch of git diffs and describing what each file's code change does — purely at the technical level, with no flow/business context.
|
|
34192
34192
|
|
|
34193
34193
|
## Your task
|
|
34194
34194
|
For EACH file given below, write a techChange entry describing what changed:
|
|
@@ -34205,8 +34205,8 @@ For EACH file given below, write a techChange entry describing what changed:
|
|
|
34205
34205
|
|
|
34206
34206
|
## Output format
|
|
34207
34207
|
{ "techChanges": [ { "file": "...", "confidence": "high|low", "techBefore": "...", "techAfter": "..." }, ... ] }
|
|
34208
|
-
One entry per file in the batch, in any order. Do NOT emit productChanges or affectedSteps.`}function
|
|
34209
|
-
`);return`## Files in this batch (${e.length})\n${o}\n\n${a}\n\nEmit one techChange entry per file above.`}function
|
|
34208
|
+
One entry per file in the batch, in any order. Do NOT emit productChanges or affectedSteps.`}function dx(e,t,n,r){let i=t.length>6e4?`${t.slice(0,6e4)}\n... (truncated)`:t,a=t.length>0?`## Git diff for this batch (${n} vs ${r}):\n\`\`\`\n${i}\n\`\`\``:`## Git diff for this batch (${n} vs ${r}):\n(no diff available — files may be untracked)`,o=e.map(e=>{let t=(0,m.isDefined)(e.reason)?`\n mapper note: ${e.reason}`:``;return`- ${e.file}${t}`}).join(`
|
|
34209
|
+
`);return`## Files in this batch (${e.length})\n${o}\n\n${a}\n\nEmit one techChange entry per file above.`}function fx(){return`You are a senior software engineer tracing how a code change affects a critical flow's observable behavior. The technical "what changed" has already been derived per-file (pass 1) and is provided to you below — your job is to judge the PRODUCT-level impact for THIS flow. Focus on what changes from the user/caller's perspective.
|
|
34210
34210
|
|
|
34211
34211
|
## What you receive
|
|
34212
34212
|
- flow metadata (name, entry points, why it matters, product flow steps)
|
|
@@ -34218,7 +34218,7 @@ One entry per file in the batch, in any order. Do NOT emit productChanges or aff
|
|
|
34218
34218
|
- Use the Read tool to read files, not Bash with cat
|
|
34219
34219
|
- RELOCATION CHECK (do this BEFORE flagging any "removed" code as a regression): when a techChange reports that a NAMED, top-level symbol was removed — in ANY language, e.g. a function/method, class/struct/interface/enum, constant, registered task/handler/route, or an import/include/use/require statement (NOT an edit to lines inside a symbol that still exists) — verify it was not simply MOVED before treating it as a deletion. A move pushes both halves into this same PR, so look for the symbol being RE-ADDED, cheapest source first: (1) scan the techChanges/diff already provided for the symbol re-appearing in another file; (2) if a candidate target file is omitted/budgeted, run its \`git diff\` to read it; (3) only if neither shows it, \`Grep\` the tree for the symbol (covers a move into a file that pre-existed the anchor). The symbol may be RENAMED on the move (e.g. \`_notify_slack_500\` → \`_notify_error_500\`) — match by code/behavior, not just by name. If it reappears elsewhere with callers/importers updated to the new location, it is a RELOCATION (refactor) — score 1–2 and do NOT report a removal/breakage risk. Only when the symbol appears NOWHERE is it a genuine removal worth flagging.
|
|
34220
34220
|
|
|
34221
|
-
${
|
|
34221
|
+
${lx}
|
|
34222
34222
|
|
|
34223
34223
|
## Your task:
|
|
34224
34224
|
1. The "Pre-computed techChanges" section gives the connection AND what changed per file — the heavy "describe the diff" work is already done. Do NOT re-derive techBefore/techAfter from scratch. Use Read/Grep only to verify a techChange that looks wrong in this flow's context, or to inspect a changed function's callers for compatibility (changed return values, removed parameters, new error paths, changed defaults). This is where regressions hide.
|
|
@@ -34348,7 +34348,7 @@ Only output \`priority\` when \`verdict.score >= 5\` (change is likely a regress
|
|
|
34348
34348
|
- 1: fix immediately — CRITICAL severity with HIGH+ importance, or HIGH severity on a CRITICAL importance behavior in a high-catalog-score flow
|
|
34349
34349
|
- 2: fix this release — CRITICAL severity with MEDIUM or lower importance, HIGH severity, MEDIUM severity with CRITICAL/HIGH importance, or MEDIUM severity in a high-catalog-score flow
|
|
34350
34350
|
- 3: fix soon — MEDIUM severity with MEDIUM or lower importance, or LOW severity with HIGH+ importance
|
|
34351
|
-
- 4: backlog — LOW severity with MEDIUM or lower importance`}function
|
|
34351
|
+
- 4: backlog — LOW severity with MEDIUM or lower importance`}function px(e,t,n,r,i){let a=(0,m.isDefined)(e.productFlow)&&e.productFlow.steps.length>0?`
|
|
34352
34352
|
## Product Flow Steps:
|
|
34353
34353
|
**Trigger:** ${e.productFlow.trigger}
|
|
34354
34354
|
${e.productFlow.steps.map(e=>`- [${e.stepId}] **${e.actor}** → ${e.action} → _${e.outcome}_`).join(`
|
|
@@ -34371,7 +34371,7 @@ ${a}
|
|
|
34371
34371
|
## Pre-computed techChanges for the files in this flow
|
|
34372
34372
|
${s.length>0?s:`(no files mapped to this flow)`}
|
|
34373
34373
|
|
|
34374
|
-
Judge the productChanges, severity, importance, priority, verdict, and affectedSteps for THIS flow. List the in-scope files as **inScopeFiles** (string[] of file paths from the techChanges above) — drop any that don't affect this flow's observable behavior. Do NOT re-emit techBefore/techAfter; the pipeline already has them.`}function
|
|
34374
|
+
Judge the productChanges, severity, importance, priority, verdict, and affectedSteps for THIS flow. List the in-scope files as **inScopeFiles** (string[] of file paths from the techChanges above) — drop any that don't affect this flow's observable behavior. Do NOT re-emit techBefore/techAfter; the pipeline already has them.`}function mx(e=!1){return`You are a senior software engineer judging how a code change affects MULTIPLE related product flows IN ONE PASS. ${e?`Per-file technical changes are NOT pre-computed — the user prompt contains the raw git diff. For each in-scope file you reference, derive techBefore (one or two sentences — what the file/function did BEFORE the diff) and techAfter (one or two sentences — what it does AFTER) yourself, AND judge the PRODUCT-level impact for EACH flow in this group, independently.`:`Per-file technical changes have already been derived (pass 1) and are provided below as a SHARED techChanges list. Your job is to score the PRODUCT-level impact for EACH flow in this group, independently — using ONLY that flow's metadata and the files attributed to it.`}
|
|
34375
34375
|
|
|
34376
34376
|
## What you receive
|
|
34377
34377
|
- a group of related flows (they share most of their changed files — that's why they're grouped)
|
|
@@ -34383,10 +34383,10 @@ Judge the productChanges, severity, importance, priority, verdict, and affectedS
|
|
|
34383
34383
|
- Investigate each shared file AT MOST ONCE. Use Read/Grep/Glob to verify a techChange or check callers when needed — but if you already read a file for one flow in this group, do NOT read it again for another flow.
|
|
34384
34384
|
- RELOCATION CHECK (do this BEFORE flagging any "removed" code as a regression): when a techChange reports that a NAMED, top-level symbol was removed — in ANY language, e.g. a function/method, class/struct/interface/enum, constant, registered task/handler/route, or an import/include/use/require statement (NOT an edit to lines inside a symbol that still exists) — verify it was not simply MOVED before treating it as a deletion. A move pushes both halves into this same PR, so look for the symbol being RE-ADDED, cheapest source first: (1) scan the diff already shown for the symbol re-appearing in another file; (2) if a candidate target file sits in the OMITTED footer, run its provided \`git diff\` to read it; (3) only if neither shows it, \`Grep\` the tree for the symbol (covers a move into a file that pre-existed the anchor). The symbol may be RENAMED on the move (e.g. \`_notify_slack_500\` → \`_notify_error_500\`) — match by code/behavior, not just by name. If it reappears elsewhere and the callers/importers were updated to the new location, it is a RELOCATION (refactor), not a removal — score it 1–2 and do NOT report a removal/breakage risk. Only when the symbol appears NOWHERE is it a genuine removal worth flagging.
|
|
34385
34385
|
- Do NOT use \`find\` — use the Glob tool. Do NOT spawn sub-agents (Task). Use Read for file contents, not Bash with cat.
|
|
34386
|
-
${
|
|
34386
|
+
${sx}${e?cx:``}
|
|
34387
34387
|
- Do NOT re-derive techBefore/techAfter — they are already provided. Pick which files are inScope per flow.
|
|
34388
34388
|
|
|
34389
|
-
${
|
|
34389
|
+
${lx}
|
|
34390
34390
|
|
|
34391
34391
|
## Your task per flow
|
|
34392
34392
|
1. Pick **inScopeFiles** for the flow — the subset of the group's files that actually affect THIS flow's observable behavior. Use file paths EXACTLY as given.
|
|
@@ -34495,7 +34495,7 @@ Only output \`priority\` when \`verdict.score >= 5\`. Weigh severity, behavior i
|
|
|
34495
34495
|
- 1: fix immediately — CRITICAL severity with HIGH+ importance, or HIGH severity on a CRITICAL behavior in a high-catalog-score flow
|
|
34496
34496
|
- 2: fix this release — CRITICAL severity with MEDIUM- importance, HIGH severity, MEDIUM severity with CRITICAL/HIGH importance, or MEDIUM severity in a high-catalog-score flow
|
|
34497
34497
|
- 3: fix soon — MEDIUM severity with MEDIUM- importance, or LOW severity with HIGH+ importance
|
|
34498
|
-
- 4: backlog — LOW severity with MEDIUM- importance`}function
|
|
34498
|
+
- 4: backlog — LOW severity with MEDIUM- importance`}function hx(e,t,n,r,i,a,s,c){let l=new Set(e.flatMap(e=>e.changedFiles)),u=s===void 0?[]:Object.entries(s).filter(([e])=>l.has(e)),d=u.map(([e,t])=>`| ${e} | ${t.fileAgeDays===0?`new/unknown`:`${t.fileAgeDays}d ago`} | ${t.authorCommits} | ${t.bugFixCommits} | ${t.revertCommits} |`).join(`
|
|
34499
34499
|
`),f=u.length>0?`\n## Git signals (pre-computed):\n| File | Last touched | Author commits (90d) | Fix commits (90d) | Revert commits (90d) |\n|---|---|---|---|---|\n${d}\n`:``,p=t.map(e=>`- **${e.file}** (confidence: ${e.confidence})\n before: ${e.techBefore}\n after: ${e.techAfter}`).join(`
|
|
34500
34500
|
`),h=e.map(e=>{let t=(0,m.isDefined)(e.flow.productFlow)&&e.flow.productFlow.steps.length>0?`**Product Flow:**\n**Trigger:** ${e.flow.productFlow.trigger}\n${e.flow.productFlow.steps.map(e=>`- [${e.stepId}] **${e.actor}** → ${e.action} → _${e.outcome}_`).join(`
|
|
34501
34501
|
`)}\n**Outcome:** ${e.flow.productFlow.outcome}`:``,n=c?.get(e.flow.flowId),r=e.changedFiles.length>0?e.changedFiles.map(e=>{let t=n?.get(e);return(0,m.isDefined)(t)?`${e} (mapper: ${t})`:e}).join(`, `):`(none)`;return`### Flow
|
|
@@ -34527,7 +34527,7 @@ ${h}
|
|
|
34527
34527
|
|
|
34528
34528
|
${_}
|
|
34529
34529
|
|
|
34530
|
-
${v}`}function
|
|
34530
|
+
${v}`}function gx(e=!1){return`You are a senior software engineer checking whether a code change introduced a REGRESSION in one or more product flows. ${e?`Per-file technical changes are NOT pre-computed — the user prompt contains the raw git diff. For each file attributed to a flow, derive techBefore/techAfter yourself from the diff, AND perform the contract-divergence analysis for EACH flow in this group, independently.`:`Per-file technical changes have already been derived (pass 1) and are provided below as a SHARED techChanges list. Perform the contract-divergence analysis for EACH flow in this group, independently — using that flow's metadata + the files attributed to it.`}
|
|
34531
34531
|
|
|
34532
34532
|
Your job has TWO parts per flow:
|
|
34533
34533
|
1. **Detect the divergence:** the flow is SUPPOSED to do X; decide whether after this change it can do Y != X on any path (including the failure path). If X == Y everywhere, there is no change — clear the flow.
|
|
@@ -34544,10 +34544,10 @@ The verdict.score answers part 2: **how likely is this an UNWANTED regression?**
|
|
|
34544
34544
|
- Treat each flow independently. Do NOT carry context, severity, or verdict between flows.
|
|
34545
34545
|
- Investigate each shared file AT MOST ONCE across the group. Use Read/Grep/Glob to confirm what the code now does — but do not re-read a file you already read for another flow in this group.
|
|
34546
34546
|
- Do NOT use \`find\` — use Glob. Do NOT spawn sub-agents (Task). Use Read for file contents, not Bash with cat.
|
|
34547
|
-
${
|
|
34547
|
+
${sx}${e?cx:``}
|
|
34548
34548
|
- Do NOT re-derive techBefore/techAfter when they are provided — use them.
|
|
34549
34549
|
|
|
34550
|
-
${
|
|
34550
|
+
${lx}
|
|
34551
34551
|
|
|
34552
34552
|
## Your task per flow — reason in THIS order before scoring
|
|
34553
34553
|
The files attributed to this flow are GIVEN to you (by the upstream file-to-flow mapping) and are authoritative — do NOT re-decide which files are in scope or drop a file because you think it doesn't reach this flow. Take ALL attributed files as in-scope and judge whether the flow's BEHAVIOR diverges. You may still clear the flow, but ONLY via the X == Y test below (no divergence), never via a scope argument.
|
|
@@ -34650,14 +34650,14 @@ Only output \`priority\` when \`verdict.score >= 5\`. Weigh severity, behavior i
|
|
|
34650
34650
|
- 1: fix immediately — CRITICAL severity with HIGH+ importance, or HIGH severity on a CRITICAL behavior in a high-catalog-score flow
|
|
34651
34651
|
- 2: fix this release — CRITICAL severity with MEDIUM- importance, HIGH severity, MEDIUM severity with CRITICAL/HIGH importance, or MEDIUM severity in a high-catalog-score flow
|
|
34652
34652
|
- 3: fix soon — MEDIUM severity with MEDIUM- importance, or LOW severity with HIGH+ importance
|
|
34653
|
-
- 4: backlog — LOW severity with MEDIUM- importance`}function
|
|
34653
|
+
- 4: backlog — LOW severity with MEDIUM- importance`}function _x(e,t,r,i,a){try{let o=I.default.join(e,`reports`,`deep-prompts`);(0,y.mkdirSync)(o,{recursive:!0});let s=new Date().toISOString().replaceAll(/[:.]/g,`-`),c=I.default.join(o,`${s}-${t}.prompt.log`),l=`${a===void 0?``:`# TOOLS / CONFIG\n\n${JSON.stringify(a,null,2)}\n\n`}# SYSTEM PROMPT\n\n${r}\n\n# USER PROMPT\n\n${i}\n`;(0,y.writeFileSync)(c,l,`utf8`),n.logger.info.defaultLog(`[regression-impact] Deep prompt (${t}) written to ${c}`)}catch(e){n.logger.info.defaultLog(`[regression-impact] Failed to write deep prompt (${t}): ${String(e)}`)}}function vx(e){return e.replaceAll(/[^A-Za-z0-9._-]+/g,`_`)}function yx(e,t){let n=[...e].sort((e,t)=>t.changedFiles.length-e.changedFiles.length),r=[];for(let e of n){let n=bx(e,r,t);n===void 0?r.push([e]):n.push(e)}return r}function bx(e,t,n){let r=new Set(e.changedFiles),i,a=0;for(let e of t){if(e.length>=n.maxGroupSize)continue;let t=xx(r,new Set(e.flatMap(e=>e.changedFiles)));t>a&&t>=n.minOverlap&&(a=t,i=e)}return i}function xx(e,t){let n=0;for(let r of e)t.has(r)&&(n+=1);let r=new Set([...e,...t]).size;return r===0?0:n/r}function Sx(e,t,n){let r=Object.keys(e);if(t<=0)return{diff:r.map(t=>e[t]).join(`
|
|
34654
34654
|
`),omittedFiles:[]};let i=[...r].sort((t,n)=>{let r=e[n].length-e[t].length;return r===0?t.localeCompare(n):r}),a=[],o=[],s=0;for(let n of i){let r=e[n],i=s+r.length<=t,c=a.length===0&&r.length>t;if(i||c){a.push(r),s+=r.length;continue}o.push(n)}let c=a.join(`
|
|
34655
|
-
`);return o.length===0?{diff:c,omittedFiles:o}:{diff:`${c}\n${
|
|
34656
|
-
`)}var
|
|
34657
|
-
`),r=this.sizeCache.get(n);if(r!==void 0)return r;let i=this.measureUnionDiffChars(t);return this.sizeCache.set(n,i),i}};function
|
|
34658
|
-
`),r=e.get(n);if(r!==void 0)return r;let i=this.fetchDiff(t);return e.set(n,i),i}}capDiff(e,t){let r=this.diffCapChars;return r<=0||e.length<=r?e:(n.logger.info.defaultLog(`[regression-impact] pass2-group #${t}: raw diff truncated ${e.length} → ${r} chars (use Read/Grep to inspect omitted files)`),`${e.slice(0,r)}\n... (diff truncated at ${r} chars — use Read/Grep/Glob to inspect the rest)`)}},Ox=class{constructor(e,t){this.resultApplier=e,this.shouldUseContractEngine=t}async run(e,t,r){let a=new Dx(e=>o.getDiffForFiles(e,r.rootPath,r.branch,r.resolvedAnchorBranch,r.isUncommitted),{fetchPerFileDiffs:e=>o.getPerFileDiffs(e,r.rootPath,r.branch,r.resolvedAnchorBranch,r.isUncommitted),gitDiffCommandFor:e=>r.isUncommitted?`git diff -- ${e}`:`git diff ${r.resolvedAnchorBranch}...${r.branch} -- ${e}`}).plan(e),s=new A.default({concurrency:o.REGRESSION_IMPACT_DEEP_PASS2_CONCURRENCY}),c=(await Promise.all([...a.entries()].map(([e,i])=>s.add(async()=>{let{group:a,rawDiff:o}=i,s=[...new Set(a.flatMap(e=>e.changedFiles))].map(e=>t.get(e)).filter(m.isDefined);try{let t=Date.now();return{fgi:e,group:a,sharedTech:s,rawDiff:o,result:await this.runPerGroupPass(a,s,r,e+1,o),elapsedSec:((Date.now()-t)/1e3).toFixed(1)}}catch(t){return n.logger.info.defaultLog(`[regression-impact] Pass 2 grouped crashed for sub-group #${e+1} (${a.length} flow(s)): ${String(t)}`),{fgi:e,group:a,sharedTech:s,rawDiff:o,result:void 0,elapsedSec:`0.0`}}})))).filter(e=>e!==void 0).sort((e,t)=>e.fgi-t.fgi),l=0,u=0,d=!1,f=!1,p=0,h=0,g=0,_=0,v=[],y=0;for(let e of c){let{fgi:r,group:i,sharedTech:o,rawDiff:s,result:c,elapsedSec:b}=e;y+=1;let x=s===void 0?``:`, raw diff ${s.length} chars`,S=new Set(i.flatMap(e=>e.changedFiles)).size;if(n.logger.info.defaultLog(`[regression-impact] pass2-group ${y}/${a.length} - sub-group #${r+1} (${i.length} flow(s), ${S} unique file(s), ${o.length} pre-derived tech${x})`),c===void 0){n.logger.info.defaultLog(`[regression-impact] Pass 2 grouped returned null for sub-group #${r+1} — keeping default severities for ${i.length} flow(s)`);continue}n.logger.info.defaultLog(`[regression-impact] pass2-group sub-group #${r+1} DONE in ${b}s (${i.length} flow(s), ${c.turns} turns)`),l+=c.costUsd,u+=c.turns,d||=c.maxTurnsHit,f||=c.maxBudgetHit,p+=c.tokens.cacheReadTokens,h+=c.tokens.cacheCreationTokens,g+=c.tokens.inputTokens,_+=c.tokens.outputTokens,v.push({label:`group-${r+1} (${i.length} flow${i.length===1?``:`s`})`,costUsd:c.costUsd,turns:c.turns,maxTurnsHit:c.maxTurnsHit,maxBudgetHit:c.maxBudgetHit,tokens:{inputTokens:c.tokens.inputTokens,outputTokens:c.tokens.outputTokens,cacheReadTokens:c.tokens.cacheReadTokens,cacheCreationTokens:c.tokens.cacheCreationTokens}});let C=new Map(c.structured.flows.map(e=>[e.flowId,e]));for(let e of i){let i=C.get(e.flow.flowId);if(i===void 0){n.logger.info.defaultLog(`[regression-impact] Pass 2 grouped: no entry for flow "${e.flow.name}" (${e.flow.flowId}) in sub-group #${r+1} — keeping default severity`);continue}let a=e.changedFiles.map(e=>t.get(e)).filter(m.isDefined);this.resultApplier.apply(e,{structured:i},a)}}return i.logCacheTokens(`pass 2 totals`,{cacheReadTokens:p,cacheCreationTokens:h,inputTokens:g,outputTokens:_}),{costUsd:l,turns:u,maxTurnsHit:d,maxBudgetHit:f,tokens:{inputTokens:g,outputTokens:_,cacheReadTokens:p,cacheCreationTokens:h},batches:v}}async runPerGroupPass(e,t,r,a,s){let{query:c,getMessageContentBlocks:l,isResultMessage:u,isErrorResult:d}=await Promise.resolve().then(()=>lz()),f=`grouped-pass2 #${a}`,p=mx(e,t,r.branch,r.resolvedAnchorBranch,r.commitMessages,s,r.gitSignals,r.flowFileReasons),m=this.shouldUseContractEngine??o.REGRESSION_IMPACT_DEEP_CONTRACT_MODE,h=m?`divergence (X!=Y)`:`intent-rubric (20-signal)`,g=m?hx(s!==void 0):px(s!==void 0);n.logger.info.defaultLog(`[regression-impact] grouped pass2 group ${a}: deep engine = ${h}`),o.REGRESSION_IMPACT_LOG_DEEP_PROMPT&&gx(r.rootPath,`pass2-group-${a}`,g,p,{model:o.REGRESSION_IMPACT_DEEP_MODEL,allowedTools:[`Read`,`Grep`,`Glob`,`Bash`],maxTurns:o.REGRESSION_IMPACT_DEEP_MAX_TURNS,maxBudgetUsd:o.REGRESSION_IMPACT_DEEP_MAX_BUDGET_USD,outputSchema:`SONNET_DEEP_GROUPED_OUTPUT_SCHEMA`});let _=c({prompt:p,options:{model:o.REGRESSION_IMPACT_DEEP_MODEL,systemPrompt:g,allowedTools:[`Read`,`Grep`,`Glob`,`Bash`],permissionMode:o.REGRESSION_PERMISSION_MODE,allowDangerouslySkipPermissions:!0,maxBudgetUsd:o.REGRESSION_IMPACT_DEEP_MAX_BUDGET_USD,maxTurns:o.REGRESSION_IMPACT_DEEP_MAX_TURNS,cwd:r.rootPath,sessionId:(0,v.randomUUID)(),outputFormat:{type:`json_schema`,schema:i.SONNET_DEEP_GROUPED_OUTPUT_SCHEMA},env:{...process.env,...i.buildAnthropicSdkEnv({proxyUrl:r.anthropicBaseUrl,jwtToken:r.jwtToken??``,requestId:n.logger.getRequestId()})}}});i.logAgentCwd(f,r.rootPath);let y=0;for await(let e of _){if(!u(e)){let t=l(e);t!==void 0&&t.length>0&&(y++,i.logAgentActivity(f,y,t));continue}if(d(e)){n.logger.info.defaultLog(`[regression-impact] Pass 2 grouped error for group #${a}: ${String(e.subtype)}`);return}let t=e.total_cost_usd,r=e.num_turns,s=r>=o.REGRESSION_IMPACT_DEEP_MAX_TURNS,c=i.logCacheTokensFromMessage(`pass2 group #${a}`,e),p=e.structured_output;if(p===void 0||!Array.isArray(p.flows)){n.logger.info.defaultLog(`[regression-impact] Pass 2 grouped: missing or malformed structured_output for group #${a}`);return}return{structured:p,costUsd:t,turns:r,maxTurnsHit:s,maxBudgetHit:!1,tokens:c}}}};let kx=[`NONE`,`LOW`,`MEDIUM`,`HIGH`,`CRITICAL`];function Ax(e){if(e==null)return;let t=typeof e==`number`?e:Number(e);if(!(!Number.isFinite(t)||!Number.isInteger(t)||t<1||t>4))return t}function jx(e){if(typeof e!=`object`||!e)return;let t=e.inScopeFiles;if(Array.isArray(t))return t.filter(e=>typeof e==`string`)}var Mx=class{apply(e,t,n){let r=jx(t.structured),i=n.length===0&&Array.isArray(t.structured.techChanges)&&t.structured.techChanges.length>0?t.structured.techChanges.map(e=>({file:e.file,confidence:e.confidence,techBefore:e.techBefore,techAfter:e.techAfter})):n,a=new Map(i.map(e=>[e.file,e])),o=(r===void 0?i:r.map(e=>a.get(e)).filter(m.isDefined)).map(e=>({file:e.file,confidence:e.confidence,techBefore:e.techBefore,techAfter:e.techAfter})),s=t.structured.productChanges.map(e=>{let t=Ax(e.priority);return{...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},...t===void 0?{}:{priority:t},...e.verdict===void 0?{}:{verdictScore:e.verdict.score,...e.verdict.reason===void 0?{}:{verdictReason:e.verdict.reason}}}}),c=this.deriveSeverity(s);e.severity=c,e.severityReason=s.find(e=>e.severity===c)?.severityReason,e.techChanges=o,e.productChanges=s,t.structured.affectedSteps!==void 0&&(e.affectedSteps=this.enrichAffectedSteps(e.flow,t.structured.affectedSteps)),e.uncertain===!0&&(e.affected=c!==`NONE`,e.uncertain=!1)}deriveSeverity(e){return e.length===0?`NONE`:e.reduce((e,t)=>kx.indexOf(t.severity)>kx.indexOf(e)?t.severity:e,`NONE`)}enrichAffectedSteps(e,t){if(!(0,m.isDefined)(e.productFlow))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,m.isDefined)(t))return{stepId:e.stepId,actor:t.actor,action:t.action,reason:e.reason}}).filter(m.isDefined)}};function Nx(e){let t=uv(e),n=mv(e),r=dv(e);if(e.branch===void 0||e.resolvedAnchorBranch===void 0||e.commitMessages===void 0)throw Error(`[impact-pipeline] buildDeepRunContext requires branch/resolvedAnchorBranch/commitMessages`);let i=n.filter(e=>e.affected&&e.severity!==`NONE`&&e.severity!==void 0||e.uncertain===!0),a=[...new Set(i.flatMap(e=>e.changedFiles))],s=o.getAuthorEmail(r,e.branch,e.isUncommitted),c=o.getGitSignalsForFiles(r,a,s,e.anchorSha,e.resolvedAnchorBranch),l=new Map(t.map(e=>[e.flowId,e]));return{rootPath:r,branch:e.branch,resolvedAnchorBranch:e.resolvedAnchorBranch,jwtToken:e.jwtToken,anthropicBaseUrl:e.anthropicBaseUrl,isUncommitted:e.isUncommitted,commitMessages:e.commitMessages,anchorSha:e.anchorSha,flowFileReasons:e.flowFileReasons,flowsByFlowId:l,gitSignals:c}}var Px=class{async execute(e){let t=mv(e).filter(e=>e.affected&&e.severity!==`NONE`&&e.severity!==void 0||e.uncertain===!0);if(t.length===0)return{costUsd:0,turns:0,maxTurnsHit:!1};let n=Nx(e),r=await this.createStrategy(new Mx).run(t,e.fileTechByFile??new Map,n);return{costUsd:r.costUsd,turns:r.turns,maxTurnsHit:r.maxTurnsHit,maxBudgetHit:r.maxBudgetHit??!1,tokens:r.tokens,batches:r.batches}}},Fx=class extends Px{name;constructor(e){super(),this.shouldUseContractEngine=e,this.name=`groupedDeepAnalysis (${e??o.REGRESSION_IMPACT_DEEP_CONTRACT_MODE?`divergence`:`intent-rubric`})`}createStrategy(e){return new Ox(e,this.shouldUseContractEngine)}};function Ix(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,m.isDefined)(t))return{stepId:e.stepId,actor:t.actor,action:t.action,reason:e.reason}}).filter(m.isDefined)}async function Lx(e,t,r,i,a,s,c,l,u,d){let f=e.filter(e=>e.affected&&e.severity!==`NONE`&&e.severity!==void 0),p=e.filter(e=>e.uncertain===!0),m=[...f,...p.filter(e=>!f.includes(e))],h=0;if(n.logger.info.defaultLog(`[regression-impact] Sonnet deep analysis for ${m.length} flow(s) (${f.length} affected, ${p.length} uncertain) in parallel...`),m.length===0)return{costUsd:0,turns:0,maxTurnsHit:!1};let g=[...new Set(m.flatMap(e=>e.changedFiles))],_=o.getAuthorEmail(t,r,c),v=o.getGitSignalsForFiles(t,g,_,u,i),y=0,b=0,x=!1,S=new A.default({concurrency:6});for(let e of m)S.add(async()=>{try{h+=1,n.logger.info.defaultLog(`[regression-impact] ${h} - Sonnet deep analysis: ${e.flow.name} (${e.changedFiles.length} file(s))`);let o=await c_(e.flow,e.changedFiles,t,r,i,a,s,c,l,v,d?.get(e.flow.flowId));if(o===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}y+=o.costUsd,b+=o.turns,x||=o.maxTurnsHit,Rx(e,o)}catch(t){n.logger.info.defaultLog(`[regression-impact] Sonnet deep crashed for flow "${e.flow.name}": ${String(t)}`)}});return await S.onIdle(),{costUsd:y,turns:b,maxTurnsHit:x}}function Rx(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=Ix(e.flow,t.affectedSteps)),e.uncertain===!0&&(e.affected=t.severity!==`NONE`,e.uncertain=!1)}var zx=class{name=`deepAnalysis`;async execute(e){let t=mv(e),n=dv(e);if(e.branch===void 0||e.resolvedAnchorBranch===void 0||e.commitMessages===void 0)throw Error(`[impact-pipeline] LegacyDeepStep requires branch/resolvedAnchorBranch/commitMessages`);let r=await Lx(t,n,e.branch,e.resolvedAnchorBranch,e.jwtToken,e.anthropicBaseUrl,e.isUncommitted,e.commitMessages,e.anchorSha,e.flowFileReasons);return{costUsd:r.costUsd,turns:r.turns,maxTurnsHit:r.maxTurnsHit}}},Bx=class{name=`loadLibraryForSpecificRun`;async execute(e){let t=e.jobInput?.baselineFromAnalysisId?.trim()??``;if(t.length===0)throw Error(`[impact-pipeline] LoadBaselineFromRunStep requires jobInput.baselineFromAnalysisId — the factory should only select this step when it is set`);let{bundle:r,anchorBranch:i,anchorSha:a,catalogId:s,projectType:c,flows:l}=await rv(e.apiService,e.jobInput,t);if(e.jobInput===null)throw Error(`[impact-pipeline] jobInput is required to resolve catalog roots`);let u;try{u=Rm(e.jobInput)}catch(e){throw Error(`[impact-pipeline] failed to resolve catalog roots: ${String(e)}`,{cause:e})}let d=u.cwd,f=Z_(d,i,a,e.isUncommitted),p=o.getCommitMessages(d,f),h=(0,m.isDefined)(a)?`, sha: ${a}`:``;return n.logger.info.defaultLog(`[regression-impact] Anchor: ${i} (resolved: ${f}${h}) — baseline reused from run ${t}`),e.bundle=r,e.flows=l,e.catalogId=s,e.projectType=c,e.anchorBranch=i,e.anchorSha=a,e.resolvedAnchorBranch=f,e.rootPath=d,e.primarySource=u.primarySource,e.dependencyRoots=u.dependencyRoots,e.commitMessages=p,u_}},Vx=class{name=`mappingSnapshotRead`;execute(e){let t=by(dv(e));if(t===void 0)throw Error(`[impact-pipeline] mapping snapshot resume expected a cache file but none loaded — delete the snapshot or disable REGRESSION_IMPACT_DEV_MAPPING_SNAPSHOT`);let r=[...new Set([...t.flowFileMap.values()].flatMap(e=>[...e]))];return n.logger.info.defaultLog(`[regression-impact] Mapping snapshot RESUME — skipped pre-filter + mapping (${r.length} file(s) from cached flowFileMap drive deep analysis)`),e.mappingResult=t,e.flowFileReasons=t.flowFileReasons,e.changedFiles=r,Promise.resolve(u_)}},Hx=class{name=`mappingSnapshotWrite`;execute(e){let t=dv(e),n=uv(e),r=pv(e);if(e.changedFiles===void 0||e.resolvedAnchorBranch===void 0)throw Error(`[impact-pipeline] mapping snapshot write requires changedFiles/resolvedAnchorBranch from prior steps`);return xy(t,{changedFiles:e.changedFiles,flowIds:n.map(e=>e.flowId),resolvedAnchorBranch:e.resolvedAnchorBranch,strategy:o.REGRESSION_IMPACT_MAPPING_STRATEGY},r),Promise.resolve(u_)}};function Ux(e){if(typeof e!=`object`||!e)return;let t=e.techChanges;if(Array.isArray(t))return t}var Wx=class{async derive(e,t){let n=e.filter(e=>e.affected&&e.severity!==`NONE`&&e.severity!==void 0||e.uncertain===!0),r=[...new Set(n.flatMap(e=>e.changedFiles))];return this.runPass1(r,n,t)}async runPass1(e,t,r){let a=new Map,s=0,c=0,l=!1,u=0,d=0,f=0,p=0,m=this.indexFileReasons(e,t,r.flowFileReasons),h=[];for(let t=0;t<e.length;t+=o.REGRESSION_IMPACT_DEEP_PASS1_BATCH_SIZE){let n=e.slice(t,t+o.REGRESSION_IMPACT_DEEP_PASS1_BATCH_SIZE);h.push(n.map(e=>({file:e,reason:m.get(e)})))}n.logger.info.defaultLog(`[regression-impact] pass 1: ${e.length} file(s) in ${h.length} batch(es) (concurrency ${o.REGRESSION_IMPACT_DEEP_PASS1_CONCURRENCY})`);let g=new A.default({concurrency:o.REGRESSION_IMPACT_DEEP_PASS1_CONCURRENCY}),_=0;for(let[e,t]of h.entries())g.add(async()=>{try{let i=await this.runTechPassForBatch(t,e+1,r);if(_+=1,n.logger.info.defaultLog(`[regression-impact] pass1 batch ${_}/${h.length} (#${e+1}, ${t.length} file(s)) - got ${i?.techs.length??0} techChange(s)`),i===void 0)return;for(let e of i.techs)a.set(e.file,e);s+=i.costUsd,c+=i.turns,l||=i.maxTurnsHit,u+=i.cacheReadTokens,d+=i.cacheCreationTokens,f+=i.inputTokens,p+=i.outputTokens}catch(e){n.logger.info.defaultLog(`[regression-impact] Dedup deep pass 1 batch crashed (${t.length} file(s)): ${String(e)}`)}});return await g.onIdle(),i.logCacheTokens(`pass 1 totals`,{cacheReadTokens:u,cacheCreationTokens:d,inputTokens:f,outputTokens:p}),{fileTechByFile:a,costUsd:s,turns:c,maxTurnsHit:l}}indexFileReasons(e,t,n){let r=new Map;if(n===void 0)return r;for(let i of e)for(let e of t){if(!e.changedFiles.includes(i))continue;let t=n.get(e.flow.flowId)?.get(i);if((0,m.isDefined)(t)&&t.length>0){r.set(i,t);break}}return r}async runTechPassForBatch(e,t,r){let{query:a,getMessageContentBlocks:s,isResultMessage:c,isErrorResult:l}=await Promise.resolve().then(()=>lz()),u=`pass1 batch #${t}`;i.logAgentCwd(u,r.rootPath);let d=e.map(e=>e.file),f=ux(e,o.getDiffForFiles(d,r.rootPath,r.branch,r.resolvedAnchorBranch,r.isUncommitted),r.branch,r.resolvedAnchorBranch),p=lx();o.REGRESSION_IMPACT_LOG_DEEP_PROMPT&&gx(r.rootPath,`pass1-batch-${t}`,p,f);let m=a({prompt:f,options:{model:o.REGRESSION_IMPACT_DEEP_MODEL,systemPrompt:p,allowedTools:[],disallowedTools:[`Read`,`Grep`,`Glob`,`Bash`,`Task`,`TodoWrite`,`Edit`,`Write`,`WebFetch`,`WebSearch`,`NotebookEdit`],permissionMode:o.REGRESSION_PERMISSION_MODE,allowDangerouslySkipPermissions:!0,maxBudgetUsd:o.REGRESSION_IMPACT_DEEP_MAX_BUDGET_USD,maxTurns:o.REGRESSION_IMPACT_DEEP_MAX_TURNS,cwd:r.rootPath,sessionId:(0,v.randomUUID)(),outputFormat:{type:`json_schema`,schema:i.SONNET_DEEP_OUTPUT_SCHEMA},env:{...process.env,...i.buildAnthropicSdkEnv({proxyUrl:r.anthropicBaseUrl,jwtToken:r.jwtToken??``,requestId:n.logger.getRequestId()})}}}),h=0;for await(let e of m){if(!c(e)){let t=s(e);t!==void 0&&t.length>0&&(h++,i.logAgentActivity(u,h,t));continue}if(l(e)){n.logger.info.defaultLog(`[regression-impact] Pass 1 batch error: ${String(e.subtype)}`);return}let r=e.total_cost_usd,a=e.num_turns,f=a>=o.REGRESSION_IMPACT_DEEP_MAX_TURNS,{cacheReadTokens:p,cacheCreationTokens:m,inputTokens:g,outputTokens:_}=i.logCacheTokensFromMessage(`pass1 batch #${t}`,e),v=Ux(e.structured_output);if(v===void 0||v.length===0){n.logger.info.defaultLog(`[regression-impact] Pass 1 batch returned no techChanges (${d.length} file(s))`);return}let y=new Set(d),b=v.filter(e=>y.has(e.file));if(b.length<d.length){let e=d.filter(e=>!b.some(t=>t.file===e));n.logger.info.defaultLog(`[regression-impact] Pass 1 batch produced ${b.length}/${d.length} techChange(s); missing: ${e.join(`, `)}`)}return{techs:b,costUsd:r,turns:a,maxTurnsHit:f,cacheReadTokens:p,cacheCreationTokens:m,inputTokens:g,outputTokens:_}}}},Gx=class{name=`deepAnalysisPass1`;async execute(e){let t=mv(e),n=Nx(e),r=await new Wx().derive(t,n);return e.fileTechByFile=r.fileTechByFile,{costUsd:r.costUsd,turns:r.turns,maxTurnsHit:r.maxTurnsHit}}},Kx=class{constructor(e){this.resultApplier=e}async run(e,t,r){let a=0,s=0,c=!1,l=!1,u=0,d=0,f=0,p=0,h=new Map,g=new A.default({concurrency:o.REGRESSION_IMPACT_DEEP_PASS2_CONCURRENCY}),_=0;for(let[i,o]of e.entries())g.add(async()=>{try{_+=1;let g=o.changedFiles.map(e=>t.get(e)).filter(m.isDefined);n.logger.info.defaultLog(`[regression-impact] pass2 ${_}/${e.length} - ${o.flow.name} (${g.length}/${o.changedFiles.length} pre-derived tech)`);let v=Date.now(),y=await this.runPerFlowPass(o,g,r),b=((Date.now()-v)/1e3).toFixed(1);if(y===void 0){n.logger.info.defaultLog(`[regression-impact] Pass 2 returned null for flow "${o.flow.name}" — keeping default severity "${o.severity}" with no techChanges/productChanges`);return}n.logger.info.defaultLog(`[regression-impact] pass2 ${_}/${e.length} - ${o.flow.name} DONE in ${b}s (${y.turns} turns)`),a+=y.costUsd,s+=y.turns,c||=y.maxTurnsHit,l||=y.maxBudgetHit,u+=y.tokens.cacheReadTokens,d+=y.tokens.cacheCreationTokens,f+=y.tokens.inputTokens,p+=y.tokens.outputTokens,h.set(i+1,{label:`flow-${i+1} (${o.flow.name})`,costUsd:y.costUsd,turns:y.turns,maxTurnsHit:y.maxTurnsHit,maxBudgetHit:y.maxBudgetHit,tokens:{inputTokens:y.tokens.inputTokens,outputTokens:y.tokens.outputTokens,cacheReadTokens:y.tokens.cacheReadTokens,cacheCreationTokens:y.tokens.cacheCreationTokens}}),this.resultApplier.apply(o,y,g)}catch(e){n.logger.info.defaultLog(`[regression-impact] Pass 2 crashed for flow "${o.flow.name}": ${String(e)}`)}});await g.onIdle(),i.logCacheTokens(`pass 2 totals`,{cacheReadTokens:u,cacheCreationTokens:d,inputTokens:f,outputTokens:p});let v=[...h.entries()].sort(([e],[t])=>e-t).map(([,e])=>e);return{costUsd:a,turns:s,maxTurnsHit:c,maxBudgetHit:l,tokens:{inputTokens:f,outputTokens:p,cacheReadTokens:u,cacheCreationTokens:d},batches:v}}async runPerFlowPass(e,t,r){let{query:a,getMessageContentBlocks:s,isResultMessage:c,isErrorResult:l}=await Promise.resolve().then(()=>lz()),u=`per-flow-pass2 (${e.flow.name})`;i.logAgentCwd(u,r.rootPath);let d=fx(e.flow,t,r.branch,r.resolvedAnchorBranch,r.commitMessages),f=dx();o.REGRESSION_IMPACT_LOG_DEEP_PROMPT&&gx(r.rootPath,`pass2-flow-${_x(e.flow.flowId)}`,f,d);let p=a({prompt:d,options:{model:o.REGRESSION_IMPACT_DEEP_MODEL,systemPrompt:f,allowedTools:[`Read`,`Grep`,`Glob`,`Bash`],permissionMode:o.REGRESSION_PERMISSION_MODE,allowDangerouslySkipPermissions:!0,maxBudgetUsd:o.REGRESSION_IMPACT_DEEP_MAX_BUDGET_USD,maxTurns:o.REGRESSION_IMPACT_DEEP_MAX_TURNS,cwd:r.rootPath,sessionId:(0,v.randomUUID)(),outputFormat:{type:`json_schema`,schema:i.SONNET_DEEP_OUTPUT_SCHEMA},env:{...process.env,...i.buildAnthropicSdkEnv({proxyUrl:r.anthropicBaseUrl,jwtToken:r.jwtToken??``,requestId:n.logger.getRequestId()})}}}),m=0;for await(let t of p){if(!c(t)){let e=s(t);e!==void 0&&e.length>0&&(m++,i.logAgentActivity(u,m,e));continue}if(l(t)){n.logger.info.defaultLog(`[regression-impact] Pass 2 error for flow "${e.flow.name}": ${String(t.subtype)}`);return}let r=t.total_cost_usd,a=t.num_turns,d=a>=o.REGRESSION_IMPACT_DEEP_MAX_TURNS,f=i.logCacheTokensFromMessage(`pass2 flow "${e.flow.name}"`,t),p=t.structured_output;if(p===void 0){n.logger.info.defaultLog(`[regression-impact] Pass 2: missing structured_output for "${e.flow.name}"`);return}return{structured:p,costUsd:r,turns:a,maxTurnsHit:d,maxBudgetHit:!1,tokens:f}}}},qx=class extends Px{name=`perFlowDeepAnalysis`;createStrategy(e){return new Kx(e)}},Jx=class{name=`postDetectExperimental`;isTerminal=!0;async execute(e){let t=e.jobInput?.projectId??e.globalConfigService.getProjectId();if(!(0,m.isDefined)(t)||t.length===0)return n.logger.info.defaultLog(`[regression-first] No projectId — skipping experimental post (detect result still in local file)`),u_;let r=e.detectedRegressions??[],i=e.detectTokens??{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0},a=i.cacheReadTokens+i.cacheCreationTokens+i.inputTokens,o=a>0?i.cacheReadTokens/a*100:0,s={anchorRef:e.resolvedAnchorBranch??`unknown`,compareRef:e.branch??`unknown`,count:r.length,costUsd:e.detectCostUsd??0,turns:e.detectTurns??0,durationSeconds:(Date.now()-e.startTime)/1e3,tokens:{...i,cacheHitPct:Number(o.toFixed(1))},findings:r};try{let r=await e.apiService.post(`/api/experimental/key-values`,{type:`regression-first`,key:t,data:s});n.logger.info.defaultLog(`[regression-first] Detect result posted to experimental store: id=${r.id} type=regression-first key=${t}`)}catch(e){n.logger.info.defaultLog(`[regression-first] WARN: failed to post detect result to experimental store (key=${t}): ${String(e)}`)}return u_}},Yx=class{name=`preFilter`;async execute(e){let t=dv(e);if(e.branch===void 0)throw Error(`[impact-pipeline] ctx.branch is unset — ResolveCompareStep must run before this step`);if(e.resolvedAnchorBranch===void 0)throw Error(`[impact-pipeline] ctx.resolvedAnchorBranch is unset — LoadLibraryStep must run before this step`);let r=[e.primarySource??t,...(e.dependencyRoots??[]).map(e=>e.sourcePath)],{changedFiles:i,compareDescription:a,preFilterCostUsd:o,preFilterTurns:s,preFilterMaxTurnsHit:c}=await Sv(t,e.branch,e.resolvedAnchorBranch,e.runType,e.jwtToken,e.anthropicBaseUrl,r);return n.logger.info.defaultLog(`[regression-impact] Compare: ${a}`),e.changedFiles=i,e.compareDescription=a,i.length===0?(n.logger.info.defaultLog(`[regression-impact] No changes detected`),{costUsd:o,turns:s,maxTurnsHit:c,status:l_.Halt}):(n.logger.info.defaultLog(`[regression-impact] ${i.length} changed files`),{costUsd:o,turns:s,maxTurnsHit:c})}};let Xx={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0},Zx={roughGuessedFlowIds:new Set,rescuedFiles:[],totalFiles:0,costUsd:0,turns:0,maxTurnsHit:!1,tokens:Xx,batchMetrics:[]};function Qx(e,t){let n=e;return n===void 0||!Array.isArray(n.guesses)?[]:n.guesses.map(e=>({file:e.file,flowIds:(Array.isArray(e.flowIds)?e.flowIds:[]).filter(e=>t.has(e)),reason:e.reason}))}function $x(e,t,r){let i=new Set,a=[],s=r.flowFileReasons??new Map;for(let c of e){if(!t.has(c.file)||c.flowIds.length===0)continue;let e=c.flowIds.slice(0,o.REGRESSION_IMPACT_ROUGH_MAP_CAP),l=c.reason??`rough-map: guessed from diff (precise mapper aborted)`;for(let t of e){let e=r.flowFileMap.get(t)??new Set;e.add(c.file),r.flowFileMap.set(t,e),i.add(t);let n=s.get(t)??new Map;n.set(c.file,`rough-map (low confidence): ${l}`),s.set(t,n)}a.push(c.file),n.logger.info.defaultLog(`[regression-impact] Rough-map rescued ${c.file} -> ${e.length} flow(s): ${e.join(`, `)}`)}return r.flowFileReasons=s,{roughGuessedFlowIds:i,rescuedFiles:a}}function eS(e,t){let n=[];for(let r=0;r<e.length;r+=Math.max(1,t))n.push(e.slice(r,r+Math.max(1,t)));return n}async function tS(e,t,r,a,s,l,u,d,f,p){let{query:m,isResultMessage:h,isErrorResult:g,getMessageContentBlocks:_}=await Promise.resolve().then(()=>lz()),y=`residual batch #${a}`,b={guesses:[],costUsd:0,turns:0,maxTurnsHit:!1,tokens:Xx},x=o.getPerFileDiffs(t,s,l,u,p),S=m({prompt:c.buildResidualRoughMapPrompt(e,t,x,l,u),options:{model:o.REGRESSION_IMPACT_SONNET_MODEL,systemPrompt:c.buildResidualRoughMapSystemPrompt(o.REGRESSION_IMPACT_ROUGH_MAP_CAP),allowedTools:[],permissionMode:o.REGRESSION_PERMISSION_MODE,allowDangerouslySkipPermissions:!0,maxBudgetUsd:o.REGRESSION_IMPACT_AGENTIC_MAX_BUDGET_USD,maxTurns:10,cwd:s,sessionId:(0,v.randomUUID)(),outputFormat:{type:`json_schema`,schema:i.RESIDUAL_ROUGH_MAP_OUTPUT_SCHEMA},env:{...process.env,...i.buildAnthropicSdkEnv({proxyUrl:f,jwtToken:d??``,requestId:n.logger.getRequestId()})}}});i.logAgentCwd(y,s);let C=0;for await(let e of S){if(!h(e)){let t=_(e);t!==void 0&&t.length>0&&(C++,i.logAgentActivity(y,C,t));continue}if(g(e))return n.logger.info.defaultLog(`[regression-impact] Residual rough-map ${y} error: ${e.subtype} — its files remain incomplete`),b;let t=e.num_turns,a=i.extractCacheTokens(e);return i.logCacheTokensFromMessage(y,e),{guesses:Qx(e.structured_output,r),costUsd:e.total_cost_usd,turns:t,maxTurnsHit:t>=10,tokens:a}}return b}async function nS(e,t,r,i,a,s,c,l,u=!1){if(t.length===0)return Zx;let d=new Set(e.map(e=>e.flowId)),f=new Set(t),p=eS(t,o.REGRESSION_IMPACT_RESIDUAL_BATCH_SIZE);n.logger.info.defaultLog(`[regression-impact] Residual rough-map: guessing flows for ${t.length} dropped file(s) in ${p.length} batch(es): ${t.join(`, `)}`);let m=new A.default({concurrency:o.REGRESSION_IMPACT_RESIDUAL_CONCURRENCY}),h=p.entries(),g=(await Promise.all([...h].map(([t,r])=>m.add(async()=>{try{return{batchIndex:t,batchFiles:r,...await tS(e,r,d,t+1,i,a,s,c,l,u)}}catch(e){n.logger.info.defaultLog(`[regression-impact] Residual rough-map batch #${t+1} crashed (${r.length} file(s)): ${String(e)}`);return}})))).filter(e=>e!==void 0).sort((e,t)=>e.batchIndex-t.batchIndex),_=new Set,v=new Set,y=0,b=0,x=!1,S={...Xx},C=[];for(let e of g){let t=$x(e.guesses,f,r);for(let e of t.roughGuessedFlowIds)_.add(e);for(let e of t.rescuedFiles)v.add(e);y+=e.costUsd,b+=e.turns,x||=e.maxTurnsHit,S.inputTokens+=e.tokens.inputTokens,S.outputTokens+=e.tokens.outputTokens,S.cacheReadTokens+=e.tokens.cacheReadTokens,S.cacheCreationTokens+=e.tokens.cacheCreationTokens,C.push({label:`residual-batch-${e.batchIndex+1}`,totalFiles:e.batchFiles.length,costUsd:e.costUsd,turns:e.turns,maxTurnsHit:e.maxTurnsHit,maxBudgetHit:!1,tokens:e.tokens})}let w=[...v],T=t.filter(e=>!v.has(e));return n.logger.info.defaultLog(`[regression-impact] Residual rough-map: rescued ${w.length} file(s) onto ${_.size} flow(s); ${T.length} file(s) still incomplete`+(T.length>0?` (no confident guess): ${T.join(`, `)}`:``)),n.logger.info.defaultLog(`[regression-impact] Residual rough-map summary (${t.length} dropped file(s)):`),n.logger.info.defaultLog(`[regression-impact] → rescued onto flows (${w.length}): ${w.length>0?w.join(`, `):`(none)`}`),n.logger.info.defaultLog(`[regression-impact] → still unmapped (${T.length}): ${T.length>0?T.join(`, `):`(none)`}`),{roughGuessedFlowIds:_,rescuedFiles:w,totalFiles:t.length,costUsd:y,turns:b,maxTurnsHit:x,tokens:S,batchMetrics:C}}var rS=class{name=`residualRoughMap`;async execute(e){let t=pv(e),n=t.incompleteFiles??[];if(n.length===0)return u_;let r=uv(e),i=dv(e);if(e.branch===void 0||e.resolvedAnchorBranch===void 0)throw Error(`[impact-pipeline] ResidualRoughMapStep requires branch/resolvedAnchorBranch`);let a=await nS(r,n,t,i,e.branch,e.resolvedAnchorBranch,e.jwtToken,e.anthropicBaseUrl,e.isUncommitted);if(e.roughGuessedFlowIds=a.roughGuessedFlowIds,a.rescuedFiles.length>0){let e=new Set(a.rescuedFiles);t.incompleteFiles=n.filter(t=>!e.has(t))}return{costUsd:a.costUsd,turns:a.turns,maxTurnsHit:a.maxTurnsHit,tokens:a.tokens,totalFiles:a.totalFiles,mappedFiles:a.rescuedFiles.length,batches:a.batchMetrics.length>0?a.batchMetrics:void 0}}},iS=class{name=`verifyProductIntent`;async execute(e){let t=e.detectedRegressions??[];if(t.length===0)return u_;let n=dv(e);if(e.branch===void 0||e.resolvedAnchorBranch===void 0)throw Error(`[impact-pipeline] VerifyProductIntentStep requires branch/resolvedAnchorBranch from ResolveCompare`);let r=e.changedFiles??[],i=o.getDiffForFiles(r,n,e.branch,e.resolvedAnchorBranch,e.isUncommitted),a=o.formatCommitMessagesBlock(e.commitMessages??[]),s=wy(e.jobInput,n),c=await gb({anchorRef:e.resolvedAnchorBranch,compareRef:e.branch,rootPath:n,diffText:i,commitMessagesBlock:a,jwtToken:e.jwtToken,anthropicBaseUrl:e.anthropicBaseUrl,primarySource:s.primarySource,dependencyRoots:s.dependencyRoots},t);e.detectedRegressions=c.regressions,e.detectCostUsd=(e.detectCostUsd??0)+c.costUsd,e.detectTurns=(e.detectTurns??0)+c.turns;let l=e.detectTokens;return e.detectTokens=l===void 0?c.tokens:{inputTokens:(l.inputTokens??0)+(c.tokens.inputTokens??0),outputTokens:(l.outputTokens??0)+(c.tokens.outputTokens??0),cacheReadTokens:(l.cacheReadTokens??0)+(c.tokens.cacheReadTokens??0),cacheCreationTokens:(l.cacheCreationTokens??0)+(c.tokens.cacheCreationTokens??0)},{costUsd:c.costUsd,turns:c.turns,maxTurnsHit:c.maxTurnsHit,totalFiles:c.regressions.length,tokens:c.tokens}}},aS=class{name=`writeDetectResult`;isTerminal=!0;async execute(e){let t=e.detectedRegressions??[],r=e.branch??`unknown`,i=`(file write disabled)`;if(o.REGRESSION_FIRST_WRITE_DETECT_FILE){let n=e.detectCostUsd??0,a=e.detectTurns??0,s=e.detectTokens??{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0},c=s.cacheReadTokens+s.cacheCreationTokens+s.inputTokens,l=c>0?s.cacheReadTokens/c*100:0;if(!I.default.isAbsolute(o.REGRESSION_DEV_ARTIFACT_DIR))throw Error(`[regression-first] REGRESSION_DEV_ARTIFACT_DIR must be an absolute path when REGRESSION_FIRST_WRITE_DETECT_FILE is enabled (got: "${o.REGRESSION_DEV_ARTIFACT_DIR}"). A relative/empty dir resolves against the scanned repo's cwd.`);let u=Zy(r,e.detectVariant??`v1`),d=I.default.join(o.REGRESSION_DEV_ARTIFACT_DIR,`my-runs`);(0,y.mkdirSync)(d,{recursive:!0}),i=I.default.join(d,`regression-detect-${u}.json`);let f={anchorRef:e.resolvedAnchorBranch??`unknown`,compareRef:r,count:t.length,costUsd:n,turns:a,durationSeconds:(Date.now()-e.startTime)/1e3,tokens:{...s,cacheHitPct:Number(l.toFixed(1))},findings:t};(0,y.writeFileSync)(i,JSON.stringify(f,null,2))}let a=[...t].sort((e,t)=>t.score-e.score);n.logger.info.defaultLog(`[regression-first] Detect result: ${t.length} finding(s) → ${i}`);for(let e of a)n.logger.info.defaultLog(`[regression-first] [${e.score}] ${e.severity} ${e.title} (${e.file})`);return u_}};function oS(e){if(e===`agentic`||e===`agentic-ast`||e===`shallow`)return new kb(e);throw Error(`[impact-pipeline] unsupported mapping strategy "${e}" — only "agentic", "agentic-ast", and "shallow" are wired in this version`)}function sS(e,t){if(t&&e.devMappingSnapshotResume)return[new Vx];let n=t?[new Yx,oS(e.mappingStrategy)]:[oS(e.mappingStrategy)];return e.residualRoughMap&&n.push(new rS),e.devMappingSnapshotWrite&&n.push(new Hx),n}function cS(e,t,n){let r=[e,new Cv,new ax,new Yx,t];return n!==void 0&&r.push(n),r.push(new Yb,new Jb,new aS),o.REGRESSION_FIRST_POST_EXPERIMENTAL&&r.push(new Jx),r.push(new Ib,new vv,new cv),r}function lS(e){return e.regressionFirstV2===!0||e.regressionFirstV2Adj===!0?new ex:e.regressionFirstV3===!0?new tx:e.regressionFirstSingle===!0?new $b:e.regressionFirstMono===!0?new Qb:e.regressionFirstExperiment===!0?new Zb:new Xb}function uS(e,t){if(!(e.regressionFirst!==!0&&e.regressionFirstV2!==!0&&e.regressionFirstV3!==!0&&e.regressionFirstV2Adj!==!0&&e.regressionFirstSingle!==!0&&e.regressionFirstMono!==!0&&e.regressionFirstExperiment!==!0))return new Y_(cS(t,lS(e),dS(e)))}function dS(e){if(e.regressionFirstV3===!0)return new iS;if(e.regressionFirstV2Adj===!0)return new Eb}let fS={create(e,t=!1){let n=e.baselineFromAnalysisId!==void 0&&e.baselineFromAnalysisId.length>0?new Bx:new av,r=uS(e,n);if(r!==void 0)return r;let i=t?[...sS(e,!1),new jb]:[n,new Cv,...sS(e,!0),new jb];if(e.stopAfterMapping)return i.push(new vv,new cv),new Y_(i);if(e.deepMode===`legacy`)i.push(new zx);else{if(!e.skipPass1&&(i.push(new Gx),e.stopAfterPass1))return i.push(new vv,new cv),new Y_(i);i.push(e.pass2Grouped?new Fx(e.contractMode):new qx)}return e.calibrationEnabled&&i.push(new Vb),i.push(new vv,new cv),new Y_(i)}};function pS(e){if(e!==void 0)return e===`perflow`?`legacy`:`dedup`}function mS(e){if(e!==void 0)return e===`divergence`}function hS(e){return e===`regression-first`}function gS(e){return e===`regression-first-2`}function _S(e){return e===`regression-first-3`}function vS(e){return e===`regression-first-2-adj`}function yS(e){return e===`regression-first-single`}function bS(e){return e===`regression-first-mono`}function xS(e){return e===`regression-first-experiment`}async function SS(e,t,n,r,a,o,s,c){let l=Date.now(),u=t===`LOCAL`;i.setAgentLogEnabled(s?.agentLog??!1);let d={reportsDir:e,runType:t,isUncommitted:u,jwtToken:n,anthropicBaseUrl:r,apiService:a,globalConfigService:o,jobInput:s,compareBranch:c,startTime:l,stepMetrics:[]},f=s?.analysisMode??`regression-first-2`,p=pS(f),m=mS(f),h=hS(f),g=gS(f),_=_S(f),v=vS(f),y=yS(f),b=bS(f),x=xS(f),S=Cy(s?.projectRootPath,p,s?.baselineFromAnalysisId,m,s?.fileMappingMode,h,g,_,v,y,b,x);if(await fS.create(S).run(d),h||g||_||v||y)return d.result??{flowImpacts:[],catalogId:null,rootPath:d.rootPath??``,changedFiles:d.changedFiles??[],branch:d.branch??``,headSha:d.headSha,anchorBranch:d.resolvedAnchorBranch??``,anchorSha:d.anchorSha,runType:t};if(d.result===void 0)throw Error(`[regression-impact] pipeline finished without producing a result (ReportStep did not run)`);return d.result}var CS=t.__toESM(n.require_decorateMetadata()),wS=t.__toESM(nn()),TS=t.__toESM(n.require_decorate()),ES,DS;let OS=class{constructor(e,t,n){this.globalConfigService=e,this.apiService=t,this.authStorage=n}async run(e){let t=await this.authStorage.getJWTToken(),n=await xh(this.apiService,this.globalConfigService);return n?.crossComponent?J_(e.reportsDir,t,this.globalConfigService.getAnthropicProxyUrl(),this.apiService,this.globalConfigService,n,e.compareBranch):(n?.analysisMode===`hunterImpact`?py:SS)(e.reportsDir,e.runType,t,this.globalConfigService.getAnthropicProxyUrl(),this.apiService,this.globalConfigService,n,e.compareBranch)}};OS=(0,TS.default)([(0,h.injectable)(),(0,wS.default)(0,(0,h.inject)(n.GlobalConfigService)),(0,wS.default)(1,(0,h.inject)(ln)),(0,wS.default)(2,(0,h.inject)(tn)),(0,CS.default)(`design:paramtypes`,[Object,typeof(ES=ln!==void 0&&ln)==`function`?ES:Object,typeof(DS=tn!==void 0&&tn)==`function`?DS:Object])],OS);var kS=t.__toESM(n.require_decorateMetadata()),AS=t.__toESM(nn()),jS=t.__toESM(n.require_decorate()),MS,NS;let PS=class{constructor(e,t,n){this.globalConfigService=e,this.apiService=t,this.authStorage=n}async run(e){let t=await this.authStorage.getJWTToken(),n=await xh(this.apiService,this.globalConfigService);return py(e.reportsDir,e.runType,t,this.globalConfigService.getAnthropicProxyUrl(),this.apiService,this.globalConfigService,n,e.compareBranch)}};PS=(0,jS.default)([(0,h.injectable)(),(0,AS.default)(0,(0,h.inject)(n.GlobalConfigService)),(0,AS.default)(1,(0,h.inject)(ln)),(0,AS.default)(2,(0,h.inject)(tn)),(0,kS.default)(`design:paramtypes`,[Object,typeof(MS=ln!==void 0&&ln)==`function`?MS:Object,typeof(NS=tn!==void 0&&tn)==`function`?NS:Object])],PS);let FS=`claude-haiku-4-5-20251001`,IS=`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(`,`),LS={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 RS=t.__toESM(n.require_decorateMetadata()),zS=t.__toESM(nn()),BS=t.__toESM(n.require_decorate()),VS,HS,US,WS;function GS(e){if((0,m.isDefined)(e))return e;try{let e=(0,L.createRequire)(__filename)?.resolve?.(`@anthropic-ai/claude-agent-sdk`);if(e)return d.default.join(d.default.dirname(e),`cli.js`)}catch{}return d.default.join(__dirname,`..`,`..`,`node_modules`,`@anthropic-ai`,`claude-agent-sdk`,`cli.js`)}function KS(){return d.default.join(__dirname,`..`,`plugin`)}function qS(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 JS(e,t){return{type:`user`,message:{role:`user`,content:e},parent_tool_use_id:null,session_id:t}}async function*YS(e,t,n,r,i){yield JS(e,t),await qS(3e4,n),!n.aborted&&(await r.flush(),i.debug(`[plugin-agent] Phase transition: recon → draft`),yield JS(`<system-reminder>Recon time is over. Move to Phase 3 — draft the test file now.</system-reminder>`,t),await qS(3e4,n),!n.aborted&&(await r.flush(),i.debug(`[plugin-agent] Phase transition: draft → validate`),yield JS(`<system-reminder>Draft time is over. Move to Phase 4 — run test, lint, and format gates now.</system-reminder>`,t),await qS(15e3,n),!n.aborted&&(await r.flush(),i.debug(`[plugin-agent] Phase transition: validate → stop`),yield JS(`<system-reminder>Time is up. Stop all work. Exit with your structured output now.</system-reminder>`,t))))}let XS=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()??KS(),o=d.default.join(t,`skills`,`early-generate-unit-tests`,`references`),s=this.globalConfigService.getBackendURL(),c=Date.now(),l=()=>Date.now()-c;if(!s)return{outcome:`error`,success:!1,error:`backendURL is not configured`,durationMs:l()};let u=e.requestId??n.logger.getRequestId(),p=new AbortController;(0,m.isDefined)(e.abortSignal)&&(e.abortSignal.aborted?p.abort():e.abortSignal.addEventListener(`abort`,()=>p.abort(),{once:!0}));let h=await this.authStorage.getJWTToken()??``,g=GS(this.globalConfigService.getClaudeCodeExecutablePath()),_=r.getFileLanguage(e.filePath),y=r.isPythonFile(e.filePath)?n.TestFramework.PYTEST:this.globalConfigService.getTestFramework();try{await this.apiService.post(`/api/v1/tests/generate-prompt`,{testedCodeDataSource:{filePath:e.filePath,relativePathToTestFile:``,testFramework:y,language:_,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:{[Ht]:u}})}catch(e){if(e instanceof Bt&&e.code===Rt.NOT_ENOUGH_BALANCE_ERROR)return{outcome:`error`,success:!1,error:e.message,errorCode:e.code,durationMs:l()};n.logger.info.defaultLog(`[plugin-agent] generate-prompt side-effect failed: ${e}`)}let b=(0,m.isDefined)(e.testFilePath)?new vr(e.testFilePath):await vr.getNextTestFile(e.filePath,e.methodName,e.workingDirectory);if(e.preserveExistingContent===!0&&!(0,m.isDefined)(e.testFilePath)){let t=await vr.getLatestTestFile(e.filePath,e.methodName);if((0,m.isDefined)(t)){let e=await new vr(r.absoluteToRelativePath(t)).getText();e.trim().length>0&&await b.replace(e)}}let x=(await b.isFileExists()?await b.getText():``).trim().length>0,S=e.preserveExistingContent===!0&&x;if(e.preserveExistingContent===!0&&!x&&n.logger.default.warn(`[plugin-agent] preserveExistingContent was requested but the target file is empty — falling back to generate mode.`),!S){let t=r.isPythonFile(e.filePath)?`#`:`//`;await b.replace(`${t} early-test-generation-in-progress`)}let C=b.getAbsoluteFilePath(),w=b.getFilePath(),T=d.default.relative(e.workingDirectory,C),E=d.default.join(o,`framework`,`${y}.md`),D=d.default.join(o,`${_}.md`),O=e=>(0,f.readFile)(e,`utf8`).catch(()=>(n.logger.default.warn(`[plugin-agent] Reference file not found: ${e}`),``)),[k,A]=await Promise.all([O(E),O(D)]),j=[`Generate unit tests for method \`${e.methodName}\` in: ${e.filePath}`,`Framework: ${y}`,`Working directory: ${d.default.normalize(e.workingDirectory)}`,`testFilePath: ${d.default.normalize(T)}`];S&&j.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,m.isDefined)(e.userPrompt)&&e.userPrompt.trim()!==``&&j.push(``,e.userPrompt),k!==``&&j.push(``,`---`,`## Framework Reference`,k),A!==``&&j.push(``,`---`,`## Language Reference`,A);let M=j.join(`
|
|
34659
|
-
`),ee=this.globalConfigService.getProgressLogger({methodName:e.methodName});n.logger.info.defaultLog(`[plugin-agent] Starting plugin agent for file: ${e.filePath}, testFile: ${T}`);let N=u,te=new sf(this.metricReportService,N,
|
|
34660
|
-
`)},model:FS,pathToClaudeCodeExecutable:g,allowedTools:[...IS],permissionMode:`dontAsk`,maxBudgetUsd:2,cwd:e.workingDirectory,abortController:p,outputFormat:{type:`json_schema`,schema:LS},sessionId:F,env:{...process.env,...i.buildAnthropicSdkEnv({proxyUrl:this.globalConfigService.getAnthropicProxyUrl(),jwtToken:h,requestId:u})},stderr:e=>{n.logger.info.defaultLog(`[plugin-agent] STDERR: ${e}`)},hooks:{PreToolUse:[{matcher:`Write|Edit`,hooks:[P]},{matcher:`Read`,hooks:[sd]},{matcher:`Bash`,hooks:[od,Au]}]}}}),L=0;try{for await(let t of I){L+=1,await te.processMessage(t);let r=t.type;if(ee.debug(`[plugin-agent] stream message #${L} type=${r??`unknown`}`),r===`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`);if(i.length>0)n.logger.info.defaultLog(`[plugin-agent] Tool calls: ${i.join(`, `)}`);else if(a){let e=r.filter(e=>e.type===`text`).map(e=>e.text).join(` `).slice(0,500);n.logger.info.defaultLog(`[plugin-agent] Agent thinking: ${e}`)}}if(a.isResultMessage(t)){await te.flush();let r=l();if(a.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:r};n.logger.info.defaultLog(`[plugin-agent] Agent completed. Cost: $${t.total_cost_usd.toFixed(4)} — ${r}ms`);let i=ZS(t.structured_output),o=i?.status,s=i?.reason;if(o===`skipped`||o===`aborted`||o===`no-viable-tests`){let e=(0,m.isDefined)(s)?`${o}: ${s}`:o;return n.logger.info.defaultLog(`[plugin-agent] ${o} by skill: ${s??`no reason given`}`),this.metricReportService.saveTestMetrics({requestId:N,timeElapsed:r,errorCause:e}),o===`skipped`?{outcome:`skipped`,success:!0,skipped:!0,skipReason:s??`trivial`,costUsd:t.total_cost_usd,durationMs:r}:{outcome:o,success:!1,costUsd:t.total_cost_usd,error:e,durationMs:r}}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:r};let c=await b.getText(),u=await this.testResultCounterService.getValidationReport(C,e.methodName).catch(()=>void 0),d=te.getLatestTestResult(),f=i?.passedCount??d?.passed??u?.greenTestsCount,p=i?.failedCount??d?.failed??u?.redTestsCount;return this.metricReportService.saveTestMetrics({requestId:N,timeElapsed:r,validationReport:u}),c!==``&&this.metricReportService.saveOperationMetricsTrace({parentRequestId:N,llmModel:FS,testFileContent:c}),{outcome:`generated`,success:!0,costUsd:t.total_cost_usd,testFilePath:w,durationMs:r,greenTestsCount:f,redTestsCount:p}}}return await te.flush(),{outcome:`error`,success:!1,error:`stream_ended_without_result`,durationMs:l()}}finally{p.abort()}}};XS=(0,BS.default)([(0,h.injectable)(),(0,zS.default)(0,(0,h.inject)(n.GlobalConfigService)),(0,zS.default)(1,(0,h.inject)(tn)),(0,zS.default)(2,(0,h.inject)(ln)),(0,zS.default)(3,(0,h.inject)(Dn)),(0,zS.default)(4,(0,h.inject)(jl)),(0,RS.default)(`design:paramtypes`,[Object,typeof(VS=tn!==void 0&&tn)==`function`?VS:Object,typeof(HS=ln!==void 0&&ln)==`function`?HS:Object,typeof(US=Dn!==void 0&&Dn)==`function`?US:Object,typeof(WS=jl!==void 0&&jl)==`function`?WS:Object])],XS);function ZS(e){if(!(0,m.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 QS=t.__toESM(n.require_decorateMetadata()),$S=t.__toESM(nn()),eC=t.__toESM(n.require_decorate()),tC,nC,rC,iC,aC,oC,sC,cC,lC,uC,dC,fC,pC,mC,hC;let gC=class{constructor(e,t,n,r,i,a,o,s,c,l,u,d,f,p){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.regressionE2eCatalogManager=d,this.pluginAgentRunner=f,this.huntFirstImpactManager=p}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 runHuntFirstImpact(e){return this.huntFirstImpactManager.run(e)}async runRegressionCatalog(){return this.regressionCatalogManager.run()}async runRegressionE2eCatalog(){return this.regressionE2eCatalogManager.run()}async runPluginAgent(e){let t=this.globalConfigService.getRootPath();return this.pluginAgentRunner.run({...e,workingDirectory:t})}};(0,eC.default)([n.WithLoggerContext({category:V.INITIALIZATION}),(0,QS.default)(`design:type`,Function),(0,QS.default)(`design:paramtypes`,[String]),(0,QS.default)(`design:returntype`,Promise)],gC.prototype,`init`,null),(0,eC.default)([n.WithLoggerContext({category:V.GET_TESTABLES}),(0,QS.default)(`design:type`,Function),(0,QS.default)(`design:paramtypes`,[String]),(0,QS.default)(`design:returntype`,Promise)],gC.prototype,`getTestables`,null),(0,eC.default)([n.WithLoggerContext({category:V.GET_TESTABLES}),(0,QS.default)(`design:type`,Function),(0,QS.default)(`design:paramtypes`,[String]),(0,QS.default)(`design:returntype`,Promise)],gC.prototype,`getAllMethodsCount`,null),(0,eC.default)([n.WithLoggerContext({category:V.GET_TESTABLES}),(0,QS.default)(`design:type`,Function),(0,QS.default)(`design:paramtypes`,[Object]),(0,QS.default)(`design:returntype`,Promise)],gC.prototype,`resolveEarlyTestFile`,null),(0,eC.default)([n.WithLoggerContext({category:V.GET_TESTABLES}),(0,QS.default)(`design:type`,Function),(0,QS.default)(`design:paramtypes`,[Array]),(0,QS.default)(`design:returntype`,Promise)],gC.prototype,`getTestableFileMap`,null),(0,eC.default)([n.WithLoggerContext({category:V.GENERATE_COVERAGE}),(0,QS.default)(`design:type`,Function),(0,QS.default)(`design:paramtypes`,[Array]),(0,QS.default)(`design:returntype`,Promise)],gC.prototype,`generateCoverage`,null),(0,eC.default)([n.WithLoggerContext({category:V.SET_COVERAGE}),(0,QS.default)(`design:type`,Function),(0,QS.default)(`design:paramtypes`,[Object]),(0,QS.default)(`design:returntype`,Promise)],gC.prototype,`setCoverage`,null),(0,eC.default)([n.WithLoggerContext({category:V.GET_COVERAGE}),(0,QS.default)(`design:type`,Function),(0,QS.default)(`design:paramtypes`,[]),(0,QS.default)(`design:returntype`,Promise)],gC.prototype,`getCoverageTree`,null),(0,eC.default)([n.WithLoggerContext({category:V.GET_COVERAGE}),(0,QS.default)(`design:type`,Function),(0,QS.default)(`design:paramtypes`,[Array]),(0,QS.default)(`design:returntype`,Promise)],gC.prototype,`getCoverageForFiles`,null),(0,eC.default)([n.WithLoggerContext({category:V.GENERATE_TESTS}),(0,QS.default)(`design:type`,Function),(0,QS.default)(`design:paramtypes`,[String,Object]),(0,QS.default)(`design:returntype`,Promise)],gC.prototype,`generateTests`,null),(0,eC.default)([n.WithLoggerContext({category:V.GENERATE_TESTS}),(0,QS.default)(`design:type`,Function),(0,QS.default)(`design:paramtypes`,[Array,Object,String,typeof(hC=m.Fn!==void 0&&m.Fn)==`function`?hC:Object]),(0,QS.default)(`design:returntype`,Promise)],gC.prototype,`bulkGenerateTests`,null),(0,eC.default)([n.WithLoggerContext({category:V.GENERATE_TESTS}),(0,QS.default)(`design:type`,Function),(0,QS.default)(`design:paramtypes`,[String,String]),(0,QS.default)(`design:returntype`,Promise)],gC.prototype,`getValidationReport`,null),(0,eC.default)([n.WithLoggerContext({category:V.GET_TESTED_CODE_DATA_SOURCE}),(0,QS.default)(`design:type`,Function),(0,QS.default)(`design:paramtypes`,[String,Object,String]),(0,QS.default)(`design:returntype`,Promise)],gC.prototype,`getTestedCodeDataSource`,null),(0,eC.default)([n.WithLoggerContext({category:V.DYNAMIC_PROMPT}),(0,QS.default)(`design:type`,Function),(0,QS.default)(`design:paramtypes`,[String,Object,String]),(0,QS.default)(`design:returntype`,Promise)],gC.prototype,`runDynamicPrompt`,null),(0,eC.default)([n.WithLoggerContext({category:V.TEST_VALIDATION}),(0,QS.default)(`design:type`,Function),(0,QS.default)(`design:paramtypes`,[String,String]),(0,QS.default)(`design:returntype`,Promise)],gC.prototype,`validateTestsByCode`,null),(0,eC.default)([n.WithLoggerContext({category:V.REGRESSION_IMPACT}),(0,QS.default)(`design:type`,Function),(0,QS.default)(`design:paramtypes`,[Object]),(0,QS.default)(`design:returntype`,Promise)],gC.prototype,`runRegressionImpact`,null),(0,eC.default)([n.WithLoggerContext({category:V.REGRESSION_IMPACT}),(0,QS.default)(`design:type`,Function),(0,QS.default)(`design:paramtypes`,[Object]),(0,QS.default)(`design:returntype`,Promise)],gC.prototype,`runHuntFirstImpact`,null),(0,eC.default)([n.WithLoggerContext({category:V.REGRESSION_CATALOG}),(0,QS.default)(`design:type`,Function),(0,QS.default)(`design:paramtypes`,[]),(0,QS.default)(`design:returntype`,Promise)],gC.prototype,`runRegressionCatalog`,null),(0,eC.default)([n.WithLoggerContext({category:V.REGRESSION_CATALOG}),(0,QS.default)(`design:type`,Function),(0,QS.default)(`design:paramtypes`,[]),(0,QS.default)(`design:returntype`,Promise)],gC.prototype,`runRegressionE2eCatalog`,null),(0,eC.default)([n.WithLoggerContext({category:V.GENERATE_TESTS}),(0,QS.default)(`design:type`,Function),(0,QS.default)(`design:paramtypes`,[Object]),(0,QS.default)(`design:returntype`,Promise)],gC.prototype,`runPluginAgent`,null),gC=(0,eC.default)([(0,h.injectable)(),(0,$S.default)(0,(0,h.inject)(Mm)),(0,$S.default)(1,(0,h.inject)(It)),(0,$S.default)(2,(0,h.inject)(Sm)),(0,$S.default)(3,(0,h.inject)(Yo)),(0,$S.default)(4,(0,h.inject)(n.GlobalConfigService)),(0,$S.default)(5,(0,h.inject)(jl)),(0,$S.default)(6,(0,h.inject)(Wp)),(0,$S.default)(7,(0,h.inject)(Yl)),(0,$S.default)(8,(0,h.inject)(ml)),(0,$S.default)(9,(0,h.inject)(OS)),(0,$S.default)(10,(0,h.inject)(Oh)),(0,$S.default)(11,(0,h.inject)($g)),(0,$S.default)(12,(0,h.inject)(XS)),(0,$S.default)(13,(0,h.inject)(PS)),(0,QS.default)(`design:paramtypes`,[typeof(tC=Mm!==void 0&&Mm)==`function`?tC:Object,typeof(nC=It!==void 0&&It)==`function`?nC:Object,typeof(rC=Sm!==void 0&&Sm)==`function`?rC:Object,typeof(iC=Yo!==void 0&&Yo)==`function`?iC:Object,typeof(aC=n.GlobalConfigService!==void 0&&n.GlobalConfigService)==`function`?aC:Object,typeof(oC=jl!==void 0&&jl)==`function`?oC:Object,typeof(sC=Wp!==void 0&&Wp)==`function`?sC:Object,typeof(cC=Yl!==void 0&&Yl)==`function`?cC:Object,typeof(lC=ml!==void 0&&ml)==`function`?lC:Object,typeof(uC=OS!==void 0&&OS)==`function`?uC:Object,typeof(dC=Oh!==void 0&&Oh)==`function`?dC:Object,typeof(fC=$g!==void 0&&$g)==`function`?fC:Object,typeof(pC=XS!==void 0&&XS)==`function`?pC:Object,typeof(mC=PS!==void 0&&PS)==`function`?mC:Object])],gC);let _C=!1;e.AST=dt,e.AccessModifierType=le,e.AstModuleInfo=lt,e.CONCURRENCY=n.CONCURRENCY,e.COVERAGE_THRESHOLD=n.COVERAGE_THRESHOLD,e.CalculateCoverageOption=n.CalculateCoverageOption,e.DEFAULT_TYPE_KIND=de,e.ExportType=ce,e.GenerateTestsOutputType=n.GenerateTestsOutputType,e.GeneratedTestStructure=n.GeneratedTestStructure,e.LibraryName=ue,e.RequestSource=n.RequestSource,Object.defineProperty(e,`TSAgent`,{enumerable:!0,get:function(){return gC}}),e.TestFileName=n.TestFileName,e.TestFramework=n.TestFramework,e.TestStructureVariant=n.TestStructureVariant,e.TestSuffix=n.TestSuffix,e.WithTsMorphManager=ke,e.createTSAgent=(e={})=>((_C?n.inversify_default.rebindSync(n.GlobalConfigService):n.inversify_default.bind(n.GlobalConfigService)).toDynamicValue(()=>new n.GlobalConfigService(e)).inSingletonScope(),_C=!0,n.inversify_default.get(gC)),e.findLintConfigPath=B,e.getUnitTests=He,e.tsMorphManager=Oe}))();const PU={TSAgent:Symbol.for(`TSAgent`),CliOptions:Symbol.for(`CliOptions`),SCMHostService:Symbol.for(`SCMHostService`)};var FU=u(vR());let IU=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.HUNT_FIRST_IMPACT=`generate-hunt-first-impact`,e.PROCESS_JOB=`process-job`,e}({});const LU=Object.freeze({status:`aborted`});function RU(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 zU=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},BU=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};const VU={};function HU(e){return e&&Object.assign(VU,e),VU}function UU(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 WU(e,t){return typeof t==`bigint`?t.toString():t}function GU(e){return{get value(){{let t=e();return Object.defineProperty(this,`value`,{value:t}),t}throw Error(`cached value already set`)}}}function KU(e){return e==null}function qU(e){let t=e.startsWith(`^`)?1:0,n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function JU(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 YU=Symbol(`evaluating`);function XU(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==YU)return r===void 0&&(r=YU,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function ZU(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function QU(...e){let t={};for(let n of e){let e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function $U(e){return JSON.stringify(e)}const eW=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function tW(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const nW=GU(()=>{if(typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function rW(e){if(tW(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(tW(n)===!1||Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)===!1)}function iW(e){return rW(e)?{...e}:Array.isArray(e)?[...e]:e}const aW=new Set([`string`,`number`,`symbol`]);function oW(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function sW(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function cW(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 lW(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}const uW={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function dW(e,t){let n=e._zod.def;return sW(e,QU(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 ZU(this,`shape`,e),e},checks:[]}))}function fW(e,t){let n=e._zod.def;return sW(e,QU(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 ZU(this,`shape`,r),r},checks:[]}))}function pW(e,t){if(!rW(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 sW(e,QU(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return ZU(this,`shape`,n),n},checks:[]}))}function mW(e,t){if(!rW(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return sW(e,{...e._zod.def,get shape(){let n={...e._zod.def.shape,...t};return ZU(this,`shape`,n),n},checks:e._zod.def.checks})}function hW(e,t){return sW(e,QU(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return ZU(this,`shape`,n),n},get catchall(){return t._zod.def.catchall},checks:[]}))}function gW(e,t,n){return sW(t,QU(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 ZU(this,`shape`,i),i},checks:[]}))}function _W(e,t,n){return sW(t,QU(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 ZU(this,`shape`,i),i},checks:[]}))}function vW(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 yW(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function bW(e){return typeof e==`string`?e:e?.message}function xW(e,t,n){let r={...e,path:e.path??[]};return e.message||(r.message=bW(e.inst?._zod.def?.error?.(e))??bW(t?.error?.(e))??bW(n.customError?.(e))??bW(n.localeError?.(e))??`Invalid input`),delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function SW(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function CW(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}const wW=(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,WU,2),Object.defineProperty(e,`toString`,{value:()=>e.message,enumerable:!1})},TW=RU(`$ZodError`,wW),EW=RU(`$ZodError`,wW,{Parent:Error});function Fee(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 DW(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 OW=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 zU;if(o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>xW(e,a,HU())));throw eW(t,i?.callee),t}return o.value},kW=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=>xW(e,a,HU())));throw eW(t,i?.callee),t}return o.value},AW=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 zU;return a.issues.length?{success:!1,error:new(e??TW)(a.issues.map(e=>xW(e,i,HU())))}:{success:!0,data:a.value}},jW=AW(EW),MW=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=>xW(e,i,HU())))}:{success:!0,data:a.value}},NW=MW(EW),PW=e=>(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return OW(e)(t,n,i)},FW=e=>(t,n,r)=>OW(e)(t,n,r),Iee=e=>async(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return kW(e)(t,n,i)},IW=e=>async(t,n,r)=>kW(e)(t,n,r),LW=e=>(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return AW(e)(t,n,i)},Lee=e=>(t,n,r)=>AW(e)(t,n,r),RW=e=>async(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return MW(e)(t,n,i)},zW=e=>async(t,n,r)=>MW(e)(t,n,r),BW=/^[cC][^\s-]{8,}$/,VW=/^[0-9a-z]+$/,HW=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,UW=/^[0-9a-vA-V]{20}$/,WW=/^[A-Za-z0-9]{27}$/,GW=/^[a-zA-Z0-9_-]{21}$/,KW=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,qW=/^([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})$/,JW=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)$/,YW=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function XW(){return RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)}const ZW=/^(?:(?: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])$/,QW=/^(([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}|:))$/,$W=/^((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])$/,eG=/^(([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])$/,tG=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,nG=/^[A-Za-z0-9_-]*$/,rG=/^(?=.{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])?)*\.?$/,iG=/^\+(?:[0-9]){6,14}[0-9]$/,aG=`(?:(?:\\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])))`,oG=RegExp(`^${aG}$`);function sG(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 cG(e){return RegExp(`^${sG(e)}$`)}function lG(e){let t=sG({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(`^${aG}T(?:${r})$`)}const uG=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},Ree=/^-?\d+$/,dG=/^-?\d+(?:\.\d+)?/,fG=/^(?:true|false)$/i,pG=/^[^A-Z]*$/,mG=/^[^a-z]*$/,hG=RU(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),gG={number:`number`,bigint:`bigint`,object:`date`},_G=RU(`$ZodCheckLessThan`,(e,t)=>{hG.init(e,t);let n=gG[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})}}),vG=RU(`$ZodCheckGreaterThan`,(e,t)=>{hG.init(e,t);let n=gG[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})}}),yG=RU(`$ZodCheckMultipleOf`,(e,t)=>{hG.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):JU(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})}}),bG=RU(`$ZodCheckNumberFormat`,(e,t)=>{hG.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=uW[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=Ree)}),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})}}),xG=RU(`$ZodCheckMaxLength`,(e,t)=>{var n;hG.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!KU(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=SW(r);n.issues.push({origin:i,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),zee=RU(`$ZodCheckMinLength`,(e,t)=>{var n;hG.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!KU(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=SW(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),SG=RU(`$ZodCheckLengthEquals`,(e,t)=>{var n;hG.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!KU(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=SW(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})}}),CG=RU(`$ZodCheckStringFormat`,(e,t)=>{var n,r;hG.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=()=>{})}),wG=RU(`$ZodCheckRegex`,(e,t)=>{CG.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})}}),Bee=RU(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=pG,CG.init(e,t)}),Vee=RU(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=mG,CG.init(e,t)}),TG=RU(`$ZodCheckIncludes`,(e,t)=>{hG.init(e,t);let n=oW(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})}}),EG=RU(`$ZodCheckStartsWith`,(e,t)=>{hG.init(e,t);let n=RegExp(`^${oW(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})}}),DG=RU(`$ZodCheckEndsWith`,(e,t)=>{hG.init(e,t);let n=RegExp(`.*${oW(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})}}),Hee=RU(`$ZodCheckOverwrite`,(e,t)=>{hG.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});var Uee=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(`
|
|
34655
|
+
`);return o.length===0?{diff:c,omittedFiles:o}:{diff:`${c}\n${Cx(o,n)}`,omittedFiles:o}}function Cx(e,t){return[`\n── OMITTED (${e.length} file(s) exceeded the diff budget) ──`,`These files changed but their diff did not fit. Run the matching command to read any you need:`,...e.map(e=>` ${t(e)}`)].join(`
|
|
34656
|
+
`)}var wx=class{sizeCache=new Map;constructor(e,t,n=0){this.cap=e,this.measureUnionDiffChars=t,this.maxSubGroups=n}split(e){if(e.length===0)return[];if(this.cap<=0)return[this.toSubGroup(e,!1)];let t=this.packRecursively(e,[]);return!t.some(e=>!e.isTruncated)&&t.length>1?[this.toSubGroup(e,!0)]:t}packRecursively(e,t){if(this.unionDiffSize(e)<=this.cap)return t.push(this.toSubGroup(e,!1)),t;if(e.length===1||this.maxSubGroups>0&&t.length+1>=this.maxSubGroups)return t.push(this.toSubGroup(e,!0)),t;let[n,r]=this.partitionByOverlap(e);return this.packRecursively(n,t),this.packRecursively(r,t),t}partitionByOverlap(e){let t=[...e].sort((e,t)=>t.changedFiles.length-e.changedFiles.length),n=[t[0]],r=t.slice(1),i=[];for(;r.length>0;){let{index:e,score:t}=Ex(r,new Set(n.flatMap(e=>e.changedFiles))),a=r[e],o=this.unionDiffSize([...n,a])<=this.cap;if(t<=0||!o){i.push(a),r.splice(e,1);continue}n.push(a),r.splice(e,1)}return i.length===0&&i.push(n.pop()),[n,i]}toSubGroup(e,t){return{flows:e,files:Tx(e),isTruncated:t}}unionDiffSize(e){let t=Tx(e),n=t.join(`
|
|
34657
|
+
`),r=this.sizeCache.get(n);if(r!==void 0)return r;let i=this.measureUnionDiffChars(t);return this.sizeCache.set(n,i),i}};function Tx(e){return[...new Set(e.flatMap(e=>e.changedFiles))].sort((e,t)=>e.localeCompare(t))}function Ex(e,t){let n=0,r=-1;for(let[i,a]of e.entries()){let e=Dx(new Set(a.changedFiles),t);e>r&&(r=e,n=i)}return{index:n,score:r}}function Dx(e,t){let n=0;for(let r of e)t.has(r)&&(n+=1);let r=new Set([...e,...t]).size;return r===0?0:n/r}var Ox=class{maxGroupSize;minOverlap;diffCapChars;maxSubGroups;skipPass1;fetchPerFileDiffs;gitDiffCommandFor;constructor(e,t={}){this.fetchDiff=e,this.maxGroupSize=t.maxGroupSize??o.REGRESSION_IMPACT_PASS2_MAX_GROUP_SIZE,this.minOverlap=t.minOverlap??o.REGRESSION_IMPACT_PASS2_MIN_OVERLAP,this.diffCapChars=t.diffCapChars??o.REGRESSION_IMPACT_PASS2_GROUP_DIFF_MAX_CHARS,this.maxSubGroups=t.maxSubGroups??o.REGRESSION_IMPACT_PASS2_MAX_SUBGROUPS,this.skipPass1=t.skipPass1??o.REGRESSION_IMPACT_SKIP_PASS1,this.fetchPerFileDiffs=t.fetchPerFileDiffs,this.gitDiffCommandFor=t.gitDiffCommandFor}plan(e){let t=yx(e,{maxGroupSize:this.maxGroupSize,minOverlap:this.minOverlap});n.logger.info.defaultLog(`[regression-impact] pass 2 grouped: ${e.length} flow(s) → ${t.length} group(s) (max ${this.maxGroupSize}, min overlap ${this.minOverlap})`);for(let[e,r]of t.entries())n.logger.info.defaultLog(`[regression-impact] group #${e+1} (${r.length}): ${r.map(e=>e.flow.name).join(` | `)}`);if(!this.skipPass1)return t.map(e=>({group:e,rawDiff:void 0}));let r=this.memoizedFetch(),i=new wx(this.diffCapChars,e=>r(e).length,this.maxSubGroups),a=[];for(let[e,n]of t.entries())a.push(...this.planCluster(n,e,i,r));return n.logger.info.defaultLog(`[regression-impact] pass 2 grouped: ${t.length} cluster(s) → ${a.length} sub-group(s) after diff-size split`),a}planCluster(e,t,r,a){let o=r.split(e),s=o.length>1||o.some(e=>e.isTruncated),c=o.map(e=>e.isTruncated?{subGroup:e,rawDiff:this.buildOverCapDiff(e.files,t+1,a)}:{subGroup:e,rawDiff:a(e.files)});return s&&(n.logger.info.defaultLog(`[regression-impact] pass2 cluster #${t+1} diff over cap → ${o.length} sub-group(s)`),i.logAgentGroupSplit(`pass2 cluster #${t+1}`,{flows:e.map(e=>({name:e.flow.name,flowId:e.flow.flowId})),diffChars:a([...new Set(e.flatMap(e=>e.changedFiles))]).length},c.map(({subGroup:e,rawDiff:t})=>({flows:e.flows.map(e=>({name:e.flow.name,flowId:e.flow.flowId})),diffChars:t.length,isTruncated:e.isTruncated})))),c.map(({subGroup:e,rawDiff:t})=>({group:e.flows,rawDiff:t}))}buildOverCapDiff(e,t,r){if(this.fetchPerFileDiffs===void 0||this.gitDiffCommandFor===void 0)return this.capDiff(r(e),t);let{diff:i,omittedFiles:a}=Sx(this.fetchPerFileDiffs(e),this.diffCapChars,this.gitDiffCommandFor);return a.length>0&&n.logger.info.defaultLog(`[regression-impact] pass2-group #${t}: budgeted diff packed ${e.length-a.length}/${e.length} whole file(s) under ${this.diffCapChars} chars; ${a.length} omitted (agent can git diff them): ${a.join(`, `)}`),i}memoizedFetch(){let e=new Map;return t=>{let n=t.join(`
|
|
34658
|
+
`),r=e.get(n);if(r!==void 0)return r;let i=this.fetchDiff(t);return e.set(n,i),i}}capDiff(e,t){let r=this.diffCapChars;return r<=0||e.length<=r?e:(n.logger.info.defaultLog(`[regression-impact] pass2-group #${t}: raw diff truncated ${e.length} → ${r} chars (use Read/Grep to inspect omitted files)`),`${e.slice(0,r)}\n... (diff truncated at ${r} chars — use Read/Grep/Glob to inspect the rest)`)}},kx=class{constructor(e,t){this.resultApplier=e,this.shouldUseContractEngine=t}async run(e,t,r){let a=new Ox(e=>o.getDiffForFiles(e,r.rootPath,r.branch,r.resolvedAnchorBranch,r.isUncommitted),{fetchPerFileDiffs:e=>o.getPerFileDiffs(e,r.rootPath,r.branch,r.resolvedAnchorBranch,r.isUncommitted),gitDiffCommandFor:e=>r.isUncommitted?`git diff -- ${e}`:`git diff ${r.resolvedAnchorBranch}...${r.branch} -- ${e}`}).plan(e),s=new A.default({concurrency:o.REGRESSION_IMPACT_DEEP_PASS2_CONCURRENCY}),c=(await Promise.all([...a.entries()].map(([e,i])=>s.add(async()=>{let{group:a,rawDiff:o}=i,s=[...new Set(a.flatMap(e=>e.changedFiles))].map(e=>t.get(e)).filter(m.isDefined);try{let t=Date.now();return{fgi:e,group:a,sharedTech:s,rawDiff:o,result:await this.runPerGroupPass(a,s,r,e+1,o),elapsedSec:((Date.now()-t)/1e3).toFixed(1)}}catch(t){return n.logger.info.defaultLog(`[regression-impact] Pass 2 grouped crashed for sub-group #${e+1} (${a.length} flow(s)): ${String(t)}`),{fgi:e,group:a,sharedTech:s,rawDiff:o,result:void 0,elapsedSec:`0.0`}}})))).filter(e=>e!==void 0).sort((e,t)=>e.fgi-t.fgi),l=0,u=0,d=!1,f=!1,p=0,h=0,g=0,_=0,v=[],y=0;for(let e of c){let{fgi:r,group:i,sharedTech:o,rawDiff:s,result:c,elapsedSec:b}=e;y+=1;let x=s===void 0?``:`, raw diff ${s.length} chars`,S=new Set(i.flatMap(e=>e.changedFiles)).size;if(n.logger.info.defaultLog(`[regression-impact] pass2-group ${y}/${a.length} - sub-group #${r+1} (${i.length} flow(s), ${S} unique file(s), ${o.length} pre-derived tech${x})`),c===void 0){n.logger.info.defaultLog(`[regression-impact] Pass 2 grouped returned null for sub-group #${r+1} — keeping default severities for ${i.length} flow(s)`);continue}n.logger.info.defaultLog(`[regression-impact] pass2-group sub-group #${r+1} DONE in ${b}s (${i.length} flow(s), ${c.turns} turns)`),l+=c.costUsd,u+=c.turns,d||=c.maxTurnsHit,f||=c.maxBudgetHit,p+=c.tokens.cacheReadTokens,h+=c.tokens.cacheCreationTokens,g+=c.tokens.inputTokens,_+=c.tokens.outputTokens,v.push({label:`group-${r+1} (${i.length} flow${i.length===1?``:`s`})`,costUsd:c.costUsd,turns:c.turns,maxTurnsHit:c.maxTurnsHit,maxBudgetHit:c.maxBudgetHit,tokens:{inputTokens:c.tokens.inputTokens,outputTokens:c.tokens.outputTokens,cacheReadTokens:c.tokens.cacheReadTokens,cacheCreationTokens:c.tokens.cacheCreationTokens}});let C=new Map(c.structured.flows.map(e=>[e.flowId,e]));for(let e of i){let i=C.get(e.flow.flowId);if(i===void 0){n.logger.info.defaultLog(`[regression-impact] Pass 2 grouped: no entry for flow "${e.flow.name}" (${e.flow.flowId}) in sub-group #${r+1} — keeping default severity`);continue}let a=e.changedFiles.map(e=>t.get(e)).filter(m.isDefined);this.resultApplier.apply(e,{structured:i},a)}}return i.logCacheTokens(`pass 2 totals`,{cacheReadTokens:p,cacheCreationTokens:h,inputTokens:g,outputTokens:_}),{costUsd:l,turns:u,maxTurnsHit:d,maxBudgetHit:f,tokens:{inputTokens:g,outputTokens:_,cacheReadTokens:p,cacheCreationTokens:h},batches:v}}async runPerGroupPass(e,t,r,a,s){let{query:c,getMessageContentBlocks:l,isResultMessage:u,isErrorResult:d}=await Promise.resolve().then(()=>lz()),f=`grouped-pass2 #${a}`,p=hx(e,t,r.branch,r.resolvedAnchorBranch,r.commitMessages,s,r.gitSignals,r.flowFileReasons),m=this.shouldUseContractEngine??o.REGRESSION_IMPACT_DEEP_CONTRACT_MODE,h=m?`divergence (X!=Y)`:`intent-rubric (20-signal)`,g=m?gx(s!==void 0):mx(s!==void 0);n.logger.info.defaultLog(`[regression-impact] grouped pass2 group ${a}: deep engine = ${h}`),o.REGRESSION_IMPACT_LOG_DEEP_PROMPT&&_x(r.rootPath,`pass2-group-${a}`,g,p,{model:o.REGRESSION_IMPACT_DEEP_MODEL,...o.REGRESSION_SONNET_ANALYZER_REASONING,allowedTools:[`Read`,`Grep`,`Glob`,`Bash`],maxTurns:o.REGRESSION_IMPACT_DEEP_MAX_TURNS,maxBudgetUsd:o.REGRESSION_IMPACT_DEEP_MAX_BUDGET_USD,outputSchema:`SONNET_DEEP_GROUPED_OUTPUT_SCHEMA`});let _=c({prompt:p,options:{model:o.REGRESSION_IMPACT_DEEP_MODEL,...o.REGRESSION_SONNET_ANALYZER_REASONING,systemPrompt:g,allowedTools:[`Read`,`Grep`,`Glob`,`Bash`],permissionMode:o.REGRESSION_PERMISSION_MODE,allowDangerouslySkipPermissions:!0,maxBudgetUsd:o.REGRESSION_IMPACT_DEEP_MAX_BUDGET_USD,maxTurns:o.REGRESSION_IMPACT_DEEP_MAX_TURNS,cwd:r.rootPath,sessionId:(0,v.randomUUID)(),outputFormat:{type:`json_schema`,schema:i.SONNET_DEEP_GROUPED_OUTPUT_SCHEMA},env:{...process.env,...i.buildAnthropicSdkEnv({proxyUrl:r.anthropicBaseUrl,jwtToken:r.jwtToken??``,requestId:n.logger.getRequestId()})}}});i.logAgentCwd(f,r.rootPath);let y=0;for await(let e of _){if(!u(e)){let t=l(e);t!==void 0&&t.length>0&&(y++,i.logAgentActivity(f,y,t));continue}if(d(e)){n.logger.info.defaultLog(`[regression-impact] Pass 2 grouped error for group #${a}: ${String(e.subtype)}`);return}let t=e.total_cost_usd,r=e.num_turns,s=r>=o.REGRESSION_IMPACT_DEEP_MAX_TURNS,c=i.logCacheTokensFromMessage(`pass2 group #${a}`,e),p=e.structured_output;if(p===void 0||!Array.isArray(p.flows)){n.logger.info.defaultLog(`[regression-impact] Pass 2 grouped: missing or malformed structured_output for group #${a}`);return}return{structured:p,costUsd:t,turns:r,maxTurnsHit:s,maxBudgetHit:!1,tokens:c}}}};let Ax=[`NONE`,`LOW`,`MEDIUM`,`HIGH`,`CRITICAL`];function jx(e){if(e==null)return;let t=typeof e==`number`?e:Number(e);if(!(!Number.isFinite(t)||!Number.isInteger(t)||t<1||t>4))return t}function Mx(e){if(typeof e!=`object`||!e)return;let t=e.inScopeFiles;if(Array.isArray(t))return t.filter(e=>typeof e==`string`)}var Nx=class{apply(e,t,n){let r=Mx(t.structured),i=n.length===0&&Array.isArray(t.structured.techChanges)&&t.structured.techChanges.length>0?t.structured.techChanges.map(e=>({file:e.file,confidence:e.confidence,techBefore:e.techBefore,techAfter:e.techAfter})):n,a=new Map(i.map(e=>[e.file,e])),o=(r===void 0?i:r.map(e=>a.get(e)).filter(m.isDefined)).map(e=>({file:e.file,confidence:e.confidence,techBefore:e.techBefore,techAfter:e.techAfter})),s=t.structured.productChanges.map(e=>{let t=jx(e.priority);return{...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},...t===void 0?{}:{priority:t},...e.verdict===void 0?{}:{verdictScore:e.verdict.score,...e.verdict.reason===void 0?{}:{verdictReason:e.verdict.reason}}}}),c=this.deriveSeverity(s);e.severity=c,e.severityReason=s.find(e=>e.severity===c)?.severityReason,e.techChanges=o,e.productChanges=s,t.structured.affectedSteps!==void 0&&(e.affectedSteps=this.enrichAffectedSteps(e.flow,t.structured.affectedSteps)),e.uncertain===!0&&(e.affected=c!==`NONE`,e.uncertain=!1)}deriveSeverity(e){return e.length===0?`NONE`:e.reduce((e,t)=>Ax.indexOf(t.severity)>Ax.indexOf(e)?t.severity:e,`NONE`)}enrichAffectedSteps(e,t){if(!(0,m.isDefined)(e.productFlow))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,m.isDefined)(t))return{stepId:e.stepId,actor:t.actor,action:t.action,reason:e.reason}}).filter(m.isDefined)}};function Px(e){let t=uv(e),n=mv(e),r=dv(e);if(e.branch===void 0||e.resolvedAnchorBranch===void 0||e.commitMessages===void 0)throw Error(`[impact-pipeline] buildDeepRunContext requires branch/resolvedAnchorBranch/commitMessages`);let i=n.filter(e=>e.affected&&e.severity!==`NONE`&&e.severity!==void 0||e.uncertain===!0),a=[...new Set(i.flatMap(e=>e.changedFiles))],s=o.getAuthorEmail(r,e.branch,e.isUncommitted),c=o.getGitSignalsForFiles(r,a,s,e.anchorSha,e.resolvedAnchorBranch),l=new Map(t.map(e=>[e.flowId,e]));return{rootPath:r,branch:e.branch,resolvedAnchorBranch:e.resolvedAnchorBranch,jwtToken:e.jwtToken,anthropicBaseUrl:e.anthropicBaseUrl,isUncommitted:e.isUncommitted,commitMessages:e.commitMessages,anchorSha:e.anchorSha,flowFileReasons:e.flowFileReasons,flowsByFlowId:l,gitSignals:c}}var Fx=class{async execute(e){let t=mv(e).filter(e=>e.affected&&e.severity!==`NONE`&&e.severity!==void 0||e.uncertain===!0);if(t.length===0)return{costUsd:0,turns:0,maxTurnsHit:!1};let n=Px(e),r=await this.createStrategy(new Nx).run(t,e.fileTechByFile??new Map,n);return{costUsd:r.costUsd,turns:r.turns,maxTurnsHit:r.maxTurnsHit,maxBudgetHit:r.maxBudgetHit??!1,tokens:r.tokens,batches:r.batches}}},Ix=class extends Fx{name;constructor(e){super(),this.shouldUseContractEngine=e,this.name=`groupedDeepAnalysis (${e??o.REGRESSION_IMPACT_DEEP_CONTRACT_MODE?`divergence`:`intent-rubric`})`}createStrategy(e){return new kx(e,this.shouldUseContractEngine)}};function Lx(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,m.isDefined)(t))return{stepId:e.stepId,actor:t.actor,action:t.action,reason:e.reason}}).filter(m.isDefined)}async function Rx(e,t,r,i,a,s,c,l,u,d){let f=e.filter(e=>e.affected&&e.severity!==`NONE`&&e.severity!==void 0),p=e.filter(e=>e.uncertain===!0),m=[...f,...p.filter(e=>!f.includes(e))],h=0;if(n.logger.info.defaultLog(`[regression-impact] Sonnet deep analysis for ${m.length} flow(s) (${f.length} affected, ${p.length} uncertain) in parallel...`),m.length===0)return{costUsd:0,turns:0,maxTurnsHit:!1};let g=[...new Set(m.flatMap(e=>e.changedFiles))],_=o.getAuthorEmail(t,r,c),v=o.getGitSignalsForFiles(t,g,_,u,i),y=0,b=0,x=!1,S=new A.default({concurrency:6});for(let e of m)S.add(async()=>{try{h+=1,n.logger.info.defaultLog(`[regression-impact] ${h} - Sonnet deep analysis: ${e.flow.name} (${e.changedFiles.length} file(s))`);let o=await c_(e.flow,e.changedFiles,t,r,i,a,s,c,l,v,d?.get(e.flow.flowId));if(o===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}y+=o.costUsd,b+=o.turns,x||=o.maxTurnsHit,zx(e,o)}catch(t){n.logger.info.defaultLog(`[regression-impact] Sonnet deep crashed for flow "${e.flow.name}": ${String(t)}`)}});return await S.onIdle(),{costUsd:y,turns:b,maxTurnsHit:x}}function zx(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=Lx(e.flow,t.affectedSteps)),e.uncertain===!0&&(e.affected=t.severity!==`NONE`,e.uncertain=!1)}var Bx=class{name=`deepAnalysis`;async execute(e){let t=mv(e),n=dv(e);if(e.branch===void 0||e.resolvedAnchorBranch===void 0||e.commitMessages===void 0)throw Error(`[impact-pipeline] LegacyDeepStep requires branch/resolvedAnchorBranch/commitMessages`);let r=await Rx(t,n,e.branch,e.resolvedAnchorBranch,e.jwtToken,e.anthropicBaseUrl,e.isUncommitted,e.commitMessages,e.anchorSha,e.flowFileReasons);return{costUsd:r.costUsd,turns:r.turns,maxTurnsHit:r.maxTurnsHit}}},Vx=class{name=`loadLibraryForSpecificRun`;async execute(e){let t=e.jobInput?.baselineFromAnalysisId?.trim()??``;if(t.length===0)throw Error(`[impact-pipeline] LoadBaselineFromRunStep requires jobInput.baselineFromAnalysisId — the factory should only select this step when it is set`);let{bundle:r,anchorBranch:i,anchorSha:a,catalogId:s,projectType:c,flows:l}=await rv(e.apiService,e.jobInput,t);if(e.jobInput===null)throw Error(`[impact-pipeline] jobInput is required to resolve catalog roots`);let u;try{u=Rm(e.jobInput)}catch(e){throw Error(`[impact-pipeline] failed to resolve catalog roots: ${String(e)}`,{cause:e})}let d=u.cwd,f=Z_(d,i,a,e.isUncommitted),p=o.getCommitMessages(d,f),h=(0,m.isDefined)(a)?`, sha: ${a}`:``;return n.logger.info.defaultLog(`[regression-impact] Anchor: ${i} (resolved: ${f}${h}) — baseline reused from run ${t}`),e.bundle=r,e.flows=l,e.catalogId=s,e.projectType=c,e.anchorBranch=i,e.anchorSha=a,e.resolvedAnchorBranch=f,e.rootPath=d,e.primarySource=u.primarySource,e.dependencyRoots=u.dependencyRoots,e.commitMessages=p,u_}},Hx=class{name=`mappingSnapshotRead`;execute(e){let t=by(dv(e));if(t===void 0)throw Error(`[impact-pipeline] mapping snapshot resume expected a cache file but none loaded — delete the snapshot or disable REGRESSION_IMPACT_DEV_MAPPING_SNAPSHOT`);let r=[...new Set([...t.flowFileMap.values()].flatMap(e=>[...e]))];return n.logger.info.defaultLog(`[regression-impact] Mapping snapshot RESUME — skipped pre-filter + mapping (${r.length} file(s) from cached flowFileMap drive deep analysis)`),e.mappingResult=t,e.flowFileReasons=t.flowFileReasons,e.changedFiles=r,Promise.resolve(u_)}},Ux=class{name=`mappingSnapshotWrite`;execute(e){let t=dv(e),n=uv(e),r=pv(e);if(e.changedFiles===void 0||e.resolvedAnchorBranch===void 0)throw Error(`[impact-pipeline] mapping snapshot write requires changedFiles/resolvedAnchorBranch from prior steps`);return xy(t,{changedFiles:e.changedFiles,flowIds:n.map(e=>e.flowId),resolvedAnchorBranch:e.resolvedAnchorBranch,strategy:o.REGRESSION_IMPACT_MAPPING_STRATEGY},r),Promise.resolve(u_)}};function Wx(e){if(typeof e!=`object`||!e)return;let t=e.techChanges;if(Array.isArray(t))return t}var Gx=class{async derive(e,t){let n=e.filter(e=>e.affected&&e.severity!==`NONE`&&e.severity!==void 0||e.uncertain===!0),r=[...new Set(n.flatMap(e=>e.changedFiles))];return this.runPass1(r,n,t)}async runPass1(e,t,r){let a=new Map,s=0,c=0,l=!1,u=0,d=0,f=0,p=0,m=this.indexFileReasons(e,t,r.flowFileReasons),h=[];for(let t=0;t<e.length;t+=o.REGRESSION_IMPACT_DEEP_PASS1_BATCH_SIZE){let n=e.slice(t,t+o.REGRESSION_IMPACT_DEEP_PASS1_BATCH_SIZE);h.push(n.map(e=>({file:e,reason:m.get(e)})))}n.logger.info.defaultLog(`[regression-impact] pass 1: ${e.length} file(s) in ${h.length} batch(es) (concurrency ${o.REGRESSION_IMPACT_DEEP_PASS1_CONCURRENCY})`);let g=new A.default({concurrency:o.REGRESSION_IMPACT_DEEP_PASS1_CONCURRENCY}),_=0;for(let[e,t]of h.entries())g.add(async()=>{try{let i=await this.runTechPassForBatch(t,e+1,r);if(_+=1,n.logger.info.defaultLog(`[regression-impact] pass1 batch ${_}/${h.length} (#${e+1}, ${t.length} file(s)) - got ${i?.techs.length??0} techChange(s)`),i===void 0)return;for(let e of i.techs)a.set(e.file,e);s+=i.costUsd,c+=i.turns,l||=i.maxTurnsHit,u+=i.cacheReadTokens,d+=i.cacheCreationTokens,f+=i.inputTokens,p+=i.outputTokens}catch(e){n.logger.info.defaultLog(`[regression-impact] Dedup deep pass 1 batch crashed (${t.length} file(s)): ${String(e)}`)}});return await g.onIdle(),i.logCacheTokens(`pass 1 totals`,{cacheReadTokens:u,cacheCreationTokens:d,inputTokens:f,outputTokens:p}),{fileTechByFile:a,costUsd:s,turns:c,maxTurnsHit:l}}indexFileReasons(e,t,n){let r=new Map;if(n===void 0)return r;for(let i of e)for(let e of t){if(!e.changedFiles.includes(i))continue;let t=n.get(e.flow.flowId)?.get(i);if((0,m.isDefined)(t)&&t.length>0){r.set(i,t);break}}return r}async runTechPassForBatch(e,t,r){let{query:a,getMessageContentBlocks:s,isResultMessage:c,isErrorResult:l}=await Promise.resolve().then(()=>lz()),u=`pass1 batch #${t}`;i.logAgentCwd(u,r.rootPath);let d=e.map(e=>e.file),f=dx(e,o.getDiffForFiles(d,r.rootPath,r.branch,r.resolvedAnchorBranch,r.isUncommitted),r.branch,r.resolvedAnchorBranch),p=ux();o.REGRESSION_IMPACT_LOG_DEEP_PROMPT&&_x(r.rootPath,`pass1-batch-${t}`,p,f);let m=a({prompt:f,options:{model:o.REGRESSION_IMPACT_DEEP_MODEL,...o.REGRESSION_SONNET_ANALYZER_REASONING,systemPrompt:p,allowedTools:[],disallowedTools:[`Read`,`Grep`,`Glob`,`Bash`,`Task`,`TodoWrite`,`Edit`,`Write`,`WebFetch`,`WebSearch`,`NotebookEdit`],permissionMode:o.REGRESSION_PERMISSION_MODE,allowDangerouslySkipPermissions:!0,maxBudgetUsd:o.REGRESSION_IMPACT_DEEP_MAX_BUDGET_USD,maxTurns:o.REGRESSION_IMPACT_DEEP_MAX_TURNS,cwd:r.rootPath,sessionId:(0,v.randomUUID)(),outputFormat:{type:`json_schema`,schema:i.SONNET_DEEP_OUTPUT_SCHEMA},env:{...process.env,...i.buildAnthropicSdkEnv({proxyUrl:r.anthropicBaseUrl,jwtToken:r.jwtToken??``,requestId:n.logger.getRequestId()})}}}),h=0;for await(let e of m){if(!c(e)){let t=s(e);t!==void 0&&t.length>0&&(h++,i.logAgentActivity(u,h,t));continue}if(l(e)){n.logger.info.defaultLog(`[regression-impact] Pass 1 batch error: ${String(e.subtype)}`);return}let r=e.total_cost_usd,a=e.num_turns,f=a>=o.REGRESSION_IMPACT_DEEP_MAX_TURNS,{cacheReadTokens:p,cacheCreationTokens:m,inputTokens:g,outputTokens:_}=i.logCacheTokensFromMessage(`pass1 batch #${t}`,e),v=Wx(e.structured_output);if(v===void 0||v.length===0){n.logger.info.defaultLog(`[regression-impact] Pass 1 batch returned no techChanges (${d.length} file(s))`);return}let y=new Set(d),b=v.filter(e=>y.has(e.file));if(b.length<d.length){let e=d.filter(e=>!b.some(t=>t.file===e));n.logger.info.defaultLog(`[regression-impact] Pass 1 batch produced ${b.length}/${d.length} techChange(s); missing: ${e.join(`, `)}`)}return{techs:b,costUsd:r,turns:a,maxTurnsHit:f,cacheReadTokens:p,cacheCreationTokens:m,inputTokens:g,outputTokens:_}}}},Kx=class{name=`deepAnalysisPass1`;async execute(e){let t=mv(e),n=Px(e),r=await new Gx().derive(t,n);return e.fileTechByFile=r.fileTechByFile,{costUsd:r.costUsd,turns:r.turns,maxTurnsHit:r.maxTurnsHit}}},qx=class{constructor(e){this.resultApplier=e}async run(e,t,r){let a=0,s=0,c=!1,l=!1,u=0,d=0,f=0,p=0,h=new Map,g=new A.default({concurrency:o.REGRESSION_IMPACT_DEEP_PASS2_CONCURRENCY}),_=0;for(let[i,o]of e.entries())g.add(async()=>{try{_+=1;let g=o.changedFiles.map(e=>t.get(e)).filter(m.isDefined);n.logger.info.defaultLog(`[regression-impact] pass2 ${_}/${e.length} - ${o.flow.name} (${g.length}/${o.changedFiles.length} pre-derived tech)`);let v=Date.now(),y=await this.runPerFlowPass(o,g,r),b=((Date.now()-v)/1e3).toFixed(1);if(y===void 0){n.logger.info.defaultLog(`[regression-impact] Pass 2 returned null for flow "${o.flow.name}" — keeping default severity "${o.severity}" with no techChanges/productChanges`);return}n.logger.info.defaultLog(`[regression-impact] pass2 ${_}/${e.length} - ${o.flow.name} DONE in ${b}s (${y.turns} turns)`),a+=y.costUsd,s+=y.turns,c||=y.maxTurnsHit,l||=y.maxBudgetHit,u+=y.tokens.cacheReadTokens,d+=y.tokens.cacheCreationTokens,f+=y.tokens.inputTokens,p+=y.tokens.outputTokens,h.set(i+1,{label:`flow-${i+1} (${o.flow.name})`,costUsd:y.costUsd,turns:y.turns,maxTurnsHit:y.maxTurnsHit,maxBudgetHit:y.maxBudgetHit,tokens:{inputTokens:y.tokens.inputTokens,outputTokens:y.tokens.outputTokens,cacheReadTokens:y.tokens.cacheReadTokens,cacheCreationTokens:y.tokens.cacheCreationTokens}}),this.resultApplier.apply(o,y,g)}catch(e){n.logger.info.defaultLog(`[regression-impact] Pass 2 crashed for flow "${o.flow.name}": ${String(e)}`)}});await g.onIdle(),i.logCacheTokens(`pass 2 totals`,{cacheReadTokens:u,cacheCreationTokens:d,inputTokens:f,outputTokens:p});let v=[...h.entries()].sort(([e],[t])=>e-t).map(([,e])=>e);return{costUsd:a,turns:s,maxTurnsHit:c,maxBudgetHit:l,tokens:{inputTokens:f,outputTokens:p,cacheReadTokens:u,cacheCreationTokens:d},batches:v}}async runPerFlowPass(e,t,r){let{query:a,getMessageContentBlocks:s,isResultMessage:c,isErrorResult:l}=await Promise.resolve().then(()=>lz()),u=`per-flow-pass2 (${e.flow.name})`;i.logAgentCwd(u,r.rootPath);let d=px(e.flow,t,r.branch,r.resolvedAnchorBranch,r.commitMessages),f=fx();o.REGRESSION_IMPACT_LOG_DEEP_PROMPT&&_x(r.rootPath,`pass2-flow-${vx(e.flow.flowId)}`,f,d);let p=a({prompt:d,options:{model:o.REGRESSION_IMPACT_DEEP_MODEL,...o.REGRESSION_SONNET_ANALYZER_REASONING,systemPrompt:f,allowedTools:[`Read`,`Grep`,`Glob`,`Bash`],permissionMode:o.REGRESSION_PERMISSION_MODE,allowDangerouslySkipPermissions:!0,maxBudgetUsd:o.REGRESSION_IMPACT_DEEP_MAX_BUDGET_USD,maxTurns:o.REGRESSION_IMPACT_DEEP_MAX_TURNS,cwd:r.rootPath,sessionId:(0,v.randomUUID)(),outputFormat:{type:`json_schema`,schema:i.SONNET_DEEP_OUTPUT_SCHEMA},env:{...process.env,...i.buildAnthropicSdkEnv({proxyUrl:r.anthropicBaseUrl,jwtToken:r.jwtToken??``,requestId:n.logger.getRequestId()})}}}),m=0;for await(let t of p){if(!c(t)){let e=s(t);e!==void 0&&e.length>0&&(m++,i.logAgentActivity(u,m,e));continue}if(l(t)){n.logger.info.defaultLog(`[regression-impact] Pass 2 error for flow "${e.flow.name}": ${String(t.subtype)}`);return}let r=t.total_cost_usd,a=t.num_turns,d=a>=o.REGRESSION_IMPACT_DEEP_MAX_TURNS,f=i.logCacheTokensFromMessage(`pass2 flow "${e.flow.name}"`,t),p=t.structured_output;if(p===void 0){n.logger.info.defaultLog(`[regression-impact] Pass 2: missing structured_output for "${e.flow.name}"`);return}return{structured:p,costUsd:r,turns:a,maxTurnsHit:d,maxBudgetHit:!1,tokens:f}}}},Jx=class extends Fx{name=`perFlowDeepAnalysis`;createStrategy(e){return new qx(e)}},Yx=class{name=`postDetectExperimental`;isTerminal=!0;async execute(e){let t=e.jobInput?.projectId??e.globalConfigService.getProjectId();if(!(0,m.isDefined)(t)||t.length===0)return n.logger.info.defaultLog(`[regression-first] No projectId — skipping experimental post (detect result still in local file)`),u_;let r=e.detectedRegressions??[],i=e.detectTokens??{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0},a=i.cacheReadTokens+i.cacheCreationTokens+i.inputTokens,o=a>0?i.cacheReadTokens/a*100:0,s={anchorRef:e.resolvedAnchorBranch??`unknown`,compareRef:e.branch??`unknown`,count:r.length,costUsd:e.detectCostUsd??0,turns:e.detectTurns??0,durationSeconds:(Date.now()-e.startTime)/1e3,tokens:{...i,cacheHitPct:Number(o.toFixed(1))},findings:r};try{let r=await e.apiService.post(`/api/experimental/key-values`,{type:`regression-first`,key:t,data:s});n.logger.info.defaultLog(`[regression-first] Detect result posted to experimental store: id=${r.id} type=regression-first key=${t}`)}catch(e){n.logger.info.defaultLog(`[regression-first] WARN: failed to post detect result to experimental store (key=${t}): ${String(e)}`)}return u_}},Xx=class{name=`preFilter`;async execute(e){let t=dv(e);if(e.branch===void 0)throw Error(`[impact-pipeline] ctx.branch is unset — ResolveCompareStep must run before this step`);if(e.resolvedAnchorBranch===void 0)throw Error(`[impact-pipeline] ctx.resolvedAnchorBranch is unset — LoadLibraryStep must run before this step`);let r=[e.primarySource??t,...(e.dependencyRoots??[]).map(e=>e.sourcePath)],{changedFiles:i,compareDescription:a,changeDetection:o,preFilterCostUsd:s,preFilterTurns:c,preFilterMaxTurnsHit:l}=await Sv(t,e.branch,e.resolvedAnchorBranch,e.runType,e.jwtToken,e.anthropicBaseUrl,r);return n.logger.info.defaultLog(`[regression-impact] Compare: ${a}`),e.changedFiles=i,e.compareDescription=a,e.changeDetection=o,i.length===0?(n.logger.info.defaultLog(`[regression-impact] No changes detected`),{costUsd:s,turns:c,maxTurnsHit:l,status:l_.Halt}):(n.logger.info.defaultLog(`[regression-impact] ${i.length} changed files`),{costUsd:s,turns:c,maxTurnsHit:l})}};let Zx={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0},Qx={roughGuessedFlowIds:new Set,rescuedFiles:[],totalFiles:0,costUsd:0,turns:0,maxTurnsHit:!1,tokens:Zx,batchMetrics:[]};function $x(e,t){let n=e;return n===void 0||!Array.isArray(n.guesses)?[]:n.guesses.map(e=>({file:e.file,flowIds:(Array.isArray(e.flowIds)?e.flowIds:[]).filter(e=>t.has(e)),reason:e.reason}))}function eS(e,t,r){let i=new Set,a=[],s=r.flowFileReasons??new Map;for(let c of e){if(!t.has(c.file)||c.flowIds.length===0)continue;let e=c.flowIds.slice(0,o.REGRESSION_IMPACT_ROUGH_MAP_CAP),l=c.reason??`rough-map: guessed from diff (precise mapper aborted)`;for(let t of e){let e=r.flowFileMap.get(t)??new Set;e.add(c.file),r.flowFileMap.set(t,e),i.add(t);let n=s.get(t)??new Map;n.set(c.file,`rough-map (low confidence): ${l}`),s.set(t,n)}a.push(c.file),n.logger.info.defaultLog(`[regression-impact] Rough-map rescued ${c.file} -> ${e.length} flow(s): ${e.join(`, `)}`)}return r.flowFileReasons=s,{roughGuessedFlowIds:i,rescuedFiles:a}}function tS(e,t){let n=[];for(let r=0;r<e.length;r+=Math.max(1,t))n.push(e.slice(r,r+Math.max(1,t)));return n}async function nS(e,t,r,a,s,l,u,d,f,p){let{query:m,isResultMessage:h,isErrorResult:g,getMessageContentBlocks:_}=await Promise.resolve().then(()=>lz()),y=`residual batch #${a}`,b={guesses:[],costUsd:0,turns:0,maxTurnsHit:!1,tokens:Zx},x=o.getPerFileDiffs(t,s,l,u,p),S=m({prompt:c.buildResidualRoughMapPrompt(e,t,x,l,u),options:{model:o.REGRESSION_IMPACT_SONNET_MODEL,...o.REGRESSION_SONNET_ANALYZER_REASONING,systemPrompt:c.buildResidualRoughMapSystemPrompt(o.REGRESSION_IMPACT_ROUGH_MAP_CAP),allowedTools:[],permissionMode:o.REGRESSION_PERMISSION_MODE,allowDangerouslySkipPermissions:!0,maxBudgetUsd:o.REGRESSION_IMPACT_AGENTIC_MAX_BUDGET_USD,maxTurns:10,cwd:s,sessionId:(0,v.randomUUID)(),outputFormat:{type:`json_schema`,schema:i.RESIDUAL_ROUGH_MAP_OUTPUT_SCHEMA},env:{...process.env,...i.buildAnthropicSdkEnv({proxyUrl:f,jwtToken:d??``,requestId:n.logger.getRequestId()})}}});i.logAgentCwd(y,s);let C=0;for await(let e of S){if(!h(e)){let t=_(e);t!==void 0&&t.length>0&&(C++,i.logAgentActivity(y,C,t));continue}if(g(e))return n.logger.info.defaultLog(`[regression-impact] Residual rough-map ${y} error: ${e.subtype} — its files remain incomplete`),b;let t=e.num_turns,a=i.extractCacheTokens(e);return i.logCacheTokensFromMessage(y,e),{guesses:$x(e.structured_output,r),costUsd:e.total_cost_usd,turns:t,maxTurnsHit:t>=10,tokens:a}}return b}async function rS(e,t,r,i,a,s,c,l,u=!1){if(t.length===0)return Qx;let d=new Set(e.map(e=>e.flowId)),f=new Set(t),p=tS(t,o.REGRESSION_IMPACT_RESIDUAL_BATCH_SIZE);n.logger.info.defaultLog(`[regression-impact] Residual rough-map: guessing flows for ${t.length} dropped file(s) in ${p.length} batch(es): ${t.join(`, `)}`);let m=new A.default({concurrency:o.REGRESSION_IMPACT_RESIDUAL_CONCURRENCY}),h=p.entries(),g=(await Promise.all([...h].map(([t,r])=>m.add(async()=>{try{return{batchIndex:t,batchFiles:r,...await nS(e,r,d,t+1,i,a,s,c,l,u)}}catch(e){n.logger.info.defaultLog(`[regression-impact] Residual rough-map batch #${t+1} crashed (${r.length} file(s)): ${String(e)}`);return}})))).filter(e=>e!==void 0).sort((e,t)=>e.batchIndex-t.batchIndex),_=new Set,v=new Set,y=0,b=0,x=!1,S={...Zx},C=[];for(let e of g){let t=eS(e.guesses,f,r);for(let e of t.roughGuessedFlowIds)_.add(e);for(let e of t.rescuedFiles)v.add(e);y+=e.costUsd,b+=e.turns,x||=e.maxTurnsHit,S.inputTokens+=e.tokens.inputTokens,S.outputTokens+=e.tokens.outputTokens,S.cacheReadTokens+=e.tokens.cacheReadTokens,S.cacheCreationTokens+=e.tokens.cacheCreationTokens,C.push({label:`residual-batch-${e.batchIndex+1}`,totalFiles:e.batchFiles.length,costUsd:e.costUsd,turns:e.turns,maxTurnsHit:e.maxTurnsHit,maxBudgetHit:!1,tokens:e.tokens})}let w=[...v],T=t.filter(e=>!v.has(e));return n.logger.info.defaultLog(`[regression-impact] Residual rough-map: rescued ${w.length} file(s) onto ${_.size} flow(s); ${T.length} file(s) still incomplete`+(T.length>0?` (no confident guess): ${T.join(`, `)}`:``)),n.logger.info.defaultLog(`[regression-impact] Residual rough-map summary (${t.length} dropped file(s)):`),n.logger.info.defaultLog(`[regression-impact] → rescued onto flows (${w.length}): ${w.length>0?w.join(`, `):`(none)`}`),n.logger.info.defaultLog(`[regression-impact] → still unmapped (${T.length}): ${T.length>0?T.join(`, `):`(none)`}`),{roughGuessedFlowIds:_,rescuedFiles:w,totalFiles:t.length,costUsd:y,turns:b,maxTurnsHit:x,tokens:S,batchMetrics:C}}var iS=class{name=`residualRoughMap`;async execute(e){let t=pv(e),n=t.incompleteFiles??[];if(n.length===0)return u_;let r=uv(e),i=dv(e);if(e.branch===void 0||e.resolvedAnchorBranch===void 0)throw Error(`[impact-pipeline] ResidualRoughMapStep requires branch/resolvedAnchorBranch`);let a=await rS(r,n,t,i,e.branch,e.resolvedAnchorBranch,e.jwtToken,e.anthropicBaseUrl,e.isUncommitted);if(e.roughGuessedFlowIds=a.roughGuessedFlowIds,a.rescuedFiles.length>0){let e=new Set(a.rescuedFiles);t.incompleteFiles=n.filter(t=>!e.has(t))}return{costUsd:a.costUsd,turns:a.turns,maxTurnsHit:a.maxTurnsHit,tokens:a.tokens,totalFiles:a.totalFiles,mappedFiles:a.rescuedFiles.length,batches:a.batchMetrics.length>0?a.batchMetrics:void 0}}},aS=class{name=`verifyProductIntent`;async execute(e){let t=e.detectedRegressions??[];if(t.length===0)return u_;let n=dv(e);if(e.branch===void 0||e.resolvedAnchorBranch===void 0)throw Error(`[impact-pipeline] VerifyProductIntentStep requires branch/resolvedAnchorBranch from ResolveCompare`);let r=e.changedFiles??[],i=o.getDiffForFiles(r,n,e.branch,e.resolvedAnchorBranch,e.isUncommitted),a=o.formatCommitMessagesBlock(e.commitMessages??[]),s=wy(e.jobInput,n),c=await _b({anchorRef:e.resolvedAnchorBranch,compareRef:e.branch,rootPath:n,diffText:i,commitMessagesBlock:a,jwtToken:e.jwtToken,anthropicBaseUrl:e.anthropicBaseUrl,primarySource:s.primarySource,dependencyRoots:s.dependencyRoots},t);e.detectedRegressions=c.regressions,e.detectCostUsd=(e.detectCostUsd??0)+c.costUsd,e.detectTurns=(e.detectTurns??0)+c.turns;let l=e.detectTokens;return e.detectTokens=l===void 0?c.tokens:{inputTokens:(l.inputTokens??0)+(c.tokens.inputTokens??0),outputTokens:(l.outputTokens??0)+(c.tokens.outputTokens??0),cacheReadTokens:(l.cacheReadTokens??0)+(c.tokens.cacheReadTokens??0),cacheCreationTokens:(l.cacheCreationTokens??0)+(c.tokens.cacheCreationTokens??0)},{costUsd:c.costUsd,turns:c.turns,maxTurnsHit:c.maxTurnsHit,totalFiles:c.regressions.length,tokens:c.tokens}}},oS=class{name=`writeDetectResult`;isTerminal=!0;async execute(e){let t=e.detectedRegressions??[],r=e.branch??`unknown`,i=`(file write disabled)`;if(o.REGRESSION_FIRST_WRITE_DETECT_FILE){let n=e.detectCostUsd??0,a=e.detectTurns??0,s=e.detectTokens??{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0},c=s.cacheReadTokens+s.cacheCreationTokens+s.inputTokens,l=c>0?s.cacheReadTokens/c*100:0;if(!I.default.isAbsolute(o.REGRESSION_DEV_ARTIFACT_DIR))throw Error(`[regression-first] REGRESSION_DEV_ARTIFACT_DIR must be an absolute path when REGRESSION_FIRST_WRITE_DETECT_FILE is enabled (got: "${o.REGRESSION_DEV_ARTIFACT_DIR}"). A relative/empty dir resolves against the scanned repo's cwd.`);let u=Zy(r,e.detectVariant??`v1`),d=I.default.join(o.REGRESSION_DEV_ARTIFACT_DIR,`my-runs`);(0,y.mkdirSync)(d,{recursive:!0}),i=I.default.join(d,`regression-detect-${u}.json`);let f={anchorRef:e.resolvedAnchorBranch??`unknown`,compareRef:r,count:t.length,costUsd:n,turns:a,durationSeconds:(Date.now()-e.startTime)/1e3,tokens:{...s,cacheHitPct:Number(l.toFixed(1))},findings:t};(0,y.writeFileSync)(i,JSON.stringify(f,null,2))}let a=[...t].sort((e,t)=>t.score-e.score);n.logger.info.defaultLog(`[regression-first] Detect result: ${t.length} finding(s) → ${i}`);for(let e of a)n.logger.info.defaultLog(`[regression-first] [${e.score}] ${e.severity} ${e.title} (${e.file})`);return u_}};function sS(e){if(e===`agentic`||e===`agentic-ast`||e===`shallow`)return new Ab(e);throw Error(`[impact-pipeline] unsupported mapping strategy "${e}" — only "agentic", "agentic-ast", and "shallow" are wired in this version`)}function cS(e,t){if(t&&e.devMappingSnapshotResume)return[new Hx];let n=t?[new Xx,sS(e.mappingStrategy)]:[sS(e.mappingStrategy)];return e.residualRoughMap&&n.push(new iS),e.devMappingSnapshotWrite&&n.push(new Ux),n}function lS(e,t,n){let r=[e,new Cv,new ox,new Xx,t];return n!==void 0&&r.push(n),r.push(new Xb,new Yb,new oS),o.REGRESSION_FIRST_POST_EXPERIMENTAL&&r.push(new Yx),r.push(new Lb,new vv,new cv),r}function uS(e){return e.regressionFirstV2===!0||e.regressionFirstV2Adj===!0?new tx:e.regressionFirstV3===!0?new nx:e.regressionFirstSingle===!0?new ex:e.regressionFirstMono===!0?new $b:e.regressionFirstExperiment===!0?new Qb:new Zb}function dS(e,t){if(!(e.regressionFirst!==!0&&e.regressionFirstV2!==!0&&e.regressionFirstV3!==!0&&e.regressionFirstV2Adj!==!0&&e.regressionFirstSingle!==!0&&e.regressionFirstMono!==!0&&e.regressionFirstExperiment!==!0))return new Y_(lS(t,uS(e),fS(e)))}function fS(e){if(e.regressionFirstV3===!0)return new aS;if(e.regressionFirstV2Adj===!0)return new Db}let pS={create(e,t=!1){let n=e.baselineFromAnalysisId!==void 0&&e.baselineFromAnalysisId.length>0?new Vx:new av,r=dS(e,n);if(r!==void 0)return r;let i=t?[...cS(e,!1),new Mb]:[n,new Cv,...cS(e,!0),new Mb];if(e.stopAfterMapping)return i.push(new vv,new cv),new Y_(i);if(e.deepMode===`legacy`)i.push(new Bx);else{if(!e.skipPass1&&(i.push(new Kx),e.stopAfterPass1))return i.push(new vv,new cv),new Y_(i);i.push(e.pass2Grouped?new Ix(e.contractMode):new Jx)}return e.calibrationEnabled&&i.push(new Hb),i.push(new vv,new cv),new Y_(i)}};function mS(e){if(e!==void 0)return e===`perflow`?`legacy`:`dedup`}function hS(e){if(e!==void 0)return e===`divergence`}function gS(e){return e===`regression-first`}function _S(e){return e===`regression-first-2`}function vS(e){return e===`regression-first-3`}function yS(e){return e===`regression-first-2-adj`}function bS(e){return e===`regression-first-single`}function xS(e){return e===`regression-first-mono`}function SS(e){return e===`regression-first-experiment`}async function CS(e,t,n,r,a,o,s,c){let l=Date.now(),u=t===`LOCAL`;i.setAgentLogEnabled(s?.agentLog??!1);let d={reportsDir:e,runType:t,isUncommitted:u,jwtToken:n,anthropicBaseUrl:r,apiService:a,globalConfigService:o,jobInput:s,compareBranch:c,startTime:l,stepMetrics:[]},f=s?.analysisMode??`regression-first-2`,p=mS(f),m=hS(f),h=gS(f),g=_S(f),_=vS(f),v=yS(f),y=bS(f),b=xS(f),x=SS(f),S=Cy(s?.projectRootPath,p,s?.baselineFromAnalysisId,m,s?.fileMappingMode,h,g,_,v,y,b,x);if(await pS.create(S).run(d),h||g||_||v||y)return d.result??{flowImpacts:[],catalogId:null,rootPath:d.rootPath??``,changedFiles:d.changedFiles??[],branch:d.branch??``,headSha:d.headSha,anchorBranch:d.resolvedAnchorBranch??``,anchorSha:d.anchorSha,runType:t};if(d.result===void 0)throw Error(`[regression-impact] pipeline finished without producing a result (ReportStep did not run)`);return d.result}var wS=t.__toESM(n.require_decorateMetadata()),TS=t.__toESM(nn()),ES=t.__toESM(n.require_decorate()),DS,OS;let kS=class{constructor(e,t,n){this.globalConfigService=e,this.apiService=t,this.authStorage=n}async run(e){let t=await this.authStorage.getJWTToken(),n=await xh(this.apiService,this.globalConfigService);return n?.crossComponent?J_(e.reportsDir,t,this.globalConfigService.getAnthropicProxyUrl(),this.apiService,this.globalConfigService,n,e.compareBranch):(n?.analysisMode===`hunterImpact`?py:CS)(e.reportsDir,e.runType,t,this.globalConfigService.getAnthropicProxyUrl(),this.apiService,this.globalConfigService,n,e.compareBranch)}};kS=(0,ES.default)([(0,h.injectable)(),(0,TS.default)(0,(0,h.inject)(n.GlobalConfigService)),(0,TS.default)(1,(0,h.inject)(ln)),(0,TS.default)(2,(0,h.inject)(tn)),(0,wS.default)(`design:paramtypes`,[Object,typeof(DS=ln!==void 0&&ln)==`function`?DS:Object,typeof(OS=tn!==void 0&&tn)==`function`?OS:Object])],kS);var AS=t.__toESM(n.require_decorateMetadata()),jS=t.__toESM(nn()),MS=t.__toESM(n.require_decorate()),NS,PS;let FS=class{constructor(e,t,n){this.globalConfigService=e,this.apiService=t,this.authStorage=n}async run(e){let t=await this.authStorage.getJWTToken(),n=await xh(this.apiService,this.globalConfigService);return py(e.reportsDir,e.runType,t,this.globalConfigService.getAnthropicProxyUrl(),this.apiService,this.globalConfigService,n,e.compareBranch)}};FS=(0,MS.default)([(0,h.injectable)(),(0,jS.default)(0,(0,h.inject)(n.GlobalConfigService)),(0,jS.default)(1,(0,h.inject)(ln)),(0,jS.default)(2,(0,h.inject)(tn)),(0,AS.default)(`design:paramtypes`,[Object,typeof(NS=ln!==void 0&&ln)==`function`?NS:Object,typeof(PS=tn!==void 0&&tn)==`function`?PS:Object])],FS);let IS=`claude-haiku-4-5-20251001`,LS=`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(`,`),RS={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 zS=t.__toESM(n.require_decorateMetadata()),BS=t.__toESM(nn()),VS=t.__toESM(n.require_decorate()),HS,US,WS,GS;function KS(e){if((0,m.isDefined)(e))return e;try{let e=(0,L.createRequire)(__filename)?.resolve?.(`@anthropic-ai/claude-agent-sdk`);if(e)return d.default.join(d.default.dirname(e),`cli.js`)}catch{}return d.default.join(__dirname,`..`,`..`,`node_modules`,`@anthropic-ai`,`claude-agent-sdk`,`cli.js`)}function qS(){return d.default.join(__dirname,`..`,`plugin`)}function JS(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 YS(e,t){return{type:`user`,message:{role:`user`,content:e},parent_tool_use_id:null,session_id:t}}async function*XS(e,t,n,r,i){yield YS(e,t),await JS(3e4,n),!n.aborted&&(await r.flush(),i.debug(`[plugin-agent] Phase transition: recon → draft`),yield YS(`<system-reminder>Recon time is over. Move to Phase 3 — draft the test file now.</system-reminder>`,t),await JS(3e4,n),!n.aborted&&(await r.flush(),i.debug(`[plugin-agent] Phase transition: draft → validate`),yield YS(`<system-reminder>Draft time is over. Move to Phase 4 — run test, lint, and format gates now.</system-reminder>`,t),await JS(15e3,n),!n.aborted&&(await r.flush(),i.debug(`[plugin-agent] Phase transition: validate → stop`),yield YS(`<system-reminder>Time is up. Stop all work. Exit with your structured output now.</system-reminder>`,t))))}let ZS=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()??qS(),o=d.default.join(t,`skills`,`early-generate-unit-tests`,`references`),s=this.globalConfigService.getBackendURL(),c=Date.now(),l=()=>Date.now()-c;if(!s)return{outcome:`error`,success:!1,error:`backendURL is not configured`,durationMs:l()};let u=e.requestId??n.logger.getRequestId(),p=new AbortController;(0,m.isDefined)(e.abortSignal)&&(e.abortSignal.aborted?p.abort():e.abortSignal.addEventListener(`abort`,()=>p.abort(),{once:!0}));let h=await this.authStorage.getJWTToken()??``,g=KS(this.globalConfigService.getClaudeCodeExecutablePath()),_=r.getFileLanguage(e.filePath),y=r.isPythonFile(e.filePath)?n.TestFramework.PYTEST:this.globalConfigService.getTestFramework();try{await this.apiService.post(`/api/v1/tests/generate-prompt`,{testedCodeDataSource:{filePath:e.filePath,relativePathToTestFile:``,testFramework:y,language:_,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:{[Ht]:u}})}catch(e){if(e instanceof Bt&&e.code===Rt.NOT_ENOUGH_BALANCE_ERROR)return{outcome:`error`,success:!1,error:e.message,errorCode:e.code,durationMs:l()};n.logger.info.defaultLog(`[plugin-agent] generate-prompt side-effect failed: ${e}`)}let b=(0,m.isDefined)(e.testFilePath)?new vr(e.testFilePath):await vr.getNextTestFile(e.filePath,e.methodName,e.workingDirectory);if(e.preserveExistingContent===!0&&!(0,m.isDefined)(e.testFilePath)){let t=await vr.getLatestTestFile(e.filePath,e.methodName);if((0,m.isDefined)(t)){let e=await new vr(r.absoluteToRelativePath(t)).getText();e.trim().length>0&&await b.replace(e)}}let x=(await b.isFileExists()?await b.getText():``).trim().length>0,S=e.preserveExistingContent===!0&&x;if(e.preserveExistingContent===!0&&!x&&n.logger.default.warn(`[plugin-agent] preserveExistingContent was requested but the target file is empty — falling back to generate mode.`),!S){let t=r.isPythonFile(e.filePath)?`#`:`//`;await b.replace(`${t} early-test-generation-in-progress`)}let C=b.getAbsoluteFilePath(),w=b.getFilePath(),T=d.default.relative(e.workingDirectory,C),E=d.default.join(o,`framework`,`${y}.md`),D=d.default.join(o,`${_}.md`),O=e=>(0,f.readFile)(e,`utf8`).catch(()=>(n.logger.default.warn(`[plugin-agent] Reference file not found: ${e}`),``)),[k,A]=await Promise.all([O(E),O(D)]),j=[`Generate unit tests for method \`${e.methodName}\` in: ${e.filePath}`,`Framework: ${y}`,`Working directory: ${d.default.normalize(e.workingDirectory)}`,`testFilePath: ${d.default.normalize(T)}`];S&&j.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,m.isDefined)(e.userPrompt)&&e.userPrompt.trim()!==``&&j.push(``,e.userPrompt),k!==``&&j.push(``,`---`,`## Framework Reference`,k),A!==``&&j.push(``,`---`,`## Language Reference`,A);let M=j.join(`
|
|
34659
|
+
`),ee=this.globalConfigService.getProgressLogger({methodName:e.methodName});n.logger.info.defaultLog(`[plugin-agent] Starting plugin agent for file: ${e.filePath}, testFile: ${T}`);let N=u,te=new sf(this.metricReportService,N,IS,C,e.workingDirectory),P=cd(C,e.workingDirectory),F=(0,v.randomUUID)(),I=(0,ne.query)({prompt:XS(M,F,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(`
|
|
34660
|
+
`)},model:IS,pathToClaudeCodeExecutable:g,allowedTools:[...LS],permissionMode:`dontAsk`,maxBudgetUsd:2,cwd:e.workingDirectory,abortController:p,outputFormat:{type:`json_schema`,schema:RS},sessionId:F,env:{...process.env,...i.buildAnthropicSdkEnv({proxyUrl:this.globalConfigService.getAnthropicProxyUrl(),jwtToken:h,requestId:u})},stderr:e=>{n.logger.info.defaultLog(`[plugin-agent] STDERR: ${e}`)},hooks:{PreToolUse:[{matcher:`Write|Edit`,hooks:[P]},{matcher:`Read`,hooks:[sd]},{matcher:`Bash`,hooks:[od,Au]}]}}}),L=0;try{for await(let t of I){L+=1,await te.processMessage(t);let r=t.type;if(ee.debug(`[plugin-agent] stream message #${L} type=${r??`unknown`}`),r===`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`);if(i.length>0)n.logger.info.defaultLog(`[plugin-agent] Tool calls: ${i.join(`, `)}`);else if(a){let e=r.filter(e=>e.type===`text`).map(e=>e.text).join(` `).slice(0,500);n.logger.info.defaultLog(`[plugin-agent] Agent thinking: ${e}`)}}if(a.isResultMessage(t)){await te.flush();let r=l();if(a.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:r};n.logger.info.defaultLog(`[plugin-agent] Agent completed. Cost: $${t.total_cost_usd.toFixed(4)} — ${r}ms`);let i=QS(t.structured_output),o=i?.status,s=i?.reason;if(o===`skipped`||o===`aborted`||o===`no-viable-tests`){let e=(0,m.isDefined)(s)?`${o}: ${s}`:o;return n.logger.info.defaultLog(`[plugin-agent] ${o} by skill: ${s??`no reason given`}`),this.metricReportService.saveTestMetrics({requestId:N,timeElapsed:r,errorCause:e}),o===`skipped`?{outcome:`skipped`,success:!0,skipped:!0,skipReason:s??`trivial`,costUsd:t.total_cost_usd,durationMs:r}:{outcome:o,success:!1,costUsd:t.total_cost_usd,error:e,durationMs:r}}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:r};let c=await b.getText(),u=await this.testResultCounterService.getValidationReport(C,e.methodName).catch(()=>void 0),d=te.getLatestTestResult(),f=i?.passedCount??d?.passed??u?.greenTestsCount,p=i?.failedCount??d?.failed??u?.redTestsCount;return this.metricReportService.saveTestMetrics({requestId:N,timeElapsed:r,validationReport:u}),c!==``&&this.metricReportService.saveOperationMetricsTrace({parentRequestId:N,llmModel:IS,testFileContent:c}),{outcome:`generated`,success:!0,costUsd:t.total_cost_usd,testFilePath:w,durationMs:r,greenTestsCount:f,redTestsCount:p}}}return await te.flush(),{outcome:`error`,success:!1,error:`stream_ended_without_result`,durationMs:l()}}finally{p.abort()}}};ZS=(0,VS.default)([(0,h.injectable)(),(0,BS.default)(0,(0,h.inject)(n.GlobalConfigService)),(0,BS.default)(1,(0,h.inject)(tn)),(0,BS.default)(2,(0,h.inject)(ln)),(0,BS.default)(3,(0,h.inject)(Dn)),(0,BS.default)(4,(0,h.inject)(jl)),(0,zS.default)(`design:paramtypes`,[Object,typeof(HS=tn!==void 0&&tn)==`function`?HS:Object,typeof(US=ln!==void 0&&ln)==`function`?US:Object,typeof(WS=Dn!==void 0&&Dn)==`function`?WS:Object,typeof(GS=jl!==void 0&&jl)==`function`?GS:Object])],ZS);function QS(e){if(!(0,m.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 $S=t.__toESM(n.require_decorateMetadata()),eC=t.__toESM(nn()),tC=t.__toESM(n.require_decorate()),nC,rC,iC,aC,oC,sC,cC,lC,uC,dC,fC,pC,mC,hC,gC;let _C=class{constructor(e,t,n,r,i,a,o,s,c,l,u,d,f,p){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.regressionE2eCatalogManager=d,this.pluginAgentRunner=f,this.huntFirstImpactManager=p}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 runHuntFirstImpact(e){return this.huntFirstImpactManager.run(e)}async runRegressionCatalog(){return this.regressionCatalogManager.run()}async runRegressionE2eCatalog(){return this.regressionE2eCatalogManager.run()}async runPluginAgent(e){let t=this.globalConfigService.getRootPath();return this.pluginAgentRunner.run({...e,workingDirectory:t})}};(0,tC.default)([n.WithLoggerContext({category:V.INITIALIZATION}),(0,$S.default)(`design:type`,Function),(0,$S.default)(`design:paramtypes`,[String]),(0,$S.default)(`design:returntype`,Promise)],_C.prototype,`init`,null),(0,tC.default)([n.WithLoggerContext({category:V.GET_TESTABLES}),(0,$S.default)(`design:type`,Function),(0,$S.default)(`design:paramtypes`,[String]),(0,$S.default)(`design:returntype`,Promise)],_C.prototype,`getTestables`,null),(0,tC.default)([n.WithLoggerContext({category:V.GET_TESTABLES}),(0,$S.default)(`design:type`,Function),(0,$S.default)(`design:paramtypes`,[String]),(0,$S.default)(`design:returntype`,Promise)],_C.prototype,`getAllMethodsCount`,null),(0,tC.default)([n.WithLoggerContext({category:V.GET_TESTABLES}),(0,$S.default)(`design:type`,Function),(0,$S.default)(`design:paramtypes`,[Object]),(0,$S.default)(`design:returntype`,Promise)],_C.prototype,`resolveEarlyTestFile`,null),(0,tC.default)([n.WithLoggerContext({category:V.GET_TESTABLES}),(0,$S.default)(`design:type`,Function),(0,$S.default)(`design:paramtypes`,[Array]),(0,$S.default)(`design:returntype`,Promise)],_C.prototype,`getTestableFileMap`,null),(0,tC.default)([n.WithLoggerContext({category:V.GENERATE_COVERAGE}),(0,$S.default)(`design:type`,Function),(0,$S.default)(`design:paramtypes`,[Array]),(0,$S.default)(`design:returntype`,Promise)],_C.prototype,`generateCoverage`,null),(0,tC.default)([n.WithLoggerContext({category:V.SET_COVERAGE}),(0,$S.default)(`design:type`,Function),(0,$S.default)(`design:paramtypes`,[Object]),(0,$S.default)(`design:returntype`,Promise)],_C.prototype,`setCoverage`,null),(0,tC.default)([n.WithLoggerContext({category:V.GET_COVERAGE}),(0,$S.default)(`design:type`,Function),(0,$S.default)(`design:paramtypes`,[]),(0,$S.default)(`design:returntype`,Promise)],_C.prototype,`getCoverageTree`,null),(0,tC.default)([n.WithLoggerContext({category:V.GET_COVERAGE}),(0,$S.default)(`design:type`,Function),(0,$S.default)(`design:paramtypes`,[Array]),(0,$S.default)(`design:returntype`,Promise)],_C.prototype,`getCoverageForFiles`,null),(0,tC.default)([n.WithLoggerContext({category:V.GENERATE_TESTS}),(0,$S.default)(`design:type`,Function),(0,$S.default)(`design:paramtypes`,[String,Object]),(0,$S.default)(`design:returntype`,Promise)],_C.prototype,`generateTests`,null),(0,tC.default)([n.WithLoggerContext({category:V.GENERATE_TESTS}),(0,$S.default)(`design:type`,Function),(0,$S.default)(`design:paramtypes`,[Array,Object,String,typeof(gC=m.Fn!==void 0&&m.Fn)==`function`?gC:Object]),(0,$S.default)(`design:returntype`,Promise)],_C.prototype,`bulkGenerateTests`,null),(0,tC.default)([n.WithLoggerContext({category:V.GENERATE_TESTS}),(0,$S.default)(`design:type`,Function),(0,$S.default)(`design:paramtypes`,[String,String]),(0,$S.default)(`design:returntype`,Promise)],_C.prototype,`getValidationReport`,null),(0,tC.default)([n.WithLoggerContext({category:V.GET_TESTED_CODE_DATA_SOURCE}),(0,$S.default)(`design:type`,Function),(0,$S.default)(`design:paramtypes`,[String,Object,String]),(0,$S.default)(`design:returntype`,Promise)],_C.prototype,`getTestedCodeDataSource`,null),(0,tC.default)([n.WithLoggerContext({category:V.DYNAMIC_PROMPT}),(0,$S.default)(`design:type`,Function),(0,$S.default)(`design:paramtypes`,[String,Object,String]),(0,$S.default)(`design:returntype`,Promise)],_C.prototype,`runDynamicPrompt`,null),(0,tC.default)([n.WithLoggerContext({category:V.TEST_VALIDATION}),(0,$S.default)(`design:type`,Function),(0,$S.default)(`design:paramtypes`,[String,String]),(0,$S.default)(`design:returntype`,Promise)],_C.prototype,`validateTestsByCode`,null),(0,tC.default)([n.WithLoggerContext({category:V.REGRESSION_IMPACT}),(0,$S.default)(`design:type`,Function),(0,$S.default)(`design:paramtypes`,[Object]),(0,$S.default)(`design:returntype`,Promise)],_C.prototype,`runRegressionImpact`,null),(0,tC.default)([n.WithLoggerContext({category:V.REGRESSION_IMPACT}),(0,$S.default)(`design:type`,Function),(0,$S.default)(`design:paramtypes`,[Object]),(0,$S.default)(`design:returntype`,Promise)],_C.prototype,`runHuntFirstImpact`,null),(0,tC.default)([n.WithLoggerContext({category:V.REGRESSION_CATALOG}),(0,$S.default)(`design:type`,Function),(0,$S.default)(`design:paramtypes`,[]),(0,$S.default)(`design:returntype`,Promise)],_C.prototype,`runRegressionCatalog`,null),(0,tC.default)([n.WithLoggerContext({category:V.REGRESSION_CATALOG}),(0,$S.default)(`design:type`,Function),(0,$S.default)(`design:paramtypes`,[]),(0,$S.default)(`design:returntype`,Promise)],_C.prototype,`runRegressionE2eCatalog`,null),(0,tC.default)([n.WithLoggerContext({category:V.GENERATE_TESTS}),(0,$S.default)(`design:type`,Function),(0,$S.default)(`design:paramtypes`,[Object]),(0,$S.default)(`design:returntype`,Promise)],_C.prototype,`runPluginAgent`,null),_C=(0,tC.default)([(0,h.injectable)(),(0,eC.default)(0,(0,h.inject)(Mm)),(0,eC.default)(1,(0,h.inject)(It)),(0,eC.default)(2,(0,h.inject)(Sm)),(0,eC.default)(3,(0,h.inject)(Yo)),(0,eC.default)(4,(0,h.inject)(n.GlobalConfigService)),(0,eC.default)(5,(0,h.inject)(jl)),(0,eC.default)(6,(0,h.inject)(Wp)),(0,eC.default)(7,(0,h.inject)(Yl)),(0,eC.default)(8,(0,h.inject)(ml)),(0,eC.default)(9,(0,h.inject)(kS)),(0,eC.default)(10,(0,h.inject)(Oh)),(0,eC.default)(11,(0,h.inject)($g)),(0,eC.default)(12,(0,h.inject)(ZS)),(0,eC.default)(13,(0,h.inject)(FS)),(0,$S.default)(`design:paramtypes`,[typeof(nC=Mm!==void 0&&Mm)==`function`?nC:Object,typeof(rC=It!==void 0&&It)==`function`?rC:Object,typeof(iC=Sm!==void 0&&Sm)==`function`?iC:Object,typeof(aC=Yo!==void 0&&Yo)==`function`?aC:Object,typeof(oC=n.GlobalConfigService!==void 0&&n.GlobalConfigService)==`function`?oC:Object,typeof(sC=jl!==void 0&&jl)==`function`?sC:Object,typeof(cC=Wp!==void 0&&Wp)==`function`?cC:Object,typeof(lC=Yl!==void 0&&Yl)==`function`?lC:Object,typeof(uC=ml!==void 0&&ml)==`function`?uC:Object,typeof(dC=kS!==void 0&&kS)==`function`?dC:Object,typeof(fC=Oh!==void 0&&Oh)==`function`?fC:Object,typeof(pC=$g!==void 0&&$g)==`function`?pC:Object,typeof(mC=ZS!==void 0&&ZS)==`function`?mC:Object,typeof(hC=FS!==void 0&&FS)==`function`?hC:Object])],_C);let vC=!1;e.AST=dt,e.AccessModifierType=le,e.AstModuleInfo=lt,e.CONCURRENCY=n.CONCURRENCY,e.COVERAGE_THRESHOLD=n.COVERAGE_THRESHOLD,e.CalculateCoverageOption=n.CalculateCoverageOption,e.DEFAULT_TYPE_KIND=de,e.ExportType=ce,e.GenerateTestsOutputType=n.GenerateTestsOutputType,e.GeneratedTestStructure=n.GeneratedTestStructure,e.LibraryName=ue,e.RequestSource=n.RequestSource,Object.defineProperty(e,`TSAgent`,{enumerable:!0,get:function(){return _C}}),e.TestFileName=n.TestFileName,e.TestFramework=n.TestFramework,e.TestStructureVariant=n.TestStructureVariant,e.TestSuffix=n.TestSuffix,e.WithTsMorphManager=ke,e.createTSAgent=(e={})=>((vC?n.inversify_default.rebindSync(n.GlobalConfigService):n.inversify_default.bind(n.GlobalConfigService)).toDynamicValue(()=>new n.GlobalConfigService(e)).inSingletonScope(),vC=!0,n.inversify_default.get(_C)),e.findLintConfigPath=B,e.getUnitTests=He,e.tsMorphManager=Oe}))();const PU={TSAgent:Symbol.for(`TSAgent`),CliOptions:Symbol.for(`CliOptions`),SCMHostService:Symbol.for(`SCMHostService`)};var FU=u(vR());let IU=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.HUNT_FIRST_IMPACT=`generate-hunt-first-impact`,e.PROCESS_JOB=`process-job`,e}({});const LU=Object.freeze({status:`aborted`});function RU(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 zU=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},BU=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};const VU={};function HU(e){return e&&Object.assign(VU,e),VU}function UU(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 WU(e,t){return typeof t==`bigint`?t.toString():t}function GU(e){return{get value(){{let t=e();return Object.defineProperty(this,`value`,{value:t}),t}throw Error(`cached value already set`)}}}function KU(e){return e==null}function qU(e){let t=e.startsWith(`^`)?1:0,n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function JU(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 YU=Symbol(`evaluating`);function XU(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==YU)return r===void 0&&(r=YU,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function ZU(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function QU(...e){let t={};for(let n of e){let e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function $U(e){return JSON.stringify(e)}const eW=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function tW(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const nW=GU(()=>{if(typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function rW(e){if(tW(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(tW(n)===!1||Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)===!1)}function iW(e){return rW(e)?{...e}:Array.isArray(e)?[...e]:e}const aW=new Set([`string`,`number`,`symbol`]);function oW(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function sW(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function cW(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 lW(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}const uW={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function dW(e,t){let n=e._zod.def;return sW(e,QU(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 ZU(this,`shape`,e),e},checks:[]}))}function fW(e,t){let n=e._zod.def;return sW(e,QU(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 ZU(this,`shape`,r),r},checks:[]}))}function pW(e,t){if(!rW(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 sW(e,QU(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return ZU(this,`shape`,n),n},checks:[]}))}function mW(e,t){if(!rW(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return sW(e,{...e._zod.def,get shape(){let n={...e._zod.def.shape,...t};return ZU(this,`shape`,n),n},checks:e._zod.def.checks})}function hW(e,t){return sW(e,QU(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return ZU(this,`shape`,n),n},get catchall(){return t._zod.def.catchall},checks:[]}))}function gW(e,t,n){return sW(t,QU(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 ZU(this,`shape`,i),i},checks:[]}))}function _W(e,t,n){return sW(t,QU(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 ZU(this,`shape`,i),i},checks:[]}))}function vW(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 yW(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function bW(e){return typeof e==`string`?e:e?.message}function xW(e,t,n){let r={...e,path:e.path??[]};return e.message||(r.message=bW(e.inst?._zod.def?.error?.(e))??bW(t?.error?.(e))??bW(n.customError?.(e))??bW(n.localeError?.(e))??`Invalid input`),delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function SW(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function CW(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}const wW=(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,WU,2),Object.defineProperty(e,`toString`,{value:()=>e.message,enumerable:!1})},TW=RU(`$ZodError`,wW),EW=RU(`$ZodError`,wW,{Parent:Error});function Fee(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 DW(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 OW=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 zU;if(o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>xW(e,a,HU())));throw eW(t,i?.callee),t}return o.value},kW=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=>xW(e,a,HU())));throw eW(t,i?.callee),t}return o.value},AW=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 zU;return a.issues.length?{success:!1,error:new(e??TW)(a.issues.map(e=>xW(e,i,HU())))}:{success:!0,data:a.value}},jW=AW(EW),MW=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=>xW(e,i,HU())))}:{success:!0,data:a.value}},NW=MW(EW),PW=e=>(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return OW(e)(t,n,i)},FW=e=>(t,n,r)=>OW(e)(t,n,r),Iee=e=>async(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return kW(e)(t,n,i)},IW=e=>async(t,n,r)=>kW(e)(t,n,r),LW=e=>(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return AW(e)(t,n,i)},Lee=e=>(t,n,r)=>AW(e)(t,n,r),RW=e=>async(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return MW(e)(t,n,i)},zW=e=>async(t,n,r)=>MW(e)(t,n,r),BW=/^[cC][^\s-]{8,}$/,VW=/^[0-9a-z]+$/,HW=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,UW=/^[0-9a-vA-V]{20}$/,WW=/^[A-Za-z0-9]{27}$/,GW=/^[a-zA-Z0-9_-]{21}$/,KW=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,qW=/^([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})$/,JW=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)$/,YW=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function XW(){return RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)}const ZW=/^(?:(?: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])$/,QW=/^(([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}|:))$/,$W=/^((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])$/,eG=/^(([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])$/,tG=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,nG=/^[A-Za-z0-9_-]*$/,rG=/^(?=.{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])?)*\.?$/,iG=/^\+(?:[0-9]){6,14}[0-9]$/,aG=`(?:(?:\\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])))`,oG=RegExp(`^${aG}$`);function sG(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 cG(e){return RegExp(`^${sG(e)}$`)}function lG(e){let t=sG({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(`^${aG}T(?:${r})$`)}const uG=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},Ree=/^-?\d+$/,dG=/^-?\d+(?:\.\d+)?/,fG=/^(?:true|false)$/i,pG=/^[^A-Z]*$/,mG=/^[^a-z]*$/,hG=RU(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),gG={number:`number`,bigint:`bigint`,object:`date`},_G=RU(`$ZodCheckLessThan`,(e,t)=>{hG.init(e,t);let n=gG[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})}}),vG=RU(`$ZodCheckGreaterThan`,(e,t)=>{hG.init(e,t);let n=gG[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})}}),yG=RU(`$ZodCheckMultipleOf`,(e,t)=>{hG.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):JU(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})}}),bG=RU(`$ZodCheckNumberFormat`,(e,t)=>{hG.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=uW[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=Ree)}),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})}}),xG=RU(`$ZodCheckMaxLength`,(e,t)=>{var n;hG.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!KU(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=SW(r);n.issues.push({origin:i,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),zee=RU(`$ZodCheckMinLength`,(e,t)=>{var n;hG.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!KU(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=SW(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),SG=RU(`$ZodCheckLengthEquals`,(e,t)=>{var n;hG.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!KU(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=SW(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})}}),CG=RU(`$ZodCheckStringFormat`,(e,t)=>{var n,r;hG.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=()=>{})}),wG=RU(`$ZodCheckRegex`,(e,t)=>{CG.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})}}),Bee=RU(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=pG,CG.init(e,t)}),Vee=RU(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=mG,CG.init(e,t)}),TG=RU(`$ZodCheckIncludes`,(e,t)=>{hG.init(e,t);let n=oW(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})}}),EG=RU(`$ZodCheckStartsWith`,(e,t)=>{hG.init(e,t);let n=RegExp(`^${oW(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})}}),DG=RU(`$ZodCheckEndsWith`,(e,t)=>{hG.init(e,t);let n=RegExp(`.*${oW(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})}}),Hee=RU(`$ZodCheckOverwrite`,(e,t)=>{hG.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});var Uee=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(`
|
|
34661
34661
|
`).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(`
|
|
34662
34662
|
`))}};const OG={major:4,minor:1,patch:11},kG=RU(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=OG;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=vW(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 zU;if(i||o instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await o,e.issues.length!==t&&(r||=vW(e,t))});else{if(e.issues.length===t)continue;r||=vW(e,t)}}return i?i.then(()=>e):e},n=(n,i,a)=>{if(vW(n))return n.aborted=!0,n;let o=t(i,r,a);if(o instanceof Promise){if(a.async===!1)throw new zU;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 zU;return o.then(e=>t(e,r,a))}return t(o,r,a)}}e[`~standard`]={validate:t=>{try{let n=jW(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch{return NW(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:`zod`,version:1}}),AG=RU(`$ZodString`,(e,t)=>{kG.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??uG(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}}),jG=RU(`$ZodStringFormat`,(e,t)=>{CG.init(e,t),AG.init(e,t)}),MG=RU(`$ZodGUID`,(e,t)=>{t.pattern??=qW,jG.init(e,t)}),NG=RU(`$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??=JW(e)}else t.pattern??=JW();jG.init(e,t)}),PG=RU(`$ZodEmail`,(e,t)=>{t.pattern??=YW,jG.init(e,t)}),FG=RU(`$ZodURL`,(e,t)=>{jG.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:rG.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})}}}),IG=RU(`$ZodEmoji`,(e,t)=>{t.pattern??=XW(),jG.init(e,t)}),LG=RU(`$ZodNanoID`,(e,t)=>{t.pattern??=GW,jG.init(e,t)}),RG=RU(`$ZodCUID`,(e,t)=>{t.pattern??=BW,jG.init(e,t)}),zG=RU(`$ZodCUID2`,(e,t)=>{t.pattern??=VW,jG.init(e,t)}),Wee=RU(`$ZodULID`,(e,t)=>{t.pattern??=HW,jG.init(e,t)}),BG=RU(`$ZodXID`,(e,t)=>{t.pattern??=UW,jG.init(e,t)}),VG=RU(`$ZodKSUID`,(e,t)=>{t.pattern??=WW,jG.init(e,t)}),HG=RU(`$ZodISODateTime`,(e,t)=>{t.pattern??=lG(t),jG.init(e,t)}),UG=RU(`$ZodISODate`,(e,t)=>{t.pattern??=oG,jG.init(e,t)}),WG=RU(`$ZodISOTime`,(e,t)=>{t.pattern??=cG(t),jG.init(e,t)}),GG=RU(`$ZodISODuration`,(e,t)=>{t.pattern??=KW,jG.init(e,t)}),KG=RU(`$ZodIPv4`,(e,t)=>{t.pattern??=ZW,jG.init(e,t),e._zod.onattach.push(e=>{let t=e._zod.bag;t.format=`ipv4`})}),qG=RU(`$ZodIPv6`,(e,t)=>{t.pattern??=QW,jG.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})}}}),JG=RU(`$ZodCIDRv4`,(e,t)=>{t.pattern??=$W,jG.init(e,t)}),YG=RU(`$ZodCIDRv6`,(e,t)=>{t.pattern??=eG,jG.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 XG(e){if(e===``)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const ZG=RU(`$ZodBase64`,(e,t)=>{t.pattern??=tG,jG.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.contentEncoding=`base64`}),e._zod.check=n=>{XG(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}});function QG(e){if(!nG.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return XG(t.padEnd(Math.ceil(t.length/4)*4,`=`))}const $G=RU(`$ZodBase64URL`,(e,t)=>{t.pattern??=nG,jG.init(e,t),e._zod.onattach.push(e=>{e._zod.bag.contentEncoding=`base64url`}),e._zod.check=n=>{QG(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),eK=RU(`$ZodE164`,(e,t)=>{t.pattern??=iG,jG.init(e,t)});function tK(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 nK=RU(`$ZodJWT`,(e,t)=>{jG.init(e,t),e._zod.check=n=>{tK(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),rK=RU(`$ZodNumber`,(e,t)=>{kG.init(e,t),e._zod.pattern=e._zod.bag.pattern??dG,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}}),iK=RU(`$ZodNumber`,(e,t)=>{bG.init(e,t),rK.init(e,t)}),aK=RU(`$ZodBoolean`,(e,t)=>{kG.init(e,t),e._zod.pattern=fG,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),oK=RU(`$ZodUnknown`,(e,t)=>{kG.init(e,t),e._zod.parse=e=>e}),sK=RU(`$ZodNever`,(e,t)=>{kG.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function cK(e,t,n){e.issues.length&&t.issues.push(...yW(n,e.issues)),t.value[n]=e.value}const lK=RU(`$ZodArray`,(e,t)=>{kG.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=>cK(t,n,e))):cK(s,n,e)}return a.length?Promise.all(a).then(()=>n):n}});function uK(e,t,n,r){e.issues.length&&t.issues.push(...yW(n,e.issues)),e.value===void 0?n in r&&(t.value[n]=void 0):t.value[n]=e.value}function dK(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=lW(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function fK(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=>uK(e,n,i,t))):uK(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 pK=RU(`$ZodObject`,(e,t)=>{if(kG.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=GU(()=>dK(t));XU(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=tW,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=>uK(n,t,e,s))):uK(n,t,e,s)}return i?fK(c,s,t,o,n.value,e):c.length?Promise.all(c).then(()=>t):t}}),mK=RU(`$ZodObjectJIT`,(e,t)=>{pK.init(e,t);let n=e._zod.parse,r=GU(()=>dK(t)),i=e=>{let t=new Uee([`shape`,`payload`,`ctx`]),n=r.value,i=e=>{let t=$U(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=$U(e);t.write(`const ${n} = ${i(e)};`),t.write(`
|
|
34663
34663
|
if (${n}.issues.length) {
|