@chaos-maker/core 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,110 @@
1
- (function(E,b){typeof exports=="object"&&typeof module<"u"?b(exports):typeof define=="function"&&define.amd?define(["exports"],b):(E=typeof globalThis<"u"?globalThis:E||self,b(E.ChaosMaker={}))})(this,(function(E){"use strict";var Ss=Object.defineProperty;var Ts=(E,b,re)=>b in E?Ss(E,b,{enumerable:!0,configurable:!0,writable:!0,value:re}):E[b]=re;var Z=(E,b,re)=>Ts(E,typeof b!="symbol"?b+"":b,re);var b;(function(s){s.assertEqual=n=>{};function e(n){}s.assertIs=e;function t(n){throw new Error}s.assertNever=t,s.arrayToEnum=n=>{const a={};for(const i of n)a[i]=i;return a},s.getValidEnumValues=n=>{const a=s.objectKeys(n).filter(o=>typeof n[n[o]]!="number"),i={};for(const o of a)i[o]=n[o];return s.objectValues(i)},s.objectValues=n=>s.objectKeys(n).map(function(a){return n[a]}),s.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{const a=[];for(const i in n)Object.prototype.hasOwnProperty.call(n,i)&&a.push(i);return a},s.find=(n,a)=>{for(const i of n)if(a(i))return i},s.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&Number.isFinite(n)&&Math.floor(n)===n;function r(n,a=" | "){return n.map(i=>typeof i=="string"?`'${i}'`:i).join(a)}s.joinValues=r,s.jsonStringifyReplacer=(n,a)=>typeof a=="bigint"?a.toString():a})(b||(b={}));var re;(function(s){s.mergeShapes=(e,t)=>({...e,...t})})(re||(re={}));const h=b.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ee=s=>{switch(typeof s){case"undefined":return h.undefined;case"string":return h.string;case"number":return Number.isNaN(s)?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(s)?h.array:s===null?h.null:s.then&&typeof s.then=="function"&&s.catch&&typeof s.catch=="function"?h.promise:typeof Map<"u"&&s instanceof Map?h.map:typeof Set<"u"&&s instanceof Set?h.set:typeof Date<"u"&&s instanceof Date?h.date:h.object;default:return h.unknown}},u=b.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 J extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(a){return a.message},r={_errors:[]},n=a=>{for(const i of a.issues)if(i.code==="invalid_union")i.unionErrors.map(n);else if(i.code==="invalid_return_type")n(i.returnTypeError);else if(i.code==="invalid_arguments")n(i.argumentsError);else if(i.path.length===0)r._errors.push(t(i));else{let o=r,l=0;for(;l<i.path.length;){const c=i.path[l];l===i.path.length-1?(o[c]=o[c]||{_errors:[]},o[c]._errors.push(t(i))):o[c]=o[c]||{_errors:[]},o=o[c],l++}}};return n(this),r}static assert(e){if(!(e instanceof J))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,b.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},r=[];for(const n of this.issues)if(n.path.length>0){const a=n.path[0];t[a]=t[a]||[],t[a].push(e(n))}else r.push(e(n));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}J.create=s=>new J(s);const Oe=(s,e)=>{let t;switch(s.code){case u.invalid_type:s.received===h.undefined?t="Required":t=`Expected ${s.expected}, received ${s.received}`;break;case u.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(s.expected,b.jsonStringifyReplacer)}`;break;case u.unrecognized_keys:t=`Unrecognized key(s) in object: ${b.joinValues(s.keys,", ")}`;break;case u.invalid_union:t="Invalid input";break;case u.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${b.joinValues(s.options)}`;break;case u.invalid_enum_value:t=`Invalid enum value. Expected ${b.joinValues(s.options)}, received '${s.received}'`;break;case u.invalid_arguments:t="Invalid function arguments";break;case u.invalid_return_type:t="Invalid function return type";break;case u.invalid_date:t="Invalid date";break;case u.invalid_string:typeof s.validation=="object"?"includes"in s.validation?(t=`Invalid input: must include "${s.validation.includes}"`,typeof s.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${s.validation.position}`)):"startsWith"in s.validation?t=`Invalid input: must start with "${s.validation.startsWith}"`:"endsWith"in s.validation?t=`Invalid input: must end with "${s.validation.endsWith}"`:b.assertNever(s.validation):s.validation!=="regex"?t=`Invalid ${s.validation}`:t="Invalid";break;case u.too_small:s.type==="array"?t=`Array must contain ${s.exact?"exactly":s.inclusive?"at least":"more than"} ${s.minimum} element(s)`:s.type==="string"?t=`String must contain ${s.exact?"exactly":s.inclusive?"at least":"over"} ${s.minimum} character(s)`:s.type==="number"?t=`Number must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${s.minimum}`:s.type==="bigint"?t=`Number must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${s.minimum}`:s.type==="date"?t=`Date must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(s.minimum))}`:t="Invalid input";break;case u.too_big:s.type==="array"?t=`Array must contain ${s.exact?"exactly":s.inclusive?"at most":"less than"} ${s.maximum} element(s)`:s.type==="string"?t=`String must contain ${s.exact?"exactly":s.inclusive?"at most":"under"} ${s.maximum} character(s)`:s.type==="number"?t=`Number must be ${s.exact?"exactly":s.inclusive?"less than or equal to":"less than"} ${s.maximum}`:s.type==="bigint"?t=`BigInt must be ${s.exact?"exactly":s.inclusive?"less than or equal to":"less than"} ${s.maximum}`:s.type==="date"?t=`Date must be ${s.exact?"exactly":s.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(s.maximum))}`:t="Invalid input";break;case u.custom:t="Invalid input";break;case u.invalid_intersection_types:t="Intersection results could not be merged";break;case u.not_multiple_of:t=`Number must be a multiple of ${s.multipleOf}`;break;case u.not_finite:t="Number must be finite";break;default:t=e.defaultError,b.assertNever(s)}return{message:t}};let _t=Oe;function bt(){return _t}const kt=s=>{const{data:e,path:t,errorMaps:r,issueData:n}=s,a=[...t,...n.path||[]],i={...n,path:a};if(n.message!==void 0)return{...n,path:a,message:n.message};let o="";const l=r.filter(c=>!!c).slice().reverse();for(const c of l)o=c(i,{data:e,defaultError:o}).message;return{...n,path:a,message:o}};function f(s,e){const t=bt(),r=kt({issueData:e,data:s.data,path:s.path,errorMaps:[s.common.contextualErrorMap,s.schemaErrorMap,t,t===Oe?void 0:Oe].filter(n=>!!n)});s.common.issues.push(r)}class ${constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const r=[];for(const n of t){if(n.status==="aborted")return _;n.status==="dirty"&&e.dirty(),r.push(n.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const n of t){const a=await n.key,i=await n.value;r.push({key:a,value:i})}return $.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const n of t){const{key:a,value:i}=n;if(a.status==="aborted"||i.status==="aborted")return _;a.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof i.value<"u"||n.alwaysSet)&&(r[a.value]=i.value)}return{status:e.value,value:r}}}const _=Object.freeze({status:"aborted"}),pe=s=>({status:"dirty",value:s}),z=s=>({status:"valid",value:s}),Le=s=>s.status==="aborted",De=s=>s.status==="dirty",ie=s=>s.status==="valid",ve=s=>typeof Promise<"u"&&s instanceof Promise;var m;(function(s){s.errToObj=e=>typeof e=="string"?{message:e}:e||{},s.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(m||(m={}));class H{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||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Ve=(s,e)=>{if(ie(e))return{success:!0,data:e.value};if(!s.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 J(s.common.issues);return this._error=t,this._error}}};function w(s){if(!s)return{};const{errorMap:e,invalid_type_error:t,required_error:r,description:n}=s;if(e&&(t||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:n}:{errorMap:(i,o)=>{const{message:l}=s;return i.code==="invalid_enum_value"?{message:l??o.defaultError}:typeof o.data>"u"?{message:l??r??o.defaultError}:i.code!=="invalid_type"?{message:o.defaultError}:{message:l??t??o.defaultError}},description:n}}class C{get description(){return this._def.description}_getType(e){return ee(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:ee(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new $,ctx:{common:e.parent.common,data:e.data,parsedType:ee(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(ve(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){const r={common:{issues:[],async:(t==null?void 0:t.async)??!1,contextualErrorMap:t==null?void 0:t.errorMap},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ee(e)},n=this._parseSync({data:e,path:r.path,parent:r});return Ve(r,n)}"~validate"(e){var r,n;const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ee(e)};if(!this["~standard"].async)try{const a=this._parseSync({data:e,path:[],parent:t});return ie(a)?{value:a.value}:{issues:t.common.issues}}catch(a){(n=(r=a==null?void 0:a.message)==null?void 0:r.toLowerCase())!=null&&n.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(a=>ie(a)?{value:a.value}:{issues:t.common.issues})}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:t==null?void 0:t.errorMap,async:!0},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ee(e)},n=this._parse({data:e,path:r.path,parent:r}),a=await(ve(n)?n:Promise.resolve(n));return Ve(r,a)}refine(e,t){const r=n=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(n):t;return this._refinement((n,a)=>{const i=e(n),o=()=>a.addIssue({code:u.custom,...r(n)});return typeof Promise<"u"&&i instanceof Promise?i.then(l=>l?!0:(o(),!1)):i?!0:(o(),!1)})}refinement(e,t){return this._refinement((r,n)=>e(r)?!0:(n.addIssue(typeof t=="function"?t(r,n):t),!1))}_refinement(e){return new ue({schema:this,typeName:v.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}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),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return se.create(this,this._def)}nullable(){return le.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return W.create(this)}promise(){return xe.create(this,this._def)}or(e){return be.create([this,e],this._def)}and(e){return ke.create(this,e,this._def)}transform(e){return new ue({...w(this._def),schema:this,typeName:v.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new Ee({...w(this._def),innerType:this,defaultValue:t,typeName:v.ZodDefault})}brand(){return new Ft({typeName:v.ZodBranded,type:this,...w(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new Re({...w(this._def),innerType:this,catchValue:t,typeName:v.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Me.create(this,e)}readonly(){return je.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const wt=/^c[^\s-]{8,}$/i,xt=/^[0-9a-z]+$/,Ct=/^[0-9A-HJKMNP-TV-Z]{26}$/i,St=/^[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,Tt=/^[a-z0-9_-]{21}$/i,Ot=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Nt=/^[-+]?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)?)??$/,At=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Et="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Ne;const Rt=/^(?:(?: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])$/,Mt=/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,jt=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Pt=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Zt=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,$t=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ze="((\\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])))",It=new RegExp(`^${ze}$`);function Ue(s){let e="[0-5]\\d";s.precision?e=`${e}\\.\\d{${s.precision}}`:s.precision==null&&(e=`${e}(\\.\\d+)?`);const t=s.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function Lt(s){return new RegExp(`^${Ue(s)}$`)}function Dt(s){let e=`${ze}T${Ue(s)}`;const t=[];return t.push(s.local?"Z?":"Z"),s.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Vt(s,e){return!!((e==="v4"||!e)&&Rt.test(s)||(e==="v6"||!e)&&jt.test(s))}function zt(s,e){if(!Ot.test(s))return!1;try{const[t]=s.split(".");if(!t)return!1;const r=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),n=JSON.parse(atob(r));return!(typeof n!="object"||n===null||"typ"in n&&(n==null?void 0:n.typ)!=="JWT"||!n.alg||e&&n.alg!==e)}catch{return!1}}function Ut(s,e){return!!((e==="v4"||!e)&&Mt.test(s)||(e==="v6"||!e)&&Pt.test(s))}class Y extends C{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==h.string){const a=this._getOrReturnCtx(e);return f(a,{code:u.invalid_type,expected:h.string,received:a.parsedType}),_}const r=new $;let n;for(const a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(n=this._getOrReturnCtx(e,n),f(n,{code:u.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),r.dirty());else if(a.kind==="max")e.data.length>a.value&&(n=this._getOrReturnCtx(e,n),f(n,{code:u.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),r.dirty());else if(a.kind==="length"){const i=e.data.length>a.value,o=e.data.length<a.value;(i||o)&&(n=this._getOrReturnCtx(e,n),i?f(n,{code:u.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):o&&f(n,{code:u.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),r.dirty())}else if(a.kind==="email")At.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"email",code:u.invalid_string,message:a.message}),r.dirty());else if(a.kind==="emoji")Ne||(Ne=new RegExp(Et,"u")),Ne.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"emoji",code:u.invalid_string,message:a.message}),r.dirty());else if(a.kind==="uuid")St.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"uuid",code:u.invalid_string,message:a.message}),r.dirty());else if(a.kind==="nanoid")Tt.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"nanoid",code:u.invalid_string,message:a.message}),r.dirty());else if(a.kind==="cuid")wt.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"cuid",code:u.invalid_string,message:a.message}),r.dirty());else if(a.kind==="cuid2")xt.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"cuid2",code:u.invalid_string,message:a.message}),r.dirty());else if(a.kind==="ulid")Ct.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"ulid",code:u.invalid_string,message:a.message}),r.dirty());else if(a.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),f(n,{validation:"url",code:u.invalid_string,message:a.message}),r.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"regex",code:u.invalid_string,message:a.message}),r.dirty())):a.kind==="trim"?e.data=e.data.trim():a.kind==="includes"?e.data.includes(a.value,a.position)||(n=this._getOrReturnCtx(e,n),f(n,{code:u.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),r.dirty()):a.kind==="toLowerCase"?e.data=e.data.toLowerCase():a.kind==="toUpperCase"?e.data=e.data.toUpperCase():a.kind==="startsWith"?e.data.startsWith(a.value)||(n=this._getOrReturnCtx(e,n),f(n,{code:u.invalid_string,validation:{startsWith:a.value},message:a.message}),r.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(n=this._getOrReturnCtx(e,n),f(n,{code:u.invalid_string,validation:{endsWith:a.value},message:a.message}),r.dirty()):a.kind==="datetime"?Dt(a).test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{code:u.invalid_string,validation:"datetime",message:a.message}),r.dirty()):a.kind==="date"?It.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{code:u.invalid_string,validation:"date",message:a.message}),r.dirty()):a.kind==="time"?Lt(a).test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{code:u.invalid_string,validation:"time",message:a.message}),r.dirty()):a.kind==="duration"?Nt.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"duration",code:u.invalid_string,message:a.message}),r.dirty()):a.kind==="ip"?Vt(e.data,a.version)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"ip",code:u.invalid_string,message:a.message}),r.dirty()):a.kind==="jwt"?zt(e.data,a.alg)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"jwt",code:u.invalid_string,message:a.message}),r.dirty()):a.kind==="cidr"?Ut(e.data,a.version)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"cidr",code:u.invalid_string,message:a.message}),r.dirty()):a.kind==="base64"?Zt.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"base64",code:u.invalid_string,message:a.message}),r.dirty()):a.kind==="base64url"?$t.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"base64url",code:u.invalid_string,message:a.message}),r.dirty()):b.assertNever(a);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement(n=>e.test(n),{validation:t,code:u.invalid_string,...m.errToObj(r)})}_addCheck(e){return new Y({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...m.errToObj(e)})}url(e){return this._addCheck({kind:"url",...m.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...m.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...m.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...m.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...m.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...m.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...m.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...m.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...m.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...m.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...m.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...m.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(e==null?void 0:e.offset)??!1,local:(e==null?void 0:e.local)??!1,...m.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...m.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...m.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...m.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t==null?void 0:t.position,...m.errToObj(t==null?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...m.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...m.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...m.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...m.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...m.errToObj(t)})}nonempty(e){return this.min(1,m.errToObj(e))}trim(){return new Y({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Y({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Y({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}Y.create=s=>new Y({checks:[],typeName:v.ZodString,coerce:(s==null?void 0:s.coerce)??!1,...w(s)});function qt(s,e){const t=(s.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,n=t>r?t:r,a=Number.parseInt(s.toFixed(n).replace(".","")),i=Number.parseInt(e.toFixed(n).replace(".",""));return a%i/10**n}class oe extends C{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==h.number){const a=this._getOrReturnCtx(e);return f(a,{code:u.invalid_type,expected:h.number,received:a.parsedType}),_}let r;const n=new $;for(const a of this._def.checks)a.kind==="int"?b.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{code:u.invalid_type,expected:"integer",received:"float",message:a.message}),n.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(r=this._getOrReturnCtx(e,r),f(r,{code:u.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),n.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(r=this._getOrReturnCtx(e,r),f(r,{code:u.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),n.dirty()):a.kind==="multipleOf"?qt(e.data,a.value)!==0&&(r=this._getOrReturnCtx(e,r),f(r,{code:u.not_multiple_of,multipleOf:a.value,message:a.message}),n.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{code:u.not_finite,message:a.message}),n.dirty()):b.assertNever(a);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,m.toString(t))}gt(e,t){return this.setLimit("min",e,!1,m.toString(t))}lte(e,t){return this.setLimit("max",e,!0,m.toString(t))}lt(e,t){return this.setLimit("max",e,!1,m.toString(t))}setLimit(e,t,r,n){return new oe({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:m.toString(n)}]})}_addCheck(e){return new oe({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:m.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:m.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:m.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:m.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:m.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:m.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:m.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:m.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:m.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&b.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(t===null||r.value>t)&&(t=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}}oe.create=s=>new oe({checks:[],typeName:v.ZodNumber,coerce:(s==null?void 0:s.coerce)||!1,...w(s)});class me extends C{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==h.bigint)return this._getInvalidInput(e);let r;const n=new $;for(const a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(r=this._getOrReturnCtx(e,r),f(r,{code:u.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),n.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(r=this._getOrReturnCtx(e,r),f(r,{code:u.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),n.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),f(r,{code:u.not_multiple_of,multipleOf:a.value,message:a.message}),n.dirty()):b.assertNever(a);return{status:n.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:h.bigint,received:t.parsedType}),_}gte(e,t){return this.setLimit("min",e,!0,m.toString(t))}gt(e,t){return this.setLimit("min",e,!1,m.toString(t))}lte(e,t){return this.setLimit("max",e,!0,m.toString(t))}lt(e,t){return this.setLimit("max",e,!1,m.toString(t))}setLimit(e,t,r,n){return new me({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:m.toString(n)}]})}_addCheck(e){return new me({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:m.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:m.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:m.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:m.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:m.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}me.create=s=>new me({checks:[],typeName:v.ZodBigInt,coerce:(s==null?void 0:s.coerce)??!1,...w(s)});class qe extends C{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==h.boolean){const r=this._getOrReturnCtx(e);return f(r,{code:u.invalid_type,expected:h.boolean,received:r.parsedType}),_}return z(e.data)}}qe.create=s=>new qe({typeName:v.ZodBoolean,coerce:(s==null?void 0:s.coerce)||!1,...w(s)});class _e extends C{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==h.date){const a=this._getOrReturnCtx(e);return f(a,{code:u.invalid_type,expected:h.date,received:a.parsedType}),_}if(Number.isNaN(e.data.getTime())){const a=this._getOrReturnCtx(e);return f(a,{code:u.invalid_date}),_}const r=new $;let n;for(const a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(n=this._getOrReturnCtx(e,n),f(n,{code:u.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),r.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(n=this._getOrReturnCtx(e,n),f(n,{code:u.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),r.dirty()):b.assertNever(a);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new _e({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:m.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:m.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}_e.create=s=>new _e({checks:[],coerce:(s==null?void 0:s.coerce)||!1,typeName:v.ZodDate,...w(s)});class Fe extends C{_parse(e){if(this._getType(e)!==h.symbol){const r=this._getOrReturnCtx(e);return f(r,{code:u.invalid_type,expected:h.symbol,received:r.parsedType}),_}return z(e.data)}}Fe.create=s=>new Fe({typeName:v.ZodSymbol,...w(s)});class Be extends C{_parse(e){if(this._getType(e)!==h.undefined){const r=this._getOrReturnCtx(e);return f(r,{code:u.invalid_type,expected:h.undefined,received:r.parsedType}),_}return z(e.data)}}Be.create=s=>new Be({typeName:v.ZodUndefined,...w(s)});class He extends C{_parse(e){if(this._getType(e)!==h.null){const r=this._getOrReturnCtx(e);return f(r,{code:u.invalid_type,expected:h.null,received:r.parsedType}),_}return z(e.data)}}He.create=s=>new He({typeName:v.ZodNull,...w(s)});class We extends C{constructor(){super(...arguments),this._any=!0}_parse(e){return z(e.data)}}We.create=s=>new We({typeName:v.ZodAny,...w(s)});class Xe extends C{constructor(){super(...arguments),this._unknown=!0}_parse(e){return z(e.data)}}Xe.create=s=>new Xe({typeName:v.ZodUnknown,...w(s)});class te extends C{_parse(e){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:h.never,received:t.parsedType}),_}}te.create=s=>new te({typeName:v.ZodNever,...w(s)});class Ge extends C{_parse(e){if(this._getType(e)!==h.undefined){const r=this._getOrReturnCtx(e);return f(r,{code:u.invalid_type,expected:h.void,received:r.parsedType}),_}return z(e.data)}}Ge.create=s=>new Ge({typeName:v.ZodVoid,...w(s)});class W extends C{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),n=this._def;if(t.parsedType!==h.array)return f(t,{code:u.invalid_type,expected:h.array,received:t.parsedType}),_;if(n.exactLength!==null){const i=t.data.length>n.exactLength.value,o=t.data.length<n.exactLength.value;(i||o)&&(f(t,{code:i?u.too_big:u.too_small,minimum:o?n.exactLength.value:void 0,maximum:i?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),r.dirty())}if(n.minLength!==null&&t.data.length<n.minLength.value&&(f(t,{code:u.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),r.dirty()),n.maxLength!==null&&t.data.length>n.maxLength.value&&(f(t,{code:u.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((i,o)=>n.type._parseAsync(new H(t,i,t.path,o)))).then(i=>$.mergeArray(r,i));const a=[...t.data].map((i,o)=>n.type._parseSync(new H(t,i,t.path,o)));return $.mergeArray(r,a)}get element(){return this._def.type}min(e,t){return new W({...this._def,minLength:{value:e,message:m.toString(t)}})}max(e,t){return new W({...this._def,maxLength:{value:e,message:m.toString(t)}})}length(e,t){return new W({...this._def,exactLength:{value:e,message:m.toString(t)}})}nonempty(e){return this.min(1,e)}}W.create=(s,e)=>new W({type:s,minLength:null,maxLength:null,exactLength:null,typeName:v.ZodArray,...w(e)});function ce(s){if(s instanceof N){const e={};for(const t in s.shape){const r=s.shape[t];e[t]=se.create(ce(r))}return new N({...s._def,shape:()=>e})}else return s instanceof W?new W({...s._def,type:ce(s.element)}):s instanceof se?se.create(ce(s.unwrap())):s instanceof le?le.create(ce(s.unwrap())):s instanceof ne?ne.create(s.items.map(e=>ce(e))):s}class N extends C{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),t=b.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==h.object){const c=this._getOrReturnCtx(e);return f(c,{code:u.invalid_type,expected:h.object,received:c.parsedType}),_}const{status:r,ctx:n}=this._processInputParams(e),{shape:a,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof te&&this._def.unknownKeys==="strip"))for(const c in n.data)i.includes(c)||o.push(c);const l=[];for(const c of i){const g=a[c],O=n.data[c];l.push({key:{status:"valid",value:c},value:g._parse(new H(n,O,n.path,c)),alwaysSet:c in n.data})}if(this._def.catchall instanceof te){const c=this._def.unknownKeys;if(c==="passthrough")for(const g of o)l.push({key:{status:"valid",value:g},value:{status:"valid",value:n.data[g]}});else if(c==="strict")o.length>0&&(f(n,{code:u.unrecognized_keys,keys:o}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const c=this._def.catchall;for(const g of o){const O=n.data[g];l.push({key:{status:"valid",value:g},value:c._parse(new H(n,O,n.path,g)),alwaysSet:g in n.data})}}return n.common.async?Promise.resolve().then(async()=>{const c=[];for(const g of l){const O=await g.key,A=await g.value;c.push({key:O,value:A,alwaysSet:g.alwaysSet})}return c}).then(c=>$.mergeObjectSync(r,c)):$.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(e){return m.errToObj,new N({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,r)=>{var a,i;const n=((i=(a=this._def).errorMap)==null?void 0:i.call(a,t,r).message)??r.defaultError;return t.code==="unrecognized_keys"?{message:m.errToObj(e).message??n}:{message:n}}}:{}})}strip(){return new N({...this._def,unknownKeys:"strip"})}passthrough(){return new N({...this._def,unknownKeys:"passthrough"})}extend(e){return new N({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new N({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:v.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new N({...this._def,catchall:e})}pick(e){const t={};for(const r of b.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new N({...this._def,shape:()=>t})}omit(e){const t={};for(const r of b.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new N({...this._def,shape:()=>t})}deepPartial(){return ce(this)}partial(e){const t={};for(const r of b.objectKeys(this.shape)){const n=this.shape[r];e&&!e[r]?t[r]=n:t[r]=n.optional()}return new N({...this._def,shape:()=>t})}required(e){const t={};for(const r of b.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let a=this.shape[r];for(;a instanceof se;)a=a._def.innerType;t[r]=a}return new N({...this._def,shape:()=>t})}keyof(){return Ke(b.objectKeys(this.shape))}}N.create=(s,e)=>new N({shape:()=>s,unknownKeys:"strip",catchall:te.create(),typeName:v.ZodObject,...w(e)}),N.strictCreate=(s,e)=>new N({shape:()=>s,unknownKeys:"strict",catchall:te.create(),typeName:v.ZodObject,...w(e)}),N.lazycreate=(s,e)=>new N({shape:s,unknownKeys:"strip",catchall:te.create(),typeName:v.ZodObject,...w(e)});class be extends C{_parse(e){const{ctx:t}=this._processInputParams(e),r=this._def.options;function n(a){for(const o of a)if(o.result.status==="valid")return o.result;for(const o of a)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;const i=a.map(o=>new J(o.ctx.common.issues));return f(t,{code:u.invalid_union,unionErrors:i}),_}if(t.common.async)return Promise.all(r.map(async a=>{const i={...t,common:{...t.common,issues:[]},parent:null};return{result:await a._parseAsync({data:t.data,path:t.path,parent:i}),ctx:i}})).then(n);{let a;const i=[];for(const l of r){const c={...t,common:{...t.common,issues:[]},parent:null},g=l._parseSync({data:t.data,path:t.path,parent:c});if(g.status==="valid")return g;g.status==="dirty"&&!a&&(a={result:g,ctx:c}),c.common.issues.length&&i.push(c.common.issues)}if(a)return t.common.issues.push(...a.ctx.common.issues),a.result;const o=i.map(l=>new J(l));return f(t,{code:u.invalid_union,unionErrors:o}),_}}get options(){return this._def.options}}be.create=(s,e)=>new be({options:s,typeName:v.ZodUnion,...w(e)});function Ae(s,e){const t=ee(s),r=ee(e);if(s===e)return{valid:!0,data:s};if(t===h.object&&r===h.object){const n=b.objectKeys(e),a=b.objectKeys(s).filter(o=>n.indexOf(o)!==-1),i={...s,...e};for(const o of a){const l=Ae(s[o],e[o]);if(!l.valid)return{valid:!1};i[o]=l.data}return{valid:!0,data:i}}else if(t===h.array&&r===h.array){if(s.length!==e.length)return{valid:!1};const n=[];for(let a=0;a<s.length;a++){const i=s[a],o=e[a],l=Ae(i,o);if(!l.valid)return{valid:!1};n.push(l.data)}return{valid:!0,data:n}}else return t===h.date&&r===h.date&&+s==+e?{valid:!0,data:s}:{valid:!1}}class ke extends C{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=(a,i)=>{if(Le(a)||Le(i))return _;const o=Ae(a.value,i.value);return o.valid?((De(a)||De(i))&&t.dirty(),{status:t.value,value:o.data}):(f(r,{code:u.invalid_intersection_types}),_)};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(([a,i])=>n(a,i)):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}))}}ke.create=(s,e,t)=>new ke({left:s,right:e,typeName:v.ZodIntersection,...w(t)});class ne extends C{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==h.array)return f(r,{code:u.invalid_type,expected:h.array,received:r.parsedType}),_;if(r.data.length<this._def.items.length)return f(r,{code:u.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),_;!this._def.rest&&r.data.length>this._def.items.length&&(f(r,{code:u.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const a=[...r.data].map((i,o)=>{const l=this._def.items[o]||this._def.rest;return l?l._parse(new H(r,i,r.path,o)):null}).filter(i=>!!i);return r.common.async?Promise.all(a).then(i=>$.mergeArray(t,i)):$.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new ne({...this._def,rest:e})}}ne.create=(s,e)=>{if(!Array.isArray(s))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ne({items:s,typeName:v.ZodTuple,rest:null,...w(e)})};class we extends C{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 f(r,{code:u.invalid_type,expected:h.object,received:r.parsedType}),_;const n=[],a=this._def.keyType,i=this._def.valueType;for(const o in r.data)n.push({key:a._parse(new H(r,o,r.path,o)),value:i._parse(new H(r,r.data[o],r.path,o)),alwaysSet:o in r.data});return r.common.async?$.mergeObjectAsync(t,n):$.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,r){return t instanceof C?new we({keyType:e,valueType:t,typeName:v.ZodRecord,...w(r)}):new we({keyType:Y.create(),valueType:e,typeName:v.ZodRecord,...w(t)})}}class Je extends C{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 f(r,{code:u.invalid_type,expected:h.map,received:r.parsedType}),_;const n=this._def.keyType,a=this._def.valueType,i=[...r.data.entries()].map(([o,l],c)=>({key:n._parse(new H(r,o,r.path,[c,"key"])),value:a._parse(new H(r,l,r.path,[c,"value"]))}));if(r.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const l of i){const c=await l.key,g=await l.value;if(c.status==="aborted"||g.status==="aborted")return _;(c.status==="dirty"||g.status==="dirty")&&t.dirty(),o.set(c.value,g.value)}return{status:t.value,value:o}})}else{const o=new Map;for(const l of i){const c=l.key,g=l.value;if(c.status==="aborted"||g.status==="aborted")return _;(c.status==="dirty"||g.status==="dirty")&&t.dirty(),o.set(c.value,g.value)}return{status:t.value,value:o}}}}Je.create=(s,e,t)=>new Je({valueType:e,keyType:s,typeName:v.ZodMap,...w(t)});class ye extends C{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==h.set)return f(r,{code:u.invalid_type,expected:h.set,received:r.parsedType}),_;const n=this._def;n.minSize!==null&&r.data.size<n.minSize.value&&(f(r,{code:u.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()),n.maxSize!==null&&r.data.size>n.maxSize.value&&(f(r,{code:u.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());const a=this._def.valueType;function i(l){const c=new Set;for(const g of l){if(g.status==="aborted")return _;g.status==="dirty"&&t.dirty(),c.add(g.value)}return{status:t.value,value:c}}const o=[...r.data.values()].map((l,c)=>a._parse(new H(r,l,r.path,c)));return r.common.async?Promise.all(o).then(l=>i(l)):i(o)}min(e,t){return new ye({...this._def,minSize:{value:e,message:m.toString(t)}})}max(e,t){return new ye({...this._def,maxSize:{value:e,message:m.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ye.create=(s,e)=>new ye({valueType:s,minSize:null,maxSize:null,typeName:v.ZodSet,...w(e)});class Ye extends C{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})}}Ye.create=(s,e)=>new Ye({getter:s,typeName:v.ZodLazy,...w(e)});class Qe extends C{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return f(t,{received:t.data,code:u.invalid_literal,expected:this._def.value}),_}return{status:"valid",value:e.data}}get value(){return this._def.value}}Qe.create=(s,e)=>new Qe({value:s,typeName:v.ZodLiteral,...w(e)});function Ke(s,e){return new de({values:s,typeName:v.ZodEnum,...w(e)})}class de extends C{_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),r=this._def.values;return f(t,{expected:b.joinValues(r),received:t.parsedType,code:u.invalid_type}),_}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return f(t,{received:t.data,code:u.invalid_enum_value,options:r}),_}return z(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 de.create(e,{...this._def,...t})}exclude(e,t=this._def){return de.create(this.options.filter(r=>!e.includes(r)),{...this._def,...t})}}de.create=Ke;class et extends C{_parse(e){const t=b.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==h.string&&r.parsedType!==h.number){const n=b.objectValues(t);return f(r,{expected:b.joinValues(n),received:r.parsedType,code:u.invalid_type}),_}if(this._cache||(this._cache=new Set(b.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const n=b.objectValues(t);return f(r,{received:r.data,code:u.invalid_enum_value,options:n}),_}return z(e.data)}get enum(){return this._def.values}}et.create=(s,e)=>new et({values:s,typeName:v.ZodNativeEnum,...w(e)});class xe extends C{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==h.promise&&t.common.async===!1)return f(t,{code:u.invalid_type,expected:h.promise,received:t.parsedType}),_;const r=t.parsedType===h.promise?t.data:Promise.resolve(t.data);return z(r.then(n=>this._def.type.parseAsync(n,{path:t.path,errorMap:t.common.contextualErrorMap})))}}xe.create=(s,e)=>new xe({type:s,typeName:v.ZodPromise,...w(e)});class ue extends C{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===v.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=this._def.effect||null,a={addIssue:i=>{f(r,i),i.fatal?t.abort():t.dirty()},get path(){return r.path}};if(a.addIssue=a.addIssue.bind(a),n.type==="preprocess"){const i=n.transform(r.data,a);if(r.common.async)return Promise.resolve(i).then(async o=>{if(t.value==="aborted")return _;const l=await this._def.schema._parseAsync({data:o,path:r.path,parent:r});return l.status==="aborted"?_:l.status==="dirty"||t.value==="dirty"?pe(l.value):l});{if(t.value==="aborted")return _;const o=this._def.schema._parseSync({data:i,path:r.path,parent:r});return o.status==="aborted"?_:o.status==="dirty"||t.value==="dirty"?pe(o.value):o}}if(n.type==="refinement"){const i=o=>{const l=n.refinement(o,a);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(r.common.async===!1){const o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?_:(o.status==="dirty"&&t.dirty(),i(o.value),{status:t.value,value:o.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>o.status==="aborted"?_:(o.status==="dirty"&&t.dirty(),i(o.value).then(()=>({status:t.value,value:o.value}))))}if(n.type==="transform")if(r.common.async===!1){const i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!ie(i))return _;const o=n.transform(i.value,a);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:o}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>ie(i)?Promise.resolve(n.transform(i.value,a)).then(o=>({status:t.value,value:o})):_);b.assertNever(n)}}ue.create=(s,e,t)=>new ue({schema:s,typeName:v.ZodEffects,effect:e,...w(t)}),ue.createWithPreprocess=(s,e,t)=>new ue({schema:e,effect:{type:"preprocess",transform:s},typeName:v.ZodEffects,...w(t)});class se extends C{_parse(e){return this._getType(e)===h.undefined?z(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}se.create=(s,e)=>new se({innerType:s,typeName:v.ZodOptional,...w(e)});class le extends C{_parse(e){return this._getType(e)===h.null?z(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}le.create=(s,e)=>new le({innerType:s,typeName:v.ZodNullable,...w(e)});class Ee extends C{_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}}Ee.create=(s,e)=>new Ee({innerType:s,typeName:v.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...w(e)});class Re extends C{_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 ve(n)?n.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new J(r.common.issues)},input:r.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new J(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Re.create=(s,e)=>new Re({innerType:s,typeName:v.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...w(e)});class tt extends C{_parse(e){if(this._getType(e)!==h.nan){const r=this._getOrReturnCtx(e);return f(r,{code:u.invalid_type,expected:h.nan,received:r.parsedType}),_}return{status:"valid",value:e.data}}}tt.create=s=>new tt({typeName:v.ZodNaN,...w(s)});class Ft extends C{_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 C{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{const a=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?_:a.status==="dirty"?(t.dirty(),pe(a.value)):this._def.out._parseAsync({data:a.value,path:r.path,parent:r})})();{const n=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return n.status==="aborted"?_:n.status==="dirty"?(t.dirty(),{status:"dirty",value:n.value}):this._def.out._parseSync({data:n.value,path:r.path,parent:r})}}static create(e,t){return new Me({in:e,out:t,typeName:v.ZodPipeline})}}class je extends C{_parse(e){const t=this._def.innerType._parse(e),r=n=>(ie(n)&&(n.value=Object.freeze(n.value)),n);return ve(t)?t.then(n=>r(n)):r(t)}unwrap(){return this._def.innerType}}je.create=(s,e)=>new je({innerType:s,typeName:v.ZodReadonly,...w(e)});var v;(function(s){s.ZodString="ZodString",s.ZodNumber="ZodNumber",s.ZodNaN="ZodNaN",s.ZodBigInt="ZodBigInt",s.ZodBoolean="ZodBoolean",s.ZodDate="ZodDate",s.ZodSymbol="ZodSymbol",s.ZodUndefined="ZodUndefined",s.ZodNull="ZodNull",s.ZodAny="ZodAny",s.ZodUnknown="ZodUnknown",s.ZodNever="ZodNever",s.ZodVoid="ZodVoid",s.ZodArray="ZodArray",s.ZodObject="ZodObject",s.ZodUnion="ZodUnion",s.ZodDiscriminatedUnion="ZodDiscriminatedUnion",s.ZodIntersection="ZodIntersection",s.ZodTuple="ZodTuple",s.ZodRecord="ZodRecord",s.ZodMap="ZodMap",s.ZodSet="ZodSet",s.ZodFunction="ZodFunction",s.ZodLazy="ZodLazy",s.ZodLiteral="ZodLiteral",s.ZodEnum="ZodEnum",s.ZodEffects="ZodEffects",s.ZodNativeEnum="ZodNativeEnum",s.ZodOptional="ZodOptional",s.ZodNullable="ZodNullable",s.ZodDefault="ZodDefault",s.ZodCatch="ZodCatch",s.ZodPromise="ZodPromise",s.ZodBranded="ZodBranded",s.ZodPipeline="ZodPipeline",s.ZodReadonly="ZodReadonly"})(v||(v={}));const R=Y.create,X=oe.create;te.create;const I=W.create,L=N.create;be.create,ke.create,ne.create;const Bt=we.create,Ce=de.create;xe.create,se.create,le.create;class st extends Error{constructor(t){const r=`Invalid ChaosConfig:
2
- ${t.map(n=>` - ${n}`).join(`
3
- `)}`;super(r);Z(this,"issues");this.name="ChaosConfigError",this.issues=t}}const G=X().min(0,"Probability must be >= 0").max(1,"Probability must be <= 1"),rt=X().int().min(1),Q={onNth:rt.optional(),everyNth:rt.optional(),afterN:X().int().min(0).optional()},K=[s=>[s.onNth,s.everyNth,s.afterN].filter(e=>e!==void 0).length<=1,{message:"Only one of onNth, everyNth, or afterN may be set on a single rule"}],Ht=L({urlPattern:R().min(1,"urlPattern must not be empty"),methods:I(R()).optional(),statusCode:X().int().min(100).max(599),probability:G,body:R().optional(),statusText:R().optional(),headers:Bt(R()).optional(),...Q}).strict().refine(...K),Wt=L({urlPattern:R().min(1,"urlPattern must not be empty"),methods:I(R()).optional(),delayMs:X().min(0,"delayMs must be >= 0"),probability:G,...Q}).strict().refine(...K),Xt=L({urlPattern:R().min(1,"urlPattern must not be empty"),methods:I(R()).optional(),probability:G,timeout:X().min(0,"timeout must be >= 0").optional(),...Q}).strict().refine(...K),Gt=L({urlPattern:R().min(1,"urlPattern must not be empty"),methods:I(R()).optional(),probability:G,strategy:Ce(["truncate","malformed-json","empty","wrong-type"]),...Q}).strict().refine(...K),Jt=L({urlPattern:R().min(1,"urlPattern must not be empty"),methods:I(R()).optional(),probability:G,...Q}).strict().refine(...K),Yt=L({failures:I(Ht).optional(),latencies:I(Wt).optional(),aborts:I(Xt).optional(),corruptions:I(Gt).optional(),cors:I(Jt).optional()}).strict(),Qt=L({selector:R().min(1,"selector must not be empty"),action:Ce(["disable","hide","remove"]),probability:G}).strict(),Kt=L({assaults:I(Qt).optional()}).strict(),Pe=Ce(["inbound","outbound","both"]),es=L({urlPattern:R().min(1,"urlPattern must not be empty"),direction:Pe,probability:G,...Q}).strict().refine(...K),ts=L({urlPattern:R().min(1,"urlPattern must not be empty"),direction:Pe,delayMs:X().min(0,"delayMs must be >= 0"),probability:G,...Q}).strict().refine(...K),ss=L({urlPattern:R().min(1,"urlPattern must not be empty"),direction:Pe,strategy:Ce(["truncate","malformed-json","empty","wrong-type"]),probability:G,...Q}).strict().refine(...K),rs=X().int().refine(s=>s===1e3||s>=3e3&&s<=4999,{message:"code must be 1000 or in the range 3000-4999"}),ns=R().refine(s=>new TextEncoder().encode(s).length<=123,{message:"reason must be <= 123 UTF-8 bytes"}),as=L({urlPattern:R().min(1,"urlPattern must not be empty"),code:rs.optional(),reason:ns.optional(),afterMs:X().min(0,"afterMs must be >= 0").optional(),probability:G,...Q}).strict().refine(...K),is=L({drops:I(es).optional(),delays:I(ts).optional(),corruptions:I(ss).optional(),closes:I(as).optional()}).strict(),os=L({network:Yt.optional(),ui:Kt.optional(),websocket:is.optional(),seed:X().int("Seed must be an integer").optional()}).strict();function nt(s){const e=os.safeParse(s);if(!e.success){const t=e.error.issues.map(r=>`${r.path.join(".")}: ${r.message}`);throw new st(t)}return e.data}function cs(s){let e=s|0;return()=>{e=e+1831565813|0;let t=Math.imul(e^e>>>15,1|e);return t=t+Math.imul(t^t>>>7,61|t)^t,((t^t>>>14)>>>0)/4294967296}}function at(){return Math.random()*4294967296>>>0}function it(s){const e=s??at();return{random:cs(e),seed:e}}class ot{constructor(e=2e3){Z(this,"listeners",new Map);Z(this,"log",[]);this.maxLogEntries=e}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t)}off(e,t){var r;(r=this.listeners.get(e))==null||r.delete(t)}emit(e){this.log.push(e),this.log.length>this.maxLogEntries&&this.log.shift(),this.notify(this.listeners.get(e.type),e),this.notify(this.listeners.get("*"),e)}getLog(){return[...this.log]}clearLog(){this.log=[]}notify(e,t){if(e)for(const r of e)try{r(t)}catch{}}}function D(s,e){return e()<s}function U(s,e){const t=(e.get(s)??0)+1;return e.set(s,t),t}function q(s,e){return s.onNth!==void 0?e===s.onNth:s.everyNth!==void 0?e%s.everyNth===0:s.afterN!==void 0?e>s.afterN:!0}function F(s,e){return e==="*"?!0:s.includes(e)}function ct(s,e){switch(e){case"truncate":return s.slice(0,Math.max(0,Math.floor(s.length/2)));case"malformed-json":return`${s}"}`;case"empty":return"";case"wrong-type":return"<html><body>Unexpected HTML</body></html>"}}function Ze(s){return typeof Request<"u"&&s instanceof Request}function ds(s){return Ze(s)?s.url:s.toString()}function us(s,e){return e!=null&&e.method?e.method.toUpperCase():Ze(s)?s.method.toUpperCase():"GET"}function ls(s,e){if(e!=null&&e.signal)return e.signal;if(Ze(s))return s.signal}function fs(){if(typeof DOMException<"u")return new DOMException("The user aborted a request.","AbortError");const s=new Error("The user aborted a request.");return s.name="AbortError",s}function hs(s,e){if(!e)return s;const t=new AbortController,r=o=>{i(),t.signal.aborted||t.abort(o.reason)},n=()=>r(s),a=()=>r(e),i=()=>{s.removeEventListener("abort",n),e.removeEventListener("abort",a)};return s.aborted?(r(s),t.signal):e.aborted?(r(e),t.signal):(s.addEventListener("abort",n,{once:!0}),e.addEventListener("abort",a,{once:!0}),t.signal)}function ps(s,e){return e?{...s??{},signal:e}:s}function dt(s,e,t,r,n){s==null||s.emit({type:"network:abort",timestamp:Date.now(),applied:n,detail:{url:t,method:r,timeoutMs:e.timeout}})}function Se(s,e,t,r,n){s==null||s.emit({type:"network:corruption",timestamp:Date.now(),applied:n,detail:{url:t,method:r,strategy:e.strategy}})}function ms(s,e,t,r,n=new Map){return async(a,i)=>{const o=ds(a),l=us(a,i),c=ls(a,i);if(e.cors){for(const d of e.cors)if(F(o,d.urlPattern)&&(!d.methods||d.methods.includes(l))){const k=U(d,n);if(!q(d,k))continue;const x=D(d.probability,t);if(r==null||r.emit({type:"network:cors",timestamp:Date.now(),applied:x,detail:{url:o,method:l}}),x){console.debug(`[chaos-maker] CORS block: ${l} ${o}`);const S=new TypeError("Failed to fetch");throw S.stack="",S}}}let g=null,O,A,j=!1;const M=d=>{!g||j||(j=!0,A&&(clearTimeout(A),A=void 0),dt(r,g,o,l,d))};if(e.aborts){for(const d of e.aborts)if(F(o,d.urlPattern)&&(!d.methods||d.methods.includes(l))){const k=U(d,n);if(!q(d,k))continue;if(!D(d.probability,t)){dt(r,d,o,l,!1);continue}console.warn(`CHAOS: Aborting ${l} ${o} after ${d.timeout||0}ms`),g=d;const S=new AbortController;O=hs(S.signal,c);const T=()=>{j||(M(!0),S.abort(fs()))};d.timeout?A=setTimeout(T,d.timeout):T();break}}if(g)try{const d=await s(a,ps(i,O));return M(!1),d}catch(d){throw M(!1),d}if(e.failures){for(const d of e.failures)if(F(o,d.urlPattern)&&(!d.methods||d.methods.includes(l))){const k=U(d,n);if(!q(d,k))continue;const x=D(d.probability,t);if(r==null||r.emit({type:"network:failure",timestamp:Date.now(),applied:x,detail:{url:o,method:l,statusCode:d.statusCode}}),x){console.warn(`CHAOS: Forcing ${d.statusCode} for ${l} ${o}`);const S=d.body??JSON.stringify({error:"Chaos Maker Attack!"}),T=d.headers??{};return new Response(S,{status:d.statusCode,statusText:d.statusText??"Service Unavailable (Chaos)",headers:T})}}}if(e.latencies){for(const d of e.latencies)if(F(o,d.urlPattern)&&(!d.methods||d.methods.includes(l))){const k=U(d,n);if(!q(d,k))continue;const x=D(d.probability,t);r==null||r.emit({type:"network:latency",timestamp:Date.now(),applied:x,detail:{url:o,method:l,delayMs:d.delayMs}}),x&&(console.warn(`CHAOS: Adding ${d.delayMs}ms latency to ${l} ${o}`),await new Promise(S=>setTimeout(S,d.delayMs)))}}let y=null;if(e.corruptions){for(const d of e.corruptions)if(F(o,d.urlPattern)&&(!d.methods||d.methods.includes(l))){const k=U(d,n);if(!q(d,k))continue;if(!D(d.probability,t)){Se(r,d,o,l,!1);continue}y=d;break}}let p;try{p=await s(a,i)}catch(d){throw y&&Se(r,y,o,l,!1),d}if(!y)return p;try{console.warn(`CHAOS: Corrupting response for ${l} ${o} with strategy: ${y.strategy}`);const d=await p.text(),k=ct(d,y.strategy);return Se(r,y,o,l,!0),new Response(k,{status:p.status,statusText:p.statusText,headers:p.headers})}catch(d){throw Se(r,y,o,l,!1),d}}}function ut(s,e,t,r,n){s==null||s.emit({type:"network:abort",timestamp:Date.now(),applied:n,detail:{url:t,method:r,timeoutMs:e.timeout}})}function lt(s,e,t,r,n){s==null||s.emit({type:"network:corruption",timestamp:Date.now(),applied:n,detail:{url:t,method:r,strategy:e.strategy}})}function ys(s,e,t,r,n=new Map){return function(a){const i=this._chaos_url,o=this._chaos_method;if(e.cors){for(const c of e.cors)if(F(i,c.urlPattern)&&(!c.methods||c.methods.includes(o))){const g=U(c,n);if(!q(c,g))continue;const O=D(c.probability,t);if(r==null||r.emit({type:"network:cors",timestamp:Date.now(),applied:O,detail:{url:i,method:o}}),O){console.debug(`[chaos-maker] CORS block: ${o} ${i}`),Object.defineProperty(this,"status",{value:0}),Object.defineProperty(this,"statusText",{value:""}),this.dispatchEvent(new Event("error")),this.dispatchEvent(new Event("loadend"));return}}}if(e.aborts){for(const c of e.aborts)if(F(i,c.urlPattern)&&(!c.methods||c.methods.includes(o))){const g=U(c,n);if(!q(c,g))continue;if(!D(c.probability,t)){ut(r,c,i,o,!1);continue}console.warn(`CHAOS: Aborting ${o} ${i} after ${c.timeout||0}ms`);let A=!1,j;const M=()=>{j&&(clearTimeout(j),j=void 0),typeof this.removeEventListener=="function"&&this.removeEventListener("loadend",p)},y=k=>{A||(A=!0,M(),ut(r,c,i,o,k))},p=()=>{y(!1)},d=()=>{A||(y(!0),this.abort())};typeof this.addEventListener=="function"&&this.addEventListener("loadend",p);try{s.call(this,a)}catch(k){throw y(!1),k}if(A)return;c.timeout?j=setTimeout(d,c.timeout):d();return}}if(e.failures){for(const c of e.failures)if(F(i,c.urlPattern)&&(!c.methods||c.methods.includes(o))){const g=U(c,n);if(!q(c,g))continue;const O=D(c.probability,t);if(r==null||r.emit({type:"network:failure",timestamp:Date.now(),applied:O,detail:{url:i,method:o,statusCode:c.statusCode}}),O){console.warn(`CHAOS: Forcing ${c.statusCode} for ${o} ${i}`),Object.defineProperty(this,"status",{value:c.statusCode}),Object.defineProperty(this,"statusText",{value:c.statusText??"Service Unavailable (Chaos)"});const A=c.body??JSON.stringify({error:"Chaos Maker Attack!"});Object.defineProperty(this,"responseText",{value:A,configurable:!0});const j=c.headers??{};Object.defineProperty(this,"getResponseHeader",{value:M=>{const y=Object.keys(j).find(p=>p.toLowerCase()===M.toLowerCase());return y?j[y]:null},configurable:!0}),Object.defineProperty(this,"getAllResponseHeaders",{value:()=>Object.entries(j).map(([M,y])=>`${M}: ${y}`).join(`\r
4
- `),configurable:!0}),this.dispatchEvent(new Event("error")),this.dispatchEvent(new Event("load")),this.dispatchEvent(new Event("loadend"));return}}}let l=null;if(e.corruptions){for(const c of e.corruptions)if(F(i,c.urlPattern)&&(!c.methods||c.methods.includes(o))){const g=U(c,n);if(!q(c,g))continue;if(!D(c.probability,t)){lt(r,c,i,o,!1);continue}l=c;break}}if(l){let c=!1,g=null;const O=()=>{typeof this.removeEventListener=="function"&&(this.removeEventListener("error",M),this.removeEventListener("abort",M),this.removeEventListener("loadend",y))},A=p=>{c||(c=!0,lt(r,l,i,o,p),O())},j=()=>{if(g!==null)return g;delete this.responseText;try{const p=this.responseText;return typeof p!="string"?(Object.defineProperty(this,"responseText",{value:p,configurable:!0}),A(!1),p):(g=ct(p,l.strategy),Object.defineProperty(this,"responseText",{value:g,configurable:!0}),A(!0),g)}catch(p){throw A(!1),p}},M=()=>{A(!1)},y=()=>{if(!c)try{j()}catch{}};typeof this.addEventListener=="function"&&(this.addEventListener("error",M),this.addEventListener("abort",M),this.addEventListener("loadend",y)),Object.defineProperty(this,"responseText",{get(){return j()},configurable:!0})}if(e.latencies){for(const c of e.latencies)if(F(i,c.urlPattern)&&(!c.methods||c.methods.includes(o))){const g=U(c,n);if(!q(c,g))continue;const O=D(c.probability,t);if(r==null||r.emit({type:"network:latency",timestamp:Date.now(),applied:O,detail:{url:i,method:o,delayMs:c.delayMs}}),O){console.warn(`CHAOS: Adding ${c.delayMs}ms latency to ${o} ${i}`),setTimeout(()=>{s.call(this,a)},c.delayMs);return}}}s.call(this,a)}}function gs(s){return function(e,t){this._chaos_url=t.toString(),this._chaos_method=e.toUpperCase(),s.call(this,e,t)}}function $e(s,e,t,r){const n=D(e.probability,t);if(r==null||r.emit({type:"ui:assault",timestamp:Date.now(),applied:n,detail:{selector:e.selector,action:e.action}}),!!n){console.warn(`CHAOS: Applying action '${e.action}' to element:`,s);try{switch(e.action){case"disable":"disabled"in s&&(s.disabled=!0);break;case"hide":s.style.display="none";break;case"remove":s.remove();break}}catch(a){console.error("Chaos Maker failed to assault element:",a,s)}}}function vs(s,e,t,r){if(s.nodeType!==Node.ELEMENT_NODE||!e.assaults)return;const n=s;for(const a of e.assaults)try{n.matches(a.selector)&&$e(n,a,t,r),n.querySelectorAll(a.selector).forEach(i=>{$e(i,a,t,r)})}catch(i){console.error(`Chaos Maker: Invalid selector '${a.selector}'`,i)}}function _s(s,e,t){if(s.assaults){console.log("CHAOS: Running initial DOM scan for existing elements...");for(const n of s.assaults)try{document.querySelectorAll(n.selector).forEach(a=>{$e(a,n,e,t)})}catch(a){console.error(`Chaos Maker: Invalid selector in initial scan '${n.selector}'`,a)}}return new MutationObserver(n=>{for(const a of n)a.type==="childList"&&a.addedNodes.forEach(i=>vs(i,s,e,t))})}const ft=Symbol.for("chaos-maker.websocket.intercepted");function bs(s,e){return s==="both"?!0:s===e}function ht(s){return typeof s=="string"?"text":"binary"}function pt(s,e){switch(e){case"truncate":return s.slice(0,Math.max(0,Math.floor(s.length/2)));case"malformed-json":return`${s}"}`;case"empty":return"";case"wrong-type":return"<html><body>Unexpected HTML</body></html>"}}function mt(s,e){if(e==="malformed-json"||e==="wrong-type")return null;if(e==="empty")return typeof Blob<"u"&&s instanceof Blob?new Blob([]):s instanceof ArrayBuffer?new ArrayBuffer(0):new Uint8Array(0);if(typeof Blob<"u"&&s instanceof Blob)return s.slice(0,Math.max(0,Math.floor(s.size/2)));if(s instanceof ArrayBuffer)return s.slice(0,Math.max(0,Math.floor(s.byteLength/2)));const t=s,r=Math.max(0,Math.floor(t.byteLength/2));return new Uint8Array(t.buffer.slice(t.byteOffset,t.byteOffset+r))}function fe(s,e,t,r,n){if(!s)return null;for(const a of s){if(!F(e,a.urlPattern)||!bs(a.direction,t))continue;const i=U(a,n);if(q(a,i)&&D(a.probability,r))return a}return null}function Te(s,e,t,r,n){s.emit({type:"websocket:drop",timestamp:Date.now(),applied:!0,detail:{url:e,direction:t,payloadType:r,...n?{reason:n}:{}}})}function yt(s,e,t,r,n){s.emit({type:"websocket:delay",timestamp:Date.now(),applied:!0,detail:{url:e,direction:t,payloadType:r,delayMs:n}})}function he(s,e,t,r,n,a,i){s.emit({type:"websocket:corrupt",timestamp:Date.now(),applied:a,detail:{url:e,direction:t,payloadType:r,strategy:n,...i?{reason:i}:{}}})}function ks(s,e,t,r){s.emit({type:"websocket:close",timestamp:Date.now(),applied:!0,detail:{url:e,closeCode:t,closeReason:r}})}function ws(s,e,t,r,n){const a=new Map;let i=!0;const o=(y,p)=>{let d=a.get(y);d||(d=new Set,a.set(y,d)),d.add(p)},l=(y,p)=>{var d;(d=a.get(y))==null||d.delete(p)},c=(y,p)=>{const d=a.get(y);if(d){for(const k of d)clearTimeout(k.handle),k.kind==="delay"&&Te(t,k.url,k.direction,k.payloadType,p);a.delete(y)}},g=(y,p,d)=>{const k=new MessageEvent("message",{data:d,origin:p.origin,lastEventId:p.lastEventId,source:p.source,ports:Array.from(p.ports??[])});k[ft]=!0,y.dispatchEvent(k)},O=(y,p,d,k)=>{if(!i)return{handled:!1,data:d};const x="outbound",S=ht(d);if(fe(e.drops,p,x,r,n))return Te(t,p,x,S),{handled:!0,data:d};let T=d;const P=fe(e.corruptions,p,x,r,n);if(P)if(S==="text")T=pt(T,P.strategy),he(t,p,x,S,P.strategy,!0);else{const B=mt(T,P.strategy);B===null?he(t,p,x,S,P.strategy,!1,"incompatible-payload-type"):(T=B,he(t,p,x,S,P.strategy,!0))}const V=fe(e.delays,p,x,r,n);if(V){yt(t,p,x,S,V.delayMs);const B={kind:"delay",handle:setTimeout(()=>{l(y,B);try{k(T)}catch{}},V.delayMs),url:p,direction:x,payloadType:S};return o(y,B),{handled:!0,data:T}}return{handled:!1,data:T}},A=(y,p)=>{y.addEventListener("message",d=>{const k=d;if(k[ft]||!i)return;const x="inbound",S=ht(k.data);if(fe(e.drops,p,x,r,n)){k.stopImmediatePropagation(),Te(t,p,x,S);return}let T=k.data,P=!1;const V=fe(e.corruptions,p,x,r,n);if(V)if(S==="text")T=pt(T,V.strategy),P=!0,he(t,p,x,S,V.strategy,!0);else{const ge=mt(T,V.strategy);ge===null?he(t,p,x,S,V.strategy,!1,"incompatible-payload-type"):(T=ge,P=!0,he(t,p,x,S,V.strategy,!0))}const B=fe(e.delays,p,x,r,n);if(B){k.stopImmediatePropagation(),yt(t,p,x,S,B.delayMs);const ge={kind:"delay",handle:setTimeout(()=>{l(y,ge),g(y,k,T)},B.delayMs),url:p,direction:x,payloadType:S};o(y,ge);return}P&&(k.stopImmediatePropagation(),g(y,k,T))})},j=(y,p)=>{if(e.closes)for(const d of e.closes){if(!F(p,d.urlPattern))continue;const k=U(d,n);if(!q(d,k)||!D(d.probability,r))continue;const x=d.code??1e3,S=d.reason??"Chaos Maker close",T=d.afterMs??0,P=()=>{if(i){c(y,"close-interrupt"),ks(t,p,x,S);try{y.close(x,S)}catch{try{y.close()}catch{}}}};if(T<=0)y.readyState===y.OPEN?P():y.addEventListener("open",P,{once:!0});else{const V=()=>{const B={kind:"close",handle:setTimeout(P,T)};o(y,B)};y.readyState===y.OPEN?V():y.addEventListener("open",V,{once:!0})}return}};function M(y,p){const d=new s(y,p),k=typeof y=="string"?y:y.toString(),x=d.send.bind(d);return d.send=function(T){const P=O(d,k,T,x);P.handled||x(P.data)},A(d,k),j(d,k),d}Object.defineProperty(M,"prototype",{value:s.prototype,writable:!1});for(const y of["CONNECTING","OPEN","CLOSING","CLOSED"])M[y]=s[y];return{Wrapped:M,uninstall(){i=!1;for(const[,y]of a)for(const p of y)clearTimeout(p.handle),p.kind==="delay"&&Te(t,p.url,p.direction,p.payloadType,"stop-during-delay");a.clear()}}}class Ie{constructor(e){Z(this,"config");Z(this,"emitter");Z(this,"random");Z(this,"seed");Z(this,"running",!1);Z(this,"originalFetch");Z(this,"originalXhrSend");Z(this,"originalXhrOpen");Z(this,"domObserver");Z(this,"originalWebSocket");Z(this,"webSocketHandle");Z(this,"requestCounters",new Map);this.config=nt(e),this.emitter=new ot;const t=it(e.seed);this.random=t.random,this.seed=t.seed,console.log(`Chaos Maker initialized (seed: ${this.seed})`)}getSeed(){return this.seed}on(e,t){this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}getLog(){return this.emitter.getLog()}clearLog(){this.emitter.clearLog()}start(){if(this.running){console.warn("Chaos Maker is already running. Call stop() first.");return}this.requestCounters.clear(),this.running=!0,console.log("🛠️ Chaos Maker ENGAGED 🛠️"),this.config.network&&(this.originalFetch=window.fetch,window.fetch=ms(this.originalFetch.bind(window),this.config.network,this.random,this.emitter,this.requestCounters),this.originalXhrOpen=window.XMLHttpRequest.prototype.open,window.XMLHttpRequest.prototype.open=gs(this.originalXhrOpen),this.originalXhrSend=window.XMLHttpRequest.prototype.send,window.XMLHttpRequest.prototype.send=ys(this.originalXhrSend,this.config.network,this.random,this.emitter,this.requestCounters)),this.config.ui&&(this.domObserver=_s(this.config.ui,this.random,this.emitter),this.domObserver.observe(document.body,{childList:!0,subtree:!0}),console.log("UI Assailant is now observing the DOM.")),this.config.websocket&&typeof window<"u"&&typeof window.WebSocket<"u"&&(this.originalWebSocket=window.WebSocket,this.webSocketHandle=ws(this.originalWebSocket,this.config.websocket,this.emitter,this.random,this.requestCounters),window.WebSocket=this.webSocketHandle.Wrapped)}stop(){this.running=!1,console.log("🛑 Chaos Maker DISENGAGED 🛑"),this.originalFetch&&(window.fetch=this.originalFetch),this.originalXhrSend&&(window.XMLHttpRequest.prototype.send=this.originalXhrSend),this.originalXhrOpen&&(window.XMLHttpRequest.prototype.open=this.originalXhrOpen),this.domObserver&&(this.domObserver.disconnect(),console.log("UI Assailant has stopped observing.")),this.originalWebSocket&&(window.WebSocket=this.originalWebSocket,this.originalWebSocket=void 0),this.webSocketHandle&&(this.webSocketHandle.uninstall(),this.webSocketHandle=void 0)}}function gt(s){return JSON.parse(JSON.stringify(s))}class xs{constructor(e){Z(this,"config");this.config=e?gt(e):{network:{},ui:{},websocket:{}},this.config.network||(this.config.network={}),this.config.ui||(this.config.ui={}),this.config.websocket||(this.config.websocket={})}failRequests(e,t,r,n,a,i,o){return this.config.network.failures||(this.config.network.failures=[]),this.config.network.failures.push({urlPattern:e,statusCode:t,probability:r,methods:n,body:a,headers:i,...o}),this}addLatency(e,t,r,n,a){return this.config.network.latencies||(this.config.network.latencies=[]),this.config.network.latencies.push({urlPattern:e,delayMs:t,probability:r,methods:n,...a}),this}abortRequests(e,t,r,n,a){return this.config.network.aborts||(this.config.network.aborts=[]),this.config.network.aborts.push({urlPattern:e,probability:t,timeout:r,methods:n,...a}),this}corruptResponses(e,t,r,n,a){return this.config.network.corruptions||(this.config.network.corruptions=[]),this.config.network.corruptions.push({urlPattern:e,strategy:t,probability:r,methods:n,...a}),this}simulateCors(e,t,r,n){return this.config.network.cors||(this.config.network.cors=[]),this.config.network.cors.push({urlPattern:e,probability:t,methods:r,...n}),this}failRequestsOnNth(e,t,r,n){return this.failRequests(e,t,1,n,void 0,void 0,{onNth:r})}addLatencyOnNth(e,t,r,n){return this.addLatency(e,t,1,n,{onNth:r})}abortRequestsOnNth(e,t,r,n){return this.abortRequests(e,1,r,n,{onNth:t})}corruptResponsesOnNth(e,t,r,n){return this.corruptResponses(e,t,1,n,{onNth:r})}simulateCorsOnNth(e,t,r){return this.simulateCors(e,1,r,{onNth:t})}failRequestsEveryNth(e,t,r,n){return this.failRequests(e,t,1,n,void 0,void 0,{everyNth:r})}addLatencyEveryNth(e,t,r,n){return this.addLatency(e,t,1,n,{everyNth:r})}abortRequestsEveryNth(e,t,r,n){return this.abortRequests(e,1,r,n,{everyNth:t})}corruptResponsesEveryNth(e,t,r,n){return this.corruptResponses(e,t,1,n,{everyNth:r})}simulateCorsEveryNth(e,t,r){return this.simulateCors(e,1,r,{everyNth:t})}failRequestsAfterN(e,t,r,n){return this.failRequests(e,t,1,n,void 0,void 0,{afterN:r})}addLatencyAfterN(e,t,r,n){return this.addLatency(e,t,1,n,{afterN:r})}abortRequestsAfterN(e,t,r,n){return this.abortRequests(e,1,r,n,{afterN:t})}corruptResponsesAfterN(e,t,r,n){return this.corruptResponses(e,t,1,n,{afterN:r})}simulateCorsAfterN(e,t,r){return this.simulateCors(e,1,r,{afterN:t})}assaultUi(e,t,r){return this.config.ui.assaults||(this.config.ui.assaults=[]),this.config.ui.assaults.push({selector:e,action:t,probability:r}),this}dropMessages(e,t,r,n){return this.config.websocket.drops||(this.config.websocket.drops=[]),this.config.websocket.drops.push({urlPattern:e,direction:t,probability:r,...n}),this}delayMessages(e,t,r,n,a){return this.config.websocket.delays||(this.config.websocket.delays=[]),this.config.websocket.delays.push({urlPattern:e,direction:t,delayMs:r,probability:n,...a}),this}corruptMessages(e,t,r,n,a){return this.config.websocket.corruptions||(this.config.websocket.corruptions=[]),this.config.websocket.corruptions.push({urlPattern:e,direction:t,strategy:r,probability:n,...a}),this}closeConnection(e,t,r,n){return this.config.websocket.closes||(this.config.websocket.closes=[]),this.config.websocket.closes.push({urlPattern:e,probability:t,...r,...n}),this}dropMessagesOnNth(e,t,r){return this.dropMessages(e,t,1,{onNth:r})}delayMessagesOnNth(e,t,r,n){return this.delayMessages(e,t,r,1,{onNth:n})}withSeed(e){return this.config.seed=e,this}build(){return gt(this.config)}}const ae="*";function vt(s){if(s&&typeof s=="object"&&!Object.isFrozen(s)){Object.freeze(s);for(const e of Object.values(s))vt(e)}return s}const Cs=vt({unstableApi:{network:{failures:[{urlPattern:"/api/",statusCode:500,probability:.1}],latencies:[{urlPattern:"/api/",delayMs:1e3,probability:.2}]}},slowNetwork:{network:{latencies:[{urlPattern:ae,delayMs:2e3,probability:1}]}},offlineMode:{network:{cors:[{urlPattern:ae,probability:1}]}},flakyConnection:{network:{aborts:[{urlPattern:ae,probability:.05}],latencies:[{urlPattern:ae,delayMs:3e3,probability:.1}]}},degradedUi:{ui:{assaults:[{selector:"button",action:"disable",probability:.2},{selector:"a",action:"hide",probability:.1}]}},unreliableWebSocket:{websocket:{drops:[{urlPattern:ae,direction:"both",probability:.1}],delays:[{urlPattern:ae,direction:"inbound",delayMs:500,probability:1}],corruptions:[{urlPattern:ae,direction:"inbound",strategy:"truncate",probability:.05}]}}});if(typeof window<"u"){window.ChaosMaker=Ie;const s={instance:null,start:e=>{try{return s.instance&&s.instance.stop(),s.instance=new Ie(e),s.instance.start(),{success:!0,message:"Chaos started"}}catch(t){return console.error("Chaos Utils Error:",t),{success:!1,message:t.message}}},stop:()=>s.instance?(s.instance.stop(),s.instance=null,{success:!0,message:"Chaos stopped"}):{success:!1,message:"No chaos instance to stop"},getLog:()=>s.instance?s.instance.getLog():[],getSeed:()=>s.instance?s.instance.getSeed():null};if(window.chaosUtils=s,window.__CHAOS_CONFIG__)try{const e=window.__CHAOS_CONFIG__;s.start(e),delete window.__CHAOS_CONFIG__}catch(e){console.error("ChaosMaker auto-start failed:",e)}}E.ChaosConfigBuilder=xs,E.ChaosConfigError=st,E.ChaosEventEmitter=ot,E.ChaosMaker=Ie,E.createPrng=it,E.generateSeed=at,E.presets=Cs,E.validateConfig=nt,Object.defineProperty(E,Symbol.toStringTag,{value:"Module"})}));
1
+ (function(R,x){typeof exports=="object"&&typeof module<"u"?x(exports):typeof define=="function"&&define.amd?define(["exports"],x):(R=typeof globalThis<"u"?globalThis:R||self,x(R.ChaosMaker={}))})(this,(function(R){"use strict";var bn=Object.defineProperty;var kn=(R,x,ce)=>x in R?bn(R,x,{enumerable:!0,configurable:!0,writable:!0,value:ce}):R[x]=ce;var L=(R,x,ce)=>kn(R,typeof x!="symbol"?x+"":x,ce);var x;(function(r){r.assertEqual=s=>{};function e(s){}r.assertIs=e;function t(s){throw new Error}r.assertNever=t,r.arrayToEnum=s=>{const a={};for(const o of s)a[o]=o;return a},r.getValidEnumValues=s=>{const a=r.objectKeys(s).filter(i=>typeof s[s[i]]!="number"),o={};for(const i of a)o[i]=s[i];return r.objectValues(o)},r.objectValues=s=>r.objectKeys(s).map(function(a){return s[a]}),r.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const a=[];for(const o in s)Object.prototype.hasOwnProperty.call(s,o)&&a.push(o);return a},r.find=(s,a)=>{for(const o of s)if(a(o))return o},r.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,a=" | "){return s.map(o=>typeof o=="string"?`'${o}'`:o).join(a)}r.joinValues=n,r.jsonStringifyReplacer=(s,a)=>typeof a=="bigint"?a.toString():a})(x||(x={}));var ce;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(ce||(ce={}));const g=x.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),re=r=>{switch(typeof r){case"undefined":return g.undefined;case"string":return g.string;case"number":return Number.isNaN(r)?g.nan:g.number;case"boolean":return g.boolean;case"function":return g.function;case"bigint":return g.bigint;case"symbol":return g.symbol;case"object":return Array.isArray(r)?g.array:r===null?g.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?g.promise:typeof Map<"u"&&r instanceof Map?g.map:typeof Set<"u"&&r instanceof Set?g.set:typeof Date<"u"&&r instanceof Date?g.date:g.object;default:return g.unknown}},d=x.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 Y extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(a){return a.message},n={_errors:[]},s=a=>{for(const o of a.issues)if(o.code==="invalid_union")o.unionErrors.map(s);else if(o.code==="invalid_return_type")s(o.returnTypeError);else if(o.code==="invalid_arguments")s(o.argumentsError);else if(o.path.length===0)n._errors.push(t(o));else{let i=n,u=0;for(;u<o.path.length;){const y=o.path[u];u===o.path.length-1?(i[y]=i[y]||{_errors:[]},i[y]._errors.push(t(o))):i[y]=i[y]||{_errors:[]},i=i[y],u++}}};return s(this),n}static assert(e){if(!(e instanceof Y))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,x.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},n=[];for(const s of this.issues)if(s.path.length>0){const a=s.path[0];t[a]=t[a]||[],t[a].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}}Y.create=r=>new Y(r);const Fe=(r,e)=>{let t;switch(r.code){case d.invalid_type:r.received===g.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case d.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,x.jsonStringifyReplacer)}`;break;case d.unrecognized_keys:t=`Unrecognized key(s) in object: ${x.joinValues(r.keys,", ")}`;break;case d.invalid_union:t="Invalid input";break;case d.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${x.joinValues(r.options)}`;break;case d.invalid_enum_value:t=`Invalid enum value. Expected ${x.joinValues(r.options)}, received '${r.received}'`;break;case d.invalid_arguments:t="Invalid function arguments";break;case d.invalid_return_type:t="Invalid function return type";break;case d.invalid_date:t="Invalid date";break;case d.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:x.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case d.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case d.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case d.custom:t="Invalid input";break;case d.invalid_intersection_types:t="Intersection results could not be merged";break;case d.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case d.not_finite:t="Number must be finite";break;default:t=e.defaultError,x.assertNever(r)}return{message:t}};let Ut=Fe;function Wt(){return Ut}const Bt=r=>{const{data:e,path:t,errorMaps:n,issueData:s}=r,a=[...t,...s.path||[]],o={...s,path:a};if(s.message!==void 0)return{...s,path:a,message:s.message};let i="";const u=n.filter(y=>!!y).slice().reverse();for(const y of u)i=y(o,{data:e,defaultError:i}).message;return{...s,path:a,message:i}};function p(r,e){const t=Wt(),n=Bt({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===Fe?void 0:Fe].filter(s=>!!s)});r.common.issues.push(n)}class Z{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const n=[];for(const s of t){if(s.status==="aborted")return w;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){const n=[];for(const s of t){const a=await s.key,o=await s.value;n.push({key:a,value:o})}return Z.mergeObjectSync(e,n)}static mergeObjectSync(e,t){const n={};for(const s of t){const{key:a,value:o}=s;if(a.status==="aborted"||o.status==="aborted")return w;a.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof o.value<"u"||s.alwaysSet)&&(n[a.value]=o.value)}return{status:e.value,value:n}}}const w=Object.freeze({status:"aborted"}),_e=r=>({status:"dirty",value:r}),B=r=>({status:"valid",value:r}),ot=r=>r.status==="aborted",ct=r=>r.status==="dirty",de=r=>r.status==="valid",Ne=r=>typeof Promise<"u"&&r instanceof Promise;var v;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(v||(v={}));class X{constructor(e,t,n,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const ut=(r,e)=>{if(de(e))return{success:!0,data:e.value};if(!r.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 Y(r.common.issues);return this._error=t,this._error}}};function S(r){if(!r)return{};const{errorMap:e,invalid_type_error:t,required_error:n,description:s}=r;if(e&&(t||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(o,i)=>{const{message:u}=r;return o.code==="invalid_enum_value"?{message:u??i.defaultError}:typeof i.data>"u"?{message:u??n??i.defaultError}:o.code!=="invalid_type"?{message:i.defaultError}:{message:u??t??i.defaultError}},description:s}}class N{get description(){return this._def.description}_getType(e){return re(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:re(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Z,ctx:{common:e.parent.common,data:e.data,parsedType:re(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(Ne(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 n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){const n={common:{issues:[],async:(t==null?void 0:t.async)??!1,contextualErrorMap:t==null?void 0:t.errorMap},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:re(e)},s=this._parseSync({data:e,path:n.path,parent:n});return ut(n,s)}"~validate"(e){var n,s;const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:re(e)};if(!this["~standard"].async)try{const a=this._parseSync({data:e,path:[],parent:t});return de(a)?{value:a.value}:{issues:t.common.issues}}catch(a){(s=(n=a==null?void 0:a.message)==null?void 0:n.toLowerCase())!=null&&s.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(a=>de(a)?{value:a.value}:{issues:t.common.issues})}async parseAsync(e,t){const n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){const n={common:{issues:[],contextualErrorMap:t==null?void 0:t.errorMap,async:!0},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:re(e)},s=this._parse({data:e,path:n.path,parent:n}),a=await(Ne(s)?s:Promise.resolve(s));return ut(n,a)}refine(e,t){const n=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,a)=>{const o=e(s),i=()=>a.addIssue({code:d.custom,...n(s)});return typeof Promise<"u"&&o instanceof Promise?o.then(u=>u?!0:(i(),!1)):o?!0:(i(),!1)})}refinement(e,t){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof t=="function"?t(n,s):t),!1))}_refinement(e){return new me({schema:this,typeName:k.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}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),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return se.create(this,this._def)}nullable(){return ye.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Q.create(this)}promise(){return Pe.create(this,this._def)}or(e){return Re.create([this,e],this._def)}and(e){return Me.create(this,e,this._def)}transform(e){return new me({...S(this._def),schema:this,typeName:k.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new Be({...S(this._def),innerType:this,defaultValue:t,typeName:k.ZodDefault})}brand(){return new mr({typeName:k.ZodBranded,type:this,...S(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new He({...S(this._def),innerType:this,catchValue:t,typeName:k.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Ge.create(this,e)}readonly(){return Xe.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Ht=/^c[^\s-]{8,}$/i,Gt=/^[0-9a-z]+$/,Xt=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Qt=/^[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,Jt=/^[a-z0-9_-]{21}$/i,Yt=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Kt=/^[-+]?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)?)??$/,er=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,tr="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Ue;const rr=/^(?:(?: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])$/,nr=/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,sr=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ar=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,ir=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,or=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,lt="((\\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])))",cr=new RegExp(`^${lt}$`);function dt(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);const t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function ur(r){return new RegExp(`^${dt(r)}$`)}function lr(r){let e=`${lt}T${dt(r)}`;const t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function dr(r,e){return!!((e==="v4"||!e)&&rr.test(r)||(e==="v6"||!e)&&sr.test(r))}function fr(r,e){if(!Yt.test(r))return!1;try{const[t]=r.split(".");if(!t)return!1;const n=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&(s==null?void 0:s.typ)!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function hr(r,e){return!!((e==="v4"||!e)&&nr.test(r)||(e==="v6"||!e)&&ar.test(r))}class K extends N{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==g.string){const a=this._getOrReturnCtx(e);return p(a,{code:d.invalid_type,expected:g.string,received:a.parsedType}),w}const n=new Z;let s;for(const a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(s=this._getOrReturnCtx(e,s),p(s,{code:d.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="max")e.data.length>a.value&&(s=this._getOrReturnCtx(e,s),p(s,{code:d.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="length"){const o=e.data.length>a.value,i=e.data.length<a.value;(o||i)&&(s=this._getOrReturnCtx(e,s),o?p(s,{code:d.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):i&&p(s,{code:d.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),n.dirty())}else if(a.kind==="email")er.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"email",code:d.invalid_string,message:a.message}),n.dirty());else if(a.kind==="emoji")Ue||(Ue=new RegExp(tr,"u")),Ue.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"emoji",code:d.invalid_string,message:a.message}),n.dirty());else if(a.kind==="uuid")Qt.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"uuid",code:d.invalid_string,message:a.message}),n.dirty());else if(a.kind==="nanoid")Jt.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"nanoid",code:d.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid")Ht.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"cuid",code:d.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid2")Gt.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"cuid2",code:d.invalid_string,message:a.message}),n.dirty());else if(a.kind==="ulid")Xt.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"ulid",code:d.invalid_string,message:a.message}),n.dirty());else if(a.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),p(s,{validation:"url",code:d.invalid_string,message:a.message}),n.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"regex",code:d.invalid_string,message:a.message}),n.dirty())):a.kind==="trim"?e.data=e.data.trim():a.kind==="includes"?e.data.includes(a.value,a.position)||(s=this._getOrReturnCtx(e,s),p(s,{code:d.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),n.dirty()):a.kind==="toLowerCase"?e.data=e.data.toLowerCase():a.kind==="toUpperCase"?e.data=e.data.toUpperCase():a.kind==="startsWith"?e.data.startsWith(a.value)||(s=this._getOrReturnCtx(e,s),p(s,{code:d.invalid_string,validation:{startsWith:a.value},message:a.message}),n.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(s=this._getOrReturnCtx(e,s),p(s,{code:d.invalid_string,validation:{endsWith:a.value},message:a.message}),n.dirty()):a.kind==="datetime"?lr(a).test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{code:d.invalid_string,validation:"datetime",message:a.message}),n.dirty()):a.kind==="date"?cr.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{code:d.invalid_string,validation:"date",message:a.message}),n.dirty()):a.kind==="time"?ur(a).test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{code:d.invalid_string,validation:"time",message:a.message}),n.dirty()):a.kind==="duration"?Kt.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"duration",code:d.invalid_string,message:a.message}),n.dirty()):a.kind==="ip"?dr(e.data,a.version)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"ip",code:d.invalid_string,message:a.message}),n.dirty()):a.kind==="jwt"?fr(e.data,a.alg)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"jwt",code:d.invalid_string,message:a.message}),n.dirty()):a.kind==="cidr"?hr(e.data,a.version)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"cidr",code:d.invalid_string,message:a.message}),n.dirty()):a.kind==="base64"?ir.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"base64",code:d.invalid_string,message:a.message}),n.dirty()):a.kind==="base64url"?or.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"base64url",code:d.invalid_string,message:a.message}),n.dirty()):x.assertNever(a);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(s=>e.test(s),{validation:t,code:d.invalid_string,...v.errToObj(n)})}_addCheck(e){return new K({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...v.errToObj(e)})}url(e){return this._addCheck({kind:"url",...v.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...v.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...v.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...v.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...v.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...v.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...v.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...v.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...v.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...v.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...v.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...v.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(e==null?void 0:e.offset)??!1,local:(e==null?void 0:e.local)??!1,...v.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...v.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...v.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...v.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t==null?void 0:t.position,...v.errToObj(t==null?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...v.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...v.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...v.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...v.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...v.errToObj(t)})}nonempty(e){return this.min(1,v.errToObj(e))}trim(){return new K({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new K({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new K({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}K.create=r=>new K({checks:[],typeName:k.ZodString,coerce:(r==null?void 0:r.coerce)??!1,...S(r)});function pr(r,e){const t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=t>n?t:n,a=Number.parseInt(r.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return a%o/10**s}class fe extends N{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==g.number){const a=this._getOrReturnCtx(e);return p(a,{code:d.invalid_type,expected:g.number,received:a.parsedType}),w}let n;const s=new Z;for(const a of this._def.checks)a.kind==="int"?x.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:d.invalid_type,expected:"integer",received:"float",message:a.message}),s.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(n=this._getOrReturnCtx(e,n),p(n,{code:d.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),p(n,{code:d.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="multipleOf"?pr(e.data,a.value)!==0&&(n=this._getOrReturnCtx(e,n),p(n,{code:d.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:d.not_finite,message:a.message}),s.dirty()):x.assertNever(a);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,v.toString(t))}gt(e,t){return this.setLimit("min",e,!1,v.toString(t))}lte(e,t){return this.setLimit("max",e,!0,v.toString(t))}lt(e,t){return this.setLimit("max",e,!1,v.toString(t))}setLimit(e,t,n,s){return new fe({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:v.toString(s)}]})}_addCheck(e){return new fe({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:v.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:v.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:v.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:v.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:v.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:v.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:v.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:v.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:v.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&x.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}}fe.create=r=>new fe({checks:[],typeName:k.ZodNumber,coerce:(r==null?void 0:r.coerce)||!1,...S(r)});class be extends N{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==g.bigint)return this._getInvalidInput(e);let n;const s=new Z;for(const a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(n=this._getOrReturnCtx(e,n),p(n,{code:d.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),p(n,{code:d.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),p(n,{code:d.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):x.assertNever(a);return{status:s.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return p(t,{code:d.invalid_type,expected:g.bigint,received:t.parsedType}),w}gte(e,t){return this.setLimit("min",e,!0,v.toString(t))}gt(e,t){return this.setLimit("min",e,!1,v.toString(t))}lte(e,t){return this.setLimit("max",e,!0,v.toString(t))}lt(e,t){return this.setLimit("max",e,!1,v.toString(t))}setLimit(e,t,n,s){return new be({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:v.toString(s)}]})}_addCheck(e){return new be({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:v.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:v.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:v.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:v.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:v.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}be.create=r=>new be({checks:[],typeName:k.ZodBigInt,coerce:(r==null?void 0:r.coerce)??!1,...S(r)});class ft extends N{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==g.boolean){const n=this._getOrReturnCtx(e);return p(n,{code:d.invalid_type,expected:g.boolean,received:n.parsedType}),w}return B(e.data)}}ft.create=r=>new ft({typeName:k.ZodBoolean,coerce:(r==null?void 0:r.coerce)||!1,...S(r)});class Ae extends N{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==g.date){const a=this._getOrReturnCtx(e);return p(a,{code:d.invalid_type,expected:g.date,received:a.parsedType}),w}if(Number.isNaN(e.data.getTime())){const a=this._getOrReturnCtx(e);return p(a,{code:d.invalid_date}),w}const n=new Z;let s;for(const a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(s=this._getOrReturnCtx(e,s),p(s,{code:d.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),n.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(s=this._getOrReturnCtx(e,s),p(s,{code:d.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),n.dirty()):x.assertNever(a);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Ae({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:v.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:v.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}Ae.create=r=>new Ae({checks:[],coerce:(r==null?void 0:r.coerce)||!1,typeName:k.ZodDate,...S(r)});class ht extends N{_parse(e){if(this._getType(e)!==g.symbol){const n=this._getOrReturnCtx(e);return p(n,{code:d.invalid_type,expected:g.symbol,received:n.parsedType}),w}return B(e.data)}}ht.create=r=>new ht({typeName:k.ZodSymbol,...S(r)});class pt extends N{_parse(e){if(this._getType(e)!==g.undefined){const n=this._getOrReturnCtx(e);return p(n,{code:d.invalid_type,expected:g.undefined,received:n.parsedType}),w}return B(e.data)}}pt.create=r=>new pt({typeName:k.ZodUndefined,...S(r)});class mt extends N{_parse(e){if(this._getType(e)!==g.null){const n=this._getOrReturnCtx(e);return p(n,{code:d.invalid_type,expected:g.null,received:n.parsedType}),w}return B(e.data)}}mt.create=r=>new mt({typeName:k.ZodNull,...S(r)});class ke extends N{constructor(){super(...arguments),this._any=!0}_parse(e){return B(e.data)}}ke.create=r=>new ke({typeName:k.ZodAny,...S(r)});class yt extends N{constructor(){super(...arguments),this._unknown=!0}_parse(e){return B(e.data)}}yt.create=r=>new yt({typeName:k.ZodUnknown,...S(r)});class ne extends N{_parse(e){const t=this._getOrReturnCtx(e);return p(t,{code:d.invalid_type,expected:g.never,received:t.parsedType}),w}}ne.create=r=>new ne({typeName:k.ZodNever,...S(r)});class gt extends N{_parse(e){if(this._getType(e)!==g.undefined){const n=this._getOrReturnCtx(e);return p(n,{code:d.invalid_type,expected:g.void,received:n.parsedType}),w}return B(e.data)}}gt.create=r=>new gt({typeName:k.ZodVoid,...S(r)});class Q extends N{_parse(e){const{ctx:t,status:n}=this._processInputParams(e),s=this._def;if(t.parsedType!==g.array)return p(t,{code:d.invalid_type,expected:g.array,received:t.parsedType}),w;if(s.exactLength!==null){const o=t.data.length>s.exactLength.value,i=t.data.length<s.exactLength.value;(o||i)&&(p(t,{code:o?d.too_big:d.too_small,minimum:i?s.exactLength.value:void 0,maximum:o?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(p(t,{code:d.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(p(t,{code:d.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((o,i)=>s.type._parseAsync(new X(t,o,t.path,i)))).then(o=>Z.mergeArray(n,o));const a=[...t.data].map((o,i)=>s.type._parseSync(new X(t,o,t.path,i)));return Z.mergeArray(n,a)}get element(){return this._def.type}min(e,t){return new Q({...this._def,minLength:{value:e,message:v.toString(t)}})}max(e,t){return new Q({...this._def,maxLength:{value:e,message:v.toString(t)}})}length(e,t){return new Q({...this._def,exactLength:{value:e,message:v.toString(t)}})}nonempty(e){return this.min(1,e)}}Q.create=(r,e)=>new Q({type:r,minLength:null,maxLength:null,exactLength:null,typeName:k.ZodArray,...S(e)});function he(r){if(r instanceof M){const e={};for(const t in r.shape){const n=r.shape[t];e[t]=se.create(he(n))}return new M({...r._def,shape:()=>e})}else return r instanceof Q?new Q({...r._def,type:he(r.element)}):r instanceof se?se.create(he(r.unwrap())):r instanceof ye?ye.create(he(r.unwrap())):r instanceof ue?ue.create(r.items.map(e=>he(e))):r}class M extends N{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),t=x.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==g.object){const y=this._getOrReturnCtx(e);return p(y,{code:d.invalid_type,expected:g.object,received:y.parsedType}),w}const{status:n,ctx:s}=this._processInputParams(e),{shape:a,keys:o}=this._getCached(),i=[];if(!(this._def.catchall instanceof ne&&this._def.unknownKeys==="strip"))for(const y in s.data)o.includes(y)||i.push(y);const u=[];for(const y of o){const C=a[y],j=s.data[y];u.push({key:{status:"valid",value:y},value:C._parse(new X(s,j,s.path,y)),alwaysSet:y in s.data})}if(this._def.catchall instanceof ne){const y=this._def.unknownKeys;if(y==="passthrough")for(const C of i)u.push({key:{status:"valid",value:C},value:{status:"valid",value:s.data[C]}});else if(y==="strict")i.length>0&&(p(s,{code:d.unrecognized_keys,keys:i}),n.dirty());else if(y!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const y=this._def.catchall;for(const C of i){const j=s.data[C];u.push({key:{status:"valid",value:C},value:y._parse(new X(s,j,s.path,C)),alwaysSet:C in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const y=[];for(const C of u){const j=await C.key,U=await C.value;y.push({key:j,value:U,alwaysSet:C.alwaysSet})}return y}).then(y=>Z.mergeObjectSync(n,y)):Z.mergeObjectSync(n,u)}get shape(){return this._def.shape()}strict(e){return v.errToObj,new M({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{var a,o;const s=((o=(a=this._def).errorMap)==null?void 0:o.call(a,t,n).message)??n.defaultError;return t.code==="unrecognized_keys"?{message:v.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new M({...this._def,unknownKeys:"strip"})}passthrough(){return new M({...this._def,unknownKeys:"passthrough"})}extend(e){return new M({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new M({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:k.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new M({...this._def,catchall:e})}pick(e){const t={};for(const n of x.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new M({...this._def,shape:()=>t})}omit(e){const t={};for(const n of x.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new M({...this._def,shape:()=>t})}deepPartial(){return he(this)}partial(e){const t={};for(const n of x.objectKeys(this.shape)){const s=this.shape[n];e&&!e[n]?t[n]=s:t[n]=s.optional()}return new M({...this._def,shape:()=>t})}required(e){const t={};for(const n of x.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let a=this.shape[n];for(;a instanceof se;)a=a._def.innerType;t[n]=a}return new M({...this._def,shape:()=>t})}keyof(){return kt(x.objectKeys(this.shape))}}M.create=(r,e)=>new M({shape:()=>r,unknownKeys:"strip",catchall:ne.create(),typeName:k.ZodObject,...S(e)}),M.strictCreate=(r,e)=>new M({shape:()=>r,unknownKeys:"strict",catchall:ne.create(),typeName:k.ZodObject,...S(e)}),M.lazycreate=(r,e)=>new M({shape:r,unknownKeys:"strip",catchall:ne.create(),typeName:k.ZodObject,...S(e)});class Re extends N{_parse(e){const{ctx:t}=this._processInputParams(e),n=this._def.options;function s(a){for(const i of a)if(i.result.status==="valid")return i.result;for(const i of a)if(i.result.status==="dirty")return t.common.issues.push(...i.ctx.common.issues),i.result;const o=a.map(i=>new Y(i.ctx.common.issues));return p(t,{code:d.invalid_union,unionErrors:o}),w}if(t.common.async)return Promise.all(n.map(async a=>{const o={...t,common:{...t.common,issues:[]},parent:null};return{result:await a._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(s);{let a;const o=[];for(const u of n){const y={...t,common:{...t.common,issues:[]},parent:null},C=u._parseSync({data:t.data,path:t.path,parent:y});if(C.status==="valid")return C;C.status==="dirty"&&!a&&(a={result:C,ctx:y}),y.common.issues.length&&o.push(y.common.issues)}if(a)return t.common.issues.push(...a.ctx.common.issues),a.result;const i=o.map(u=>new Y(u));return p(t,{code:d.invalid_union,unionErrors:i}),w}}get options(){return this._def.options}}Re.create=(r,e)=>new Re({options:r,typeName:k.ZodUnion,...S(e)});function We(r,e){const t=re(r),n=re(e);if(r===e)return{valid:!0,data:r};if(t===g.object&&n===g.object){const s=x.objectKeys(e),a=x.objectKeys(r).filter(i=>s.indexOf(i)!==-1),o={...r,...e};for(const i of a){const u=We(r[i],e[i]);if(!u.valid)return{valid:!1};o[i]=u.data}return{valid:!0,data:o}}else if(t===g.array&&n===g.array){if(r.length!==e.length)return{valid:!1};const s=[];for(let a=0;a<r.length;a++){const o=r[a],i=e[a],u=We(o,i);if(!u.valid)return{valid:!1};s.push(u.data)}return{valid:!0,data:s}}else return t===g.date&&n===g.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}class Me extends N{_parse(e){const{status:t,ctx:n}=this._processInputParams(e),s=(a,o)=>{if(ot(a)||ot(o))return w;const i=We(a.value,o.value);return i.valid?((ct(a)||ct(o))&&t.dirty(),{status:t.value,value:i.data}):(p(n,{code:d.invalid_intersection_types}),w)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([a,o])=>s(a,o)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}Me.create=(r,e,t)=>new Me({left:r,right:e,typeName:k.ZodIntersection,...S(t)});class ue extends N{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==g.array)return p(n,{code:d.invalid_type,expected:g.array,received:n.parsedType}),w;if(n.data.length<this._def.items.length)return p(n,{code:d.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),w;!this._def.rest&&n.data.length>this._def.items.length&&(p(n,{code:d.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const a=[...n.data].map((o,i)=>{const u=this._def.items[i]||this._def.rest;return u?u._parse(new X(n,o,n.path,i)):null}).filter(o=>!!o);return n.common.async?Promise.all(a).then(o=>Z.mergeArray(t,o)):Z.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new ue({...this._def,rest:e})}}ue.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ue({items:r,typeName:k.ZodTuple,rest:null,...S(e)})};class Le extends N{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==g.object)return p(n,{code:d.invalid_type,expected:g.object,received:n.parsedType}),w;const s=[],a=this._def.keyType,o=this._def.valueType;for(const i in n.data)s.push({key:a._parse(new X(n,i,n.path,i)),value:o._parse(new X(n,n.data[i],n.path,i)),alwaysSet:i in n.data});return n.common.async?Z.mergeObjectAsync(t,s):Z.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof N?new Le({keyType:e,valueType:t,typeName:k.ZodRecord,...S(n)}):new Le({keyType:K.create(),valueType:e,typeName:k.ZodRecord,...S(t)})}}class vt extends N{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==g.map)return p(n,{code:d.invalid_type,expected:g.map,received:n.parsedType}),w;const s=this._def.keyType,a=this._def.valueType,o=[...n.data.entries()].map(([i,u],y)=>({key:s._parse(new X(n,i,n.path,[y,"key"])),value:a._parse(new X(n,u,n.path,[y,"value"]))}));if(n.common.async){const i=new Map;return Promise.resolve().then(async()=>{for(const u of o){const y=await u.key,C=await u.value;if(y.status==="aborted"||C.status==="aborted")return w;(y.status==="dirty"||C.status==="dirty")&&t.dirty(),i.set(y.value,C.value)}return{status:t.value,value:i}})}else{const i=new Map;for(const u of o){const y=u.key,C=u.value;if(y.status==="aborted"||C.status==="aborted")return w;(y.status==="dirty"||C.status==="dirty")&&t.dirty(),i.set(y.value,C.value)}return{status:t.value,value:i}}}}vt.create=(r,e,t)=>new vt({valueType:e,keyType:r,typeName:k.ZodMap,...S(t)});class we extends N{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==g.set)return p(n,{code:d.invalid_type,expected:g.set,received:n.parsedType}),w;const s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(p(n,{code:d.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(p(n,{code:d.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());const a=this._def.valueType;function o(u){const y=new Set;for(const C of u){if(C.status==="aborted")return w;C.status==="dirty"&&t.dirty(),y.add(C.value)}return{status:t.value,value:y}}const i=[...n.data.values()].map((u,y)=>a._parse(new X(n,u,n.path,y)));return n.common.async?Promise.all(i).then(u=>o(u)):o(i)}min(e,t){return new we({...this._def,minSize:{value:e,message:v.toString(t)}})}max(e,t){return new we({...this._def,maxSize:{value:e,message:v.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}we.create=(r,e)=>new we({valueType:r,minSize:null,maxSize:null,typeName:k.ZodSet,...S(e)});class _t extends N{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})}}_t.create=(r,e)=>new _t({getter:r,typeName:k.ZodLazy,...S(e)});class bt extends N{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return p(t,{received:t.data,code:d.invalid_literal,expected:this._def.value}),w}return{status:"valid",value:e.data}}get value(){return this._def.value}}bt.create=(r,e)=>new bt({value:r,typeName:k.ZodLiteral,...S(e)});function kt(r,e){return new pe({values:r,typeName:k.ZodEnum,...S(e)})}class pe extends N{_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),n=this._def.values;return p(t,{expected:x.joinValues(n),received:t.parsedType,code:d.invalid_type}),w}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),n=this._def.values;return p(t,{received:t.data,code:d.invalid_enum_value,options:n}),w}return B(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 pe.create(e,{...this._def,...t})}exclude(e,t=this._def){return pe.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}}pe.create=kt;class wt extends N{_parse(e){const t=x.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==g.string&&n.parsedType!==g.number){const s=x.objectValues(t);return p(n,{expected:x.joinValues(s),received:n.parsedType,code:d.invalid_type}),w}if(this._cache||(this._cache=new Set(x.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const s=x.objectValues(t);return p(n,{received:n.data,code:d.invalid_enum_value,options:s}),w}return B(e.data)}get enum(){return this._def.values}}wt.create=(r,e)=>new wt({values:r,typeName:k.ZodNativeEnum,...S(e)});class Pe extends N{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==g.promise&&t.common.async===!1)return p(t,{code:d.invalid_type,expected:g.promise,received:t.parsedType}),w;const n=t.parsedType===g.promise?t.data:Promise.resolve(t.data);return B(n.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Pe.create=(r,e)=>new Pe({type:r,typeName:k.ZodPromise,...S(e)});class me extends N{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===k.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:n}=this._processInputParams(e),s=this._def.effect||null,a={addIssue:o=>{p(n,o),o.fatal?t.abort():t.dirty()},get path(){return n.path}};if(a.addIssue=a.addIssue.bind(a),s.type==="preprocess"){const o=s.transform(n.data,a);if(n.common.async)return Promise.resolve(o).then(async i=>{if(t.value==="aborted")return w;const u=await this._def.schema._parseAsync({data:i,path:n.path,parent:n});return u.status==="aborted"?w:u.status==="dirty"||t.value==="dirty"?_e(u.value):u});{if(t.value==="aborted")return w;const i=this._def.schema._parseSync({data:o,path:n.path,parent:n});return i.status==="aborted"?w:i.status==="dirty"||t.value==="dirty"?_e(i.value):i}}if(s.type==="refinement"){const o=i=>{const u=s.refinement(i,a);if(n.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return i};if(n.common.async===!1){const i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?w:(i.status==="dirty"&&t.dirty(),o(i.value),{status:t.value,value:i.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>i.status==="aborted"?w:(i.status==="dirty"&&t.dirty(),o(i.value).then(()=>({status:t.value,value:i.value}))))}if(s.type==="transform")if(n.common.async===!1){const o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!de(o))return w;const i=s.transform(o.value,a);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:i}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>de(o)?Promise.resolve(s.transform(o.value,a)).then(i=>({status:t.value,value:i})):w);x.assertNever(s)}}me.create=(r,e,t)=>new me({schema:r,typeName:k.ZodEffects,effect:e,...S(t)}),me.createWithPreprocess=(r,e,t)=>new me({schema:e,effect:{type:"preprocess",transform:r},typeName:k.ZodEffects,...S(t)});class se extends N{_parse(e){return this._getType(e)===g.undefined?B(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}se.create=(r,e)=>new se({innerType:r,typeName:k.ZodOptional,...S(e)});class ye extends N{_parse(e){return this._getType(e)===g.null?B(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ye.create=(r,e)=>new ye({innerType:r,typeName:k.ZodNullable,...S(e)});class Be extends N{_parse(e){const{ctx:t}=this._processInputParams(e);let n=t.data;return t.parsedType===g.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Be.create=(r,e)=>new Be({innerType:r,typeName:k.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...S(e)});class He extends N{_parse(e){const{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Ne(s)?s.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new Y(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Y(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}He.create=(r,e)=>new He({innerType:r,typeName:k.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...S(e)});class xt extends N{_parse(e){if(this._getType(e)!==g.nan){const n=this._getOrReturnCtx(e);return p(n,{code:d.invalid_type,expected:g.nan,received:n.parsedType}),w}return{status:"valid",value:e.data}}}xt.create=r=>new xt({typeName:k.ZodNaN,...S(r)});class mr extends N{_parse(e){const{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}}class Ge extends N{_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const a=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?w:a.status==="dirty"?(t.dirty(),_e(a.value)):this._def.out._parseAsync({data:a.value,path:n.path,parent:n})})();{const s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?w:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,t){return new Ge({in:e,out:t,typeName:k.ZodPipeline})}}class Xe extends N{_parse(e){const t=this._def.innerType._parse(e),n=s=>(de(s)&&(s.value=Object.freeze(s.value)),s);return Ne(t)?t.then(s=>n(s)):n(t)}unwrap(){return this._def.innerType}}Xe.create=(r,e)=>new Xe({innerType:r,typeName:k.ZodReadonly,...S(e)});function Ct(r,e){const t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function yr(r,e={},t){return r?ke.create().superRefine((n,s)=>{const a=r(n);if(a instanceof Promise)return a.then(o=>{if(!o){const i=Ct(e,n),u=i.fatal??t??!0;s.addIssue({code:"custom",...i,fatal:u})}});if(!a){const o=Ct(e,n),i=o.fatal??t??!0;s.addIssue({code:"custom",...o,fatal:i})}}):ke.create()}var k;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(k||(k={}));const gr=(r,e={message:`Input not instance of ${r.name}`})=>yr(t=>t instanceof r,e),$=K.create,H=fe.create;ke.create,ne.create;const D=Q.create,P=M.create,vr=Re.create;Me.create,ue.create;const _r=Le.create,xe=pe.create;Pe.create,se.create,ye.create;class St extends Error{constructor(t){const n=`Invalid ChaosConfig:
2
+ ${t.map(s=>` - ${s}`).join(`
3
+ `)}`;super(n);L(this,"issues");this.name="ChaosConfigError",this.issues=t}}const z=H().min(0,"Probability must be >= 0").max(1,"Probability must be <= 1"),Tt=H().int().min(1),V={onNth:Tt.optional(),everyNth:Tt.optional(),afterN:H().int().min(0).optional()},F=[r=>[r.onNth,r.everyNth,r.afterN].filter(e=>e!==void 0).length<=1,{message:"Only one of onNth, everyNth, or afterN may be set on a single rule"}],br=vr([$().min(1,"graphqlOperation must not be empty"),gr(RegExp).refine(r=>!r.global&&!r.sticky,{message:"graphqlOperation RegExp must not use global (g) or sticky (y) flags due to lastIndex mutation"})]),Ce={urlPattern:$().min(1,"urlPattern must not be empty"),methods:D($()).optional(),graphqlOperation:br.optional()},kr=P({...Ce,statusCode:H().int().min(100).max(599),probability:z,body:$().optional(),statusText:$().optional(),headers:_r($()).optional(),...V}).strict().refine(...F),wr=P({...Ce,delayMs:H().min(0,"delayMs must be >= 0"),probability:z,...V}).strict().refine(...F),xr=P({...Ce,probability:z,timeout:H().min(0,"timeout must be >= 0").optional(),...V}).strict().refine(...F),Cr=P({...Ce,probability:z,strategy:xe(["truncate","malformed-json","empty","wrong-type"]),...V}).strict().refine(...F),Sr=P({...Ce,probability:z,...V}).strict().refine(...F),Tr=P({failures:D(kr).optional(),latencies:D(wr).optional(),aborts:D(xr).optional(),corruptions:D(Cr).optional(),cors:D(Sr).optional()}).strict(),Er=P({selector:$().min(1,"selector must not be empty"),action:xe(["disable","hide","remove"]),probability:z}).strict(),Or=P({assaults:D(Er).optional()}).strict(),Qe=xe(["inbound","outbound","both"]),Nr=P({urlPattern:$().min(1,"urlPattern must not be empty"),direction:Qe,probability:z,...V}).strict().refine(...F),Ar=P({urlPattern:$().min(1,"urlPattern must not be empty"),direction:Qe,delayMs:H().min(0,"delayMs must be >= 0"),probability:z,...V}).strict().refine(...F),Rr=P({urlPattern:$().min(1,"urlPattern must not be empty"),direction:Qe,strategy:xe(["truncate","malformed-json","empty","wrong-type"]),probability:z,...V}).strict().refine(...F),Mr=H().int().refine(r=>r===1e3||r>=3e3&&r<=4999,{message:"code must be 1000 or in the range 3000-4999"}),Lr=$().refine(r=>new TextEncoder().encode(r).length<=123,{message:"reason must be <= 123 UTF-8 bytes"}),Pr=P({urlPattern:$().min(1,"urlPattern must not be empty"),code:Mr.optional(),reason:Lr.optional(),afterMs:H().min(0,"afterMs must be >= 0").optional(),probability:z,...V}).strict().refine(...F),jr=P({drops:D(Nr).optional(),delays:D(Ar).optional(),corruptions:D(Rr).optional(),closes:D(Pr).optional()}).strict(),Je=$().min(1,"eventType must not be empty"),Ir=P({urlPattern:$().min(1,"urlPattern must not be empty"),eventType:Je.optional(),probability:z,...V}).strict().refine(...F),$r=P({urlPattern:$().min(1,"urlPattern must not be empty"),eventType:Je.optional(),delayMs:H().min(0,"delayMs must be >= 0"),probability:z,...V}).strict().refine(...F),Zr=P({urlPattern:$().min(1,"urlPattern must not be empty"),eventType:Je.optional(),strategy:xe(["truncate","malformed-json","empty","wrong-type"]),probability:z,...V}).strict().refine(...F),Dr=P({urlPattern:$().min(1,"urlPattern must not be empty"),afterMs:H().min(0,"afterMs must be >= 0").optional(),probability:z,...V}).strict().refine(...F),qr=P({drops:D(Ir).optional(),delays:D($r).optional(),corruptions:D(Zr).optional(),closes:D(Dr).optional()}).strict(),zr=P({network:Tr.optional(),ui:Or.optional(),websocket:jr.optional(),sse:qr.optional(),seed:H().int("Seed must be an integer").optional()}).strict();function Et(r){const e=zr.safeParse(r);if(!e.success){const t=e.error.issues.map(n=>`${n.path.join(".")}: ${n.message}`);throw new St(t)}return e.data}function Vr(r){let e=r|0;return()=>{e=e+1831565813|0;let t=Math.imul(e^e>>>15,1|e);return t=t+Math.imul(t^t>>>7,61|t)^t,((t^t>>>14)>>>0)/4294967296}}function Ot(){return Math.random()*4294967296>>>0}function Nt(r){const e=r??Ot();return{random:Vr(e),seed:e}}class At{constructor(e=2e3){L(this,"listeners",new Map);L(this,"log",[]);this.maxLogEntries=e}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t)}off(e,t){var n;(n=this.listeners.get(e))==null||n.delete(t)}emit(e){this.log.push(e),this.log.length>this.maxLogEntries&&this.log.shift(),this.notify(this.listeners.get(e.type),e),this.notify(this.listeners.get("*"),e)}getLog(){return[...this.log]}clearLog(){this.log=[]}notify(e,t){if(e)for(const n of e)try{n(t)}catch{}}}function q(r,e){return e()<r}function ae(r,e){const t=(e.get(r)??0)+1;return e.set(r,t),t}function ie(r,e){return r.onNth!==void 0?e===r.onNth:r.everyNth!==void 0?e%r.everyNth===0:r.afterN!==void 0?e>r.afterN:!0}function oe(r,e){return e==="*"?!0:r.includes(e)}function Ye(r,e){switch(e){case"truncate":return r.slice(0,Math.max(0,Math.floor(r.length/2)));case"malformed-json":return`${r}"}`;case"empty":return"";case"wrong-type":return"<html><body>Unexpected HTML</body></html>"}}function Ke(r){const e=r.replace(/#[^\r\n]*/g," "),t=/\b(?:query|mutation|subscription)\s+([A-Za-z_][A-Za-z0-9_]*)/.exec(e);return(t==null?void 0:t[1])??null}function Fr(r){try{return JSON.parse(r)}catch{return}}function Rt(r){if(!r||typeof r!="object")return{isGraphQL:!1,operationName:null};if(Array.isArray(r))return r.length===0?{isGraphQL:!1,operationName:null}:Rt(r[0]);const e=r,t=typeof e.query=="string",n=typeof e.operationName=="string";return!t&&!n?{isGraphQL:!1,operationName:null}:n&&e.operationName.length>0?{isGraphQL:!0,operationName:e.operationName}:t?{isGraphQL:!0,operationName:Ke(e.query)}:{isGraphQL:!0,operationName:null}}function Ur(r){let e;try{e=new URL(r,"http://_chaos-maker.invalid")}catch{return{kind:"not-graphql"}}const t=e.searchParams.get("operationName"),n=e.searchParams.get("query");return t&&t.length>0?{kind:"extracted",operationName:t}:n&&n.length>0?{kind:"extracted",operationName:Ke(n)}:{kind:"not-graphql"}}function et(r,e,t,n){const s=r.toUpperCase();if(s==="POST"){if(t!==null){const a=Fr(t);if(a===void 0)return{kind:"not-graphql"};const{isGraphQL:o,operationName:i}=Rt(a);return o?{kind:"extracted",operationName:i}:{kind:"not-graphql"}}return n?{kind:"unparseable"}:{kind:"not-graphql"}}return s==="GET"?Ur(e):{kind:"not-graphql"}}function Mt(r,e){return e===null?!1:typeof r=="string"?r===e:((r.global||r.sticky)&&(r.lastIndex=0),r.test(e))}function je(r,e){return r?e.kind==="not-graphql"?{kind:"no-match"}:e.kind==="unparseable"?{kind:"unparseable"}:Mt(r,e.operationName)?{kind:"match",operationName:e.operationName}:{kind:"no-match"}:e.kind==="extracted"?{kind:"skip-no-constraint",operationName:e.operationName}:{kind:"skip-no-constraint",operationName:null}}function Ie(r){return typeof Request<"u"&&r instanceof Request}function Wr(r){return Ie(r)?r.url:r.toString()}function Br(r,e){return e!=null&&e.method?e.method.toUpperCase():Ie(r)?r.method.toUpperCase():"GET"}function Hr(r,e){if(e!=null&&e.signal)return e.signal;if(Ie(r))return r.signal}function Gr(){if(typeof DOMException<"u")return new DOMException("The user aborted a request.","AbortError");const r=new Error("The user aborted a request.");return r.name="AbortError",r}function Xr(r,e){if(!e)return r;const t=new AbortController,n=i=>{o(),t.signal.aborted||t.abort(i.reason)},s=()=>n(r),a=()=>n(e),o=()=>{r.removeEventListener("abort",s),e.removeEventListener("abort",a)};return r.aborted?(n(r),t.signal):e.aborted?(n(e),t.signal):(r.addEventListener("abort",s,{once:!0}),e.addEventListener("abort",a,{once:!0}),t.signal)}function Qr(r,e){return e?{...r??{},signal:e}:r}async function Jr(r,e){const t=e==null?void 0:e.body;if(t!=null){if(typeof t=="string")return{text:t,unparseable:!1};if(typeof URLSearchParams<"u"&&t instanceof URLSearchParams)return{text:t.toString(),unparseable:!1};if(typeof Blob<"u"&&t instanceof Blob){if(!(t.type===""||/json|text|graphql/i.test(t.type)))return{text:null,unparseable:!0};try{return{text:await t.text(),unparseable:!1}}catch{return{text:null,unparseable:!0}}}return{text:null,unparseable:!0}}if(Ie(r)){if(r.body===null)return{text:null,unparseable:!1};try{return{text:await r.clone().text(),unparseable:!1}}catch{return{text:null,unparseable:!0}}}return{text:null,unparseable:!1}}function Se(r,e,t,n,s){r==null||r.emit({type:e,timestamp:Date.now(),applied:!1,detail:{url:t,method:n,...s,reason:"graphql-body-unparseable"}})}function $e(r,e,t,n,s){if(!oe(e,r.urlPattern))return{proceed:!1,outcome:null};if(r.methods&&!r.methods.includes(t))return{proceed:!1,outcome:null};const a=je(r.graphqlOperation,n);if(a.kind==="no-match"||a.kind==="unparseable")return{proceed:!1,outcome:a};const o=ae(r,s);return ie(r,o)?{proceed:!0,outcome:a}:{proceed:!1,outcome:a}}function Te(r){return r?r.kind==="match"||r.kind==="skip-no-constraint"?r.operationName?{operationName:r.operationName}:{}:{}:{}}function Lt(r,e,t,n,s,a){r==null||r.emit({type:"network:abort",timestamp:Date.now(),applied:s,detail:{url:t,method:n,timeoutMs:e.timeout,...Te(a)}})}function Ze(r,e,t,n,s,a){r==null||r.emit({type:"network:corruption",timestamp:Date.now(),applied:s,detail:{url:t,method:n,strategy:e.strategy,...Te(a)}})}function Yr(r){return r.graphqlOperation!==void 0}function Kr(r,e,t,n,s=new Map){return async(a,o)=>{var T,E,O,I;const i=Wr(a),u=Br(a,o),y=Hr(a,o),C=(()=>{const h=[e.failures,e.latencies,e.aborts,e.corruptions,e.cors];for(const A of h)if(A!=null&&A.some(Yr))return!0;return!1})();let j={kind:"not-graphql"};if(C){const h=await Jr(a,o);j=et(u,i,h.text,h.unparseable)}if(e.cors)for(const h of e.cors){if(!oe(i,h.urlPattern)||h.methods&&!h.methods.includes(u))continue;const A=je(h.graphqlOperation,j);if(A.kind==="no-match")continue;if(A.kind==="unparseable"){Se(n,"network:cors",i,u,{});continue}const G=ae(h,s);if(!ie(h,G))continue;const te=q(h.probability,t);if(n==null||n.emit({type:"network:cors",timestamp:Date.now(),applied:te,detail:{url:i,method:u,...Te(A)}}),te){console.debug(`[chaos-maker] CORS block: ${u} ${i}`);const le=new TypeError("Failed to fetch");throw le.stack="",le}}let U=null,ee=null,W,f,c=!1;const l=h=>{!U||c||(c=!0,f&&(clearTimeout(f),f=void 0),Lt(n,U,i,u,h,ee))};if(e.aborts)for(const h of e.aborts){const A=$e(h,i,u,j,s);if(!A.proceed){((T=A.outcome)==null?void 0:T.kind)==="unparseable"&&Se(n,"network:abort",i,u,{timeoutMs:h.timeout});continue}if(!q(h.probability,t)){Lt(n,h,i,u,!1,A.outcome);continue}console.warn(`CHAOS: Aborting ${u} ${i} after ${h.timeout||0}ms`),U=h,ee=A.outcome;const te=new AbortController;W=Xr(te.signal,y);const le=()=>{c||(l(!0),te.abort(Gr()))};h.timeout?f=setTimeout(le,h.timeout):le();break}if(U)try{const h=await r(a,Qr(o,W));return l(!1),h}catch(h){throw l(!1),h}if(e.failures)for(const h of e.failures){const A=$e(h,i,u,j,s);if(!A.proceed){((E=A.outcome)==null?void 0:E.kind)==="unparseable"&&Se(n,"network:failure",i,u,{statusCode:h.statusCode});continue}const G=q(h.probability,t);if(n==null||n.emit({type:"network:failure",timestamp:Date.now(),applied:G,detail:{url:i,method:u,statusCode:h.statusCode,...Te(A.outcome)}}),G){console.warn(`CHAOS: Forcing ${h.statusCode} for ${u} ${i}`);const te=h.body??JSON.stringify({error:"Chaos Maker Attack!"}),le=h.headers??{};return new Response(te,{status:h.statusCode,statusText:h.statusText??"Service Unavailable (Chaos)",headers:le})}}if(e.latencies)for(const h of e.latencies){const A=$e(h,i,u,j,s);if(!A.proceed){((O=A.outcome)==null?void 0:O.kind)==="unparseable"&&Se(n,"network:latency",i,u,{delayMs:h.delayMs});continue}const G=q(h.probability,t);n==null||n.emit({type:"network:latency",timestamp:Date.now(),applied:G,detail:{url:i,method:u,delayMs:h.delayMs,...Te(A.outcome)}}),G&&(console.warn(`CHAOS: Adding ${h.delayMs}ms latency to ${u} ${i}`),await new Promise(te=>setTimeout(te,h.delayMs)))}let m=null,_=null;if(e.corruptions)for(const h of e.corruptions){const A=$e(h,i,u,j,s);if(!A.proceed){((I=A.outcome)==null?void 0:I.kind)==="unparseable"&&Se(n,"network:corruption",i,u,{strategy:h.strategy});continue}if(!q(h.probability,t)){Ze(n,h,i,u,!1,A.outcome);continue}m=h,_=A.outcome;break}let b;try{b=await r(a,o)}catch(h){throw m&&Ze(n,m,i,u,!1,_),h}if(!m)return b;try{console.warn(`CHAOS: Corrupting response for ${u} ${i} with strategy: ${m.strategy}`);const h=await b.text(),A=Ye(h,m.strategy);return Ze(n,m,i,u,!0,_),new Response(A,{status:b.status,statusText:b.statusText,headers:b.headers})}catch(h){throw Ze(n,m,i,u,!1,_),h}}}function en(r){return r==null?{text:null,unparseable:!1}:typeof r=="string"?{text:r,unparseable:!1}:typeof URLSearchParams<"u"&&r instanceof URLSearchParams?{text:r.toString(),unparseable:!1}:{text:null,unparseable:!0}}function tn(r){return r.graphqlOperation!==void 0}function rn(r){const e=[r.failures,r.latencies,r.aborts,r.corruptions,r.cors];for(const t of e)if(t!=null&&t.some(tn))return!0;return!1}function Ee(r,e,t,n,s){r==null||r.emit({type:e,timestamp:Date.now(),applied:!1,detail:{url:t,method:n,...s,reason:"graphql-body-unparseable"}})}function De(r,e,t,n,s){if(!oe(e,r.urlPattern))return{proceed:!1,outcome:null};if(r.methods&&!r.methods.includes(t))return{proceed:!1,outcome:null};const a=je(r.graphqlOperation,n);if(a.kind==="no-match"||a.kind==="unparseable")return{proceed:!1,outcome:a};const o=ae(r,s);return ie(r,o)?{proceed:!0,outcome:a}:{proceed:!1,outcome:a}}function Oe(r){return r?r.kind==="match"||r.kind==="skip-no-constraint"?r.operationName?{operationName:r.operationName}:{}:{}:{}}function Pt(r,e,t,n,s,a){r==null||r.emit({type:"network:abort",timestamp:Date.now(),applied:s,detail:{url:t,method:n,timeoutMs:e.timeout,...Oe(a)}})}function jt(r,e,t,n,s,a){r==null||r.emit({type:"network:corruption",timestamp:Date.now(),applied:s,detail:{url:t,method:n,strategy:e.strategy,...Oe(a)}})}function nn(r,e,t,n,s=new Map){const a=rn(e);return function(o){var U,ee,W,f;const i=this._chaos_url,u=this._chaos_method;let y={kind:"not-graphql"};if(a){const c=en(o);y=et(u,i,c.text,c.unparseable)}if(e.cors)for(const c of e.cors){if(!oe(i,c.urlPattern)||c.methods&&!c.methods.includes(u))continue;const l=je(c.graphqlOperation,y);if(l.kind==="no-match")continue;if(l.kind==="unparseable"){Ee(n,"network:cors",i,u,{});continue}const m=ae(c,s);if(!ie(c,m))continue;const _=q(c.probability,t);if(n==null||n.emit({type:"network:cors",timestamp:Date.now(),applied:_,detail:{url:i,method:u,...Oe(l)}}),_){console.debug(`[chaos-maker] CORS block: ${u} ${i}`),Object.defineProperty(this,"status",{value:0}),Object.defineProperty(this,"statusText",{value:""}),this.dispatchEvent(new Event("error")),this.dispatchEvent(new Event("loadend"));return}}if(e.aborts)for(const c of e.aborts){const l=De(c,i,u,y,s);if(!l.proceed){((U=l.outcome)==null?void 0:U.kind)==="unparseable"&&Ee(n,"network:abort",i,u,{timeoutMs:c.timeout});continue}if(!q(c.probability,t)){Pt(n,c,i,u,!1,l.outcome);continue}console.warn(`CHAOS: Aborting ${u} ${i} after ${c.timeout||0}ms`);let _=!1,b;const T=()=>{b&&(clearTimeout(b),b=void 0),typeof this.removeEventListener=="function"&&this.removeEventListener("loadend",O)},E=h=>{_||(_=!0,T(),Pt(n,c,i,u,h,l.outcome))},O=()=>{E(!1)},I=()=>{_||(E(!0),this.abort())};typeof this.addEventListener=="function"&&this.addEventListener("loadend",O);try{r.call(this,o)}catch(h){throw E(!1),h}if(_)return;c.timeout?b=setTimeout(I,c.timeout):I();return}if(e.failures)for(const c of e.failures){const l=De(c,i,u,y,s);if(!l.proceed){((ee=l.outcome)==null?void 0:ee.kind)==="unparseable"&&Ee(n,"network:failure",i,u,{statusCode:c.statusCode});continue}const m=q(c.probability,t);if(n==null||n.emit({type:"network:failure",timestamp:Date.now(),applied:m,detail:{url:i,method:u,statusCode:c.statusCode,...Oe(l.outcome)}}),m){console.warn(`CHAOS: Forcing ${c.statusCode} for ${u} ${i}`),Object.defineProperty(this,"status",{value:c.statusCode}),Object.defineProperty(this,"statusText",{value:c.statusText??"Service Unavailable (Chaos)"});const _=c.body??JSON.stringify({error:"Chaos Maker Attack!"});Object.defineProperty(this,"responseText",{value:_,configurable:!0});const b=c.headers??{};Object.defineProperty(this,"getResponseHeader",{value:T=>{const E=Object.keys(b).find(O=>O.toLowerCase()===T.toLowerCase());return E?b[E]:null},configurable:!0}),Object.defineProperty(this,"getAllResponseHeaders",{value:()=>Object.entries(b).map(([T,E])=>`${T}: ${E}`).join(`\r
4
+ `),configurable:!0}),this.dispatchEvent(new Event("error")),this.dispatchEvent(new Event("load")),this.dispatchEvent(new Event("loadend"));return}}let C=null,j=null;if(e.corruptions)for(const c of e.corruptions){const l=De(c,i,u,y,s);if(!l.proceed){((W=l.outcome)==null?void 0:W.kind)==="unparseable"&&Ee(n,"network:corruption",i,u,{strategy:c.strategy});continue}if(!q(c.probability,t)){jt(n,c,i,u,!1,l.outcome);continue}C=c,j=l.outcome;break}if(C){let c=!1,l=null;const m=()=>{typeof this.removeEventListener=="function"&&(this.removeEventListener("error",T),this.removeEventListener("abort",T),this.removeEventListener("loadend",E))},_=O=>{c||(c=!0,jt(n,C,i,u,O,j),m())},b=()=>{if(l!==null)return l;delete this.responseText;try{const O=this.responseText;return typeof O!="string"?(Object.defineProperty(this,"responseText",{value:O,configurable:!0}),_(!1),O):(l=Ye(O,C.strategy),Object.defineProperty(this,"responseText",{value:l,configurable:!0}),_(!0),l)}catch(O){throw _(!1),O}},T=()=>{_(!1)},E=()=>{if(!c)try{b()}catch{}};typeof this.addEventListener=="function"&&(this.addEventListener("error",T),this.addEventListener("abort",T),this.addEventListener("loadend",E)),Object.defineProperty(this,"responseText",{get(){return b()},configurable:!0})}if(e.latencies)for(const c of e.latencies){const l=De(c,i,u,y,s);if(!l.proceed){((f=l.outcome)==null?void 0:f.kind)==="unparseable"&&Ee(n,"network:latency",i,u,{delayMs:c.delayMs});continue}const m=q(c.probability,t);if(n==null||n.emit({type:"network:latency",timestamp:Date.now(),applied:m,detail:{url:i,method:u,delayMs:c.delayMs,...Oe(l.outcome)}}),m){console.warn(`CHAOS: Adding ${c.delayMs}ms latency to ${u} ${i}`),setTimeout(()=>{r.call(this,o)},c.delayMs);return}}r.call(this,o)}}function sn(r){return function(e,t){this._chaos_url=t.toString(),this._chaos_method=e.toUpperCase(),r.call(this,e,t)}}function tt(r,e,t,n){const s=q(e.probability,t);if(n==null||n.emit({type:"ui:assault",timestamp:Date.now(),applied:s,detail:{selector:e.selector,action:e.action}}),!!s){console.warn(`CHAOS: Applying action '${e.action}' to element:`,r);try{switch(e.action){case"disable":"disabled"in r&&(r.disabled=!0);break;case"hide":r.style.display="none";break;case"remove":r.remove();break}}catch(a){console.error("Chaos Maker failed to assault element:",a,r)}}}function an(r,e,t,n){if(r.nodeType!==Node.ELEMENT_NODE||!e.assaults)return;const s=r;for(const a of e.assaults)try{s.matches(a.selector)&&tt(s,a,t,n),s.querySelectorAll(a.selector).forEach(o=>{tt(o,a,t,n)})}catch(o){console.error(`Chaos Maker: Invalid selector '${a.selector}'`,o)}}function on(r,e,t){if(r.assaults){console.log("CHAOS: Running initial DOM scan for existing elements...");for(const s of r.assaults)try{document.querySelectorAll(s.selector).forEach(a=>{tt(a,s,e,t)})}catch(a){console.error(`Chaos Maker: Invalid selector in initial scan '${s.selector}'`,a)}}return new MutationObserver(s=>{for(const a of s)a.type==="childList"&&a.addedNodes.forEach(o=>an(o,r,e,t))})}const It=Symbol.for("chaos-maker.websocket.intercepted");function cn(r,e){return r==="both"?!0:r===e}function $t(r){return typeof r=="string"?"text":"binary"}function Zt(r,e){switch(e){case"truncate":return r.slice(0,Math.max(0,Math.floor(r.length/2)));case"malformed-json":return`${r}"}`;case"empty":return"";case"wrong-type":return"<html><body>Unexpected HTML</body></html>"}}function Dt(r,e){if(e==="malformed-json"||e==="wrong-type")return null;if(e==="empty")return typeof Blob<"u"&&r instanceof Blob?new Blob([]):r instanceof ArrayBuffer?new ArrayBuffer(0):new Uint8Array(0);if(typeof Blob<"u"&&r instanceof Blob)return r.slice(0,Math.max(0,Math.floor(r.size/2)));if(r instanceof ArrayBuffer)return r.slice(0,Math.max(0,Math.floor(r.byteLength/2)));const t=r,n=Math.max(0,Math.floor(t.byteLength/2));return new Uint8Array(t.buffer.slice(t.byteOffset,t.byteOffset+n))}function ge(r,e,t,n,s){if(!r)return null;for(const a of r){if(!oe(e,a.urlPattern)||!cn(a.direction,t))continue;const o=ae(a,s);if(ie(a,o)&&q(a.probability,n))return a}return null}function qe(r,e,t,n,s){r.emit({type:"websocket:drop",timestamp:Date.now(),applied:!0,detail:{url:e,direction:t,payloadType:n,...s?{reason:s}:{}}})}function qt(r,e,t,n,s){r.emit({type:"websocket:delay",timestamp:Date.now(),applied:!0,detail:{url:e,direction:t,payloadType:n,delayMs:s}})}function ve(r,e,t,n,s,a,o){r.emit({type:"websocket:corrupt",timestamp:Date.now(),applied:a,detail:{url:e,direction:t,payloadType:n,strategy:s,...o?{reason:o}:{}}})}function un(r,e,t,n){r.emit({type:"websocket:close",timestamp:Date.now(),applied:!0,detail:{url:e,closeCode:t,closeReason:n}})}function ln(r,e,t,n,s){const a=new Map;let o=!0;const i=(f,c)=>{let l=a.get(f);l||(l=new Set,a.set(f,l)),l.add(c)},u=(f,c)=>{var l;(l=a.get(f))==null||l.delete(c)},y=(f,c)=>{const l=a.get(f);if(l){for(const m of l)clearTimeout(m.handle),m.kind==="delay"&&qe(t,m.url,m.direction,m.payloadType,c);a.delete(f)}},C=(f,c,l)=>{const m=new MessageEvent("message",{data:l,origin:c.origin,lastEventId:c.lastEventId,source:c.source,ports:Array.from(c.ports??[])});m[It]=!0,f.dispatchEvent(m)},j=(f,c,l,m)=>{if(!o)return{handled:!1,data:l};const _="outbound",b=$t(l);if(ge(e.drops,c,_,n,s))return qe(t,c,_,b),{handled:!0,data:l};let T=l;const E=ge(e.corruptions,c,_,n,s);if(E)if(b==="text")T=Zt(T,E.strategy),ve(t,c,_,b,E.strategy,!0);else{const I=Dt(T,E.strategy);I===null?ve(t,c,_,b,E.strategy,!1,"incompatible-payload-type"):(T=I,ve(t,c,_,b,E.strategy,!0))}const O=ge(e.delays,c,_,n,s);if(O){qt(t,c,_,b,O.delayMs);const I={kind:"delay",handle:setTimeout(()=>{u(f,I);try{m(T)}catch{}},O.delayMs),url:c,direction:_,payloadType:b};return i(f,I),{handled:!0,data:T}}return{handled:!1,data:T}},U=(f,c)=>{f.addEventListener("message",l=>{const m=l;if(m[It]||!o)return;const _="inbound",b=$t(m.data);if(ge(e.drops,c,_,n,s)){m.stopImmediatePropagation(),qe(t,c,_,b);return}let T=m.data,E=!1;const O=ge(e.corruptions,c,_,n,s);if(O)if(b==="text")T=Zt(T,O.strategy),E=!0,ve(t,c,_,b,O.strategy,!0);else{const h=Dt(T,O.strategy);h===null?ve(t,c,_,b,O.strategy,!1,"incompatible-payload-type"):(T=h,E=!0,ve(t,c,_,b,O.strategy,!0))}const I=ge(e.delays,c,_,n,s);if(I){m.stopImmediatePropagation(),qt(t,c,_,b,I.delayMs);const h={kind:"delay",handle:setTimeout(()=>{u(f,h),C(f,m,T)},I.delayMs),url:c,direction:_,payloadType:b};i(f,h);return}E&&(m.stopImmediatePropagation(),C(f,m,T))})},ee=(f,c)=>{if(e.closes)for(const l of e.closes){if(!oe(c,l.urlPattern))continue;const m=ae(l,s);if(!ie(l,m)||!q(l.probability,n))continue;const _=l.code??1e3,b=l.reason??"Chaos Maker close",T=l.afterMs??0,E=()=>{if(o){y(f,"close-interrupt"),un(t,c,_,b);try{f.close(_,b)}catch{try{f.close()}catch{}}}};if(T<=0)f.readyState===f.OPEN?E():f.addEventListener("open",E,{once:!0});else{const O=()=>{const I={kind:"close",handle:setTimeout(E,T)};i(f,I)};f.readyState===f.OPEN?O():f.addEventListener("open",O,{once:!0})}return}};function W(f,c){const l=new r(f,c),m=typeof f=="string"?f:f.toString(),_=l.send.bind(l);return l.send=function(T){const E=j(l,m,T,_);E.handled||_(E.data)},U(l,m),ee(l,m),l}Object.defineProperty(W,"prototype",{value:r.prototype,writable:!1});for(const f of["CONNECTING","OPEN","CLOSING","CLOSED"])W[f]=r[f];return{Wrapped:W,uninstall(){o=!1;for(const[,f]of a)for(const c of f)clearTimeout(c.handle),c.kind==="delay"&&qe(t,c.url,c.direction,c.payloadType,"stop-during-delay");a.clear()}}}const zt=Symbol.for("chaos-maker.eventsource.intercepted");function dn(r,e){return r===void 0||r==="*"?!0:r===e}function rt(r,e,t,n,s){if(!r)return null;for(const a of r){if(!oe(e,a.urlPattern)||!dn(a.eventType,t))continue;const o=ae(a,s);if(ie(a,o)&&q(a.probability,n))return a}return null}function nt(r,e,t,n){r.emit({type:"sse:drop",timestamp:Date.now(),applied:!0,detail:{url:e,eventType:t,...n?{reason:n}:{}}})}function fn(r,e,t,n){r.emit({type:"sse:delay",timestamp:Date.now(),applied:!0,detail:{url:e,eventType:t,delayMs:n}})}function hn(r,e,t,n){r.emit({type:"sse:corrupt",timestamp:Date.now(),applied:!0,detail:{url:e,eventType:t,strategy:n}})}function pn(r,e,t){r.emit({type:"sse:close",timestamp:Date.now(),applied:!0,detail:{url:e,reason:t}})}function mn(r,e,t,n,s){const a=new Map;let o=!0;const i=(f,c)=>{let l=a.get(f);l||(l=new Set,a.set(f,l)),l.add(c)},u=(f,c)=>{var l;(l=a.get(f))==null||l.delete(c)},y=(f,c)=>{const l=a.get(f);if(l){for(const m of l)clearTimeout(m.handle),m.kind==="delay"&&nt(t,m.url,m.eventType,c);a.delete(f)}},C=(f,c,l)=>{const m=new MessageEvent(c.type||"message",{data:l,origin:c.origin,lastEventId:c.lastEventId});m[zt]=!0,f.dispatchEvent(m)},j=(f,c,l)=>{if(l[zt]||!o)return;const m=l.type||"message";if(rt(e.drops,c,m,n,s)){l.stopImmediatePropagation(),nt(t,c,m);return}let _=typeof l.data=="string"?l.data:String(l.data),b=!1;const T=rt(e.corruptions,c,m,n,s);T&&(_=Ye(_,T.strategy),b=!0,hn(t,c,m,T.strategy));const E=rt(e.delays,c,m,n,s);if(E){l.stopImmediatePropagation(),fn(t,c,m,E.delayMs);const O={kind:"delay",handle:setTimeout(()=>{u(f,O),o&&f.readyState!==f.CLOSED&&C(f,l,_)},E.delayMs),url:c,eventType:m};i(f,O);return}b&&(l.stopImmediatePropagation(),C(f,l,_))},U=f=>{if(!e.closes)return null;for(const c of e.closes){if(!oe(f,c.urlPattern))continue;const l=ae(c,s);if(ie(c,l)&&q(c.probability,n))return c}return null},ee=(f,c)=>{const l=U(c);if(!l)return;const m=l.afterMs??0,_=()=>{if(o){y(f,"close-interrupt"),pn(t,c,"chaos-maker-close");try{f.close()}catch{}try{f.dispatchEvent(new Event("error"))}catch{}}};if(m<=0){const b={kind:"close",handle:setTimeout(_,0)};i(f,b)}else{const b={kind:"close",handle:setTimeout(_,m)};i(f,b)}};function W(f,c){const l=new r(f,c),m=typeof f=="string"?f:f.toString(),_=h=>{j(l,m,h)},b=new Set,T=l.addEventListener.bind(l),E=h=>{b.has(h)||(b.add(h),T(h,_,{capture:!0}))};E("message");const O=h=>{if(h)for(const A of h)A.eventType&&A.eventType!=="*"&&A.eventType!=="message"&&E(A.eventType)};O(e.drops),O(e.delays),O(e.corruptions);const I=(h,A,G)=>{h!=="open"&&h!=="error"&&E(h),T(h,A,G)};return l.addEventListener=I,ee(l,m),l}Object.defineProperty(W,"prototype",{value:r.prototype,writable:!1});for(const f of["CONNECTING","OPEN","CLOSED"])W[f]=r[f];return{Wrapped:W,uninstall(){o=!1;for(const[,f]of a)for(const c of f)clearTimeout(c.handle),c.kind==="delay"&&nt(t,c.url,c.eventType,"stop-during-delay");a.clear()}}}class st{constructor(e,t={}){L(this,"config");L(this,"emitter");L(this,"random");L(this,"seed");L(this,"running",!1);L(this,"target");L(this,"originalFetch");L(this,"originalXhrSend");L(this,"originalXhrOpen");L(this,"domObserver");L(this,"originalWebSocket");L(this,"webSocketHandle");L(this,"originalEventSource");L(this,"eventSourceHandle");L(this,"requestCounters",new Map);this.config=Et(e),this.emitter=new At;const n=Nt(e.seed);this.random=n.random,this.seed=n.seed,this.target=t.target??globalThis,console.log(`Chaos Maker initialized (seed: ${this.seed})`)}getSeed(){return this.seed}on(e,t){this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}getLog(){return this.emitter.getLog()}clearLog(){this.emitter.clearLog()}start(){if(this.running){console.warn("Chaos Maker is already running. Call stop() first.");return}this.requestCounters.clear(),this.running=!0,console.log("🛠️ Chaos Maker ENGAGED 🛠️");const e=this.target;this.config.network&&(typeof e.fetch=="function"&&(this.originalFetch=e.fetch,e.fetch=Kr(this.originalFetch.bind(e),this.config.network,this.random,this.emitter,this.requestCounters)),typeof e.XMLHttpRequest=="function"&&(this.originalXhrOpen=e.XMLHttpRequest.prototype.open,e.XMLHttpRequest.prototype.open=sn(this.originalXhrOpen),this.originalXhrSend=e.XMLHttpRequest.prototype.send,e.XMLHttpRequest.prototype.send=nn(this.originalXhrSend,this.config.network,this.random,this.emitter,this.requestCounters))),this.config.ui&&(typeof document>"u"||typeof MutationObserver>"u"?console.warn("Chaos Maker: UI config ignored — no DOM available in current context."):(this.domObserver=on(this.config.ui,this.random,this.emitter),this.domObserver.observe(document.body,{childList:!0,subtree:!0}),console.log("UI Assailant is now observing the DOM."))),this.config.websocket&&typeof e.WebSocket<"u"&&(this.originalWebSocket=e.WebSocket,this.webSocketHandle=ln(this.originalWebSocket,this.config.websocket,this.emitter,this.random,this.requestCounters),e.WebSocket=this.webSocketHandle.Wrapped),this.config.sse&&typeof e.EventSource<"u"&&(this.originalEventSource=e.EventSource,this.eventSourceHandle=mn(this.originalEventSource,this.config.sse,this.emitter,this.random,this.requestCounters),e.EventSource=this.eventSourceHandle.Wrapped)}stop(){this.running=!1,console.log("🛑 Chaos Maker DISENGAGED 🛑");const e=this.target;this.originalFetch&&(e.fetch=this.originalFetch),this.originalXhrSend&&typeof e.XMLHttpRequest=="function"&&(e.XMLHttpRequest.prototype.send=this.originalXhrSend),this.originalXhrOpen&&typeof e.XMLHttpRequest=="function"&&(e.XMLHttpRequest.prototype.open=this.originalXhrOpen),this.domObserver&&(this.domObserver.disconnect(),console.log("UI Assailant has stopped observing.")),this.originalWebSocket&&(e.WebSocket=this.originalWebSocket,this.originalWebSocket=void 0),this.webSocketHandle&&(this.webSocketHandle.uninstall(),this.webSocketHandle=void 0),this.originalEventSource&&(e.EventSource=this.originalEventSource,this.originalEventSource=void 0),this.eventSourceHandle&&(this.eventSourceHandle.uninstall(),this.eventSourceHandle=void 0)}}function at(r){if(r===null||typeof r!="object")return r;if(r instanceof RegExp)return new RegExp(r.source,r.flags);if(Array.isArray(r))return r.map(t=>at(t));const e={};for(const[t,n]of Object.entries(r))e[t]=at(n);return e}function Vt(r){return at(r)}class yn{constructor(e){L(this,"config");this.config=e?Vt(e):{network:{},ui:{},websocket:{},sse:{}},this.config.network||(this.config.network={}),this.config.ui||(this.config.ui={}),this.config.websocket||(this.config.websocket={}),this.config.sse||(this.config.sse={})}failRequests(e,t,n,s,a,o,i){return this.config.network.failures||(this.config.network.failures=[]),this.config.network.failures.push({urlPattern:e,statusCode:t,probability:n,methods:s,body:a,headers:o,...i}),this}addLatency(e,t,n,s,a){return this.config.network.latencies||(this.config.network.latencies=[]),this.config.network.latencies.push({urlPattern:e,delayMs:t,probability:n,methods:s,...a}),this}abortRequests(e,t,n,s,a){return this.config.network.aborts||(this.config.network.aborts=[]),this.config.network.aborts.push({urlPattern:e,probability:t,timeout:n,methods:s,...a}),this}corruptResponses(e,t,n,s,a){return this.config.network.corruptions||(this.config.network.corruptions=[]),this.config.network.corruptions.push({urlPattern:e,strategy:t,probability:n,methods:s,...a}),this}simulateCors(e,t,n,s){return this.config.network.cors||(this.config.network.cors=[]),this.config.network.cors.push({urlPattern:e,probability:t,methods:n,...s}),this}failRequestsOnNth(e,t,n,s){return this.failRequests(e,t,1,s,void 0,void 0,{onNth:n})}addLatencyOnNth(e,t,n,s){return this.addLatency(e,t,1,s,{onNth:n})}abortRequestsOnNth(e,t,n,s){return this.abortRequests(e,1,n,s,{onNth:t})}corruptResponsesOnNth(e,t,n,s){return this.corruptResponses(e,t,1,s,{onNth:n})}simulateCorsOnNth(e,t,n){return this.simulateCors(e,1,n,{onNth:t})}failRequestsEveryNth(e,t,n,s){return this.failRequests(e,t,1,s,void 0,void 0,{everyNth:n})}addLatencyEveryNth(e,t,n,s){return this.addLatency(e,t,1,s,{everyNth:n})}abortRequestsEveryNth(e,t,n,s){return this.abortRequests(e,1,n,s,{everyNth:t})}corruptResponsesEveryNth(e,t,n,s){return this.corruptResponses(e,t,1,s,{everyNth:n})}simulateCorsEveryNth(e,t,n){return this.simulateCors(e,1,n,{everyNth:t})}failRequestsAfterN(e,t,n,s){return this.failRequests(e,t,1,s,void 0,void 0,{afterN:n})}addLatencyAfterN(e,t,n,s){return this.addLatency(e,t,1,s,{afterN:n})}abortRequestsAfterN(e,t,n,s){return this.abortRequests(e,1,n,s,{afterN:t})}corruptResponsesAfterN(e,t,n,s){return this.corruptResponses(e,t,1,s,{afterN:n})}simulateCorsAfterN(e,t,n){return this.simulateCors(e,1,n,{afterN:t})}assaultUi(e,t,n){return this.config.ui.assaults||(this.config.ui.assaults=[]),this.config.ui.assaults.push({selector:e,action:t,probability:n}),this}dropMessages(e,t,n,s){return this.config.websocket.drops||(this.config.websocket.drops=[]),this.config.websocket.drops.push({urlPattern:e,direction:t,probability:n,...s}),this}delayMessages(e,t,n,s,a){return this.config.websocket.delays||(this.config.websocket.delays=[]),this.config.websocket.delays.push({urlPattern:e,direction:t,delayMs:n,probability:s,...a}),this}corruptMessages(e,t,n,s,a){return this.config.websocket.corruptions||(this.config.websocket.corruptions=[]),this.config.websocket.corruptions.push({urlPattern:e,direction:t,strategy:n,probability:s,...a}),this}closeConnection(e,t,n,s){return this.config.websocket.closes||(this.config.websocket.closes=[]),this.config.websocket.closes.push({urlPattern:e,probability:t,...n,...s}),this}dropMessagesOnNth(e,t,n){return this.dropMessages(e,t,1,{onNth:n})}delayMessagesOnNth(e,t,n,s){return this.delayMessages(e,t,n,1,{onNth:s})}failGraphQLOperation(e,t,n,s="*"){return this.config.network.failures||(this.config.network.failures=[]),this.config.network.failures.push({urlPattern:s,statusCode:t,probability:n,graphqlOperation:e}),this}delayGraphQLOperation(e,t,n,s="*"){return this.config.network.latencies||(this.config.network.latencies=[]),this.config.network.latencies.push({urlPattern:s,delayMs:t,probability:n,graphqlOperation:e}),this}dropSSE(e,t,n,s){return this.config.sse.drops||(this.config.sse.drops=[]),this.config.sse.drops.push({urlPattern:e,probability:t,...n?{eventType:n}:{},...s}),this}delaySSE(e,t,n,s,a){return this.config.sse.delays||(this.config.sse.delays=[]),this.config.sse.delays.push({urlPattern:e,delayMs:t,probability:n,...s?{eventType:s}:{},...a}),this}corruptSSE(e,t,n,s,a){return this.config.sse.corruptions||(this.config.sse.corruptions=[]),this.config.sse.corruptions.push({urlPattern:e,strategy:t,probability:n,...s?{eventType:s}:{},...a}),this}closeSSE(e,t,n,s){return this.config.sse.closes||(this.config.sse.closes=[]),this.config.sse.closes.push({urlPattern:e,probability:t,...n,...s}),this}withSeed(e){return this.config.seed=e,this}build(){return Vt(this.config)}}const J="*";function Ft(r){if(r&&typeof r=="object"&&!Object.isFrozen(r)){Object.freeze(r);for(const e of Object.values(r))Ft(e)}return r}const gn=Ft({unstableApi:{network:{failures:[{urlPattern:"/api/",statusCode:500,probability:.1}],latencies:[{urlPattern:"/api/",delayMs:1e3,probability:.2}]}},slowNetwork:{network:{latencies:[{urlPattern:J,delayMs:2e3,probability:1}]}},offlineMode:{network:{cors:[{urlPattern:J,probability:1}]}},flakyConnection:{network:{aborts:[{urlPattern:J,probability:.05}],latencies:[{urlPattern:J,delayMs:3e3,probability:.1}]}},degradedUi:{ui:{assaults:[{selector:"button",action:"disable",probability:.2},{selector:"a",action:"hide",probability:.1}]}},unreliableWebSocket:{websocket:{drops:[{urlPattern:J,direction:"both",probability:.1}],delays:[{urlPattern:J,direction:"inbound",delayMs:500,probability:1}],corruptions:[{urlPattern:J,direction:"inbound",strategy:"truncate",probability:.05}]}},unreliableEventStream:{sse:{drops:[{urlPattern:J,probability:.05}],delays:[{urlPattern:J,delayMs:200,probability:1}],closes:[{urlPattern:J,probability:.02,afterMs:2e3}]}}}),ze="__chaosMakerRegExp";function vn(r){if(r===null||typeof r!="object")return!1;const e=r,t=Object.keys(e);if(t.length!==1||t[0]!==ze)return!1;const n=e[ze];if(!n||typeof n!="object")return!1;const s=n;for(const a of Object.keys(s))if(a!=="source"&&a!=="flags")return!1;return typeof s.source=="string"&&typeof s.flags=="string"}function it(r){if(r===null||typeof r!="object")return r;if(r instanceof RegExp)return{[ze]:{source:r.source,flags:r.flags}};if(Array.isArray(r))return r.map(t=>it(t));const e={};for(const[t,n]of Object.entries(r))e[t]=it(n);return e}function Ve(r){if(r===null||typeof r!="object"||r instanceof RegExp)return r;if(vn(r)){const{source:t,flags:n}=r[ze];try{return new RegExp(t,n)}catch(s){return console.warn(`[chaos-maker] deserializeForTransport: invalid RegExp { source: ${JSON.stringify(t)}, flags: ${JSON.stringify(n)} } — ${s.message}`),r}}if(Array.isArray(r))return r.map(t=>Ve(t));const e={};for(const[t,n]of Object.entries(r))e[t]=Ve(n);return e}const _n=`
5
+ (function installChaosMakerSWBridge() {
6
+ if (typeof window === 'undefined') return;
7
+ if (window.__chaosMakerSWBridgeInstalled) return;
8
+ window.__chaosMakerSWBridgeInstalled = true;
9
+
10
+ var log = [];
11
+ var lastConfig = null;
12
+
13
+ function addSwListeners() {
14
+ if (!('serviceWorker' in navigator)) return;
15
+ navigator.serviceWorker.addEventListener('message', function (evt) {
16
+ var data = evt && evt.data;
17
+ if (data && data.__chaosMakerSWEvent && data.event) {
18
+ log.push(data.event);
19
+ }
20
+ });
21
+ navigator.serviceWorker.addEventListener('controllerchange', function () {
22
+ if (lastConfig) {
23
+ postConfig(lastConfig, 5000).catch(function (err) {
24
+ try { console.warn('[chaos-maker] re-apply after controllerchange failed', err); } catch (_) {}
25
+ });
26
+ }
27
+ });
28
+ }
29
+
30
+ function waitForController(timeoutMs) {
31
+ return new Promise(function (resolve, reject) {
32
+ if (!('serviceWorker' in navigator)) {
33
+ reject(new Error('[chaos-maker] service worker API not available on this page'));
34
+ return;
35
+ }
36
+ var start = Date.now();
37
+ (function poll() {
38
+ if (navigator.serviceWorker.controller) {
39
+ resolve(navigator.serviceWorker.controller);
40
+ return;
41
+ }
42
+ if (Date.now() - start >= timeoutMs) {
43
+ reject(new Error('[chaos-maker] no SW controller after ' + timeoutMs + 'ms — did you register the SW?'));
44
+ return;
45
+ }
46
+ setTimeout(poll, 50);
47
+ })();
48
+ });
49
+ }
50
+
51
+ function postViaPort(controller, message, timeoutMs) {
52
+ return new Promise(function (resolve, reject) {
53
+ var channel = new MessageChannel();
54
+ var settled = false;
55
+ var timer = setTimeout(function () {
56
+ if (settled) return;
57
+ settled = true;
58
+ try { channel.port1.close(); } catch (_) {}
59
+ reject(new Error('[chaos-maker] SW ack timeout after ' + timeoutMs + 'ms'));
60
+ }, timeoutMs);
61
+ channel.port1.onmessage = function (evt) {
62
+ if (settled) return;
63
+ settled = true;
64
+ clearTimeout(timer);
65
+ resolve(evt && evt.data);
66
+ };
67
+ controller.postMessage(message, [channel.port2]);
68
+ });
69
+ }
70
+
71
+ function postConfig(cfg, timeoutMs) {
72
+ return waitForController(timeoutMs).then(function (ctrl) {
73
+ return postViaPort(ctrl, { __chaosMakerConfig: cfg }, timeoutMs);
74
+ });
75
+ }
76
+
77
+ window.__chaosMakerSWBridge = {
78
+ apply: function (cfg, timeoutMs) {
79
+ // Stash cfg BEFORE awaiting ack — intentional. If the first ack times
80
+ // out (e.g. SW still installing), the controllerchange listener above
81
+ // will retry with this config once the new SW claims the page. Caller
82
+ // still sees the rejection from this attempt and can re-throw.
83
+ lastConfig = cfg;
84
+ return postConfig(cfg, timeoutMs).then(function (ack) {
85
+ return { seed: ack && typeof ack.seed === 'number' ? ack.seed : null };
86
+ });
87
+ },
88
+ stop: function (timeoutMs) {
89
+ lastConfig = null;
90
+ if (!('serviceWorker' in navigator) || !navigator.serviceWorker.controller) {
91
+ return Promise.resolve({ running: false });
92
+ }
93
+ return postViaPort(navigator.serviceWorker.controller, { __chaosMakerStop: true }, timeoutMs);
94
+ },
95
+ getLocalLog: function () { return log.slice(); },
96
+ clearLocalLog: function () { log.length = 0; },
97
+ getRemoteLog: function (timeoutMs) {
98
+ if (!('serviceWorker' in navigator) || !navigator.serviceWorker.controller) {
99
+ return Promise.resolve([]);
100
+ }
101
+ return postViaPort(navigator.serviceWorker.controller, { __chaosMakerGetLog: true }, timeoutMs)
102
+ .then(function (reply) {
103
+ return (reply && Array.isArray(reply.log)) ? reply.log : [];
104
+ });
105
+ },
106
+ };
107
+
108
+ addSwListeners();
109
+ })();
110
+ `;if(typeof window<"u"){window.ChaosMaker=st;const r={instance:null,start:e=>{try{r.instance&&r.instance.stop();const t=Ve(e);return r.instance=new st(t),r.instance.start(),{success:!0,message:"Chaos started"}}catch(t){return console.error("Chaos Utils Error:",t),{success:!1,message:t.message}}},stop:()=>r.instance?(r.instance.stop(),r.instance=null,{success:!0,message:"Chaos stopped"}):{success:!1,message:"No chaos instance to stop"},getLog:()=>r.instance?r.instance.getLog():[],getSeed:()=>r.instance?r.instance.getSeed():null};if(window.chaosUtils=r,window.__CHAOS_CONFIG__)try{const e=window.__CHAOS_CONFIG__;r.start(e),delete window.__CHAOS_CONFIG__}catch(e){console.error("ChaosMaker auto-start failed:",e)}}R.ChaosConfigBuilder=yn,R.ChaosConfigError=St,R.ChaosEventEmitter=At,R.ChaosMaker=st,R.SW_BRIDGE_SOURCE=_n,R.createPrng=Nt,R.deserializeForTransport=Ve,R.extractGraphQLOperation=et,R.generateSeed=Ot,R.operationNameMatches=Mt,R.parseOperationFromQueryString=Ke,R.presets=gn,R.serializeForTransport=it,R.validateConfig=Et,Object.defineProperty(R,Symbol.toStringTag,{value:"Module"})}));
package/dist/sw.js ADDED
@@ -0,0 +1 @@
1
+ var ChaosMakerSW=(function(E){"use strict";var Ne=Object.defineProperty;var Te=(E,v,O)=>v in E?Ne(E,v,{enumerable:!0,configurable:!0,writable:!0,value:O}):E[v]=O;var z=(E,v,O)=>Te(E,typeof v!="symbol"?v+"":v,O);class v{constructor(t=2e3){z(this,"listeners",new Map);z(this,"log",[]);this.maxLogEntries=t}on(t,n){this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(n)}off(t,n){var r;(r=this.listeners.get(t))==null||r.delete(n)}emit(t){this.log.push(t),this.log.length>this.maxLogEntries&&this.log.shift(),this.notify(this.listeners.get(t.type),t),this.notify(this.listeners.get("*"),t)}getLog(){return[...this.log]}clearLog(){this.log=[]}notify(t,n){if(t)for(const r of t)try{r(n)}catch{}}}function O(e){let t=e|0;return()=>{t=t+1831565813|0;let n=Math.imul(t^t>>>15,1|t);return n=n+Math.imul(n^n>>>7,61|n)^n,((n^n>>>14)>>>0)/4294967296}}function ue(){return Math.random()*4294967296>>>0}function K(e){const t=e??ue();return{random:O(t),seed:t}}function x(e,t){return t()<e}function D(e,t){const n=(t.get(e)??0)+1;return t.set(e,n),n}function W(e,t){return e.onNth!==void 0?t===e.onNth:e.everyNth!==void 0?t%e.everyNth===0:e.afterN!==void 0?t>e.afterN:!0}function $(e,t){return t==="*"?!0:e.includes(t)}function le(e,t){switch(t){case"truncate":return e.slice(0,Math.max(0,Math.floor(e.length/2)));case"malformed-json":return`${e}"}`;case"empty":return"";case"wrong-type":return"<html><body>Unexpected HTML</body></html>"}}function Z(e){const t=e.replace(/#[^\r\n]*/g," "),n=/\b(?:query|mutation|subscription)\s+([A-Za-z_][A-Za-z0-9_]*)/.exec(t);return(n==null?void 0:n[1])??null}function ce(e){try{return JSON.parse(e)}catch{return}}function V(e){if(!e||typeof e!="object")return{isGraphQL:!1,operationName:null};if(Array.isArray(e))return e.length===0?{isGraphQL:!1,operationName:null}:V(e[0]);const t=e,n=typeof t.query=="string",r=typeof t.operationName=="string";return!n&&!r?{isGraphQL:!1,operationName:null}:r&&t.operationName.length>0?{isGraphQL:!0,operationName:t.operationName}:n?{isGraphQL:!0,operationName:Z(t.query)}:{isGraphQL:!0,operationName:null}}function fe(e){let t;try{t=new URL(e,"http://_chaos-maker.invalid")}catch{return{kind:"not-graphql"}}const n=t.searchParams.get("operationName"),r=t.searchParams.get("query");return n&&n.length>0?{kind:"extracted",operationName:n}:r&&r.length>0?{kind:"extracted",operationName:Z(r)}:{kind:"not-graphql"}}function de(e,t,n,r){const a=e.toUpperCase();if(a==="POST"){if(n!==null){const u=ce(n);if(u===void 0)return{kind:"not-graphql"};const{isGraphQL:p,operationName:c}=V(u);return p?{kind:"extracted",operationName:c}:{kind:"not-graphql"}}return r?{kind:"unparseable"}:{kind:"not-graphql"}}return a==="GET"?fe(t):{kind:"not-graphql"}}function pe(e,t){return t===null?!1:typeof e=="string"?e===t:((e.global||e.sticky)&&(e.lastIndex=0),e.test(t))}function X(e,t){return e?t.kind==="not-graphql"?{kind:"no-match"}:t.kind==="unparseable"?{kind:"unparseable"}:pe(e,t.operationName)?{kind:"match",operationName:t.operationName}:{kind:"no-match"}:t.kind==="extracted"?{kind:"skip-no-constraint",operationName:t.operationName}:{kind:"skip-no-constraint",operationName:null}}function B(e){return typeof Request<"u"&&e instanceof Request}function he(e){return B(e)?e.url:e.toString()}function ye(e,t){return t!=null&&t.method?t.method.toUpperCase():B(e)?e.method.toUpperCase():"GET"}function ge(e,t){if(t!=null&&t.signal)return t.signal;if(B(e))return e.signal}function be(){if(typeof DOMException<"u")return new DOMException("The user aborted a request.","AbortError");const e=new Error("The user aborted a request.");return e.name="AbortError",e}function me(e,t){if(!t)return e;const n=new AbortController,r=c=>{p(),n.signal.aborted||n.abort(c.reason)},a=()=>r(e),u=()=>r(t),p=()=>{e.removeEventListener("abort",a),t.removeEventListener("abort",u)};return e.aborted?(r(e),n.signal):t.aborted?(r(t),n.signal):(e.addEventListener("abort",a,{once:!0}),t.addEventListener("abort",u,{once:!0}),n.signal)}function ke(e,t){return t?{...e??{},signal:t}:e}async function we(e,t){const n=t==null?void 0:t.body;if(n!=null){if(typeof n=="string")return{text:n,unparseable:!1};if(typeof URLSearchParams<"u"&&n instanceof URLSearchParams)return{text:n.toString(),unparseable:!1};if(typeof Blob<"u"&&n instanceof Blob){if(!(n.type===""||/json|text|graphql/i.test(n.type)))return{text:null,unparseable:!0};try{return{text:await n.text(),unparseable:!1}}catch{return{text:null,unparseable:!0}}}return{text:null,unparseable:!0}}if(B(e)){if(e.body===null)return{text:null,unparseable:!1};try{return{text:await e.clone().text(),unparseable:!1}}catch{return{text:null,unparseable:!0}}}return{text:null,unparseable:!1}}function F(e,t,n,r,a){e==null||e.emit({type:t,timestamp:Date.now(),applied:!1,detail:{url:n,method:r,...a,reason:"graphql-body-unparseable"}})}function U(e,t,n,r,a){if(!$(t,e.urlPattern))return{proceed:!1,outcome:null};if(e.methods&&!e.methods.includes(n))return{proceed:!1,outcome:null};const u=X(e.graphqlOperation,r);if(u.kind==="no-match"||u.kind==="unparseable")return{proceed:!1,outcome:u};const p=D(e,a);return W(e,p)?{proceed:!0,outcome:u}:{proceed:!1,outcome:u}}function G(e){return e?e.kind==="match"||e.kind==="skip-no-constraint"?e.operationName?{operationName:e.operationName}:{}:{}:{}}function Y(e,t,n,r,a,u){e==null||e.emit({type:"network:abort",timestamp:Date.now(),applied:a,detail:{url:n,method:r,timeoutMs:t.timeout,...G(u)}})}function H(e,t,n,r,a,u){e==null||e.emit({type:"network:corruption",timestamp:Date.now(),applied:a,detail:{url:n,method:r,strategy:t.strategy,...G(u)}})}function Se(e){return e.graphqlOperation!==void 0}function Me(e,t,n,r,a=new Map){return async(u,p)=>{var b,m,k,w;const c=he(u),d=ye(u,p),C=ge(u,p),L=(()=>{const o=[t.failures,t.latencies,t.aborts,t.corruptions,t.cors];for(const y of o)if(y!=null&&y.some(Se))return!0;return!1})();let S={kind:"not-graphql"};if(L){const o=await we(u,p);S=de(d,c,o.text,o.unparseable)}if(t.cors)for(const o of t.cors){if(!$(c,o.urlPattern)||o.methods&&!o.methods.includes(d))continue;const y=X(o.graphqlOperation,S);if(y.kind==="no-match")continue;if(y.kind==="unparseable"){F(r,"network:cors",c,d,{});continue}const N=D(o,a);if(!W(o,N))continue;const T=x(o.probability,n);if(r==null||r.emit({type:"network:cors",timestamp:Date.now(),applied:T,detail:{url:c,method:d,...G(y)}}),T){console.debug(`[chaos-maker] CORS block: ${d} ${c}`);const A=new TypeError("Failed to fetch");throw A.stack="",A}}let M=null,P=null,R,i,s=!1;const l=o=>{!M||s||(s=!0,i&&(clearTimeout(i),i=void 0),Y(r,M,c,d,o,P))};if(t.aborts)for(const o of t.aborts){const y=U(o,c,d,S,a);if(!y.proceed){((b=y.outcome)==null?void 0:b.kind)==="unparseable"&&F(r,"network:abort",c,d,{timeoutMs:o.timeout});continue}if(!x(o.probability,n)){Y(r,o,c,d,!1,y.outcome);continue}console.warn(`CHAOS: Aborting ${d} ${c} after ${o.timeout||0}ms`),M=o,P=y.outcome;const T=new AbortController;R=me(T.signal,C);const A=()=>{s||(l(!0),T.abort(be()))};o.timeout?i=setTimeout(A,o.timeout):A();break}if(M)try{const o=await e(u,ke(p,R));return l(!1),o}catch(o){throw l(!1),o}if(t.failures)for(const o of t.failures){const y=U(o,c,d,S,a);if(!y.proceed){((m=y.outcome)==null?void 0:m.kind)==="unparseable"&&F(r,"network:failure",c,d,{statusCode:o.statusCode});continue}const N=x(o.probability,n);if(r==null||r.emit({type:"network:failure",timestamp:Date.now(),applied:N,detail:{url:c,method:d,statusCode:o.statusCode,...G(y.outcome)}}),N){console.warn(`CHAOS: Forcing ${o.statusCode} for ${d} ${c}`);const T=o.body??JSON.stringify({error:"Chaos Maker Attack!"}),A=o.headers??{};return new Response(T,{status:o.statusCode,statusText:o.statusText??"Service Unavailable (Chaos)",headers:A})}}if(t.latencies)for(const o of t.latencies){const y=U(o,c,d,S,a);if(!y.proceed){((k=y.outcome)==null?void 0:k.kind)==="unparseable"&&F(r,"network:latency",c,d,{delayMs:o.delayMs});continue}const N=x(o.probability,n);r==null||r.emit({type:"network:latency",timestamp:Date.now(),applied:N,detail:{url:c,method:d,delayMs:o.delayMs,...G(y.outcome)}}),N&&(console.warn(`CHAOS: Adding ${o.delayMs}ms latency to ${d} ${c}`),await new Promise(T=>setTimeout(T,o.delayMs)))}let f=null,h=null;if(t.corruptions)for(const o of t.corruptions){const y=U(o,c,d,S,a);if(!y.proceed){((w=y.outcome)==null?void 0:w.kind)==="unparseable"&&F(r,"network:corruption",c,d,{strategy:o.strategy});continue}if(!x(o.probability,n)){H(r,o,c,d,!1,y.outcome);continue}f=o,h=y.outcome;break}let g;try{g=await e(u,p)}catch(o){throw f&&H(r,f,c,d,!1,h),o}if(!f)return g;try{console.warn(`CHAOS: Corrupting response for ${d} ${c} with strategy: ${f.strategy}`);const o=await g.text(),y=le(o,f.strategy);return H(r,f,c,d,!0,h),new Response(y,{status:g.status,statusText:g.statusText,headers:g.headers})}catch(o){throw H(r,f,c,d,!1,h),o}}}const ee=Symbol.for("chaos-maker.websocket.intercepted");function Ce(e,t){return e==="both"?!0:e===t}function te(e){return typeof e=="string"?"text":"binary"}function ne(e,t){switch(t){case"truncate":return e.slice(0,Math.max(0,Math.floor(e.length/2)));case"malformed-json":return`${e}"}`;case"empty":return"";case"wrong-type":return"<html><body>Unexpected HTML</body></html>"}}function re(e,t){if(t==="malformed-json"||t==="wrong-type")return null;if(t==="empty")return typeof Blob<"u"&&e instanceof Blob?new Blob([]):e instanceof ArrayBuffer?new ArrayBuffer(0):new Uint8Array(0);if(typeof Blob<"u"&&e instanceof Blob)return e.slice(0,Math.max(0,Math.floor(e.size/2)));if(e instanceof ArrayBuffer)return e.slice(0,Math.max(0,Math.floor(e.byteLength/2)));const n=e,r=Math.max(0,Math.floor(n.byteLength/2));return new Uint8Array(n.buffer.slice(n.byteOffset,n.byteOffset+r))}function _(e,t,n,r,a){if(!e)return null;for(const u of e){if(!$(t,u.urlPattern)||!Ce(u.direction,n))continue;const p=D(u,a);if(W(u,p)&&x(u.probability,r))return u}return null}function Q(e,t,n,r,a){e.emit({type:"websocket:drop",timestamp:Date.now(),applied:!0,detail:{url:t,direction:n,payloadType:r,...a?{reason:a}:{}}})}function oe(e,t,n,r,a){e.emit({type:"websocket:delay",timestamp:Date.now(),applied:!0,detail:{url:t,direction:n,payloadType:r,delayMs:a}})}function q(e,t,n,r,a,u,p){e.emit({type:"websocket:corrupt",timestamp:Date.now(),applied:u,detail:{url:t,direction:n,payloadType:r,strategy:a,...p?{reason:p}:{}}})}function Le(e,t,n,r){e.emit({type:"websocket:close",timestamp:Date.now(),applied:!0,detail:{url:t,closeCode:n,closeReason:r}})}function Ee(e,t,n,r,a){const u=new Map;let p=!0;const c=(i,s)=>{let l=u.get(i);l||(l=new Set,u.set(i,l)),l.add(s)},d=(i,s)=>{var l;(l=u.get(i))==null||l.delete(s)},C=(i,s)=>{const l=u.get(i);if(l){for(const f of l)clearTimeout(f.handle),f.kind==="delay"&&Q(n,f.url,f.direction,f.payloadType,s);u.delete(i)}},L=(i,s,l)=>{const f=new MessageEvent("message",{data:l,origin:s.origin,lastEventId:s.lastEventId,source:s.source,ports:Array.from(s.ports??[])});f[ee]=!0,i.dispatchEvent(f)},S=(i,s,l,f)=>{if(!p)return{handled:!1,data:l};const h="outbound",g=te(l);if(_(t.drops,s,h,r,a))return Q(n,s,h,g),{handled:!0,data:l};let b=l;const m=_(t.corruptions,s,h,r,a);if(m)if(g==="text")b=ne(b,m.strategy),q(n,s,h,g,m.strategy,!0);else{const w=re(b,m.strategy);w===null?q(n,s,h,g,m.strategy,!1,"incompatible-payload-type"):(b=w,q(n,s,h,g,m.strategy,!0))}const k=_(t.delays,s,h,r,a);if(k){oe(n,s,h,g,k.delayMs);const w={kind:"delay",handle:setTimeout(()=>{d(i,w);try{f(b)}catch{}},k.delayMs),url:s,direction:h,payloadType:g};return c(i,w),{handled:!0,data:b}}return{handled:!1,data:b}},M=(i,s)=>{i.addEventListener("message",l=>{const f=l;if(f[ee]||!p)return;const h="inbound",g=te(f.data);if(_(t.drops,s,h,r,a)){f.stopImmediatePropagation(),Q(n,s,h,g);return}let b=f.data,m=!1;const k=_(t.corruptions,s,h,r,a);if(k)if(g==="text")b=ne(b,k.strategy),m=!0,q(n,s,h,g,k.strategy,!0);else{const o=re(b,k.strategy);o===null?q(n,s,h,g,k.strategy,!1,"incompatible-payload-type"):(b=o,m=!0,q(n,s,h,g,k.strategy,!0))}const w=_(t.delays,s,h,r,a);if(w){f.stopImmediatePropagation(),oe(n,s,h,g,w.delayMs);const o={kind:"delay",handle:setTimeout(()=>{d(i,o),L(i,f,b)},w.delayMs),url:s,direction:h,payloadType:g};c(i,o);return}m&&(f.stopImmediatePropagation(),L(i,f,b))})},P=(i,s)=>{if(t.closes)for(const l of t.closes){if(!$(s,l.urlPattern))continue;const f=D(l,a);if(!W(l,f)||!x(l.probability,r))continue;const h=l.code??1e3,g=l.reason??"Chaos Maker close",b=l.afterMs??0,m=()=>{if(p){C(i,"close-interrupt"),Le(n,s,h,g);try{i.close(h,g)}catch{try{i.close()}catch{}}}};if(b<=0)i.readyState===i.OPEN?m():i.addEventListener("open",m,{once:!0});else{const k=()=>{const w={kind:"close",handle:setTimeout(m,b)};c(i,w)};i.readyState===i.OPEN?k():i.addEventListener("open",k,{once:!0})}return}};function R(i,s){const l=new e(i,s),f=typeof i=="string"?i:i.toString(),h=l.send.bind(l);return l.send=function(b){const m=S(l,f,b,h);m.handled||h(m.data)},M(l,f),P(l,f),l}Object.defineProperty(R,"prototype",{value:e.prototype,writable:!1});for(const i of["CONNECTING","OPEN","CLOSING","CLOSED"])R[i]=e[i];return{Wrapped:R,uninstall(){p=!1;for(const[,i]of u)for(const s of i)clearTimeout(s.handle),s.kind==="delay"&&Q(n,s.url,s.direction,s.payloadType,"stop-during-delay");u.clear()}}}const j=Symbol.for("chaos-maker.sw.installed");function ve(){return typeof self<"u"?self:typeof globalThis<"u"?globalThis:null}function ae(e,t){const n=e.clients;!n||typeof n.matchAll!="function"||n.matchAll({includeUncontrolled:!0}).then(r=>{for(const a of r)try{a.postMessage(t)}catch{}}).catch(()=>{})}function se(e,t){e.running&&J(e);const n=K(t.seed);if(e.seed=n.seed,e.random=n.random,e.requestCounters=new Map,t.network){const r=e.target;typeof r.fetch=="function"&&(e.originalFetch=r.fetch,r.fetch=Me(e.originalFetch.bind(r),t.network,e.random,e.emitter,e.requestCounters))}return t.websocket&&typeof e.target.WebSocket<"u"&&(e.originalWebSocket=e.target.WebSocket,e.webSocketHandle=Ee(e.originalWebSocket,t.websocket,e.emitter,e.random,e.requestCounters),e.target.WebSocket=e.webSocketHandle.Wrapped),e.running=!0,e.seed}function J(e){!e.running&&!e.originalFetch&&!e.originalWebSocket||(e.originalFetch&&(e.target.fetch=e.originalFetch,e.originalFetch=void 0),e.originalWebSocket&&(e.target.WebSocket=e.originalWebSocket,e.originalWebSocket=void 0),e.webSocketHandle&&(e.webSocketHandle.uninstall(),e.webSocketHandle=void 0),e.running=!1)}function I(e,t,n){var a;const r=(a=t.ports)==null?void 0:a[0];if(r&&typeof r.postMessage=="function")try{r.postMessage(n);return}catch{}ae(e,n)}function ie(e={}){const t=ve(),n={isRunning:()=>!1,getSeed:()=>null,getLog:()=>[],clearLog:()=>{},uninstall:()=>{}};if(!t||typeof t.fetch!="function"||typeof t.addEventListener!="function")return n;const r=t[j];if(r)return r;const a=new v(e.maxLogEntries??2e3),u=K(0),p={target:t,emitter:a,running:!1,seed:null,random:u.random,requestCounters:new Map};a.on("*",C=>{ae(t,{__chaosMakerSWEvent:!0,event:C})});const c=C=>{const L=C,S=L.data;if(!S||typeof S!="object")return;const M=S;if(M.__chaosMakerConfig){const P=se(p,M.__chaosMakerConfig);I(t,L,{__chaosMakerAck:!0,seed:P,running:p.running});return}if(M.__chaosMakerStop){J(p),I(t,L,{__chaosMakerAck:!0,running:!1});return}if(M.__chaosMakerGetLog){I(t,L,{__chaosMakerLog:!0,log:a.getLog()});return}if(M.__chaosMakerClearLog){a.clearLog(),I(t,L,{__chaosMakerAck:!0,running:p.running});return}};if(t.addEventListener("message",c),(e.source??"message")==="self-global"){const C=t.__CHAOS_CONFIG__;C&&typeof C=="object"&&se(p,C)}const d={isRunning:()=>p.running,getSeed:()=>p.seed,getLog:()=>a.getLog(),clearLog:()=>a.clearLog(),uninstall:()=>{t.removeEventListener("message",c),J(p),delete t[j]}};return t[j]=d,d}return typeof self<"u"&&typeof importScripts=="function"&&ie({source:"message"}),E.installChaosSW=ie,Object.defineProperty(E,Symbol.toStringTag,{value:"Module"}),E})({});