UNPKG

directus-extension-ai-sdk-bundle

Version:

A small bundle of Flow Operations which enable interaction with the [OpenAI](https://beta.openai.com/overview) and [Stability](https://stability.ai/) API's.

6 lines 235 kB
"use strict";var e=require("crypto"),t=require("node:http"),r=require("node:https"),n=require("node:zlib"),s=require("node:stream"),a=require("node:buffer"),o=require("node:util"),i=require("node:url"),l=require("node:net");require("node:fs"),require("node:path");var c,u,d="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};!function(e){e.assertEqual=e=>e,e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const r of e)t[r]=r;return t},e.getValidEnumValues=t=>{const r=e.objectKeys(t).filter((e=>"number"!=typeof t[t[e]])),n={};for(const e of r)n[e]=t[e];return e.objectValues(n)},e.objectValues=t=>e.objectKeys(t).map((function(e){return t[e]})),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},e.find=(e,t)=>{for(const r of e)if(t(r))return r},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map((e=>"string"==typeof e?`'${e}'`:e)).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(c||(c={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(u||(u={}));const h=c.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),f=e=>{switch(typeof e){case"undefined":return h.undefined;case"string":return h.string;case"number":return isNaN(e)?h.nan:h.number;case"boolean":return h.boolean;case"function":return h.function;case"bigint":return h.bigint;case"symbol":return h.symbol;case"object":return Array.isArray(e)?h.array:null===e?h.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?h.promise:"undefined"!=typeof Map&&e instanceof Map?h.map:"undefined"!=typeof Set&&e instanceof Set?h.set:"undefined"!=typeof Date&&e instanceof Date?h.date:h.object;default:return h.unknown}},p=c.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class m extends Error{constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}get errors(){return this.issues}format(e){const t=e||function(e){return e.message},r={_errors:[]},n=e=>{for(const s of e.issues)if("invalid_union"===s.code)s.unionErrors.map(n);else if("invalid_return_type"===s.code)n(s.returnTypeError);else if("invalid_arguments"===s.code)n(s.argumentsError);else if(0===s.path.length)r._errors.push(t(s));else{let e=r,n=0;for(;n<s.path.length;){const r=s.path[n];n===s.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(s))):e[r]=e[r]||{_errors:[]},e=e[r],n++}}};return n(this),r}static assert(e){if(!(e instanceof m))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,c.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=(e=>e.message)){const t={},r=[];for(const n of this.issues)n.path.length>0?(t[n.path[0]]=t[n.path[0]]||[],t[n.path[0]].push(e(n))):r.push(e(n));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}m.create=e=>new m(e);const y=(e,t)=>{let r;switch(e.code){case p.invalid_type:r=e.received===h.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case p.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,c.jsonStringifyReplacer)}`;break;case p.unrecognized_keys:r=`Unrecognized key(s) in object: ${c.joinValues(e.keys,", ")}`;break;case p.invalid_union:r="Invalid input";break;case p.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${c.joinValues(e.options)}`;break;case p.invalid_enum_value:r=`Invalid enum value. Expected ${c.joinValues(e.options)}, received '${e.received}'`;break;case p.invalid_arguments:r="Invalid function arguments";break;case p.invalid_return_type:r="Invalid function return type";break;case p.invalid_date:r="Invalid date";break;case p.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:c.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case p.too_small:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case p.too_big:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case p.custom:r="Invalid input";break;case p.invalid_intersection_types:r="Intersection results could not be merged";break;case p.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case p.not_finite:r="Number must be finite";break;default:r=t.defaultError,c.assertNever(e)}return{message:r}};let g=y;function _(){return g}const b=e=>{const{data:t,path:r,errorMaps:n,issueData:s}=e,a=[...r,...s.path||[]],o={...s,path:a};if(void 0!==s.message)return{...s,path:a,message:s.message};let i="";const l=n.filter((e=>!!e)).slice().reverse();for(const e of l)i=e(o,{data:t,defaultError:i}).message;return{...s,path:a,message:i}};function w(e,t){const r=_(),n=b({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===y?void 0:y].filter((e=>!!e))});e.common.issues.push(n)}class v{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const r=[];for(const n of t){if("aborted"===n.status)return S;"dirty"===n.status&&e.dirty(),r.push(n.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const e of t){const t=await e.key,n=await e.value;r.push({key:t,value:n})}return v.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const n of t){const{key:t,value:s}=n;if("aborted"===t.status)return S;if("aborted"===s.status)return S;"dirty"===t.status&&e.dirty(),"dirty"===s.status&&e.dirty(),"__proto__"===t.value||void 0===s.value&&!n.alwaysSet||(r[t.value]=s.value)}return{status:e.value,value:r}}}const S=Object.freeze({status:"aborted"}),x=e=>({status:"dirty",value:e}),k=e=>({status:"valid",value:e}),T=e=>"aborted"===e.status,E=e=>"dirty"===e.status,R=e=>"valid"===e.status,A=e=>"undefined"!=typeof Promise&&e instanceof Promise;function P(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)}function C(e,t,r,n,s){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?s.call(e,r):s?s.value=r:t.set(e,r),r}var O,j,I;"function"==typeof SuppressedError&&SuppressedError,function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:null==e?void 0:e.message}(O||(O={}));class ${constructor(e,t,r,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=n}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const q=(e,t)=>{if(R(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new m(e.common.issues);return this._error=t,this._error}}};function N(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:n,description:s}=e;if(t&&(r||n))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:s};return{errorMap:(t,s)=>{var a,o;const{message:i}=e;return"invalid_enum_value"===t.code?{message:null!=i?i:s.defaultError}:void 0===s.data?{message:null!==(a=null!=i?i:n)&&void 0!==a?a:s.defaultError}:"invalid_type"!==t.code?{message:s.defaultError}:{message:null!==(o=null!=i?i:r)&&void 0!==o?o:s.defaultError}},description:s}}class L{constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(e){return f(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:f(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new v,ctx:{common:e.parent.common,data:e.data,parsedType:f(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(A(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){var r;const n={common:{issues:[],async:null!==(r=null==t?void 0:t.async)&&void 0!==r&&r,contextualErrorMap:null==t?void 0:t.errorMap},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:f(e)},s=this._parseSync({data:e,path:n.path,parent:n});return q(n,s)}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:null==t?void 0:t.errorMap,async:!0},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:f(e)},n=this._parse({data:e,path:r.path,parent:r}),s=await(A(n)?n:Promise.resolve(n));return q(r,s)}refine(e,t){const r=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement(((t,n)=>{const s=e(t),a=()=>n.addIssue({code:p.custom,...r(t)});return"undefined"!=typeof Promise&&s instanceof Promise?s.then((e=>!!e||(a(),!1))):!!s||(a(),!1)}))}refinement(e,t){return this._refinement(((r,n)=>!!e(r)||(n.addIssue("function"==typeof t?t(r,n):t),!1)))}_refinement(e){return new Oe({schema:this,typeName:Ze.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}optional(){return je.create(this,this._def)}nullable(){return Ie.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return he.create(this,this._def)}promise(){return Ce.create(this,this._def)}or(e){return me.create([this,e],this._def)}and(e){return be.create(this,e,this._def)}transform(e){return new Oe({...N(this._def),schema:this,typeName:Ze.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new $e({...N(this._def),innerType:this,defaultValue:t,typeName:Ze.ZodDefault})}brand(){return new Be({typeName:Ze.ZodBranded,type:this,...N(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new qe({...N(this._def),innerType:this,catchValue:t,typeName:Ze.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return Me.create(this,e)}readonly(){return De.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const B=/^c[^\s-]{8,}$/i,M=/^[0-9a-z]+$/,D=/^[0-9A-HJKMNP-TV-Z]{26}$/,F=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,W=/^[a-z0-9_-]{21}$/i,Z=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,z=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let U;const H=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,V=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,K=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,J="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",X=new RegExp(`^${J}$`);function Q(e){let t="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`),t}function Y(e){let t=`${J}T${Q(e)}`;const r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}class G extends L{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==h.string){const t=this._getOrReturnCtx(e);return w(t,{code:p.invalid_type,expected:h.string,received:t.parsedType}),S}const t=new v;let r;for(const a of this._def.checks)if("min"===a.kind)e.data.length<a.value&&(r=this._getOrReturnCtx(e,r),w(r,{code:p.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),t.dirty());else if("max"===a.kind)e.data.length>a.value&&(r=this._getOrReturnCtx(e,r),w(r,{code:p.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),t.dirty());else if("length"===a.kind){const n=e.data.length>a.value,s=e.data.length<a.value;(n||s)&&(r=this._getOrReturnCtx(e,r),n?w(r,{code:p.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):s&&w(r,{code:p.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),t.dirty())}else if("email"===a.kind)z.test(e.data)||(r=this._getOrReturnCtx(e,r),w(r,{validation:"email",code:p.invalid_string,message:a.message}),t.dirty());else if("emoji"===a.kind)U||(U=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),U.test(e.data)||(r=this._getOrReturnCtx(e,r),w(r,{validation:"emoji",code:p.invalid_string,message:a.message}),t.dirty());else if("uuid"===a.kind)F.test(e.data)||(r=this._getOrReturnCtx(e,r),w(r,{validation:"uuid",code:p.invalid_string,message:a.message}),t.dirty());else if("nanoid"===a.kind)W.test(e.data)||(r=this._getOrReturnCtx(e,r),w(r,{validation:"nanoid",code:p.invalid_string,message:a.message}),t.dirty());else if("cuid"===a.kind)B.test(e.data)||(r=this._getOrReturnCtx(e,r),w(r,{validation:"cuid",code:p.invalid_string,message:a.message}),t.dirty());else if("cuid2"===a.kind)M.test(e.data)||(r=this._getOrReturnCtx(e,r),w(r,{validation:"cuid2",code:p.invalid_string,message:a.message}),t.dirty());else if("ulid"===a.kind)D.test(e.data)||(r=this._getOrReturnCtx(e,r),w(r,{validation:"ulid",code:p.invalid_string,message:a.message}),t.dirty());else if("url"===a.kind)try{new URL(e.data)}catch(n){r=this._getOrReturnCtx(e,r),w(r,{validation:"url",code:p.invalid_string,message:a.message}),t.dirty()}else if("regex"===a.kind){a.regex.lastIndex=0;a.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),w(r,{validation:"regex",code:p.invalid_string,message:a.message}),t.dirty())}else if("trim"===a.kind)e.data=e.data.trim();else if("includes"===a.kind)e.data.includes(a.value,a.position)||(r=this._getOrReturnCtx(e,r),w(r,{code:p.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),t.dirty());else if("toLowerCase"===a.kind)e.data=e.data.toLowerCase();else if("toUpperCase"===a.kind)e.data=e.data.toUpperCase();else if("startsWith"===a.kind)e.data.startsWith(a.value)||(r=this._getOrReturnCtx(e,r),w(r,{code:p.invalid_string,validation:{startsWith:a.value},message:a.message}),t.dirty());else if("endsWith"===a.kind)e.data.endsWith(a.value)||(r=this._getOrReturnCtx(e,r),w(r,{code:p.invalid_string,validation:{endsWith:a.value},message:a.message}),t.dirty());else if("datetime"===a.kind){Y(a).test(e.data)||(r=this._getOrReturnCtx(e,r),w(r,{code:p.invalid_string,validation:"datetime",message:a.message}),t.dirty())}else if("date"===a.kind){X.test(e.data)||(r=this._getOrReturnCtx(e,r),w(r,{code:p.invalid_string,validation:"date",message:a.message}),t.dirty())}else if("time"===a.kind){new RegExp(`^${Q(a)}$`).test(e.data)||(r=this._getOrReturnCtx(e,r),w(r,{code:p.invalid_string,validation:"time",message:a.message}),t.dirty())}else"duration"===a.kind?Z.test(e.data)||(r=this._getOrReturnCtx(e,r),w(r,{validation:"duration",code:p.invalid_string,message:a.message}),t.dirty()):"ip"===a.kind?(n=e.data,("v4"!==(s=a.version)&&s||!H.test(n))&&("v6"!==s&&s||!V.test(n))&&(r=this._getOrReturnCtx(e,r),w(r,{validation:"ip",code:p.invalid_string,message:a.message}),t.dirty())):"base64"===a.kind?K.test(e.data)||(r=this._getOrReturnCtx(e,r),w(r,{validation:"base64",code:p.invalid_string,message:a.message}),t.dirty()):c.assertNever(a);var n,s;return{status:t.value,value:e.data}}_regex(e,t,r){return this.refinement((t=>e.test(t)),{validation:t,code:p.invalid_string,...O.errToObj(r)})}_addCheck(e){return new G({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...O.errToObj(e)})}url(e){return this._addCheck({kind:"url",...O.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...O.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...O.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...O.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...O.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...O.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...O.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...O.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...O.errToObj(e)})}datetime(e){var t,r;return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===(null==e?void 0:e.precision)?null:null==e?void 0:e.precision,offset:null!==(t=null==e?void 0:e.offset)&&void 0!==t&&t,local:null!==(r=null==e?void 0:e.local)&&void 0!==r&&r,...O.errToObj(null==e?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===(null==e?void 0:e.precision)?null:null==e?void 0:e.precision,...O.errToObj(null==e?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...O.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...O.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:null==t?void 0:t.position,...O.errToObj(null==t?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...O.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...O.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...O.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...O.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...O.errToObj(t)})}nonempty(e){return this.min(1,O.errToObj(e))}trim(){return new G({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new G({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new G({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((e=>"datetime"===e.kind))}get isDate(){return!!this._def.checks.find((e=>"date"===e.kind))}get isTime(){return!!this._def.checks.find((e=>"time"===e.kind))}get isDuration(){return!!this._def.checks.find((e=>"duration"===e.kind))}get isEmail(){return!!this._def.checks.find((e=>"email"===e.kind))}get isURL(){return!!this._def.checks.find((e=>"url"===e.kind))}get isEmoji(){return!!this._def.checks.find((e=>"emoji"===e.kind))}get isUUID(){return!!this._def.checks.find((e=>"uuid"===e.kind))}get isNANOID(){return!!this._def.checks.find((e=>"nanoid"===e.kind))}get isCUID(){return!!this._def.checks.find((e=>"cuid"===e.kind))}get isCUID2(){return!!this._def.checks.find((e=>"cuid2"===e.kind))}get isULID(){return!!this._def.checks.find((e=>"ulid"===e.kind))}get isIP(){return!!this._def.checks.find((e=>"ip"===e.kind))}get isBase64(){return!!this._def.checks.find((e=>"base64"===e.kind))}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function ee(e,t){const r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,s=r>n?r:n;return parseInt(e.toFixed(s).replace(".",""))%parseInt(t.toFixed(s).replace(".",""))/Math.pow(10,s)}G.create=e=>{var t;return new G({checks:[],typeName:Ze.ZodString,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...N(e)})};class te extends L{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){this._def.coerce&&(e.data=Number(e.data));if(this._getType(e)!==h.number){const t=this._getOrReturnCtx(e);return w(t,{code:p.invalid_type,expected:h.number,received:t.parsedType}),S}let t;const r=new v;for(const n of this._def.checks)if("int"===n.kind)c.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),w(t,{code:p.invalid_type,expected:"integer",received:"float",message:n.message}),r.dirty());else if("min"===n.kind){(n.inclusive?e.data<n.value:e.data<=n.value)&&(t=this._getOrReturnCtx(e,t),w(t,{code:p.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty())}else if("max"===n.kind){(n.inclusive?e.data>n.value:e.data>=n.value)&&(t=this._getOrReturnCtx(e,t),w(t,{code:p.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty())}else"multipleOf"===n.kind?0!==ee(e.data,n.value)&&(t=this._getOrReturnCtx(e,t),w(t,{code:p.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):"finite"===n.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),w(t,{code:p.not_finite,message:n.message}),r.dirty()):c.assertNever(n);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,O.toString(t))}gt(e,t){return this.setLimit("min",e,!1,O.toString(t))}lte(e,t){return this.setLimit("max",e,!0,O.toString(t))}lt(e,t){return this.setLimit("max",e,!1,O.toString(t))}setLimit(e,t,r,n){return new te({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:O.toString(n)}]})}_addCheck(e){return new te({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:O.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:O.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:O.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:O.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:O.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:O.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:O.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:O.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:O.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find((e=>"int"===e.kind||"multipleOf"===e.kind&&c.isInteger(e.value)))}get isFinite(){let e=null,t=null;for(const r of this._def.checks){if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}}te.create=e=>new te({checks:[],typeName:Ze.ZodNumber,coerce:(null==e?void 0:e.coerce)||!1,...N(e)});class re extends L{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){this._def.coerce&&(e.data=BigInt(e.data));if(this._getType(e)!==h.bigint){const t=this._getOrReturnCtx(e);return w(t,{code:p.invalid_type,expected:h.bigint,received:t.parsedType}),S}let t;const r=new v;for(const n of this._def.checks)if("min"===n.kind){(n.inclusive?e.data<n.value:e.data<=n.value)&&(t=this._getOrReturnCtx(e,t),w(t,{code:p.too_small,type:"bigint",minimum:n.value,inclusive:n.inclusive,message:n.message}),r.dirty())}else if("max"===n.kind){(n.inclusive?e.data>n.value:e.data>=n.value)&&(t=this._getOrReturnCtx(e,t),w(t,{code:p.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),r.dirty())}else"multipleOf"===n.kind?e.data%n.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),w(t,{code:p.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):c.assertNever(n);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,O.toString(t))}gt(e,t){return this.setLimit("min",e,!1,O.toString(t))}lte(e,t){return this.setLimit("max",e,!0,O.toString(t))}lt(e,t){return this.setLimit("max",e,!1,O.toString(t))}setLimit(e,t,r,n){return new re({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:O.toString(n)}]})}_addCheck(e){return new re({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:O.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:O.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:O.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:O.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:O.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}re.create=e=>{var t;return new re({checks:[],typeName:Ze.ZodBigInt,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...N(e)})};class ne extends L{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==h.boolean){const t=this._getOrReturnCtx(e);return w(t,{code:p.invalid_type,expected:h.boolean,received:t.parsedType}),S}return k(e.data)}}ne.create=e=>new ne({typeName:Ze.ZodBoolean,coerce:(null==e?void 0:e.coerce)||!1,...N(e)});class se extends L{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==h.date){const t=this._getOrReturnCtx(e);return w(t,{code:p.invalid_type,expected:h.date,received:t.parsedType}),S}if(isNaN(e.data.getTime())){return w(this._getOrReturnCtx(e),{code:p.invalid_date}),S}const t=new v;let r;for(const n of this._def.checks)"min"===n.kind?e.data.getTime()<n.value&&(r=this._getOrReturnCtx(e,r),w(r,{code:p.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),t.dirty()):"max"===n.kind?e.data.getTime()>n.value&&(r=this._getOrReturnCtx(e,r),w(r,{code:p.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),t.dirty()):c.assertNever(n);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new se({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:O.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:O.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}se.create=e=>new se({checks:[],coerce:(null==e?void 0:e.coerce)||!1,typeName:Ze.ZodDate,...N(e)});class ae extends L{_parse(e){if(this._getType(e)!==h.symbol){const t=this._getOrReturnCtx(e);return w(t,{code:p.invalid_type,expected:h.symbol,received:t.parsedType}),S}return k(e.data)}}ae.create=e=>new ae({typeName:Ze.ZodSymbol,...N(e)});class oe extends L{_parse(e){if(this._getType(e)!==h.undefined){const t=this._getOrReturnCtx(e);return w(t,{code:p.invalid_type,expected:h.undefined,received:t.parsedType}),S}return k(e.data)}}oe.create=e=>new oe({typeName:Ze.ZodUndefined,...N(e)});class ie extends L{_parse(e){if(this._getType(e)!==h.null){const t=this._getOrReturnCtx(e);return w(t,{code:p.invalid_type,expected:h.null,received:t.parsedType}),S}return k(e.data)}}ie.create=e=>new ie({typeName:Ze.ZodNull,...N(e)});class le extends L{constructor(){super(...arguments),this._any=!0}_parse(e){return k(e.data)}}le.create=e=>new le({typeName:Ze.ZodAny,...N(e)});class ce extends L{constructor(){super(...arguments),this._unknown=!0}_parse(e){return k(e.data)}}ce.create=e=>new ce({typeName:Ze.ZodUnknown,...N(e)});class ue extends L{_parse(e){const t=this._getOrReturnCtx(e);return w(t,{code:p.invalid_type,expected:h.never,received:t.parsedType}),S}}ue.create=e=>new ue({typeName:Ze.ZodNever,...N(e)});class de extends L{_parse(e){if(this._getType(e)!==h.undefined){const t=this._getOrReturnCtx(e);return w(t,{code:p.invalid_type,expected:h.void,received:t.parsedType}),S}return k(e.data)}}de.create=e=>new de({typeName:Ze.ZodVoid,...N(e)});class he extends L{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),n=this._def;if(t.parsedType!==h.array)return w(t,{code:p.invalid_type,expected:h.array,received:t.parsedType}),S;if(null!==n.exactLength){const e=t.data.length>n.exactLength.value,s=t.data.length<n.exactLength.value;(e||s)&&(w(t,{code:e?p.too_big:p.too_small,minimum:s?n.exactLength.value:void 0,maximum:e?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),r.dirty())}if(null!==n.minLength&&t.data.length<n.minLength.value&&(w(t,{code:p.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),r.dirty()),null!==n.maxLength&&t.data.length>n.maxLength.value&&(w(t,{code:p.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map(((e,r)=>n.type._parseAsync(new $(t,e,t.path,r))))).then((e=>v.mergeArray(r,e)));const s=[...t.data].map(((e,r)=>n.type._parseSync(new $(t,e,t.path,r))));return v.mergeArray(r,s)}get element(){return this._def.type}min(e,t){return new he({...this._def,minLength:{value:e,message:O.toString(t)}})}max(e,t){return new he({...this._def,maxLength:{value:e,message:O.toString(t)}})}length(e,t){return new he({...this._def,exactLength:{value:e,message:O.toString(t)}})}nonempty(e){return this.min(1,e)}}function fe(e){if(e instanceof pe){const t={};for(const r in e.shape){const n=e.shape[r];t[r]=je.create(fe(n))}return new pe({...e._def,shape:()=>t})}return e instanceof he?new he({...e._def,type:fe(e.element)}):e instanceof je?je.create(fe(e.unwrap())):e instanceof Ie?Ie.create(fe(e.unwrap())):e instanceof we?we.create(e.items.map((e=>fe(e)))):e}he.create=(e,t)=>new he({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Ze.ZodArray,...N(t)});class pe extends L{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=c.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==h.object){const t=this._getOrReturnCtx(e);return w(t,{code:p.invalid_type,expected:h.object,received:t.parsedType}),S}const{status:t,ctx:r}=this._processInputParams(e),{shape:n,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof ue&&"strip"===this._def.unknownKeys))for(const e in r.data)s.includes(e)||a.push(e);const o=[];for(const e of s){const t=n[e],s=r.data[e];o.push({key:{status:"valid",value:e},value:t._parse(new $(r,s,r.path,e)),alwaysSet:e in r.data})}if(this._def.catchall instanceof ue){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of a)o.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)a.length>0&&(w(r,{code:p.unrecognized_keys,keys:a}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of a){const n=r.data[t];o.push({key:{status:"valid",value:t},value:e._parse(new $(r,n,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then((async()=>{const e=[];for(const t of o){const r=await t.key,n=await t.value;e.push({key:r,value:n,alwaysSet:t.alwaysSet})}return e})).then((e=>v.mergeObjectSync(t,e))):v.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(e){return O.errToObj,new pe({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{var n,s,a,o;const i=null!==(a=null===(s=(n=this._def).errorMap)||void 0===s?void 0:s.call(n,t,r).message)&&void 0!==a?a:r.defaultError;return"unrecognized_keys"===t.code?{message:null!==(o=O.errToObj(e).message)&&void 0!==o?o:i}:{message:i}}}:{}})}strip(){return new pe({...this._def,unknownKeys:"strip"})}passthrough(){return new pe({...this._def,unknownKeys:"passthrough"})}extend(e){return new pe({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new pe({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Ze.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new pe({...this._def,catchall:e})}pick(e){const t={};return c.objectKeys(e).forEach((r=>{e[r]&&this.shape[r]&&(t[r]=this.shape[r])})),new pe({...this._def,shape:()=>t})}omit(e){const t={};return c.objectKeys(this.shape).forEach((r=>{e[r]||(t[r]=this.shape[r])})),new pe({...this._def,shape:()=>t})}deepPartial(){return fe(this)}partial(e){const t={};return c.objectKeys(this.shape).forEach((r=>{const n=this.shape[r];e&&!e[r]?t[r]=n:t[r]=n.optional()})),new pe({...this._def,shape:()=>t})}required(e){const t={};return c.objectKeys(this.shape).forEach((r=>{if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof je;)e=e._def.innerType;t[r]=e}})),new pe({...this._def,shape:()=>t})}keyof(){return Re(c.objectKeys(this.shape))}}pe.create=(e,t)=>new pe({shape:()=>e,unknownKeys:"strip",catchall:ue.create(),typeName:Ze.ZodObject,...N(t)}),pe.strictCreate=(e,t)=>new pe({shape:()=>e,unknownKeys:"strict",catchall:ue.create(),typeName:Ze.ZodObject,...N(t)}),pe.lazycreate=(e,t)=>new pe({shape:e,unknownKeys:"strip",catchall:ue.create(),typeName:Ze.ZodObject,...N(t)});class me extends L{_parse(e){const{ctx:t}=this._processInputParams(e),r=this._def.options;if(t.common.async)return Promise.all(r.map((async e=>{const r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}}))).then((function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;const r=e.map((e=>new m(e.ctx.common.issues)));return w(t,{code:p.invalid_union,unionErrors:r}),S}));{let e;const n=[];for(const s of r){const r={...t,common:{...t.common,issues:[]},parent:null},a=s._parseSync({data:t.data,path:t.path,parent:r});if("valid"===a.status)return a;"dirty"!==a.status||e||(e={result:a,ctx:r}),r.common.issues.length&&n.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const s=n.map((e=>new m(e)));return w(t,{code:p.invalid_union,unionErrors:s}),S}}get options(){return this._def.options}}me.create=(e,t)=>new me({options:e,typeName:Ze.ZodUnion,...N(t)});const ye=e=>e instanceof Te?ye(e.schema):e instanceof Oe?ye(e.innerType()):e instanceof Ee?[e.value]:e instanceof Ae?e.options:e instanceof Pe?c.objectValues(e.enum):e instanceof $e?ye(e._def.innerType):e instanceof oe?[void 0]:e instanceof ie?[null]:e instanceof je?[void 0,...ye(e.unwrap())]:e instanceof Ie?[null,...ye(e.unwrap())]:e instanceof Be||e instanceof De?ye(e.unwrap()):e instanceof qe?ye(e._def.innerType):[];class ge extends L{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==h.object)return w(t,{code:p.invalid_type,expected:h.object,received:t.parsedType}),S;const r=this.discriminator,n=t.data[r],s=this.optionsMap.get(n);return s?t.common.async?s._parseAsync({data:t.data,path:t.path,parent:t}):s._parseSync({data:t.data,path:t.path,parent:t}):(w(t,{code:p.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),S)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){const n=new Map;for(const r of t){const t=ye(r.shape[e]);if(!t.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const s of t){if(n.has(s))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(s)}`);n.set(s,r)}}return new ge({typeName:Ze.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...N(r)})}}function _e(e,t){const r=f(e),n=f(t);if(e===t)return{valid:!0,data:e};if(r===h.object&&n===h.object){const r=c.objectKeys(t),n=c.objectKeys(e).filter((e=>-1!==r.indexOf(e))),s={...e,...t};for(const r of n){const n=_e(e[r],t[r]);if(!n.valid)return{valid:!1};s[r]=n.data}return{valid:!0,data:s}}if(r===h.array&&n===h.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let n=0;n<e.length;n++){const s=_e(e[n],t[n]);if(!s.valid)return{valid:!1};r.push(s.data)}return{valid:!0,data:r}}return r===h.date&&n===h.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class be extends L{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=(e,n)=>{if(T(e)||T(n))return S;const s=_e(e.value,n.value);return s.valid?((E(e)||E(n))&&t.dirty(),{status:t.value,value:s.data}):(w(r,{code:p.invalid_intersection_types}),S)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then((([e,t])=>n(e,t))):n(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}be.create=(e,t,r)=>new be({left:e,right:t,typeName:Ze.ZodIntersection,...N(r)});class we extends L{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==h.array)return w(r,{code:p.invalid_type,expected:h.array,received:r.parsedType}),S;if(r.data.length<this._def.items.length)return w(r,{code:p.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),S;!this._def.rest&&r.data.length>this._def.items.length&&(w(r,{code:p.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const n=[...r.data].map(((e,t)=>{const n=this._def.items[t]||this._def.rest;return n?n._parse(new $(r,e,r.path,t)):null})).filter((e=>!!e));return r.common.async?Promise.all(n).then((e=>v.mergeArray(t,e))):v.mergeArray(t,n)}get items(){return this._def.items}rest(e){return new we({...this._def,rest:e})}}we.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new we({items:e,typeName:Ze.ZodTuple,rest:null,...N(t)})};class ve extends L{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==h.object)return w(r,{code:p.invalid_type,expected:h.object,received:r.parsedType}),S;const n=[],s=this._def.keyType,a=this._def.valueType;for(const e in r.data)n.push({key:s._parse(new $(r,e,r.path,e)),value:a._parse(new $(r,r.data[e],r.path,e)),alwaysSet:e in r.data});return r.common.async?v.mergeObjectAsync(t,n):v.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,r){return new ve(t instanceof L?{keyType:e,valueType:t,typeName:Ze.ZodRecord,...N(r)}:{keyType:G.create(),valueType:e,typeName:Ze.ZodRecord,...N(t)})}}class Se extends L{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==h.map)return w(r,{code:p.invalid_type,expected:h.map,received:r.parsedType}),S;const n=this._def.keyType,s=this._def.valueType,a=[...r.data.entries()].map((([e,t],a)=>({key:n._parse(new $(r,e,r.path,[a,"key"])),value:s._parse(new $(r,t,r.path,[a,"value"]))})));if(r.common.async){const e=new Map;return Promise.resolve().then((async()=>{for(const r of a){const n=await r.key,s=await r.value;if("aborted"===n.status||"aborted"===s.status)return S;"dirty"!==n.status&&"dirty"!==s.status||t.dirty(),e.set(n.value,s.value)}return{status:t.value,value:e}}))}{const e=new Map;for(const r of a){const n=r.key,s=r.value;if("aborted"===n.status||"aborted"===s.status)return S;"dirty"!==n.status&&"dirty"!==s.status||t.dirty(),e.set(n.value,s.value)}return{status:t.value,value:e}}}}Se.create=(e,t,r)=>new Se({valueType:t,keyType:e,typeName:Ze.ZodMap,...N(r)});class xe extends L{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==h.set)return w(r,{code:p.invalid_type,expected:h.set,received:r.parsedType}),S;const n=this._def;null!==n.minSize&&r.data.size<n.minSize.value&&(w(r,{code:p.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()),null!==n.maxSize&&r.data.size>n.maxSize.value&&(w(r,{code:p.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());const s=this._def.valueType;function a(e){const r=new Set;for(const n of e){if("aborted"===n.status)return S;"dirty"===n.status&&t.dirty(),r.add(n.value)}return{status:t.value,value:r}}const o=[...r.data.values()].map(((e,t)=>s._parse(new $(r,e,r.path,t))));return r.common.async?Promise.all(o).then((e=>a(e))):a(o)}min(e,t){return new xe({...this._def,minSize:{value:e,message:O.toString(t)}})}max(e,t){return new xe({...this._def,maxSize:{value:e,message:O.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}xe.create=(e,t)=>new xe({valueType:e,minSize:null,maxSize:null,typeName:Ze.ZodSet,...N(t)});class ke extends L{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==h.function)return w(t,{code:p.invalid_type,expected:h.function,received:t.parsedType}),S;function r(e,r){return b({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,_(),y].filter((e=>!!e)),issueData:{code:p.invalid_arguments,argumentsError:r}})}function n(e,r){return b({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,_(),y].filter((e=>!!e)),issueData:{code:p.invalid_return_type,returnTypeError:r}})}const s={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof Ce){const e=this;return k((async function(...t){const o=new m([]),i=await e._def.args.parseAsync(t,s).catch((e=>{throw o.addIssue(r(t,e)),o})),l=await Reflect.apply(a,this,i),c=await e._def.returns._def.type.parseAsync(l,s).catch((e=>{throw o.addIssue(n(l,e)),o}));return c}))}{const e=this;return k((function(...t){const o=e._def.args.safeParse(t,s);if(!o.success)throw new m([r(t,o.error)]);const i=Reflect.apply(a,this,o.data),l=e._def.returns.safeParse(i,s);if(!l.success)throw new m([n(i,l.error)]);return l.data}))}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new ke({...this._def,args:we.create(e).rest(ce.create())})}returns(e){return new ke({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new ke({args:e||we.create([]).rest(ce.create()),returns:t||ce.create(),typeName:Ze.ZodFunction,...N(r)})}}class Te extends L{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}Te.create=(e,t)=>new Te({getter:e,typeName:Ze.ZodLazy,...N(t)});class Ee extends L{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return w(t,{received:t.data,code:p.invalid_literal,expected:this._def.value}),S}return{status:"valid",value:e.data}}get value(){return this._def.value}}function Re(e,t){return new Ae({values:e,typeName:Ze.ZodEnum,...N(t)})}Ee.create=(e,t)=>new Ee({value:e,typeName:Ze.ZodLiteral,...N(t)});class Ae extends L{constructor(){super(...arguments),j.set(this,void 0)}_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),r=this._def.values;return w(t,{expected:c.joinValues(r),received:t.parsedType,code:p.invalid_type}),S}if(P(this,j,"f")||C(this,j,new Set(this._def.values),"f"),!P(this,j,"f").has(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return w(t,{received:t.data,code:p.invalid_enum_value,options:r}),S}return k(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return Ae.create(e,{...this._def,...t})}exclude(e,t=this._def){return Ae.create(this.options.filter((t=>!e.includes(t))),{...this._def,...t})}}j=new WeakMap,Ae.create=Re;class Pe extends L{constructor(){super(...arguments),I.set(this,void 0)}_parse(e){const t=c.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==h.string&&r.parsedType!==h.number){const e=c.objectValues(t);return w(r,{expected:c.joinValues(e),received:r.parsedType,code:p.invalid_type}),S}if(P(this,I,"f")||C(this,I,new Set(c.getValidEnumValues(this._def.values)),"f"),!P(this,I,"f").has(e.data)){const e=c.objectValues(t);return w(r,{received:r.data,code:p.invalid_enum_value,options:e}),S}return k(e.data)}get enum(){return this._def.values}}I=new WeakMap,Pe.create=(e,t)=>new Pe({values:e,typeName:Ze.ZodNativeEnum,...N(t)});class Ce extends L{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==h.promise&&!1===t.common.async)return w(t,{code:p.invalid_type,expected:h.promise,received:t.parsedType}),S;const r=t.parsedType===h.promise?t.data:Promise.resolve(t.data);return k(r.then((e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap}))))}}Ce.create=(e,t)=>new Ce({type:e,typeName:Ze.ZodPromise,...N(t)});class Oe extends L{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Ze.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=this._def.effect||null,s={addIssue:e=>{w(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),"preprocess"===n.type){const e=n.transform(r.data,s);if(r.common.async)return Promise.resolve(e).then((async e=>{if("aborted"===t.value)return S;const n=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return"aborted"===n.status?S:"dirty"===n.status||"dirty"===t.value?x(n.value):n}));{if("aborted"===t.value)return S;const n=this._def.schema._parseSync({data:e,path:r.path,parent:r});return"aborted"===n.status?S:"dirty"===n.status||"dirty"===t.value?x(n.value):n}}if("refinement"===n.type){const e=e=>{const t=n.refinement(e,s);if(r.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===r.common.async){const n=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===n.status?S:("dirty"===n.status&&t.dirty(),e(n.value),{status:t.value,value:n.value})}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then((r=>"aborted"===r.status?S:("dirty"===r.status&&t.dirty(),e(r.value).then((()=>({status:t.value,value:r.value}))))))}if("transform"===n.type){if(!1===r.common.async){const e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!R(e))return e;const a=n.transform(e.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:a}}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then((e=>R(e)?Promise.resolve(n.transform(e.value,s)).then((e=>({status:t.value,value:e}))):e))}c.assertNever(n)}}Oe.create=(e,t,r)=>new Oe({schema:e,typeName:Ze.ZodEffects,effect:t,...N(r)}),Oe.createWithPreprocess=(e,t,r)=>new Oe({schema:t,effect:{type:"preprocess",transform:e},typeName:Ze.ZodEffects,...N(r)});class je extends L{_parse(e){return this._getType(e)===h.undefined?k(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}je.create=(e,t)=>new je({innerType:e,typeName:Ze.ZodOptional,...N(t)});class Ie extends L{_parse(e){return this._getType(e)===h.null?k(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ie.create=(e,t)=>new Ie({innerType:e,typeName:Ze.ZodNullable,...N(t)});class $e extends L{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===h.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}$e.create=(e,t)=>new $e({innerType:e,typeName:Ze.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...N(t)});class qe extends L{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return A(n)?n.then((e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new m(r.common.issues)},input:r.data})}))):{status:"valid",value:"valid"===n.status?n.value:this._def.catchValue({get error(){return new m(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}qe.create=(e,t)=>new qe({innerType:e,typeName:Ze.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...N(t)});class Ne extends L{_parse(e){if(this._getType(e)!==h.nan){const t=this._getOrReturnCtx(e);return w(t,{code:p.invalid_type,expected:h.nan,received:t.parsedType}),S}return{status:"valid",value:e.data}}}Ne.create=e=>new Ne({typeName:Ze.ZodNaN,...N(e)});const Le=Symbol("zod_brand");class Be extends L{_parse(e){const{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class Me extends L{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.common.async){return(async()=>{const e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?S:"dirty"===e.status?(t.dirty(),x(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})()}{const e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?S:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(e,t){return new Me({in:e,out:t,typeName:Ze.ZodPipeline})}}class De extends L{_parse(e){const t=this._def.innerType._parse(e),r=e=>(R(e)&&(e.value=Object.freeze(e.value)),e);return A(t)?t.then((e=>r(e))):r(t)}unwrap(){return this._def.innerType}}function Fe(e,t={},r){return e?le.create().superRefine(((n,s)=>{var a,o;if(!e(n)){const e="function"==typeof t?t(n):"string"==typeof t?{message:t}:t,i=null===(o=null!==(a=e.fatal)&&void 0!==a?a:r)||void 0===o||o,l="string"==typeof e?{message:e}:e;s.addIssue({code:"custom",...l,fatal:i})}})):le.create()}De.create=(e,t)=>new De({innerType:e,typeName:Ze.ZodReadonly,...N(t)});const We={object:pe.lazycreate};var Ze;!function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"}(Ze||(Ze={}));const ze=G.create,Ue=te.create,He=Ne.create,Ve=re.create,Ke=ne.create,Je=se.create,Xe=ae.create,Qe=oe.create,Ye=ie.create,Ge=le.create,et=ce.create,tt=ue.create,rt=de.create,nt=he.create,st=pe.create,at=pe.strictCreate,ot=me.create,it=ge.create,lt=be.create,ct=we.create,ut=ve.create,dt=Se.create,ht=xe.create,ft=ke.create,pt=Te.create,mt=Ee.create,yt=Ae.create,gt=Pe.create,_t=Ce.create,bt=Oe.create,wt=je.create,vt=Ie.create,St=Oe.createWithPreprocess,xt=Me.create,kt={string:e=>G.create({...e,coerce:!0}),number:e=>te.create({...e,coerce:!0}),boolean:e=>ne.create({...e,coerce:!0}),bigint:e=>re.create({...e,coerce:!0}),date:e=>se.create({...e,coerce:!0})},Tt=S;var Et=Object.freeze({__proto__:null,defaultErrorMap:y,setErrorMap:function(e){g=e},getErrorMap:_,makeIssue:b,EMPTY_PATH:[],addIssueToContext:w,ParseStatus:v,INVALID:S,DIRTY:x,OK:k,isAborted:T,isDirty:E,isValid:R,isAsync:A,get util(){return c},get objectUtil(){return u},ZodParsedType:h,getParsedType:f,ZodType:L,datetimeRegex:Y,ZodString:G,ZodNumber:te,ZodBigInt:re,ZodBoolean:ne,ZodDate:se,ZodSymbol:ae,ZodUndefined:oe,ZodNull:ie,ZodAny:le,ZodUnknown:ce,ZodNever:ue,ZodVoid:de,ZodArray:he,ZodObject:pe,ZodUnion:me,ZodDiscriminatedUnion:ge,ZodIntersection:be,ZodTuple:we,ZodRecord:ve,ZodMap:Se,ZodSet:xe,ZodFunction:ke,ZodLazy:Te,ZodLiteral:Ee,ZodEnum:Ae,ZodNativeEnum:Pe,ZodPromise:Ce,ZodEffects:Oe,ZodTransformer:Oe,ZodOptional:je,ZodNullable:Ie,ZodDefault:$e,ZodCatch:qe,ZodNaN:Ne,BRAND:Le,ZodBranded:Be,ZodPipeline:Me,ZodReadonly:De,custom:Fe,Schema:L,ZodSchema:L,late:We,get ZodFirstPartyTypeKind(){return Ze},coerce:kt,any:Ge,array:nt,bigint:Ve,boolean:Ke,date:Je,discriminatedUnion:it,effect:bt,enum:yt,function:ft,instanceof:(e,t={message:`Input not instance of ${e.name}`})=>Fe((t=>t instanceof e),t),intersection:lt,lazy:pt,literal:mt,map:dt,nan:He,nativeEnum:gt,never:tt,null:Ye,nullable:vt,number:Ue,object:st,oboolean:()=>Ke().optional(),onumber:()=>Ue().optional(),optional:wt,ostring:()=>ze().optional(),pipeline:xt,preprocess:St,promise:_t,record:ut,set:ht,strictObject:at,string:ze,symbol:Xe,transformer:bt,tuple:ct,undefined:Qe,union:ot,unknown:et,void:rt,NEVER:Tt,ZodIssueCode:p,quotelessJson:e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),ZodError:m}),Rt=["interface","display","layout","module","panel","theme"],At=["hook","endpoint"],Pt=["operation"],Ct=Et.object({app:Et.string(),api:Et.string()}),Ot=Et.object({request:Et.optional(Et.object({urls:Et.array(Et.string()),methods:Et.array(Et.union([Et.literal("GET"),Et.literal("POST"),Et.literal("PATCH"),Et.literal("PUT"),Et.literal("DELETE")]))})),log:Et.optional(Et.object({})),sleep:Et.optional(Et.object({}))}),jt=Et.optional(Et.object({enabled:Et.boolean(),requestedScopes:Ot})),It=Et.union([Et.object({type:Et.enum(At),name:Et.string(),source:Et.string()}),Et.object({type:Et.enum(Rt),name:Et.string(),source:Et.string()}),Et.object({type:Et.enum(Pt),name:Et.string(),source:Ct})]),$t=Et.object({host:Et.string(),hidden:Et.boolean().optional()}),qt=Et.object({type:Et.enum(Rt),path:Et.string(),source:Et.string()}),Nt=Et.object({type:Et.enum(At),path:Et.string(),source:Et.string(),sandbox:jt}),Lt=Et.object({type:Et.enum(Pt),path:Ct,source:Ct,sandbox:jt}),Bt=Et.object({type:Et.literal("bundle"),partial:Et.boolean().optional(),path:Ct,entries:Et.array(It)});Et.array(It);var Mt=$t.and(Et.union([qt,Nt,Lt,Bt]));Et.object({name:Et.string(),version:Et.string(),type:Et.union([Et.literal("module"),Et.literal("commonjs")]).optional(),description:Et.string().optional(),icon:Et.string().optional(),dependencies:Et.record(Et.string()).optional(),devDependencies:Et.record(Et.string()).optional(),"directus:extension":Mt});const Dt="RFC3986",Ft={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:e=>String(e)},Wt=Array.isArray,Zt=(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})(),zt=1024;function Ut(e,t){if(Wt(e)){const r=[];for(let n=0;n<e.length;n+=1)r.push(t(e[n]));return r}return t(e)}const Ht=Object.prototype.hasOwnProperty,Vt={brackets:e=>String(e)+"[]",comma:"comma",indices:(e,t)=>String(e)+"["+t+"]",repeat:e=>String(e)},Kt=Array.isArray,Jt=Array.prototype.push,Xt=function(e,t){Jt.apply(e,Kt(t)?t:[t])},Qt=Date.prototype.toISOString,Yt={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:(e,t,r,n,s)=>{if(0===e.length)return e;let a=e;if("symbol"==typeof e?a=Symbol.prototype.toString.call(e):"string"!=typeof e&&(a=String(e)),"iso-8859-1"===r)return escape(a).replace(/%u[0-9a-f]{4}/gi,(function(e){return"%26%23"+parseInt(e.slice(2),16)+"%3B"}));let o="";for(let e=0;e<a.length;e+=zt){const t=a.length>=zt?a.slice(e,e+zt):a,r=[];for(let e=0;e<t.length;++e){let n=t.charCodeAt(e);45===n||46===n||95===n||126===n||n>=48&&n<=57||n>=65&&n<=90||n>=97&&n<=122||"RFC1738"===s&&(40===n||41===n)?r[r.length]=t.charAt(e):n<128?r[r.length]=Zt[n]:n<2048?r[r.length]=Zt[192|n>>6]+Zt[128|63&n]:n<55296||n>=57344?r[r.length]=Zt[224|n>>12]+Zt[128|n>>6&63]+Zt[128|63&n]:(e+=1,n=65536+((1023&n)<<10|1023&t.charCodeAt(e)),r[r.length]=Zt[240|n>>18]+Zt[128|n>>12&63]+Zt[128|n>>6&63]+Zt[128|63&n])}o+=r.join("")}return o},encodeValuesOnly:!1,format:Dt,formatter:Ft[Dt],indices:!1,serializeDate:e=>Qt.call(e),skipNulls:!1,strictNullHandling:!1};const Gt={};function er(e,t,r,n,s,a,o,i,l,c,u,d,h,f,p,m,y,g){let _=e,b=g,w=0,v=!1;for(;void 0!==(b=b.get(Gt))&&!v;){const t=b.get(e);if(w+=1,void 0!==t){if(t===w)throw new RangeError("Cyclic object value");v=!0}void 0===b.get(Gt)&&(w=0)}if("function"==typeof c?_=c(t,_):_ instanceof Date?_=h?.(_):"comma"===r&&Kt(_)&&(_=Ut(_,(function(e){return e instanceof Date?h?.(e):e}))),null===_){if(a)return l&&!m?l(t,Yt.encoder,y,"key",f):t;_=""}if("string"==typeof(S=_)||"number"==typeof S||"boolean"==typeof S||"symbol"==typeof S||"bigint"==typeof S||function(e){return!(!e||"object"!=typeof e||!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e)))}(_)){if(l){const e=m?t:l(t,Yt.encoder,y,"key",f);return[p?.(e)+"="+p?.(l(_,Yt.encoder,y,"value",f))]}return[p?.(t)+"="+p?.(String(_))]}var S;const x=[];if(void 0===_)return x;let k;if("comma"===r&&Kt(_))m&&l&&(_=Ut(_,l)),k=[{value:_.length>0?_.join(",")||null:void 0}];else if(Kt(c))k=c;else{const e=Object.keys(_);k=u?e.sort(u):e}const T=i?String(t).replace(/\./g,"%2E"):String(t),E=n&&Kt(_)&&1===_.length?T+"[]":T;if(s&&Kt(_)&&0===_.length)return E+"[]";for(let t=0;t<k.length;++t){const b=k[t],v="object"==typeof b&&void 0!==b.value?b.value:_[b];if(o&&null===v)continue;const S=d&&i?b.replace(/\./g,"%2E"):b,T=Kt(_)?"function"==typeof r?r(E,S):E:E+(d?"."+S:"["+S+"]");g.set(e,w);const R=new WeakMap;R.set(Gt,g),Xt(x,er(v,T,r,n,s,a,o,i,"comma"===r&&m&&Kt(_)?null:l,c,u,d,h,f,p,m,y,R))}return x}function tr(e,t={}){let r=e;const n=function(e=Yt){if(void 0!==e.allowEmptyArrays&&"boolean"!=typeof e.allowEmptyArrays)throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(void 0!==e.encodeDotInKeys&&"boolean"!=typeof e.encodeDotInKeys)throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(null!==e.encoder&&void 0!==e.encoder&&"function"!=typeof e.encoder)throw new TypeError("Encoder has to be a function.");const t=e.charset||Yt.charset;if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let r=Dt;if(void 0!==e.format){if(!Ht.call(Ft,e.format))throw new TypeError("Unknown format option provided.");r=e.format}const n=Ft[r];let s,a=Yt.filter;if(("function"==typeof e.filter||Kt(e.filter))&&(a=e.filter),s=e.arrayFormat&&e.arrayFormat in Vt?e.arrayFormat:"indices"in e?e.indices?"indices":"repeat":Yt.arrayFormat,"commaRoundTrip"in e&&"boolean"!=typeof e.commaRoundTrip)throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const o=void 0===e.allowDots?1==!!e.encodeDotInKeys||Yt.allowDots:!!e.allowDots;return{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:Yt.addQueryPrefix,allowDots:o,allowEmptyArrays:"boolean"==typeof e.allowEmptyArrays?!!e.allowEmptyArrays:Yt.allowEmptyArrays,arrayFormat:s,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:Yt.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:void 0===e.delimiter?Yt.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:Yt.encode,encodeDotInKeys:"boolean"==typeof e.encodeDotInKeys?e.encodeDotInKeys:Yt.encodeDotInKeys,encoder:"function"==typeof e.encoder?e.encoder:Yt.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:Yt.encodeValuesOnly,filter:a,format:r,formatter:n,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:Yt.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:Yt.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:Yt.strictNullHandling}}(t);let s,a;"function"==typeof n.filter?(a=n.filter,r=a("",r)):Kt(n.filter)&&(a=n.filter,s=a);const o=[];if("object"!=typeof r||null===r)return"";const i=Vt[n.arrayFormat],l="comma"===i&&n.commaRoundTrip;s||(s=Object.keys(r)),n.sort&&s.sort(n.sort);const c=new WeakMap;for(let e=0;e<s.length;++e){const t=s[e];n.skipNulls&&null===r[t]||Xt(o,er(r[t],t,i,l,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,c))}const u=o.join(n.delimiter);let d=!0===n.addQueryPrefix?"?":"";return n.charsetSentinel&&("iso-8859-1"===n.charset?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),u.length>0?d+u:""}const rr="4.72.0";let nr,sr,ar,or,ir,lr,cr,ur,dr,hr=!1;class fr{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}}nr||function(e,t={auto:!1}){if(hr)throw new Error(`you must \`import 'openai/shims/${e.kind}'\` before importing anything else from openai`);if(nr)throw new Error(`can't \`import 'openai/shims/${e.kind}'\` after \`import 'openai/shims/${nr}'\``);hr=t.auto,nr=e.kind,sr=e.fetch,e.Request,e.Response,e.Headers,ar=e.FormData,e.Blob,or=e.File,ir=e.ReadableStream,lr=e.getMultipartRequestOptions,cr=e.getDefaultAgent,ur=e.fileFromPath,dr=e.isFsReadStream}(function({manuallyImported:e}={}){const t=e?"You may need to use polyfills":"Add one of these imports before your first `import … from 'openai'`:\n- `import 'openai/shims/node'` (if you're running on Node)\n- `import 'openai/shims/web'` (otherwise)\n";let r,n,s,a;try{r=fetch,n=Request,s=Response,a=Headers}catch(e){throw new Error(`this environment is missing the following Web Fetch API type: ${e.message}. ${t}`)}return{kind:"web",fetch:r,Request:n,Response:s,Headers:a,FormData:"undefined"!=typeof FormData?FormData:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${t}`)}},Blob:"undefined"!=typeof Blob?Blob:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${t}`)}},File:"undefined"!=typeof File?File:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${t}`)}},ReadableStream:"undefined"!=typeof ReadableStream?ReadableStream:class{constructor(){throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${t}`)}},getMultipartRequestOptions:async(e,t)=>({...t,body:new fr(e)}),getDefaultAgent:e=>{},fileFromPath:()=>{throw new Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/openai/openai-node#file-uploads")},isFsReadStream:e=>!1}}(),{auto:!0});class pr extends Error{}class mr extends pr{constructor(e,t,r,n){super(`${mr.makeMessage(e,t,r)}`),this.status=e,this.headers=n,this.request_id=n?.["x-request-id"];const s=t;this.error=s,this.code=s?.code,this.param=s?.param,this.type=s?.type}static makeMessage(e,t,r){const n=t?.message?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,r,n){if(!e)return new gr({message:r,cause:fn(t)});const s=t?.error;return 400===e?new br(e,s,r,n):401===e?new wr(e,s,r,n):403===e?new vr(e,s,r,n):404===e?new Sr(e,s,r,n):409===e?new xr(e,s,r,n):422===e?new kr(e,s,r,n):429===e?new Tr(e,s,r,n):e>=500?new Er(e,s,r,n):new mr(e,s,r,n)}}class yr extends mr{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0),this.status=void 0}}class gr extends mr{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),this.status=void 0,t&&(this.cause=t)}}class _r extends gr{constructor({message:e}={}){super({message:e??"Request timed out."})}}class br extends mr{constructor(){super(...arguments),this.status=400}}class wr extends mr{constructor(){super(...arguments),this.status=401}}class vr extends mr{constructor(){super(...arguments),this.status=403}}class Sr extends mr{constructor(){super(...arguments),this.status=404}}class xr extends mr{constructor(){super(...arguments),this.status=409}}class kr extends mr{constructor(){super(...arguments),this.status=422}}class Tr extends mr{constructor(){super(...arguments),this.status=429}}class Er extends mr{}class Rr extends pr{constructor(){super("Could not parse response content as the length limit was reached")}}class Ar extends pr{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class Pr{constructor(){this.buffer=[],this.trailingCR=!1}decode(e){let t=this.decodeText(e);if(this.trailingCR&&(t="\r"+t,this.trailingCR=!1),t.endsWith("\r")&&(this.trailingCR=!0,t=t.slice(0,-1)),!t)return[];const r=Pr.NEWLINE_CHARS.has(t[t.length-1]||"");let n=t.split(Pr.NEWLINE_REGEXP);return r&&n.pop(),1!==n.length||r?(this.buffer.length>0&&(n=[this.buffer.join("")+n[0],...n.slice(1)],this.buffer=[]),r||(this.buffer=[n.pop()||""]),n):(this.buffer.push(n[0]),[])}decodeText(e){if(null==e)return"";if("string"==typeof e)return e;if("undefined"!=typeof Buffer){if(e instanceof Buffer)return e.toString();if(e instanceof Uint8Array)return Buffer.from(e).toString();throw new pr(`Unexpected: received non-Uint8Array (${e.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if("undefined"!=typeof TextDecoder){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(e);throw new pr(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new pr("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){if(!this.buffer.length&&!this.trailingCR)return[];const e=[this.buffer.join("")];return this.buffer=[],this.trailingCR=!1,e}}Pr.NEWLINE_CHARS=new Set(["\n","\r"]),Pr.NEWLINE_REGEXP=/\r\n|[\n\r]/g;class Cr{constructor(e,t){this.iterator=e,this.controller=t}static fromSSEResponse(e,t){let r=!1;return new Cr((async function*(){if(r)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let n=!1;try{for await(const r of async function*(e,t){if(!e.body)throw t.abort(),new pr("Attempted to iterate over a response with no body");const r=new jr,n=new Pr,s=Ir(e.body);for await(const e of async function*(e){let t=new Uint8Array;for await(const r of e){if(null==r)continue;const e=r instanceof ArrayBuffer?new Uint8Array(r):"string"==typeof r?(new TextEncoder).encode(r):r;let n,s=new Uint8Array(t.length+e.length);for(s.set(t),s.set(e,t.length),t=s;-1!==(n=Or(t));)yield t.slice(0,n),t=t.slice(n)}t.length>0&&(yield t)}(s))for(const t of n.decode(e)){const e=r.decode(t);e&&(yield e)}for(const e of n.flush()){const t=r.decode(e);t&&(yield t)}}(e,t))if(!n)if(r.data.startsWith("[DONE]"))n=!0;else if(null===r.event){let e;try{e=JSON.parse(r.data)}catch(e){throw console.error("Could not parse message into JSON:",r.data),console.error("From chunk:",r.raw),e}if(e&&e.error)throw new mr(void 0,e.error,void 0,void 0);yield e}else{let e;try{e=JSON.parse(r.data)}catch(e){throw console.error("Could not parse message into JSON:",r.data),console.error("From chunk:",r.raw),e}if("error"==r.event)throw new mr(void 0,e.error,e.message,void 0);yield{event:r.event,data:e}}n=!0}catch(e){if(e instanceof Error&&"AbortError"===e.name)return;throw e}finally{n||t.abort()}}),t)}static fromReadableStream(e,t){let r=!1;return new Cr((async function*(){if(r)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let n=!1;try{for await(const t of async function*(){const t=new Pr,r=Ir(e);for await(const e of r)for(const r of t.decode(e))yield r;for(const e of t.flush())yield e}())n||t&&(yield JSON.parse(t));n=!0}catch(e){if(e instanceof Error&&"AbortError"===e.name)return;throw e}finally{n||t.abort()}}),t)}[Symbol.asyncIterator](){return this.iterator()}tee(){const e=[],t=[],r=this.iterator(),n=n=>({next:()=>{if(0===n.length){const n=r.next();e.push(n),t.push(n)}return n.shift()}});return[new Cr((()=>n(e)),this.controller),new Cr((()=>n(t)),this.controller)]}toReadableStream(){const e=this;let t;const r=new TextEncoder;return new ir({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{const{value:n,done:s}=await t.next();if(s)return e.close();const a=r.encode(JSON.stringify(n)+"\n");e.enqueue(a)}catch(t){e.error(t)}},async cancel(){await(t.return?.())}})}}function Or(e){for(let t=0;t<e.length-2;t++){if(10===e[t]&&10===e[t+1])return t+2;if(13===e[t]&&13===e[t+1])return t+2;if(13===e[t]&&10===e[t+1]&&t+3<e.length&&13===e[t+2]&&10===e[t+3])return t+4}return-1}class jr{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const e={event:this.event,data:this.data.join("\n"),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,n]=function(e,t){const r=e.indexOf(t);if(-1!==r)return[e.substring(0,r),t,e.substring(r+t.length)];return[e,"",""]}(e,":");return n.startsWith(" ")&&(n=n.substring(1)),"event"===t?this.event=n:"data"===t&&this.data.push(n),null}}function Ir(e){if(e[Symbol.asyncIterator])return e;const t=e.getReader();return{async next(){try{const e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){const e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}const $r=e=>null!=e&&"object"==typeof e&&"string"==typeof e.url&&"function"==typeof e.blob,qr=e=>null!=e&&"object"==typeof e&&"string"==typeof e.name&&"number"==typeof e.lastModified&&Nr(e),Nr=e=>null!=e&&"object"==typeof e&&"number"==typeof e.size&&"string"==typeof e.type&&"function"==typeof e.text&&"function"==typeof e.slice&&"function"==typeof e.arrayBuffer;async function Lr(e,t,r){if(e=await e,qr(e))return e;if($r(e)){const n=await e.blob();t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()??"unknown_file");const s=Nr(n)?[await n.arrayBuffer()]:[n];return new or(s,t,r)}const n=await async function(e){let t=[];if("string"==typeof e||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(Nr(e))t.push(await e.arrayBuffer());else{if(!Mr(e))throw new Error(`Unexpected data type: ${typeof e}; constructor: ${e?.constructor?.name}; props: ${function(e){const t=Object.getOwnPropertyNames(e);return`[${t.map((e=>`"${e}"`)).join(", ")}]`}(e)}`);for await(const r of e)t.push(r)}return t}(e);if(t||(t=function(e){return Br(e.name)||Br(e.filename)||Br(e.path)?.split(/[\\/]/).pop()}(e)??"unknown_file"),!r?.type){const e=n[0]?.type;"string"==typeof e&&(r={...r,type:e})}return new or(n,t,r)}const Br=e=>"string"==typeof e?e:"undefined"!=typeof Buffer&&e instanceof Buffer?String(e):void 0,Mr=e=>null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator],Dr=e=>e&&"object"==typeof e&&e.body&&"MultipartBody"===e[Symbol.toStringTag],Fr=async e=>{const t=await Wr(e.body);return lr(t,e)},Wr=async e=>{const t=new ar;return await Promise.all(Object.entries(e||{}).map((([e,r])=>Zr(t,e,r)))),t},Zr=async(e,t,r)=>{if(void 0!==r){if(null==r)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if("string"==typeof r||"number"==typeof r||"boolean"==typeof r)e.append(t,String(r));else if((e=>qr(e)||$r(e)||dr(e))(r)){const n=await Lr(r);e.append(t,n)}else if(Array.isArray(r))await Promise.all(r.map((r=>Zr(e,t+"[]",r))));else{if("object"!=typeof r)throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`);await Promise.all(Object.entries(r).map((([r,n])=>Zr(e,`${t}[${r}]`,n))))}}};var zr,Ur=function(e,t,r,n,s){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?s.call(e,r):s?s.value=r:t.set(e,r),r},Hr=function(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)};async function Vr(e){const{response:t}=e;if(e.options.stream)return _n("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller):Cr.fromSSEResponse(t,e.controller);if(204===t.status)return null;if(e.options.__binaryResponse)return t;const r=t.headers.get("content-type");if(r?.includes("application/json")||r?.includes("application/vnd.api+json")){const e=await t.json();return _n("response",t.status,t.url,t.headers,e),Kr(e,t)}const n=await t.text();return _n("response",t.status,t.url,t.headers,n),n}function Kr(e,t){return!e||"object"!=typeof e||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get("x-request-id"),enumerable:!1})}class Jr extends Promise{constructor(e,t=Vr){super((e=>{e(null)})),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new Jr(this.responsePromise,(async t=>Kr(e(await this.parseResponse(t),t),t.response)))}asResponse(){return this.responsePromise.then((e=>e.response))}async withResponse(){const[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(this.parseResponse)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}class Xr{constructor({baseURL:e,maxRetries:t=2,timeout:r=6e5,httpAgent:n,fetch:s}){this.baseURL=e,this.maxRetries=hn("maxRetries",t),this.timeout=hn("timeout",r),this.httpAgent=n,this.fetch=s??sr}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...on(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${bn()}`}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then((async r=>{const n=r&&Nr(r?.body)?new DataView(await r.body.arrayBuffer()):r?.body instanceof DataView?r.body:r?.body instanceof ArrayBuffer?new DataView(r.body):r&&ArrayBuffer.isView(r?.body)?new DataView(r.body.buffer):r?.body;return{method:e,path:t,...r,body:n}})))}getAPIList(e,t,r){return this.requestAPIList(t,{method:"get",path:e,...r})}calculateContentLength(e){if("string"==typeof e){if("undefined"!=typeof Buffer)return Buffer.byteLength(e,"utf8").toString();if("undefined"!=typeof TextEncoder){return(new TextEncoder).encode(e).length.toString()}}else if(ArrayBuffer.isView(e))return e.byteLength.toString();return null}buildRequest(e,{retryCount:t=0}={}){const{method:r,path:n,query:s,headers:a={}}=e,o=ArrayBuffer.isView(e.body)||e.__binaryRequest&&"string"==typeof e.body?e.body:Dr(e.body)?e.body.body:e.body?JSON.stringify(e.body,null,2):null,i=this.calculateContentLength(o),l=this.buildURL(n,s);"timeout"in e&&hn("timeout",e.timeout);const c=e.timeout??this.timeout,u=e.httpAgent??this.httpAgent??cr(l),d=c+1e3;"number"==typeof u?.options?.timeout&&d>(u.options.timeout??0)&&(u.options.timeout=d),this.idempotencyHeader&&"get"!==r&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),a[this.idempotencyHeader]=e.idempotencyKey);return{req:{method:r,...o&&{body:o},headers:this.buildHeaders({options:e,headers:a,contentLength:i,retryCount:t}),...u&&{agent:u},signal:e.signal??null},url:l,timeout:c}}buildHeaders({options:e,headers:t,contentLength:r,retryCount:n}){const s={};r&&(s["content-length"]=r);const a=this.defaultHeaders(e);return gn(s,a),gn(s,t),Dr(e.body)&&"node"!==nr&&delete s["content-type"],void 0===wn(a,"x-stainless-retry-count")&&void 0===wn(t,"x-stainless-retry-count")&&(s["x-stainless-retry-count"]=String(n)),this.validateHeaders(s,t),s}async prepareOptions(e){}async prepareRequest(e,{url:t,options:r}){}parseHeaders(e){return e?Symbol.iterator in e?Object.fromEntries(Array.from(e).map((e=>[...e]))):{...e}:{}}makeStatusError(e,t,r,n){return mr.generate(e,t,r,n)}request(e,t=null){return new Jr(this.makeRequest(e,t))}async makeRequest(e,t){const r=await e,n=r.maxRetries??this.maxRetries;null==t&&(t=n),await this.prepareOptions(r);const{req:s,url:a,timeout:o}=this.buildRequest(r,{retryCount:n-t});if(await this.prepareRequest(s,{url:a,options:r}),_n("request",a,r,s.headers),r.signal?.aborted)throw new yr;const i=new AbortController,l=await this.fetchWithTimeout(a,s,o,i).catch(fn);if(l instanceof Error){if(r.signal?.aborted)throw new yr;if(t)return this.retryRequest(r,t);if("AbortError"===l.name)throw new _r;throw new gr({cause:l})}const c=Gr(l.headers);if(!l.ok){if(t&&this.shouldRetry(l)){return _n(`response (error; ${`retrying, ${t} attempts remaining`})`,l.status,a,c),this.retryRequest(r,t,c)}const e=await l.text().catch((e=>fn(e).message)),n=ln(e),s=n?void 0:e;_n(`response (error; ${t?"(error; no more retries left)":"(error; not retryable)"})`,l.status,a,c,s);throw this.makeStatusError(l.status,n,s,c)}return{response:l,options:r,controller:i}}requestAPIList(e,t){const r=this.makeRequest(t,null);return new Yr(this,r,e)}buildURL(e,t){const r=un(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),n=this.defaultQuery();return mn(n)||(t={...n,...t}),"object"==typeof t&&t&&!Array.isArray(t)&&(r.search=this.stringifyQuery(t)),r.toString()}stringifyQuery(e){return Object.entries(e).filter((([e,t])=>void 0!==t)).map((([e,t])=>{if("string"==typeof t||"number"==typeof t||"boolean"==typeof t)return`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(null===t)return`${encodeURIComponent(e)}=`;throw new pr(`Cannot stringify type ${typeof t}; 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("&")}async fetchWithTimeout(e,t,r,n){const{signal:s,...a}=t||{};s&&s.addEventListener("abort",(()=>n.abort()));const o=setTimeout((()=>n.abort()),r);return this.getRequestClient().fetch.call(void 0,e,{signal:n.signal,...a}).finally((()=>{clearTimeout(o)}))}getRequestClient(){return{fetch:this.fetch}}shouldRetry(e){const t=e.headers.get("x-should-retry");return"true"===t||"false"!==t&&(408===e.status||(409===e.status||(429===e.status||e.status>=500)))}async retryRequest(e,t,r){let n;const s=r?.["retry-after-ms"];if(s){const e=parseFloat(s);Number.isNaN(e)||(n=e)}const a=r?.["retry-after"];if(a&&!n){const e=parseFloat(a);n=Number.isNaN(e)?Date.parse(a)-Date.now():1e3*e}if(!(n&&0<=n&&n<6e4)){const r=e.maxRetries??this.maxRetries;n=this.calculateDefaultRetryTimeoutMillis(t,r)}return await dn(n),this.makeRequest(e,t-1)}calculateDefaultRetryTimeoutMillis(e,t){const r=t-e;return Math.min(.5*Math.pow(2,r),8)*(1-.25*Math.random())*1e3}getUserAgent(){return`${this.constructor.name}/JS ${rr}`}}class Qr{constructor(e,t,r,n){zr.set(this,void 0),Ur(this,zr,e,"f"),this.options=n,this.response=t,this.body=r}hasNextPage(){return!!this.getPaginatedItems().length&&null!=this.nextPageInfo()}async getNextPage(){const e=this.nextPageInfo();if(!e)throw new pr("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");const t={...this.options};if("params"in e&&"object"==typeof t.query)t.query={...t.query,...e.params};else if("url"in e){const r=[...Object.entries(t.query||{}),...e.url.searchParams.entries()];for(const[t,n]of r)e.url.searchParams.set(t,n);t.query=void 0,t.path=e.url.toString()}return await Hr(this,zr,"f").requestAPIList(this.constructor,t)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(zr=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class Yr extends Jr{constructor(e,t,r){super(t,(async t=>new r(e,t.response,await Vr(t),t.options)))}async*[Symbol.asyncIterator](){const e=await(this);for await(const t of e)yield t}}const Gr=e=>new Proxy(Object.fromEntries(e.entries()),{get(e,t){const r=t.toString();return e[r.toLowerCase()]||e[r]}}),en={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0},tn=e=>"object"==typeof e&&null!==e&&!mn(e)&&Object.keys(e).every((e=>yn(en,e))),rn=()=>{if("undefined"!=typeof Deno&&null!=Deno.build)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":rr,"X-Stainless-OS":sn(Deno.build.os),"X-Stainless-Arch":nn(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":"string"==typeof Deno.version?Deno.version:Deno.version?.deno??"unknown"};if("undefined"!=typeof EdgeRuntime)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":rr,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":process.version};if("[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0))return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":rr,"X-Stainless-OS":sn(process.platform),"X-Stainless-Arch":nn(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};const e=function(){if("undefined"==typeof navigator||!navigator)return null;const e=[{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(const{key:t,pattern:r}of e){const e=r.exec(navigator.userAgent);if(e){return{browser:t,version:`${e[1]||0}.${e[2]||0}.${e[3]||0}`}}}return null}();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":rr,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":rr,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};const nn=e=>"x32"===e?"x32":"x86_64"===e||"x64"===e?"x64":"arm"===e?"arm":"aarch64"===e||"arm64"===e?"arm64":e?`other:${e}`:"unknown",sn=e=>(e=e.toLowerCase()).includes("ios")?"iOS":"android"===e?"Android":"darwin"===e?"MacOS":"win32"===e?"Windows":"freebsd"===e?"FreeBSD":"openbsd"===e?"OpenBSD":"linux"===e?"Linux":e?`Other:${e}`:"Unknown";let an;const on=()=>an??(an=rn()),ln=e=>{try{return JSON.parse(e)}catch(e){return}},cn=new RegExp("^(?:[a-z]+:)?//","i"),un=e=>cn.test(e),dn=e=>new Promise((t=>setTimeout(t,e))),hn=(e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new pr(`${e} must be an integer`);if(t<0)throw new pr(`${e} must be a positive integer`);return t},fn=e=>{if(e instanceof Error)return e;if("object"==typeof e&&null!==e)try{return new Error(JSON.stringify(e))}catch{}return new Error(e)},pn=e=>"undefined"!=typeof process?process.env?.[e]?.trim()??void 0:"undefined"!=typeof Deno?Deno.env?.get?.(e)?.trim():void 0;function mn(e){if(!e)return!0;for(const t in e)return!1;return!0}function yn(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function gn(e,t){for(const r in t){if(!yn(t,r))continue;const n=r.toLowerCase();if(!n)continue;const s=t[r];null===s?delete e[n]:void 0!==s&&(e[n]=s)}}function _n(e,...t){"undefined"!=typeof process&&"true"===process?.env?.DEBUG&&console.log(`OpenAI:DEBUG:${e}`,...t)}const bn=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})),wn=(e,t)=>{const r=t.toLowerCase();if((e=>"function"==typeof e?.get)(e)){const n=t[0]?.toUpperCase()+t.substring(1).replace(/([^\w])(\w)/g,((e,t,r)=>t+r.toUpperCase()));for(const s of[t,r,t.toUpperCase(),n]){const t=e.get(s);if(t)return t}}for(const[n,s]of Object.entries(e))if(n.toLowerCase()===r)return Array.isArray(s)?(s.length<=1||console.warn(`Received ${s.length} entries for the ${t} header, using the first entry.`),s[0]):s};function vn(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)}class Sn extends Qr{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageParams(){return null}nextPageInfo(){return null}}class xn extends Qr{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[]}getPaginatedItems(){return this.data??[]}nextPageParams(){const e=this.nextPageInfo();if(!e)return null;if("params"in e)return e.params;const t=Object.fromEntries(e.url.searchParams);return Object.keys(t).length?t:null}nextPageInfo(){const e=this.getPaginatedItems();if(!e.length)return null;const t=e[e.length-1]?.id;return t?{params:{after:t}}:null}}class kn{constructor(e){this._client=e}}let Tn=class extends kn{create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}},En=class extends kn{constructor(){super(...arguments),this.completions=new Tn(this._client)}};En.Completions=Tn;class Rn extends kn{create(e,t){return this._client.post("/audio/speech",{body:e,...t,__binaryResponse:!0})}}class An extends kn{create(e,t){return this._client.post("/audio/transcriptions",Fr({body:e,...t}))}}class Pn extends kn{create(e,t){return this._client.post("/audio/translations",Fr({body:e,...t}))}}class Cn extends kn{constructor(){super(...arguments),this.transcriptions=new An(this._client),this.translations=new Pn(this._client),this.speech=new Rn(this._client)}}Cn.Transcriptions=An,Cn.Translations=Pn,Cn.Speech=Rn;class On extends kn{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(`/batches/${e}`,t)}list(e={},t){return tn(e)?this.list({},e):this._client.getAPIList("/batches",jn,{query:e,...t})}cancel(e,t){return this._client.post(`/batches/${e}/cancel`,t)}}class jn extends xn{}On.BatchesPage=jn;class In extends kn{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}retrieve(e,t){return this._client.get(`/assistants/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}update(e,t,r){return this._client.post(`/assistants/${e}`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}list(e={},t){return tn(e)?this.list({},e):this._client.getAPIList("/assistants",$n,{query:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}del(e,t){return this._client.delete(`/assistants/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}}class $n extends xn{}function qn(e){return"function"==typeof e.parse}In.AssistantsPage=$n;const Nn=e=>"assistant"===e?.role,Ln=e=>"function"===e?.role,Bn=e=>"tool"===e?.role;var Mn,Dn,Fn,Wn,Zn,zn,Un,Hn,Vn,Kn,Jn,Xn,Qn,Yn=function(e,t,r,n,s){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?s.call(e,r):s?s.value=r:t.set(e,r),r},Gn=function(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)};class es{constructor(){Mn.add(this),this.controller=new AbortController,Dn.set(this,void 0),Fn.set(this,(()=>{})),Wn.set(this,(()=>{})),Zn.set(this,void 0),zn.set(this,(()=>{})),Un.set(this,(()=>{})),Hn.set(this,{}),Vn.set(this,!1),Kn.set(this,!1),Jn.set(this,!1),Xn.set(this,!1),Yn(this,Dn,new Promise(((e,t)=>{Yn(this,Fn,e,"f"),Yn(this,Wn,t,"f")})),"f"),Yn(this,Zn,new Promise(((e,t)=>{Yn(this,zn,e,"f"),Yn(this,Un,t,"f")})),"f"),Gn(this,Dn,"f").catch((()=>{})),Gn(this,Zn,"f").catch((()=>{}))}_run(e){setTimeout((()=>{e().then((()=>{this._emitFinal(),this._emit("end")}),Gn(this,Mn,"m",Qn).bind(this))}),0)}_connected(){this.ended||(Gn(this,Fn,"f").call(this),this._emit("connect"))}get ended(){return Gn(this,Vn,"f")}get errored(){return Gn(this,Kn,"f")}get aborted(){return Gn(this,Jn,"f")}abort(){this.controller.abort()}on(e,t){return(Gn(this,Hn,"f")[e]||(Gn(this,Hn,"f")[e]=[])).push({listener:t}),this}off(e,t){const r=Gn(this,Hn,"f")[e];if(!r)return this;const n=r.findIndex((e=>e.listener===t));return n>=0&&r.splice(n,1),this}once(e,t){return(Gn(this,Hn,"f")[e]||(Gn(this,Hn,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise(((t,r)=>{Yn(this,Xn,!0,"f"),"error"!==e&&this.once("error",r),this.once(e,t)}))}async done(){Yn(this,Xn,!0,"f"),await Gn(this,Zn,"f")}_emit(e,...t){if(Gn(this,Vn,"f"))return;"end"===e&&(Yn(this,Vn,!0,"f"),Gn(this,zn,"f").call(this));const r=Gn(this,Hn,"f")[e];if(r&&(Gn(this,Hn,"f")[e]=r.filter((e=>!e.once)),r.forEach((({listener:e})=>e(...t)))),"abort"===e){const e=t[0];return Gn(this,Xn,"f")||r?.length||Promise.reject(e),Gn(this,Wn,"f").call(this,e),Gn(this,Un,"f").call(this,e),void this._emit("end")}if("error"===e){const e=t[0];Gn(this,Xn,"f")||r?.length||Promise.reject(e),Gn(this,Wn,"f").call(this,e),Gn(this,Un,"f").call(this,e),this._emit("end")}}_emitFinal(){}}function ts(e){return"auto-parseable-response-format"===e?.$brand}function rs(e){return"auto-parseable-tool"===e?.$brand}function ns(e,t){const r=e.choices.map((e=>{if("length"===e.finish_reason)throw new Rr;if("content_filter"===e.finish_reason)throw new Ar;return{...e,message:{...e.message,tool_calls:e.message.tool_calls?.map((e=>function(e,t){const r=e.tools?.find((e=>e.function?.name===t.function.name));return{...t,function:{...t.function,parsed_arguments:rs(r)?r.$parseRaw(t.function.arguments):r?.function.strict?JSON.parse(t.function.arguments):null}}}(t,e)))??[],parsed:e.message.content&&!e.message.refusal?ss(t,e.message.content):null}}}));return{...e,choices:r}}function ss(e,t){if("json_schema"!==e.response_format?.type)return null;if("json_schema"===e.response_format?.type){if("$parseRaw"in e.response_format){return e.response_format.$parseRaw(t)}return JSON.parse(t)}return null}function as(e,t){if(!e)return!1;const r=e.tools?.find((e=>e.function?.name===t.function.name));return rs(r)||r?.function.strict||!1}function os(e){return!!ts(e.response_format)||(e.tools?.some((e=>rs(e)||"function"===e.type&&!0===e.function.strict))??!1)}Dn=new WeakMap,Fn=new WeakMap,Wn=new WeakMap,Zn=new WeakMap,zn=new WeakMap,Un=new WeakMap,Hn=new WeakMap,Vn=new WeakMap,Kn=new WeakMap,Jn=new WeakMap,Xn=new WeakMap,Mn=new WeakSet,Qn=function(e){if(Yn(this,Kn,!0,"f"),e instanceof Error&&"AbortError"===e.name&&(e=new yr),e instanceof yr)return Yn(this,Jn,!0,"f"),this._emit("abort",e);if(e instanceof pr)return this._emit("error",e);if(e instanceof Error){const t=new pr(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new pr(String(e)))};var is,ls,cs,us,ds,hs,fs,ps,ms=function(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)};const ys=10;class gs extends es{constructor(){super(...arguments),is.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);const t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if("content"in e||(e.content=null),this.messages.push(e),t)if(this._emit("message",e),(Ln(e)||Bn(e))&&e.content)this._emit("functionCallResult",e.content);else if(Nn(e)&&e.function_call)this._emit("functionCall",e.function_call);else if(Nn(e)&&e.tool_calls)for(const t of e.tool_calls)"function"===t.type&&this._emit("functionCall",t.function)}async finalChatCompletion(){await this.done();const e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new pr("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),ms(this,is,"m",ls).call(this)}async finalMessage(){return await this.done(),ms(this,is,"m",cs).call(this)}async finalFunctionCall(){return await this.done(),ms(this,is,"m",us).call(this)}async finalFunctionCallResult(){return await this.done(),ms(this,is,"m",ds).call(this)}async totalUsage(){return await this.done(),ms(this,is,"m",hs).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=ms(this,is,"m",cs).call(this);t&&this._emit("finalMessage",t);const r=ms(this,is,"m",ls).call(this);r&&this._emit("finalContent",r);const n=ms(this,is,"m",us).call(this);n&&this._emit("finalFunctionCall",n);const s=ms(this,is,"m",ds).call(this);null!=s&&this._emit("finalFunctionCallResult",s),this._chatCompletions.some((e=>e.usage))&&this._emit("totalUsage",ms(this,is,"m",hs).call(this))}async _createChatCompletion(e,t,r){const n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",(()=>this.controller.abort()))),ms(this,is,"m",fs).call(this,t);const s=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(ns(s,t))}async _runChatCompletion(e,t,r){for(const e of t.messages)this._addMessage(e,!1);return await this._createChatCompletion(e,t,r)}async _runFunctions(e,t,r){const n="function",{function_call:s="auto",stream:a,...o}=t,i="string"!=typeof s&&s?.name,{maxChatCompletions:l=ys}=r||{},c={};for(const e of t.functions)c[e.name||e.function.name]=e;const u=t.functions.map((e=>({name:e.name||e.function.name,parameters:e.parameters,description:e.description})));for(const e of t.messages)this._addMessage(e,!1);for(let t=0;t<l;++t){const t=await this._createChatCompletion(e,{...o,function_call:s,functions:u,messages:[...this.messages]},r),a=t.choices[0]?.message;if(!a)throw new pr("missing message in ChatCompletion response");if(!a.function_call)return;const{name:l,arguments:d}=a.function_call,h=c[l];if(!h){const e=`Invalid function_call: ${JSON.stringify(l)}. Available options are: ${u.map((e=>JSON.stringify(e.name))).join(", ")}. Please try again`;this._addMessage({role:n,name:l,content:e});continue}if(i&&i!==l){const e=`Invalid function_call: ${JSON.stringify(l)}. ${JSON.stringify(i)} requested. Please try again`;this._addMessage({role:n,name:l,content:e});continue}let f;try{f=qn(h)?await h.parse(d):d}catch(e){this._addMessage({role:n,name:l,content:e instanceof Error?e.message:String(e)});continue}const p=await h.function(f,this),m=ms(this,is,"m",ps).call(this,p);if(this._addMessage({role:n,name:l,content:m}),i)return}}async _runTools(e,t,r){const n="tool",{tool_choice:s="auto",stream:a,...o}=t,i="string"!=typeof s&&s?.function?.name,{maxChatCompletions:l=ys}=r||{},c=t.tools.map((e=>{if(rs(e)){if(!e.$callback)throw new pr("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:e.$callback,name:e.function.name,description:e.function.description||"",parameters:e.function.parameters,parse:e.$parseRaw,strict:!0}}}return e})),u={};for(const e of c)"function"===e.type&&(u[e.function.name||e.function.function.name]=e.function);const d="tools"in t?c.map((e=>"function"===e.type?{type:"function",function:{name:e.function.name||e.function.function.name,parameters:e.function.parameters,description:e.function.description,strict:e.function.strict}}:e)):void 0;for(const e of t.messages)this._addMessage(e,!1);for(let t=0;t<l;++t){const t=await this._createChatCompletion(e,{...o,tool_choice:s,tools:d,messages:[...this.messages]},r),a=t.choices[0]?.message;if(!a)throw new pr("missing message in ChatCompletion response");if(!a.tool_calls?.length)return;for(const e of a.tool_calls){if("function"!==e.type)continue;const t=e.id,{name:r,arguments:s}=e.function,a=u[r];if(!a){const e=`Invalid tool_call: ${JSON.stringify(r)}. Available options are: ${Object.keys(u).map((e=>JSON.stringify(e))).join(", ")}. Please try again`;this._addMessage({role:n,tool_call_id:t,content:e});continue}if(i&&i!==r){const e=`Invalid tool_call: ${JSON.stringify(r)}. ${JSON.stringify(i)} requested. Please try again`;this._addMessage({role:n,tool_call_id:t,content:e});continue}let o;try{o=qn(a)?await a.parse(s):s}catch(e){const r=e instanceof Error?e.message:String(e);this._addMessage({role:n,tool_call_id:t,content:r});continue}const l=await a.function(o,this),c=ms(this,is,"m",ps).call(this,l);if(this._addMessage({role:n,tool_call_id:t,content:c}),i)return}}}}is=new WeakSet,ls=function(){return ms(this,is,"m",cs).call(this).content??null},cs=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(Nn(t)){const{function_call:e,...r}=t,n={...r,content:t.content??null,refusal:t.refusal??null};return e&&(n.function_call=e),n}}throw new pr("stream ended without producing a ChatCompletionMessage with role=assistant")},us=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(Nn(t)&&t?.function_call)return t.function_call;if(Nn(t)&&t?.tool_calls?.length)return t.tool_calls.at(-1)?.function}},ds=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(Ln(t)&&null!=t.content)return t.content;if(Bn(t)&&null!=t.content&&"string"==typeof t.content&&this.messages.some((e=>"assistant"===e.role&&e.tool_calls?.some((e=>"function"===e.type&&e.id===t.tool_call_id)))))return t.content}},hs=function(){const e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},fs=function(e){if(null!=e.n&&e.n>1)throw new pr("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},ps=function(e){return"string"==typeof e?e:void 0===e?"undefined":JSON.stringify(e)};class _s extends gs{static runFunctions(e,t,r){const n=new _s,s={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return n._run((()=>n._runFunctions(e,t,s))),n}static runTools(e,t,r){const n=new _s,s={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run((()=>n._runTools(e,t,s))),n}_addMessage(e,t=!0){super._addMessage(e,t),Nn(e)&&e.content&&this._emit("content",e.content)}}const bs=1,ws=2,vs=4,Ss=8,xs=16,ks=32,Ts=64,Es=128,Rs=256,As=511;class Ps extends Error{}class Cs extends Error{}const Os=(e,t)=>{const r=e.length;let n=0;const s=e=>{throw new Ps(`${e} at position ${n}`)},a=e=>{throw new Cs(`${e} at position ${n}`)},o=()=>(d(),n>=r&&s("Unexpected end of input"),'"'===e[n]?i():"{"===e[n]?l():"["===e[n]?c():"null"===e.substring(n,n+4)||xs&t&&r-n<4&&"null".startsWith(e.substring(n))?(n+=4,null):"true"===e.substring(n,n+4)||ks&t&&r-n<4&&"true".startsWith(e.substring(n))?(n+=4,!0):"false"===e.substring(n,n+5)||ks&t&&r-n<5&&"false".startsWith(e.substring(n))?(n+=5,!1):"Infinity"===e.substring(n,n+8)||Es&t&&r-n<8&&"Infinity".startsWith(e.substring(n))?(n+=8,1/0):"-Infinity"===e.substring(n,n+9)||Rs&t&&1<r-n&&r-n<9&&"-Infinity".startsWith(e.substring(n))?(n+=9,-1/0):"NaN"===e.substring(n,n+3)||Ts&t&&r-n<3&&"NaN".startsWith(e.substring(n))?(n+=3,NaN):u()),i=()=>{const o=n;let i=!1;for(n++;n<r&&('"'!==e[n]||i&&"\\"===e[n-1]);)i="\\"===e[n]&&!i,n++;if('"'==e.charAt(n))try{return JSON.parse(e.substring(o,++n-Number(i)))}catch(e){a(String(e))}else if(bs&t)try{return JSON.parse(e.substring(o,n-Number(i))+'"')}catch(t){return JSON.parse(e.substring(o,e.lastIndexOf("\\"))+'"')}s("Unterminated string literal")},l=()=>{n++,d();const a={};try{for(;"}"!==e[n];){if(d(),n>=r&&Ss&t)return a;const s=i();d(),n++;try{const e=o();Object.defineProperty(a,s,{value:e,writable:!0,enumerable:!0,configurable:!0})}catch(e){if(Ss&t)return a;throw e}d(),","===e[n]&&n++}}catch(e){if(Ss&t)return a;s("Expected '}' at end of object")}return n++,a},c=()=>{n++;const r=[];try{for(;"]"!==e[n];)r.push(o()),d(),","===e[n]&&n++}catch(e){if(vs&t)return r;s("Expected ']' at end of array")}return n++,r},u=()=>{if(0===n){"-"===e&&ws&t&&s("Not sure what '-' is");try{return JSON.parse(e)}catch(r){if(ws&t)try{return"."===e[e.length-1]?JSON.parse(e.substring(0,e.lastIndexOf("."))):JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch(e){}a(String(r))}}const o=n;for("-"===e[n]&&n++;e[n]&&!",]}".includes(e[n]);)n++;n!=r||ws&t||s("Unterminated number literal");try{return JSON.parse(e.substring(o,n))}catch(r){"-"===e.substring(o,n)&&ws&t&&s("Not sure what '-' is");try{return JSON.parse(e.substring(o,e.lastIndexOf("e")))}catch(e){a(String(e))}}},d=()=>{for(;n<r&&" \n\r\t".includes(e[n]);)n++};return o()},js=e=>function(e,t=As){if("string"!=typeof e)throw new TypeError("expecting str, got "+typeof e);if(!e.trim())throw new Error(`${e} is empty`);return Os(e.trim(),t)}(e,As^ws);var Is,$s,qs,Ns,Ls,Bs,Ms,Ds,Fs,Ws,Zs,zs,Us=function(e,t,r,n,s){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?s.call(e,r):s?s.value=r:t.set(e,r),r},Hs=function(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)};class Vs extends gs{constructor(e){super(),Is.add(this),$s.set(this,void 0),qs.set(this,void 0),Ns.set(this,void 0),Us(this,$s,e,"f"),Us(this,qs,[],"f")}get currentChatCompletionSnapshot(){return Hs(this,Ns,"f")}static fromReadableStream(e){const t=new Vs(null);return t._run((()=>t._fromReadableStream(e))),t}static createChatCompletion(e,t,r){const n=new Vs(t);return n._run((()=>n._runChatCompletion(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}}))),n}async _createChatCompletion(e,t,r){super._createChatCompletion;const n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",(()=>this.controller.abort()))),Hs(this,Is,"m",Ls).call(this);const s=await e.chat.completions.create({...t,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(const e of s)Hs(this,Is,"m",Ms).call(this,e);if(s.controller.signal?.aborted)throw new yr;return this._addChatCompletion(Hs(this,Is,"m",Ws).call(this))}async _fromReadableStream(e,t){const r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",(()=>this.controller.abort()))),Hs(this,Is,"m",Ls).call(this),this._connected();const n=Cr.fromReadableStream(e,this.controller);let s;for await(const e of n)s&&s!==e.id&&this._addChatCompletion(Hs(this,Is,"m",Ws).call(this)),Hs(this,Is,"m",Ms).call(this,e),s=e.id;if(n.controller.signal?.aborted)throw new yr;return this._addChatCompletion(Hs(this,Is,"m",Ws).call(this))}[($s=new WeakMap,qs=new WeakMap,Ns=new WeakMap,Is=new WeakSet,Ls=function(){this.ended||Us(this,Ns,void 0,"f")},Bs=function(e){let t=Hs(this,qs,"f")[e.index];return t||(t={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},Hs(this,qs,"f")[e.index]=t,t)},Ms=function(e){if(this.ended)return;const t=Hs(this,Is,"m",zs).call(this,e);this._emit("chunk",e,t);for(const r of e.choices){const e=t.choices[r.index];null!=r.delta.content&&"assistant"===e.message?.role&&e.message?.content&&(this._emit("content",r.delta.content,e.message.content),this._emit("content.delta",{delta:r.delta.content,snapshot:e.message.content,parsed:e.message.parsed})),null!=r.delta.refusal&&"assistant"===e.message?.role&&e.message?.refusal&&this._emit("refusal.delta",{delta:r.delta.refusal,snapshot:e.message.refusal}),null!=r.logprobs?.content&&"assistant"===e.message?.role&&this._emit("logprobs.content.delta",{content:r.logprobs?.content,snapshot:e.logprobs?.content??[]}),null!=r.logprobs?.refusal&&"assistant"===e.message?.role&&this._emit("logprobs.refusal.delta",{refusal:r.logprobs?.refusal,snapshot:e.logprobs?.refusal??[]});const n=Hs(this,Is,"m",Bs).call(this,e);e.finish_reason&&(Hs(this,Is,"m",Fs).call(this,e),null!=n.current_tool_call_index&&Hs(this,Is,"m",Ds).call(this,e,n.current_tool_call_index));for(const t of r.delta.tool_calls??[])n.current_tool_call_index!==t.index&&(Hs(this,Is,"m",Fs).call(this,e),null!=n.current_tool_call_index&&Hs(this,Is,"m",Ds).call(this,e,n.current_tool_call_index)),n.current_tool_call_index=t.index;for(const t of r.delta.tool_calls??[]){const r=e.message.tool_calls?.[t.index];r?.type&&("function"===r?.type?this._emit("tool_calls.function.arguments.delta",{name:r.function?.name,index:t.index,arguments:r.function.arguments,parsed_arguments:r.function.parsed_arguments,arguments_delta:t.function?.arguments??""}):r?.type)}}},Ds=function(e,t){if(Hs(this,Is,"m",Bs).call(this,e).done_tool_calls.has(t))return;const r=e.message.tool_calls?.[t];if(!r)throw new Error("no tool call snapshot");if(!r.type)throw new Error("tool call snapshot missing `type`");if("function"===r.type){const e=Hs(this,$s,"f")?.tools?.find((e=>"function"===e.type&&e.function.name===r.function.name));this._emit("tool_calls.function.arguments.done",{name:r.function.name,index:t,arguments:r.function.arguments,parsed_arguments:rs(e)?e.$parseRaw(r.function.arguments):e?.function.strict?JSON.parse(r.function.arguments):null})}else r.type},Fs=function(e){const t=Hs(this,Is,"m",Bs).call(this,e);if(e.message.content&&!t.content_done){t.content_done=!0;const r=Hs(this,Is,"m",Zs).call(this);this._emit("content.done",{content:e.message.content,parsed:r?r.$parseRaw(e.message.content):null})}e.message.refusal&&!t.refusal_done&&(t.refusal_done=!0,this._emit("refusal.done",{refusal:e.message.refusal})),e.logprobs?.content&&!t.logprobs_content_done&&(t.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:e.logprobs.content})),e.logprobs?.refusal&&!t.logprobs_refusal_done&&(t.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:e.logprobs.refusal}))},Ws=function(){if(this.ended)throw new pr("stream has ended, this shouldn't happen");const e=Hs(this,Ns,"f");if(!e)throw new pr("request ended without sending any chunks");return Us(this,Ns,void 0,"f"),Us(this,qs,[],"f"),function(e,t){const{id:r,choices:n,created:s,model:a,system_fingerprint:o,...i}=e,l={...i,id:r,choices:n.map((({message:t,finish_reason:r,index:n,logprobs:s,...a})=>{if(!r)throw new pr(`missing finish_reason for choice ${n}`);const{content:o=null,function_call:i,tool_calls:l,...c}=t,u=t.role;if(!u)throw new pr(`missing role for choice ${n}`);if(i){const{arguments:e,name:l}=i;if(null==e)throw new pr(`missing function_call.arguments for choice ${n}`);if(!l)throw new pr(`missing function_call.name for choice ${n}`);return{...a,message:{content:o,function_call:{arguments:e,name:l},role:u,refusal:t.refusal??null},finish_reason:r,index:n,logprobs:s}}return l?{...a,index:n,finish_reason:r,logprobs:s,message:{...c,role:u,content:o,refusal:t.refusal??null,tool_calls:l.map(((t,r)=>{const{function:s,type:a,id:o,...i}=t,{arguments:l,name:c,...u}=s||{};if(null==o)throw new pr(`missing choices[${n}].tool_calls[${r}].id\n${Ks(e)}`);if(null==a)throw new pr(`missing choices[${n}].tool_calls[${r}].type\n${Ks(e)}`);if(null==c)throw new pr(`missing choices[${n}].tool_calls[${r}].function.name\n${Ks(e)}`);if(null==l)throw new pr(`missing choices[${n}].tool_calls[${r}].function.arguments\n${Ks(e)}`);return{...i,id:o,type:a,function:{...u,name:c,arguments:l}}}))}}:{...a,message:{...c,content:o,role:u,refusal:t.refusal??null},finish_reason:r,index:n,logprobs:s}})),created:s,model:a,object:"chat.completion",...o?{system_fingerprint:o}:{}};return function(e,t){return t&&os(t)?ns(e,t):{...e,choices:e.choices.map((e=>({...e,message:{...e.message,parsed:null,tool_calls:e.message.tool_calls??[]}})))}}(l,t)}(e,Hs(this,$s,"f"))},Zs=function(){const e=Hs(this,$s,"f")?.response_format;return ts(e)?e:null},zs=function(e){var t,r,n,s;let a=Hs(this,Ns,"f");const{choices:o,...i}=e;a?Object.assign(a,i):a=Us(this,Ns,{...i,choices:[]},"f");for(const{delta:o,finish_reason:i,index:l,logprobs:c=null,...u}of e.choices){let e=a.choices[l];if(e||(e=a.choices[l]={finish_reason:i,index:l,message:{},logprobs:c,...u}),c)if(e.logprobs){const{content:n,refusal:s,...a}=c;Object.assign(e.logprobs,a),n&&((t=e.logprobs).content??(t.content=[]),e.logprobs.content.push(...n)),s&&((r=e.logprobs).refusal??(r.refusal=[]),e.logprobs.refusal.push(...s))}else e.logprobs=Object.assign({},c);if(i&&(e.finish_reason=i,Hs(this,$s,"f")&&os(Hs(this,$s,"f")))){if("length"===i)throw new Rr;if("content_filter"===i)throw new Ar}if(Object.assign(e,u),!o)continue;const{content:d,refusal:h,function_call:f,role:p,tool_calls:m,...y}=o;if(Object.assign(e.message,y),h&&(e.message.refusal=(e.message.refusal||"")+h),p&&(e.message.role=p),f&&(e.message.function_call?(f.name&&(e.message.function_call.name=f.name),f.arguments&&((n=e.message.function_call).arguments??(n.arguments=""),e.message.function_call.arguments+=f.arguments)):e.message.function_call=f),d&&(e.message.content=(e.message.content||"")+d,!e.message.refusal&&Hs(this,Is,"m",Zs).call(this)&&(e.message.parsed=js(e.message.content))),m){e.message.tool_calls||(e.message.tool_calls=[]);for(const{index:t,id:r,type:n,function:a,...o}of m){const i=(s=e.message.tool_calls)[t]??(s[t]={});Object.assign(i,o),r&&(i.id=r),n&&(i.type=n),a&&(i.function??(i.function={name:a.name??"",arguments:""})),a?.name&&(i.function.name=a.name),a?.arguments&&(i.function.arguments+=a.arguments,as(Hs(this,$s,"f"),i)&&(i.function.parsed_arguments=js(i.function.arguments)))}}}return a},Symbol.asyncIterator)](){const e=[],t=[];let r=!1;return this.on("chunk",(r=>{const n=t.shift();n?n.resolve(r):e.push(r)})),this.on("end",(()=>{r=!0;for(const e of t)e.resolve(void 0);t.length=0})),this.on("abort",(e=>{r=!0;for(const r of t)r.reject(e);t.length=0})),this.on("error",(e=>{r=!0;for(const r of t)r.reject(e);t.length=0})),{next:async()=>{if(!e.length)return r?{value:void 0,done:!0}:new Promise(((e,r)=>t.push({resolve:e,reject:r}))).then((e=>e?{value:e,done:!1}:{value:void 0,done:!0}));return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Cr(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function Ks(e){return JSON.stringify(e)}class Js extends Vs{static fromReadableStream(e){const t=new Js(null);return t._run((()=>t._fromReadableStream(e))),t}static runFunctions(e,t,r){const n=new Js(null),s={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return n._run((()=>n._runFunctions(e,t,s))),n}static runTools(e,t,r){const n=new Js(t),s={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run((()=>n._runTools(e,t,s))),n}}let Xs=class extends kn{parse(e,t){return function(e){for(const t of e??[]){if("function"!==t.type)throw new pr(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(!0!==t.function.strict)throw new pr(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"beta.chat.completions.parse"}})._thenUnwrap((t=>ns(t,e)))}runFunctions(e,t){return e.stream?Js.runFunctions(this._client,e,t):_s.runFunctions(this._client,e,t)}runTools(e,t){return e.stream?Js.runTools(this._client,e,t):_s.runTools(this._client,e,t)}stream(e,t){return Vs.createChatCompletion(this._client,e,t)}};class Qs extends kn{constructor(){super(...arguments),this.completions=new Xs(this._client)}}!function(e){e.Completions=Xs}(Qs||(Qs={}));var Ys,Gs,ea,ta,ra,na,sa,aa,oa,ia,la,ca,ua,da,ha,fa,pa,ma,ya,ga,_a,ba,wa=function(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)},va=function(e,t,r,n,s){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?s.call(e,r):s?s.value=r:t.set(e,r),r};class Sa extends es{constructor(){super(...arguments),Ys.add(this),Gs.set(this,[]),ea.set(this,{}),ta.set(this,{}),ra.set(this,void 0),na.set(this,void 0),sa.set(this,void 0),aa.set(this,void 0),oa.set(this,void 0),ia.set(this,void 0),la.set(this,void 0),ca.set(this,void 0),ua.set(this,void 0)}[(Gs=new WeakMap,ea=new WeakMap,ta=new WeakMap,ra=new WeakMap,na=new WeakMap,sa=new WeakMap,aa=new WeakMap,oa=new WeakMap,ia=new WeakMap,la=new WeakMap,ca=new WeakMap,ua=new WeakMap,Ys=new WeakSet,Symbol.asyncIterator)](){const e=[],t=[];let r=!1;return this.on("event",(r=>{const n=t.shift();n?n.resolve(r):e.push(r)})),this.on("end",(()=>{r=!0;for(const e of t)e.resolve(void 0);t.length=0})),this.on("abort",(e=>{r=!0;for(const r of t)r.reject(e);t.length=0})),this.on("error",(e=>{r=!0;for(const r of t)r.reject(e);t.length=0})),{next:async()=>{if(!e.length)return r?{value:void 0,done:!0}:new Promise(((e,r)=>t.push({resolve:e,reject:r}))).then((e=>e?{value:e,done:!1}:{value:void 0,done:!0}));return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){const t=new Sa;return t._run((()=>t._fromReadableStream(e))),t}async _fromReadableStream(e,t){const r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",(()=>this.controller.abort()))),this._connected();const n=Cr.fromReadableStream(e,this.controller);for await(const e of n)wa(this,Ys,"m",da).call(this,e);if(n.controller.signal?.aborted)throw new yr;return this._addRun(wa(this,Ys,"m",ha).call(this))}toReadableStream(){return new Cr(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,n,s){const a=new Sa;return a._run((()=>a._runToolAssistantStream(e,t,r,n,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}}))),a}async _createToolAssistantStream(e,t,r,n,s){const a=s?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",(()=>this.controller.abort())));const o={...n,stream:!0},i=await e.submitToolOutputs(t,r,o,{...s,signal:this.controller.signal});this._connected();for await(const e of i)wa(this,Ys,"m",da).call(this,e);if(i.controller.signal?.aborted)throw new yr;return this._addRun(wa(this,Ys,"m",ha).call(this))}static createThreadAssistantStream(e,t,r){const n=new Sa;return n._run((()=>n._threadAssistantStream(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}}))),n}static createAssistantStream(e,t,r,n){const s=new Sa;return s._run((()=>s._runAssistantStream(e,t,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}}))),s}currentEvent(){return wa(this,la,"f")}currentRun(){return wa(this,ca,"f")}currentMessageSnapshot(){return wa(this,ra,"f")}currentRunStepSnapshot(){return wa(this,ua,"f")}async finalRunSteps(){return await this.done(),Object.values(wa(this,ea,"f"))}async finalMessages(){return await this.done(),Object.values(wa(this,ta,"f"))}async finalRun(){if(await this.done(),!wa(this,na,"f"))throw Error("Final run was not received.");return wa(this,na,"f")}async _createThreadAssistantStream(e,t,r){const n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",(()=>this.controller.abort())));const s={...t,stream:!0},a=await e.createAndRun(s,{...r,signal:this.controller.signal});this._connected();for await(const e of a)wa(this,Ys,"m",da).call(this,e);if(a.controller.signal?.aborted)throw new yr;return this._addRun(wa(this,Ys,"m",ha).call(this))}async _createAssistantStream(e,t,r,n){const s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",(()=>this.controller.abort())));const a={...r,stream:!0},o=await e.create(t,a,{...n,signal:this.controller.signal});this._connected();for await(const e of o)wa(this,Ys,"m",da).call(this,e);if(o.controller.signal?.aborted)throw new yr;return this._addRun(wa(this,Ys,"m",ha).call(this))}static accumulateDelta(e,t){for(const[r,n]of Object.entries(t)){if(!e.hasOwnProperty(r)){e[r]=n;continue}let t=e[r];if(null!=t)if("index"!==r&&"type"!==r){if("string"==typeof t&&"string"==typeof n)t+=n;else if("number"==typeof t&&"number"==typeof n)t+=n;else{if(!vn(t)||!vn(n)){if(Array.isArray(t)&&Array.isArray(n)){if(t.every((e=>"string"==typeof e||"number"==typeof e))){t.push(...n);continue}for(const e of n){if(!vn(e))throw new Error(`Expected array delta entry to be an object but got: ${e}`);const r=e.index;if(null==r)throw console.error(e),new Error("Expected array delta entry to have an `index` property");if("number"!=typeof r)throw new Error(`Expected array delta entry \`index\` property to be a number but got ${r}`);const n=t[r];null==n?t.push(e):t[r]=this.accumulateDelta(n,e)}continue}throw Error(`Unhandled record type: ${r}, deltaValue: ${n}, accValue: ${t}`)}t=this.accumulateDelta(t,n)}e[r]=t}else e[r]=n;else e[r]=n}return e}_addRun(e){return e}async _threadAssistantStream(e,t,r){return await this._createThreadAssistantStream(t,e,r)}async _runAssistantStream(e,t,r,n){return await this._createAssistantStream(t,e,r,n)}async _runToolAssistantStream(e,t,r,n,s){return await this._createToolAssistantStream(r,e,t,n,s)}}da=function(e){if(!this.ended)switch(va(this,la,e,"f"),wa(this,Ys,"m",ma).call(this,e),e.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.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":wa(this,Ys,"m",ba).call(this,e);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":wa(this,Ys,"m",pa).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":wa(this,Ys,"m",fa).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},ha=function(){if(this.ended)throw new pr("stream has ended, this shouldn't happen");if(!wa(this,na,"f"))throw Error("Final run has not been received");return wa(this,na,"f")},fa=function(e){const[t,r]=wa(this,Ys,"m",ga).call(this,e,wa(this,ra,"f"));va(this,ra,t,"f"),wa(this,ta,"f")[t.id]=t;for(const e of r){const r=t.content[e.index];"text"==r?.type&&this._emit("textCreated",r.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(const r of e.data.delta.content){if("text"==r.type&&r.text){let e=r.text,n=t.content[r.index];if(!n||"text"!=n.type)throw Error("The snapshot associated with this text delta is not text or missing");this._emit("textDelta",e,n.text)}if(r.index!=wa(this,sa,"f")){if(wa(this,aa,"f"))switch(wa(this,aa,"f").type){case"text":this._emit("textDone",wa(this,aa,"f").text,wa(this,ra,"f"));break;case"image_file":this._emit("imageFileDone",wa(this,aa,"f").image_file,wa(this,ra,"f"))}va(this,sa,r.index,"f")}va(this,aa,t.content[r.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(void 0!==wa(this,sa,"f")){const t=e.data.content[wa(this,sa,"f")];if(t)switch(t.type){case"image_file":this._emit("imageFileDone",t.image_file,wa(this,ra,"f"));break;case"text":this._emit("textDone",t.text,wa(this,ra,"f"))}}wa(this,ra,"f")&&this._emit("messageDone",e.data),va(this,ra,void 0,"f")}},pa=function(e){const t=wa(this,Ys,"m",ya).call(this,e);switch(va(this,ua,t,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":const r=e.data.delta;if(r.step_details&&"tool_calls"==r.step_details.type&&r.step_details.tool_calls&&"tool_calls"==t.step_details.type)for(const e of r.step_details.tool_calls)e.index==wa(this,oa,"f")?this._emit("toolCallDelta",e,t.step_details.tool_calls[e.index]):(wa(this,ia,"f")&&this._emit("toolCallDone",wa(this,ia,"f")),va(this,oa,e.index,"f"),va(this,ia,t.step_details.tool_calls[e.index],"f"),wa(this,ia,"f")&&this._emit("toolCallCreated",wa(this,ia,"f")));this._emit("runStepDelta",e.data.delta,t);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":va(this,ua,void 0,"f");"tool_calls"==e.data.step_details.type&&wa(this,ia,"f")&&(this._emit("toolCallDone",wa(this,ia,"f")),va(this,ia,void 0,"f")),this._emit("runStepDone",e.data,t)}},ma=function(e){wa(this,Gs,"f").push(e),this._emit("event",e)},ya=function(e){switch(e.event){case"thread.run.step.created":return wa(this,ea,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=wa(this,ea,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let r=e.data;if(r.delta){const n=Sa.accumulateDelta(t,r.delta);wa(this,ea,"f")[e.data.id]=n}return wa(this,ea,"f")[e.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":wa(this,ea,"f")[e.data.id]=e.data}if(wa(this,ea,"f")[e.data.id])return wa(this,ea,"f")[e.data.id];throw new Error("No snapshot available")},ga=function(e,t){let r=[];switch(e.event){case"thread.message.created":return[e.data,r];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let n=e.data;if(n.delta.content)for(const e of n.delta.content)if(e.index in t.content){let r=t.content[e.index];t.content[e.index]=wa(this,Ys,"m",_a).call(this,e,r)}else t.content[e.index]=e,r.push(e);return[t,r];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,r];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},_a=function(e,t){return Sa.accumulateDelta(t,e)},ba=function(e){switch(va(this,ca,e.data,"f"),e.event){case"thread.run.created":case"thread.run.queued":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":va(this,na,e.data,"f"),wa(this,ia,"f")&&(this._emit("toolCallDone",wa(this,ia,"f")),va(this,ia,void 0,"f"))}};class xa extends kn{create(e,t,r){return this._client.post(`/threads/${e}/messages`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}retrieve(e,t,r){return this._client.get(`/threads/${e}/messages/${t}`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}update(e,t,r,n){return this._client.post(`/threads/${e}/messages/${t}`,{body:r,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}list(e,t={},r){return tn(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/messages`,ka,{query:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}del(e,t,r){return this._client.delete(`/threads/${e}/messages/${t}`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}}class ka extends xn{}xa.MessagesPage=ka;class Ta extends kn{retrieve(e,t,r,n={},s){return tn(n)?this.retrieve(e,t,r,{},n):this._client.get(`/threads/${e}/runs/${t}/steps/${r}`,{query:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}list(e,t,r={},n){return tn(r)?this.list(e,t,{},r):this._client.getAPIList(`/threads/${e}/runs/${t}/steps`,Ea,{query:r,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}}class Ea extends xn{}Ta.RunStepsPage=Ea;class Ra extends kn{constructor(){super(...arguments),this.steps=new Ta(this._client)}create(e,t,r){const{include:n,...s}=t;return this._client.post(`/threads/${e}/runs`,{query:{include:n},body:s,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers},stream:t.stream??!1})}retrieve(e,t,r){return this._client.get(`/threads/${e}/runs/${t}`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}update(e,t,r,n){return this._client.post(`/threads/${e}/runs/${t}`,{body:r,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}list(e,t={},r){return tn(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/runs`,Aa,{query:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}cancel(e,t,r){return this._client.post(`/threads/${e}/runs/${t}/cancel`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}async createAndPoll(e,t,r){const n=await this.create(e,t,r);return await this.poll(e,n.id,r)}createAndStream(e,t,r){return Sa.createAssistantStream(e,this._client.beta.threads.runs,t,r)}async poll(e,t,r){const n={...r?.headers,"X-Stainless-Poll-Helper":"true"};for(r?.pollIntervalMs&&(n["X-Stainless-Custom-Poll-Interval"]=r.pollIntervalMs.toString());;){const{data:s,response:a}=await this.retrieve(e,t,{...r,headers:{...r?.headers,...n}}).withResponse();switch(s.status){case"queued":case"in_progress":case"cancelling":let e=5e3;if(r?.pollIntervalMs)e=r.pollIntervalMs;else{const t=a.headers.get("openai-poll-after-ms");if(t){const r=parseInt(t);isNaN(r)||(e=r)}}await dn(e);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return s}}}stream(e,t,r){return Sa.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r,n){return this._client.post(`/threads/${e}/runs/${t}/submit_tool_outputs`,{body:r,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers},stream:r.stream??!1})}async submitToolOutputsAndPoll(e,t,r,n){const s=await this.submitToolOutputs(e,t,r,n);return await this.poll(e,s.id,n)}submitToolOutputsStream(e,t,r,n){return Sa.createToolAssistantStream(e,t,this._client.beta.threads.runs,r,n)}}class Aa extends xn{}Ra.RunsPage=Aa,Ra.Steps=Ta,Ra.RunStepsPage=Ea;class Pa extends kn{constructor(){super(...arguments),this.runs=new Ra(this._client),this.messages=new xa(this._client)}create(e={},t){return tn(e)?this.create({},e):this._client.post("/threads",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}retrieve(e,t){return this._client.get(`/threads/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}update(e,t,r){return this._client.post(`/threads/${e}`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}del(e,t){return this._client.delete(`/threads/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers},stream:e.stream??!1})}async createAndRunPoll(e,t){const r=await this.createAndRun(e,t);return await this.runs.poll(r.thread_id,r.id,t)}createAndRunStream(e,t){return Sa.createThreadAssistantStream(e,this._client.beta.threads,t)}}Pa.Runs=Ra,Pa.RunsPage=Aa,Pa.Messages=xa,Pa.MessagesPage=ka;let Ca=class extends kn{create(e,t,r){return this._client.post(`/vector_stores/${e}/files`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}retrieve(e,t,r){return this._client.get(`/vector_stores/${e}/files/${t}`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}list(e,t={},r){return tn(t)?this.list(e,{},t):this._client.getAPIList(`/vector_stores/${e}/files`,Oa,{query:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}del(e,t,r){return this._client.delete(`/vector_stores/${e}/files/${t}`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}async createAndPoll(e,t,r){const n=await this.create(e,t,r);return await this.poll(e,n.id,r)}async poll(e,t,r){const n={...r?.headers,"X-Stainless-Poll-Helper":"true"};for(r?.pollIntervalMs&&(n["X-Stainless-Custom-Poll-Interval"]=r.pollIntervalMs.toString());;){const s=await this.retrieve(e,t,{...r,headers:n}).withResponse(),a=s.data;switch(a.status){case"in_progress":let e=5e3;if(r?.pollIntervalMs)e=r.pollIntervalMs;else{const t=s.response.headers.get("openai-poll-after-ms");if(t){const r=parseInt(t);isNaN(r)||(e=r)}}await dn(e);break;case"failed":case"completed":return a}}}async upload(e,t,r){const n=await this._client.files.create({file:t,purpose:"assistants"},r);return this.create(e,{file_id:n.id},r)}async uploadAndPoll(e,t,r){const n=await this.upload(e,t,r);return await this.poll(e,n.id,r)}};class Oa extends xn{}Ca.VectorStoreFilesPage=Oa;class ja extends kn{create(e,t,r){return this._client.post(`/vector_stores/${e}/file_batches`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}retrieve(e,t,r){return this._client.get(`/vector_stores/${e}/file_batches/${t}`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}cancel(e,t,r){return this._client.post(`/vector_stores/${e}/file_batches/${t}/cancel`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}async createAndPoll(e,t,r){const n=await this.create(e,t);return await this.poll(e,n.id,r)}listFiles(e,t,r={},n){return tn(r)?this.listFiles(e,t,{},r):this._client.getAPIList(`/vector_stores/${e}/file_batches/${t}/files`,Oa,{query:r,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}async poll(e,t,r){const n={...r?.headers,"X-Stainless-Poll-Helper":"true"};for(r?.pollIntervalMs&&(n["X-Stainless-Custom-Poll-Interval"]=r.pollIntervalMs.toString());;){const{data:s,response:a}=await this.retrieve(e,t,{...r,headers:n}).withResponse();switch(s.status){case"in_progress":let e=5e3;if(r?.pollIntervalMs)e=r.pollIntervalMs;else{const t=a.headers.get("openai-poll-after-ms");if(t){const r=parseInt(t);isNaN(r)||(e=r)}}await dn(e);break;case"failed":case"cancelled":case"completed":return s}}}async uploadAndPoll(e,{files:t,fileIds:r=[]},n){if(null==t||0==t.length)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const s=n?.maxConcurrency??5,a=Math.min(s,t.length),o=this._client,i=t.values(),l=[...r];const c=Array(a).fill(i).map((async function(e){for(let t of e){const e=await o.files.create({file:t,purpose:"assistants"},n);l.push(e.id)}}));return await(async e=>{const t=await Promise.allSettled(e),r=t.filter((e=>"rejected"===e.status));if(r.length){for(const e of r)console.error(e.reason);throw new Error(`${r.length} promise(s) failed - see the above errors`)}const n=[];for(const e of t)"fulfilled"===e.status&&n.push(e.value);return n})(c),await this.createAndPoll(e,{file_ids:l})}}class Ia extends kn{constructor(){super(...arguments),this.files=new Ca(this._client),this.fileBatches=new ja(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}retrieve(e,t){return this._client.get(`/vector_stores/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}update(e,t,r){return this._client.post(`/vector_stores/${e}`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}list(e={},t){return tn(e)?this.list({},e):this._client.getAPIList("/vector_stores",$a,{query:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}del(e,t){return this._client.delete(`/vector_stores/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}}class $a extends xn{}Ia.VectorStoresPage=$a,Ia.Files=Ca,Ia.VectorStoreFilesPage=Oa,Ia.FileBatches=ja;class qa extends kn{constructor(){super(...arguments),this.vectorStores=new Ia(this._client),this.chat=new Qs(this._client),this.assistants=new In(this._client),this.threads=new Pa(this._client)}}qa.VectorStores=Ia,qa.VectorStoresPage=$a,qa.Assistants=In,qa.AssistantsPage=$n,qa.Threads=Pa;class Na extends kn{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class La extends kn{create(e,t){return this._client.post("/embeddings",{body:e,...t})}}class Ba extends kn{create(e,t){return this._client.post("/files",Fr({body:e,...t}))}retrieve(e,t){return this._client.get(`/files/${e}`,t)}list(e={},t){return tn(e)?this.list({},e):this._client.getAPIList("/files",Ma,{query:e,...t})}del(e,t){return this._client.delete(`/files/${e}`,t)}content(e,t){return this._client.get(`/files/${e}/content`,{...t,__binaryResponse:!0})}retrieveContent(e,t){return this._client.get(`/files/${e}/content`,{...t,headers:{Accept:"application/json",...t?.headers}})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:r=18e5}={}){const n=new Set(["processed","error","deleted"]),s=Date.now();let a=await this.retrieve(e);for(;!a.status||!n.has(a.status);)if(await dn(t),a=await this.retrieve(e),Date.now()-s>r)throw new _r({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return a}}class Ma extends xn{}Ba.FileObjectsPage=Ma;class Da extends kn{list(e,t={},r){return tn(t)?this.list(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/checkpoints`,Fa,{query:t,...r})}}class Fa extends xn{}Da.FineTuningJobCheckpointsPage=Fa;class Wa extends kn{constructor(){super(...arguments),this.checkpoints=new Da(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(`/fine_tuning/jobs/${e}`,t)}list(e={},t){return tn(e)?this.list({},e):this._client.getAPIList("/fine_tuning/jobs",Za,{query:e,...t})}cancel(e,t){return this._client.post(`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},r){return tn(t)?this.listEvents(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/events`,za,{query:t,...r})}}class Za extends xn{}class za extends xn{}Wa.FineTuningJobsPage=Za,Wa.FineTuningJobEventsPage=za,Wa.Checkpoints=Da,Wa.FineTuningJobCheckpointsPage=Fa;class Ua extends kn{constructor(){super(...arguments),this.jobs=new Wa(this._client)}}Ua.Jobs=Wa,Ua.FineTuningJobsPage=Za,Ua.FineTuningJobEventsPage=za;class Ha extends kn{createVariation(e,t){return this._client.post("/images/variations",Fr({body:e,...t}))}edit(e,t){return this._client.post("/images/edits",Fr({body:e,...t}))}generate(e,t){return this._client.post("/images/generations",{body:e,...t})}}class Va extends kn{retrieve(e,t){return this._client.get(`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",Ka,e)}del(e,t){return this._client.delete(`/models/${e}`,t)}}class Ka extends Sn{}Va.ModelsPage=Ka;class Ja extends kn{create(e,t){return this._client.post("/moderations",{body:e,...t})}}class Xa extends kn{create(e,t,r){return this._client.post(`/uploads/${e}/parts`,Fr({body:t,...r}))}}class Qa extends kn{constructor(){super(...arguments),this.parts=new Xa(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(`/uploads/${e}/cancel`,t)}complete(e,t,r){return this._client.post(`/uploads/${e}/complete`,{body:t,...r})}}var Ya;Qa.Parts=Xa;class Ga extends Xr{constructor({baseURL:e=pn("OPENAI_BASE_URL"),apiKey:t=pn("OPENAI_API_KEY"),organization:r=pn("OPENAI_ORG_ID")??null,project:n=pn("OPENAI_PROJECT_ID")??null,...s}={}){if(void 0===t)throw new pr("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");const a={apiKey:t,organization:r,project:n,...s,baseURL:e||"https://api.openai.com/v1"};if(!a.dangerouslyAllowBrowser&&"undefined"!=typeof window&&void 0!==window.document&&"undefined"!=typeof navigator)throw new pr("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n");super({baseURL:a.baseURL,timeout:a.timeout??6e5,httpAgent:a.httpAgent,maxRetries:a.maxRetries,fetch:a.fetch}),this.completions=new Na(this),this.chat=new En(this),this.embeddings=new La(this),this.files=new Ba(this),this.images=new Ha(this),this.audio=new Cn(this),this.moderations=new Ja(this),this.models=new Va(this),this.fineTuning=new Ua(this),this.beta=new qa(this),this.batches=new On(this),this.uploads=new Qa(this),this._options=a,this.apiKey=t,this.organization=r,this.project=n}defaultQuery(){return this._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project,...this._options.defaultHeaders}}authHeaders(e){return{Authorization:`Bearer ${this.apiKey}`}}stringifyQuery(e){return tr(e,{arrayFormat:"brackets"})}}Ya=Ga,Ga.OpenAI=Ya,Ga.DEFAULT_TIMEOUT=6e5,Ga.OpenAIError=pr,Ga.APIError=mr,Ga.APIConnectionError=gr,Ga.APIConnectionTimeoutError=_r,Ga.APIUserAbortError=yr,Ga.NotFoundError=Sr,Ga.ConflictError=xr,Ga.RateLimitError=Tr,Ga.BadRequestError=br,Ga.AuthenticationError=wr,Ga.InternalServerError=Er,Ga.PermissionDeniedError=vr,Ga.UnprocessableEntityError=kr,Ga.toFile=Lr,Ga.fileFromPath=ur,Ga.Completions=Na,Ga.Chat=En,Ga.Embeddings=La,Ga.Files=Ba,Ga.FileObjectsPage=Ma,Ga.Images=Ha,Ga.Audio=Cn,Ga.Moderations=Ja,Ga.Models=Va,Ga.ModelsPage=Ka,Ga.FineTuning=Ua,Ga.Beta=qa,Ga.Batches=On,Ga.BatchesPage=jn,Ga.Uploads=Qa;var eo=Ga;const to={collection:"directus_settings",field:"ai_pack_config",type:"alias",schema:null,meta:{collection:"directus_settings",field:"ai_pack_config",special:["alias","no-data","group"],interface:"group-detail",options:{headerIcon:"rocket_launch"},display:null,display_options:null,readonly:!1,hidden:!1,sort:null,width:"full",translations:null,note:null,conditions:null,required:!1,group:null,validation:null,validation_message:null}},ro={collection:"directus_settings",field:"Open_AI_API_Key",type:"string",schema:{name:"Open_AI_API_Key",table:"directus_settings",data_type:"varchar",default_value:null,max_length:255,numeric_precision:null,numeric_scale:null,is_generated:!1,generation_expression:null,is_nullable:!0,is_unique:!1,is_primary_key:!1,has_auto_increment:!1,foreign_key_column:null,foreign_key_table:null},meta:{collection:"directus_settings",field:"Open_AI_API_Key",special:null,interface:"input",options:{masked:!0},display:null,display_options:null,readonly:!1,hidden:!1,sort:2,width:"full",translations:null,note:null,conditions:null,required:!1,group:to.field,validation:null,validation_message:null}},no={collection:"directus_settings",field:"Stability_AI_API_Key",type:"string",schema:{name:"Stability_AI_API_Key",table:"directus_settings",data_type:"varchar",default_value:null,max_length:255,numeric_precision:null,numeric_scale:null,is_generated:!1,generation_expression:null,is_nullable:!0,is_unique:!1,is_primary_key:!1,has_auto_increment:!1,foreign_key_column:null,foreign_key_table:null},meta:{collection:"directus_settings",field:"Stability_AI_API_Key",special:null,interface:"input",options:{masked:!0},display:null,display_options:null,readonly:!1,hidden:!1,sort:2,width:"full",translations:null,note:null,conditions:null,required:!1,group:to.field,validation:null,validation_message:null}},so={collection:"directus_settings",field:"Deep_AI_API_Key",type:"string",schema:{name:"Deep_AI_API_Key",table:"directus_settings",data_type:"varchar",default_value:null,max_length:255,numeric_precision:null,numeric_scale:null,is_generated:!1,generation_expression:null,is_nullable:!0,is_unique:!1,is_primary_key:!1,has_auto_increment:!1,foreign_key_column:null,foreign_key_table:null},meta:{collection:"directus_settings",field:"Deep_AI_API_Key",special:null,interface:"input",options:{masked:!0},display:null,display_options:null,readonly:!1,hidden:!1,sort:3,width:"full",translations:null,note:null,conditions:null,required:!1,group:to.field,validation:null,validation_message:null}};async function ao(e,t,r){if(r)return r;const n=await e.readSingleton({fields:[t]}).catch((()=>!1));return n?n[t]:null}var oo={id:"dall-e-operation",handler:async({text:e,api_key:t,amount:r=1,size:n="1024x1024",save_assets:s=!0},{services:a,database:o,getSchema:i})=>{const{FilesService:l,SettingsService:c}=a,u=await i(),d=new c({schema:u,knex:o}),h=new l({schema:u,knex:o}),f=new eo({apiKey:await ao(d,ro.field,t)}),p=await f.images.generate({model:"dall-e-3",prompt:e,n:r,size:n});let m=[],y=[];for(let e=0;e<r;e++){const t=p.data[e].url;if(m.push(t),s){const e=await h.importOne(t);y.push(e)}}return 1===r?{url:m[0],id:y[0]??null}:{url:m,id:y}}};var io,lo={exports:{}};if(!globalThis.ReadableStream)try{const e=require("node:process"),{emitWarning:t}=e;try{e.emitWarning=()=>{},Object.assign(globalThis,require("node:stream/web")),e.emitWarning=t}catch(r){throw e.emitWarning=t,r}}catch(e){Object.assign(globalThis,(io||(io=1,function(e){const t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol:e=>`Symbol(${e})`;function r(){}function n(){return"undefined"!=typeof self?self:"undefined"!=typeof window?window:void 0!==d?d:void 0}const s=n();function a(e){return"object"==typeof e&&null!==e||"function"==typeof e}const o=r,i=Promise,l=Promise.prototype.then,c=Promise.resolve.bind(i),u=Promise.reject.bind(i);function h(e){return new i(e)}function f(e){return c(e)}function p(e){return u(e)}function m(e,t,r){return l.call(e,t,r)}function y(e,t,r){m(m(e,t,r),void 0,o)}function g(e,t){y(e,t)}function _(e,t){y(e,void 0,t)}function b(e,t,r){return m(e,t,r)}function w(e){m(e,void 0,o)}const v=(()=>{const e=s&&s.queueMicrotask;if("function"==typeof e)return e;const t=f(void 0);return e=>m(t,e)})();function S(e,t,r){if("function"!=typeof e)throw new TypeError("Argument is not a function");return Function.prototype.apply.call(e,t,r)}function x(e,t,r){try{return f(S(e,t,r))}catch(e){return p(e)}}const k=16384;class T{constructor(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}get length(){return this._size}push(e){const t=this._back;let r=t;t._elements.length===k-1&&(r={_elements:[],_next:void 0}),t._elements.push(e),r!==t&&(this._back=r,t._next=r),++this._size}shift(){const e=this._front;let t=e;const r=this._cursor;let n=r+1;const s=e._elements,a=s[r];return n===k&&(t=e._next,n=0),--this._size,this._cursor=n,e!==t&&(this._front=t),s[r]=void 0,a}forEach(e){let t=this._cursor,r=this._front,n=r._elements;for(;!(t===n.length&&void 0===r._next||t===n.length&&(r=r._next,n=r._elements,t=0,0===n.length));)e(n[t]),++t}peek(){const e=this._front,t=this._cursor;return e._elements[t]}}function E(e,t){e._ownerReadableStream=t,t._reader=e,"readable"===t._state?C(e):"closed"===t._state?j(e):O(e,t._storedError)}function R(e,t){return Tn(e._ownerReadableStream,t)}function A(e){"readable"===e._ownerReadableStream._state?I(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):$(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),e._ownerReadableStream._reader=void 0,e._ownerReadableStream=void 0}function P(e){return new TypeError("Cannot "+e+" a stream using a released reader")}function C(e){e._closedPromise=h(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r}))}function O(e,t){C(e),I(e,t)}function j(e){C(e),q(e)}function I(e,t){void 0!==e._closedPromise_reject&&(w(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}function $(e,t){O(e,t)}function q(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}const N=t("[[AbortSteps]]"),L=t("[[ErrorSteps]]"),B=t("[[CancelSteps]]"),M=t("[[PullSteps]]"),D=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},F=Math.trunc||function(e){return e<0?Math.ceil(e):Math.floor(e)};function W(e){return"object"==typeof e||"function"==typeof e}function Z(e,t){if(void 0!==e&&!W(e))throw new TypeError(`${t} is not an object.`)}function z(e,t){if("function"!=typeof e)throw new TypeError(`${t} is not a function.`)}function U(e){return"object"==typeof e&&null!==e||"function"==typeof e}function H(e,t){if(!U(e))throw new TypeError(`${t} is not an object.`)}function V(e,t,r){if(void 0===e)throw new TypeError(`Parameter ${t} is required in '${r}'.`)}function K(e,t,r){if(void 0===e)throw new TypeError(`${t} is required in '${r}'.`)}function J(e){return Number(e)}function X(e){return 0===e?0:e}function Q(e){return X(F(e))}function Y(e,t){const r=0,n=Number.MAX_SAFE_INTEGER;let s=Number(e);if(s=X(s),!D(s))throw new TypeError(`${t} is not a finite number`);if(s=Q(s),s<r||s>n)throw new TypeError(`${t} is outside the accepted range of ${r} to ${n}, inclusive`);return D(s)&&0!==s?s:0}function G(e,t){if(!xn(e))throw new TypeError(`${t} is not a ReadableStream.`)}function ee(e){return new ae(e)}function te(e,t){e._reader._readRequests.push(t)}function re(e,t,r){const n=e._reader._readRequests.shift();r?n._closeSteps():n._chunkSteps(t)}function ne(e){return e._reader._readRequests.length}function se(e){const t=e._reader;return void 0!==t&&!!oe(t)}class ae{constructor(e){if(V(e,1,"ReadableStreamDefaultReader"),G(e,"First parameter"),kn(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");E(this,e),this._readRequests=new T}get closed(){return oe(this)?this._closedPromise:p(le("closed"))}cancel(e=void 0){return oe(this)?void 0===this._ownerReadableStream?p(P("cancel")):R(this,e):p(le("cancel"))}read(){if(!oe(this))return p(le("read"));if(void 0===this._ownerReadableStream)return p(P("read from"));let e,t;const r=h(((r,n)=>{e=r,t=n})),n={_chunkSteps:t=>e({value:t,done:!1}),_closeSteps:()=>e({value:void 0,done:!0}),_errorSteps:e=>t(e)};return ie(this,n),r}releaseLock(){if(!oe(this))throw le("releaseLock");if(void 0!==this._ownerReadableStream){if(this._readRequests.length>0)throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled");A(this)}}}function oe(e){return!!a(e)&&!!Object.prototype.hasOwnProperty.call(e,"_readRequests")&&e instanceof ae}function ie(e,t){const r=e._ownerReadableStream;r._disturbed=!0,"closed"===r._state?t._closeSteps():"errored"===r._state?t._errorSteps(r._storedError):r._readableStreamController[M](t)}function le(e){return new TypeError(`ReadableStreamDefaultReader.prototype.${e} can only be used on a ReadableStreamDefaultReader`)}Object.defineProperties(ae.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(ae.prototype,t.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});const ce=Object.getPrototypeOf(Object.getPrototypeOf((async function*(){})).prototype);class ue{constructor(e,t){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=e,this._preventCancel=t}next(){const e=()=>this._nextSteps();return this._ongoingPromise=this._ongoingPromise?b(this._ongoingPromise,e,e):e(),this._ongoingPromise}return(e){const t=()=>this._returnSteps(e);return this._ongoingPromise?b(this._ongoingPromise,t,t):t()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});const e=this._reader;if(void 0===e._ownerReadableStream)return p(P("iterate"));let t,r;const n=h(((e,n)=>{t=e,r=n}));return ie(e,{_chunkSteps:e=>{this._ongoingPromise=void 0,v((()=>t({value:e,done:!1})))},_closeSteps:()=>{this._ongoingPromise=void 0,this._isFinished=!0,A(e),t({value:void 0,done:!0})},_errorSteps:t=>{this._ongoingPromise=void 0,this._isFinished=!0,A(e),r(t)}}),n}_returnSteps(e){if(this._isFinished)return Promise.resolve({value:e,done:!0});this._isFinished=!0;const t=this._reader;if(void 0===t._ownerReadableStream)return p(P("finish iterating"));if(!this._preventCancel){const r=R(t,e);return A(t),b(r,(()=>({value:e,done:!0})))}return A(t),f({value:e,done:!0})}}const de={next(){return fe(this)?this._asyncIteratorImpl.next():p(pe("next"))},return(e){return fe(this)?this._asyncIteratorImpl.return(e):p(pe("return"))}};function he(e,t){const r=ee(e),n=new ue(r,t),s=Object.create(de);return s._asyncIteratorImpl=n,s}function fe(e){if(!a(e))return!1;if(!Object.prototype.hasOwnProperty.call(e,"_asyncIteratorImpl"))return!1;try{return e._asyncIteratorImpl instanceof ue}catch(e){return!1}}function pe(e){return new TypeError(`ReadableStreamAsyncIterator.${e} can only be used on a ReadableSteamAsyncIterator`)}void 0!==ce&&Object.setPrototypeOf(de,ce);const me=Number.isNaN||function(e){return e!=e};function ye(e){return e.slice()}function ge(e,t,r,n,s){new Uint8Array(e).set(new Uint8Array(r,n,s),t)}function _e(e){return e}function be(e){return!1}function we(e,t,r){if(e.slice)return e.slice(t,r);const n=r-t,s=new ArrayBuffer(n);return ge(s,0,e,t,n),s}function ve(e){return!("number"!=typeof e||me(e)||e<0)}function Se(e){const t=we(e.buffer,e.byteOffset,e.byteOffset+e.byteLength);return new Uint8Array(t)}function xe(e){const t=e._queue.shift();return e._queueTotalSize-=t.size,e._queueTotalSize<0&&(e._queueTotalSize=0),t.value}function ke(e,t,r){if(!ve(r)||r===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");e._queue.push({value:t,size:r}),e._queueTotalSize+=r}function Te(e){return e._queue.peek().value}function Ee(e){e._queue=new T,e._queueTotalSize=0}class Re{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!Ce(this))throw st("view");return this._view}respond(e){if(!Ce(this))throw st("respond");if(V(e,1,"respond"),e=Y(e,"First parameter"),void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");be(this._view.buffer),Ge(this._associatedReadableByteStreamController,e)}respondWithNewView(e){if(!Ce(this))throw st("respondWithNewView");if(V(e,1,"respondWithNewView"),!ArrayBuffer.isView(e))throw new TypeError("You can only respond with array buffer views");if(void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");be(e.buffer),et(this._associatedReadableByteStreamController,e)}}Object.defineProperties(Re.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(Re.prototype,t.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class Ae{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!Pe(this))throw at("byobRequest");return Qe(this)}get desiredSize(){if(!Pe(this))throw at("desiredSize");return Ye(this)}close(){if(!Pe(this))throw at("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");const e=this._controlledReadableByteStream._state;if("readable"!==e)throw new TypeError(`The stream (in ${e} state) is not in the readable state and cannot be closed`);Ke(this)}enqueue(e){if(!Pe(this))throw at("enqueue");if(V(e,1,"enqueue"),!ArrayBuffer.isView(e))throw new TypeError("chunk must be an array buffer view");if(0===e.byteLength)throw new TypeError("chunk must have non-zero byteLength");if(0===e.buffer.byteLength)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");const t=this._controlledReadableByteStream._state;if("readable"!==t)throw new TypeError(`The stream (in ${t} state) is not in the readable state and cannot be enqueued to`);Je(this,e)}error(e=void 0){if(!Pe(this))throw at("error");Xe(this,e)}[B](e){je(this),Ee(this);const t=this._cancelAlgorithm(e);return Ve(this),t}[M](e){const t=this._controlledReadableByteStream;if(this._queueTotalSize>0){const t=this._queue.shift();this._queueTotalSize-=t.byteLength,Be(this);const r=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);return void e._chunkSteps(r)}const r=this._autoAllocateChunkSize;if(void 0!==r){let t;try{t=new ArrayBuffer(r)}catch(t){return void e._errorSteps(t)}const n={buffer:t,bufferByteLength:r,byteOffset:0,byteLength:r,bytesFilled:0,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(n)}te(t,e),Oe(this)}}function Pe(e){return!!a(e)&&!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableByteStream")&&e instanceof Ae}function Ce(e){return!!a(e)&&!!Object.prototype.hasOwnProperty.call(e,"_associatedReadableByteStreamController")&&e instanceof Re}function Oe(e){He(e)&&(e._pulling?e._pullAgain=!0:(e._pulling=!0,y(e._pullAlgorithm(),(()=>{e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,Oe(e))}),(t=>{Xe(e,t)}))))}function je(e){Me(e),e._pendingPullIntos=new T}function Ie(e,t){let r=!1;"closed"===e._state&&(r=!0);const n=$e(t);"default"===t.readerType?re(e,n,r):lt(e,n,r)}function $e(e){const t=e.bytesFilled,r=e.elementSize;return new e.viewConstructor(e.buffer,e.byteOffset,t/r)}function qe(e,t,r,n){e._queue.push({buffer:t,byteOffset:r,byteLength:n}),e._queueTotalSize+=n}function Ne(e,t){const r=t.elementSize,n=t.bytesFilled-t.bytesFilled%r,s=Math.min(e._queueTotalSize,t.byteLength-t.bytesFilled),a=t.bytesFilled+s,o=a-a%r;let i=s,l=!1;o>n&&(i=o-t.bytesFilled,l=!0);const c=e._queue;for(;i>0;){const r=c.peek(),n=Math.min(i,r.byteLength),s=t.byteOffset+t.bytesFilled;ge(t.buffer,s,r.buffer,r.byteOffset,n),r.byteLength===n?c.shift():(r.byteOffset+=n,r.byteLength-=n),e._queueTotalSize-=n,Le(e,n,t),i-=n}return l}function Le(e,t,r){r.bytesFilled+=t}function Be(e){0===e._queueTotalSize&&e._closeRequested?(Ve(e),En(e._controlledReadableByteStream)):Oe(e)}function Me(e){null!==e._byobRequest&&(e._byobRequest._associatedReadableByteStreamController=void 0,e._byobRequest._view=null,e._byobRequest=null)}function De(e){for(;e._pendingPullIntos.length>0;){if(0===e._queueTotalSize)return;const t=e._pendingPullIntos.peek();Ne(e,t)&&(Ue(e),Ie(e._controlledReadableByteStream,t))}}function Fe(e,t,r){const n=e._controlledReadableByteStream;let s=1;t.constructor!==DataView&&(s=t.constructor.BYTES_PER_ELEMENT);const a=t.constructor,o=_e(t.buffer),i={buffer:o,bufferByteLength:o.byteLength,byteOffset:t.byteOffset,byteLength:t.byteLength,bytesFilled:0,elementSize:s,viewConstructor:a,readerType:"byob"};if(e._pendingPullIntos.length>0)return e._pendingPullIntos.push(i),void it(n,r);if("closed"!==n._state){if(e._queueTotalSize>0){if(Ne(e,i)){const t=$e(i);return Be(e),void r._chunkSteps(t)}if(e._closeRequested){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");return Xe(e,t),void r._errorSteps(t)}}e._pendingPullIntos.push(i),it(n,r),Oe(e)}else{const e=new a(i.buffer,i.byteOffset,0);r._closeSteps(e)}}function We(e,t){const r=e._controlledReadableByteStream;if(ut(r))for(;ct(r)>0;)Ie(r,Ue(e))}function Ze(e,t,r){if(Le(e,t,r),r.bytesFilled<r.elementSize)return;Ue(e);const n=r.bytesFilled%r.elementSize;if(n>0){const t=r.byteOffset+r.bytesFilled,s=we(r.buffer,t-n,t);qe(e,s,0,s.byteLength)}r.bytesFilled-=n,Ie(e._controlledReadableByteStream,r),De(e)}function ze(e,t){const r=e._pendingPullIntos.peek();Me(e),"closed"===e._controlledReadableByteStream._state?We(e):Ze(e,t,r),Oe(e)}function Ue(e){return e._pendingPullIntos.shift()}function He(e){const t=e._controlledReadableByteStream;return"readable"===t._state&&!e._closeRequested&&!!e._started&&(!!(se(t)&&ne(t)>0)||!!(ut(t)&&ct(t)>0)||Ye(e)>0)}function Ve(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0}function Ke(e){const t=e._controlledReadableByteStream;if(!e._closeRequested&&"readable"===t._state)if(e._queueTotalSize>0)e._closeRequested=!0;else{if(e._pendingPullIntos.length>0&&e._pendingPullIntos.peek().bytesFilled>0){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");throw Xe(e,t),t}Ve(e),En(t)}}function Je(e,t){const r=e._controlledReadableByteStream;if(e._closeRequested||"readable"!==r._state)return;const n=t.buffer,s=t.byteOffset,a=t.byteLength,o=_e(n);if(e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek();be(t.buffer),t.buffer=_e(t.buffer)}Me(e),se(r)?0===ne(r)?qe(e,o,s,a):(e._pendingPullIntos.length>0&&Ue(e),re(r,new Uint8Array(o,s,a),!1)):ut(r)?(qe(e,o,s,a),De(e)):qe(e,o,s,a),Oe(e)}function Xe(e,t){const r=e._controlledReadableByteStream;"readable"===r._state&&(je(e),Ee(e),Ve(e),Rn(r,t))}function Qe(e){if(null===e._byobRequest&&e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek(),r=new Uint8Array(t.buffer,t.byteOffset+t.bytesFilled,t.byteLength-t.bytesFilled),n=Object.create(Re.prototype);nt(n,e,r),e._byobRequest=n}return e._byobRequest}function Ye(e){const t=e._controlledReadableByteStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function Ge(e,t){const r=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==t)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(0===t)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(r.bytesFilled+t>r.byteLength)throw new RangeError("bytesWritten out of range")}r.buffer=_e(r.buffer),ze(e,t)}function et(e,t){const r=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==t.byteLength)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(0===t.byteLength)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(r.byteOffset+r.bytesFilled!==t.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(r.bufferByteLength!==t.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(r.bytesFilled+t.byteLength>r.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");const n=t.byteLength;r.buffer=_e(t.buffer),ze(e,n)}function tt(e,t,r,n,s,a,o){t._controlledReadableByteStream=e,t._pullAgain=!1,t._pulling=!1,t._byobRequest=null,t._queue=t._queueTotalSize=void 0,Ee(t),t._closeRequested=!1,t._started=!1,t._strategyHWM=a,t._pullAlgorithm=n,t._cancelAlgorithm=s,t._autoAllocateChunkSize=o,t._pendingPullIntos=new T,e._readableStreamController=t,y(f(r()),(()=>{t._started=!0,Oe(t)}),(e=>{Xe(t,e)}))}function rt(e,t,r){const n=Object.create(Ae.prototype);let s=()=>{},a=()=>f(void 0),o=()=>f(void 0);void 0!==t.start&&(s=()=>t.start(n)),void 0!==t.pull&&(a=()=>t.pull(n)),void 0!==t.cancel&&(o=e=>t.cancel(e));const i=t.autoAllocateChunkSize;if(0===i)throw new TypeError("autoAllocateChunkSize must be greater than 0");tt(e,n,s,a,o,r,i)}function nt(e,t,r){e._associatedReadableByteStreamController=t,e._view=r}function st(e){return new TypeError(`ReadableStreamBYOBRequest.prototype.${e} can only be used on a ReadableStreamBYOBRequest`)}function at(e){return new TypeError(`ReadableByteStreamController.prototype.${e} can only be used on a ReadableByteStreamController`)}function ot(e){return new dt(e)}function it(e,t){e._reader._readIntoRequests.push(t)}function lt(e,t,r){const n=e._reader._readIntoRequests.shift();r?n._closeSteps(t):n._chunkSteps(t)}function ct(e){return e._reader._readIntoRequests.length}function ut(e){const t=e._reader;return void 0!==t&&!!ht(t)}Object.defineProperties(Ae.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(Ae.prototype,t.toStringTag,{value:"ReadableByteStreamController",configurable:!0});class dt{constructor(e){if(V(e,1,"ReadableStreamBYOBReader"),G(e,"First parameter"),kn(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!Pe(e._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");E(this,e),this._readIntoRequests=new T}get closed(){return ht(this)?this._closedPromise:p(pt("closed"))}cancel(e=void 0){return ht(this)?void 0===this._ownerReadableStream?p(P("cancel")):R(this,e):p(pt("cancel"))}read(e){if(!ht(this))return p(pt("read"));if(!ArrayBuffer.isView(e))return p(new TypeError("view must be an array buffer view"));if(0===e.byteLength)return p(new TypeError("view must have non-zero byteLength"));if(0===e.buffer.byteLength)return p(new TypeError("view's buffer must have non-zero byteLength"));if(be(e.buffer),void 0===this._ownerReadableStream)return p(P("read from"));let t,r;const n=h(((e,n)=>{t=e,r=n})),s={_chunkSteps:e=>t({value:e,done:!1}),_closeSteps:e=>t({value:e,done:!0}),_errorSteps:e=>r(e)};return ft(this,e,s),n}releaseLock(){if(!ht(this))throw pt("releaseLock");if(void 0!==this._ownerReadableStream){if(this._readIntoRequests.length>0)throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled");A(this)}}}function ht(e){return!!a(e)&&!!Object.prototype.hasOwnProperty.call(e,"_readIntoRequests")&&e instanceof dt}function ft(e,t,r){const n=e._ownerReadableStream;n._disturbed=!0,"errored"===n._state?r._errorSteps(n._storedError):Fe(n._readableStreamController,t,r)}function pt(e){return new TypeError(`ReadableStreamBYOBReader.prototype.${e} can only be used on a ReadableStreamBYOBReader`)}function mt(e,t){const{highWaterMark:r}=e;if(void 0===r)return t;if(me(r)||r<0)throw new RangeError("Invalid highWaterMark");return r}function yt(e){const{size:t}=e;return t||(()=>1)}function gt(e,t){Z(e,t);const r=null==e?void 0:e.highWaterMark,n=null==e?void 0:e.size;return{highWaterMark:void 0===r?void 0:J(r),size:void 0===n?void 0:_t(n,`${t} has member 'size' that`)}}function _t(e,t){return z(e,t),t=>J(e(t))}function bt(e,t){Z(e,t);const r=null==e?void 0:e.abort,n=null==e?void 0:e.close,s=null==e?void 0:e.start,a=null==e?void 0:e.type,o=null==e?void 0:e.write;return{abort:void 0===r?void 0:wt(r,e,`${t} has member 'abort' that`),close:void 0===n?void 0:vt(n,e,`${t} has member 'close' that`),start:void 0===s?void 0:St(s,e,`${t} has member 'start' that`),write:void 0===o?void 0:xt(o,e,`${t} has member 'write' that`),type:a}}function wt(e,t,r){return z(e,r),r=>x(e,t,[r])}function vt(e,t,r){return z(e,r),()=>x(e,t,[])}function St(e,t,r){return z(e,r),r=>S(e,t,[r])}function xt(e,t,r){return z(e,r),(r,n)=>x(e,t,[r,n])}function kt(e,t){if(!jt(e))throw new TypeError(`${t} is not a WritableStream.`)}function Tt(e){if("object"!=typeof e||null===e)return!1;try{return"boolean"==typeof e.aborted}catch(e){return!1}}Object.defineProperties(dt.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(dt.prototype,t.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});const Et="function"==typeof AbortController;function Rt(){if(Et)return new AbortController}class At{constructor(e={},t={}){void 0===e?e=null:H(e,"First parameter");const r=gt(t,"Second parameter"),n=bt(e,"First parameter");if(Ot(this),void 0!==n.type)throw new RangeError("Invalid type is specified");const s=yt(r);ur(this,n,mt(r,1),s)}get locked(){if(!jt(this))throw Sr("locked");return It(this)}abort(e=void 0){return jt(this)?It(this)?p(new TypeError("Cannot abort a stream that already has a writer")):$t(this,e):p(Sr("abort"))}close(){return jt(this)?It(this)?p(new TypeError("Cannot close a stream that already has a writer")):zt(this)?p(new TypeError("Cannot close an already-closing stream")):qt(this):p(Sr("close"))}getWriter(){if(!jt(this))throw Sr("getWriter");return Pt(this)}}function Pt(e){return new Xt(e)}function Ct(e,t,r,n,s=1,a=(()=>1)){const o=Object.create(At.prototype);return Ot(o),cr(o,Object.create(ir.prototype),e,t,r,n,s,a),o}function Ot(e){e._state="writable",e._storedError=void 0,e._writer=void 0,e._writableStreamController=void 0,e._writeRequests=new T,e._inFlightWriteRequest=void 0,e._closeRequest=void 0,e._inFlightCloseRequest=void 0,e._pendingAbortRequest=void 0,e._backpressure=!1}function jt(e){return!!a(e)&&!!Object.prototype.hasOwnProperty.call(e,"_writableStreamController")&&e instanceof At}function It(e){return void 0!==e._writer}function $t(e,t){var r;if("closed"===e._state||"errored"===e._state)return f(void 0);e._writableStreamController._abortReason=t,null===(r=e._writableStreamController._abortController)||void 0===r||r.abort();const n=e._state;if("closed"===n||"errored"===n)return f(void 0);if(void 0!==e._pendingAbortRequest)return e._pendingAbortRequest._promise;let s=!1;"erroring"===n&&(s=!0,t=void 0);const a=h(((r,n)=>{e._pendingAbortRequest={_promise:void 0,_resolve:r,_reject:n,_reason:t,_wasAlreadyErroring:s}}));return e._pendingAbortRequest._promise=a,s||Bt(e,t),a}function qt(e){const t=e._state;if("closed"===t||"errored"===t)return p(new TypeError(`The stream (in ${t} state) is not in the writable state and cannot be closed`));const r=h(((t,r)=>{const n={_resolve:t,_reject:r};e._closeRequest=n})),n=e._writer;return void 0!==n&&e._backpressure&&"writable"===t&&Br(n),hr(e._writableStreamController),r}function Nt(e){return h(((t,r)=>{const n={_resolve:t,_reject:r};e._writeRequests.push(n)}))}function Lt(e,t){"writable"!==e._state?Mt(e):Bt(e,t)}function Bt(e,t){const r=e._writableStreamController;e._state="erroring",e._storedError=t;const n=e._writer;void 0!==n&&rr(n,t),!Ut(e)&&r._started&&Mt(e)}function Mt(e){e._state="errored",e._writableStreamController[L]();const t=e._storedError;if(e._writeRequests.forEach((e=>{e._reject(t)})),e._writeRequests=new T,void 0===e._pendingAbortRequest)return void Kt(e);const r=e._pendingAbortRequest;if(e._pendingAbortRequest=void 0,r._wasAlreadyErroring)return r._reject(t),void Kt(e);y(e._writableStreamController[N](r._reason),(()=>{r._resolve(),Kt(e)}),(t=>{r._reject(t),Kt(e)}))}function Dt(e){e._inFlightWriteRequest._resolve(void 0),e._inFlightWriteRequest=void 0}function Ft(e,t){e._inFlightWriteRequest._reject(t),e._inFlightWriteRequest=void 0,Lt(e,t)}function Wt(e){e._inFlightCloseRequest._resolve(void 0),e._inFlightCloseRequest=void 0,"erroring"===e._state&&(e._storedError=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._resolve(),e._pendingAbortRequest=void 0)),e._state="closed";const t=e._writer;void 0!==t&&Or(t)}function Zt(e,t){e._inFlightCloseRequest._reject(t),e._inFlightCloseRequest=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._reject(t),e._pendingAbortRequest=void 0),Lt(e,t)}function zt(e){return void 0!==e._closeRequest||void 0!==e._inFlightCloseRequest}function Ut(e){return void 0!==e._inFlightWriteRequest||void 0!==e._inFlightCloseRequest}function Ht(e){e._inFlightCloseRequest=e._closeRequest,e._closeRequest=void 0}function Vt(e){e._inFlightWriteRequest=e._writeRequests.shift()}function Kt(e){void 0!==e._closeRequest&&(e._closeRequest._reject(e._storedError),e._closeRequest=void 0);const t=e._writer;void 0!==t&&Pr(t,e._storedError)}function Jt(e,t){const r=e._writer;void 0!==r&&t!==e._backpressure&&(t?Nr(r):Br(r)),e._backpressure=t}Object.defineProperties(At.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(At.prototype,t.toStringTag,{value:"WritableStream",configurable:!0});class Xt{constructor(e){if(V(e,1,"WritableStreamDefaultWriter"),kt(e,"First parameter"),It(e))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=e,e._writer=this;const t=e._state;if("writable"===t)!zt(e)&&e._backpressure?jr(this):$r(this),Er(this);else if("erroring"===t)Ir(this,e._storedError),Er(this);else if("closed"===t)$r(this),Ar(this);else{const t=e._storedError;Ir(this,t),Rr(this,t)}}get closed(){return Qt(this)?this._closedPromise:p(kr("closed"))}get desiredSize(){if(!Qt(this))throw kr("desiredSize");if(void 0===this._ownerWritableStream)throw Tr("desiredSize");return nr(this)}get ready(){return Qt(this)?this._readyPromise:p(kr("ready"))}abort(e=void 0){return Qt(this)?void 0===this._ownerWritableStream?p(Tr("abort")):Yt(this,e):p(kr("abort"))}close(){if(!Qt(this))return p(kr("close"));const e=this._ownerWritableStream;return void 0===e?p(Tr("close")):zt(e)?p(new TypeError("Cannot close an already-closing stream")):Gt(this)}releaseLock(){if(!Qt(this))throw kr("releaseLock");void 0!==this._ownerWritableStream&&sr(this)}write(e=void 0){return Qt(this)?void 0===this._ownerWritableStream?p(Tr("write to")):ar(this,e):p(kr("write"))}}function Qt(e){return!!a(e)&&!!Object.prototype.hasOwnProperty.call(e,"_ownerWritableStream")&&e instanceof Xt}function Yt(e,t){return $t(e._ownerWritableStream,t)}function Gt(e){return qt(e._ownerWritableStream)}function er(e){const t=e._ownerWritableStream,r=t._state;return zt(t)||"closed"===r?f(void 0):"errored"===r?p(t._storedError):Gt(e)}function tr(e,t){"pending"===e._closedPromiseState?Pr(e,t):Cr(e,t)}function rr(e,t){"pending"===e._readyPromiseState?qr(e,t):Lr(e,t)}function nr(e){const t=e._ownerWritableStream,r=t._state;return"errored"===r||"erroring"===r?null:"closed"===r?0:pr(t._writableStreamController)}function sr(e){const t=e._ownerWritableStream,r=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");rr(e,r),tr(e,r),t._writer=void 0,e._ownerWritableStream=void 0}function ar(e,t){const r=e._ownerWritableStream,n=r._writableStreamController,s=fr(n,t);if(r!==e._ownerWritableStream)return p(Tr("write to"));const a=r._state;if("errored"===a)return p(r._storedError);if(zt(r)||"closed"===a)return p(new TypeError("The stream is closing or closed and cannot be written to"));if("erroring"===a)return p(r._storedError);const o=Nt(r);return mr(n,t,s),o}Object.defineProperties(Xt.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(Xt.prototype,t.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});const or={};class ir{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!lr(this))throw xr("abortReason");return this._abortReason}get signal(){if(!lr(this))throw xr("signal");if(void 0===this._abortController)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(e=void 0){if(!lr(this))throw xr("error");"writable"===this._controlledWritableStream._state&&vr(this,e)}[N](e){const t=this._abortAlgorithm(e);return dr(this),t}[L](){Ee(this)}}function lr(e){return!!a(e)&&!!Object.prototype.hasOwnProperty.call(e,"_controlledWritableStream")&&e instanceof ir}function cr(e,t,r,n,s,a,o,i){t._controlledWritableStream=e,e._writableStreamController=t,t._queue=void 0,t._queueTotalSize=void 0,Ee(t),t._abortReason=void 0,t._abortController=Rt(),t._started=!1,t._strategySizeAlgorithm=i,t._strategyHWM=o,t._writeAlgorithm=n,t._closeAlgorithm=s,t._abortAlgorithm=a;const l=wr(t);Jt(e,l),y(f(r()),(()=>{t._started=!0,yr(t)}),(r=>{t._started=!0,Lt(e,r)}))}function ur(e,t,r,n){const s=Object.create(ir.prototype);let a=()=>{},o=()=>f(void 0),i=()=>f(void 0),l=()=>f(void 0);void 0!==t.start&&(a=()=>t.start(s)),void 0!==t.write&&(o=e=>t.write(e,s)),void 0!==t.close&&(i=()=>t.close()),void 0!==t.abort&&(l=e=>t.abort(e)),cr(e,s,a,o,i,l,r,n)}function dr(e){e._writeAlgorithm=void 0,e._closeAlgorithm=void 0,e._abortAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function hr(e){ke(e,or,0),yr(e)}function fr(e,t){try{return e._strategySizeAlgorithm(t)}catch(t){return gr(e,t),1}}function pr(e){return e._strategyHWM-e._queueTotalSize}function mr(e,t,r){try{ke(e,t,r)}catch(t){return void gr(e,t)}const n=e._controlledWritableStream;zt(n)||"writable"!==n._state||Jt(n,wr(e)),yr(e)}function yr(e){const t=e._controlledWritableStream;if(!e._started)return;if(void 0!==t._inFlightWriteRequest)return;if("erroring"===t._state)return void Mt(t);if(0===e._queue.length)return;const r=Te(e);r===or?_r(e):br(e,r)}function gr(e,t){"writable"===e._controlledWritableStream._state&&vr(e,t)}function _r(e){const t=e._controlledWritableStream;Ht(t),xe(e);const r=e._closeAlgorithm();dr(e),y(r,(()=>{Wt(t)}),(e=>{Zt(t,e)}))}function br(e,t){const r=e._controlledWritableStream;Vt(r),y(e._writeAlgorithm(t),(()=>{Dt(r);const t=r._state;if(xe(e),!zt(r)&&"writable"===t){const t=wr(e);Jt(r,t)}yr(e)}),(t=>{"writable"===r._state&&dr(e),Ft(r,t)}))}function wr(e){return pr(e)<=0}function vr(e,t){const r=e._controlledWritableStream;dr(e),Bt(r,t)}function Sr(e){return new TypeError(`WritableStream.prototype.${e} can only be used on a WritableStream`)}function xr(e){return new TypeError(`WritableStreamDefaultController.prototype.${e} can only be used on a WritableStreamDefaultController`)}function kr(e){return new TypeError(`WritableStreamDefaultWriter.prototype.${e} can only be used on a WritableStreamDefaultWriter`)}function Tr(e){return new TypeError("Cannot "+e+" a stream using a released writer")}function Er(e){e._closedPromise=h(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r,e._closedPromiseState="pending"}))}function Rr(e,t){Er(e),Pr(e,t)}function Ar(e){Er(e),Or(e)}function Pr(e,t){void 0!==e._closedPromise_reject&&(w(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="rejected")}function Cr(e,t){Rr(e,t)}function Or(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="resolved")}function jr(e){e._readyPromise=h(((t,r)=>{e._readyPromise_resolve=t,e._readyPromise_reject=r})),e._readyPromiseState="pending"}function Ir(e,t){jr(e),qr(e,t)}function $r(e){jr(e),Br(e)}function qr(e,t){void 0!==e._readyPromise_reject&&(w(e._readyPromise),e._readyPromise_reject(t),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="rejected")}function Nr(e){jr(e)}function Lr(e,t){Ir(e,t)}function Br(e){void 0!==e._readyPromise_resolve&&(e._readyPromise_resolve(void 0),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="fulfilled")}Object.defineProperties(ir.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(ir.prototype,t.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});const Mr="undefined"!=typeof DOMException?DOMException:void 0;function Dr(e){if("function"!=typeof e&&"object"!=typeof e)return!1;try{return new e,!0}catch(e){return!1}}function Fr(){const e=function(e,t){this.message=e||"",this.name=t||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)};return e.prototype=Object.create(Error.prototype),Object.defineProperty(e.prototype,"constructor",{value:e,writable:!0,configurable:!0}),e}const Wr=Dr(Mr)?Mr:Fr();function Zr(e,t,n,s,a,o){const i=ee(e),l=Pt(t);e._disturbed=!0;let c=!1,u=f(void 0);return h(((d,p)=>{let b;if(void 0!==o){if(b=()=>{const r=new Wr("Aborted","AbortError"),n=[];s||n.push((()=>"writable"===t._state?$t(t,r):f(void 0))),a||n.push((()=>"readable"===e._state?Tn(e,r):f(void 0))),E((()=>Promise.all(n.map((e=>e())))),!0,r)},o.aborted)return void b();o.addEventListener("abort",b)}function v(){return h(((e,t)=>{function r(n){n?e():m(S(),r,t)}r(!1)}))}function S(){return c?f(!0):m(l._readyPromise,(()=>h(((e,t)=>{ie(i,{_chunkSteps:t=>{u=m(ar(l,t),void 0,r),e(!1)},_closeSteps:()=>e(!0),_errorSteps:t})}))))}if(k(e,i._closedPromise,(e=>{s?R(!0,e):E((()=>$t(t,e)),!0,e)})),k(t,l._closedPromise,(t=>{a?R(!0,t):E((()=>Tn(e,t)),!0,t)})),T(e,i._closedPromise,(()=>{n?R():E((()=>er(l)))})),zt(t)||"closed"===t._state){const t=new TypeError("the destination writable stream closed before all data could be piped to it");a?R(!0,t):E((()=>Tn(e,t)),!0,t)}function x(){const e=u;return m(u,(()=>e!==u?x():void 0))}function k(e,t,r){"errored"===e._state?r(e._storedError):_(t,r)}function T(e,t,r){"closed"===e._state?r():g(t,r)}function E(e,r,n){function s(){y(e(),(()=>P(r,n)),(e=>P(!0,e)))}c||(c=!0,"writable"!==t._state||zt(t)?s():g(x(),s))}function R(e,r){c||(c=!0,"writable"!==t._state||zt(t)?P(e,r):g(x(),(()=>P(e,r))))}function P(e,t){sr(l),A(i),void 0!==o&&o.removeEventListener("abort",b),e?p(t):d(void 0)}w(v())}))}class zr{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Ur(this))throw nn("desiredSize");return Yr(this)}close(){if(!Ur(this))throw nn("close");if(!en(this))throw new TypeError("The stream is not in a state that permits close");Jr(this)}enqueue(e=void 0){if(!Ur(this))throw nn("enqueue");if(!en(this))throw new TypeError("The stream is not in a state that permits enqueue");return Xr(this,e)}error(e=void 0){if(!Ur(this))throw nn("error");Qr(this,e)}[B](e){Ee(this);const t=this._cancelAlgorithm(e);return Kr(this),t}[M](e){const t=this._controlledReadableStream;if(this._queue.length>0){const r=xe(this);this._closeRequested&&0===this._queue.length?(Kr(this),En(t)):Hr(this),e._chunkSteps(r)}else te(t,e),Hr(this)}}function Ur(e){return!!a(e)&&!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableStream")&&e instanceof zr}function Hr(e){Vr(e)&&(e._pulling?e._pullAgain=!0:(e._pulling=!0,y(e._pullAlgorithm(),(()=>{e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,Hr(e))}),(t=>{Qr(e,t)}))))}function Vr(e){const t=e._controlledReadableStream;return!!en(e)&&!!e._started&&(!!(kn(t)&&ne(t)>0)||Yr(e)>0)}function Kr(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function Jr(e){if(!en(e))return;const t=e._controlledReadableStream;e._closeRequested=!0,0===e._queue.length&&(Kr(e),En(t))}function Xr(e,t){if(!en(e))return;const r=e._controlledReadableStream;if(kn(r)&&ne(r)>0)re(r,t,!1);else{let r;try{r=e._strategySizeAlgorithm(t)}catch(t){throw Qr(e,t),t}try{ke(e,t,r)}catch(t){throw Qr(e,t),t}}Hr(e)}function Qr(e,t){const r=e._controlledReadableStream;"readable"===r._state&&(Ee(e),Kr(e),Rn(r,t))}function Yr(e){const t=e._controlledReadableStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function Gr(e){return!Vr(e)}function en(e){const t=e._controlledReadableStream._state;return!e._closeRequested&&"readable"===t}function tn(e,t,r,n,s,a,o){t._controlledReadableStream=e,t._queue=void 0,t._queueTotalSize=void 0,Ee(t),t._started=!1,t._closeRequested=!1,t._pullAgain=!1,t._pulling=!1,t._strategySizeAlgorithm=o,t._strategyHWM=a,t._pullAlgorithm=n,t._cancelAlgorithm=s,e._readableStreamController=t,y(f(r()),(()=>{t._started=!0,Hr(t)}),(e=>{Qr(t,e)}))}function rn(e,t,r,n){const s=Object.create(zr.prototype);let a=()=>{},o=()=>f(void 0),i=()=>f(void 0);void 0!==t.start&&(a=()=>t.start(s)),void 0!==t.pull&&(o=()=>t.pull(s)),void 0!==t.cancel&&(i=e=>t.cancel(e)),tn(e,s,a,o,i,r,n)}function nn(e){return new TypeError(`ReadableStreamDefaultController.prototype.${e} can only be used on a ReadableStreamDefaultController`)}function sn(e,t){return Pe(e._readableStreamController)?on(e):an(e)}function an(e,t){const r=ee(e);let n,s,a,o,i,l=!1,c=!1,u=!1,d=!1;const p=h((e=>{i=e}));function m(){return l?(c=!0,f(void 0)):(l=!0,ie(r,{_chunkSteps:e=>{v((()=>{c=!1;const t=e,r=e;u||Xr(a._readableStreamController,t),d||Xr(o._readableStreamController,r),l=!1,c&&m()}))},_closeSteps:()=>{l=!1,u||Jr(a._readableStreamController),d||Jr(o._readableStreamController),u&&d||i(void 0)},_errorSteps:()=>{l=!1}}),f(void 0))}function y(t){if(u=!0,n=t,d){const t=ye([n,s]),r=Tn(e,t);i(r)}return p}function g(t){if(d=!0,s=t,u){const t=ye([n,s]),r=Tn(e,t);i(r)}return p}function b(){}return a=wn(b,m,y),o=wn(b,m,g),_(r._closedPromise,(e=>{Qr(a._readableStreamController,e),Qr(o._readableStreamController,e),u&&d||i(void 0)})),[a,o]}function on(e){let t,r,n,s,a,o=ee(e),i=!1,l=!1,c=!1,u=!1,d=!1;const p=h((e=>{a=e}));function m(e){_(e._closedPromise,(t=>{e===o&&(Xe(n._readableStreamController,t),Xe(s._readableStreamController,t),u&&d||a(void 0))}))}function y(){ht(o)&&(A(o),o=ee(e),m(o)),ie(o,{_chunkSteps:t=>{v((()=>{l=!1,c=!1;const r=t;let o=t;if(!u&&!d)try{o=Se(t)}catch(t){return Xe(n._readableStreamController,t),Xe(s._readableStreamController,t),void a(Tn(e,t))}u||Je(n._readableStreamController,r),d||Je(s._readableStreamController,o),i=!1,l?b():c&&w()}))},_closeSteps:()=>{i=!1,u||Ke(n._readableStreamController),d||Ke(s._readableStreamController),n._readableStreamController._pendingPullIntos.length>0&&Ge(n._readableStreamController,0),s._readableStreamController._pendingPullIntos.length>0&&Ge(s._readableStreamController,0),u&&d||a(void 0)},_errorSteps:()=>{i=!1}})}function g(t,r){oe(o)&&(A(o),o=ot(e),m(o));const h=r?s:n,f=r?n:s;ft(o,t,{_chunkSteps:t=>{v((()=>{l=!1,c=!1;const n=r?d:u;if(r?u:d)n||et(h._readableStreamController,t);else{let r;try{r=Se(t)}catch(t){return Xe(h._readableStreamController,t),Xe(f._readableStreamController,t),void a(Tn(e,t))}n||et(h._readableStreamController,t),Je(f._readableStreamController,r)}i=!1,l?b():c&&w()}))},_closeSteps:e=>{i=!1;const t=r?d:u,n=r?u:d;t||Ke(h._readableStreamController),n||Ke(f._readableStreamController),void 0!==e&&(t||et(h._readableStreamController,e),!n&&f._readableStreamController._pendingPullIntos.length>0&&Ge(f._readableStreamController,0)),t&&n||a(void 0)},_errorSteps:()=>{i=!1}})}function b(){if(i)return l=!0,f(void 0);i=!0;const e=Qe(n._readableStreamController);return null===e?y():g(e._view,!1),f(void 0)}function w(){if(i)return c=!0,f(void 0);i=!0;const e=Qe(s._readableStreamController);return null===e?y():g(e._view,!0),f(void 0)}function S(n){if(u=!0,t=n,d){const n=ye([t,r]),s=Tn(e,n);a(s)}return p}function x(n){if(d=!0,r=n,u){const n=ye([t,r]),s=Tn(e,n);a(s)}return p}function k(){}return n=vn(k,b,S),s=vn(k,w,x),m(o),[n,s]}function ln(e,t){Z(e,t);const r=e,n=null==r?void 0:r.autoAllocateChunkSize,s=null==r?void 0:r.cancel,a=null==r?void 0:r.pull,o=null==r?void 0:r.start,i=null==r?void 0:r.type;return{autoAllocateChunkSize:void 0===n?void 0:Y(n,`${t} has member 'autoAllocateChunkSize' that`),cancel:void 0===s?void 0:cn(s,r,`${t} has member 'cancel' that`),pull:void 0===a?void 0:un(a,r,`${t} has member 'pull' that`),start:void 0===o?void 0:dn(o,r,`${t} has member 'start' that`),type:void 0===i?void 0:hn(i,`${t} has member 'type' that`)}}function cn(e,t,r){return z(e,r),r=>x(e,t,[r])}function un(e,t,r){return z(e,r),r=>x(e,t,[r])}function dn(e,t,r){return z(e,r),r=>S(e,t,[r])}function hn(e,t){if("bytes"!=(e=`${e}`))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamType`);return e}function fn(e,t){Z(e,t);const r=null==e?void 0:e.mode;return{mode:void 0===r?void 0:pn(r,`${t} has member 'mode' that`)}}function pn(e,t){if("byob"!=(e=`${e}`))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamReaderMode`);return e}function mn(e,t){Z(e,t);const r=null==e?void 0:e.preventCancel;return{preventCancel:Boolean(r)}}function yn(e,t){Z(e,t);const r=null==e?void 0:e.preventAbort,n=null==e?void 0:e.preventCancel,s=null==e?void 0:e.preventClose,a=null==e?void 0:e.signal;return void 0!==a&&gn(a,`${t} has member 'signal' that`),{preventAbort:Boolean(r),preventCancel:Boolean(n),preventClose:Boolean(s),signal:a}}function gn(e,t){if(!Tt(e))throw new TypeError(`${t} is not an AbortSignal.`)}function _n(e,t){Z(e,t);const r=null==e?void 0:e.readable;K(r,"readable","ReadableWritablePair"),G(r,`${t} has member 'readable' that`);const n=null==e?void 0:e.writable;return K(n,"writable","ReadableWritablePair"),kt(n,`${t} has member 'writable' that`),{readable:r,writable:n}}Object.defineProperties(zr.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(zr.prototype,t.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});class bn{constructor(e={},t={}){void 0===e?e=null:H(e,"First parameter");const r=gt(t,"Second parameter"),n=ln(e,"First parameter");if(Sn(this),"bytes"===n.type){if(void 0!==r.size)throw new RangeError("The strategy for a byte stream cannot have a size function");rt(this,n,mt(r,0))}else{const e=yt(r);rn(this,n,mt(r,1),e)}}get locked(){if(!xn(this))throw An("locked");return kn(this)}cancel(e=void 0){return xn(this)?kn(this)?p(new TypeError("Cannot cancel a stream that already has a reader")):Tn(this,e):p(An("cancel"))}getReader(e=void 0){if(!xn(this))throw An("getReader");return void 0===fn(e,"First parameter").mode?ee(this):ot(this)}pipeThrough(e,t={}){if(!xn(this))throw An("pipeThrough");V(e,1,"pipeThrough");const r=_n(e,"First parameter"),n=yn(t,"Second parameter");if(kn(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(It(r.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");return w(Zr(this,r.writable,n.preventClose,n.preventAbort,n.preventCancel,n.signal)),r.readable}pipeTo(e,t={}){if(!xn(this))return p(An("pipeTo"));if(void 0===e)return p("Parameter 1 is required in 'pipeTo'.");if(!jt(e))return p(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let r;try{r=yn(t,"Second parameter")}catch(e){return p(e)}return kn(this)?p(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):It(e)?p(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):Zr(this,e,r.preventClose,r.preventAbort,r.preventCancel,r.signal)}tee(){if(!xn(this))throw An("tee");return ye(sn(this))}values(e=void 0){if(!xn(this))throw An("values");return he(this,mn(e,"First parameter").preventCancel)}}function wn(e,t,r,n=1,s=(()=>1)){const a=Object.create(bn.prototype);return Sn(a),tn(a,Object.create(zr.prototype),e,t,r,n,s),a}function vn(e,t,r){const n=Object.create(bn.prototype);return Sn(n),tt(n,Object.create(Ae.prototype),e,t,r,0,void 0),n}function Sn(e){e._state="readable",e._reader=void 0,e._storedError=void 0,e._disturbed=!1}function xn(e){return!!a(e)&&!!Object.prototype.hasOwnProperty.call(e,"_readableStreamController")&&e instanceof bn}function kn(e){return void 0!==e._reader}function Tn(e,t){if(e._disturbed=!0,"closed"===e._state)return f(void 0);if("errored"===e._state)return p(e._storedError);En(e);const n=e._reader;return void 0!==n&&ht(n)&&(n._readIntoRequests.forEach((e=>{e._closeSteps(void 0)})),n._readIntoRequests=new T),b(e._readableStreamController[B](t),r)}function En(e){e._state="closed";const t=e._reader;void 0!==t&&(q(t),oe(t)&&(t._readRequests.forEach((e=>{e._closeSteps()})),t._readRequests=new T))}function Rn(e,t){e._state="errored",e._storedError=t;const r=e._reader;void 0!==r&&(I(r,t),oe(r)?(r._readRequests.forEach((e=>{e._errorSteps(t)})),r._readRequests=new T):(r._readIntoRequests.forEach((e=>{e._errorSteps(t)})),r._readIntoRequests=new T))}function An(e){return new TypeError(`ReadableStream.prototype.${e} can only be used on a ReadableStream`)}function Pn(e,t){Z(e,t);const r=null==e?void 0:e.highWaterMark;return K(r,"highWaterMark","QueuingStrategyInit"),{highWaterMark:J(r)}}Object.defineProperties(bn.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(bn.prototype,t.toStringTag,{value:"ReadableStream",configurable:!0}),"symbol"==typeof t.asyncIterator&&Object.defineProperty(bn.prototype,t.asyncIterator,{value:bn.prototype.values,writable:!0,configurable:!0});const Cn=e=>e.byteLength;try{Object.defineProperty(Cn,"name",{value:"size",configurable:!0})}catch(e){}class On{constructor(e){V(e,1,"ByteLengthQueuingStrategy"),e=Pn(e,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!In(this))throw jn("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!In(this))throw jn("size");return Cn}}function jn(e){return new TypeError(`ByteLengthQueuingStrategy.prototype.${e} can only be used on a ByteLengthQueuingStrategy`)}function In(e){return!!a(e)&&!!Object.prototype.hasOwnProperty.call(e,"_byteLengthQueuingStrategyHighWaterMark")&&e instanceof On}Object.defineProperties(On.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(On.prototype,t.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});const $n=()=>1;try{Object.defineProperty($n,"name",{value:"size",configurable:!0})}catch(e){}class qn{constructor(e){V(e,1,"CountQueuingStrategy"),e=Pn(e,"First parameter"),this._countQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!Ln(this))throw Nn("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!Ln(this))throw Nn("size");return $n}}function Nn(e){return new TypeError(`CountQueuingStrategy.prototype.${e} can only be used on a CountQueuingStrategy`)}function Ln(e){return!!a(e)&&!!Object.prototype.hasOwnProperty.call(e,"_countQueuingStrategyHighWaterMark")&&e instanceof qn}function Bn(e,t){Z(e,t);const r=null==e?void 0:e.flush,n=null==e?void 0:e.readableType,s=null==e?void 0:e.start,a=null==e?void 0:e.transform,o=null==e?void 0:e.writableType;return{flush:void 0===r?void 0:Mn(r,e,`${t} has member 'flush' that`),readableType:n,start:void 0===s?void 0:Dn(s,e,`${t} has member 'start' that`),transform:void 0===a?void 0:Fn(a,e,`${t} has member 'transform' that`),writableType:o}}function Mn(e,t,r){return z(e,r),r=>x(e,t,[r])}function Dn(e,t,r){return z(e,r),r=>S(e,t,[r])}function Fn(e,t,r){return z(e,r),(r,n)=>x(e,t,[r,n])}Object.defineProperties(qn.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(qn.prototype,t.toStringTag,{value:"CountQueuingStrategy",configurable:!0});class Wn{constructor(e={},t={},r={}){void 0===e&&(e=null);const n=gt(t,"Second parameter"),s=gt(r,"Third parameter"),a=Bn(e,"First parameter");if(void 0!==a.readableType)throw new RangeError("Invalid readableType specified");if(void 0!==a.writableType)throw new RangeError("Invalid writableType specified");const o=mt(s,0),i=yt(s),l=mt(n,1),c=yt(n);let u;Zn(this,h((e=>{u=e})),l,c,o,i),Qn(this,a),void 0!==a.start?u(a.start(this._transformStreamController)):u(void 0)}get readable(){if(!zn(this))throw ls("readable");return this._readable}get writable(){if(!zn(this))throw ls("writable");return this._writable}}function Zn(e,t,r,n,s,a){function o(){return t}function i(t){return ns(e,t)}function l(t){return ss(e,t)}function c(){return as(e)}function u(){return os(e)}function d(t){return Hn(e,t),f(void 0)}e._writable=Ct(o,i,c,l,r,n),e._readable=wn(o,u,d,s,a),e._backpressure=void 0,e._backpressureChangePromise=void 0,e._backpressureChangePromise_resolve=void 0,Vn(e,!0),e._transformStreamController=void 0}function zn(e){return!!a(e)&&!!Object.prototype.hasOwnProperty.call(e,"_transformStreamController")&&e instanceof Wn}function Un(e,t){Qr(e._readable._readableStreamController,t),Hn(e,t)}function Hn(e,t){Yn(e._transformStreamController),gr(e._writable._writableStreamController,t),e._backpressure&&Vn(e,!1)}function Vn(e,t){void 0!==e._backpressureChangePromise&&e._backpressureChangePromise_resolve(),e._backpressureChangePromise=h((t=>{e._backpressureChangePromise_resolve=t})),e._backpressure=t}Object.defineProperties(Wn.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(Wn.prototype,t.toStringTag,{value:"TransformStream",configurable:!0});class Kn{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Jn(this))throw is("desiredSize");return Yr(this._controlledTransformStream._readable._readableStreamController)}enqueue(e=void 0){if(!Jn(this))throw is("enqueue");Gn(this,e)}error(e=void 0){if(!Jn(this))throw is("error");es(this,e)}terminate(){if(!Jn(this))throw is("terminate");rs(this)}}function Jn(e){return!!a(e)&&!!Object.prototype.hasOwnProperty.call(e,"_controlledTransformStream")&&e instanceof Kn}function Xn(e,t,r,n){t._controlledTransformStream=e,e._transformStreamController=t,t._transformAlgorithm=r,t._flushAlgorithm=n}function Qn(e,t){const r=Object.create(Kn.prototype);let n=e=>{try{return Gn(r,e),f(void 0)}catch(e){return p(e)}},s=()=>f(void 0);void 0!==t.transform&&(n=e=>t.transform(e,r)),void 0!==t.flush&&(s=()=>t.flush(r)),Xn(e,r,n,s)}function Yn(e){e._transformAlgorithm=void 0,e._flushAlgorithm=void 0}function Gn(e,t){const r=e._controlledTransformStream,n=r._readable._readableStreamController;if(!en(n))throw new TypeError("Readable side is not in a state that permits enqueue");try{Xr(n,t)}catch(e){throw Hn(r,e),r._readable._storedError}Gr(n)!==r._backpressure&&Vn(r,!0)}function es(e,t){Un(e._controlledTransformStream,t)}function ts(e,t){return b(e._transformAlgorithm(t),void 0,(t=>{throw Un(e._controlledTransformStream,t),t}))}function rs(e){const t=e._controlledTransformStream;Jr(t._readable._readableStreamController),Hn(t,new TypeError("TransformStream terminated"))}function ns(e,t){const r=e._transformStreamController;return e._backpressure?b(e._backpressureChangePromise,(()=>{const n=e._writable;if("erroring"===n._state)throw n._storedError;return ts(r,t)})):ts(r,t)}function ss(e,t){return Un(e,t),f(void 0)}function as(e){const t=e._readable,r=e._transformStreamController,n=r._flushAlgorithm();return Yn(r),b(n,(()=>{if("errored"===t._state)throw t._storedError;Jr(t._readableStreamController)}),(r=>{throw Un(e,r),t._storedError}))}function os(e){return Vn(e,!1),e._backpressureChangePromise}function is(e){return new TypeError(`TransformStreamDefaultController.prototype.${e} can only be used on a TransformStreamDefaultController`)}function ls(e){return new TypeError(`TransformStream.prototype.${e} can only be used on a TransformStream`)}Object.defineProperties(Kn.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(Kn.prototype,t.toStringTag,{value:"TransformStreamDefaultController",configurable:!0}),e.ByteLengthQueuingStrategy=On,e.CountQueuingStrategy=qn,e.ReadableByteStreamController=Ae,e.ReadableStream=bn,e.ReadableStreamBYOBReader=dt,e.ReadableStreamBYOBRequest=Re,e.ReadableStreamDefaultController=zr,e.ReadableStreamDefaultReader=ae,e.TransformStream=Wn,e.TransformStreamDefaultController=Kn,e.WritableStream=At,e.WritableStreamDefaultController=ir,e.WritableStreamDefaultWriter=Xt,Object.defineProperty(e,"__esModule",{value:!0})}(lo.exports)),lo.exports))}try{const{Blob:e}=require("buffer");e&&!e.prototype.stream&&(e.prototype.stream=function(e){let t=0;const r=this;return new ReadableStream({type:"bytes",async pull(e){const n=r.slice(t,Math.min(r.size,t+65536)),s=await n.arrayBuffer();t+=s.byteLength,e.enqueue(new Uint8Array(s)),t===r.size&&e.close()}})})}catch(e){}
/*! fetch-blob. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */async function*co(e,t=!0){for(const r of e)if("stream"in r)yield*r.stream();else if(ArrayBuffer.isView(r))if(t){let e=r.byteOffset;const t=r.byteOffset+r.byteLength;for(;e!==t;){const n=Math.min(t-e,65536),s=r.buffer.slice(e,e+n);e+=s.byteLength,yield new Uint8Array(s)}}else yield r;else{let e=0,t=r;for(;e!==t.size;){const r=t.slice(e,Math.min(t.size,e+65536)),n=await r.arrayBuffer();e+=n.byteLength,yield new Uint8Array(n)}}}const uo=class e{#e=[];#t="";#r=0;#n="transparent";constructor(t=[],r={}){if("object"!=typeof t||null===t)throw new TypeError("Failed to construct 'Blob': The provided value cannot be converted to a sequence.");if("function"!=typeof t[Symbol.iterator])throw new TypeError("Failed to construct 'Blob': The object must have a callable @@iterator property.");if("object"!=typeof r&&"function"!=typeof r)throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary.");null===r&&(r={});const n=new TextEncoder;for(const r of t){let t;t=ArrayBuffer.isView(r)?new Uint8Array(r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength)):r instanceof ArrayBuffer?new Uint8Array(r.slice(0)):r instanceof e?r:n.encode(`${r}`),this.#r+=ArrayBuffer.isView(t)?t.byteLength:t.size,this.#e.push(t)}this.#n=`${void 0===r.endings?"transparent":r.endings}`;const s=void 0===r.type?"":String(r.type);this.#t=/^[\x20-\x7E]*$/.test(s)?s:""}get size(){return this.#r}get type(){return this.#t}async text(){const e=new TextDecoder;let t="";for await(const r of co(this.#e,!1))t+=e.decode(r,{stream:!0});return t+=e.decode(),t}async arrayBuffer(){const e=new Uint8Array(this.size);let t=0;for await(const r of co(this.#e,!1))e.set(r,t),t+=r.length;return e.buffer}stream(){const e=co(this.#e,!0);return new globalThis.ReadableStream({type:"bytes",async pull(t){const r=await e.next();r.done?t.close():t.enqueue(r.value)},async cancel(){await e.return()}})}slice(t=0,r=this.size,n=""){const{size:s}=this;let a=t<0?Math.max(s+t,0):Math.min(t,s),o=r<0?Math.max(s+r,0):Math.min(r,s);const i=Math.max(o-a,0),l=this.#e,c=[];let u=0;for(const e of l){if(u>=i)break;const t=ArrayBuffer.isView(e)?e.byteLength:e.size;if(a&&t<=a)a-=t,o-=t;else{let r;ArrayBuffer.isView(e)?(r=e.subarray(a,Math.min(t,o)),u+=r.byteLength):(r=e.slice(a,Math.min(t,o)),u+=r.size),o-=t,c.push(r),a=0}}const d=new e([],{type:String(n).toLowerCase()});return d.#r=i,d.#e=c,d}get[Symbol.toStringTag](){return"Blob"}static[Symbol.hasInstance](e){return e&&"object"==typeof e&&"function"==typeof e.constructor&&("function"==typeof e.stream||"function"==typeof e.arrayBuffer)&&/^(Blob|File)$/.test(e[Symbol.toStringTag])}};Object.defineProperties(uo.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});var ho=uo;const fo=class extends ho{#s=0;#a="";constructor(e,t,r={}){if(arguments.length<2)throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`);super(e,r),null===r&&(r={});const n=void 0===r.lastModified?Date.now():Number(r.lastModified);Number.isNaN(n)||(this.#s=n),this.#a=String(t)}get name(){return this.#a}get lastModified(){return this.#s}get[Symbol.toStringTag](){return"File"}static[Symbol.hasInstance](e){return!!e&&e instanceof ho&&/^(File)$/.test(e[Symbol.toStringTag])}};
/*! formdata-polyfill. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */
var{toStringTag:po,iterator:mo,hasInstance:yo}=Symbol,go=Math.random,_o="append,set,get,getAll,delete,keys,values,entries,forEach,constructor".split(","),bo=(e,t,r)=>(e+="",/^(Blob|File)$/.test(t&&t[po])?[(r=void 0!==r?r+"":"File"==t[po]?t.name:"blob",e),t.name!==r||"blob"==t[po]?new fo([t],r,t):t]:[e,t+""]),wo=(e,t)=>(t?e:e.replace(/\r?\n|\r/g,"\r\n")).replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22"),vo=(e,t,r)=>{if(t.length<r)throw new TypeError(`Failed to execute '${e}' on 'FormData': ${r} arguments required, but only ${t.length} present.`)};const So=class{#o=[];constructor(...e){if(e.length)throw new TypeError("Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.")}get[po](){return"FormData"}[mo](){return this.entries()}static[yo](e){return e&&"object"==typeof e&&"FormData"===e[po]&&!_o.some((t=>"function"!=typeof e[t]))}append(...e){vo("append",arguments,2),this.#o.push(bo(...e))}delete(e){vo("delete",arguments,1),e+="",this.#o=this.#o.filter((([t])=>t!==e))}get(e){vo("get",arguments,1),e+="";for(var t=this.#o,r=t.length,n=0;n<r;n++)if(t[n][0]===e)return t[n][1];return null}getAll(e,t){return vo("getAll",arguments,1),t=[],e+="",this.#o.forEach((r=>r[0]===e&&t.push(r[1]))),t}has(e){return vo("has",arguments,1),e+="",this.#o.some((t=>t[0]===e))}forEach(e,t){for(var[r,n]of(vo("forEach",arguments,1),this))e.call(t,n,r,this)}set(...e){vo("set",arguments,2);var t=[],r=!0;e=bo(...e),this.#o.forEach((n=>{n[0]===e[0]?r&&(r=!t.push(e)):t.push(n)})),r&&t.push(e),this.#o=t}*entries(){yield*this.#o}*keys(){for(var[e]of this)yield e}*values(){for(var[,e]of this)yield e}};class xo extends Error{constructor(e,t){super(e),Error.captureStackTrace(this,this.constructor),this.type=t}get name(){return this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}}class ko extends xo{constructor(e,t,r){super(e,t),r&&(this.code=this.errno=r.code,this.erroredSysCall=r.syscall)}}const To=Symbol.toStringTag,Eo=e=>"object"==typeof e&&"function"==typeof e.append&&"function"==typeof e.delete&&"function"==typeof e.get&&"function"==typeof e.getAll&&"function"==typeof e.has&&"function"==typeof e.set&&"function"==typeof e.sort&&"URLSearchParams"===e[To],Ro=e=>e&&"object"==typeof e&&"function"==typeof e.arrayBuffer&&"string"==typeof e.type&&"function"==typeof e.stream&&"function"==typeof e.constructor&&/^(Blob|File)$/.test(e[To]),Ao=o.promisify(s.pipeline),Po=Symbol("Body internals");class Co{constructor(e,{size:t=0}={}){let r=null;null===e?e=null:Eo(e)?e=a.Buffer.from(e.toString()):Ro(e)||a.Buffer.isBuffer(e)||(o.types.isAnyArrayBuffer(e)?e=a.Buffer.from(e):ArrayBuffer.isView(e)?e=a.Buffer.from(e.buffer,e.byteOffset,e.byteLength):e instanceof s||(e instanceof So?(e=function(e,t=ho){var r=`${go()}${go()}`.replace(/\./g,"").slice(-28).padStart(32,"-"),n=[],s=`--${r}\r\nContent-Disposition: form-data; name="`;return e.forEach(((e,t)=>"string"==typeof e?n.push(s+wo(t)+`"\r\n\r\n${e.replace(/\r(?!\n)|(?<!\r)\n/g,"\r\n")}\r\n`):n.push(s+wo(t)+`"; filename="${wo(e.name,1)}"\r\nContent-Type: ${e.type||"application/octet-stream"}\r\n\r\n`,e,"\r\n"))),n.push(`--${r}--`),new t(n,{type:"multipart/form-data; boundary="+r})}(e),r=e.type.split("=")[1]):e=a.Buffer.from(String(e))));let n=e;a.Buffer.isBuffer(e)?n=s.Readable.from(e):Ro(e)&&(n=s.Readable.from(e.stream())),this[Po]={body:e,stream:n,boundary:r,disturbed:!1,error:null},this.size=t,e instanceof s&&e.on("error",(e=>{const t=e instanceof xo?e:new ko(`Invalid response body while trying to fetch ${this.url}: ${e.message}`,"system",e);this[Po].error=t}))}get body(){return this[Po].stream}get bodyUsed(){return this[Po].disturbed}async arrayBuffer(){const{buffer:e,byteOffset:t,byteLength:r}=await Oo(this);return e.slice(t,t+r)}async formData(){const e=this.headers.get("content-type");if(e.startsWith("application/x-www-form-urlencoded")){const e=new So,t=new URLSearchParams(await this.text());for(const[r,n]of t)e.append(r,n);return e}const{toFormData:t}=await Promise.resolve().then((function(){return ui}));return t(this.body,e)}async blob(){const e=this.headers&&this.headers.get("content-type")||this[Po].body&&this[Po].body.type||"",t=await this.arrayBuffer();return new ho([t],{type:e})}async json(){const e=await this.text();return JSON.parse(e)}async text(){const e=await Oo(this);return(new TextDecoder).decode(e)}buffer(){return Oo(this)}}async function Oo(e){if(e[Po].disturbed)throw new TypeError(`body used already for: ${e.url}`);if(e[Po].disturbed=!0,e[Po].error)throw e[Po].error;const{body:t}=e;if(null===t)return a.Buffer.alloc(0);if(!(t instanceof s))return a.Buffer.alloc(0);const r=[];let n=0;try{for await(const s of t){if(e.size>0&&n+s.length>e.size){const r=new ko(`content size at ${e.url} over limit: ${e.size}`,"max-size");throw t.destroy(r),r}n+=s.length,r.push(s)}}catch(t){throw t instanceof xo?t:new ko(`Invalid response body while trying to fetch ${e.url}: ${t.message}`,"system",t)}if(!0!==t.readableEnded&&!0!==t._readableState.ended)throw new ko(`Premature close of server response while trying to fetch ${e.url}`);try{return r.every((e=>"string"==typeof e))?a.Buffer.from(r.join("")):a.Buffer.concat(r,n)}catch(t){throw new ko(`Could not create Buffer from response body for ${e.url}: ${t.message}`,"system",t)}}Co.prototype.buffer=o.deprecate(Co.prototype.buffer,"Please use 'response.arrayBuffer()' instead of 'response.buffer()'","node-fetch#buffer"),Object.defineProperties(Co.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0},data:{get:o.deprecate((()=>{}),"data doesn't exist, use json(), text(), arrayBuffer(), or body instead","https://github.com/node-fetch/node-fetch/issues/1000 (response)")}});const jo=(e,t)=>{let r,n,{body:a}=e[Po];if(e.bodyUsed)throw new Error("cannot clone body after it is used");return a instanceof s&&"function"!=typeof a.getBoundary&&(r=new s.PassThrough({highWaterMark:t}),n=new s.PassThrough({highWaterMark:t}),a.pipe(r),a.pipe(n),e[Po].stream=r,a=n),a},Io=o.deprecate((e=>e.getBoundary()),"form-data doesn't follow the spec and requires special treatment. Use alternative package","https://github.com/node-fetch/node-fetch/issues/1167"),$o=(e,t)=>null===e?null:"string"==typeof e?"text/plain;charset=UTF-8":Eo(e)?"application/x-www-form-urlencoded;charset=UTF-8":Ro(e)?e.type||null:a.Buffer.isBuffer(e)||o.types.isAnyArrayBuffer(e)||ArrayBuffer.isView(e)?null:e instanceof So?`multipart/form-data; boundary=${t[Po].boundary}`:e&&"function"==typeof e.getBoundary?`multipart/form-data;boundary=${Io(e)}`:e instanceof s?null:"text/plain;charset=UTF-8",qo="function"==typeof t.validateHeaderName?t.validateHeaderName:e=>{if(!/^[\^`\-\w!#$%&'*+.|~]+$/.test(e)){const t=new TypeError(`Header name must be a valid HTTP token [${e}]`);throw Object.defineProperty(t,"code",{value:"ERR_INVALID_HTTP_TOKEN"}),t}},No="function"==typeof t.validateHeaderValue?t.validateHeaderValue:(e,t)=>{if(/[^\t\u0020-\u007E\u0080-\u00FF]/.test(t)){const t=new TypeError(`Invalid character in header content ["${e}"]`);throw Object.defineProperty(t,"code",{value:"ERR_INVALID_CHAR"}),t}};let Lo=class e extends URLSearchParams{constructor(t){let r=[];if(t instanceof e){const e=t.raw();for(const[t,n]of Object.entries(e))r.push(...n.map((e=>[t,e])))}else if(null==t);else{if("object"!=typeof t||o.types.isBoxedPrimitive(t))throw new TypeError("Failed to construct 'Headers': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)");{const e=t[Symbol.iterator];if(null==e)r.push(...Object.entries(t));else{if("function"!=typeof e)throw new TypeError("Header pairs must be iterable");r=[...t].map((e=>{if("object"!=typeof e||o.types.isBoxedPrimitive(e))throw new TypeError("Each header pair must be an iterable object");return[...e]})).map((e=>{if(2!==e.length)throw new TypeError("Each header pair must be a name/value tuple");return[...e]}))}}}return r=r.length>0?r.map((([e,t])=>(qo(e),No(e,String(t)),[String(e).toLowerCase(),String(t)]))):void 0,super(r),new Proxy(this,{get(e,t,r){switch(t){case"append":case"set":return(r,n)=>(qo(r),No(r,String(n)),URLSearchParams.prototype[t].call(e,String(r).toLowerCase(),String(n)));case"delete":case"has":case"getAll":return r=>(qo(r),URLSearchParams.prototype[t].call(e,String(r).toLowerCase()));case"keys":return()=>(e.sort(),new Set(URLSearchParams.prototype.keys.call(e)).keys());default:return Reflect.get(e,t,r)}}})}get[Symbol.toStringTag](){return this.constructor.name}toString(){return Object.prototype.toString.call(this)}get(e){const t=this.getAll(e);if(0===t.length)return null;let r=t.join(", ");return/^content-encoding$/i.test(e)&&(r=r.toLowerCase()),r}forEach(e,t=void 0){for(const r of this.keys())Reflect.apply(e,t,[this.get(r),r,this])}*values(){for(const e of this.keys())yield this.get(e)}*entries(){for(const e of this.keys())yield[e,this.get(e)]}[Symbol.iterator](){return this.entries()}raw(){return[...this.keys()].reduce(((e,t)=>(e[t]=this.getAll(t),e)),{})}[Symbol.for("nodejs.util.inspect.custom")](){return[...this.keys()].reduce(((e,t)=>{const r=this.getAll(t);return e[t]="host"===t?r[0]:r.length>1?r:r[0],e}),{})}};Object.defineProperties(Lo.prototype,["get","entries","forEach","values"].reduce(((e,t)=>(e[t]={enumerable:!0},e)),{}));const Bo=new Set([301,302,303,307,308]),Mo=e=>Bo.has(e),Do=Symbol("Response internals");let Fo=class e extends Co{constructor(e=null,t={}){super(e,t);const r=null!=t.status?t.status:200,n=new Lo(t.headers);if(null!==e&&!n.has("Content-Type")){const t=$o(e,this);t&&n.append("Content-Type",t)}this[Do]={type:"default",url:t.url,status:r,statusText:t.statusText||"",headers:n,counter:t.counter,highWaterMark:t.highWaterMark}}get type(){return this[Do].type}get url(){return this[Do].url||""}get status(){return this[Do].status}get ok(){return this[Do].status>=200&&this[Do].status<300}get redirected(){return this[Do].counter>0}get statusText(){return this[Do].statusText}get headers(){return this[Do].headers}get highWaterMark(){return this[Do].highWaterMark}clone(){return new e(jo(this,this.highWaterMark),{type:this.type,url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok,redirected:this.redirected,size:this.size,highWaterMark:this.highWaterMark})}static redirect(t,r=302){if(!Mo(r))throw new RangeError('Failed to execute "redirect" on "response": Invalid status code');return new e(null,{headers:{location:new URL(t).toString()},status:r})}static error(){const t=new e(null,{status:0,statusText:""});return t[Do].type="error",t}static json(t=void 0,r={}){const n=JSON.stringify(t);if(void 0===n)throw new TypeError("data is not JSON serializable");const s=new Lo(r&&r.headers);return s.has("content-type")||s.set("content-type","application/json"),new e(n,{...r,headers:s})}get[Symbol.toStringTag](){return"Response"}};Object.defineProperties(Fo.prototype,{type:{enumerable:!0},url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},redirected:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}});function Wo(e,t=!1){return null==e?"no-referrer":(e=new URL(e),/^(about|blob|data):$/.test(e.protocol)?"no-referrer":(e.username="",e.password="",e.hash="",t&&(e.pathname="",e.search=""),e))}const Zo=new Set(["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"]);function zo(e){return!!/^about:(blank|srcdoc)$/.test(e)||("data:"===e.protocol||(!!/^(blob|filesystem):$/.test(e.protocol)||function(e){if(/^(http|ws)s:$/.test(e.protocol))return!0;const t=e.host.replace(/(^\[)|(]$)/g,""),r=l.isIP(t);return!(4!==r||!/^127\./.test(t))||!(6!==r||!/^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(t))||"localhost"!==e.host&&!e.host.endsWith(".localhost")&&"file:"===e.protocol}(e)))}const Uo=Symbol("Request internals"),Ho=e=>"object"==typeof e&&"object"==typeof e[Uo],Vo=o.deprecate((()=>{}),".data is not a valid RequestInit property, use .body instead","https://github.com/node-fetch/node-fetch/issues/1000 (request)");let Ko=class e extends Co{constructor(e,t={}){let r;if(Ho(e)?r=new URL(e.url):(r=new URL(e),e={}),""!==r.username||""!==r.password)throw new TypeError(`${r} is an url with embedded credentials.`);let n=t.method||e.method||"GET";if(/^(delete|get|head|options|post|put)$/i.test(n)&&(n=n.toUpperCase()),!Ho(t)&&"data"in t&&Vo(),(null!=t.body||Ho(e)&&null!==e.body)&&("GET"===n||"HEAD"===n))throw new TypeError("Request with GET/HEAD method cannot have body");const s=t.body?t.body:Ho(e)&&null!==e.body?jo(e):null;super(s,{size:t.size||e.size||0});const a=new Lo(t.headers||e.headers||{});if(null!==s&&!a.has("Content-Type")){const e=$o(s,this);e&&a.set("Content-Type",e)}let o=Ho(e)?e.signal:null;if("signal"in t&&(o=t.signal),null!=o&&("object"!=typeof(i=o)||"AbortSignal"!==i[To]&&"EventTarget"!==i[To]))throw new TypeError("Expected signal to be an instanceof AbortSignal or EventTarget");var i;let l=null==t.referrer?e.referrer:t.referrer;if(""===l)l="no-referrer";else if(l){const e=new URL(l);l=/^about:(\/\/)?client$/.test(e)?"client":e}else l=void 0;this[Uo]={method:n,redirect:t.redirect||e.redirect||"follow",headers:a,parsedURL:r,signal:o,referrer:l},this.follow=void 0===t.follow?void 0===e.follow?20:e.follow:t.follow,this.compress=void 0===t.compress?void 0===e.compress||e.compress:t.compress,this.counter=t.counter||e.counter||0,this.agent=t.agent||e.agent,this.highWaterMark=t.highWaterMark||e.highWaterMark||16384,this.insecureHTTPParser=t.insecureHTTPParser||e.insecureHTTPParser||!1,this.referrerPolicy=t.referrerPolicy||e.referrerPolicy||""}get method(){return this[Uo].method}get url(){return i.format(this[Uo].parsedURL)}get headers(){return this[Uo].headers}get redirect(){return this[Uo].redirect}get signal(){return this[Uo].signal}get referrer(){return"no-referrer"===this[Uo].referrer?"":"client"===this[Uo].referrer?"about:client":this[Uo].referrer?this[Uo].referrer.toString():void 0}get referrerPolicy(){return this[Uo].referrerPolicy}set referrerPolicy(e){this[Uo].referrerPolicy=function(e){if(!Zo.has(e))throw new TypeError(`Invalid referrerPolicy: ${e}`);return e}(e)}clone(){return new e(this)}get[Symbol.toStringTag](){return"Request"}};Object.defineProperties(Ko.prototype,{method:{enumerable:!0},url:{enumerable:!0},headers:{enumerable:!0},redirect:{enumerable:!0},clone:{enumerable:!0},signal:{enumerable:!0},referrer:{enumerable:!0},referrerPolicy:{enumerable:!0}});const Jo=e=>{const{parsedURL:t}=e[Uo],r=new Lo(e[Uo].headers);r.has("Accept")||r.set("Accept","*/*");let n=null;if(null===e.body&&/^(post|put)$/i.test(e.method)&&(n="0"),null!==e.body){const t=(e=>{const{body:t}=e[Po];return null===t?0:Ro(t)?t.size:a.Buffer.isBuffer(t)?t.length:t&&"function"==typeof t.getLengthSync&&t.hasKnownLength&&t.hasKnownLength()?t.getLengthSync():null})(e);"number"!=typeof t||Number.isNaN(t)||(n=String(t))}n&&r.set("Content-Length",n),""===e.referrerPolicy&&(e.referrerPolicy="strict-origin-when-cross-origin"),e.referrer&&"no-referrer"!==e.referrer?e[Uo].referrer=function(e,{referrerURLCallback:t,referrerOriginCallback:r}={}){if("no-referrer"===e.referrer||""===e.referrerPolicy)return null;const n=e.referrerPolicy;if("about:client"===e.referrer)return"no-referrer";const s=e.referrer;let a=Wo(s),o=Wo(s,!0);a.toString().length>4096&&(a=o),t&&(a=t(a)),r&&(o=r(o));const i=new URL(e.url);switch(n){case"no-referrer":return"no-referrer";case"origin":return o;case"unsafe-url":return a;case"strict-origin":return zo(a)&&!zo(i)?"no-referrer":o.toString();case"strict-origin-when-cross-origin":return a.origin===i.origin?a:zo(a)&&!zo(i)?"no-referrer":o;case"same-origin":return a.origin===i.origin?a:"no-referrer";case"origin-when-cross-origin":return a.origin===i.origin?a:o;case"no-referrer-when-downgrade":return zo(a)&&!zo(i)?"no-referrer":a;default:throw new TypeError(`Invalid referrerPolicy: ${n}`)}}(e):e[Uo].referrer="no-referrer",e[Uo].referrer instanceof URL&&r.set("Referer",e.referrer),r.has("User-Agent")||r.set("User-Agent","node-fetch"),e.compress&&!r.has("Accept-Encoding")&&r.set("Accept-Encoding","gzip, deflate, br");let{agent:s}=e;"function"==typeof s&&(s=s(t));const o=(e=>{if(e.search)return e.search;const t=e.href.length-1,r=e.hash||("#"===e.href[t]?"#":"");return"?"===e.href[t-r.length]?"?":""})(t);return{parsedURL:t,options:{path:t.pathname+o,method:e.method,headers:r[Symbol.for("nodejs.util.inspect.custom")](),insecureHTTPParser:e.insecureHTTPParser,agent:s}}};class Xo extends xo{constructor(e,t="aborted"){super(e,t)}}
/*! node-domexception. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */if(!globalThis.DOMException)try{const{MessageChannel:e}=require("worker_threads"),t=(new e).port1,r=new ArrayBuffer;t.postMessage(r,[r,r])}catch(e){"DOMException"===e.constructor.name&&(globalThis.DOMException=e.constructor)}const Qo=new Set(["data:","http:","https:"]);async function Yo(e,o){return new Promise(((i,l)=>{const c=new Ko(e,o),{parsedURL:u,options:d}=Jo(c);if(!Qo.has(u.protocol))throw new TypeError(`node-fetch cannot load ${e}. URL scheme "${u.protocol.replace(/:$/,"")}" is not supported.`);if("data:"===u.protocol){const e=function(e){if(!/^data:/i.test(e))throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")');const t=(e=e.replace(/\r?\n/g,"")).indexOf(",");if(-1===t||t<=4)throw new TypeError("malformed data: URI");const r=e.substring(5,t).split(";");let n="",s=!1;const a=r[0]||"text/plain";let o=a;for(let e=1;e<r.length;e++)"base64"===r[e]?s=!0:r[e]&&(o+=`;${r[e]}`,0===r[e].indexOf("charset=")&&(n=r[e].substring(8)));r[0]||n.length||(o+=";charset=US-ASCII",n="US-ASCII");const i=s?"base64":"ascii",l=unescape(e.substring(t+1)),c=Buffer.from(l,i);return c.type=a,c.typeFull=o,c.charset=n,c}(c.url),t=new Fo(e,{headers:{"Content-Type":e.typeFull}});return void i(t)}const h=("https:"===u.protocol?r:t).request,{signal:f}=c;let p=null;const m=()=>{const e=new Xo("The operation was aborted.");l(e),c.body&&c.body instanceof s.Readable&&c.body.destroy(e),p&&p.body&&p.body.emit("error",e)};if(f&&f.aborted)return void m();const y=()=>{m(),_()},g=h(u.toString(),d);f&&f.addEventListener("abort",y);const _=()=>{g.abort(),f&&f.removeEventListener("abort",y)};g.on("error",(e=>{l(new ko(`request to ${c.url} failed, reason: ${e.message}`,"system",e)),_()})),function(e,t){const r=a.Buffer.from("0\r\n\r\n");let n,s=!1,o=!1;e.on("response",(e=>{const{headers:t}=e;s="chunked"===t["transfer-encoding"]&&!t["content-length"]})),e.on("socket",(i=>{const l=()=>{if(s&&!o){const e=new Error("Premature close");e.code="ERR_STREAM_PREMATURE_CLOSE",t(e)}},c=e=>{o=0===a.Buffer.compare(e.slice(-5),r),!o&&n&&(o=0===a.Buffer.compare(n.slice(-3),r.slice(0,3))&&0===a.Buffer.compare(e.slice(-2),r.slice(3))),n=e};i.prependListener("close",l),i.on("data",c),e.on("close",(()=>{i.removeListener("close",l),i.removeListener("data",c)}))}))}(g,(e=>{p&&p.body&&p.body.destroy(e)})),process.version<"v14"&&g.on("socket",(e=>{let t;e.prependListener("end",(()=>{t=e._eventsCount})),e.prependListener("close",(r=>{if(p&&t<e._eventsCount&&!r){const e=new Error("Premature close");e.code="ERR_STREAM_PREMATURE_CLOSE",p.body.emit("error",e)}}))})),g.on("response",(e=>{g.setTimeout(0);const t=function(e=[]){return new Lo(e.reduce(((e,t,r,n)=>(r%2==0&&e.push(n.slice(r,r+2)),e)),[]).filter((([e,t])=>{try{return qo(e),No(e,String(t)),!0}catch{return!1}})))}(e.rawHeaders);if(Mo(e.statusCode)){const n=t.get("Location");let a=null;try{a=null===n?null:new URL(n,c.url)}catch{if("manual"!==c.redirect)return l(new ko(`uri requested responds with an invalid redirect URL: ${n}`,"invalid-redirect")),void _()}switch(c.redirect){case"error":return l(new ko(`uri requested responds with a redirect, redirect mode is set to error: ${c.url}`,"no-redirect")),void _();case"manual":break;case"follow":{if(null===a)break;if(c.counter>=c.follow)return l(new ko(`maximum redirect reached at: ${c.url}`,"max-redirect")),void _();const n={headers:new Lo(c.headers),follow:c.follow,counter:c.counter+1,agent:c.agent,compress:c.compress,method:c.method,body:jo(c),signal:c.signal,size:c.size,referrer:c.referrer,referrerPolicy:c.referrerPolicy};if(!((e,t)=>{const r=new URL(t).hostname,n=new URL(e).hostname;return r===n||r.endsWith(`.${n}`)})(c.url,a)||(r=c.url,new URL(a).protocol!==new URL(r).protocol))for(const e of["authorization","www-authenticate","cookie","cookie2"])n.headers.delete(e);if(303!==e.statusCode&&c.body&&o.body instanceof s.Readable)return l(new ko("Cannot follow redirect with body being a readable stream","unsupported-redirect")),void _();303!==e.statusCode&&(301!==e.statusCode&&302!==e.statusCode||"POST"!==c.method)||(n.method="GET",n.body=void 0,n.headers.delete("content-length"));const u=function(e){const t=(e.get("referrer-policy")||"").split(/[,\s]+/);let r="";for(const e of t)e&&Zo.has(e)&&(r=e);return r}(t);return u&&(n.referrerPolicy=u),i(Yo(new Ko(a,n))),void _()}default:return l(new TypeError(`Redirect option '${c.redirect}' is not a valid value of RequestRedirect`))}}var r;f&&e.once("end",(()=>{f.removeEventListener("abort",y)}));let a=s.pipeline(e,new s.PassThrough,(e=>{e&&l(e)}));process.version<"v12.10"&&e.on("aborted",y);const u={url:c.url,status:e.statusCode,statusText:e.statusMessage,headers:t,size:c.size,counter:c.counter,highWaterMark:c.highWaterMark},d=t.get("Content-Encoding");if(!c.compress||"HEAD"===c.method||null===d||204===e.statusCode||304===e.statusCode)return p=new Fo(a,u),void i(p);const h={flush:n.Z_SYNC_FLUSH,finishFlush:n.Z_SYNC_FLUSH};if("gzip"===d||"x-gzip"===d)return a=s.pipeline(a,n.createGunzip(h),(e=>{e&&l(e)})),p=new Fo(a,u),void i(p);if("deflate"===d||"x-deflate"===d){const t=s.pipeline(e,new s.PassThrough,(e=>{e&&l(e)}));return t.once("data",(e=>{a=8==(15&e[0])?s.pipeline(a,n.createInflate(),(e=>{e&&l(e)})):s.pipeline(a,n.createInflateRaw(),(e=>{e&&l(e)})),p=new Fo(a,u),i(p)})),void t.once("end",(()=>{p||(p=new Fo(a,u),i(p))}))}if("br"===d)return a=s.pipeline(a,n.createBrotliDecompress(),(e=>{e&&l(e)})),p=new Fo(a,u),void i(p);p=new Fo(a,u),i(p)})),(async(e,{body:t})=>{null===t?e.end():await Ao(t,e)})(g,c).catch(l)}))}class Go{constructor(e,t,r=void 0){this.api_url=r||"https://api.stability.ai",this.api_key=e,this.engine=t}async txt2img(e,t={}){const r=`${this.api_url}/v1/generation/${this.engine}/text-to-image`,n=await Yo(r,{method:"POST",headers:{"Content-Type":"application/json",Accept:"image/png",Authorization:"Bearer "+this.api_key},body:JSON.stringify({clip_guidance_preset:"FAST_BLUE",samples:1,width:t.width??512,height:t.height??512,cfg_scale:t.cfg_scale??7,steps:t.steps??50,text_prompts:[{text:e,weight:1},{text:t.negative??"blurry, bad",weight:-1}],style_preset:t.style??"cinematic"})});if(!n.ok)throw new Error(`Non-200 response: ${await n.text()}`);return n}}const ei=[{name:"configuration",config:({init:e},{services:t,database:r,getSchema:n})=>{const{FieldsService:s}=t;async function a(e,t){await t.readOne(e.collection,e.field).catch((()=>!1))||await t.createField(e.collection,e)}e("routes.custom.after",(async()=>{const e=await n(),t=new s({knex:r,schema:e});await a(to,t),await a(ro,t),await a(no,t),await a(so,t)}))}}],ti=[{name:"dall-e-operation",config:oo},{name:"stable-diffusion-operation",config:{id:"stable-diffusion-operation",handler:async({prompt:t,style:r="cinematic",engine:n="stable-diffusion-512-v2-1",api_key:s,width:a=512,height:o=512,cfg_scale:i=7,steps:l=50,negative:c="blurry, bad",location:u="local"},{services:d,database:h,getSchema:f})=>{const{FilesService:p,SettingsService:m}=d,y=await f(),g=new m({schema:y,knex:h}),_=new p({schema:y,knex:h}),b=await ao(g,no.field,s),w=new Go(b,n),v=await w.txt2img(t,{width:a,height:o,cfg_scale:i,steps:l,style:r,negative:c});return{id:await _.uploadOne(v.body,{type:"image/png",filename_download:e.randomUUID()+".png",storage:u||"local"})}}}},{name:"chatgpt-operation",config:{id:"chatgpt-operation",handler:async({system:e,text:t,engine:r="gpt-3.5-turbo",api_key:n,base_url:s,amodel:a,temperature:o=.5,max_tokens:i=2048,top_p:l=1,frequency_penalty:c=0,presence_penalty:u=0,json_mode:d=!1,stream:h=!1,thread:f=!1},{services:p,database:m,getSchema:y})=>{const{SettingsService:g}=p,_=new g({schema:await y(),knex:m}),b=await ao(_,ro.field,n),w=new eo({apiKey:b,baseURL:s??"https://api.openai.com/v1"}),v=[];let S=e??"";d&&(S+="You are a helpful assistant designed to output JSON."),v.push({role:"system",content:S}),f&&v.push(...f),t&&v.push({role:"user",content:t});let x={model:a??r,messages:[...v],stream:h??!1,temperature:o??.6,max_tokens:i??2048,top_p:l??1,frequency_penalty:c??0,presence_penalty:u??0,n:1};d&&(x.response_format={type:"json_object"},delete x.max_tokens);const k=await w.chat.completions.create(x);if(h){let e="";if(h){let t="";for await(const e of k){const r=e.choices[0]?.delta?.content||"";r&&(t+=r)}e=d&&"string"==typeof t?JSON.parse(t):t}return{response:e}}return{response:k.choices[0].message.content}}}},{name:"whisper-operation",config:{id:"whisper-operation",handler:async({asset_id:e,api_key:t,translate:r=!1,prompt:n,temperature:s=0},{services:a,database:o,getSchema:i})=>{const{FilesService:l,SettingsService:c,AssetsService:u}=a,d=await i(),h=new c({schema:d,knex:o}),f=new l({schema:d,knex:o}),p=new u({schema:d,knex:o}),m=await ao(h,ro.field,t),y=new eo({apiKey:m});n="undefined"===n?void 0:n;const g=await f.readOne(e);if(!g)throw new Error("file not found");if(g.filesize>25e6)throw new Error("file is more than the 25mb limit!");const _=["audio/mpeg","video/mpeg","video/mp4","audio/x-wav","video/webm","audio/webm"];if(!_.includes(g.type))throw new Error(`mime "${g.type}" is allowed (${_.join(", ")})`);const b=["mp3","mp4","mpeg","mpga","m4a","wav","webm"];if(!b.some((e=>g.filename_download?.endsWith(e))))throw new Error(`extension is not one of ${b.join(", ")}`);const w=await p.getAsset(e,{});if(r){return{response:(await y.audio.translations.create({file:w.stream,model:"whisper-1",prompt:n,response_format:"json",temperature:s})).text}}return{response:(await y.audio.transcriptions.create({file:w.stream,model:"whisper-1",prompt:n,response_format:"json",temperature:s})).text}}}}];let ri=0;const ni={START_BOUNDARY:ri++,HEADER_FIELD_START:ri++,HEADER_FIELD:ri++,HEADER_VALUE_START:ri++,HEADER_VALUE:ri++,HEADER_VALUE_ALMOST_DONE:ri++,HEADERS_ALMOST_DONE:ri++,PART_DATA_START:ri++,PART_DATA:ri++,END:ri++};let si=1;const ai=si,oi=si*=2,ii=e=>32|e,li=()=>{};class ci{constructor(e){this.index=0,this.flags=0,this.onHeaderEnd=li,this.onHeaderField=li,this.onHeadersEnd=li,this.onHeaderValue=li,this.onPartBegin=li,this.onPartData=li,this.onPartEnd=li,this.boundaryChars={},e="\r\n--"+e;const t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r),this.boundaryChars[t[r]]=!0;this.boundary=t,this.lookbehind=new Uint8Array(this.boundary.length+8),this.state=ni.START_BOUNDARY}write(e){let t=0;const r=e.length;let n=this.index,{lookbehind:s,boundary:a,boundaryChars:o,index:i,state:l,flags:c}=this;const u=this.boundary.length,d=u-1,h=e.length;let f,p;const m=e=>{this[e+"Mark"]=t},y=e=>{delete this[e+"Mark"]},g=(e,t,r,n)=>{void 0!==t&&t===r||this[e](n&&n.subarray(t,r))},_=(r,n)=>{const s=r+"Mark";s in this&&(n?(g(r,this[s],t,e),delete this[s]):(g(r,this[s],e.length,e),this[s]=0))};for(t=0;t<r;t++)switch(f=e[t],l){case ni.START_BOUNDARY:if(i===a.length-2){if(45===f)c|=oi;else if(13!==f)return;i++;break}if(i-1==a.length-2){if(c&oi&&45===f)l=ni.END,c=0;else{if(c&oi||10!==f)return;i=0,g("onPartBegin"),l=ni.HEADER_FIELD_START}break}f!==a[i+2]&&(i=-2),f===a[i+2]&&i++;break;case ni.HEADER_FIELD_START:l=ni.HEADER_FIELD,m("onHeaderField"),i=0;case ni.HEADER_FIELD:if(13===f){y("onHeaderField"),l=ni.HEADERS_ALMOST_DONE;break}if(i++,45===f)break;if(58===f){if(1===i)return;_("onHeaderField",!0),l=ni.HEADER_VALUE_START;break}if(p=ii(f),p<97||p>122)return;break;case ni.HEADER_VALUE_START:if(32===f)break;m("onHeaderValue"),l=ni.HEADER_VALUE;case ni.HEADER_VALUE:13===f&&(_("onHeaderValue",!0),g("onHeaderEnd"),l=ni.HEADER_VALUE_ALMOST_DONE);break;case ni.HEADER_VALUE_ALMOST_DONE:if(10!==f)return;l=ni.HEADER_FIELD_START;break;case ni.HEADERS_ALMOST_DONE:if(10!==f)return;g("onHeadersEnd"),l=ni.PART_DATA_START;break;case ni.PART_DATA_START:l=ni.PART_DATA,m("onPartData");case ni.PART_DATA:if(n=i,0===i){for(t+=d;t<h&&!(e[t]in o);)t+=u;t-=d,f=e[t]}if(i<a.length)a[i]===f?(0===i&&_("onPartData",!0),i++):i=0;else if(i===a.length)i++,13===f?c|=ai:45===f?c|=oi:i=0;else if(i-1===a.length)if(c&ai){if(i=0,10===f){c&=~ai,g("onPartEnd"),g("onPartBegin"),l=ni.HEADER_FIELD_START;break}}else c&oi&&45===f?(g("onPartEnd"),l=ni.END,c=0):i=0;if(i>0)s[i-1]=f;else if(n>0){const e=new Uint8Array(s.buffer,s.byteOffset,s.byteLength);g("onPartData",0,n,e),n=0,m("onPartData"),t--}break;case ni.END:break;default:throw new Error(`Unexpected state entered: ${l}`)}_("onHeaderField"),_("onHeaderValue"),_("onPartData"),this.index=i,this.state=l,this.flags=c}end(){if(this.state===ni.HEADER_FIELD_START&&0===this.index||this.state===ni.PART_DATA&&this.index===this.boundary.length)this.onPartEnd();else if(this.state!==ni.END)throw new Error("MultipartParser.end(): stream ended unexpectedly")}}var ui=Object.freeze({__proto__:null,toFormData:async function(e,t){if(!/multipart/i.test(t))throw new TypeError("Failed to fetch");const r=t.match(/boundary=(?:"([^"]+)"|([^;]+))/i);if(!r)throw new TypeError("no or bad content-type header, no multipart boundary");const n=new ci(r[1]||r[2]);let s,a,o,i,l,c;const u=[],d=new So,h=e=>{o+=y.decode(e,{stream:!0})},f=e=>{u.push(e)},p=()=>{const e=new fo(u,c,{type:l});d.append(i,e)},m=()=>{d.append(i,o)},y=new TextDecoder("utf-8");y.decode(),n.onPartBegin=function(){n.onPartData=h,n.onPartEnd=m,s="",a="",o="",i="",l="",c=null,u.length=0},n.onHeaderField=function(e){s+=y.decode(e,{stream:!0})},n.onHeaderValue=function(e){a+=y.decode(e,{stream:!0})},n.onHeaderEnd=function(){if(a+=y.decode(),s=s.toLowerCase(),"content-disposition"===s){const e=a.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);e&&(i=e[2]||e[3]||""),c=function(e){const t=e.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i);if(!t)return;const r=t[2]||t[3]||"";let n=r.slice(r.lastIndexOf("\\")+1);return n=n.replace(/%22/g,'"'),n=n.replace(/&#(\d{4});/g,((e,t)=>String.fromCharCode(t))),n}(a),c&&(n.onPartData=f,n.onPartEnd=p)}else"content-type"===s&&(l=a);a="",s=""};for await(const t of e)n.write(t);return n.end(),d}});exports.endpoints=[],exports.hooks=ei,exports.operations=ti;