@twinklerg/coden 0.1.1 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +32 -14
- package/dist/index.js +84 -82
- package/dist/plugin/index.d.ts +25 -0
- package/dist/plugin/index.js +1 -0
- package/package.json +11 -3
package/dist/index.js
CHANGED
|
@@ -1,105 +1,105 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// @bun
|
|
3
|
-
import{createRequire as
|
|
4
|
-
`)}displayWidth($){return
|
|
3
|
+
import{createRequire as gz}from"node:module";var Cz=Object.create;var{getPrototypeOf:jz,defineProperty:_W,getOwnPropertyNames:Iz}=Object;var yz=Object.prototype.hasOwnProperty;function bz($){return this[$]}var xz,_z,R4=($,w,Z)=>{var W=$!=null&&typeof $==="object";if(W){var X=w?xz??=new WeakMap:_z??=new WeakMap,Y=X.get($);if(Y)return Y}Z=$!=null?Cz(jz($)):{};let G=w||!$||!$.__esModule?_W(Z,"default",{value:$,enumerable:!0}):Z;for(let J of Iz($))if(!yz.call(G,J))_W(G,J,{get:bz.bind($,J),enumerable:!0});if(W)X.set($,G);return G};var L=($,w)=>()=>(w||$((w={exports:{}}).exports,w),w.exports);var Dw=gz(import.meta.url);var fw=L((vz)=>{class g6 extends Error{constructor($,w,Z){super(Z);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=w,this.exitCode=$,this.nestedError=void 0}}class gW extends g6{constructor($){super(1,"commander.invalidArgument",$);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}vz.CommanderError=g6;vz.InvalidArgumentError=gW});var C4=L((lz)=>{var{InvalidArgumentError:iz}=fw();class vW{constructor($,w){switch(this.description=w||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,$[0]){case"<":this.required=!0,this._name=$.slice(1,-1);break;case"[":this.required=!1,this._name=$.slice(1,-1);break;default:this.required=!0,this._name=$;break}if(this._name.endsWith("..."))this.variadic=!0,this._name=this._name.slice(0,-3)}name(){return this._name}_collectValue($,w){if(w===this.defaultValue||!Array.isArray(w))return[$];return w.push($),w}default($,w){return this.defaultValue=$,this.defaultValueDescription=w,this}argParser($){return this.parseArg=$,this}choices($){return this.argChoices=$.slice(),this.parseArg=(w,Z)=>{if(!this.argChoices.includes(w))throw new iz(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(w,Z);return w},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function mz($){let w=$.name()+($.variadic===!0?"...":"");return $.required?"<"+w+">":"["+w+"]"}lz.Argument=vW;lz.humanReadableArgName=mz});var v6=L((nz)=>{var{humanReadableArgName:pz}=C4();class uW{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext($){this.helpWidth=this.helpWidth??$.helpWidth??80}visibleCommands($){let w=$.commands.filter((W)=>!W._hidden),Z=$._getHelpCommand();if(Z&&!Z._hidden)w.push(Z);if(this.sortSubcommands)w.sort((W,X)=>{return W.name().localeCompare(X.name())});return w}compareOptions($,w){let Z=(W)=>{return W.short?W.short.replace(/^-/,""):W.long.replace(/^--/,"")};return Z($).localeCompare(Z(w))}visibleOptions($){let w=$.options.filter((W)=>!W.hidden),Z=$._getHelpOption();if(Z&&!Z.hidden){let W=Z.short&&$._findOption(Z.short),X=Z.long&&$._findOption(Z.long);if(!W&&!X)w.push(Z);else if(Z.long&&!X)w.push($.createOption(Z.long,Z.description));else if(Z.short&&!W)w.push($.createOption(Z.short,Z.description))}if(this.sortOptions)w.sort(this.compareOptions);return w}visibleGlobalOptions($){if(!this.showGlobalOptions)return[];let w=[];for(let Z=$.parent;Z;Z=Z.parent){let W=Z.options.filter((X)=>!X.hidden);w.push(...W)}if(this.sortOptions)w.sort(this.compareOptions);return w}visibleArguments($){if($._argsDescription)$.registeredArguments.forEach((w)=>{w.description=w.description||$._argsDescription[w.name()]||""});if($.registeredArguments.find((w)=>w.description))return $.registeredArguments;return[]}subcommandTerm($){let w=$.registeredArguments.map((Z)=>pz(Z)).join(" ");return $._name+($._aliases[0]?"|"+$._aliases[0]:"")+($.options.length?" [options]":"")+(w?" "+w:"")}optionTerm($){return $.flags}argumentTerm($){return $.name()}longestSubcommandTermLength($,w){return w.visibleCommands($).reduce((Z,W)=>{return Math.max(Z,this.displayWidth(w.styleSubcommandTerm(w.subcommandTerm(W))))},0)}longestOptionTermLength($,w){return w.visibleOptions($).reduce((Z,W)=>{return Math.max(Z,this.displayWidth(w.styleOptionTerm(w.optionTerm(W))))},0)}longestGlobalOptionTermLength($,w){return w.visibleGlobalOptions($).reduce((Z,W)=>{return Math.max(Z,this.displayWidth(w.styleOptionTerm(w.optionTerm(W))))},0)}longestArgumentTermLength($,w){return w.visibleArguments($).reduce((Z,W)=>{return Math.max(Z,this.displayWidth(w.styleArgumentTerm(w.argumentTerm(W))))},0)}commandUsage($){let w=$._name;if($._aliases[0])w=w+"|"+$._aliases[0];let Z="";for(let W=$.parent;W;W=W.parent)Z=W.name()+" "+Z;return Z+w+" "+$.usage()}commandDescription($){return $.description()}subcommandDescription($){return $.summary()||$.description()}optionDescription($){let w=[];if($.argChoices)w.push(`choices: ${$.argChoices.map((Z)=>JSON.stringify(Z)).join(", ")}`);if($.defaultValue!==void 0){if($.required||$.optional||$.isBoolean()&&typeof $.defaultValue==="boolean")w.push(`default: ${$.defaultValueDescription||JSON.stringify($.defaultValue)}`)}if($.presetArg!==void 0&&$.optional)w.push(`preset: ${JSON.stringify($.presetArg)}`);if($.envVar!==void 0)w.push(`env: ${$.envVar}`);if(w.length>0){let Z=`(${w.join(", ")})`;if($.description)return`${$.description} ${Z}`;return Z}return $.description}argumentDescription($){let w=[];if($.argChoices)w.push(`choices: ${$.argChoices.map((Z)=>JSON.stringify(Z)).join(", ")}`);if($.defaultValue!==void 0)w.push(`default: ${$.defaultValueDescription||JSON.stringify($.defaultValue)}`);if(w.length>0){let Z=`(${w.join(", ")})`;if($.description)return`${$.description} ${Z}`;return Z}return $.description}formatItemList($,w,Z){if(w.length===0)return[];return[Z.styleTitle($),...w,""]}groupItems($,w,Z){let W=new Map;return $.forEach((X)=>{let Y=Z(X);if(!W.has(Y))W.set(Y,[])}),w.forEach((X)=>{let Y=Z(X);if(!W.has(Y))W.set(Y,[]);W.get(Y).push(X)}),W}formatHelp($,w){let Z=w.padWidth($,w),W=w.helpWidth??80;function X(M,T){return w.formatItem(M,Z,T,w)}let Y=[`${w.styleTitle("Usage:")} ${w.styleUsage(w.commandUsage($))}`,""],G=w.commandDescription($);if(G.length>0)Y=Y.concat([w.boxWrap(w.styleCommandDescription(G),W),""]);let J=w.visibleArguments($).map((M)=>{return X(w.styleArgumentTerm(w.argumentTerm(M)),w.styleArgumentDescription(w.argumentDescription(M)))});if(Y=Y.concat(this.formatItemList("Arguments:",J,w)),this.groupItems($.options,w.visibleOptions($),(M)=>M.helpGroupHeading??"Options:").forEach((M,T)=>{let N=M.map((K)=>{return X(w.styleOptionTerm(w.optionTerm(K)),w.styleOptionDescription(w.optionDescription(K)))});Y=Y.concat(this.formatItemList(T,N,w))}),w.showGlobalOptions){let M=w.visibleGlobalOptions($).map((T)=>{return X(w.styleOptionTerm(w.optionTerm(T)),w.styleOptionDescription(w.optionDescription(T)))});Y=Y.concat(this.formatItemList("Global Options:",M,w))}return this.groupItems($.commands,w.visibleCommands($),(M)=>M.helpGroup()||"Commands:").forEach((M,T)=>{let N=M.map((K)=>{return X(w.styleSubcommandTerm(w.subcommandTerm(K)),w.styleSubcommandDescription(w.subcommandDescription(K)))});Y=Y.concat(this.formatItemList(T,N,w))}),Y.join(`
|
|
4
|
+
`)}displayWidth($){return hW($).length}styleTitle($){return $}styleUsage($){return $.split(" ").map((w)=>{if(w==="[options]")return this.styleOptionText(w);if(w==="[command]")return this.styleSubcommandText(w);if(w[0]==="["||w[0]==="<")return this.styleArgumentText(w);return this.styleCommandText(w)}).join(" ")}styleCommandDescription($){return this.styleDescriptionText($)}styleOptionDescription($){return this.styleDescriptionText($)}styleSubcommandDescription($){return this.styleDescriptionText($)}styleArgumentDescription($){return this.styleDescriptionText($)}styleDescriptionText($){return $}styleOptionTerm($){return this.styleOptionText($)}styleSubcommandTerm($){return $.split(" ").map((w)=>{if(w==="[options]")return this.styleOptionText(w);if(w[0]==="["||w[0]==="<")return this.styleArgumentText(w);return this.styleSubcommandText(w)}).join(" ")}styleArgumentTerm($){return this.styleArgumentText($)}styleOptionText($){return $}styleArgumentText($){return $}styleSubcommandText($){return $}styleCommandText($){return $}padWidth($,w){return Math.max(w.longestOptionTermLength($,w),w.longestGlobalOptionTermLength($,w),w.longestSubcommandTermLength($,w),w.longestArgumentTermLength($,w))}preformatted($){return/\n[^\S\r\n]/.test($)}formatItem($,w,Z,W){let Y=" ".repeat(2);if(!Z)return Y+$;let G=$.padEnd(w+$.length-W.displayWidth($)),J=2,z=(this.helpWidth??80)-w-J-2,M;if(z<this.minWidthToWrap||W.preformatted(Z))M=Z;else M=W.boxWrap(Z,z).replace(/\n/g,`
|
|
5
5
|
`+" ".repeat(w+J));return Y+G+" ".repeat(J)+M.replace(/\n/g,`
|
|
6
6
|
${Y}`)}boxWrap($,w){if(w<this.minWidthToWrap)return $;let Z=$.split(/\r\n|\n/),W=/[\s]*[^\s]+/g,X=[];return Z.forEach((Y)=>{let G=Y.match(W);if(G===null){X.push("");return}let J=[G.shift()],Q=this.displayWidth(J[0]);G.forEach((z)=>{let M=this.displayWidth(z);if(Q+M<=w){J.push(z),Q+=M;return}X.push(J.join(""));let T=z.trimStart();J=[T],Q=this.displayWidth(T)}),X.push(J.join(""))}),X.join(`
|
|
7
|
-
`)}}function
|
|
7
|
+
`)}}function hW($){let w=/\x1b\[\d*(;\d*)*m/g;return $.replace(w,"")}nz.Help=uW;nz.stripColor=hW});var u6=L((oz)=>{var{InvalidArgumentError:sz}=fw();class mW{constructor($,w){this.flags=$,this.description=w||"",this.required=$.includes("<"),this.optional=$.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test($),this.mandatory=!1;let Z=az($);if(this.short=Z.shortFlag,this.long=Z.longFlag,this.negate=!1,this.long)this.negate=this.long.startsWith("--no-");this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default($,w){return this.defaultValue=$,this.defaultValueDescription=w,this}preset($){return this.presetArg=$,this}conflicts($){return this.conflictsWith=this.conflictsWith.concat($),this}implies($){let w=$;if(typeof $==="string")w={[$]:!0};return this.implied=Object.assign(this.implied||{},w),this}env($){return this.envVar=$,this}argParser($){return this.parseArg=$,this}makeOptionMandatory($=!0){return this.mandatory=!!$,this}hideHelp($=!0){return this.hidden=!!$,this}_collectValue($,w){if(w===this.defaultValue||!Array.isArray(w))return[$];return w.push($),w}choices($){return this.argChoices=$.slice(),this.parseArg=(w,Z)=>{if(!this.argChoices.includes(w))throw new sz(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(w,Z);return w},this}name(){if(this.long)return this.long.replace(/^--/,"");return this.short.replace(/^-/,"")}attributeName(){if(this.negate)return iW(this.name().replace(/^no-/,""));return iW(this.name())}helpGroup($){return this.helpGroupHeading=$,this}is($){return this.short===$||this.long===$}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class lW{constructor($){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,$.forEach((w)=>{if(w.negate)this.negativeOptions.set(w.attributeName(),w);else this.positiveOptions.set(w.attributeName(),w)}),this.negativeOptions.forEach((w,Z)=>{if(this.positiveOptions.has(Z))this.dualOptions.add(Z)})}valueFromOption($,w){let Z=w.attributeName();if(!this.dualOptions.has(Z))return!0;let W=this.negativeOptions.get(Z).presetArg,X=W!==void 0?W:!1;return w.negate===(X===$)}}function iW($){return $.split("-").reduce((w,Z)=>{return w+Z[0].toUpperCase()+Z.slice(1)})}function az($){let w,Z,W=/^-[^-]$/,X=/^--[^-]/,Y=$.split(/[ |,]+/).concat("guard");if(W.test(Y[0]))w=Y.shift();if(X.test(Y[0]))Z=Y.shift();if(!w&&W.test(Y[0]))w=Y.shift();if(!w&&X.test(Y[0]))w=Z,Z=Y.shift();if(Y[0].startsWith("-")){let G=Y[0],J=`option creation failed due to '${G}' in option flags '${$}'`;if(/^-[^-][^-]/.test(G))throw Error(`${J}
|
|
8
8
|
- a short flag is a single dash and a single character
|
|
9
9
|
- either use a single dash and a single character (for a short flag)
|
|
10
10
|
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`);if(W.test(G))throw Error(`${J}
|
|
11
11
|
- too many short flags`);if(X.test(G))throw Error(`${J}
|
|
12
12
|
- too many long flags`);throw Error(`${J}
|
|
13
|
-
- unrecognised flag format`)}if(w===void 0&&Z===void 0)throw Error(`option creation failed due to no flags found in '${$}'.`);return{shortFlag:w,longFlag:Z}}
|
|
13
|
+
- unrecognised flag format`)}if(w===void 0&&Z===void 0)throw Error(`option creation failed due to no flags found in '${$}'.`);return{shortFlag:w,longFlag:Z}}oz.Option=mW;oz.DualOptions=lW});var cW=L((WM)=>{function wM($,w){if(Math.abs($.length-w.length)>3)return Math.max($.length,w.length);let Z=[];for(let W=0;W<=$.length;W++)Z[W]=[W];for(let W=0;W<=w.length;W++)Z[0][W]=W;for(let W=1;W<=w.length;W++)for(let X=1;X<=$.length;X++){let Y=1;if($[X-1]===w[W-1])Y=0;else Y=1;if(Z[X][W]=Math.min(Z[X-1][W]+1,Z[X][W-1]+1,Z[X-1][W-1]+Y),X>1&&W>1&&$[X-1]===w[W-2]&&$[X-2]===w[W-1])Z[X][W]=Math.min(Z[X][W],Z[X-2][W-2]+1)}return Z[$.length][w.length]}function ZM($,w){if(!w||w.length===0)return"";w=Array.from(new Set(w));let Z=$.startsWith("--");if(Z)$=$.slice(2),w=w.map((G)=>G.slice(2));let W=[],X=3,Y=0.4;if(w.forEach((G)=>{if(G.length<=1)return;let J=wM($,G),Q=Math.max($.length,G.length);if((Q-J)/Q>Y){if(J<X)X=J,W=[G];else if(J===X)W.push(G)}}),W.sort((G,J)=>G.localeCompare(J)),Z)W=W.map((G)=>`--${G}`);if(W.length>1)return`
|
|
14
14
|
(Did you mean one of ${W.join(", ")}?)`;if(W.length===1)return`
|
|
15
|
-
(Did you mean ${W[0]}?)`;return""}
|
|
16
|
-
- specify the name in Command constructor or using .name()`);if(w=w||{},w.isDefault)this._defaultCommandName=$._name;if(w.noHelp||w.hidden)$._hidden=!0;return this._registerCommand($),$.parent=this,$._checkForBrokenPassThrough(),this}createArgument($,w){return new
|
|
17
|
-
Expecting one of '${Z.join("', '")}'`);if(this._lifeCycleHooks[$])this._lifeCycleHooks[$].push(w);else this._lifeCycleHooks[$]=[w];return this}exitOverride($){if($)this._exitCallback=$;else this._exitCallback=(w)=>{if(w.code!=="commander.executeSubCommandAsync")throw w};return this}_exit($,w,Z){if(this._exitCallback)this._exitCallback(new i6($,w,Z));p.exit($)}action($){let w=(Z)=>{let W=this.registeredArguments.length,X=Z.slice(0,W);if(this._storeOptionsAsProperties)X[W]=this;else X[W]=this.opts();return X.push(this),$.apply(this,X)};return this._actionHandler=w,this}createOption($,w){return new
|
|
18
|
-
- already used by option '${w.flags}'`)}this._initOptionGroup($),this.options.push($)}_registerCommand($){let w=(W)=>{return[W.name()].concat(W.aliases())},Z=w($).find((W)=>this._findCommand(W));if(Z){let W=w(this._findCommand(Z)).join("|"),X=w($).join("|");throw Error(`cannot add command '${X}' as already have command '${W}'`)}this._initCommandGroup($),this.commands.push($)}addOption($){this._registerOption($);let w=$.name(),Z=$.attributeName();if($.negate){let X=$.long.replace(/^--no-/,"--");if(!this._findOption(X))this.setOptionValueWithSource(Z,$.defaultValue===void 0?!0:$.defaultValue,"default")}else if($.defaultValue!==void 0)this.setOptionValueWithSource(Z,$.defaultValue,"default");let W=(X,Y,G)=>{if(X==null&&$.presetArg!==void 0)X=$.presetArg;let J=this.getOptionValue(Z);if(X!==null&&$.parseArg)X=this._callParseArg($,X,J,Y);else if(X!==null&&$.variadic)X=$._collectValue(X,J);if(X==null)if($.negate)X=!1;else if($.isBoolean()||$.optional)X=!0;else X="";this.setOptionValueWithSource(Z,X,G)};if(this.on("option:"+w,(X)=>{let Y=`error: option '${$.flags}' argument '${X}' is invalid.`;W(X,Y,"cli")}),$.envVar)this.on("optionEnv:"+w,(X)=>{let Y=`error: option '${$.flags}' value '${X}' from env '${$.envVar}' is invalid.`;W(X,Y,"env")});return this}_optionEx($,w,Z,W,X){if(typeof w==="object"&&w instanceof
|
|
15
|
+
(Did you mean ${W[0]}?)`;return""}WM.suggestSimilar=ZM});var tW=L((TM)=>{var YM=Dw("node:events").EventEmitter,h6=Dw("node:child_process"),W$=Dw("node:path"),j4=Dw("node:fs"),p=Dw("node:process"),{Argument:GM,humanReadableArgName:JM}=C4(),{CommanderError:i6}=fw(),{Help:QM,stripColor:zM}=v6(),{Option:dW,DualOptions:MM}=u6(),{suggestSimilar:pW}=cW();class l6 extends YM{constructor($){super();this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=$||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:(w)=>p.stdout.write(w),writeErr:(w)=>p.stderr.write(w),outputError:(w,Z)=>Z(w),getOutHelpWidth:()=>p.stdout.isTTY?p.stdout.columns:void 0,getErrHelpWidth:()=>p.stderr.isTTY?p.stderr.columns:void 0,getOutHasColors:()=>m6()??(p.stdout.isTTY&&p.stdout.hasColors?.()),getErrHasColors:()=>m6()??(p.stderr.isTTY&&p.stderr.hasColors?.()),stripColor:(w)=>zM(w)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings($){return this._outputConfiguration=$._outputConfiguration,this._helpOption=$._helpOption,this._helpCommand=$._helpCommand,this._helpConfiguration=$._helpConfiguration,this._exitCallback=$._exitCallback,this._storeOptionsAsProperties=$._storeOptionsAsProperties,this._combineFlagAndOptionalValue=$._combineFlagAndOptionalValue,this._allowExcessArguments=$._allowExcessArguments,this._enablePositionalOptions=$._enablePositionalOptions,this._showHelpAfterError=$._showHelpAfterError,this._showSuggestionAfterError=$._showSuggestionAfterError,this}_getCommandAndAncestors(){let $=[];for(let w=this;w;w=w.parent)$.push(w);return $}command($,w,Z){let W=w,X=Z;if(typeof W==="object"&&W!==null)X=W,W=null;X=X||{};let[,Y,G]=$.match(/([^ ]+) *(.*)/),J=this.createCommand(Y);if(W)J.description(W),J._executableHandler=!0;if(X.isDefault)this._defaultCommandName=J._name;if(J._hidden=!!(X.noHelp||X.hidden),J._executableFile=X.executableFile||null,G)J.arguments(G);if(this._registerCommand(J),J.parent=this,J.copyInheritedSettings(this),W)return this;return J}createCommand($){return new l6($)}createHelp(){return Object.assign(new QM,this.configureHelp())}configureHelp($){if($===void 0)return this._helpConfiguration;return this._helpConfiguration=$,this}configureOutput($){if($===void 0)return this._outputConfiguration;return this._outputConfiguration={...this._outputConfiguration,...$},this}showHelpAfterError($=!0){if(typeof $!=="string")$=!!$;return this._showHelpAfterError=$,this}showSuggestionAfterError($=!0){return this._showSuggestionAfterError=!!$,this}addCommand($,w){if(!$._name)throw Error(`Command passed to .addCommand() must have a name
|
|
16
|
+
- specify the name in Command constructor or using .name()`);if(w=w||{},w.isDefault)this._defaultCommandName=$._name;if(w.noHelp||w.hidden)$._hidden=!0;return this._registerCommand($),$.parent=this,$._checkForBrokenPassThrough(),this}createArgument($,w){return new GM($,w)}argument($,w,Z,W){let X=this.createArgument($,w);if(typeof Z==="function")X.default(W).argParser(Z);else X.default(Z);return this.addArgument(X),this}arguments($){return $.trim().split(/ +/).forEach((w)=>{this.argument(w)}),this}addArgument($){let w=this.registeredArguments.slice(-1)[0];if(w?.variadic)throw Error(`only the last argument can be variadic '${w.name()}'`);if($.required&&$.defaultValue!==void 0&&$.parseArg===void 0)throw Error(`a default value for a required argument is never used: '${$.name()}'`);return this.registeredArguments.push($),this}helpCommand($,w){if(typeof $==="boolean"){if(this._addImplicitHelpCommand=$,$&&this._defaultCommandGroup)this._initCommandGroup(this._getHelpCommand());return this}let Z=$??"help [command]",[,W,X]=Z.match(/([^ ]+) *(.*)/),Y=w??"display help for command",G=this.createCommand(W);if(G.helpOption(!1),X)G.arguments(X);if(Y)G.description(Y);if(this._addImplicitHelpCommand=!0,this._helpCommand=G,$||w)this._initCommandGroup(G);return this}addHelpCommand($,w){if(typeof $!=="object")return this.helpCommand($,w),this;return this._addImplicitHelpCommand=!0,this._helpCommand=$,this._initCommandGroup($),this}_getHelpCommand(){if(this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))){if(this._helpCommand===void 0)this.helpCommand(void 0,void 0);return this._helpCommand}return null}hook($,w){let Z=["preSubcommand","preAction","postAction"];if(!Z.includes($))throw Error(`Unexpected value for event passed to hook : '${$}'.
|
|
17
|
+
Expecting one of '${Z.join("', '")}'`);if(this._lifeCycleHooks[$])this._lifeCycleHooks[$].push(w);else this._lifeCycleHooks[$]=[w];return this}exitOverride($){if($)this._exitCallback=$;else this._exitCallback=(w)=>{if(w.code!=="commander.executeSubCommandAsync")throw w};return this}_exit($,w,Z){if(this._exitCallback)this._exitCallback(new i6($,w,Z));p.exit($)}action($){let w=(Z)=>{let W=this.registeredArguments.length,X=Z.slice(0,W);if(this._storeOptionsAsProperties)X[W]=this;else X[W]=this.opts();return X.push(this),$.apply(this,X)};return this._actionHandler=w,this}createOption($,w){return new dW($,w)}_callParseArg($,w,Z,W){try{return $.parseArg(w,Z)}catch(X){if(X.code==="commander.invalidArgument"){let Y=`${W} ${X.message}`;this.error(Y,{exitCode:X.exitCode,code:X.code})}throw X}}_registerOption($){let w=$.short&&this._findOption($.short)||$.long&&this._findOption($.long);if(w){let Z=$.long&&this._findOption($.long)?$.long:$.short;throw Error(`Cannot add option '${$.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${Z}'
|
|
18
|
+
- already used by option '${w.flags}'`)}this._initOptionGroup($),this.options.push($)}_registerCommand($){let w=(W)=>{return[W.name()].concat(W.aliases())},Z=w($).find((W)=>this._findCommand(W));if(Z){let W=w(this._findCommand(Z)).join("|"),X=w($).join("|");throw Error(`cannot add command '${X}' as already have command '${W}'`)}this._initCommandGroup($),this.commands.push($)}addOption($){this._registerOption($);let w=$.name(),Z=$.attributeName();if($.negate){let X=$.long.replace(/^--no-/,"--");if(!this._findOption(X))this.setOptionValueWithSource(Z,$.defaultValue===void 0?!0:$.defaultValue,"default")}else if($.defaultValue!==void 0)this.setOptionValueWithSource(Z,$.defaultValue,"default");let W=(X,Y,G)=>{if(X==null&&$.presetArg!==void 0)X=$.presetArg;let J=this.getOptionValue(Z);if(X!==null&&$.parseArg)X=this._callParseArg($,X,J,Y);else if(X!==null&&$.variadic)X=$._collectValue(X,J);if(X==null)if($.negate)X=!1;else if($.isBoolean()||$.optional)X=!0;else X="";this.setOptionValueWithSource(Z,X,G)};if(this.on("option:"+w,(X)=>{let Y=`error: option '${$.flags}' argument '${X}' is invalid.`;W(X,Y,"cli")}),$.envVar)this.on("optionEnv:"+w,(X)=>{let Y=`error: option '${$.flags}' value '${X}' from env '${$.envVar}' is invalid.`;W(X,Y,"env")});return this}_optionEx($,w,Z,W,X){if(typeof w==="object"&&w instanceof dW)throw Error("To add an Option object use addOption() instead of option() or requiredOption()");let Y=this.createOption(w,Z);if(Y.makeOptionMandatory(!!$.mandatory),typeof W==="function")Y.default(X).argParser(W);else if(W instanceof RegExp){let G=W;W=(J,Q)=>{let z=G.exec(J);return z?z[0]:Q},Y.default(X).argParser(W)}else Y.default(W);return this.addOption(Y)}option($,w,Z,W){return this._optionEx({},$,w,Z,W)}requiredOption($,w,Z,W){return this._optionEx({mandatory:!0},$,w,Z,W)}combineFlagAndOptionalValue($=!0){return this._combineFlagAndOptionalValue=!!$,this}allowUnknownOption($=!0){return this._allowUnknownOption=!!$,this}allowExcessArguments($=!0){return this._allowExcessArguments=!!$,this}enablePositionalOptions($=!0){return this._enablePositionalOptions=!!$,this}passThroughOptions($=!0){return this._passThroughOptions=!!$,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties($=!0){if(this.options.length)throw Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!$,this}getOptionValue($){if(this._storeOptionsAsProperties)return this[$];return this._optionValues[$]}setOptionValue($,w){return this.setOptionValueWithSource($,w,void 0)}setOptionValueWithSource($,w,Z){if(this._storeOptionsAsProperties)this[$]=w;else this._optionValues[$]=w;return this._optionValueSources[$]=Z,this}getOptionValueSource($){return this._optionValueSources[$]}getOptionValueSourceWithGlobals($){let w;return this._getCommandAndAncestors().forEach((Z)=>{if(Z.getOptionValueSource($)!==void 0)w=Z.getOptionValueSource($)}),w}_prepareUserArgs($,w){if($!==void 0&&!Array.isArray($))throw Error("first parameter to parse must be array or undefined");if(w=w||{},$===void 0&&w.from===void 0){if(p.versions?.electron)w.from="electron";let W=p.execArgv??[];if(W.includes("-e")||W.includes("--eval")||W.includes("-p")||W.includes("--print"))w.from="eval"}if($===void 0)$=p.argv;this.rawArgs=$.slice();let Z;switch(w.from){case void 0:case"node":this._scriptPath=$[1],Z=$.slice(2);break;case"electron":if(p.defaultApp)this._scriptPath=$[1],Z=$.slice(2);else Z=$.slice(1);break;case"user":Z=$.slice(0);break;case"eval":Z=$.slice(1);break;default:throw Error(`unexpected parse option { from: '${w.from}' }`)}if(!this._name&&this._scriptPath)this.nameFromFilename(this._scriptPath);return this._name=this._name||"program",Z}parse($,w){this._prepareForParse();let Z=this._prepareUserArgs($,w);return this._parseCommand([],Z),this}async parseAsync($,w){this._prepareForParse();let Z=this._prepareUserArgs($,w);return await this._parseCommand([],Z),this}_prepareForParse(){if(this._savedState===null)this.saveStateBeforeParse();else this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw Error(`Can not call parse again when storeOptionsAsProperties is true.
|
|
19
19
|
- either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable($,w,Z){if(j4.existsSync($))return;let W=w?`searched for local subcommand relative to directory '${w}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",X=`'${$}' does not exist
|
|
20
20
|
- if '${Z}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
21
21
|
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
22
|
-
- ${W}`;throw Error(X)}_executeSubCommand($,w){w=w.slice();let Z=!1,W=[".js",".ts",".tsx",".mjs",".cjs"];function X(z,M){let T=
|
|
22
|
+
- ${W}`;throw Error(X)}_executeSubCommand($,w){w=w.slice();let Z=!1,W=[".js",".ts",".tsx",".mjs",".cjs"];function X(z,M){let T=W$.resolve(z,M);if(j4.existsSync(T))return T;if(W.includes(W$.extname(M)))return;let N=W.find((K)=>j4.existsSync(`${T}${K}`));if(N)return`${T}${N}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let Y=$._executableFile||`${this._name}-${$._name}`,G=this._executableDir||"";if(this._scriptPath){let z;try{z=j4.realpathSync(this._scriptPath)}catch{z=this._scriptPath}G=W$.resolve(W$.dirname(z),G)}if(G){let z=X(G,Y);if(!z&&!$._executableFile&&this._scriptPath){let M=W$.basename(this._scriptPath,W$.extname(this._scriptPath));if(M!==this._name)z=X(G,`${M}-${$._name}`)}Y=z||Y}Z=W.includes(W$.extname(Y));let J;if(p.platform!=="win32")if(Z)w.unshift(Y),w=nW(p.execArgv).concat(w),J=h6.spawn(p.argv[0],w,{stdio:"inherit"});else J=h6.spawn(Y,w,{stdio:"inherit"});else this._checkForMissingExecutable(Y,G,$._name),w.unshift(Y),w=nW(p.execArgv).concat(w),J=h6.spawn(p.execPath,w,{stdio:"inherit"});if(!J.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((M)=>{p.on(M,()=>{if(J.killed===!1&&J.exitCode===null)J.kill(M)})});let Q=this._exitCallback;J.on("close",(z)=>{if(z=z??1,!Q)p.exit(z);else Q(new i6(z,"commander.executeSubCommandAsync","(close)"))}),J.on("error",(z)=>{if(z.code==="ENOENT")this._checkForMissingExecutable(Y,G,$._name);else if(z.code==="EACCES")throw Error(`'${Y}' not executable`);if(!Q)p.exit(1);else{let M=new i6(1,"commander.executeSubCommandAsync","(error)");M.nestedError=z,Q(M)}}),this.runningCommand=J}_dispatchSubcommand($,w,Z){let W=this._findCommand($);if(!W)this.help({error:!0});W._prepareForParse();let X;return X=this._chainOrCallSubCommandHook(X,W,"preSubcommand"),X=this._chainOrCall(X,()=>{if(W._executableHandler)this._executeSubCommand(W,w.concat(Z));else return W._parseCommand(w,Z)}),X}_dispatchHelpCommand($){if(!$)this.help();let w=this._findCommand($);if(w&&!w._executableHandler)w.help();return this._dispatchSubcommand($,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){if(this.registeredArguments.forEach(($,w)=>{if($.required&&this.args[w]==null)this.missingArgument($.name())}),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)return;if(this.args.length>this.registeredArguments.length)this._excessArguments(this.args)}_processArguments(){let $=(Z,W,X)=>{let Y=W;if(W!==null&&Z.parseArg){let G=`error: command-argument value '${W}' is invalid for argument '${Z.name()}'.`;Y=this._callParseArg(Z,W,X,G)}return Y};this._checkNumberOfArguments();let w=[];this.registeredArguments.forEach((Z,W)=>{let X=Z.defaultValue;if(Z.variadic){if(W<this.args.length){if(X=this.args.slice(W),Z.parseArg)X=X.reduce((Y,G)=>{return $(Z,G,Y)},Z.defaultValue)}else if(X===void 0)X=[]}else if(W<this.args.length){if(X=this.args[W],Z.parseArg)X=$(Z,X,Z.defaultValue)}w[W]=X}),this.processedArgs=w}_chainOrCall($,w){if($?.then&&typeof $.then==="function")return $.then(()=>w());return w()}_chainOrCallHooks($,w){let Z=$,W=[];if(this._getCommandAndAncestors().reverse().filter((X)=>X._lifeCycleHooks[w]!==void 0).forEach((X)=>{X._lifeCycleHooks[w].forEach((Y)=>{W.push({hookedCommand:X,callback:Y})})}),w==="postAction")W.reverse();return W.forEach((X)=>{Z=this._chainOrCall(Z,()=>{return X.callback(X.hookedCommand,this)})}),Z}_chainOrCallSubCommandHook($,w,Z){let W=$;if(this._lifeCycleHooks[Z]!==void 0)this._lifeCycleHooks[Z].forEach((X)=>{W=this._chainOrCall(W,()=>{return X(this,w)})});return W}_parseCommand($,w){let Z=this.parseOptions(w);if(this._parseOptionsEnv(),this._parseOptionsImplied(),$=$.concat(Z.operands),w=Z.unknown,this.args=$.concat(w),$&&this._findCommand($[0]))return this._dispatchSubcommand($[0],$.slice(1),w);if(this._getHelpCommand()&&$[0]===this._getHelpCommand().name())return this._dispatchHelpCommand($[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(w),this._dispatchSubcommand(this._defaultCommandName,$,w);if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName)this.help({error:!0});this._outputHelpIfRequested(Z.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let W=()=>{if(Z.unknown.length>0)this.unknownOption(Z.unknown[0])},X=`command:${this.name()}`;if(this._actionHandler){W(),this._processArguments();let Y;if(Y=this._chainOrCallHooks(Y,"preAction"),Y=this._chainOrCall(Y,()=>this._actionHandler(this.processedArgs)),this.parent)Y=this._chainOrCall(Y,()=>{this.parent.emit(X,$,w)});return Y=this._chainOrCallHooks(Y,"postAction"),Y}if(this.parent?.listenerCount(X))W(),this._processArguments(),this.parent.emit(X,$,w);else if($.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",$,w);if(this.listenerCount("command:*"))this.emit("command:*",$,w);else if(this.commands.length)this.unknownCommand();else W(),this._processArguments()}else if(this.commands.length)W(),this.help({error:!0});else W(),this._processArguments()}_findCommand($){if(!$)return;return this.commands.find((w)=>w._name===$||w._aliases.includes($))}_findOption($){return this.options.find((w)=>w.is($))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(($)=>{$.options.forEach((w)=>{if(w.mandatory&&$.getOptionValue(w.attributeName())===void 0)$.missingMandatoryOptionValue(w)})})}_checkForConflictingLocalOptions(){let $=this.options.filter((Z)=>{let W=Z.attributeName();if(this.getOptionValue(W)===void 0)return!1;return this.getOptionValueSource(W)!=="default"});$.filter((Z)=>Z.conflictsWith.length>0).forEach((Z)=>{let W=$.find((X)=>Z.conflictsWith.includes(X.attributeName()));if(W)this._conflictingOption(Z,W)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(($)=>{$._checkForConflictingLocalOptions()})}parseOptions($){let w=[],Z=[],W=w;function X(z){return z.length>1&&z[0]==="-"}let Y=(z)=>{if(!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(z))return!1;return!this._getCommandAndAncestors().some((M)=>M.options.map((T)=>T.short).some((T)=>/^-\d$/.test(T)))},G=null,J=null,Q=0;while(Q<$.length||J){let z=J??$[Q++];if(J=null,z==="--"){if(W===Z)W.push(z);W.push(...$.slice(Q));break}if(G&&(!X(z)||Y(z))){this.emit(`option:${G.name()}`,z);continue}if(G=null,X(z)){let M=this._findOption(z);if(M){if(M.required){let T=$[Q++];if(T===void 0)this.optionMissingArgument(M);this.emit(`option:${M.name()}`,T)}else if(M.optional){let T=null;if(Q<$.length&&(!X($[Q])||Y($[Q])))T=$[Q++];this.emit(`option:${M.name()}`,T)}else this.emit(`option:${M.name()}`);G=M.variadic?M:null;continue}}if(z.length>2&&z[0]==="-"&&z[1]!=="-"){let M=this._findOption(`-${z[1]}`);if(M){if(M.required||M.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${M.name()}`,z.slice(2));else this.emit(`option:${M.name()}`),J=`-${z.slice(2)}`;continue}}if(/^--[^=]+=/.test(z)){let M=z.indexOf("="),T=this._findOption(z.slice(0,M));if(T&&(T.required||T.optional)){this.emit(`option:${T.name()}`,z.slice(M+1));continue}}if(W===w&&X(z)&&!(this.commands.length===0&&Y(z)))W=Z;if((this._enablePositionalOptions||this._passThroughOptions)&&w.length===0&&Z.length===0){if(this._findCommand(z)){w.push(z),Z.push(...$.slice(Q));break}else if(this._getHelpCommand()&&z===this._getHelpCommand().name()){w.push(z,...$.slice(Q));break}else if(this._defaultCommandName){Z.push(z,...$.slice(Q));break}}if(this._passThroughOptions){W.push(z,...$.slice(Q));break}W.push(z)}return{operands:w,unknown:Z}}opts(){if(this._storeOptionsAsProperties){let $={},w=this.options.length;for(let Z=0;Z<w;Z++){let W=this.options[Z].attributeName();$[W]=W===this._versionOptionName?this._version:this[W]}return $}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce(($,w)=>Object.assign($,w.opts()),{})}error($,w){if(this._outputConfiguration.outputError(`${$}
|
|
23
23
|
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==="string")this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
24
24
|
`);else if(this._showHelpAfterError)this._outputConfiguration.writeErr(`
|
|
25
|
-
`),this.outputHelp({error:!0});let Z=w||{},W=Z.exitCode||1,X=Z.code||"commander.error";this._exit(W,X,$)}_parseOptionsEnv(){this.options.forEach(($)=>{if($.envVar&&$.envVar in p.env){let w=$.attributeName();if(this.getOptionValue(w)===void 0||["default","config","env"].includes(this.getOptionValueSource(w)))if($.required||$.optional)this.emit(`optionEnv:${$.name()}`,p.env[$.envVar]);else this.emit(`optionEnv:${$.name()}`)}})}_parseOptionsImplied(){let $=new
|
|
26
|
-
`),this._exit(0,"commander.version",$)}),this}description($,w){if($===void 0&&w===void 0)return this._description;if(this._description=$,w)this._argsDescription=w;return this}summary($){if($===void 0)return this._summary;return this._summary=$,this}alias($){if($===void 0)return this._aliases[0];let w=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)w=this.commands[this.commands.length-1];if($===w._name)throw Error("Command alias can't be the same as its name");let Z=this.parent?._findCommand($);if(Z){let W=[Z.name()].concat(Z.aliases()).join("|");throw Error(`cannot add alias '${$}' to command '${this.name()}' as already have command '${W}'`)}return w._aliases.push($),this}aliases($){if($===void 0)return this._aliases;return $.forEach((w)=>this.alias(w)),this}usage($){if($===void 0){if(this._usage)return this._usage;let w=this.registeredArguments.map((Z)=>{return
|
|
25
|
+
`),this.outputHelp({error:!0});let Z=w||{},W=Z.exitCode||1,X=Z.code||"commander.error";this._exit(W,X,$)}_parseOptionsEnv(){this.options.forEach(($)=>{if($.envVar&&$.envVar in p.env){let w=$.attributeName();if(this.getOptionValue(w)===void 0||["default","config","env"].includes(this.getOptionValueSource(w)))if($.required||$.optional)this.emit(`optionEnv:${$.name()}`,p.env[$.envVar]);else this.emit(`optionEnv:${$.name()}`)}})}_parseOptionsImplied(){let $=new MM(this.options),w=(Z)=>{return this.getOptionValue(Z)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(Z))};this.options.filter((Z)=>Z.implied!==void 0&&w(Z.attributeName())&&$.valueFromOption(this.getOptionValue(Z.attributeName()),Z)).forEach((Z)=>{Object.keys(Z.implied).filter((W)=>!w(W)).forEach((W)=>{this.setOptionValueWithSource(W,Z.implied[W],"implied")})})}missingArgument($){let w=`error: missing required argument '${$}'`;this.error(w,{code:"commander.missingArgument"})}optionMissingArgument($){let w=`error: option '${$.flags}' argument missing`;this.error(w,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue($){let w=`error: required option '${$.flags}' not specified`;this.error(w,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption($,w){let Z=(Y)=>{let G=Y.attributeName(),J=this.getOptionValue(G),Q=this.options.find((M)=>M.negate&&G===M.attributeName()),z=this.options.find((M)=>!M.negate&&G===M.attributeName());if(Q&&(Q.presetArg===void 0&&J===!1||Q.presetArg!==void 0&&J===Q.presetArg))return Q;return z||Y},W=(Y)=>{let G=Z(Y),J=G.attributeName();if(this.getOptionValueSource(J)==="env")return`environment variable '${G.envVar}'`;return`option '${G.flags}'`},X=`error: ${W($)} cannot be used with ${W(w)}`;this.error(X,{code:"commander.conflictingOption"})}unknownOption($){if(this._allowUnknownOption)return;let w="";if($.startsWith("--")&&this._showSuggestionAfterError){let W=[],X=this;do{let Y=X.createHelp().visibleOptions(X).filter((G)=>G.long).map((G)=>G.long);W=W.concat(Y),X=X.parent}while(X&&!X._enablePositionalOptions);w=pW($,W)}let Z=`error: unknown option '${$}'${w}`;this.error(Z,{code:"commander.unknownOption"})}_excessArguments($){if(this._allowExcessArguments)return;let w=this.registeredArguments.length,Z=w===1?"":"s",X=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${w} argument${Z} but got ${$.length}.`;this.error(X,{code:"commander.excessArguments"})}unknownCommand(){let $=this.args[0],w="";if(this._showSuggestionAfterError){let W=[];this.createHelp().visibleCommands(this).forEach((X)=>{if(W.push(X.name()),X.alias())W.push(X.alias())}),w=pW($,W)}let Z=`error: unknown command '${$}'${w}`;this.error(Z,{code:"commander.unknownCommand"})}version($,w,Z){if($===void 0)return this._version;this._version=$,w=w||"-V, --version",Z=Z||"output the version number";let W=this.createOption(w,Z);return this._versionOptionName=W.attributeName(),this._registerOption(W),this.on("option:"+W.name(),()=>{this._outputConfiguration.writeOut(`${$}
|
|
26
|
+
`),this._exit(0,"commander.version",$)}),this}description($,w){if($===void 0&&w===void 0)return this._description;if(this._description=$,w)this._argsDescription=w;return this}summary($){if($===void 0)return this._summary;return this._summary=$,this}alias($){if($===void 0)return this._aliases[0];let w=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)w=this.commands[this.commands.length-1];if($===w._name)throw Error("Command alias can't be the same as its name");let Z=this.parent?._findCommand($);if(Z){let W=[Z.name()].concat(Z.aliases()).join("|");throw Error(`cannot add alias '${$}' to command '${this.name()}' as already have command '${W}'`)}return w._aliases.push($),this}aliases($){if($===void 0)return this._aliases;return $.forEach((w)=>this.alias(w)),this}usage($){if($===void 0){if(this._usage)return this._usage;let w=this.registeredArguments.map((Z)=>{return JM(Z)});return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?w:[]).join(" ")}return this._usage=$,this}name($){if($===void 0)return this._name;return this._name=$,this}helpGroup($){if($===void 0)return this._helpGroupHeading??"";return this._helpGroupHeading=$,this}commandsGroup($){if($===void 0)return this._defaultCommandGroup??"";return this._defaultCommandGroup=$,this}optionsGroup($){if($===void 0)return this._defaultOptionGroup??"";return this._defaultOptionGroup=$,this}_initOptionGroup($){if(this._defaultOptionGroup&&!$.helpGroupHeading)$.helpGroup(this._defaultOptionGroup)}_initCommandGroup($){if(this._defaultCommandGroup&&!$.helpGroup())$.helpGroup(this._defaultCommandGroup)}nameFromFilename($){return this._name=W$.basename($,W$.extname($)),this}executableDir($){if($===void 0)return this._executableDir;return this._executableDir=$,this}helpInformation($){let w=this.createHelp(),Z=this._getOutputContext($);w.prepareContext({error:Z.error,helpWidth:Z.helpWidth,outputHasColors:Z.hasColors});let W=w.formatHelp(this,w);if(Z.hasColors)return W;return this._outputConfiguration.stripColor(W)}_getOutputContext($){$=$||{};let w=!!$.error,Z,W,X;if(w)Z=(G)=>this._outputConfiguration.writeErr(G),W=this._outputConfiguration.getErrHasColors(),X=this._outputConfiguration.getErrHelpWidth();else Z=(G)=>this._outputConfiguration.writeOut(G),W=this._outputConfiguration.getOutHasColors(),X=this._outputConfiguration.getOutHelpWidth();return{error:w,write:(G)=>{if(!W)G=this._outputConfiguration.stripColor(G);return Z(G)},hasColors:W,helpWidth:X}}outputHelp($){let w;if(typeof $==="function")w=$,$=void 0;let Z=this._getOutputContext($),W={error:Z.error,write:Z.write,command:this};this._getCommandAndAncestors().reverse().forEach((Y)=>Y.emit("beforeAllHelp",W)),this.emit("beforeHelp",W);let X=this.helpInformation({error:Z.error});if(w){if(X=w(X),typeof X!=="string"&&!Buffer.isBuffer(X))throw Error("outputHelp callback must return a string or a Buffer")}if(Z.write(X),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",W),this._getCommandAndAncestors().forEach((Y)=>Y.emit("afterAllHelp",W))}helpOption($,w){if(typeof $==="boolean"){if($){if(this._helpOption===null)this._helpOption=void 0;if(this._defaultOptionGroup)this._initOptionGroup(this._getHelpOption())}else this._helpOption=null;return this}if(this._helpOption=this.createOption($??"-h, --help",w??"display help for command"),$||w)this._initOptionGroup(this._helpOption);return this}_getHelpOption(){if(this._helpOption===void 0)this.helpOption(void 0,void 0);return this._helpOption}addHelpOption($){return this._helpOption=$,this._initOptionGroup($),this}help($){this.outputHelp($);let w=Number(p.exitCode??0);if(w===0&&$&&typeof $!=="function"&&$.error)w=1;this._exit(w,"commander.help","(outputHelp)")}addHelpText($,w){let Z=["beforeAll","before","after","afterAll"];if(!Z.includes($))throw Error(`Unexpected value for position to addHelpText.
|
|
27
27
|
Expecting one of '${Z.join("', '")}'`);let W=`${$}Help`;return this.on(W,(X)=>{let Y;if(typeof w==="function")Y=w({error:X.error,command:X.command});else Y=w;if(Y)X.write(`${Y}
|
|
28
|
-
`)}),this}_outputHelpIfRequested($){let w=this._getHelpOption();if(w&&$.find((W)=>w.is(W)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function dW($){return $.map((w)=>{if(!w.startsWith("--inspect"))return w;let Z,W="127.0.0.1",X="9229",Y;if((Y=w.match(/^(--inspect(-brk)?)$/))!==null)Z=Y[1];else if((Y=w.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(Z=Y[1],/^\d+$/.test(Y[3]))X=Y[3];else W=Y[3];else if((Y=w.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)Z=Y[1],W=Y[3],X=Y[4];if(Z&&X!=="0")return`${Z}=${W}:${parseInt(X)+1}`;return w})}function m6(){if(p.env.NO_COLOR||p.env.FORCE_COLOR==="0"||p.env.FORCE_COLOR==="false")return!1;if(p.env.FORCE_COLOR||p.env.CLICOLOR_FORCE!==void 0)return!0;return}JM.Command=l6;JM.useColor=m6});var d6=L((KM)=>{var{Argument:nW}=C4(),{Command:c6}=pW(),{CommanderError:MM,InvalidArgumentError:tW}=fw(),{Help:TM}=v6(),{Option:rW}=u6();KM.program=new c6;KM.createCommand=($)=>new c6($);KM.createOption=($,w)=>new rW($,w);KM.createArgument=($,w)=>new nW($,w);KM.Command=c6;KM.Option=rW;KM.Argument=nW;KM.Help=TM;KM.CommanderError=MM;KM.InvalidArgumentError=tW;KM.InvalidOptionArgumentError=tW});var Aw=L((XX)=>{Object.defineProperty(XX,"__esModule",{value:!0});XX.regexpCode=XX.getEsmExportName=XX.getProperty=XX.safeStringify=XX.stringify=XX.strConcat=XX.addCodeArg=XX.str=XX._=XX.nil=XX._Code=XX.Name=XX.IDENTIFIER=XX._CodeOrName=void 0;class b4{}XX._CodeOrName=b4;XX.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class C1 extends b4{constructor($){super();if(!XX.IDENTIFIER.test($))throw Error("CodeGen: name must be a valid identifier");this.str=$}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}XX.Name=C1;class h0 extends b4{constructor($){super();this._items=typeof $==="string"?[$]:$}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let $=this._items[0];return $===""||$==='""'}get str(){var $;return($=this._str)!==null&&$!==void 0?$:this._str=this._items.reduce((w,Z)=>`${w}${Z}`,"")}get names(){var $;return($=this._names)!==null&&$!==void 0?$:this._names=this._items.reduce((w,Z)=>{if(Z instanceof C1)w[Z.str]=(w[Z.str]||0)+1;return w},{})}}XX._Code=h0;XX.nil=new h0("");function ZX($,...w){let Z=[$[0]],W=0;while(W<w.length)s6(Z,w[W]),Z.push($[++W]);return new h0(Z)}XX._=ZX;var r6=new h0("+");function WX($,...w){let Z=[kw($[0])],W=0;while(W<w.length)Z.push(r6),s6(Z,w[W]),Z.push(r6,kw($[++W]));return CM(Z),new h0(Z)}XX.str=WX;function s6($,w){if(w instanceof h0)$.push(...w._items);else if(w instanceof C1)$.push(w);else $.push(yM(w))}XX.addCodeArg=s6;function CM($){let w=1;while(w<$.length-1){if($[w]===r6){let Z=jM($[w-1],$[w+1]);if(Z!==void 0){$.splice(w-1,3,Z);continue}$[w++]="+"}w++}}function jM($,w){if(w==='""')return $;if($==='""')return w;if(typeof $=="string"){if(w instanceof C1||$[$.length-1]!=='"')return;if(typeof w!="string")return`${$.slice(0,-1)}${w}"`;if(w[0]==='"')return $.slice(0,-1)+w.slice(1);return}if(typeof w=="string"&&w[0]==='"'&&!($ instanceof C1))return`"${$}${w.slice(1)}`;return}function IM($,w){return w.emptyStr()?$:$.emptyStr()?w:WX`${$}${w}`}XX.strConcat=IM;function yM($){return typeof $=="number"||typeof $=="boolean"||$===null?$:kw(Array.isArray($)?$.join(","):$)}function bM($){return new h0(kw($))}XX.stringify=bM;function kw($){return JSON.stringify($).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}XX.safeStringify=kw;function xM($){return typeof $=="string"&&XX.IDENTIFIER.test($)?new h0(`.${$}`):ZX`[${$}]`}XX.getProperty=xM;function _M($){if(typeof $=="string"&&XX.IDENTIFIER.test($))return new h0(`${$}`);throw Error(`CodeGen: invalid export name: ${$}, use explicit $id name mapping`)}XX.getEsmExportName=_M;function gM($){return new h0($.toString())}XX.regexpCode=gM});var $Z=L((QX)=>{Object.defineProperty(QX,"__esModule",{value:!0});QX.ValueScope=QX.ValueScopeName=QX.Scope=QX.varKinds=QX.UsedValueState=void 0;var O0=Aw();class GX extends Error{constructor($){super(`CodeGen: "code" for ${$} not defined`);this.value=$.value}}var _4;(function($){$[$.Started=0]="Started",$[$.Completed=1]="Completed"})(_4||(QX.UsedValueState=_4={}));QX.varKinds={const:new O0.Name("const"),let:new O0.Name("let"),var:new O0.Name("var")};class o6{constructor({prefixes:$,parent:w}={}){this._names={},this._prefixes=$,this._parent=w}toName($){return $ instanceof O0.Name?$:this.name($)}name($){return new O0.Name(this._newName($))}_newName($){let w=this._names[$]||this._nameGroup($);return`${$}${w.index++}`}_nameGroup($){var w,Z;if(((Z=(w=this._parent)===null||w===void 0?void 0:w._prefixes)===null||Z===void 0?void 0:Z.has($))||this._prefixes&&!this._prefixes.has($))throw Error(`CodeGen: prefix "${$}" is not allowed in this scope`);return this._names[$]={prefix:$,index:0}}}QX.Scope=o6;class e6 extends O0.Name{constructor($,w){super(w);this.prefix=$}setValue($,{property:w,itemIndex:Z}){this.value=$,this.scopePath=O0._`.${new O0.Name(w)}[${Z}]`}}QX.ValueScopeName=e6;var sM=O0._`\n`;class JX extends o6{constructor($){super($);this._values={},this._scope=$.scope,this.opts={...$,_n:$.lines?sM:O0.nil}}get(){return this._scope}name($){return new e6($,this._newName($))}value($,w){var Z;if(w.ref===void 0)throw Error("CodeGen: ref must be passed in value");let W=this.toName($),{prefix:X}=W,Y=(Z=w.key)!==null&&Z!==void 0?Z:w.ref,G=this._values[X];if(G){let z=G.get(Y);if(z)return z}else G=this._values[X]=new Map;G.set(Y,W);let J=this._scope[X]||(this._scope[X]=[]),Q=J.length;return J[Q]=w.ref,W.setValue(w,{property:X,itemIndex:Q}),W}getValue($,w){let Z=this._values[$];if(!Z)return;return Z.get(w)}scopeRefs($,w=this._values){return this._reduceValues(w,(Z)=>{if(Z.scopePath===void 0)throw Error(`CodeGen: name "${Z}" has no value`);return O0._`${$}${Z.scopePath}`})}scopeCode($=this._values,w,Z){return this._reduceValues($,(W)=>{if(W.value===void 0)throw Error(`CodeGen: name "${W}" has no value`);return W.value.code},w,Z)}_reduceValues($,w,Z={},W){let X=O0.nil;for(let Y in $){let G=$[Y];if(!G)continue;let J=Z[Y]=Z[Y]||new Map;G.forEach((Q)=>{if(J.has(Q))return;J.set(Q,_4.Started);let z=w(Q);if(z){let M=this.opts.es5?QX.varKinds.var:QX.varKinds.const;X=O0._`${X}${M} ${Q} = ${z};${this.opts._n}`}else if(z=W===null||W===void 0?void 0:W(Q))X=O0._`${X}${z}${this.opts._n}`;else throw new GX(Q);J.set(Q,_4.Completed)})}return X}}QX.ValueScope=JX});var v=L((E0)=>{Object.defineProperty(E0,"__esModule",{value:!0});E0.or=E0.and=E0.not=E0.CodeGen=E0.operators=E0.varKinds=E0.ValueScopeName=E0.ValueScope=E0.Scope=E0.Name=E0.regexpCode=E0.stringify=E0.getProperty=E0.nil=E0.strConcat=E0.str=E0._=void 0;var m=Aw(),i0=$Z(),L$=Aw();Object.defineProperty(E0,"_",{enumerable:!0,get:function(){return L$._}});Object.defineProperty(E0,"str",{enumerable:!0,get:function(){return L$.str}});Object.defineProperty(E0,"strConcat",{enumerable:!0,get:function(){return L$.strConcat}});Object.defineProperty(E0,"nil",{enumerable:!0,get:function(){return L$.nil}});Object.defineProperty(E0,"getProperty",{enumerable:!0,get:function(){return L$.getProperty}});Object.defineProperty(E0,"stringify",{enumerable:!0,get:function(){return L$.stringify}});Object.defineProperty(E0,"regexpCode",{enumerable:!0,get:function(){return L$.regexpCode}});Object.defineProperty(E0,"Name",{enumerable:!0,get:function(){return L$.Name}});var m4=$Z();Object.defineProperty(E0,"Scope",{enumerable:!0,get:function(){return m4.Scope}});Object.defineProperty(E0,"ValueScope",{enumerable:!0,get:function(){return m4.ValueScope}});Object.defineProperty(E0,"ValueScopeName",{enumerable:!0,get:function(){return m4.ValueScopeName}});Object.defineProperty(E0,"varKinds",{enumerable:!0,get:function(){return m4.varKinds}});E0.operators={GT:new m._Code(">"),GTE:new m._Code(">="),LT:new m._Code("<"),LTE:new m._Code("<="),EQ:new m._Code("==="),NEQ:new m._Code("!=="),NOT:new m._Code("!"),OR:new m._Code("||"),AND:new m._Code("&&"),ADD:new m._Code("+")};class D${optimizeNodes(){return this}optimizeNames($,w){return this}}class MX extends D${constructor($,w,Z){super();this.varKind=$,this.name=w,this.rhs=Z}render({es5:$,_n:w}){let Z=$?i0.varKinds.var:this.varKind,W=this.rhs===void 0?"":` = ${this.rhs}`;return`${Z} ${this.name}${W};`+w}optimizeNames($,w){if(!$[this.name.str])return;if(this.rhs)this.rhs=I1(this.rhs,$,w);return this}get names(){return this.rhs instanceof m._CodeOrName?this.rhs.names:{}}}class WZ extends D${constructor($,w,Z){super();this.lhs=$,this.rhs=w,this.sideEffects=Z}render({_n:$}){return`${this.lhs} = ${this.rhs};`+$}optimizeNames($,w){if(this.lhs instanceof m.Name&&!$[this.lhs.str]&&!this.sideEffects)return;return this.rhs=I1(this.rhs,$,w),this}get names(){let $=this.lhs instanceof m.Name?{}:{...this.lhs.names};return i4($,this.rhs)}}class TX extends WZ{constructor($,w,Z,W){super($,Z,W);this.op=w}render({_n:$}){return`${this.lhs} ${this.op}= ${this.rhs};`+$}}class KX extends D${constructor($){super();this.label=$,this.names={}}render({_n:$}){return`${this.label}:`+$}}class NX extends D${constructor($){super();this.label=$,this.names={}}render({_n:$}){return`break${this.label?` ${this.label}`:""};`+$}}class BX extends D${constructor($){super();this.error=$}render({_n:$}){return`throw ${this.error};`+$}get names(){return this.error.names}}class VX extends D${constructor($){super();this.code=$}render({_n:$}){return`${this.code};`+$}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames($,w){return this.code=I1(this.code,$,w),this}get names(){return this.code instanceof m._CodeOrName?this.code.names:{}}}class l4 extends D${constructor($=[]){super();this.nodes=$}render($){return this.nodes.reduce((w,Z)=>w+Z.render($),"")}optimizeNodes(){let{nodes:$}=this,w=$.length;while(w--){let Z=$[w].optimizeNodes();if(Array.isArray(Z))$.splice(w,1,...Z);else if(Z)$[w]=Z;else $.splice(w,1)}return $.length>0?this:void 0}optimizeNames($,w){let{nodes:Z}=this,W=Z.length;while(W--){let X=Z[W];if(X.optimizeNames($,w))continue;$T($,X.names),Z.splice(W,1)}return Z.length>0?this:void 0}get names(){return this.nodes.reduce(($,w)=>n$($,w.names),{})}}class f$ extends l4{render($){return"{"+$._n+super.render($)+"}"+$._n}}class PX extends l4{}class Sw extends f${}Sw.kind="else";class W$ extends f${constructor($,w){super(w);this.condition=$}render($){let w=`if(${this.condition})`+super.render($);if(this.else)w+="else "+this.else.render($);return w}optimizeNodes(){super.optimizeNodes();let $=this.condition;if($===!0)return this.nodes;let w=this.else;if(w){let Z=w.optimizeNodes();w=this.else=Array.isArray(Z)?new Sw(Z):Z}if(w){if($===!1)return w instanceof W$?w:w.nodes;if(this.nodes.length)return this;return new W$(OX($),w instanceof W$?[w]:w.nodes)}if($===!1||!this.nodes.length)return;return this}optimizeNames($,w){var Z;if(this.else=(Z=this.else)===null||Z===void 0?void 0:Z.optimizeNames($,w),!(super.optimizeNames($,w)||this.else))return;return this.condition=I1(this.condition,$,w),this}get names(){let $=super.names;if(i4($,this.condition),this.else)n$($,this.else.names);return $}}W$.kind="if";class j1 extends f${}j1.kind="for";class qX extends j1{constructor($){super();this.iteration=$}render($){return`for(${this.iteration})`+super.render($)}optimizeNames($,w){if(!super.optimizeNames($,w))return;return this.iteration=I1(this.iteration,$,w),this}get names(){return n$(super.names,this.iteration.names)}}class UX extends j1{constructor($,w,Z,W){super();this.varKind=$,this.name=w,this.from=Z,this.to=W}render($){let w=$.es5?i0.varKinds.var:this.varKind,{name:Z,from:W,to:X}=this;return`for(${w} ${Z}=${W}; ${Z}<${X}; ${Z}++)`+super.render($)}get names(){let $=i4(super.names,this.from);return i4($,this.to)}}class wZ extends j1{constructor($,w,Z,W){super();this.loop=$,this.varKind=w,this.name=Z,this.iterable=W}render($){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render($)}optimizeNames($,w){if(!super.optimizeNames($,w))return;return this.iterable=I1(this.iterable,$,w),this}get names(){return n$(super.names,this.iterable.names)}}class g4 extends f${constructor($,w,Z){super();this.name=$,this.args=w,this.async=Z}render($){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render($)}}g4.kind="func";class v4 extends l4{render($){return"return "+super.render($)}}v4.kind="return";class HX extends f${render($){let w="try"+super.render($);if(this.catch)w+=this.catch.render($);if(this.finally)w+=this.finally.render($);return w}optimizeNodes(){var $,w;return super.optimizeNodes(),($=this.catch)===null||$===void 0||$.optimizeNodes(),(w=this.finally)===null||w===void 0||w.optimizeNodes(),this}optimizeNames($,w){var Z,W;return super.optimizeNames($,w),(Z=this.catch)===null||Z===void 0||Z.optimizeNames($,w),(W=this.finally)===null||W===void 0||W.optimizeNames($,w),this}get names(){let $=super.names;if(this.catch)n$($,this.catch.names);if(this.finally)n$($,this.finally.names);return $}}class u4 extends f${constructor($){super();this.error=$}render($){return`catch(${this.error})`+super.render($)}}u4.kind="catch";class h4 extends f${render($){return"finally"+super.render($)}}h4.kind="finally";class FX{constructor($,w={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...w,_n:w.lines?`
|
|
29
|
-
`:""},this._extScope=$,this._scope=new i0.Scope({parent:$}),this._nodes=[new PX]}toString(){return this._root.render(this.opts)}name($){return this._scope.name($)}scopeName($){return this._extScope.name($)}scopeValue($,w){let Z=this._extScope.value($,w);return(this._values[Z.prefix]||(this._values[Z.prefix]=new Set)).add(Z),Z}getScopeValue($,w){return this._extScope.getValue($,w)}scopeRefs($){return this._extScope.scopeRefs($,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def($,w,Z,W){let X=this._scope.toName(w);if(Z!==void 0&&W)this._constants[X.str]=Z;return this._leafNode(new MX($,X,Z)),X}const($,w,Z){return this._def(i0.varKinds.const,$,w,Z)}let($,w,Z){return this._def(i0.varKinds.let,$,w,Z)}var($,w,Z){return this._def(i0.varKinds.var,$,w,Z)}assign($,w,Z){return this._leafNode(new WZ($,w,Z))}add($,w){return this._leafNode(new TX($,E0.operators.ADD,w))}code($){if(typeof $=="function")$();else if($!==m.nil)this._leafNode(new VX($));return this}object(...$){let w=["{"];for(let[Z,W]of $){if(w.length>1)w.push(",");if(w.push(Z),Z!==W||this.opts.es5)w.push(":"),(0,m.addCodeArg)(w,W)}return w.push("}"),new m._Code(w)}if($,w,Z){if(this._blockNode(new W$($)),w&&Z)this.code(w).else().code(Z).endIf();else if(w)this.code(w).endIf();else if(Z)throw Error('CodeGen: "else" body without "then" body');return this}elseIf($){return this._elseNode(new W$($))}else(){return this._elseNode(new Sw)}endIf(){return this._endBlockNode(W$,Sw)}_for($,w){if(this._blockNode($),w)this.code(w).endFor();return this}for($,w){return this._for(new qX($),w)}forRange($,w,Z,W,X=this.opts.es5?i0.varKinds.var:i0.varKinds.let){let Y=this._scope.toName($);return this._for(new UX(X,Y,w,Z),()=>W(Y))}forOf($,w,Z,W=i0.varKinds.const){let X=this._scope.toName($);if(this.opts.es5){let Y=w instanceof m.Name?w:this.var("_arr",w);return this.forRange("_i",0,m._`${Y}.length`,(G)=>{this.var(X,m._`${Y}[${G}]`),Z(X)})}return this._for(new wZ("of",W,X,w),()=>Z(X))}forIn($,w,Z,W=this.opts.es5?i0.varKinds.var:i0.varKinds.const){if(this.opts.ownProperties)return this.forOf($,m._`Object.keys(${w})`,Z);let X=this._scope.toName($);return this._for(new wZ("in",W,X,w),()=>Z(X))}endFor(){return this._endBlockNode(j1)}label($){return this._leafNode(new KX($))}break($){return this._leafNode(new NX($))}return($){let w=new v4;if(this._blockNode(w),this.code($),w.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(v4)}try($,w,Z){if(!w&&!Z)throw Error('CodeGen: "try" without "catch" and "finally"');let W=new HX;if(this._blockNode(W),this.code($),w){let X=this.name("e");this._currNode=W.catch=new u4(X),w(X)}if(Z)this._currNode=W.finally=new h4,this.code(Z);return this._endBlockNode(u4,h4)}throw($){return this._leafNode(new BX($))}block($,w){if(this._blockStarts.push(this._nodes.length),$)this.code($).endBlock(w);return this}endBlock($){let w=this._blockStarts.pop();if(w===void 0)throw Error("CodeGen: not in self-balancing block");let Z=this._nodes.length-w;if(Z<0||$!==void 0&&Z!==$)throw Error(`CodeGen: wrong number of nodes: ${Z} vs ${$} expected`);return this._nodes.length=w,this}func($,w=m.nil,Z,W){if(this._blockNode(new g4($,w,Z)),W)this.code(W).endFunc();return this}endFunc(){return this._endBlockNode(g4)}optimize($=1){while($-- >0)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode($){return this._currNode.nodes.push($),this}_blockNode($){this._currNode.nodes.push($),this._nodes.push($)}_endBlockNode($,w){let Z=this._currNode;if(Z instanceof $||w&&Z instanceof w)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${w?`${$.kind}/${w.kind}`:$.kind}"`)}_elseNode($){let w=this._currNode;if(!(w instanceof W$))throw Error('CodeGen: "else" without "if"');return this._currNode=w.else=$,this}get _root(){return this._nodes[0]}get _currNode(){let $=this._nodes;return $[$.length-1]}set _currNode($){let w=this._nodes;w[w.length-1]=$}}E0.CodeGen=FX;function n$($,w){for(let Z in w)$[Z]=($[Z]||0)+(w[Z]||0);return $}function i4($,w){return w instanceof m._CodeOrName?n$($,w.names):$}function I1($,w,Z){if($ instanceof m.Name)return W($);if(!X($))return $;return new m._Code($._items.reduce((Y,G)=>{if(G instanceof m.Name)G=W(G);if(G instanceof m._Code)Y.push(...G._items);else Y.push(G);return Y},[]));function W(Y){let G=Z[Y.str];if(G===void 0||w[Y.str]!==1)return Y;return delete w[Y.str],G}function X(Y){return Y instanceof m._Code&&Y._items.some((G)=>G instanceof m.Name&&w[G.str]===1&&Z[G.str]!==void 0)}}function $T($,w){for(let Z in w)$[Z]=($[Z]||0)-(w[Z]||0)}function OX($){return typeof $=="boolean"||typeof $=="number"||$===null?!$:m._`!${ZZ($)}`}E0.not=OX;var wT=EX(E0.operators.AND);function ZT(...$){return $.reduce(wT)}E0.and=ZT;var WT=EX(E0.operators.OR);function XT(...$){return $.reduce(WT)}E0.or=XT;function EX($){return(w,Z)=>w===m.nil?Z:Z===m.nil?w:m._`${ZZ(w)} ${$} ${ZZ(Z)}`}function ZZ($){return $ instanceof m.Name?$:m._`(${$})`}});var l=L((jX)=>{Object.defineProperty(jX,"__esModule",{value:!0});jX.checkStrictMode=jX.getErrorPath=jX.Type=jX.useFunc=jX.setEvaluated=jX.evaluatedPropsToName=jX.mergeEvaluated=jX.eachItem=jX.unescapeJsonPointer=jX.escapeJsonPointer=jX.escapeFragment=jX.unescapeFragment=jX.schemaRefOrVal=jX.schemaHasRulesButRef=jX.schemaHasRules=jX.checkUnknownRules=jX.alwaysValidSchema=jX.toHash=void 0;var n=v(),QT=Aw();function zT($){let w={};for(let Z of $)w[Z]=!0;return w}jX.toHash=zT;function MT($,w){if(typeof w=="boolean")return w;if(Object.keys(w).length===0)return!0;return kX($,w),!AX(w,$.self.RULES.all)}jX.alwaysValidSchema=MT;function kX($,w=$.schema){let{opts:Z,self:W}=$;if(!Z.strictSchema)return;if(typeof w==="boolean")return;let X=W.RULES.keywords;for(let Y in w)if(!X[Y])CX($,`unknown keyword: "${Y}"`)}jX.checkUnknownRules=kX;function AX($,w){if(typeof $=="boolean")return!$;for(let Z in $)if(w[Z])return!0;return!1}jX.schemaHasRules=AX;function TT($,w){if(typeof $=="boolean")return!$;for(let Z in $)if(Z!=="$ref"&&w.all[Z])return!0;return!1}jX.schemaHasRulesButRef=TT;function KT({topSchemaRef:$,schemaPath:w},Z,W,X){if(!X){if(typeof Z=="number"||typeof Z=="boolean")return Z;if(typeof Z=="string")return n._`${Z}`}return n._`${$}${w}${(0,n.getProperty)(W)}`}jX.schemaRefOrVal=KT;function NT($){return SX(decodeURIComponent($))}jX.unescapeFragment=NT;function BT($){return encodeURIComponent(YZ($))}jX.escapeFragment=BT;function YZ($){if(typeof $=="number")return`${$}`;return $.replace(/~/g,"~0").replace(/\//g,"~1")}jX.escapeJsonPointer=YZ;function SX($){return $.replace(/~1/g,"/").replace(/~0/g,"~")}jX.unescapeJsonPointer=SX;function VT($,w){if(Array.isArray($))for(let Z of $)w(Z);else w($)}jX.eachItem=VT;function DX({mergeNames:$,mergeToName:w,mergeValues:Z,resultToName:W}){return(X,Y,G,J)=>{let Q=G===void 0?Y:G instanceof n.Name?(Y instanceof n.Name?$(X,Y,G):w(X,Y,G),G):Y instanceof n.Name?(w(X,G,Y),Y):Z(Y,G);return J===n.Name&&!(Q instanceof n.Name)?W(X,Q):Q}}jX.mergeEvaluated={props:DX({mergeNames:($,w,Z)=>$.if(n._`${Z} !== true && ${w} !== undefined`,()=>{$.if(n._`${w} === true`,()=>$.assign(Z,!0),()=>$.assign(Z,n._`${Z} || {}`).code(n._`Object.assign(${Z}, ${w})`))}),mergeToName:($,w,Z)=>$.if(n._`${Z} !== true`,()=>{if(w===!0)$.assign(Z,!0);else $.assign(Z,n._`${Z} || {}`),GZ($,Z,w)}),mergeValues:($,w)=>$===!0?!0:{...$,...w},resultToName:RX}),items:DX({mergeNames:($,w,Z)=>$.if(n._`${Z} !== true && ${w} !== undefined`,()=>$.assign(Z,n._`${w} === true ? true : ${Z} > ${w} ? ${Z} : ${w}`)),mergeToName:($,w,Z)=>$.if(n._`${Z} !== true`,()=>$.assign(Z,w===!0?!0:n._`${Z} > ${w} ? ${Z} : ${w}`)),mergeValues:($,w)=>$===!0?!0:Math.max($,w),resultToName:($,w)=>$.var("items",w)})};function RX($,w){if(w===!0)return $.var("props",!0);let Z=$.var("props",n._`{}`);if(w!==void 0)GZ($,Z,w);return Z}jX.evaluatedPropsToName=RX;function GZ($,w,Z){Object.keys(Z).forEach((W)=>$.assign(n._`${w}${(0,n.getProperty)(W)}`,!0))}jX.setEvaluated=GZ;var fX={};function PT($,w){return $.scopeValue("func",{ref:w,code:fX[w.code]||(fX[w.code]=new QT._Code(w.code))})}jX.useFunc=PT;var XZ;(function($){$[$.Num=0]="Num",$[$.Str=1]="Str"})(XZ||(jX.Type=XZ={}));function qT($,w,Z){if($ instanceof n.Name){let W=w===XZ.Num;return Z?W?n._`"[" + ${$} + "]"`:n._`"['" + ${$} + "']"`:W?n._`"/" + ${$}`:n._`"/" + ${$}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return Z?(0,n.getProperty)($).toString():"/"+YZ($)}jX.getErrorPath=qT;function CX($,w,Z=$.opts.strictSchema){if(!Z)return;if(w=`strict mode: ${w}`,Z===!0)throw Error(w);$.self.logger.warn(w)}jX.checkStrictMode=CX});var X$=L((yX)=>{Object.defineProperty(yX,"__esModule",{value:!0});var K0=v(),xT={data:new K0.Name("data"),valCxt:new K0.Name("valCxt"),instancePath:new K0.Name("instancePath"),parentData:new K0.Name("parentData"),parentDataProperty:new K0.Name("parentDataProperty"),rootData:new K0.Name("rootData"),dynamicAnchors:new K0.Name("dynamicAnchors"),vErrors:new K0.Name("vErrors"),errors:new K0.Name("errors"),this:new K0.Name("this"),self:new K0.Name("self"),scope:new K0.Name("scope"),json:new K0.Name("json"),jsonPos:new K0.Name("jsonPos"),jsonLen:new K0.Name("jsonLen"),jsonPart:new K0.Name("jsonPart")};yX.default=xT});var Rw=L((gX)=>{Object.defineProperty(gX,"__esModule",{value:!0});gX.extendErrors=gX.resetErrorsCount=gX.reportExtraError=gX.reportError=gX.keyword$DataError=gX.keywordError=void 0;var c=v(),d4=l(),U0=X$();gX.keywordError={message:({keyword:$})=>c.str`must pass "${$}" keyword validation`};gX.keyword$DataError={message:({keyword:$,schemaType:w})=>w?c.str`"${$}" keyword must be ${w} ($data)`:c.str`"${$}" keyword is invalid ($data)`};function gT($,w=gX.keywordError,Z,W){let{it:X}=$,{gen:Y,compositeRule:G,allErrors:J}=X,Q=_X($,w,Z);if(W!==null&&W!==void 0?W:G||J)bX(Y,Q);else xX(X,c._`[${Q}]`)}gX.reportError=gT;function vT($,w=gX.keywordError,Z){let{it:W}=$,{gen:X,compositeRule:Y,allErrors:G}=W,J=_X($,w,Z);if(bX(X,J),!(Y||G))xX(W,U0.default.vErrors)}gX.reportExtraError=vT;function uT($,w){$.assign(U0.default.errors,w),$.if(c._`${U0.default.vErrors} !== null`,()=>$.if(w,()=>$.assign(c._`${U0.default.vErrors}.length`,w),()=>$.assign(U0.default.vErrors,null)))}gX.resetErrorsCount=uT;function hT({gen:$,keyword:w,schemaValue:Z,data:W,errsCount:X,it:Y}){if(X===void 0)throw Error("ajv implementation error");let G=$.name("err");$.forRange("i",X,U0.default.errors,(J)=>{if($.const(G,c._`${U0.default.vErrors}[${J}]`),$.if(c._`${G}.instancePath === undefined`,()=>$.assign(c._`${G}.instancePath`,(0,c.strConcat)(U0.default.instancePath,Y.errorPath))),$.assign(c._`${G}.schemaPath`,c.str`${Y.errSchemaPath}/${w}`),Y.opts.verbose)$.assign(c._`${G}.schema`,Z),$.assign(c._`${G}.data`,W)})}gX.extendErrors=hT;function bX($,w){let Z=$.const("err",w);$.if(c._`${U0.default.vErrors} === null`,()=>$.assign(U0.default.vErrors,c._`[${Z}]`),c._`${U0.default.vErrors}.push(${Z})`),$.code(c._`${U0.default.errors}++`)}function xX($,w){let{gen:Z,validateName:W,schemaEnv:X}=$;if(X.$async)Z.throw(c._`new ${$.ValidationError}(${w})`);else Z.assign(c._`${W}.errors`,w),Z.return(!1)}var t$={keyword:new c.Name("keyword"),schemaPath:new c.Name("schemaPath"),params:new c.Name("params"),propertyName:new c.Name("propertyName"),message:new c.Name("message"),schema:new c.Name("schema"),parentSchema:new c.Name("parentSchema")};function _X($,w,Z){let{createErrors:W}=$.it;if(W===!1)return c._`{}`;return iT($,w,Z)}function iT($,w,Z={}){let{gen:W,it:X}=$,Y=[mT(X,Z),lT($,Z)];return cT($,w,Y),W.object(...Y)}function mT({errorPath:$},{instancePath:w}){let Z=w?c.str`${$}${(0,d4.getErrorPath)(w,d4.Type.Str)}`:$;return[U0.default.instancePath,(0,c.strConcat)(U0.default.instancePath,Z)]}function lT({keyword:$,it:{errSchemaPath:w}},{schemaPath:Z,parentSchema:W}){let X=W?w:c.str`${w}/${$}`;if(Z)X=c.str`${X}${(0,d4.getErrorPath)(Z,d4.Type.Str)}`;return[t$.schemaPath,X]}function cT($,{params:w,message:Z},W){let{keyword:X,data:Y,schemaValue:G,it:J}=$,{opts:Q,propertyName:z,topSchemaRef:M,schemaPath:T}=J;if(W.push([t$.keyword,X],[t$.params,typeof w=="function"?w($):w||c._`{}`]),Q.messages)W.push([t$.message,typeof Z=="function"?Z($):Z]);if(Q.verbose)W.push([t$.schema,G],[t$.parentSchema,c._`${M}${T}`],[U0.default.data,Y]);if(z)W.push([t$.propertyName,z])}});var mX=L((hX)=>{Object.defineProperty(hX,"__esModule",{value:!0});hX.boolOrEmptySchema=hX.topBoolOrEmptySchema=void 0;var rT=Rw(),sT=v(),aT=X$(),oT={message:"boolean schema is false"};function eT($){let{gen:w,schema:Z,validateName:W}=$;if(Z===!1)uX($,!1);else if(typeof Z=="object"&&Z.$async===!0)w.return(aT.default.data);else w.assign(sT._`${W}.errors`,null),w.return(!0)}hX.topBoolOrEmptySchema=eT;function $K($,w){let{gen:Z,schema:W}=$;if(W===!1)Z.var(w,!1),uX($);else Z.var(w,!0)}hX.boolOrEmptySchema=$K;function uX($,w){let{gen:Z,data:W}=$,X={gen:Z,keyword:"false schema",data:W,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:$};(0,rT.reportError)(X,oT,void 0,w)}});var QZ=L((lX)=>{Object.defineProperty(lX,"__esModule",{value:!0});lX.getRules=lX.isJSONType=void 0;var ZK=["string","number","integer","boolean","null","object","array"],WK=new Set(ZK);function XK($){return typeof $=="string"&&WK.has($)}lX.isJSONType=XK;function YK(){let $={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...$,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},$.number,$.string,$.array,$.object],post:{rules:[]},all:{},keywords:{}}}lX.getRules=YK});var zZ=L((nX)=>{Object.defineProperty(nX,"__esModule",{value:!0});nX.shouldUseRule=nX.shouldUseGroup=nX.schemaHasRulesForType=void 0;function JK({schema:$,self:w},Z){let W=w.RULES.types[Z];return W&&W!==!0&&dX($,W)}nX.schemaHasRulesForType=JK;function dX($,w){return w.rules.some((Z)=>pX($,Z))}nX.shouldUseGroup=dX;function pX($,w){var Z;return $[w.keyword]!==void 0||((Z=w.definition.implements)===null||Z===void 0?void 0:Z.some((W)=>$[W]!==void 0))}nX.shouldUseRule=pX});var Cw=L((oX)=>{Object.defineProperty(oX,"__esModule",{value:!0});oX.reportTypeError=oX.checkDataTypes=oX.checkDataType=oX.coerceAndCheckDataType=oX.getJSONTypes=oX.getSchemaTypes=oX.DataType=void 0;var MK=QZ(),TK=zZ(),KK=Rw(),_=v(),rX=l(),y1;(function($){$[$.Correct=0]="Correct",$[$.Wrong=1]="Wrong"})(y1||(oX.DataType=y1={}));function NK($){let w=sX($.type);if(w.includes("null")){if($.nullable===!1)throw Error("type: null contradicts nullable: false")}else{if(!w.length&&$.nullable!==void 0)throw Error('"nullable" cannot be used without "type"');if($.nullable===!0)w.push("null")}return w}oX.getSchemaTypes=NK;function sX($){let w=Array.isArray($)?$:$?[$]:[];if(w.every(MK.isJSONType))return w;throw Error("type must be JSONType or JSONType[]: "+w.join(","))}oX.getJSONTypes=sX;function BK($,w){let{gen:Z,data:W,opts:X}=$,Y=VK(w,X.coerceTypes),G=w.length>0&&!(Y.length===0&&w.length===1&&(0,TK.schemaHasRulesForType)($,w[0]));if(G){let J=TZ(w,W,X.strictNumbers,y1.Wrong);Z.if(J,()=>{if(Y.length)PK($,w,Y);else KZ($)})}return G}oX.coerceAndCheckDataType=BK;var aX=new Set(["string","number","integer","boolean","null"]);function VK($,w){return w?$.filter((Z)=>aX.has(Z)||w==="array"&&Z==="array"):[]}function PK($,w,Z){let{gen:W,data:X,opts:Y}=$,G=W.let("dataType",_._`typeof ${X}`),J=W.let("coerced",_._`undefined`);if(Y.coerceTypes==="array")W.if(_._`${G} == 'object' && Array.isArray(${X}) && ${X}.length == 1`,()=>W.assign(X,_._`${X}[0]`).assign(G,_._`typeof ${X}`).if(TZ(w,X,Y.strictNumbers),()=>W.assign(J,X)));W.if(_._`${J} !== undefined`);for(let z of Z)if(aX.has(z)||z==="array"&&Y.coerceTypes==="array")Q(z);W.else(),KZ($),W.endIf(),W.if(_._`${J} !== undefined`,()=>{W.assign(X,J),qK($,J)});function Q(z){switch(z){case"string":W.elseIf(_._`${G} == "number" || ${G} == "boolean"`).assign(J,_._`"" + ${X}`).elseIf(_._`${X} === null`).assign(J,_._`""`);return;case"number":W.elseIf(_._`${G} == "boolean" || ${X} === null
|
|
28
|
+
`)}),this}_outputHelpIfRequested($){let w=this._getHelpOption();if(w&&$.find((W)=>w.is(W)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function nW($){return $.map((w)=>{if(!w.startsWith("--inspect"))return w;let Z,W="127.0.0.1",X="9229",Y;if((Y=w.match(/^(--inspect(-brk)?)$/))!==null)Z=Y[1];else if((Y=w.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(Z=Y[1],/^\d+$/.test(Y[3]))X=Y[3];else W=Y[3];else if((Y=w.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)Z=Y[1],W=Y[3],X=Y[4];if(Z&&X!=="0")return`${Z}=${W}:${parseInt(X)+1}`;return w})}function m6(){if(p.env.NO_COLOR||p.env.FORCE_COLOR==="0"||p.env.FORCE_COLOR==="false")return!1;if(p.env.FORCE_COLOR||p.env.CLICOLOR_FORCE!==void 0)return!0;return}TM.Command=l6;TM.useColor=m6});var d6=L((PM)=>{var{Argument:rW}=C4(),{Command:c6}=tW(),{CommanderError:BM,InvalidArgumentError:sW}=fw(),{Help:VM}=v6(),{Option:aW}=u6();PM.program=new c6;PM.createCommand=($)=>new c6($);PM.createOption=($,w)=>new aW($,w);PM.createArgument=($,w)=>new rW($,w);PM.Command=c6;PM.Option=aW;PM.Argument=rW;PM.Help=VM;PM.CommanderError=BM;PM.InvalidArgumentError=sW;PM.InvalidOptionArgumentError=sW});var Aw=L((GX)=>{Object.defineProperty(GX,"__esModule",{value:!0});GX.regexpCode=GX.getEsmExportName=GX.getProperty=GX.safeStringify=GX.stringify=GX.strConcat=GX.addCodeArg=GX.str=GX._=GX.nil=GX._Code=GX.Name=GX.IDENTIFIER=GX._CodeOrName=void 0;class b4{}GX._CodeOrName=b4;GX.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class C1 extends b4{constructor($){super();if(!GX.IDENTIFIER.test($))throw Error("CodeGen: name must be a valid identifier");this.str=$}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}GX.Name=C1;class h0 extends b4{constructor($){super();this._items=typeof $==="string"?[$]:$}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let $=this._items[0];return $===""||$==='""'}get str(){var $;return($=this._str)!==null&&$!==void 0?$:this._str=this._items.reduce((w,Z)=>`${w}${Z}`,"")}get names(){var $;return($=this._names)!==null&&$!==void 0?$:this._names=this._items.reduce((w,Z)=>{if(Z instanceof C1)w[Z.str]=(w[Z.str]||0)+1;return w},{})}}GX._Code=h0;GX.nil=new h0("");function XX($,...w){let Z=[$[0]],W=0;while(W<w.length)s6(Z,w[W]),Z.push($[++W]);return new h0(Z)}GX._=XX;var r6=new h0("+");function YX($,...w){let Z=[kw($[0])],W=0;while(W<w.length)Z.push(r6),s6(Z,w[W]),Z.push(r6,kw($[++W]));return bM(Z),new h0(Z)}GX.str=YX;function s6($,w){if(w instanceof h0)$.push(...w._items);else if(w instanceof C1)$.push(w);else $.push(gM(w))}GX.addCodeArg=s6;function bM($){let w=1;while(w<$.length-1){if($[w]===r6){let Z=xM($[w-1],$[w+1]);if(Z!==void 0){$.splice(w-1,3,Z);continue}$[w++]="+"}w++}}function xM($,w){if(w==='""')return $;if($==='""')return w;if(typeof $=="string"){if(w instanceof C1||$[$.length-1]!=='"')return;if(typeof w!="string")return`${$.slice(0,-1)}${w}"`;if(w[0]==='"')return $.slice(0,-1)+w.slice(1);return}if(typeof w=="string"&&w[0]==='"'&&!($ instanceof C1))return`"${$}${w.slice(1)}`;return}function _M($,w){return w.emptyStr()?$:$.emptyStr()?w:YX`${$}${w}`}GX.strConcat=_M;function gM($){return typeof $=="number"||typeof $=="boolean"||$===null?$:kw(Array.isArray($)?$.join(","):$)}function vM($){return new h0(kw($))}GX.stringify=vM;function kw($){return JSON.stringify($).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}GX.safeStringify=kw;function uM($){return typeof $=="string"&&GX.IDENTIFIER.test($)?new h0(`.${$}`):XX`[${$}]`}GX.getProperty=uM;function hM($){if(typeof $=="string"&&GX.IDENTIFIER.test($))return new h0(`${$}`);throw Error(`CodeGen: invalid export name: ${$}, use explicit $id name mapping`)}GX.getEsmExportName=hM;function iM($){return new h0($.toString())}GX.regexpCode=iM});var $Z=L((MX)=>{Object.defineProperty(MX,"__esModule",{value:!0});MX.ValueScope=MX.ValueScopeName=MX.Scope=MX.varKinds=MX.UsedValueState=void 0;var O0=Aw();class QX extends Error{constructor($){super(`CodeGen: "code" for ${$} not defined`);this.value=$.value}}var _4;(function($){$[$.Started=0]="Started",$[$.Completed=1]="Completed"})(_4||(MX.UsedValueState=_4={}));MX.varKinds={const:new O0.Name("const"),let:new O0.Name("let"),var:new O0.Name("var")};class o6{constructor({prefixes:$,parent:w}={}){this._names={},this._prefixes=$,this._parent=w}toName($){return $ instanceof O0.Name?$:this.name($)}name($){return new O0.Name(this._newName($))}_newName($){let w=this._names[$]||this._nameGroup($);return`${$}${w.index++}`}_nameGroup($){var w,Z;if(((Z=(w=this._parent)===null||w===void 0?void 0:w._prefixes)===null||Z===void 0?void 0:Z.has($))||this._prefixes&&!this._prefixes.has($))throw Error(`CodeGen: prefix "${$}" is not allowed in this scope`);return this._names[$]={prefix:$,index:0}}}MX.Scope=o6;class e6 extends O0.Name{constructor($,w){super(w);this.prefix=$}setValue($,{property:w,itemIndex:Z}){this.value=$,this.scopePath=O0._`.${new O0.Name(w)}[${Z}]`}}MX.ValueScopeName=e6;var $T=O0._`\n`;class zX extends o6{constructor($){super($);this._values={},this._scope=$.scope,this.opts={...$,_n:$.lines?$T:O0.nil}}get(){return this._scope}name($){return new e6($,this._newName($))}value($,w){var Z;if(w.ref===void 0)throw Error("CodeGen: ref must be passed in value");let W=this.toName($),{prefix:X}=W,Y=(Z=w.key)!==null&&Z!==void 0?Z:w.ref,G=this._values[X];if(G){let z=G.get(Y);if(z)return z}else G=this._values[X]=new Map;G.set(Y,W);let J=this._scope[X]||(this._scope[X]=[]),Q=J.length;return J[Q]=w.ref,W.setValue(w,{property:X,itemIndex:Q}),W}getValue($,w){let Z=this._values[$];if(!Z)return;return Z.get(w)}scopeRefs($,w=this._values){return this._reduceValues(w,(Z)=>{if(Z.scopePath===void 0)throw Error(`CodeGen: name "${Z}" has no value`);return O0._`${$}${Z.scopePath}`})}scopeCode($=this._values,w,Z){return this._reduceValues($,(W)=>{if(W.value===void 0)throw Error(`CodeGen: name "${W}" has no value`);return W.value.code},w,Z)}_reduceValues($,w,Z={},W){let X=O0.nil;for(let Y in $){let G=$[Y];if(!G)continue;let J=Z[Y]=Z[Y]||new Map;G.forEach((Q)=>{if(J.has(Q))return;J.set(Q,_4.Started);let z=w(Q);if(z){let M=this.opts.es5?MX.varKinds.var:MX.varKinds.const;X=O0._`${X}${M} ${Q} = ${z};${this.opts._n}`}else if(z=W===null||W===void 0?void 0:W(Q))X=O0._`${X}${z}${this.opts._n}`;else throw new QX(Q);J.set(Q,_4.Completed)})}return X}}MX.ValueScope=zX});var v=L((E0)=>{Object.defineProperty(E0,"__esModule",{value:!0});E0.or=E0.and=E0.not=E0.CodeGen=E0.operators=E0.varKinds=E0.ValueScopeName=E0.ValueScope=E0.Scope=E0.Name=E0.regexpCode=E0.stringify=E0.getProperty=E0.nil=E0.strConcat=E0.str=E0._=void 0;var m=Aw(),i0=$Z(),L$=Aw();Object.defineProperty(E0,"_",{enumerable:!0,get:function(){return L$._}});Object.defineProperty(E0,"str",{enumerable:!0,get:function(){return L$.str}});Object.defineProperty(E0,"strConcat",{enumerable:!0,get:function(){return L$.strConcat}});Object.defineProperty(E0,"nil",{enumerable:!0,get:function(){return L$.nil}});Object.defineProperty(E0,"getProperty",{enumerable:!0,get:function(){return L$.getProperty}});Object.defineProperty(E0,"stringify",{enumerable:!0,get:function(){return L$.stringify}});Object.defineProperty(E0,"regexpCode",{enumerable:!0,get:function(){return L$.regexpCode}});Object.defineProperty(E0,"Name",{enumerable:!0,get:function(){return L$.Name}});var m4=$Z();Object.defineProperty(E0,"Scope",{enumerable:!0,get:function(){return m4.Scope}});Object.defineProperty(E0,"ValueScope",{enumerable:!0,get:function(){return m4.ValueScope}});Object.defineProperty(E0,"ValueScopeName",{enumerable:!0,get:function(){return m4.ValueScopeName}});Object.defineProperty(E0,"varKinds",{enumerable:!0,get:function(){return m4.varKinds}});E0.operators={GT:new m._Code(">"),GTE:new m._Code(">="),LT:new m._Code("<"),LTE:new m._Code("<="),EQ:new m._Code("==="),NEQ:new m._Code("!=="),NOT:new m._Code("!"),OR:new m._Code("||"),AND:new m._Code("&&"),ADD:new m._Code("+")};class D${optimizeNodes(){return this}optimizeNames($,w){return this}}class NX extends D${constructor($,w,Z){super();this.varKind=$,this.name=w,this.rhs=Z}render({es5:$,_n:w}){let Z=$?i0.varKinds.var:this.varKind,W=this.rhs===void 0?"":` = ${this.rhs}`;return`${Z} ${this.name}${W};`+w}optimizeNames($,w){if(!$[this.name.str])return;if(this.rhs)this.rhs=I1(this.rhs,$,w);return this}get names(){return this.rhs instanceof m._CodeOrName?this.rhs.names:{}}}class WZ extends D${constructor($,w,Z){super();this.lhs=$,this.rhs=w,this.sideEffects=Z}render({_n:$}){return`${this.lhs} = ${this.rhs};`+$}optimizeNames($,w){if(this.lhs instanceof m.Name&&!$[this.lhs.str]&&!this.sideEffects)return;return this.rhs=I1(this.rhs,$,w),this}get names(){let $=this.lhs instanceof m.Name?{}:{...this.lhs.names};return i4($,this.rhs)}}class KX extends WZ{constructor($,w,Z,W){super($,Z,W);this.op=w}render({_n:$}){return`${this.lhs} ${this.op}= ${this.rhs};`+$}}class BX extends D${constructor($){super();this.label=$,this.names={}}render({_n:$}){return`${this.label}:`+$}}class VX extends D${constructor($){super();this.label=$,this.names={}}render({_n:$}){return`break${this.label?` ${this.label}`:""};`+$}}class PX extends D${constructor($){super();this.error=$}render({_n:$}){return`throw ${this.error};`+$}get names(){return this.error.names}}class qX extends D${constructor($){super();this.code=$}render({_n:$}){return`${this.code};`+$}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames($,w){return this.code=I1(this.code,$,w),this}get names(){return this.code instanceof m._CodeOrName?this.code.names:{}}}class l4 extends D${constructor($=[]){super();this.nodes=$}render($){return this.nodes.reduce((w,Z)=>w+Z.render($),"")}optimizeNodes(){let{nodes:$}=this,w=$.length;while(w--){let Z=$[w].optimizeNodes();if(Array.isArray(Z))$.splice(w,1,...Z);else if(Z)$[w]=Z;else $.splice(w,1)}return $.length>0?this:void 0}optimizeNames($,w){let{nodes:Z}=this,W=Z.length;while(W--){let X=Z[W];if(X.optimizeNames($,w))continue;XT($,X.names),Z.splice(W,1)}return Z.length>0?this:void 0}get names(){return this.nodes.reduce(($,w)=>n$($,w.names),{})}}class f$ extends l4{render($){return"{"+$._n+super.render($)+"}"+$._n}}class UX extends l4{}class Sw extends f${}Sw.kind="else";class X$ extends f${constructor($,w){super(w);this.condition=$}render($){let w=`if(${this.condition})`+super.render($);if(this.else)w+="else "+this.else.render($);return w}optimizeNodes(){super.optimizeNodes();let $=this.condition;if($===!0)return this.nodes;let w=this.else;if(w){let Z=w.optimizeNodes();w=this.else=Array.isArray(Z)?new Sw(Z):Z}if(w){if($===!1)return w instanceof X$?w:w.nodes;if(this.nodes.length)return this;return new X$(LX($),w instanceof X$?[w]:w.nodes)}if($===!1||!this.nodes.length)return;return this}optimizeNames($,w){var Z;if(this.else=(Z=this.else)===null||Z===void 0?void 0:Z.optimizeNames($,w),!(super.optimizeNames($,w)||this.else))return;return this.condition=I1(this.condition,$,w),this}get names(){let $=super.names;if(i4($,this.condition),this.else)n$($,this.else.names);return $}}X$.kind="if";class j1 extends f${}j1.kind="for";class HX extends j1{constructor($){super();this.iteration=$}render($){return`for(${this.iteration})`+super.render($)}optimizeNames($,w){if(!super.optimizeNames($,w))return;return this.iteration=I1(this.iteration,$,w),this}get names(){return n$(super.names,this.iteration.names)}}class FX extends j1{constructor($,w,Z,W){super();this.varKind=$,this.name=w,this.from=Z,this.to=W}render($){let w=$.es5?i0.varKinds.var:this.varKind,{name:Z,from:W,to:X}=this;return`for(${w} ${Z}=${W}; ${Z}<${X}; ${Z}++)`+super.render($)}get names(){let $=i4(super.names,this.from);return i4($,this.to)}}class wZ extends j1{constructor($,w,Z,W){super();this.loop=$,this.varKind=w,this.name=Z,this.iterable=W}render($){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render($)}optimizeNames($,w){if(!super.optimizeNames($,w))return;return this.iterable=I1(this.iterable,$,w),this}get names(){return n$(super.names,this.iterable.names)}}class g4 extends f${constructor($,w,Z){super();this.name=$,this.args=w,this.async=Z}render($){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render($)}}g4.kind="func";class v4 extends l4{render($){return"return "+super.render($)}}v4.kind="return";class OX extends f${render($){let w="try"+super.render($);if(this.catch)w+=this.catch.render($);if(this.finally)w+=this.finally.render($);return w}optimizeNodes(){var $,w;return super.optimizeNodes(),($=this.catch)===null||$===void 0||$.optimizeNodes(),(w=this.finally)===null||w===void 0||w.optimizeNodes(),this}optimizeNames($,w){var Z,W;return super.optimizeNames($,w),(Z=this.catch)===null||Z===void 0||Z.optimizeNames($,w),(W=this.finally)===null||W===void 0||W.optimizeNames($,w),this}get names(){let $=super.names;if(this.catch)n$($,this.catch.names);if(this.finally)n$($,this.finally.names);return $}}class u4 extends f${constructor($){super();this.error=$}render($){return`catch(${this.error})`+super.render($)}}u4.kind="catch";class h4 extends f${render($){return"finally"+super.render($)}}h4.kind="finally";class EX{constructor($,w={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...w,_n:w.lines?`
|
|
29
|
+
`:""},this._extScope=$,this._scope=new i0.Scope({parent:$}),this._nodes=[new UX]}toString(){return this._root.render(this.opts)}name($){return this._scope.name($)}scopeName($){return this._extScope.name($)}scopeValue($,w){let Z=this._extScope.value($,w);return(this._values[Z.prefix]||(this._values[Z.prefix]=new Set)).add(Z),Z}getScopeValue($,w){return this._extScope.getValue($,w)}scopeRefs($){return this._extScope.scopeRefs($,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def($,w,Z,W){let X=this._scope.toName(w);if(Z!==void 0&&W)this._constants[X.str]=Z;return this._leafNode(new NX($,X,Z)),X}const($,w,Z){return this._def(i0.varKinds.const,$,w,Z)}let($,w,Z){return this._def(i0.varKinds.let,$,w,Z)}var($,w,Z){return this._def(i0.varKinds.var,$,w,Z)}assign($,w,Z){return this._leafNode(new WZ($,w,Z))}add($,w){return this._leafNode(new KX($,E0.operators.ADD,w))}code($){if(typeof $=="function")$();else if($!==m.nil)this._leafNode(new qX($));return this}object(...$){let w=["{"];for(let[Z,W]of $){if(w.length>1)w.push(",");if(w.push(Z),Z!==W||this.opts.es5)w.push(":"),(0,m.addCodeArg)(w,W)}return w.push("}"),new m._Code(w)}if($,w,Z){if(this._blockNode(new X$($)),w&&Z)this.code(w).else().code(Z).endIf();else if(w)this.code(w).endIf();else if(Z)throw Error('CodeGen: "else" body without "then" body');return this}elseIf($){return this._elseNode(new X$($))}else(){return this._elseNode(new Sw)}endIf(){return this._endBlockNode(X$,Sw)}_for($,w){if(this._blockNode($),w)this.code(w).endFor();return this}for($,w){return this._for(new HX($),w)}forRange($,w,Z,W,X=this.opts.es5?i0.varKinds.var:i0.varKinds.let){let Y=this._scope.toName($);return this._for(new FX(X,Y,w,Z),()=>W(Y))}forOf($,w,Z,W=i0.varKinds.const){let X=this._scope.toName($);if(this.opts.es5){let Y=w instanceof m.Name?w:this.var("_arr",w);return this.forRange("_i",0,m._`${Y}.length`,(G)=>{this.var(X,m._`${Y}[${G}]`),Z(X)})}return this._for(new wZ("of",W,X,w),()=>Z(X))}forIn($,w,Z,W=this.opts.es5?i0.varKinds.var:i0.varKinds.const){if(this.opts.ownProperties)return this.forOf($,m._`Object.keys(${w})`,Z);let X=this._scope.toName($);return this._for(new wZ("in",W,X,w),()=>Z(X))}endFor(){return this._endBlockNode(j1)}label($){return this._leafNode(new BX($))}break($){return this._leafNode(new VX($))}return($){let w=new v4;if(this._blockNode(w),this.code($),w.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(v4)}try($,w,Z){if(!w&&!Z)throw Error('CodeGen: "try" without "catch" and "finally"');let W=new OX;if(this._blockNode(W),this.code($),w){let X=this.name("e");this._currNode=W.catch=new u4(X),w(X)}if(Z)this._currNode=W.finally=new h4,this.code(Z);return this._endBlockNode(u4,h4)}throw($){return this._leafNode(new PX($))}block($,w){if(this._blockStarts.push(this._nodes.length),$)this.code($).endBlock(w);return this}endBlock($){let w=this._blockStarts.pop();if(w===void 0)throw Error("CodeGen: not in self-balancing block");let Z=this._nodes.length-w;if(Z<0||$!==void 0&&Z!==$)throw Error(`CodeGen: wrong number of nodes: ${Z} vs ${$} expected`);return this._nodes.length=w,this}func($,w=m.nil,Z,W){if(this._blockNode(new g4($,w,Z)),W)this.code(W).endFunc();return this}endFunc(){return this._endBlockNode(g4)}optimize($=1){while($-- >0)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode($){return this._currNode.nodes.push($),this}_blockNode($){this._currNode.nodes.push($),this._nodes.push($)}_endBlockNode($,w){let Z=this._currNode;if(Z instanceof $||w&&Z instanceof w)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${w?`${$.kind}/${w.kind}`:$.kind}"`)}_elseNode($){let w=this._currNode;if(!(w instanceof X$))throw Error('CodeGen: "else" without "if"');return this._currNode=w.else=$,this}get _root(){return this._nodes[0]}get _currNode(){let $=this._nodes;return $[$.length-1]}set _currNode($){let w=this._nodes;w[w.length-1]=$}}E0.CodeGen=EX;function n$($,w){for(let Z in w)$[Z]=($[Z]||0)+(w[Z]||0);return $}function i4($,w){return w instanceof m._CodeOrName?n$($,w.names):$}function I1($,w,Z){if($ instanceof m.Name)return W($);if(!X($))return $;return new m._Code($._items.reduce((Y,G)=>{if(G instanceof m.Name)G=W(G);if(G instanceof m._Code)Y.push(...G._items);else Y.push(G);return Y},[]));function W(Y){let G=Z[Y.str];if(G===void 0||w[Y.str]!==1)return Y;return delete w[Y.str],G}function X(Y){return Y instanceof m._Code&&Y._items.some((G)=>G instanceof m.Name&&w[G.str]===1&&Z[G.str]!==void 0)}}function XT($,w){for(let Z in w)$[Z]=($[Z]||0)-(w[Z]||0)}function LX($){return typeof $=="boolean"||typeof $=="number"||$===null?!$:m._`!${ZZ($)}`}E0.not=LX;var YT=DX(E0.operators.AND);function GT(...$){return $.reduce(YT)}E0.and=GT;var JT=DX(E0.operators.OR);function QT(...$){return $.reduce(JT)}E0.or=QT;function DX($){return(w,Z)=>w===m.nil?Z:Z===m.nil?w:m._`${ZZ(w)} ${$} ${ZZ(Z)}`}function ZZ($){return $ instanceof m.Name?$:m._`(${$})`}});var l=L((yX)=>{Object.defineProperty(yX,"__esModule",{value:!0});yX.checkStrictMode=yX.getErrorPath=yX.Type=yX.useFunc=yX.setEvaluated=yX.evaluatedPropsToName=yX.mergeEvaluated=yX.eachItem=yX.unescapeJsonPointer=yX.escapeJsonPointer=yX.escapeFragment=yX.unescapeFragment=yX.schemaRefOrVal=yX.schemaHasRulesButRef=yX.schemaHasRules=yX.checkUnknownRules=yX.alwaysValidSchema=yX.toHash=void 0;var n=v(),NT=Aw();function KT($){let w={};for(let Z of $)w[Z]=!0;return w}yX.toHash=KT;function BT($,w){if(typeof w=="boolean")return w;if(Object.keys(w).length===0)return!0;return SX($,w),!RX(w,$.self.RULES.all)}yX.alwaysValidSchema=BT;function SX($,w=$.schema){let{opts:Z,self:W}=$;if(!Z.strictSchema)return;if(typeof w==="boolean")return;let X=W.RULES.keywords;for(let Y in w)if(!X[Y])IX($,`unknown keyword: "${Y}"`)}yX.checkUnknownRules=SX;function RX($,w){if(typeof $=="boolean")return!$;for(let Z in $)if(w[Z])return!0;return!1}yX.schemaHasRules=RX;function VT($,w){if(typeof $=="boolean")return!$;for(let Z in $)if(Z!=="$ref"&&w.all[Z])return!0;return!1}yX.schemaHasRulesButRef=VT;function PT({topSchemaRef:$,schemaPath:w},Z,W,X){if(!X){if(typeof Z=="number"||typeof Z=="boolean")return Z;if(typeof Z=="string")return n._`${Z}`}return n._`${$}${w}${(0,n.getProperty)(W)}`}yX.schemaRefOrVal=PT;function qT($){return CX(decodeURIComponent($))}yX.unescapeFragment=qT;function UT($){return encodeURIComponent(YZ($))}yX.escapeFragment=UT;function YZ($){if(typeof $=="number")return`${$}`;return $.replace(/~/g,"~0").replace(/\//g,"~1")}yX.escapeJsonPointer=YZ;function CX($){return $.replace(/~1/g,"/").replace(/~0/g,"~")}yX.unescapeJsonPointer=CX;function HT($,w){if(Array.isArray($))for(let Z of $)w(Z);else w($)}yX.eachItem=HT;function kX({mergeNames:$,mergeToName:w,mergeValues:Z,resultToName:W}){return(X,Y,G,J)=>{let Q=G===void 0?Y:G instanceof n.Name?(Y instanceof n.Name?$(X,Y,G):w(X,Y,G),G):Y instanceof n.Name?(w(X,G,Y),Y):Z(Y,G);return J===n.Name&&!(Q instanceof n.Name)?W(X,Q):Q}}yX.mergeEvaluated={props:kX({mergeNames:($,w,Z)=>$.if(n._`${Z} !== true && ${w} !== undefined`,()=>{$.if(n._`${w} === true`,()=>$.assign(Z,!0),()=>$.assign(Z,n._`${Z} || {}`).code(n._`Object.assign(${Z}, ${w})`))}),mergeToName:($,w,Z)=>$.if(n._`${Z} !== true`,()=>{if(w===!0)$.assign(Z,!0);else $.assign(Z,n._`${Z} || {}`),GZ($,Z,w)}),mergeValues:($,w)=>$===!0?!0:{...$,...w},resultToName:jX}),items:kX({mergeNames:($,w,Z)=>$.if(n._`${Z} !== true && ${w} !== undefined`,()=>$.assign(Z,n._`${w} === true ? true : ${Z} > ${w} ? ${Z} : ${w}`)),mergeToName:($,w,Z)=>$.if(n._`${Z} !== true`,()=>$.assign(Z,w===!0?!0:n._`${Z} > ${w} ? ${Z} : ${w}`)),mergeValues:($,w)=>$===!0?!0:Math.max($,w),resultToName:($,w)=>$.var("items",w)})};function jX($,w){if(w===!0)return $.var("props",!0);let Z=$.var("props",n._`{}`);if(w!==void 0)GZ($,Z,w);return Z}yX.evaluatedPropsToName=jX;function GZ($,w,Z){Object.keys(Z).forEach((W)=>$.assign(n._`${w}${(0,n.getProperty)(W)}`,!0))}yX.setEvaluated=GZ;var AX={};function FT($,w){return $.scopeValue("func",{ref:w,code:AX[w.code]||(AX[w.code]=new NT._Code(w.code))})}yX.useFunc=FT;var XZ;(function($){$[$.Num=0]="Num",$[$.Str=1]="Str"})(XZ||(yX.Type=XZ={}));function OT($,w,Z){if($ instanceof n.Name){let W=w===XZ.Num;return Z?W?n._`"[" + ${$} + "]"`:n._`"['" + ${$} + "']"`:W?n._`"/" + ${$}`:n._`"/" + ${$}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return Z?(0,n.getProperty)($).toString():"/"+YZ($)}yX.getErrorPath=OT;function IX($,w,Z=$.opts.strictSchema){if(!Z)return;if(w=`strict mode: ${w}`,Z===!0)throw Error(w);$.self.logger.warn(w)}yX.checkStrictMode=IX});var Y$=L((xX)=>{Object.defineProperty(xX,"__esModule",{value:!0});var N0=v(),uT={data:new N0.Name("data"),valCxt:new N0.Name("valCxt"),instancePath:new N0.Name("instancePath"),parentData:new N0.Name("parentData"),parentDataProperty:new N0.Name("parentDataProperty"),rootData:new N0.Name("rootData"),dynamicAnchors:new N0.Name("dynamicAnchors"),vErrors:new N0.Name("vErrors"),errors:new N0.Name("errors"),this:new N0.Name("this"),self:new N0.Name("self"),scope:new N0.Name("scope"),json:new N0.Name("json"),jsonPos:new N0.Name("jsonPos"),jsonLen:new N0.Name("jsonLen"),jsonPart:new N0.Name("jsonPart")};xX.default=uT});var Rw=L((uX)=>{Object.defineProperty(uX,"__esModule",{value:!0});uX.extendErrors=uX.resetErrorsCount=uX.reportExtraError=uX.reportError=uX.keyword$DataError=uX.keywordError=void 0;var c=v(),d4=l(),U0=Y$();uX.keywordError={message:({keyword:$})=>c.str`must pass "${$}" keyword validation`};uX.keyword$DataError={message:({keyword:$,schemaType:w})=>w?c.str`"${$}" keyword must be ${w} ($data)`:c.str`"${$}" keyword is invalid ($data)`};function iT($,w=uX.keywordError,Z,W){let{it:X}=$,{gen:Y,compositeRule:G,allErrors:J}=X,Q=vX($,w,Z);if(W!==null&&W!==void 0?W:G||J)_X(Y,Q);else gX(X,c._`[${Q}]`)}uX.reportError=iT;function mT($,w=uX.keywordError,Z){let{it:W}=$,{gen:X,compositeRule:Y,allErrors:G}=W,J=vX($,w,Z);if(_X(X,J),!(Y||G))gX(W,U0.default.vErrors)}uX.reportExtraError=mT;function lT($,w){$.assign(U0.default.errors,w),$.if(c._`${U0.default.vErrors} !== null`,()=>$.if(w,()=>$.assign(c._`${U0.default.vErrors}.length`,w),()=>$.assign(U0.default.vErrors,null)))}uX.resetErrorsCount=lT;function cT({gen:$,keyword:w,schemaValue:Z,data:W,errsCount:X,it:Y}){if(X===void 0)throw Error("ajv implementation error");let G=$.name("err");$.forRange("i",X,U0.default.errors,(J)=>{if($.const(G,c._`${U0.default.vErrors}[${J}]`),$.if(c._`${G}.instancePath === undefined`,()=>$.assign(c._`${G}.instancePath`,(0,c.strConcat)(U0.default.instancePath,Y.errorPath))),$.assign(c._`${G}.schemaPath`,c.str`${Y.errSchemaPath}/${w}`),Y.opts.verbose)$.assign(c._`${G}.schema`,Z),$.assign(c._`${G}.data`,W)})}uX.extendErrors=cT;function _X($,w){let Z=$.const("err",w);$.if(c._`${U0.default.vErrors} === null`,()=>$.assign(U0.default.vErrors,c._`[${Z}]`),c._`${U0.default.vErrors}.push(${Z})`),$.code(c._`${U0.default.errors}++`)}function gX($,w){let{gen:Z,validateName:W,schemaEnv:X}=$;if(X.$async)Z.throw(c._`new ${$.ValidationError}(${w})`);else Z.assign(c._`${W}.errors`,w),Z.return(!1)}var t$={keyword:new c.Name("keyword"),schemaPath:new c.Name("schemaPath"),params:new c.Name("params"),propertyName:new c.Name("propertyName"),message:new c.Name("message"),schema:new c.Name("schema"),parentSchema:new c.Name("parentSchema")};function vX($,w,Z){let{createErrors:W}=$.it;if(W===!1)return c._`{}`;return dT($,w,Z)}function dT($,w,Z={}){let{gen:W,it:X}=$,Y=[pT(X,Z),nT($,Z)];return tT($,w,Y),W.object(...Y)}function pT({errorPath:$},{instancePath:w}){let Z=w?c.str`${$}${(0,d4.getErrorPath)(w,d4.Type.Str)}`:$;return[U0.default.instancePath,(0,c.strConcat)(U0.default.instancePath,Z)]}function nT({keyword:$,it:{errSchemaPath:w}},{schemaPath:Z,parentSchema:W}){let X=W?w:c.str`${w}/${$}`;if(Z)X=c.str`${X}${(0,d4.getErrorPath)(Z,d4.Type.Str)}`;return[t$.schemaPath,X]}function tT($,{params:w,message:Z},W){let{keyword:X,data:Y,schemaValue:G,it:J}=$,{opts:Q,propertyName:z,topSchemaRef:M,schemaPath:T}=J;if(W.push([t$.keyword,X],[t$.params,typeof w=="function"?w($):w||c._`{}`]),Q.messages)W.push([t$.message,typeof Z=="function"?Z($):Z]);if(Q.verbose)W.push([t$.schema,G],[t$.parentSchema,c._`${M}${T}`],[U0.default.data,Y]);if(z)W.push([t$.propertyName,z])}});var cX=L((mX)=>{Object.defineProperty(mX,"__esModule",{value:!0});mX.boolOrEmptySchema=mX.topBoolOrEmptySchema=void 0;var eT=Rw(),$N=v(),wN=Y$(),ZN={message:"boolean schema is false"};function WN($){let{gen:w,schema:Z,validateName:W}=$;if(Z===!1)iX($,!1);else if(typeof Z=="object"&&Z.$async===!0)w.return(wN.default.data);else w.assign($N._`${W}.errors`,null),w.return(!0)}mX.topBoolOrEmptySchema=WN;function XN($,w){let{gen:Z,schema:W}=$;if(W===!1)Z.var(w,!1),iX($);else Z.var(w,!0)}mX.boolOrEmptySchema=XN;function iX($,w){let{gen:Z,data:W}=$,X={gen:Z,keyword:"false schema",data:W,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:$};(0,eT.reportError)(X,ZN,void 0,w)}});var QZ=L((dX)=>{Object.defineProperty(dX,"__esModule",{value:!0});dX.getRules=dX.isJSONType=void 0;var GN=["string","number","integer","boolean","null","object","array"],JN=new Set(GN);function QN($){return typeof $=="string"&&JN.has($)}dX.isJSONType=QN;function zN(){let $={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...$,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},$.number,$.string,$.array,$.object],post:{rules:[]},all:{},keywords:{}}}dX.getRules=zN});var zZ=L((rX)=>{Object.defineProperty(rX,"__esModule",{value:!0});rX.shouldUseRule=rX.shouldUseGroup=rX.schemaHasRulesForType=void 0;function TN({schema:$,self:w},Z){let W=w.RULES.types[Z];return W&&W!==!0&&nX($,W)}rX.schemaHasRulesForType=TN;function nX($,w){return w.rules.some((Z)=>tX($,Z))}rX.shouldUseGroup=nX;function tX($,w){var Z;return $[w.keyword]!==void 0||((Z=w.definition.implements)===null||Z===void 0?void 0:Z.some((W)=>$[W]!==void 0))}rX.shouldUseRule=tX});var Cw=L(($Y)=>{Object.defineProperty($Y,"__esModule",{value:!0});$Y.reportTypeError=$Y.checkDataTypes=$Y.checkDataType=$Y.coerceAndCheckDataType=$Y.getJSONTypes=$Y.getSchemaTypes=$Y.DataType=void 0;var BN=QZ(),VN=zZ(),PN=Rw(),_=v(),aX=l(),y1;(function($){$[$.Correct=0]="Correct",$[$.Wrong=1]="Wrong"})(y1||($Y.DataType=y1={}));function qN($){let w=oX($.type);if(w.includes("null")){if($.nullable===!1)throw Error("type: null contradicts nullable: false")}else{if(!w.length&&$.nullable!==void 0)throw Error('"nullable" cannot be used without "type"');if($.nullable===!0)w.push("null")}return w}$Y.getSchemaTypes=qN;function oX($){let w=Array.isArray($)?$:$?[$]:[];if(w.every(BN.isJSONType))return w;throw Error("type must be JSONType or JSONType[]: "+w.join(","))}$Y.getJSONTypes=oX;function UN($,w){let{gen:Z,data:W,opts:X}=$,Y=HN(w,X.coerceTypes),G=w.length>0&&!(Y.length===0&&w.length===1&&(0,VN.schemaHasRulesForType)($,w[0]));if(G){let J=TZ(w,W,X.strictNumbers,y1.Wrong);Z.if(J,()=>{if(Y.length)FN($,w,Y);else NZ($)})}return G}$Y.coerceAndCheckDataType=UN;var eX=new Set(["string","number","integer","boolean","null"]);function HN($,w){return w?$.filter((Z)=>eX.has(Z)||w==="array"&&Z==="array"):[]}function FN($,w,Z){let{gen:W,data:X,opts:Y}=$,G=W.let("dataType",_._`typeof ${X}`),J=W.let("coerced",_._`undefined`);if(Y.coerceTypes==="array")W.if(_._`${G} == 'object' && Array.isArray(${X}) && ${X}.length == 1`,()=>W.assign(X,_._`${X}[0]`).assign(G,_._`typeof ${X}`).if(TZ(w,X,Y.strictNumbers),()=>W.assign(J,X)));W.if(_._`${J} !== undefined`);for(let z of Z)if(eX.has(z)||z==="array"&&Y.coerceTypes==="array")Q(z);W.else(),NZ($),W.endIf(),W.if(_._`${J} !== undefined`,()=>{W.assign(X,J),ON($,J)});function Q(z){switch(z){case"string":W.elseIf(_._`${G} == "number" || ${G} == "boolean"`).assign(J,_._`"" + ${X}`).elseIf(_._`${X} === null`).assign(J,_._`""`);return;case"number":W.elseIf(_._`${G} == "boolean" || ${X} === null
|
|
30
30
|
|| (${G} == "string" && ${X} && ${X} == +${X})`).assign(J,_._`+${X}`);return;case"integer":W.elseIf(_._`${G} === "boolean" || ${X} === null
|
|
31
31
|
|| (${G} === "string" && ${X} && ${X} == +${X} && !(${X} % 1))`).assign(J,_._`+${X}`);return;case"boolean":W.elseIf(_._`${X} === "false" || ${X} === 0 || ${X} === null`).assign(J,!1).elseIf(_._`${X} === "true" || ${X} === 1`).assign(J,!0);return;case"null":W.elseIf(_._`${X} === "" || ${X} === 0 || ${X} === false`),W.assign(J,null);return;case"array":W.elseIf(_._`${G} === "string" || ${G} === "number"
|
|
32
|
-
|| ${G} === "boolean" || ${X} === null`).assign(J,_._`[${X}]`)}}}function qK({gen:$,parentData:w,parentDataProperty:Z},W){$.if(_._`${w} !== undefined`,()=>$.assign(_._`${w}[${Z}]`,W))}function MZ($,w,Z,W=y1.Correct){let X=W===y1.Correct?_.operators.EQ:_.operators.NEQ,Y;switch($){case"null":return _._`${w} ${X} null`;case"array":Y=_._`Array.isArray(${w})`;break;case"object":Y=_._`${w} && typeof ${w} == "object" && !Array.isArray(${w})`;break;case"integer":Y=G(_._`!(${w} % 1) && !isNaN(${w})`);break;case"number":Y=G();break;default:return _._`typeof ${w} ${X} ${$}`}return W===y1.Correct?Y:(0,_.not)(Y);function G(J=_.nil){return(0,_.and)(_._`typeof ${w} == "number"`,J,Z?_._`isFinite(${w})`:_.nil)}}oX.checkDataType=MZ;function TZ($,w,Z,W){if($.length===1)return MZ($[0],w,Z,W);let X,Y=(0,rX.toHash)($);if(Y.array&&Y.object){let G=_._`typeof ${w} != "object"`;X=Y.null?G:_._`!${w} || ${G}`,delete Y.null,delete Y.array,delete Y.object}else X=_.nil;if(Y.number)delete Y.integer;for(let G in Y)X=(0,_.and)(X,MZ(G,w,Z,W));return X}oX.checkDataTypes=TZ;var UK={message:({schema:$})=>`must be ${$}`,params:({schema:$,schemaValue:w})=>typeof $=="string"?_._`{type: ${$}}`:_._`{type: ${w}}`};function KZ($){let w=HK($);(0,KK.reportError)(w,UK)}oX.reportTypeError=KZ;function HK($){let{gen:w,data:Z,schema:W}=$,X=(0,rX.schemaRefOrVal)($,W,"type");return{gen:w,keyword:"type",data:Z,schema:W.type,schemaCode:X,schemaValue:X,parentSchema:W,params:{},it:$}}});var WY=L((wY)=>{Object.defineProperty(wY,"__esModule",{value:!0});wY.assignDefaults=void 0;var b1=v(),kK=l();function AK($,w){let{properties:Z,items:W}=$.schema;if(w==="object"&&Z)for(let X in Z)$Y($,X,Z[X].default);else if(w==="array"&&Array.isArray(W))W.forEach((X,Y)=>$Y($,Y,X.default))}wY.assignDefaults=AK;function $Y($,w,Z){let{gen:W,compositeRule:X,data:Y,opts:G}=$;if(Z===void 0)return;let J=b1._`${Y}${(0,b1.getProperty)(w)}`;if(X){(0,kK.checkStrictMode)($,`default is ignored for: ${J}`);return}let Q=b1._`${J} === undefined`;if(G.useDefaults==="empty")Q=b1._`${Q} || ${J} === null || ${J} === ""`;W.if(Q,b1._`${J} = ${(0,b1.stringify)(Z)}`)}});var _0=L((GY)=>{Object.defineProperty(GY,"__esModule",{value:!0});GY.validateUnion=GY.validateArray=GY.usePattern=GY.callValidateCode=GY.schemaProperties=GY.allSchemaProperties=GY.noPropertyInData=GY.propertyInData=GY.isOwnProperty=GY.hasPropFunc=GY.reportMissingProp=GY.checkMissingProp=GY.checkReportMissingProp=void 0;var t=v(),NZ=l(),k$=X$(),SK=l();function RK($,w){let{gen:Z,data:W,it:X}=$;Z.if(VZ(Z,W,w,X.opts.ownProperties),()=>{$.setParams({missingProperty:t._`${w}`},!0),$.error()})}GY.checkReportMissingProp=RK;function CK({gen:$,data:w,it:{opts:Z}},W,X){return(0,t.or)(...W.map((Y)=>(0,t.and)(VZ($,w,Y,Z.ownProperties),t._`${X} = ${Y}`)))}GY.checkMissingProp=CK;function jK($,w){$.setParams({missingProperty:w},!0),$.error()}GY.reportMissingProp=jK;function XY($){return $.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:t._`Object.prototype.hasOwnProperty`})}GY.hasPropFunc=XY;function BZ($,w,Z){return t._`${XY($)}.call(${w}, ${Z})`}GY.isOwnProperty=BZ;function IK($,w,Z,W){let X=t._`${w}${(0,t.getProperty)(Z)} !== undefined`;return W?t._`${X} && ${BZ($,w,Z)}`:X}GY.propertyInData=IK;function VZ($,w,Z,W){let X=t._`${w}${(0,t.getProperty)(Z)} === undefined`;return W?(0,t.or)(X,(0,t.not)(BZ($,w,Z))):X}GY.noPropertyInData=VZ;function YY($){return $?Object.keys($).filter((w)=>w!=="__proto__"):[]}GY.allSchemaProperties=YY;function yK($,w){return YY(w).filter((Z)=>!(0,NZ.alwaysValidSchema)($,w[Z]))}GY.schemaProperties=yK;function bK({schemaCode:$,data:w,it:{gen:Z,topSchemaRef:W,schemaPath:X,errorPath:Y},it:G},J,Q,z){let M=z?t._`${$}, ${w}, ${W}${X}`:w,T=[[k$.default.instancePath,(0,t.strConcat)(k$.default.instancePath,Y)],[k$.default.parentData,G.parentData],[k$.default.parentDataProperty,G.parentDataProperty],[k$.default.rootData,k$.default.rootData]];if(G.opts.dynamicRef)T.push([k$.default.dynamicAnchors,k$.default.dynamicAnchors]);let K=t._`${M}, ${Z.object(...T)}`;return Q!==t.nil?t._`${J}.call(${Q}, ${K})`:t._`${J}(${K})`}GY.callValidateCode=bK;var xK=t._`new RegExp`;function _K({gen:$,it:{opts:w}},Z){let W=w.unicodeRegExp?"u":"",{regExp:X}=w.code,Y=X(Z,W);return $.scopeValue("pattern",{key:Y.toString(),ref:Y,code:t._`${X.code==="new RegExp"?xK:(0,SK.useFunc)($,X)}(${Z}, ${W})`})}GY.usePattern=_K;function gK($){let{gen:w,data:Z,keyword:W,it:X}=$,Y=w.name("valid");if(X.allErrors){let J=w.let("valid",!0);return G(()=>w.assign(J,!1)),J}return w.var(Y,!0),G(()=>w.break()),Y;function G(J){let Q=w.const("len",t._`${Z}.length`);w.forRange("i",0,Q,(z)=>{$.subschema({keyword:W,dataProp:z,dataPropType:NZ.Type.Num},Y),w.if((0,t.not)(Y),J)})}}GY.validateArray=gK;function vK($){let{gen:w,schema:Z,keyword:W,it:X}=$;if(!Array.isArray(Z))throw Error("ajv implementation error");if(Z.some((Q)=>(0,NZ.alwaysValidSchema)(X,Q))&&!X.opts.unevaluated)return;let G=w.let("valid",!1),J=w.name("_valid");w.block(()=>Z.forEach((Q,z)=>{let M=$.subschema({keyword:W,schemaProp:z,compositeRule:!0},J);if(w.assign(G,t._`${G} || ${J}`),!$.mergeValidEvaluated(M,J))w.if((0,t.not)(G))})),$.result(G,()=>$.reset(),()=>$.error(!0))}GY.validateUnion=vK});var KY=L((MY)=>{Object.defineProperty(MY,"__esModule",{value:!0});MY.validateKeywordUsage=MY.validSchemaType=MY.funcKeywordCode=MY.macroKeywordCode=void 0;var H0=v(),r$=X$(),aK=_0(),oK=Rw();function eK($,w){let{gen:Z,keyword:W,schema:X,parentSchema:Y,it:G}=$,J=w.macro.call(G.self,X,Y,G),Q=zY(Z,W,J);if(G.opts.validateSchema!==!1)G.self.validateSchema(J,!0);let z=Z.name("valid");$.subschema({schema:J,schemaPath:H0.nil,errSchemaPath:`${G.errSchemaPath}/${W}`,topSchemaRef:Q,compositeRule:!0},z),$.pass(z,()=>$.error(!0))}MY.macroKeywordCode=eK;function $N($,w){var Z;let{gen:W,keyword:X,schema:Y,parentSchema:G,$data:J,it:Q}=$;ZN(Q,w);let z=!J&&w.compile?w.compile.call(Q.self,Y,G,Q):w.validate,M=zY(W,X,z),T=W.let("valid");$.block$data(T,K),$.ok((Z=w.valid)!==null&&Z!==void 0?Z:T);function K(){if(w.errors===!1){if(P(),w.modifying)QY($);q(()=>$.error())}else{let U=w.async?N():B();if(w.modifying)QY($);q(()=>wN($,U))}}function N(){let U=W.let("ruleErrs",null);return W.try(()=>P(H0._`await `),(O)=>W.assign(T,!1).if(H0._`${O} instanceof ${Q.ValidationError}`,()=>W.assign(U,H0._`${O}.errors`),()=>W.throw(O))),U}function B(){let U=H0._`${M}.errors`;return W.assign(U,null),P(H0.nil),U}function P(U=w.async?H0._`await `:H0.nil){let O=Q.opts.passContext?r$.default.this:r$.default.self,f=!(("compile"in w)&&!J||w.schema===!1);W.assign(T,H0._`${U}${(0,aK.callValidateCode)($,M,O,f)}`,w.modifying)}function q(U){var O;W.if((0,H0.not)((O=w.valid)!==null&&O!==void 0?O:T),U)}}MY.funcKeywordCode=$N;function QY($){let{gen:w,data:Z,it:W}=$;w.if(W.parentData,()=>w.assign(Z,H0._`${W.parentData}[${W.parentDataProperty}]`))}function wN($,w){let{gen:Z}=$;Z.if(H0._`Array.isArray(${w})`,()=>{Z.assign(r$.default.vErrors,H0._`${r$.default.vErrors} === null ? ${w} : ${r$.default.vErrors}.concat(${w})`).assign(r$.default.errors,H0._`${r$.default.vErrors}.length`),(0,oK.extendErrors)($)},()=>$.error())}function ZN({schemaEnv:$},w){if(w.async&&!$.$async)throw Error("async keyword in sync schema")}function zY($,w,Z){if(Z===void 0)throw Error(`keyword "${w}" failed to compile`);return $.scopeValue("keyword",typeof Z=="function"?{ref:Z}:{ref:Z,code:(0,H0.stringify)(Z)})}function WN($,w,Z=!1){return!w.length||w.some((W)=>W==="array"?Array.isArray($):W==="object"?$&&typeof $=="object"&&!Array.isArray($):typeof $==W||Z&&typeof $>"u")}MY.validSchemaType=WN;function XN({schema:$,opts:w,self:Z,errSchemaPath:W},X,Y){if(Array.isArray(X.keyword)?!X.keyword.includes(Y):X.keyword!==Y)throw Error("ajv implementation error");let G=X.dependencies;if(G===null||G===void 0?void 0:G.some((J)=>!Object.prototype.hasOwnProperty.call($,J)))throw Error(`parent schema must have dependencies of ${Y}: ${G.join(",")}`);if(X.validateSchema){if(!X.validateSchema($[Y])){let Q=`keyword "${Y}" value is invalid at path "${W}": `+Z.errorsText(X.validateSchema.errors);if(w.validateSchema==="log")Z.logger.error(Q);else throw Error(Q)}}}MY.validateKeywordUsage=XN});var PY=L((BY)=>{Object.defineProperty(BY,"__esModule",{value:!0});BY.extendSubschemaMode=BY.extendSubschemaData=BY.getSubschema=void 0;var n0=v(),NY=l();function QN($,{keyword:w,schemaProp:Z,schema:W,schemaPath:X,errSchemaPath:Y,topSchemaRef:G}){if(w!==void 0&&W!==void 0)throw Error('both "keyword" and "schema" passed, only one allowed');if(w!==void 0){let J=$.schema[w];return Z===void 0?{schema:J,schemaPath:n0._`${$.schemaPath}${(0,n0.getProperty)(w)}`,errSchemaPath:`${$.errSchemaPath}/${w}`}:{schema:J[Z],schemaPath:n0._`${$.schemaPath}${(0,n0.getProperty)(w)}${(0,n0.getProperty)(Z)}`,errSchemaPath:`${$.errSchemaPath}/${w}/${(0,NY.escapeFragment)(Z)}`}}if(W!==void 0){if(X===void 0||Y===void 0||G===void 0)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:W,schemaPath:X,topSchemaRef:G,errSchemaPath:Y}}throw Error('either "keyword" or "schema" must be passed')}BY.getSubschema=QN;function zN($,w,{dataProp:Z,dataPropType:W,data:X,dataTypes:Y,propertyName:G}){if(X!==void 0&&Z!==void 0)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:J}=w;if(Z!==void 0){let{errorPath:z,dataPathArr:M,opts:T}=w,K=J.let("data",n0._`${w.data}${(0,n0.getProperty)(Z)}`,!0);Q(K),$.errorPath=n0.str`${z}${(0,NY.getErrorPath)(Z,W,T.jsPropertySyntax)}`,$.parentDataProperty=n0._`${Z}`,$.dataPathArr=[...M,$.parentDataProperty]}if(X!==void 0){let z=X instanceof n0.Name?X:J.let("data",X,!0);if(Q(z),G!==void 0)$.propertyName=G}if(Y)$.dataTypes=Y;function Q(z){$.data=z,$.dataLevel=w.dataLevel+1,$.dataTypes=[],w.definedProperties=new Set,$.parentData=w.data,$.dataNames=[...w.dataNames,z]}}BY.extendSubschemaData=zN;function MN($,{jtdDiscriminator:w,jtdMetadata:Z,compositeRule:W,createErrors:X,allErrors:Y}){if(W!==void 0)$.compositeRule=W;if(X!==void 0)$.createErrors=X;if(Y!==void 0)$.allErrors=Y;$.jtdDiscriminator=w,$.jtdMetadata=Z}BY.extendSubschemaMode=MN});var PZ=L((SL,qY)=>{qY.exports=function $(w,Z){if(w===Z)return!0;if(w&&Z&&typeof w=="object"&&typeof Z=="object"){if(w.constructor!==Z.constructor)return!1;var W,X,Y;if(Array.isArray(w)){if(W=w.length,W!=Z.length)return!1;for(X=W;X--!==0;)if(!$(w[X],Z[X]))return!1;return!0}if(w.constructor===RegExp)return w.source===Z.source&&w.flags===Z.flags;if(w.valueOf!==Object.prototype.valueOf)return w.valueOf()===Z.valueOf();if(w.toString!==Object.prototype.toString)return w.toString()===Z.toString();if(Y=Object.keys(w),W=Y.length,W!==Object.keys(Z).length)return!1;for(X=W;X--!==0;)if(!Object.prototype.hasOwnProperty.call(Z,Y[X]))return!1;for(X=W;X--!==0;){var G=Y[X];if(!$(w[G],Z[G]))return!1}return!0}return w!==w&&Z!==Z}});var HY=L((RL,UY)=>{var A$=UY.exports=function($,w,Z){if(typeof w=="function")Z=w,w={};Z=w.cb||Z;var W=typeof Z=="function"?Z:Z.pre||function(){},X=Z.post||function(){};p4(w,W,X,$,"",$)};A$.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};A$.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};A$.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};A$.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function p4($,w,Z,W,X,Y,G,J,Q,z){if(W&&typeof W=="object"&&!Array.isArray(W)){w(W,X,Y,G,J,Q,z);for(var M in W){var T=W[M];if(Array.isArray(T)){if(M in A$.arrayKeywords)for(var K=0;K<T.length;K++)p4($,w,Z,T[K],X+"/"+M+"/"+K,Y,X,M,W,K)}else if(M in A$.propsKeywords){if(T&&typeof T=="object")for(var N in T)p4($,w,Z,T[N],X+"/"+M+"/"+NN(N),Y,X,M,W,N)}else if(M in A$.keywords||$.allKeys&&!(M in A$.skipKeywords))p4($,w,Z,T,X+"/"+M,Y,X,M,W)}Z(W,X,Y,G,J,Q,z)}}function NN($){return $.replace(/~/g,"~0").replace(/\//g,"~1")}});var jw=L((LY)=>{Object.defineProperty(LY,"__esModule",{value:!0});LY.getSchemaRefs=LY.resolveUrl=LY.normalizeId=LY._getFullPath=LY.getFullPath=LY.inlineRef=void 0;var BN=l(),VN=PZ(),PN=HY(),qN=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function UN($,w=!0){if(typeof $=="boolean")return!0;if(w===!0)return!qZ($);if(!w)return!1;return FY($)<=w}LY.inlineRef=UN;var HN=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function qZ($){for(let w in $){if(HN.has(w))return!0;let Z=$[w];if(Array.isArray(Z)&&Z.some(qZ))return!0;if(typeof Z=="object"&&qZ(Z))return!0}return!1}function FY($){let w=0;for(let Z in $){if(Z==="$ref")return 1/0;if(w++,qN.has(Z))continue;if(typeof $[Z]=="object")(0,BN.eachItem)($[Z],(W)=>w+=FY(W));if(w===1/0)return 1/0}return w}function OY($,w="",Z){if(Z!==!1)w=x1(w);let W=$.parse(w);return EY($,W)}LY.getFullPath=OY;function EY($,w){return $.serialize(w).split("#")[0]+"#"}LY._getFullPath=EY;var FN=/#\/?$/;function x1($){return $?$.replace(FN,""):""}LY.normalizeId=x1;function ON($,w,Z){return Z=x1(Z),$.resolve(w,Z)}LY.resolveUrl=ON;var EN=/^[a-z_][-a-z0-9._]*$/i;function LN($,w){if(typeof $=="boolean")return{};let{schemaId:Z,uriResolver:W}=this.opts,X=x1($[Z]||w),Y={"":X},G=OY(W,X,!1),J={},Q=new Set;return PN($,{allKeys:!0},(T,K,N,B)=>{if(B===void 0)return;let P=G+K,q=Y[B];if(typeof T[Z]=="string")q=U.call(this,T[Z]);O.call(this,T.$anchor),O.call(this,T.$dynamicAnchor),Y[K]=q;function U(f){let C=this.opts.uriResolver.resolve;if(f=x1(q?C(q,f):f),Q.has(f))throw M(f);Q.add(f);let A=this.refs[f];if(typeof A=="string")A=this.refs[A];if(typeof A=="object")z(T,A.schema,f);else if(f!==x1(P))if(f[0]==="#")z(T,J[f],f),J[f]=T;else this.refs[f]=P;return f}function O(f){if(typeof f=="string"){if(!EN.test(f))throw Error(`invalid anchor "${f}"`);U.call(this,`#${f}`)}}}),J;function z(T,K,N){if(K!==void 0&&!VN(T,K))throw M(N)}function M(T){return Error(`reference "${T}" resolves to more than one schema`)}}LY.getSchemaRefs=LN});var bw=L((uY)=>{Object.defineProperty(uY,"__esModule",{value:!0});uY.getData=uY.KeywordCxt=uY.validateFunctionCode=void 0;var RY=mX(),fY=Cw(),HZ=zZ(),n4=Cw(),RN=WY(),yw=KY(),UZ=PY(),S=v(),b=X$(),CN=jw(),Y$=l(),Iw=Rw();function jN($){if(IY($)){if(yY($),jY($)){bN($);return}}CY($,()=>(0,RY.topBoolOrEmptySchema)($))}uY.validateFunctionCode=jN;function CY({gen:$,validateName:w,schema:Z,schemaEnv:W,opts:X},Y){if(X.code.es5)$.func(w,S._`${b.default.data}, ${b.default.valCxt}`,W.$async,()=>{$.code(S._`"use strict"; ${kY(Z,X)}`),yN($,X),$.code(Y)});else $.func(w,S._`${b.default.data}, ${IN(X)}`,W.$async,()=>$.code(kY(Z,X)).code(Y))}function IN($){return S._`{${b.default.instancePath}="", ${b.default.parentData}, ${b.default.parentDataProperty}, ${b.default.rootData}=${b.default.data}${$.dynamicRef?S._`, ${b.default.dynamicAnchors}={}`:S.nil}}={}`}function yN($,w){$.if(b.default.valCxt,()=>{if($.var(b.default.instancePath,S._`${b.default.valCxt}.${b.default.instancePath}`),$.var(b.default.parentData,S._`${b.default.valCxt}.${b.default.parentData}`),$.var(b.default.parentDataProperty,S._`${b.default.valCxt}.${b.default.parentDataProperty}`),$.var(b.default.rootData,S._`${b.default.valCxt}.${b.default.rootData}`),w.dynamicRef)$.var(b.default.dynamicAnchors,S._`${b.default.valCxt}.${b.default.dynamicAnchors}`)},()=>{if($.var(b.default.instancePath,S._`""`),$.var(b.default.parentData,S._`undefined`),$.var(b.default.parentDataProperty,S._`undefined`),$.var(b.default.rootData,b.default.data),w.dynamicRef)$.var(b.default.dynamicAnchors,S._`{}`)})}function bN($){let{schema:w,opts:Z,gen:W}=$;CY($,()=>{if(Z.$comment&&w.$comment)xY($);if(uN($),W.let(b.default.vErrors,null),W.let(b.default.errors,0),Z.unevaluated)xN($);bY($),mN($)});return}function xN($){let{gen:w,validateName:Z}=$;$.evaluated=w.const("evaluated",S._`${Z}.evaluated`),w.if(S._`${$.evaluated}.dynamicProps`,()=>w.assign(S._`${$.evaluated}.props`,S._`undefined`)),w.if(S._`${$.evaluated}.dynamicItems`,()=>w.assign(S._`${$.evaluated}.items`,S._`undefined`))}function kY($,w){let Z=typeof $=="object"&&$[w.schemaId];return Z&&(w.code.source||w.code.process)?S._`/*# sourceURL=${Z} */`:S.nil}function _N($,w){if(IY($)){if(yY($),jY($)){gN($,w);return}}(0,RY.boolOrEmptySchema)($,w)}function jY({schema:$,self:w}){if(typeof $=="boolean")return!$;for(let Z in $)if(w.RULES.all[Z])return!0;return!1}function IY($){return typeof $.schema!="boolean"}function gN($,w){let{schema:Z,gen:W,opts:X}=$;if(X.$comment&&Z.$comment)xY($);hN($),iN($);let Y=W.const("_errs",b.default.errors);bY($,Y),W.var(w,S._`${Y} === ${b.default.errors}`)}function yY($){(0,Y$.checkUnknownRules)($),vN($)}function bY($,w){if($.opts.jtd)return AY($,[],!1,w);let Z=(0,fY.getSchemaTypes)($.schema),W=(0,fY.coerceAndCheckDataType)($,Z);AY($,Z,!W,w)}function vN($){let{schema:w,errSchemaPath:Z,opts:W,self:X}=$;if(w.$ref&&W.ignoreKeywordsWithRef&&(0,Y$.schemaHasRulesButRef)(w,X.RULES))X.logger.warn(`$ref: keywords ignored in schema at path "${Z}"`)}function uN($){let{schema:w,opts:Z}=$;if(w.default!==void 0&&Z.useDefaults&&Z.strictSchema)(0,Y$.checkStrictMode)($,"default is ignored in the schema root")}function hN($){let w=$.schema[$.opts.schemaId];if(w)$.baseId=(0,CN.resolveUrl)($.opts.uriResolver,$.baseId,w)}function iN($){if($.schema.$async&&!$.schemaEnv.$async)throw Error("async schema in sync schema")}function xY({gen:$,schemaEnv:w,schema:Z,errSchemaPath:W,opts:X}){let Y=Z.$comment;if(X.$comment===!0)$.code(S._`${b.default.self}.logger.log(${Y})`);else if(typeof X.$comment=="function"){let G=S.str`${W}/$comment`,J=$.scopeValue("root",{ref:w.root});$.code(S._`${b.default.self}.opts.$comment(${Y}, ${G}, ${J}.schema)`)}}function mN($){let{gen:w,schemaEnv:Z,validateName:W,ValidationError:X,opts:Y}=$;if(Z.$async)w.if(S._`${b.default.errors} === 0`,()=>w.return(b.default.data),()=>w.throw(S._`new ${X}(${b.default.vErrors})`));else{if(w.assign(S._`${W}.errors`,b.default.vErrors),Y.unevaluated)lN($);w.return(S._`${b.default.errors} === 0`)}}function lN({gen:$,evaluated:w,props:Z,items:W}){if(Z instanceof S.Name)$.assign(S._`${w}.props`,Z);if(W instanceof S.Name)$.assign(S._`${w}.items`,W)}function AY($,w,Z,W){let{gen:X,schema:Y,data:G,allErrors:J,opts:Q,self:z}=$,{RULES:M}=z;if(Y.$ref&&(Q.ignoreKeywordsWithRef||!(0,Y$.schemaHasRulesButRef)(Y,M))){X.block(()=>gY($,"$ref",M.all.$ref.definition));return}if(!Q.jtd)cN($,w);X.block(()=>{for(let K of M.rules)T(K);T(M.post)});function T(K){if(!(0,HZ.shouldUseGroup)(Y,K))return;if(K.type){if(X.if((0,n4.checkDataType)(K.type,G,Q.strictNumbers)),SY($,K),w.length===1&&w[0]===K.type&&Z)X.else(),(0,n4.reportTypeError)($);X.endIf()}else SY($,K);if(!J)X.if(S._`${b.default.errors} === ${W||0}`)}}function SY($,w){let{gen:Z,schema:W,opts:{useDefaults:X}}=$;if(X)(0,RN.assignDefaults)($,w.type);Z.block(()=>{for(let Y of w.rules)if((0,HZ.shouldUseRule)(W,Y))gY($,Y.keyword,Y.definition,w.type)})}function cN($,w){if($.schemaEnv.meta||!$.opts.strictTypes)return;if(dN($,w),!$.opts.allowUnionTypes)pN($,w);nN($,$.dataTypes)}function dN($,w){if(!w.length)return;if(!$.dataTypes.length){$.dataTypes=w;return}w.forEach((Z)=>{if(!_Y($.dataTypes,Z))FZ($,`type "${Z}" not allowed by context "${$.dataTypes.join(",")}"`)}),rN($,w)}function pN($,w){if(w.length>1&&!(w.length===2&&w.includes("null")))FZ($,"use allowUnionTypes to allow union type keyword")}function nN($,w){let Z=$.self.RULES.all;for(let W in Z){let X=Z[W];if(typeof X=="object"&&(0,HZ.shouldUseRule)($.schema,X)){let{type:Y}=X.definition;if(Y.length&&!Y.some((G)=>tN(w,G)))FZ($,`missing type "${Y.join(",")}" for keyword "${W}"`)}}}function tN($,w){return $.includes(w)||w==="number"&&$.includes("integer")}function _Y($,w){return $.includes(w)||w==="integer"&&$.includes("number")}function rN($,w){let Z=[];for(let W of $.dataTypes)if(_Y(w,W))Z.push(W);else if(w.includes("integer")&&W==="number")Z.push("integer");$.dataTypes=Z}function FZ($,w){let Z=$.schemaEnv.baseId+$.errSchemaPath;w+=` at "${Z}" (strictTypes)`,(0,Y$.checkStrictMode)($,w,$.opts.strictTypes)}class OZ{constructor($,w,Z){if((0,yw.validateKeywordUsage)($,w,Z),this.gen=$.gen,this.allErrors=$.allErrors,this.keyword=Z,this.data=$.data,this.schema=$.schema[Z],this.$data=w.$data&&$.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Y$.schemaRefOrVal)($,this.schema,Z,this.$data),this.schemaType=w.schemaType,this.parentSchema=$.schema,this.params={},this.it=$,this.def=w,this.$data)this.schemaCode=$.gen.const("vSchema",vY(this.$data,$));else if(this.schemaCode=this.schemaValue,!(0,yw.validSchemaType)(this.schema,w.schemaType,w.allowUndefined))throw Error(`${Z} value must be ${JSON.stringify(w.schemaType)}`);if("code"in w?w.trackErrors:w.errors!==!1)this.errsCount=$.gen.const("_errs",b.default.errors)}result($,w,Z){this.failResult((0,S.not)($),w,Z)}failResult($,w,Z){if(this.gen.if($),Z)Z();else this.error();if(w){if(this.gen.else(),w(),this.allErrors)this.gen.endIf()}else if(this.allErrors)this.gen.endIf();else this.gen.else()}pass($,w){this.failResult((0,S.not)($),void 0,w)}fail($){if($===void 0){if(this.error(),!this.allErrors)this.gen.if(!1);return}if(this.gen.if($),this.error(),this.allErrors)this.gen.endIf();else this.gen.else()}fail$data($){if(!this.$data)return this.fail($);let{schemaCode:w}=this;this.fail(S._`${w} !== undefined && (${(0,S.or)(this.invalid$data(),$)})`)}error($,w,Z){if(w){this.setParams(w),this._error($,Z),this.setParams({});return}this._error($,Z)}_error($,w){($?Iw.reportExtraError:Iw.reportError)(this,this.def.error,w)}$dataError(){(0,Iw.reportError)(this,this.def.$dataError||Iw.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error('add "trackErrors" to keyword definition');(0,Iw.resetErrorsCount)(this.gen,this.errsCount)}ok($){if(!this.allErrors)this.gen.if($)}setParams($,w){if(w)Object.assign(this.params,$);else this.params=$}block$data($,w,Z=S.nil){this.gen.block(()=>{this.check$data($,Z),w()})}check$data($=S.nil,w=S.nil){if(!this.$data)return;let{gen:Z,schemaCode:W,schemaType:X,def:Y}=this;if(Z.if((0,S.or)(S._`${W} === undefined`,w)),$!==S.nil)Z.assign($,!0);if(X.length||Y.validateSchema){if(Z.elseIf(this.invalid$data()),this.$dataError(),$!==S.nil)Z.assign($,!1)}Z.else()}invalid$data(){let{gen:$,schemaCode:w,schemaType:Z,def:W,it:X}=this;return(0,S.or)(Y(),G());function Y(){if(Z.length){if(!(w instanceof S.Name))throw Error("ajv implementation error");let J=Array.isArray(Z)?Z:[Z];return S._`${(0,n4.checkDataTypes)(J,w,X.opts.strictNumbers,n4.DataType.Wrong)}`}return S.nil}function G(){if(W.validateSchema){let J=$.scopeValue("validate$data",{ref:W.validateSchema});return S._`!${J}(${w})`}return S.nil}}subschema($,w){let Z=(0,UZ.getSubschema)(this.it,$);(0,UZ.extendSubschemaData)(Z,this.it,$),(0,UZ.extendSubschemaMode)(Z,$);let W={...this.it,...Z,items:void 0,props:void 0};return _N(W,w),W}mergeEvaluated($,w){let{it:Z,gen:W}=this;if(!Z.opts.unevaluated)return;if(Z.props!==!0&&$.props!==void 0)Z.props=Y$.mergeEvaluated.props(W,$.props,Z.props,w);if(Z.items!==!0&&$.items!==void 0)Z.items=Y$.mergeEvaluated.items(W,$.items,Z.items,w)}mergeValidEvaluated($,w){let{it:Z,gen:W}=this;if(Z.opts.unevaluated&&(Z.props!==!0||Z.items!==!0))return W.if(w,()=>this.mergeEvaluated($,S.Name)),!0}}uY.KeywordCxt=OZ;function gY($,w,Z,W){let X=new OZ($,Z,w);if("code"in Z)Z.code(X,W);else if(X.$data&&Z.validate)(0,yw.funcKeywordCode)(X,Z);else if("macro"in Z)(0,yw.macroKeywordCode)(X,Z);else if(Z.compile||Z.validate)(0,yw.funcKeywordCode)(X,Z)}var sN=/^\/(?:[^~]|~0|~1)*$/,aN=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function vY($,{dataLevel:w,dataNames:Z,dataPathArr:W}){let X,Y;if($==="")return b.default.rootData;if($[0]==="/"){if(!sN.test($))throw Error(`Invalid JSON-pointer: ${$}`);X=$,Y=b.default.rootData}else{let z=aN.exec($);if(!z)throw Error(`Invalid JSON-pointer: ${$}`);let M=+z[1];if(X=z[2],X==="#"){if(M>=w)throw Error(Q("property/index",M));return W[w-M]}if(M>w)throw Error(Q("data",M));if(Y=Z[w-M],!X)return Y}let G=Y,J=X.split("/");for(let z of J)if(z)Y=S._`${Y}${(0,S.getProperty)((0,Y$.unescapeJsonPointer)(z))}`,G=S._`${G} && ${Y}`;return G;function Q(z,M){return`Cannot access ${z} ${M} levels up, current level is ${w}`}}uY.getData=vY});var t4=L((mY)=>{Object.defineProperty(mY,"__esModule",{value:!0});class iY extends Error{constructor($){super("validation failed");this.errors=$,this.ajv=this.validation=!0}}mY.default=iY});var xw=L((cY)=>{Object.defineProperty(cY,"__esModule",{value:!0});var EZ=jw();class lY extends Error{constructor($,w,Z,W){super(W||`can't resolve reference ${Z} from id ${w}`);this.missingRef=(0,EZ.resolveUrl)($,w,Z),this.missingSchema=(0,EZ.normalizeId)((0,EZ.getFullPath)($,this.missingRef))}}cY.default=lY});var s4=L((nY)=>{Object.defineProperty(nY,"__esModule",{value:!0});nY.resolveSchema=nY.getCompilingSchema=nY.resolveRef=nY.compileSchema=nY.SchemaEnv=void 0;var m0=v(),ZB=t4(),s$=X$(),l0=jw(),dY=l(),WB=bw();class _w{constructor($){var w;this.refs={},this.dynamicAnchors={};let Z;if(typeof $.schema=="object")Z=$.schema;this.schema=$.schema,this.schemaId=$.schemaId,this.root=$.root||this,this.baseId=(w=$.baseId)!==null&&w!==void 0?w:(0,l0.normalizeId)(Z===null||Z===void 0?void 0:Z[$.schemaId||"$id"]),this.schemaPath=$.schemaPath,this.localRefs=$.localRefs,this.meta=$.meta,this.$async=Z===null||Z===void 0?void 0:Z.$async,this.refs={}}}nY.SchemaEnv=_w;function DZ($){let w=pY.call(this,$);if(w)return w;let Z=(0,l0.getFullPath)(this.opts.uriResolver,$.root.baseId),{es5:W,lines:X}=this.opts.code,{ownProperties:Y}=this.opts,G=new m0.CodeGen(this.scope,{es5:W,lines:X,ownProperties:Y}),J;if($.$async)J=G.scopeValue("Error",{ref:ZB.default,code:m0._`require("ajv/dist/runtime/validation_error").default`});let Q=G.scopeName("validate");$.validateName=Q;let z={gen:G,allErrors:this.opts.allErrors,data:s$.default.data,parentData:s$.default.parentData,parentDataProperty:s$.default.parentDataProperty,dataNames:[s$.default.data],dataPathArr:[m0.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:G.scopeValue("schema",this.opts.code.source===!0?{ref:$.schema,code:(0,m0.stringify)($.schema)}:{ref:$.schema}),validateName:Q,ValidationError:J,schema:$.schema,schemaEnv:$,rootId:Z,baseId:$.baseId||Z,schemaPath:m0.nil,errSchemaPath:$.schemaPath||(this.opts.jtd?"":"#"),errorPath:m0._`""`,opts:this.opts,self:this},M;try{this._compilations.add($),(0,WB.validateFunctionCode)(z),G.optimize(this.opts.code.optimize);let T=G.toString();if(M=`${G.scopeRefs(s$.default.scope)}return ${T}`,this.opts.code.process)M=this.opts.code.process(M,$);let N=Function(`${s$.default.self}`,`${s$.default.scope}`,M)(this,this.scope.get());if(this.scope.value(Q,{ref:N}),N.errors=null,N.schema=$.schema,N.schemaEnv=$,$.$async)N.$async=!0;if(this.opts.code.source===!0)N.source={validateName:Q,validateCode:T,scopeValues:G._values};if(this.opts.unevaluated){let{props:B,items:P}=z;if(N.evaluated={props:B instanceof m0.Name?void 0:B,items:P instanceof m0.Name?void 0:P,dynamicProps:B instanceof m0.Name,dynamicItems:P instanceof m0.Name},N.source)N.source.evaluated=(0,m0.stringify)(N.evaluated)}return $.validate=N,$}catch(T){if(delete $.validate,delete $.validateName,M)this.logger.error("Error compiling schema, function code:",M);throw T}finally{this._compilations.delete($)}}nY.compileSchema=DZ;function XB($,w,Z){var W;Z=(0,l0.resolveUrl)(this.opts.uriResolver,w,Z);let X=$.refs[Z];if(X)return X;let Y=JB.call(this,$,Z);if(Y===void 0){let G=(W=$.localRefs)===null||W===void 0?void 0:W[Z],{schemaId:J}=this.opts;if(G)Y=new _w({schema:G,schemaId:J,root:$,baseId:w})}if(Y===void 0)return;return $.refs[Z]=YB.call(this,Y)}nY.resolveRef=XB;function YB($){if((0,l0.inlineRef)($.schema,this.opts.inlineRefs))return $.schema;return $.validate?$:DZ.call(this,$)}function pY($){for(let w of this._compilations)if(GB(w,$))return w}nY.getCompilingSchema=pY;function GB($,w){return $.schema===w.schema&&$.root===w.root&&$.baseId===w.baseId}function JB($,w){let Z;while(typeof(Z=this.refs[w])=="string")w=Z;return Z||this.schemas[w]||r4.call(this,$,w)}function r4($,w){let Z=this.opts.uriResolver.parse(w),W=(0,l0._getFullPath)(this.opts.uriResolver,Z),X=(0,l0.getFullPath)(this.opts.uriResolver,$.baseId,void 0);if(Object.keys($.schema).length>0&&W===X)return LZ.call(this,Z,$);let Y=(0,l0.normalizeId)(W),G=this.refs[Y]||this.schemas[Y];if(typeof G=="string"){let J=r4.call(this,$,G);if(typeof(J===null||J===void 0?void 0:J.schema)!=="object")return;return LZ.call(this,Z,J)}if(typeof(G===null||G===void 0?void 0:G.schema)!=="object")return;if(!G.validate)DZ.call(this,G);if(Y===(0,l0.normalizeId)(w)){let{schema:J}=G,{schemaId:Q}=this.opts,z=J[Q];if(z)X=(0,l0.resolveUrl)(this.opts.uriResolver,X,z);return new _w({schema:J,schemaId:Q,root:$,baseId:X})}return LZ.call(this,Z,G)}nY.resolveSchema=r4;var QB=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function LZ($,{baseId:w,schema:Z,root:W}){var X;if(((X=$.fragment)===null||X===void 0?void 0:X[0])!=="/")return;for(let J of $.fragment.slice(1).split("/")){if(typeof Z==="boolean")return;let Q=Z[(0,dY.unescapeFragment)(J)];if(Q===void 0)return;Z=Q;let z=typeof Z==="object"&&Z[this.opts.schemaId];if(!QB.has(J)&&z)w=(0,l0.resolveUrl)(this.opts.uriResolver,w,z)}let Y;if(typeof Z!="boolean"&&Z.$ref&&!(0,dY.schemaHasRulesButRef)(Z,this.RULES)){let J=(0,l0.resolveUrl)(this.opts.uriResolver,w,Z.$ref);Y=r4.call(this,W,J)}let{schemaId:G}=this.opts;if(Y=Y||new _w({schema:Z,schemaId:G,root:W,baseId:w}),Y.schema!==Y.root.schema)return Y;return}});var rY=L((xL,NB)=>{NB.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var CZ=L((_L,Z3)=>{var BB=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),kZ=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),a$=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),AZ=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),aY=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),SZ=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),VB=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),L0=Array(256);for(let w=0;w<256;w++)L0[w]="%"+"0123456789ABCDEF"[w>>4]+"0123456789ABCDEF"[w&15];function N0($){if($<2048)return L0[192|$>>6]+L0[128|$&63];if($<65536)return L0[224|$>>12]+L0[128|$>>6&63]+L0[128|$&63];return L0[240|$>>18]+L0[128|$>>12&63]+L0[128|$>>6&63]+L0[128|$&63]}function PB($){let w="",Z=0,W=0;for(W=0;W<$.length;W++){if(Z=$[W].charCodeAt(0),Z===48)continue;if(!(Z>=48&&Z<=57||Z>=65&&Z<=70||Z>=97&&Z<=102))return"";w+=$[W];break}for(W+=1;W<$.length;W++){if(Z=$[W].charCodeAt(0),!(Z>=48&&Z<=57||Z>=65&&Z<=70||Z>=97&&Z<=102))return"";w+=$[W]}return w}var qB=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),UB=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),HB=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),FB=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function OB($){if($.length===0)return!1;for(let w=0;w<$.length;w++){if(HB($[w]))continue;if($[w]==="%"&&w+2<$.length&&a$($.slice(w+1,w+3))){w+=2;continue}return!1}return!0}function sY($){let w=-1,Z=0,W=-1,X=0;for(let J=0;J<$.length;J++)if($[J]==="0"){if(W===-1)W=J;if(X++,X>Z)Z=X,w=W}else W=-1,X=0;if(Z<2)return $.join(":");let Y=$.slice(0,w).join(":"),G=$.slice(w+Z).join(":");return Y+"::"+G}function EB($){let w=$.indexOf("::");if(w!==-1&&$.indexOf("::",w+1)!==-1)return;let Z=w===-1?$.split(":"):$.slice(0,w).split(":"),W=w===-1?[]:$.slice(w+2).split(":");if(w!==-1){if(Z.length===1&&Z[0]==="")Z.length=0;if(W.length===1&&W[0]==="")W.length=0}let X=Z.concat(W),Y=0;for(let J=0;J<X.length;J++){let Q=X[J];if(Q==="")return;if(Q.indexOf(".")!==-1){if(J!==X.length-1||w!==-1&&W.length===0||!kZ(Q))return;Y+=2;continue}if(!qB(Q))return;X[J]=parseInt(Q,16).toString(16),Y++}if(w===-1){if(Y!==8)return;return sY(X)}if(Y>=8)return;let G=X.slice(0,Z.length);for(let J=Y;J<8;J++)G.push("0");for(let J=Z.length;J<X.length;J++)G.push(X[J]);return sY(G)}function fZ($){let w=$[0]==="["&&$[$.length-1]==="]";if(($[0]==="["||$[$.length-1]==="]")&&!w)return{host:$,isIPV6:!1,error:!0};let W=w?$.slice(1,-1):$;if(w&&UB(W))return W=W.toLowerCase(),{host:`[${W}]`,escapedHost:W,isIPV6:!1,isIPVFuture:!0};if(LB(W,":")<2)return{host:$,isIPV6:!1,error:w};let X="",Y=W.indexOf("%");if(Y!==-1){let J=W.slice(Y,Y+3).toLowerCase()==="%25"?3:1;if(X=W.slice(Y+J),!OB(X))return{host:$,isIPV6:!1,error:!0};W=W.slice(0,Y)}let G=EB(W);if(G===void 0)return{host:$,isIPV6:!1,error:!0};return{host:G+(X?"%"+X:""),escapedHost:G+(X?"%25"+X:""),isIPV6:!0}}function LB($,w){let Z=0;for(let W=0;W<$.length;W++)if($[W]===w)Z++;return Z}function DB($){let w=$,Z=[],W=-1,X=0;while(X=w.length){if(X===1)if(w===".")break;else if(w==="/"){Z.push("/");break}else{Z.push(w);break}else if(X===2){if(w[0]==="."){if(w[1]===".")break;else if(w[1]==="/"){w=w.slice(2);continue}}else if(w[0]==="/"){if(w[1]==="."||w[1]==="/"){Z.push("/");break}}}else if(X===3){if(w==="/.."){if(Z.length!==0)Z.pop();Z.push("/");break}}if(w[0]==="."){if(w[1]==="."){if(w[2]==="/"){w=w.slice(3);continue}}else if(w[1]==="/"){w=w.slice(2);continue}}else if(w[0]==="/"){if(w[1]==="."){if(w[2]==="/"){w=w.slice(2);continue}else if(w[2]==="."){if(w[3]==="/"){if(w=w.slice(3),Z.length!==0)Z.pop();continue}}}}if((W=w.indexOf("/",1))===-1){Z.push(w);break}else Z.push(w.slice(0,W)),w=w.slice(W)}return Z.join("")}var fB={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},kB=/[@/?#:]/g,AB=/[@/?#]/g;function oY($,w){let Z=w?AB:kB;return Z.lastIndex=0,$.replace(Z,(W)=>fB[W])}function eY($,w=!1){if($.indexOf("%")===-1)return $;let Z="";for(let W=0;W<$.length;W++){if($[W]==="%"&&W+2<$.length){let X=$.slice(W+1,W+3);if(a$(X)){let Y=X.toUpperCase(),G=String.fromCharCode(parseInt(Y,16));if(w&&AZ(G))Z+=G;else Z+="%"+Y;W+=2;continue}}Z+=$[W]}return Z}function SB($){let w="";for(let Z=0;Z<$.length;Z++){let W=$[Z];if(W==="%"&&Z+2<$.length){let X=$.slice(Z+1,Z+3);if(a$(X)){let Y=X.toUpperCase(),G=String.fromCharCode(parseInt(Y,16));if(G!=="."&&AZ(G))w+=G;else w+="%"+Y;Z+=2;continue}}if(aY(W))w+=W;else{let X=$.charCodeAt(Z);if(X<128)w+=w3(X)?W:L0[X];else if(X<55296||X>57343)w+=N0(X);else if(X<=56319&&Z+1<$.length){let Y=$.charCodeAt(Z+1);if(Y>=56320&&Y<=57343)w+=N0(65536+(X-55296<<10)+(Y-56320)),Z++;else w+=N0(65533)}else w+=N0(65533)}}return w}function RB($,w=!1){let Z="",W=w&&$[0]!=="/";for(let X=0;X<$.length;X++){let Y=$[X];if(Y==="%"&&X+2<$.length){let G=$.slice(X+1,X+3);if(a$(G)){Z+="%"+G.toUpperCase(),X+=2;continue}}if(Y==="/")W=!1;if(aY(Y)&&(Y!==":"||!W))Z+=Y;else{let G=$.charCodeAt(X);if(G<128)Z+=L0[G];else if(G<55296||G>57343)Z+=N0(G);else if(G<=56319&&X+1<$.length){let J=$.charCodeAt(X+1);if(J>=56320&&J<=57343)Z+=N0(65536+(G-55296<<10)+(J-56320)),X++;else Z+=N0(65533)}else Z+=N0(65533)}}return Z}function RZ($,w){let Z="";for(let W=0;W<$.length;W++){let X=$[W];if(X==="%"&&W+2<$.length){let Y=$.slice(W+1,W+3);if(a$(Y)){Z+="%"+Y.toUpperCase(),W+=2;continue}}if(w(X))Z+=X;else{let Y=$.charCodeAt(W);if(Y<128)Z+=L0[Y];else if(Y<55296||Y>57343)Z+=N0(Y);else if(Y<=56319&&W+1<$.length){let G=$.charCodeAt(W+1);if(G>=56320&&G<=57343)Z+=N0(65536+(Y-55296<<10)+(G-56320)),W++;else Z+=N0(65533)}else Z+=N0(65533)}}return Z}function $3($){return RZ($,VB)}function CB($){return RZ($,SZ)}function jB($){return RZ($,SZ)}function w3($){return $>=48&&$<=57||$>=65&&$<=90||$>=97&&$<=122||$===42||$===43||$===45||$===46||$===47||$===64||$===95}function IB($){let w="";for(let Z=0;Z<$.length;Z++){let W=$[Z];if(W==="%"&&Z+2<$.length){let X=$.slice(Z+1,Z+3);if(a$(X)){let Y=X.toUpperCase(),G=String.fromCharCode(parseInt(Y,16));if(AZ(G))w+=G;else w+="%"+Y;Z+=2;continue}}if(SZ(W))w+=W;else{let X=$.charCodeAt(Z);if(X<128)w+=w3(X)?W:L0[X];else if(X<55296||X>57343)w+=N0(X);else if(X<=56319&&Z+1<$.length){let Y=$.charCodeAt(Z+1);if(Y>=56320&&Y<=57343)w+=N0(65536+(X-55296<<10)+(Y-56320)),Z++;else w+=N0(65533)}else w+=N0(65533)}}return w}function yB($){let w="";for(let Z=0;Z<$.length;Z++){if($[Z]==="%"&&Z+2<$.length){let W=$.slice(Z+1,Z+3);if(a$(W)){w+="%"+W.toUpperCase(),Z+=2;continue}}w+=escape($[Z])}return w}function bB($){let w=[];if($.userinfo!==void 0)w.push($3($.userinfo)),w.push("@");if($.host!==void 0){let Z=$.host;if(!kZ(Z)){let W=fZ(Z);if(W.isIPV6!==!0&&W.isIPVFuture!==!0)Z=eY(Z,!0),W=fZ(Z);if(W.isIPV6===!0||W.isIPVFuture===!0)Z=`[${W.escapedHost}]`;else Z=oY(Z,!1)}w.push(Z)}if(typeof $.port==="number"||typeof $.port==="string")w.push(":"),w.push(String($.port));return w.length?w.join(""):void 0}Z3.exports={nonSimpleDomain:FB,recomposeAuthority:bB,reescapeHostDelimiters:oY,normalizePercentEncoding:eY,normalizePathEncoding:SB,serializePathEncoding:RB,normalizeQueryFragmentEncoding:IB,encodeUserinfo:$3,encodeQuery:CB,encodeFragment:jB,escapePreservingEscapes:yB,removeDotSegments:DB,isIPv4:kZ,isUUID:BB,normalizeIPv6:fZ,stringArrayToHexStripped:PB}});var J3=L((gL,G3)=>{var{isUUID:xB}=CZ(),_B=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,gB=["http","https","ws","wss","urn","urn:uuid"];function vB($){return gB.indexOf($)!==-1}function jZ($){if($.secure===!0)return!0;else if($.secure===!1)return!1;else if($.scheme)return $.scheme.length===3&&($.scheme[0]==="w"||$.scheme[0]==="W")&&($.scheme[1]==="s"||$.scheme[1]==="S")&&($.scheme[2]==="s"||$.scheme[2]==="S");else return!1}function W3($){if(!$.host)$.error=$.error||"HTTP URIs must have a host.";return $}function X3($){let w=String($.scheme).toLowerCase()==="https";if($.port===(w?443:80)||$.port==="")$.port=void 0;if(!$.path)$.path="/";return $}function uB($){return $.secure=jZ($),$.resourceName=($.path||"/")+($.query?"?"+$.query:""),$.path=void 0,$.query=void 0,$}function hB($){if($.port===(jZ($)?443:80)||$.port==="")$.port=void 0;if(typeof $.secure==="boolean")$.scheme=$.secure?"wss":"ws",$.secure=void 0;if($.resourceName){let w=$.resourceName.indexOf("?"),Z=w===-1?$.resourceName:$.resourceName.slice(0,w);$.path=Z&&Z!=="/"?Z:void 0,$.query=w===-1?void 0:$.resourceName.slice(w+1),$.resourceName=void 0}return $.fragment=void 0,$}function iB($,w){if(!$.path)return $.error="URN can not be parsed",$;let Z=$.path.match(_B);if(Z&&Z[0]===$.path){let W=w.scheme||$.scheme||"urn";$.nid=Z[1].toLowerCase(),$.nss=Z[2];let X=`${W}:${w.nid||$.nid}`,Y=IZ(X);if($.path=void 0,Y)$=Y.parse($,w)}else $.error=$.error||"URN can not be parsed.";return $}function mB($,w){if($.nid===void 0)throw Error("URN without nid cannot be serialized");let Z=w.scheme||$.scheme||"urn",W=$.nid.toLowerCase(),X=`${Z}:${w.nid||W}`,Y=IZ(X);if(Y)$=Y.serialize($,w);let G=$,J=$.nss;return G.path=`${W||w.nid}:${J}`,w.skipEscape=!0,G}function lB($,w){let Z=$;if(Z.uuid=Z.nss,Z.nss=void 0,!w.tolerant&&(!Z.uuid||!xB(Z.uuid)))Z.error=Z.error||"UUID is not valid.";return Z}function cB($){let w=$;return w.nss=($.uuid||"").toLowerCase(),w}var Y3={scheme:"http",domainHost:!0,parse:W3,serialize:X3},dB={scheme:"https",domainHost:Y3.domainHost,parse:W3,serialize:X3},a4={scheme:"ws",domainHost:!0,parse:uB,serialize:hB},pB={scheme:"wss",domainHost:a4.domainHost,parse:a4.parse,serialize:a4.serialize},nB={scheme:"urn",parse:iB,serialize:mB,skipNormalize:!0},tB={scheme:"urn:uuid",parse:lB,serialize:cB,skipNormalize:!0},o4={http:Y3,https:dB,ws:a4,wss:pB,urn:nB,"urn:uuid":tB};Object.setPrototypeOf(o4,null);function IZ($){return $&&(o4[$]||o4[$.toLowerCase()])||void 0}G3.exports={wsIsSecure:jZ,SCHEMES:o4,isValidSchemeName:vB,getSchemeHandler:IZ}});var F3=L((vL,w8)=>{var{normalizeIPv6:K3,removeDotSegments:vw,recomposeAuthority:rB,normalizePercentEncoding:N3,normalizePathEncoding:sB,serializePathEncoding:Q3,normalizeQueryFragmentEncoding:z3,encodeQuery:aB,encodeFragment:oB,reescapeHostDelimiters:eB,isIPv4:B3,nonSimpleDomain:$V}=CZ(),{SCHEMES:V3,getSchemeHandler:yZ}=J3(),P3=/^[A-Za-z][A-Za-z0-9+.-]*$/u;function M3($){let w=unescape(String($));if(!P3.test(w))throw TypeError("URI scheme is malformed.");return w}function wV($,w){if(typeof $==="string")$=zV($,w);else if(typeof $==="object")$=$8(o$($,w),w);return $}function ZV($,w,Z){let W=Z?Object.assign({scheme:"null"},Z):{scheme:"null"},{parsed:X,malformedAuthorityOrPort:Y,malformedPercentEncoding:G,malformedSchemeSpecific:J,malformedHost:Q,malformedScheme:z}=e4($,W),{parsed:M,malformedAuthorityOrPort:T,malformedPercentEncoding:K,malformedSchemeSpecific:N,malformedHost:B,malformedScheme:P}=e4(w,W);if(Y||T||G||K||J||N||Q||B||z||P)throw Error(X.error||M.error||"URI is malformed.");let q=q3(X,M,W,!0),U=yZ(Z&&Z.scheme||q.scheme),O=q.host,f=O!==void 0&&O!==""&&(B3(O)||K3(O).isIPV6);U3(q,Z||{},U,f);let C=O&&O.indexOf("%")!==-1&&!/\P{ASCII}/u.test(O);if(q.error&&!C)throw Error(q.error);return W.skipEscape=!0,o$(q,W)}function q3($,w,Z,W){let X={};if(!W)$=$8(o$($,Z),Z),w=$8(o$(w,Z),Z);if(Z=Z||{},!Z.tolerant&&w.scheme)X.scheme=w.scheme,X.userinfo=w.userinfo,X.host=w.host,X.port=w.port,X.path=vw(w.path||""),X.query=w.query;else{if(w.userinfo!==void 0||w.host!==void 0||w.port!==void 0)X.userinfo=w.userinfo,X.host=w.host,X.port=w.port,X.path=vw(w.path||""),X.query=w.query;else{if(!w.path)if(X.path=$.path,w.query!==void 0)X.query=w.query;else X.query=$.query;else{if(w.path[0]==="/")X.path=vw(w.path);else{if(($.userinfo!==void 0||$.host!==void 0||$.port!==void 0)&&!$.path)X.path="/"+w.path;else if(!$.path)X.path=w.path;else X.path=$.path.slice(0,$.path.lastIndexOf("/")+1)+w.path;X.path=vw(X.path)}X.query=w.query}X.userinfo=$.userinfo,X.host=$.host,X.port=$.port}X.scheme=$.scheme}return X.fragment=w.fragment,X}function WV($,w,Z){let W=T3($,Z),X=T3(w,Z);return W!==void 0&&X!==void 0&&W===X}function o$($,w){let Z={host:$.host,scheme:$.scheme,userinfo:$.userinfo,port:$.port,path:$.path,query:$.query,nid:$.nid,nss:$.nss,uuid:$.uuid,fragment:$.fragment,reference:$.reference,resourceName:$.resourceName,secure:$.secure,error:""},W=Object.assign({},w),X=[];if(Z.scheme)Z.scheme=M3(Z.scheme);let Y=yZ(W.scheme||Z.scheme);if(Y&&Y.serialize)Y.serialize(Z,W);let G=Z.userinfo!==void 0||Z.host!==void 0||Z.port!==void 0,J=!W.skipEscape&&Z.scheme===void 0&&!G;if(Z.path!==void 0)if(!W.skipEscape)Z.path=Q3(Z.path,J);else Z.path=N3(Z.path);if(W.reference!=="suffix"&&Z.scheme)Z.scheme=M3(Z.scheme),X.push(Z.scheme,":");let Q=rB(Z);if(Q!==void 0){if(W.reference!=="suffix")X.push("//");if(X.push(Q),Z.path&&Z.path[0]!=="/")X.push("/")}if(Z.path!==void 0){let z=Z.path;if(!W.absolutePath&&(!Y||!Y.absolutePath))z=vw(z);if(J)z=Q3(z,!0);if(Q===void 0&&z[0]==="/"&&z[1]==="/")z="/%2F"+z.slice(2);X.push(z)}if(Z.query!==void 0)X.push("?",aB(Z.query));if(Z.fragment!==void 0)X.push("#",oB(Z.fragment));return X.join("")}var XV=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,YV=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,GV=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function JV($,w){if(w[2]!==void 0&&$.path&&$.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof $.port==="number"&&($.port<0||$.port>65535))return"URI port is malformed.";return}function gw($){if($===void 0)return!1;let w=$.indexOf("%");while(w!==-1){if(w+2>=$.length||!/^[\da-f]{2}$/iu.test($.slice(w+1,w+3)))return!0;w=$.indexOf("%",w+3)}return!1}function QV($){let w=$[4];return gw($[3])||w!==void 0&&!(w[0]==="["&&w[w.length-1]==="]")&&gw(w)||gw($[6])||gw($[7])||gw($[8])}function U3($,w,Z,W){if(!w.unicodeSupport&&(!Z||!Z.unicodeSupport)&&$.host&&$.host[0]!=="["&&(w.domainHost||Z&&Z.domainHost)&&W===!1&&$V($.host))try{$.host=new URL("http://"+$.host).hostname}catch(X){return $.error=$.error||"Host's domain name can not be converted to ASCII: "+X,!0}return!1}function e4($,w){let Z=Object.assign({},w),W={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},X=!1,Y=!1,G=!1,J=!1,Q=!1,z=!1,M=!1;if(Z.reference==="suffix")if(Z.scheme)$=Z.scheme+":"+$;else $="//"+$;let T=$.match(YV);if(T!==null&&T[1].indexOf("\\")!==-1)W.error="URI authority must not contain a literal backslash.",X=!0;let K=$.match(GV);if(K!==null){let B=K[1],P=B.replace(/[\t\n\r]/g,"");if(P.length>=2){if(P.slice(0,2)!=="//")W.error=W.error||"URI authority must not contain a literal backslash.",X=!0;else if(B.length!==P.length)W.error=W.error||"URI authority introducer must not contain whitespace.",X=!0}}let N=$.match(XV);if(N){if(W.scheme=N[1],W.userinfo=N[3],W.host=N[4],W.port=parseInt(N[5],10),W.path=N[6]||"",W.query=N[7],W.fragment=N[8],W.scheme!==void 0){let q=unescape(W.scheme);if(P3.test(q))W.scheme=q.toLowerCase();else W.error=W.error||"URI scheme is malformed.",z=!0}if(Y=QV(N),Y)W.error=W.error||"URI contains malformed percent-encoding.";if(isNaN(W.port))W.port=N[5];let B=JV(W,N);if(B!==void 0)W.error=W.error||B,X=!0;if(W.host)if(B3(W.host)===!1){let U=W.host[0]==="["&&W.host[W.host.length-1]==="]",O=K3(W.host);if(M=O.isIPV6||O.isIPVFuture===!0,Q=U&&O.error===!0,W.host=M?O.host:O.host.toLowerCase(),Q)W.error=W.error||"URI host is malformed.",X=!0}else M=!0;if(W.scheme===void 0&&W.userinfo===void 0&&W.host===void 0&&W.port===void 0&&W.query===void 0&&!W.path)W.reference="same-document";else if(W.scheme===void 0)W.reference="relative";else if(W.fragment===void 0)W.reference="absolute";else W.reference="uri";if(Z.reference&&Z.reference!=="suffix"&&Z.reference!==W.reference)W.error=W.error||"URI is not a "+Z.reference+" reference.";let P=yZ(Z.scheme||W.scheme);if(J=U3(W,Z,P,M),!P||P&&!P.skipNormalize){if($.indexOf("%")!==-1){if(W.host!==void 0&&!Q){let q=M?W.host:N3(W.host,!0);W.host=eB(q,M)}}if(W.path)W.path=sB(W.path);if(W.query)W.query=z3(W.query);if(W.fragment)W.fragment=z3(W.fragment)}if(P&&P.parse){if(P.parse(W,Z),P===V3.urn&&W.nid===void 0)G=!0}}else W.error=W.error||"URI can not be parsed.";return{parsed:W,malformedAuthorityOrPort:X,malformedPercentEncoding:Y,malformedSchemeSpecific:G,malformedHost:J,malformedScheme:z}}function $8($,w){return e4($,w).parsed}function zV($,w){return H3($,w).normalized}function H3($,w){let{parsed:Z,malformedAuthorityOrPort:W,malformedPercentEncoding:X,malformedSchemeSpecific:Y,malformedHost:G,malformedScheme:J}=e4($,w);return{normalized:W||X||Y||G||J?$:o$(Z,w),malformedAuthorityOrPort:W,malformedPercentEncoding:X,malformedSchemeSpecific:Y,malformedHost:G,malformedScheme:J}}function T3($,w){if(typeof $!=="string"&&typeof $!=="object")return;let Z;try{Z=typeof $==="string"?$:o$($,w)}catch{return}let{normalized:W,malformedAuthorityOrPort:X,malformedPercentEncoding:Y,malformedSchemeSpecific:G,malformedHost:J,malformedScheme:Q}=H3(Z,w);return X||Y||G||J||Q?void 0:W}var bZ={SCHEMES:V3,normalize:wV,resolve:ZV,resolveComponent:q3,equal:WV,serialize:o$,parse:$8};w8.exports=bZ;w8.exports.default=bZ;w8.exports.fastUri=bZ});var L3=L((E3)=>{Object.defineProperty(E3,"__esModule",{value:!0});var O3=F3();O3.code='require("ajv/dist/runtime/uri").default';E3.default=O3});var j3=L((G$)=>{Object.defineProperty(G$,"__esModule",{value:!0});G$.CodeGen=G$.Name=G$.nil=G$.stringify=G$.str=G$._=G$.KeywordCxt=void 0;var TV=bw();Object.defineProperty(G$,"KeywordCxt",{enumerable:!0,get:function(){return TV.KeywordCxt}});var _1=v();Object.defineProperty(G$,"_",{enumerable:!0,get:function(){return _1._}});Object.defineProperty(G$,"str",{enumerable:!0,get:function(){return _1.str}});Object.defineProperty(G$,"stringify",{enumerable:!0,get:function(){return _1.stringify}});Object.defineProperty(G$,"nil",{enumerable:!0,get:function(){return _1.nil}});Object.defineProperty(G$,"Name",{enumerable:!0,get:function(){return _1.Name}});Object.defineProperty(G$,"CodeGen",{enumerable:!0,get:function(){return _1.CodeGen}});var KV=t4(),S3=xw(),NV=QZ(),uw=s4(),BV=v(),hw=jw(),Z8=Cw(),_Z=l(),D3=rY(),VV=L3(),R3=($,w)=>new RegExp($,w);R3.code="new RegExp";var PV=["removeAdditional","useDefaults","coerceTypes"],qV=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),UV={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},HV={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},f3=200;function FV($){var w,Z,W,X,Y,G,J,Q,z,M,T,K,N,B,P,q,U,O,f,C,A,u,i,r,z0;let h=$.strict,q0=(w=$.code)===null||w===void 0?void 0:w.optimize,p$=q0===!0||q0===void 0?1:q0||0,w$=(W=(Z=$.code)===null||Z===void 0?void 0:Z.regExp)!==null&&W!==void 0?W:R3,S1=(X=$.uriResolver)!==null&&X!==void 0?X:VV.default;return{strictSchema:(G=(Y=$.strictSchema)!==null&&Y!==void 0?Y:h)!==null&&G!==void 0?G:!0,strictNumbers:(Q=(J=$.strictNumbers)!==null&&J!==void 0?J:h)!==null&&Q!==void 0?Q:!0,strictTypes:(M=(z=$.strictTypes)!==null&&z!==void 0?z:h)!==null&&M!==void 0?M:"log",strictTuples:(K=(T=$.strictTuples)!==null&&T!==void 0?T:h)!==null&&K!==void 0?K:"log",strictRequired:(B=(N=$.strictRequired)!==null&&N!==void 0?N:h)!==null&&B!==void 0?B:!1,code:$.code?{...$.code,optimize:p$,regExp:w$}:{optimize:p$,regExp:w$},loopRequired:(P=$.loopRequired)!==null&&P!==void 0?P:f3,loopEnum:(q=$.loopEnum)!==null&&q!==void 0?q:f3,meta:(U=$.meta)!==null&&U!==void 0?U:!0,messages:(O=$.messages)!==null&&O!==void 0?O:!0,inlineRefs:(f=$.inlineRefs)!==null&&f!==void 0?f:!0,schemaId:(C=$.schemaId)!==null&&C!==void 0?C:"$id",addUsedSchema:(A=$.addUsedSchema)!==null&&A!==void 0?A:!0,validateSchema:(u=$.validateSchema)!==null&&u!==void 0?u:!0,validateFormats:(i=$.validateFormats)!==null&&i!==void 0?i:!0,unicodeRegExp:(r=$.unicodeRegExp)!==null&&r!==void 0?r:!0,int32range:(z0=$.int32range)!==null&&z0!==void 0?z0:!0,uriResolver:S1}}class W8{constructor($={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,$=this.opts={...$,...FV($)};let{es5:w,lines:Z}=this.opts.code;this.scope=new BV.ValueScope({scope:{},prefixes:qV,es5:w,lines:Z}),this.logger=kV($.logger);let W=$.validateFormats;if($.validateFormats=!1,this.RULES=(0,NV.getRules)(),k3.call(this,UV,$,"NOT SUPPORTED"),k3.call(this,HV,$,"DEPRECATED","warn"),this._metaOpts=DV.call(this),$.formats)EV.call(this);if(this._addVocabularies(),this._addDefaultMetaSchema(),$.keywords)LV.call(this,$.keywords);if(typeof $.meta=="object")this.addMetaSchema($.meta);OV.call(this),$.validateFormats=W}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:$,meta:w,schemaId:Z}=this.opts,W=D3;if(Z==="id")W={...D3},W.id=W.$id,delete W.$id;if(w&&$)this.addMetaSchema(W,W[Z],!1)}defaultMeta(){let{meta:$,schemaId:w}=this.opts;return this.opts.defaultMeta=typeof $=="object"?$[w]||$:void 0}validate($,w){let Z;if(typeof $=="string"){if(Z=this.getSchema($),!Z)throw Error(`no schema with key or ref "${$}"`)}else Z=this.compile($);let W=Z(w);if(!("$async"in Z))this.errors=Z.errors;return W}compile($,w){let Z=this._addSchema($,w);return Z.validate||this._compileSchemaEnv(Z)}compileAsync($,w){if(typeof this.opts.loadSchema!="function")throw Error("options.loadSchema should be a function");let{loadSchema:Z}=this.opts;return W.call(this,$,w);async function W(z,M){await X.call(this,z.$schema);let T=this._addSchema(z,M);return T.validate||Y.call(this,T)}async function X(z){if(z&&!this.getSchema(z))await W.call(this,{$ref:z},!0)}async function Y(z){try{return this._compileSchemaEnv(z)}catch(M){if(!(M instanceof S3.default))throw M;return G.call(this,M),await J.call(this,M.missingSchema),Y.call(this,z)}}function G({missingSchema:z,missingRef:M}){if(this.refs[z])throw Error(`AnySchema ${z} is loaded but ${M} cannot be resolved`)}async function J(z){let M=await Q.call(this,z);if(!this.refs[z])await X.call(this,M.$schema);if(!this.refs[z])this.addSchema(M,z,w)}async function Q(z){let M=this._loading[z];if(M)return M;try{return await(this._loading[z]=Z(z))}finally{delete this._loading[z]}}}addSchema($,w,Z,W=this.opts.validateSchema){if(Array.isArray($)){for(let Y of $)this.addSchema(Y,void 0,Z,W);return this}let X;if(typeof $==="object"){let{schemaId:Y}=this.opts;if(X=$[Y],X!==void 0&&typeof X!="string")throw Error(`schema ${Y} must be string`)}return w=(0,hw.normalizeId)(w||X),this._checkUnique(w),this.schemas[w]=this._addSchema($,Z,w,W,!0),this}addMetaSchema($,w,Z=this.opts.validateSchema){return this.addSchema($,w,!0,Z),this}validateSchema($,w){if(typeof $=="boolean")return!0;let Z;if(Z=$.$schema,Z!==void 0&&typeof Z!="string")throw Error("$schema must be a string");if(Z=Z||this.opts.defaultMeta||this.defaultMeta(),!Z)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let W=this.validate(Z,$);if(!W&&w){let X="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(X);else throw Error(X)}return W}getSchema($){let w;while(typeof(w=A3.call(this,$))=="string")$=w;if(w===void 0){let{schemaId:Z}=this.opts,W=new uw.SchemaEnv({schema:{},schemaId:Z});if(w=uw.resolveSchema.call(this,W,$),!w)return;this.refs[$]=w}return w.validate||this._compileSchemaEnv(w)}removeSchema($){if($ instanceof RegExp)return this._removeAllSchemas(this.schemas,$),this._removeAllSchemas(this.refs,$),this;switch(typeof $){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let w=A3.call(this,$);if(typeof w=="object")this._cache.delete(w.schema);return delete this.schemas[$],delete this.refs[$],this}case"object":{let w=$;this._cache.delete(w);let Z=$[this.opts.schemaId];if(Z)Z=(0,hw.normalizeId)(Z),delete this.schemas[Z],delete this.refs[Z];return this}default:throw Error("ajv.removeSchema: invalid parameter")}}addVocabulary($){for(let w of $)this.addKeyword(w);return this}addKeyword($,w){let Z;if(typeof $=="string"){if(Z=$,typeof w=="object")this.logger.warn("these parameters are deprecated, see docs for addKeyword"),w.keyword=Z}else if(typeof $=="object"&&w===void 0){if(w=$,Z=w.keyword,Array.isArray(Z)&&!Z.length)throw Error("addKeywords: keyword must be string or non-empty array")}else throw Error("invalid addKeywords parameters");if(SV.call(this,Z,w),!w)return(0,_Z.eachItem)(Z,(X)=>xZ.call(this,X)),this;CV.call(this,w);let W={...w,type:(0,Z8.getJSONTypes)(w.type),schemaType:(0,Z8.getJSONTypes)(w.schemaType)};return(0,_Z.eachItem)(Z,W.type.length===0?(X)=>xZ.call(this,X,W):(X)=>W.type.forEach((Y)=>xZ.call(this,X,W,Y))),this}getKeyword($){let w=this.RULES.all[$];return typeof w=="object"?w.definition:!!w}removeKeyword($){let{RULES:w}=this;delete w.keywords[$],delete w.all[$];for(let Z of w.rules){let W=Z.rules.findIndex((X)=>X.keyword===$);if(W>=0)Z.rules.splice(W,1)}return this}addFormat($,w){if(typeof w=="string")w=new RegExp(w);return this.formats[$]=w,this}errorsText($=this.errors,{separator:w=", ",dataVar:Z="data"}={}){if(!$||$.length===0)return"No errors";return $.map((W)=>`${Z}${W.instancePath} ${W.message}`).reduce((W,X)=>W+w+X)}$dataMetaSchema($,w){let Z=this.RULES.all;$=JSON.parse(JSON.stringify($));for(let W of w){let X=W.split("/").slice(1),Y=$;for(let G of X)Y=Y[G];for(let G in Z){let J=Z[G];if(typeof J!="object")continue;let{$data:Q}=J.definition,z=Y[G];if(Q&&z)Y[G]=C3(z)}}return $}_removeAllSchemas($,w){for(let Z in $){let W=$[Z];if(!w||w.test(Z)){if(typeof W=="string")delete $[Z];else if(W&&!W.meta)this._cache.delete(W.schema),delete $[Z]}}}_addSchema($,w,Z,W=this.opts.validateSchema,X=this.opts.addUsedSchema){let Y,{schemaId:G}=this.opts;if(typeof $=="object")Y=$[G];else if(this.opts.jtd)throw Error("schema must be object");else if(typeof $!="boolean")throw Error("schema must be object or boolean");let J=this._cache.get($);if(J!==void 0)return J;Z=(0,hw.normalizeId)(Y||Z);let Q=hw.getSchemaRefs.call(this,$,Z);if(J=new uw.SchemaEnv({schema:$,schemaId:G,meta:w,baseId:Z,localRefs:Q}),this._cache.set(J.schema,J),X&&!Z.startsWith("#")){if(Z)this._checkUnique(Z);this.refs[Z]=J}if(W)this.validateSchema($,!0);return J}_checkUnique($){if(this.schemas[$]||this.refs[$])throw Error(`schema with key or id "${$}" already exists`)}_compileSchemaEnv($){if($.meta)this._compileMetaSchema($);else uw.compileSchema.call(this,$);if(!$.validate)throw Error("ajv implementation error");return $.validate}_compileMetaSchema($){let w=this.opts;this.opts=this._metaOpts;try{uw.compileSchema.call(this,$)}finally{this.opts=w}}}W8.ValidationError=KV.default;W8.MissingRefError=S3.default;G$.default=W8;function k3($,w,Z,W="error"){for(let X in $){let Y=X;if(Y in w)this.logger[W](`${Z}: option ${X}. ${$[Y]}`)}}function A3($){return $=(0,hw.normalizeId)($),this.schemas[$]||this.refs[$]}function OV(){let $=this.opts.schemas;if(!$)return;if(Array.isArray($))this.addSchema($);else for(let w in $)this.addSchema($[w],w)}function EV(){for(let $ in this.opts.formats){let w=this.opts.formats[$];if(w)this.addFormat($,w)}}function LV($){if(Array.isArray($)){this.addVocabulary($);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let w in $){let Z=$[w];if(!Z.keyword)Z.keyword=w;this.addKeyword(Z)}}function DV(){let $={...this.opts};for(let w of PV)delete $[w];return $}var fV={log(){},warn(){},error(){}};function kV($){if($===!1)return fV;if($===void 0)return console;if($.log&&$.warn&&$.error)return $;throw Error("logger must implement log, warn and error methods")}var AV=/^[a-z_$][a-z0-9_$:-]*$/i;function SV($,w){let{RULES:Z}=this;if((0,_Z.eachItem)($,(W)=>{if(Z.keywords[W])throw Error(`Keyword ${W} is already defined`);if(!AV.test(W))throw Error(`Keyword ${W} has invalid name`)}),!w)return;if(w.$data&&!(("code"in w)||("validate"in w)))throw Error('$data keyword must have "code" or "validate" function')}function xZ($,w,Z){var W;let X=w===null||w===void 0?void 0:w.post;if(Z&&X)throw Error('keyword with "post" flag cannot have "type"');let{RULES:Y}=this,G=X?Y.post:Y.rules.find(({type:Q})=>Q===Z);if(!G)G={type:Z,rules:[]},Y.rules.push(G);if(Y.keywords[$]=!0,!w)return;let J={keyword:$,definition:{...w,type:(0,Z8.getJSONTypes)(w.type),schemaType:(0,Z8.getJSONTypes)(w.schemaType)}};if(w.before)RV.call(this,G,J,w.before);else G.rules.push(J);Y.all[$]=J,(W=w.implements)===null||W===void 0||W.forEach((Q)=>this.addKeyword(Q))}function RV($,w,Z){let W=$.rules.findIndex((X)=>X.keyword===Z);if(W>=0)$.rules.splice(W,0,w);else $.rules.push(w),this.logger.warn(`rule ${Z} is not defined`)}function CV($){let{metaSchema:w}=$;if(w===void 0)return;if($.$data&&this.opts.$data)w=C3(w);$.validateSchema=this.compile(w,!0)}var jV={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function C3($){return{anyOf:[$,jV]}}});var y3=L((I3)=>{Object.defineProperty(I3,"__esModule",{value:!0});var bV={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};I3.default=bV});var u3=L((g3)=>{Object.defineProperty(g3,"__esModule",{value:!0});g3.callRef=g3.getValidate=void 0;var _V=xw(),b3=_0(),D0=v(),g1=X$(),x3=s4(),X8=l(),gV={keyword:"$ref",schemaType:"string",code($){let{gen:w,schema:Z,it:W}=$,{baseId:X,schemaEnv:Y,validateName:G,opts:J,self:Q}=W,{root:z}=Y;if((Z==="#"||Z==="#/")&&X===z.baseId)return T();let M=x3.resolveRef.call(Q,z,X,Z);if(M===void 0)throw new _V.default(W.opts.uriResolver,X,Z);if(M instanceof x3.SchemaEnv)return K(M);return N(M);function T(){if(Y===z)return Y8($,G,Y,Y.$async);let B=w.scopeValue("root",{ref:z});return Y8($,D0._`${B}.validate`,z,z.$async)}function K(B){let P=_3($,B);Y8($,P,B,B.$async)}function N(B){let P=w.scopeValue("schema",J.code.source===!0?{ref:B,code:(0,D0.stringify)(B)}:{ref:B}),q=w.name("valid"),U=$.subschema({schema:B,dataTypes:[],schemaPath:D0.nil,topSchemaRef:P,errSchemaPath:Z},q);$.mergeEvaluated(U),$.ok(q)}}};function _3($,w){let{gen:Z}=$;return w.validate?Z.scopeValue("validate",{ref:w.validate}):D0._`${Z.scopeValue("wrapper",{ref:w})}.validate`}g3.getValidate=_3;function Y8($,w,Z,W){let{gen:X,it:Y}=$,{allErrors:G,schemaEnv:J,opts:Q}=Y,z=Q.passContext?g1.default.this:D0.nil;if(W)M();else T();function M(){if(!J.$async)throw Error("async schema referenced by sync schema");let B=X.let("valid");X.try(()=>{if(X.code(D0._`await ${(0,b3.callValidateCode)($,w,z)}`),N(w),!G)X.assign(B,!0)},(P)=>{if(X.if(D0._`!(${P} instanceof ${Y.ValidationError})`,()=>X.throw(P)),K(P),!G)X.assign(B,!1)}),$.ok(B)}function T(){$.result((0,b3.callValidateCode)($,w,z),()=>N(w),()=>K(w))}function K(B){let P=D0._`${B}.errors`;X.assign(g1.default.vErrors,D0._`${g1.default.vErrors} === null ? ${P} : ${g1.default.vErrors}.concat(${P})`),X.assign(g1.default.errors,D0._`${g1.default.vErrors}.length`)}function N(B){var P;if(!Y.opts.unevaluated)return;let q=(P=Z===null||Z===void 0?void 0:Z.validate)===null||P===void 0?void 0:P.evaluated;if(Y.props!==!0)if(q&&!q.dynamicProps){if(q.props!==void 0)Y.props=X8.mergeEvaluated.props(X,q.props,Y.props)}else{let U=X.var("props",D0._`${B}.evaluated.props`);Y.props=X8.mergeEvaluated.props(X,U,Y.props,D0.Name)}if(Y.items!==!0)if(q&&!q.dynamicItems){if(q.items!==void 0)Y.items=X8.mergeEvaluated.items(X,q.items,Y.items)}else{let U=X.var("items",D0._`${B}.evaluated.items`);Y.items=X8.mergeEvaluated.items(X,U,Y.items,D0.Name)}}}g3.callRef=Y8;g3.default=gV});var i3=L((h3)=>{Object.defineProperty(h3,"__esModule",{value:!0});var hV=y3(),iV=u3(),mV=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",hV.default,iV.default];h3.default=mV});var l3=L((m3)=>{Object.defineProperty(m3,"__esModule",{value:!0});var G8=v(),S$=G8.operators,J8={maximum:{okStr:"<=",ok:S$.LTE,fail:S$.GT},minimum:{okStr:">=",ok:S$.GTE,fail:S$.LT},exclusiveMaximum:{okStr:"<",ok:S$.LT,fail:S$.GTE},exclusiveMinimum:{okStr:">",ok:S$.GT,fail:S$.LTE}},cV={message:({keyword:$,schemaCode:w})=>G8.str`must be ${J8[$].okStr} ${w}`,params:({keyword:$,schemaCode:w})=>G8._`{comparison: ${J8[$].okStr}, limit: ${w}}`},dV={keyword:Object.keys(J8),type:"number",schemaType:"number",$data:!0,error:cV,code($){let{keyword:w,data:Z,schemaCode:W}=$;$.fail$data(G8._`${Z} ${J8[w].fail} ${W} || isNaN(${Z})`)}};m3.default=dV});var d3=L((c3)=>{Object.defineProperty(c3,"__esModule",{value:!0});var iw=v(),nV={message:({schemaCode:$})=>iw.str`must be multiple of ${$}`,params:({schemaCode:$})=>iw._`{multipleOf: ${$}}`},tV={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:nV,code($){let{gen:w,data:Z,schemaCode:W,it:X}=$,Y=X.opts.multipleOfPrecision,G=w.let("res"),J=Y?iw._`Math.abs(Math.round(${G}) - ${G}) > 1e-${Y}`:iw._`${G} !== parseInt(${G})`;$.fail$data(iw._`(${W} === 0 || (${G} = ${Z}/${W}, ${J}))`)}};c3.default=tV});var t3=L((n3)=>{Object.defineProperty(n3,"__esModule",{value:!0});function p3($){let w=$.length,Z=0,W=0,X;while(W<w)if(Z++,X=$.charCodeAt(W++),X>=55296&&X<=56319&&W<w){if(X=$.charCodeAt(W),(X&64512)===56320)W++}return Z}n3.default=p3;p3.code='require("ajv/dist/runtime/ucs2length").default'});var s3=L((r3)=>{Object.defineProperty(r3,"__esModule",{value:!0});var e$=v(),aV=l(),oV=t3(),eV={message({keyword:$,schemaCode:w}){let Z=$==="maxLength"?"more":"fewer";return e$.str`must NOT have ${Z} than ${w} characters`},params:({schemaCode:$})=>e$._`{limit: ${$}}`},$P={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:eV,code($){let{keyword:w,data:Z,schemaCode:W,it:X}=$,Y=w==="maxLength"?e$.operators.GT:e$.operators.LT,G=X.opts.unicode===!1?e$._`${Z}.length`:e$._`${(0,aV.useFunc)($.gen,oV.default)}(${Z})`;$.fail$data(e$._`${G} ${Y} ${W}`)}};r3.default=$P});var o3=L((a3)=>{Object.defineProperty(a3,"__esModule",{value:!0});var ZP=_0(),WP=l(),v1=v(),XP={message:({schemaCode:$})=>v1.str`must match pattern "${$}"`,params:({schemaCode:$})=>v1._`{pattern: ${$}}`},YP={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:XP,code($){let{gen:w,data:Z,$data:W,schema:X,schemaCode:Y,it:G}=$,J=G.opts.unicodeRegExp?"u":"";if(W){let{regExp:Q}=G.opts.code,z=Q.code==="new RegExp"?v1._`new RegExp`:(0,WP.useFunc)(w,Q),M=w.let("valid");w.try(()=>w.assign(M,v1._`${z}(${Y}, ${J}).test(${Z})`),()=>w.assign(M,!1)),$.fail$data(v1._`!${M}`)}else{let Q=(0,ZP.usePattern)($,X);$.fail$data(v1._`!${Q}.test(${Z})`)}}};a3.default=YP});var $G=L((e3)=>{Object.defineProperty(e3,"__esModule",{value:!0});var mw=v(),JP={message({keyword:$,schemaCode:w}){let Z=$==="maxProperties"?"more":"fewer";return mw.str`must NOT have ${Z} than ${w} properties`},params:({schemaCode:$})=>mw._`{limit: ${$}}`},QP={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:JP,code($){let{keyword:w,data:Z,schemaCode:W}=$,X=w==="maxProperties"?mw.operators.GT:mw.operators.LT;$.fail$data(mw._`Object.keys(${Z}).length ${X} ${W}`)}};e3.default=QP});var ZG=L((wG)=>{Object.defineProperty(wG,"__esModule",{value:!0});var lw=_0(),cw=v(),MP=l(),TP={message:({params:{missingProperty:$}})=>cw.str`must have required property '${$}'`,params:({params:{missingProperty:$}})=>cw._`{missingProperty: ${$}}`},KP={keyword:"required",type:"object",schemaType:"array",$data:!0,error:TP,code($){let{gen:w,schema:Z,schemaCode:W,data:X,$data:Y,it:G}=$,{opts:J}=G;if(!Y&&Z.length===0)return;let Q=Z.length>=J.loopRequired;if(G.allErrors)z();else M();if(J.strictRequired){let N=$.parentSchema.properties,{definedProperties:B}=$.it;for(let P of Z)if((N===null||N===void 0?void 0:N[P])===void 0&&!B.has(P)){let q=G.schemaEnv.baseId+G.errSchemaPath,U=`required property "${P}" is not defined at "${q}" (strictRequired)`;(0,MP.checkStrictMode)(G,U,G.opts.strictRequired)}}function z(){if(Q||Y)$.block$data(cw.nil,T);else for(let N of Z)(0,lw.checkReportMissingProp)($,N)}function M(){let N=w.let("missing");if(Q||Y){let B=w.let("valid",!0);$.block$data(B,()=>K(N,B)),$.ok(B)}else w.if((0,lw.checkMissingProp)($,Z,N)),(0,lw.reportMissingProp)($,N),w.else()}function T(){w.forOf("prop",W,(N)=>{$.setParams({missingProperty:N}),w.if((0,lw.noPropertyInData)(w,X,N,J.ownProperties),()=>$.error())})}function K(N,B){$.setParams({missingProperty:N}),w.forOf(N,W,()=>{w.assign(B,(0,lw.propertyInData)(w,X,N,J.ownProperties)),w.if((0,cw.not)(B),()=>{$.error(),w.break()})},cw.nil)}}};wG.default=KP});var XG=L((WG)=>{Object.defineProperty(WG,"__esModule",{value:!0});var dw=v(),BP={message({keyword:$,schemaCode:w}){let Z=$==="maxItems"?"more":"fewer";return dw.str`must NOT have ${Z} than ${w} items`},params:({schemaCode:$})=>dw._`{limit: ${$}}`},VP={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:BP,code($){let{keyword:w,data:Z,schemaCode:W}=$,X=w==="maxItems"?dw.operators.GT:dw.operators.LT;$.fail$data(dw._`${Z}.length ${X} ${W}`)}};WG.default=VP});var Q8=L((GG)=>{Object.defineProperty(GG,"__esModule",{value:!0});var YG=PZ();YG.code='require("ajv/dist/runtime/equal").default';GG.default=YG});var QG=L((JG)=>{Object.defineProperty(JG,"__esModule",{value:!0});var gZ=Cw(),M0=v(),UP=l(),HP=Q8(),FP={message:({params:{i:$,j:w}})=>M0.str`must NOT have duplicate items (items ## ${w} and ${$} are identical)`,params:({params:{i:$,j:w}})=>M0._`{i: ${$}, j: ${w}}`},OP={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:FP,code($){let{gen:w,data:Z,$data:W,schema:X,parentSchema:Y,schemaCode:G,it:J}=$;if(!W&&!X)return;let Q=w.let("valid"),z=Y.items?(0,gZ.getSchemaTypes)(Y.items):[];$.block$data(Q,M,M0._`${G} === false`),$.ok(Q);function M(){let B=w.let("i",M0._`${Z}.length`),P=w.let("j");$.setParams({i:B,j:P}),w.assign(Q,!0),w.if(M0._`${B} > 1`,()=>(T()?K:N)(B,P))}function T(){return z.length>0&&!z.some((B)=>B==="object"||B==="array")}function K(B,P){let q=w.name("item"),U=(0,gZ.checkDataTypes)(z,q,J.opts.strictNumbers,gZ.DataType.Wrong),O=w.const("indices",M0._`{}`);w.for(M0._`;${B}--;`,()=>{if(w.let(q,M0._`${Z}[${B}]`),w.if(U,M0._`continue`),z.length>1)w.if(M0._`typeof ${q} == "string"`,M0._`${q} += "_"`);w.if(M0._`typeof ${O}[${q}] == "number"`,()=>{w.assign(P,M0._`${O}[${q}]`),$.error(),w.assign(Q,!1).break()}).code(M0._`${O}[${q}] = ${B}`)})}function N(B,P){let q=(0,UP.useFunc)(w,HP.default),U=w.name("outer");w.label(U).for(M0._`;${B}--;`,()=>w.for(M0._`${P} = ${B}; ${P}--;`,()=>w.if(M0._`${q}(${Z}[${B}], ${Z}[${P}])`,()=>{$.error(),w.assign(Q,!1).break(U)})))}}};JG.default=OP});var MG=L((zG)=>{Object.defineProperty(zG,"__esModule",{value:!0});var vZ=v(),LP=l(),DP=Q8(),fP={message:"must be equal to constant",params:({schemaCode:$})=>vZ._`{allowedValue: ${$}}`},kP={keyword:"const",$data:!0,error:fP,code($){let{gen:w,data:Z,$data:W,schemaCode:X,schema:Y}=$;if(W||Y&&typeof Y=="object")$.fail$data(vZ._`!${(0,LP.useFunc)(w,DP.default)}(${Z}, ${X})`);else $.fail(vZ._`${Y} !== ${Z}`)}};zG.default=kP});var KG=L((TG)=>{Object.defineProperty(TG,"__esModule",{value:!0});var pw=v(),SP=l(),RP=Q8(),CP={message:"must be equal to one of the allowed values",params:({schemaCode:$})=>pw._`{allowedValues: ${$}}`},jP={keyword:"enum",schemaType:"array",$data:!0,error:CP,code($){let{gen:w,data:Z,$data:W,schema:X,schemaCode:Y,it:G}=$;if(!W&&X.length===0)throw Error("enum must have non-empty array");let J=X.length>=G.opts.loopEnum,Q,z=()=>Q!==null&&Q!==void 0?Q:Q=(0,SP.useFunc)(w,RP.default),M;if(J||W)M=w.let("valid"),$.block$data(M,T);else{if(!Array.isArray(X))throw Error("ajv implementation error");let N=w.const("vSchema",Y);M=(0,pw.or)(...X.map((B,P)=>K(N,P)))}$.pass(M);function T(){w.assign(M,!1),w.forOf("v",Y,(N)=>w.if(pw._`${z()}(${Z}, ${N})`,()=>w.assign(M,!0).break()))}function K(N,B){let P=X[B];return typeof P==="object"&&P!==null?pw._`${z()}(${Z}, ${N}[${B}])`:pw._`${Z} === ${P}`}}};TG.default=jP});var BG=L((NG)=>{Object.defineProperty(NG,"__esModule",{value:!0});var yP=l3(),bP=d3(),xP=s3(),_P=o3(),gP=$G(),vP=ZG(),uP=XG(),hP=QG(),iP=MG(),mP=KG(),lP=[yP.default,bP.default,xP.default,_P.default,gP.default,vP.default,uP.default,hP.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},iP.default,mP.default];NG.default=lP});var hZ=L((PG)=>{Object.defineProperty(PG,"__esModule",{value:!0});PG.validateAdditionalItems=void 0;var $1=v(),uZ=l(),dP={message:({params:{len:$}})=>$1.str`must NOT have more than ${$} items`,params:({params:{len:$}})=>$1._`{limit: ${$}}`},pP={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:dP,code($){let{parentSchema:w,it:Z}=$,{items:W}=w;if(!Array.isArray(W)){(0,uZ.checkStrictMode)(Z,'"additionalItems" is ignored when "items" is not an array of schemas');return}VG($,W)}};function VG($,w){let{gen:Z,schema:W,data:X,keyword:Y,it:G}=$;G.items=!0;let J=Z.const("len",$1._`${X}.length`);if(W===!1)$.setParams({len:w.length}),$.pass($1._`${J} <= ${w.length}`);else if(typeof W=="object"&&!(0,uZ.alwaysValidSchema)(G,W)){let z=Z.var("valid",$1._`${J} <= ${w.length}`);Z.if((0,$1.not)(z),()=>Q(z)),$.ok(z)}function Q(z){Z.forRange("i",w.length,J,(M)=>{if($.subschema({keyword:Y,dataProp:M,dataPropType:uZ.Type.Num},z),!G.allErrors)Z.if((0,$1.not)(z),()=>Z.break())})}}PG.validateAdditionalItems=VG;PG.default=pP});var iZ=L((FG)=>{Object.defineProperty(FG,"__esModule",{value:!0});FG.validateTuple=void 0;var UG=v(),z8=l(),tP=_0(),rP={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code($){let{schema:w,it:Z}=$;if(Array.isArray(w))return HG($,"additionalItems",w);if(Z.items=!0,(0,z8.alwaysValidSchema)(Z,w))return;$.ok((0,tP.validateArray)($))}};function HG($,w,Z=$.schema){let{gen:W,parentSchema:X,data:Y,keyword:G,it:J}=$;if(M(X),J.opts.unevaluated&&Z.length&&J.items!==!0)J.items=z8.mergeEvaluated.items(W,Z.length,J.items);let Q=W.name("valid"),z=W.const("len",UG._`${Y}.length`);Z.forEach((T,K)=>{if((0,z8.alwaysValidSchema)(J,T))return;W.if(UG._`${z} > ${K}`,()=>$.subschema({keyword:G,schemaProp:K,dataProp:K},Q)),$.ok(Q)});function M(T){let{opts:K,errSchemaPath:N}=J,B=Z.length,P=B===T.minItems&&(B===T.maxItems||T[w]===!1);if(K.strictTuples&&!P){let q=`"${G}" is ${B}-tuple, but minItems or maxItems/${w} are not specified or different at path "${N}"`;(0,z8.checkStrictMode)(J,q,K.strictTuples)}}}FG.validateTuple=HG;FG.default=rP});var LG=L((EG)=>{Object.defineProperty(EG,"__esModule",{value:!0});var aP=iZ(),oP={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:($)=>(0,aP.validateTuple)($,"items")};EG.default=oP});var kG=L((fG)=>{Object.defineProperty(fG,"__esModule",{value:!0});var DG=v(),$q=l(),wq=_0(),Zq=hZ(),Wq={message:({params:{len:$}})=>DG.str`must NOT have more than ${$} items`,params:({params:{len:$}})=>DG._`{limit: ${$}}`},Xq={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:Wq,code($){let{schema:w,parentSchema:Z,it:W}=$,{prefixItems:X}=Z;if(W.items=!0,(0,$q.alwaysValidSchema)(W,w))return;if(X)(0,Zq.validateAdditionalItems)($,X);else $.ok((0,wq.validateArray)($))}};fG.default=Xq});var SG=L((AG)=>{Object.defineProperty(AG,"__esModule",{value:!0});var g0=v(),M8=l(),Gq={message:({params:{min:$,max:w}})=>w===void 0?g0.str`must contain at least ${$} valid item(s)`:g0.str`must contain at least ${$} and no more than ${w} valid item(s)`,params:({params:{min:$,max:w}})=>w===void 0?g0._`{minContains: ${$}}`:g0._`{minContains: ${$}, maxContains: ${w}}`},Jq={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:Gq,code($){let{gen:w,schema:Z,parentSchema:W,data:X,it:Y}=$,G,J,{minContains:Q,maxContains:z}=W;if(Y.opts.next)G=Q===void 0?1:Q,J=z;else G=1;let M=w.const("len",g0._`${X}.length`);if($.setParams({min:G,max:J}),J===void 0&&G===0){(0,M8.checkStrictMode)(Y,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(J!==void 0&&G>J){(0,M8.checkStrictMode)(Y,'"minContains" > "maxContains" is always invalid'),$.fail();return}if((0,M8.alwaysValidSchema)(Y,Z)){let P=g0._`${M} >= ${G}`;if(J!==void 0)P=g0._`${P} && ${M} <= ${J}`;$.pass(P);return}Y.items=!0;let T=w.name("valid");if(J===void 0&&G===1)N(T,()=>w.if(T,()=>w.break()));else if(G===0){if(w.let(T,!0),J!==void 0)w.if(g0._`${X}.length > 0`,K)}else w.let(T,!1),K();$.result(T,()=>$.reset());function K(){let P=w.name("_valid"),q=w.let("count",0);N(P,()=>w.if(P,()=>B(q)))}function N(P,q){w.forRange("i",0,M,(U)=>{$.subschema({keyword:"contains",dataProp:U,dataPropType:M8.Type.Num,compositeRule:!0},P),q()})}function B(P){if(w.code(g0._`${P}++`),J===void 0)w.if(g0._`${P} >= ${G}`,()=>w.assign(T,!0).break());else if(w.if(g0._`${P} > ${J}`,()=>w.assign(T,!1).break()),G===1)w.assign(T,!0);else w.if(g0._`${P} >= ${G}`,()=>w.assign(T,!0))}}};AG.default=Jq});var bG=L((jG)=>{Object.defineProperty(jG,"__esModule",{value:!0});jG.validateSchemaDeps=jG.validatePropertyDeps=jG.error=void 0;var mZ=v(),zq=l(),nw=_0();jG.error={message:({params:{property:$,depsCount:w,deps:Z}})=>{let W=w===1?"property":"properties";return mZ.str`must have ${W} ${Z} when property ${$} is present`},params:({params:{property:$,depsCount:w,deps:Z,missingProperty:W}})=>mZ._`{property: ${$},
|
|
32
|
+
|| ${G} === "boolean" || ${X} === null`).assign(J,_._`[${X}]`)}}}function ON({gen:$,parentData:w,parentDataProperty:Z},W){$.if(_._`${w} !== undefined`,()=>$.assign(_._`${w}[${Z}]`,W))}function MZ($,w,Z,W=y1.Correct){let X=W===y1.Correct?_.operators.EQ:_.operators.NEQ,Y;switch($){case"null":return _._`${w} ${X} null`;case"array":Y=_._`Array.isArray(${w})`;break;case"object":Y=_._`${w} && typeof ${w} == "object" && !Array.isArray(${w})`;break;case"integer":Y=G(_._`!(${w} % 1) && !isNaN(${w})`);break;case"number":Y=G();break;default:return _._`typeof ${w} ${X} ${$}`}return W===y1.Correct?Y:(0,_.not)(Y);function G(J=_.nil){return(0,_.and)(_._`typeof ${w} == "number"`,J,Z?_._`isFinite(${w})`:_.nil)}}$Y.checkDataType=MZ;function TZ($,w,Z,W){if($.length===1)return MZ($[0],w,Z,W);let X,Y=(0,aX.toHash)($);if(Y.array&&Y.object){let G=_._`typeof ${w} != "object"`;X=Y.null?G:_._`!${w} || ${G}`,delete Y.null,delete Y.array,delete Y.object}else X=_.nil;if(Y.number)delete Y.integer;for(let G in Y)X=(0,_.and)(X,MZ(G,w,Z,W));return X}$Y.checkDataTypes=TZ;var EN={message:({schema:$})=>`must be ${$}`,params:({schema:$,schemaValue:w})=>typeof $=="string"?_._`{type: ${$}}`:_._`{type: ${w}}`};function NZ($){let w=LN($);(0,PN.reportError)(w,EN)}$Y.reportTypeError=NZ;function LN($){let{gen:w,data:Z,schema:W}=$,X=(0,aX.schemaRefOrVal)($,W,"type");return{gen:w,keyword:"type",data:Z,schema:W.type,schemaCode:X,schemaValue:X,parentSchema:W,params:{},it:$}}});var YY=L((WY)=>{Object.defineProperty(WY,"__esModule",{value:!0});WY.assignDefaults=void 0;var b1=v(),CN=l();function jN($,w){let{properties:Z,items:W}=$.schema;if(w==="object"&&Z)for(let X in Z)ZY($,X,Z[X].default);else if(w==="array"&&Array.isArray(W))W.forEach((X,Y)=>ZY($,Y,X.default))}WY.assignDefaults=jN;function ZY($,w,Z){let{gen:W,compositeRule:X,data:Y,opts:G}=$;if(Z===void 0)return;let J=b1._`${Y}${(0,b1.getProperty)(w)}`;if(X){(0,CN.checkStrictMode)($,`default is ignored for: ${J}`);return}let Q=b1._`${J} === undefined`;if(G.useDefaults==="empty")Q=b1._`${Q} || ${J} === null || ${J} === ""`;W.if(Q,b1._`${J} = ${(0,b1.stringify)(Z)}`)}});var _0=L((QY)=>{Object.defineProperty(QY,"__esModule",{value:!0});QY.validateUnion=QY.validateArray=QY.usePattern=QY.callValidateCode=QY.schemaProperties=QY.allSchemaProperties=QY.noPropertyInData=QY.propertyInData=QY.isOwnProperty=QY.hasPropFunc=QY.reportMissingProp=QY.checkMissingProp=QY.checkReportMissingProp=void 0;var t=v(),KZ=l(),k$=Y$(),IN=l();function yN($,w){let{gen:Z,data:W,it:X}=$;Z.if(VZ(Z,W,w,X.opts.ownProperties),()=>{$.setParams({missingProperty:t._`${w}`},!0),$.error()})}QY.checkReportMissingProp=yN;function bN({gen:$,data:w,it:{opts:Z}},W,X){return(0,t.or)(...W.map((Y)=>(0,t.and)(VZ($,w,Y,Z.ownProperties),t._`${X} = ${Y}`)))}QY.checkMissingProp=bN;function xN($,w){$.setParams({missingProperty:w},!0),$.error()}QY.reportMissingProp=xN;function GY($){return $.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:t._`Object.prototype.hasOwnProperty`})}QY.hasPropFunc=GY;function BZ($,w,Z){return t._`${GY($)}.call(${w}, ${Z})`}QY.isOwnProperty=BZ;function _N($,w,Z,W){let X=t._`${w}${(0,t.getProperty)(Z)} !== undefined`;return W?t._`${X} && ${BZ($,w,Z)}`:X}QY.propertyInData=_N;function VZ($,w,Z,W){let X=t._`${w}${(0,t.getProperty)(Z)} === undefined`;return W?(0,t.or)(X,(0,t.not)(BZ($,w,Z))):X}QY.noPropertyInData=VZ;function JY($){return $?Object.keys($).filter((w)=>w!=="__proto__"):[]}QY.allSchemaProperties=JY;function gN($,w){return JY(w).filter((Z)=>!(0,KZ.alwaysValidSchema)($,w[Z]))}QY.schemaProperties=gN;function vN({schemaCode:$,data:w,it:{gen:Z,topSchemaRef:W,schemaPath:X,errorPath:Y},it:G},J,Q,z){let M=z?t._`${$}, ${w}, ${W}${X}`:w,T=[[k$.default.instancePath,(0,t.strConcat)(k$.default.instancePath,Y)],[k$.default.parentData,G.parentData],[k$.default.parentDataProperty,G.parentDataProperty],[k$.default.rootData,k$.default.rootData]];if(G.opts.dynamicRef)T.push([k$.default.dynamicAnchors,k$.default.dynamicAnchors]);let N=t._`${M}, ${Z.object(...T)}`;return Q!==t.nil?t._`${J}.call(${Q}, ${N})`:t._`${J}(${N})`}QY.callValidateCode=vN;var uN=t._`new RegExp`;function hN({gen:$,it:{opts:w}},Z){let W=w.unicodeRegExp?"u":"",{regExp:X}=w.code,Y=X(Z,W);return $.scopeValue("pattern",{key:Y.toString(),ref:Y,code:t._`${X.code==="new RegExp"?uN:(0,IN.useFunc)($,X)}(${Z}, ${W})`})}QY.usePattern=hN;function iN($){let{gen:w,data:Z,keyword:W,it:X}=$,Y=w.name("valid");if(X.allErrors){let J=w.let("valid",!0);return G(()=>w.assign(J,!1)),J}return w.var(Y,!0),G(()=>w.break()),Y;function G(J){let Q=w.const("len",t._`${Z}.length`);w.forRange("i",0,Q,(z)=>{$.subschema({keyword:W,dataProp:z,dataPropType:KZ.Type.Num},Y),w.if((0,t.not)(Y),J)})}}QY.validateArray=iN;function mN($){let{gen:w,schema:Z,keyword:W,it:X}=$;if(!Array.isArray(Z))throw Error("ajv implementation error");if(Z.some((Q)=>(0,KZ.alwaysValidSchema)(X,Q))&&!X.opts.unevaluated)return;let G=w.let("valid",!1),J=w.name("_valid");w.block(()=>Z.forEach((Q,z)=>{let M=$.subschema({keyword:W,schemaProp:z,compositeRule:!0},J);if(w.assign(G,t._`${G} || ${J}`),!$.mergeValidEvaluated(M,J))w.if((0,t.not)(G))})),$.result(G,()=>$.reset(),()=>$.error(!0))}QY.validateUnion=mN});var BY=L((NY)=>{Object.defineProperty(NY,"__esModule",{value:!0});NY.validateKeywordUsage=NY.validSchemaType=NY.funcKeywordCode=NY.macroKeywordCode=void 0;var H0=v(),r$=Y$(),wK=_0(),ZK=Rw();function WK($,w){let{gen:Z,keyword:W,schema:X,parentSchema:Y,it:G}=$,J=w.macro.call(G.self,X,Y,G),Q=TY(Z,W,J);if(G.opts.validateSchema!==!1)G.self.validateSchema(J,!0);let z=Z.name("valid");$.subschema({schema:J,schemaPath:H0.nil,errSchemaPath:`${G.errSchemaPath}/${W}`,topSchemaRef:Q,compositeRule:!0},z),$.pass(z,()=>$.error(!0))}NY.macroKeywordCode=WK;function XK($,w){var Z;let{gen:W,keyword:X,schema:Y,parentSchema:G,$data:J,it:Q}=$;GK(Q,w);let z=!J&&w.compile?w.compile.call(Q.self,Y,G,Q):w.validate,M=TY(W,X,z),T=W.let("valid");$.block$data(T,N),$.ok((Z=w.valid)!==null&&Z!==void 0?Z:T);function N(){if(w.errors===!1){if(P(),w.modifying)MY($);q(()=>$.error())}else{let U=w.async?K():B();if(w.modifying)MY($);q(()=>YK($,U))}}function K(){let U=W.let("ruleErrs",null);return W.try(()=>P(H0._`await `),(O)=>W.assign(T,!1).if(H0._`${O} instanceof ${Q.ValidationError}`,()=>W.assign(U,H0._`${O}.errors`),()=>W.throw(O))),U}function B(){let U=H0._`${M}.errors`;return W.assign(U,null),P(H0.nil),U}function P(U=w.async?H0._`await `:H0.nil){let O=Q.opts.passContext?r$.default.this:r$.default.self,f=!(("compile"in w)&&!J||w.schema===!1);W.assign(T,H0._`${U}${(0,wK.callValidateCode)($,M,O,f)}`,w.modifying)}function q(U){var O;W.if((0,H0.not)((O=w.valid)!==null&&O!==void 0?O:T),U)}}NY.funcKeywordCode=XK;function MY($){let{gen:w,data:Z,it:W}=$;w.if(W.parentData,()=>w.assign(Z,H0._`${W.parentData}[${W.parentDataProperty}]`))}function YK($,w){let{gen:Z}=$;Z.if(H0._`Array.isArray(${w})`,()=>{Z.assign(r$.default.vErrors,H0._`${r$.default.vErrors} === null ? ${w} : ${r$.default.vErrors}.concat(${w})`).assign(r$.default.errors,H0._`${r$.default.vErrors}.length`),(0,ZK.extendErrors)($)},()=>$.error())}function GK({schemaEnv:$},w){if(w.async&&!$.$async)throw Error("async keyword in sync schema")}function TY($,w,Z){if(Z===void 0)throw Error(`keyword "${w}" failed to compile`);return $.scopeValue("keyword",typeof Z=="function"?{ref:Z}:{ref:Z,code:(0,H0.stringify)(Z)})}function JK($,w,Z=!1){return!w.length||w.some((W)=>W==="array"?Array.isArray($):W==="object"?$&&typeof $=="object"&&!Array.isArray($):typeof $==W||Z&&typeof $>"u")}NY.validSchemaType=JK;function QK({schema:$,opts:w,self:Z,errSchemaPath:W},X,Y){if(Array.isArray(X.keyword)?!X.keyword.includes(Y):X.keyword!==Y)throw Error("ajv implementation error");let G=X.dependencies;if(G===null||G===void 0?void 0:G.some((J)=>!Object.prototype.hasOwnProperty.call($,J)))throw Error(`parent schema must have dependencies of ${Y}: ${G.join(",")}`);if(X.validateSchema){if(!X.validateSchema($[Y])){let Q=`keyword "${Y}" value is invalid at path "${W}": `+Z.errorsText(X.validateSchema.errors);if(w.validateSchema==="log")Z.logger.error(Q);else throw Error(Q)}}}NY.validateKeywordUsage=QK});var UY=L((PY)=>{Object.defineProperty(PY,"__esModule",{value:!0});PY.extendSubschemaMode=PY.extendSubschemaData=PY.getSubschema=void 0;var t0=v(),VY=l();function NK($,{keyword:w,schemaProp:Z,schema:W,schemaPath:X,errSchemaPath:Y,topSchemaRef:G}){if(w!==void 0&&W!==void 0)throw Error('both "keyword" and "schema" passed, only one allowed');if(w!==void 0){let J=$.schema[w];return Z===void 0?{schema:J,schemaPath:t0._`${$.schemaPath}${(0,t0.getProperty)(w)}`,errSchemaPath:`${$.errSchemaPath}/${w}`}:{schema:J[Z],schemaPath:t0._`${$.schemaPath}${(0,t0.getProperty)(w)}${(0,t0.getProperty)(Z)}`,errSchemaPath:`${$.errSchemaPath}/${w}/${(0,VY.escapeFragment)(Z)}`}}if(W!==void 0){if(X===void 0||Y===void 0||G===void 0)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:W,schemaPath:X,topSchemaRef:G,errSchemaPath:Y}}throw Error('either "keyword" or "schema" must be passed')}PY.getSubschema=NK;function KK($,w,{dataProp:Z,dataPropType:W,data:X,dataTypes:Y,propertyName:G}){if(X!==void 0&&Z!==void 0)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:J}=w;if(Z!==void 0){let{errorPath:z,dataPathArr:M,opts:T}=w,N=J.let("data",t0._`${w.data}${(0,t0.getProperty)(Z)}`,!0);Q(N),$.errorPath=t0.str`${z}${(0,VY.getErrorPath)(Z,W,T.jsPropertySyntax)}`,$.parentDataProperty=t0._`${Z}`,$.dataPathArr=[...M,$.parentDataProperty]}if(X!==void 0){let z=X instanceof t0.Name?X:J.let("data",X,!0);if(Q(z),G!==void 0)$.propertyName=G}if(Y)$.dataTypes=Y;function Q(z){$.data=z,$.dataLevel=w.dataLevel+1,$.dataTypes=[],w.definedProperties=new Set,$.parentData=w.data,$.dataNames=[...w.dataNames,z]}}PY.extendSubschemaData=KK;function BK($,{jtdDiscriminator:w,jtdMetadata:Z,compositeRule:W,createErrors:X,allErrors:Y}){if(W!==void 0)$.compositeRule=W;if(X!==void 0)$.createErrors=X;if(Y!==void 0)$.allErrors=Y;$.jtdDiscriminator=w,$.jtdMetadata=Z}PY.extendSubschemaMode=BK});var PZ=L((CL,HY)=>{HY.exports=function $(w,Z){if(w===Z)return!0;if(w&&Z&&typeof w=="object"&&typeof Z=="object"){if(w.constructor!==Z.constructor)return!1;var W,X,Y;if(Array.isArray(w)){if(W=w.length,W!=Z.length)return!1;for(X=W;X--!==0;)if(!$(w[X],Z[X]))return!1;return!0}if(w.constructor===RegExp)return w.source===Z.source&&w.flags===Z.flags;if(w.valueOf!==Object.prototype.valueOf)return w.valueOf()===Z.valueOf();if(w.toString!==Object.prototype.toString)return w.toString()===Z.toString();if(Y=Object.keys(w),W=Y.length,W!==Object.keys(Z).length)return!1;for(X=W;X--!==0;)if(!Object.prototype.hasOwnProperty.call(Z,Y[X]))return!1;for(X=W;X--!==0;){var G=Y[X];if(!$(w[G],Z[G]))return!1}return!0}return w!==w&&Z!==Z}});var OY=L((jL,FY)=>{var A$=FY.exports=function($,w,Z){if(typeof w=="function")Z=w,w={};Z=w.cb||Z;var W=typeof Z=="function"?Z:Z.pre||function(){},X=Z.post||function(){};p4(w,W,X,$,"",$)};A$.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};A$.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};A$.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};A$.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function p4($,w,Z,W,X,Y,G,J,Q,z){if(W&&typeof W=="object"&&!Array.isArray(W)){w(W,X,Y,G,J,Q,z);for(var M in W){var T=W[M];if(Array.isArray(T)){if(M in A$.arrayKeywords)for(var N=0;N<T.length;N++)p4($,w,Z,T[N],X+"/"+M+"/"+N,Y,X,M,W,N)}else if(M in A$.propsKeywords){if(T&&typeof T=="object")for(var K in T)p4($,w,Z,T[K],X+"/"+M+"/"+qK(K),Y,X,M,W,K)}else if(M in A$.keywords||$.allKeys&&!(M in A$.skipKeywords))p4($,w,Z,T,X+"/"+M,Y,X,M,W)}Z(W,X,Y,G,J,Q,z)}}function qK($){return $.replace(/~/g,"~0").replace(/\//g,"~1")}});var jw=L((fY)=>{Object.defineProperty(fY,"__esModule",{value:!0});fY.getSchemaRefs=fY.resolveUrl=fY.normalizeId=fY._getFullPath=fY.getFullPath=fY.inlineRef=void 0;var UK=l(),HK=PZ(),FK=OY(),OK=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function EK($,w=!0){if(typeof $=="boolean")return!0;if(w===!0)return!qZ($);if(!w)return!1;return EY($)<=w}fY.inlineRef=EK;var LK=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function qZ($){for(let w in $){if(LK.has(w))return!0;let Z=$[w];if(Array.isArray(Z)&&Z.some(qZ))return!0;if(typeof Z=="object"&&qZ(Z))return!0}return!1}function EY($){let w=0;for(let Z in $){if(Z==="$ref")return 1/0;if(w++,OK.has(Z))continue;if(typeof $[Z]=="object")(0,UK.eachItem)($[Z],(W)=>w+=EY(W));if(w===1/0)return 1/0}return w}function LY($,w="",Z){if(Z!==!1)w=x1(w);let W=$.parse(w);return DY($,W)}fY.getFullPath=LY;function DY($,w){return $.serialize(w).split("#")[0]+"#"}fY._getFullPath=DY;var DK=/#\/?$/;function x1($){return $?$.replace(DK,""):""}fY.normalizeId=x1;function fK($,w,Z){return Z=x1(Z),$.resolve(w,Z)}fY.resolveUrl=fK;var kK=/^[a-z_][-a-z0-9._]*$/i;function AK($,w){if(typeof $=="boolean")return{};let{schemaId:Z,uriResolver:W}=this.opts,X=x1($[Z]||w),Y={"":X},G=LY(W,X,!1),J={},Q=new Set;return FK($,{allKeys:!0},(T,N,K,B)=>{if(B===void 0)return;let P=G+N,q=Y[B];if(typeof T[Z]=="string")q=U.call(this,T[Z]);O.call(this,T.$anchor),O.call(this,T.$dynamicAnchor),Y[N]=q;function U(f){let C=this.opts.uriResolver.resolve;if(f=x1(q?C(q,f):f),Q.has(f))throw M(f);Q.add(f);let A=this.refs[f];if(typeof A=="string")A=this.refs[A];if(typeof A=="object")z(T,A.schema,f);else if(f!==x1(P))if(f[0]==="#")z(T,J[f],f),J[f]=T;else this.refs[f]=P;return f}function O(f){if(typeof f=="string"){if(!kK.test(f))throw Error(`invalid anchor "${f}"`);U.call(this,`#${f}`)}}}),J;function z(T,N,K){if(N!==void 0&&!HK(T,N))throw M(K)}function M(T){return Error(`reference "${T}" resolves to more than one schema`)}}fY.getSchemaRefs=AK});var bw=L((iY)=>{Object.defineProperty(iY,"__esModule",{value:!0});iY.getData=iY.KeywordCxt=iY.validateFunctionCode=void 0;var jY=cX(),AY=Cw(),HZ=zZ(),n4=Cw(),yK=YY(),yw=BY(),UZ=UY(),S=v(),b=Y$(),bK=jw(),G$=l(),Iw=Rw();function xK($){if(bY($)){if(xY($),yY($)){vK($);return}}IY($,()=>(0,jY.topBoolOrEmptySchema)($))}iY.validateFunctionCode=xK;function IY({gen:$,validateName:w,schema:Z,schemaEnv:W,opts:X},Y){if(X.code.es5)$.func(w,S._`${b.default.data}, ${b.default.valCxt}`,W.$async,()=>{$.code(S._`"use strict"; ${SY(Z,X)}`),gK($,X),$.code(Y)});else $.func(w,S._`${b.default.data}, ${_K(X)}`,W.$async,()=>$.code(SY(Z,X)).code(Y))}function _K($){return S._`{${b.default.instancePath}="", ${b.default.parentData}, ${b.default.parentDataProperty}, ${b.default.rootData}=${b.default.data}${$.dynamicRef?S._`, ${b.default.dynamicAnchors}={}`:S.nil}}={}`}function gK($,w){$.if(b.default.valCxt,()=>{if($.var(b.default.instancePath,S._`${b.default.valCxt}.${b.default.instancePath}`),$.var(b.default.parentData,S._`${b.default.valCxt}.${b.default.parentData}`),$.var(b.default.parentDataProperty,S._`${b.default.valCxt}.${b.default.parentDataProperty}`),$.var(b.default.rootData,S._`${b.default.valCxt}.${b.default.rootData}`),w.dynamicRef)$.var(b.default.dynamicAnchors,S._`${b.default.valCxt}.${b.default.dynamicAnchors}`)},()=>{if($.var(b.default.instancePath,S._`""`),$.var(b.default.parentData,S._`undefined`),$.var(b.default.parentDataProperty,S._`undefined`),$.var(b.default.rootData,b.default.data),w.dynamicRef)$.var(b.default.dynamicAnchors,S._`{}`)})}function vK($){let{schema:w,opts:Z,gen:W}=$;IY($,()=>{if(Z.$comment&&w.$comment)gY($);if(lK($),W.let(b.default.vErrors,null),W.let(b.default.errors,0),Z.unevaluated)uK($);_Y($),pK($)});return}function uK($){let{gen:w,validateName:Z}=$;$.evaluated=w.const("evaluated",S._`${Z}.evaluated`),w.if(S._`${$.evaluated}.dynamicProps`,()=>w.assign(S._`${$.evaluated}.props`,S._`undefined`)),w.if(S._`${$.evaluated}.dynamicItems`,()=>w.assign(S._`${$.evaluated}.items`,S._`undefined`))}function SY($,w){let Z=typeof $=="object"&&$[w.schemaId];return Z&&(w.code.source||w.code.process)?S._`/*# sourceURL=${Z} */`:S.nil}function hK($,w){if(bY($)){if(xY($),yY($)){iK($,w);return}}(0,jY.boolOrEmptySchema)($,w)}function yY({schema:$,self:w}){if(typeof $=="boolean")return!$;for(let Z in $)if(w.RULES.all[Z])return!0;return!1}function bY($){return typeof $.schema!="boolean"}function iK($,w){let{schema:Z,gen:W,opts:X}=$;if(X.$comment&&Z.$comment)gY($);cK($),dK($);let Y=W.const("_errs",b.default.errors);_Y($,Y),W.var(w,S._`${Y} === ${b.default.errors}`)}function xY($){(0,G$.checkUnknownRules)($),mK($)}function _Y($,w){if($.opts.jtd)return RY($,[],!1,w);let Z=(0,AY.getSchemaTypes)($.schema),W=(0,AY.coerceAndCheckDataType)($,Z);RY($,Z,!W,w)}function mK($){let{schema:w,errSchemaPath:Z,opts:W,self:X}=$;if(w.$ref&&W.ignoreKeywordsWithRef&&(0,G$.schemaHasRulesButRef)(w,X.RULES))X.logger.warn(`$ref: keywords ignored in schema at path "${Z}"`)}function lK($){let{schema:w,opts:Z}=$;if(w.default!==void 0&&Z.useDefaults&&Z.strictSchema)(0,G$.checkStrictMode)($,"default is ignored in the schema root")}function cK($){let w=$.schema[$.opts.schemaId];if(w)$.baseId=(0,bK.resolveUrl)($.opts.uriResolver,$.baseId,w)}function dK($){if($.schema.$async&&!$.schemaEnv.$async)throw Error("async schema in sync schema")}function gY({gen:$,schemaEnv:w,schema:Z,errSchemaPath:W,opts:X}){let Y=Z.$comment;if(X.$comment===!0)$.code(S._`${b.default.self}.logger.log(${Y})`);else if(typeof X.$comment=="function"){let G=S.str`${W}/$comment`,J=$.scopeValue("root",{ref:w.root});$.code(S._`${b.default.self}.opts.$comment(${Y}, ${G}, ${J}.schema)`)}}function pK($){let{gen:w,schemaEnv:Z,validateName:W,ValidationError:X,opts:Y}=$;if(Z.$async)w.if(S._`${b.default.errors} === 0`,()=>w.return(b.default.data),()=>w.throw(S._`new ${X}(${b.default.vErrors})`));else{if(w.assign(S._`${W}.errors`,b.default.vErrors),Y.unevaluated)nK($);w.return(S._`${b.default.errors} === 0`)}}function nK({gen:$,evaluated:w,props:Z,items:W}){if(Z instanceof S.Name)$.assign(S._`${w}.props`,Z);if(W instanceof S.Name)$.assign(S._`${w}.items`,W)}function RY($,w,Z,W){let{gen:X,schema:Y,data:G,allErrors:J,opts:Q,self:z}=$,{RULES:M}=z;if(Y.$ref&&(Q.ignoreKeywordsWithRef||!(0,G$.schemaHasRulesButRef)(Y,M))){X.block(()=>uY($,"$ref",M.all.$ref.definition));return}if(!Q.jtd)tK($,w);X.block(()=>{for(let N of M.rules)T(N);T(M.post)});function T(N){if(!(0,HZ.shouldUseGroup)(Y,N))return;if(N.type){if(X.if((0,n4.checkDataType)(N.type,G,Q.strictNumbers)),CY($,N),w.length===1&&w[0]===N.type&&Z)X.else(),(0,n4.reportTypeError)($);X.endIf()}else CY($,N);if(!J)X.if(S._`${b.default.errors} === ${W||0}`)}}function CY($,w){let{gen:Z,schema:W,opts:{useDefaults:X}}=$;if(X)(0,yK.assignDefaults)($,w.type);Z.block(()=>{for(let Y of w.rules)if((0,HZ.shouldUseRule)(W,Y))uY($,Y.keyword,Y.definition,w.type)})}function tK($,w){if($.schemaEnv.meta||!$.opts.strictTypes)return;if(rK($,w),!$.opts.allowUnionTypes)sK($,w);aK($,$.dataTypes)}function rK($,w){if(!w.length)return;if(!$.dataTypes.length){$.dataTypes=w;return}w.forEach((Z)=>{if(!vY($.dataTypes,Z))FZ($,`type "${Z}" not allowed by context "${$.dataTypes.join(",")}"`)}),eK($,w)}function sK($,w){if(w.length>1&&!(w.length===2&&w.includes("null")))FZ($,"use allowUnionTypes to allow union type keyword")}function aK($,w){let Z=$.self.RULES.all;for(let W in Z){let X=Z[W];if(typeof X=="object"&&(0,HZ.shouldUseRule)($.schema,X)){let{type:Y}=X.definition;if(Y.length&&!Y.some((G)=>oK(w,G)))FZ($,`missing type "${Y.join(",")}" for keyword "${W}"`)}}}function oK($,w){return $.includes(w)||w==="number"&&$.includes("integer")}function vY($,w){return $.includes(w)||w==="integer"&&$.includes("number")}function eK($,w){let Z=[];for(let W of $.dataTypes)if(vY(w,W))Z.push(W);else if(w.includes("integer")&&W==="number")Z.push("integer");$.dataTypes=Z}function FZ($,w){let Z=$.schemaEnv.baseId+$.errSchemaPath;w+=` at "${Z}" (strictTypes)`,(0,G$.checkStrictMode)($,w,$.opts.strictTypes)}class OZ{constructor($,w,Z){if((0,yw.validateKeywordUsage)($,w,Z),this.gen=$.gen,this.allErrors=$.allErrors,this.keyword=Z,this.data=$.data,this.schema=$.schema[Z],this.$data=w.$data&&$.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,G$.schemaRefOrVal)($,this.schema,Z,this.$data),this.schemaType=w.schemaType,this.parentSchema=$.schema,this.params={},this.it=$,this.def=w,this.$data)this.schemaCode=$.gen.const("vSchema",hY(this.$data,$));else if(this.schemaCode=this.schemaValue,!(0,yw.validSchemaType)(this.schema,w.schemaType,w.allowUndefined))throw Error(`${Z} value must be ${JSON.stringify(w.schemaType)}`);if("code"in w?w.trackErrors:w.errors!==!1)this.errsCount=$.gen.const("_errs",b.default.errors)}result($,w,Z){this.failResult((0,S.not)($),w,Z)}failResult($,w,Z){if(this.gen.if($),Z)Z();else this.error();if(w){if(this.gen.else(),w(),this.allErrors)this.gen.endIf()}else if(this.allErrors)this.gen.endIf();else this.gen.else()}pass($,w){this.failResult((0,S.not)($),void 0,w)}fail($){if($===void 0){if(this.error(),!this.allErrors)this.gen.if(!1);return}if(this.gen.if($),this.error(),this.allErrors)this.gen.endIf();else this.gen.else()}fail$data($){if(!this.$data)return this.fail($);let{schemaCode:w}=this;this.fail(S._`${w} !== undefined && (${(0,S.or)(this.invalid$data(),$)})`)}error($,w,Z){if(w){this.setParams(w),this._error($,Z),this.setParams({});return}this._error($,Z)}_error($,w){($?Iw.reportExtraError:Iw.reportError)(this,this.def.error,w)}$dataError(){(0,Iw.reportError)(this,this.def.$dataError||Iw.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error('add "trackErrors" to keyword definition');(0,Iw.resetErrorsCount)(this.gen,this.errsCount)}ok($){if(!this.allErrors)this.gen.if($)}setParams($,w){if(w)Object.assign(this.params,$);else this.params=$}block$data($,w,Z=S.nil){this.gen.block(()=>{this.check$data($,Z),w()})}check$data($=S.nil,w=S.nil){if(!this.$data)return;let{gen:Z,schemaCode:W,schemaType:X,def:Y}=this;if(Z.if((0,S.or)(S._`${W} === undefined`,w)),$!==S.nil)Z.assign($,!0);if(X.length||Y.validateSchema){if(Z.elseIf(this.invalid$data()),this.$dataError(),$!==S.nil)Z.assign($,!1)}Z.else()}invalid$data(){let{gen:$,schemaCode:w,schemaType:Z,def:W,it:X}=this;return(0,S.or)(Y(),G());function Y(){if(Z.length){if(!(w instanceof S.Name))throw Error("ajv implementation error");let J=Array.isArray(Z)?Z:[Z];return S._`${(0,n4.checkDataTypes)(J,w,X.opts.strictNumbers,n4.DataType.Wrong)}`}return S.nil}function G(){if(W.validateSchema){let J=$.scopeValue("validate$data",{ref:W.validateSchema});return S._`!${J}(${w})`}return S.nil}}subschema($,w){let Z=(0,UZ.getSubschema)(this.it,$);(0,UZ.extendSubschemaData)(Z,this.it,$),(0,UZ.extendSubschemaMode)(Z,$);let W={...this.it,...Z,items:void 0,props:void 0};return hK(W,w),W}mergeEvaluated($,w){let{it:Z,gen:W}=this;if(!Z.opts.unevaluated)return;if(Z.props!==!0&&$.props!==void 0)Z.props=G$.mergeEvaluated.props(W,$.props,Z.props,w);if(Z.items!==!0&&$.items!==void 0)Z.items=G$.mergeEvaluated.items(W,$.items,Z.items,w)}mergeValidEvaluated($,w){let{it:Z,gen:W}=this;if(Z.opts.unevaluated&&(Z.props!==!0||Z.items!==!0))return W.if(w,()=>this.mergeEvaluated($,S.Name)),!0}}iY.KeywordCxt=OZ;function uY($,w,Z,W){let X=new OZ($,Z,w);if("code"in Z)Z.code(X,W);else if(X.$data&&Z.validate)(0,yw.funcKeywordCode)(X,Z);else if("macro"in Z)(0,yw.macroKeywordCode)(X,Z);else if(Z.compile||Z.validate)(0,yw.funcKeywordCode)(X,Z)}var $B=/^\/(?:[^~]|~0|~1)*$/,wB=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function hY($,{dataLevel:w,dataNames:Z,dataPathArr:W}){let X,Y;if($==="")return b.default.rootData;if($[0]==="/"){if(!$B.test($))throw Error(`Invalid JSON-pointer: ${$}`);X=$,Y=b.default.rootData}else{let z=wB.exec($);if(!z)throw Error(`Invalid JSON-pointer: ${$}`);let M=+z[1];if(X=z[2],X==="#"){if(M>=w)throw Error(Q("property/index",M));return W[w-M]}if(M>w)throw Error(Q("data",M));if(Y=Z[w-M],!X)return Y}let G=Y,J=X.split("/");for(let z of J)if(z)Y=S._`${Y}${(0,S.getProperty)((0,G$.unescapeJsonPointer)(z))}`,G=S._`${G} && ${Y}`;return G;function Q(z,M){return`Cannot access ${z} ${M} levels up, current level is ${w}`}}iY.getData=hY});var t4=L((cY)=>{Object.defineProperty(cY,"__esModule",{value:!0});class lY extends Error{constructor($){super("validation failed");this.errors=$,this.ajv=this.validation=!0}}cY.default=lY});var xw=L((pY)=>{Object.defineProperty(pY,"__esModule",{value:!0});var EZ=jw();class dY extends Error{constructor($,w,Z,W){super(W||`can't resolve reference ${Z} from id ${w}`);this.missingRef=(0,EZ.resolveUrl)($,w,Z),this.missingSchema=(0,EZ.normalizeId)((0,EZ.getFullPath)($,this.missingRef))}}pY.default=dY});var s4=L((rY)=>{Object.defineProperty(rY,"__esModule",{value:!0});rY.resolveSchema=rY.getCompilingSchema=rY.resolveRef=rY.compileSchema=rY.SchemaEnv=void 0;var m0=v(),GB=t4(),s$=Y$(),l0=jw(),nY=l(),JB=bw();class _w{constructor($){var w;this.refs={},this.dynamicAnchors={};let Z;if(typeof $.schema=="object")Z=$.schema;this.schema=$.schema,this.schemaId=$.schemaId,this.root=$.root||this,this.baseId=(w=$.baseId)!==null&&w!==void 0?w:(0,l0.normalizeId)(Z===null||Z===void 0?void 0:Z[$.schemaId||"$id"]),this.schemaPath=$.schemaPath,this.localRefs=$.localRefs,this.meta=$.meta,this.$async=Z===null||Z===void 0?void 0:Z.$async,this.refs={}}}rY.SchemaEnv=_w;function DZ($){let w=tY.call(this,$);if(w)return w;let Z=(0,l0.getFullPath)(this.opts.uriResolver,$.root.baseId),{es5:W,lines:X}=this.opts.code,{ownProperties:Y}=this.opts,G=new m0.CodeGen(this.scope,{es5:W,lines:X,ownProperties:Y}),J;if($.$async)J=G.scopeValue("Error",{ref:GB.default,code:m0._`require("ajv/dist/runtime/validation_error").default`});let Q=G.scopeName("validate");$.validateName=Q;let z={gen:G,allErrors:this.opts.allErrors,data:s$.default.data,parentData:s$.default.parentData,parentDataProperty:s$.default.parentDataProperty,dataNames:[s$.default.data],dataPathArr:[m0.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:G.scopeValue("schema",this.opts.code.source===!0?{ref:$.schema,code:(0,m0.stringify)($.schema)}:{ref:$.schema}),validateName:Q,ValidationError:J,schema:$.schema,schemaEnv:$,rootId:Z,baseId:$.baseId||Z,schemaPath:m0.nil,errSchemaPath:$.schemaPath||(this.opts.jtd?"":"#"),errorPath:m0._`""`,opts:this.opts,self:this},M;try{this._compilations.add($),(0,JB.validateFunctionCode)(z),G.optimize(this.opts.code.optimize);let T=G.toString();if(M=`${G.scopeRefs(s$.default.scope)}return ${T}`,this.opts.code.process)M=this.opts.code.process(M,$);let K=Function(`${s$.default.self}`,`${s$.default.scope}`,M)(this,this.scope.get());if(this.scope.value(Q,{ref:K}),K.errors=null,K.schema=$.schema,K.schemaEnv=$,$.$async)K.$async=!0;if(this.opts.code.source===!0)K.source={validateName:Q,validateCode:T,scopeValues:G._values};if(this.opts.unevaluated){let{props:B,items:P}=z;if(K.evaluated={props:B instanceof m0.Name?void 0:B,items:P instanceof m0.Name?void 0:P,dynamicProps:B instanceof m0.Name,dynamicItems:P instanceof m0.Name},K.source)K.source.evaluated=(0,m0.stringify)(K.evaluated)}return $.validate=K,$}catch(T){if(delete $.validate,delete $.validateName,M)this.logger.error("Error compiling schema, function code:",M);throw T}finally{this._compilations.delete($)}}rY.compileSchema=DZ;function QB($,w,Z){var W;Z=(0,l0.resolveUrl)(this.opts.uriResolver,w,Z);let X=$.refs[Z];if(X)return X;let Y=TB.call(this,$,Z);if(Y===void 0){let G=(W=$.localRefs)===null||W===void 0?void 0:W[Z],{schemaId:J}=this.opts;if(G)Y=new _w({schema:G,schemaId:J,root:$,baseId:w})}if(Y===void 0)return;return $.refs[Z]=zB.call(this,Y)}rY.resolveRef=QB;function zB($){if((0,l0.inlineRef)($.schema,this.opts.inlineRefs))return $.schema;return $.validate?$:DZ.call(this,$)}function tY($){for(let w of this._compilations)if(MB(w,$))return w}rY.getCompilingSchema=tY;function MB($,w){return $.schema===w.schema&&$.root===w.root&&$.baseId===w.baseId}function TB($,w){let Z;while(typeof(Z=this.refs[w])=="string")w=Z;return Z||this.schemas[w]||r4.call(this,$,w)}function r4($,w){let Z=this.opts.uriResolver.parse(w),W=(0,l0._getFullPath)(this.opts.uriResolver,Z),X=(0,l0.getFullPath)(this.opts.uriResolver,$.baseId,void 0);if(Object.keys($.schema).length>0&&W===X)return LZ.call(this,Z,$);let Y=(0,l0.normalizeId)(W),G=this.refs[Y]||this.schemas[Y];if(typeof G=="string"){let J=r4.call(this,$,G);if(typeof(J===null||J===void 0?void 0:J.schema)!=="object")return;return LZ.call(this,Z,J)}if(typeof(G===null||G===void 0?void 0:G.schema)!=="object")return;if(!G.validate)DZ.call(this,G);if(Y===(0,l0.normalizeId)(w)){let{schema:J}=G,{schemaId:Q}=this.opts,z=J[Q];if(z)X=(0,l0.resolveUrl)(this.opts.uriResolver,X,z);return new _w({schema:J,schemaId:Q,root:$,baseId:X})}return LZ.call(this,Z,G)}rY.resolveSchema=r4;var NB=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function LZ($,{baseId:w,schema:Z,root:W}){var X;if(((X=$.fragment)===null||X===void 0?void 0:X[0])!=="/")return;for(let J of $.fragment.slice(1).split("/")){if(typeof Z==="boolean")return;let Q=Z[(0,nY.unescapeFragment)(J)];if(Q===void 0)return;Z=Q;let z=typeof Z==="object"&&Z[this.opts.schemaId];if(!NB.has(J)&&z)w=(0,l0.resolveUrl)(this.opts.uriResolver,w,z)}let Y;if(typeof Z!="boolean"&&Z.$ref&&!(0,nY.schemaHasRulesButRef)(Z,this.RULES)){let J=(0,l0.resolveUrl)(this.opts.uriResolver,w,Z.$ref);Y=r4.call(this,W,J)}let{schemaId:G}=this.opts;if(Y=Y||new _w({schema:Z,schemaId:G,root:W,baseId:w}),Y.schema!==Y.root.schema)return Y;return}});var aY=L((gL,qB)=>{qB.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var CZ=L((vL,XG)=>{var UB=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),kZ=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),a$=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),AZ=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),eY=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),SZ=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),HB=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),L0=Array(256);for(let w=0;w<256;w++)L0[w]="%"+"0123456789ABCDEF"[w>>4]+"0123456789ABCDEF"[w&15];function K0($){if($<2048)return L0[192|$>>6]+L0[128|$&63];if($<65536)return L0[224|$>>12]+L0[128|$>>6&63]+L0[128|$&63];return L0[240|$>>18]+L0[128|$>>12&63]+L0[128|$>>6&63]+L0[128|$&63]}function FB($){let w="",Z=0,W=0;for(W=0;W<$.length;W++){if(Z=$[W].charCodeAt(0),Z===48)continue;if(!(Z>=48&&Z<=57||Z>=65&&Z<=70||Z>=97&&Z<=102))return"";w+=$[W];break}for(W+=1;W<$.length;W++){if(Z=$[W].charCodeAt(0),!(Z>=48&&Z<=57||Z>=65&&Z<=70||Z>=97&&Z<=102))return"";w+=$[W]}return w}var OB=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),EB=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),LB=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),DB=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function fB($){if($.length===0)return!1;for(let w=0;w<$.length;w++){if(LB($[w]))continue;if($[w]==="%"&&w+2<$.length&&a$($.slice(w+1,w+3))){w+=2;continue}return!1}return!0}function oY($){let w=-1,Z=0,W=-1,X=0;for(let J=0;J<$.length;J++)if($[J]==="0"){if(W===-1)W=J;if(X++,X>Z)Z=X,w=W}else W=-1,X=0;if(Z<2)return $.join(":");let Y=$.slice(0,w).join(":"),G=$.slice(w+Z).join(":");return Y+"::"+G}function kB($){let w=$.indexOf("::");if(w!==-1&&$.indexOf("::",w+1)!==-1)return;let Z=w===-1?$.split(":"):$.slice(0,w).split(":"),W=w===-1?[]:$.slice(w+2).split(":");if(w!==-1){if(Z.length===1&&Z[0]==="")Z.length=0;if(W.length===1&&W[0]==="")W.length=0}let X=Z.concat(W),Y=0;for(let J=0;J<X.length;J++){let Q=X[J];if(Q==="")return;if(Q.indexOf(".")!==-1){if(J!==X.length-1||w!==-1&&W.length===0||!kZ(Q))return;Y+=2;continue}if(!OB(Q))return;X[J]=parseInt(Q,16).toString(16),Y++}if(w===-1){if(Y!==8)return;return oY(X)}if(Y>=8)return;let G=X.slice(0,Z.length);for(let J=Y;J<8;J++)G.push("0");for(let J=Z.length;J<X.length;J++)G.push(X[J]);return oY(G)}function fZ($){let w=$[0]==="["&&$[$.length-1]==="]";if(($[0]==="["||$[$.length-1]==="]")&&!w)return{host:$,isIPV6:!1,error:!0};let W=w?$.slice(1,-1):$;if(w&&EB(W))return W=W.toLowerCase(),{host:`[${W}]`,escapedHost:W,isIPV6:!1,isIPVFuture:!0};if(AB(W,":")<2)return{host:$,isIPV6:!1,error:w};let X="",Y=W.indexOf("%");if(Y!==-1){let J=W.slice(Y,Y+3).toLowerCase()==="%25"?3:1;if(X=W.slice(Y+J),!fB(X))return{host:$,isIPV6:!1,error:!0};W=W.slice(0,Y)}let G=kB(W);if(G===void 0)return{host:$,isIPV6:!1,error:!0};return{host:G+(X?"%"+X:""),escapedHost:G+(X?"%25"+X:""),isIPV6:!0}}function AB($,w){let Z=0;for(let W=0;W<$.length;W++)if($[W]===w)Z++;return Z}function SB($){let w=$,Z=[],W=-1,X=0;while(X=w.length){if(X===1)if(w===".")break;else if(w==="/"){Z.push("/");break}else{Z.push(w);break}else if(X===2){if(w[0]==="."){if(w[1]===".")break;else if(w[1]==="/"){w=w.slice(2);continue}}else if(w[0]==="/"){if(w[1]==="."||w[1]==="/"){Z.push("/");break}}}else if(X===3){if(w==="/.."){if(Z.length!==0)Z.pop();Z.push("/");break}}if(w[0]==="."){if(w[1]==="."){if(w[2]==="/"){w=w.slice(3);continue}}else if(w[1]==="/"){w=w.slice(2);continue}}else if(w[0]==="/"){if(w[1]==="."){if(w[2]==="/"){w=w.slice(2);continue}else if(w[2]==="."){if(w[3]==="/"){if(w=w.slice(3),Z.length!==0)Z.pop();continue}}}}if((W=w.indexOf("/",1))===-1){Z.push(w);break}else Z.push(w.slice(0,W)),w=w.slice(W)}return Z.join("")}var RB={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},CB=/[@/?#:]/g,jB=/[@/?#]/g;function $G($,w){let Z=w?jB:CB;return Z.lastIndex=0,$.replace(Z,(W)=>RB[W])}function wG($,w=!1){if($.indexOf("%")===-1)return $;let Z="";for(let W=0;W<$.length;W++){if($[W]==="%"&&W+2<$.length){let X=$.slice(W+1,W+3);if(a$(X)){let Y=X.toUpperCase(),G=String.fromCharCode(parseInt(Y,16));if(w&&AZ(G))Z+=G;else Z+="%"+Y;W+=2;continue}}Z+=$[W]}return Z}function IB($){let w="";for(let Z=0;Z<$.length;Z++){let W=$[Z];if(W==="%"&&Z+2<$.length){let X=$.slice(Z+1,Z+3);if(a$(X)){let Y=X.toUpperCase(),G=String.fromCharCode(parseInt(Y,16));if(G!=="."&&AZ(G))w+=G;else w+="%"+Y;Z+=2;continue}}if(eY(W))w+=W;else{let X=$.charCodeAt(Z);if(X<128)w+=WG(X)?W:L0[X];else if(X<55296||X>57343)w+=K0(X);else if(X<=56319&&Z+1<$.length){let Y=$.charCodeAt(Z+1);if(Y>=56320&&Y<=57343)w+=K0(65536+(X-55296<<10)+(Y-56320)),Z++;else w+=K0(65533)}else w+=K0(65533)}}return w}function yB($,w=!1){let Z="",W=w&&$[0]!=="/";for(let X=0;X<$.length;X++){let Y=$[X];if(Y==="%"&&X+2<$.length){let G=$.slice(X+1,X+3);if(a$(G)){Z+="%"+G.toUpperCase(),X+=2;continue}}if(Y==="/")W=!1;if(eY(Y)&&(Y!==":"||!W))Z+=Y;else{let G=$.charCodeAt(X);if(G<128)Z+=L0[G];else if(G<55296||G>57343)Z+=K0(G);else if(G<=56319&&X+1<$.length){let J=$.charCodeAt(X+1);if(J>=56320&&J<=57343)Z+=K0(65536+(G-55296<<10)+(J-56320)),X++;else Z+=K0(65533)}else Z+=K0(65533)}}return Z}function RZ($,w){let Z="";for(let W=0;W<$.length;W++){let X=$[W];if(X==="%"&&W+2<$.length){let Y=$.slice(W+1,W+3);if(a$(Y)){Z+="%"+Y.toUpperCase(),W+=2;continue}}if(w(X))Z+=X;else{let Y=$.charCodeAt(W);if(Y<128)Z+=L0[Y];else if(Y<55296||Y>57343)Z+=K0(Y);else if(Y<=56319&&W+1<$.length){let G=$.charCodeAt(W+1);if(G>=56320&&G<=57343)Z+=K0(65536+(Y-55296<<10)+(G-56320)),W++;else Z+=K0(65533)}else Z+=K0(65533)}}return Z}function ZG($){return RZ($,HB)}function bB($){return RZ($,SZ)}function xB($){return RZ($,SZ)}function WG($){return $>=48&&$<=57||$>=65&&$<=90||$>=97&&$<=122||$===42||$===43||$===45||$===46||$===47||$===64||$===95}function _B($){let w="";for(let Z=0;Z<$.length;Z++){let W=$[Z];if(W==="%"&&Z+2<$.length){let X=$.slice(Z+1,Z+3);if(a$(X)){let Y=X.toUpperCase(),G=String.fromCharCode(parseInt(Y,16));if(AZ(G))w+=G;else w+="%"+Y;Z+=2;continue}}if(SZ(W))w+=W;else{let X=$.charCodeAt(Z);if(X<128)w+=WG(X)?W:L0[X];else if(X<55296||X>57343)w+=K0(X);else if(X<=56319&&Z+1<$.length){let Y=$.charCodeAt(Z+1);if(Y>=56320&&Y<=57343)w+=K0(65536+(X-55296<<10)+(Y-56320)),Z++;else w+=K0(65533)}else w+=K0(65533)}}return w}function gB($){let w="";for(let Z=0;Z<$.length;Z++){if($[Z]==="%"&&Z+2<$.length){let W=$.slice(Z+1,Z+3);if(a$(W)){w+="%"+W.toUpperCase(),Z+=2;continue}}w+=escape($[Z])}return w}function vB($){let w=[];if($.userinfo!==void 0)w.push(ZG($.userinfo)),w.push("@");if($.host!==void 0){let Z=$.host;if(!kZ(Z)){let W=fZ(Z);if(W.isIPV6!==!0&&W.isIPVFuture!==!0)Z=wG(Z,!0),W=fZ(Z);if(W.isIPV6===!0||W.isIPVFuture===!0)Z=`[${W.escapedHost}]`;else Z=$G(Z,!1)}w.push(Z)}if(typeof $.port==="number"||typeof $.port==="string")w.push(":"),w.push(String($.port));return w.length?w.join(""):void 0}XG.exports={nonSimpleDomain:DB,recomposeAuthority:vB,reescapeHostDelimiters:$G,normalizePercentEncoding:wG,normalizePathEncoding:IB,serializePathEncoding:yB,normalizeQueryFragmentEncoding:_B,encodeUserinfo:ZG,encodeQuery:bB,encodeFragment:xB,escapePreservingEscapes:gB,removeDotSegments:SB,isIPv4:kZ,isUUID:UB,normalizeIPv6:fZ,stringArrayToHexStripped:FB}});var zG=L((uL,QG)=>{var{isUUID:uB}=CZ(),hB=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,iB=["http","https","ws","wss","urn","urn:uuid"];function mB($){return iB.indexOf($)!==-1}function jZ($){if($.secure===!0)return!0;else if($.secure===!1)return!1;else if($.scheme)return $.scheme.length===3&&($.scheme[0]==="w"||$.scheme[0]==="W")&&($.scheme[1]==="s"||$.scheme[1]==="S")&&($.scheme[2]==="s"||$.scheme[2]==="S");else return!1}function YG($){if(!$.host)$.error=$.error||"HTTP URIs must have a host.";return $}function GG($){let w=String($.scheme).toLowerCase()==="https";if($.port===(w?443:80)||$.port==="")$.port=void 0;if(!$.path)$.path="/";return $}function lB($){return $.secure=jZ($),$.resourceName=($.path||"/")+($.query?"?"+$.query:""),$.path=void 0,$.query=void 0,$}function cB($){if($.port===(jZ($)?443:80)||$.port==="")$.port=void 0;if(typeof $.secure==="boolean")$.scheme=$.secure?"wss":"ws",$.secure=void 0;if($.resourceName){let w=$.resourceName.indexOf("?"),Z=w===-1?$.resourceName:$.resourceName.slice(0,w);$.path=Z&&Z!=="/"?Z:void 0,$.query=w===-1?void 0:$.resourceName.slice(w+1),$.resourceName=void 0}return $.fragment=void 0,$}function dB($,w){if(!$.path)return $.error="URN can not be parsed",$;let Z=$.path.match(hB);if(Z&&Z[0]===$.path){let W=w.scheme||$.scheme||"urn";$.nid=Z[1].toLowerCase(),$.nss=Z[2];let X=`${W}:${w.nid||$.nid}`,Y=IZ(X);if($.path=void 0,Y)$=Y.parse($,w)}else $.error=$.error||"URN can not be parsed.";return $}function pB($,w){if($.nid===void 0)throw Error("URN without nid cannot be serialized");let Z=w.scheme||$.scheme||"urn",W=$.nid.toLowerCase(),X=`${Z}:${w.nid||W}`,Y=IZ(X);if(Y)$=Y.serialize($,w);let G=$,J=$.nss;return G.path=`${W||w.nid}:${J}`,w.skipEscape=!0,G}function nB($,w){let Z=$;if(Z.uuid=Z.nss,Z.nss=void 0,!w.tolerant&&(!Z.uuid||!uB(Z.uuid)))Z.error=Z.error||"UUID is not valid.";return Z}function tB($){let w=$;return w.nss=($.uuid||"").toLowerCase(),w}var JG={scheme:"http",domainHost:!0,parse:YG,serialize:GG},rB={scheme:"https",domainHost:JG.domainHost,parse:YG,serialize:GG},a4={scheme:"ws",domainHost:!0,parse:lB,serialize:cB},sB={scheme:"wss",domainHost:a4.domainHost,parse:a4.parse,serialize:a4.serialize},aB={scheme:"urn",parse:dB,serialize:pB,skipNormalize:!0},oB={scheme:"urn:uuid",parse:nB,serialize:tB,skipNormalize:!0},o4={http:JG,https:rB,ws:a4,wss:sB,urn:aB,"urn:uuid":oB};Object.setPrototypeOf(o4,null);function IZ($){return $&&(o4[$]||o4[$.toLowerCase()])||void 0}QG.exports={wsIsSecure:jZ,SCHEMES:o4,isValidSchemeName:mB,getSchemeHandler:IZ}});var EG=L((hL,w8)=>{var{normalizeIPv6:BG,removeDotSegments:vw,recomposeAuthority:eB,normalizePercentEncoding:VG,normalizePathEncoding:$V,serializePathEncoding:MG,normalizeQueryFragmentEncoding:TG,encodeQuery:wV,encodeFragment:ZV,reescapeHostDelimiters:WV,isIPv4:PG,nonSimpleDomain:XV}=CZ(),{SCHEMES:qG,getSchemeHandler:yZ}=zG(),UG=/^[A-Za-z][A-Za-z0-9+.-]*$/u;function NG($){let w=unescape(String($));if(!UG.test(w))throw TypeError("URI scheme is malformed.");return w}function YV($,w){if(typeof $==="string")$=KV($,w);else if(typeof $==="object")$=$8(o$($,w),w);return $}function GV($,w,Z){let W=Z?Object.assign({scheme:"null"},Z):{scheme:"null"},{parsed:X,malformedAuthorityOrPort:Y,malformedPercentEncoding:G,malformedSchemeSpecific:J,malformedHost:Q,malformedScheme:z}=e4($,W),{parsed:M,malformedAuthorityOrPort:T,malformedPercentEncoding:N,malformedSchemeSpecific:K,malformedHost:B,malformedScheme:P}=e4(w,W);if(Y||T||G||N||J||K||Q||B||z||P)throw Error(X.error||M.error||"URI is malformed.");let q=HG(X,M,W,!0),U=yZ(Z&&Z.scheme||q.scheme),O=q.host,f=O!==void 0&&O!==""&&(PG(O)||BG(O).isIPV6);FG(q,Z||{},U,f);let C=O&&O.indexOf("%")!==-1&&!/\P{ASCII}/u.test(O);if(q.error&&!C)throw Error(q.error);return W.skipEscape=!0,o$(q,W)}function HG($,w,Z,W){let X={};if(!W)$=$8(o$($,Z),Z),w=$8(o$(w,Z),Z);if(Z=Z||{},!Z.tolerant&&w.scheme)X.scheme=w.scheme,X.userinfo=w.userinfo,X.host=w.host,X.port=w.port,X.path=vw(w.path||""),X.query=w.query;else{if(w.userinfo!==void 0||w.host!==void 0||w.port!==void 0)X.userinfo=w.userinfo,X.host=w.host,X.port=w.port,X.path=vw(w.path||""),X.query=w.query;else{if(!w.path)if(X.path=$.path,w.query!==void 0)X.query=w.query;else X.query=$.query;else{if(w.path[0]==="/")X.path=vw(w.path);else{if(($.userinfo!==void 0||$.host!==void 0||$.port!==void 0)&&!$.path)X.path="/"+w.path;else if(!$.path)X.path=w.path;else X.path=$.path.slice(0,$.path.lastIndexOf("/")+1)+w.path;X.path=vw(X.path)}X.query=w.query}X.userinfo=$.userinfo,X.host=$.host,X.port=$.port}X.scheme=$.scheme}return X.fragment=w.fragment,X}function JV($,w,Z){let W=KG($,Z),X=KG(w,Z);return W!==void 0&&X!==void 0&&W===X}function o$($,w){let Z={host:$.host,scheme:$.scheme,userinfo:$.userinfo,port:$.port,path:$.path,query:$.query,nid:$.nid,nss:$.nss,uuid:$.uuid,fragment:$.fragment,reference:$.reference,resourceName:$.resourceName,secure:$.secure,error:""},W=Object.assign({},w),X=[];if(Z.scheme)Z.scheme=NG(Z.scheme);let Y=yZ(W.scheme||Z.scheme);if(Y&&Y.serialize)Y.serialize(Z,W);let G=Z.userinfo!==void 0||Z.host!==void 0||Z.port!==void 0,J=!W.skipEscape&&Z.scheme===void 0&&!G;if(Z.path!==void 0)if(!W.skipEscape)Z.path=MG(Z.path,J);else Z.path=VG(Z.path);if(W.reference!=="suffix"&&Z.scheme)Z.scheme=NG(Z.scheme),X.push(Z.scheme,":");let Q=eB(Z);if(Q!==void 0){if(W.reference!=="suffix")X.push("//");if(X.push(Q),Z.path&&Z.path[0]!=="/")X.push("/")}if(Z.path!==void 0){let z=Z.path;if(!W.absolutePath&&(!Y||!Y.absolutePath))z=vw(z);if(J)z=MG(z,!0);if(Q===void 0&&z[0]==="/"&&z[1]==="/")z="/%2F"+z.slice(2);X.push(z)}if(Z.query!==void 0)X.push("?",wV(Z.query));if(Z.fragment!==void 0)X.push("#",ZV(Z.fragment));return X.join("")}var QV=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,zV=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,MV=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function TV($,w){if(w[2]!==void 0&&$.path&&$.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof $.port==="number"&&($.port<0||$.port>65535))return"URI port is malformed.";return}function gw($){if($===void 0)return!1;let w=$.indexOf("%");while(w!==-1){if(w+2>=$.length||!/^[\da-f]{2}$/iu.test($.slice(w+1,w+3)))return!0;w=$.indexOf("%",w+3)}return!1}function NV($){let w=$[4];return gw($[3])||w!==void 0&&!(w[0]==="["&&w[w.length-1]==="]")&&gw(w)||gw($[6])||gw($[7])||gw($[8])}function FG($,w,Z,W){if(!w.unicodeSupport&&(!Z||!Z.unicodeSupport)&&$.host&&$.host[0]!=="["&&(w.domainHost||Z&&Z.domainHost)&&W===!1&&XV($.host))try{$.host=new URL("http://"+$.host).hostname}catch(X){return $.error=$.error||"Host's domain name can not be converted to ASCII: "+X,!0}return!1}function e4($,w){let Z=Object.assign({},w),W={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},X=!1,Y=!1,G=!1,J=!1,Q=!1,z=!1,M=!1;if(Z.reference==="suffix")if(Z.scheme)$=Z.scheme+":"+$;else $="//"+$;let T=$.match(zV);if(T!==null&&T[1].indexOf("\\")!==-1)W.error="URI authority must not contain a literal backslash.",X=!0;let N=$.match(MV);if(N!==null){let B=N[1],P=B.replace(/[\t\n\r]/g,"");if(P.length>=2){if(P.slice(0,2)!=="//")W.error=W.error||"URI authority must not contain a literal backslash.",X=!0;else if(B.length!==P.length)W.error=W.error||"URI authority introducer must not contain whitespace.",X=!0}}let K=$.match(QV);if(K){if(W.scheme=K[1],W.userinfo=K[3],W.host=K[4],W.port=parseInt(K[5],10),W.path=K[6]||"",W.query=K[7],W.fragment=K[8],W.scheme!==void 0){let q=unescape(W.scheme);if(UG.test(q))W.scheme=q.toLowerCase();else W.error=W.error||"URI scheme is malformed.",z=!0}if(Y=NV(K),Y)W.error=W.error||"URI contains malformed percent-encoding.";if(isNaN(W.port))W.port=K[5];let B=TV(W,K);if(B!==void 0)W.error=W.error||B,X=!0;if(W.host)if(PG(W.host)===!1){let U=W.host[0]==="["&&W.host[W.host.length-1]==="]",O=BG(W.host);if(M=O.isIPV6||O.isIPVFuture===!0,Q=U&&O.error===!0,W.host=M?O.host:O.host.toLowerCase(),Q)W.error=W.error||"URI host is malformed.",X=!0}else M=!0;if(W.scheme===void 0&&W.userinfo===void 0&&W.host===void 0&&W.port===void 0&&W.query===void 0&&!W.path)W.reference="same-document";else if(W.scheme===void 0)W.reference="relative";else if(W.fragment===void 0)W.reference="absolute";else W.reference="uri";if(Z.reference&&Z.reference!=="suffix"&&Z.reference!==W.reference)W.error=W.error||"URI is not a "+Z.reference+" reference.";let P=yZ(Z.scheme||W.scheme);if(J=FG(W,Z,P,M),!P||P&&!P.skipNormalize){if($.indexOf("%")!==-1){if(W.host!==void 0&&!Q){let q=M?W.host:VG(W.host,!0);W.host=WV(q,M)}}if(W.path)W.path=$V(W.path);if(W.query)W.query=TG(W.query);if(W.fragment)W.fragment=TG(W.fragment)}if(P&&P.parse){if(P.parse(W,Z),P===qG.urn&&W.nid===void 0)G=!0}}else W.error=W.error||"URI can not be parsed.";return{parsed:W,malformedAuthorityOrPort:X,malformedPercentEncoding:Y,malformedSchemeSpecific:G,malformedHost:J,malformedScheme:z}}function $8($,w){return e4($,w).parsed}function KV($,w){return OG($,w).normalized}function OG($,w){let{parsed:Z,malformedAuthorityOrPort:W,malformedPercentEncoding:X,malformedSchemeSpecific:Y,malformedHost:G,malformedScheme:J}=e4($,w);return{normalized:W||X||Y||G||J?$:o$(Z,w),malformedAuthorityOrPort:W,malformedPercentEncoding:X,malformedSchemeSpecific:Y,malformedHost:G,malformedScheme:J}}function KG($,w){if(typeof $!=="string"&&typeof $!=="object")return;let Z;try{Z=typeof $==="string"?$:o$($,w)}catch{return}let{normalized:W,malformedAuthorityOrPort:X,malformedPercentEncoding:Y,malformedSchemeSpecific:G,malformedHost:J,malformedScheme:Q}=OG(Z,w);return X||Y||G||J||Q?void 0:W}var bZ={SCHEMES:qG,normalize:YV,resolve:GV,resolveComponent:HG,equal:JV,serialize:o$,parse:$8};w8.exports=bZ;w8.exports.default=bZ;w8.exports.fastUri=bZ});var fG=L((DG)=>{Object.defineProperty(DG,"__esModule",{value:!0});var LG=EG();LG.code='require("ajv/dist/runtime/uri").default';DG.default=LG});var yG=L((J$)=>{Object.defineProperty(J$,"__esModule",{value:!0});J$.CodeGen=J$.Name=J$.nil=J$.stringify=J$.str=J$._=J$.KeywordCxt=void 0;var VV=bw();Object.defineProperty(J$,"KeywordCxt",{enumerable:!0,get:function(){return VV.KeywordCxt}});var _1=v();Object.defineProperty(J$,"_",{enumerable:!0,get:function(){return _1._}});Object.defineProperty(J$,"str",{enumerable:!0,get:function(){return _1.str}});Object.defineProperty(J$,"stringify",{enumerable:!0,get:function(){return _1.stringify}});Object.defineProperty(J$,"nil",{enumerable:!0,get:function(){return _1.nil}});Object.defineProperty(J$,"Name",{enumerable:!0,get:function(){return _1.Name}});Object.defineProperty(J$,"CodeGen",{enumerable:!0,get:function(){return _1.CodeGen}});var PV=t4(),CG=xw(),qV=QZ(),uw=s4(),UV=v(),hw=jw(),Z8=Cw(),_Z=l(),kG=aY(),HV=fG(),jG=($,w)=>new RegExp($,w);jG.code="new RegExp";var FV=["removeAdditional","useDefaults","coerceTypes"],OV=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),EV={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},LV={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},AG=200;function DV($){var w,Z,W,X,Y,G,J,Q,z,M,T,N,K,B,P,q,U,O,f,C,A,u,i,r,z0;let h=$.strict,q0=(w=$.code)===null||w===void 0?void 0:w.optimize,p$=q0===!0||q0===void 0?1:q0||0,Z$=(W=(Z=$.code)===null||Z===void 0?void 0:Z.regExp)!==null&&W!==void 0?W:jG,S1=(X=$.uriResolver)!==null&&X!==void 0?X:HV.default;return{strictSchema:(G=(Y=$.strictSchema)!==null&&Y!==void 0?Y:h)!==null&&G!==void 0?G:!0,strictNumbers:(Q=(J=$.strictNumbers)!==null&&J!==void 0?J:h)!==null&&Q!==void 0?Q:!0,strictTypes:(M=(z=$.strictTypes)!==null&&z!==void 0?z:h)!==null&&M!==void 0?M:"log",strictTuples:(N=(T=$.strictTuples)!==null&&T!==void 0?T:h)!==null&&N!==void 0?N:"log",strictRequired:(B=(K=$.strictRequired)!==null&&K!==void 0?K:h)!==null&&B!==void 0?B:!1,code:$.code?{...$.code,optimize:p$,regExp:Z$}:{optimize:p$,regExp:Z$},loopRequired:(P=$.loopRequired)!==null&&P!==void 0?P:AG,loopEnum:(q=$.loopEnum)!==null&&q!==void 0?q:AG,meta:(U=$.meta)!==null&&U!==void 0?U:!0,messages:(O=$.messages)!==null&&O!==void 0?O:!0,inlineRefs:(f=$.inlineRefs)!==null&&f!==void 0?f:!0,schemaId:(C=$.schemaId)!==null&&C!==void 0?C:"$id",addUsedSchema:(A=$.addUsedSchema)!==null&&A!==void 0?A:!0,validateSchema:(u=$.validateSchema)!==null&&u!==void 0?u:!0,validateFormats:(i=$.validateFormats)!==null&&i!==void 0?i:!0,unicodeRegExp:(r=$.unicodeRegExp)!==null&&r!==void 0?r:!0,int32range:(z0=$.int32range)!==null&&z0!==void 0?z0:!0,uriResolver:S1}}class W8{constructor($={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,$=this.opts={...$,...DV($)};let{es5:w,lines:Z}=this.opts.code;this.scope=new UV.ValueScope({scope:{},prefixes:OV,es5:w,lines:Z}),this.logger=CV($.logger);let W=$.validateFormats;if($.validateFormats=!1,this.RULES=(0,qV.getRules)(),SG.call(this,EV,$,"NOT SUPPORTED"),SG.call(this,LV,$,"DEPRECATED","warn"),this._metaOpts=SV.call(this),$.formats)kV.call(this);if(this._addVocabularies(),this._addDefaultMetaSchema(),$.keywords)AV.call(this,$.keywords);if(typeof $.meta=="object")this.addMetaSchema($.meta);fV.call(this),$.validateFormats=W}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:$,meta:w,schemaId:Z}=this.opts,W=kG;if(Z==="id")W={...kG},W.id=W.$id,delete W.$id;if(w&&$)this.addMetaSchema(W,W[Z],!1)}defaultMeta(){let{meta:$,schemaId:w}=this.opts;return this.opts.defaultMeta=typeof $=="object"?$[w]||$:void 0}validate($,w){let Z;if(typeof $=="string"){if(Z=this.getSchema($),!Z)throw Error(`no schema with key or ref "${$}"`)}else Z=this.compile($);let W=Z(w);if(!("$async"in Z))this.errors=Z.errors;return W}compile($,w){let Z=this._addSchema($,w);return Z.validate||this._compileSchemaEnv(Z)}compileAsync($,w){if(typeof this.opts.loadSchema!="function")throw Error("options.loadSchema should be a function");let{loadSchema:Z}=this.opts;return W.call(this,$,w);async function W(z,M){await X.call(this,z.$schema);let T=this._addSchema(z,M);return T.validate||Y.call(this,T)}async function X(z){if(z&&!this.getSchema(z))await W.call(this,{$ref:z},!0)}async function Y(z){try{return this._compileSchemaEnv(z)}catch(M){if(!(M instanceof CG.default))throw M;return G.call(this,M),await J.call(this,M.missingSchema),Y.call(this,z)}}function G({missingSchema:z,missingRef:M}){if(this.refs[z])throw Error(`AnySchema ${z} is loaded but ${M} cannot be resolved`)}async function J(z){let M=await Q.call(this,z);if(!this.refs[z])await X.call(this,M.$schema);if(!this.refs[z])this.addSchema(M,z,w)}async function Q(z){let M=this._loading[z];if(M)return M;try{return await(this._loading[z]=Z(z))}finally{delete this._loading[z]}}}addSchema($,w,Z,W=this.opts.validateSchema){if(Array.isArray($)){for(let Y of $)this.addSchema(Y,void 0,Z,W);return this}let X;if(typeof $==="object"){let{schemaId:Y}=this.opts;if(X=$[Y],X!==void 0&&typeof X!="string")throw Error(`schema ${Y} must be string`)}return w=(0,hw.normalizeId)(w||X),this._checkUnique(w),this.schemas[w]=this._addSchema($,Z,w,W,!0),this}addMetaSchema($,w,Z=this.opts.validateSchema){return this.addSchema($,w,!0,Z),this}validateSchema($,w){if(typeof $=="boolean")return!0;let Z;if(Z=$.$schema,Z!==void 0&&typeof Z!="string")throw Error("$schema must be a string");if(Z=Z||this.opts.defaultMeta||this.defaultMeta(),!Z)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let W=this.validate(Z,$);if(!W&&w){let X="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(X);else throw Error(X)}return W}getSchema($){let w;while(typeof(w=RG.call(this,$))=="string")$=w;if(w===void 0){let{schemaId:Z}=this.opts,W=new uw.SchemaEnv({schema:{},schemaId:Z});if(w=uw.resolveSchema.call(this,W,$),!w)return;this.refs[$]=w}return w.validate||this._compileSchemaEnv(w)}removeSchema($){if($ instanceof RegExp)return this._removeAllSchemas(this.schemas,$),this._removeAllSchemas(this.refs,$),this;switch(typeof $){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let w=RG.call(this,$);if(typeof w=="object")this._cache.delete(w.schema);return delete this.schemas[$],delete this.refs[$],this}case"object":{let w=$;this._cache.delete(w);let Z=$[this.opts.schemaId];if(Z)Z=(0,hw.normalizeId)(Z),delete this.schemas[Z],delete this.refs[Z];return this}default:throw Error("ajv.removeSchema: invalid parameter")}}addVocabulary($){for(let w of $)this.addKeyword(w);return this}addKeyword($,w){let Z;if(typeof $=="string"){if(Z=$,typeof w=="object")this.logger.warn("these parameters are deprecated, see docs for addKeyword"),w.keyword=Z}else if(typeof $=="object"&&w===void 0){if(w=$,Z=w.keyword,Array.isArray(Z)&&!Z.length)throw Error("addKeywords: keyword must be string or non-empty array")}else throw Error("invalid addKeywords parameters");if(IV.call(this,Z,w),!w)return(0,_Z.eachItem)(Z,(X)=>xZ.call(this,X)),this;bV.call(this,w);let W={...w,type:(0,Z8.getJSONTypes)(w.type),schemaType:(0,Z8.getJSONTypes)(w.schemaType)};return(0,_Z.eachItem)(Z,W.type.length===0?(X)=>xZ.call(this,X,W):(X)=>W.type.forEach((Y)=>xZ.call(this,X,W,Y))),this}getKeyword($){let w=this.RULES.all[$];return typeof w=="object"?w.definition:!!w}removeKeyword($){let{RULES:w}=this;delete w.keywords[$],delete w.all[$];for(let Z of w.rules){let W=Z.rules.findIndex((X)=>X.keyword===$);if(W>=0)Z.rules.splice(W,1)}return this}addFormat($,w){if(typeof w=="string")w=new RegExp(w);return this.formats[$]=w,this}errorsText($=this.errors,{separator:w=", ",dataVar:Z="data"}={}){if(!$||$.length===0)return"No errors";return $.map((W)=>`${Z}${W.instancePath} ${W.message}`).reduce((W,X)=>W+w+X)}$dataMetaSchema($,w){let Z=this.RULES.all;$=JSON.parse(JSON.stringify($));for(let W of w){let X=W.split("/").slice(1),Y=$;for(let G of X)Y=Y[G];for(let G in Z){let J=Z[G];if(typeof J!="object")continue;let{$data:Q}=J.definition,z=Y[G];if(Q&&z)Y[G]=IG(z)}}return $}_removeAllSchemas($,w){for(let Z in $){let W=$[Z];if(!w||w.test(Z)){if(typeof W=="string")delete $[Z];else if(W&&!W.meta)this._cache.delete(W.schema),delete $[Z]}}}_addSchema($,w,Z,W=this.opts.validateSchema,X=this.opts.addUsedSchema){let Y,{schemaId:G}=this.opts;if(typeof $=="object")Y=$[G];else if(this.opts.jtd)throw Error("schema must be object");else if(typeof $!="boolean")throw Error("schema must be object or boolean");let J=this._cache.get($);if(J!==void 0)return J;Z=(0,hw.normalizeId)(Y||Z);let Q=hw.getSchemaRefs.call(this,$,Z);if(J=new uw.SchemaEnv({schema:$,schemaId:G,meta:w,baseId:Z,localRefs:Q}),this._cache.set(J.schema,J),X&&!Z.startsWith("#")){if(Z)this._checkUnique(Z);this.refs[Z]=J}if(W)this.validateSchema($,!0);return J}_checkUnique($){if(this.schemas[$]||this.refs[$])throw Error(`schema with key or id "${$}" already exists`)}_compileSchemaEnv($){if($.meta)this._compileMetaSchema($);else uw.compileSchema.call(this,$);if(!$.validate)throw Error("ajv implementation error");return $.validate}_compileMetaSchema($){let w=this.opts;this.opts=this._metaOpts;try{uw.compileSchema.call(this,$)}finally{this.opts=w}}}W8.ValidationError=PV.default;W8.MissingRefError=CG.default;J$.default=W8;function SG($,w,Z,W="error"){for(let X in $){let Y=X;if(Y in w)this.logger[W](`${Z}: option ${X}. ${$[Y]}`)}}function RG($){return $=(0,hw.normalizeId)($),this.schemas[$]||this.refs[$]}function fV(){let $=this.opts.schemas;if(!$)return;if(Array.isArray($))this.addSchema($);else for(let w in $)this.addSchema($[w],w)}function kV(){for(let $ in this.opts.formats){let w=this.opts.formats[$];if(w)this.addFormat($,w)}}function AV($){if(Array.isArray($)){this.addVocabulary($);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let w in $){let Z=$[w];if(!Z.keyword)Z.keyword=w;this.addKeyword(Z)}}function SV(){let $={...this.opts};for(let w of FV)delete $[w];return $}var RV={log(){},warn(){},error(){}};function CV($){if($===!1)return RV;if($===void 0)return console;if($.log&&$.warn&&$.error)return $;throw Error("logger must implement log, warn and error methods")}var jV=/^[a-z_$][a-z0-9_$:-]*$/i;function IV($,w){let{RULES:Z}=this;if((0,_Z.eachItem)($,(W)=>{if(Z.keywords[W])throw Error(`Keyword ${W} is already defined`);if(!jV.test(W))throw Error(`Keyword ${W} has invalid name`)}),!w)return;if(w.$data&&!(("code"in w)||("validate"in w)))throw Error('$data keyword must have "code" or "validate" function')}function xZ($,w,Z){var W;let X=w===null||w===void 0?void 0:w.post;if(Z&&X)throw Error('keyword with "post" flag cannot have "type"');let{RULES:Y}=this,G=X?Y.post:Y.rules.find(({type:Q})=>Q===Z);if(!G)G={type:Z,rules:[]},Y.rules.push(G);if(Y.keywords[$]=!0,!w)return;let J={keyword:$,definition:{...w,type:(0,Z8.getJSONTypes)(w.type),schemaType:(0,Z8.getJSONTypes)(w.schemaType)}};if(w.before)yV.call(this,G,J,w.before);else G.rules.push(J);Y.all[$]=J,(W=w.implements)===null||W===void 0||W.forEach((Q)=>this.addKeyword(Q))}function yV($,w,Z){let W=$.rules.findIndex((X)=>X.keyword===Z);if(W>=0)$.rules.splice(W,0,w);else $.rules.push(w),this.logger.warn(`rule ${Z} is not defined`)}function bV($){let{metaSchema:w}=$;if(w===void 0)return;if($.$data&&this.opts.$data)w=IG(w);$.validateSchema=this.compile(w,!0)}var xV={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function IG($){return{anyOf:[$,xV]}}});var xG=L((bG)=>{Object.defineProperty(bG,"__esModule",{value:!0});var vV={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};bG.default=vV});var iG=L((uG)=>{Object.defineProperty(uG,"__esModule",{value:!0});uG.callRef=uG.getValidate=void 0;var hV=xw(),_G=_0(),D0=v(),g1=Y$(),gG=s4(),X8=l(),iV={keyword:"$ref",schemaType:"string",code($){let{gen:w,schema:Z,it:W}=$,{baseId:X,schemaEnv:Y,validateName:G,opts:J,self:Q}=W,{root:z}=Y;if((Z==="#"||Z==="#/")&&X===z.baseId)return T();let M=gG.resolveRef.call(Q,z,X,Z);if(M===void 0)throw new hV.default(W.opts.uriResolver,X,Z);if(M instanceof gG.SchemaEnv)return N(M);return K(M);function T(){if(Y===z)return Y8($,G,Y,Y.$async);let B=w.scopeValue("root",{ref:z});return Y8($,D0._`${B}.validate`,z,z.$async)}function N(B){let P=vG($,B);Y8($,P,B,B.$async)}function K(B){let P=w.scopeValue("schema",J.code.source===!0?{ref:B,code:(0,D0.stringify)(B)}:{ref:B}),q=w.name("valid"),U=$.subschema({schema:B,dataTypes:[],schemaPath:D0.nil,topSchemaRef:P,errSchemaPath:Z},q);$.mergeEvaluated(U),$.ok(q)}}};function vG($,w){let{gen:Z}=$;return w.validate?Z.scopeValue("validate",{ref:w.validate}):D0._`${Z.scopeValue("wrapper",{ref:w})}.validate`}uG.getValidate=vG;function Y8($,w,Z,W){let{gen:X,it:Y}=$,{allErrors:G,schemaEnv:J,opts:Q}=Y,z=Q.passContext?g1.default.this:D0.nil;if(W)M();else T();function M(){if(!J.$async)throw Error("async schema referenced by sync schema");let B=X.let("valid");X.try(()=>{if(X.code(D0._`await ${(0,_G.callValidateCode)($,w,z)}`),K(w),!G)X.assign(B,!0)},(P)=>{if(X.if(D0._`!(${P} instanceof ${Y.ValidationError})`,()=>X.throw(P)),N(P),!G)X.assign(B,!1)}),$.ok(B)}function T(){$.result((0,_G.callValidateCode)($,w,z),()=>K(w),()=>N(w))}function N(B){let P=D0._`${B}.errors`;X.assign(g1.default.vErrors,D0._`${g1.default.vErrors} === null ? ${P} : ${g1.default.vErrors}.concat(${P})`),X.assign(g1.default.errors,D0._`${g1.default.vErrors}.length`)}function K(B){var P;if(!Y.opts.unevaluated)return;let q=(P=Z===null||Z===void 0?void 0:Z.validate)===null||P===void 0?void 0:P.evaluated;if(Y.props!==!0)if(q&&!q.dynamicProps){if(q.props!==void 0)Y.props=X8.mergeEvaluated.props(X,q.props,Y.props)}else{let U=X.var("props",D0._`${B}.evaluated.props`);Y.props=X8.mergeEvaluated.props(X,U,Y.props,D0.Name)}if(Y.items!==!0)if(q&&!q.dynamicItems){if(q.items!==void 0)Y.items=X8.mergeEvaluated.items(X,q.items,Y.items)}else{let U=X.var("items",D0._`${B}.evaluated.items`);Y.items=X8.mergeEvaluated.items(X,U,Y.items,D0.Name)}}}uG.callRef=Y8;uG.default=iV});var lG=L((mG)=>{Object.defineProperty(mG,"__esModule",{value:!0});var cV=xG(),dV=iG(),pV=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",cV.default,dV.default];mG.default=pV});var dG=L((cG)=>{Object.defineProperty(cG,"__esModule",{value:!0});var G8=v(),S$=G8.operators,J8={maximum:{okStr:"<=",ok:S$.LTE,fail:S$.GT},minimum:{okStr:">=",ok:S$.GTE,fail:S$.LT},exclusiveMaximum:{okStr:"<",ok:S$.LT,fail:S$.GTE},exclusiveMinimum:{okStr:">",ok:S$.GT,fail:S$.LTE}},tV={message:({keyword:$,schemaCode:w})=>G8.str`must be ${J8[$].okStr} ${w}`,params:({keyword:$,schemaCode:w})=>G8._`{comparison: ${J8[$].okStr}, limit: ${w}}`},rV={keyword:Object.keys(J8),type:"number",schemaType:"number",$data:!0,error:tV,code($){let{keyword:w,data:Z,schemaCode:W}=$;$.fail$data(G8._`${Z} ${J8[w].fail} ${W} || isNaN(${Z})`)}};cG.default=rV});var nG=L((pG)=>{Object.defineProperty(pG,"__esModule",{value:!0});var iw=v(),aV={message:({schemaCode:$})=>iw.str`must be multiple of ${$}`,params:({schemaCode:$})=>iw._`{multipleOf: ${$}}`},oV={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:aV,code($){let{gen:w,data:Z,schemaCode:W,it:X}=$,Y=X.opts.multipleOfPrecision,G=w.let("res"),J=Y?iw._`Math.abs(Math.round(${G}) - ${G}) > 1e-${Y}`:iw._`${G} !== parseInt(${G})`;$.fail$data(iw._`(${W} === 0 || (${G} = ${Z}/${W}, ${J}))`)}};pG.default=oV});var sG=L((rG)=>{Object.defineProperty(rG,"__esModule",{value:!0});function tG($){let w=$.length,Z=0,W=0,X;while(W<w)if(Z++,X=$.charCodeAt(W++),X>=55296&&X<=56319&&W<w){if(X=$.charCodeAt(W),(X&64512)===56320)W++}return Z}rG.default=tG;tG.code='require("ajv/dist/runtime/ucs2length").default'});var oG=L((aG)=>{Object.defineProperty(aG,"__esModule",{value:!0});var e$=v(),wP=l(),ZP=sG(),WP={message({keyword:$,schemaCode:w}){let Z=$==="maxLength"?"more":"fewer";return e$.str`must NOT have ${Z} than ${w} characters`},params:({schemaCode:$})=>e$._`{limit: ${$}}`},XP={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:WP,code($){let{keyword:w,data:Z,schemaCode:W,it:X}=$,Y=w==="maxLength"?e$.operators.GT:e$.operators.LT,G=X.opts.unicode===!1?e$._`${Z}.length`:e$._`${(0,wP.useFunc)($.gen,ZP.default)}(${Z})`;$.fail$data(e$._`${G} ${Y} ${W}`)}};aG.default=XP});var $3=L((eG)=>{Object.defineProperty(eG,"__esModule",{value:!0});var GP=_0(),JP=l(),v1=v(),QP={message:({schemaCode:$})=>v1.str`must match pattern "${$}"`,params:({schemaCode:$})=>v1._`{pattern: ${$}}`},zP={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:QP,code($){let{gen:w,data:Z,$data:W,schema:X,schemaCode:Y,it:G}=$,J=G.opts.unicodeRegExp?"u":"";if(W){let{regExp:Q}=G.opts.code,z=Q.code==="new RegExp"?v1._`new RegExp`:(0,JP.useFunc)(w,Q),M=w.let("valid");w.try(()=>w.assign(M,v1._`${z}(${Y}, ${J}).test(${Z})`),()=>w.assign(M,!1)),$.fail$data(v1._`!${M}`)}else{let Q=(0,GP.usePattern)($,X);$.fail$data(v1._`!${Q}.test(${Z})`)}}};eG.default=zP});var Z3=L((w3)=>{Object.defineProperty(w3,"__esModule",{value:!0});var mw=v(),TP={message({keyword:$,schemaCode:w}){let Z=$==="maxProperties"?"more":"fewer";return mw.str`must NOT have ${Z} than ${w} properties`},params:({schemaCode:$})=>mw._`{limit: ${$}}`},NP={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:TP,code($){let{keyword:w,data:Z,schemaCode:W}=$,X=w==="maxProperties"?mw.operators.GT:mw.operators.LT;$.fail$data(mw._`Object.keys(${Z}).length ${X} ${W}`)}};w3.default=NP});var X3=L((W3)=>{Object.defineProperty(W3,"__esModule",{value:!0});var lw=_0(),cw=v(),BP=l(),VP={message:({params:{missingProperty:$}})=>cw.str`must have required property '${$}'`,params:({params:{missingProperty:$}})=>cw._`{missingProperty: ${$}}`},PP={keyword:"required",type:"object",schemaType:"array",$data:!0,error:VP,code($){let{gen:w,schema:Z,schemaCode:W,data:X,$data:Y,it:G}=$,{opts:J}=G;if(!Y&&Z.length===0)return;let Q=Z.length>=J.loopRequired;if(G.allErrors)z();else M();if(J.strictRequired){let K=$.parentSchema.properties,{definedProperties:B}=$.it;for(let P of Z)if((K===null||K===void 0?void 0:K[P])===void 0&&!B.has(P)){let q=G.schemaEnv.baseId+G.errSchemaPath,U=`required property "${P}" is not defined at "${q}" (strictRequired)`;(0,BP.checkStrictMode)(G,U,G.opts.strictRequired)}}function z(){if(Q||Y)$.block$data(cw.nil,T);else for(let K of Z)(0,lw.checkReportMissingProp)($,K)}function M(){let K=w.let("missing");if(Q||Y){let B=w.let("valid",!0);$.block$data(B,()=>N(K,B)),$.ok(B)}else w.if((0,lw.checkMissingProp)($,Z,K)),(0,lw.reportMissingProp)($,K),w.else()}function T(){w.forOf("prop",W,(K)=>{$.setParams({missingProperty:K}),w.if((0,lw.noPropertyInData)(w,X,K,J.ownProperties),()=>$.error())})}function N(K,B){$.setParams({missingProperty:K}),w.forOf(K,W,()=>{w.assign(B,(0,lw.propertyInData)(w,X,K,J.ownProperties)),w.if((0,cw.not)(B),()=>{$.error(),w.break()})},cw.nil)}}};W3.default=PP});var G3=L((Y3)=>{Object.defineProperty(Y3,"__esModule",{value:!0});var dw=v(),UP={message({keyword:$,schemaCode:w}){let Z=$==="maxItems"?"more":"fewer";return dw.str`must NOT have ${Z} than ${w} items`},params:({schemaCode:$})=>dw._`{limit: ${$}}`},HP={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:UP,code($){let{keyword:w,data:Z,schemaCode:W}=$,X=w==="maxItems"?dw.operators.GT:dw.operators.LT;$.fail$data(dw._`${Z}.length ${X} ${W}`)}};Y3.default=HP});var Q8=L((Q3)=>{Object.defineProperty(Q3,"__esModule",{value:!0});var J3=PZ();J3.code='require("ajv/dist/runtime/equal").default';Q3.default=J3});var M3=L((z3)=>{Object.defineProperty(z3,"__esModule",{value:!0});var gZ=Cw(),M0=v(),EP=l(),LP=Q8(),DP={message:({params:{i:$,j:w}})=>M0.str`must NOT have duplicate items (items ## ${w} and ${$} are identical)`,params:({params:{i:$,j:w}})=>M0._`{i: ${$}, j: ${w}}`},fP={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:DP,code($){let{gen:w,data:Z,$data:W,schema:X,parentSchema:Y,schemaCode:G,it:J}=$;if(!W&&!X)return;let Q=w.let("valid"),z=Y.items?(0,gZ.getSchemaTypes)(Y.items):[];$.block$data(Q,M,M0._`${G} === false`),$.ok(Q);function M(){let B=w.let("i",M0._`${Z}.length`),P=w.let("j");$.setParams({i:B,j:P}),w.assign(Q,!0),w.if(M0._`${B} > 1`,()=>(T()?N:K)(B,P))}function T(){return z.length>0&&!z.some((B)=>B==="object"||B==="array")}function N(B,P){let q=w.name("item"),U=(0,gZ.checkDataTypes)(z,q,J.opts.strictNumbers,gZ.DataType.Wrong),O=w.const("indices",M0._`{}`);w.for(M0._`;${B}--;`,()=>{if(w.let(q,M0._`${Z}[${B}]`),w.if(U,M0._`continue`),z.length>1)w.if(M0._`typeof ${q} == "string"`,M0._`${q} += "_"`);w.if(M0._`typeof ${O}[${q}] == "number"`,()=>{w.assign(P,M0._`${O}[${q}]`),$.error(),w.assign(Q,!1).break()}).code(M0._`${O}[${q}] = ${B}`)})}function K(B,P){let q=(0,EP.useFunc)(w,LP.default),U=w.name("outer");w.label(U).for(M0._`;${B}--;`,()=>w.for(M0._`${P} = ${B}; ${P}--;`,()=>w.if(M0._`${q}(${Z}[${B}], ${Z}[${P}])`,()=>{$.error(),w.assign(Q,!1).break(U)})))}}};z3.default=fP});var N3=L((T3)=>{Object.defineProperty(T3,"__esModule",{value:!0});var vZ=v(),AP=l(),SP=Q8(),RP={message:"must be equal to constant",params:({schemaCode:$})=>vZ._`{allowedValue: ${$}}`},CP={keyword:"const",$data:!0,error:RP,code($){let{gen:w,data:Z,$data:W,schemaCode:X,schema:Y}=$;if(W||Y&&typeof Y=="object")$.fail$data(vZ._`!${(0,AP.useFunc)(w,SP.default)}(${Z}, ${X})`);else $.fail(vZ._`${Y} !== ${Z}`)}};T3.default=CP});var B3=L((K3)=>{Object.defineProperty(K3,"__esModule",{value:!0});var pw=v(),IP=l(),yP=Q8(),bP={message:"must be equal to one of the allowed values",params:({schemaCode:$})=>pw._`{allowedValues: ${$}}`},xP={keyword:"enum",schemaType:"array",$data:!0,error:bP,code($){let{gen:w,data:Z,$data:W,schema:X,schemaCode:Y,it:G}=$;if(!W&&X.length===0)throw Error("enum must have non-empty array");let J=X.length>=G.opts.loopEnum,Q,z=()=>Q!==null&&Q!==void 0?Q:Q=(0,IP.useFunc)(w,yP.default),M;if(J||W)M=w.let("valid"),$.block$data(M,T);else{if(!Array.isArray(X))throw Error("ajv implementation error");let K=w.const("vSchema",Y);M=(0,pw.or)(...X.map((B,P)=>N(K,P)))}$.pass(M);function T(){w.assign(M,!1),w.forOf("v",Y,(K)=>w.if(pw._`${z()}(${Z}, ${K})`,()=>w.assign(M,!0).break()))}function N(K,B){let P=X[B];return typeof P==="object"&&P!==null?pw._`${z()}(${Z}, ${K}[${B}])`:pw._`${Z} === ${P}`}}};K3.default=xP});var P3=L((V3)=>{Object.defineProperty(V3,"__esModule",{value:!0});var gP=dG(),vP=nG(),uP=oG(),hP=$3(),iP=Z3(),mP=X3(),lP=G3(),cP=M3(),dP=N3(),pP=B3(),nP=[gP.default,vP.default,uP.default,hP.default,iP.default,mP.default,lP.default,cP.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},dP.default,pP.default];V3.default=nP});var hZ=L((U3)=>{Object.defineProperty(U3,"__esModule",{value:!0});U3.validateAdditionalItems=void 0;var $1=v(),uZ=l(),rP={message:({params:{len:$}})=>$1.str`must NOT have more than ${$} items`,params:({params:{len:$}})=>$1._`{limit: ${$}}`},sP={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:rP,code($){let{parentSchema:w,it:Z}=$,{items:W}=w;if(!Array.isArray(W)){(0,uZ.checkStrictMode)(Z,'"additionalItems" is ignored when "items" is not an array of schemas');return}q3($,W)}};function q3($,w){let{gen:Z,schema:W,data:X,keyword:Y,it:G}=$;G.items=!0;let J=Z.const("len",$1._`${X}.length`);if(W===!1)$.setParams({len:w.length}),$.pass($1._`${J} <= ${w.length}`);else if(typeof W=="object"&&!(0,uZ.alwaysValidSchema)(G,W)){let z=Z.var("valid",$1._`${J} <= ${w.length}`);Z.if((0,$1.not)(z),()=>Q(z)),$.ok(z)}function Q(z){Z.forRange("i",w.length,J,(M)=>{if($.subschema({keyword:Y,dataProp:M,dataPropType:uZ.Type.Num},z),!G.allErrors)Z.if((0,$1.not)(z),()=>Z.break())})}}U3.validateAdditionalItems=q3;U3.default=sP});var iZ=L((E3)=>{Object.defineProperty(E3,"__esModule",{value:!0});E3.validateTuple=void 0;var F3=v(),z8=l(),oP=_0(),eP={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code($){let{schema:w,it:Z}=$;if(Array.isArray(w))return O3($,"additionalItems",w);if(Z.items=!0,(0,z8.alwaysValidSchema)(Z,w))return;$.ok((0,oP.validateArray)($))}};function O3($,w,Z=$.schema){let{gen:W,parentSchema:X,data:Y,keyword:G,it:J}=$;if(M(X),J.opts.unevaluated&&Z.length&&J.items!==!0)J.items=z8.mergeEvaluated.items(W,Z.length,J.items);let Q=W.name("valid"),z=W.const("len",F3._`${Y}.length`);Z.forEach((T,N)=>{if((0,z8.alwaysValidSchema)(J,T))return;W.if(F3._`${z} > ${N}`,()=>$.subschema({keyword:G,schemaProp:N,dataProp:N},Q)),$.ok(Q)});function M(T){let{opts:N,errSchemaPath:K}=J,B=Z.length,P=B===T.minItems&&(B===T.maxItems||T[w]===!1);if(N.strictTuples&&!P){let q=`"${G}" is ${B}-tuple, but minItems or maxItems/${w} are not specified or different at path "${K}"`;(0,z8.checkStrictMode)(J,q,N.strictTuples)}}}E3.validateTuple=O3;E3.default=eP});var f3=L((D3)=>{Object.defineProperty(D3,"__esModule",{value:!0});var wq=iZ(),Zq={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:($)=>(0,wq.validateTuple)($,"items")};D3.default=Zq});var S3=L((A3)=>{Object.defineProperty(A3,"__esModule",{value:!0});var k3=v(),Xq=l(),Yq=_0(),Gq=hZ(),Jq={message:({params:{len:$}})=>k3.str`must NOT have more than ${$} items`,params:({params:{len:$}})=>k3._`{limit: ${$}}`},Qq={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:Jq,code($){let{schema:w,parentSchema:Z,it:W}=$,{prefixItems:X}=Z;if(W.items=!0,(0,Xq.alwaysValidSchema)(W,w))return;if(X)(0,Gq.validateAdditionalItems)($,X);else $.ok((0,Yq.validateArray)($))}};A3.default=Qq});var C3=L((R3)=>{Object.defineProperty(R3,"__esModule",{value:!0});var g0=v(),M8=l(),Mq={message:({params:{min:$,max:w}})=>w===void 0?g0.str`must contain at least ${$} valid item(s)`:g0.str`must contain at least ${$} and no more than ${w} valid item(s)`,params:({params:{min:$,max:w}})=>w===void 0?g0._`{minContains: ${$}}`:g0._`{minContains: ${$}, maxContains: ${w}}`},Tq={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:Mq,code($){let{gen:w,schema:Z,parentSchema:W,data:X,it:Y}=$,G,J,{minContains:Q,maxContains:z}=W;if(Y.opts.next)G=Q===void 0?1:Q,J=z;else G=1;let M=w.const("len",g0._`${X}.length`);if($.setParams({min:G,max:J}),J===void 0&&G===0){(0,M8.checkStrictMode)(Y,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(J!==void 0&&G>J){(0,M8.checkStrictMode)(Y,'"minContains" > "maxContains" is always invalid'),$.fail();return}if((0,M8.alwaysValidSchema)(Y,Z)){let P=g0._`${M} >= ${G}`;if(J!==void 0)P=g0._`${P} && ${M} <= ${J}`;$.pass(P);return}Y.items=!0;let T=w.name("valid");if(J===void 0&&G===1)K(T,()=>w.if(T,()=>w.break()));else if(G===0){if(w.let(T,!0),J!==void 0)w.if(g0._`${X}.length > 0`,N)}else w.let(T,!1),N();$.result(T,()=>$.reset());function N(){let P=w.name("_valid"),q=w.let("count",0);K(P,()=>w.if(P,()=>B(q)))}function K(P,q){w.forRange("i",0,M,(U)=>{$.subschema({keyword:"contains",dataProp:U,dataPropType:M8.Type.Num,compositeRule:!0},P),q()})}function B(P){if(w.code(g0._`${P}++`),J===void 0)w.if(g0._`${P} >= ${G}`,()=>w.assign(T,!0).break());else if(w.if(g0._`${P} > ${J}`,()=>w.assign(T,!1).break()),G===1)w.assign(T,!0);else w.if(g0._`${P} >= ${G}`,()=>w.assign(T,!0))}}};R3.default=Tq});var _3=L((y3)=>{Object.defineProperty(y3,"__esModule",{value:!0});y3.validateSchemaDeps=y3.validatePropertyDeps=y3.error=void 0;var mZ=v(),Kq=l(),nw=_0();y3.error={message:({params:{property:$,depsCount:w,deps:Z}})=>{let W=w===1?"property":"properties";return mZ.str`must have ${W} ${Z} when property ${$} is present`},params:({params:{property:$,depsCount:w,deps:Z,missingProperty:W}})=>mZ._`{property: ${$},
|
|
33
33
|
missingProperty: ${W},
|
|
34
34
|
depsCount: ${w},
|
|
35
|
-
deps: ${Z}}`};var Mq={keyword:"dependencies",type:"object",schemaType:"object",error:jG.error,code($){let[w,Z]=Tq($);RG($,w),CG($,Z)}};function Tq({schema:$}){let w={},Z={};for(let W in $){if(W==="__proto__")continue;let X=Array.isArray($[W])?w:Z;X[W]=$[W]}return[w,Z]}function RG($,w=$.schema){let{gen:Z,data:W,it:X}=$;if(Object.keys(w).length===0)return;let Y=Z.let("missing");for(let G in w){let J=w[G];if(J.length===0)continue;let Q=(0,nw.propertyInData)(Z,W,G,X.opts.ownProperties);if($.setParams({property:G,depsCount:J.length,deps:J.join(", ")}),X.allErrors)Z.if(Q,()=>{for(let z of J)(0,nw.checkReportMissingProp)($,z)});else Z.if(mZ._`${Q} && (${(0,nw.checkMissingProp)($,J,Y)})`),(0,nw.reportMissingProp)($,Y),Z.else()}}jG.validatePropertyDeps=RG;function CG($,w=$.schema){let{gen:Z,data:W,keyword:X,it:Y}=$,G=Z.name("valid");for(let J in w){if((0,zq.alwaysValidSchema)(Y,w[J]))continue;Z.if((0,nw.propertyInData)(Z,W,J,Y.opts.ownProperties),()=>{let Q=$.subschema({keyword:X,schemaProp:J},G);$.mergeValidEvaluated(Q,G)},()=>Z.var(G,!0)),$.ok(G)}}jG.validateSchemaDeps=CG;jG.default=Mq});var gG=L((_G)=>{Object.defineProperty(_G,"__esModule",{value:!0});var xG=v(),Bq=l(),Vq={message:"property name must be valid",params:({params:$})=>xG._`{propertyName: ${$.propertyName}}`},Pq={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Vq,code($){let{gen:w,schema:Z,data:W,it:X}=$;if((0,Bq.alwaysValidSchema)(X,Z))return;let Y=w.name("valid");w.forIn("key",W,(G)=>{$.setParams({propertyName:G}),$.subschema({keyword:"propertyNames",data:G,dataTypes:["string"],propertyName:G,compositeRule:!0},Y),w.if((0,xG.not)(Y),()=>{if($.error(!0),!X.allErrors)w.break()})}),$.ok(Y)}};_G.default=Pq});var lZ=L((vG)=>{Object.defineProperty(vG,"__esModule",{value:!0});var T8=_0(),c0=v(),Uq=X$(),K8=l(),Hq={message:"must NOT have additional properties",params:({params:$})=>c0._`{additionalProperty: ${$.additionalProperty}}`},Fq={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Hq,code($){let{gen:w,schema:Z,parentSchema:W,data:X,errsCount:Y,it:G}=$;if(!Y)throw Error("ajv implementation error");let{allErrors:J,opts:Q}=G;if(G.props=!0,Q.removeAdditional!=="all"&&(0,K8.alwaysValidSchema)(G,Z))return;let z=(0,T8.allSchemaProperties)(W.properties),M=(0,T8.allSchemaProperties)(W.patternProperties);T(),$.ok(c0._`${Y} === ${Uq.default.errors}`);function T(){w.forIn("key",X,(q)=>{if(!z.length&&!M.length)B(q);else w.if(K(q),()=>B(q))})}function K(q){let U;if(z.length>8){let O=(0,K8.schemaRefOrVal)(G,W.properties,"properties");U=(0,T8.isOwnProperty)(w,O,q)}else if(z.length)U=(0,c0.or)(...z.map((O)=>c0._`${q} === ${O}`));else U=c0.nil;if(M.length)U=(0,c0.or)(U,...M.map((O)=>c0._`${(0,T8.usePattern)($,O)}.test(${q})`));return(0,c0.not)(U)}function N(q){w.code(c0._`delete ${X}[${q}]`)}function B(q){if(Q.removeAdditional==="all"||Q.removeAdditional&&Z===!1){N(q);return}if(Z===!1){if($.setParams({additionalProperty:q}),$.error(),!J)w.break();return}if(typeof Z=="object"&&!(0,K8.alwaysValidSchema)(G,Z)){let U=w.name("valid");if(Q.removeAdditional==="failing")P(q,U,!1),w.if((0,c0.not)(U),()=>{$.reset(),N(q)});else if(P(q,U),!J)w.if((0,c0.not)(U),()=>w.break())}}function P(q,U,O){let f={keyword:"additionalProperties",dataProp:q,dataPropType:K8.Type.Str};if(O===!1)Object.assign(f,{compositeRule:!0,createErrors:!1,allErrors:!1});$.subschema(f,U)}}};vG.default=Fq});var mG=L((iG)=>{Object.defineProperty(iG,"__esModule",{value:!0});var Eq=bw(),uG=_0(),cZ=l(),hG=lZ(),Lq={keyword:"properties",type:"object",schemaType:"object",code($){let{gen:w,schema:Z,parentSchema:W,data:X,it:Y}=$;if(Y.opts.removeAdditional==="all"&&W.additionalProperties===void 0)hG.default.code(new Eq.KeywordCxt(Y,hG.default,"additionalProperties"));let G=(0,uG.allSchemaProperties)(Z);for(let T of G)Y.definedProperties.add(T);if(Y.opts.unevaluated&&G.length&&Y.props!==!0)Y.props=cZ.mergeEvaluated.props(w,(0,cZ.toHash)(G),Y.props);let J=G.filter((T)=>!(0,cZ.alwaysValidSchema)(Y,Z[T]));if(J.length===0)return;let Q=w.name("valid");for(let T of J){if(z(T))M(T);else{if(w.if((0,uG.propertyInData)(w,X,T,Y.opts.ownProperties)),M(T),!Y.allErrors)w.else().var(Q,!0);w.endIf()}$.it.definedProperties.add(T),$.ok(Q)}function z(T){return Y.opts.useDefaults&&!Y.compositeRule&&Z[T].default!==void 0}function M(T){$.subschema({keyword:"properties",schemaProp:T,dataProp:T},Q)}}};iG.default=Lq});var nG=L((pG)=>{Object.defineProperty(pG,"__esModule",{value:!0});var lG=_0(),N8=v(),cG=l(),dG=l(),fq={keyword:"patternProperties",type:"object",schemaType:"object",code($){let{gen:w,schema:Z,data:W,parentSchema:X,it:Y}=$,{opts:G}=Y,J=(0,lG.allSchemaProperties)(Z),Q=J.filter((P)=>(0,cG.alwaysValidSchema)(Y,Z[P]));if(J.length===0||Q.length===J.length&&(!Y.opts.unevaluated||Y.props===!0))return;let z=G.strictSchema&&!G.allowMatchingProperties&&X.properties,M=w.name("valid");if(Y.props!==!0&&!(Y.props instanceof N8.Name))Y.props=(0,dG.evaluatedPropsToName)(w,Y.props);let{props:T}=Y;K();function K(){for(let P of J){if(z)N(P);if(Y.allErrors)B(P);else w.var(M,!0),B(P),w.if(M)}}function N(P){for(let q in z)if(new RegExp(P).test(q))(0,cG.checkStrictMode)(Y,`property ${q} matches pattern ${P} (use allowMatchingProperties)`)}function B(P){w.forIn("key",W,(q)=>{w.if(N8._`${(0,lG.usePattern)($,P)}.test(${q})`,()=>{let U=Q.includes(P);if(!U)$.subschema({keyword:"patternProperties",schemaProp:P,dataProp:q,dataPropType:dG.Type.Str},M);if(Y.opts.unevaluated&&T!==!0)w.assign(N8._`${T}[${q}]`,!0);else if(!U&&!Y.allErrors)w.if((0,N8.not)(M),()=>w.break())})})}}};pG.default=fq});var rG=L((tG)=>{Object.defineProperty(tG,"__esModule",{value:!0});var Aq=l(),Sq={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code($){let{gen:w,schema:Z,it:W}=$;if((0,Aq.alwaysValidSchema)(W,Z)){$.fail();return}let X=w.name("valid");$.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},X),$.failResult(X,()=>$.reset(),()=>$.error())},error:{message:"must NOT be valid"}};tG.default=Sq});var aG=L((sG)=>{Object.defineProperty(sG,"__esModule",{value:!0});var Cq=_0(),jq={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Cq.validateUnion,error:{message:"must match a schema in anyOf"}};sG.default=jq});var eG=L((oG)=>{Object.defineProperty(oG,"__esModule",{value:!0});var B8=v(),yq=l(),bq={message:"must match exactly one schema in oneOf",params:({params:$})=>B8._`{passingSchemas: ${$.passing}}`},xq={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:bq,code($){let{gen:w,schema:Z,parentSchema:W,it:X}=$;if(!Array.isArray(Z))throw Error("ajv implementation error");if(X.opts.discriminator&&W.discriminator)return;let Y=Z,G=w.let("valid",!1),J=w.let("passing",null),Q=w.name("_valid");$.setParams({passing:J}),w.block(z),$.result(G,()=>$.reset(),()=>$.error(!0));function z(){Y.forEach((M,T)=>{let K;if((0,yq.alwaysValidSchema)(X,M))w.var(Q,!0);else K=$.subschema({keyword:"oneOf",schemaProp:T,compositeRule:!0},Q);if(T>0)w.if(B8._`${Q} && ${G}`).assign(G,!1).assign(J,B8._`[${J}, ${T}]`).else();w.if(Q,()=>{if(w.assign(G,!0),w.assign(J,T),K)$.mergeEvaluated(K,B8.Name)})})}}};oG.default=xq});var w7=L(($7)=>{Object.defineProperty($7,"__esModule",{value:!0});var gq=l(),vq={keyword:"allOf",schemaType:"array",code($){let{gen:w,schema:Z,it:W}=$;if(!Array.isArray(Z))throw Error("ajv implementation error");let X=w.name("valid");Z.forEach((Y,G)=>{if((0,gq.alwaysValidSchema)(W,Y))return;let J=$.subschema({keyword:"allOf",schemaProp:G},X);$.ok(X),$.mergeEvaluated(J)})}};$7.default=vq});var Y7=L((X7)=>{Object.defineProperty(X7,"__esModule",{value:!0});var V8=v(),W7=l(),hq={message:({params:$})=>V8.str`must match "${$.ifClause}" schema`,params:({params:$})=>V8._`{failingKeyword: ${$.ifClause}}`},iq={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:hq,code($){let{gen:w,parentSchema:Z,it:W}=$;if(Z.then===void 0&&Z.else===void 0)(0,W7.checkStrictMode)(W,'"if" without "then" and "else" is ignored');let X=Z7(W,"then"),Y=Z7(W,"else");if(!X&&!Y)return;let G=w.let("valid",!0),J=w.name("_valid");if(Q(),$.reset(),X&&Y){let M=w.let("ifClause");$.setParams({ifClause:M}),w.if(J,z("then",M),z("else",M))}else if(X)w.if(J,z("then"));else w.if((0,V8.not)(J),z("else"));$.pass(G,()=>$.error(!0));function Q(){let M=$.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},J);$.mergeEvaluated(M)}function z(M,T){return()=>{let K=$.subschema({keyword:M},J);if(w.assign(G,J),$.mergeValidEvaluated(K,G),T)w.assign(T,V8._`${M}`);else $.setParams({ifClause:M})}}}};function Z7($,w){let Z=$.schema[w];return Z!==void 0&&!(0,W7.alwaysValidSchema)($,Z)}X7.default=iq});var J7=L((G7)=>{Object.defineProperty(G7,"__esModule",{value:!0});var lq=l(),cq={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:$,parentSchema:w,it:Z}){if(w.if===void 0)(0,lq.checkStrictMode)(Z,`"${$}" without "if" is ignored`)}};G7.default=cq});var z7=L((Q7)=>{Object.defineProperty(Q7,"__esModule",{value:!0});var pq=hZ(),nq=LG(),tq=iZ(),rq=kG(),sq=SG(),aq=bG(),oq=gG(),eq=lZ(),$U=mG(),wU=nG(),ZU=rG(),WU=aG(),XU=eG(),YU=w7(),GU=Y7(),JU=J7();function QU($=!1){let w=[ZU.default,WU.default,XU.default,YU.default,GU.default,JU.default,oq.default,eq.default,aq.default,$U.default,wU.default];if($)w.push(nq.default,rq.default);else w.push(pq.default,tq.default);return w.push(sq.default),w}Q7.default=QU});var T7=L((M7)=>{Object.defineProperty(M7,"__esModule",{value:!0});var o=v(),MU={message:({schemaCode:$})=>o.str`must match format "${$}"`,params:({schemaCode:$})=>o._`{format: ${$}}`},TU={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:MU,code($,w){let{gen:Z,data:W,$data:X,schema:Y,schemaCode:G,it:J}=$,{opts:Q,errSchemaPath:z,schemaEnv:M,self:T}=J;if(!Q.validateFormats)return;if(X)K();else N();function K(){let B=Z.scopeValue("formats",{ref:T.formats,code:Q.code.formats}),P=Z.const("fDef",o._`${B}[${G}]`),q=Z.let("fType"),U=Z.let("format");Z.if(o._`typeof ${P} == "object" && !(${P} instanceof RegExp)`,()=>Z.assign(q,o._`${P}.type || "string"`).assign(U,o._`${P}.validate`),()=>Z.assign(q,o._`"string"`).assign(U,P)),$.fail$data((0,o.or)(O(),f()));function O(){if(Q.strictSchema===!1)return o.nil;return o._`${G} && !${U}`}function f(){let C=M.$async?o._`(${P}.async ? await ${U}(${W}) : ${U}(${W}))`:o._`${U}(${W})`,A=o._`(typeof ${U} == "function" ? ${C} : ${U}.test(${W}))`;return o._`${U} && ${U} !== true && ${q} === ${w} && !${A}`}}function N(){let B=T.formats[Y];if(!B){O();return}if(B===!0)return;let[P,q,U]=f(B);if(P===w)$.pass(C());function O(){if(Q.strictSchema===!1){T.logger.warn(A());return}throw Error(A());function A(){return`unknown format "${Y}" ignored in schema at path "${z}"`}}function f(A){let u=A instanceof RegExp?(0,o.regexpCode)(A):Q.code.formats?o._`${Q.code.formats}${(0,o.getProperty)(Y)}`:void 0,i=Z.scopeValue("formats",{key:Y,ref:A,code:u});if(typeof A=="object"&&!(A instanceof RegExp))return[A.type||"string",A.validate,o._`${i}.validate`];return["string",A,i]}function C(){if(typeof B=="object"&&!(B instanceof RegExp)&&B.async){if(!M.$async)throw Error("async format in sync schema");return o._`await ${U}(${W})`}return typeof q=="function"?o._`${U}(${W})`:o._`${U}.test(${W})`}}}};M7.default=TU});var N7=L((K7)=>{Object.defineProperty(K7,"__esModule",{value:!0});var NU=T7(),BU=[NU.default];K7.default=BU});var P7=L((B7)=>{Object.defineProperty(B7,"__esModule",{value:!0});B7.contentVocabulary=B7.metadataVocabulary=void 0;B7.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];B7.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var H7=L((U7)=>{Object.defineProperty(U7,"__esModule",{value:!0});var qU=i3(),UU=BG(),HU=z7(),FU=N7(),q7=P7(),OU=[qU.default,UU.default,(0,HU.default)(),FU.default,q7.metadataVocabulary,q7.contentVocabulary];U7.default=OU});var L7=L((O7)=>{Object.defineProperty(O7,"__esModule",{value:!0});O7.DiscrError=void 0;var F7;(function($){$.Tag="tag",$.Mapping="mapping"})(F7||(O7.DiscrError=F7={}))});var k7=L((f7)=>{Object.defineProperty(f7,"__esModule",{value:!0});var u1=v(),dZ=L7(),D7=s4(),LU=xw(),DU=l(),fU={message:({params:{discrError:$,tagName:w}})=>$===dZ.DiscrError.Tag?`tag "${w}" must be string`:`value of tag "${w}" must be in oneOf`,params:({params:{discrError:$,tag:w,tagName:Z}})=>u1._`{error: ${$}, tag: ${Z}, tagValue: ${w}}`},kU={keyword:"discriminator",type:"object",schemaType:"object",error:fU,code($){let{gen:w,data:Z,schema:W,parentSchema:X,it:Y}=$,{oneOf:G}=X;if(!Y.opts.discriminator)throw Error("discriminator: requires discriminator option");let J=W.propertyName;if(typeof J!="string")throw Error("discriminator: requires propertyName");if(W.mapping)throw Error("discriminator: mapping is not supported");if(!G)throw Error("discriminator: requires oneOf keyword");let Q=w.let("valid",!1),z=w.const("tag",u1._`${Z}${(0,u1.getProperty)(J)}`);w.if(u1._`typeof ${z} == "string"`,()=>M(),()=>$.error(!1,{discrError:dZ.DiscrError.Tag,tag:z,tagName:J})),$.ok(Q);function M(){let N=K();w.if(!1);for(let B in N)w.elseIf(u1._`${z} === ${B}`),w.assign(Q,T(N[B]));w.else(),$.error(!1,{discrError:dZ.DiscrError.Mapping,tag:z,tagName:J}),w.endIf()}function T(N){let B=w.name("valid"),P=$.subschema({keyword:"oneOf",schemaProp:N},B);return $.mergeEvaluated(P,u1.Name),B}function K(){var N;let B={},P=U(X),q=!0;for(let C=0;C<G.length;C++){let A=G[C];if((A===null||A===void 0?void 0:A.$ref)&&!(0,DU.schemaHasRulesButRef)(A,Y.self.RULES)){let i=A.$ref;if(A=D7.resolveRef.call(Y.self,Y.schemaEnv.root,Y.baseId,i),A instanceof D7.SchemaEnv)A=A.schema;if(A===void 0)throw new LU.default(Y.opts.uriResolver,Y.baseId,i)}let u=(N=A===null||A===void 0?void 0:A.properties)===null||N===void 0?void 0:N[J];if(typeof u!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${J}"`);q=q&&(P||U(A)),O(u,C)}if(!q)throw Error(`discriminator: "${J}" must be required`);return B;function U({required:C}){return Array.isArray(C)&&C.includes(J)}function O(C,A){if(C.const)f(C.const,A);else if(C.enum)for(let u of C.enum)f(u,A);else throw Error(`discriminator: "properties/${J}" must have "const" or "enum"`)}function f(C,A){if(typeof C!="string"||C in B)throw Error(`discriminator: "${J}" values must be unique strings`);B[C]=A}}}};f7.default=kU});var A7=L((ID,SU)=>{SU.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var R7=L((f0,pZ)=>{Object.defineProperty(f0,"__esModule",{value:!0});f0.MissingRefError=f0.ValidationError=f0.CodeGen=f0.Name=f0.nil=f0.stringify=f0.str=f0._=f0.KeywordCxt=f0.Ajv=void 0;var RU=j3(),CU=H7(),jU=k7(),S7=A7(),IU=["/properties"],P8="http://json-schema.org/draft-07/schema";class tw extends RU.default{_addVocabularies(){if(super._addVocabularies(),CU.default.forEach(($)=>this.addVocabulary($)),this.opts.discriminator)this.addKeyword(jU.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let $=this.opts.$data?this.$dataMetaSchema(S7,IU):S7;this.addMetaSchema($,P8,!1),this.refs["http://json-schema.org/schema"]=P8}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(P8)?P8:void 0)}}f0.Ajv=tw;pZ.exports=f0=tw;pZ.exports.Ajv=tw;Object.defineProperty(f0,"__esModule",{value:!0});f0.default=tw;var yU=bw();Object.defineProperty(f0,"KeywordCxt",{enumerable:!0,get:function(){return yU.KeywordCxt}});var h1=v();Object.defineProperty(f0,"_",{enumerable:!0,get:function(){return h1._}});Object.defineProperty(f0,"str",{enumerable:!0,get:function(){return h1.str}});Object.defineProperty(f0,"stringify",{enumerable:!0,get:function(){return h1.stringify}});Object.defineProperty(f0,"nil",{enumerable:!0,get:function(){return h1.nil}});Object.defineProperty(f0,"Name",{enumerable:!0,get:function(){return h1.Name}});Object.defineProperty(f0,"CodeGen",{enumerable:!0,get:function(){return h1.CodeGen}});var bU=t4();Object.defineProperty(f0,"ValidationError",{enumerable:!0,get:function(){return bU.default}});var xU=xw();Object.defineProperty(f0,"MissingRefError",{enumerable:!0,get:function(){return xU.default}})});var MJ=L((xk,K5)=>{var C8=process||{},QJ=C8.argv||[],R8=C8.env||{},xH=!(!!R8.NO_COLOR||QJ.includes("--no-color"))&&(!!R8.FORCE_COLOR||QJ.includes("--color")||C8.platform==="win32"||(C8.stdout||{}).isTTY&&R8.TERM!=="dumb"||!!R8.CI),_H=($,w,Z=$)=>(W)=>{let X=""+W,Y=X.indexOf(w,$.length);return~Y?$+gH(X,w,Z,Y)+w:$+X+w},gH=($,w,Z,W)=>{let X="",Y=0;do X+=$.substring(Y,W)+Z,Y=W+w.length,W=$.indexOf(w,Y);while(~W);return X+$.substring(Y)},zJ=($=xH)=>{let w=$?_H:()=>String;return{isColorSupported:$,reset:w("\x1B[0m","\x1B[0m"),bold:w("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:w("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:w("\x1B[3m","\x1B[23m"),underline:w("\x1B[4m","\x1B[24m"),inverse:w("\x1B[7m","\x1B[27m"),hidden:w("\x1B[8m","\x1B[28m"),strikethrough:w("\x1B[9m","\x1B[29m"),black:w("\x1B[30m","\x1B[39m"),red:w("\x1B[31m","\x1B[39m"),green:w("\x1B[32m","\x1B[39m"),yellow:w("\x1B[33m","\x1B[39m"),blue:w("\x1B[34m","\x1B[39m"),magenta:w("\x1B[35m","\x1B[39m"),cyan:w("\x1B[36m","\x1B[39m"),white:w("\x1B[37m","\x1B[39m"),gray:w("\x1B[90m","\x1B[39m"),bgBlack:w("\x1B[40m","\x1B[49m"),bgRed:w("\x1B[41m","\x1B[49m"),bgGreen:w("\x1B[42m","\x1B[49m"),bgYellow:w("\x1B[43m","\x1B[49m"),bgBlue:w("\x1B[44m","\x1B[49m"),bgMagenta:w("\x1B[45m","\x1B[49m"),bgCyan:w("\x1B[46m","\x1B[49m"),bgWhite:w("\x1B[47m","\x1B[49m"),blackBright:w("\x1B[90m","\x1B[39m"),redBright:w("\x1B[91m","\x1B[39m"),greenBright:w("\x1B[92m","\x1B[39m"),yellowBright:w("\x1B[93m","\x1B[39m"),blueBright:w("\x1B[94m","\x1B[39m"),magentaBright:w("\x1B[95m","\x1B[39m"),cyanBright:w("\x1B[96m","\x1B[39m"),whiteBright:w("\x1B[97m","\x1B[39m"),bgBlackBright:w("\x1B[100m","\x1B[49m"),bgRedBright:w("\x1B[101m","\x1B[49m"),bgGreenBright:w("\x1B[102m","\x1B[49m"),bgYellowBright:w("\x1B[103m","\x1B[49m"),bgBlueBright:w("\x1B[104m","\x1B[49m"),bgMagentaBright:w("\x1B[105m","\x1B[49m"),bgCyanBright:w("\x1B[106m","\x1B[49m"),bgWhiteBright:w("\x1B[107m","\x1B[49m")}};K5.exports=zJ();K5.exports.createColors=zJ});import{realpathSync as Lz}from"fs";import{realpath as BE}from"fs/promises";import VE from"path";import{createInterface as PE}from"readline/promises";import{fileURLToPath as qE}from"url";var sW=R4(d6(),1),{program:jE,createCommand:IE,createArgument:yE,createOption:bE,CommanderError:xE,InvalidArgumentError:_E,InvalidOptionArgumentError:gE,Command:aW,Argument:vE,Option:uE,Help:hE}=sW.default;import oW from"node:os";import I4 from"node:path";function eW(){return process.env.XDG_CONFIG_HOME?I4.join(process.env.XDG_CONFIG_HOME,"coden"):I4.join(oW.homedir(),".config","coden")}function $X(){return process.env.XDG_DATA_HOME?I4.join(process.env.XDG_DATA_HOME,"coden"):I4.join(oW.homedir(),".local","share","coden")}import{mkdir as DM,readFile as fM,realpath as wX,writeFile as kM}from"node:fs/promises";import AM from"node:path";class p6{file;constructor($){this.file=$}async isTrusted($){return(await this.read()).includes($)}async isWorkspaceTrusted($){return this.isTrusted(await wX($))}async trustWorkspace($){return this.trust(await wX($))}async trust($){let w=await this.read();if(!w.includes($))w.push($);await DM(AM.dirname(this.file),{recursive:!0}),await kM(this.file,`${JSON.stringify(w,null,2)}
|
|
36
|
-
`,{encoding:"utf8",mode:384})}async read(){try{let $=JSON.parse(await
|
|
35
|
+
deps: ${Z}}`};var Bq={keyword:"dependencies",type:"object",schemaType:"object",error:y3.error,code($){let[w,Z]=Vq($);j3($,w),I3($,Z)}};function Vq({schema:$}){let w={},Z={};for(let W in $){if(W==="__proto__")continue;let X=Array.isArray($[W])?w:Z;X[W]=$[W]}return[w,Z]}function j3($,w=$.schema){let{gen:Z,data:W,it:X}=$;if(Object.keys(w).length===0)return;let Y=Z.let("missing");for(let G in w){let J=w[G];if(J.length===0)continue;let Q=(0,nw.propertyInData)(Z,W,G,X.opts.ownProperties);if($.setParams({property:G,depsCount:J.length,deps:J.join(", ")}),X.allErrors)Z.if(Q,()=>{for(let z of J)(0,nw.checkReportMissingProp)($,z)});else Z.if(mZ._`${Q} && (${(0,nw.checkMissingProp)($,J,Y)})`),(0,nw.reportMissingProp)($,Y),Z.else()}}y3.validatePropertyDeps=j3;function I3($,w=$.schema){let{gen:Z,data:W,keyword:X,it:Y}=$,G=Z.name("valid");for(let J in w){if((0,Kq.alwaysValidSchema)(Y,w[J]))continue;Z.if((0,nw.propertyInData)(Z,W,J,Y.opts.ownProperties),()=>{let Q=$.subschema({keyword:X,schemaProp:J},G);$.mergeValidEvaluated(Q,G)},()=>Z.var(G,!0)),$.ok(G)}}y3.validateSchemaDeps=I3;y3.default=Bq});var u3=L((v3)=>{Object.defineProperty(v3,"__esModule",{value:!0});var g3=v(),Uq=l(),Hq={message:"property name must be valid",params:({params:$})=>g3._`{propertyName: ${$.propertyName}}`},Fq={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Hq,code($){let{gen:w,schema:Z,data:W,it:X}=$;if((0,Uq.alwaysValidSchema)(X,Z))return;let Y=w.name("valid");w.forIn("key",W,(G)=>{$.setParams({propertyName:G}),$.subschema({keyword:"propertyNames",data:G,dataTypes:["string"],propertyName:G,compositeRule:!0},Y),w.if((0,g3.not)(Y),()=>{if($.error(!0),!X.allErrors)w.break()})}),$.ok(Y)}};v3.default=Fq});var lZ=L((h3)=>{Object.defineProperty(h3,"__esModule",{value:!0});var T8=_0(),c0=v(),Eq=Y$(),N8=l(),Lq={message:"must NOT have additional properties",params:({params:$})=>c0._`{additionalProperty: ${$.additionalProperty}}`},Dq={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Lq,code($){let{gen:w,schema:Z,parentSchema:W,data:X,errsCount:Y,it:G}=$;if(!Y)throw Error("ajv implementation error");let{allErrors:J,opts:Q}=G;if(G.props=!0,Q.removeAdditional!=="all"&&(0,N8.alwaysValidSchema)(G,Z))return;let z=(0,T8.allSchemaProperties)(W.properties),M=(0,T8.allSchemaProperties)(W.patternProperties);T(),$.ok(c0._`${Y} === ${Eq.default.errors}`);function T(){w.forIn("key",X,(q)=>{if(!z.length&&!M.length)B(q);else w.if(N(q),()=>B(q))})}function N(q){let U;if(z.length>8){let O=(0,N8.schemaRefOrVal)(G,W.properties,"properties");U=(0,T8.isOwnProperty)(w,O,q)}else if(z.length)U=(0,c0.or)(...z.map((O)=>c0._`${q} === ${O}`));else U=c0.nil;if(M.length)U=(0,c0.or)(U,...M.map((O)=>c0._`${(0,T8.usePattern)($,O)}.test(${q})`));return(0,c0.not)(U)}function K(q){w.code(c0._`delete ${X}[${q}]`)}function B(q){if(Q.removeAdditional==="all"||Q.removeAdditional&&Z===!1){K(q);return}if(Z===!1){if($.setParams({additionalProperty:q}),$.error(),!J)w.break();return}if(typeof Z=="object"&&!(0,N8.alwaysValidSchema)(G,Z)){let U=w.name("valid");if(Q.removeAdditional==="failing")P(q,U,!1),w.if((0,c0.not)(U),()=>{$.reset(),K(q)});else if(P(q,U),!J)w.if((0,c0.not)(U),()=>w.break())}}function P(q,U,O){let f={keyword:"additionalProperties",dataProp:q,dataPropType:N8.Type.Str};if(O===!1)Object.assign(f,{compositeRule:!0,createErrors:!1,allErrors:!1});$.subschema(f,U)}}};h3.default=Dq});var c3=L((l3)=>{Object.defineProperty(l3,"__esModule",{value:!0});var kq=bw(),i3=_0(),cZ=l(),m3=lZ(),Aq={keyword:"properties",type:"object",schemaType:"object",code($){let{gen:w,schema:Z,parentSchema:W,data:X,it:Y}=$;if(Y.opts.removeAdditional==="all"&&W.additionalProperties===void 0)m3.default.code(new kq.KeywordCxt(Y,m3.default,"additionalProperties"));let G=(0,i3.allSchemaProperties)(Z);for(let T of G)Y.definedProperties.add(T);if(Y.opts.unevaluated&&G.length&&Y.props!==!0)Y.props=cZ.mergeEvaluated.props(w,(0,cZ.toHash)(G),Y.props);let J=G.filter((T)=>!(0,cZ.alwaysValidSchema)(Y,Z[T]));if(J.length===0)return;let Q=w.name("valid");for(let T of J){if(z(T))M(T);else{if(w.if((0,i3.propertyInData)(w,X,T,Y.opts.ownProperties)),M(T),!Y.allErrors)w.else().var(Q,!0);w.endIf()}$.it.definedProperties.add(T),$.ok(Q)}function z(T){return Y.opts.useDefaults&&!Y.compositeRule&&Z[T].default!==void 0}function M(T){$.subschema({keyword:"properties",schemaProp:T,dataProp:T},Q)}}};l3.default=Aq});var r3=L((t3)=>{Object.defineProperty(t3,"__esModule",{value:!0});var d3=_0(),K8=v(),p3=l(),n3=l(),Rq={keyword:"patternProperties",type:"object",schemaType:"object",code($){let{gen:w,schema:Z,data:W,parentSchema:X,it:Y}=$,{opts:G}=Y,J=(0,d3.allSchemaProperties)(Z),Q=J.filter((P)=>(0,p3.alwaysValidSchema)(Y,Z[P]));if(J.length===0||Q.length===J.length&&(!Y.opts.unevaluated||Y.props===!0))return;let z=G.strictSchema&&!G.allowMatchingProperties&&X.properties,M=w.name("valid");if(Y.props!==!0&&!(Y.props instanceof K8.Name))Y.props=(0,n3.evaluatedPropsToName)(w,Y.props);let{props:T}=Y;N();function N(){for(let P of J){if(z)K(P);if(Y.allErrors)B(P);else w.var(M,!0),B(P),w.if(M)}}function K(P){for(let q in z)if(new RegExp(P).test(q))(0,p3.checkStrictMode)(Y,`property ${q} matches pattern ${P} (use allowMatchingProperties)`)}function B(P){w.forIn("key",W,(q)=>{w.if(K8._`${(0,d3.usePattern)($,P)}.test(${q})`,()=>{let U=Q.includes(P);if(!U)$.subschema({keyword:"patternProperties",schemaProp:P,dataProp:q,dataPropType:n3.Type.Str},M);if(Y.opts.unevaluated&&T!==!0)w.assign(K8._`${T}[${q}]`,!0);else if(!U&&!Y.allErrors)w.if((0,K8.not)(M),()=>w.break())})})}}};t3.default=Rq});var a3=L((s3)=>{Object.defineProperty(s3,"__esModule",{value:!0});var jq=l(),Iq={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code($){let{gen:w,schema:Z,it:W}=$;if((0,jq.alwaysValidSchema)(W,Z)){$.fail();return}let X=w.name("valid");$.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},X),$.failResult(X,()=>$.reset(),()=>$.error())},error:{message:"must NOT be valid"}};s3.default=Iq});var e3=L((o3)=>{Object.defineProperty(o3,"__esModule",{value:!0});var bq=_0(),xq={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:bq.validateUnion,error:{message:"must match a schema in anyOf"}};o3.default=xq});var w7=L(($7)=>{Object.defineProperty($7,"__esModule",{value:!0});var B8=v(),gq=l(),vq={message:"must match exactly one schema in oneOf",params:({params:$})=>B8._`{passingSchemas: ${$.passing}}`},uq={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:vq,code($){let{gen:w,schema:Z,parentSchema:W,it:X}=$;if(!Array.isArray(Z))throw Error("ajv implementation error");if(X.opts.discriminator&&W.discriminator)return;let Y=Z,G=w.let("valid",!1),J=w.let("passing",null),Q=w.name("_valid");$.setParams({passing:J}),w.block(z),$.result(G,()=>$.reset(),()=>$.error(!0));function z(){Y.forEach((M,T)=>{let N;if((0,gq.alwaysValidSchema)(X,M))w.var(Q,!0);else N=$.subschema({keyword:"oneOf",schemaProp:T,compositeRule:!0},Q);if(T>0)w.if(B8._`${Q} && ${G}`).assign(G,!1).assign(J,B8._`[${J}, ${T}]`).else();w.if(Q,()=>{if(w.assign(G,!0),w.assign(J,T),N)$.mergeEvaluated(N,B8.Name)})})}}};$7.default=uq});var W7=L((Z7)=>{Object.defineProperty(Z7,"__esModule",{value:!0});var iq=l(),mq={keyword:"allOf",schemaType:"array",code($){let{gen:w,schema:Z,it:W}=$;if(!Array.isArray(Z))throw Error("ajv implementation error");let X=w.name("valid");Z.forEach((Y,G)=>{if((0,iq.alwaysValidSchema)(W,Y))return;let J=$.subschema({keyword:"allOf",schemaProp:G},X);$.ok(X),$.mergeEvaluated(J)})}};Z7.default=mq});var J7=L((G7)=>{Object.defineProperty(G7,"__esModule",{value:!0});var V8=v(),Y7=l(),cq={message:({params:$})=>V8.str`must match "${$.ifClause}" schema`,params:({params:$})=>V8._`{failingKeyword: ${$.ifClause}}`},dq={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:cq,code($){let{gen:w,parentSchema:Z,it:W}=$;if(Z.then===void 0&&Z.else===void 0)(0,Y7.checkStrictMode)(W,'"if" without "then" and "else" is ignored');let X=X7(W,"then"),Y=X7(W,"else");if(!X&&!Y)return;let G=w.let("valid",!0),J=w.name("_valid");if(Q(),$.reset(),X&&Y){let M=w.let("ifClause");$.setParams({ifClause:M}),w.if(J,z("then",M),z("else",M))}else if(X)w.if(J,z("then"));else w.if((0,V8.not)(J),z("else"));$.pass(G,()=>$.error(!0));function Q(){let M=$.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},J);$.mergeEvaluated(M)}function z(M,T){return()=>{let N=$.subschema({keyword:M},J);if(w.assign(G,J),$.mergeValidEvaluated(N,G),T)w.assign(T,V8._`${M}`);else $.setParams({ifClause:M})}}}};function X7($,w){let Z=$.schema[w];return Z!==void 0&&!(0,Y7.alwaysValidSchema)($,Z)}G7.default=dq});var z7=L((Q7)=>{Object.defineProperty(Q7,"__esModule",{value:!0});var nq=l(),tq={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:$,parentSchema:w,it:Z}){if(w.if===void 0)(0,nq.checkStrictMode)(Z,`"${$}" without "if" is ignored`)}};Q7.default=tq});var T7=L((M7)=>{Object.defineProperty(M7,"__esModule",{value:!0});var sq=hZ(),aq=f3(),oq=iZ(),eq=S3(),$U=C3(),wU=_3(),ZU=u3(),WU=lZ(),XU=c3(),YU=r3(),GU=a3(),JU=e3(),QU=w7(),zU=W7(),MU=J7(),TU=z7();function NU($=!1){let w=[GU.default,JU.default,QU.default,zU.default,MU.default,TU.default,ZU.default,WU.default,wU.default,XU.default,YU.default];if($)w.push(aq.default,eq.default);else w.push(sq.default,oq.default);return w.push($U.default),w}M7.default=NU});var K7=L((N7)=>{Object.defineProperty(N7,"__esModule",{value:!0});var o=v(),BU={message:({schemaCode:$})=>o.str`must match format "${$}"`,params:({schemaCode:$})=>o._`{format: ${$}}`},VU={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:BU,code($,w){let{gen:Z,data:W,$data:X,schema:Y,schemaCode:G,it:J}=$,{opts:Q,errSchemaPath:z,schemaEnv:M,self:T}=J;if(!Q.validateFormats)return;if(X)N();else K();function N(){let B=Z.scopeValue("formats",{ref:T.formats,code:Q.code.formats}),P=Z.const("fDef",o._`${B}[${G}]`),q=Z.let("fType"),U=Z.let("format");Z.if(o._`typeof ${P} == "object" && !(${P} instanceof RegExp)`,()=>Z.assign(q,o._`${P}.type || "string"`).assign(U,o._`${P}.validate`),()=>Z.assign(q,o._`"string"`).assign(U,P)),$.fail$data((0,o.or)(O(),f()));function O(){if(Q.strictSchema===!1)return o.nil;return o._`${G} && !${U}`}function f(){let C=M.$async?o._`(${P}.async ? await ${U}(${W}) : ${U}(${W}))`:o._`${U}(${W})`,A=o._`(typeof ${U} == "function" ? ${C} : ${U}.test(${W}))`;return o._`${U} && ${U} !== true && ${q} === ${w} && !${A}`}}function K(){let B=T.formats[Y];if(!B){O();return}if(B===!0)return;let[P,q,U]=f(B);if(P===w)$.pass(C());function O(){if(Q.strictSchema===!1){T.logger.warn(A());return}throw Error(A());function A(){return`unknown format "${Y}" ignored in schema at path "${z}"`}}function f(A){let u=A instanceof RegExp?(0,o.regexpCode)(A):Q.code.formats?o._`${Q.code.formats}${(0,o.getProperty)(Y)}`:void 0,i=Z.scopeValue("formats",{key:Y,ref:A,code:u});if(typeof A=="object"&&!(A instanceof RegExp))return[A.type||"string",A.validate,o._`${i}.validate`];return["string",A,i]}function C(){if(typeof B=="object"&&!(B instanceof RegExp)&&B.async){if(!M.$async)throw Error("async format in sync schema");return o._`await ${U}(${W})`}return typeof q=="function"?o._`${U}(${W})`:o._`${U}.test(${W})`}}}};N7.default=VU});var V7=L((B7)=>{Object.defineProperty(B7,"__esModule",{value:!0});var qU=K7(),UU=[qU.default];B7.default=UU});var U7=L((P7)=>{Object.defineProperty(P7,"__esModule",{value:!0});P7.contentVocabulary=P7.metadataVocabulary=void 0;P7.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];P7.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var O7=L((F7)=>{Object.defineProperty(F7,"__esModule",{value:!0});var OU=lG(),EU=P3(),LU=T7(),DU=V7(),H7=U7(),fU=[OU.default,EU.default,(0,LU.default)(),DU.default,H7.metadataVocabulary,H7.contentVocabulary];F7.default=fU});var f7=L((L7)=>{Object.defineProperty(L7,"__esModule",{value:!0});L7.DiscrError=void 0;var E7;(function($){$.Tag="tag",$.Mapping="mapping"})(E7||(L7.DiscrError=E7={}))});var S7=L((A7)=>{Object.defineProperty(A7,"__esModule",{value:!0});var u1=v(),dZ=f7(),k7=s4(),AU=xw(),SU=l(),RU={message:({params:{discrError:$,tagName:w}})=>$===dZ.DiscrError.Tag?`tag "${w}" must be string`:`value of tag "${w}" must be in oneOf`,params:({params:{discrError:$,tag:w,tagName:Z}})=>u1._`{error: ${$}, tag: ${Z}, tagValue: ${w}}`},CU={keyword:"discriminator",type:"object",schemaType:"object",error:RU,code($){let{gen:w,data:Z,schema:W,parentSchema:X,it:Y}=$,{oneOf:G}=X;if(!Y.opts.discriminator)throw Error("discriminator: requires discriminator option");let J=W.propertyName;if(typeof J!="string")throw Error("discriminator: requires propertyName");if(W.mapping)throw Error("discriminator: mapping is not supported");if(!G)throw Error("discriminator: requires oneOf keyword");let Q=w.let("valid",!1),z=w.const("tag",u1._`${Z}${(0,u1.getProperty)(J)}`);w.if(u1._`typeof ${z} == "string"`,()=>M(),()=>$.error(!1,{discrError:dZ.DiscrError.Tag,tag:z,tagName:J})),$.ok(Q);function M(){let K=N();w.if(!1);for(let B in K)w.elseIf(u1._`${z} === ${B}`),w.assign(Q,T(K[B]));w.else(),$.error(!1,{discrError:dZ.DiscrError.Mapping,tag:z,tagName:J}),w.endIf()}function T(K){let B=w.name("valid"),P=$.subschema({keyword:"oneOf",schemaProp:K},B);return $.mergeEvaluated(P,u1.Name),B}function N(){var K;let B={},P=U(X),q=!0;for(let C=0;C<G.length;C++){let A=G[C];if((A===null||A===void 0?void 0:A.$ref)&&!(0,SU.schemaHasRulesButRef)(A,Y.self.RULES)){let i=A.$ref;if(A=k7.resolveRef.call(Y.self,Y.schemaEnv.root,Y.baseId,i),A instanceof k7.SchemaEnv)A=A.schema;if(A===void 0)throw new AU.default(Y.opts.uriResolver,Y.baseId,i)}let u=(K=A===null||A===void 0?void 0:A.properties)===null||K===void 0?void 0:K[J];if(typeof u!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${J}"`);q=q&&(P||U(A)),O(u,C)}if(!q)throw Error(`discriminator: "${J}" must be required`);return B;function U({required:C}){return Array.isArray(C)&&C.includes(J)}function O(C,A){if(C.const)f(C.const,A);else if(C.enum)for(let u of C.enum)f(u,A);else throw Error(`discriminator: "properties/${J}" must have "const" or "enum"`)}function f(C,A){if(typeof C!="string"||C in B)throw Error(`discriminator: "${J}" values must be unique strings`);B[C]=A}}}};A7.default=CU});var R7=L((bD,IU)=>{IU.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var j7=L((f0,pZ)=>{Object.defineProperty(f0,"__esModule",{value:!0});f0.MissingRefError=f0.ValidationError=f0.CodeGen=f0.Name=f0.nil=f0.stringify=f0.str=f0._=f0.KeywordCxt=f0.Ajv=void 0;var yU=yG(),bU=O7(),xU=S7(),C7=R7(),_U=["/properties"],P8="http://json-schema.org/draft-07/schema";class tw extends yU.default{_addVocabularies(){if(super._addVocabularies(),bU.default.forEach(($)=>this.addVocabulary($)),this.opts.discriminator)this.addKeyword(xU.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let $=this.opts.$data?this.$dataMetaSchema(C7,_U):C7;this.addMetaSchema($,P8,!1),this.refs["http://json-schema.org/schema"]=P8}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(P8)?P8:void 0)}}f0.Ajv=tw;pZ.exports=f0=tw;pZ.exports.Ajv=tw;Object.defineProperty(f0,"__esModule",{value:!0});f0.default=tw;var gU=bw();Object.defineProperty(f0,"KeywordCxt",{enumerable:!0,get:function(){return gU.KeywordCxt}});var h1=v();Object.defineProperty(f0,"_",{enumerable:!0,get:function(){return h1._}});Object.defineProperty(f0,"str",{enumerable:!0,get:function(){return h1.str}});Object.defineProperty(f0,"stringify",{enumerable:!0,get:function(){return h1.stringify}});Object.defineProperty(f0,"nil",{enumerable:!0,get:function(){return h1.nil}});Object.defineProperty(f0,"Name",{enumerable:!0,get:function(){return h1.Name}});Object.defineProperty(f0,"CodeGen",{enumerable:!0,get:function(){return h1.CodeGen}});var vU=t4();Object.defineProperty(f0,"ValidationError",{enumerable:!0,get:function(){return vU.default}});var uU=xw();Object.defineProperty(f0,"MissingRefError",{enumerable:!0,get:function(){return uU.default}})});var KJ=L((ik,K5)=>{var C8=process||{},TJ=C8.argv||[],R8=C8.env||{},vH=!(!!R8.NO_COLOR||TJ.includes("--no-color"))&&(!!R8.FORCE_COLOR||TJ.includes("--color")||C8.platform==="win32"||(C8.stdout||{}).isTTY&&R8.TERM!=="dumb"||!!R8.CI),uH=($,w,Z=$)=>(W)=>{let X=""+W,Y=X.indexOf(w,$.length);return~Y?$+hH(X,w,Z,Y)+w:$+X+w},hH=($,w,Z,W)=>{let X="",Y=0;do X+=$.substring(Y,W)+Z,Y=W+w.length,W=$.indexOf(w,Y);while(~W);return X+$.substring(Y)},NJ=($=vH)=>{let w=$?uH:()=>String;return{isColorSupported:$,reset:w("\x1B[0m","\x1B[0m"),bold:w("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:w("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:w("\x1B[3m","\x1B[23m"),underline:w("\x1B[4m","\x1B[24m"),inverse:w("\x1B[7m","\x1B[27m"),hidden:w("\x1B[8m","\x1B[28m"),strikethrough:w("\x1B[9m","\x1B[29m"),black:w("\x1B[30m","\x1B[39m"),red:w("\x1B[31m","\x1B[39m"),green:w("\x1B[32m","\x1B[39m"),yellow:w("\x1B[33m","\x1B[39m"),blue:w("\x1B[34m","\x1B[39m"),magenta:w("\x1B[35m","\x1B[39m"),cyan:w("\x1B[36m","\x1B[39m"),white:w("\x1B[37m","\x1B[39m"),gray:w("\x1B[90m","\x1B[39m"),bgBlack:w("\x1B[40m","\x1B[49m"),bgRed:w("\x1B[41m","\x1B[49m"),bgGreen:w("\x1B[42m","\x1B[49m"),bgYellow:w("\x1B[43m","\x1B[49m"),bgBlue:w("\x1B[44m","\x1B[49m"),bgMagenta:w("\x1B[45m","\x1B[49m"),bgCyan:w("\x1B[46m","\x1B[49m"),bgWhite:w("\x1B[47m","\x1B[49m"),blackBright:w("\x1B[90m","\x1B[39m"),redBright:w("\x1B[91m","\x1B[39m"),greenBright:w("\x1B[92m","\x1B[39m"),yellowBright:w("\x1B[93m","\x1B[39m"),blueBright:w("\x1B[94m","\x1B[39m"),magentaBright:w("\x1B[95m","\x1B[39m"),cyanBright:w("\x1B[96m","\x1B[39m"),whiteBright:w("\x1B[97m","\x1B[39m"),bgBlackBright:w("\x1B[100m","\x1B[49m"),bgRedBright:w("\x1B[101m","\x1B[49m"),bgGreenBright:w("\x1B[102m","\x1B[49m"),bgYellowBright:w("\x1B[103m","\x1B[49m"),bgBlueBright:w("\x1B[104m","\x1B[49m"),bgMagentaBright:w("\x1B[105m","\x1B[49m"),bgCyanBright:w("\x1B[106m","\x1B[49m"),bgWhiteBright:w("\x1B[107m","\x1B[49m")}};K5.exports=NJ();K5.exports.createColors=NJ});import{realpathSync as Az}from"fs";import{realpath as PE}from"fs/promises";import qE from"path";import{createInterface as UE}from"readline/promises";import{fileURLToPath as HE}from"url";var oW=R4(d6(),1),{program:yE,createCommand:bE,createArgument:xE,createOption:_E,CommanderError:gE,InvalidArgumentError:vE,InvalidOptionArgumentError:uE,Command:eW,Argument:hE,Option:iE,Help:mE}=oW.default;import $X from"node:os";import I4 from"node:path";function wX(){return process.env.XDG_CONFIG_HOME?I4.join(process.env.XDG_CONFIG_HOME,"coden"):I4.join($X.homedir(),".config","coden")}function ZX(){return process.env.XDG_DATA_HOME?I4.join(process.env.XDG_DATA_HOME,"coden"):I4.join($X.homedir(),".local","share","coden")}import{mkdir as SM,readFile as RM,realpath as WX,writeFile as CM}from"node:fs/promises";import jM from"node:path";class p6{file;constructor($){this.file=$}async isTrusted($){return(await this.read()).includes($)}async isWorkspaceTrusted($){return this.isTrusted(await WX($))}async trustWorkspace($){return this.trust(await WX($))}async trust($){let w=await this.read();if(!w.includes($))w.push($);await SM(jM.dirname(this.file),{recursive:!0}),await CM(this.file,`${JSON.stringify(w,null,2)}
|
|
36
|
+
`,{encoding:"utf8",mode:384})}async read(){try{let $=JSON.parse(await RM(this.file,"utf8"));return Array.isArray($)?$.filter((w)=>typeof w==="string"):[]}catch($){if($.code==="ENOENT")return[];throw $}}}function R1($,w){if($.length<=w)return $;let W=Math.max(0,w-80),X=Math.ceil(W/2),Y=Math.floor(W/2),G=$.length-X-Y;return`${$.slice(0,X)}
|
|
37
37
|
... [${G} characters omitted] ...
|
|
38
|
-
${$.slice($.length-Y)}`}class j extends Error{category;code;retryable;details;constructor($,w,Z,W=!1,X,Y){super(Z,Y);this.category=$;this.code=w;this.retryable=W;this.details=X;this.name="CodeNError"}}import{spawn as
|
|
38
|
+
${$.slice($.length-Y)}`}class j extends Error{category;code;retryable;details;constructor($,w,Z,W=!1,X,Y){super(Z,Y);this.category=$;this.code=w;this.retryable=W;this.details=X;this.name="CodeNError"}}import{spawn as IM}from"node:child_process";class n6{headLimit;tailLimit;head="";tail="";total=0;constructor($){this.headLimit=Math.ceil($*0.6),this.tailLimit=Math.floor($*0.4)}add($){this.total+=$.length;let w=Math.max(0,this.headLimit-this.head.length);this.head+=$.slice(0,w);let Z=$.slice(w);if(Z)this.tail=`${this.tail}${Z}`.slice(-this.tailLimit)}value(){let $=this.total-this.head.length-this.tail.length;return $>0?`${this.head}
|
|
39
39
|
... [${$} characters omitted while capturing] ...
|
|
40
|
-
${this.tail}`:`${this.head}${this.tail}`}}var y4=($,w,Z)=>new Promise((W)=>{let X=process.platform!=="win32",Y=
|
|
40
|
+
${this.tail}`:`${this.head}${this.tail}`}}var y4=($,w,Z)=>new Promise((W)=>{let X=process.platform!=="win32",Y=IM($,w,{cwd:Z.cwd,env:Z.env,stdio:["ignore","pipe","pipe"],detached:X}),G=new n6(Z.maxOutputChars),J=new n6(Z.maxOutputChars),Q=!1,z=!1,M=!1,T,N,K=(U)=>{if(X&&Y.pid)try{process.kill(-Y.pid,U);return}catch{}Y.kill(U)},B=(U,O)=>{if(M)return;if((Q||z)&&X&&Y.pid)try{process.kill(-Y.pid,"SIGKILL")}catch{}if(M=!0,clearTimeout(N),T)clearTimeout(T);Z.signal?.removeEventListener("abort",q),W({ok:!Q&&!z&&U===0,stdout:G.value(),stderr:J.value(),exitCode:U,signal:O,timedOut:Q,cancelled:z})},P=()=>{if(T)return;T=setTimeout(()=>K("SIGKILL"),500),T.unref()},q=()=>{if(z)return;z=!0,K("SIGTERM"),P()};if(Y.stdout.setEncoding("utf8"),Y.stderr.setEncoding("utf8"),Y.stdout.on("data",(U)=>G.add(U)),Y.stderr.on("data",(U)=>J.add(U)),Y.once("error",(U)=>{J.add(U.message),B(null,null)}),Y.once("close",B),Z.signal?.aborted)q();else Z.signal?.addEventListener("abort",q,{once:!0});N=setTimeout(()=>{Q=!0,K("SIGTERM"),P()},Z.timeoutMs)});function yM($){let w=$.timedOut?"bun install timed out":$.cancelled?"bun install cancelled":`bun install exited with code ${$.exitCode??"null"}${$.signal?` (signal ${$.signal})`:""}`;return R1([w,$.stderr?`stderr:
|
|
41
41
|
${$.stderr}`:`stderr:
|
|
42
42
|
<empty>`].join(`
|
|
43
|
-
`),4000)}class t6{runner;constructor($=y4){this.runner=$}async install($){let w=["install","--registry","https://registry.npmjs.org"];if($.frozenLockfile)w.push("--frozen-lockfile");if(!$.allowScripts)w.push("--ignore-scripts");let Z=await this.runner("bun",w,{cwd:$.cwd,env:process.env,...$.signal?{signal:$.signal}:{},timeoutMs:120000,maxOutputChars:30000});if(!Z.ok)throw new j("plugin","plugin.install_failed",
|
|
44
|
-
`}function b7($){let w=rZ($),Z={};for(let[W,X]of Object.entries(w.plugins))Z[W]=X.requested;return{private:!0,dependencies:Z}}function rZ($){if(!$||typeof $!=="object")throw Z1();let w=$;if(w.schemaVersion!==1)throw Z1();if(!w.plugins||typeof w.plugins!=="object"||Array.isArray(w.plugins))throw Z1();let Z={};for(let W of Object.keys(w.plugins).sort()){if(!w1(W))throw Z1();let X=w.plugins[W];if(!X||typeof X!=="object"||Array.isArray(X))throw Z1();let Y=X;if(Y.source!=="npm"||typeof Y.requested!=="string"||!Y.requested)throw Z1();Z[W]={source:"npm",requested:Y.requested}}return{schemaVersion:1,plugins:Z}}function lU($){return typeof $==="object"&&$!==null&&"code"in $&&$.code==="ENOENT"}function Z1($,w){return new j("plugin","plugin.manifest_invalid",w?`plugin.manifest_invalid: ${w}`:"plugin.manifest_invalid",!1,void 0,$ instanceof Error?{cause:$}:void 0)}import{readFile as cU,realpath as dU}from"node:fs/promises";import U8 from"node:path";async function i1($,w){if(!w1(w))throw W1();let Z=U8.join($,"node_modules",...w.split("/")),W=U8.join(Z,"package.json"),X;try{X=JSON.parse(await cU(W,"utf8"))}catch{throw W1()}let Y=pU(X,w),G=await x7(Z),J=U8.resolve(Z,Y.entry),Q=await x7(J,!0);if(!nU(G,Q))throw sZ();return{packageName:w,version:Y.version,packageDirectory:G,entryPath:Q,apiVersion:1}}function pU($,w){if(!$||typeof $!=="object")throw W1();let Z=$;if(Z.name!==w||typeof Z.version!=="string"||!Z.version)throw W1();if(Z.type!=="module")throw W1();if(!Z.coden||typeof Z.coden!=="object"||Array.isArray(Z.coden))throw W1();let W=Z.coden;if(W.apiVersion!==1)throw rU(W.apiVersion);if(typeof W.plugin!=="string"||!tU(W.plugin))throw sZ();return{version:Z.version,entry:W.plugin}}async function x7($,w=!1){try{return await dU($)}catch{if(w)throw sZ();throw W1()}}function nU($,w){return w===$||w.startsWith(`${$}${U8.sep}`)}function tU($){if(!$.startsWith("./"))return!1;if($.includes("\\")||$.includes("://")||/\s/.test($))return!1;if(!($.endsWith(".js")||$.endsWith(".mjs")))return!1;if($.split("/").includes(".."))return!1;return!0}function W1(){return new j("plugin","plugin.metadata_missing","plugin.metadata_missing")}function rU($){return new j("plugin","plugin.api_unsupported",`plugin.api_unsupported: ${String($)}`)}function sZ(){return new j("plugin","plugin.entry_invalid","plugin.entry_invalid")}class aZ{importer;constructor($=(w)=>import(w)){this.importer=$}async loadScope($){let w=await J$($.manifestPath),Z=[],W=[];for(let X of Object.keys(w.plugins).sort()){let Y=oU($.runtimeDir,X);try{let G=await i1($.runtimeDir,X);try{let J=await this.importer(aU(G.entryPath).href),Q=q8(J.default,X);Z.push({packageName:X,version:G.version,entryPath:G.entryPath,tools:Q})}catch(J){W.push({packageName:X,path:G.entryPath,message:_7(J)})}}catch(G){W.push({packageName:X,path:Y,message:_7(G)})}}return{loaded:Z,failed:W}}}function oU($,w){return sU.join($,"node_modules",...w.split("/"))}function _7($){return $ instanceof Error?$.message:String($)}import{constants as zH}from"node:fs";import{access as MH,copyFile as TH,mkdir as KH,writeFile as O8}from"node:fs/promises";import j$ from"node:path";import eU from"node:path";import{pathToFileURL as $H}from"node:url";class oZ{importer;constructor($=(w)=>import(w)){this.importer=$}async loadScope($){let w=await J$($.manifestPath),Z=[],W=[];for(let X of Object.keys(w.plugins).sort()){let Y=ZH($.runtimeDir,X);try{let G=await i1($.runtimeDir,X);try{let J=await this.importer($H(G.entryPath).href),Q=q8(J.default,X);Z.push({packageName:X,version:G.version,entryPath:G.entryPath,tools:Q})}catch(J){W.push({packageName:X,path:G.entryPath,message:v7(J)})}}catch(G){W.push({packageName:X,path:Y,message:v7(G)})}}return{loaded:Z,failed:W}}}function eZ($,w,Z){let W=new t0($),X=new Map(Z.map((Q)=>[Q.packageName,Q])),Y=[],G=[];for(let Q of w){let z=X.get(Q.packageName);if(z){Y.push({packageName:Q.packageName,globalVersion:Q.version,projectVersion:z.version});continue}G.push(Q)}let J=[...G,...Z];for(let Q of J)wH(W,Q);return{registry:W,effective:J,shadowed:Y}}function wH($,w){let Z={kind:"npm",pluginName:w.packageName,pluginVersion:w.version,path:w.entryPath};for(let W of w.tools){let X=$.source(W.name);if(X)throw new j("plugin","plugin.tool_conflict",`plugin.tool_conflict: ${W.name} from ${g7(X)} conflicts with ${g7(Z)}`);$.register(W,Z)}}function ZH($,w){return eU.join($,"node_modules",...w.split("/"))}function g7($){switch($.kind){case"builtin":return"builtin";case"local":return $.path?`local:${$.path}`:"local";case"npm":return $.path?`${$.pluginName}@${$.pluginVersion}:${$.path}`:`${$.pluginName}@${$.pluginVersion}`}}function v7($){return $ instanceof Error?$.message:String($)}import r0 from"node:path";import{readFile as WH}from"node:fs/promises";import i7 from"node:os";import m1 from"node:path";function H8(){return process.env.XDG_CONFIG_HOME?m1.join(process.env.XDG_CONFIG_HOME,"coden"):m1.join(i7.homedir(),".config","coden")}function $5(){return process.env.XDG_DATA_HOME?m1.join(process.env.XDG_DATA_HOME,"coden"):m1.join(i7.homedir(),".local","share","coden")}async function u7($){try{let w=JSON.parse(await WH($,"utf8"));return XH(w)}catch(w){if(w.code==="ENOENT")return{};throw Error(`Cannot read config ${$}: ${w instanceof Error?w.message:String(w)}`)}}function XH($){let w={};if($.provider==="openai"||$.provider==="anthropic")w.provider=$.provider;if(typeof $.model==="string")w.model=$.model;if(typeof $.maxSteps==="number")w.maxSteps=$.maxSteps;if(typeof $.contextWindow==="number")w.contextWindow=$.contextWindow;if(typeof $.reservedOutputTokens==="number")w.reservedOutputTokens=$.reservedOutputTokens;if(typeof $.safetyMargin==="number")w.safetyMargin=$.safetyMargin;if(Array.isArray($.plugins))w.plugins=$.plugins.filter((Z)=>typeof Z==="string");if($.env!==void 0){if(typeof $.env!=="object"||$.env===null||Array.isArray($.env))throw Error("env must be an object");let Z={};for(let[W,X]of Object.entries($.env)){if(typeof X!=="string")throw Error(`env "${W}" must be a string`);Z[W]=X}w.env=Z}return w}function h7($){let{env:w,...Z}=$;return Z}async function m7($,w={}){let Z={provider:"openai",model:"gpt-5-mini",maxSteps:20,contextWindow:128000,reservedOutputTokens:8192,safetyMargin:4096,plugins:[],dataDir:$5(),env:{}},W=await u7(m1.join(H8(),"config.json")),X=await u7(m1.join($,".coden","config.json")),Y={};if(process.env.CODEN_PROVIDER==="openai"||process.env.CODEN_PROVIDER==="anthropic")Y.provider=process.env.CODEN_PROVIDER;if(process.env.CODEN_MODEL)Y.model=process.env.CODEN_MODEL;if(process.env.CODEN_MAX_STEPS)Y.maxSteps=Number(process.env.CODEN_MAX_STEPS);let G={...W.env??{},...X.env??{}};for(let[Q,z]of Object.entries(G))if(process.env[Q]===void 0)process.env[Q]=z;let J={...Z,...h7(W),...h7(X),...Y,...w,env:G};if(J.plugins=[...W.plugins??[],...X.plugins??[],...w.plugins??[]],J.provider!=="openai"&&J.provider!=="anthropic")throw Error("provider must be openai or anthropic");if(typeof J.model!=="string"||!J.model.trim())throw Error("model must be a non-empty string");if(!Number.isInteger(J.maxSteps)||J.maxSteps<1)throw Error("maxSteps must be a positive integer");for(let Q of["contextWindow","reservedOutputTokens","safetyMargin"])if(!Number.isInteger(J[Q])||J[Q]<0)throw Error(`${Q} must be a non-negative integer`);if(J.contextWindow===0||J.reservedOutputTokens===0)throw Error("contextWindow and reservedOutputTokens must be positive");if(J.contextWindow<=J.reservedOutputTokens+J.safetyMargin)throw Error("contextWindow must exceed reservedOutputTokens plus safetyMargin");if(!Array.isArray(J.plugins)||J.plugins.some((Q)=>typeof Q!=="string"))throw Error("plugins must be an array of paths");return J}function sw($,w,Z=$5()){if(w==="project"){let Y=r0.join($,".coden"),G=r0.join(Y,"plugin-runtime");return{scope:w,root:Y,manifestPath:r0.join(Y,"plugins.json"),runtimeDir:G,lockPath:r0.join(Y,"plugin-lock"),transactionPath:r0.join(Y,"plugin-transaction.json")}}let W=r0.join(Z,"plugins"),X=r0.join(W,"runtime");return{scope:w,root:W,manifestPath:r0.join(W,"plugins.json"),runtimeDir:X,lockPath:r0.join(W,"plugin-lock"),transactionPath:r0.join(W,"plugin-transaction.json")}}import{randomUUID as YH}from"node:crypto";import{constants as GH}from"node:fs";import{access as JH,mkdir as F8,readFile as l7,rename as R$,rm as e,writeFile as c7}from"node:fs/promises";import C$ from"node:path";class Z5 extends Error{constructor($){super($ instanceof Error?$.message:String($),$ instanceof Error?{cause:$}:void 0);this.name="FaultInterruption"}}class A0{paths;options;constructor($,w={}){this.paths=$;this.options=w}async run($){let w=!1,Z;try{await this.acquireLock(),w=!0,await this.recoverLocked();let W=YH(),X=C$.join(this.paths.root,`.transaction-${W}-stage`);Z={version:1,id:W,phase:"prepared",stageDirectory:X,backupManifestPath:C$.join(this.paths.root,`.transaction-${W}-plugins.json.bak`),backupRuntimeDir:C$.join(this.paths.root,`.transaction-${W}-runtime.bak`),hadManifest:await aw(this.paths.manifestPath),hadRuntime:await aw(this.paths.runtimeDir)},await F8(X,{recursive:!0});let Y={manifestPath:C$.join(X,"plugins.json"),runtimeDir:C$.join(X,"runtime")},G=await $(Y);await this.verifyCandidate(Y),await this.writeMarker(Z),await this.backupCurrent(Z);let J={...Z,phase:"backed-up"};await this.writeMarker(J),Z=J,this.fault("after-backup"),await R$(Y.runtimeDir,this.paths.runtimeDir);let Q={...Z,phase:"runtime-committed"};await this.writeMarker(Q),Z=Q,this.fault("after-runtime-commit"),await R$(Y.manifestPath,this.paths.manifestPath);let z={...Z,phase:"manifest-committed"};return await this.writeMarker(z),Z=z,this.fault("after-manifest-commit"),await this.cleanupCommitted(Z),G}catch(W){if(W instanceof Z5)throw W.cause??W;throw await this.rollbackAfterError(Z),W}finally{if(w)await this.releaseLock()}}async recover(){let $=!1;try{await this.acquireLock(),$=!0,await this.recoverLocked()}finally{if($)await this.releaseLock()}}async acquireLock(){await F8(this.paths.root,{recursive:!0});for(let $=0;$<2;$++){try{await F8(this.paths.lockPath)}catch(w){if(!w5(w,"EEXIST"))throw w;let Z=await this.readLockOwner();if(!Z||this.isProcessAlive(Z.pid))throw new j("plugin","plugin.install_busy",`plugin.install_busy: ${this.paths.scope} plugin installation is already running`,!0,{scope:this.paths.scope});if($===1)throw new j("plugin","plugin.install_busy",`plugin.install_busy: could not acquire ${this.paths.scope} plugin lock`,!0,{scope:this.paths.scope});await e(this.paths.lockPath,{recursive:!0,force:!0});continue}try{await c7(C$.join(this.paths.lockPath,"owner.json"),`${JSON.stringify({pid:process.pid,createdAt:this.now()})}
|
|
45
|
-
`,{mode:384});return}catch(w){throw await e(this.paths.lockPath,{recursive:!0,force:!0}),w}}}async readLockOwner(){try{let $=JSON.parse(await
|
|
46
|
-
`,{mode:384}),await R$(w,this.paths.transactionPath)}async cleanupCommitted($){await e($.backupManifestPath,{force:!0}),await e($.backupRuntimeDir,{recursive:!0,force:!0}),await e($.stageDirectory,{recursive:!0,force:!0}),await e(this.paths.transactionPath,{force:!0}),await e(`${this.paths.transactionPath}.tmp`,{recursive:!0,force:!0})}async cleanupRecoveryArtifacts($){await e($.stageDirectory,{recursive:!0,force:!0}),await e(this.paths.transactionPath,{force:!0}),await e(`${this.paths.transactionPath}.tmp`,{recursive:!0,force:!0})}async removeCurrentTargets(){await e(this.paths.manifestPath,{force:!0}),await e(this.paths.runtimeDir,{recursive:!0,force:!0})}async restoreBackups($){if($.hadManifest)await R$($.backupManifestPath,this.paths.manifestPath);if($.hadRuntime)await R$($.backupRuntimeDir,this.paths.runtimeDir)}async restoreBackupPairBestEffort($){await this.restoreSingleBackup({hadTarget:$.hadManifest,backupPath:$.backupManifestPath,targetPath:this.paths.manifestPath,directory:!1}),await this.restoreSingleBackup({hadTarget:$.hadRuntime,backupPath:$.backupRuntimeDir,targetPath:this.paths.runtimeDir,directory:!0})}async restoreSingleBackup($){if(await aw($.backupPath)){await e($.targetPath,{recursive:$.directory,force:!0}),await R$($.backupPath,$.targetPath);return}if(!$.hadTarget)await e($.targetPath,{recursive:$.directory,force:!0})}fault($){try{this.options.fault?.($)}catch(w){throw new
|
|
47
|
-
`,"utf8"),await
|
|
43
|
+
`),4000)}class t6{runner;constructor($=y4){this.runner=$}async install($){let w=["install","--registry","https://registry.npmjs.org"];if($.frozenLockfile)w.push("--frozen-lockfile");if(!$.allowScripts)w.push("--ignore-scripts");let Z=await this.runner("bun",w,{cwd:$.cwd,env:process.env,...$.signal?{signal:$.signal}:{},timeoutMs:120000,maxOutputChars:30000});if(!Z.ok)throw new j("plugin","plugin.install_failed",yM(Z))}}import eU from"node:path";import{pathToFileURL as $H}from"node:url";var y7=R4(j7(),1);var nZ=new y7.default({allErrors:!0,strict:!1,useDefaults:!0});class r0{#$=new Map;constructor($=[]){for(let w of $)this.register(w,{kind:"builtin"})}register($,w={kind:"local"}){if(!/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/.test($.name))throw new j("plugin","tool.invalid_name",`Invalid tool name: ${$.name}`);let Z=this.#$.get($.name);if(Z)throw new j("plugin","tool.duplicate",`Duplicate tool: ${$.name} from ${I7(Z.source)} and ${I7(w)}`);try{nZ.compile($.inputSchema)}catch(W){throw new j("plugin","tool.invalid_schema",`Invalid schema for ${$.name}`,!1,void 0,{cause:W})}this.#$.set($.name,{definition:$,source:w})}get($){return this.#$.get($)?.definition}list(){return[...this.#$.values()].map(($)=>$.definition)}source($){return this.#$.get($)?.source}entries(){return[...this.#$.values()].map(($)=>({definition:$.definition,source:$.source}))}clone(){let $=new r0;return $.#$=new Map(this.#$),$}replaceWith($){this.#$=new Map($.#$)}validate($,w){let Z=this.get($);if(!Z)return{valid:!1,errors:`Unknown tool: ${$}`};let W=nZ.compile(Z.inputSchema);return W(w)?{valid:!0}:{valid:!1,errors:nZ.errorsText(W.errors)}}}function I7($){switch($.kind){case"builtin":return"builtin";case"local":return $.path?`local:${$.path}`:"local";case"npm":return $.path?`${$.pluginName}@${$.pluginVersion}:${$.path}`:`${$.pluginName}@${$.pluginVersion}`}}var tZ=1;function q8($,w){if(b7($))return[$];if(!$||typeof $!=="object")throw new j("plugin","plugin.export_invalid","plugin.export_invalid: default export must be a tool or CodeNPlugin");let Z=$;if(Z.apiVersion!==tZ)throw new j("plugin","plugin.api_unsupported",`plugin.api_unsupported: ${String(Z.apiVersion)}`);if(Z.name!==w)throw new j("plugin","plugin.name_mismatch",`plugin.name_mismatch: expected ${w}, received ${String(Z.name)}`);if(!Array.isArray(Z.tools)||Z.tools.length===0)throw new j("plugin","plugin.export_invalid","plugin.export_invalid: tools must be a non-empty array");if(!Z.tools.every(b7))throw new j("plugin","plugin.export_invalid","plugin.export_invalid: every tool must match ToolDefinition");return Z.tools}function b7($){if(!$||typeof $!=="object")return!1;let w=$;return typeof w.name==="string"&&typeof w.description==="string"&&(w.risk==="read"||w.risk==="modify"||w.risk==="dangerous")&&!!w.inputSchema&&typeof w.execute==="function"}import{readFile as cU}from"node:fs/promises";var mU=/^(?:@[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*|[a-z0-9][a-z0-9._-]*)$/;function w1($){return mU.test($)&&!$.includes("..")&&!$.includes("\\")}function x7($){if(typeof $!=="string"||!$.startsWith("npm:"))throw rw($);let w=$.slice(4);if(!w||/\s/.test(w)||w.includes("\\")||w.includes("://"))throw rw($);let{packageName:Z,requested:W}=lU(w);if(!w1(Z))throw rw($);if(!W||/\s/.test(W)||W.includes("\\")||W.includes("/")||W.includes(":")||W.includes(".."))throw rw($);return{source:"npm",packageName:Z,requested:W,raw:$}}function lU($){if($.startsWith("@")){let Z=$.indexOf("/");if(Z<2)throw rw($);let W=$.lastIndexOf("@");if(W<=Z)return{packageName:$,requested:"latest"};return{packageName:$.slice(0,W),requested:$.slice(W+1)}}let w=$.lastIndexOf("@");if(w===-1)return{packageName:$,requested:"latest"};return{packageName:$.slice(0,w),requested:$.slice(w+1)}}function rw($){return new j("plugin","plugin.specifier_invalid",`plugin.specifier_invalid: ${String($)}`)}var dU=()=>({schemaVersion:1,plugins:{}});async function Q$($){try{let w=JSON.parse(await cU($,"utf8"));return sZ(w)}catch(w){if(pU(w))return dU();if(w instanceof j)throw w;throw Z1(w,$)}}function rZ($){return`${JSON.stringify(sZ($),null,2)}
|
|
44
|
+
`}function _7($){let w=sZ($),Z={};for(let[W,X]of Object.entries(w.plugins))Z[W]=X.requested;return{private:!0,dependencies:Z}}function sZ($){if(!$||typeof $!=="object")throw Z1();let w=$;if(w.schemaVersion!==1)throw Z1();if(!w.plugins||typeof w.plugins!=="object"||Array.isArray(w.plugins))throw Z1();let Z={};for(let W of Object.keys(w.plugins).sort()){if(!w1(W))throw Z1();let X=w.plugins[W];if(!X||typeof X!=="object"||Array.isArray(X))throw Z1();let Y=X;if(Y.source!=="npm"||typeof Y.requested!=="string"||!Y.requested)throw Z1();Z[W]={source:"npm",requested:Y.requested}}return{schemaVersion:1,plugins:Z}}function pU($){return typeof $==="object"&&$!==null&&"code"in $&&$.code==="ENOENT"}function Z1($,w){return new j("plugin","plugin.manifest_invalid",w?`plugin.manifest_invalid: ${w}`:"plugin.manifest_invalid",!1,void 0,$ instanceof Error?{cause:$}:void 0)}import{readFile as nU,realpath as tU}from"node:fs/promises";import U8 from"node:path";async function i1($,w){if(!w1(w))throw W1();let Z=U8.join($,"node_modules",...w.split("/")),W=U8.join(Z,"package.json"),X;try{X=JSON.parse(await nU(W,"utf8"))}catch{throw W1()}let Y=rU(X,w),G=await g7(Z),J=U8.resolve(Z,Y.entry),Q=await g7(J,!0);if(!sU(G,Q))throw aZ();return{packageName:w,version:Y.version,packageDirectory:G,entryPath:Q,apiVersion:1}}function rU($,w){if(!$||typeof $!=="object")throw W1();let Z=$;if(Z.name!==w||typeof Z.version!=="string"||!Z.version)throw W1();if(Z.type!=="module")throw W1();if(!Z.coden||typeof Z.coden!=="object"||Array.isArray(Z.coden))throw W1();let W=Z.coden;if(W.apiVersion!==1)throw oU(W.apiVersion);if(typeof W.plugin!=="string"||!aU(W.plugin))throw aZ();return{version:Z.version,entry:W.plugin}}async function g7($,w=!1){try{return await tU($)}catch{if(w)throw aZ();throw W1()}}function sU($,w){return w===$||w.startsWith(`${$}${U8.sep}`)}function aU($){if(!$.startsWith("./"))return!1;if($.includes("\\")||$.includes("://")||/\s/.test($))return!1;if(!($.endsWith(".js")||$.endsWith(".mjs")))return!1;if($.split("/").includes(".."))return!1;return!0}function W1(){return new j("plugin","plugin.metadata_missing","plugin.metadata_missing")}function oU($){return new j("plugin","plugin.api_unsupported",`plugin.api_unsupported: ${String($)}`)}function aZ(){return new j("plugin","plugin.entry_invalid","plugin.entry_invalid")}class oZ{importer;constructor($=(w)=>import(w)){this.importer=$}async loadScope($){let w=await Q$($.manifestPath),Z=[],W=[];for(let X of Object.keys(w.plugins).sort()){let Y=wH($.runtimeDir,X);try{let G=await i1($.runtimeDir,X);try{let J=await this.importer($H(G.entryPath).href),Q=q8(J.default,X);Z.push({packageName:X,version:G.version,entryPath:G.entryPath,tools:Q})}catch(J){W.push({packageName:X,path:G.entryPath,message:v7(J)})}}catch(G){W.push({packageName:X,path:Y,message:v7(G)})}}return{loaded:Z,failed:W}}}function wH($,w){return eU.join($,"node_modules",...w.split("/"))}function v7($){return $ instanceof Error?$.message:String($)}import{constants as NH}from"node:fs";import{access as KH,copyFile as BH,mkdir as VH,writeFile as O8}from"node:fs/promises";import j$ from"node:path";import ZH from"node:path";import{pathToFileURL as WH}from"node:url";class eZ{importer;constructor($=(w)=>import(w)){this.importer=$}async loadScope($){let w=await Q$($.manifestPath),Z=[],W=[];for(let X of Object.keys(w.plugins).sort()){let Y=YH($.runtimeDir,X);try{let G=await i1($.runtimeDir,X);try{let J=await this.importer(WH(G.entryPath).href),Q=q8(J.default,X);Z.push({packageName:X,version:G.version,entryPath:G.entryPath,tools:Q})}catch(J){W.push({packageName:X,path:G.entryPath,message:h7(J)})}}catch(G){W.push({packageName:X,path:Y,message:h7(G)})}}return{loaded:Z,failed:W}}}function $5($,w,Z){let W=new r0($),X=new Map(Z.map((Q)=>[Q.packageName,Q])),Y=[],G=[];for(let Q of w){let z=X.get(Q.packageName);if(z){Y.push({packageName:Q.packageName,globalVersion:Q.version,projectVersion:z.version});continue}G.push(Q)}let J=[...G,...Z];for(let Q of J)XH(W,Q);return{registry:W,effective:J,shadowed:Y}}function XH($,w){let Z={kind:"npm",pluginName:w.packageName,pluginVersion:w.version,path:w.entryPath};for(let W of w.tools){let X=$.source(W.name);if(X)throw new j("plugin","plugin.tool_conflict",`plugin.tool_conflict: ${W.name} from ${u7(X)} conflicts with ${u7(Z)}`);$.register(W,Z)}}function YH($,w){return ZH.join($,"node_modules",...w.split("/"))}function u7($){switch($.kind){case"builtin":return"builtin";case"local":return $.path?`local:${$.path}`:"local";case"npm":return $.path?`${$.pluginName}@${$.pluginVersion}:${$.path}`:`${$.pluginName}@${$.pluginVersion}`}}function h7($){return $ instanceof Error?$.message:String($)}import s0 from"node:path";import{readFile as GH}from"node:fs/promises";import l7 from"node:os";import m1 from"node:path";function H8(){return process.env.XDG_CONFIG_HOME?m1.join(process.env.XDG_CONFIG_HOME,"coden"):m1.join(l7.homedir(),".config","coden")}function w5(){return process.env.XDG_DATA_HOME?m1.join(process.env.XDG_DATA_HOME,"coden"):m1.join(l7.homedir(),".local","share","coden")}async function i7($){try{let w=JSON.parse(await GH($,"utf8"));return JH(w)}catch(w){if(w.code==="ENOENT")return{};throw Error(`Cannot read config ${$}: ${w instanceof Error?w.message:String(w)}`)}}function JH($){let w={};if($.provider==="openai"||$.provider==="anthropic")w.provider=$.provider;if(typeof $.model==="string")w.model=$.model;if(typeof $.maxSteps==="number")w.maxSteps=$.maxSteps;if(typeof $.contextWindow==="number")w.contextWindow=$.contextWindow;if(typeof $.reservedOutputTokens==="number")w.reservedOutputTokens=$.reservedOutputTokens;if(typeof $.safetyMargin==="number")w.safetyMargin=$.safetyMargin;if(Array.isArray($.plugins))w.plugins=$.plugins.filter((Z)=>typeof Z==="string");if($.env!==void 0){if(typeof $.env!=="object"||$.env===null||Array.isArray($.env))throw Error("env must be an object");let Z={};for(let[W,X]of Object.entries($.env)){if(typeof X!=="string")throw Error(`env "${W}" must be a string`);Z[W]=X}w.env=Z}return w}function m7($){let{env:w,...Z}=$;return Z}async function c7($,w={}){let Z={provider:"openai",model:"gpt-5-mini",maxSteps:20,contextWindow:128000,reservedOutputTokens:8192,safetyMargin:4096,plugins:[],dataDir:w5(),env:{}},W=await i7(m1.join(H8(),"config.json")),X=await i7(m1.join($,".coden","config.json")),Y={};if(process.env.CODEN_PROVIDER==="openai"||process.env.CODEN_PROVIDER==="anthropic")Y.provider=process.env.CODEN_PROVIDER;if(process.env.CODEN_MODEL)Y.model=process.env.CODEN_MODEL;if(process.env.CODEN_MAX_STEPS)Y.maxSteps=Number(process.env.CODEN_MAX_STEPS);let G={...W.env??{},...X.env??{}};for(let[Q,z]of Object.entries(G))if(process.env[Q]===void 0)process.env[Q]=z;let J={...Z,...m7(W),...m7(X),...Y,...w,env:G};if(J.plugins=[...W.plugins??[],...X.plugins??[],...w.plugins??[]],J.provider!=="openai"&&J.provider!=="anthropic")throw Error("provider must be openai or anthropic");if(typeof J.model!=="string"||!J.model.trim())throw Error("model must be a non-empty string");if(!Number.isInteger(J.maxSteps)||J.maxSteps<1)throw Error("maxSteps must be a positive integer");for(let Q of["contextWindow","reservedOutputTokens","safetyMargin"])if(!Number.isInteger(J[Q])||J[Q]<0)throw Error(`${Q} must be a non-negative integer`);if(J.contextWindow===0||J.reservedOutputTokens===0)throw Error("contextWindow and reservedOutputTokens must be positive");if(J.contextWindow<=J.reservedOutputTokens+J.safetyMargin)throw Error("contextWindow must exceed reservedOutputTokens plus safetyMargin");if(!Array.isArray(J.plugins)||J.plugins.some((Q)=>typeof Q!=="string"))throw Error("plugins must be an array of paths");return J}function sw($,w,Z=w5()){if(w==="project"){let Y=s0.join($,".coden"),G=s0.join(Y,"plugin-runtime");return{scope:w,root:Y,manifestPath:s0.join(Y,"plugins.json"),runtimeDir:G,lockPath:s0.join(Y,"plugin-lock"),transactionPath:s0.join(Y,"plugin-transaction.json")}}let W=s0.join(Z,"plugins"),X=s0.join(W,"runtime");return{scope:w,root:W,manifestPath:s0.join(W,"plugins.json"),runtimeDir:X,lockPath:s0.join(W,"plugin-lock"),transactionPath:s0.join(W,"plugin-transaction.json")}}import{randomUUID as QH}from"node:crypto";import{constants as zH}from"node:fs";import{access as MH,mkdir as F8,readFile as d7,rename as R$,rm as e,writeFile as p7}from"node:fs/promises";import C$ from"node:path";class W5 extends Error{constructor($){super($ instanceof Error?$.message:String($),$ instanceof Error?{cause:$}:void 0);this.name="FaultInterruption"}}class A0{paths;options;constructor($,w={}){this.paths=$;this.options=w}async run($){let w=!1,Z;try{await this.acquireLock(),w=!0,await this.recoverLocked();let W=QH(),X=C$.join(this.paths.root,`.transaction-${W}-stage`);Z={version:1,id:W,phase:"prepared",stageDirectory:X,backupManifestPath:C$.join(this.paths.root,`.transaction-${W}-plugins.json.bak`),backupRuntimeDir:C$.join(this.paths.root,`.transaction-${W}-runtime.bak`),hadManifest:await aw(this.paths.manifestPath),hadRuntime:await aw(this.paths.runtimeDir)},await F8(X,{recursive:!0});let Y={manifestPath:C$.join(X,"plugins.json"),runtimeDir:C$.join(X,"runtime")},G=await $(Y);await this.verifyCandidate(Y),await this.writeMarker(Z),await this.backupCurrent(Z);let J={...Z,phase:"backed-up"};await this.writeMarker(J),Z=J,this.fault("after-backup"),await R$(Y.runtimeDir,this.paths.runtimeDir);let Q={...Z,phase:"runtime-committed"};await this.writeMarker(Q),Z=Q,this.fault("after-runtime-commit"),await R$(Y.manifestPath,this.paths.manifestPath);let z={...Z,phase:"manifest-committed"};return await this.writeMarker(z),Z=z,this.fault("after-manifest-commit"),await this.cleanupCommitted(Z),G}catch(W){if(W instanceof W5)throw W.cause??W;throw await this.rollbackAfterError(Z),W}finally{if(w)await this.releaseLock()}}async recover(){let $=!1;try{await this.acquireLock(),$=!0,await this.recoverLocked()}finally{if($)await this.releaseLock()}}async acquireLock(){await F8(this.paths.root,{recursive:!0});for(let $=0;$<2;$++){try{await F8(this.paths.lockPath)}catch(w){if(!Z5(w,"EEXIST"))throw w;let Z=await this.readLockOwner();if(!Z||this.isProcessAlive(Z.pid))throw new j("plugin","plugin.install_busy",`plugin.install_busy: ${this.paths.scope} plugin installation is already running`,!0,{scope:this.paths.scope});if($===1)throw new j("plugin","plugin.install_busy",`plugin.install_busy: could not acquire ${this.paths.scope} plugin lock`,!0,{scope:this.paths.scope});await e(this.paths.lockPath,{recursive:!0,force:!0});continue}try{await p7(C$.join(this.paths.lockPath,"owner.json"),`${JSON.stringify({pid:process.pid,createdAt:this.now()})}
|
|
45
|
+
`,{mode:384});return}catch(w){throw await e(this.paths.lockPath,{recursive:!0,force:!0}),w}}}async readLockOwner(){try{let $=JSON.parse(await d7(C$.join(this.paths.lockPath,"owner.json"),"utf8"));if(typeof $.pid==="number"&&Number.isInteger($.pid)&&$.pid>0)return{pid:$.pid,createdAt:typeof $.createdAt==="number"?$.createdAt:0};return}catch{return}}async releaseLock(){await e(this.paths.lockPath,{recursive:!0,force:!0})}async verifyCandidate($){if(!await aw($.manifestPath)||!await aw($.runtimeDir))throw new j("plugin","plugin.transaction_recovery_failed","plugin.transaction_recovery_failed: candidate manifest and runtime are required",!1,{scope:this.paths.scope})}async backupCurrent($){if(await e($.backupManifestPath,{force:!0}),await e($.backupRuntimeDir,{recursive:!0,force:!0}),$.hadManifest)await R$(this.paths.manifestPath,$.backupManifestPath);if($.hadRuntime)await R$(this.paths.runtimeDir,$.backupRuntimeDir)}async rollbackAfterError($){if(!$)return;try{if($.phase==="manifest-committed"){await this.cleanupCommitted($);return}await this.restoreBackupPairBestEffort($),await this.cleanupRecoveryArtifacts($)}catch(w){throw new j("plugin","plugin.transaction_recovery_failed",`plugin.transaction_recovery_failed: could not roll back ${this.paths.scope} plugin transaction`,!1,{scope:this.paths.scope},w instanceof Error?{cause:w}:void 0)}}async recoverLocked(){let $=await this.readMarker();if(!$)return;try{if($.phase==="prepared"){await e($.stageDirectory,{recursive:!0,force:!0}),await e(this.paths.transactionPath,{force:!0});return}if($.phase==="backed-up"||$.phase==="runtime-committed"){await this.removeCurrentTargets(),await this.restoreBackups($),await this.cleanupRecoveryArtifacts($);return}await e($.backupManifestPath,{force:!0}),await e($.backupRuntimeDir,{recursive:!0,force:!0}),await this.cleanupRecoveryArtifacts($)}catch(w){throw new j("plugin","plugin.transaction_recovery_failed",`plugin.transaction_recovery_failed: could not recover ${this.paths.scope} plugin transaction`,!1,{scope:this.paths.scope},w instanceof Error?{cause:w}:void 0)}}async readMarker(){try{let $=JSON.parse(await d7(this.paths.transactionPath,"utf8"));if(!TH($))throw Error("invalid transaction marker");return $}catch($){if(Z5($,"ENOENT"))return;throw new j("plugin","plugin.transaction_recovery_failed",`plugin.transaction_recovery_failed: invalid ${this.paths.scope} plugin transaction marker`,!1,{scope:this.paths.scope},$ instanceof Error?{cause:$}:void 0)}}async writeMarker($){await F8(C$.dirname(this.paths.transactionPath),{recursive:!0});let w=`${this.paths.transactionPath}.tmp`;await p7(w,`${JSON.stringify($,null,2)}
|
|
46
|
+
`,{mode:384}),await R$(w,this.paths.transactionPath)}async cleanupCommitted($){await e($.backupManifestPath,{force:!0}),await e($.backupRuntimeDir,{recursive:!0,force:!0}),await e($.stageDirectory,{recursive:!0,force:!0}),await e(this.paths.transactionPath,{force:!0}),await e(`${this.paths.transactionPath}.tmp`,{recursive:!0,force:!0})}async cleanupRecoveryArtifacts($){await e($.stageDirectory,{recursive:!0,force:!0}),await e(this.paths.transactionPath,{force:!0}),await e(`${this.paths.transactionPath}.tmp`,{recursive:!0,force:!0})}async removeCurrentTargets(){await e(this.paths.manifestPath,{force:!0}),await e(this.paths.runtimeDir,{recursive:!0,force:!0})}async restoreBackups($){if($.hadManifest)await R$($.backupManifestPath,this.paths.manifestPath);if($.hadRuntime)await R$($.backupRuntimeDir,this.paths.runtimeDir)}async restoreBackupPairBestEffort($){await this.restoreSingleBackup({hadTarget:$.hadManifest,backupPath:$.backupManifestPath,targetPath:this.paths.manifestPath,directory:!1}),await this.restoreSingleBackup({hadTarget:$.hadRuntime,backupPath:$.backupRuntimeDir,targetPath:this.paths.runtimeDir,directory:!0})}async restoreSingleBackup($){if(await aw($.backupPath)){await e($.targetPath,{recursive:$.directory,force:!0}),await R$($.backupPath,$.targetPath);return}if(!$.hadTarget)await e($.targetPath,{recursive:$.directory,force:!0})}fault($){try{this.options.fault?.($)}catch(w){throw new W5(w)}}now(){return this.options.now?.()??Date.now()}isProcessAlive($){if(this.options.isProcessAlive)return this.options.isProcessAlive($);try{return process.kill($,0),!0}catch(w){return!Z5(w,"ESRCH")}}}function TH($){return $.version===1&&typeof $.id==="string"&&["prepared","backed-up","runtime-committed","manifest-committed"].includes(String($.phase))&&typeof $.stageDirectory==="string"&&typeof $.backupManifestPath==="string"&&typeof $.backupRuntimeDir==="string"&&typeof $.hadManifest==="boolean"&&typeof $.hadRuntime==="boolean"}async function aw($){try{return await MH($,zH.F_OK),!0}catch{return!1}}function Z5($,w){return typeof $==="object"&&$!==null&&"code"in $&&$.code===w}class G5{workspace;dataDir;packageManager;loader;builtins;constructor($,w,Z,W,X){this.workspace=$;this.dataDir=w;this.packageManager=Z;this.loader=W;this.builtins=X}async install($,w){let Z=x7($),W=this.paths(w.scope);await new A0(W).recover();let X=await Q$(W.manifestPath);if(X.plugins[Z.packageName]?.requested===Z.requested){let Q=await this.loader.loadScope(W),z=Q.loaded.find((M)=>M.packageName===Z.packageName);if(Q.failed.length===0&&z)return X5(z,Z.requested,w.scope)}let Y=n7(X);Y.plugins[Z.packageName]={source:"npm",requested:Z.requested};let G=[];await new A0(W).run(async(Q)=>{G=await this.buildCandidate(Q,Y,W,w,!1),await this.validateCandidate(W.scope,G)});let J=G.find((Q)=>Q.packageName===Z.packageName);if(!J)throw Y5([{packageName:Z.packageName,path:W.runtimeDir,message:"plugin did not load"}]);return X5(J,Z.requested,w.scope)}async remove($,w){if(!w1($))throw UH($);let Z=this.paths(w.scope);await new A0(Z).recover();let W=await Q$(Z.manifestPath);if(!W.plugins[$])throw new j("plugin","plugin.install_failed",`plugin.install_failed: ${$} is not installed in ${w.scope} scope`);let X=n7(W);delete X.plugins[$],await new A0(Z).run(async(Y)=>{let G=await this.buildCandidate(Y,X,Z,w,!1);await this.validateCandidate(Z.scope,G)})}async sync($){let w=this.paths($.scope);await new A0(w).recover();let Z=await Q$(w.manifestPath);if($.scope==="project"&&Object.keys(Z.plugins).length>0&&!await t7(j$.join(w.runtimeDir,"bun.lock")))throw new j("plugin","plugin.lock_missing",`plugin.lock_missing: ${$.scope} plugin sync requires ${j$.join(w.runtimeDir,"bun.lock")}`);let W=[];return await new A0(w).run(async(X)=>{W=await this.buildCandidate(X,Z,w,$,!0),await this.validateCandidate(w.scope,W)}),W.map((X)=>X5(X,Z.plugins[X.packageName]?.requested??"latest",$.scope))}async list(){let[$,w]=await Promise.all([this.listScope(this.paths("project")),this.listScope(this.paths("global"))]),Z=new Set($.map((W)=>W.packageName));return{project:$,global:w.map((W)=>({...W,shadowedByProject:Z.has(W.packageName)}))}}paths($){return sw(this.workspace,$,this.dataDir)}async buildCandidate($,w,Z,W,X){if(await VH($.runtimeDir,{recursive:!0}),await O8($.manifestPath,rZ(w),"utf8"),await O8(j$.join($.runtimeDir,"package.json"),`${JSON.stringify(_7(w),null,2)}
|
|
47
|
+
`,"utf8"),await t7(j$.join(Z.runtimeDir,"bun.lock")))await BH(j$.join(Z.runtimeDir,"bun.lock"),j$.join($.runtimeDir,"bun.lock"));try{await this.packageManager.install({cwd:$.runtimeDir,frozenLockfile:X,allowScripts:W.allowScripts,...W.signal?{signal:W.signal}:{}})}catch(G){throw HH(G,X)}await PH($.runtimeDir,w),await qH($.runtimeDir,Z.scope);let Y=await this.loader.loadScope({...Z,manifestPath:$.manifestPath,runtimeDir:$.runtimeDir});if(Y.failed.length>0)throw Y5(Y.failed);return Y.loaded}async validateCandidate($,w){if($==="global"){$5(this.builtins,w,[]);return}let Z=this.paths("global");await new A0(Z).recover();let W=await this.loadScopeOrThrow(Z);$5(this.builtins,W,w)}async loadScopeOrThrow($){let w=await this.loader.loadScope($);if(w.failed.length>0)throw Y5(w.failed);return w.loaded}async listScope($){await new A0($).recover();let w=await Q$($.manifestPath),Z=[];for(let W of Object.keys(w.plugins).sort()){let X=await i1($.runtimeDir,W);Z.push({packageName:W,requested:w.plugins[W]?.requested??"latest",version:X.version,tools:[],scope:$.scope,shadowedByProject:!1})}return Z}}async function PH($,w){if(Object.keys(w.plugins).length>0)return;await O8(j$.join($,"bun.lock"),"","utf8")}async function qH($,w){if(w!=="project")return;await O8(j$.join($,".gitignore"),`*
|
|
48
48
|
!.gitignore
|
|
49
49
|
!bun.lock
|
|
50
|
-
`,"utf8")}function
|
|
51
|
-
${$ instanceof j?$.code:""}`;return/frozen-lockfile|lockfile.*out.?of.?date|lockfile.*would.*change|lockfile had changes/i.test(w)}async function
|
|
50
|
+
`,"utf8")}function X5($,w,Z){return{packageName:$.packageName,requested:w,version:$.version,tools:$.tools.map((W)=>W.name).sort(),scope:Z}}function n7($){return JSON.parse(rZ($))}function Y5($){let w=$.map((Z)=>`${Z.packageName}: ${Z.message} (${Z.path})`).join("; ");return new j("plugin","plugin.sync_failed",`plugin.sync_failed: ${w}`)}function UH($){return new j("plugin","plugin.specifier_invalid",`plugin.specifier_invalid: ${$}`)}function HH($,w){if(w&&FH($))return new j("plugin","plugin.lock_outdated","plugin.lock_outdated: committed plugin lockfile is out of date",!1,void 0,$ instanceof Error?{cause:$}:void 0);return $}function FH($){if(!($ instanceof Error))return!1;let w=`${$.message}
|
|
51
|
+
${$ instanceof j?$.code:""}`;return/frozen-lockfile|lockfile.*out.?of.?date|lockfile.*would.*change|lockfile had changes/i.test(w)}async function t7($){try{return await KH($,NH.F_OK),!0}catch{return!1}}var E8={name:"bash",description:"Run a bash command in the workspace with timeout and bounded output.",risk:"modify",inputSchema:{type:"object",additionalProperties:!1,required:["command"],properties:{command:{type:"string",minLength:1},timeout:{type:"integer",minimum:100,maximum:60000,default:30000},maxOutput:{type:"integer",minimum:1000,maximum:1e5,default:30000}}},async execute($,w){let{command:Z,timeout:W=30000,maxOutput:X=30000}=$,Y=await y4("bash",["-lc",Z],{cwd:w.workspace,env:process.env,signal:w.signal,timeoutMs:W,maxOutputChars:X}),G=[Y.stdout&&`stdout:
|
|
52
52
|
${Y.stdout}`,Y.stderr&&`stderr:
|
|
53
53
|
${Y.stderr}`].filter(Boolean).join(`
|
|
54
54
|
`);if(Y.exitCode===null&&!Y.timedOut&&!Y.cancelled&&Y.signal===null)return{content:`bash.spawn_error: ${Y.stderr||"unknown error"}`,isError:!0};let J=Y.timedOut?`Timed out after ${W}ms`:Y.cancelled?"Cancelled":`Exit code: ${Y.exitCode??"null"}${Y.signal?` (signal ${Y.signal})`:""}`;return{content:R1(`${J}
|
|
55
|
-
${G}`.trimEnd(),X),isError:Y.timedOut||Y.cancelled||Y.exitCode!==0,metadata:{exitCode:Y.exitCode,signal:Y.signal,timedOut:Y.timedOut,cancelled:Y.cancelled}}}};import{constants as
|
|
56
|
-
... [${this.omitted} selected characters omitted]`:this.text}}var k8={name:"read",description:"Read a UTF-8 text file by 1-based line offset and limit.",risk:"read",inputSchema:{type:"object",additionalProperties:!1,required:["path"],properties:{path:{type:"string"},offset:{type:"integer",minimum:1,default:1},limit:{type:"integer",minimum:1,maximum:2000,default:500}}},async execute($,w){let{path:Z,offset:W=1,limit:X=500}=$,Y=await
|
|
57
|
-
`);Q++,z=!0}G.add(P)},
|
|
55
|
+
${G}`.trimEnd(),X),isError:Y.timedOut||Y.cancelled||Y.exitCode!==0,metadata:{exitCode:Y.exitCode,signal:Y.signal,timedOut:Y.timedOut,cancelled:Y.cancelled}}}};import{constants as $J}from"node:fs";import{open as DH}from"node:fs/promises";import{constants as r7}from"node:fs";import{lstat as s7,open as OH,readlink as a7,realpath as L8}from"node:fs/promises";import k0 from"node:path";function D8($,w){let Z=k0.relative(w,$);return Z===""||!Z.startsWith("..")&&!k0.isAbsolute(Z)}async function o7($,w,Z=1e6){let W=await a0($,w),X=await OH(W,r7.O_RDONLY|r7.O_NOFOLLOW);try{if((await X.stat()).size>Z)throw new j("context","workspace.instructions_too_large",`${w} exceeds the ${Z}-byte instruction limit`);return await X.readFile("utf8")}finally{await X.close()}}async function a0($,w){let Z=await L8($),W=k0.resolve(Z,w);if(!D8(W,Z))throw new j("permission","workspace.outside",`Path is outside workspace: ${w}`);try{let X=await L8(W);if(!D8(X,Z))throw new j("permission","workspace.symlink_escape",`Path escapes workspace through a symlink: ${w}`);return X}catch(X){if(X instanceof j)throw X;try{if((await s7(W)).isSymbolicLink()){let G=k0.resolve(k0.dirname(W),await a7(W));await e7(G,Z,w,"dangling symlink")}}catch(Y){if(Y instanceof j)throw Y}return await EH(W,Z,w),W}}async function e7($,w,Z,W){let X=await LH($);if(!X||!D8(X,w))throw new j("permission","workspace.symlink_escape",`Path escapes workspace through a ${W}: ${Z}`)}async function EH($,w,Z){let W=k0.dirname($);while(W!==k0.dirname(W)){let X;try{X=await s7(W)}catch{W=k0.dirname(W);continue}if(!X){W=k0.dirname(W);continue}if(X.isSymbolicLink()){let Y=k0.resolve(k0.dirname(W),await a7(W));await e7(Y,w,Z,"symlink")}else{let Y;try{Y=await L8(W)}catch{W=k0.dirname(W);continue}if(!Y)continue;if(D8(Y,w))return;throw new j("permission","workspace.symlink_escape",`Parent escapes workspace: ${Z}`)}W=k0.dirname(W)}}async function LH($){let w=$;while(!0)try{return await L8(w)}catch{let Z=k0.dirname(w);if(Z===w)return;w=Z}}var f8={name:"edit",description:"Replace one uniquely matching exact text block in a UTF-8 file.",risk:"modify",inputSchema:{type:"object",additionalProperties:!1,required:["path","oldText","newText"],properties:{path:{type:"string"},oldText:{type:"string",minLength:1},newText:{type:"string"}}},async execute($,w){let{path:Z,oldText:W,newText:X}=$,Y=await a0(w.workspace,Z),G=await DH(Y,$J.O_RDWR|$J.O_NOFOLLOW);try{let J=await G.readFile("utf8"),Q=J.indexOf(W);if(Q<0)return{content:"edit.no_match: oldText was not found",isError:!0};if(J.indexOf(W,Q+1)>=0)return{content:"edit.multiple_matches: oldText is not unique",isError:!0};let z=`${J.slice(0,Q)}${X}${J.slice(Q+W.length)}`;await G.truncate(0),await G.write(z,0,"utf8")}finally{await G.close()}return{content:`Edited ${Z}`}}};import{constants as wJ}from"node:fs";import{open as fH}from"node:fs/promises";class ZJ{limit;text="";omitted=0;constructor($){this.limit=$}add($){let w=Math.max(0,this.limit-this.text.length);this.text+=$.slice(0,w),this.omitted+=Math.max(0,$.length-w)}value(){return this.omitted>0?`${this.text}
|
|
56
|
+
... [${this.omitted} selected characters omitted]`:this.text}}var k8={name:"read",description:"Read a UTF-8 text file by 1-based line offset and limit.",risk:"read",inputSchema:{type:"object",additionalProperties:!1,required:["path"],properties:{path:{type:"string"},offset:{type:"integer",minimum:1,default:1},limit:{type:"integer",minimum:1,maximum:2000,default:500}}},async execute($,w){let{path:Z,offset:W=1,limit:X=500}=$,Y=await a0(w.workspace,Z),G=new ZJ(50000),J=1,Q=0,z=!1,M=()=>J>=W&&J<W+X,T=(P)=>{if(!M())return;if(!z){if(Q>0)G.add(`
|
|
57
|
+
`);Q++,z=!0}G.add(P)},N=await fH(Y,wJ.O_RDONLY|wJ.O_NOFOLLOW);try{let P=N.createReadStream({encoding:"utf8",autoClose:!1,highWaterMark:65536,signal:w.signal});for await(let q of P){let U=String(q),O=0;for(let f=U.indexOf(`
|
|
58
58
|
`,O);f>=0;f=U.indexOf(`
|
|
59
|
-
`,O))T(U.slice(O,f)),J++,z=!1,O=f+1;T(U.slice(O))}}finally{await
|
|
60
|
-
... [${B} lines omitted]`:""),metadata:{totalLines:
|
|
61
|
-
`,{encoding:"utf8",mode:384})}async read(){try{let $=JSON.parse(await
|
|
62
|
-
${
|
|
63
|
-
${
|
|
64
|
-
`).slice(0,6000)}function
|
|
65
|
-
${W.text.trim()}`}catch(W){await this.events.emit("context.compaction_failed",{message:W instanceof Error?W.message:String(W),fallback:"deterministic"},Z);return}}async requestWithRetry($,w,Z){let W=$,X=!1;for(let Y=0;;Y++)try{await this.events.emit("provider.started",{attempt:Y},w);let G=await
|
|
66
|
-
`),this.status(`done: ${String($.data?.tools)} tools, ${String($.data?.durationMs)}ms, ${String($.data?.inputTokens)}/${String($.data?.outputTokens)} tokens`);if($.type==="turn.failed")this.status(I$.default.red(`failed: ${String($.data?.message)}`));if($.type==="plugin.loaded"&&this.options.verbose)this.status(`plugin loaded: ${I8($)}`);if($.type==="plugin.failed")this.status(I$.default.red(`plugin failed: ${I8($)}${
|
|
59
|
+
`,O))T(U.slice(O,f)),J++,z=!1,O=f+1;T(U.slice(O))}}finally{await N.close()}T("");let K=J,B=Math.max(0,K-(W-1+Q));return{content:G.value()+(B>0?`
|
|
60
|
+
... [${B} lines omitted]`:""),metadata:{totalLines:K,offset:W,limit:X}}}};import{constants as A8}from"node:fs";import{mkdir as kH,open as AH}from"node:fs/promises";import SH from"node:path";var S8={name:"write",description:"Create or overwrite a UTF-8 file inside the workspace.",risk:"modify",inputSchema:{type:"object",additionalProperties:!1,required:["path","content"],properties:{path:{type:"string"},content:{type:"string"}}},async execute($,w){let{path:Z,content:W}=$,X=await a0(w.workspace,Z);await kH(SH.dirname(X),{recursive:!0}),X=await a0(w.workspace,Z);let Y=await AH(X,A8.O_WRONLY|A8.O_CREAT|A8.O_TRUNC|A8.O_NOFOLLOW,384);try{await Y.writeFile(W,"utf8")}finally{await Y.close()}return{content:`Wrote ${Buffer.byteLength(W)} bytes to ${Z}`}}};function WJ(){return[k8,S8,f8,E8]}var XJ="0.1.2";import y6 from"node:path";import{stdin as ZE,stdout as n0}from"node:process";import{createInterface as WE}from"node:readline/promises";var YJ=R4(d6(),1),{program:Ok,createCommand:Ek,createArgument:Lk,createOption:Dk,CommanderError:fk,InvalidArgumentError:J5,InvalidOptionArgumentError:kk,Command:Ak,Argument:Sk,Option:Rk,Help:Ck}=YJ.default;import{mkdir as RH,readFile as CH,realpath as GJ,writeFile as jH}from"node:fs/promises";import IH from"node:path";class Q5{file;constructor($){this.file=$}async isTrusted($){return(await this.read()).includes($)}async isWorkspaceTrusted($){return this.isTrusted(await GJ($))}async trustWorkspace($){return this.trust(await GJ($))}async trust($){let w=await this.read();if(!w.includes($))w.push($);await RH(IH.dirname(this.file),{recursive:!0}),await jH(this.file,`${JSON.stringify(w,null,2)}
|
|
61
|
+
`,{encoding:"utf8",mode:384})}async read(){try{let $=JSON.parse(await CH(this.file,"utf8"));return Array.isArray($)?$.filter((w)=>typeof w==="string"):[]}catch($){if($.code==="ENOENT")return[];throw $}}}class zJ{estimateText($){return Math.ceil($.length/3.5)}estimateMessages($){return $.reduce((w,Z)=>w+6+this.estimateText(JSON.stringify(Z)),0)}estimateTools($){return this.estimateText(JSON.stringify($.map(({execute:w,...Z})=>Z)))}}class z5{budget;threshold;estimator=new zJ;summary;compactionRange;compactedThrough=0;constructor($,w=0.8){this.budget=$;this.threshold=w}inputBudget(){return this.budget.contextWindow-this.budget.reservedOutputTokens-this.budget.safetyMargin}prepare($,w){let Z=$[0]??{role:"system",content:"You are CodeN."},W=JJ($.slice(1)),X=this.estimator.estimateTools(w),Y=this.inputBudget(),G=this.summary?W.filter((T)=>T.end>this.compactedThrough):[...W],J=Math.min(3,G.length),Q=this.project(Z,G),z=this.estimator.estimateMessages(Q)+X,M=!1;if(z>Y*this.threshold&&G.length>J){let T=G.slice(0,-J);G=G.slice(-J);let N=[...this.summary?[this.summary]:[],...T.flatMap((K)=>K.messages)];this.compactionRange={start:T[0]?.start??1,end:T.at(-1)?.end??1},this.compactedThrough=this.compactionRange.end,this.summary={role:"system",content:`Compacted conversation summary:
|
|
62
|
+
${QJ(N)}`},Q=this.project(Z,G),z=this.estimator.estimateMessages(Q)+X,M=!0}while(z>Y&&G.length>1)G=G.slice(1),Q=this.project(Z,G),z=this.estimator.estimateMessages(Q)+X,M=!0;return{messages:Q,estimatedTokens:z,compacted:M}}forceCompact($,w){let Z=$[0]??{role:"system",content:"You are CodeN."},W=JJ($.slice(1)),X=this.summary?W.filter((M)=>M.end>this.compactedThrough):W,Y=X.slice(-1),G=X.slice(0,-1),J=[...this.summary?[this.summary]:[],...G.flatMap((M)=>M.messages)];if(G.length)this.compactionRange={start:G[0]?.start??1,end:G.at(-1)?.end??1},this.compactedThrough=this.compactionRange.end;this.summary={role:"system",content:`Emergency compacted summary:
|
|
63
|
+
${QJ(J)}`};let Q=this.project(Z,Y),z=this.estimator.estimateMessages(Q)+this.estimator.estimateTools(w);return{messages:Q,estimatedTokens:z,compacted:!0}}setSummary($,w=0){this.summary={role:"system",content:$},this.compactedThrough=w}getSummary(){return this.summary?.content}getCompactionRange(){return this.compactionRange}clearSummary(){this.summary=void 0,this.compactionRange=void 0,this.compactedThrough=0}project($,w){return[$,...this.summary?[this.summary]:[],...w.flatMap((Z)=>Z.messages)]}}function JJ($){let w=[],Z;for(let W=0;W<$.length;W++){let X=$[W];if(!X)continue;let Y=W+1;if(X.role==="user"||!Z){if(Z)w.push(Z);Z={messages:[X],start:Y,end:Y}}else Z.messages.push(X),Z.end=Y}if(Z)w.push(Z);return w}function QJ($){return $.map((Z)=>{if(Z.role==="tool")return`Tool ${Z.name} (${Z.isError?"error":"ok"}): ${Z.content.slice(0,300)}`;return`${Z.role}: ${Z.content.slice(0,500)}`}).join(`
|
|
64
|
+
`).slice(0,6000)}function M5($,w,Z,W,X){let Y={model:$,messages:w.messages,tools:Z,maxOutputTokens:W.reservedOutputTokens};if(X)Y.signal=X;return Y}class T5{#$=new Set;on($){return this.#$.add($),()=>this.#$.delete($)}async emit($,w,Z){let W={type:$,timestamp:new Date().toISOString()};if(Z!==void 0)W.turnId=Z;if(w!==void 0)W.data=w;return await Promise.all([...this.#$].map((X)=>X(W))),W}}import{randomUUID as yH}from"node:crypto";class N5{provider;registry;executor;context;sessions;events;options;messages;maxSteps;retries;retryBaseMs;systemPersisted;constructor($,w,Z,W,X,Y,G,J){this.provider=$;this.registry=w;this.executor=Z;this.context=W;this.sessions=X;this.events=Y;this.options=G;this.maxSteps=G.maxSteps??20,this.retries=G.retries??3,this.retryBaseMs=G.retryBaseMs??250,this.systemPersisted=Boolean(J?.length),this.messages=J?.length?[...J]:[{role:"system",content:G.systemPrompt??"You are CodeN, a concise coding agent. Inspect before editing, use tools carefully, and verify changes."}]}async reset(){let $=this.messages.find((w)=>w.role==="system")??{role:"system",content:"You are CodeN."};await this.sessions.append("session.reset",{}),this.messages.splice(0,this.messages.length,$),this.context.clearSummary(),this.systemPersisted=!1}async compact(){let $=this.context.forceCompact(this.messages,this.registry.list()),w=this.context.getSummary();if(w)await this.sessions.appendCompaction(w,this.context.getCompactionRange());await this.events.emit("context.compacted",{manual:!0,estimatedTokens:$.estimatedTokens})}async run($,w=new AbortController().signal){let Z=yH(),W=Date.now(),X=0,Y={inputTokens:0,outputTokens:0};await this.events.emit("turn.started",{input:$},Z);try{if(!this.systemPersisted){let Q=this.messages[0];if(Q?.role==="system")await this.sessions.appendMessage(Q);this.systemPersisted=!0}let G=this.messages.some((Q)=>Q.role==="user"),J={role:"user",content:$};if(this.messages.push(J),await this.sessions.appendMessage(J),!G)await this.sessions.setTitle($);for(let Q=0;Q<this.maxSteps;Q++){let z=this.context.prepare(this.messages,this.registry.list());if(z.compacted){let N=this.context.getSummary();if(N){let K=await this.refineSummary(N,w,Z);if(K){let B=N;N=K,this.context.setSummary(K,this.context.getCompactionRange()?.end??0),z.messages=z.messages.map((P)=>P.role==="system"&&P.content===B?{role:"system",content:K}:P)}await this.sessions.appendCompaction(N,this.context.getCompactionRange())}await this.events.emit("context.compacted",{estimatedTokens:z.estimatedTokens},Z)}await this.events.emit("context.prepared",{estimatedTokens:z.estimatedTokens,budget:this.context.inputBudget()},Z);let M=await this.requestWithRetry(M5(this.options.model,z,this.registry.list(),this.context.budget,w),Z,async()=>{z=this.context.forceCompact(this.messages,this.registry.list());let N=this.context.getSummary();if(N)await this.sessions.appendCompaction(N,this.context.getCompactionRange());return M5(this.options.model,z,this.registry.list(),this.context.budget,w)});Y.inputTokens+=M.usage.inputTokens,Y.outputTokens+=M.usage.outputTokens;let T={role:"assistant",content:M.text,toolCalls:M.toolCalls,model:this.options.model,usage:M.usage};if(this.messages.push(T),await this.sessions.appendMessage(T),T.toolCalls.length===0)return await this.events.emit("turn.completed",{tools:X,durationMs:Date.now()-W,inputTokens:Y.inputTokens,outputTokens:Y.outputTokens,contextTokens:z.estimatedTokens},Z),{answer:T.content,messages:this.messages,toolsExecuted:X,usage:Y};for(let N of T.toolCalls){let K=await this.executor.execute(N,w,Z);X++;let B={role:"tool",callId:N.callId,name:N.name,content:K.content,isError:K.isError??!1};this.messages.push(B),await this.sessions.appendMessage(B)}}throw new j("runtime","runtime.step_limit",`Maximum model steps (${this.maxSteps}) reached`)}catch(G){throw await this.events.emit("turn.failed",{code:G instanceof j?G.code:"runtime.unknown",message:G instanceof Error?G.message:String(G)},Z),G}}async refineSummary($,w,Z){try{await this.events.emit("context.compaction_started",{model:this.options.model},Z);let W=await MJ(this.provider.stream({model:this.options.model,messages:[{role:"system",content:"Rewrite the supplied coding-session summary concisely. Preserve goals, constraints, decisions, changed files, tool/test results, unresolved errors, and next steps. Return only the summary."},{role:"user",content:$}],tools:[],maxOutputTokens:Math.min(2048,this.context.budget.reservedOutputTokens),signal:w}));if(W.toolCalls.length>0||!W.text.trim())return;return`Compacted conversation summary:
|
|
65
|
+
${W.text.trim()}`}catch(W){await this.events.emit("context.compaction_failed",{message:W instanceof Error?W.message:String(W),fallback:"deterministic"},Z);return}}async requestWithRetry($,w,Z){let W=$,X=!1;for(let Y=0;;Y++)try{await this.events.emit("provider.started",{attempt:Y},w);let G=await MJ(this.provider.stream(W),async(J)=>{await this.events.emit("provider.delta",{text:J},w)},async(J)=>{await this.events.emit("provider.reasoning_delta",{text:J},w)});return await this.events.emit("provider.completed",{usage:G.usage},w),G}catch(G){if(W.signal?.aborted)throw G;if(_H(G)){if(!X){X=!0,W=await Z(),await this.events.emit("context.compacted",{emergency:!0},w);continue}throw new j("context","context.exhausted","Context is still over the provider limit after emergency compaction",!1,void 0,{cause:G})}if(Y>=this.retries||!bH(G))throw G;await this.events.emit("provider.retry",{attempt:Y+1,message:G instanceof Error?G.message:String(G)},w);let J=xH(G),Q=this.retryBaseMs*2**Y*(0.8+Math.random()*0.4);await gH(J??Math.min(30000,Q),W.signal)}}}async function MJ($,w,Z){let W="",X={inputTokens:0,outputTokens:0},Y=new Map;for await(let J of $)if(J.type==="reasoning_delta")await Z?.(J.text);else if(J.type==="text_delta")W+=J.text,await w?.(J.text);else if(J.type==="tool_call_start")Y.set(J.index,{callId:J.callId,name:J.name,json:"",ended:!1});else if(J.type==="tool_call_delta"){let Q=Y.get(J.index);if(!Q)throw new j("provider","provider.invalid_stream","Tool arguments arrived before tool start");Q.json+=J.argumentsDelta}else if(J.type==="tool_call_end"){let Q=Y.get(J.index);if(Q)Q.ended=!0}else if(J.type==="usage")X={inputTokens:Math.max(X.inputTokens,J.usage.inputTokens),outputTokens:Math.max(X.outputTokens,J.usage.outputTokens)};let G=[...Y.entries()].sort(([J],[Q])=>J-Q).map(([,J])=>{if(!J.ended)throw new j("provider","provider.incomplete_tool_call",`Incomplete tool call: ${J.name}`);try{return{callId:J.callId,name:J.name,input:JSON.parse(J.json||"{}")}}catch(Q){throw new j("provider","provider.invalid_tool_json",`Invalid JSON for tool ${J.name}`,!1,void 0,{cause:Q})}});return{text:W,toolCalls:G,usage:X}}function bH($){if($ instanceof j)return $.retryable;let w=$?.status;return typeof w!=="number"||w===429||w>=500}function xH($){let Z=$?.headers?.get?.("retry-after");if(!Z)return;let W=Number(Z);if(Number.isFinite(W))return Math.max(0,W*1000);let X=Date.parse(Z);return Number.isNaN(X)?void 0:Math.max(0,X-Date.now())}function _H($){let w=$?.status,Z=$ instanceof Error?$.message:String($);return w===413||/context.{0,20}(?:length|window|limit|too long)/i.test(Z)}function gH($,w){return new Promise((Z,W)=>{if(w?.aborted){W(w.reason);return}let X=setTimeout(Z,$);w?.addEventListener("abort",()=>{clearTimeout(X),W(w.reason)},{once:!0})})}var I$=R4(KJ(),1);import*as y$ from"node:readline";var j8=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"];class V5{options;stdout;stderr;tty;spinner;frame=0;providerStartedAt;reasoningText="";contentStarted=!1;pendingText="";constructor($,w={}){this.options=w;this.stdout=w.stdout??process.stdout,this.stderr=w.stderr??process.stderr,this.tty=w.tty??Boolean(process.stderr.isTTY&&!process.env.NO_COLOR&&!process.env.CI),$.on((Z)=>this.render(Z))}render($){if($.type==="provider.started")this.startProviderAttempt();if($.type==="provider.reasoning_delta"){let w=String($.data?.text??"");if(this.tty&&this.providerStartedAt!==void 0&&!this.contentStarted&&w)this.reasoningText+=w,this.renderThinkingLine()}if($.type==="provider.delta"){let w=String($.data?.text??"");if(w&&!this.contentStarted)this.finishThinking();if(this.tty)this.stdout.write(w);else this.pendingText+=w}if($.type==="provider.completed"){if(!this.tty&&this.pendingText)this.stdout.write(this.pendingText),this.pendingText="";this.endProviderAttempt()}if($.type==="provider.retry"||$.type==="turn.failed")this.endProviderAttempt(),this.pendingText="";if($.type==="tool.started")this.endProviderAttempt(),this.status(`tool ${String($.data?.name)} started`);if($.type==="tool.completed")this.status(`tool ${String($.data?.name)} ${$.data?.isError?"failed":"completed"} (${String($.data?.durationMs)}ms)`);if($.type==="provider.retry"&&this.options.verbose)this.status(`provider retry ${String($.data?.attempt)}`);if($.type==="turn.completed")this.endProviderAttempt(),this.stdout.write(`
|
|
66
|
+
`),this.status(`done: ${String($.data?.tools)} tools, ${String($.data?.durationMs)}ms, ${String($.data?.inputTokens)}/${String($.data?.outputTokens)} tokens`);if($.type==="turn.failed")this.status(I$.default.red(`failed: ${String($.data?.message)}`));if($.type==="plugin.loaded"&&this.options.verbose)this.status(`plugin loaded: ${I8($)}`);if($.type==="plugin.failed")this.status(I$.default.red(`plugin failed: ${I8($)}${B5($)}`));if($.type==="plugin.unavailable")this.status(I$.default.yellow(`plugin unavailable: ${I8($)}${B5($)}`));if($.type==="plugin.restart_required")this.status(I$.default.yellow(`plugin restart required: ${I8($)}${B5($)}`))}status($){this.stderr.write(this.tty?`${I$.default.dim($)}
|
|
67
67
|
`:`[coden] ${$}
|
|
68
68
|
`)}startProviderAttempt(){this.endProviderAttempt(),this.providerStartedAt=Date.now(),this.startSpinner()}endProviderAttempt(){this.stopSpinner(),this.providerStartedAt=void 0,this.reasoningText="",this.contentStarted=!1}finishThinking(){let $=this.providerStartedAt,w=Boolean(this.normalizedReasoning());if(this.stopSpinner(),this.contentStarted=!0,this.tty&&$!==void 0&&w){let Z=((Date.now()-$)/1000).toFixed(1);this.stderr.write(`${I$.default.dim(`thought for ${Z}s`)}
|
|
69
|
-
`)}}normalizedReasoning(){return this.reasoningText.replace(/\s+/g," ").trim()}renderThinkingLine(){let $=this.normalizedReasoning();if(!$)return;let w=this.stderr.columns??80,Z=j8[this.frame++%j8.length]??"",W=this.truncateTail($,Math.max(0,w-2));y$.clearLine(this.stderr,0),y$.cursorTo(this.stderr,0),this.stderr.write(I$.default.dim(`${Z} ${W}`))}truncateTail($,w){if(w<=0)return"";let Z=Array.from($),W=(J)=>(J.codePointAt(0)??0)<=255?1:2;if(Z.reduce((J,Q)=>J+W(Q),0)<=w)return $;let Y=[],G=1;for(let J=Z.length-1;J>=0;J--){let Q=Z[J];if(Q===void 0||G+W(Q)>w)break;Y.unshift(Q),G+=W(Q)}return`…${Y.join("")}`}startSpinner(){if(!this.tty||this.spinner){if(!this.tty&&this.options.verbose)this.status("requesting model");return}this.spinner=setInterval(()=>{if(this.normalizedReasoning()){this.renderThinkingLine();return}y$.clearLine(this.stderr,0),y$.cursorTo(this.stderr,0);let $=j8[this.frame++%j8.length]??"";this.stderr.write(`${$} thinking`)},80)}stopSpinner(){if(!this.spinner)return;clearInterval(this.spinner),this.spinner=void 0,y$.clearLine(this.stderr,0),y$.cursorTo(this.stderr,0)}dispose(){this.endProviderAttempt()}}function I8($){let w=$.data??{},Z=X1(w.scope),W=X1(w.packageName),X=X1(w.version??w.diskVersion),Y=X1(w.name),G=X1(w.path),J=X1(w.source);if(W)return`${Z?`${Z} `:""}${W}${X?`@${X}`:""}`;if(Y)return Y;if(G)return`${Z?`${Z} `:""}${G}`;if(J)return J;return"plugin"}function
|
|
70
|
-
`,{encoding:"utf8",mode:384}),await
|
|
69
|
+
`)}}normalizedReasoning(){return this.reasoningText.replace(/\s+/g," ").trim()}renderThinkingLine(){let $=this.normalizedReasoning();if(!$)return;let w=this.stderr.columns??80,Z=j8[this.frame++%j8.length]??"",W=this.truncateTail($,Math.max(0,w-2));y$.clearLine(this.stderr,0),y$.cursorTo(this.stderr,0),this.stderr.write(I$.default.dim(`${Z} ${W}`))}truncateTail($,w){if(w<=0)return"";let Z=Array.from($),W=(J)=>(J.codePointAt(0)??0)<=255?1:2;if(Z.reduce((J,Q)=>J+W(Q),0)<=w)return $;let Y=[],G=1;for(let J=Z.length-1;J>=0;J--){let Q=Z[J];if(Q===void 0||G+W(Q)>w)break;Y.unshift(Q),G+=W(Q)}return`…${Y.join("")}`}startSpinner(){if(!this.tty||this.spinner){if(!this.tty&&this.options.verbose)this.status("requesting model");return}this.spinner=setInterval(()=>{if(this.normalizedReasoning()){this.renderThinkingLine();return}y$.clearLine(this.stderr,0),y$.cursorTo(this.stderr,0);let $=j8[this.frame++%j8.length]??"";this.stderr.write(`${$} thinking`)},80)}stopSpinner(){if(!this.spinner)return;clearInterval(this.spinner),this.spinner=void 0,y$.clearLine(this.stderr,0),y$.cursorTo(this.stderr,0)}dispose(){this.endProviderAttempt()}}function I8($){let w=$.data??{},Z=X1(w.scope),W=X1(w.packageName),X=X1(w.version??w.diskVersion),Y=X1(w.name),G=X1(w.path),J=X1(w.source);if(W)return`${Z?`${Z} `:""}${W}${X?`@${X}`:""}`;if(Y)return Y;if(G)return`${Z?`${Z} `:""}${G}`;if(J)return J;return"plugin"}function B5($){let w=X1($.data?.message??$.data?.reason);return w?` — ${w}`:""}function X1($){return typeof $==="string"&&$.length>0?$:void 0}import{appendFile as iH,chmod as BJ,mkdir as mH}from"node:fs/promises";import lH from"node:path";class P5{file;#$=Promise.resolve();constructor($,w){this.file=$;w.on((Z)=>this.write(Z))}write($){let w=this.#$.then(async()=>{let Z=lH.dirname(this.file);await mH(Z,{recursive:!0,mode:448}),await BJ(Z,448),await iH(this.file,`${JSON.stringify($)}
|
|
70
|
+
`,{encoding:"utf8",mode:384}),await BJ(this.file,384)});return this.#$=w.catch(()=>{}),w}async flush(){await this.#$}}var cH=[/\brm\s+(?:-[^\s]*r[^\s]*\s+|--recursive\b)/i,/\bsudo\b/i,/\bgit\b[^;&|\n]*\breset\s+--hard\b/i,/\bgit\b[^;&|\n]*\bclean\s+(?:-[^\s]*f[^\s]*|--force)\b/i,/\bgit\b[^;&|\n]*\bpush\b[^;&|\n]*(?:--force(?:-with-lease)?|-f)\b/i,/\bgit\b[^;&|\n]*\bcheckout\s+--\s/i,/\bgit\b[^;&|\n]*\brestore\b/i,/\b(?:mkfs|fdisk|dd)\b/i,/\b(?:killall|pkill)\b/i,/(?:curl|wget)[^|;&]*(?:\||&&)\s*(?:sh|bash)\b/i,/(?:^|\s)(?:\/etc|\/usr|\/bin|\/sbin)\//];function dH($){return cH.some((w)=>w.test($))?"dangerous":"modify"}class q5{auto;prompt;#$=new Set;constructor($,w){this.auto=$;this.prompt=w}async authorize($,w,Z){let W=$.risk;if($.name==="bash"&&typeof w.input?.command==="string"){if(dH(w.input.command)==="dangerous")W="dangerous"}if(this.auto||W==="read"||W==="modify"&&this.#$.has($.name))return{allowed:!0,risk:W};if(!this.prompt)return{allowed:!1,risk:W};let X=await this.prompt($,w,W,Z);if(X==="allow_session"&&W!=="dangerous")this.#$.add($.name);return{allowed:X!=="deny",risk:W}}}function I($,w,Z,W,X){if(W==="m")throw TypeError("Private method is not writable");if(W==="a"&&!X)throw TypeError("Private accessor was defined without a setter");if(typeof w==="function"?$!==w||!X:!w.has($))throw TypeError("Cannot write private member to an object whose class did not declare it");return W==="a"?X.call($,Z):X?X.value=Z:w.set($,Z),Z}function F($,w,Z,W){if(Z==="a"&&!W)throw TypeError("Private accessor was defined without a getter");if(typeof w==="function"?$!==w||!W:!w.has($))throw TypeError("Cannot read private member from an object whose class did not declare it");return Z==="m"?W:Z==="a"?W.call($):W?W.value:w.get($)}var U5=function(){let{crypto:$}=globalThis;if($?.randomUUID)return U5=$.randomUUID.bind($),$.randomUUID();let w=new Uint8Array(1),Z=$?()=>$.getRandomValues(w)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(W)=>(+W^Z()&15>>+W/4).toString(16))};function z$($){return typeof $==="object"&&$!==null&&(("name"in $)&&$.name==="AbortError"||("message"in $)&&String($.message).includes("FetchRequestCanceledException"))}var ow=($)=>{if($ instanceof Error)return $;if(typeof $==="object"&&$!==null){try{if(Object.prototype.toString.call($)==="[object Error]"){let w=Error($.message,$.cause?{cause:$.cause}:{});if($.stack)w.stack=$.stack;if($.cause&&!w.cause)w.cause=$.cause;if($.name)w.name=$.name;return w}}catch{}try{return Error(JSON.stringify($))}catch{}}return Error($)};class y extends Error{}class Z0 extends y{constructor($,w,Z,W){super(`${Z0.makeMessage($,w,Z)}`);this.status=$,this.headers=W,this.requestID=W?.get("request-id"),this.error=w}static makeMessage($,w,Z){let W=w?.message?typeof w.message==="string"?w.message:JSON.stringify(w.message):w?JSON.stringify(w):Z;if($&&W)return`${$} ${W}`;if($)return`${$} status code (no body)`;if(W)return W;return"(no status code or body)"}static generate($,w,Z,W){if(!$||!W)return new Y1({message:Z,cause:ow(w)});let X=w;if($===400)return new $9($,X,Z,W);if($===401)return new w9($,X,Z,W);if($===403)return new Z9($,X,Z,W);if($===404)return new W9($,X,Z,W);if($===409)return new X9($,X,Z,W);if($===422)return new Y9($,X,Z,W);if($===429)return new G9($,X,Z,W);if($>=500)return new J9($,X,Z,W);return new Z0($,X,Z,W)}}class B0 extends Z0{constructor({message:$}={}){super(void 0,void 0,$||"Request was aborted.",void 0)}}class Y1 extends Z0{constructor({message:$,cause:w}){super(void 0,void 0,$||"Connection error.",void 0);if(w)this.cause=w}}class ew extends Y1{constructor({message:$}={}){super({message:$??"Request timed out."})}}class $9 extends Z0{}class w9 extends Z0{}class Z9 extends Z0{}class W9 extends Z0{}class X9 extends Z0{}class Y9 extends Z0{}class G9 extends Z0{}class J9 extends Z0{}var nH=/^[a-z][a-z0-9+.-]*:/i,VJ=($)=>{return nH.test($)},H5=($)=>(H5=Array.isArray,H5($)),F5=H5;function O5($){if(typeof $!=="object")return{};return $??{}}function PJ($){if(!$)return!0;for(let w in $)return!1;return!0}function qJ($,w){return Object.prototype.hasOwnProperty.call($,w)}var UJ=($,w)=>{if(typeof w!=="number"||!Number.isInteger(w))throw new y(`${$} must be an integer`);if(w<0)throw new y(`${$} must be a positive integer`);return w};var y8=($)=>{try{return JSON.parse($)}catch(w){return}};var HJ=($)=>new Promise((w)=>setTimeout(w,$));var b$="0.61.0";var LJ=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"};function tH(){if(typeof Deno<"u"&&Deno.build!=null)return"deno";if(typeof EdgeRuntime<"u")return"edge";if(Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]")return"node";return"unknown"}var rH=()=>{let $=tH();if($==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":b$,"X-Stainless-OS":OJ(Deno.build.os),"X-Stainless-Arch":FJ(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version==="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":b$,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if($==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":b$,"X-Stainless-OS":OJ(globalThis.process.platform??"unknown"),"X-Stainless-Arch":FJ(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let w=sH();if(w)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":b$,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${w.browser}`,"X-Stainless-Runtime-Version":w.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":b$,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function sH(){if(typeof navigator>"u"||!navigator)return null;let $=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:w,pattern:Z}of $){let W=Z.exec(navigator.userAgent);if(W){let X=W[1]||0,Y=W[2]||0,G=W[3]||0;return{browser:w,version:`${X}.${Y}.${G}`}}}return null}var FJ=($)=>{if($==="x32")return"x32";if($==="x86_64"||$==="x64")return"x64";if($==="arm")return"arm";if($==="aarch64"||$==="arm64")return"arm64";if($)return`other:${$}`;return"unknown"},OJ=($)=>{if($=$.toLowerCase(),$.includes("ios"))return"iOS";if($==="android")return"Android";if($==="darwin")return"MacOS";if($==="win32")return"Windows";if($==="freebsd")return"FreeBSD";if($==="openbsd")return"OpenBSD";if($==="linux")return"Linux";if($)return`Other:${$}`;return"Unknown"},EJ,DJ=()=>{return EJ??(EJ=rH())};function fJ(){if(typeof fetch<"u")return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function E5(...$){let w=globalThis.ReadableStream;if(typeof w>"u")throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new w(...$)}function b8($){let w=Symbol.asyncIterator in $?$[Symbol.asyncIterator]():$[Symbol.iterator]();return E5({start(){},async pull(Z){let{done:W,value:X}=await w.next();if(W)Z.close();else Z.enqueue(X)},async cancel(){await w.return?.()}})}function Q9($){if($[Symbol.asyncIterator])return $;let w=$.getReader();return{async next(){try{let Z=await w.read();if(Z?.done)w.releaseLock();return Z}catch(Z){throw w.releaseLock(),Z}},async return(){let Z=w.cancel();return w.releaseLock(),await Z,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function kJ($){if($===null||typeof $!=="object")return;if($[Symbol.asyncIterator]){await $[Symbol.asyncIterator]().return?.();return}let w=$.getReader(),Z=w.cancel();w.releaseLock(),await Z}var AJ=({headers:$,body:w})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(w)}};function CJ($){let w=0;for(let X of $)w+=X.length;let Z=new Uint8Array(w),W=0;for(let X of $)Z.set(X,W),W+=X.length;return Z}var SJ;function z9($){let w;return(SJ??(w=new globalThis.TextEncoder,SJ=w.encode.bind(w)))($)}var RJ;function L5($){let w;return(RJ??(w=new globalThis.TextDecoder,RJ=w.decode.bind(w)))($)}var S0,R0;class x${constructor(){S0.set(this,void 0),R0.set(this,void 0),I(this,S0,new Uint8Array,"f"),I(this,R0,null,"f")}decode($){if($==null)return[];let w=$ instanceof ArrayBuffer?new Uint8Array($):typeof $==="string"?z9($):$;I(this,S0,CJ([F(this,S0,"f"),w]),"f");let Z=[],W;while((W=eH(F(this,S0,"f"),F(this,R0,"f")))!=null){if(W.carriage&&F(this,R0,"f")==null){I(this,R0,W.index,"f");continue}if(F(this,R0,"f")!=null&&(W.index!==F(this,R0,"f")+1||W.carriage)){Z.push(L5(F(this,S0,"f").subarray(0,F(this,R0,"f")-1))),I(this,S0,F(this,S0,"f").subarray(F(this,R0,"f")),"f"),I(this,R0,null,"f");continue}let X=F(this,R0,"f")!==null?W.preceding-1:W.preceding,Y=L5(F(this,S0,"f").subarray(0,X));Z.push(Y),I(this,S0,F(this,S0,"f").subarray(W.index),"f"),I(this,R0,null,"f")}return Z}flush(){if(!F(this,S0,"f").length)return[];return this.decode(`
|
|
71
71
|
`)}}S0=new WeakMap,R0=new WeakMap;x$.NEWLINE_CHARS=new Set([`
|
|
72
|
-
`,"\r"]);x$.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function
|
|
73
|
-
`);Z.enqueue(Y)}catch(W){Z.error(W)}},async cancel(){await w.return?.()}})}}async function*
|
|
74
|
-
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],X}if(this.chunks.push($),$.startsWith(":"))return null;let[w,Z,W]
|
|
75
|
-
${Y.map((
|
|
72
|
+
`,"\r"]);x$.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function eH($,w){for(let X=w??0;X<$.length;X++){if($[X]===10)return{preceding:X,index:X+1,carriage:!1};if($[X]===13)return{preceding:X,index:X+1,carriage:!0}}return null}function jJ($){for(let W=0;W<$.length-1;W++){if($[W]===10&&$[W+1]===10)return W+2;if($[W]===13&&$[W+1]===13)return W+2;if($[W]===13&&$[W+1]===10&&W+3<$.length&&$[W+2]===13&&$[W+3]===10)return W+4}return-1}var _8={off:0,error:200,warn:300,info:400,debug:500},D5=($,w,Z)=>{if(!$)return;if(qJ(_8,$))return $;J0(Z).warn(`${w} was set to ${JSON.stringify($)}, expected one of ${JSON.stringify(Object.keys(_8))}`);return};function M9(){}function x8($,w,Z){if(!w||_8[$]>_8[Z])return M9;else return w[$].bind(w)}var $F={error:M9,warn:M9,info:M9,debug:M9},IJ=new WeakMap;function J0($){let w=$.logger,Z=$.logLevel??"off";if(!w)return $F;let W=IJ.get(w);if(W&&W[0]===Z)return W[1];let X={error:x8("error",w,Z),warn:x8("warn",w,Z),info:x8("info",w,Z),debug:x8("debug",w,Z)};return IJ.set(w,[Z,X]),X}var M$=($)=>{if($.options)$.options={...$.options},delete $.options.headers;if($.headers)$.headers=Object.fromEntries(($.headers instanceof Headers?[...$.headers]:Object.entries($.headers)).map(([w,Z])=>[w,w.toLowerCase()==="x-api-key"||w.toLowerCase()==="authorization"||w.toLowerCase()==="cookie"||w.toLowerCase()==="set-cookie"?"***":Z]));if("retryOfRequestLogID"in $){if($.retryOfRequestLogID)$.retryOf=$.retryOfRequestLogID;delete $.retryOfRequestLogID}return $};var T9;class C0{constructor($,w,Z){this.iterator=$,T9.set(this,void 0),this.controller=w,I(this,T9,Z,"f")}static fromSSEResponse($,w,Z){let W=!1,X=Z?J0(Z):console;async function*Y(){if(W)throw new y("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");W=!0;let G=!1;try{for await(let J of wF($,w)){if(J.event==="completion")try{yield JSON.parse(J.data)}catch(Q){throw X.error("Could not parse message into JSON:",J.data),X.error("From chunk:",J.raw),Q}if(J.event==="message_start"||J.event==="message_delta"||J.event==="message_stop"||J.event==="content_block_start"||J.event==="content_block_delta"||J.event==="content_block_stop")try{yield JSON.parse(J.data)}catch(Q){throw X.error("Could not parse message into JSON:",J.data),X.error("From chunk:",J.raw),Q}if(J.event==="ping")continue;if(J.event==="error")throw new Z0(void 0,y8(J.data)??J.data,void 0,$.headers)}G=!0}catch(J){if(z$(J))return;throw J}finally{if(!G)w.abort()}}return new C0(Y,w,Z)}static fromReadableStream($,w,Z){let W=!1;async function*X(){let G=new x$,J=Q9($);for await(let Q of J)for(let z of G.decode(Q))yield z;for(let Q of G.flush())yield Q}async function*Y(){if(W)throw new y("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");W=!0;let G=!1;try{for await(let J of X()){if(G)continue;if(J)yield JSON.parse(J)}G=!0}catch(J){if(z$(J))return;throw J}finally{if(!G)w.abort()}}return new C0(Y,w,Z)}[(T9=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let $=[],w=[],Z=this.iterator(),W=(X)=>{return{next:()=>{if(X.length===0){let Y=Z.next();$.push(Y),w.push(Y)}return X.shift()}}};return[new C0(()=>W($),this.controller,F(this,T9,"f")),new C0(()=>W(w),this.controller,F(this,T9,"f"))]}toReadableStream(){let $=this,w;return E5({async start(){w=$[Symbol.asyncIterator]()},async pull(Z){try{let{value:W,done:X}=await w.next();if(X)return Z.close();let Y=z9(JSON.stringify(W)+`
|
|
73
|
+
`);Z.enqueue(Y)}catch(W){Z.error(W)}},async cancel(){await w.return?.()}})}}async function*wF($,w){if(!$.body){if(w.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new y("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new y("Attempted to iterate over a response with no body")}let Z=new yJ,W=new x$,X=Q9($.body);for await(let Y of ZF(X))for(let G of W.decode(Y)){let J=Z.decode(G);if(J)yield J}for(let Y of W.flush()){let G=Z.decode(Y);if(G)yield G}}async function*ZF($){let w=new Uint8Array;for await(let Z of $){if(Z==null)continue;let W=Z instanceof ArrayBuffer?new Uint8Array(Z):typeof Z==="string"?z9(Z):Z,X=new Uint8Array(w.length+W.length);X.set(w),X.set(W,w.length),w=X;let Y;while((Y=jJ(w))!==-1)yield w.slice(0,Y),w=w.slice(Y)}if(w.length>0)yield w}class yJ{constructor(){this.event=null,this.data=[],this.chunks=[]}decode($){if($.endsWith("\r"))$=$.substring(0,$.length-1);if(!$){if(!this.event&&!this.data.length)return null;let X={event:this.event,data:this.data.join(`
|
|
74
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],X}if(this.chunks.push($),$.startsWith(":"))return null;let[w,Z,W]=WF($,":");if(W.startsWith(" "))W=W.substring(1);if(w==="event")this.event=W;else if(w==="data")this.data.push(W);return null}}function WF($,w){let Z=$.indexOf(w);if(Z!==-1)return[$.substring(0,Z),w,$.substring(Z+w.length)];return[$,"",""]}async function g8($,w){let{response:Z,requestLogID:W,retryOfRequestLogID:X,startTime:Y}=w,G=await(async()=>{if(w.options.stream){if(J0($).debug("response",Z.status,Z.url,Z.headers,Z.body),w.options.__streamClass)return w.options.__streamClass.fromSSEResponse(Z,w.controller);return C0.fromSSEResponse(Z,w.controller)}if(Z.status===204)return null;if(w.options.__binaryResponse)return Z;let Q=Z.headers.get("content-type")?.split(";")[0]?.trim();if(Q?.includes("application/json")||Q?.endsWith("+json")){let T=await Z.json();return f5(T,Z)}return await Z.text()})();return J0($).debug(`[${W}] response parsed`,M$({retryOfRequestLogID:X,url:Z.url,status:Z.status,body:G,durationMs:Date.now()-Y})),G}function f5($,w){if(!$||typeof $!=="object"||Array.isArray($))return $;return Object.defineProperty($,"_request_id",{value:w.headers.get("request-id"),enumerable:!1})}var N9;class G1 extends Promise{constructor($,w,Z=g8){super((W)=>{W(null)});this.responsePromise=w,this.parseResponse=Z,N9.set(this,void 0),I(this,N9,$,"f")}_thenUnwrap($){return new G1(F(this,N9,"f"),this.responsePromise,async(w,Z)=>f5($(await this.parseResponse(w,Z),Z),Z.response))}asResponse(){return this.responsePromise.then(($)=>$.response)}async withResponse(){let[$,w]=await Promise.all([this.parse(),this.asResponse()]);return{data:$,response:w,request_id:w.headers.get("request-id")}}parse(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then(($)=>this.parseResponse(F(this,N9,"f"),$));return this.parsedPromise}then($,w){return this.parse().then($,w)}catch($){return this.parse().catch($)}finally($){return this.parse().finally($)}}N9=new WeakMap;var v8;class bJ{constructor($,w,Z,W){v8.set(this,void 0),I(this,v8,$,"f"),this.options=W,this.response=w,this.body=Z}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageRequestOptions()!=null}async getNextPage(){let $=this.nextPageRequestOptions();if(!$)throw new y("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await F(this,v8,"f").requestAPIList(this.constructor,$)}async*iterPages(){let $=this;yield $;while($.hasNextPage())$=await $.getNextPage(),yield $}async*[(v8=new WeakMap,Symbol.asyncIterator)](){for await(let $ of this.iterPages())for(let w of $.getPaginatedItems())yield w}}class u8 extends G1{constructor($,w,Z){super($,w,async(W,X)=>new Z(W,X.response,await g8(W,X),X.options))}async*[Symbol.asyncIterator](){let $=await this;for await(let w of $)yield w}}class d0 extends bJ{constructor($,w,Z,W){super($,w,Z,W);this.data=Z.data||[],this.has_more=Z.has_more||!1,this.first_id=Z.first_id||null,this.last_id=Z.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){let w=this.first_id;if(!w)return null;return{...this.options,query:{...O5(this.options.query),before_id:w}}}let $=this.last_id;if(!$)return null;return{...this.options,query:{...O5(this.options.query),after_id:$}}}}var A5=()=>{if(typeof File>"u"){let{process:$}=globalThis,w=typeof $?.versions?.node==="string"&&parseInt($.versions.node.split("."))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(w?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function J1($,w,Z){return A5(),new File($,w??"unknown_file",Z)}function K9($){return(typeof $==="object"&&$!==null&&(("name"in $)&&$.name&&String($.name)||("url"in $)&&$.url&&String($.url)||("filename"in $)&&$.filename&&String($.filename)||("path"in $)&&$.path&&String($.path))||"").split(/[\\/]/).pop()||void 0}var S5=($)=>$!=null&&typeof $==="object"&&typeof $[Symbol.asyncIterator]==="function";var _J=async($,w)=>{return{...$,body:await GF($.body,w)}},xJ=new WeakMap;function YF($){let w=typeof $==="function"?$:$.fetch,Z=xJ.get(w);if(Z)return Z;let W=(async()=>{try{let X="Response"in w?w.Response:(await w("data:,")).constructor,Y=new FormData;if(Y.toString()===await new X(Y).text())return!1;return!0}catch{return!0}})();return xJ.set(w,W),W}var GF=async($,w)=>{if(!await YF(w))throw TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let Z=new FormData;return await Promise.all(Object.entries($||{}).map(([W,X])=>k5(Z,W,X))),Z},JF=($)=>$ instanceof Blob&&("name"in $);var k5=async($,w,Z)=>{if(Z===void 0)return;if(Z==null)throw TypeError(`Received null for "${w}"; to pass null in FormData, you must use the string 'null'`);if(typeof Z==="string"||typeof Z==="number"||typeof Z==="boolean")$.append(w,String(Z));else if(Z instanceof Response){let W={},X=Z.headers.get("Content-Type");if(X)W={type:X};$.append(w,J1([await Z.blob()],K9(Z),W))}else if(S5(Z))$.append(w,J1([await new Response(b8(Z)).blob()],K9(Z)));else if(JF(Z))$.append(w,J1([Z],K9(Z),{type:Z.type}));else if(Array.isArray(Z))await Promise.all(Z.map((W)=>k5($,w+"[]",W)));else if(typeof Z==="object")await Promise.all(Object.entries(Z).map(([W,X])=>k5($,`${w}[${W}]`,X)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${Z} instead`)};var gJ=($)=>$!=null&&typeof $==="object"&&typeof $.size==="number"&&typeof $.type==="string"&&typeof $.text==="function"&&typeof $.slice==="function"&&typeof $.arrayBuffer==="function",QF=($)=>$!=null&&typeof $==="object"&&typeof $.name==="string"&&typeof $.lastModified==="number"&&gJ($),zF=($)=>$!=null&&typeof $==="object"&&typeof $.url==="string"&&typeof $.blob==="function";async function h8($,w,Z){if(A5(),$=await $,w||(w=K9($)),QF($)){if($ instanceof File&&w==null&&Z==null)return $;return J1([await $.arrayBuffer()],w??$.name,{type:$.type,lastModified:$.lastModified,...Z})}if(zF($)){let X=await $.blob();return w||(w=new URL($.url).pathname.split(/[\\/]/).pop()),J1(await R5(X),w,Z)}let W=await R5($);if(!Z?.type){let X=W.find((Y)=>typeof Y==="object"&&("type"in Y)&&Y.type);if(typeof X==="string")Z={...Z,type:X}}return J1(W,w,Z)}async function R5($){let w=[];if(typeof $==="string"||ArrayBuffer.isView($)||$ instanceof ArrayBuffer)w.push($);else if(gJ($))w.push($ instanceof Blob?$:await $.arrayBuffer());else if(S5($))for await(let Z of $)w.push(...await R5(Z));else{let Z=$?.constructor?.name;throw Error(`Unexpected data type: ${typeof $}${Z?`; constructor: ${Z}`:""}${MF($)}`)}return w}function MF($){if(typeof $!=="object"||$===null)return"";return`; props: [${Object.getOwnPropertyNames($).map((Z)=>`"${Z}"`).join(", ")}]`}class W0{constructor($){this._client=$}}var vJ=Symbol.for("brand.privateNullableHeaders");function*NF($){if(!$)return;if(vJ in $){let{values:W,nulls:X}=$;yield*W.entries();for(let Y of X)yield[Y,null];return}let w=!1,Z;if($ instanceof Headers)Z=$.entries();else if(F5($))Z=$;else w=!0,Z=Object.entries($??{});for(let W of Z){let X=W[0];if(typeof X!=="string")throw TypeError("expected header name to be a string");let Y=F5(W[1])?W[1]:[W[1]],G=!1;for(let J of Y){if(J===void 0)continue;if(w&&!G)G=!0,yield[X,null];yield[X,J]}}}var d=($)=>{let w=new Headers,Z=new Set;for(let W of $){let X=new Set;for(let[Y,G]of NF(W)){let J=Y.toLowerCase();if(!X.has(J))w.delete(Y),X.add(J);if(G===null)w.delete(Y),Z.add(J);else w.append(Y,G),Z.delete(J)}}return{[vJ]:!0,values:w,nulls:Z}};function hJ($){return $.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var uJ=Object.freeze(Object.create(null)),KF=($=hJ)=>function(Z,...W){if(Z.length===1)return Z[0];let X=!1,Y=[],G=Z.reduce((M,T,N)=>{if(/[?#]/.test(T))X=!0;let K=W[N],B=(X?encodeURIComponent:$)(""+K);if(N!==W.length&&(K==null||typeof K==="object"&&K.toString===Object.getPrototypeOf(Object.getPrototypeOf(K.hasOwnProperty??uJ)??uJ)?.toString))B=K+"",Y.push({start:M.length+T.length,length:B.length,error:`Value of type ${Object.prototype.toString.call(K).slice(8,-1)} is not a valid path parameter`});return M+T+(N===W.length?"":B)},""),J=G.split(/[?#]/,1)[0],Q=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,z;while((z=Q.exec(J))!==null)Y.push({start:z.index,length:z[0].length,error:`Value "${z[0]}" can't be safely passed as a path parameter`});if(Y.sort((M,T)=>M.start-T.start),Y.length>0){let M=0,T=Y.reduce((N,K)=>{let B=" ".repeat(K.start-M),P="^".repeat(K.length);return M=K.start+K.length,N+B+P},"");throw new y(`Path parameters result in path with invalid segments:
|
|
75
|
+
${Y.map((N)=>N.error).join(`
|
|
76
76
|
`)}
|
|
77
77
|
${G}
|
|
78
|
-
${T}`)}return G},V0=MF(gJ);class B9 extends W0{list($={},w){let{betas:Z,...W}=$??{};return this._client.getAPIList("/v1/files",d0,{query:W,...w,headers:d([{"anthropic-beta":[...Z??[],"files-api-2025-04-14"].toString()},w?.headers])})}delete($,w={},Z){let{betas:W}=w??{};return this._client.delete(V0`/v1/files/${$}`,{...Z,headers:d([{"anthropic-beta":[...W??[],"files-api-2025-04-14"].toString()},Z?.headers])})}download($,w={},Z){let{betas:W}=w??{};return this._client.get(V0`/v1/files/${$}/content`,{...Z,headers:d([{"anthropic-beta":[...W??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},Z?.headers]),__binaryResponse:!0})}retrieveMetadata($,w={},Z){let{betas:W}=w??{};return this._client.get(V0`/v1/files/${$}`,{...Z,headers:d([{"anthropic-beta":[...W??[],"files-api-2025-04-14"].toString()},Z?.headers])})}upload($,w){let{betas:Z,...W}=$;return this._client.post("/v1/files",yJ({body:W,...w,headers:d([{"anthropic-beta":[...Z??[],"files-api-2025-04-14"].toString()},w?.headers])},this._client))}}class V9 extends W0{retrieve($,w={},Z){let{betas:W}=w??{};return this._client.get(V0`/v1/models/${$}?beta=true`,{...Z,headers:d([{...W?.toString()!=null?{"anthropic-beta":W?.toString()}:void 0},Z?.headers])})}list($={},w){let{betas:Z,...W}=$??{};return this._client.getAPIList("/v1/models?beta=true",d0,{query:W,...w,headers:d([{...Z?.toString()!=null?{"anthropic-beta":Z?.toString()}:void 0},w?.headers])})}}class l1{constructor($,w){this.iterator=$,this.controller=w}async*decoder(){let $=new x$;for await(let w of this.iterator)for(let Z of $.decode(w))yield JSON.parse(Z);for(let w of $.flush())yield JSON.parse(w)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse($,w){if(!$.body){if(w.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new y("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new y("Attempted to iterate over a response with no body")}return new l1(Q9($.body),w)}}class P9 extends W0{create($,w){let{betas:Z,...W}=$;return this._client.post("/v1/messages/batches?beta=true",{body:W,...w,headers:d([{"anthropic-beta":[...Z??[],"message-batches-2024-09-24"].toString()},w?.headers])})}retrieve($,w={},Z){let{betas:W}=w??{};return this._client.get(V0`/v1/messages/batches/${$}?beta=true`,{...Z,headers:d([{"anthropic-beta":[...W??[],"message-batches-2024-09-24"].toString()},Z?.headers])})}list($={},w){let{betas:Z,...W}=$??{};return this._client.getAPIList("/v1/messages/batches?beta=true",d0,{query:W,...w,headers:d([{"anthropic-beta":[...Z??[],"message-batches-2024-09-24"].toString()},w?.headers])})}delete($,w={},Z){let{betas:W}=w??{};return this._client.delete(V0`/v1/messages/batches/${$}?beta=true`,{...Z,headers:d([{"anthropic-beta":[...W??[],"message-batches-2024-09-24"].toString()},Z?.headers])})}cancel($,w={},Z){let{betas:W}=w??{};return this._client.post(V0`/v1/messages/batches/${$}/cancel?beta=true`,{...Z,headers:d([{"anthropic-beta":[...W??[],"message-batches-2024-09-24"].toString()},Z?.headers])})}async results($,w={},Z){let W=await this.retrieve($);if(!W.results_url)throw new y(`No batch \`results_url\`; Has it finished processing? ${W.processing_status} - ${W.id}`);let{betas:X}=w??{};return this._client.get(W.results_url,{...Z,headers:d([{"anthropic-beta":[...X??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},Z?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((Y,G)=>l1.fromResponse(G.response,G.controller))}}var BF=($)=>{let w=0,Z=[];while(w<$.length){let W=$[w];if(W==="\\"){w++;continue}if(W==="{"){Z.push({type:"brace",value:"{"}),w++;continue}if(W==="}"){Z.push({type:"brace",value:"}"}),w++;continue}if(W==="["){Z.push({type:"paren",value:"["}),w++;continue}if(W==="]"){Z.push({type:"paren",value:"]"}),w++;continue}if(W===":"){Z.push({type:"separator",value:":"}),w++;continue}if(W===","){Z.push({type:"delimiter",value:","}),w++;continue}if(W==='"'){let J="",Q=!1;W=$[++w];while(W!=='"'){if(w===$.length){Q=!0;break}if(W==="\\"){if(w++,w===$.length){Q=!0;break}J+=W+$[w],W=$[++w]}else J+=W,W=$[++w]}if(W=$[++w],!Q)Z.push({type:"string",value:J});continue}if(W&&/\s/.test(W)){w++;continue}let Y=/[0-9]/;if(W&&Y.test(W)||W==="-"||W==="."){let J="";if(W==="-")J+=W,W=$[++w];while(W&&Y.test(W)||W===".")J+=W,W=$[++w];Z.push({type:"number",value:J});continue}let G=/[a-z]/i;if(W&&G.test(W)){let J="";while(W&&G.test(W)){if(w===$.length)break;J+=W,W=$[++w]}if(J=="true"||J=="false"||J==="null")Z.push({type:"name",value:J});else{w++;continue}continue}w++}return Z},c1=($)=>{if($.length===0)return $;let w=$[$.length-1];switch(w.type){case"separator":return $=$.slice(0,$.length-1),c1($);break;case"number":let Z=w.value[w.value.length-1];if(Z==="."||Z==="-")return $=$.slice(0,$.length-1),c1($);case"string":let W=$[$.length-2];if(W?.type==="delimiter")return $=$.slice(0,$.length-1),c1($);else if(W?.type==="brace"&&W.value==="{")return $=$.slice(0,$.length-1),c1($);break;case"delimiter":return $=$.slice(0,$.length-1),c1($);break}return $},VF=($)=>{let w=[];if($.map((Z)=>{if(Z.type==="brace")if(Z.value==="{")w.push("}");else w.splice(w.lastIndexOf("}"),1);if(Z.type==="paren")if(Z.value==="[")w.push("]");else w.splice(w.lastIndexOf("]"),1)}),w.length>0)w.reverse().map((Z)=>{if(Z==="}")$.push({type:"brace",value:"}"});else if(Z==="]")$.push({type:"paren",value:"]"})});return $},PF=($)=>{let w="";return $.map((Z)=>{switch(Z.type){case"string":w+='"'+Z.value+'"';break;default:w+=Z.value;break}}),w},i8=($)=>JSON.parse(PF(VF(c1(BF($)))));var v0,_$,q9,m8,U9,H9,l8,F9,M$,O9,c8,d8,d1,p8,n8,R5,vJ,t8,C5,j5,I5,uJ,hJ="__json_buf";function iJ($){return $.type==="tool_use"||$.type==="server_tool_use"||$.type==="mcp_tool_use"}class E9{constructor(){v0.add(this),this.messages=[],this.receivedMessages=[],_$.set(this,void 0),this.controller=new AbortController,q9.set(this,void 0),m8.set(this,()=>{}),U9.set(this,()=>{}),H9.set(this,void 0),l8.set(this,()=>{}),F9.set(this,()=>{}),M$.set(this,{}),O9.set(this,!1),c8.set(this,!1),d8.set(this,!1),d1.set(this,!1),p8.set(this,void 0),n8.set(this,void 0),t8.set(this,($)=>{if(I(this,c8,!0,"f"),Q$($))$=new B0;if($ instanceof B0)return I(this,d8,!0,"f"),this._emit("abort",$);if($ instanceof y)return this._emit("error",$);if($ instanceof Error){let w=new y($.message);return w.cause=$,this._emit("error",w)}return this._emit("error",new y(String($)))}),I(this,q9,new Promise(($,w)=>{I(this,m8,$,"f"),I(this,U9,w,"f")}),"f"),I(this,H9,new Promise(($,w)=>{I(this,l8,$,"f"),I(this,F9,w,"f")}),"f"),F(this,q9,"f").catch(()=>{}),F(this,H9,"f").catch(()=>{})}get response(){return F(this,p8,"f")}get request_id(){return F(this,n8,"f")}async withResponse(){let $=await F(this,q9,"f");if(!$)throw Error("Could not resolve a `Response` object");return{data:this,response:$,request_id:$.headers.get("request-id")}}static fromReadableStream($){let w=new E9;return w._run(()=>w._fromReadableStream($)),w}static createMessage($,w,Z){let W=new E9;for(let X of w.messages)W._addMessageParam(X);return W._run(()=>W._createMessage($,{...w,stream:!0},{...Z,headers:{...Z?.headers,"X-Stainless-Helper-Method":"stream"}})),W}_run($){$().then(()=>{this._emitFinal(),this._emit("end")},F(this,t8,"f"))}_addMessageParam($){this.messages.push($)}_addMessage($,w=!0){if(this.receivedMessages.push($),w)this._emit("message",$)}async _createMessage($,w,Z){let W=Z?.signal,X;if(W){if(W.aborted)this.controller.abort();X=this.controller.abort.bind(this.controller),W.addEventListener("abort",X)}try{F(this,v0,"m",C5).call(this);let{response:Y,data:G}=await $.create({...w,stream:!0},{...Z,signal:this.controller.signal}).withResponse();this._connected(Y);for await(let J of G)F(this,v0,"m",j5).call(this,J);if(G.controller.signal?.aborted)throw new B0;F(this,v0,"m",I5).call(this)}finally{if(W&&X)W.removeEventListener("abort",X)}}_connected($){if(this.ended)return;I(this,p8,$,"f"),I(this,n8,$?.headers.get("request-id"),"f"),F(this,m8,"f").call(this,$),this._emit("connect")}get ended(){return F(this,O9,"f")}get errored(){return F(this,c8,"f")}get aborted(){return F(this,d8,"f")}abort(){this.controller.abort()}on($,w){return(F(this,M$,"f")[$]||(F(this,M$,"f")[$]=[])).push({listener:w}),this}off($,w){let Z=F(this,M$,"f")[$];if(!Z)return this;let W=Z.findIndex((X)=>X.listener===w);if(W>=0)Z.splice(W,1);return this}once($,w){return(F(this,M$,"f")[$]||(F(this,M$,"f")[$]=[])).push({listener:w,once:!0}),this}emitted($){return new Promise((w,Z)=>{if(I(this,d1,!0,"f"),$!=="error")this.once("error",Z);this.once($,w)})}async done(){I(this,d1,!0,"f"),await F(this,H9,"f")}get currentMessage(){return F(this,_$,"f")}async finalMessage(){return await this.done(),F(this,v0,"m",R5).call(this)}async finalText(){return await this.done(),F(this,v0,"m",vJ).call(this)}_emit($,...w){if(F(this,O9,"f"))return;if($==="end")I(this,O9,!0,"f"),F(this,l8,"f").call(this);let Z=F(this,M$,"f")[$];if(Z)F(this,M$,"f")[$]=Z.filter((W)=>!W.once),Z.forEach(({listener:W})=>W(...w));if($==="abort"){let W=w[0];if(!F(this,d1,"f")&&!Z?.length)Promise.reject(W);F(this,U9,"f").call(this,W),F(this,F9,"f").call(this,W),this._emit("end");return}if($==="error"){let W=w[0];if(!F(this,d1,"f")&&!Z?.length)Promise.reject(W);F(this,U9,"f").call(this,W),F(this,F9,"f").call(this,W),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",F(this,v0,"m",R5).call(this))}async _fromReadableStream($,w){let Z=w?.signal,W;if(Z){if(Z.aborted)this.controller.abort();W=this.controller.abort.bind(this.controller),Z.addEventListener("abort",W)}try{F(this,v0,"m",C5).call(this),this._connected(null);let X=C0.fromReadableStream($,this.controller);for await(let Y of X)F(this,v0,"m",j5).call(this,Y);if(X.controller.signal?.aborted)throw new B0;F(this,v0,"m",I5).call(this)}finally{if(Z&&W)Z.removeEventListener("abort",W)}}[(_$=new WeakMap,q9=new WeakMap,m8=new WeakMap,U9=new WeakMap,H9=new WeakMap,l8=new WeakMap,F9=new WeakMap,M$=new WeakMap,O9=new WeakMap,c8=new WeakMap,d8=new WeakMap,d1=new WeakMap,p8=new WeakMap,n8=new WeakMap,t8=new WeakMap,v0=new WeakSet,R5=function(){if(this.receivedMessages.length===0)throw new y("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},vJ=function(){if(this.receivedMessages.length===0)throw new y("stream ended without producing a Message with role=assistant");let w=this.receivedMessages.at(-1).content.filter((Z)=>Z.type==="text").map((Z)=>Z.text);if(w.length===0)throw new y("stream ended without producing a content block with type=text");return w.join(" ")},C5=function(){if(this.ended)return;I(this,_$,void 0,"f")},j5=function(w){if(this.ended)return;let Z=F(this,v0,"m",uJ).call(this,w);switch(this._emit("streamEvent",w,Z),w.type){case"content_block_delta":{let W=Z.content.at(-1);switch(w.delta.type){case"text_delta":{if(W.type==="text")this._emit("text",w.delta.text,W.text||"");break}case"citations_delta":{if(W.type==="text")this._emit("citation",w.delta.citation,W.citations??[]);break}case"input_json_delta":{if(iJ(W)&&W.input)this._emit("inputJson",w.delta.partial_json,W.input);break}case"thinking_delta":{if(W.type==="thinking")this._emit("thinking",w.delta.thinking,W.thinking);break}case"signature_delta":{if(W.type==="thinking")this._emit("signature",W.signature);break}default:mJ(w.delta)}break}case"message_stop":{this._addMessageParam(Z),this._addMessage(Z,!0);break}case"content_block_stop":{this._emit("contentBlock",Z.content.at(-1));break}case"message_start":{I(this,_$,Z,"f");break}case"content_block_start":case"message_delta":break}},I5=function(){if(this.ended)throw new y("stream has ended, this shouldn't happen");let w=F(this,_$,"f");if(!w)throw new y("request ended without sending any chunks");return I(this,_$,void 0,"f"),w},uJ=function(w){let Z=F(this,_$,"f");if(w.type==="message_start"){if(Z)throw new y(`Unexpected event order, got ${w.type} before receiving "message_stop"`);return w.message}if(!Z)throw new y(`Unexpected event order, got ${w.type} before "message_start"`);switch(w.type){case"message_stop":return Z;case"message_delta":if(Z.container=w.delta.container,Z.stop_reason=w.delta.stop_reason,Z.stop_sequence=w.delta.stop_sequence,Z.usage.output_tokens=w.usage.output_tokens,w.usage.input_tokens!=null)Z.usage.input_tokens=w.usage.input_tokens;if(w.usage.cache_creation_input_tokens!=null)Z.usage.cache_creation_input_tokens=w.usage.cache_creation_input_tokens;if(w.usage.cache_read_input_tokens!=null)Z.usage.cache_read_input_tokens=w.usage.cache_read_input_tokens;if(w.usage.server_tool_use!=null)Z.usage.server_tool_use=w.usage.server_tool_use;return Z;case"content_block_start":return Z.content.push(w.content_block),Z;case"content_block_delta":{let W=Z.content.at(w.index);switch(w.delta.type){case"text_delta":{if(W?.type==="text")Z.content[w.index]={...W,text:(W.text||"")+w.delta.text};break}case"citations_delta":{if(W?.type==="text")Z.content[w.index]={...W,citations:[...W.citations??[],w.delta.citation]};break}case"input_json_delta":{if(W&&iJ(W)){let X=W[hJ]||"";X+=w.delta.partial_json;let Y={...W};if(Object.defineProperty(Y,hJ,{value:X,enumerable:!1,writable:!0}),X)try{Y.input=i8(X)}catch(G){let J=new y(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${G}. JSON: ${X}`);F(this,t8,"f").call(this,J)}Z.content[w.index]=Y}break}case"thinking_delta":{if(W?.type==="thinking")Z.content[w.index]={...W,thinking:W.thinking+w.delta.thinking};break}case"signature_delta":{if(W?.type==="thinking")Z.content[w.index]={...W,signature:w.delta.signature};break}default:mJ(w.delta)}return Z}case"content_block_stop":return Z}},Symbol.asyncIterator)](){let $=[],w=[],Z=!1;return this.on("streamEvent",(W)=>{let X=w.shift();if(X)X.resolve(W);else $.push(W)}),this.on("end",()=>{Z=!0;for(let W of w)W.resolve(void 0);w.length=0}),this.on("abort",(W)=>{Z=!0;for(let X of w)X.reject(W);w.length=0}),this.on("error",(W)=>{Z=!0;for(let X of w)X.reject(W);w.length=0}),{next:async()=>{if(!$.length){if(Z)return{value:void 0,done:!0};return new Promise((X,Y)=>w.push({resolve:X,reject:Y})).then((X)=>X?{value:X,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new C0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function mJ($){}var r8={"claude-opus-4-20250514":8192,"claude-opus-4-0":8192,"claude-4-opus-20250514":8192,"anthropic.claude-opus-4-20250514-v1:0":8192,"claude-opus-4@20250514":8192,"claude-opus-4-1-20250805":8192,"anthropic.claude-opus-4-1-20250805-v1:0":8192,"claude-opus-4-1@20250805":8192};var lJ={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-5-sonnet-20241022":"October 22, 2025","claude-3-5-sonnet-20240620":"October 22, 2025"};class p1 extends W0{constructor(){super(...arguments);this.batches=new P9(this._client)}create($,w){let{betas:Z,...W}=$;if(W.model in lJ)console.warn(`The model '${W.model}' is deprecated and will reach end-of-life on ${lJ[W.model]}
|
|
79
|
-
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);let X=this._client._options.timeout;if(!W.stream&&X==null){let Y=r8[W.model]??void 0;X=this._client.calculateNonstreamingTimeout(W.max_tokens,Y)}return this._client.post("/v1/messages?beta=true",{body:W,timeout:X??600000,...w,headers:d([{...Z?.toString()!=null?{"anthropic-beta":Z?.toString()}:void 0},w?.headers]),stream:$.stream??!1})}stream($,w){return E9.createMessage(this,$,w)}countTokens($,w){let{betas:Z,...W}=$;return this._client.post("/v1/messages/count_tokens?beta=true",{body:W,...w,headers:d([{"anthropic-beta":[...Z??[],"token-counting-2024-11-01"].toString()},w?.headers])})}}p1.Batches=P9;class T$ extends W0{constructor(){super(...arguments);this.models=new V9(this._client),this.messages=new p1(this._client),this.files=new B9(this._client)}}T$.Models=V9;T$.Messages=p1;T$.Files=B9;class n1 extends W0{create($,w){let{betas:Z,...W}=$;return this._client.post("/v1/complete",{body:W,timeout:this._client._options.timeout??600000,...w,headers:d([{...Z?.toString()!=null?{"anthropic-beta":Z?.toString()}:void 0},w?.headers]),stream:$.stream??!1})}}var u0,g$,L9,s8,D9,f9,a8,k9,K$,A9,o8,e8,t1,$6,w6,y5,cJ,b5,x5,_5,g5,dJ,pJ="__json_buf";function nJ($){return $.type==="tool_use"||$.type==="server_tool_use"}class S9{constructor(){u0.add(this),this.messages=[],this.receivedMessages=[],g$.set(this,void 0),this.controller=new AbortController,L9.set(this,void 0),s8.set(this,()=>{}),D9.set(this,()=>{}),f9.set(this,void 0),a8.set(this,()=>{}),k9.set(this,()=>{}),K$.set(this,{}),A9.set(this,!1),o8.set(this,!1),e8.set(this,!1),t1.set(this,!1),$6.set(this,void 0),w6.set(this,void 0),b5.set(this,($)=>{if(I(this,o8,!0,"f"),Q$($))$=new B0;if($ instanceof B0)return I(this,e8,!0,"f"),this._emit("abort",$);if($ instanceof y)return this._emit("error",$);if($ instanceof Error){let w=new y($.message);return w.cause=$,this._emit("error",w)}return this._emit("error",new y(String($)))}),I(this,L9,new Promise(($,w)=>{I(this,s8,$,"f"),I(this,D9,w,"f")}),"f"),I(this,f9,new Promise(($,w)=>{I(this,a8,$,"f"),I(this,k9,w,"f")}),"f"),F(this,L9,"f").catch(()=>{}),F(this,f9,"f").catch(()=>{})}get response(){return F(this,$6,"f")}get request_id(){return F(this,w6,"f")}async withResponse(){let $=await F(this,L9,"f");if(!$)throw Error("Could not resolve a `Response` object");return{data:this,response:$,request_id:$.headers.get("request-id")}}static fromReadableStream($){let w=new S9;return w._run(()=>w._fromReadableStream($)),w}static createMessage($,w,Z){let W=new S9;for(let X of w.messages)W._addMessageParam(X);return W._run(()=>W._createMessage($,{...w,stream:!0},{...Z,headers:{...Z?.headers,"X-Stainless-Helper-Method":"stream"}})),W}_run($){$().then(()=>{this._emitFinal(),this._emit("end")},F(this,b5,"f"))}_addMessageParam($){this.messages.push($)}_addMessage($,w=!0){if(this.receivedMessages.push($),w)this._emit("message",$)}async _createMessage($,w,Z){let W=Z?.signal,X;if(W){if(W.aborted)this.controller.abort();X=this.controller.abort.bind(this.controller),W.addEventListener("abort",X)}try{F(this,u0,"m",x5).call(this);let{response:Y,data:G}=await $.create({...w,stream:!0},{...Z,signal:this.controller.signal}).withResponse();this._connected(Y);for await(let J of G)F(this,u0,"m",_5).call(this,J);if(G.controller.signal?.aborted)throw new B0;F(this,u0,"m",g5).call(this)}finally{if(W&&X)W.removeEventListener("abort",X)}}_connected($){if(this.ended)return;I(this,$6,$,"f"),I(this,w6,$?.headers.get("request-id"),"f"),F(this,s8,"f").call(this,$),this._emit("connect")}get ended(){return F(this,A9,"f")}get errored(){return F(this,o8,"f")}get aborted(){return F(this,e8,"f")}abort(){this.controller.abort()}on($,w){return(F(this,K$,"f")[$]||(F(this,K$,"f")[$]=[])).push({listener:w}),this}off($,w){let Z=F(this,K$,"f")[$];if(!Z)return this;let W=Z.findIndex((X)=>X.listener===w);if(W>=0)Z.splice(W,1);return this}once($,w){return(F(this,K$,"f")[$]||(F(this,K$,"f")[$]=[])).push({listener:w,once:!0}),this}emitted($){return new Promise((w,Z)=>{if(I(this,t1,!0,"f"),$!=="error")this.once("error",Z);this.once($,w)})}async done(){I(this,t1,!0,"f"),await F(this,f9,"f")}get currentMessage(){return F(this,g$,"f")}async finalMessage(){return await this.done(),F(this,u0,"m",y5).call(this)}async finalText(){return await this.done(),F(this,u0,"m",cJ).call(this)}_emit($,...w){if(F(this,A9,"f"))return;if($==="end")I(this,A9,!0,"f"),F(this,a8,"f").call(this);let Z=F(this,K$,"f")[$];if(Z)F(this,K$,"f")[$]=Z.filter((W)=>!W.once),Z.forEach(({listener:W})=>W(...w));if($==="abort"){let W=w[0];if(!F(this,t1,"f")&&!Z?.length)Promise.reject(W);F(this,D9,"f").call(this,W),F(this,k9,"f").call(this,W),this._emit("end");return}if($==="error"){let W=w[0];if(!F(this,t1,"f")&&!Z?.length)Promise.reject(W);F(this,D9,"f").call(this,W),F(this,k9,"f").call(this,W),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",F(this,u0,"m",y5).call(this))}async _fromReadableStream($,w){let Z=w?.signal,W;if(Z){if(Z.aborted)this.controller.abort();W=this.controller.abort.bind(this.controller),Z.addEventListener("abort",W)}try{F(this,u0,"m",x5).call(this),this._connected(null);let X=C0.fromReadableStream($,this.controller);for await(let Y of X)F(this,u0,"m",_5).call(this,Y);if(X.controller.signal?.aborted)throw new B0;F(this,u0,"m",g5).call(this)}finally{if(Z&&W)Z.removeEventListener("abort",W)}}[(g$=new WeakMap,L9=new WeakMap,s8=new WeakMap,D9=new WeakMap,f9=new WeakMap,a8=new WeakMap,k9=new WeakMap,K$=new WeakMap,A9=new WeakMap,o8=new WeakMap,e8=new WeakMap,t1=new WeakMap,$6=new WeakMap,w6=new WeakMap,b5=new WeakMap,u0=new WeakSet,y5=function(){if(this.receivedMessages.length===0)throw new y("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},cJ=function(){if(this.receivedMessages.length===0)throw new y("stream ended without producing a Message with role=assistant");let w=this.receivedMessages.at(-1).content.filter((Z)=>Z.type==="text").map((Z)=>Z.text);if(w.length===0)throw new y("stream ended without producing a content block with type=text");return w.join(" ")},x5=function(){if(this.ended)return;I(this,g$,void 0,"f")},_5=function(w){if(this.ended)return;let Z=F(this,u0,"m",dJ).call(this,w);switch(this._emit("streamEvent",w,Z),w.type){case"content_block_delta":{let W=Z.content.at(-1);switch(w.delta.type){case"text_delta":{if(W.type==="text")this._emit("text",w.delta.text,W.text||"");break}case"citations_delta":{if(W.type==="text")this._emit("citation",w.delta.citation,W.citations??[]);break}case"input_json_delta":{if(nJ(W)&&W.input)this._emit("inputJson",w.delta.partial_json,W.input);break}case"thinking_delta":{if(W.type==="thinking")this._emit("thinking",w.delta.thinking,W.thinking);break}case"signature_delta":{if(W.type==="thinking")this._emit("signature",W.signature);break}default:tJ(w.delta)}break}case"message_stop":{this._addMessageParam(Z),this._addMessage(Z,!0);break}case"content_block_stop":{this._emit("contentBlock",Z.content.at(-1));break}case"message_start":{I(this,g$,Z,"f");break}case"content_block_start":case"message_delta":break}},g5=function(){if(this.ended)throw new y("stream has ended, this shouldn't happen");let w=F(this,g$,"f");if(!w)throw new y("request ended without sending any chunks");return I(this,g$,void 0,"f"),w},dJ=function(w){let Z=F(this,g$,"f");if(w.type==="message_start"){if(Z)throw new y(`Unexpected event order, got ${w.type} before receiving "message_stop"`);return w.message}if(!Z)throw new y(`Unexpected event order, got ${w.type} before "message_start"`);switch(w.type){case"message_stop":return Z;case"message_delta":if(Z.stop_reason=w.delta.stop_reason,Z.stop_sequence=w.delta.stop_sequence,Z.usage.output_tokens=w.usage.output_tokens,w.usage.input_tokens!=null)Z.usage.input_tokens=w.usage.input_tokens;if(w.usage.cache_creation_input_tokens!=null)Z.usage.cache_creation_input_tokens=w.usage.cache_creation_input_tokens;if(w.usage.cache_read_input_tokens!=null)Z.usage.cache_read_input_tokens=w.usage.cache_read_input_tokens;if(w.usage.server_tool_use!=null)Z.usage.server_tool_use=w.usage.server_tool_use;return Z;case"content_block_start":return Z.content.push({...w.content_block}),Z;case"content_block_delta":{let W=Z.content.at(w.index);switch(w.delta.type){case"text_delta":{if(W?.type==="text")Z.content[w.index]={...W,text:(W.text||"")+w.delta.text};break}case"citations_delta":{if(W?.type==="text")Z.content[w.index]={...W,citations:[...W.citations??[],w.delta.citation]};break}case"input_json_delta":{if(W&&nJ(W)){let X=W[pJ]||"";X+=w.delta.partial_json;let Y={...W};if(Object.defineProperty(Y,pJ,{value:X,enumerable:!1,writable:!0}),X)Y.input=i8(X);Z.content[w.index]=Y}break}case"thinking_delta":{if(W?.type==="thinking")Z.content[w.index]={...W,thinking:W.thinking+w.delta.thinking};break}case"signature_delta":{if(W?.type==="thinking")Z.content[w.index]={...W,signature:w.delta.signature};break}default:tJ(w.delta)}return Z}case"content_block_stop":return Z}},Symbol.asyncIterator)](){let $=[],w=[],Z=!1;return this.on("streamEvent",(W)=>{let X=w.shift();if(X)X.resolve(W);else $.push(W)}),this.on("end",()=>{Z=!0;for(let W of w)W.resolve(void 0);w.length=0}),this.on("abort",(W)=>{Z=!0;for(let X of w)X.reject(W);w.length=0}),this.on("error",(W)=>{Z=!0;for(let X of w)X.reject(W);w.length=0}),{next:async()=>{if(!$.length){if(Z)return{value:void 0,done:!0};return new Promise((X,Y)=>w.push({resolve:X,reject:Y})).then((X)=>X?{value:X,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new C0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function tJ($){}class R9 extends W0{create($,w){return this._client.post("/v1/messages/batches",{body:$,...w})}retrieve($,w){return this._client.get(V0`/v1/messages/batches/${$}`,w)}list($={},w){return this._client.getAPIList("/v1/messages/batches",d0,{query:$,...w})}delete($,w){return this._client.delete(V0`/v1/messages/batches/${$}`,w)}cancel($,w){return this._client.post(V0`/v1/messages/batches/${$}/cancel`,w)}async results($,w){let Z=await this.retrieve($);if(!Z.results_url)throw new y(`No batch \`results_url\`; Has it finished processing? ${Z.processing_status} - ${Z.id}`);return this._client.get(Z.results_url,{...w,headers:d([{Accept:"application/binary"},w?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((W,X)=>l1.fromResponse(X.response,X.controller))}}class Q1 extends W0{constructor(){super(...arguments);this.batches=new R9(this._client)}create($,w){if($.model in rJ)console.warn(`The model '${$.model}' is deprecated and will reach end-of-life on ${rJ[$.model]}
|
|
80
|
-
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);let Z=this._client._options.timeout;if(!$.stream&&Z==null){let W=r8[$.model]??void 0;Z=this._client.calculateNonstreamingTimeout($.max_tokens,W)}return this._client.post("/v1/messages",{body:$,timeout:Z??600000,...w,stream:$.stream??!1})}stream($,w){return S9.createMessage(this,$,w)}countTokens($,w){return this._client.post("/v1/messages/count_tokens",{body:$,...w})}}var
|
|
78
|
+
${T}`)}return G},V0=KF(hJ);class B9 extends W0{list($={},w){let{betas:Z,...W}=$??{};return this._client.getAPIList("/v1/files",d0,{query:W,...w,headers:d([{"anthropic-beta":[...Z??[],"files-api-2025-04-14"].toString()},w?.headers])})}delete($,w={},Z){let{betas:W}=w??{};return this._client.delete(V0`/v1/files/${$}`,{...Z,headers:d([{"anthropic-beta":[...W??[],"files-api-2025-04-14"].toString()},Z?.headers])})}download($,w={},Z){let{betas:W}=w??{};return this._client.get(V0`/v1/files/${$}/content`,{...Z,headers:d([{"anthropic-beta":[...W??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},Z?.headers]),__binaryResponse:!0})}retrieveMetadata($,w={},Z){let{betas:W}=w??{};return this._client.get(V0`/v1/files/${$}`,{...Z,headers:d([{"anthropic-beta":[...W??[],"files-api-2025-04-14"].toString()},Z?.headers])})}upload($,w){let{betas:Z,...W}=$;return this._client.post("/v1/files",_J({body:W,...w,headers:d([{"anthropic-beta":[...Z??[],"files-api-2025-04-14"].toString()},w?.headers])},this._client))}}class V9 extends W0{retrieve($,w={},Z){let{betas:W}=w??{};return this._client.get(V0`/v1/models/${$}?beta=true`,{...Z,headers:d([{...W?.toString()!=null?{"anthropic-beta":W?.toString()}:void 0},Z?.headers])})}list($={},w){let{betas:Z,...W}=$??{};return this._client.getAPIList("/v1/models?beta=true",d0,{query:W,...w,headers:d([{...Z?.toString()!=null?{"anthropic-beta":Z?.toString()}:void 0},w?.headers])})}}class l1{constructor($,w){this.iterator=$,this.controller=w}async*decoder(){let $=new x$;for await(let w of this.iterator)for(let Z of $.decode(w))yield JSON.parse(Z);for(let w of $.flush())yield JSON.parse(w)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse($,w){if(!$.body){if(w.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new y("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new y("Attempted to iterate over a response with no body")}return new l1(Q9($.body),w)}}class P9 extends W0{create($,w){let{betas:Z,...W}=$;return this._client.post("/v1/messages/batches?beta=true",{body:W,...w,headers:d([{"anthropic-beta":[...Z??[],"message-batches-2024-09-24"].toString()},w?.headers])})}retrieve($,w={},Z){let{betas:W}=w??{};return this._client.get(V0`/v1/messages/batches/${$}?beta=true`,{...Z,headers:d([{"anthropic-beta":[...W??[],"message-batches-2024-09-24"].toString()},Z?.headers])})}list($={},w){let{betas:Z,...W}=$??{};return this._client.getAPIList("/v1/messages/batches?beta=true",d0,{query:W,...w,headers:d([{"anthropic-beta":[...Z??[],"message-batches-2024-09-24"].toString()},w?.headers])})}delete($,w={},Z){let{betas:W}=w??{};return this._client.delete(V0`/v1/messages/batches/${$}?beta=true`,{...Z,headers:d([{"anthropic-beta":[...W??[],"message-batches-2024-09-24"].toString()},Z?.headers])})}cancel($,w={},Z){let{betas:W}=w??{};return this._client.post(V0`/v1/messages/batches/${$}/cancel?beta=true`,{...Z,headers:d([{"anthropic-beta":[...W??[],"message-batches-2024-09-24"].toString()},Z?.headers])})}async results($,w={},Z){let W=await this.retrieve($);if(!W.results_url)throw new y(`No batch \`results_url\`; Has it finished processing? ${W.processing_status} - ${W.id}`);let{betas:X}=w??{};return this._client.get(W.results_url,{...Z,headers:d([{"anthropic-beta":[...X??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},Z?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((Y,G)=>l1.fromResponse(G.response,G.controller))}}var qF=($)=>{let w=0,Z=[];while(w<$.length){let W=$[w];if(W==="\\"){w++;continue}if(W==="{"){Z.push({type:"brace",value:"{"}),w++;continue}if(W==="}"){Z.push({type:"brace",value:"}"}),w++;continue}if(W==="["){Z.push({type:"paren",value:"["}),w++;continue}if(W==="]"){Z.push({type:"paren",value:"]"}),w++;continue}if(W===":"){Z.push({type:"separator",value:":"}),w++;continue}if(W===","){Z.push({type:"delimiter",value:","}),w++;continue}if(W==='"'){let J="",Q=!1;W=$[++w];while(W!=='"'){if(w===$.length){Q=!0;break}if(W==="\\"){if(w++,w===$.length){Q=!0;break}J+=W+$[w],W=$[++w]}else J+=W,W=$[++w]}if(W=$[++w],!Q)Z.push({type:"string",value:J});continue}if(W&&/\s/.test(W)){w++;continue}let Y=/[0-9]/;if(W&&Y.test(W)||W==="-"||W==="."){let J="";if(W==="-")J+=W,W=$[++w];while(W&&Y.test(W)||W===".")J+=W,W=$[++w];Z.push({type:"number",value:J});continue}let G=/[a-z]/i;if(W&&G.test(W)){let J="";while(W&&G.test(W)){if(w===$.length)break;J+=W,W=$[++w]}if(J=="true"||J=="false"||J==="null")Z.push({type:"name",value:J});else{w++;continue}continue}w++}return Z},c1=($)=>{if($.length===0)return $;let w=$[$.length-1];switch(w.type){case"separator":return $=$.slice(0,$.length-1),c1($);break;case"number":let Z=w.value[w.value.length-1];if(Z==="."||Z==="-")return $=$.slice(0,$.length-1),c1($);case"string":let W=$[$.length-2];if(W?.type==="delimiter")return $=$.slice(0,$.length-1),c1($);else if(W?.type==="brace"&&W.value==="{")return $=$.slice(0,$.length-1),c1($);break;case"delimiter":return $=$.slice(0,$.length-1),c1($);break}return $},UF=($)=>{let w=[];if($.map((Z)=>{if(Z.type==="brace")if(Z.value==="{")w.push("}");else w.splice(w.lastIndexOf("}"),1);if(Z.type==="paren")if(Z.value==="[")w.push("]");else w.splice(w.lastIndexOf("]"),1)}),w.length>0)w.reverse().map((Z)=>{if(Z==="}")$.push({type:"brace",value:"}"});else if(Z==="]")$.push({type:"paren",value:"]"})});return $},HF=($)=>{let w="";return $.map((Z)=>{switch(Z.type){case"string":w+='"'+Z.value+'"';break;default:w+=Z.value;break}}),w},i8=($)=>JSON.parse(HF(UF(c1(qF($)))));var v0,_$,q9,m8,U9,H9,l8,F9,T$,O9,c8,d8,d1,p8,n8,C5,iJ,t8,j5,I5,y5,mJ,lJ="__json_buf";function cJ($){return $.type==="tool_use"||$.type==="server_tool_use"||$.type==="mcp_tool_use"}class E9{constructor(){v0.add(this),this.messages=[],this.receivedMessages=[],_$.set(this,void 0),this.controller=new AbortController,q9.set(this,void 0),m8.set(this,()=>{}),U9.set(this,()=>{}),H9.set(this,void 0),l8.set(this,()=>{}),F9.set(this,()=>{}),T$.set(this,{}),O9.set(this,!1),c8.set(this,!1),d8.set(this,!1),d1.set(this,!1),p8.set(this,void 0),n8.set(this,void 0),t8.set(this,($)=>{if(I(this,c8,!0,"f"),z$($))$=new B0;if($ instanceof B0)return I(this,d8,!0,"f"),this._emit("abort",$);if($ instanceof y)return this._emit("error",$);if($ instanceof Error){let w=new y($.message);return w.cause=$,this._emit("error",w)}return this._emit("error",new y(String($)))}),I(this,q9,new Promise(($,w)=>{I(this,m8,$,"f"),I(this,U9,w,"f")}),"f"),I(this,H9,new Promise(($,w)=>{I(this,l8,$,"f"),I(this,F9,w,"f")}),"f"),F(this,q9,"f").catch(()=>{}),F(this,H9,"f").catch(()=>{})}get response(){return F(this,p8,"f")}get request_id(){return F(this,n8,"f")}async withResponse(){let $=await F(this,q9,"f");if(!$)throw Error("Could not resolve a `Response` object");return{data:this,response:$,request_id:$.headers.get("request-id")}}static fromReadableStream($){let w=new E9;return w._run(()=>w._fromReadableStream($)),w}static createMessage($,w,Z){let W=new E9;for(let X of w.messages)W._addMessageParam(X);return W._run(()=>W._createMessage($,{...w,stream:!0},{...Z,headers:{...Z?.headers,"X-Stainless-Helper-Method":"stream"}})),W}_run($){$().then(()=>{this._emitFinal(),this._emit("end")},F(this,t8,"f"))}_addMessageParam($){this.messages.push($)}_addMessage($,w=!0){if(this.receivedMessages.push($),w)this._emit("message",$)}async _createMessage($,w,Z){let W=Z?.signal,X;if(W){if(W.aborted)this.controller.abort();X=this.controller.abort.bind(this.controller),W.addEventListener("abort",X)}try{F(this,v0,"m",j5).call(this);let{response:Y,data:G}=await $.create({...w,stream:!0},{...Z,signal:this.controller.signal}).withResponse();this._connected(Y);for await(let J of G)F(this,v0,"m",I5).call(this,J);if(G.controller.signal?.aborted)throw new B0;F(this,v0,"m",y5).call(this)}finally{if(W&&X)W.removeEventListener("abort",X)}}_connected($){if(this.ended)return;I(this,p8,$,"f"),I(this,n8,$?.headers.get("request-id"),"f"),F(this,m8,"f").call(this,$),this._emit("connect")}get ended(){return F(this,O9,"f")}get errored(){return F(this,c8,"f")}get aborted(){return F(this,d8,"f")}abort(){this.controller.abort()}on($,w){return(F(this,T$,"f")[$]||(F(this,T$,"f")[$]=[])).push({listener:w}),this}off($,w){let Z=F(this,T$,"f")[$];if(!Z)return this;let W=Z.findIndex((X)=>X.listener===w);if(W>=0)Z.splice(W,1);return this}once($,w){return(F(this,T$,"f")[$]||(F(this,T$,"f")[$]=[])).push({listener:w,once:!0}),this}emitted($){return new Promise((w,Z)=>{if(I(this,d1,!0,"f"),$!=="error")this.once("error",Z);this.once($,w)})}async done(){I(this,d1,!0,"f"),await F(this,H9,"f")}get currentMessage(){return F(this,_$,"f")}async finalMessage(){return await this.done(),F(this,v0,"m",C5).call(this)}async finalText(){return await this.done(),F(this,v0,"m",iJ).call(this)}_emit($,...w){if(F(this,O9,"f"))return;if($==="end")I(this,O9,!0,"f"),F(this,l8,"f").call(this);let Z=F(this,T$,"f")[$];if(Z)F(this,T$,"f")[$]=Z.filter((W)=>!W.once),Z.forEach(({listener:W})=>W(...w));if($==="abort"){let W=w[0];if(!F(this,d1,"f")&&!Z?.length)Promise.reject(W);F(this,U9,"f").call(this,W),F(this,F9,"f").call(this,W),this._emit("end");return}if($==="error"){let W=w[0];if(!F(this,d1,"f")&&!Z?.length)Promise.reject(W);F(this,U9,"f").call(this,W),F(this,F9,"f").call(this,W),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",F(this,v0,"m",C5).call(this))}async _fromReadableStream($,w){let Z=w?.signal,W;if(Z){if(Z.aborted)this.controller.abort();W=this.controller.abort.bind(this.controller),Z.addEventListener("abort",W)}try{F(this,v0,"m",j5).call(this),this._connected(null);let X=C0.fromReadableStream($,this.controller);for await(let Y of X)F(this,v0,"m",I5).call(this,Y);if(X.controller.signal?.aborted)throw new B0;F(this,v0,"m",y5).call(this)}finally{if(Z&&W)Z.removeEventListener("abort",W)}}[(_$=new WeakMap,q9=new WeakMap,m8=new WeakMap,U9=new WeakMap,H9=new WeakMap,l8=new WeakMap,F9=new WeakMap,T$=new WeakMap,O9=new WeakMap,c8=new WeakMap,d8=new WeakMap,d1=new WeakMap,p8=new WeakMap,n8=new WeakMap,t8=new WeakMap,v0=new WeakSet,C5=function(){if(this.receivedMessages.length===0)throw new y("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},iJ=function(){if(this.receivedMessages.length===0)throw new y("stream ended without producing a Message with role=assistant");let w=this.receivedMessages.at(-1).content.filter((Z)=>Z.type==="text").map((Z)=>Z.text);if(w.length===0)throw new y("stream ended without producing a content block with type=text");return w.join(" ")},j5=function(){if(this.ended)return;I(this,_$,void 0,"f")},I5=function(w){if(this.ended)return;let Z=F(this,v0,"m",mJ).call(this,w);switch(this._emit("streamEvent",w,Z),w.type){case"content_block_delta":{let W=Z.content.at(-1);switch(w.delta.type){case"text_delta":{if(W.type==="text")this._emit("text",w.delta.text,W.text||"");break}case"citations_delta":{if(W.type==="text")this._emit("citation",w.delta.citation,W.citations??[]);break}case"input_json_delta":{if(cJ(W)&&W.input)this._emit("inputJson",w.delta.partial_json,W.input);break}case"thinking_delta":{if(W.type==="thinking")this._emit("thinking",w.delta.thinking,W.thinking);break}case"signature_delta":{if(W.type==="thinking")this._emit("signature",W.signature);break}default:dJ(w.delta)}break}case"message_stop":{this._addMessageParam(Z),this._addMessage(Z,!0);break}case"content_block_stop":{this._emit("contentBlock",Z.content.at(-1));break}case"message_start":{I(this,_$,Z,"f");break}case"content_block_start":case"message_delta":break}},y5=function(){if(this.ended)throw new y("stream has ended, this shouldn't happen");let w=F(this,_$,"f");if(!w)throw new y("request ended without sending any chunks");return I(this,_$,void 0,"f"),w},mJ=function(w){let Z=F(this,_$,"f");if(w.type==="message_start"){if(Z)throw new y(`Unexpected event order, got ${w.type} before receiving "message_stop"`);return w.message}if(!Z)throw new y(`Unexpected event order, got ${w.type} before "message_start"`);switch(w.type){case"message_stop":return Z;case"message_delta":if(Z.container=w.delta.container,Z.stop_reason=w.delta.stop_reason,Z.stop_sequence=w.delta.stop_sequence,Z.usage.output_tokens=w.usage.output_tokens,w.usage.input_tokens!=null)Z.usage.input_tokens=w.usage.input_tokens;if(w.usage.cache_creation_input_tokens!=null)Z.usage.cache_creation_input_tokens=w.usage.cache_creation_input_tokens;if(w.usage.cache_read_input_tokens!=null)Z.usage.cache_read_input_tokens=w.usage.cache_read_input_tokens;if(w.usage.server_tool_use!=null)Z.usage.server_tool_use=w.usage.server_tool_use;return Z;case"content_block_start":return Z.content.push(w.content_block),Z;case"content_block_delta":{let W=Z.content.at(w.index);switch(w.delta.type){case"text_delta":{if(W?.type==="text")Z.content[w.index]={...W,text:(W.text||"")+w.delta.text};break}case"citations_delta":{if(W?.type==="text")Z.content[w.index]={...W,citations:[...W.citations??[],w.delta.citation]};break}case"input_json_delta":{if(W&&cJ(W)){let X=W[lJ]||"";X+=w.delta.partial_json;let Y={...W};if(Object.defineProperty(Y,lJ,{value:X,enumerable:!1,writable:!0}),X)try{Y.input=i8(X)}catch(G){let J=new y(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${G}. JSON: ${X}`);F(this,t8,"f").call(this,J)}Z.content[w.index]=Y}break}case"thinking_delta":{if(W?.type==="thinking")Z.content[w.index]={...W,thinking:W.thinking+w.delta.thinking};break}case"signature_delta":{if(W?.type==="thinking")Z.content[w.index]={...W,signature:w.delta.signature};break}default:dJ(w.delta)}return Z}case"content_block_stop":return Z}},Symbol.asyncIterator)](){let $=[],w=[],Z=!1;return this.on("streamEvent",(W)=>{let X=w.shift();if(X)X.resolve(W);else $.push(W)}),this.on("end",()=>{Z=!0;for(let W of w)W.resolve(void 0);w.length=0}),this.on("abort",(W)=>{Z=!0;for(let X of w)X.reject(W);w.length=0}),this.on("error",(W)=>{Z=!0;for(let X of w)X.reject(W);w.length=0}),{next:async()=>{if(!$.length){if(Z)return{value:void 0,done:!0};return new Promise((X,Y)=>w.push({resolve:X,reject:Y})).then((X)=>X?{value:X,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new C0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function dJ($){}var r8={"claude-opus-4-20250514":8192,"claude-opus-4-0":8192,"claude-4-opus-20250514":8192,"anthropic.claude-opus-4-20250514-v1:0":8192,"claude-opus-4@20250514":8192,"claude-opus-4-1-20250805":8192,"anthropic.claude-opus-4-1-20250805-v1:0":8192,"claude-opus-4-1@20250805":8192};var pJ={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-5-sonnet-20241022":"October 22, 2025","claude-3-5-sonnet-20240620":"October 22, 2025"};class p1 extends W0{constructor(){super(...arguments);this.batches=new P9(this._client)}create($,w){let{betas:Z,...W}=$;if(W.model in pJ)console.warn(`The model '${W.model}' is deprecated and will reach end-of-life on ${pJ[W.model]}
|
|
79
|
+
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);let X=this._client._options.timeout;if(!W.stream&&X==null){let Y=r8[W.model]??void 0;X=this._client.calculateNonstreamingTimeout(W.max_tokens,Y)}return this._client.post("/v1/messages?beta=true",{body:W,timeout:X??600000,...w,headers:d([{...Z?.toString()!=null?{"anthropic-beta":Z?.toString()}:void 0},w?.headers]),stream:$.stream??!1})}stream($,w){return E9.createMessage(this,$,w)}countTokens($,w){let{betas:Z,...W}=$;return this._client.post("/v1/messages/count_tokens?beta=true",{body:W,...w,headers:d([{"anthropic-beta":[...Z??[],"token-counting-2024-11-01"].toString()},w?.headers])})}}p1.Batches=P9;class N$ extends W0{constructor(){super(...arguments);this.models=new V9(this._client),this.messages=new p1(this._client),this.files=new B9(this._client)}}N$.Models=V9;N$.Messages=p1;N$.Files=B9;class n1 extends W0{create($,w){let{betas:Z,...W}=$;return this._client.post("/v1/complete",{body:W,timeout:this._client._options.timeout??600000,...w,headers:d([{...Z?.toString()!=null?{"anthropic-beta":Z?.toString()}:void 0},w?.headers]),stream:$.stream??!1})}}var u0,g$,L9,s8,D9,f9,a8,k9,K$,A9,o8,e8,t1,$6,w6,b5,nJ,x5,_5,g5,v5,tJ,rJ="__json_buf";function sJ($){return $.type==="tool_use"||$.type==="server_tool_use"}class S9{constructor(){u0.add(this),this.messages=[],this.receivedMessages=[],g$.set(this,void 0),this.controller=new AbortController,L9.set(this,void 0),s8.set(this,()=>{}),D9.set(this,()=>{}),f9.set(this,void 0),a8.set(this,()=>{}),k9.set(this,()=>{}),K$.set(this,{}),A9.set(this,!1),o8.set(this,!1),e8.set(this,!1),t1.set(this,!1),$6.set(this,void 0),w6.set(this,void 0),x5.set(this,($)=>{if(I(this,o8,!0,"f"),z$($))$=new B0;if($ instanceof B0)return I(this,e8,!0,"f"),this._emit("abort",$);if($ instanceof y)return this._emit("error",$);if($ instanceof Error){let w=new y($.message);return w.cause=$,this._emit("error",w)}return this._emit("error",new y(String($)))}),I(this,L9,new Promise(($,w)=>{I(this,s8,$,"f"),I(this,D9,w,"f")}),"f"),I(this,f9,new Promise(($,w)=>{I(this,a8,$,"f"),I(this,k9,w,"f")}),"f"),F(this,L9,"f").catch(()=>{}),F(this,f9,"f").catch(()=>{})}get response(){return F(this,$6,"f")}get request_id(){return F(this,w6,"f")}async withResponse(){let $=await F(this,L9,"f");if(!$)throw Error("Could not resolve a `Response` object");return{data:this,response:$,request_id:$.headers.get("request-id")}}static fromReadableStream($){let w=new S9;return w._run(()=>w._fromReadableStream($)),w}static createMessage($,w,Z){let W=new S9;for(let X of w.messages)W._addMessageParam(X);return W._run(()=>W._createMessage($,{...w,stream:!0},{...Z,headers:{...Z?.headers,"X-Stainless-Helper-Method":"stream"}})),W}_run($){$().then(()=>{this._emitFinal(),this._emit("end")},F(this,x5,"f"))}_addMessageParam($){this.messages.push($)}_addMessage($,w=!0){if(this.receivedMessages.push($),w)this._emit("message",$)}async _createMessage($,w,Z){let W=Z?.signal,X;if(W){if(W.aborted)this.controller.abort();X=this.controller.abort.bind(this.controller),W.addEventListener("abort",X)}try{F(this,u0,"m",_5).call(this);let{response:Y,data:G}=await $.create({...w,stream:!0},{...Z,signal:this.controller.signal}).withResponse();this._connected(Y);for await(let J of G)F(this,u0,"m",g5).call(this,J);if(G.controller.signal?.aborted)throw new B0;F(this,u0,"m",v5).call(this)}finally{if(W&&X)W.removeEventListener("abort",X)}}_connected($){if(this.ended)return;I(this,$6,$,"f"),I(this,w6,$?.headers.get("request-id"),"f"),F(this,s8,"f").call(this,$),this._emit("connect")}get ended(){return F(this,A9,"f")}get errored(){return F(this,o8,"f")}get aborted(){return F(this,e8,"f")}abort(){this.controller.abort()}on($,w){return(F(this,K$,"f")[$]||(F(this,K$,"f")[$]=[])).push({listener:w}),this}off($,w){let Z=F(this,K$,"f")[$];if(!Z)return this;let W=Z.findIndex((X)=>X.listener===w);if(W>=0)Z.splice(W,1);return this}once($,w){return(F(this,K$,"f")[$]||(F(this,K$,"f")[$]=[])).push({listener:w,once:!0}),this}emitted($){return new Promise((w,Z)=>{if(I(this,t1,!0,"f"),$!=="error")this.once("error",Z);this.once($,w)})}async done(){I(this,t1,!0,"f"),await F(this,f9,"f")}get currentMessage(){return F(this,g$,"f")}async finalMessage(){return await this.done(),F(this,u0,"m",b5).call(this)}async finalText(){return await this.done(),F(this,u0,"m",nJ).call(this)}_emit($,...w){if(F(this,A9,"f"))return;if($==="end")I(this,A9,!0,"f"),F(this,a8,"f").call(this);let Z=F(this,K$,"f")[$];if(Z)F(this,K$,"f")[$]=Z.filter((W)=>!W.once),Z.forEach(({listener:W})=>W(...w));if($==="abort"){let W=w[0];if(!F(this,t1,"f")&&!Z?.length)Promise.reject(W);F(this,D9,"f").call(this,W),F(this,k9,"f").call(this,W),this._emit("end");return}if($==="error"){let W=w[0];if(!F(this,t1,"f")&&!Z?.length)Promise.reject(W);F(this,D9,"f").call(this,W),F(this,k9,"f").call(this,W),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",F(this,u0,"m",b5).call(this))}async _fromReadableStream($,w){let Z=w?.signal,W;if(Z){if(Z.aborted)this.controller.abort();W=this.controller.abort.bind(this.controller),Z.addEventListener("abort",W)}try{F(this,u0,"m",_5).call(this),this._connected(null);let X=C0.fromReadableStream($,this.controller);for await(let Y of X)F(this,u0,"m",g5).call(this,Y);if(X.controller.signal?.aborted)throw new B0;F(this,u0,"m",v5).call(this)}finally{if(Z&&W)Z.removeEventListener("abort",W)}}[(g$=new WeakMap,L9=new WeakMap,s8=new WeakMap,D9=new WeakMap,f9=new WeakMap,a8=new WeakMap,k9=new WeakMap,K$=new WeakMap,A9=new WeakMap,o8=new WeakMap,e8=new WeakMap,t1=new WeakMap,$6=new WeakMap,w6=new WeakMap,x5=new WeakMap,u0=new WeakSet,b5=function(){if(this.receivedMessages.length===0)throw new y("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},nJ=function(){if(this.receivedMessages.length===0)throw new y("stream ended without producing a Message with role=assistant");let w=this.receivedMessages.at(-1).content.filter((Z)=>Z.type==="text").map((Z)=>Z.text);if(w.length===0)throw new y("stream ended without producing a content block with type=text");return w.join(" ")},_5=function(){if(this.ended)return;I(this,g$,void 0,"f")},g5=function(w){if(this.ended)return;let Z=F(this,u0,"m",tJ).call(this,w);switch(this._emit("streamEvent",w,Z),w.type){case"content_block_delta":{let W=Z.content.at(-1);switch(w.delta.type){case"text_delta":{if(W.type==="text")this._emit("text",w.delta.text,W.text||"");break}case"citations_delta":{if(W.type==="text")this._emit("citation",w.delta.citation,W.citations??[]);break}case"input_json_delta":{if(sJ(W)&&W.input)this._emit("inputJson",w.delta.partial_json,W.input);break}case"thinking_delta":{if(W.type==="thinking")this._emit("thinking",w.delta.thinking,W.thinking);break}case"signature_delta":{if(W.type==="thinking")this._emit("signature",W.signature);break}default:aJ(w.delta)}break}case"message_stop":{this._addMessageParam(Z),this._addMessage(Z,!0);break}case"content_block_stop":{this._emit("contentBlock",Z.content.at(-1));break}case"message_start":{I(this,g$,Z,"f");break}case"content_block_start":case"message_delta":break}},v5=function(){if(this.ended)throw new y("stream has ended, this shouldn't happen");let w=F(this,g$,"f");if(!w)throw new y("request ended without sending any chunks");return I(this,g$,void 0,"f"),w},tJ=function(w){let Z=F(this,g$,"f");if(w.type==="message_start"){if(Z)throw new y(`Unexpected event order, got ${w.type} before receiving "message_stop"`);return w.message}if(!Z)throw new y(`Unexpected event order, got ${w.type} before "message_start"`);switch(w.type){case"message_stop":return Z;case"message_delta":if(Z.stop_reason=w.delta.stop_reason,Z.stop_sequence=w.delta.stop_sequence,Z.usage.output_tokens=w.usage.output_tokens,w.usage.input_tokens!=null)Z.usage.input_tokens=w.usage.input_tokens;if(w.usage.cache_creation_input_tokens!=null)Z.usage.cache_creation_input_tokens=w.usage.cache_creation_input_tokens;if(w.usage.cache_read_input_tokens!=null)Z.usage.cache_read_input_tokens=w.usage.cache_read_input_tokens;if(w.usage.server_tool_use!=null)Z.usage.server_tool_use=w.usage.server_tool_use;return Z;case"content_block_start":return Z.content.push({...w.content_block}),Z;case"content_block_delta":{let W=Z.content.at(w.index);switch(w.delta.type){case"text_delta":{if(W?.type==="text")Z.content[w.index]={...W,text:(W.text||"")+w.delta.text};break}case"citations_delta":{if(W?.type==="text")Z.content[w.index]={...W,citations:[...W.citations??[],w.delta.citation]};break}case"input_json_delta":{if(W&&sJ(W)){let X=W[rJ]||"";X+=w.delta.partial_json;let Y={...W};if(Object.defineProperty(Y,rJ,{value:X,enumerable:!1,writable:!0}),X)Y.input=i8(X);Z.content[w.index]=Y}break}case"thinking_delta":{if(W?.type==="thinking")Z.content[w.index]={...W,thinking:W.thinking+w.delta.thinking};break}case"signature_delta":{if(W?.type==="thinking")Z.content[w.index]={...W,signature:w.delta.signature};break}default:aJ(w.delta)}return Z}case"content_block_stop":return Z}},Symbol.asyncIterator)](){let $=[],w=[],Z=!1;return this.on("streamEvent",(W)=>{let X=w.shift();if(X)X.resolve(W);else $.push(W)}),this.on("end",()=>{Z=!0;for(let W of w)W.resolve(void 0);w.length=0}),this.on("abort",(W)=>{Z=!0;for(let X of w)X.reject(W);w.length=0}),this.on("error",(W)=>{Z=!0;for(let X of w)X.reject(W);w.length=0}),{next:async()=>{if(!$.length){if(Z)return{value:void 0,done:!0};return new Promise((X,Y)=>w.push({resolve:X,reject:Y})).then((X)=>X?{value:X,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new C0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function aJ($){}class R9 extends W0{create($,w){return this._client.post("/v1/messages/batches",{body:$,...w})}retrieve($,w){return this._client.get(V0`/v1/messages/batches/${$}`,w)}list($={},w){return this._client.getAPIList("/v1/messages/batches",d0,{query:$,...w})}delete($,w){return this._client.delete(V0`/v1/messages/batches/${$}`,w)}cancel($,w){return this._client.post(V0`/v1/messages/batches/${$}/cancel`,w)}async results($,w){let Z=await this.retrieve($);if(!Z.results_url)throw new y(`No batch \`results_url\`; Has it finished processing? ${Z.processing_status} - ${Z.id}`);return this._client.get(Z.results_url,{...w,headers:d([{Accept:"application/binary"},w?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((W,X)=>l1.fromResponse(X.response,X.controller))}}class Q1 extends W0{constructor(){super(...arguments);this.batches=new R9(this._client)}create($,w){if($.model in oJ)console.warn(`The model '${$.model}' is deprecated and will reach end-of-life on ${oJ[$.model]}
|
|
80
|
+
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);let Z=this._client._options.timeout;if(!$.stream&&Z==null){let W=r8[$.model]??void 0;Z=this._client.calculateNonstreamingTimeout($.max_tokens,W)}return this._client.post("/v1/messages",{body:$,timeout:Z??600000,...w,stream:$.stream??!1})}stream($,w){return S9.createMessage(this,$,w)}countTokens($,w){return this._client.post("/v1/messages/count_tokens",{body:$,...w})}}var oJ={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-5-sonnet-20241022":"October 22, 2025","claude-3-5-sonnet-20240620":"October 22, 2025"};Q1.Batches=R9;class r1 extends W0{retrieve($,w={},Z){let{betas:W}=w??{};return this._client.get(V0`/v1/models/${$}`,{...Z,headers:d([{...W?.toString()!=null?{"anthropic-beta":W?.toString()}:void 0},Z?.headers])})}list($={},w){let{betas:Z,...W}=$??{};return this._client.getAPIList("/v1/models",d0,{query:W,...w,headers:d([{...Z?.toString()!=null?{"anthropic-beta":Z?.toString()}:void 0},w?.headers])})}}var C9=($)=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[$]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.($)?.trim();return};var u5,h5,Z6,eJ,$Q="\\n\\nHuman:",wQ="\\n\\nAssistant:";class s{constructor({baseURL:$=C9("ANTHROPIC_BASE_URL"),apiKey:w=C9("ANTHROPIC_API_KEY")??null,authToken:Z=C9("ANTHROPIC_AUTH_TOKEN")??null,...W}={}){u5.add(this),Z6.set(this,void 0);let X={apiKey:w,authToken:Z,...W,baseURL:$||"https://api.anthropic.com"};if(!X.dangerouslyAllowBrowser&&LJ())throw new y(`It looks like you're running in a browser-like environment.
|
|
81
81
|
|
|
82
82
|
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
83
83
|
If you understand the risks and have appropriate mitigations in place,
|
|
84
84
|
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
85
85
|
|
|
86
86
|
new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
|
|
87
|
-
`);this.baseURL=X.baseURL,this.timeout=X.timeout??u5.DEFAULT_TIMEOUT,this.logger=X.logger??console;let Y="warn";this.logLevel=Y,this.logLevel=L5(X.logLevel,"ClientOptions.logLevel",this)??L5(C9("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??Y,this.fetchOptions=X.fetchOptions,this.maxRetries=X.maxRetries??2,this.fetch=X.fetch??EJ(),I(this,Z6,DJ,"f"),this._options=X,this.apiKey=w,this.authToken=Z}withOptions($){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...$})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:$,nulls:w}){if(this.apiKey&&$.get("x-api-key"))return;if(w.has("x-api-key"))return;if(this.authToken&&$.get("authorization"))return;if(w.has("authorization"))return;throw Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}async authHeaders($){return d([await this.apiKeyAuth($),await this.bearerAuth($)])}async apiKeyAuth($){if(this.apiKey==null)return;return d([{"X-Api-Key":this.apiKey}])}async bearerAuth($){if(this.authToken==null)return;return d([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery($){return Object.entries($).filter(([w,Z])=>typeof Z<"u").map(([w,Z])=>{if(typeof Z==="string"||typeof Z==="number"||typeof Z==="boolean")return`${encodeURIComponent(w)}=${encodeURIComponent(Z)}`;if(Z===null)return`${encodeURIComponent(w)}=`;throw new y(`Cannot stringify type ${typeof Z}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${b$}`}defaultIdempotencyKey(){return`stainless-node-retry-${q5()}`}makeStatusError($,w,Z,W){return Z0.generate($,w,Z,W)}buildURL($,w,Z){let W=!F(this,v5,"m",sJ).call(this)&&Z||this.baseURL,X=KJ($)?new URL($):new URL(W+(W.endsWith("/")&&$.startsWith("/")?$.slice(1):$)),Y=this.defaultQuery();if(!NJ(Y))w={...Y,...w};if(typeof w==="object"&&w&&!Array.isArray(w))X.search=this.stringifyQuery(w);return X.toString()}_calculateNonstreamingTimeout($){if(3600*$/128000>600)throw new y("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600000}async prepareOptions($){}async prepareRequest($,{url:w,options:Z}){}get($,w){return this.methodRequest("get",$,w)}post($,w){return this.methodRequest("post",$,w)}patch($,w){return this.methodRequest("patch",$,w)}put($,w){return this.methodRequest("put",$,w)}delete($,w){return this.methodRequest("delete",$,w)}methodRequest($,w,Z){return this.request(Promise.resolve(Z).then((W)=>{return{method:$,path:w,...W}}))}request($,w=null){return new G1(this,this.makeRequest($,w,void 0))}async makeRequest($,w,Z){let W=await $,X=W.maxRetries??this.maxRetries;if(w==null)w=X;await this.prepareOptions(W);let{req:Y,url:G,timeout:J}=await this.buildRequest(W,{retryCount:X-w});await this.prepareRequest(Y,{url:G,options:W});let Q="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),z=Z===void 0?"":`, retryOf: ${Z}`,M=Date.now();if(J0(this).debug(`[${Q}] sending request`,z$({retryOfRequestLogID:Z,method:W.method,url:G,options:W,headers:Y.headers})),W.signal?.aborted)throw new B0;let T=new AbortController,K=await this.fetchWithTimeout(G,Y,J,T).catch(ow),N=Date.now();if(K instanceof globalThis.Error){let q=`retrying, ${w} attempts remaining`;if(W.signal?.aborted)throw new B0;let U=Q$(K)||/timed? ?out/i.test(String(K)+("cause"in K?String(K.cause):""));if(w)return J0(this).info(`[${Q}] connection ${U?"timed out":"failed"} - ${q}`),J0(this).debug(`[${Q}] connection ${U?"timed out":"failed"} (${q})`,z$({retryOfRequestLogID:Z,url:G,durationMs:N-M,message:K.message})),this.retryRequest(W,w,Z??Q);if(J0(this).info(`[${Q}] connection ${U?"timed out":"failed"} - error; no more retries left`),J0(this).debug(`[${Q}] connection ${U?"timed out":"failed"} (error; no more retries left)`,z$({retryOfRequestLogID:Z,url:G,durationMs:N-M,message:K.message})),U)throw new ew;throw new Y1({cause:K})}let B=[...K.headers.entries()].filter(([q])=>q==="request-id").map(([q,U])=>", "+q+": "+JSON.stringify(U)).join(""),P=`[${Q}${z}${B}] ${Y.method} ${G} ${K.ok?"succeeded":"failed"} with status ${K.status} in ${N-M}ms`;if(!K.ok){let q=await this.shouldRetry(K);if(w&&q){let u=`retrying, ${w} attempts remaining`;return await LJ(K.body),J0(this).info(`${P} - ${u}`),J0(this).debug(`[${Q}] response error (${u})`,z$({retryOfRequestLogID:Z,url:K.url,status:K.status,headers:K.headers,durationMs:N-M})),this.retryRequest(W,w,Z??Q,K.headers)}let U=q?"error; no more retries left":"error; not retryable";J0(this).info(`${P} - ${U}`);let O=await K.text().catch((u)=>ow(u).message),f=y8(O),C=f?void 0:O;throw J0(this).debug(`[${Q}] response error (${U})`,z$({retryOfRequestLogID:Z,url:K.url,status:K.status,headers:K.headers,message:C,durationMs:Date.now()-M})),this.makeStatusError(K.status,f,C,K.headers)}return J0(this).info(P),J0(this).debug(`[${Q}] response start`,z$({retryOfRequestLogID:Z,url:K.url,status:K.status,headers:K.headers,durationMs:N-M})),{response:K,options:W,controller:T,requestLogID:Q,retryOfRequestLogID:Z,startTime:M}}getAPIList($,w,Z){return this.requestAPIList(w,{method:"get",path:$,...Z})}requestAPIList($,w){let Z=this.makeRequest(w,null,void 0);return new u8(this,Z,$)}async fetchWithTimeout($,w,Z,W){let{signal:X,method:Y,...G}=w||{};if(X)X.addEventListener("abort",()=>W.abort());let J=setTimeout(()=>W.abort(),Z),Q=globalThis.ReadableStream&&G.body instanceof globalThis.ReadableStream||typeof G.body==="object"&&G.body!==null&&Symbol.asyncIterator in G.body,z={signal:W.signal,...Q?{duplex:"half"}:{},method:"GET",...G};if(Y)z.method=Y.toUpperCase();try{return await this.fetch.call(void 0,$,z)}finally{clearTimeout(J)}}async shouldRetry($){let w=$.headers.get("x-should-retry");if(w==="true")return!0;if(w==="false")return!1;if($.status===408)return!0;if($.status===409)return!0;if($.status===429)return!0;if($.status>=500)return!0;return!1}async retryRequest($,w,Z,W){let X,Y=W?.get("retry-after-ms");if(Y){let J=parseFloat(Y);if(!Number.isNaN(J))X=J}let G=W?.get("retry-after");if(G&&!X){let J=parseFloat(G);if(!Number.isNaN(J))X=J*1000;else X=Date.parse(G)-Date.now()}if(!(X&&0<=X&&X<60000)){let J=$.maxRetries??this.maxRetries;X=this.calculateDefaultRetryTimeoutMillis(w,J)}return await PJ(X),this.makeRequest($,w-1,Z)}calculateDefaultRetryTimeoutMillis($,w){let X=w-$,Y=Math.min(0.5*Math.pow(2,X),8),G=1-Math.random()*0.25;return Y*G*1000}calculateNonstreamingTimeout($,w){if(3600000*$/128000>600000||w!=null&&$>w)throw new y("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 600000}async buildRequest($,{retryCount:w=0}={}){let Z={...$},{method:W,path:X,query:Y,defaultBaseURL:G}=Z,J=this.buildURL(X,Y,G);if("timeout"in Z)VJ("timeout",Z.timeout);Z.timeout=Z.timeout??this.timeout;let{bodyHeaders:Q,body:z}=this.buildBody({options:Z}),M=await this.buildHeaders({options:$,method:W,bodyHeaders:Q,retryCount:w});return{req:{method:W,headers:M,...Z.signal&&{signal:Z.signal},...globalThis.ReadableStream&&z instanceof globalThis.ReadableStream&&{duplex:"half"},...z&&{body:z},...this.fetchOptions??{},...Z.fetchOptions??{}},url:J,timeout:Z.timeout}}async buildHeaders({options:$,method:w,bodyHeaders:Z,retryCount:W}){let X={};if(this.idempotencyHeader&&w!=="get"){if(!$.idempotencyKey)$.idempotencyKey=this.defaultIdempotencyKey();X[this.idempotencyHeader]=$.idempotencyKey}let Y=d([X,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(W),...$.timeout?{"X-Stainless-Timeout":String(Math.trunc($.timeout/1000))}:{},...OJ(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders($),this._options.defaultHeaders,Z,$.headers]);return this.validateHeaders(Y),Y.values}buildBody({options:{body:$,headers:w}}){if(!$)return{bodyHeaders:void 0,body:void 0};let Z=d([w]);if(ArrayBuffer.isView($)||$ instanceof ArrayBuffer||$ instanceof DataView||typeof $==="string"&&Z.values.has("content-type")||globalThis.Blob&&$ instanceof globalThis.Blob||$ instanceof FormData||$ instanceof URLSearchParams||globalThis.ReadableStream&&$ instanceof globalThis.ReadableStream)return{bodyHeaders:void 0,body:$};else if(typeof $==="object"&&((Symbol.asyncIterator in $)||(Symbol.iterator in $)&&("next"in $)&&typeof $.next==="function"))return{bodyHeaders:void 0,body:b8($)};else return F(this,Z6,"f").call(this,{body:$,headers:Z})}}u5=s,Z6=new WeakMap,v5=new WeakSet,sJ=function(){return this.baseURL!=="https://api.anthropic.com"};s.Anthropic=u5;s.HUMAN_PROMPT=aJ;s.AI_PROMPT=oJ;s.DEFAULT_TIMEOUT=600000;s.AnthropicError=y;s.APIError=Z0;s.APIConnectionError=Y1;s.APIConnectionTimeoutError=ew;s.APIUserAbortError=B0;s.NotFoundError=W9;s.ConflictError=X9;s.RateLimitError=G9;s.BadRequestError=$9;s.AuthenticationError=w9;s.InternalServerError=J9;s.PermissionDeniedError=Z9;s.UnprocessableEntityError=Y9;s.toFile=h8;class N$ extends s{constructor(){super(...arguments);this.completions=new n1(this),this.messages=new Q1(this),this.models=new r1(this),this.beta=new T$(this)}}N$.Completions=n1;N$.Messages=Q1;N$.Models=r1;N$.Beta=T$;class h5{client;constructor($){this.client=new N$({...$,maxRetries:0})}async*stream($){let{system:w,messages:Z}=FF($.messages),W=this.client.messages.stream({model:$.model,system:w,messages:Z,max_tokens:$.maxOutputTokens,...$.tools.length?{tools:$.tools.map((Y)=>({name:Y.name,description:Y.description,input_schema:Y.inputSchema}))}:{}},$.signal?{signal:$.signal}:void 0),X=new Map;for await(let Y of W)if(Y.type==="content_block_start"&&Y.content_block.type==="tool_use")X.set(Y.index,""),yield{type:"tool_call_start",index:Y.index,callId:Y.content_block.id,name:Y.content_block.name};else if(Y.type==="content_block_delta"&&Y.delta.type==="text_delta")yield{type:"text_delta",text:Y.delta.text};else if(Y.type==="content_block_delta"&&Y.delta.type==="input_json_delta")X.set(Y.index,(X.get(Y.index)??"")+Y.delta.partial_json),yield{type:"tool_call_delta",index:Y.index,argumentsDelta:Y.delta.partial_json};else if(Y.type==="content_block_stop"&&X.has(Y.index))yield{type:"tool_call_end",index:Y.index};else if(Y.type==="message_start")yield{type:"usage",usage:{inputTokens:Y.message.usage.input_tokens,outputTokens:Y.message.usage.output_tokens}};else if(Y.type==="message_delta")yield{type:"usage",usage:{inputTokens:0,outputTokens:Y.usage.output_tokens}};yield{type:"done"}}}function FF($){let w=$.filter((W)=>W.role==="system").map((W)=>W.content).join(`
|
|
87
|
+
`);this.baseURL=X.baseURL,this.timeout=X.timeout??h5.DEFAULT_TIMEOUT,this.logger=X.logger??console;let Y="warn";this.logLevel=Y,this.logLevel=D5(X.logLevel,"ClientOptions.logLevel",this)??D5(C9("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??Y,this.fetchOptions=X.fetchOptions,this.maxRetries=X.maxRetries??2,this.fetch=X.fetch??fJ(),I(this,Z6,AJ,"f"),this._options=X,this.apiKey=w,this.authToken=Z}withOptions($){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...$})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:$,nulls:w}){if(this.apiKey&&$.get("x-api-key"))return;if(w.has("x-api-key"))return;if(this.authToken&&$.get("authorization"))return;if(w.has("authorization"))return;throw Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}async authHeaders($){return d([await this.apiKeyAuth($),await this.bearerAuth($)])}async apiKeyAuth($){if(this.apiKey==null)return;return d([{"X-Api-Key":this.apiKey}])}async bearerAuth($){if(this.authToken==null)return;return d([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery($){return Object.entries($).filter(([w,Z])=>typeof Z<"u").map(([w,Z])=>{if(typeof Z==="string"||typeof Z==="number"||typeof Z==="boolean")return`${encodeURIComponent(w)}=${encodeURIComponent(Z)}`;if(Z===null)return`${encodeURIComponent(w)}=`;throw new y(`Cannot stringify type ${typeof Z}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${b$}`}defaultIdempotencyKey(){return`stainless-node-retry-${U5()}`}makeStatusError($,w,Z,W){return Z0.generate($,w,Z,W)}buildURL($,w,Z){let W=!F(this,u5,"m",eJ).call(this)&&Z||this.baseURL,X=VJ($)?new URL($):new URL(W+(W.endsWith("/")&&$.startsWith("/")?$.slice(1):$)),Y=this.defaultQuery();if(!PJ(Y))w={...Y,...w};if(typeof w==="object"&&w&&!Array.isArray(w))X.search=this.stringifyQuery(w);return X.toString()}_calculateNonstreamingTimeout($){if(3600*$/128000>600)throw new y("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600000}async prepareOptions($){}async prepareRequest($,{url:w,options:Z}){}get($,w){return this.methodRequest("get",$,w)}post($,w){return this.methodRequest("post",$,w)}patch($,w){return this.methodRequest("patch",$,w)}put($,w){return this.methodRequest("put",$,w)}delete($,w){return this.methodRequest("delete",$,w)}methodRequest($,w,Z){return this.request(Promise.resolve(Z).then((W)=>{return{method:$,path:w,...W}}))}request($,w=null){return new G1(this,this.makeRequest($,w,void 0))}async makeRequest($,w,Z){let W=await $,X=W.maxRetries??this.maxRetries;if(w==null)w=X;await this.prepareOptions(W);let{req:Y,url:G,timeout:J}=await this.buildRequest(W,{retryCount:X-w});await this.prepareRequest(Y,{url:G,options:W});let Q="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),z=Z===void 0?"":`, retryOf: ${Z}`,M=Date.now();if(J0(this).debug(`[${Q}] sending request`,M$({retryOfRequestLogID:Z,method:W.method,url:G,options:W,headers:Y.headers})),W.signal?.aborted)throw new B0;let T=new AbortController,N=await this.fetchWithTimeout(G,Y,J,T).catch(ow),K=Date.now();if(N instanceof globalThis.Error){let q=`retrying, ${w} attempts remaining`;if(W.signal?.aborted)throw new B0;let U=z$(N)||/timed? ?out/i.test(String(N)+("cause"in N?String(N.cause):""));if(w)return J0(this).info(`[${Q}] connection ${U?"timed out":"failed"} - ${q}`),J0(this).debug(`[${Q}] connection ${U?"timed out":"failed"} (${q})`,M$({retryOfRequestLogID:Z,url:G,durationMs:K-M,message:N.message})),this.retryRequest(W,w,Z??Q);if(J0(this).info(`[${Q}] connection ${U?"timed out":"failed"} - error; no more retries left`),J0(this).debug(`[${Q}] connection ${U?"timed out":"failed"} (error; no more retries left)`,M$({retryOfRequestLogID:Z,url:G,durationMs:K-M,message:N.message})),U)throw new ew;throw new Y1({cause:N})}let B=[...N.headers.entries()].filter(([q])=>q==="request-id").map(([q,U])=>", "+q+": "+JSON.stringify(U)).join(""),P=`[${Q}${z}${B}] ${Y.method} ${G} ${N.ok?"succeeded":"failed"} with status ${N.status} in ${K-M}ms`;if(!N.ok){let q=await this.shouldRetry(N);if(w&&q){let u=`retrying, ${w} attempts remaining`;return await kJ(N.body),J0(this).info(`${P} - ${u}`),J0(this).debug(`[${Q}] response error (${u})`,M$({retryOfRequestLogID:Z,url:N.url,status:N.status,headers:N.headers,durationMs:K-M})),this.retryRequest(W,w,Z??Q,N.headers)}let U=q?"error; no more retries left":"error; not retryable";J0(this).info(`${P} - ${U}`);let O=await N.text().catch((u)=>ow(u).message),f=y8(O),C=f?void 0:O;throw J0(this).debug(`[${Q}] response error (${U})`,M$({retryOfRequestLogID:Z,url:N.url,status:N.status,headers:N.headers,message:C,durationMs:Date.now()-M})),this.makeStatusError(N.status,f,C,N.headers)}return J0(this).info(P),J0(this).debug(`[${Q}] response start`,M$({retryOfRequestLogID:Z,url:N.url,status:N.status,headers:N.headers,durationMs:K-M})),{response:N,options:W,controller:T,requestLogID:Q,retryOfRequestLogID:Z,startTime:M}}getAPIList($,w,Z){return this.requestAPIList(w,{method:"get",path:$,...Z})}requestAPIList($,w){let Z=this.makeRequest(w,null,void 0);return new u8(this,Z,$)}async fetchWithTimeout($,w,Z,W){let{signal:X,method:Y,...G}=w||{};if(X)X.addEventListener("abort",()=>W.abort());let J=setTimeout(()=>W.abort(),Z),Q=globalThis.ReadableStream&&G.body instanceof globalThis.ReadableStream||typeof G.body==="object"&&G.body!==null&&Symbol.asyncIterator in G.body,z={signal:W.signal,...Q?{duplex:"half"}:{},method:"GET",...G};if(Y)z.method=Y.toUpperCase();try{return await this.fetch.call(void 0,$,z)}finally{clearTimeout(J)}}async shouldRetry($){let w=$.headers.get("x-should-retry");if(w==="true")return!0;if(w==="false")return!1;if($.status===408)return!0;if($.status===409)return!0;if($.status===429)return!0;if($.status>=500)return!0;return!1}async retryRequest($,w,Z,W){let X,Y=W?.get("retry-after-ms");if(Y){let J=parseFloat(Y);if(!Number.isNaN(J))X=J}let G=W?.get("retry-after");if(G&&!X){let J=parseFloat(G);if(!Number.isNaN(J))X=J*1000;else X=Date.parse(G)-Date.now()}if(!(X&&0<=X&&X<60000)){let J=$.maxRetries??this.maxRetries;X=this.calculateDefaultRetryTimeoutMillis(w,J)}return await HJ(X),this.makeRequest($,w-1,Z)}calculateDefaultRetryTimeoutMillis($,w){let X=w-$,Y=Math.min(0.5*Math.pow(2,X),8),G=1-Math.random()*0.25;return Y*G*1000}calculateNonstreamingTimeout($,w){if(3600000*$/128000>600000||w!=null&&$>w)throw new y("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 600000}async buildRequest($,{retryCount:w=0}={}){let Z={...$},{method:W,path:X,query:Y,defaultBaseURL:G}=Z,J=this.buildURL(X,Y,G);if("timeout"in Z)UJ("timeout",Z.timeout);Z.timeout=Z.timeout??this.timeout;let{bodyHeaders:Q,body:z}=this.buildBody({options:Z}),M=await this.buildHeaders({options:$,method:W,bodyHeaders:Q,retryCount:w});return{req:{method:W,headers:M,...Z.signal&&{signal:Z.signal},...globalThis.ReadableStream&&z instanceof globalThis.ReadableStream&&{duplex:"half"},...z&&{body:z},...this.fetchOptions??{},...Z.fetchOptions??{}},url:J,timeout:Z.timeout}}async buildHeaders({options:$,method:w,bodyHeaders:Z,retryCount:W}){let X={};if(this.idempotencyHeader&&w!=="get"){if(!$.idempotencyKey)$.idempotencyKey=this.defaultIdempotencyKey();X[this.idempotencyHeader]=$.idempotencyKey}let Y=d([X,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(W),...$.timeout?{"X-Stainless-Timeout":String(Math.trunc($.timeout/1000))}:{},...DJ(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders($),this._options.defaultHeaders,Z,$.headers]);return this.validateHeaders(Y),Y.values}buildBody({options:{body:$,headers:w}}){if(!$)return{bodyHeaders:void 0,body:void 0};let Z=d([w]);if(ArrayBuffer.isView($)||$ instanceof ArrayBuffer||$ instanceof DataView||typeof $==="string"&&Z.values.has("content-type")||globalThis.Blob&&$ instanceof globalThis.Blob||$ instanceof FormData||$ instanceof URLSearchParams||globalThis.ReadableStream&&$ instanceof globalThis.ReadableStream)return{bodyHeaders:void 0,body:$};else if(typeof $==="object"&&((Symbol.asyncIterator in $)||(Symbol.iterator in $)&&("next"in $)&&typeof $.next==="function"))return{bodyHeaders:void 0,body:b8($)};else return F(this,Z6,"f").call(this,{body:$,headers:Z})}}h5=s,Z6=new WeakMap,u5=new WeakSet,eJ=function(){return this.baseURL!=="https://api.anthropic.com"};s.Anthropic=h5;s.HUMAN_PROMPT=$Q;s.AI_PROMPT=wQ;s.DEFAULT_TIMEOUT=600000;s.AnthropicError=y;s.APIError=Z0;s.APIConnectionError=Y1;s.APIConnectionTimeoutError=ew;s.APIUserAbortError=B0;s.NotFoundError=W9;s.ConflictError=X9;s.RateLimitError=G9;s.BadRequestError=$9;s.AuthenticationError=w9;s.InternalServerError=J9;s.PermissionDeniedError=Z9;s.UnprocessableEntityError=Y9;s.toFile=h8;class B$ extends s{constructor(){super(...arguments);this.completions=new n1(this),this.messages=new Q1(this),this.models=new r1(this),this.beta=new N$(this)}}B$.Completions=n1;B$.Messages=Q1;B$.Models=r1;B$.Beta=N$;class i5{client;constructor($){this.client=new B$({...$,maxRetries:0})}async*stream($){let{system:w,messages:Z}=LF($.messages),W=this.client.messages.stream({model:$.model,system:w,messages:Z,max_tokens:$.maxOutputTokens,...$.tools.length?{tools:$.tools.map((Y)=>({name:Y.name,description:Y.description,input_schema:Y.inputSchema}))}:{}},$.signal?{signal:$.signal}:void 0),X=new Map;for await(let Y of W)if(Y.type==="content_block_start"&&Y.content_block.type==="tool_use")X.set(Y.index,""),yield{type:"tool_call_start",index:Y.index,callId:Y.content_block.id,name:Y.content_block.name};else if(Y.type==="content_block_delta"&&Y.delta.type==="text_delta")yield{type:"text_delta",text:Y.delta.text};else if(Y.type==="content_block_delta"&&Y.delta.type==="input_json_delta")X.set(Y.index,(X.get(Y.index)??"")+Y.delta.partial_json),yield{type:"tool_call_delta",index:Y.index,argumentsDelta:Y.delta.partial_json};else if(Y.type==="content_block_stop"&&X.has(Y.index))yield{type:"tool_call_end",index:Y.index};else if(Y.type==="message_start")yield{type:"usage",usage:{inputTokens:Y.message.usage.input_tokens,outputTokens:Y.message.usage.output_tokens}};else if(Y.type==="message_delta")yield{type:"usage",usage:{inputTokens:0,outputTokens:Y.usage.output_tokens}};yield{type:"done"}}}function LF($){let w=$.filter((W)=>W.role==="system").map((W)=>W.content).join(`
|
|
88
88
|
|
|
89
|
-
`),Z=[];for(let W of $){if(W.role==="system")continue;if(W.role==="user")Z.push({role:"user",content:W.content});else if(W.role==="assistant")Z.push({role:"assistant",content:[...W.content?[{type:"text",text:W.content}]:[],...W.toolCalls.map((X)=>({type:"tool_use",id:X.callId,name:X.name,input:X.input}))]});else{let X={type:"tool_result",tool_use_id:W.callId,content:W.content,is_error:W.isError},Y=Z.at(-1);if(Y?.role==="user"&&Array.isArray(Y.content))Y.content=[...Y.content,X];else Z.push({role:"user",content:[X]})}}return{system:w,messages:Z}}function R($,w,Z,W,X){if(W==="m")throw TypeError("Private method is not writable");if(W==="a"&&!X)throw TypeError("Private accessor was defined without a setter");if(typeof w==="function"?$!==w||!X:!w.has($))throw TypeError("Cannot write private member to an object whose class did not declare it");return W==="a"?X.call($,Z):X?X.value=Z:w.set($,Z),Z}function V($,w,Z,W){if(Z==="a"&&!W)throw TypeError("Private accessor was defined without a getter");if(typeof w==="function"?$!==w||!W:!w.has($))throw TypeError("Cannot read private member from an object whose class did not declare it");return Z==="m"?W:Z==="a"?W.call($):W?W.value:w.get($)}var i5=function(){let{crypto:$}=globalThis;if($?.randomUUID)return i5=$.randomUUID.bind($),$.randomUUID();let w=new Uint8Array(1),Z=$?()=>$.getRandomValues(w)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(W)=>(+W^Z()&15>>+W/4).toString(16))};function j9($){return typeof $==="object"&&$!==null&&(("name"in $)&&$.name==="AbortError"||("message"in $)&&String($.message).includes("FetchRequestCanceledException"))}var I9=($)=>{if($ instanceof Error)return $;if(typeof $==="object"&&$!==null){try{if(Object.prototype.toString.call($)==="[object Error]"){let w=Error($.message,$.cause?{cause:$.cause}:{});if($.stack)w.stack=$.stack;if($.cause&&!w.cause)w.cause=$.cause;if($.name)w.name=$.name;return w}}catch{}try{return Error(JSON.stringify($))}catch{}}return Error($)};class k extends Error{}class w0 extends k{constructor($,w,Z,W){super(`${w0.makeMessage($,w,Z)}`);this.status=$,this.headers=W,this.requestID=W?.get("x-request-id"),this.error=w;let X=w;this.code=X?.code,this.param=X?.param,this.type=X?.type}static makeMessage($,w,Z){let W=w?.message?typeof w.message==="string"?w.message:JSON.stringify(w.message):w?JSON.stringify(w):Z;if($&&W)return`${$} ${W}`;if($)return`${$} status code (no body)`;if(W)return W;return"(no status code or body)"}static generate($,w,Z,W){if(!$||!W)return new z1({message:Z,cause:I9(w)});let X=w?.error;if($===400)return new y9($,X,Z,W);if($===401)return new b9($,X,Z,W);if($===403)return new x9($,X,Z,W);if($===404)return new _9($,X,Z,W);if($===409)return new g9($,X,Z,W);if($===422)return new v9($,X,Z,W);if($===429)return new u9($,X,Z,W);if($>=500)return new h9($,X,Z,W);return new w0($,X,Z,W)}}class X0 extends w0{constructor({message:$}={}){super(void 0,void 0,$||"Request was aborted.",void 0)}}class z1 extends w0{constructor({message:$,cause:w}){super(void 0,void 0,$||"Connection error.",void 0);if(w)this.cause=w}}class M1 extends z1{constructor({message:$}={}){super({message:$??"Request timed out."})}}class y9 extends w0{}class b9 extends w0{}class x9 extends w0{}class _9 extends w0{}class g9 extends w0{}class v9 extends w0{}class u9 extends w0{}class h9 extends w0{}class i9 extends k{constructor(){super("Could not parse response content as the length limit was reached")}}class m9 extends k{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class B$ extends Error{constructor($){super($)}}var EF=/^[a-z][a-z0-9+.-]*:/i,eJ=($)=>{return EF.test($)},P0=($)=>(P0=Array.isArray,P0($)),m5=P0;function l5($){if(typeof $!=="object")return{};return $??{}}function $Q($){if(!$)return!0;for(let w in $)return!1;return!0}function wQ($,w){return Object.prototype.hasOwnProperty.call($,w)}function l9($){return $!=null&&typeof $==="object"&&!Array.isArray($)}var ZQ=($,w)=>{if(typeof w!=="number"||!Number.isInteger(w))throw new k(`${$} must be an integer`);if(w<0)throw new k(`${$} must be a positive integer`);return w};var WQ=($)=>{try{return JSON.parse($)}catch(w){return}};var a0=($)=>new Promise((w)=>setTimeout(w,$));var v$="5.23.2";var JQ=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"};function LF(){if(typeof Deno<"u"&&Deno.build!=null)return"deno";if(typeof EdgeRuntime<"u")return"edge";if(Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]")return"node";return"unknown"}var DF=()=>{let $=LF();if($==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":v$,"X-Stainless-OS":YQ(Deno.build.os),"X-Stainless-Arch":XQ(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version==="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":v$,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if($==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":v$,"X-Stainless-OS":YQ(globalThis.process.platform??"unknown"),"X-Stainless-Arch":XQ(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let w=fF();if(w)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":v$,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${w.browser}`,"X-Stainless-Runtime-Version":w.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":v$,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function fF(){if(typeof navigator>"u"||!navigator)return null;let $=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:w,pattern:Z}of $){let W=Z.exec(navigator.userAgent);if(W){let X=W[1]||0,Y=W[2]||0,G=W[3]||0;return{browser:w,version:`${X}.${Y}.${G}`}}}return null}var XQ=($)=>{if($==="x32")return"x32";if($==="x86_64"||$==="x64")return"x64";if($==="arm")return"arm";if($==="aarch64"||$==="arm64")return"arm64";if($)return`other:${$}`;return"unknown"},YQ=($)=>{if($=$.toLowerCase(),$.includes("ios"))return"iOS";if($==="android")return"Android";if($==="darwin")return"MacOS";if($==="win32")return"Windows";if($==="freebsd")return"FreeBSD";if($==="openbsd")return"OpenBSD";if($==="linux")return"Linux";if($)return`Other:${$}`;return"Unknown"},GQ,QQ=()=>{return GQ??(GQ=DF())};function zQ(){if(typeof fetch<"u")return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function c5(...$){let w=globalThis.ReadableStream;if(typeof w>"u")throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new w(...$)}function W6($){let w=Symbol.asyncIterator in $?$[Symbol.asyncIterator]():$[Symbol.iterator]();return c5({start(){},async pull(Z){let{done:W,value:X}=await w.next();if(W)Z.close();else Z.enqueue(X)},async cancel(){await w.return?.()}})}function d5($){if($[Symbol.asyncIterator])return $;let w=$.getReader();return{async next(){try{let Z=await w.read();if(Z?.done)w.releaseLock();return Z}catch(Z){throw w.releaseLock(),Z}},async return(){let Z=w.cancel();return w.releaseLock(),await Z,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function MQ($){if($===null||typeof $!=="object")return;if($[Symbol.asyncIterator]){await $[Symbol.asyncIterator]().return?.();return}let w=$.getReader(),Z=w.cancel();w.releaseLock(),await Z}var TQ=({headers:$,body:w})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(w)}};var X6="RFC3986",p5=($)=>String($),Y6={RFC1738:($)=>String($).replace(/%20/g,"+"),RFC3986:p5},n5="RFC1738";var G6=($,w)=>(G6=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),G6($,w)),o0=(()=>{let $=[];for(let w=0;w<256;++w)$.push("%"+((w<16?"0":"")+w.toString(16)).toUpperCase());return $})();var t5=1024,KQ=($,w,Z,W,X)=>{if($.length===0)return $;let Y=$;if(typeof $==="symbol")Y=Symbol.prototype.toString.call($);else if(typeof $!=="string")Y=String($);if(Z==="iso-8859-1")return escape(Y).replace(/%u[0-9a-f]{4}/gi,function(J){return"%26%23"+parseInt(J.slice(2),16)+"%3B"});let G="";for(let J=0;J<Y.length;J+=t5){let Q=Y.length>=t5?Y.slice(J,J+t5):Y,z=[];for(let M=0;M<Q.length;++M){let T=Q.charCodeAt(M);if(T===45||T===46||T===95||T===126||T>=48&&T<=57||T>=65&&T<=90||T>=97&&T<=122||X===n5&&(T===40||T===41)){z[z.length]=Q.charAt(M);continue}if(T<128){z[z.length]=o0[T];continue}if(T<2048){z[z.length]=o0[192|T>>6]+o0[128|T&63];continue}if(T<55296||T>=57344){z[z.length]=o0[224|T>>12]+o0[128|T>>6&63]+o0[128|T&63];continue}M+=1,T=65536+((T&1023)<<10|Q.charCodeAt(M)&1023),z[z.length]=o0[240|T>>18]+o0[128|T>>12&63]+o0[128|T>>6&63]+o0[128|T&63]}G+=z.join("")}return G};function NQ($){if(!$||typeof $!=="object")return!1;return!!($.constructor&&$.constructor.isBuffer&&$.constructor.isBuffer($))}function r5($,w){if(P0($)){let Z=[];for(let W=0;W<$.length;W+=1)Z.push(w($[W]));return Z}return w($)}var VQ={brackets($){return String($)+"[]"},comma:"comma",indices($,w){return String($)+"["+w+"]"},repeat($){return String($)}},PQ=function($,w){Array.prototype.push.apply($,P0(w)?w:[w])},BQ,Y0={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:KQ,encodeValuesOnly:!1,format:X6,formatter:p5,indices:!1,serializeDate($){return(BQ??(BQ=Function.prototype.call.bind(Date.prototype.toISOString)))($)},skipNulls:!1,strictNullHandling:!1};function SF($){return typeof $==="string"||typeof $==="number"||typeof $==="boolean"||typeof $==="symbol"||typeof $==="bigint"}var s5={};function qQ($,w,Z,W,X,Y,G,J,Q,z,M,T,K,N,B,P,q,U){let O=$,f=U,C=0,A=!1;while((f=f.get(s5))!==void 0&&!A){let h=f.get($);if(C+=1,typeof h<"u")if(h===C)throw RangeError("Cyclic object value");else A=!0;if(typeof f.get(s5)>"u")C=0}if(typeof z==="function")O=z(w,O);else if(O instanceof Date)O=K?.(O);else if(Z==="comma"&&P0(O))O=r5(O,function(h){if(h instanceof Date)return K?.(h);return h});if(O===null){if(Y)return Q&&!P?Q(w,Y0.encoder,q,"key",N):w;O=""}if(SF(O)||NQ(O)){if(Q){let h=P?w:Q(w,Y0.encoder,q,"key",N);return[B?.(h)+"="+B?.(Q(O,Y0.encoder,q,"value",N))]}return[B?.(w)+"="+B?.(String(O))]}let u=[];if(typeof O>"u")return u;let i;if(Z==="comma"&&P0(O)){if(P&&Q)O=r5(O,Q);i=[{value:O.length>0?O.join(",")||null:void 0}]}else if(P0(z))i=z;else{let h=Object.keys(O);i=M?h.sort(M):h}let r=J?String(w).replace(/\./g,"%2E"):String(w),z0=W&&P0(O)&&O.length===1?r+"[]":r;if(X&&P0(O)&&O.length===0)return z0+"[]";for(let h=0;h<i.length;++h){let q0=i[h],p$=typeof q0==="object"&&typeof q0.value<"u"?q0.value:O[q0];if(G&&p$===null)continue;let w$=T&&J?q0.replace(/\./g,"%2E"):q0,S1=P0(O)?typeof Z==="function"?Z(z0,w$):z0:z0+(T?"."+w$:"["+w$+"]");U.set($,C);let Ew=new WeakMap;Ew.set(s5,U),PQ(u,qQ(p$,S1,Z,W,X,Y,G,J,Z==="comma"&&P&&P0(O)?null:Q,z,M,T,K,N,B,P,q,Ew))}return u}function RF($=Y0){if(typeof $.allowEmptyArrays<"u"&&typeof $.allowEmptyArrays!=="boolean")throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof $.encodeDotInKeys<"u"&&typeof $.encodeDotInKeys!=="boolean")throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if($.encoder!==null&&typeof $.encoder<"u"&&typeof $.encoder!=="function")throw TypeError("Encoder has to be a function.");let w=$.charset||Y0.charset;if(typeof $.charset<"u"&&$.charset!=="utf-8"&&$.charset!=="iso-8859-1")throw TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let Z=X6;if(typeof $.format<"u"){if(!G6(Y6,$.format))throw TypeError("Unknown format option provided.");Z=$.format}let W=Y6[Z],X=Y0.filter;if(typeof $.filter==="function"||P0($.filter))X=$.filter;let Y;if($.arrayFormat&&$.arrayFormat in VQ)Y=$.arrayFormat;else if("indices"in $)Y=$.indices?"indices":"repeat";else Y=Y0.arrayFormat;if("commaRoundTrip"in $&&typeof $.commaRoundTrip!=="boolean")throw TypeError("`commaRoundTrip` must be a boolean, or absent");let G=typeof $.allowDots>"u"?!!$.encodeDotInKeys===!0?!0:Y0.allowDots:!!$.allowDots;return{addQueryPrefix:typeof $.addQueryPrefix==="boolean"?$.addQueryPrefix:Y0.addQueryPrefix,allowDots:G,allowEmptyArrays:typeof $.allowEmptyArrays==="boolean"?!!$.allowEmptyArrays:Y0.allowEmptyArrays,arrayFormat:Y,charset:w,charsetSentinel:typeof $.charsetSentinel==="boolean"?$.charsetSentinel:Y0.charsetSentinel,commaRoundTrip:!!$.commaRoundTrip,delimiter:typeof $.delimiter>"u"?Y0.delimiter:$.delimiter,encode:typeof $.encode==="boolean"?$.encode:Y0.encode,encodeDotInKeys:typeof $.encodeDotInKeys==="boolean"?$.encodeDotInKeys:Y0.encodeDotInKeys,encoder:typeof $.encoder==="function"?$.encoder:Y0.encoder,encodeValuesOnly:typeof $.encodeValuesOnly==="boolean"?$.encodeValuesOnly:Y0.encodeValuesOnly,filter:X,format:Z,formatter:W,serializeDate:typeof $.serializeDate==="function"?$.serializeDate:Y0.serializeDate,skipNulls:typeof $.skipNulls==="boolean"?$.skipNulls:Y0.skipNulls,sort:typeof $.sort==="function"?$.sort:null,strictNullHandling:typeof $.strictNullHandling==="boolean"?$.strictNullHandling:Y0.strictNullHandling}}function a5($,w={}){let Z=$,W=RF(w),X,Y;if(typeof W.filter==="function")Y=W.filter,Z=Y("",Z);else if(P0(W.filter))Y=W.filter,X=Y;let G=[];if(typeof Z!=="object"||Z===null)return"";let J=VQ[W.arrayFormat],Q=J==="comma"&&W.commaRoundTrip;if(!X)X=Object.keys(Z);if(W.sort)X.sort(W.sort);let z=new WeakMap;for(let K=0;K<X.length;++K){let N=X[K];if(W.skipNulls&&Z[N]===null)continue;PQ(G,qQ(Z[N],N,J,Q,W.allowEmptyArrays,W.strictNullHandling,W.skipNulls,W.encodeDotInKeys,W.encode?W.encoder:null,W.filter,W.sort,W.allowDots,W.serializeDate,W.format,W.formatter,W.encodeValuesOnly,W.charset,z))}let M=G.join(W.delimiter),T=W.addQueryPrefix===!0?"?":"";if(W.charsetSentinel)if(W.charset==="iso-8859-1")T+="utf8=%26%2310003%3B&";else T+="utf8=%E2%9C%93&";return M.length>0?T+M:""}function FQ($){let w=0;for(let X of $)w+=X.length;let Z=new Uint8Array(w),W=0;for(let X of $)Z.set(X,W),W+=X.length;return Z}var UQ;function s1($){let w;return(UQ??(w=new globalThis.TextEncoder,UQ=w.encode.bind(w)))($)}var HQ;function o5($){let w;return(HQ??(w=new globalThis.TextDecoder,HQ=w.decode.bind(w)))($)}var j0,I0;class a1{constructor(){j0.set(this,void 0),I0.set(this,void 0),R(this,j0,new Uint8Array,"f"),R(this,I0,null,"f")}decode($){if($==null)return[];let w=$ instanceof ArrayBuffer?new Uint8Array($):typeof $==="string"?s1($):$;R(this,j0,FQ([V(this,j0,"f"),w]),"f");let Z=[],W;while((W=jF(V(this,j0,"f"),V(this,I0,"f")))!=null){if(W.carriage&&V(this,I0,"f")==null){R(this,I0,W.index,"f");continue}if(V(this,I0,"f")!=null&&(W.index!==V(this,I0,"f")+1||W.carriage)){Z.push(o5(V(this,j0,"f").subarray(0,V(this,I0,"f")-1))),R(this,j0,V(this,j0,"f").subarray(V(this,I0,"f")),"f"),R(this,I0,null,"f");continue}let X=V(this,I0,"f")!==null?W.preceding-1:W.preceding,Y=o5(V(this,j0,"f").subarray(0,X));Z.push(Y),R(this,j0,V(this,j0,"f").subarray(W.index),"f"),R(this,I0,null,"f")}return Z}flush(){if(!V(this,j0,"f").length)return[];return this.decode(`
|
|
89
|
+
`),Z=[];for(let W of $){if(W.role==="system")continue;if(W.role==="user")Z.push({role:"user",content:W.content});else if(W.role==="assistant")Z.push({role:"assistant",content:[...W.content?[{type:"text",text:W.content}]:[],...W.toolCalls.map((X)=>({type:"tool_use",id:X.callId,name:X.name,input:X.input}))]});else{let X={type:"tool_result",tool_use_id:W.callId,content:W.content,is_error:W.isError},Y=Z.at(-1);if(Y?.role==="user"&&Array.isArray(Y.content))Y.content=[...Y.content,X];else Z.push({role:"user",content:[X]})}}return{system:w,messages:Z}}function R($,w,Z,W,X){if(W==="m")throw TypeError("Private method is not writable");if(W==="a"&&!X)throw TypeError("Private accessor was defined without a setter");if(typeof w==="function"?$!==w||!X:!w.has($))throw TypeError("Cannot write private member to an object whose class did not declare it");return W==="a"?X.call($,Z):X?X.value=Z:w.set($,Z),Z}function V($,w,Z,W){if(Z==="a"&&!W)throw TypeError("Private accessor was defined without a getter");if(typeof w==="function"?$!==w||!W:!w.has($))throw TypeError("Cannot read private member from an object whose class did not declare it");return Z==="m"?W:Z==="a"?W.call($):W?W.value:w.get($)}var m5=function(){let{crypto:$}=globalThis;if($?.randomUUID)return m5=$.randomUUID.bind($),$.randomUUID();let w=new Uint8Array(1),Z=$?()=>$.getRandomValues(w)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(W)=>(+W^Z()&15>>+W/4).toString(16))};function j9($){return typeof $==="object"&&$!==null&&(("name"in $)&&$.name==="AbortError"||("message"in $)&&String($.message).includes("FetchRequestCanceledException"))}var I9=($)=>{if($ instanceof Error)return $;if(typeof $==="object"&&$!==null){try{if(Object.prototype.toString.call($)==="[object Error]"){let w=Error($.message,$.cause?{cause:$.cause}:{});if($.stack)w.stack=$.stack;if($.cause&&!w.cause)w.cause=$.cause;if($.name)w.name=$.name;return w}}catch{}try{return Error(JSON.stringify($))}catch{}}return Error($)};class k extends Error{}class w0 extends k{constructor($,w,Z,W){super(`${w0.makeMessage($,w,Z)}`);this.status=$,this.headers=W,this.requestID=W?.get("x-request-id"),this.error=w;let X=w;this.code=X?.code,this.param=X?.param,this.type=X?.type}static makeMessage($,w,Z){let W=w?.message?typeof w.message==="string"?w.message:JSON.stringify(w.message):w?JSON.stringify(w):Z;if($&&W)return`${$} ${W}`;if($)return`${$} status code (no body)`;if(W)return W;return"(no status code or body)"}static generate($,w,Z,W){if(!$||!W)return new z1({message:Z,cause:I9(w)});let X=w?.error;if($===400)return new y9($,X,Z,W);if($===401)return new b9($,X,Z,W);if($===403)return new x9($,X,Z,W);if($===404)return new _9($,X,Z,W);if($===409)return new g9($,X,Z,W);if($===422)return new v9($,X,Z,W);if($===429)return new u9($,X,Z,W);if($>=500)return new h9($,X,Z,W);return new w0($,X,Z,W)}}class X0 extends w0{constructor({message:$}={}){super(void 0,void 0,$||"Request was aborted.",void 0)}}class z1 extends w0{constructor({message:$,cause:w}){super(void 0,void 0,$||"Connection error.",void 0);if(w)this.cause=w}}class M1 extends z1{constructor({message:$}={}){super({message:$??"Request timed out."})}}class y9 extends w0{}class b9 extends w0{}class x9 extends w0{}class _9 extends w0{}class g9 extends w0{}class v9 extends w0{}class u9 extends w0{}class h9 extends w0{}class i9 extends k{constructor(){super("Could not parse response content as the length limit was reached")}}class m9 extends k{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class V$ extends Error{constructor($){super($)}}var fF=/^[a-z][a-z0-9+.-]*:/i,ZQ=($)=>{return fF.test($)},P0=($)=>(P0=Array.isArray,P0($)),l5=P0;function c5($){if(typeof $!=="object")return{};return $??{}}function WQ($){if(!$)return!0;for(let w in $)return!1;return!0}function XQ($,w){return Object.prototype.hasOwnProperty.call($,w)}function l9($){return $!=null&&typeof $==="object"&&!Array.isArray($)}var YQ=($,w)=>{if(typeof w!=="number"||!Number.isInteger(w))throw new k(`${$} must be an integer`);if(w<0)throw new k(`${$} must be a positive integer`);return w};var GQ=($)=>{try{return JSON.parse($)}catch(w){return}};var o0=($)=>new Promise((w)=>setTimeout(w,$));var v$="5.23.2";var MQ=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"};function kF(){if(typeof Deno<"u"&&Deno.build!=null)return"deno";if(typeof EdgeRuntime<"u")return"edge";if(Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]")return"node";return"unknown"}var AF=()=>{let $=kF();if($==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":v$,"X-Stainless-OS":QQ(Deno.build.os),"X-Stainless-Arch":JQ(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version==="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":v$,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if($==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":v$,"X-Stainless-OS":QQ(globalThis.process.platform??"unknown"),"X-Stainless-Arch":JQ(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let w=SF();if(w)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":v$,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${w.browser}`,"X-Stainless-Runtime-Version":w.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":v$,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function SF(){if(typeof navigator>"u"||!navigator)return null;let $=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:w,pattern:Z}of $){let W=Z.exec(navigator.userAgent);if(W){let X=W[1]||0,Y=W[2]||0,G=W[3]||0;return{browser:w,version:`${X}.${Y}.${G}`}}}return null}var JQ=($)=>{if($==="x32")return"x32";if($==="x86_64"||$==="x64")return"x64";if($==="arm")return"arm";if($==="aarch64"||$==="arm64")return"arm64";if($)return`other:${$}`;return"unknown"},QQ=($)=>{if($=$.toLowerCase(),$.includes("ios"))return"iOS";if($==="android")return"Android";if($==="darwin")return"MacOS";if($==="win32")return"Windows";if($==="freebsd")return"FreeBSD";if($==="openbsd")return"OpenBSD";if($==="linux")return"Linux";if($)return`Other:${$}`;return"Unknown"},zQ,TQ=()=>{return zQ??(zQ=AF())};function NQ(){if(typeof fetch<"u")return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function d5(...$){let w=globalThis.ReadableStream;if(typeof w>"u")throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new w(...$)}function W6($){let w=Symbol.asyncIterator in $?$[Symbol.asyncIterator]():$[Symbol.iterator]();return d5({start(){},async pull(Z){let{done:W,value:X}=await w.next();if(W)Z.close();else Z.enqueue(X)},async cancel(){await w.return?.()}})}function p5($){if($[Symbol.asyncIterator])return $;let w=$.getReader();return{async next(){try{let Z=await w.read();if(Z?.done)w.releaseLock();return Z}catch(Z){throw w.releaseLock(),Z}},async return(){let Z=w.cancel();return w.releaseLock(),await Z,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function KQ($){if($===null||typeof $!=="object")return;if($[Symbol.asyncIterator]){await $[Symbol.asyncIterator]().return?.();return}let w=$.getReader(),Z=w.cancel();w.releaseLock(),await Z}var BQ=({headers:$,body:w})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(w)}};var X6="RFC3986",n5=($)=>String($),Y6={RFC1738:($)=>String($).replace(/%20/g,"+"),RFC3986:n5},t5="RFC1738";var G6=($,w)=>(G6=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),G6($,w)),e0=(()=>{let $=[];for(let w=0;w<256;++w)$.push("%"+((w<16?"0":"")+w.toString(16)).toUpperCase());return $})();var r5=1024,VQ=($,w,Z,W,X)=>{if($.length===0)return $;let Y=$;if(typeof $==="symbol")Y=Symbol.prototype.toString.call($);else if(typeof $!=="string")Y=String($);if(Z==="iso-8859-1")return escape(Y).replace(/%u[0-9a-f]{4}/gi,function(J){return"%26%23"+parseInt(J.slice(2),16)+"%3B"});let G="";for(let J=0;J<Y.length;J+=r5){let Q=Y.length>=r5?Y.slice(J,J+r5):Y,z=[];for(let M=0;M<Q.length;++M){let T=Q.charCodeAt(M);if(T===45||T===46||T===95||T===126||T>=48&&T<=57||T>=65&&T<=90||T>=97&&T<=122||X===t5&&(T===40||T===41)){z[z.length]=Q.charAt(M);continue}if(T<128){z[z.length]=e0[T];continue}if(T<2048){z[z.length]=e0[192|T>>6]+e0[128|T&63];continue}if(T<55296||T>=57344){z[z.length]=e0[224|T>>12]+e0[128|T>>6&63]+e0[128|T&63];continue}M+=1,T=65536+((T&1023)<<10|Q.charCodeAt(M)&1023),z[z.length]=e0[240|T>>18]+e0[128|T>>12&63]+e0[128|T>>6&63]+e0[128|T&63]}G+=z.join("")}return G};function PQ($){if(!$||typeof $!=="object")return!1;return!!($.constructor&&$.constructor.isBuffer&&$.constructor.isBuffer($))}function s5($,w){if(P0($)){let Z=[];for(let W=0;W<$.length;W+=1)Z.push(w($[W]));return Z}return w($)}var UQ={brackets($){return String($)+"[]"},comma:"comma",indices($,w){return String($)+"["+w+"]"},repeat($){return String($)}},HQ=function($,w){Array.prototype.push.apply($,P0(w)?w:[w])},qQ,Y0={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:VQ,encodeValuesOnly:!1,format:X6,formatter:n5,indices:!1,serializeDate($){return(qQ??(qQ=Function.prototype.call.bind(Date.prototype.toISOString)))($)},skipNulls:!1,strictNullHandling:!1};function jF($){return typeof $==="string"||typeof $==="number"||typeof $==="boolean"||typeof $==="symbol"||typeof $==="bigint"}var a5={};function FQ($,w,Z,W,X,Y,G,J,Q,z,M,T,N,K,B,P,q,U){let O=$,f=U,C=0,A=!1;while((f=f.get(a5))!==void 0&&!A){let h=f.get($);if(C+=1,typeof h<"u")if(h===C)throw RangeError("Cyclic object value");else A=!0;if(typeof f.get(a5)>"u")C=0}if(typeof z==="function")O=z(w,O);else if(O instanceof Date)O=N?.(O);else if(Z==="comma"&&P0(O))O=s5(O,function(h){if(h instanceof Date)return N?.(h);return h});if(O===null){if(Y)return Q&&!P?Q(w,Y0.encoder,q,"key",K):w;O=""}if(jF(O)||PQ(O)){if(Q){let h=P?w:Q(w,Y0.encoder,q,"key",K);return[B?.(h)+"="+B?.(Q(O,Y0.encoder,q,"value",K))]}return[B?.(w)+"="+B?.(String(O))]}let u=[];if(typeof O>"u")return u;let i;if(Z==="comma"&&P0(O)){if(P&&Q)O=s5(O,Q);i=[{value:O.length>0?O.join(",")||null:void 0}]}else if(P0(z))i=z;else{let h=Object.keys(O);i=M?h.sort(M):h}let r=J?String(w).replace(/\./g,"%2E"):String(w),z0=W&&P0(O)&&O.length===1?r+"[]":r;if(X&&P0(O)&&O.length===0)return z0+"[]";for(let h=0;h<i.length;++h){let q0=i[h],p$=typeof q0==="object"&&typeof q0.value<"u"?q0.value:O[q0];if(G&&p$===null)continue;let Z$=T&&J?q0.replace(/\./g,"%2E"):q0,S1=P0(O)?typeof Z==="function"?Z(z0,Z$):z0:z0+(T?"."+Z$:"["+Z$+"]");U.set($,C);let Ew=new WeakMap;Ew.set(a5,U),HQ(u,FQ(p$,S1,Z,W,X,Y,G,J,Z==="comma"&&P&&P0(O)?null:Q,z,M,T,N,K,B,P,q,Ew))}return u}function IF($=Y0){if(typeof $.allowEmptyArrays<"u"&&typeof $.allowEmptyArrays!=="boolean")throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof $.encodeDotInKeys<"u"&&typeof $.encodeDotInKeys!=="boolean")throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if($.encoder!==null&&typeof $.encoder<"u"&&typeof $.encoder!=="function")throw TypeError("Encoder has to be a function.");let w=$.charset||Y0.charset;if(typeof $.charset<"u"&&$.charset!=="utf-8"&&$.charset!=="iso-8859-1")throw TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let Z=X6;if(typeof $.format<"u"){if(!G6(Y6,$.format))throw TypeError("Unknown format option provided.");Z=$.format}let W=Y6[Z],X=Y0.filter;if(typeof $.filter==="function"||P0($.filter))X=$.filter;let Y;if($.arrayFormat&&$.arrayFormat in UQ)Y=$.arrayFormat;else if("indices"in $)Y=$.indices?"indices":"repeat";else Y=Y0.arrayFormat;if("commaRoundTrip"in $&&typeof $.commaRoundTrip!=="boolean")throw TypeError("`commaRoundTrip` must be a boolean, or absent");let G=typeof $.allowDots>"u"?!!$.encodeDotInKeys===!0?!0:Y0.allowDots:!!$.allowDots;return{addQueryPrefix:typeof $.addQueryPrefix==="boolean"?$.addQueryPrefix:Y0.addQueryPrefix,allowDots:G,allowEmptyArrays:typeof $.allowEmptyArrays==="boolean"?!!$.allowEmptyArrays:Y0.allowEmptyArrays,arrayFormat:Y,charset:w,charsetSentinel:typeof $.charsetSentinel==="boolean"?$.charsetSentinel:Y0.charsetSentinel,commaRoundTrip:!!$.commaRoundTrip,delimiter:typeof $.delimiter>"u"?Y0.delimiter:$.delimiter,encode:typeof $.encode==="boolean"?$.encode:Y0.encode,encodeDotInKeys:typeof $.encodeDotInKeys==="boolean"?$.encodeDotInKeys:Y0.encodeDotInKeys,encoder:typeof $.encoder==="function"?$.encoder:Y0.encoder,encodeValuesOnly:typeof $.encodeValuesOnly==="boolean"?$.encodeValuesOnly:Y0.encodeValuesOnly,filter:X,format:Z,formatter:W,serializeDate:typeof $.serializeDate==="function"?$.serializeDate:Y0.serializeDate,skipNulls:typeof $.skipNulls==="boolean"?$.skipNulls:Y0.skipNulls,sort:typeof $.sort==="function"?$.sort:null,strictNullHandling:typeof $.strictNullHandling==="boolean"?$.strictNullHandling:Y0.strictNullHandling}}function o5($,w={}){let Z=$,W=IF(w),X,Y;if(typeof W.filter==="function")Y=W.filter,Z=Y("",Z);else if(P0(W.filter))Y=W.filter,X=Y;let G=[];if(typeof Z!=="object"||Z===null)return"";let J=UQ[W.arrayFormat],Q=J==="comma"&&W.commaRoundTrip;if(!X)X=Object.keys(Z);if(W.sort)X.sort(W.sort);let z=new WeakMap;for(let N=0;N<X.length;++N){let K=X[N];if(W.skipNulls&&Z[K]===null)continue;HQ(G,FQ(Z[K],K,J,Q,W.allowEmptyArrays,W.strictNullHandling,W.skipNulls,W.encodeDotInKeys,W.encode?W.encoder:null,W.filter,W.sort,W.allowDots,W.serializeDate,W.format,W.formatter,W.encodeValuesOnly,W.charset,z))}let M=G.join(W.delimiter),T=W.addQueryPrefix===!0?"?":"";if(W.charsetSentinel)if(W.charset==="iso-8859-1")T+="utf8=%26%2310003%3B&";else T+="utf8=%E2%9C%93&";return M.length>0?T+M:""}function LQ($){let w=0;for(let X of $)w+=X.length;let Z=new Uint8Array(w),W=0;for(let X of $)Z.set(X,W),W+=X.length;return Z}var OQ;function s1($){let w;return(OQ??(w=new globalThis.TextEncoder,OQ=w.encode.bind(w)))($)}var EQ;function e5($){let w;return(EQ??(w=new globalThis.TextDecoder,EQ=w.decode.bind(w)))($)}var j0,I0;class a1{constructor(){j0.set(this,void 0),I0.set(this,void 0),R(this,j0,new Uint8Array,"f"),R(this,I0,null,"f")}decode($){if($==null)return[];let w=$ instanceof ArrayBuffer?new Uint8Array($):typeof $==="string"?s1($):$;R(this,j0,LQ([V(this,j0,"f"),w]),"f");let Z=[],W;while((W=bF(V(this,j0,"f"),V(this,I0,"f")))!=null){if(W.carriage&&V(this,I0,"f")==null){R(this,I0,W.index,"f");continue}if(V(this,I0,"f")!=null&&(W.index!==V(this,I0,"f")+1||W.carriage)){Z.push(e5(V(this,j0,"f").subarray(0,V(this,I0,"f")-1))),R(this,j0,V(this,j0,"f").subarray(V(this,I0,"f")),"f"),R(this,I0,null,"f");continue}let X=V(this,I0,"f")!==null?W.preceding-1:W.preceding,Y=e5(V(this,j0,"f").subarray(0,X));Z.push(Y),R(this,j0,V(this,j0,"f").subarray(W.index),"f"),R(this,I0,null,"f")}return Z}flush(){if(!V(this,j0,"f").length)return[];return this.decode(`
|
|
90
90
|
`)}}j0=new WeakMap,I0=new WeakMap;a1.NEWLINE_CHARS=new Set([`
|
|
91
|
-
`,"\r"]);a1.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function
|
|
92
|
-
`);Z.enqueue(Y)}catch(W){Z.error(W)}},async cancel(){await w.return?.()}})}}async function*
|
|
93
|
-
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],X}if(this.chunks.push($),$.startsWith(":"))return null;let[w,Z,W]=
|
|
94
|
-
${Y.map((
|
|
91
|
+
`,"\r"]);a1.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function bF($,w){for(let X=w??0;X<$.length;X++){if($[X]===10)return{preceding:X,index:X+1,carriage:!1};if($[X]===13)return{preceding:X,index:X+1,carriage:!0}}return null}function DQ($){for(let W=0;W<$.length-1;W++){if($[W]===10&&$[W+1]===10)return W+2;if($[W]===13&&$[W+1]===13)return W+2;if($[W]===13&&$[W+1]===10&&W+3<$.length&&$[W+2]===13&&$[W+3]===10)return W+4}return-1}var Q6={off:0,error:200,warn:300,info:400,debug:500},$W=($,w,Z)=>{if(!$)return;if(XQ(Q6,$))return $;$0(Z).warn(`${w} was set to ${JSON.stringify($)}, expected one of ${JSON.stringify(Object.keys(Q6))}`);return};function c9(){}function J6($,w,Z){if(!w||Q6[$]>Q6[Z])return c9;else return w[$].bind(w)}var xF={error:c9,warn:c9,info:c9,debug:c9},fQ=new WeakMap;function $0($){let w=$.logger,Z=$.logLevel??"off";if(!w)return xF;let W=fQ.get(w);if(W&&W[0]===Z)return W[1];let X={error:J6("error",w,Z),warn:J6("warn",w,Z),info:J6("info",w,Z),debug:J6("debug",w,Z)};return fQ.set(w,[Z,X]),X}var P$=($)=>{if($.options)$.options={...$.options},delete $.options.headers;if($.headers)$.headers=Object.fromEntries(($.headers instanceof Headers?[...$.headers]:Object.entries($.headers)).map(([w,Z])=>[w,w.toLowerCase()==="authorization"||w.toLowerCase()==="cookie"||w.toLowerCase()==="set-cookie"?"***":Z]));if("retryOfRequestLogID"in $){if($.retryOfRequestLogID)$.retryOf=$.retryOfRequestLogID;delete $.retryOfRequestLogID}return $};var d9;class y0{constructor($,w,Z){this.iterator=$,d9.set(this,void 0),this.controller=w,R(this,d9,Z,"f")}static fromSSEResponse($,w,Z){let W=!1,X=Z?$0(Z):console;async function*Y(){if(W)throw new k("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");W=!0;let G=!1;try{for await(let J of _F($,w)){if(G)continue;if(J.data.startsWith("[DONE]")){G=!0;continue}if(J.event===null||!J.event.startsWith("thread.")){let Q;try{Q=JSON.parse(J.data)}catch(z){throw X.error("Could not parse message into JSON:",J.data),X.error("From chunk:",J.raw),z}if(Q&&Q.error)throw new w0(void 0,Q.error,void 0,$.headers);yield Q}else{let Q;try{Q=JSON.parse(J.data)}catch(z){throw console.error("Could not parse message into JSON:",J.data),console.error("From chunk:",J.raw),z}if(J.event=="error")throw new w0(void 0,Q.error,Q.message,void 0);yield{event:J.event,data:Q}}}G=!0}catch(J){if(j9(J))return;throw J}finally{if(!G)w.abort()}}return new y0(Y,w,Z)}static fromReadableStream($,w,Z){let W=!1;async function*X(){let G=new a1,J=p5($);for await(let Q of J)for(let z of G.decode(Q))yield z;for(let Q of G.flush())yield Q}async function*Y(){if(W)throw new k("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");W=!0;let G=!1;try{for await(let J of X()){if(G)continue;if(J)yield JSON.parse(J)}G=!0}catch(J){if(j9(J))return;throw J}finally{if(!G)w.abort()}}return new y0(Y,w,Z)}[(d9=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let $=[],w=[],Z=this.iterator(),W=(X)=>{return{next:()=>{if(X.length===0){let Y=Z.next();$.push(Y),w.push(Y)}return X.shift()}}};return[new y0(()=>W($),this.controller,V(this,d9,"f")),new y0(()=>W(w),this.controller,V(this,d9,"f"))]}toReadableStream(){let $=this,w;return d5({async start(){w=$[Symbol.asyncIterator]()},async pull(Z){try{let{value:W,done:X}=await w.next();if(X)return Z.close();let Y=s1(JSON.stringify(W)+`
|
|
92
|
+
`);Z.enqueue(Y)}catch(W){Z.error(W)}},async cancel(){await w.return?.()}})}}async function*_F($,w){if(!$.body){if(w.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new k("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new k("Attempted to iterate over a response with no body")}let Z=new kQ,W=new a1,X=p5($.body);for await(let Y of gF(X))for(let G of W.decode(Y)){let J=Z.decode(G);if(J)yield J}for(let Y of W.flush()){let G=Z.decode(Y);if(G)yield G}}async function*gF($){let w=new Uint8Array;for await(let Z of $){if(Z==null)continue;let W=Z instanceof ArrayBuffer?new Uint8Array(Z):typeof Z==="string"?s1(Z):Z,X=new Uint8Array(w.length+W.length);X.set(w),X.set(W,w.length),w=X;let Y;while((Y=DQ(w))!==-1)yield w.slice(0,Y),w=w.slice(Y)}if(w.length>0)yield w}class kQ{constructor(){this.event=null,this.data=[],this.chunks=[]}decode($){if($.endsWith("\r"))$=$.substring(0,$.length-1);if(!$){if(!this.event&&!this.data.length)return null;let X={event:this.event,data:this.data.join(`
|
|
93
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],X}if(this.chunks.push($),$.startsWith(":"))return null;let[w,Z,W]=vF($,":");if(W.startsWith(" "))W=W.substring(1);if(w==="event")this.event=W;else if(w==="data")this.data.push(W);return null}}function vF($,w){let Z=$.indexOf(w);if(Z!==-1)return[$.substring(0,Z),w,$.substring(Z+w.length)];return[$,"",""]}async function z6($,w){let{response:Z,requestLogID:W,retryOfRequestLogID:X,startTime:Y}=w,G=await(async()=>{if(w.options.stream){if($0($).debug("response",Z.status,Z.url,Z.headers,Z.body),w.options.__streamClass)return w.options.__streamClass.fromSSEResponse(Z,w.controller,$);return y0.fromSSEResponse(Z,w.controller,$)}if(Z.status===204)return null;if(w.options.__binaryResponse)return Z;let Q=Z.headers.get("content-type")?.split(";")[0]?.trim();if(Q?.includes("application/json")||Q?.endsWith("+json")){let T=await Z.json();return wW(T,Z)}return await Z.text()})();return $0($).debug(`[${W}] response parsed`,P$({retryOfRequestLogID:X,url:Z.url,status:Z.status,body:G,durationMs:Date.now()-Y})),G}function wW($,w){if(!$||typeof $!=="object"||Array.isArray($))return $;return Object.defineProperty($,"_request_id",{value:w.headers.get("x-request-id"),enumerable:!1})}var p9;class T1 extends Promise{constructor($,w,Z=z6){super((W)=>{W(null)});this.responsePromise=w,this.parseResponse=Z,p9.set(this,void 0),R(this,p9,$,"f")}_thenUnwrap($){return new T1(V(this,p9,"f"),this.responsePromise,async(w,Z)=>wW($(await this.parseResponse(w,Z),Z),Z.response))}asResponse(){return this.responsePromise.then(($)=>$.response)}async withResponse(){let[$,w]=await Promise.all([this.parse(),this.asResponse()]);return{data:$,response:w,request_id:w.headers.get("x-request-id")}}parse(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then(($)=>this.parseResponse(V(this,p9,"f"),$));return this.parsedPromise}then($,w){return this.parse().then($,w)}catch($){return this.parse().catch($)}finally($){return this.parse().finally($)}}p9=new WeakMap;var M6;class T6{constructor($,w,Z,W){M6.set(this,void 0),R(this,M6,$,"f"),this.options=W,this.response=w,this.body=Z}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageRequestOptions()!=null}async getNextPage(){let $=this.nextPageRequestOptions();if(!$)throw new k("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await V(this,M6,"f").requestAPIList(this.constructor,$)}async*iterPages(){let $=this;yield $;while($.hasNextPage())$=await $.getNextPage(),yield $}async*[(M6=new WeakMap,Symbol.asyncIterator)](){for await(let $ of this.iterPages())for(let w of $.getPaginatedItems())yield w}}class N6 extends T1{constructor($,w,Z){super($,w,async(W,X)=>new Z(W,X.response,await z6(W,X),X.options))}async*[Symbol.asyncIterator](){let $=await this;for await(let w of $)yield w}}class q$ extends T6{constructor($,w,Z,W){super($,w,Z,W);this.data=Z.data||[],this.object=Z.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class g extends T6{constructor($,w,Z,W){super($,w,Z,W);this.data=Z.data||[],this.has_more=Z.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){let $=this.getPaginatedItems(),w=$[$.length-1]?.id;if(!w)return null;return{...this.options,query:{...c5(this.options.query),after:w}}}}class ZW extends T6{constructor($,w,Z,W){super($,w,Z,W);this.data=Z.data||[],this.has_more=Z.has_more||!1,this.last_id=Z.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){let $=this.last_id;if(!$)return null;return{...this.options,query:{...c5(this.options.query),after:$}}}}var XW=()=>{if(typeof File>"u"){let{process:$}=globalThis,w=typeof $?.versions?.node==="string"&&parseInt($.versions.node.split("."))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(w?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function o1($,w,Z){return XW(),new File($,w??"unknown_file",Z)}function n9($){return(typeof $==="object"&&$!==null&&(("name"in $)&&$.name&&String($.name)||("url"in $)&&$.url&&String($.url)||("filename"in $)&&$.filename&&String($.filename)||("path"in $)&&$.path&&String($.path))||"").split(/[\\/]/).pop()||void 0}var YW=($)=>$!=null&&typeof $==="object"&&typeof $[Symbol.asyncIterator]==="function";var b0=async($,w)=>{return{...$,body:await iF($.body,w)}},AQ=new WeakMap;function hF($){let w=typeof $==="function"?$:$.fetch,Z=AQ.get(w);if(Z)return Z;let W=(async()=>{try{let X="Response"in w?w.Response:(await w("data:,")).constructor,Y=new FormData;if(Y.toString()===await new X(Y).text())return!1;return!0}catch{return!0}})();return AQ.set(w,W),W}var iF=async($,w)=>{if(!await hF(w))throw TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let Z=new FormData;return await Promise.all(Object.entries($||{}).map(([W,X])=>WW(Z,W,X))),Z},mF=($)=>$ instanceof Blob&&("name"in $);var WW=async($,w,Z)=>{if(Z===void 0)return;if(Z==null)throw TypeError(`Received null for "${w}"; to pass null in FormData, you must use the string 'null'`);if(typeof Z==="string"||typeof Z==="number"||typeof Z==="boolean")$.append(w,String(Z));else if(Z instanceof Response)$.append(w,o1([await Z.blob()],n9(Z)));else if(YW(Z))$.append(w,o1([await new Response(W6(Z)).blob()],n9(Z)));else if(mF(Z))$.append(w,Z,n9(Z));else if(Array.isArray(Z))await Promise.all(Z.map((W)=>WW($,w+"[]",W)));else if(typeof Z==="object")await Promise.all(Object.entries(Z).map(([W,X])=>WW($,`${w}[${W}]`,X)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${Z} instead`)};var SQ=($)=>$!=null&&typeof $==="object"&&typeof $.size==="number"&&typeof $.type==="string"&&typeof $.text==="function"&&typeof $.slice==="function"&&typeof $.arrayBuffer==="function",lF=($)=>$!=null&&typeof $==="object"&&typeof $.name==="string"&&typeof $.lastModified==="number"&&SQ($),cF=($)=>$!=null&&typeof $==="object"&&typeof $.url==="string"&&typeof $.blob==="function";async function K6($,w,Z){if(XW(),$=await $,lF($)){if($ instanceof File)return $;return o1([await $.arrayBuffer()],$.name)}if(cF($)){let X=await $.blob();return w||(w=new URL($.url).pathname.split(/[\\/]/).pop()),o1(await GW(X),w,Z)}let W=await GW($);if(w||(w=n9($)),!Z?.type){let X=W.find((Y)=>typeof Y==="object"&&("type"in Y)&&Y.type);if(typeof X==="string")Z={...Z,type:X}}return o1(W,w,Z)}async function GW($){let w=[];if(typeof $==="string"||ArrayBuffer.isView($)||$ instanceof ArrayBuffer)w.push($);else if(SQ($))w.push($ instanceof Blob?$:await $.arrayBuffer());else if(YW($))for await(let Z of $)w.push(...await GW(Z));else{let Z=$?.constructor?.name;throw Error(`Unexpected data type: ${typeof $}${Z?`; constructor: ${Z}`:""}${dF($)}`)}return w}function dF($){if(typeof $!=="object"||$===null)return"";return`; props: [${Object.getOwnPropertyNames($).map((Z)=>`"${Z}"`).join(", ")}]`}class E{constructor($){this._client=$}}function CQ($){return $.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var RQ=Object.freeze(Object.create(null)),nF=($=CQ)=>function(Z,...W){if(Z.length===1)return Z[0];let X=!1,Y=[],G=Z.reduce((M,T,N)=>{if(/[?#]/.test(T))X=!0;let K=W[N],B=(X?encodeURIComponent:$)(""+K);if(N!==W.length&&(K==null||typeof K==="object"&&K.toString===Object.getPrototypeOf(Object.getPrototypeOf(K.hasOwnProperty??RQ)??RQ)?.toString))B=K+"",Y.push({start:M.length+T.length,length:B.length,error:`Value of type ${Object.prototype.toString.call(K).slice(8,-1)} is not a valid path parameter`});return M+T+(N===W.length?"":B)},""),J=G.split(/[?#]/,1)[0],Q=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,z;while((z=Q.exec(J))!==null)Y.push({start:z.index,length:z[0].length,error:`Value "${z[0]}" can't be safely passed as a path parameter`});if(Y.sort((M,T)=>M.start-T.start),Y.length>0){let M=0,T=Y.reduce((N,K)=>{let B=" ".repeat(K.start-M),P="^".repeat(K.length);return M=K.start+K.length,N+B+P},"");throw new k(`Path parameters result in path with invalid segments:
|
|
94
|
+
${Y.map((N)=>N.error).join(`
|
|
95
95
|
`)}
|
|
96
96
|
${G}
|
|
97
|
-
${T}`)}return G},H=cF(AQ);class e1 extends E{list($,w={},Z){return this._client.getAPIList(H`/chat/completions/${$}/messages`,g,{query:w,...Z})}}function t9($){return $!==void 0&&"function"in $&&$.function!==void 0}function r9($){return $?.$brand==="auto-parseable-response-format"}function K1($){return $?.$brand==="auto-parseable-tool"}function SQ($,w){if(!w||!GW(w))return{...$,choices:$.choices.map((Z)=>{return CQ(Z.message.tool_calls),{...Z,message:{...Z.message,parsed:null,...Z.message.tool_calls?{tool_calls:Z.message.tool_calls}:void 0}}})};return s9($,w)}function s9($,w){let Z=$.choices.map((W)=>{if(W.finish_reason==="length")throw new i9;if(W.finish_reason==="content_filter")throw new m9;return CQ(W.message.tool_calls),{...W,message:{...W.message,...W.message.tool_calls?{tool_calls:W.message.tool_calls?.map((X)=>tF(w,X))??void 0}:void 0,parsed:W.message.content&&!W.message.refusal?nF(w,W.message.content):null}}});return{...$,choices:Z}}function nF($,w){if($.response_format?.type!=="json_schema")return null;if($.response_format?.type==="json_schema"){if("$parseRaw"in $.response_format)return $.response_format.$parseRaw(w);return JSON.parse(w)}return null}function tF($,w){let Z=$.tools?.find((W)=>t9(W)&&W.function?.name===w.function.name);return{...w,function:{...w.function,parsed_arguments:K1(Z)?Z.$parseRaw(w.function.arguments):Z?.function.strict?JSON.parse(w.function.arguments):null}}}function RQ($,w){if(!$||!("tools"in $)||!$.tools)return!1;let Z=$.tools?.find((W)=>t9(W)&&W.function?.name===w.function.name);return t9(Z)&&(K1(Z)||Z?.function.strict||!1)}function GW($){if(r9($.response_format))return!0;return $.tools?.some((w)=>K1(w)||w.type==="function"&&w.function.strict===!0)??!1}function CQ($){for(let w of $||[])if(w.type!=="function")throw new k(`Currently only \`function\` tool calls are supported; Received \`${w.type}\``)}function jQ($){for(let w of $??[]){if(w.type!=="function")throw new k(`Currently only \`function\` tool types support auto-parsing; Received \`${w.type}\``);if(w.function.strict!==!0)throw new k(`The \`${w.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var $w=($)=>{return $?.role==="assistant"},JW=($)=>{return $?.role==="tool"};var QW,B6,V6,a9,o9,P6,e9,q$,$4,q6,U6,ww,IQ;class N1{constructor(){QW.add(this),this.controller=new AbortController,B6.set(this,void 0),V6.set(this,()=>{}),a9.set(this,()=>{}),o9.set(this,void 0),P6.set(this,()=>{}),e9.set(this,()=>{}),q$.set(this,{}),$4.set(this,!1),q6.set(this,!1),U6.set(this,!1),ww.set(this,!1),R(this,B6,new Promise(($,w)=>{R(this,V6,$,"f"),R(this,a9,w,"f")}),"f"),R(this,o9,new Promise(($,w)=>{R(this,P6,$,"f"),R(this,e9,w,"f")}),"f"),V(this,B6,"f").catch(()=>{}),V(this,o9,"f").catch(()=>{})}_run($){setTimeout(()=>{$().then(()=>{this._emitFinal(),this._emit("end")},V(this,QW,"m",IQ).bind(this))},0)}_connected(){if(this.ended)return;V(this,V6,"f").call(this),this._emit("connect")}get ended(){return V(this,$4,"f")}get errored(){return V(this,q6,"f")}get aborted(){return V(this,U6,"f")}abort(){this.controller.abort()}on($,w){return(V(this,q$,"f")[$]||(V(this,q$,"f")[$]=[])).push({listener:w}),this}off($,w){let Z=V(this,q$,"f")[$];if(!Z)return this;let W=Z.findIndex((X)=>X.listener===w);if(W>=0)Z.splice(W,1);return this}once($,w){return(V(this,q$,"f")[$]||(V(this,q$,"f")[$]=[])).push({listener:w,once:!0}),this}emitted($){return new Promise((w,Z)=>{if(R(this,ww,!0,"f"),$!=="error")this.once("error",Z);this.once($,w)})}async done(){R(this,ww,!0,"f"),await V(this,o9,"f")}_emit($,...w){if(V(this,$4,"f"))return;if($==="end")R(this,$4,!0,"f"),V(this,P6,"f").call(this);let Z=V(this,q$,"f")[$];if(Z)V(this,q$,"f")[$]=Z.filter((W)=>!W.once),Z.forEach(({listener:W})=>W(...w));if($==="abort"){let W=w[0];if(!V(this,ww,"f")&&!Z?.length)Promise.reject(W);V(this,a9,"f").call(this,W),V(this,e9,"f").call(this,W),this._emit("end");return}if($==="error"){let W=w[0];if(!V(this,ww,"f")&&!Z?.length)Promise.reject(W);V(this,a9,"f").call(this,W),V(this,e9,"f").call(this,W),this._emit("end")}}_emitFinal(){}}B6=new WeakMap,V6=new WeakMap,a9=new WeakMap,o9=new WeakMap,P6=new WeakMap,e9=new WeakMap,q$=new WeakMap,$4=new WeakMap,q6=new WeakMap,U6=new WeakMap,ww=new WeakMap,QW=new WeakSet,IQ=function(w){if(R(this,q6,!0,"f"),w instanceof Error&&w.name==="AbortError")w=new X0;if(w instanceof X0)return R(this,U6,!0,"f"),this._emit("abort",w);if(w instanceof k)return this._emit("error",w);if(w instanceof Error){let Z=new k(w.message);return Z.cause=w,this._emit("error",Z)}return this._emit("error",new k(String(w)))};function yQ($){return typeof $.parse==="function"}var F0,zW,H6,MW,TW,KW,bQ,xQ,rF=10;class w4 extends N1{constructor(){super(...arguments);F0.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion($){this._chatCompletions.push($),this._emit("chatCompletion",$);let w=$.choices[0]?.message;if(w)this._addMessage(w);return $}_addMessage($,w=!0){if(!("content"in $))$.content=null;if(this.messages.push($),w){if(this._emit("message",$),JW($)&&$.content)this._emit("functionToolCallResult",$.content);else if($w($)&&$.tool_calls){for(let Z of $.tool_calls)if(Z.type==="function")this._emit("functionToolCall",Z.function)}}}async finalChatCompletion(){await this.done();let $=this._chatCompletions[this._chatCompletions.length-1];if(!$)throw new k("stream ended without producing a ChatCompletion");return $}async finalContent(){return await this.done(),V(this,F0,"m",zW).call(this)}async finalMessage(){return await this.done(),V(this,F0,"m",H6).call(this)}async finalFunctionToolCall(){return await this.done(),V(this,F0,"m",MW).call(this)}async finalFunctionToolCallResult(){return await this.done(),V(this,F0,"m",TW).call(this)}async totalUsage(){return await this.done(),V(this,F0,"m",KW).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let $=this._chatCompletions[this._chatCompletions.length-1];if($)this._emit("finalChatCompletion",$);let w=V(this,F0,"m",H6).call(this);if(w)this._emit("finalMessage",w);let Z=V(this,F0,"m",zW).call(this);if(Z)this._emit("finalContent",Z);let W=V(this,F0,"m",MW).call(this);if(W)this._emit("finalFunctionToolCall",W);let X=V(this,F0,"m",TW).call(this);if(X!=null)this._emit("finalFunctionToolCallResult",X);if(this._chatCompletions.some((Y)=>Y.usage))this._emit("totalUsage",V(this,F0,"m",KW).call(this))}async _createChatCompletion($,w,Z){let W=Z?.signal;if(W){if(W.aborted)this.controller.abort();W.addEventListener("abort",()=>this.controller.abort())}V(this,F0,"m",bQ).call(this,w);let X=await $.chat.completions.create({...w,stream:!1},{...Z,signal:this.controller.signal});return this._connected(),this._addChatCompletion(s9(X,w))}async _runChatCompletion($,w,Z){for(let W of w.messages)this._addMessage(W,!1);return await this._createChatCompletion($,w,Z)}async _runTools($,w,Z){let{tool_choice:X="auto",stream:Y,...G}=w,J=typeof X!=="string"&&X.type==="function"&&X?.function?.name,{maxChatCompletions:Q=rF}=Z||{},z=w.tools.map((K)=>{if(K1(K)){if(!K.$callback)throw new k("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:K.$callback,name:K.function.name,description:K.function.description||"",parameters:K.function.parameters,parse:K.$parseRaw,strict:!0}}}return K}),M={};for(let K of z)if(K.type==="function")M[K.function.name||K.function.function.name]=K.function;let T="tools"in w?z.map((K)=>K.type==="function"?{type:"function",function:{name:K.function.name||K.function.function.name,parameters:K.function.parameters,description:K.function.description,strict:K.function.strict}}:K):void 0;for(let K of w.messages)this._addMessage(K,!1);for(let K=0;K<Q;++K){let B=(await this._createChatCompletion($,{...G,tool_choice:X,tools:T,messages:[...this.messages]},Z)).choices[0]?.message;if(!B)throw new k("missing message in ChatCompletion response");if(!B.tool_calls?.length)return;for(let P of B.tool_calls){if(P.type!=="function")continue;let q=P.id,{name:U,arguments:O}=P.function,f=M[U];if(!f){let i=`Invalid tool_call: ${JSON.stringify(U)}. Available options are: ${Object.keys(M).map((r)=>JSON.stringify(r)).join(", ")}. Please try again`;this._addMessage({role:"tool",tool_call_id:q,content:i});continue}else if(J&&J!==U){let i=`Invalid tool_call: ${JSON.stringify(U)}. ${JSON.stringify(J)} requested. Please try again`;this._addMessage({role:"tool",tool_call_id:q,content:i});continue}let C;try{C=yQ(f)?await f.parse(O):O}catch(i){let r=i instanceof Error?i.message:String(i);this._addMessage({role:"tool",tool_call_id:q,content:r});continue}let A=await f.function(C,this),u=V(this,F0,"m",xQ).call(this,A);if(this._addMessage({role:"tool",tool_call_id:q,content:u}),J)return}}return}}F0=new WeakSet,zW=function(){return V(this,F0,"m",H6).call(this).content??null},H6=function(){let w=this.messages.length;while(w-- >0){let Z=this.messages[w];if($w(Z))return{...Z,content:Z.content??null,refusal:Z.refusal??null}}throw new k("stream ended without producing a ChatCompletionMessage with role=assistant")},MW=function(){for(let w=this.messages.length-1;w>=0;w--){let Z=this.messages[w];if($w(Z)&&Z?.tool_calls?.length)return Z.tool_calls.filter((W)=>W.type==="function").at(-1)?.function}return},TW=function(){for(let w=this.messages.length-1;w>=0;w--){let Z=this.messages[w];if(JW(Z)&&Z.content!=null&&typeof Z.content==="string"&&this.messages.some((W)=>W.role==="assistant"&&W.tool_calls?.some((X)=>X.type==="function"&&X.id===Z.tool_call_id)))return Z.content}return},KW=function(){let w={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:Z}of this._chatCompletions)if(Z)w.completion_tokens+=Z.completion_tokens,w.prompt_tokens+=Z.prompt_tokens,w.total_tokens+=Z.total_tokens;return w},bQ=function(w){if(w.n!=null&&w.n>1)throw new k("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},xQ=function(w){return typeof w==="string"?w:w===void 0?"undefined":JSON.stringify(w)};class Z4 extends w4{static runTools($,w,Z){let W=new Z4,X={...Z,headers:{...Z?.headers,"X-Stainless-Helper-Method":"runTools"}};return W._run(()=>W._runTools($,w,X)),W}_addMessage($,w=!0){if(super._addMessage($,w),$w($)&&$.content)this._emit("content",$.content)}}var Q0={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511};class _Q extends Error{}class gQ extends Error{}function sF($,w=Q0.ALL){if(typeof $!=="string")throw TypeError(`expecting str, got ${typeof $}`);if(!$.trim())throw Error(`${$} is empty`);return aF($.trim(),w)}var aF=($,w)=>{let Z=$.length,W=0,X=(K)=>{throw new _Q(`${K} at position ${W}`)},Y=(K)=>{throw new gQ(`${K} at position ${W}`)},G=()=>{if(T(),W>=Z)X("Unexpected end of input");if($[W]==='"')return J();if($[W]==="{")return Q();if($[W]==="[")return z();if($.substring(W,W+4)==="null"||Q0.NULL&w&&Z-W<4&&"null".startsWith($.substring(W)))return W+=4,null;if($.substring(W,W+4)==="true"||Q0.BOOL&w&&Z-W<4&&"true".startsWith($.substring(W)))return W+=4,!0;if($.substring(W,W+5)==="false"||Q0.BOOL&w&&Z-W<5&&"false".startsWith($.substring(W)))return W+=5,!1;if($.substring(W,W+8)==="Infinity"||Q0.INFINITY&w&&Z-W<8&&"Infinity".startsWith($.substring(W)))return W+=8,1/0;if($.substring(W,W+9)==="-Infinity"||Q0.MINUS_INFINITY&w&&1<Z-W&&Z-W<9&&"-Infinity".startsWith($.substring(W)))return W+=9,-1/0;if($.substring(W,W+3)==="NaN"||Q0.NAN&w&&Z-W<3&&"NaN".startsWith($.substring(W)))return W+=3,NaN;return M()},J=()=>{let K=W,N=!1;W++;while(W<Z&&($[W]!=='"'||N&&$[W-1]==="\\"))N=$[W]==="\\"?!N:!1,W++;if($.charAt(W)=='"')try{return JSON.parse($.substring(K,++W-Number(N)))}catch(B){Y(String(B))}else if(Q0.STR&w)try{return JSON.parse($.substring(K,W-Number(N))+'"')}catch(B){return JSON.parse($.substring(K,$.lastIndexOf("\\"))+'"')}X("Unterminated string literal")},Q=()=>{W++,T();let K={};try{while($[W]!=="}"){if(T(),W>=Z&&Q0.OBJ&w)return K;let N=J();T(),W++;try{let B=G();Object.defineProperty(K,N,{value:B,writable:!0,enumerable:!0,configurable:!0})}catch(B){if(Q0.OBJ&w)return K;else throw B}if(T(),$[W]===",")W++}}catch(N){if(Q0.OBJ&w)return K;else X("Expected '}' at end of object")}return W++,K},z=()=>{W++;let K=[];try{while($[W]!=="]")if(K.push(G()),T(),$[W]===",")W++}catch(N){if(Q0.ARR&w)return K;X("Expected ']' at end of array")}return W++,K},M=()=>{if(W===0){if($==="-"&&Q0.NUM&w)X("Not sure what '-' is");try{return JSON.parse($)}catch(N){if(Q0.NUM&w)try{if($[$.length-1]===".")return JSON.parse($.substring(0,$.lastIndexOf(".")));return JSON.parse($.substring(0,$.lastIndexOf("e")))}catch(B){}Y(String(N))}}let K=W;if($[W]==="-")W++;while($[W]&&!",]}".includes($[W]))W++;if(W==Z&&!(Q0.NUM&w))X("Unterminated number literal");try{return JSON.parse($.substring(K,W))}catch(N){if($.substring(K,W)==="-"&&Q0.NUM&w)X("Not sure what '-' is");try{return JSON.parse($.substring(K,$.lastIndexOf("e")))}catch(B){Y(String(B))}}},T=()=>{while(W<Z&&`
|
|
98
|
-
\r `.includes($[W]))W++};return G()},
|
|
97
|
+
${T}`)}return G},H=nF(CQ);class e1 extends E{list($,w={},Z){return this._client.getAPIList(H`/chat/completions/${$}/messages`,g,{query:w,...Z})}}function t9($){return $!==void 0&&"function"in $&&$.function!==void 0}function r9($){return $?.$brand==="auto-parseable-response-format"}function N1($){return $?.$brand==="auto-parseable-tool"}function jQ($,w){if(!w||!JW(w))return{...$,choices:$.choices.map((Z)=>{return yQ(Z.message.tool_calls),{...Z,message:{...Z.message,parsed:null,...Z.message.tool_calls?{tool_calls:Z.message.tool_calls}:void 0}}})};return s9($,w)}function s9($,w){let Z=$.choices.map((W)=>{if(W.finish_reason==="length")throw new i9;if(W.finish_reason==="content_filter")throw new m9;return yQ(W.message.tool_calls),{...W,message:{...W.message,...W.message.tool_calls?{tool_calls:W.message.tool_calls?.map((X)=>aF(w,X))??void 0}:void 0,parsed:W.message.content&&!W.message.refusal?sF(w,W.message.content):null}}});return{...$,choices:Z}}function sF($,w){if($.response_format?.type!=="json_schema")return null;if($.response_format?.type==="json_schema"){if("$parseRaw"in $.response_format)return $.response_format.$parseRaw(w);return JSON.parse(w)}return null}function aF($,w){let Z=$.tools?.find((W)=>t9(W)&&W.function?.name===w.function.name);return{...w,function:{...w.function,parsed_arguments:N1(Z)?Z.$parseRaw(w.function.arguments):Z?.function.strict?JSON.parse(w.function.arguments):null}}}function IQ($,w){if(!$||!("tools"in $)||!$.tools)return!1;let Z=$.tools?.find((W)=>t9(W)&&W.function?.name===w.function.name);return t9(Z)&&(N1(Z)||Z?.function.strict||!1)}function JW($){if(r9($.response_format))return!0;return $.tools?.some((w)=>N1(w)||w.type==="function"&&w.function.strict===!0)??!1}function yQ($){for(let w of $||[])if(w.type!=="function")throw new k(`Currently only \`function\` tool calls are supported; Received \`${w.type}\``)}function bQ($){for(let w of $??[]){if(w.type!=="function")throw new k(`Currently only \`function\` tool types support auto-parsing; Received \`${w.type}\``);if(w.function.strict!==!0)throw new k(`The \`${w.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var $w=($)=>{return $?.role==="assistant"},QW=($)=>{return $?.role==="tool"};var zW,B6,V6,a9,o9,P6,e9,U$,$4,q6,U6,ww,xQ;class K1{constructor(){zW.add(this),this.controller=new AbortController,B6.set(this,void 0),V6.set(this,()=>{}),a9.set(this,()=>{}),o9.set(this,void 0),P6.set(this,()=>{}),e9.set(this,()=>{}),U$.set(this,{}),$4.set(this,!1),q6.set(this,!1),U6.set(this,!1),ww.set(this,!1),R(this,B6,new Promise(($,w)=>{R(this,V6,$,"f"),R(this,a9,w,"f")}),"f"),R(this,o9,new Promise(($,w)=>{R(this,P6,$,"f"),R(this,e9,w,"f")}),"f"),V(this,B6,"f").catch(()=>{}),V(this,o9,"f").catch(()=>{})}_run($){setTimeout(()=>{$().then(()=>{this._emitFinal(),this._emit("end")},V(this,zW,"m",xQ).bind(this))},0)}_connected(){if(this.ended)return;V(this,V6,"f").call(this),this._emit("connect")}get ended(){return V(this,$4,"f")}get errored(){return V(this,q6,"f")}get aborted(){return V(this,U6,"f")}abort(){this.controller.abort()}on($,w){return(V(this,U$,"f")[$]||(V(this,U$,"f")[$]=[])).push({listener:w}),this}off($,w){let Z=V(this,U$,"f")[$];if(!Z)return this;let W=Z.findIndex((X)=>X.listener===w);if(W>=0)Z.splice(W,1);return this}once($,w){return(V(this,U$,"f")[$]||(V(this,U$,"f")[$]=[])).push({listener:w,once:!0}),this}emitted($){return new Promise((w,Z)=>{if(R(this,ww,!0,"f"),$!=="error")this.once("error",Z);this.once($,w)})}async done(){R(this,ww,!0,"f"),await V(this,o9,"f")}_emit($,...w){if(V(this,$4,"f"))return;if($==="end")R(this,$4,!0,"f"),V(this,P6,"f").call(this);let Z=V(this,U$,"f")[$];if(Z)V(this,U$,"f")[$]=Z.filter((W)=>!W.once),Z.forEach(({listener:W})=>W(...w));if($==="abort"){let W=w[0];if(!V(this,ww,"f")&&!Z?.length)Promise.reject(W);V(this,a9,"f").call(this,W),V(this,e9,"f").call(this,W),this._emit("end");return}if($==="error"){let W=w[0];if(!V(this,ww,"f")&&!Z?.length)Promise.reject(W);V(this,a9,"f").call(this,W),V(this,e9,"f").call(this,W),this._emit("end")}}_emitFinal(){}}B6=new WeakMap,V6=new WeakMap,a9=new WeakMap,o9=new WeakMap,P6=new WeakMap,e9=new WeakMap,U$=new WeakMap,$4=new WeakMap,q6=new WeakMap,U6=new WeakMap,ww=new WeakMap,zW=new WeakSet,xQ=function(w){if(R(this,q6,!0,"f"),w instanceof Error&&w.name==="AbortError")w=new X0;if(w instanceof X0)return R(this,U6,!0,"f"),this._emit("abort",w);if(w instanceof k)return this._emit("error",w);if(w instanceof Error){let Z=new k(w.message);return Z.cause=w,this._emit("error",Z)}return this._emit("error",new k(String(w)))};function _Q($){return typeof $.parse==="function"}var F0,MW,H6,TW,NW,KW,gQ,vQ,oF=10;class w4 extends K1{constructor(){super(...arguments);F0.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion($){this._chatCompletions.push($),this._emit("chatCompletion",$);let w=$.choices[0]?.message;if(w)this._addMessage(w);return $}_addMessage($,w=!0){if(!("content"in $))$.content=null;if(this.messages.push($),w){if(this._emit("message",$),QW($)&&$.content)this._emit("functionToolCallResult",$.content);else if($w($)&&$.tool_calls){for(let Z of $.tool_calls)if(Z.type==="function")this._emit("functionToolCall",Z.function)}}}async finalChatCompletion(){await this.done();let $=this._chatCompletions[this._chatCompletions.length-1];if(!$)throw new k("stream ended without producing a ChatCompletion");return $}async finalContent(){return await this.done(),V(this,F0,"m",MW).call(this)}async finalMessage(){return await this.done(),V(this,F0,"m",H6).call(this)}async finalFunctionToolCall(){return await this.done(),V(this,F0,"m",TW).call(this)}async finalFunctionToolCallResult(){return await this.done(),V(this,F0,"m",NW).call(this)}async totalUsage(){return await this.done(),V(this,F0,"m",KW).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let $=this._chatCompletions[this._chatCompletions.length-1];if($)this._emit("finalChatCompletion",$);let w=V(this,F0,"m",H6).call(this);if(w)this._emit("finalMessage",w);let Z=V(this,F0,"m",MW).call(this);if(Z)this._emit("finalContent",Z);let W=V(this,F0,"m",TW).call(this);if(W)this._emit("finalFunctionToolCall",W);let X=V(this,F0,"m",NW).call(this);if(X!=null)this._emit("finalFunctionToolCallResult",X);if(this._chatCompletions.some((Y)=>Y.usage))this._emit("totalUsage",V(this,F0,"m",KW).call(this))}async _createChatCompletion($,w,Z){let W=Z?.signal;if(W){if(W.aborted)this.controller.abort();W.addEventListener("abort",()=>this.controller.abort())}V(this,F0,"m",gQ).call(this,w);let X=await $.chat.completions.create({...w,stream:!1},{...Z,signal:this.controller.signal});return this._connected(),this._addChatCompletion(s9(X,w))}async _runChatCompletion($,w,Z){for(let W of w.messages)this._addMessage(W,!1);return await this._createChatCompletion($,w,Z)}async _runTools($,w,Z){let{tool_choice:X="auto",stream:Y,...G}=w,J=typeof X!=="string"&&X.type==="function"&&X?.function?.name,{maxChatCompletions:Q=oF}=Z||{},z=w.tools.map((N)=>{if(N1(N)){if(!N.$callback)throw new k("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:N.$callback,name:N.function.name,description:N.function.description||"",parameters:N.function.parameters,parse:N.$parseRaw,strict:!0}}}return N}),M={};for(let N of z)if(N.type==="function")M[N.function.name||N.function.function.name]=N.function;let T="tools"in w?z.map((N)=>N.type==="function"?{type:"function",function:{name:N.function.name||N.function.function.name,parameters:N.function.parameters,description:N.function.description,strict:N.function.strict}}:N):void 0;for(let N of w.messages)this._addMessage(N,!1);for(let N=0;N<Q;++N){let B=(await this._createChatCompletion($,{...G,tool_choice:X,tools:T,messages:[...this.messages]},Z)).choices[0]?.message;if(!B)throw new k("missing message in ChatCompletion response");if(!B.tool_calls?.length)return;for(let P of B.tool_calls){if(P.type!=="function")continue;let q=P.id,{name:U,arguments:O}=P.function,f=M[U];if(!f){let i=`Invalid tool_call: ${JSON.stringify(U)}. Available options are: ${Object.keys(M).map((r)=>JSON.stringify(r)).join(", ")}. Please try again`;this._addMessage({role:"tool",tool_call_id:q,content:i});continue}else if(J&&J!==U){let i=`Invalid tool_call: ${JSON.stringify(U)}. ${JSON.stringify(J)} requested. Please try again`;this._addMessage({role:"tool",tool_call_id:q,content:i});continue}let C;try{C=_Q(f)?await f.parse(O):O}catch(i){let r=i instanceof Error?i.message:String(i);this._addMessage({role:"tool",tool_call_id:q,content:r});continue}let A=await f.function(C,this),u=V(this,F0,"m",vQ).call(this,A);if(this._addMessage({role:"tool",tool_call_id:q,content:u}),J)return}}return}}F0=new WeakSet,MW=function(){return V(this,F0,"m",H6).call(this).content??null},H6=function(){let w=this.messages.length;while(w-- >0){let Z=this.messages[w];if($w(Z))return{...Z,content:Z.content??null,refusal:Z.refusal??null}}throw new k("stream ended without producing a ChatCompletionMessage with role=assistant")},TW=function(){for(let w=this.messages.length-1;w>=0;w--){let Z=this.messages[w];if($w(Z)&&Z?.tool_calls?.length)return Z.tool_calls.filter((W)=>W.type==="function").at(-1)?.function}return},NW=function(){for(let w=this.messages.length-1;w>=0;w--){let Z=this.messages[w];if(QW(Z)&&Z.content!=null&&typeof Z.content==="string"&&this.messages.some((W)=>W.role==="assistant"&&W.tool_calls?.some((X)=>X.type==="function"&&X.id===Z.tool_call_id)))return Z.content}return},KW=function(){let w={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:Z}of this._chatCompletions)if(Z)w.completion_tokens+=Z.completion_tokens,w.prompt_tokens+=Z.prompt_tokens,w.total_tokens+=Z.total_tokens;return w},gQ=function(w){if(w.n!=null&&w.n>1)throw new k("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},vQ=function(w){return typeof w==="string"?w:w===void 0?"undefined":JSON.stringify(w)};class Z4 extends w4{static runTools($,w,Z){let W=new Z4,X={...Z,headers:{...Z?.headers,"X-Stainless-Helper-Method":"runTools"}};return W._run(()=>W._runTools($,w,X)),W}_addMessage($,w=!0){if(super._addMessage($,w),$w($)&&$.content)this._emit("content",$.content)}}var Q0={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511};class uQ extends Error{}class hQ extends Error{}function eF($,w=Q0.ALL){if(typeof $!=="string")throw TypeError(`expecting str, got ${typeof $}`);if(!$.trim())throw Error(`${$} is empty`);return $O($.trim(),w)}var $O=($,w)=>{let Z=$.length,W=0,X=(N)=>{throw new uQ(`${N} at position ${W}`)},Y=(N)=>{throw new hQ(`${N} at position ${W}`)},G=()=>{if(T(),W>=Z)X("Unexpected end of input");if($[W]==='"')return J();if($[W]==="{")return Q();if($[W]==="[")return z();if($.substring(W,W+4)==="null"||Q0.NULL&w&&Z-W<4&&"null".startsWith($.substring(W)))return W+=4,null;if($.substring(W,W+4)==="true"||Q0.BOOL&w&&Z-W<4&&"true".startsWith($.substring(W)))return W+=4,!0;if($.substring(W,W+5)==="false"||Q0.BOOL&w&&Z-W<5&&"false".startsWith($.substring(W)))return W+=5,!1;if($.substring(W,W+8)==="Infinity"||Q0.INFINITY&w&&Z-W<8&&"Infinity".startsWith($.substring(W)))return W+=8,1/0;if($.substring(W,W+9)==="-Infinity"||Q0.MINUS_INFINITY&w&&1<Z-W&&Z-W<9&&"-Infinity".startsWith($.substring(W)))return W+=9,-1/0;if($.substring(W,W+3)==="NaN"||Q0.NAN&w&&Z-W<3&&"NaN".startsWith($.substring(W)))return W+=3,NaN;return M()},J=()=>{let N=W,K=!1;W++;while(W<Z&&($[W]!=='"'||K&&$[W-1]==="\\"))K=$[W]==="\\"?!K:!1,W++;if($.charAt(W)=='"')try{return JSON.parse($.substring(N,++W-Number(K)))}catch(B){Y(String(B))}else if(Q0.STR&w)try{return JSON.parse($.substring(N,W-Number(K))+'"')}catch(B){return JSON.parse($.substring(N,$.lastIndexOf("\\"))+'"')}X("Unterminated string literal")},Q=()=>{W++,T();let N={};try{while($[W]!=="}"){if(T(),W>=Z&&Q0.OBJ&w)return N;let K=J();T(),W++;try{let B=G();Object.defineProperty(N,K,{value:B,writable:!0,enumerable:!0,configurable:!0})}catch(B){if(Q0.OBJ&w)return N;else throw B}if(T(),$[W]===",")W++}}catch(K){if(Q0.OBJ&w)return N;else X("Expected '}' at end of object")}return W++,N},z=()=>{W++;let N=[];try{while($[W]!=="]")if(N.push(G()),T(),$[W]===",")W++}catch(K){if(Q0.ARR&w)return N;X("Expected ']' at end of array")}return W++,N},M=()=>{if(W===0){if($==="-"&&Q0.NUM&w)X("Not sure what '-' is");try{return JSON.parse($)}catch(K){if(Q0.NUM&w)try{if($[$.length-1]===".")return JSON.parse($.substring(0,$.lastIndexOf(".")));return JSON.parse($.substring(0,$.lastIndexOf("e")))}catch(B){}Y(String(K))}}let N=W;if($[W]==="-")W++;while($[W]&&!",]}".includes($[W]))W++;if(W==Z&&!(Q0.NUM&w))X("Unterminated number literal");try{return JSON.parse($.substring(N,W))}catch(K){if($.substring(N,W)==="-"&&Q0.NUM&w)X("Not sure what '-' is");try{return JSON.parse($.substring(N,$.lastIndexOf("e")))}catch(B){Y(String(B))}}},T=()=>{while(W<Z&&`
|
|
98
|
+
\r `.includes($[W]))W++};return G()},BW=($)=>eF($,Q0.ALL^Q0.NUM);var G0,H$,Zw,u$,VW,F6,PW,qW,UW,O6,HW,iQ;class h$ extends w4{constructor($){super();G0.add(this),H$.set(this,void 0),Zw.set(this,void 0),u$.set(this,void 0),R(this,H$,$,"f"),R(this,Zw,[],"f")}get currentChatCompletionSnapshot(){return V(this,u$,"f")}static fromReadableStream($){let w=new h$(null);return w._run(()=>w._fromReadableStream($)),w}static createChatCompletion($,w,Z){let W=new h$(w);return W._run(()=>W._runChatCompletion($,{...w,stream:!0},{...Z,headers:{...Z?.headers,"X-Stainless-Helper-Method":"stream"}})),W}async _createChatCompletion($,w,Z){super._createChatCompletion;let W=Z?.signal;if(W){if(W.aborted)this.controller.abort();W.addEventListener("abort",()=>this.controller.abort())}V(this,G0,"m",VW).call(this);let X=await $.chat.completions.create({...w,stream:!0},{...Z,signal:this.controller.signal});this._connected();for await(let Y of X)V(this,G0,"m",PW).call(this,Y);if(X.controller.signal?.aborted)throw new X0;return this._addChatCompletion(V(this,G0,"m",O6).call(this))}async _fromReadableStream($,w){let Z=w?.signal;if(Z){if(Z.aborted)this.controller.abort();Z.addEventListener("abort",()=>this.controller.abort())}V(this,G0,"m",VW).call(this),this._connected();let W=y0.fromReadableStream($,this.controller),X;for await(let Y of W){if(X&&X!==Y.id)this._addChatCompletion(V(this,G0,"m",O6).call(this));V(this,G0,"m",PW).call(this,Y),X=Y.id}if(W.controller.signal?.aborted)throw new X0;return this._addChatCompletion(V(this,G0,"m",O6).call(this))}[(H$=new WeakMap,Zw=new WeakMap,u$=new WeakMap,G0=new WeakSet,VW=function(){if(this.ended)return;R(this,u$,void 0,"f")},F6=function(w){let Z=V(this,Zw,"f")[w.index];if(Z)return Z;return Z={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},V(this,Zw,"f")[w.index]=Z,Z},PW=function(w){if(this.ended)return;let Z=V(this,G0,"m",iQ).call(this,w);this._emit("chunk",w,Z);for(let W of w.choices){let X=Z.choices[W.index];if(W.delta.content!=null&&X.message?.role==="assistant"&&X.message?.content)this._emit("content",W.delta.content,X.message.content),this._emit("content.delta",{delta:W.delta.content,snapshot:X.message.content,parsed:X.message.parsed});if(W.delta.refusal!=null&&X.message?.role==="assistant"&&X.message?.refusal)this._emit("refusal.delta",{delta:W.delta.refusal,snapshot:X.message.refusal});if(W.logprobs?.content!=null&&X.message?.role==="assistant")this._emit("logprobs.content.delta",{content:W.logprobs?.content,snapshot:X.logprobs?.content??[]});if(W.logprobs?.refusal!=null&&X.message?.role==="assistant")this._emit("logprobs.refusal.delta",{refusal:W.logprobs?.refusal,snapshot:X.logprobs?.refusal??[]});let Y=V(this,G0,"m",F6).call(this,X);if(X.finish_reason){if(V(this,G0,"m",UW).call(this,X),Y.current_tool_call_index!=null)V(this,G0,"m",qW).call(this,X,Y.current_tool_call_index)}for(let G of W.delta.tool_calls??[]){if(Y.current_tool_call_index!==G.index){if(V(this,G0,"m",UW).call(this,X),Y.current_tool_call_index!=null)V(this,G0,"m",qW).call(this,X,Y.current_tool_call_index)}Y.current_tool_call_index=G.index}for(let G of W.delta.tool_calls??[]){let J=X.message.tool_calls?.[G.index];if(!J?.type)continue;if(J?.type==="function")this._emit("tool_calls.function.arguments.delta",{name:J.function?.name,index:G.index,arguments:J.function.arguments,parsed_arguments:J.function.parsed_arguments,arguments_delta:G.function?.arguments??""});else lQ(J?.type)}}},qW=function(w,Z){if(V(this,G0,"m",F6).call(this,w).done_tool_calls.has(Z))return;let X=w.message.tool_calls?.[Z];if(!X)throw Error("no tool call snapshot");if(!X.type)throw Error("tool call snapshot missing `type`");if(X.type==="function"){let Y=V(this,H$,"f")?.tools?.find((G)=>t9(G)&&G.function.name===X.function.name);this._emit("tool_calls.function.arguments.done",{name:X.function.name,index:Z,arguments:X.function.arguments,parsed_arguments:N1(Y)?Y.$parseRaw(X.function.arguments):Y?.function.strict?JSON.parse(X.function.arguments):null})}else lQ(X.type)},UW=function(w){let Z=V(this,G0,"m",F6).call(this,w);if(w.message.content&&!Z.content_done){Z.content_done=!0;let W=V(this,G0,"m",HW).call(this);this._emit("content.done",{content:w.message.content,parsed:W?W.$parseRaw(w.message.content):null})}if(w.message.refusal&&!Z.refusal_done)Z.refusal_done=!0,this._emit("refusal.done",{refusal:w.message.refusal});if(w.logprobs?.content&&!Z.logprobs_content_done)Z.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:w.logprobs.content});if(w.logprobs?.refusal&&!Z.logprobs_refusal_done)Z.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:w.logprobs.refusal})},O6=function(){if(this.ended)throw new k("stream has ended, this shouldn't happen");let w=V(this,u$,"f");if(!w)throw new k("request ended without sending any chunks");return R(this,u$,void 0,"f"),R(this,Zw,[],"f"),wO(w,V(this,H$,"f"))},HW=function(){let w=V(this,H$,"f")?.response_format;if(r9(w))return w;return null},iQ=function(w){var Z,W,X,Y;let G=V(this,u$,"f"),{choices:J,...Q}=w;if(!G)G=R(this,u$,{...Q,choices:[]},"f");else Object.assign(G,Q);for(let{delta:z,finish_reason:M,index:T,logprobs:N=null,...K}of w.choices){let B=G.choices[T];if(!B)B=G.choices[T]={finish_reason:M,index:T,message:{},logprobs:N,...K};if(N)if(!B.logprobs)B.logprobs=Object.assign({},N);else{let{content:A,refusal:u,...i}=N;if(mQ(i),Object.assign(B.logprobs,i),A)(Z=B.logprobs).content??(Z.content=[]),B.logprobs.content.push(...A);if(u)(W=B.logprobs).refusal??(W.refusal=[]),B.logprobs.refusal.push(...u)}if(M){if(B.finish_reason=M,V(this,H$,"f")&&JW(V(this,H$,"f"))){if(M==="length")throw new i9;if(M==="content_filter")throw new m9}}if(Object.assign(B,K),!z)continue;let{content:P,refusal:q,function_call:U,role:O,tool_calls:f,...C}=z;if(mQ(C),Object.assign(B.message,C),q)B.message.refusal=(B.message.refusal||"")+q;if(O)B.message.role=O;if(U)if(!B.message.function_call)B.message.function_call=U;else{if(U.name)B.message.function_call.name=U.name;if(U.arguments)(X=B.message.function_call).arguments??(X.arguments=""),B.message.function_call.arguments+=U.arguments}if(P){if(B.message.content=(B.message.content||"")+P,!B.message.refusal&&V(this,G0,"m",HW).call(this))B.message.parsed=BW(B.message.content)}if(f){if(!B.message.tool_calls)B.message.tool_calls=[];for(let{index:A,id:u,type:i,function:r,...z0}of f){let h=(Y=B.message.tool_calls)[A]??(Y[A]={});if(Object.assign(h,z0),u)h.id=u;if(i)h.type=i;if(r)h.function??(h.function={name:r.name??"",arguments:""});if(r?.name)h.function.name=r.name;if(r?.arguments){if(h.function.arguments+=r.arguments,IQ(V(this,H$,"f"),h))h.function.parsed_arguments=BW(h.function.arguments)}}}}return G},Symbol.asyncIterator)](){let $=[],w=[],Z=!1;return this.on("chunk",(W)=>{let X=w.shift();if(X)X.resolve(W);else $.push(W)}),this.on("end",()=>{Z=!0;for(let W of w)W.resolve(void 0);w.length=0}),this.on("abort",(W)=>{Z=!0;for(let X of w)X.reject(W);w.length=0}),this.on("error",(W)=>{Z=!0;for(let X of w)X.reject(W);w.length=0}),{next:async()=>{if(!$.length){if(Z)return{value:void 0,done:!0};return new Promise((X,Y)=>w.push({resolve:X,reject:Y})).then((X)=>X?{value:X,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new y0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function wO($,w){let{id:Z,choices:W,created:X,model:Y,system_fingerprint:G,...J}=$,Q={...J,id:Z,choices:W.map(({message:z,finish_reason:M,index:T,logprobs:N,...K})=>{if(!M)throw new k(`missing finish_reason for choice ${T}`);let{content:B=null,function_call:P,tool_calls:q,...U}=z,O=z.role;if(!O)throw new k(`missing role for choice ${T}`);if(P){let{arguments:f,name:C}=P;if(f==null)throw new k(`missing function_call.arguments for choice ${T}`);if(!C)throw new k(`missing function_call.name for choice ${T}`);return{...K,message:{content:B,function_call:{arguments:f,name:C},role:O,refusal:z.refusal??null},finish_reason:M,index:T,logprobs:N}}if(q)return{...K,index:T,finish_reason:M,logprobs:N,message:{...U,role:O,content:B,refusal:z.refusal??null,tool_calls:q.map((f,C)=>{let{function:A,type:u,id:i,...r}=f,{arguments:z0,name:h,...q0}=A||{};if(i==null)throw new k(`missing choices[${T}].tool_calls[${C}].id
|
|
99
99
|
${E6($)}`);if(u==null)throw new k(`missing choices[${T}].tool_calls[${C}].type
|
|
100
100
|
${E6($)}`);if(h==null)throw new k(`missing choices[${T}].tool_calls[${C}].function.name
|
|
101
101
|
${E6($)}`);if(z0==null)throw new k(`missing choices[${T}].tool_calls[${C}].function.arguments
|
|
102
|
-
${E6($)}`);return{...r,id:i,type:u,function:{...q0,name:h,arguments:z0}}})}};return{...N,message:{...U,content:B,role:O,refusal:z.refusal??null},finish_reason:M,index:T,logprobs:K}}),created:X,model:Y,object:"chat.completion",...G?{system_fingerprint:G}:{}};return SQ(Q,w)}function E6($){return JSON.stringify($)}function uQ($){return}function hQ($){}class Ww extends h${static fromReadableStream($){let w=new Ww(null);return w._run(()=>w._fromReadableStream($)),w}static runTools($,w,Z){let W=new Ww(w),X={...Z,headers:{...Z?.headers,"X-Stainless-Helper-Method":"runTools"}};return W._run(()=>W._runTools($,w,X)),W}}class i$ extends E{constructor(){super(...arguments);this.messages=new e1(this._client)}create($,w){return this._client.post("/chat/completions",{body:$,...w,stream:$.stream??!1})}retrieve($,w){return this._client.get(H`/chat/completions/${$}`,w)}update($,w,Z){return this._client.post(H`/chat/completions/${$}`,{body:w,...Z})}list($={},w){return this._client.getAPIList("/chat/completions",g,{query:$,...w})}delete($,w){return this._client.delete(H`/chat/completions/${$}`,w)}parse($,w){return jQ($.tools),this._client.chat.completions.create($,{...w,headers:{...w?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap((Z)=>s9(Z,$))}runTools($,w){if($.stream)return Ww.runTools(this._client,$,w);return Z4.runTools(this._client,$,w)}stream($,w){return h$.createChatCompletion(this._client,$,w)}}i$.Messages=e1;class B1 extends E{constructor(){super(...arguments);this.completions=new i$(this._client)}}B1.Completions=i$;var iQ=Symbol("brand.privateNullableHeaders");function*$O($){if(!$)return;if(iQ in $){let{values:W,nulls:X}=$;yield*W.entries();for(let Y of X)yield[Y,null];return}let w=!1,Z;if($ instanceof Headers)Z=$.entries();else if(m5($))Z=$;else w=!0,Z=Object.entries($??{});for(let W of Z){let X=W[0];if(typeof X!=="string")throw TypeError("expected header name to be a string");let Y=m5(W[1])?W[1]:[W[1]],G=!1;for(let J of Y){if(J===void 0)continue;if(w&&!G)G=!0,yield[X,null];yield[X,J]}}}var D=($)=>{let w=new Headers,Z=new Set;for(let W of $){let X=new Set;for(let[Y,G]of $O(W)){let J=Y.toLowerCase();if(!X.has(J))w.delete(Y),X.add(J);if(G===null)w.delete(Y),Z.add(J);else w.append(Y,G),Z.delete(J)}}return{[iQ]:!0,values:w,nulls:Z}};class W4 extends E{create($,w){return this._client.post("/audio/speech",{body:$,...w,headers:D([{Accept:"application/octet-stream"},w?.headers]),__binaryResponse:!0})}}class X4 extends E{create($,w){return this._client.post("/audio/transcriptions",b0({body:$,...w,stream:$.stream??!1,__metadata:{model:$.model}},this._client))}}class Y4 extends E{create($,w){return this._client.post("/audio/translations",b0({body:$,...w,__metadata:{model:$.model}},this._client))}}class H$ extends E{constructor(){super(...arguments);this.transcriptions=new X4(this._client),this.translations=new Y4(this._client),this.speech=new W4(this._client)}}H$.Transcriptions=X4;H$.Translations=Y4;H$.Speech=W4;class Xw extends E{create($,w){return this._client.post("/batches",{body:$,...w})}retrieve($,w){return this._client.get(H`/batches/${$}`,w)}list($={},w){return this._client.getAPIList("/batches",g,{query:$,...w})}cancel($,w){return this._client.post(H`/batches/${$}/cancel`,w)}}class G4 extends E{create($,w){return this._client.post("/assistants",{body:$,...w,headers:D([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}retrieve($,w){return this._client.get(H`/assistants/${$}`,{...w,headers:D([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}update($,w,Z){return this._client.post(H`/assistants/${$}`,{body:w,...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}list($={},w){return this._client.getAPIList("/assistants",g,{query:$,...w,headers:D([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}delete($,w){return this._client.delete(H`/assistants/${$}`,{...w,headers:D([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}}class J4 extends E{create($,w){return this._client.post("/realtime/sessions",{body:$,...w,headers:D([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}}class Q4 extends E{create($,w){return this._client.post("/realtime/transcription_sessions",{body:$,...w,headers:D([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}}class V1 extends E{constructor(){super(...arguments);this.sessions=new J4(this._client),this.transcriptionSessions=new Q4(this._client)}}V1.Sessions=J4;V1.TranscriptionSessions=Q4;class z4 extends E{create($,w,Z){return this._client.post(H`/threads/${$}/messages`,{body:w,...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}retrieve($,w,Z){let{thread_id:W}=w;return this._client.get(H`/threads/${W}/messages/${$}`,{...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}update($,w,Z){let{thread_id:W,...X}=w;return this._client.post(H`/threads/${W}/messages/${$}`,{body:X,...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}list($,w={},Z){return this._client.getAPIList(H`/threads/${$}/messages`,g,{query:w,...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}delete($,w,Z){let{thread_id:W}=w;return this._client.delete(H`/threads/${W}/messages/${$}`,{...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}}class M4 extends E{retrieve($,w,Z){let{thread_id:W,run_id:X,...Y}=w;return this._client.get(H`/threads/${W}/runs/${X}/steps/${$}`,{query:Y,...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}list($,w,Z){let{thread_id:W,...X}=w;return this._client.getAPIList(H`/threads/${W}/runs/${$}/steps`,g,{query:X,...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}}var mQ=($)=>{if(typeof Buffer<"u"){let w=Buffer.from($,"base64");return Array.from(new Float32Array(w.buffer,w.byteOffset,w.length/Float32Array.BYTES_PER_ELEMENT))}else{let w=atob($),Z=w.length,W=new Uint8Array(Z);for(let X=0;X<Z;X++)W[X]=w.charCodeAt(X);return Array.from(new Float32Array(W.buffer))}};var m$=($)=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[$]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.($)?.trim();return};var T0,q1,HW,e0,L6,p0,U1,Yw,P1,k6,x0,D6,f6,N4,T4,K4,lQ,cQ,dQ,pQ,nQ,tQ,rQ;class l$ extends N1{constructor(){super(...arguments);T0.add(this),HW.set(this,[]),e0.set(this,{}),L6.set(this,{}),p0.set(this,void 0),U1.set(this,void 0),Yw.set(this,void 0),P1.set(this,void 0),k6.set(this,void 0),x0.set(this,void 0),D6.set(this,void 0),f6.set(this,void 0),N4.set(this,void 0)}[(HW=new WeakMap,e0=new WeakMap,L6=new WeakMap,p0=new WeakMap,U1=new WeakMap,Yw=new WeakMap,P1=new WeakMap,k6=new WeakMap,x0=new WeakMap,D6=new WeakMap,f6=new WeakMap,N4=new WeakMap,T0=new WeakSet,Symbol.asyncIterator)](){let $=[],w=[],Z=!1;return this.on("event",(W)=>{let X=w.shift();if(X)X.resolve(W);else $.push(W)}),this.on("end",()=>{Z=!0;for(let W of w)W.resolve(void 0);w.length=0}),this.on("abort",(W)=>{Z=!0;for(let X of w)X.reject(W);w.length=0}),this.on("error",(W)=>{Z=!0;for(let X of w)X.reject(W);w.length=0}),{next:async()=>{if(!$.length){if(Z)return{value:void 0,done:!0};return new Promise((X,Y)=>w.push({resolve:X,reject:Y})).then((X)=>X?{value:X,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}static fromReadableStream($){let w=new q1;return w._run(()=>w._fromReadableStream($)),w}async _fromReadableStream($,w){let Z=w?.signal;if(Z){if(Z.aborted)this.controller.abort();Z.addEventListener("abort",()=>this.controller.abort())}this._connected();let W=y0.fromReadableStream($,this.controller);for await(let X of W)V(this,T0,"m",T4).call(this,X);if(W.controller.signal?.aborted)throw new X0;return this._addRun(V(this,T0,"m",K4).call(this))}toReadableStream(){return new y0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream($,w,Z,W){let X=new q1;return X._run(()=>X._runToolAssistantStream($,w,Z,{...W,headers:{...W?.headers,"X-Stainless-Helper-Method":"stream"}})),X}async _createToolAssistantStream($,w,Z,W){let X=W?.signal;if(X){if(X.aborted)this.controller.abort();X.addEventListener("abort",()=>this.controller.abort())}let Y={...Z,stream:!0},G=await $.submitToolOutputs(w,Y,{...W,signal:this.controller.signal});this._connected();for await(let J of G)V(this,T0,"m",T4).call(this,J);if(G.controller.signal?.aborted)throw new X0;return this._addRun(V(this,T0,"m",K4).call(this))}static createThreadAssistantStream($,w,Z){let W=new q1;return W._run(()=>W._threadAssistantStream($,w,{...Z,headers:{...Z?.headers,"X-Stainless-Helper-Method":"stream"}})),W}static createAssistantStream($,w,Z,W){let X=new q1;return X._run(()=>X._runAssistantStream($,w,Z,{...W,headers:{...W?.headers,"X-Stainless-Helper-Method":"stream"}})),X}currentEvent(){return V(this,D6,"f")}currentRun(){return V(this,f6,"f")}currentMessageSnapshot(){return V(this,p0,"f")}currentRunStepSnapshot(){return V(this,N4,"f")}async finalRunSteps(){return await this.done(),Object.values(V(this,e0,"f"))}async finalMessages(){return await this.done(),Object.values(V(this,L6,"f"))}async finalRun(){if(await this.done(),!V(this,U1,"f"))throw Error("Final run was not received.");return V(this,U1,"f")}async _createThreadAssistantStream($,w,Z){let W=Z?.signal;if(W){if(W.aborted)this.controller.abort();W.addEventListener("abort",()=>this.controller.abort())}let X={...w,stream:!0},Y=await $.createAndRun(X,{...Z,signal:this.controller.signal});this._connected();for await(let G of Y)V(this,T0,"m",T4).call(this,G);if(Y.controller.signal?.aborted)throw new X0;return this._addRun(V(this,T0,"m",K4).call(this))}async _createAssistantStream($,w,Z,W){let X=W?.signal;if(X){if(X.aborted)this.controller.abort();X.addEventListener("abort",()=>this.controller.abort())}let Y={...Z,stream:!0},G=await $.create(w,Y,{...W,signal:this.controller.signal});this._connected();for await(let J of G)V(this,T0,"m",T4).call(this,J);if(G.controller.signal?.aborted)throw new X0;return this._addRun(V(this,T0,"m",K4).call(this))}static accumulateDelta($,w){for(let[Z,W]of Object.entries(w)){if(!$.hasOwnProperty(Z)){$[Z]=W;continue}let X=$[Z];if(X===null||X===void 0){$[Z]=W;continue}if(Z==="index"||Z==="type"){$[Z]=W;continue}if(typeof X==="string"&&typeof W==="string")X+=W;else if(typeof X==="number"&&typeof W==="number")X+=W;else if(l9(X)&&l9(W))X=this.accumulateDelta(X,W);else if(Array.isArray(X)&&Array.isArray(W)){if(X.every((Y)=>typeof Y==="string"||typeof Y==="number")){X.push(...W);continue}for(let Y of W){if(!l9(Y))throw Error(`Expected array delta entry to be an object but got: ${Y}`);let G=Y.index;if(G==null)throw console.error(Y),Error("Expected array delta entry to have an `index` property");if(typeof G!=="number")throw Error(`Expected array delta entry \`index\` property to be a number but got ${G}`);let J=X[G];if(J==null)X.push(Y);else X[G]=this.accumulateDelta(J,Y)}continue}else throw Error(`Unhandled record type: ${Z}, deltaValue: ${W}, accValue: ${X}`);$[Z]=X}return $}_addRun($){return $}async _threadAssistantStream($,w,Z){return await this._createThreadAssistantStream(w,$,Z)}async _runAssistantStream($,w,Z,W){return await this._createAssistantStream(w,$,Z,W)}async _runToolAssistantStream($,w,Z,W){return await this._createToolAssistantStream(w,$,Z,W)}}q1=l$,T4=function(w){if(this.ended)return;switch(R(this,D6,w,"f"),V(this,T0,"m",dQ).call(this,w),w.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":V(this,T0,"m",rQ).call(this,w);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":V(this,T0,"m",cQ).call(this,w);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":V(this,T0,"m",lQ).call(this,w);break;case"error":throw Error("Encountered an error event in event processing - errors should be processed earlier");default:MO(w)}},K4=function(){if(this.ended)throw new k("stream has ended, this shouldn't happen");if(!V(this,U1,"f"))throw Error("Final run has not been received");return V(this,U1,"f")},lQ=function(w){let[Z,W]=V(this,T0,"m",nQ).call(this,w,V(this,p0,"f"));R(this,p0,Z,"f"),V(this,L6,"f")[Z.id]=Z;for(let X of W){let Y=Z.content[X.index];if(Y?.type=="text")this._emit("textCreated",Y.text)}switch(w.event){case"thread.message.created":this._emit("messageCreated",w.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",w.data.delta,Z),w.data.delta.content)for(let X of w.data.delta.content){if(X.type=="text"&&X.text){let Y=X.text,G=Z.content[X.index];if(G&&G.type=="text")this._emit("textDelta",Y,G.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(X.index!=V(this,Yw,"f")){if(V(this,P1,"f"))switch(V(this,P1,"f").type){case"text":this._emit("textDone",V(this,P1,"f").text,V(this,p0,"f"));break;case"image_file":this._emit("imageFileDone",V(this,P1,"f").image_file,V(this,p0,"f"));break}R(this,Yw,X.index,"f")}R(this,P1,Z.content[X.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(V(this,Yw,"f")!==void 0){let X=w.data.content[V(this,Yw,"f")];if(X)switch(X.type){case"image_file":this._emit("imageFileDone",X.image_file,V(this,p0,"f"));break;case"text":this._emit("textDone",X.text,V(this,p0,"f"));break}}if(V(this,p0,"f"))this._emit("messageDone",w.data);R(this,p0,void 0,"f")}},cQ=function(w){let Z=V(this,T0,"m",pQ).call(this,w);switch(R(this,N4,Z,"f"),w.event){case"thread.run.step.created":this._emit("runStepCreated",w.data);break;case"thread.run.step.delta":let W=w.data.delta;if(W.step_details&&W.step_details.type=="tool_calls"&&W.step_details.tool_calls&&Z.step_details.type=="tool_calls")for(let Y of W.step_details.tool_calls)if(Y.index==V(this,k6,"f"))this._emit("toolCallDelta",Y,Z.step_details.tool_calls[Y.index]);else{if(V(this,x0,"f"))this._emit("toolCallDone",V(this,x0,"f"));if(R(this,k6,Y.index,"f"),R(this,x0,Z.step_details.tool_calls[Y.index],"f"),V(this,x0,"f"))this._emit("toolCallCreated",V(this,x0,"f"))}this._emit("runStepDelta",w.data.delta,Z);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":if(R(this,N4,void 0,"f"),w.data.step_details.type=="tool_calls"){if(V(this,x0,"f"))this._emit("toolCallDone",V(this,x0,"f")),R(this,x0,void 0,"f")}this._emit("runStepDone",w.data,Z);break;case"thread.run.step.in_progress":break}},dQ=function(w){V(this,HW,"f").push(w),this._emit("event",w)},pQ=function(w){switch(w.event){case"thread.run.step.created":return V(this,e0,"f")[w.data.id]=w.data,w.data;case"thread.run.step.delta":let Z=V(this,e0,"f")[w.data.id];if(!Z)throw Error("Received a RunStepDelta before creation of a snapshot");let W=w.data;if(W.delta){let X=q1.accumulateDelta(Z,W.delta);V(this,e0,"f")[w.data.id]=X}return V(this,e0,"f")[w.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":V(this,e0,"f")[w.data.id]=w.data;break}if(V(this,e0,"f")[w.data.id])return V(this,e0,"f")[w.data.id];throw Error("No snapshot available")},nQ=function(w,Z){let W=[];switch(w.event){case"thread.message.created":return[w.data,W];case"thread.message.delta":if(!Z)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let X=w.data;if(X.delta.content)for(let Y of X.delta.content)if(Y.index in Z.content){let G=Z.content[Y.index];Z.content[Y.index]=V(this,T0,"m",tQ).call(this,Y,G)}else Z.content[Y.index]=Y,W.push(Y);return[Z,W];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(Z)return[Z,W];else throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},tQ=function(w,Z){return q1.accumulateDelta(Z,w)},rQ=function(w){switch(R(this,f6,w.data,"f"),w.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":if(R(this,U1,w.data,"f"),V(this,x0,"f"))this._emit("toolCallDone",V(this,x0,"f")),R(this,x0,void 0,"f");break;case"thread.run.cancelling":break}};function MO($){}class Gw extends E{constructor(){super(...arguments);this.steps=new M4(this._client)}create($,w,Z){let{include:W,...X}=w;return this._client.post(H`/threads/${$}/runs`,{query:{include:W},body:X,...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),stream:w.stream??!1})}retrieve($,w,Z){let{thread_id:W}=w;return this._client.get(H`/threads/${W}/runs/${$}`,{...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}update($,w,Z){let{thread_id:W,...X}=w;return this._client.post(H`/threads/${W}/runs/${$}`,{body:X,...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}list($,w={},Z){return this._client.getAPIList(H`/threads/${$}/runs`,g,{query:w,...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}cancel($,w,Z){let{thread_id:W}=w;return this._client.post(H`/threads/${W}/runs/${$}/cancel`,{...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}async createAndPoll($,w,Z){let W=await this.create($,w,Z);return await this.poll(W.id,{thread_id:$},Z)}createAndStream($,w,Z){return l$.createAssistantStream($,this._client.beta.threads.runs,w,Z)}async poll($,w,Z){let W=D([Z?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":Z?.pollIntervalMs?.toString()??void 0}]);while(!0){let{data:X,response:Y}=await this.retrieve($,w,{...Z,headers:{...Z?.headers,...W}}).withResponse();switch(X.status){case"queued":case"in_progress":case"cancelling":let G=5000;if(Z?.pollIntervalMs)G=Z.pollIntervalMs;else{let J=Y.headers.get("openai-poll-after-ms");if(J){let Q=parseInt(J);if(!isNaN(Q))G=Q}}await a0(G);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return X}}}stream($,w,Z){return l$.createAssistantStream($,this._client.beta.threads.runs,w,Z)}submitToolOutputs($,w,Z){let{thread_id:W,...X}=w;return this._client.post(H`/threads/${W}/runs/${$}/submit_tool_outputs`,{body:X,...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),stream:w.stream??!1})}async submitToolOutputsAndPoll($,w,Z){let W=await this.submitToolOutputs($,w,Z);return await this.poll(W.id,w,Z)}submitToolOutputsStream($,w,Z){return l$.createToolAssistantStream($,this._client.beta.threads.runs,w,Z)}}Gw.Steps=M4;class H1 extends E{constructor(){super(...arguments);this.runs=new Gw(this._client),this.messages=new z4(this._client)}create($={},w){return this._client.post("/threads",{body:$,...w,headers:D([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}retrieve($,w){return this._client.get(H`/threads/${$}`,{...w,headers:D([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}update($,w,Z){return this._client.post(H`/threads/${$}`,{body:w,...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}delete($,w){return this._client.delete(H`/threads/${$}`,{...w,headers:D([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}createAndRun($,w){return this._client.post("/threads/runs",{body:$,...w,headers:D([{"OpenAI-Beta":"assistants=v2"},w?.headers]),stream:$.stream??!1})}async createAndRunPoll($,w){let Z=await this.createAndRun($,w);return await this.runs.poll(Z.id,{thread_id:Z.thread_id},w)}createAndRunStream($,w){return l$.createThreadAssistantStream($,this._client.beta.threads,w)}}H1.Runs=Gw;H1.Messages=z4;class F$ extends E{constructor(){super(...arguments);this.realtime=new V1(this._client),this.assistants=new G4(this._client),this.threads=new H1(this._client)}}F$.Realtime=V1;F$.Assistants=G4;F$.Threads=H1;class Jw extends E{create($,w){return this._client.post("/completions",{body:$,...w,stream:$.stream??!1})}}class B4 extends E{retrieve($,w,Z){let{container_id:W}=w;return this._client.get(H`/containers/${W}/files/${$}/content`,{...Z,headers:D([{Accept:"application/binary"},Z?.headers]),__binaryResponse:!0})}}class Qw extends E{constructor(){super(...arguments);this.content=new B4(this._client)}create($,w,Z){return this._client.post(H`/containers/${$}/files`,b0({body:w,...Z},this._client))}retrieve($,w,Z){let{container_id:W}=w;return this._client.get(H`/containers/${W}/files/${$}`,Z)}list($,w={},Z){return this._client.getAPIList(H`/containers/${$}/files`,g,{query:w,...Z})}delete($,w,Z){let{container_id:W}=w;return this._client.delete(H`/containers/${W}/files/${$}`,{...Z,headers:D([{Accept:"*/*"},Z?.headers])})}}Qw.Content=B4;class F1 extends E{constructor(){super(...arguments);this.files=new Qw(this._client)}create($,w){return this._client.post("/containers",{body:$,...w})}retrieve($,w){return this._client.get(H`/containers/${$}`,w)}list($={},w){return this._client.getAPIList("/containers",g,{query:$,...w})}delete($,w){return this._client.delete(H`/containers/${$}`,{...w,headers:D([{Accept:"*/*"},w?.headers])})}}F1.Files=Qw;class V4 extends E{create($,w,Z){let{include:W,...X}=w;return this._client.post(H`/conversations/${$}/items`,{query:{include:W},body:X,...Z})}retrieve($,w,Z){let{conversation_id:W,...X}=w;return this._client.get(H`/conversations/${W}/items/${$}`,{query:X,...Z})}list($,w={},Z){return this._client.getAPIList(H`/conversations/${$}/items`,wW,{query:w,...Z})}delete($,w,Z){let{conversation_id:W}=w;return this._client.delete(H`/conversations/${W}/items/${$}`,Z)}}class O1 extends E{constructor(){super(...arguments);this.items=new V4(this._client)}create($={},w){return this._client.post("/conversations",{body:$,...w})}retrieve($,w){return this._client.get(H`/conversations/${$}`,w)}update($,w,Z){return this._client.post(H`/conversations/${$}`,{body:w,...Z})}delete($,w){return this._client.delete(H`/conversations/${$}`,w)}}O1.Items=V4;class zw extends E{create($,w){let Z=!!$.encoding_format,W=Z?$.encoding_format:"base64";if(Z)$0(this._client).debug("embeddings/user defined encoding_format:",$.encoding_format);let X=this._client.post("/embeddings",{body:{...$,encoding_format:W},...w});if(Z)return X;return $0(this._client).debug("embeddings/decoding base64 embeddings from base64"),X._thenUnwrap((Y)=>{if(Y&&Y.data)Y.data.forEach((G)=>{let J=G.embedding;G.embedding=mQ(J)});return Y})}}class P4 extends E{retrieve($,w,Z){let{eval_id:W,run_id:X}=w;return this._client.get(H`/evals/${W}/runs/${X}/output_items/${$}`,Z)}list($,w,Z){let{eval_id:W,...X}=w;return this._client.getAPIList(H`/evals/${W}/runs/${$}/output_items`,g,{query:X,...Z})}}class Mw extends E{constructor(){super(...arguments);this.outputItems=new P4(this._client)}create($,w,Z){return this._client.post(H`/evals/${$}/runs`,{body:w,...Z})}retrieve($,w,Z){let{eval_id:W}=w;return this._client.get(H`/evals/${W}/runs/${$}`,Z)}list($,w={},Z){return this._client.getAPIList(H`/evals/${$}/runs`,g,{query:w,...Z})}delete($,w,Z){let{eval_id:W}=w;return this._client.delete(H`/evals/${W}/runs/${$}`,Z)}cancel($,w,Z){let{eval_id:W}=w;return this._client.post(H`/evals/${W}/runs/${$}`,Z)}}Mw.OutputItems=P4;class E1 extends E{constructor(){super(...arguments);this.runs=new Mw(this._client)}create($,w){return this._client.post("/evals",{body:$,...w})}retrieve($,w){return this._client.get(H`/evals/${$}`,w)}update($,w,Z){return this._client.post(H`/evals/${$}`,{body:w,...Z})}list($={},w){return this._client.getAPIList("/evals",g,{query:$,...w})}delete($,w){return this._client.delete(H`/evals/${$}`,w)}}E1.Runs=Mw;class Tw extends E{create($,w){return this._client.post("/files",b0({body:$,...w},this._client))}retrieve($,w){return this._client.get(H`/files/${$}`,w)}list($={},w){return this._client.getAPIList("/files",g,{query:$,...w})}delete($,w){return this._client.delete(H`/files/${$}`,w)}content($,w){return this._client.get(H`/files/${$}/content`,{...w,headers:D([{Accept:"application/binary"},w?.headers]),__binaryResponse:!0})}async waitForProcessing($,{pollInterval:w=5000,maxWait:Z=1800000}={}){let W=new Set(["processed","error","deleted"]),X=Date.now(),Y=await this.retrieve($);while(!Y.status||!W.has(Y.status))if(await a0(w),Y=await this.retrieve($),Date.now()-X>Z)throw new M1({message:`Giving up on waiting for file ${$} to finish processing after ${Z} milliseconds.`});return Y}}class q4 extends E{}class U4 extends E{run($,w){return this._client.post("/fine_tuning/alpha/graders/run",{body:$,...w})}validate($,w){return this._client.post("/fine_tuning/alpha/graders/validate",{body:$,...w})}}class Kw extends E{constructor(){super(...arguments);this.graders=new U4(this._client)}}Kw.Graders=U4;class H4 extends E{create($,w,Z){return this._client.getAPIList(H`/fine_tuning/checkpoints/${$}/permissions`,P$,{body:w,method:"post",...Z})}retrieve($,w={},Z){return this._client.get(H`/fine_tuning/checkpoints/${$}/permissions`,{query:w,...Z})}delete($,w,Z){let{fine_tuned_model_checkpoint:W}=w;return this._client.delete(H`/fine_tuning/checkpoints/${W}/permissions/${$}`,Z)}}class Nw extends E{constructor(){super(...arguments);this.permissions=new H4(this._client)}}Nw.Permissions=H4;class F4 extends E{list($,w={},Z){return this._client.getAPIList(H`/fine_tuning/jobs/${$}/checkpoints`,g,{query:w,...Z})}}class Bw extends E{constructor(){super(...arguments);this.checkpoints=new F4(this._client)}create($,w){return this._client.post("/fine_tuning/jobs",{body:$,...w})}retrieve($,w){return this._client.get(H`/fine_tuning/jobs/${$}`,w)}list($={},w){return this._client.getAPIList("/fine_tuning/jobs",g,{query:$,...w})}cancel($,w){return this._client.post(H`/fine_tuning/jobs/${$}/cancel`,w)}listEvents($,w={},Z){return this._client.getAPIList(H`/fine_tuning/jobs/${$}/events`,g,{query:w,...Z})}pause($,w){return this._client.post(H`/fine_tuning/jobs/${$}/pause`,w)}resume($,w){return this._client.post(H`/fine_tuning/jobs/${$}/resume`,w)}}Bw.Checkpoints=F4;class $$ extends E{constructor(){super(...arguments);this.methods=new q4(this._client),this.jobs=new Bw(this._client),this.checkpoints=new Nw(this._client),this.alpha=new Kw(this._client)}}$$.Methods=q4;$$.Jobs=Bw;$$.Checkpoints=Nw;$$.Alpha=Kw;class O4 extends E{}class L1 extends E{constructor(){super(...arguments);this.graderModels=new O4(this._client)}}L1.GraderModels=O4;class Vw extends E{createVariation($,w){return this._client.post("/images/variations",b0({body:$,...w},this._client))}edit($,w){return this._client.post("/images/edits",b0({body:$,...w,stream:$.stream??!1},this._client))}generate($,w){return this._client.post("/images/generations",{body:$,...w,stream:$.stream??!1})}}class Pw extends E{retrieve($,w){return this._client.get(H`/models/${$}`,w)}list($){return this._client.getAPIList("/models",P$,$)}delete($,w){return this._client.delete(H`/models/${$}`,w)}}class qw extends E{create($,w){return this._client.post("/moderations",{body:$,...w})}}class E4 extends E{create($,w){return this._client.post("/realtime/client_secrets",{body:$,...w})}}class D1 extends E{constructor(){super(...arguments);this.clientSecrets=new E4(this._client)}}D1.ClientSecrets=E4;function sQ($,w){if(!w||!SO(w))return{...$,output_parsed:null,output:$.output.map((Z)=>{if(Z.type==="function_call")return{...Z,parsed_arguments:null};if(Z.type==="message")return{...Z,content:Z.content.map((W)=>({...W,parsed:null}))};else return Z})};return FW($,w)}function FW($,w){let Z=$.output.map((X)=>{if(X.type==="function_call")return{...X,parsed_arguments:jO(w,X)};if(X.type==="message"){let Y=X.content.map((G)=>{if(G.type==="output_text")return{...G,parsed:AO(w,G.text)};return G});return{...X,content:Y}}return X}),W=Object.assign({},$,{output:Z});if(!Object.getOwnPropertyDescriptor($,"output_text"))A6(W);return Object.defineProperty(W,"output_parsed",{enumerable:!0,get(){for(let X of W.output){if(X.type!=="message")continue;for(let Y of X.content)if(Y.type==="output_text"&&Y.parsed!==null)return Y.parsed}return null}}),W}function AO($,w){if($.text?.format?.type!=="json_schema")return null;if("$parseRaw"in $.text?.format)return($.text?.format).$parseRaw(w);return JSON.parse(w)}function SO($){if(r9($.text?.format))return!0;return!1}function RO($){return $?.$brand==="auto-parseable-tool"}function CO($,w){return $.find((Z)=>Z.type==="function"&&Z.name===w)}function jO($,w){let Z=CO($.tools??[],w.name);return{...w,...w,parsed_arguments:RO(Z)?Z.$parseRaw(w.arguments):Z?.strict?JSON.parse(w.arguments):null}}function A6($){let w=[];for(let Z of $.output){if(Z.type!=="message")continue;for(let W of Z.content)if(W.type==="output_text")w.push(W.text)}$.output_text=w.join("")}var Uw,S6,c$,R6,aQ,oQ,eQ,$z;class C6 extends N1{constructor($){super();Uw.add(this),S6.set(this,void 0),c$.set(this,void 0),R6.set(this,void 0),R(this,S6,$,"f")}static createResponse($,w,Z){let W=new C6(w);return W._run(()=>W._createOrRetrieveResponse($,w,{...Z,headers:{...Z?.headers,"X-Stainless-Helper-Method":"stream"}})),W}async _createOrRetrieveResponse($,w,Z){let W=Z?.signal;if(W){if(W.aborted)this.controller.abort();W.addEventListener("abort",()=>this.controller.abort())}V(this,Uw,"m",aQ).call(this);let X,Y=null;if("response_id"in w)X=await $.responses.retrieve(w.response_id,{stream:!0},{...Z,signal:this.controller.signal,stream:!0}),Y=w.starting_after??null;else X=await $.responses.create({...w,stream:!0},{...Z,signal:this.controller.signal});this._connected();for await(let G of X)V(this,Uw,"m",oQ).call(this,G,Y);if(X.controller.signal?.aborted)throw new X0;return V(this,Uw,"m",eQ).call(this)}[(S6=new WeakMap,c$=new WeakMap,R6=new WeakMap,Uw=new WeakSet,aQ=function(){if(this.ended)return;R(this,c$,void 0,"f")},oQ=function(w,Z){if(this.ended)return;let W=(Y,G)=>{if(Z==null||G.sequence_number>Z)this._emit(Y,G)},X=V(this,Uw,"m",$z).call(this,w);switch(W("event",w),w.type){case"response.output_text.delta":{let Y=X.output[w.output_index];if(!Y)throw new k(`missing output at index ${w.output_index}`);if(Y.type==="message"){let G=Y.content[w.content_index];if(!G)throw new k(`missing content at index ${w.content_index}`);if(G.type!=="output_text")throw new k(`expected content to be 'output_text', got ${G.type}`);W("response.output_text.delta",{...w,snapshot:G.text})}break}case"response.function_call_arguments.delta":{let Y=X.output[w.output_index];if(!Y)throw new k(`missing output at index ${w.output_index}`);if(Y.type==="function_call")W("response.function_call_arguments.delta",{...w,snapshot:Y.arguments});break}default:W(w.type,w);break}},eQ=function(){if(this.ended)throw new k("stream has ended, this shouldn't happen");let w=V(this,c$,"f");if(!w)throw new k("request ended without sending any events");R(this,c$,void 0,"f");let Z=IO(w,V(this,S6,"f"));return R(this,R6,Z,"f"),Z},$z=function(w){let Z=V(this,c$,"f");if(!Z){if(w.type!=="response.created")throw new k(`When snapshot hasn't been set yet, expected 'response.created' event, got ${w.type}`);return Z=R(this,c$,w.response,"f"),Z}switch(w.type){case"response.output_item.added":{Z.output.push(w.item);break}case"response.content_part.added":{let W=Z.output[w.output_index];if(!W)throw new k(`missing output at index ${w.output_index}`);let X=W.type,Y=w.part;if(X==="message"&&Y.type!=="reasoning_text")W.content.push(Y);else if(X==="reasoning"&&Y.type==="reasoning_text"){if(!W.content)W.content=[];W.content.push(Y)}break}case"response.output_text.delta":{let W=Z.output[w.output_index];if(!W)throw new k(`missing output at index ${w.output_index}`);if(W.type==="message"){let X=W.content[w.content_index];if(!X)throw new k(`missing content at index ${w.content_index}`);if(X.type!=="output_text")throw new k(`expected content to be 'output_text', got ${X.type}`);X.text+=w.delta}break}case"response.function_call_arguments.delta":{let W=Z.output[w.output_index];if(!W)throw new k(`missing output at index ${w.output_index}`);if(W.type==="function_call")W.arguments+=w.delta;break}case"response.reasoning_text.delta":{let W=Z.output[w.output_index];if(!W)throw new k(`missing output at index ${w.output_index}`);if(W.type==="reasoning"){let X=W.content?.[w.content_index];if(!X)throw new k(`missing content at index ${w.content_index}`);if(X.type!=="reasoning_text")throw new k(`expected content to be 'reasoning_text', got ${X.type}`);X.text+=w.delta}break}case"response.completed":{R(this,c$,w.response,"f");break}}return Z},Symbol.asyncIterator)](){let $=[],w=[],Z=!1;return this.on("event",(W)=>{let X=w.shift();if(X)X.resolve(W);else $.push(W)}),this.on("end",()=>{Z=!0;for(let W of w)W.resolve(void 0);w.length=0}),this.on("abort",(W)=>{Z=!0;for(let X of w)X.reject(W);w.length=0}),this.on("error",(W)=>{Z=!0;for(let X of w)X.reject(W);w.length=0}),{next:async()=>{if(!$.length){if(Z)return{value:void 0,done:!0};return new Promise((X,Y)=>w.push({resolve:X,reject:Y})).then((X)=>X?{value:X,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}async finalResponse(){await this.done();let $=V(this,R6,"f");if(!$)throw new k("stream ended without producing a ChatCompletion");return $}}function IO($,w){return sQ($,w)}class L4 extends E{list($,w={},Z){return this._client.getAPIList(H`/responses/${$}/input_items`,g,{query:w,...Z})}}class f1 extends E{constructor(){super(...arguments);this.inputItems=new L4(this._client)}create($,w){return this._client.post("/responses",{body:$,...w,stream:$.stream??!1})._thenUnwrap((Z)=>{if("object"in Z&&Z.object==="response")A6(Z);return Z})}retrieve($,w={},Z){return this._client.get(H`/responses/${$}`,{query:w,...Z,stream:w?.stream??!1})._thenUnwrap((W)=>{if("object"in W&&W.object==="response")A6(W);return W})}delete($,w){return this._client.delete(H`/responses/${$}`,{...w,headers:D([{Accept:"*/*"},w?.headers])})}parse($,w){return this._client.responses.create($,w)._thenUnwrap((Z)=>FW(Z,$))}stream($,w){return C6.createResponse(this._client,$,w)}cancel($,w){return this._client.post(H`/responses/${$}/cancel`,w)}}f1.InputItems=L4;class D4 extends E{create($,w,Z){return this._client.post(H`/uploads/${$}/parts`,b0({body:w,...Z},this._client))}}class k1 extends E{constructor(){super(...arguments);this.parts=new D4(this._client)}create($,w){return this._client.post("/uploads",{body:$,...w})}cancel($,w){return this._client.post(H`/uploads/${$}/cancel`,w)}complete($,w,Z){return this._client.post(H`/uploads/${$}/complete`,{body:w,...Z})}}k1.Parts=D4;var wz=async($)=>{let w=await Promise.allSettled($),Z=w.filter((X)=>X.status==="rejected");if(Z.length){for(let X of Z)console.error(X.reason);throw Error(`${Z.length} promise(s) failed - see the above errors`)}let W=[];for(let X of w)if(X.status==="fulfilled")W.push(X.value);return W};class f4 extends E{create($,w,Z){return this._client.post(H`/vector_stores/${$}/file_batches`,{body:w,...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}retrieve($,w,Z){let{vector_store_id:W}=w;return this._client.get(H`/vector_stores/${W}/file_batches/${$}`,{...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}cancel($,w,Z){let{vector_store_id:W}=w;return this._client.post(H`/vector_stores/${W}/file_batches/${$}/cancel`,{...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}async createAndPoll($,w,Z){let W=await this.create($,w);return await this.poll($,W.id,Z)}listFiles($,w,Z){let{vector_store_id:W,...X}=w;return this._client.getAPIList(H`/vector_stores/${W}/file_batches/${$}/files`,g,{query:X,...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}async poll($,w,Z){let W=D([Z?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":Z?.pollIntervalMs?.toString()??void 0}]);while(!0){let{data:X,response:Y}=await this.retrieve(w,{vector_store_id:$},{...Z,headers:W}).withResponse();switch(X.status){case"in_progress":let G=5000;if(Z?.pollIntervalMs)G=Z.pollIntervalMs;else{let J=Y.headers.get("openai-poll-after-ms");if(J){let Q=parseInt(J);if(!isNaN(Q))G=Q}}await a0(G);break;case"failed":case"cancelled":case"completed":return X}}}async uploadAndPoll($,{files:w,fileIds:Z=[]},W){if(w==null||w.length==0)throw Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let X=W?.maxConcurrency??5,Y=Math.min(X,w.length),G=this._client,J=w.values(),Q=[...Z];async function z(T){for(let K of T){let N=await G.files.create({file:K,purpose:"assistants"},W);Q.push(N.id)}}let M=Array(Y).fill(J).map(z);return await wz(M),await this.createAndPoll($,{file_ids:Q})}}class k4 extends E{create($,w,Z){return this._client.post(H`/vector_stores/${$}/files`,{body:w,...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}retrieve($,w,Z){let{vector_store_id:W}=w;return this._client.get(H`/vector_stores/${W}/files/${$}`,{...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}update($,w,Z){let{vector_store_id:W,...X}=w;return this._client.post(H`/vector_stores/${W}/files/${$}`,{body:X,...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}list($,w={},Z){return this._client.getAPIList(H`/vector_stores/${$}/files`,g,{query:w,...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}delete($,w,Z){let{vector_store_id:W}=w;return this._client.delete(H`/vector_stores/${W}/files/${$}`,{...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}async createAndPoll($,w,Z){let W=await this.create($,w,Z);return await this.poll($,W.id,Z)}async poll($,w,Z){let W=D([Z?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":Z?.pollIntervalMs?.toString()??void 0}]);while(!0){let X=await this.retrieve(w,{vector_store_id:$},{...Z,headers:W}).withResponse(),Y=X.data;switch(Y.status){case"in_progress":let G=5000;if(Z?.pollIntervalMs)G=Z.pollIntervalMs;else{let J=X.response.headers.get("openai-poll-after-ms");if(J){let Q=parseInt(J);if(!isNaN(Q))G=Q}}await a0(G);break;case"failed":case"completed":return Y}}}async upload($,w,Z){let W=await this._client.files.create({file:w,purpose:"assistants"},Z);return this.create($,{file_id:W.id},Z)}async uploadAndPoll($,w,Z){let W=await this.upload($,w,Z);return await this.poll($,W.id,Z)}content($,w,Z){let{vector_store_id:W}=w;return this._client.getAPIList(H`/vector_stores/${W}/files/${$}/content`,P$,{...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}}class d$ extends E{constructor(){super(...arguments);this.files=new k4(this._client),this.fileBatches=new f4(this._client)}create($,w){return this._client.post("/vector_stores",{body:$,...w,headers:D([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}retrieve($,w){return this._client.get(H`/vector_stores/${$}`,{...w,headers:D([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}update($,w,Z){return this._client.post(H`/vector_stores/${$}`,{body:w,...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}list($={},w){return this._client.getAPIList("/vector_stores",g,{query:$,...w,headers:D([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}delete($,w){return this._client.delete(H`/vector_stores/${$}`,{...w,headers:D([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}search($,w,Z){return this._client.getAPIList(H`/vector_stores/${$}/search`,P$,{body:w,method:"post",...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}}d$.Files=k4;d$.FileBatches=f4;var Hw,Zz,j6;class Fw extends E{constructor(){super(...arguments);Hw.add(this)}async unwrap($,w,Z=this._client.webhookSecret,W=300){return await this.verifySignature($,w,Z,W),JSON.parse($)}async verifySignature($,w,Z=this._client.webhookSecret,W=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!=="function"||typeof crypto.subtle.verify!=="function")throw Error("Webhook signature verification is only supported when the `crypto` global is defined");V(this,Hw,"m",Zz).call(this,Z);let X=D([w]).values,Y=V(this,Hw,"m",j6).call(this,X,"webhook-signature"),G=V(this,Hw,"m",j6).call(this,X,"webhook-timestamp"),J=V(this,Hw,"m",j6).call(this,X,"webhook-id"),Q=parseInt(G,10);if(isNaN(Q))throw new B$("Invalid webhook timestamp format");let z=Math.floor(Date.now()/1000);if(z-Q>W)throw new B$("Webhook timestamp is too old");if(Q>z+W)throw new B$("Webhook timestamp is too new");let M=Y.split(" ").map((B)=>B.startsWith("v1,")?B.substring(3):B),T=Z.startsWith("whsec_")?Buffer.from(Z.replace("whsec_",""),"base64"):Buffer.from(Z,"utf-8"),K=J?`${J}.${G}.${$}`:`${G}.${$}`,N=await crypto.subtle.importKey("raw",T,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let B of M)try{let P=Buffer.from(B,"base64");if(await crypto.subtle.verify("HMAC",N,P,new TextEncoder().encode(K)))return}catch{continue}throw new B$("The given webhook signature does not match the expected signature")}}Hw=new WeakSet,Zz=function(w){if(typeof w!=="string"||w.length===0)throw Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},j6=function(w,Z){if(!w)throw Error("Headers are required");let W=w.get(Z);if(W===null||W===void 0)throw Error(`Missing required header: ${Z}`);return W};var OW,EW,I6,Wz;class x{constructor({baseURL:$=m$("OPENAI_BASE_URL"),apiKey:w=m$("OPENAI_API_KEY"),organization:Z=m$("OPENAI_ORG_ID")??null,project:W=m$("OPENAI_PROJECT_ID")??null,webhookSecret:X=m$("OPENAI_WEBHOOK_SECRET")??null,...Y}={}){if(OW.add(this),I6.set(this,void 0),this.completions=new Jw(this),this.chat=new B1(this),this.embeddings=new zw(this),this.files=new Tw(this),this.images=new Vw(this),this.audio=new H$(this),this.moderations=new qw(this),this.models=new Pw(this),this.fineTuning=new $$(this),this.graders=new L1(this),this.vectorStores=new d$(this),this.webhooks=new Fw(this),this.beta=new F$(this),this.batches=new Xw(this),this.uploads=new k1(this),this.responses=new f1(this),this.realtime=new D1(this),this.conversations=new O1(this),this.evals=new E1(this),this.containers=new F1(this),w===void 0)throw new k("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");let G={apiKey:w,organization:Z,project:W,webhookSecret:X,...Y,baseURL:$||"https://api.openai.com/v1"};if(!G.dangerouslyAllowBrowser&&JQ())throw new k(`It looks like you're running in a browser-like environment.
|
|
102
|
+
${E6($)}`);return{...r,id:i,type:u,function:{...q0,name:h,arguments:z0}}})}};return{...K,message:{...U,content:B,role:O,refusal:z.refusal??null},finish_reason:M,index:T,logprobs:N}}),created:X,model:Y,object:"chat.completion",...G?{system_fingerprint:G}:{}};return jQ(Q,w)}function E6($){return JSON.stringify($)}function mQ($){return}function lQ($){}class Ww extends h${static fromReadableStream($){let w=new Ww(null);return w._run(()=>w._fromReadableStream($)),w}static runTools($,w,Z){let W=new Ww(w),X={...Z,headers:{...Z?.headers,"X-Stainless-Helper-Method":"runTools"}};return W._run(()=>W._runTools($,w,X)),W}}class i$ extends E{constructor(){super(...arguments);this.messages=new e1(this._client)}create($,w){return this._client.post("/chat/completions",{body:$,...w,stream:$.stream??!1})}retrieve($,w){return this._client.get(H`/chat/completions/${$}`,w)}update($,w,Z){return this._client.post(H`/chat/completions/${$}`,{body:w,...Z})}list($={},w){return this._client.getAPIList("/chat/completions",g,{query:$,...w})}delete($,w){return this._client.delete(H`/chat/completions/${$}`,w)}parse($,w){return bQ($.tools),this._client.chat.completions.create($,{...w,headers:{...w?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap((Z)=>s9(Z,$))}runTools($,w){if($.stream)return Ww.runTools(this._client,$,w);return Z4.runTools(this._client,$,w)}stream($,w){return h$.createChatCompletion(this._client,$,w)}}i$.Messages=e1;class B1 extends E{constructor(){super(...arguments);this.completions=new i$(this._client)}}B1.Completions=i$;var cQ=Symbol("brand.privateNullableHeaders");function*WO($){if(!$)return;if(cQ in $){let{values:W,nulls:X}=$;yield*W.entries();for(let Y of X)yield[Y,null];return}let w=!1,Z;if($ instanceof Headers)Z=$.entries();else if(l5($))Z=$;else w=!0,Z=Object.entries($??{});for(let W of Z){let X=W[0];if(typeof X!=="string")throw TypeError("expected header name to be a string");let Y=l5(W[1])?W[1]:[W[1]],G=!1;for(let J of Y){if(J===void 0)continue;if(w&&!G)G=!0,yield[X,null];yield[X,J]}}}var D=($)=>{let w=new Headers,Z=new Set;for(let W of $){let X=new Set;for(let[Y,G]of WO(W)){let J=Y.toLowerCase();if(!X.has(J))w.delete(Y),X.add(J);if(G===null)w.delete(Y),Z.add(J);else w.append(Y,G),Z.delete(J)}}return{[cQ]:!0,values:w,nulls:Z}};class W4 extends E{create($,w){return this._client.post("/audio/speech",{body:$,...w,headers:D([{Accept:"application/octet-stream"},w?.headers]),__binaryResponse:!0})}}class X4 extends E{create($,w){return this._client.post("/audio/transcriptions",b0({body:$,...w,stream:$.stream??!1,__metadata:{model:$.model}},this._client))}}class Y4 extends E{create($,w){return this._client.post("/audio/translations",b0({body:$,...w,__metadata:{model:$.model}},this._client))}}class F$ extends E{constructor(){super(...arguments);this.transcriptions=new X4(this._client),this.translations=new Y4(this._client),this.speech=new W4(this._client)}}F$.Transcriptions=X4;F$.Translations=Y4;F$.Speech=W4;class Xw extends E{create($,w){return this._client.post("/batches",{body:$,...w})}retrieve($,w){return this._client.get(H`/batches/${$}`,w)}list($={},w){return this._client.getAPIList("/batches",g,{query:$,...w})}cancel($,w){return this._client.post(H`/batches/${$}/cancel`,w)}}class G4 extends E{create($,w){return this._client.post("/assistants",{body:$,...w,headers:D([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}retrieve($,w){return this._client.get(H`/assistants/${$}`,{...w,headers:D([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}update($,w,Z){return this._client.post(H`/assistants/${$}`,{body:w,...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}list($={},w){return this._client.getAPIList("/assistants",g,{query:$,...w,headers:D([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}delete($,w){return this._client.delete(H`/assistants/${$}`,{...w,headers:D([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}}class J4 extends E{create($,w){return this._client.post("/realtime/sessions",{body:$,...w,headers:D([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}}class Q4 extends E{create($,w){return this._client.post("/realtime/transcription_sessions",{body:$,...w,headers:D([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}}class V1 extends E{constructor(){super(...arguments);this.sessions=new J4(this._client),this.transcriptionSessions=new Q4(this._client)}}V1.Sessions=J4;V1.TranscriptionSessions=Q4;class z4 extends E{create($,w,Z){return this._client.post(H`/threads/${$}/messages`,{body:w,...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}retrieve($,w,Z){let{thread_id:W}=w;return this._client.get(H`/threads/${W}/messages/${$}`,{...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}update($,w,Z){let{thread_id:W,...X}=w;return this._client.post(H`/threads/${W}/messages/${$}`,{body:X,...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}list($,w={},Z){return this._client.getAPIList(H`/threads/${$}/messages`,g,{query:w,...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}delete($,w,Z){let{thread_id:W}=w;return this._client.delete(H`/threads/${W}/messages/${$}`,{...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}}class M4 extends E{retrieve($,w,Z){let{thread_id:W,run_id:X,...Y}=w;return this._client.get(H`/threads/${W}/runs/${X}/steps/${$}`,{query:Y,...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}list($,w,Z){let{thread_id:W,...X}=w;return this._client.getAPIList(H`/threads/${W}/runs/${$}/steps`,g,{query:X,...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}}var dQ=($)=>{if(typeof Buffer<"u"){let w=Buffer.from($,"base64");return Array.from(new Float32Array(w.buffer,w.byteOffset,w.length/Float32Array.BYTES_PER_ELEMENT))}else{let w=atob($),Z=w.length,W=new Uint8Array(Z);for(let X=0;X<Z;X++)W[X]=w.charCodeAt(X);return Array.from(new Float32Array(W.buffer))}};var m$=($)=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[$]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.($)?.trim();return};var T0,q1,FW,$$,L6,p0,U1,Yw,P1,k6,x0,D6,f6,K4,T4,N4,pQ,nQ,tQ,rQ,sQ,aQ,oQ;class l$ extends K1{constructor(){super(...arguments);T0.add(this),FW.set(this,[]),$$.set(this,{}),L6.set(this,{}),p0.set(this,void 0),U1.set(this,void 0),Yw.set(this,void 0),P1.set(this,void 0),k6.set(this,void 0),x0.set(this,void 0),D6.set(this,void 0),f6.set(this,void 0),K4.set(this,void 0)}[(FW=new WeakMap,$$=new WeakMap,L6=new WeakMap,p0=new WeakMap,U1=new WeakMap,Yw=new WeakMap,P1=new WeakMap,k6=new WeakMap,x0=new WeakMap,D6=new WeakMap,f6=new WeakMap,K4=new WeakMap,T0=new WeakSet,Symbol.asyncIterator)](){let $=[],w=[],Z=!1;return this.on("event",(W)=>{let X=w.shift();if(X)X.resolve(W);else $.push(W)}),this.on("end",()=>{Z=!0;for(let W of w)W.resolve(void 0);w.length=0}),this.on("abort",(W)=>{Z=!0;for(let X of w)X.reject(W);w.length=0}),this.on("error",(W)=>{Z=!0;for(let X of w)X.reject(W);w.length=0}),{next:async()=>{if(!$.length){if(Z)return{value:void 0,done:!0};return new Promise((X,Y)=>w.push({resolve:X,reject:Y})).then((X)=>X?{value:X,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}static fromReadableStream($){let w=new q1;return w._run(()=>w._fromReadableStream($)),w}async _fromReadableStream($,w){let Z=w?.signal;if(Z){if(Z.aborted)this.controller.abort();Z.addEventListener("abort",()=>this.controller.abort())}this._connected();let W=y0.fromReadableStream($,this.controller);for await(let X of W)V(this,T0,"m",T4).call(this,X);if(W.controller.signal?.aborted)throw new X0;return this._addRun(V(this,T0,"m",N4).call(this))}toReadableStream(){return new y0(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream($,w,Z,W){let X=new q1;return X._run(()=>X._runToolAssistantStream($,w,Z,{...W,headers:{...W?.headers,"X-Stainless-Helper-Method":"stream"}})),X}async _createToolAssistantStream($,w,Z,W){let X=W?.signal;if(X){if(X.aborted)this.controller.abort();X.addEventListener("abort",()=>this.controller.abort())}let Y={...Z,stream:!0},G=await $.submitToolOutputs(w,Y,{...W,signal:this.controller.signal});this._connected();for await(let J of G)V(this,T0,"m",T4).call(this,J);if(G.controller.signal?.aborted)throw new X0;return this._addRun(V(this,T0,"m",N4).call(this))}static createThreadAssistantStream($,w,Z){let W=new q1;return W._run(()=>W._threadAssistantStream($,w,{...Z,headers:{...Z?.headers,"X-Stainless-Helper-Method":"stream"}})),W}static createAssistantStream($,w,Z,W){let X=new q1;return X._run(()=>X._runAssistantStream($,w,Z,{...W,headers:{...W?.headers,"X-Stainless-Helper-Method":"stream"}})),X}currentEvent(){return V(this,D6,"f")}currentRun(){return V(this,f6,"f")}currentMessageSnapshot(){return V(this,p0,"f")}currentRunStepSnapshot(){return V(this,K4,"f")}async finalRunSteps(){return await this.done(),Object.values(V(this,$$,"f"))}async finalMessages(){return await this.done(),Object.values(V(this,L6,"f"))}async finalRun(){if(await this.done(),!V(this,U1,"f"))throw Error("Final run was not received.");return V(this,U1,"f")}async _createThreadAssistantStream($,w,Z){let W=Z?.signal;if(W){if(W.aborted)this.controller.abort();W.addEventListener("abort",()=>this.controller.abort())}let X={...w,stream:!0},Y=await $.createAndRun(X,{...Z,signal:this.controller.signal});this._connected();for await(let G of Y)V(this,T0,"m",T4).call(this,G);if(Y.controller.signal?.aborted)throw new X0;return this._addRun(V(this,T0,"m",N4).call(this))}async _createAssistantStream($,w,Z,W){let X=W?.signal;if(X){if(X.aborted)this.controller.abort();X.addEventListener("abort",()=>this.controller.abort())}let Y={...Z,stream:!0},G=await $.create(w,Y,{...W,signal:this.controller.signal});this._connected();for await(let J of G)V(this,T0,"m",T4).call(this,J);if(G.controller.signal?.aborted)throw new X0;return this._addRun(V(this,T0,"m",N4).call(this))}static accumulateDelta($,w){for(let[Z,W]of Object.entries(w)){if(!$.hasOwnProperty(Z)){$[Z]=W;continue}let X=$[Z];if(X===null||X===void 0){$[Z]=W;continue}if(Z==="index"||Z==="type"){$[Z]=W;continue}if(typeof X==="string"&&typeof W==="string")X+=W;else if(typeof X==="number"&&typeof W==="number")X+=W;else if(l9(X)&&l9(W))X=this.accumulateDelta(X,W);else if(Array.isArray(X)&&Array.isArray(W)){if(X.every((Y)=>typeof Y==="string"||typeof Y==="number")){X.push(...W);continue}for(let Y of W){if(!l9(Y))throw Error(`Expected array delta entry to be an object but got: ${Y}`);let G=Y.index;if(G==null)throw console.error(Y),Error("Expected array delta entry to have an `index` property");if(typeof G!=="number")throw Error(`Expected array delta entry \`index\` property to be a number but got ${G}`);let J=X[G];if(J==null)X.push(Y);else X[G]=this.accumulateDelta(J,Y)}continue}else throw Error(`Unhandled record type: ${Z}, deltaValue: ${W}, accValue: ${X}`);$[Z]=X}return $}_addRun($){return $}async _threadAssistantStream($,w,Z){return await this._createThreadAssistantStream(w,$,Z)}async _runAssistantStream($,w,Z,W){return await this._createAssistantStream(w,$,Z,W)}async _runToolAssistantStream($,w,Z,W){return await this._createToolAssistantStream(w,$,Z,W)}}q1=l$,T4=function(w){if(this.ended)return;switch(R(this,D6,w,"f"),V(this,T0,"m",tQ).call(this,w),w.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":V(this,T0,"m",oQ).call(this,w);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":V(this,T0,"m",nQ).call(this,w);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":V(this,T0,"m",pQ).call(this,w);break;case"error":throw Error("Encountered an error event in event processing - errors should be processed earlier");default:KO(w)}},N4=function(){if(this.ended)throw new k("stream has ended, this shouldn't happen");if(!V(this,U1,"f"))throw Error("Final run has not been received");return V(this,U1,"f")},pQ=function(w){let[Z,W]=V(this,T0,"m",sQ).call(this,w,V(this,p0,"f"));R(this,p0,Z,"f"),V(this,L6,"f")[Z.id]=Z;for(let X of W){let Y=Z.content[X.index];if(Y?.type=="text")this._emit("textCreated",Y.text)}switch(w.event){case"thread.message.created":this._emit("messageCreated",w.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",w.data.delta,Z),w.data.delta.content)for(let X of w.data.delta.content){if(X.type=="text"&&X.text){let Y=X.text,G=Z.content[X.index];if(G&&G.type=="text")this._emit("textDelta",Y,G.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(X.index!=V(this,Yw,"f")){if(V(this,P1,"f"))switch(V(this,P1,"f").type){case"text":this._emit("textDone",V(this,P1,"f").text,V(this,p0,"f"));break;case"image_file":this._emit("imageFileDone",V(this,P1,"f").image_file,V(this,p0,"f"));break}R(this,Yw,X.index,"f")}R(this,P1,Z.content[X.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(V(this,Yw,"f")!==void 0){let X=w.data.content[V(this,Yw,"f")];if(X)switch(X.type){case"image_file":this._emit("imageFileDone",X.image_file,V(this,p0,"f"));break;case"text":this._emit("textDone",X.text,V(this,p0,"f"));break}}if(V(this,p0,"f"))this._emit("messageDone",w.data);R(this,p0,void 0,"f")}},nQ=function(w){let Z=V(this,T0,"m",rQ).call(this,w);switch(R(this,K4,Z,"f"),w.event){case"thread.run.step.created":this._emit("runStepCreated",w.data);break;case"thread.run.step.delta":let W=w.data.delta;if(W.step_details&&W.step_details.type=="tool_calls"&&W.step_details.tool_calls&&Z.step_details.type=="tool_calls")for(let Y of W.step_details.tool_calls)if(Y.index==V(this,k6,"f"))this._emit("toolCallDelta",Y,Z.step_details.tool_calls[Y.index]);else{if(V(this,x0,"f"))this._emit("toolCallDone",V(this,x0,"f"));if(R(this,k6,Y.index,"f"),R(this,x0,Z.step_details.tool_calls[Y.index],"f"),V(this,x0,"f"))this._emit("toolCallCreated",V(this,x0,"f"))}this._emit("runStepDelta",w.data.delta,Z);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":if(R(this,K4,void 0,"f"),w.data.step_details.type=="tool_calls"){if(V(this,x0,"f"))this._emit("toolCallDone",V(this,x0,"f")),R(this,x0,void 0,"f")}this._emit("runStepDone",w.data,Z);break;case"thread.run.step.in_progress":break}},tQ=function(w){V(this,FW,"f").push(w),this._emit("event",w)},rQ=function(w){switch(w.event){case"thread.run.step.created":return V(this,$$,"f")[w.data.id]=w.data,w.data;case"thread.run.step.delta":let Z=V(this,$$,"f")[w.data.id];if(!Z)throw Error("Received a RunStepDelta before creation of a snapshot");let W=w.data;if(W.delta){let X=q1.accumulateDelta(Z,W.delta);V(this,$$,"f")[w.data.id]=X}return V(this,$$,"f")[w.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":V(this,$$,"f")[w.data.id]=w.data;break}if(V(this,$$,"f")[w.data.id])return V(this,$$,"f")[w.data.id];throw Error("No snapshot available")},sQ=function(w,Z){let W=[];switch(w.event){case"thread.message.created":return[w.data,W];case"thread.message.delta":if(!Z)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let X=w.data;if(X.delta.content)for(let Y of X.delta.content)if(Y.index in Z.content){let G=Z.content[Y.index];Z.content[Y.index]=V(this,T0,"m",aQ).call(this,Y,G)}else Z.content[Y.index]=Y,W.push(Y);return[Z,W];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(Z)return[Z,W];else throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},aQ=function(w,Z){return q1.accumulateDelta(Z,w)},oQ=function(w){switch(R(this,f6,w.data,"f"),w.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":if(R(this,U1,w.data,"f"),V(this,x0,"f"))this._emit("toolCallDone",V(this,x0,"f")),R(this,x0,void 0,"f");break;case"thread.run.cancelling":break}};function KO($){}class Gw extends E{constructor(){super(...arguments);this.steps=new M4(this._client)}create($,w,Z){let{include:W,...X}=w;return this._client.post(H`/threads/${$}/runs`,{query:{include:W},body:X,...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),stream:w.stream??!1})}retrieve($,w,Z){let{thread_id:W}=w;return this._client.get(H`/threads/${W}/runs/${$}`,{...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}update($,w,Z){let{thread_id:W,...X}=w;return this._client.post(H`/threads/${W}/runs/${$}`,{body:X,...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}list($,w={},Z){return this._client.getAPIList(H`/threads/${$}/runs`,g,{query:w,...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}cancel($,w,Z){let{thread_id:W}=w;return this._client.post(H`/threads/${W}/runs/${$}/cancel`,{...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}async createAndPoll($,w,Z){let W=await this.create($,w,Z);return await this.poll(W.id,{thread_id:$},Z)}createAndStream($,w,Z){return l$.createAssistantStream($,this._client.beta.threads.runs,w,Z)}async poll($,w,Z){let W=D([Z?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":Z?.pollIntervalMs?.toString()??void 0}]);while(!0){let{data:X,response:Y}=await this.retrieve($,w,{...Z,headers:{...Z?.headers,...W}}).withResponse();switch(X.status){case"queued":case"in_progress":case"cancelling":let G=5000;if(Z?.pollIntervalMs)G=Z.pollIntervalMs;else{let J=Y.headers.get("openai-poll-after-ms");if(J){let Q=parseInt(J);if(!isNaN(Q))G=Q}}await o0(G);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return X}}}stream($,w,Z){return l$.createAssistantStream($,this._client.beta.threads.runs,w,Z)}submitToolOutputs($,w,Z){let{thread_id:W,...X}=w;return this._client.post(H`/threads/${W}/runs/${$}/submit_tool_outputs`,{body:X,...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),stream:w.stream??!1})}async submitToolOutputsAndPoll($,w,Z){let W=await this.submitToolOutputs($,w,Z);return await this.poll(W.id,w,Z)}submitToolOutputsStream($,w,Z){return l$.createToolAssistantStream($,this._client.beta.threads.runs,w,Z)}}Gw.Steps=M4;class H1 extends E{constructor(){super(...arguments);this.runs=new Gw(this._client),this.messages=new z4(this._client)}create($={},w){return this._client.post("/threads",{body:$,...w,headers:D([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}retrieve($,w){return this._client.get(H`/threads/${$}`,{...w,headers:D([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}update($,w,Z){return this._client.post(H`/threads/${$}`,{body:w,...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}delete($,w){return this._client.delete(H`/threads/${$}`,{...w,headers:D([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}createAndRun($,w){return this._client.post("/threads/runs",{body:$,...w,headers:D([{"OpenAI-Beta":"assistants=v2"},w?.headers]),stream:$.stream??!1})}async createAndRunPoll($,w){let Z=await this.createAndRun($,w);return await this.runs.poll(Z.id,{thread_id:Z.thread_id},w)}createAndRunStream($,w){return l$.createThreadAssistantStream($,this._client.beta.threads,w)}}H1.Runs=Gw;H1.Messages=z4;class O$ extends E{constructor(){super(...arguments);this.realtime=new V1(this._client),this.assistants=new G4(this._client),this.threads=new H1(this._client)}}O$.Realtime=V1;O$.Assistants=G4;O$.Threads=H1;class Jw extends E{create($,w){return this._client.post("/completions",{body:$,...w,stream:$.stream??!1})}}class B4 extends E{retrieve($,w,Z){let{container_id:W}=w;return this._client.get(H`/containers/${W}/files/${$}/content`,{...Z,headers:D([{Accept:"application/binary"},Z?.headers]),__binaryResponse:!0})}}class Qw extends E{constructor(){super(...arguments);this.content=new B4(this._client)}create($,w,Z){return this._client.post(H`/containers/${$}/files`,b0({body:w,...Z},this._client))}retrieve($,w,Z){let{container_id:W}=w;return this._client.get(H`/containers/${W}/files/${$}`,Z)}list($,w={},Z){return this._client.getAPIList(H`/containers/${$}/files`,g,{query:w,...Z})}delete($,w,Z){let{container_id:W}=w;return this._client.delete(H`/containers/${W}/files/${$}`,{...Z,headers:D([{Accept:"*/*"},Z?.headers])})}}Qw.Content=B4;class F1 extends E{constructor(){super(...arguments);this.files=new Qw(this._client)}create($,w){return this._client.post("/containers",{body:$,...w})}retrieve($,w){return this._client.get(H`/containers/${$}`,w)}list($={},w){return this._client.getAPIList("/containers",g,{query:$,...w})}delete($,w){return this._client.delete(H`/containers/${$}`,{...w,headers:D([{Accept:"*/*"},w?.headers])})}}F1.Files=Qw;class V4 extends E{create($,w,Z){let{include:W,...X}=w;return this._client.post(H`/conversations/${$}/items`,{query:{include:W},body:X,...Z})}retrieve($,w,Z){let{conversation_id:W,...X}=w;return this._client.get(H`/conversations/${W}/items/${$}`,{query:X,...Z})}list($,w={},Z){return this._client.getAPIList(H`/conversations/${$}/items`,ZW,{query:w,...Z})}delete($,w,Z){let{conversation_id:W}=w;return this._client.delete(H`/conversations/${W}/items/${$}`,Z)}}class O1 extends E{constructor(){super(...arguments);this.items=new V4(this._client)}create($={},w){return this._client.post("/conversations",{body:$,...w})}retrieve($,w){return this._client.get(H`/conversations/${$}`,w)}update($,w,Z){return this._client.post(H`/conversations/${$}`,{body:w,...Z})}delete($,w){return this._client.delete(H`/conversations/${$}`,w)}}O1.Items=V4;class zw extends E{create($,w){let Z=!!$.encoding_format,W=Z?$.encoding_format:"base64";if(Z)$0(this._client).debug("embeddings/user defined encoding_format:",$.encoding_format);let X=this._client.post("/embeddings",{body:{...$,encoding_format:W},...w});if(Z)return X;return $0(this._client).debug("embeddings/decoding base64 embeddings from base64"),X._thenUnwrap((Y)=>{if(Y&&Y.data)Y.data.forEach((G)=>{let J=G.embedding;G.embedding=dQ(J)});return Y})}}class P4 extends E{retrieve($,w,Z){let{eval_id:W,run_id:X}=w;return this._client.get(H`/evals/${W}/runs/${X}/output_items/${$}`,Z)}list($,w,Z){let{eval_id:W,...X}=w;return this._client.getAPIList(H`/evals/${W}/runs/${$}/output_items`,g,{query:X,...Z})}}class Mw extends E{constructor(){super(...arguments);this.outputItems=new P4(this._client)}create($,w,Z){return this._client.post(H`/evals/${$}/runs`,{body:w,...Z})}retrieve($,w,Z){let{eval_id:W}=w;return this._client.get(H`/evals/${W}/runs/${$}`,Z)}list($,w={},Z){return this._client.getAPIList(H`/evals/${$}/runs`,g,{query:w,...Z})}delete($,w,Z){let{eval_id:W}=w;return this._client.delete(H`/evals/${W}/runs/${$}`,Z)}cancel($,w,Z){let{eval_id:W}=w;return this._client.post(H`/evals/${W}/runs/${$}`,Z)}}Mw.OutputItems=P4;class E1 extends E{constructor(){super(...arguments);this.runs=new Mw(this._client)}create($,w){return this._client.post("/evals",{body:$,...w})}retrieve($,w){return this._client.get(H`/evals/${$}`,w)}update($,w,Z){return this._client.post(H`/evals/${$}`,{body:w,...Z})}list($={},w){return this._client.getAPIList("/evals",g,{query:$,...w})}delete($,w){return this._client.delete(H`/evals/${$}`,w)}}E1.Runs=Mw;class Tw extends E{create($,w){return this._client.post("/files",b0({body:$,...w},this._client))}retrieve($,w){return this._client.get(H`/files/${$}`,w)}list($={},w){return this._client.getAPIList("/files",g,{query:$,...w})}delete($,w){return this._client.delete(H`/files/${$}`,w)}content($,w){return this._client.get(H`/files/${$}/content`,{...w,headers:D([{Accept:"application/binary"},w?.headers]),__binaryResponse:!0})}async waitForProcessing($,{pollInterval:w=5000,maxWait:Z=1800000}={}){let W=new Set(["processed","error","deleted"]),X=Date.now(),Y=await this.retrieve($);while(!Y.status||!W.has(Y.status))if(await o0(w),Y=await this.retrieve($),Date.now()-X>Z)throw new M1({message:`Giving up on waiting for file ${$} to finish processing after ${Z} milliseconds.`});return Y}}class q4 extends E{}class U4 extends E{run($,w){return this._client.post("/fine_tuning/alpha/graders/run",{body:$,...w})}validate($,w){return this._client.post("/fine_tuning/alpha/graders/validate",{body:$,...w})}}class Nw extends E{constructor(){super(...arguments);this.graders=new U4(this._client)}}Nw.Graders=U4;class H4 extends E{create($,w,Z){return this._client.getAPIList(H`/fine_tuning/checkpoints/${$}/permissions`,q$,{body:w,method:"post",...Z})}retrieve($,w={},Z){return this._client.get(H`/fine_tuning/checkpoints/${$}/permissions`,{query:w,...Z})}delete($,w,Z){let{fine_tuned_model_checkpoint:W}=w;return this._client.delete(H`/fine_tuning/checkpoints/${W}/permissions/${$}`,Z)}}class Kw extends E{constructor(){super(...arguments);this.permissions=new H4(this._client)}}Kw.Permissions=H4;class F4 extends E{list($,w={},Z){return this._client.getAPIList(H`/fine_tuning/jobs/${$}/checkpoints`,g,{query:w,...Z})}}class Bw extends E{constructor(){super(...arguments);this.checkpoints=new F4(this._client)}create($,w){return this._client.post("/fine_tuning/jobs",{body:$,...w})}retrieve($,w){return this._client.get(H`/fine_tuning/jobs/${$}`,w)}list($={},w){return this._client.getAPIList("/fine_tuning/jobs",g,{query:$,...w})}cancel($,w){return this._client.post(H`/fine_tuning/jobs/${$}/cancel`,w)}listEvents($,w={},Z){return this._client.getAPIList(H`/fine_tuning/jobs/${$}/events`,g,{query:w,...Z})}pause($,w){return this._client.post(H`/fine_tuning/jobs/${$}/pause`,w)}resume($,w){return this._client.post(H`/fine_tuning/jobs/${$}/resume`,w)}}Bw.Checkpoints=F4;class w$ extends E{constructor(){super(...arguments);this.methods=new q4(this._client),this.jobs=new Bw(this._client),this.checkpoints=new Kw(this._client),this.alpha=new Nw(this._client)}}w$.Methods=q4;w$.Jobs=Bw;w$.Checkpoints=Kw;w$.Alpha=Nw;class O4 extends E{}class L1 extends E{constructor(){super(...arguments);this.graderModels=new O4(this._client)}}L1.GraderModels=O4;class Vw extends E{createVariation($,w){return this._client.post("/images/variations",b0({body:$,...w},this._client))}edit($,w){return this._client.post("/images/edits",b0({body:$,...w,stream:$.stream??!1},this._client))}generate($,w){return this._client.post("/images/generations",{body:$,...w,stream:$.stream??!1})}}class Pw extends E{retrieve($,w){return this._client.get(H`/models/${$}`,w)}list($){return this._client.getAPIList("/models",q$,$)}delete($,w){return this._client.delete(H`/models/${$}`,w)}}class qw extends E{create($,w){return this._client.post("/moderations",{body:$,...w})}}class E4 extends E{create($,w){return this._client.post("/realtime/client_secrets",{body:$,...w})}}class D1 extends E{constructor(){super(...arguments);this.clientSecrets=new E4(this._client)}}D1.ClientSecrets=E4;function eQ($,w){if(!w||!jO(w))return{...$,output_parsed:null,output:$.output.map((Z)=>{if(Z.type==="function_call")return{...Z,parsed_arguments:null};if(Z.type==="message")return{...Z,content:Z.content.map((W)=>({...W,parsed:null}))};else return Z})};return OW($,w)}function OW($,w){let Z=$.output.map((X)=>{if(X.type==="function_call")return{...X,parsed_arguments:bO(w,X)};if(X.type==="message"){let Y=X.content.map((G)=>{if(G.type==="output_text")return{...G,parsed:CO(w,G.text)};return G});return{...X,content:Y}}return X}),W=Object.assign({},$,{output:Z});if(!Object.getOwnPropertyDescriptor($,"output_text"))A6(W);return Object.defineProperty(W,"output_parsed",{enumerable:!0,get(){for(let X of W.output){if(X.type!=="message")continue;for(let Y of X.content)if(Y.type==="output_text"&&Y.parsed!==null)return Y.parsed}return null}}),W}function CO($,w){if($.text?.format?.type!=="json_schema")return null;if("$parseRaw"in $.text?.format)return($.text?.format).$parseRaw(w);return JSON.parse(w)}function jO($){if(r9($.text?.format))return!0;return!1}function IO($){return $?.$brand==="auto-parseable-tool"}function yO($,w){return $.find((Z)=>Z.type==="function"&&Z.name===w)}function bO($,w){let Z=yO($.tools??[],w.name);return{...w,...w,parsed_arguments:IO(Z)?Z.$parseRaw(w.arguments):Z?.strict?JSON.parse(w.arguments):null}}function A6($){let w=[];for(let Z of $.output){if(Z.type!=="message")continue;for(let W of Z.content)if(W.type==="output_text")w.push(W.text)}$.output_text=w.join("")}var Uw,S6,c$,R6,$z,wz,Zz,Wz;class C6 extends K1{constructor($){super();Uw.add(this),S6.set(this,void 0),c$.set(this,void 0),R6.set(this,void 0),R(this,S6,$,"f")}static createResponse($,w,Z){let W=new C6(w);return W._run(()=>W._createOrRetrieveResponse($,w,{...Z,headers:{...Z?.headers,"X-Stainless-Helper-Method":"stream"}})),W}async _createOrRetrieveResponse($,w,Z){let W=Z?.signal;if(W){if(W.aborted)this.controller.abort();W.addEventListener("abort",()=>this.controller.abort())}V(this,Uw,"m",$z).call(this);let X,Y=null;if("response_id"in w)X=await $.responses.retrieve(w.response_id,{stream:!0},{...Z,signal:this.controller.signal,stream:!0}),Y=w.starting_after??null;else X=await $.responses.create({...w,stream:!0},{...Z,signal:this.controller.signal});this._connected();for await(let G of X)V(this,Uw,"m",wz).call(this,G,Y);if(X.controller.signal?.aborted)throw new X0;return V(this,Uw,"m",Zz).call(this)}[(S6=new WeakMap,c$=new WeakMap,R6=new WeakMap,Uw=new WeakSet,$z=function(){if(this.ended)return;R(this,c$,void 0,"f")},wz=function(w,Z){if(this.ended)return;let W=(Y,G)=>{if(Z==null||G.sequence_number>Z)this._emit(Y,G)},X=V(this,Uw,"m",Wz).call(this,w);switch(W("event",w),w.type){case"response.output_text.delta":{let Y=X.output[w.output_index];if(!Y)throw new k(`missing output at index ${w.output_index}`);if(Y.type==="message"){let G=Y.content[w.content_index];if(!G)throw new k(`missing content at index ${w.content_index}`);if(G.type!=="output_text")throw new k(`expected content to be 'output_text', got ${G.type}`);W("response.output_text.delta",{...w,snapshot:G.text})}break}case"response.function_call_arguments.delta":{let Y=X.output[w.output_index];if(!Y)throw new k(`missing output at index ${w.output_index}`);if(Y.type==="function_call")W("response.function_call_arguments.delta",{...w,snapshot:Y.arguments});break}default:W(w.type,w);break}},Zz=function(){if(this.ended)throw new k("stream has ended, this shouldn't happen");let w=V(this,c$,"f");if(!w)throw new k("request ended without sending any events");R(this,c$,void 0,"f");let Z=xO(w,V(this,S6,"f"));return R(this,R6,Z,"f"),Z},Wz=function(w){let Z=V(this,c$,"f");if(!Z){if(w.type!=="response.created")throw new k(`When snapshot hasn't been set yet, expected 'response.created' event, got ${w.type}`);return Z=R(this,c$,w.response,"f"),Z}switch(w.type){case"response.output_item.added":{Z.output.push(w.item);break}case"response.content_part.added":{let W=Z.output[w.output_index];if(!W)throw new k(`missing output at index ${w.output_index}`);let X=W.type,Y=w.part;if(X==="message"&&Y.type!=="reasoning_text")W.content.push(Y);else if(X==="reasoning"&&Y.type==="reasoning_text"){if(!W.content)W.content=[];W.content.push(Y)}break}case"response.output_text.delta":{let W=Z.output[w.output_index];if(!W)throw new k(`missing output at index ${w.output_index}`);if(W.type==="message"){let X=W.content[w.content_index];if(!X)throw new k(`missing content at index ${w.content_index}`);if(X.type!=="output_text")throw new k(`expected content to be 'output_text', got ${X.type}`);X.text+=w.delta}break}case"response.function_call_arguments.delta":{let W=Z.output[w.output_index];if(!W)throw new k(`missing output at index ${w.output_index}`);if(W.type==="function_call")W.arguments+=w.delta;break}case"response.reasoning_text.delta":{let W=Z.output[w.output_index];if(!W)throw new k(`missing output at index ${w.output_index}`);if(W.type==="reasoning"){let X=W.content?.[w.content_index];if(!X)throw new k(`missing content at index ${w.content_index}`);if(X.type!=="reasoning_text")throw new k(`expected content to be 'reasoning_text', got ${X.type}`);X.text+=w.delta}break}case"response.completed":{R(this,c$,w.response,"f");break}}return Z},Symbol.asyncIterator)](){let $=[],w=[],Z=!1;return this.on("event",(W)=>{let X=w.shift();if(X)X.resolve(W);else $.push(W)}),this.on("end",()=>{Z=!0;for(let W of w)W.resolve(void 0);w.length=0}),this.on("abort",(W)=>{Z=!0;for(let X of w)X.reject(W);w.length=0}),this.on("error",(W)=>{Z=!0;for(let X of w)X.reject(W);w.length=0}),{next:async()=>{if(!$.length){if(Z)return{value:void 0,done:!0};return new Promise((X,Y)=>w.push({resolve:X,reject:Y})).then((X)=>X?{value:X,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}async finalResponse(){await this.done();let $=V(this,R6,"f");if(!$)throw new k("stream ended without producing a ChatCompletion");return $}}function xO($,w){return eQ($,w)}class L4 extends E{list($,w={},Z){return this._client.getAPIList(H`/responses/${$}/input_items`,g,{query:w,...Z})}}class f1 extends E{constructor(){super(...arguments);this.inputItems=new L4(this._client)}create($,w){return this._client.post("/responses",{body:$,...w,stream:$.stream??!1})._thenUnwrap((Z)=>{if("object"in Z&&Z.object==="response")A6(Z);return Z})}retrieve($,w={},Z){return this._client.get(H`/responses/${$}`,{query:w,...Z,stream:w?.stream??!1})._thenUnwrap((W)=>{if("object"in W&&W.object==="response")A6(W);return W})}delete($,w){return this._client.delete(H`/responses/${$}`,{...w,headers:D([{Accept:"*/*"},w?.headers])})}parse($,w){return this._client.responses.create($,w)._thenUnwrap((Z)=>OW(Z,$))}stream($,w){return C6.createResponse(this._client,$,w)}cancel($,w){return this._client.post(H`/responses/${$}/cancel`,w)}}f1.InputItems=L4;class D4 extends E{create($,w,Z){return this._client.post(H`/uploads/${$}/parts`,b0({body:w,...Z},this._client))}}class k1 extends E{constructor(){super(...arguments);this.parts=new D4(this._client)}create($,w){return this._client.post("/uploads",{body:$,...w})}cancel($,w){return this._client.post(H`/uploads/${$}/cancel`,w)}complete($,w,Z){return this._client.post(H`/uploads/${$}/complete`,{body:w,...Z})}}k1.Parts=D4;var Xz=async($)=>{let w=await Promise.allSettled($),Z=w.filter((X)=>X.status==="rejected");if(Z.length){for(let X of Z)console.error(X.reason);throw Error(`${Z.length} promise(s) failed - see the above errors`)}let W=[];for(let X of w)if(X.status==="fulfilled")W.push(X.value);return W};class f4 extends E{create($,w,Z){return this._client.post(H`/vector_stores/${$}/file_batches`,{body:w,...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}retrieve($,w,Z){let{vector_store_id:W}=w;return this._client.get(H`/vector_stores/${W}/file_batches/${$}`,{...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}cancel($,w,Z){let{vector_store_id:W}=w;return this._client.post(H`/vector_stores/${W}/file_batches/${$}/cancel`,{...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}async createAndPoll($,w,Z){let W=await this.create($,w);return await this.poll($,W.id,Z)}listFiles($,w,Z){let{vector_store_id:W,...X}=w;return this._client.getAPIList(H`/vector_stores/${W}/file_batches/${$}/files`,g,{query:X,...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}async poll($,w,Z){let W=D([Z?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":Z?.pollIntervalMs?.toString()??void 0}]);while(!0){let{data:X,response:Y}=await this.retrieve(w,{vector_store_id:$},{...Z,headers:W}).withResponse();switch(X.status){case"in_progress":let G=5000;if(Z?.pollIntervalMs)G=Z.pollIntervalMs;else{let J=Y.headers.get("openai-poll-after-ms");if(J){let Q=parseInt(J);if(!isNaN(Q))G=Q}}await o0(G);break;case"failed":case"cancelled":case"completed":return X}}}async uploadAndPoll($,{files:w,fileIds:Z=[]},W){if(w==null||w.length==0)throw Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let X=W?.maxConcurrency??5,Y=Math.min(X,w.length),G=this._client,J=w.values(),Q=[...Z];async function z(T){for(let N of T){let K=await G.files.create({file:N,purpose:"assistants"},W);Q.push(K.id)}}let M=Array(Y).fill(J).map(z);return await Xz(M),await this.createAndPoll($,{file_ids:Q})}}class k4 extends E{create($,w,Z){return this._client.post(H`/vector_stores/${$}/files`,{body:w,...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}retrieve($,w,Z){let{vector_store_id:W}=w;return this._client.get(H`/vector_stores/${W}/files/${$}`,{...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}update($,w,Z){let{vector_store_id:W,...X}=w;return this._client.post(H`/vector_stores/${W}/files/${$}`,{body:X,...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}list($,w={},Z){return this._client.getAPIList(H`/vector_stores/${$}/files`,g,{query:w,...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}delete($,w,Z){let{vector_store_id:W}=w;return this._client.delete(H`/vector_stores/${W}/files/${$}`,{...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}async createAndPoll($,w,Z){let W=await this.create($,w,Z);return await this.poll($,W.id,Z)}async poll($,w,Z){let W=D([Z?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":Z?.pollIntervalMs?.toString()??void 0}]);while(!0){let X=await this.retrieve(w,{vector_store_id:$},{...Z,headers:W}).withResponse(),Y=X.data;switch(Y.status){case"in_progress":let G=5000;if(Z?.pollIntervalMs)G=Z.pollIntervalMs;else{let J=X.response.headers.get("openai-poll-after-ms");if(J){let Q=parseInt(J);if(!isNaN(Q))G=Q}}await o0(G);break;case"failed":case"completed":return Y}}}async upload($,w,Z){let W=await this._client.files.create({file:w,purpose:"assistants"},Z);return this.create($,{file_id:W.id},Z)}async uploadAndPoll($,w,Z){let W=await this.upload($,w,Z);return await this.poll($,W.id,Z)}content($,w,Z){let{vector_store_id:W}=w;return this._client.getAPIList(H`/vector_stores/${W}/files/${$}/content`,q$,{...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}}class d$ extends E{constructor(){super(...arguments);this.files=new k4(this._client),this.fileBatches=new f4(this._client)}create($,w){return this._client.post("/vector_stores",{body:$,...w,headers:D([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}retrieve($,w){return this._client.get(H`/vector_stores/${$}`,{...w,headers:D([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}update($,w,Z){return this._client.post(H`/vector_stores/${$}`,{body:w,...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}list($={},w){return this._client.getAPIList("/vector_stores",g,{query:$,...w,headers:D([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}delete($,w){return this._client.delete(H`/vector_stores/${$}`,{...w,headers:D([{"OpenAI-Beta":"assistants=v2"},w?.headers])})}search($,w,Z){return this._client.getAPIList(H`/vector_stores/${$}/search`,q$,{body:w,method:"post",...Z,headers:D([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}}d$.Files=k4;d$.FileBatches=f4;var Hw,Yz,j6;class Fw extends E{constructor(){super(...arguments);Hw.add(this)}async unwrap($,w,Z=this._client.webhookSecret,W=300){return await this.verifySignature($,w,Z,W),JSON.parse($)}async verifySignature($,w,Z=this._client.webhookSecret,W=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!=="function"||typeof crypto.subtle.verify!=="function")throw Error("Webhook signature verification is only supported when the `crypto` global is defined");V(this,Hw,"m",Yz).call(this,Z);let X=D([w]).values,Y=V(this,Hw,"m",j6).call(this,X,"webhook-signature"),G=V(this,Hw,"m",j6).call(this,X,"webhook-timestamp"),J=V(this,Hw,"m",j6).call(this,X,"webhook-id"),Q=parseInt(G,10);if(isNaN(Q))throw new V$("Invalid webhook timestamp format");let z=Math.floor(Date.now()/1000);if(z-Q>W)throw new V$("Webhook timestamp is too old");if(Q>z+W)throw new V$("Webhook timestamp is too new");let M=Y.split(" ").map((B)=>B.startsWith("v1,")?B.substring(3):B),T=Z.startsWith("whsec_")?Buffer.from(Z.replace("whsec_",""),"base64"):Buffer.from(Z,"utf-8"),N=J?`${J}.${G}.${$}`:`${G}.${$}`,K=await crypto.subtle.importKey("raw",T,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let B of M)try{let P=Buffer.from(B,"base64");if(await crypto.subtle.verify("HMAC",K,P,new TextEncoder().encode(N)))return}catch{continue}throw new V$("The given webhook signature does not match the expected signature")}}Hw=new WeakSet,Yz=function(w){if(typeof w!=="string"||w.length===0)throw Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},j6=function(w,Z){if(!w)throw Error("Headers are required");let W=w.get(Z);if(W===null||W===void 0)throw Error(`Missing required header: ${Z}`);return W};var EW,LW,I6,Gz;class x{constructor({baseURL:$=m$("OPENAI_BASE_URL"),apiKey:w=m$("OPENAI_API_KEY"),organization:Z=m$("OPENAI_ORG_ID")??null,project:W=m$("OPENAI_PROJECT_ID")??null,webhookSecret:X=m$("OPENAI_WEBHOOK_SECRET")??null,...Y}={}){if(EW.add(this),I6.set(this,void 0),this.completions=new Jw(this),this.chat=new B1(this),this.embeddings=new zw(this),this.files=new Tw(this),this.images=new Vw(this),this.audio=new F$(this),this.moderations=new qw(this),this.models=new Pw(this),this.fineTuning=new w$(this),this.graders=new L1(this),this.vectorStores=new d$(this),this.webhooks=new Fw(this),this.beta=new O$(this),this.batches=new Xw(this),this.uploads=new k1(this),this.responses=new f1(this),this.realtime=new D1(this),this.conversations=new O1(this),this.evals=new E1(this),this.containers=new F1(this),w===void 0)throw new k("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");let G={apiKey:w,organization:Z,project:W,webhookSecret:X,...Y,baseURL:$||"https://api.openai.com/v1"};if(!G.dangerouslyAllowBrowser&&MQ())throw new k(`It looks like you're running in a browser-like environment.
|
|
103
103
|
|
|
104
104
|
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
105
105
|
If you understand the risks and have appropriate mitigations in place,
|
|
@@ -108,49 +108,51 @@ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
|
108
108
|
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
109
109
|
|
|
110
110
|
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
111
|
-
`);this.baseURL=G.baseURL,this.timeout=G.timeout??EW.DEFAULT_TIMEOUT,this.logger=G.logger??console;let J="warn";this.logLevel=J,this.logLevel=e5(G.logLevel,"ClientOptions.logLevel",this)??e5(m$("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??J,this.fetchOptions=G.fetchOptions,this.maxRetries=G.maxRetries??2,this.fetch=G.fetch??zQ(),R(this,I6,TQ,"f"),this._options=G,this.apiKey=typeof w==="string"?w:"Missing Key",this.organization=Z,this.project=W,this.webhookSecret=X}withOptions($){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...$})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:$,nulls:w}){return}async authHeaders($){return D([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery($){return a5($,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${v$}`}defaultIdempotencyKey(){return`stainless-node-retry-${i5()}`}makeStatusError($,w,Z,W){return w0.generate($,w,Z,W)}async _callApiKey(){let $=this._options.apiKey;if(typeof $!=="function")return!1;let w;try{w=await $()}catch(Z){if(Z instanceof k)throw Z;throw new k(`Failed to get token from 'apiKey' function: ${Z.message}`,{cause:Z})}if(typeof w!=="string"||!w)throw new k(`Expected 'apiKey' function argument to return a string but it returned ${w}`);return this.apiKey=w,!0}buildURL($,w,Z){let W=!V(this,OW,"m",Wz).call(this)&&Z||this.baseURL,X=eJ($)?new URL($):new URL(W+(W.endsWith("/")&&$.startsWith("/")?$.slice(1):$)),Y=this.defaultQuery();if(!$Q(Y))w={...Y,...w};if(typeof w==="object"&&w&&!Array.isArray(w))X.search=this.stringifyQuery(w);return X.toString()}async prepareOptions($){await this._callApiKey()}async prepareRequest($,{url:w,options:Z}){}get($,w){return this.methodRequest("get",$,w)}post($,w){return this.methodRequest("post",$,w)}patch($,w){return this.methodRequest("patch",$,w)}put($,w){return this.methodRequest("put",$,w)}delete($,w){return this.methodRequest("delete",$,w)}methodRequest($,w,Z){return this.request(Promise.resolve(Z).then((W)=>{return{method:$,path:w,...W}}))}request($,w=null){return new T1(this,this.makeRequest($,w,void 0))}async makeRequest($,w,Z){let W=await $,X=W.maxRetries??this.maxRetries;if(w==null)w=X;await this.prepareOptions(W);let{req:Y,url:G,timeout:J}=await this.buildRequest(W,{retryCount:X-w});await this.prepareRequest(Y,{url:G,options:W});let Q="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),z=Z===void 0?"":`, retryOf: ${Z}`,M=Date.now();if($0(this).debug(`[${Q}] sending request`,V$({retryOfRequestLogID:Z,method:W.method,url:G,options:W,headers:Y.headers})),W.signal?.aborted)throw new X0;let T=new AbortController,K=await this.fetchWithTimeout(G,Y,J,T).catch(I9),N=Date.now();if(K instanceof globalThis.Error){let q=`retrying, ${w} attempts remaining`;if(W.signal?.aborted)throw new X0;let U=j9(K)||/timed? ?out/i.test(String(K)+("cause"in K?String(K.cause):""));if(w)return $0(this).info(`[${Q}] connection ${U?"timed out":"failed"} - ${q}`),$0(this).debug(`[${Q}] connection ${U?"timed out":"failed"} (${q})`,V$({retryOfRequestLogID:Z,url:G,durationMs:N-M,message:K.message})),this.retryRequest(W,w,Z??Q);if($0(this).info(`[${Q}] connection ${U?"timed out":"failed"} - error; no more retries left`),$0(this).debug(`[${Q}] connection ${U?"timed out":"failed"} (error; no more retries left)`,V$({retryOfRequestLogID:Z,url:G,durationMs:N-M,message:K.message})),U)throw new M1;throw new z1({cause:K})}let B=[...K.headers.entries()].filter(([q])=>q==="x-request-id").map(([q,U])=>", "+q+": "+JSON.stringify(U)).join(""),P=`[${Q}${z}${B}] ${Y.method} ${G} ${K.ok?"succeeded":"failed"} with status ${K.status} in ${N-M}ms`;if(!K.ok){let q=await this.shouldRetry(K);if(w&&q){let u=`retrying, ${w} attempts remaining`;return await MQ(K.body),$0(this).info(`${P} - ${u}`),$0(this).debug(`[${Q}] response error (${u})`,V$({retryOfRequestLogID:Z,url:K.url,status:K.status,headers:K.headers,durationMs:N-M})),this.retryRequest(W,w,Z??Q,K.headers)}let U=q?"error; no more retries left":"error; not retryable";$0(this).info(`${P} - ${U}`);let O=await K.text().catch((u)=>I9(u).message),f=WQ(O),C=f?void 0:O;throw $0(this).debug(`[${Q}] response error (${U})`,V$({retryOfRequestLogID:Z,url:K.url,status:K.status,headers:K.headers,message:C,durationMs:Date.now()-M})),this.makeStatusError(K.status,f,C,K.headers)}return $0(this).info(P),$0(this).debug(`[${Q}] response start`,V$({retryOfRequestLogID:Z,url:K.url,status:K.status,headers:K.headers,durationMs:N-M})),{response:K,options:W,controller:T,requestLogID:Q,retryOfRequestLogID:Z,startTime:M}}getAPIList($,w,Z){return this.requestAPIList(w,{method:"get",path:$,...Z})}requestAPIList($,w){let Z=this.makeRequest(w,null,void 0);return new K6(this,Z,$)}async fetchWithTimeout($,w,Z,W){let{signal:X,method:Y,...G}=w||{};if(X)X.addEventListener("abort",()=>W.abort());let J=setTimeout(()=>W.abort(),Z),Q=globalThis.ReadableStream&&G.body instanceof globalThis.ReadableStream||typeof G.body==="object"&&G.body!==null&&Symbol.asyncIterator in G.body,z={signal:W.signal,...Q?{duplex:"half"}:{},method:"GET",...G};if(Y)z.method=Y.toUpperCase();try{return await this.fetch.call(void 0,$,z)}finally{clearTimeout(J)}}async shouldRetry($){let w=$.headers.get("x-should-retry");if(w==="true")return!0;if(w==="false")return!1;if($.status===408)return!0;if($.status===409)return!0;if($.status===429)return!0;if($.status>=500)return!0;return!1}async retryRequest($,w,Z,W){let X,Y=W?.get("retry-after-ms");if(Y){let J=parseFloat(Y);if(!Number.isNaN(J))X=J}let G=W?.get("retry-after");if(G&&!X){let J=parseFloat(G);if(!Number.isNaN(J))X=J*1000;else X=Date.parse(G)-Date.now()}if(!(X&&0<=X&&X<60000)){let J=$.maxRetries??this.maxRetries;X=this.calculateDefaultRetryTimeoutMillis(w,J)}return await a0(X),this.makeRequest($,w-1,Z)}calculateDefaultRetryTimeoutMillis($,w){let X=w-$,Y=Math.min(0.5*Math.pow(2,X),8),G=1-Math.random()*0.25;return Y*G*1000}async buildRequest($,{retryCount:w=0}={}){let Z={...$},{method:W,path:X,query:Y,defaultBaseURL:G}=Z,J=this.buildURL(X,Y,G);if("timeout"in Z)ZQ("timeout",Z.timeout);Z.timeout=Z.timeout??this.timeout;let{bodyHeaders:Q,body:z}=this.buildBody({options:Z}),M=await this.buildHeaders({options:$,method:W,bodyHeaders:Q,retryCount:w});return{req:{method:W,headers:M,...Z.signal&&{signal:Z.signal},...globalThis.ReadableStream&&z instanceof globalThis.ReadableStream&&{duplex:"half"},...z&&{body:z},...this.fetchOptions??{},...Z.fetchOptions??{}},url:J,timeout:Z.timeout}}async buildHeaders({options:$,method:w,bodyHeaders:Z,retryCount:W}){let X={};if(this.idempotencyHeader&&w!=="get"){if(!$.idempotencyKey)$.idempotencyKey=this.defaultIdempotencyKey();X[this.idempotencyHeader]=$.idempotencyKey}let Y=D([X,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(W),...$.timeout?{"X-Stainless-Timeout":String(Math.trunc($.timeout/1000))}:{},...QQ(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders($),this._options.defaultHeaders,Z,$.headers]);return this.validateHeaders(Y),Y.values}buildBody({options:{body:$,headers:w}}){if(!$)return{bodyHeaders:void 0,body:void 0};let Z=D([w]);if(ArrayBuffer.isView($)||$ instanceof ArrayBuffer||$ instanceof DataView||typeof $==="string"&&Z.values.has("content-type")||globalThis.Blob&&$ instanceof globalThis.Blob||$ instanceof FormData||$ instanceof URLSearchParams||globalThis.ReadableStream&&$ instanceof globalThis.ReadableStream)return{bodyHeaders:void 0,body:$};else if(typeof $==="object"&&((Symbol.asyncIterator in $)||(Symbol.iterator in $)&&("next"in $)&&typeof $.next==="function"))return{bodyHeaders:void 0,body:W6($)};else return V(this,I6,"f").call(this,{body:$,headers:Z})}}EW=x,I6=new WeakMap,OW=new WeakSet,Wz=function(){return this.baseURL!=="https://api.openai.com/v1"};x.OpenAI=EW;x.DEFAULT_TIMEOUT=600000;x.OpenAIError=k;x.APIError=w0;x.APIConnectionError=z1;x.APIConnectionTimeoutError=M1;x.APIUserAbortError=X0;x.NotFoundError=_9;x.ConflictError=g9;x.RateLimitError=u9;x.BadRequestError=y9;x.AuthenticationError=b9;x.InternalServerError=h9;x.PermissionDeniedError=x9;x.UnprocessableEntityError=v9;x.InvalidWebhookSignatureError=B$;x.toFile=N6;x.Completions=Jw;x.Chat=B1;x.Embeddings=zw;x.Files=Tw;x.Images=Vw;x.Audio=H$;x.Moderations=qw;x.Models=Pw;x.FineTuning=$$;x.Graders=L1;x.VectorStores=d$;x.Webhooks=Fw;x.Beta=F$;x.Batches=Xw;x.Uploads=k1;x.Responses=f1;x.Realtime=D1;x.Conversations=O1;x.Evals=E1;x.Containers=F1;class LW{client;constructor($){this.client=new x({...$,maxRetries:0})}async*stream($){let w=await this.client.chat.completions.create({model:$.model,messages:vO($.messages),...$.tools.length?{tools:$.tools.map((W)=>({type:"function",function:{name:W.name,description:W.description,parameters:W.inputSchema}}))}:{},max_completion_tokens:$.maxOutputTokens,stream:!0,stream_options:{include_usage:!0}},$.signal?{signal:$.signal}:void 0),Z=new Set;for await(let W of w){let X=W.choices[0]?.delta,Y=X?.reasoning_content;if(Y)yield{type:"reasoning_delta",text:Y};if(X?.content)yield{type:"text_delta",text:X.content};for(let G of X?.tool_calls??[]){let J=G.index;if(!Z.has(J))Z.add(J),yield{type:"tool_call_start",index:J,callId:G.id??`call_${J}`,name:G.function?.name??""};if(G.function?.arguments)yield{type:"tool_call_delta",index:J,argumentsDelta:G.function.arguments}}if(W.usage)yield{type:"usage",usage:{inputTokens:W.usage.prompt_tokens,outputTokens:W.usage.completion_tokens}}}for(let W of Z)yield{type:"tool_call_end",index:W};yield{type:"done"}}}function vO($){return $.map((w)=>{if(w.role==="system"||w.role==="user")return{role:w.role,content:w.content};if(w.role==="tool")return{role:"tool",tool_call_id:w.callId,content:w.content};let Z={role:"assistant",content:w.content||null};if(w.toolCalls.length)Z.tool_calls=w.toolCalls.map((W)=>({id:W.callId,type:"function",function:{name:W.name,arguments:JSON.stringify(W.input)}}));return Z})}import{createHash as uO,randomUUID as Xz}from"node:crypto";import{appendFile as hO,chmod as Yz,mkdir as iO,readdir as mO,readFile as Gz}from"node:fs/promises";import A1 from"node:path";var lO=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;function Jz($){return lO.test($)}function cO($){return uO("sha256").update(A1.resolve($)).digest("hex").slice(0,16)}class DW{sessionId;sessionPath;tracePath;#$=Promise.resolve();constructor($,w,Z=Xz()){this.sessionId=Z;if(!Jz(Z))throw Error("Invalid session ID");let W=A1.join($,"sessions",cO(w));this.sessionPath=A1.join(W,`${Z}.jsonl`),this.tracePath=A1.join(W,`${Z}.trace.jsonl`)}async create($){await this.append("session.created",{workspace:$,sessionId:this.sessionId})}append($,w){let Z={version:1,id:Xz(),timestamp:new Date().toISOString(),type:$,data:w},W=this.#$.then(async()=>{let X=A1.dirname(this.sessionPath);await iO(X,{recursive:!0,mode:448}),await Yz(X,448),await hO(this.sessionPath,`${JSON.stringify(Z)}
|
|
112
|
-
`,{encoding:"utf8",mode:384}),await
|
|
113
|
-
`)){if(!z)continue;let M;try{M=JSON.parse(z)}catch{continue}if(M.version!==1)continue;if(M.timestamp)G=M.timestamp;switch(M.type){case"session.reset":W=0,Y=void 0,X=void 0;break;case"session.title":{let T=M.data;if(typeof T?.title==="string")X=T.title;break}case"message":if(W++,Y===void 0){let T=M.data;if(T?.role==="user"&&typeof T.content==="string")Y=T.content}break}}let J=X??Y,Q={id:w,messageCount:W,lastActivity:G};if(J!==void 0)Q.title=J;return Q}async recover(){let $=[],w=[],Z,W,Y=(await
|
|
114
|
-
`),G=-1;for(let z=Y.length-1;z>=0;z--)if(Y[z]){G=z;break}for(let z=0;z<Y.length;z++){let M=Y[z];if(!M)continue;let T;try{T=JSON.parse(M)}catch(
|
|
115
|
-
// coden-load: ${
|
|
111
|
+
`);this.baseURL=G.baseURL,this.timeout=G.timeout??LW.DEFAULT_TIMEOUT,this.logger=G.logger??console;let J="warn";this.logLevel=J,this.logLevel=$W(G.logLevel,"ClientOptions.logLevel",this)??$W(m$("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??J,this.fetchOptions=G.fetchOptions,this.maxRetries=G.maxRetries??2,this.fetch=G.fetch??NQ(),R(this,I6,BQ,"f"),this._options=G,this.apiKey=typeof w==="string"?w:"Missing Key",this.organization=Z,this.project=W,this.webhookSecret=X}withOptions($){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...$})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:$,nulls:w}){return}async authHeaders($){return D([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery($){return o5($,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${v$}`}defaultIdempotencyKey(){return`stainless-node-retry-${m5()}`}makeStatusError($,w,Z,W){return w0.generate($,w,Z,W)}async _callApiKey(){let $=this._options.apiKey;if(typeof $!=="function")return!1;let w;try{w=await $()}catch(Z){if(Z instanceof k)throw Z;throw new k(`Failed to get token from 'apiKey' function: ${Z.message}`,{cause:Z})}if(typeof w!=="string"||!w)throw new k(`Expected 'apiKey' function argument to return a string but it returned ${w}`);return this.apiKey=w,!0}buildURL($,w,Z){let W=!V(this,EW,"m",Gz).call(this)&&Z||this.baseURL,X=ZQ($)?new URL($):new URL(W+(W.endsWith("/")&&$.startsWith("/")?$.slice(1):$)),Y=this.defaultQuery();if(!WQ(Y))w={...Y,...w};if(typeof w==="object"&&w&&!Array.isArray(w))X.search=this.stringifyQuery(w);return X.toString()}async prepareOptions($){await this._callApiKey()}async prepareRequest($,{url:w,options:Z}){}get($,w){return this.methodRequest("get",$,w)}post($,w){return this.methodRequest("post",$,w)}patch($,w){return this.methodRequest("patch",$,w)}put($,w){return this.methodRequest("put",$,w)}delete($,w){return this.methodRequest("delete",$,w)}methodRequest($,w,Z){return this.request(Promise.resolve(Z).then((W)=>{return{method:$,path:w,...W}}))}request($,w=null){return new T1(this,this.makeRequest($,w,void 0))}async makeRequest($,w,Z){let W=await $,X=W.maxRetries??this.maxRetries;if(w==null)w=X;await this.prepareOptions(W);let{req:Y,url:G,timeout:J}=await this.buildRequest(W,{retryCount:X-w});await this.prepareRequest(Y,{url:G,options:W});let Q="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),z=Z===void 0?"":`, retryOf: ${Z}`,M=Date.now();if($0(this).debug(`[${Q}] sending request`,P$({retryOfRequestLogID:Z,method:W.method,url:G,options:W,headers:Y.headers})),W.signal?.aborted)throw new X0;let T=new AbortController,N=await this.fetchWithTimeout(G,Y,J,T).catch(I9),K=Date.now();if(N instanceof globalThis.Error){let q=`retrying, ${w} attempts remaining`;if(W.signal?.aborted)throw new X0;let U=j9(N)||/timed? ?out/i.test(String(N)+("cause"in N?String(N.cause):""));if(w)return $0(this).info(`[${Q}] connection ${U?"timed out":"failed"} - ${q}`),$0(this).debug(`[${Q}] connection ${U?"timed out":"failed"} (${q})`,P$({retryOfRequestLogID:Z,url:G,durationMs:K-M,message:N.message})),this.retryRequest(W,w,Z??Q);if($0(this).info(`[${Q}] connection ${U?"timed out":"failed"} - error; no more retries left`),$0(this).debug(`[${Q}] connection ${U?"timed out":"failed"} (error; no more retries left)`,P$({retryOfRequestLogID:Z,url:G,durationMs:K-M,message:N.message})),U)throw new M1;throw new z1({cause:N})}let B=[...N.headers.entries()].filter(([q])=>q==="x-request-id").map(([q,U])=>", "+q+": "+JSON.stringify(U)).join(""),P=`[${Q}${z}${B}] ${Y.method} ${G} ${N.ok?"succeeded":"failed"} with status ${N.status} in ${K-M}ms`;if(!N.ok){let q=await this.shouldRetry(N);if(w&&q){let u=`retrying, ${w} attempts remaining`;return await KQ(N.body),$0(this).info(`${P} - ${u}`),$0(this).debug(`[${Q}] response error (${u})`,P$({retryOfRequestLogID:Z,url:N.url,status:N.status,headers:N.headers,durationMs:K-M})),this.retryRequest(W,w,Z??Q,N.headers)}let U=q?"error; no more retries left":"error; not retryable";$0(this).info(`${P} - ${U}`);let O=await N.text().catch((u)=>I9(u).message),f=GQ(O),C=f?void 0:O;throw $0(this).debug(`[${Q}] response error (${U})`,P$({retryOfRequestLogID:Z,url:N.url,status:N.status,headers:N.headers,message:C,durationMs:Date.now()-M})),this.makeStatusError(N.status,f,C,N.headers)}return $0(this).info(P),$0(this).debug(`[${Q}] response start`,P$({retryOfRequestLogID:Z,url:N.url,status:N.status,headers:N.headers,durationMs:K-M})),{response:N,options:W,controller:T,requestLogID:Q,retryOfRequestLogID:Z,startTime:M}}getAPIList($,w,Z){return this.requestAPIList(w,{method:"get",path:$,...Z})}requestAPIList($,w){let Z=this.makeRequest(w,null,void 0);return new N6(this,Z,$)}async fetchWithTimeout($,w,Z,W){let{signal:X,method:Y,...G}=w||{};if(X)X.addEventListener("abort",()=>W.abort());let J=setTimeout(()=>W.abort(),Z),Q=globalThis.ReadableStream&&G.body instanceof globalThis.ReadableStream||typeof G.body==="object"&&G.body!==null&&Symbol.asyncIterator in G.body,z={signal:W.signal,...Q?{duplex:"half"}:{},method:"GET",...G};if(Y)z.method=Y.toUpperCase();try{return await this.fetch.call(void 0,$,z)}finally{clearTimeout(J)}}async shouldRetry($){let w=$.headers.get("x-should-retry");if(w==="true")return!0;if(w==="false")return!1;if($.status===408)return!0;if($.status===409)return!0;if($.status===429)return!0;if($.status>=500)return!0;return!1}async retryRequest($,w,Z,W){let X,Y=W?.get("retry-after-ms");if(Y){let J=parseFloat(Y);if(!Number.isNaN(J))X=J}let G=W?.get("retry-after");if(G&&!X){let J=parseFloat(G);if(!Number.isNaN(J))X=J*1000;else X=Date.parse(G)-Date.now()}if(!(X&&0<=X&&X<60000)){let J=$.maxRetries??this.maxRetries;X=this.calculateDefaultRetryTimeoutMillis(w,J)}return await o0(X),this.makeRequest($,w-1,Z)}calculateDefaultRetryTimeoutMillis($,w){let X=w-$,Y=Math.min(0.5*Math.pow(2,X),8),G=1-Math.random()*0.25;return Y*G*1000}async buildRequest($,{retryCount:w=0}={}){let Z={...$},{method:W,path:X,query:Y,defaultBaseURL:G}=Z,J=this.buildURL(X,Y,G);if("timeout"in Z)YQ("timeout",Z.timeout);Z.timeout=Z.timeout??this.timeout;let{bodyHeaders:Q,body:z}=this.buildBody({options:Z}),M=await this.buildHeaders({options:$,method:W,bodyHeaders:Q,retryCount:w});return{req:{method:W,headers:M,...Z.signal&&{signal:Z.signal},...globalThis.ReadableStream&&z instanceof globalThis.ReadableStream&&{duplex:"half"},...z&&{body:z},...this.fetchOptions??{},...Z.fetchOptions??{}},url:J,timeout:Z.timeout}}async buildHeaders({options:$,method:w,bodyHeaders:Z,retryCount:W}){let X={};if(this.idempotencyHeader&&w!=="get"){if(!$.idempotencyKey)$.idempotencyKey=this.defaultIdempotencyKey();X[this.idempotencyHeader]=$.idempotencyKey}let Y=D([X,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(W),...$.timeout?{"X-Stainless-Timeout":String(Math.trunc($.timeout/1000))}:{},...TQ(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders($),this._options.defaultHeaders,Z,$.headers]);return this.validateHeaders(Y),Y.values}buildBody({options:{body:$,headers:w}}){if(!$)return{bodyHeaders:void 0,body:void 0};let Z=D([w]);if(ArrayBuffer.isView($)||$ instanceof ArrayBuffer||$ instanceof DataView||typeof $==="string"&&Z.values.has("content-type")||globalThis.Blob&&$ instanceof globalThis.Blob||$ instanceof FormData||$ instanceof URLSearchParams||globalThis.ReadableStream&&$ instanceof globalThis.ReadableStream)return{bodyHeaders:void 0,body:$};else if(typeof $==="object"&&((Symbol.asyncIterator in $)||(Symbol.iterator in $)&&("next"in $)&&typeof $.next==="function"))return{bodyHeaders:void 0,body:W6($)};else return V(this,I6,"f").call(this,{body:$,headers:Z})}}LW=x,I6=new WeakMap,EW=new WeakSet,Gz=function(){return this.baseURL!=="https://api.openai.com/v1"};x.OpenAI=LW;x.DEFAULT_TIMEOUT=600000;x.OpenAIError=k;x.APIError=w0;x.APIConnectionError=z1;x.APIConnectionTimeoutError=M1;x.APIUserAbortError=X0;x.NotFoundError=_9;x.ConflictError=g9;x.RateLimitError=u9;x.BadRequestError=y9;x.AuthenticationError=b9;x.InternalServerError=h9;x.PermissionDeniedError=x9;x.UnprocessableEntityError=v9;x.InvalidWebhookSignatureError=V$;x.toFile=K6;x.Completions=Jw;x.Chat=B1;x.Embeddings=zw;x.Files=Tw;x.Images=Vw;x.Audio=F$;x.Moderations=qw;x.Models=Pw;x.FineTuning=w$;x.Graders=L1;x.VectorStores=d$;x.Webhooks=Fw;x.Beta=O$;x.Batches=Xw;x.Uploads=k1;x.Responses=f1;x.Realtime=D1;x.Conversations=O1;x.Evals=E1;x.Containers=F1;class DW{client;constructor($){this.client=new x({...$,maxRetries:0})}async*stream($){let w=await this.client.chat.completions.create({model:$.model,messages:iO($.messages),...$.tools.length?{tools:$.tools.map((W)=>({type:"function",function:{name:W.name,description:W.description,parameters:W.inputSchema}}))}:{},max_completion_tokens:$.maxOutputTokens,stream:!0,stream_options:{include_usage:!0}},$.signal?{signal:$.signal}:void 0),Z=new Set;for await(let W of w){let X=W.choices[0]?.delta,Y=X?.reasoning_content;if(Y)yield{type:"reasoning_delta",text:Y};if(X?.content)yield{type:"text_delta",text:X.content};for(let G of X?.tool_calls??[]){let J=G.index;if(!Z.has(J))Z.add(J),yield{type:"tool_call_start",index:J,callId:G.id??`call_${J}`,name:G.function?.name??""};if(G.function?.arguments)yield{type:"tool_call_delta",index:J,argumentsDelta:G.function.arguments}}if(W.usage)yield{type:"usage",usage:{inputTokens:W.usage.prompt_tokens,outputTokens:W.usage.completion_tokens}}}for(let W of Z)yield{type:"tool_call_end",index:W};yield{type:"done"}}}function iO($){return $.map((w)=>{if(w.role==="system"||w.role==="user")return{role:w.role,content:w.content};if(w.role==="tool")return{role:"tool",tool_call_id:w.callId,content:w.content};let Z={role:"assistant",content:w.content||null};if(w.toolCalls.length)Z.tool_calls=w.toolCalls.map((W)=>({id:W.callId,type:"function",function:{name:W.name,arguments:JSON.stringify(W.input)}}));return Z})}import{createHash as mO,randomUUID as Jz}from"node:crypto";import{appendFile as lO,chmod as Qz,mkdir as cO,readdir as dO,readFile as zz}from"node:fs/promises";import A1 from"node:path";var pO=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;function Mz($){return pO.test($)}function fW($){return mO("sha256").update(A1.resolve($)).digest("hex").slice(0,16)}class kW{sessionId;sessionPath;tracePath;#$=Promise.resolve();constructor($,w,Z=Jz()){this.sessionId=Z;if(!Mz(Z))throw Error("Invalid session ID");let W=A1.join($,"sessions",fW(w));this.sessionPath=A1.join(W,`${Z}.jsonl`),this.tracePath=A1.join(W,`${Z}.trace.jsonl`)}async create($){await this.append("session.created",{workspace:$,sessionId:this.sessionId})}append($,w){let Z={version:1,id:Jz(),timestamp:new Date().toISOString(),type:$,data:w},W=this.#$.then(async()=>{let X=A1.dirname(this.sessionPath);await cO(X,{recursive:!0,mode:448}),await Qz(X,448),await lO(this.sessionPath,`${JSON.stringify(Z)}
|
|
112
|
+
`,{encoding:"utf8",mode:384}),await Qz(this.sessionPath,384)});return this.#$=W.catch(()=>{}),W}appendMessage($){return this.append("message",$)}appendCompaction($,w){return this.append("context.compacted",w?{summary:$,sourceRange:w}:{summary:$})}setTitle($){return this.append("session.title",{title:$})}async list(){let $=A1.dirname(this.sessionPath),w;try{w=await dO($)}catch(W){if(W.code==="ENOENT")return[];throw W}let Z=[];for(let W of w){if(!W.endsWith(".jsonl")||W.endsWith(".trace.jsonl"))continue;let X=W.slice(0,-6);if(!Mz(X))continue;try{Z.push(await this.#w(A1.join($,W),X))}catch{}}return Z.sort((W,X)=>X.lastActivity.localeCompare(W.lastActivity)),Z}async#w($,w){let Z=await zz($,"utf8"),W=0,X,Y,G="";for(let z of Z.split(`
|
|
113
|
+
`)){if(!z)continue;let M;try{M=JSON.parse(z)}catch{continue}if(M.version!==1)continue;if(M.timestamp)G=M.timestamp;switch(M.type){case"session.reset":W=0,Y=void 0,X=void 0;break;case"session.title":{let T=M.data;if(typeof T?.title==="string")X=T.title;break}case"message":if(W++,Y===void 0){let T=M.data;if(T?.role==="user"&&typeof T.content==="string")Y=T.content}break}}let J=X??Y,Q={id:w,messageCount:W,lastActivity:G};if(J!==void 0)Q.title=J;return Q}async recover(){let $=[],w=[],Z,W,Y=(await zz(this.sessionPath,"utf8")).split(`
|
|
114
|
+
`),G=-1;for(let z=Y.length-1;z>=0;z--)if(Y[z]){G=z;break}for(let z=0;z<Y.length;z++){let M=Y[z];if(!M)continue;let T;try{T=JSON.parse(M)}catch(N){if(z===G){w.push("Ignored incomplete final JSONL record");break}throw Tz(z,N)}try{if(T.version!==1)throw Error("unsupported schema version");if(T.type==="session.reset")$.length=0,Z=void 0,W=void 0;if(T.type==="message"){if(!nO(T.data))throw Error("invalid message structure");$.push(T.data)}if(T.type==="context.compacted"){let N=T.data;if(typeof N?.summary!=="string")throw Error("invalid compaction record");Z=N.summary,W=typeof N.sourceRange?.start==="number"&&typeof N.sourceRange.end==="number"?{start:N.sourceRange.start,end:N.sourceRange.end}:void 0}}catch(N){throw Tz(z,N)}}let J=tO($,w);for(let z of J)await this.appendMessage(z);let Q={messages:$,warnings:w};if(Z!==void 0)Q.summary=Z;if(W!==void 0)Q.compactionRange=W;return Q}}function nO($){if(!$||typeof $!=="object")return!1;let w=$;if((w.role==="system"||w.role==="user")&&typeof w.content==="string")return!0;if(w.role==="assistant"&&typeof w.content==="string")return Array.isArray(w.toolCalls)&&w.toolCalls.every((Z)=>!!Z&&typeof Z==="object"&&typeof Z.callId==="string"&&typeof Z.name==="string"&&("input"in Z));return w.role==="tool"&&typeof w.callId==="string"&&typeof w.name==="string"&&typeof w.content==="string"&&typeof w.isError==="boolean"}function Tz($,w){return Error(`Invalid session record at line ${$+1}: ${w instanceof Error?w.message:String(w)}`)}function tO($,w){let Z=new Map,W=new Set;for(let Y of $)if(Y.role==="assistant"){if(Z.size>0)throw Error("Assistant message appeared before pending tool results");for(let G of Y.toolCalls){if(W.has(G.callId))throw Error(`Duplicate tool call ID: ${G.callId}`);W.add(G.callId),Z.set(G.callId,G.name)}}else if(Y.role==="tool"){if(!Z.delete(Y.callId))throw Error(`Orphan tool result: ${Y.callId}`)}else if(Z.size>0)throw Error(`${Y.role} message appeared before pending tool results`);if(Z.size===0)return[];let X=[];for(let[Y,G]of Z){let J={role:"tool",callId:Y,name:G,content:"runtime.interrupted: tool execution did not complete before the previous process exited",isError:!0};$.push(J),X.push(J)}return w.push(`Recovered ${Z.size} interrupted tool call(s)`),X}function Nz(){return[k8,S8,f8,E8]}class AW{registry;permissions;events;workspace;timeoutMs;constructor($,w,Z,W,X=60000){this.registry=$;this.permissions=w;this.events=Z;this.workspace=W;this.timeoutMs=X}setRegistry($){this.registry=$}async execute($,w,Z){await this.events.emit("tool.requested",{name:$.name,callId:$.callId},Z);let W=this.registry.get($.name);if(!W)return{content:`tool.not_found: ${$.name}`,isError:!0};let X=this.registry.validate($.name,$.input);if(!X.valid)return{content:`tool.invalid_input: ${X.errors}`,isError:!0};if(["read","write","edit"].includes($.name))try{await a0(this.workspace,$.input.path)}catch(T){return{content:`permission.workspace_denied: ${T instanceof Error?T.message:String(T)}`,isError:!0}}let Y=await this.permissions.authorize(W,$,w);if(await this.events.emit("permission.requested",{name:$.name,callId:$.callId,risk:Y.risk,allowed:Y.allowed},Z),!Y.allowed)return{content:`permission.denied: ${$.name} was not authorized`,isError:!0};await this.events.emit("tool.started",{name:$.name,callId:$.callId},Z);let G=Date.now(),J,Q=new AbortController,z=()=>Q.abort(w.reason);if(w.aborted)z();else w.addEventListener("abort",z,{once:!0});let M=setTimeout(()=>Q.abort(Error(`Tool timed out after ${this.timeoutMs}ms`)),this.timeoutMs);try{let T=Q.signal.aborted?Promise.reject(Q.signal.reason):new Promise((N,K)=>{Q.signal.addEventListener("abort",()=>K(Q.signal.reason),{once:!0})});J=await Promise.race([W.execute($.input,{workspace:this.workspace,signal:Q.signal}),T]),J={...J,content:R1(J.content,50000)}}catch(T){J={content:`${!w.aborted&&Q.signal.aborted?"tool.timeout (abort requested; tools must cooperate)":"tool.internal_error"}: ${T instanceof Error?T.message:String(T)}`,isError:!0}}finally{clearTimeout(M),w.removeEventListener("abort",z)}return await this.events.emit("tool.completed",{name:$.name,callId:$.callId,isError:J.isError??!1,durationMs:Date.now()-G},Z),J}}import{createHash as rO,randomUUID as sO}from"node:crypto";import{readdir as aO,readFile as oO,realpath as eO,stat as Kz}from"node:fs/promises";import Bz from"node:path";import{pathToFileURL as SW}from"node:url";class A4{builtins;events;auto;trust;importer;static defaultImporter=($)=>import($);#$=new Map;constructor($,w,Z,W,X=A4.defaultImporter){this.builtins=$;this.events=w;this.auto=Z;this.trust=W;this.importer=X}async load($,w){let Z=w?.clone()??new r0(this.builtins),W=[],X=[];for(let Y of $)try{let G=await eO(Y.path),J=await Kz(G),Q=J.isDirectory()?G:Bz.dirname(G);if(Y.project&&!this.auto){if(!(this.trust?await this.trust(Q):!1)){await this.events.emit("plugin.unavailable",{path:Q,reason:"not trusted"});continue}}let z=J.isDirectory()?(await aO(G)).filter((M)=>M.endsWith(".ts")).sort().map((M)=>Bz.join(G,M)):G.endsWith(".ts")?[G]:[];for(let M of z)try{let T=await this.importPlugin(M);if(!$E(T.default))throw Error("default export is not a ToolDefinition");Z.register(T.default,{kind:"local",path:M}),W.push(T.default.name),await this.events.emit("plugin.loaded",{path:M,name:T.default.name})}catch(T){X.push(M),await this.events.emit("plugin.failed",{path:M,message:T instanceof Error?T.message:String(T)})}}catch(G){if(G.code!=="ENOENT")X.push(Y.path),await this.events.emit("plugin.failed",{path:Y.path,message:G instanceof Error?G.message:String(G)})}return{registry:Z,loaded:W,failed:X}}async importPlugin($){if(this.importer!==A4.defaultImporter){let G=(await Kz($)).mtimeMs;return this.importer(`${SW($).href}?mtime=${G}`)}let w=await oO($,"utf8"),Z=rO("sha256").update(w).digest("hex"),W=this.#$.get($);if(W?.hash===Z)return W.module;let X=`// coden-source: ${SW($).href}
|
|
115
|
+
// coden-load: ${sO()}
|
|
116
116
|
${w}
|
|
117
|
-
//# sourceURL=${
|
|
118
|
-
`,Y=await this.importer(`data:text/typescript;base64,${Buffer.from(X).toString("base64")}`);return this.#$.set($,{hash:Z,module:Y}),Y}}function
|
|
119
|
-
`;let Z=$.map((X)=>{let Y=X.title?
|
|
117
|
+
//# sourceURL=${SW($).href}
|
|
118
|
+
`,Y=await this.importer(`data:text/typescript;base64,${Buffer.from(X).toString("base64")}`);return this.#$.set($,{hash:Z,module:Y}),Y}}function $E($){if(!$||typeof $!=="object")return!1;let w=$;return typeof w.name==="string"&&typeof w.description==="string"&&(w.risk==="read"||w.risk==="modify"||w.risk==="dangerous")&&!!w.inputSchema&&typeof w.execute==="function"}var Vz="0.1.2";function Pz($,w){let Z=$.replace(/\s+/g," ").trim();return Z.length<=w?Z:`${Z.slice(0,w-1)}…`}function wE($){let w=new Date($);if(Number.isNaN(w.getTime()))return $;let Z=(W)=>String(W).padStart(2,"0");return`${w.getFullYear()}-${Z(w.getMonth()+1)}-${Z(w.getDate())} ${Z(w.getHours())}:${Z(w.getMinutes())}`}function RW($,w){if($.length===0)return`No sessions found.
|
|
119
|
+
`;let Z=$.map((X)=>{let Y=X.title?Pz(X.title,40):"(no title)",G=X.messageCount===0?"new session":`${X.messageCount} messages`,J=X.id===w?" *":"";return`${X.id}${J} ${Y} (${G}, ${wE(X.lastActivity)})`}),W=w?`Current session: ${w}
|
|
120
120
|
`:"";return`${Z.join(`
|
|
121
121
|
`)}
|
|
122
|
-
${W}`}function
|
|
123
|
-
`)}class Ow extends Error{}async function
|
|
124
|
-
`);if(!w.print)
|
|
122
|
+
${W}`}function qz($,w){let Z=w.length,W=w.filter((Y)=>Y.role==="user"||Y.role==="assistant").slice(-3),X=[`Resumed session ${$} (${Z} messages).`,`Showing last ${W.length} of ${Z} messages.`];for(let Y of W){let G=Y.role==="user"?"user":"assistant";X.push(`┌ ${G.padEnd(9)} ${Pz(Y.content,120)}`)}return X.join(`
|
|
123
|
+
`)}class Ow extends Error{}async function XE($,w){try{return await c7($,w)}catch(Z){throw new Ow(`configuration: ${Z instanceof Error?Z.message:String(Z)}`,{cause:Z})}}async function Hz($,w){let Z=process.cwd(),W=await XE(Z,{...w.provider?{provider:w.provider}:{},...w.model?{model:w.model}:{},...w.maxSteps?{maxSteps:w.maxSteps}:{},plugins:w.plugin}),X=new T5,G=!w.auto||!$&&!w.print?WE({input:ZE,output:process.stderr}):void 0,J=typeof w.resume==="string"?w.resume:void 0,Q=new kW(W.dataDir,Z,J);if(w.resume===!0){G?.close(),n0.write(RW(await Q.list()));return}let z,M,T=0,N;if(typeof w.resume==="string"){let a=await Q.recover();z=a.messages,M=a.summary,T=a.compactionRange?.end??0;for(let E$ of a.warnings)process.stderr.write(`coden: ${E$}
|
|
124
|
+
`);if(!w.print)N=qz(Q.sessionId,a.messages)}else await Q.create(Z);let K=new P5(Q.tracePath,X),B=new V5(X,{verbose:w.verbose,printMode:w.print}),P;try{P=JE(W.provider)}catch(a){throw new Ow(`provider: ${a instanceof Error?a.message:String(a)}`,{cause:a})}let q=Nz(),U=w.auto?void 0:zE(CW(G)),O=new q5(w.auto,U),f=new r0(q),C=new AW(f,O,X,Z),A=new Q5(y6.join(H8(),"trusted-workspaces.json")),u=new A4(q,X,w.auto,async(a)=>{if(await A.isTrusted(a))return!0;let E$=await ME(CW(G),`Project plugins at ${a} run with full process permissions. Trust? [y/N] `);if(E$)await A.trust(a);return E$}),i=new eZ,r=sw(Z,"global",W.dataDir),z0=sw(Z,"project",W.dataDir),h=[{path:y6.join(H8(),"plugins"),project:!1},{path:y6.join(Z,".coden","plugins"),project:!0},...W.plugins.map((a)=>({path:y6.resolve(Z,a),project:!0}))],q0=new Map,p$=async()=>{await new A0(r).recover(),await new A0(z0).recover();let a=await Uz(i,r,X,"global"),x6=w.auto||await A.isWorkspaceTrusted(Z)?await Uz(i,z0,X,"project"):{loaded:[],failed:[],unavailable:!0};if(x6.unavailable)await X.emit("plugin.unavailable",{source:"npm",scope:"project",path:z0.root,reason:"workspace is not trusted; run coden plugin install or sync after trusting"});let xW=await YE(q,a.loaded,x6.loaded,X);for(let{scope:Rz,plugin:Lw}of xW.effective){let _6=`${Rz}:${Lw.version}`,S4=q0.get(Lw.packageName);if(S4&&S4!==_6)await X.emit("plugin.restart_required",{source:"npm",packageName:Lw.packageName,loadedIdentity:S4,diskIdentity:_6,loadedVersion:S4.split(":").slice(1).join(":"),diskVersion:Lw.version,reason:"npm plugin metadata changed; restart CodeN to load it"});q0.set(Lw.packageName,_6)}return{composed:xW,global:a,project:x6}},Z$=async()=>{let a=await p$(),E$=await u.load(h,a.composed.registry);return f.replaceWith(E$.registry),E$};await Z$();let S1=await GE(Z),Ew=new z5({contextWindow:W.contextWindow,reservedOutputTokens:W.reservedOutputTokens,safetyMargin:W.safetyMargin});if(M)Ew.setSummary(M,T);let bW=new N5(P,f,C,Ew,Q,X,{model:W.model,maxSteps:W.maxSteps,systemPrompt:"You are CodeN, a concise coding agent. Inspect before editing, use tools carefully, and verify changes."+(S1?`
|
|
125
125
|
|
|
126
126
|
Project instructions:
|
|
127
|
-
${S1}`:"")},z);try{if($){await
|
|
128
|
-
`),"";throw new Ow(`project instructions: ${w instanceof Error?w.message:String(w)}`,{cause:w})}}function
|
|
127
|
+
${S1}`:"")},z);try{if($){await Oz(bW,$,G);return}if(w.print)throw Error("print mode requires a prompt");await QE(bW,Q,Z$,f,CW(G),fW(Z),N)}finally{G?.close(),B.dispose(),await K.flush()}}async function YE($,w,Z,W){let X=new r0($),Y=new Set(Z.map((Q)=>Q.packageName)),G=[...w.map((Q)=>({scope:"global",plugin:Q})),...Z.map((Q)=>({scope:"project",plugin:Q}))],J=[];for(let Q of G){if(Q.scope==="global"&&Y.has(Q.plugin.packageName))continue;let z=X.clone(),M={kind:"npm",pluginName:Q.plugin.packageName,pluginVersion:Q.plugin.version,path:Q.plugin.entryPath};try{for(let T of Q.plugin.tools)z.register(T,M);X.replaceWith(z),J.push(Q)}catch(T){await W.emit("plugin.failed",{source:"npm",scope:Q.scope,packageName:Q.plugin.packageName,version:Q.plugin.version,path:Q.plugin.entryPath,message:`${T instanceof Error?T.message:String(T)}; package skipped to preserve earlier tools`})}}return{registry:X,effective:J}}async function Uz($,w,Z,W){try{let X=await $.loadScope(w);for(let Y of X.loaded)await Z.emit("plugin.loaded",{source:"npm",scope:W,packageName:Y.packageName,version:Y.version,path:Y.entryPath,tools:Y.tools.map((G)=>G.name)});for(let Y of X.failed)await Z.emit("plugin.failed",{source:"npm",scope:W,packageName:Y.packageName,path:Y.path,message:`${Y.message}; run coden plugin sync to repair the runtime`});return X}catch(X){let Y=X instanceof Error?X.message:String(X);return await Z.emit("plugin.failed",{source:"npm",scope:W,path:w.runtimeDir,message:`${Y}; run coden plugin sync to repair the runtime`}),{loaded:[],failed:[],unavailable:!0}}}async function GE($){try{return await o7($,"AGENTS.md")}catch(w){if(w.code==="ENOENT")return"";if(w.category==="permission")return process.stderr.write(`coden: ignoring AGENTS.md: ${w.message}
|
|
128
|
+
`),"";throw new Ow(`project instructions: ${w instanceof Error?w.message:String(w)}`,{cause:w})}}function JE($){if($==="anthropic"){let Z=process.env.CODEN_ANTHROPIC_API_KEY;if(!Z)throw Error("CODEN_ANTHROPIC_API_KEY is required");return new i5({apiKey:Z})}let w=process.env.CODEN_OPENAI_API_KEY;if(!w)throw Error("CODEN_OPENAI_API_KEY is required");return new DW({apiKey:w,...process.env.CODEN_OPENAI_BASE_URL?{baseURL:process.env.CODEN_OPENAI_BASE_URL}:{}})}async function QE($,w,Z,W,X,Y,G){n0.write(TE),n0.write(`Version: ${Vz}
|
|
129
|
+
`),n0.write(`Workspace hash: ${Y}
|
|
130
|
+
`),n0.write(G?`${G}
|
|
129
131
|
Type /help for commands.
|
|
130
132
|
`:`CodeN session ${w.sessionId}. Type /help for commands.
|
|
131
|
-
`);while(!0){let
|
|
132
|
-
`);continue}if(
|
|
133
|
-
`);continue}if(
|
|
134
|
-
`);continue}if(
|
|
135
|
-
`);continue}if(
|
|
136
|
-
`);continue}await
|
|
133
|
+
`);while(!0){let J=(await jW(X,"> ")).trim();if(J===Fz)break;if(!J)continue;if(J==="/quit")break;if(J==="/help"){n0.write(`/help /session /sessions /compact /reload /new /quit
|
|
134
|
+
`);continue}if(J==="/sessions"){n0.write(RW(await w.list(),w.sessionId));continue}if(J==="/session"){n0.write(`${w.sessionId}
|
|
135
|
+
`);continue}if(J==="/compact"){await $.compact(),n0.write(`Context compacted.
|
|
136
|
+
`);continue}if(J==="/new"){await $.reset(),n0.write(`Started a new conversation in this session.
|
|
137
|
+
`);continue}if(J==="/reload"){let Q=await Z();n0.write(`Loaded: ${Q.loaded.join(", ")||"none"}; failed: ${Q.failed.length}; tools: ${W.list().map((z)=>z.name).join(", ")}
|
|
138
|
+
`);continue}await Oz($,J,X)}}function zE($){return async(w,Z,W,X)=>{let Y=await jW($,`${W.toUpperCase()} tool ${w.name} ${JSON.stringify(Z.input)}: [y]es/[s]ession/[N]o? `,X);return Y.toLowerCase()==="y"?"allow_once":Y.toLowerCase()==="s"&&W!=="dangerous"?"allow_session":"deny"}}var Fz="\x04";async function jW($,w,Z){let W=Z?void 0:new AbortController,X=Z??W?.signal,Y=()=>W?.abort(Error("Cancelled by user"));if(W)process.once("SIGINT",Y),$.once("SIGINT",Y);try{return X?await $.question(w,{signal:X}):await $.question(w)}catch(G){if(X?.aborted)return"";if(G.code==="ERR_USE_AFTER_CLOSE"||/readline was closed/.test(G.message))return Fz;throw G}finally{if(W)process.removeListener("SIGINT",Y),$.removeListener("SIGINT",Y)}}async function ME($,w){return/^y(?:es)?$/i.test(await jW($,w))}function CW($){if(!$)throw Error("Interactive input is unavailable");return $}async function Oz($,w,Z){let W=new AbortController,X=()=>W.abort(Error("Cancelled by user"));process.once("SIGINT",X),Z?.once("SIGINT",X);try{await $.run(w,W.signal)}catch(Y){if(!W.signal.aborted)throw Y}finally{process.removeListener("SIGINT",X),Z?.removeListener("SIGINT",X)}}function Ez($){if($!=="openai"&&$!=="anthropic")throw new J5("must be openai or anthropic");return $}function Lz($){let w=Number($);if(!Number.isInteger(w)||w<1)throw new J5("must be a positive integer");return w}function Dz($,w){return[...w,$]}var TE=`
|
|
137
139
|
██████╗ ██████╗ ██████╗ ███████╗███╗ ██╗
|
|
138
140
|
██╔════╝██╔═══██╗██╔══██╗██╔════╝████╗ ██║
|
|
139
141
|
██║ ██║ ██║██║ ██║█████╗ ██╔██╗ ██║
|
|
140
142
|
██║ ██║ ██║██║ ██║██╔══╝ ██║╚██╗██║
|
|
141
143
|
╚██████╗╚██████╔╝██████╔╝███████╗██║ ╚████║
|
|
142
144
|
╚═════╝ ╚═════╝ ╚═════╝ ╚══════╝╚═╝ ╚═══╝
|
|
143
|
-
`;function
|
|
145
|
+
`;function kz($,w){let Z=$.command("plugin").description("manage installed npm plugins");Z.command("install").argument("<specifier>","npm:<package> or npm:<package>@<version-or-tag>").option("--global","install in the user-global scope").option("--allow-scripts","allow npm lifecycle scripts with full user permissions during dependency install").option("--yes","skip confirmation prompts").action((W,X)=>b6(w,async()=>{let Y=IW(X);if(!await yW(w,"Install",W,X))return;let G=await w.service.install(W,Y);w.stdout.write(NE(G,Y.allowScripts))})),Z.command("remove").argument("<package>","installed npm package name").option("--global","remove from the user-global scope").option("--allow-scripts","allow npm lifecycle scripts with full user permissions while rebuilding dependencies").option("--yes","skip confirmation prompts").action((W,X)=>b6(w,async()=>{let Y=IW(X);if(!await yW(w,"Remove",W,X))return;await w.service.remove(W,Y),w.stdout.write(`Removed ${W} from ${Y.scope} plugins.
|
|
144
146
|
Restart CodeN to use npm plugin changes.
|
|
145
|
-
`)})),Z.command("list").option("--project","show only project plugins").option("--global","show only user-global plugins").action((W)=>b6(w,async()=>{if(W.project&&W.global)throw Error("plugin list accepts only one of --project or --global");let X=await w.service.list();w.stdout.write(
|
|
146
|
-
`),!W.yes){if(!await $.confirm("Allow npm lifecycle scripts to run with full user permissions?"))return!1}}return!0}async function b6($,w){try{await w()}catch(Z){$.stderr.write(`coden: ${
|
|
147
|
-
`),process.exitCode=2}}function
|
|
148
|
-
`)}function
|
|
149
|
-
`)}function
|
|
147
|
+
`)})),Z.command("list").option("--project","show only project plugins").option("--global","show only user-global plugins").action((W)=>b6(w,async()=>{if(W.project&&W.global)throw Error("plugin list accepts only one of --project or --global");let X=await w.service.list();w.stdout.write(BE(X,W))})),Z.command("sync").option("--global","sync the user-global plugin runtime").option("--allow-scripts","allow npm lifecycle scripts with full user permissions during dependency install").option("--yes","skip confirmation prompts").action((W)=>b6(w,async()=>{let X=IW(W);if(!await yW(w,"Sync",`${X.scope} plugins`,W))return;let Y=await w.service.sync(X);w.stdout.write(KE(X.scope,Y,X.allowScripts))}))}function IW($){return{scope:$.global?"global":"project",allowScripts:$.allowScripts===!0}}async function yW($,w,Z,W){if(!W.yes){if(!await $.confirm(`${w} ${Z}? npm plugins run with full process permissions; validation imports plugin top-level code with full permissions. Continue?`))return!1}if(W.allowScripts){if($.stderr.write(`Warning: --allow-scripts lets this package and transitive dependencies run lifecycle scripts with your user permissions.
|
|
148
|
+
`),!W.yes){if(!await $.confirm("Allow npm lifecycle scripts to run with full user permissions?"))return!1}}return!0}async function b6($,w){try{await w()}catch(Z){$.stderr.write(`coden: ${VE(Z)}
|
|
149
|
+
`),process.exitCode=2}}function NE($,w){return[`Installed ${$.packageName}@${$.version} (${$.scope})`,`Requested: ${$.requested}`,`Tools: ${$.tools.length>0?$.tools.slice().sort().join(", "):"none"}`,`Lifecycle scripts: ${w?"enabled":"disabled"}`,"Restart CodeN to use npm plugin changes.",""].join(`
|
|
150
|
+
`)}function KE($,w,Z){let W=w.slice().sort((X,Y)=>X.packageName.localeCompare(Y.packageName)).map((X)=>`${X.packageName}@${X.version}`);return[`Synced ${$} plugins: ${W.join(", ")||"none"}`,`Lifecycle scripts: ${Z?"enabled":"disabled"}`,"Restart CodeN to use npm plugin changes.",""].join(`
|
|
151
|
+
`)}function BE($,w){let Z=[];if(!w.global)Z.push(fz("Project plugins",$.project));if(!w.project)Z.push(fz("Global plugins",$.global));return`${Z.join(`
|
|
150
152
|
`)}
|
|
151
|
-
`}function
|
|
153
|
+
`}function fz($,w){let Z=w.slice().sort((X,Y)=>X.packageName.localeCompare(Y.packageName));if(Z.length===0)return`${$}: none
|
|
152
154
|
`;let W=Z.map((X)=>{let Y=X.shadowedByProject?" (shadowed by project)":"";return` ${X.packageName}@${X.version} requested ${X.requested}; ${X.tools.length} tool(s)${Y}`});return`${$}:
|
|
153
155
|
${W.join(`
|
|
154
156
|
`)}
|
|
155
|
-
`}function
|
|
156
|
-
`),process.exitCode=$ instanceof Ow?2:1});export{
|
|
157
|
+
`}function VE($){let w=$ instanceof Error?$.message:String($);for(let Z of Object.values(process.env)){if(!Z||Z.length<8)continue;w=w.split(Z).join("[redacted]")}return w}function FE($={}){let w=$.confirm??EE,Z=$.pluginService??OE(w),W=new eW().name("coden").description("CodeN \u2014 a minimal coding agent").version(XJ).argument("[prompt]","task to execute").option("-p, --print","non-interactive print mode",!1).option("--provider <provider>","openai or anthropic",Ez).option("--model <model-id>","model identifier").option("--resume [session-id]","resume a previous session, or list sessions when no id is given").option("--auto","skip permission and project-plugin confirmations",!1).option("--verbose","show detailed runtime status",!1).option("--max-steps <number>","maximum model steps",Lz).option("--plugin <path>","additional local TypeScript plugin or directory",Dz,[]).action((X,Y)=>Hz(X,Y));return kz(W,{service:Z,confirm:w,stdout:process.stdout,stderr:process.stderr}),W}function OE($){let w=process.cwd(),Z=new G5(w,ZX(),new t6,new oZ,WJ()),W=new p6(qE.join(wX(),"trusted-workspaces.json"));return new Sz(Z,w,W,$)}class Sz{service;workspace;trustStore;confirm;constructor($,w,Z,W){this.service=$;this.workspace=w;this.trustStore=Z;this.confirm=W}async install($,w){if(w.scope==="project")await this.ensureProjectTrust();return this.service.install($,w)}async remove($,w){return this.service.remove($,w)}async sync($){if($.scope==="project")await this.ensureProjectTrust();return this.service.sync($)}async list(){return this.service.list()}async ensureProjectTrust(){let $=await PE(this.workspace);if(await this.trustStore.isWorkspaceTrusted($))return;if(!await this.confirm(`Project npm plugins in ${$} run in-process with full user permissions. Trust this workspace?`))throw Error("workspace is not trusted for project npm plugins");await this.trustStore.trustWorkspace($)}}async function EE($){let w=UE({input:process.stdin,output:process.stderr});try{let Z=await w.question(`${$} [y/N] `);return/^y(?:es)?$/i.test(Z)}finally{w.close()}}function LE(){let $=process.argv[1];if(!$)return!1;try{return Az(HE(import.meta.url))===Az($)}catch{return!1}}if(LE())FE().parseAsync().catch(($)=>{process.stderr.write(`coden: ${$ instanceof Error?$.message:String($)}
|
|
158
|
+
`),process.exitCode=$ instanceof Ow?2:1});export{FE as createCliProgram};
|