@chaos-maker/core 0.3.0 → 0.5.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,128 @@
1
- "use strict";var vt=Object.defineProperty;var _t=(s,e,t)=>e in s?vt(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var P=(s,e,t)=>_t(s,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});var C;(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})(C||(C={}));var $e;(function(s){s.mergeShapes=(e,t)=>({...e,...t})})($e||($e={}));const h=C.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),K=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=C.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class 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,C.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 Te=(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,C.jsonStringifyReplacer)}`;break;case u.unrecognized_keys:t=`Unrecognized key(s) in object: ${C.joinValues(s.keys,", ")}`;break;case u.invalid_union:t="Invalid input";break;case u.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${C.joinValues(s.options)}`;break;case u.invalid_enum_value:t=`Invalid enum value. Expected ${C.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}"`:C.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,C.assertNever(s)}return{message:t}};let bt=Te;function kt(){return bt}const wt=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=kt(),r=wt({issueData:e,data:s.data,path:s.path,errorMaps:[s.common.contextualErrorMap,s.schemaErrorMap,t,t===Te?void 0:Te].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"}),he=s=>({status:"dirty",value:s}),q=s=>({status:"valid",value:s}),Ie=s=>s.status==="aborted",Le=s=>s.status==="dirty",oe=s=>s.status==="valid",ve=s=>typeof Promise<"u"&&s instanceof Promise;var y;(function(s){s.errToObj=e=>typeof e=="string"?{message:e}:e||{},s.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(y||(y={}));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 De=(s,e)=>{if(oe(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 k(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 x{get description(){return this._def.description}_getType(e){return K(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:K(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:K(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:K(e)},n=this._parseSync({data:e,path:r.path,parent:r});return De(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:K(e)};if(!this["~standard"].async)try{const a=this._parseSync({data:e,path:[],parent:t});return oe(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=>oe(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:K(e)},n=this._parse({data:e,path:r.path,parent:r}),a=await(ve(n)?n:Promise.resolve(n));return De(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 ee.create(this,this._def)}nullable(){return le.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return B.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({...k(this._def),schema:this,typeName:v.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new Ne({...k(this._def),innerType:this,defaultValue:t,typeName:v.ZodDefault})}brand(){return new Bt({typeName:v.ZodBranded,type:this,...k(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new Ae({...k(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 je.create(this,e)}readonly(){return Ee.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const xt=/^c[^\s-]{8,}$/i,Ct=/^[0-9a-z]+$/,St=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Tt=/^[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,Ot=/^[a-z0-9_-]{21}$/i,Nt=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,At=/^[-+]?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)?)??$/,Et=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Rt="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Se;const 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])$/,jt=/^(?:(?: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])$/,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]))$/,Zt=/^(([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])$/,$t=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,It=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ct="((\\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])))",Lt=new RegExp(`^${ct}$`);function dt(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 Dt(s){return new RegExp(`^${dt(s)}$`)}function Vt(s){let e=`${ct}T${dt(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 zt(s,e){return!!((e==="v4"||!e)&&Mt.test(s)||(e==="v6"||!e)&&Pt.test(s))}function Ut(s,e){if(!Nt.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 qt(s,e){return!!((e==="v4"||!e)&&jt.test(s)||(e==="v6"||!e)&&Zt.test(s))}class G extends x{_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")Et.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")Se||(Se=new RegExp(Rt,"u")),Se.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")Tt.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")Ot.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")xt.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")Ct.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")St.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"?Vt(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"?Lt.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{code:u.invalid_string,validation:"date",message:a.message}),r.dirty()):a.kind==="time"?Dt(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"?At.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"duration",code:u.invalid_string,message:a.message}),r.dirty()):a.kind==="ip"?zt(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"?Ut(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"?qt(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"?$t.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"base64",code:u.invalid_string,message:a.message}),r.dirty()):a.kind==="base64url"?It.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"base64url",code:u.invalid_string,message:a.message}),r.dirty()):C.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,...y.errToObj(r)})}_addCheck(e){return new G({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...y.errToObj(e)})}url(e){return this._addCheck({kind:"url",...y.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...y.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...y.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...y.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...y.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...y.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...y.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...y.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...y.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...y.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...y.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...y.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,...y.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,...y.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...y.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...y.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t==null?void 0:t.position,...y.errToObj(t==null?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...y.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...y.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...y.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...y.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...y.errToObj(t)})}nonempty(e){return this.min(1,y.errToObj(e))}trim(){return new G({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new G({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new G({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>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}}G.create=s=>new G({checks:[],typeName:v.ZodString,coerce:(s==null?void 0:s.coerce)??!1,...k(s)});function Ft(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 ce extends x{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"?C.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"?Ft(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()):C.assertNever(a);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,y.toString(t))}gt(e,t){return this.setLimit("min",e,!1,y.toString(t))}lte(e,t){return this.setLimit("max",e,!0,y.toString(t))}lt(e,t){return this.setLimit("max",e,!1,y.toString(t))}setLimit(e,t,r,n){return new ce({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:y.toString(n)}]})}_addCheck(e){return new ce({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:y.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:y.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:y.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:y.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:y.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:y.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:y.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:y.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:y.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"&&C.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)}}ce.create=s=>new ce({checks:[],typeName:v.ZodNumber,coerce:(s==null?void 0:s.coerce)||!1,...k(s)});class pe extends x{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()):C.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,y.toString(t))}gt(e,t){return this.setLimit("min",e,!1,y.toString(t))}lte(e,t){return this.setLimit("max",e,!0,y.toString(t))}lt(e,t){return this.setLimit("max",e,!1,y.toString(t))}setLimit(e,t,r,n){return new pe({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:y.toString(n)}]})}_addCheck(e){return new pe({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:y.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:y.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:y.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:y.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:y.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}}pe.create=s=>new pe({checks:[],typeName:v.ZodBigInt,coerce:(s==null?void 0:s.coerce)??!1,...k(s)});class Ve extends x{_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 q(e.data)}}Ve.create=s=>new Ve({typeName:v.ZodBoolean,coerce:(s==null?void 0:s.coerce)||!1,...k(s)});class _e extends x{_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()):C.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:y.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:y.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,...k(s)});class ze extends x{_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 q(e.data)}}ze.create=s=>new ze({typeName:v.ZodSymbol,...k(s)});class Ue extends x{_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 q(e.data)}}Ue.create=s=>new Ue({typeName:v.ZodUndefined,...k(s)});class qe extends x{_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 q(e.data)}}qe.create=s=>new qe({typeName:v.ZodNull,...k(s)});class Fe extends x{constructor(){super(...arguments),this._any=!0}_parse(e){return q(e.data)}}Fe.create=s=>new Fe({typeName:v.ZodAny,...k(s)});class Be extends x{constructor(){super(...arguments),this._unknown=!0}_parse(e){return q(e.data)}}Be.create=s=>new Be({typeName:v.ZodUnknown,...k(s)});class te extends x{_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,...k(s)});class He extends x{_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 q(e.data)}}He.create=s=>new He({typeName:v.ZodVoid,...k(s)});class B extends x{_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 B({...this._def,minLength:{value:e,message:y.toString(t)}})}max(e,t){return new B({...this._def,maxLength:{value:e,message:y.toString(t)}})}length(e,t){return new B({...this._def,exactLength:{value:e,message:y.toString(t)}})}nonempty(e){return this.min(1,e)}}B.create=(s,e)=>new B({type:s,minLength:null,maxLength:null,exactLength:null,typeName:v.ZodArray,...k(e)});function ie(s){if(s instanceof A){const e={};for(const t in s.shape){const r=s.shape[t];e[t]=ee.create(ie(r))}return new A({...s._def,shape:()=>e})}else return s instanceof B?new B({...s._def,type:ie(s.element)}):s instanceof ee?ee.create(ie(s.unwrap())):s instanceof le?le.create(ie(s.unwrap())):s instanceof re?re.create(s.items.map(e=>ie(e))):s}class A extends x{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=C.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,N=await g.value;c.push({key:O,value:N,alwaysSet:g.alwaysSet})}return c}).then(c=>$.mergeObjectSync(r,c)):$.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(e){return y.errToObj,new A({...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:y.errToObj(e).message??n}:{message:n}}}:{}})}strip(){return new A({...this._def,unknownKeys:"strip"})}passthrough(){return new A({...this._def,unknownKeys:"passthrough"})}extend(e){return new A({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new A({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 A({...this._def,catchall:e})}pick(e){const t={};for(const r of C.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new A({...this._def,shape:()=>t})}omit(e){const t={};for(const r of C.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new A({...this._def,shape:()=>t})}deepPartial(){return ie(this)}partial(e){const t={};for(const r of C.objectKeys(this.shape)){const n=this.shape[r];e&&!e[r]?t[r]=n:t[r]=n.optional()}return new A({...this._def,shape:()=>t})}required(e){const t={};for(const r of C.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let a=this.shape[r];for(;a instanceof ee;)a=a._def.innerType;t[r]=a}return new A({...this._def,shape:()=>t})}keyof(){return ut(C.objectKeys(this.shape))}}A.create=(s,e)=>new A({shape:()=>s,unknownKeys:"strip",catchall:te.create(),typeName:v.ZodObject,...k(e)});A.strictCreate=(s,e)=>new A({shape:()=>s,unknownKeys:"strict",catchall:te.create(),typeName:v.ZodObject,...k(e)});A.lazycreate=(s,e)=>new A({shape:s,unknownKeys:"strip",catchall:te.create(),typeName:v.ZodObject,...k(e)});class be extends x{_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,...k(e)});function Oe(s,e){const t=K(s),r=K(e);if(s===e)return{valid:!0,data:s};if(t===h.object&&r===h.object){const n=C.objectKeys(e),a=C.objectKeys(s).filter(o=>n.indexOf(o)!==-1),i={...s,...e};for(const o of a){const l=Oe(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=Oe(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 x{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=(a,i)=>{if(Ie(a)||Ie(i))return _;const o=Oe(a.value,i.value);return o.valid?((Le(a)||Le(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,...k(t)});class re extends x{_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 re({...this._def,rest:e})}}re.create=(s,e)=>{if(!Array.isArray(s))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new re({items:s,typeName:v.ZodTuple,rest:null,...k(e)})};class we extends x{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 x?new we({keyType:e,valueType:t,typeName:v.ZodRecord,...k(r)}):new we({keyType:G.create(),valueType:e,typeName:v.ZodRecord,...k(t)})}}class We extends x{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}}}}We.create=(s,e,t)=>new We({valueType:e,keyType:s,typeName:v.ZodMap,...k(t)});class me extends x{_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 me({...this._def,minSize:{value:e,message:y.toString(t)}})}max(e,t){return new me({...this._def,maxSize:{value:e,message:y.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}me.create=(s,e)=>new me({valueType:s,minSize:null,maxSize:null,typeName:v.ZodSet,...k(e)});class Xe extends x{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})}}Xe.create=(s,e)=>new Xe({getter:s,typeName:v.ZodLazy,...k(e)});class Ge extends x{_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}}Ge.create=(s,e)=>new Ge({value:s,typeName:v.ZodLiteral,...k(e)});function ut(s,e){return new de({values:s,typeName:v.ZodEnum,...k(e)})}class de extends x{_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),r=this._def.values;return f(t,{expected:C.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 q(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=ut;class Je extends x{_parse(e){const t=C.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==h.string&&r.parsedType!==h.number){const n=C.objectValues(t);return f(r,{expected:C.joinValues(n),received:r.parsedType,code:u.invalid_type}),_}if(this._cache||(this._cache=new Set(C.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const n=C.objectValues(t);return f(r,{received:r.data,code:u.invalid_enum_value,options:n}),_}return q(e.data)}get enum(){return this._def.values}}Je.create=(s,e)=>new Je({values:s,typeName:v.ZodNativeEnum,...k(e)});class xe extends x{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 q(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,...k(e)});class ue extends x{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"?he(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"?he(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(!oe(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=>oe(i)?Promise.resolve(n.transform(i.value,a)).then(o=>({status:t.value,value:o})):_);C.assertNever(n)}}ue.create=(s,e,t)=>new ue({schema:s,typeName:v.ZodEffects,effect:e,...k(t)});ue.createWithPreprocess=(s,e,t)=>new ue({schema:e,effect:{type:"preprocess",transform:s},typeName:v.ZodEffects,...k(t)});class ee extends x{_parse(e){return this._getType(e)===h.undefined?q(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ee.create=(s,e)=>new ee({innerType:s,typeName:v.ZodOptional,...k(e)});class le extends x{_parse(e){return this._getType(e)===h.null?q(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}le.create=(s,e)=>new le({innerType:s,typeName:v.ZodNullable,...k(e)});class Ne extends x{_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}}Ne.create=(s,e)=>new Ne({innerType:s,typeName:v.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...k(e)});class Ae extends x{_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}}Ae.create=(s,e)=>new Ae({innerType:s,typeName:v.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...k(e)});class Ye extends x{_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}}}Ye.create=s=>new Ye({typeName:v.ZodNaN,...k(s)});class Bt extends x{_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 je extends x{_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(),he(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 je({in:e,out:t,typeName:v.ZodPipeline})}}class Ee extends x{_parse(e){const t=this._def.innerType._parse(e),r=n=>(oe(n)&&(n.value=Object.freeze(n.value)),n);return ve(t)?t.then(n=>r(n)):r(t)}unwrap(){return this._def.innerType}}Ee.create=(s,e)=>new Ee({innerType:s,typeName:v.ZodReadonly,...k(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 E=G.create,W=ce.create;te.create;const Z=B.create,I=A.create;be.create;ke.create;re.create;const Ht=we.create,Ce=de.create;xe.create;ee.create;le.create;class lt extends Error{constructor(t){const r=`Invalid ChaosConfig:
2
- ${t.map(n=>` - ${n}`).join(`
3
- `)}`;super(r);P(this,"issues");this.name="ChaosConfigError",this.issues=t}}const X=W().min(0,"Probability must be >= 0").max(1,"Probability must be <= 1"),Qe=W().int().min(1),Y={onNth:Qe.optional(),everyNth:Qe.optional(),afterN:W().int().min(0).optional()},Wt=s=>[s.onNth,s.everyNth,s.afterN].filter(e=>e!==void 0).length<=1,Q=[Wt,{message:"Only one of onNth, everyNth, or afterN may be set on a single rule"}],Xt=I({urlPattern:E().min(1,"urlPattern must not be empty"),methods:Z(E()).optional(),statusCode:W().int().min(100).max(599),probability:X,body:E().optional(),statusText:E().optional(),headers:Ht(E()).optional(),...Y}).strict().refine(...Q),Gt=I({urlPattern:E().min(1,"urlPattern must not be empty"),methods:Z(E()).optional(),delayMs:W().min(0,"delayMs must be >= 0"),probability:X,...Y}).strict().refine(...Q),Jt=I({urlPattern:E().min(1,"urlPattern must not be empty"),methods:Z(E()).optional(),probability:X,timeout:W().min(0,"timeout must be >= 0").optional(),...Y}).strict().refine(...Q),Yt=I({urlPattern:E().min(1,"urlPattern must not be empty"),methods:Z(E()).optional(),probability:X,strategy:Ce(["truncate","malformed-json","empty","wrong-type"]),...Y}).strict().refine(...Q),Qt=I({urlPattern:E().min(1,"urlPattern must not be empty"),methods:Z(E()).optional(),probability:X,...Y}).strict().refine(...Q),Kt=I({failures:Z(Xt).optional(),latencies:Z(Gt).optional(),aborts:Z(Jt).optional(),corruptions:Z(Yt).optional(),cors:Z(Qt).optional()}).strict(),es=I({selector:E().min(1,"selector must not be empty"),action:Ce(["disable","hide","remove"]),probability:X}).strict(),ts=I({assaults:Z(es).optional()}).strict(),Pe=Ce(["inbound","outbound","both"]),ss=I({urlPattern:E().min(1,"urlPattern must not be empty"),direction:Pe,probability:X,...Y}).strict().refine(...Q),rs=I({urlPattern:E().min(1,"urlPattern must not be empty"),direction:Pe,delayMs:W().min(0,"delayMs must be >= 0"),probability:X,...Y}).strict().refine(...Q),ns=I({urlPattern:E().min(1,"urlPattern must not be empty"),direction:Pe,strategy:Ce(["truncate","malformed-json","empty","wrong-type"]),probability:X,...Y}).strict().refine(...Q),as=W().int().refine(s=>s===1e3||s>=3e3&&s<=4999,{message:"code must be 1000 or in the range 3000-4999"}),is=E().refine(s=>new TextEncoder().encode(s).length<=123,{message:"reason must be <= 123 UTF-8 bytes"}),os=I({urlPattern:E().min(1,"urlPattern must not be empty"),code:as.optional(),reason:is.optional(),afterMs:W().min(0,"afterMs must be >= 0").optional(),probability:X,...Y}).strict().refine(...Q),cs=I({drops:Z(ss).optional(),delays:Z(rs).optional(),corruptions:Z(ns).optional(),closes:Z(os).optional()}).strict(),ds=I({network:Kt.optional(),ui:ts.optional(),websocket:cs.optional(),seed:W().int("Seed must be an integer").optional()}).strict();function ft(s){const e=ds.safeParse(s);if(!e.success){const t=e.error.issues.map(r=>`${r.path.join(".")}: ${r.message}`);throw new lt(t)}return e.data}function us(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 ht(){return Math.random()*4294967296>>>0}function pt(s){const e=s??ht();return{random:us(e),seed:e}}class mt{constructor(e=2e3){P(this,"listeners",new Map);P(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 V(s,e){const t=(e.get(s)??0)+1;return e.set(s,t),t}function z(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 U(s,e){return e==="*"?!0:s.includes(e)}function yt(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 ls(s){return Ze(s)?s.url:s.toString()}function fs(s,e){return e!=null&&e.method?e.method.toUpperCase():Ze(s)?s.method.toUpperCase():"GET"}function hs(s,e){if(e!=null&&e.signal)return e.signal;if(Ze(s))return s.signal}function ps(){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 ms(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 ys(s,e){return e?{...s??{},signal:e}:s}function Ke(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 ye(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 gs(s,e,t,r,n=new Map){return async(a,i)=>{const o=ls(a),l=fs(a,i),c=hs(a,i);if(e.cors){for(const d of e.cors)if(U(o,d.urlPattern)&&(!d.methods||d.methods.includes(l))){const b=V(d,n);if(!z(d,b))continue;const w=D(d.probability,t);if(r==null||r.emit({type:"network:cors",timestamp:Date.now(),applied:w,detail:{url:o,method:l}}),w){console.debug(`[chaos-maker] CORS block: ${l} ${o}`);const S=new TypeError("Failed to fetch");throw S.stack="",S}}}let g=null,O,N,M=!1;const R=d=>{!g||M||(M=!0,N&&(clearTimeout(N),N=void 0),Ke(r,g,o,l,d))};if(e.aborts){for(const d of e.aborts)if(U(o,d.urlPattern)&&(!d.methods||d.methods.includes(l))){const b=V(d,n);if(!z(d,b))continue;if(!D(d.probability,t)){Ke(r,d,o,l,!1);continue}console.warn(`CHAOS: Aborting ${l} ${o} after ${d.timeout||0}ms`),g=d;const S=new AbortController;O=ms(S.signal,c);const T=()=>{M||(R(!0),S.abort(ps()))};d.timeout?N=setTimeout(T,d.timeout):T();break}}if(g)try{const d=await s(a,ys(i,O));return R(!1),d}catch(d){throw R(!1),d}if(e.failures){for(const d of e.failures)if(U(o,d.urlPattern)&&(!d.methods||d.methods.includes(l))){const b=V(d,n);if(!z(d,b))continue;const w=D(d.probability,t);if(r==null||r.emit({type:"network:failure",timestamp:Date.now(),applied:w,detail:{url:o,method:l,statusCode:d.statusCode}}),w){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(U(o,d.urlPattern)&&(!d.methods||d.methods.includes(l))){const b=V(d,n);if(!z(d,b))continue;const w=D(d.probability,t);r==null||r.emit({type:"network:latency",timestamp:Date.now(),applied:w,detail:{url:o,method:l,delayMs:d.delayMs}}),w&&(console.warn(`CHAOS: Adding ${d.delayMs}ms latency to ${l} ${o}`),await new Promise(S=>setTimeout(S,d.delayMs)))}}let m=null;if(e.corruptions){for(const d of e.corruptions)if(U(o,d.urlPattern)&&(!d.methods||d.methods.includes(l))){const b=V(d,n);if(!z(d,b))continue;if(!D(d.probability,t)){ye(r,d,o,l,!1);continue}m=d;break}}let p;try{p=await s(a,i)}catch(d){throw m&&ye(r,m,o,l,!1),d}if(!m)return p;try{console.warn(`CHAOS: Corrupting response for ${l} ${o} with strategy: ${m.strategy}`);const d=await p.text(),b=yt(d,m.strategy);return ye(r,m,o,l,!0),new Response(b,{status:p.status,statusText:p.statusText,headers:p.headers})}catch(d){throw ye(r,m,o,l,!1),d}}}function et(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 tt(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 vs(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(U(i,c.urlPattern)&&(!c.methods||c.methods.includes(o))){const g=V(c,n);if(!z(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(U(i,c.urlPattern)&&(!c.methods||c.methods.includes(o))){const g=V(c,n);if(!z(c,g))continue;if(!D(c.probability,t)){et(r,c,i,o,!1);continue}console.warn(`CHAOS: Aborting ${o} ${i} after ${c.timeout||0}ms`);let N=!1,M;const R=()=>{M&&(clearTimeout(M),M=void 0),typeof this.removeEventListener=="function"&&this.removeEventListener("loadend",p)},m=b=>{N||(N=!0,R(),et(r,c,i,o,b))},p=()=>{m(!1)},d=()=>{N||(m(!0),this.abort())};typeof this.addEventListener=="function"&&this.addEventListener("loadend",p);try{s.call(this,a)}catch(b){throw m(!1),b}if(N)return;c.timeout?M=setTimeout(d,c.timeout):d();return}}if(e.failures){for(const c of e.failures)if(U(i,c.urlPattern)&&(!c.methods||c.methods.includes(o))){const g=V(c,n);if(!z(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 N=c.body??JSON.stringify({error:"Chaos Maker Attack!"});Object.defineProperty(this,"responseText",{value:N,configurable:!0});const M=c.headers??{};Object.defineProperty(this,"getResponseHeader",{value:R=>{const m=Object.keys(M).find(p=>p.toLowerCase()===R.toLowerCase());return m?M[m]:null},configurable:!0}),Object.defineProperty(this,"getAllResponseHeaders",{value:()=>Object.entries(M).map(([R,m])=>`${R}: ${m}`).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(U(i,c.urlPattern)&&(!c.methods||c.methods.includes(o))){const g=V(c,n);if(!z(c,g))continue;if(!D(c.probability,t)){tt(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",R),this.removeEventListener("abort",R),this.removeEventListener("loadend",m))},N=p=>{c||(c=!0,tt(r,l,i,o,p),O())},M=()=>{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}),N(!1),p):(g=yt(p,l.strategy),Object.defineProperty(this,"responseText",{value:g,configurable:!0}),N(!0),g)}catch(p){throw N(!1),p}},R=()=>{N(!1)},m=()=>{if(!c)try{M()}catch{}};typeof this.addEventListener=="function"&&(this.addEventListener("error",R),this.addEventListener("abort",R),this.addEventListener("loadend",m)),Object.defineProperty(this,"responseText",{get(){return M()},configurable:!0})}if(e.latencies){for(const c of e.latencies)if(U(i,c.urlPattern)&&(!c.methods||c.methods.includes(o))){const g=V(c,n);if(!z(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 _s(s){return function(e,t){this._chaos_url=t.toString(),this._chaos_method=e.toUpperCase(),s.call(this,e,t)}}function Re(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 bs(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)&&Re(n,a,t,r),n.querySelectorAll(a.selector).forEach(i=>{Re(i,a,t,r)})}catch(i){console.error(`Chaos Maker: Invalid selector '${a.selector}'`,i)}}function ks(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=>{Re(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=>bs(i,s,e,t))})}const st=Symbol.for("chaos-maker.websocket.intercepted");function ws(s,e){return s==="both"?!0:s===e}function rt(s){return typeof s=="string"?"text":"binary"}function nt(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 at(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 ne(s,e,t,r,n){if(!s)return null;for(const a of s){if(!U(e,a.urlPattern)||!ws(a.direction,t))continue;const i=V(a,n);if(z(a,i)&&D(a.probability,r))return a}return null}function ge(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 it(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 ae(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 xs(s,e,t,r){s.emit({type:"websocket:close",timestamp:Date.now(),applied:!0,detail:{url:e,closeCode:t,closeReason:r}})}function Cs(s,e,t,r,n){const a=new Map;let i=!0;const o=(m,p)=>{let d=a.get(m);d||(d=new Set,a.set(m,d)),d.add(p)},l=(m,p)=>{var d;(d=a.get(m))==null||d.delete(p)},c=(m,p)=>{const d=a.get(m);if(d){for(const b of d)clearTimeout(b.handle),b.kind==="delay"&&ge(t,b.url,b.direction,b.payloadType,p);a.delete(m)}},g=(m,p,d)=>{const b=new MessageEvent("message",{data:d,origin:p.origin,lastEventId:p.lastEventId,source:p.source,ports:Array.from(p.ports??[])});b[st]=!0,m.dispatchEvent(b)},O=(m,p,d,b)=>{if(!i)return{handled:!1,data:d};const w="outbound",S=rt(d);if(ne(e.drops,p,w,r,n))return ge(t,p,w,S),{handled:!0,data:d};let T=d;const j=ne(e.corruptions,p,w,r,n);if(j)if(S==="text")T=nt(T,j.strategy),ae(t,p,w,S,j.strategy,!0);else{const F=at(T,j.strategy);F===null?ae(t,p,w,S,j.strategy,!1,"incompatible-payload-type"):(T=F,ae(t,p,w,S,j.strategy,!0))}const L=ne(e.delays,p,w,r,n);if(L){it(t,p,w,S,L.delayMs);const F={kind:"delay",handle:setTimeout(()=>{l(m,F);try{b(T)}catch{}},L.delayMs),url:p,direction:w,payloadType:S};return o(m,F),{handled:!0,data:T}}return{handled:!1,data:T}},N=(m,p)=>{m.addEventListener("message",d=>{const b=d;if(b[st]||!i)return;const w="inbound",S=rt(b.data);if(ne(e.drops,p,w,r,n)){b.stopImmediatePropagation(),ge(t,p,w,S);return}let T=b.data,j=!1;const L=ne(e.corruptions,p,w,r,n);if(L)if(S==="text")T=nt(T,L.strategy),j=!0,ae(t,p,w,S,L.strategy,!0);else{const fe=at(T,L.strategy);fe===null?ae(t,p,w,S,L.strategy,!1,"incompatible-payload-type"):(T=fe,j=!0,ae(t,p,w,S,L.strategy,!0))}const F=ne(e.delays,p,w,r,n);if(F){b.stopImmediatePropagation(),it(t,p,w,S,F.delayMs);const fe={kind:"delay",handle:setTimeout(()=>{l(m,fe),g(m,b,T)},F.delayMs),url:p,direction:w,payloadType:S};o(m,fe);return}j&&(b.stopImmediatePropagation(),g(m,b,T))})},M=(m,p)=>{if(e.closes)for(const d of e.closes){if(!U(p,d.urlPattern))continue;const b=V(d,n);if(!z(d,b)||!D(d.probability,r))continue;const w=d.code??1e3,S=d.reason??"Chaos Maker close",T=d.afterMs??0,j=()=>{if(i){c(m,"close-interrupt"),xs(t,p,w,S);try{m.close(w,S)}catch{try{m.close()}catch{}}}};if(T<=0)m.readyState===m.OPEN?j():m.addEventListener("open",j,{once:!0});else{const L=()=>{const F={kind:"close",handle:setTimeout(j,T)};o(m,F)};m.readyState===m.OPEN?L():m.addEventListener("open",L,{once:!0})}return}};function R(m,p){const d=new s(m,p),b=typeof m=="string"?m:m.toString(),w=d.send.bind(d);return d.send=function(T){const j=O(d,b,T,w);j.handled||w(j.data)},N(d,b),M(d,b),d}Object.defineProperty(R,"prototype",{value:s.prototype,writable:!1});for(const m of["CONNECTING","OPEN","CLOSING","CLOSED"])R[m]=s[m];return{Wrapped:R,uninstall(){i=!1;for(const[,m]of a)for(const p of m)clearTimeout(p.handle),p.kind==="delay"&&ge(t,p.url,p.direction,p.payloadType,"stop-during-delay");a.clear()}}}class Me{constructor(e){P(this,"config");P(this,"emitter");P(this,"random");P(this,"seed");P(this,"running",!1);P(this,"originalFetch");P(this,"originalXhrSend");P(this,"originalXhrOpen");P(this,"domObserver");P(this,"originalWebSocket");P(this,"webSocketHandle");P(this,"requestCounters",new Map);this.config=ft(e),this.emitter=new mt;const t=pt(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=gs(this.originalFetch.bind(window),this.config.network,this.random,this.emitter,this.requestCounters),this.originalXhrOpen=window.XMLHttpRequest.prototype.open,window.XMLHttpRequest.prototype.open=_s(this.originalXhrOpen),this.originalXhrSend=window.XMLHttpRequest.prototype.send,window.XMLHttpRequest.prototype.send=vs(this.originalXhrSend,this.config.network,this.random,this.emitter,this.requestCounters)),this.config.ui&&(this.domObserver=ks(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=Cs(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 ot(s){return JSON.parse(JSON.stringify(s))}class Ss{constructor(e){P(this,"config");this.config=e?ot(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 ot(this.config)}}const se="*";function gt(s){if(s&&typeof s=="object"&&!Object.isFrozen(s)){Object.freeze(s);for(const e of Object.values(s))gt(e)}return s}const Ts=gt({unstableApi:{network:{failures:[{urlPattern:"/api/",statusCode:500,probability:.1}],latencies:[{urlPattern:"/api/",delayMs:1e3,probability:.2}]}},slowNetwork:{network:{latencies:[{urlPattern:se,delayMs:2e3,probability:1}]}},offlineMode:{network:{cors:[{urlPattern:se,probability:1}]}},flakyConnection:{network:{aborts:[{urlPattern:se,probability:.05}],latencies:[{urlPattern:se,delayMs:3e3,probability:.1}]}},degradedUi:{ui:{assaults:[{selector:"button",action:"disable",probability:.2},{selector:"a",action:"hide",probability:.1}]}},unreliableWebSocket:{websocket:{drops:[{urlPattern:se,direction:"both",probability:.1}],delays:[{urlPattern:se,direction:"inbound",delayMs:500,probability:1}],corruptions:[{urlPattern:se,direction:"inbound",strategy:"truncate",probability:.05}]}}});if(typeof window<"u"){window.ChaosMaker=Me;const s={instance:null,start:e=>{try{return s.instance&&s.instance.stop(),s.instance=new Me(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)}}exports.ChaosConfigBuilder=Ss;exports.ChaosConfigError=lt;exports.ChaosEventEmitter=mt;exports.ChaosMaker=Me;exports.createPrng=pt;exports.generateSeed=ht;exports.presets=Ts;exports.validateConfig=ft;
1
+ "use strict";var is=Object.defineProperty;var cs=(t,e,n)=>e in t?is(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var R=(t,e,n)=>cs(t,typeof e!="symbol"?e+"":e,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});var O;(function(t){t.assertEqual=r=>{};function e(r){}t.assertIs=e;function n(r){throw new Error}t.assertNever=n,t.arrayToEnum=r=>{const a={};for(const o of r)a[o]=o;return a},t.getValidEnumValues=r=>{const a=t.objectKeys(r).filter(i=>typeof r[r[i]]!="number"),o={};for(const i of a)o[i]=r[i];return t.objectValues(o)},t.objectValues=r=>t.objectKeys(r).map(function(a){return r[a]}),t.objectKeys=typeof Object.keys=="function"?r=>Object.keys(r):r=>{const a=[];for(const o in r)Object.prototype.hasOwnProperty.call(r,o)&&a.push(o);return a},t.find=(r,a)=>{for(const o of r)if(a(o))return o},t.isInteger=typeof Number.isInteger=="function"?r=>Number.isInteger(r):r=>typeof r=="number"&&Number.isFinite(r)&&Math.floor(r)===r;function s(r,a=" | "){return r.map(o=>typeof o=="string"?`'${o}'`:o).join(a)}t.joinValues=s,t.jsonStringifyReplacer=(r,a)=>typeof a=="bigint"?a.toString():a})(O||(O={}));var Mt;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(Mt||(Mt={}));const m=O.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ue=t=>{switch(typeof t){case"undefined":return m.undefined;case"string":return m.string;case"number":return Number.isNaN(t)?m.nan:m.number;case"boolean":return m.boolean;case"function":return m.function;case"bigint":return m.bigint;case"symbol":return m.symbol;case"object":return Array.isArray(t)?m.array:t===null?m.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?m.promise:typeof Map<"u"&&t instanceof Map?m.map:typeof Set<"u"&&t instanceof Set?m.set:typeof Date<"u"&&t instanceof Date?m.date:m.object;default:return m.unknown}},h=O.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 ce extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=s=>{this.issues=[...this.issues,s]},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){const n=e||function(a){return a.message},s={_errors:[]},r=a=>{for(const o of a.issues)if(o.code==="invalid_union")o.unionErrors.map(r);else if(o.code==="invalid_return_type")r(o.returnTypeError);else if(o.code==="invalid_arguments")r(o.argumentsError);else if(o.path.length===0)s._errors.push(n(o));else{let i=s,c=0;for(;c<o.path.length;){const u=o.path[c];c===o.path.length-1?(i[u]=i[u]||{_errors:[]},i[u]._errors.push(n(o))):i[u]=i[u]||{_errors:[]},i=i[u],c++}}};return r(this),s}static assert(e){if(!(e instanceof ce))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,O.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){const n={},s=[];for(const r of this.issues)if(r.path.length>0){const a=r.path[0];n[a]=n[a]||[],n[a].push(e(r))}else s.push(e(r));return{formErrors:s,fieldErrors:n}}get formErrors(){return this.flatten()}}ce.create=t=>new ce(t);const it=(t,e)=>{let n;switch(t.code){case h.invalid_type:t.received===m.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case h.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,O.jsonStringifyReplacer)}`;break;case h.unrecognized_keys:n=`Unrecognized key(s) in object: ${O.joinValues(t.keys,", ")}`;break;case h.invalid_union:n="Invalid input";break;case h.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${O.joinValues(t.options)}`;break;case h.invalid_enum_value:n=`Invalid enum value. Expected ${O.joinValues(t.options)}, received '${t.received}'`;break;case h.invalid_arguments:n="Invalid function arguments";break;case h.invalid_return_type:n="Invalid function return type";break;case h.invalid_date:n="Invalid date";break;case h.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:O.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case h.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case h.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case h.custom:n="Invalid input";break;case h.invalid_intersection_types:n="Intersection results could not be merged";break;case h.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case h.not_finite:n="Number must be finite";break;default:n=e.defaultError,O.assertNever(t)}return{message:n}};let us=it;function ls(){return us}const ds=t=>{const{data:e,path:n,errorMaps:s,issueData:r}=t,a=[...n,...r.path||[]],o={...r,path:a};if(r.message!==void 0)return{...r,path:a,message:r.message};let i="";const c=s.filter(u=>!!u).slice().reverse();for(const u of c)i=u(o,{data:e,defaultError:i}).message;return{...r,path:a,message:i}};function g(t,e){const n=ls(),s=ds({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===it?void 0:it].filter(r=>!!r)});t.common.issues.push(s)}class z{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){const s=[];for(const r of n){if(r.status==="aborted")return x;r.status==="dirty"&&e.dirty(),s.push(r.value)}return{status:e.value,value:s}}static async mergeObjectAsync(e,n){const s=[];for(const r of n){const a=await r.key,o=await r.value;s.push({key:a,value:o})}return z.mergeObjectSync(e,s)}static mergeObjectSync(e,n){const s={};for(const r of n){const{key:a,value:o}=r;if(a.status==="aborted"||o.status==="aborted")return x;a.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof o.value<"u"||r.alwaysSet)&&(s[a.value]=o.value)}return{status:e.value,value:s}}}const x=Object.freeze({status:"aborted"}),Te=t=>({status:"dirty",value:t}),Q=t=>({status:"valid",value:t}),jt=t=>t.status==="aborted",Pt=t=>t.status==="dirty",_e=t=>t.status==="valid",qe=t=>typeof Promise<"u"&&t instanceof Promise;var b;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(b||(b={}));class re{constructor(e,n,s,r){this._cachedPath=[],this.parent=e,this.data=n,this._path=s,this._key=r}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 $t=(t,e)=>{if(_e(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new ce(t.common.issues);return this._error=n,this._error}}};function E(t){if(!t)return{};const{errorMap:e,invalid_type_error:n,required_error:s,description:r}=t;if(e&&(n||s))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:r}:{errorMap:(o,i)=>{const{message:c}=t;return o.code==="invalid_enum_value"?{message:c??i.defaultError}:typeof i.data>"u"?{message:c??s??i.defaultError}:o.code!=="invalid_type"?{message:i.defaultError}:{message:c??n??i.defaultError}},description:r}}class T{get description(){return this._def.description}_getType(e){return ue(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:ue(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:ue(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const n=this._parse(e);if(qe(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){const n=this._parse(e);return Promise.resolve(n)}parse(e,n){const s=this.safeParse(e,n);if(s.success)return s.data;throw s.error}safeParse(e,n){const s={common:{issues:[],async:(n==null?void 0:n.async)??!1,contextualErrorMap:n==null?void 0:n.errorMap},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ue(e)},r=this._parseSync({data:e,path:s.path,parent:s});return $t(s,r)}"~validate"(e){var s,r;const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ue(e)};if(!this["~standard"].async)try{const a=this._parseSync({data:e,path:[],parent:n});return _e(a)?{value:a.value}:{issues:n.common.issues}}catch(a){(r=(s=a==null?void 0:a.message)==null?void 0:s.toLowerCase())!=null&&r.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(a=>_e(a)?{value:a.value}:{issues:n.common.issues})}async parseAsync(e,n){const s=await this.safeParseAsync(e,n);if(s.success)return s.data;throw s.error}async safeParseAsync(e,n){const s={common:{issues:[],contextualErrorMap:n==null?void 0:n.errorMap,async:!0},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ue(e)},r=this._parse({data:e,path:s.path,parent:s}),a=await(qe(r)?r:Promise.resolve(r));return $t(s,a)}refine(e,n){const s=r=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(r):n;return this._refinement((r,a)=>{const o=e(r),i=()=>a.addIssue({code:h.custom,...s(r)});return typeof Promise<"u"&&o instanceof Promise?o.then(c=>c?!0:(i(),!1)):o?!0:(i(),!1)})}refinement(e,n){return this._refinement((s,r)=>e(s)?!0:(r.addIssue(typeof n=="function"?n(s,r):n),!1))}_refinement(e){return new xe({schema:this,typeName:w.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:n=>this["~validate"](n)}}optional(){return le.create(this,this._def)}nullable(){return Se.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ne.create(this)}promise(){return He.create(this,this._def)}or(e){return ze.create([this,e],this._def)}and(e){return Fe.create(this,e,this._def)}transform(e){return new xe({...E(this._def),schema:this,typeName:w.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const n=typeof e=="function"?e:()=>e;return new dt({...E(this._def),innerType:this,defaultValue:n,typeName:w.ZodDefault})}brand(){return new Ps({typeName:w.ZodBranded,type:this,...E(this._def)})}catch(e){const n=typeof e=="function"?e:()=>e;return new ft({...E(this._def),innerType:this,catchValue:n,typeName:w.ZodCatch})}describe(e){const n=this.constructor;return new n({...this._def,description:e})}pipe(e){return _t.create(this,e)}readonly(){return ht.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const fs=/^c[^\s-]{8,}$/i,hs=/^[0-9a-z]+$/,ps=/^[0-9A-HJKMNP-TV-Z]{26}$/i,gs=/^[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,ys=/^[a-z0-9_-]{21}$/i,ms=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,bs=/^[-+]?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)?)??$/,vs=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,_s="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let st;const ks=/^(?:(?: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])$/,ws=/^(?:(?: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])$/,xs=/^(([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]))$/,Ss=/^(([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])$/,Cs=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Es=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,un="((\\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])))",Ns=new RegExp(`^${un}$`);function ln(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);const n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function Ts(t){return new RegExp(`^${ln(t)}$`)}function Os(t){let e=`${un}T${ln(t)}`;const n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function Rs(t,e){return!!((e==="v4"||!e)&&ks.test(t)||(e==="v6"||!e)&&xs.test(t))}function As(t,e){if(!ms.test(t))return!1;try{const[n]=t.split(".");if(!n)return!1;const s=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),r=JSON.parse(atob(s));return!(typeof r!="object"||r===null||"typ"in r&&(r==null?void 0:r.typ)!=="JWT"||!r.alg||e&&r.alg!==e)}catch{return!1}}function Ms(t,e){return!!((e==="v4"||!e)&&ws.test(t)||(e==="v6"||!e)&&Ss.test(t))}class ie extends T{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==m.string){const a=this._getOrReturnCtx(e);return g(a,{code:h.invalid_type,expected:m.string,received:a.parsedType}),x}const s=new z;let r;for(const a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(r=this._getOrReturnCtx(e,r),g(r,{code:h.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),s.dirty());else if(a.kind==="max")e.data.length>a.value&&(r=this._getOrReturnCtx(e,r),g(r,{code:h.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),s.dirty());else if(a.kind==="length"){const o=e.data.length>a.value,i=e.data.length<a.value;(o||i)&&(r=this._getOrReturnCtx(e,r),o?g(r,{code:h.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):i&&g(r,{code:h.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),s.dirty())}else if(a.kind==="email")vs.test(e.data)||(r=this._getOrReturnCtx(e,r),g(r,{validation:"email",code:h.invalid_string,message:a.message}),s.dirty());else if(a.kind==="emoji")st||(st=new RegExp(_s,"u")),st.test(e.data)||(r=this._getOrReturnCtx(e,r),g(r,{validation:"emoji",code:h.invalid_string,message:a.message}),s.dirty());else if(a.kind==="uuid")gs.test(e.data)||(r=this._getOrReturnCtx(e,r),g(r,{validation:"uuid",code:h.invalid_string,message:a.message}),s.dirty());else if(a.kind==="nanoid")ys.test(e.data)||(r=this._getOrReturnCtx(e,r),g(r,{validation:"nanoid",code:h.invalid_string,message:a.message}),s.dirty());else if(a.kind==="cuid")fs.test(e.data)||(r=this._getOrReturnCtx(e,r),g(r,{validation:"cuid",code:h.invalid_string,message:a.message}),s.dirty());else if(a.kind==="cuid2")hs.test(e.data)||(r=this._getOrReturnCtx(e,r),g(r,{validation:"cuid2",code:h.invalid_string,message:a.message}),s.dirty());else if(a.kind==="ulid")ps.test(e.data)||(r=this._getOrReturnCtx(e,r),g(r,{validation:"ulid",code:h.invalid_string,message:a.message}),s.dirty());else if(a.kind==="url")try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),g(r,{validation:"url",code:h.invalid_string,message:a.message}),s.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),g(r,{validation:"regex",code:h.invalid_string,message:a.message}),s.dirty())):a.kind==="trim"?e.data=e.data.trim():a.kind==="includes"?e.data.includes(a.value,a.position)||(r=this._getOrReturnCtx(e,r),g(r,{code:h.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),s.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)||(r=this._getOrReturnCtx(e,r),g(r,{code:h.invalid_string,validation:{startsWith:a.value},message:a.message}),s.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(r=this._getOrReturnCtx(e,r),g(r,{code:h.invalid_string,validation:{endsWith:a.value},message:a.message}),s.dirty()):a.kind==="datetime"?Os(a).test(e.data)||(r=this._getOrReturnCtx(e,r),g(r,{code:h.invalid_string,validation:"datetime",message:a.message}),s.dirty()):a.kind==="date"?Ns.test(e.data)||(r=this._getOrReturnCtx(e,r),g(r,{code:h.invalid_string,validation:"date",message:a.message}),s.dirty()):a.kind==="time"?Ts(a).test(e.data)||(r=this._getOrReturnCtx(e,r),g(r,{code:h.invalid_string,validation:"time",message:a.message}),s.dirty()):a.kind==="duration"?bs.test(e.data)||(r=this._getOrReturnCtx(e,r),g(r,{validation:"duration",code:h.invalid_string,message:a.message}),s.dirty()):a.kind==="ip"?Rs(e.data,a.version)||(r=this._getOrReturnCtx(e,r),g(r,{validation:"ip",code:h.invalid_string,message:a.message}),s.dirty()):a.kind==="jwt"?As(e.data,a.alg)||(r=this._getOrReturnCtx(e,r),g(r,{validation:"jwt",code:h.invalid_string,message:a.message}),s.dirty()):a.kind==="cidr"?Ms(e.data,a.version)||(r=this._getOrReturnCtx(e,r),g(r,{validation:"cidr",code:h.invalid_string,message:a.message}),s.dirty()):a.kind==="base64"?Cs.test(e.data)||(r=this._getOrReturnCtx(e,r),g(r,{validation:"base64",code:h.invalid_string,message:a.message}),s.dirty()):a.kind==="base64url"?Es.test(e.data)||(r=this._getOrReturnCtx(e,r),g(r,{validation:"base64url",code:h.invalid_string,message:a.message}),s.dirty()):O.assertNever(a);return{status:s.value,value:e.data}}_regex(e,n,s){return this.refinement(r=>e.test(r),{validation:n,code:h.invalid_string,...b.errToObj(s)})}_addCheck(e){return new ie({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...b.errToObj(e)})}url(e){return this._addCheck({kind:"url",...b.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...b.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...b.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...b.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...b.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...b.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...b.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...b.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...b.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...b.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...b.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...b.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,...b.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,...b.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...b.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...b.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n==null?void 0:n.position,...b.errToObj(n==null?void 0:n.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...b.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...b.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...b.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...b.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...b.errToObj(n)})}nonempty(e){return this.min(1,b.errToObj(e))}trim(){return new ie({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ie({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ie({...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 n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}}ie.create=t=>new ie({checks:[],typeName:w.ZodString,coerce:(t==null?void 0:t.coerce)??!1,...E(t)});function js(t,e){const n=(t.toString().split(".")[1]||"").length,s=(e.toString().split(".")[1]||"").length,r=n>s?n:s,a=Number.parseInt(t.toFixed(r).replace(".","")),o=Number.parseInt(e.toFixed(r).replace(".",""));return a%o/10**r}class ke extends T{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)!==m.number){const a=this._getOrReturnCtx(e);return g(a,{code:h.invalid_type,expected:m.number,received:a.parsedType}),x}let s;const r=new z;for(const a of this._def.checks)a.kind==="int"?O.isInteger(e.data)||(s=this._getOrReturnCtx(e,s),g(s,{code:h.invalid_type,expected:"integer",received:"float",message:a.message}),r.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(s=this._getOrReturnCtx(e,s),g(s,{code:h.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),r.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(s=this._getOrReturnCtx(e,s),g(s,{code:h.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),r.dirty()):a.kind==="multipleOf"?js(e.data,a.value)!==0&&(s=this._getOrReturnCtx(e,s),g(s,{code:h.not_multiple_of,multipleOf:a.value,message:a.message}),r.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(s=this._getOrReturnCtx(e,s),g(s,{code:h.not_finite,message:a.message}),r.dirty()):O.assertNever(a);return{status:r.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,b.toString(n))}gt(e,n){return this.setLimit("min",e,!1,b.toString(n))}lte(e,n){return this.setLimit("max",e,!0,b.toString(n))}lt(e,n){return this.setLimit("max",e,!1,b.toString(n))}setLimit(e,n,s,r){return new ke({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:s,message:b.toString(r)}]})}_addCheck(e){return new ke({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:b.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:b.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:b.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:b.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:b.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:b.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:b.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:b.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:b.toString(e)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&O.isInteger(e.value))}get isFinite(){let e=null,n=null;for(const s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(n===null||s.value>n)&&(n=s.value):s.kind==="max"&&(e===null||s.value<e)&&(e=s.value)}return Number.isFinite(n)&&Number.isFinite(e)}}ke.create=t=>new ke({checks:[],typeName:w.ZodNumber,coerce:(t==null?void 0:t.coerce)||!1,...E(t)});class Ae extends T{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)!==m.bigint)return this._getInvalidInput(e);let s;const r=new z;for(const a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(s=this._getOrReturnCtx(e,s),g(s,{code:h.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),r.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(s=this._getOrReturnCtx(e,s),g(s,{code:h.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),r.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(s=this._getOrReturnCtx(e,s),g(s,{code:h.not_multiple_of,multipleOf:a.value,message:a.message}),r.dirty()):O.assertNever(a);return{status:r.value,value:e.data}}_getInvalidInput(e){const n=this._getOrReturnCtx(e);return g(n,{code:h.invalid_type,expected:m.bigint,received:n.parsedType}),x}gte(e,n){return this.setLimit("min",e,!0,b.toString(n))}gt(e,n){return this.setLimit("min",e,!1,b.toString(n))}lte(e,n){return this.setLimit("max",e,!0,b.toString(n))}lt(e,n){return this.setLimit("max",e,!1,b.toString(n))}setLimit(e,n,s,r){return new Ae({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:s,message:b.toString(r)}]})}_addCheck(e){return new Ae({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:b.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:b.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:b.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:b.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:b.toString(n)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}}Ae.create=t=>new Ae({checks:[],typeName:w.ZodBigInt,coerce:(t==null?void 0:t.coerce)??!1,...E(t)});class ct extends T{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==m.boolean){const s=this._getOrReturnCtx(e);return g(s,{code:h.invalid_type,expected:m.boolean,received:s.parsedType}),x}return Q(e.data)}}ct.create=t=>new ct({typeName:w.ZodBoolean,coerce:(t==null?void 0:t.coerce)||!1,...E(t)});class Ve extends T{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==m.date){const a=this._getOrReturnCtx(e);return g(a,{code:h.invalid_type,expected:m.date,received:a.parsedType}),x}if(Number.isNaN(e.data.getTime())){const a=this._getOrReturnCtx(e);return g(a,{code:h.invalid_date}),x}const s=new z;let r;for(const a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(r=this._getOrReturnCtx(e,r),g(r,{code:h.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),s.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(r=this._getOrReturnCtx(e,r),g(r,{code:h.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),s.dirty()):O.assertNever(a);return{status:s.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Ve({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:b.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:b.toString(n)})}get minDate(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}}Ve.create=t=>new Ve({checks:[],coerce:(t==null?void 0:t.coerce)||!1,typeName:w.ZodDate,...E(t)});class Lt extends T{_parse(e){if(this._getType(e)!==m.symbol){const s=this._getOrReturnCtx(e);return g(s,{code:h.invalid_type,expected:m.symbol,received:s.parsedType}),x}return Q(e.data)}}Lt.create=t=>new Lt({typeName:w.ZodSymbol,...E(t)});class It extends T{_parse(e){if(this._getType(e)!==m.undefined){const s=this._getOrReturnCtx(e);return g(s,{code:h.invalid_type,expected:m.undefined,received:s.parsedType}),x}return Q(e.data)}}It.create=t=>new It({typeName:w.ZodUndefined,...E(t)});class Dt extends T{_parse(e){if(this._getType(e)!==m.null){const s=this._getOrReturnCtx(e);return g(s,{code:h.invalid_type,expected:m.null,received:s.parsedType}),x}return Q(e.data)}}Dt.create=t=>new Dt({typeName:w.ZodNull,...E(t)});class Me extends T{constructor(){super(...arguments),this._any=!0}_parse(e){return Q(e.data)}}Me.create=t=>new Me({typeName:w.ZodAny,...E(t)});class Zt extends T{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Q(e.data)}}Zt.create=t=>new Zt({typeName:w.ZodUnknown,...E(t)});class de extends T{_parse(e){const n=this._getOrReturnCtx(e);return g(n,{code:h.invalid_type,expected:m.never,received:n.parsedType}),x}}de.create=t=>new de({typeName:w.ZodNever,...E(t)});class Gt extends T{_parse(e){if(this._getType(e)!==m.undefined){const s=this._getOrReturnCtx(e);return g(s,{code:h.invalid_type,expected:m.void,received:s.parsedType}),x}return Q(e.data)}}Gt.create=t=>new Gt({typeName:w.ZodVoid,...E(t)});class ne extends T{_parse(e){const{ctx:n,status:s}=this._processInputParams(e),r=this._def;if(n.parsedType!==m.array)return g(n,{code:h.invalid_type,expected:m.array,received:n.parsedType}),x;if(r.exactLength!==null){const o=n.data.length>r.exactLength.value,i=n.data.length<r.exactLength.value;(o||i)&&(g(n,{code:o?h.too_big:h.too_small,minimum:i?r.exactLength.value:void 0,maximum:o?r.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:r.exactLength.message}),s.dirty())}if(r.minLength!==null&&n.data.length<r.minLength.value&&(g(n,{code:h.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),s.dirty()),r.maxLength!==null&&n.data.length>r.maxLength.value&&(g(n,{code:h.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),s.dirty()),n.common.async)return Promise.all([...n.data].map((o,i)=>r.type._parseAsync(new re(n,o,n.path,i)))).then(o=>z.mergeArray(s,o));const a=[...n.data].map((o,i)=>r.type._parseSync(new re(n,o,n.path,i)));return z.mergeArray(s,a)}get element(){return this._def.type}min(e,n){return new ne({...this._def,minLength:{value:e,message:b.toString(n)}})}max(e,n){return new ne({...this._def,maxLength:{value:e,message:b.toString(n)}})}length(e,n){return new ne({...this._def,exactLength:{value:e,message:b.toString(n)}})}nonempty(e){return this.min(1,e)}}ne.create=(t,e)=>new ne({type:t,minLength:null,maxLength:null,exactLength:null,typeName:w.ZodArray,...E(e)});function ve(t){if(t instanceof I){const e={};for(const n in t.shape){const s=t.shape[n];e[n]=le.create(ve(s))}return new I({...t._def,shape:()=>e})}else return t instanceof ne?new ne({...t._def,type:ve(t.element)}):t instanceof le?le.create(ve(t.unwrap())):t instanceof Se?Se.create(ve(t.unwrap())):t instanceof pe?pe.create(t.items.map(e=>ve(e))):t}class I extends T{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(),n=O.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==m.object){const u=this._getOrReturnCtx(e);return g(u,{code:h.invalid_type,expected:m.object,received:u.parsedType}),x}const{status:s,ctx:r}=this._processInputParams(e),{shape:a,keys:o}=this._getCached(),i=[];if(!(this._def.catchall instanceof de&&this._def.unknownKeys==="strip"))for(const u in r.data)o.includes(u)||i.push(u);const c=[];for(const u of o){const v=a[u],M=r.data[u];c.push({key:{status:"valid",value:u},value:v._parse(new re(r,M,r.path,u)),alwaysSet:u in r.data})}if(this._def.catchall instanceof de){const u=this._def.unknownKeys;if(u==="passthrough")for(const v of i)c.push({key:{status:"valid",value:v},value:{status:"valid",value:r.data[v]}});else if(u==="strict")i.length>0&&(g(r,{code:h.unrecognized_keys,keys:i}),s.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const u=this._def.catchall;for(const v of i){const M=r.data[v];c.push({key:{status:"valid",value:v},value:u._parse(new re(r,M,r.path,v)),alwaysSet:v in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const u=[];for(const v of c){const M=await v.key,P=await v.value;u.push({key:M,value:P,alwaysSet:v.alwaysSet})}return u}).then(u=>z.mergeObjectSync(s,u)):z.mergeObjectSync(s,c)}get shape(){return this._def.shape()}strict(e){return b.errToObj,new I({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,s)=>{var a,o;const r=((o=(a=this._def).errorMap)==null?void 0:o.call(a,n,s).message)??s.defaultError;return n.code==="unrecognized_keys"?{message:b.errToObj(e).message??r}:{message:r}}}:{}})}strip(){return new I({...this._def,unknownKeys:"strip"})}passthrough(){return new I({...this._def,unknownKeys:"passthrough"})}extend(e){return new I({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new I({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:w.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new I({...this._def,catchall:e})}pick(e){const n={};for(const s of O.objectKeys(e))e[s]&&this.shape[s]&&(n[s]=this.shape[s]);return new I({...this._def,shape:()=>n})}omit(e){const n={};for(const s of O.objectKeys(this.shape))e[s]||(n[s]=this.shape[s]);return new I({...this._def,shape:()=>n})}deepPartial(){return ve(this)}partial(e){const n={};for(const s of O.objectKeys(this.shape)){const r=this.shape[s];e&&!e[s]?n[s]=r:n[s]=r.optional()}return new I({...this._def,shape:()=>n})}required(e){const n={};for(const s of O.objectKeys(this.shape))if(e&&!e[s])n[s]=this.shape[s];else{let a=this.shape[s];for(;a instanceof le;)a=a._def.innerType;n[s]=a}return new I({...this._def,shape:()=>n})}keyof(){return dn(O.objectKeys(this.shape))}}I.create=(t,e)=>new I({shape:()=>t,unknownKeys:"strip",catchall:de.create(),typeName:w.ZodObject,...E(e)});I.strictCreate=(t,e)=>new I({shape:()=>t,unknownKeys:"strict",catchall:de.create(),typeName:w.ZodObject,...E(e)});I.lazycreate=(t,e)=>new I({shape:t,unknownKeys:"strip",catchall:de.create(),typeName:w.ZodObject,...E(e)});class ze extends T{_parse(e){const{ctx:n}=this._processInputParams(e),s=this._def.options;function r(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 n.common.issues.push(...i.ctx.common.issues),i.result;const o=a.map(i=>new ce(i.ctx.common.issues));return g(n,{code:h.invalid_union,unionErrors:o}),x}if(n.common.async)return Promise.all(s.map(async a=>{const o={...n,common:{...n.common,issues:[]},parent:null};return{result:await a._parseAsync({data:n.data,path:n.path,parent:o}),ctx:o}})).then(r);{let a;const o=[];for(const c of s){const u={...n,common:{...n.common,issues:[]},parent:null},v=c._parseSync({data:n.data,path:n.path,parent:u});if(v.status==="valid")return v;v.status==="dirty"&&!a&&(a={result:v,ctx:u}),u.common.issues.length&&o.push(u.common.issues)}if(a)return n.common.issues.push(...a.ctx.common.issues),a.result;const i=o.map(c=>new ce(c));return g(n,{code:h.invalid_union,unionErrors:i}),x}}get options(){return this._def.options}}ze.create=(t,e)=>new ze({options:t,typeName:w.ZodUnion,...E(e)});function ut(t,e){const n=ue(t),s=ue(e);if(t===e)return{valid:!0,data:t};if(n===m.object&&s===m.object){const r=O.objectKeys(e),a=O.objectKeys(t).filter(i=>r.indexOf(i)!==-1),o={...t,...e};for(const i of a){const c=ut(t[i],e[i]);if(!c.valid)return{valid:!1};o[i]=c.data}return{valid:!0,data:o}}else if(n===m.array&&s===m.array){if(t.length!==e.length)return{valid:!1};const r=[];for(let a=0;a<t.length;a++){const o=t[a],i=e[a],c=ut(o,i);if(!c.valid)return{valid:!1};r.push(c.data)}return{valid:!0,data:r}}else return n===m.date&&s===m.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}class Fe extends T{_parse(e){const{status:n,ctx:s}=this._processInputParams(e),r=(a,o)=>{if(jt(a)||jt(o))return x;const i=ut(a.value,o.value);return i.valid?((Pt(a)||Pt(o))&&n.dirty(),{status:n.value,value:i.data}):(g(s,{code:h.invalid_intersection_types}),x)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([a,o])=>r(a,o)):r(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}}Fe.create=(t,e,n)=>new Fe({left:t,right:e,typeName:w.ZodIntersection,...E(n)});class pe extends T{_parse(e){const{status:n,ctx:s}=this._processInputParams(e);if(s.parsedType!==m.array)return g(s,{code:h.invalid_type,expected:m.array,received:s.parsedType}),x;if(s.data.length<this._def.items.length)return g(s,{code:h.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),x;!this._def.rest&&s.data.length>this._def.items.length&&(g(s,{code:h.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const a=[...s.data].map((o,i)=>{const c=this._def.items[i]||this._def.rest;return c?c._parse(new re(s,o,s.path,i)):null}).filter(o=>!!o);return s.common.async?Promise.all(a).then(o=>z.mergeArray(n,o)):z.mergeArray(n,a)}get items(){return this._def.items}rest(e){return new pe({...this._def,rest:e})}}pe.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new pe({items:t,typeName:w.ZodTuple,rest:null,...E(e)})};class Be extends T{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:s}=this._processInputParams(e);if(s.parsedType!==m.object)return g(s,{code:h.invalid_type,expected:m.object,received:s.parsedType}),x;const r=[],a=this._def.keyType,o=this._def.valueType;for(const i in s.data)r.push({key:a._parse(new re(s,i,s.path,i)),value:o._parse(new re(s,s.data[i],s.path,i)),alwaysSet:i in s.data});return s.common.async?z.mergeObjectAsync(n,r):z.mergeObjectSync(n,r)}get element(){return this._def.valueType}static create(e,n,s){return n instanceof T?new Be({keyType:e,valueType:n,typeName:w.ZodRecord,...E(s)}):new Be({keyType:ie.create(),valueType:e,typeName:w.ZodRecord,...E(n)})}}class Ut extends T{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:s}=this._processInputParams(e);if(s.parsedType!==m.map)return g(s,{code:h.invalid_type,expected:m.map,received:s.parsedType}),x;const r=this._def.keyType,a=this._def.valueType,o=[...s.data.entries()].map(([i,c],u)=>({key:r._parse(new re(s,i,s.path,[u,"key"])),value:a._parse(new re(s,c,s.path,[u,"value"]))}));if(s.common.async){const i=new Map;return Promise.resolve().then(async()=>{for(const c of o){const u=await c.key,v=await c.value;if(u.status==="aborted"||v.status==="aborted")return x;(u.status==="dirty"||v.status==="dirty")&&n.dirty(),i.set(u.value,v.value)}return{status:n.value,value:i}})}else{const i=new Map;for(const c of o){const u=c.key,v=c.value;if(u.status==="aborted"||v.status==="aborted")return x;(u.status==="dirty"||v.status==="dirty")&&n.dirty(),i.set(u.value,v.value)}return{status:n.value,value:i}}}}Ut.create=(t,e,n)=>new Ut({valueType:e,keyType:t,typeName:w.ZodMap,...E(n)});class je extends T{_parse(e){const{status:n,ctx:s}=this._processInputParams(e);if(s.parsedType!==m.set)return g(s,{code:h.invalid_type,expected:m.set,received:s.parsedType}),x;const r=this._def;r.minSize!==null&&s.data.size<r.minSize.value&&(g(s,{code:h.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),n.dirty()),r.maxSize!==null&&s.data.size>r.maxSize.value&&(g(s,{code:h.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),n.dirty());const a=this._def.valueType;function o(c){const u=new Set;for(const v of c){if(v.status==="aborted")return x;v.status==="dirty"&&n.dirty(),u.add(v.value)}return{status:n.value,value:u}}const i=[...s.data.values()].map((c,u)=>a._parse(new re(s,c,s.path,u)));return s.common.async?Promise.all(i).then(c=>o(c)):o(i)}min(e,n){return new je({...this._def,minSize:{value:e,message:b.toString(n)}})}max(e,n){return new je({...this._def,maxSize:{value:e,message:b.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}}je.create=(t,e)=>new je({valueType:t,minSize:null,maxSize:null,typeName:w.ZodSet,...E(e)});class Wt extends T{get schema(){return this._def.getter()}_parse(e){const{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}Wt.create=(t,e)=>new Wt({getter:t,typeName:w.ZodLazy,...E(e)});class lt extends T{_parse(e){if(e.data!==this._def.value){const n=this._getOrReturnCtx(e);return g(n,{received:n.data,code:h.invalid_literal,expected:this._def.value}),x}return{status:"valid",value:e.data}}get value(){return this._def.value}}lt.create=(t,e)=>new lt({value:t,typeName:w.ZodLiteral,...E(e)});function dn(t,e){return new we({values:t,typeName:w.ZodEnum,...E(e)})}class we extends T{_parse(e){if(typeof e.data!="string"){const n=this._getOrReturnCtx(e),s=this._def.values;return g(n,{expected:O.joinValues(s),received:n.parsedType,code:h.invalid_type}),x}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const n=this._getOrReturnCtx(e),s=this._def.values;return g(n,{received:n.data,code:h.invalid_enum_value,options:s}),x}return Q(e.data)}get options(){return this._def.values}get enum(){const e={};for(const n of this._def.values)e[n]=n;return e}get Values(){const e={};for(const n of this._def.values)e[n]=n;return e}get Enum(){const e={};for(const n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return we.create(e,{...this._def,...n})}exclude(e,n=this._def){return we.create(this.options.filter(s=>!e.includes(s)),{...this._def,...n})}}we.create=dn;class qt extends T{_parse(e){const n=O.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==m.string&&s.parsedType!==m.number){const r=O.objectValues(n);return g(s,{expected:O.joinValues(r),received:s.parsedType,code:h.invalid_type}),x}if(this._cache||(this._cache=new Set(O.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const r=O.objectValues(n);return g(s,{received:s.data,code:h.invalid_enum_value,options:r}),x}return Q(e.data)}get enum(){return this._def.values}}qt.create=(t,e)=>new qt({values:t,typeName:w.ZodNativeEnum,...E(e)});class He extends T{unwrap(){return this._def.type}_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==m.promise&&n.common.async===!1)return g(n,{code:h.invalid_type,expected:m.promise,received:n.parsedType}),x;const s=n.parsedType===m.promise?n.data:Promise.resolve(n.data);return Q(s.then(r=>this._def.type.parseAsync(r,{path:n.path,errorMap:n.common.contextualErrorMap})))}}He.create=(t,e)=>new He({type:t,typeName:w.ZodPromise,...E(e)});class xe extends T{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===w.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:n,ctx:s}=this._processInputParams(e),r=this._def.effect||null,a={addIssue:o=>{g(s,o),o.fatal?n.abort():n.dirty()},get path(){return s.path}};if(a.addIssue=a.addIssue.bind(a),r.type==="preprocess"){const o=r.transform(s.data,a);if(s.common.async)return Promise.resolve(o).then(async i=>{if(n.value==="aborted")return x;const c=await this._def.schema._parseAsync({data:i,path:s.path,parent:s});return c.status==="aborted"?x:c.status==="dirty"||n.value==="dirty"?Te(c.value):c});{if(n.value==="aborted")return x;const i=this._def.schema._parseSync({data:o,path:s.path,parent:s});return i.status==="aborted"?x:i.status==="dirty"||n.value==="dirty"?Te(i.value):i}}if(r.type==="refinement"){const o=i=>{const c=r.refinement(i,a);if(s.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return i};if(s.common.async===!1){const i=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return i.status==="aborted"?x:(i.status==="dirty"&&n.dirty(),o(i.value),{status:n.value,value:i.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(i=>i.status==="aborted"?x:(i.status==="dirty"&&n.dirty(),o(i.value).then(()=>({status:n.value,value:i.value}))))}if(r.type==="transform")if(s.common.async===!1){const o=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!_e(o))return x;const i=r.transform(o.value,a);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:i}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(o=>_e(o)?Promise.resolve(r.transform(o.value,a)).then(i=>({status:n.value,value:i})):x);O.assertNever(r)}}xe.create=(t,e,n)=>new xe({schema:t,typeName:w.ZodEffects,effect:e,...E(n)});xe.createWithPreprocess=(t,e,n)=>new xe({schema:e,effect:{type:"preprocess",transform:t},typeName:w.ZodEffects,...E(n)});class le extends T{_parse(e){return this._getType(e)===m.undefined?Q(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}le.create=(t,e)=>new le({innerType:t,typeName:w.ZodOptional,...E(e)});class Se extends T{_parse(e){return this._getType(e)===m.null?Q(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Se.create=(t,e)=>new Se({innerType:t,typeName:w.ZodNullable,...E(e)});class dt extends T{_parse(e){const{ctx:n}=this._processInputParams(e);let s=n.data;return n.parsedType===m.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}dt.create=(t,e)=>new dt({innerType:t,typeName:w.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...E(e)});class ft extends T{_parse(e){const{ctx:n}=this._processInputParams(e),s={...n,common:{...n.common,issues:[]}},r=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return qe(r)?r.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new ce(s.common.issues)},input:s.data})})):{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new ce(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}}ft.create=(t,e)=>new ft({innerType:t,typeName:w.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...E(e)});class Vt extends T{_parse(e){if(this._getType(e)!==m.nan){const s=this._getOrReturnCtx(e);return g(s,{code:h.invalid_type,expected:m.nan,received:s.parsedType}),x}return{status:"valid",value:e.data}}}Vt.create=t=>new Vt({typeName:w.ZodNaN,...E(t)});class Ps extends T{_parse(e){const{ctx:n}=this._processInputParams(e),s=n.data;return this._def.type._parse({data:s,path:n.path,parent:n})}unwrap(){return this._def.type}}class _t extends T{_parse(e){const{status:n,ctx:s}=this._processInputParams(e);if(s.common.async)return(async()=>{const a=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return a.status==="aborted"?x:a.status==="dirty"?(n.dirty(),Te(a.value)):this._def.out._parseAsync({data:a.value,path:s.path,parent:s})})();{const r=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return r.status==="aborted"?x:r.status==="dirty"?(n.dirty(),{status:"dirty",value:r.value}):this._def.out._parseSync({data:r.value,path:s.path,parent:s})}}static create(e,n){return new _t({in:e,out:n,typeName:w.ZodPipeline})}}class ht extends T{_parse(e){const n=this._def.innerType._parse(e),s=r=>(_e(r)&&(r.value=Object.freeze(r.value)),r);return qe(n)?n.then(r=>s(r)):s(n)}unwrap(){return this._def.innerType}}ht.create=(t,e)=>new ht({innerType:t,typeName:w.ZodReadonly,...E(e)});function zt(t,e){const n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function $s(t,e={},n){return t?Me.create().superRefine((s,r)=>{const a=t(s);if(a instanceof Promise)return a.then(o=>{if(!o){const i=zt(e,s),c=i.fatal??n??!0;r.addIssue({code:"custom",...i,fatal:c})}});if(!a){const o=zt(e,s),i=o.fatal??n??!0;r.addIssue({code:"custom",...o,fatal:i})}}):Me.create()}var w;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(w||(w={}));const Ls=(t,e={message:`Input not instance of ${t.name}`})=>$s(n=>n instanceof t,e),D=ie.create,J=ke.create,pt=ct.create;Me.create;de.create;const U=ne.create,L=I.create,fn=ze.create;Fe.create;pe.create;const hn=Be.create,Is=lt.create,Le=we.create;He.create;le.create;Se.create;const Ds={network:{failures:"network.failure",latencies:"network.latency",aborts:"network.abort",corruptions:"network.corruption",cors:"network.cors"},ui:{assaults:"ui.assault"},websocket:{drops:"websocket.drop",delays:"websocket.delay",corruptions:"websocket.corrupt",closes:"websocket.close"},sse:{drops:"sse.drop",delays:"sse.delay",corruptions:"sse.corrupt",closes:"sse.close"}};function Zs(t){if(t.length===0)return"top-level";const e=t[0];if(e==="groups")return"group";if(e==="presets"||e==="customPresets")return"preset";if(typeof e=="string"){const n=Ds[e];if(n&&typeof t[1]=="string"){const s=n[t[1]];if(s)return s}}return"top-level"}function Gs(t){let e="";for(const n of t)typeof n=="number"?e+=`[${n}]`:e+=e.length===0?n:`.${n}`;return e}function Ft(t,e=80){return t.length<=e?t:`${t.slice(0,e-1)}…`}function Us(t){try{return t===void 0?"undefined":JSON.stringify(t)??String(t)}catch{return"<unserializable>"}}function Ws(t){switch(t.code){case h.unrecognized_keys:return"unknown_field";case h.invalid_type:return t.received==="undefined"?"missing_field":"invalid_type";case h.too_small:return"value_too_small";case h.too_big:return"value_too_large";case h.invalid_enum_value:return"invalid_enum";case h.invalid_string:return"invalid_string";case h.invalid_union:case h.invalid_union_discriminator:return"invalid_type";case h.custom:{const e=t.message.toLowerCase();return e.includes("mutually exclusive")||e.includes("only one of")?"mutually_exclusive":e.includes("duplicate")?"duplicate":e.includes("regexp")||e.includes("flag")?"invalid_regex":"custom"}default:return"custom"}}function qs(t){switch(t.code){case h.invalid_type:return t.expected;case h.too_small:return t.type==="number"?`>= ${t.minimum}`:t.type==="string"?`length >= ${t.minimum}`:t.type==="array"?`length >= ${t.minimum}`:`>= ${t.minimum}`;case h.too_big:return t.type==="number"?`<= ${t.maximum}`:t.type==="string"?`length <= ${t.maximum}`:t.type==="array"?`length <= ${t.maximum}`:`<= ${t.maximum}`;case h.invalid_enum_value:return t.options.map(e=>JSON.stringify(e)).join("|");case h.unrecognized_keys:return"no extra keys";default:return}}function Vs(t){if(t.code===h.invalid_type)return t.received;if(t.code===h.invalid_enum_value)return Ft(Us(t.received));if(t.code===h.unrecognized_keys)return Ft(t.keys.map(e=>JSON.stringify(e)).join(", "))}function pn(t){return{path:Gs(t.path),code:Ws(t),ruleType:Zs(t.path),message:t.message,expected:qs(t),received:Vs(t)}}function zs(t){return[...t].sort((e,n)=>e.path<n.path?-1:e.path>n.path?1:e.code<n.code?-1:e.code>n.code?1:0)}function Fs(t,e={}){const n=e.maxIssues??50,s=t.slice(0,n),r=Math.max(0,t.length-n),a=s.map(o=>{let i=`[${o.ruleType}] ${o.path||"<root>"} (${o.code}): ${o.message}`;return o.expected!==void 0&&(i+=`, expected ${o.expected}`),o.received!==void 0&&(i+=`, received ${o.received}`),i});return r>0&&a.push(`... and ${r} more`),`Invalid ChaosConfig:
2
+ ${a.map(o=>` - ${o}`).join(`
3
+ `)}`}class he extends Error{constructor(n){const s=Bs(n)?n.map(a=>({path:"",code:"legacy",ruleType:"top-level",message:a})):n,r=zs(s);super(Fs(r,{maxIssues:50}));R(this,"issues");this.name="ChaosConfigError",this.issues=r}get messages(){return this.issues.map(n=>`${n.path||"<root>"}: ${n.message}`)}}function Bs(t){return t.length>0&&typeof t[0]=="string"}const Pe="default";class gn{constructor(){R(this,"groups",new Map);R(this,"gatedEmitted",new Set)}ensure(e,n){const s=this.groups.get(e);if(s)return n!=null&&n.explicit&&(s.explicit=!0),(n==null?void 0:n.enabled)!==void 0&&(s.enabled=n.enabled),s;const r={name:e,enabled:(n==null?void 0:n.enabled)??!0,explicit:(n==null?void 0:n.explicit)??!1};return this.groups.set(e,r),r}setEnabled(e,n){this.ensure(e).enabled=n,this.gatedEmitted.clear()}isActive(e){return this.ensure(e??Pe).enabled}shouldEmitGated(e){return this.gatedEmitted.has(e)?!1:(this.gatedEmitted.add(e),!0)}has(e){return this.groups.has(e)}remove(e,n,s){if(e===Pe)return!1;if(!(s!=null&&s.force)&&n.has(e))throw new Error(`[chaos-maker] Cannot remove group '${e}': still referenced by one or more rules. Pass { force: true } to override.`);const r=this.groups.delete(e);return r&&this.gatedEmitted.delete(e),r}list(){return[...this.groups.values()].map(e=>({...e}))}getSnapshot(){const e={};for(const n of this.groups.values())e[n.name]=n.enabled;return e}}function $e(t){if(t===null||typeof t!="object")return t;if(t instanceof RegExp)return new RegExp(t.source,t.flags);if(Array.isArray(t))return t.map(n=>$e(n));const e={};for(const[n,s]of Object.entries(t))e[n]=$e(s);return e}function q(t,e){return e()<t}function ee(t,e){const n=(e.get(t)??0)+1;return e.set(t,n),n}function te(t,e){return t.onNth!==void 0?e===t.onNth:t.everyNth!==void 0?e%t.everyNth===0:t.afterN!==void 0?e>t.afterN:!0}function ge(t,e){return e==="*"?!0:t.includes(e)}function kt(t,e){switch(e){case"truncate":return t.slice(0,Math.max(0,Math.floor(t.length/2)));case"malformed-json":return`${t}"}`;case"empty":return"";case"wrong-type":return"<html><body>Unexpected HTML</body></html>"}}function V(t,e,n,s){if(!e||e.isActive(t.group))return!0;const r=t.group??Pe;return e.shouldEmitGated(r)&&n&&n.emit({type:"rule-group:gated",timestamp:Date.now(),applied:!1,detail:{...s,groupName:r}}),n==null||n.debug("rule-skip-group",{...s,groupName:r},t),!1}function Bt(t,e){var s,r,a,o,i,c,u,v,M,P,F,X,W,p;const n=l=>{if(l)for(const f of l)e(f)};n((s=t.network)==null?void 0:s.failures),n((r=t.network)==null?void 0:r.latencies),n((a=t.network)==null?void 0:a.aborts),n((o=t.network)==null?void 0:o.corruptions),n((i=t.network)==null?void 0:i.cors),n((c=t.ui)==null?void 0:c.assaults),n((u=t.websocket)==null?void 0:u.drops),n((v=t.websocket)==null?void 0:v.delays),n((M=t.websocket)==null?void 0:M.corruptions),n((P=t.websocket)==null?void 0:P.closes),n((F=t.sse)==null?void 0:F.drops),n((X=t.sse)==null?void 0:X.delays),n((W=t.sse)==null?void 0:W.corruptions),n((p=t.sse)==null?void 0:p.closes)}const se="*",Ye={network:{latencies:[{urlPattern:se,delayMs:2e3,probability:1}]}},Ke={network:{aborts:[{urlPattern:se,probability:.05}],latencies:[{urlPattern:se,delayMs:3e3,probability:.1}]}},Xe={network:{cors:[{urlPattern:se,probability:1}]}},Qe={network:{failures:[{urlPattern:"/api/",statusCode:500,probability:.1}],latencies:[{urlPattern:"/api/",delayMs:1e3,probability:.2}]}},wt={ui:{assaults:[{selector:"button",action:"disable",probability:.2},{selector:"a",action:"hide",probability:.1}]}},xt={websocket:{drops:[{urlPattern:se,direction:"both",probability:.1}],delays:[{urlPattern:se,direction:"inbound",delayMs:500,probability:1}],corruptions:[{urlPattern:se,direction:"inbound",strategy:"truncate",probability:.05}]}},St={sse:{drops:[{urlPattern:se,probability:.05}],delays:[{urlPattern:se,delayMs:200,probability:1}],closes:[{urlPattern:se,probability:.02,afterMs:2e3}]}};function yn(t){if(t&&typeof t=="object"&&!Object.isFrozen(t)){Object.freeze(t);for(const e of Object.values(t))yn(e)}return t}[Ye,Ke,Xe,Qe,wt,xt,St].forEach(yn);const mn=Object.freeze([{name:"unstableApi",config:Qe},{name:"slowNetwork",config:Ye},{name:"offlineMode",config:Xe},{name:"flakyConnection",config:Ke},{name:"degradedUi",config:wt},{name:"unreliableWebSocket",config:xt},{name:"unreliableEventStream",config:St},{name:"slow-api",config:Ye},{name:"flaky-api",config:Ke},{name:"offline-mode",config:Xe},{name:"high-latency",config:Qe}].map(t=>Object.freeze(t)));function rt(t){const e=t.trim();if(!e)throw new Error("[chaos-maker] preset name cannot be empty");return e}class bn{constructor(e=mn){R(this,"map",new Map);for(const n of e)this.register(n)}register(e){const n=rt(e.name);if(this.map.has(n))throw new Error(`[chaos-maker] preset '${n}' already registered`);this.map.set(n,e.config)}registerAll(e){if(e)for(const[n,s]of Object.entries(e))this.register({name:n,config:s})}has(e){return this.map.has(rt(e))}get(e){const n=rt(e),s=this.map.get(n);if(!s)throw new Error(`[chaos-maker] preset '${n}' is not registered. Known: ${this.list().join(", ")}`);return s}list(){return[...this.map.keys()]}}function Ht(t,e){var n,s,r;for(const a of["network","ui","websocket","sse"]){const o=e[a];if(!o)continue;const i=t[a]??(t[a]={});for(const[c,u]of Object.entries(o)){if(!Array.isArray(u)){let v;try{const M=u===null?"null":((n=u==null?void 0:u.constructor)==null?void 0:n.name)??typeof u,P=((s=JSON.stringify(u))==null?void 0:s.slice(0,80))??"<unserializable>";v=`${M} ${P}`}catch{v=`${typeof u} <unserializable>`}throw new Error(`[chaos-maker] internal: preset slice category '${a}.${c}' must be an array (got ${v}). Update appendSlice when adding non-array category fields.`)}(i[c]??(i[c]=[])).push(...u)}}(r=e.groups)!=null&&r.length&&(t.groups??(t.groups=[])).push(...e.groups)}function vn(t,e){const n=new Set,s=new Set,r=[];for(const i of t.presets??[]){const c=i.trim();if(!c||n.has(c))continue;n.add(c);const u=e.get(c);s.has(u)||(s.add(u),r.push(u))}const a={};for(const i of r)Ht(a,$e(i));const o=$e(t);return delete o.presets,delete o.customPresets,o.seed!==void 0&&(a.seed=o.seed),o.debug!==void 0&&(a.debug=o.debug),Ht(a,o),a}const Hs=Object.freeze({unstableApi:Qe,slowNetwork:Ye,offlineMode:Xe,flakyConnection:Ke,degradedUi:wt,unreliableWebSocket:xt,unreliableEventStream:St}),Yt=new Map;function Ys(t,e){if(Yt.size===0)return;const n=t;for(const[s,r]of Yt){if(n[s]===void 0)continue;const a={path:s,code:"deprecated",ruleType:"top-level",message:r.message};e&&e(a);try{console.warn(`[chaos-maker] deprecated: ${s} — ${r.message}`)}catch{}}}const Ie=["urlPattern","methods","graphqlOperation","probability","onNth","everyNth","afterN","group"],Ks=new Set([...Ie,"statusCode","body","statusText","headers"]),Xs=new Set([...Ie,"delayMs"]),Qs=new Set([...Ie,"timeout"]),Js=new Set([...Ie,"strategy"]),er=new Set(Ie),tr=new Set(["selector","action","probability","group"]),nr=new Set(["urlPattern","direction","probability","onNth","everyNth","afterN","group"]),sr=new Set(["urlPattern","direction","delayMs","probability","onNth","everyNth","afterN","group"]),rr=new Set(["urlPattern","direction","strategy","probability","onNth","everyNth","afterN","group"]),ar=new Set(["urlPattern","code","reason","afterMs","probability","onNth","everyNth","afterN","group"]),or=new Set(["urlPattern","eventType","probability","onNth","everyNth","afterN","group"]),ir=new Set(["urlPattern","eventType","delayMs","probability","onNth","everyNth","afterN","group"]),cr=new Set(["urlPattern","eventType","strategy","probability","onNth","everyNth","afterN","group"]),ur=new Set(["urlPattern","afterMs","probability","onNth","everyNth","afterN","group"]),_n=new Set(["name","enabled"]),kn={failures:Ks,latencies:Xs,aborts:Qs,corruptions:Js,cors:er},wn={assaults:tr},xn={drops:nr,delays:sr,corruptions:rr,closes:ar},Sn={drops:or,delays:ir,corruptions:cr,closes:ur},Cn=new Set(["network","ui","websocket","sse","groups","presets","customPresets","seed","debug","schemaVersion"]),tt={network:new Set(Object.keys(kn)),ui:new Set(Object.keys(wn)),websocket:new Set(Object.keys(xn)),sse:new Set(Object.keys(Sn))},fe={network:kn,ui:wn,websocket:xn,sse:Sn};function En(t,e){const n={};if(!t||typeof t!="object")return n;const s=t;for(const r of Object.keys(s))e.has(r)&&(n[r]=s[r]);return n}function lr(t,e){return Array.isArray(t)?t.map(n=>En(n,e)):[]}function Nn(t,e,n){const s={};if(!t||typeof t!="object")return s;const r=t;for(const a of Object.keys(r)){if(!n.has(a))continue;const o=e[a];o&&(s[a]=lr(r[a],o))}return s}function Tn(t){return Array.isArray(t)?t.map(e=>En(e,_n)):[]}function dr(t){const e={};if(!t||typeof t!="object")return e;const n=t;for(const s of Object.keys(fe))n[s]!==void 0&&(e[s]=Nn(n[s],fe[s],tt[s]));return n.groups!==void 0&&(e.groups=Tn(n.groups)),e}function fr(t){const e={};if(!t||typeof t!="object")return e;const n=t;for(const s of Object.keys(n))if(Cn.has(s))if(s in fe)e[s]=Nn(n[s],fe[s],tt[s]);else if(s==="groups")e[s]=Tn(n[s]);else if(s==="customPresets"){const r=n[s];if(r&&typeof r=="object"){const a={};for(const[o,i]of Object.entries(r))a[o]=dr(i);e[s]=a}}else e[s]=n[s];return e}function hr(t){const e=[];return pr(t,"",e),e.sort()}function pr(t,e,n){if(!(!t||typeof t!="object")){const s=t;for(const r of Object.keys(s)){if(!Cn.has(r)){n.push(r);continue}r in fe?On(s[r],r,fe[r],tt[r],n):r==="groups"?Rn(s[r],"groups",n):r==="customPresets"&&gr(s[r],n)}}}function On(t,e,n,s,r){if(!t||typeof t!="object")return;const a=t;for(const o of Object.keys(a)){const i=`${e}.${o}`;if(!s.has(o)){r.push(i);continue}const c=n[o];c&&Array.isArray(a[o])&&a[o].forEach((u,v)=>{if(!u||typeof u!="object")return;const M=u;for(const P of Object.keys(M))c.has(P)||r.push(`${i}[${v}].${P}`)})}}function Rn(t,e,n){Array.isArray(t)&&t.forEach((s,r)=>{if(!s||typeof s!="object")return;const a=s;for(const o of Object.keys(a))_n.has(o)||n.push(`${e}[${r}].${o}`)})}function gr(t,e){if(!(!t||typeof t!="object"))for(const[n,s]of Object.entries(t)){if(!s||typeof s!="object")continue;const r=s;for(const a of Object.keys(r)){if(a==="groups"){Rn(r[a],`customPresets.${n}.groups`,e);continue}if(!(a in fe)){e.push(`customPresets.${n}.${a}`);continue}On(r[a],`customPresets.${n}.${a}`,fe[a],tt[a],e)}}}function $(t,e){return e==="strict"?t.strict():t.passthrough()}const B=J().min(0,"Probability must be >= 0").max(1,"Probability must be <= 1"),Kt=J().int().min(1),Y={onNth:Kt.optional(),everyNth:Kt.optional(),afterN:J().int().min(0).optional()},H={group:D().trim().min(1,"group must not be empty").optional()},yr=t=>[t.onNth,t.everyNth,t.afterN].filter(e=>e!==void 0).length<=1,K=[yr,{message:"Only one of onNth, everyNth, or afterN may be set on a single rule"}],mr=fn([D().min(1,"graphqlOperation must not be empty"),Ls(RegExp).refine(t=>!t.global&&!t.sticky,{message:"graphqlOperation RegExp must not use global (g) or sticky (y) flags due to lastIndex mutation"})]),De={urlPattern:D().min(1,"urlPattern must not be empty"),methods:U(D()).optional(),graphqlOperation:mr.optional()},An=t=>$(L({...De,statusCode:J().int().min(100).max(599),probability:B,body:D().optional(),statusText:D().optional(),headers:hn(D()).optional(),...Y,...H}),t).refine(...K),Mn=t=>$(L({...De,delayMs:J().min(0,"delayMs must be >= 0"),probability:B,...Y,...H}),t).refine(...K),jn=t=>$(L({...De,probability:B,timeout:J().min(0,"timeout must be >= 0").optional(),...Y,...H}),t).refine(...K),Pn=t=>$(L({...De,probability:B,strategy:Le(["truncate","malformed-json","empty","wrong-type"]),...Y,...H}),t).refine(...K),$n=t=>$(L({...De,probability:B,...Y,...H}),t).refine(...K),br=t=>$(L({failures:U(An(t)).optional(),latencies:U(Mn(t)).optional(),aborts:U(jn(t)).optional(),corruptions:U(Pn(t)).optional(),cors:U($n(t)).optional()}),t),Ln=t=>$(L({selector:D().min(1,"selector must not be empty"),action:Le(["disable","hide","remove"]),probability:B,...H}),t),vr=t=>$(L({assaults:U(Ln(t)).optional()}),t),Ct=Le(["inbound","outbound","both"]),In=t=>$(L({urlPattern:D().min(1,"urlPattern must not be empty"),direction:Ct,probability:B,...Y,...H}),t).refine(...K),Dn=t=>$(L({urlPattern:D().min(1,"urlPattern must not be empty"),direction:Ct,delayMs:J().min(0,"delayMs must be >= 0"),probability:B,...Y,...H}),t).refine(...K),Zn=t=>$(L({urlPattern:D().min(1,"urlPattern must not be empty"),direction:Ct,strategy:Le(["truncate","malformed-json","empty","wrong-type"]),probability:B,...Y,...H}),t).refine(...K),_r=J().int().refine(t=>t===1e3||t>=3e3&&t<=4999,{message:"code must be 1000 or in the range 3000-4999"}),kr=D().refine(t=>new TextEncoder().encode(t).length<=123,{message:"reason must be <= 123 UTF-8 bytes"}),Gn=t=>$(L({urlPattern:D().min(1,"urlPattern must not be empty"),code:_r.optional(),reason:kr.optional(),afterMs:J().min(0,"afterMs must be >= 0").optional(),probability:B,...Y,...H}),t).refine(...K),wr=t=>$(L({drops:U(In(t)).optional(),delays:U(Dn(t)).optional(),corruptions:U(Zn(t)).optional(),closes:U(Gn(t)).optional()}),t),Et=D().min(1,"eventType must not be empty"),Un=t=>$(L({urlPattern:D().min(1,"urlPattern must not be empty"),eventType:Et.optional(),probability:B,...Y,...H}),t).refine(...K),Wn=t=>$(L({urlPattern:D().min(1,"urlPattern must not be empty"),eventType:Et.optional(),delayMs:J().min(0,"delayMs must be >= 0"),probability:B,...Y,...H}),t).refine(...K),qn=t=>$(L({urlPattern:D().min(1,"urlPattern must not be empty"),eventType:Et.optional(),strategy:Le(["truncate","malformed-json","empty","wrong-type"]),probability:B,...Y,...H}),t).refine(...K),Vn=t=>$(L({urlPattern:D().min(1,"urlPattern must not be empty"),afterMs:J().min(0,"afterMs must be >= 0").optional(),probability:B,...Y,...H}),t).refine(...K),xr=t=>$(L({drops:U(Un(t)).optional(),delays:U(Wn(t)).optional(),corruptions:U(qn(t)).optional(),closes:U(Vn(t)).optional()}),t),zn=t=>$(L({name:D().trim().min(1,"group name must not be empty"),enabled:pt().optional()}),t),Sr=t=>U(zn(t)).superRefine((e,n)=>{const s=new Set;for(const[r,a]of e.entries()){const o=a.name.trim();if(s.has(o)){n.addIssue({code:h.custom,message:"duplicate group name after normalization",path:[r,"name"]});continue}s.add(o)}}),Cr=t=>fn([pt(),$(L({enabled:pt()}),t)]),gt=t=>$(L({network:br(t).optional(),ui:vr(t).optional(),websocket:wr(t).optional(),sse:xr(t).optional(),groups:Sr(t).optional()}),t),Fn=D().trim().min(1,"preset name must not be empty"),Er=U(Fn).transform(t=>{const e=new Set,n=[];for(const s of t){const r=s.trim();e.has(r)||(e.add(r),n.push(r))}return n}),Bn=t=>$(gt(t).extend({presets:Er.optional(),customPresets:hn(Fn,gt(t)).optional(),seed:J().int("Seed must be an integer").optional(),debug:Cr(t).optional(),schemaVersion:Is(1).optional()}),t),Nt=Bn("strict"),Hn=Bn("passthrough");gt("strict");An("strict"),Mn("strict"),jn("strict"),Pn("strict"),$n("strict"),Ln("strict"),In("strict"),Dn("strict"),Zn("strict"),Gn("strict"),Un("strict"),Wn("strict"),qn("strict"),Vn("strict"),zn("strict");const Nr={network:{failures:"network.failure",latencies:"network.latency",aborts:"network.abort",corruptions:"network.corruption",cors:"network.cors"},ui:{assaults:"ui.assault"},websocket:{drops:"websocket.drop",delays:"websocket.delay",corruptions:"websocket.corrupt",closes:"websocket.close"},sse:{drops:"sse.drop",delays:"sse.delay",corruptions:"sse.corrupt",closes:"sse.close"}},Yn=Symbol.for("chaos-maker.validated"),yt=1;function Tr(t,e){return!t||typeof t!="object"?!1:t[Yn]===e}function Or(t,e){return Object.defineProperty(t,Yn,{value:e,enumerable:!1,writable:!1,configurable:!1}),t}function Kn(t){const e=Nt.safeParse(t);if(!e.success)throw new he(e.error.issues.map(pn));return e.data}function Xn(t,e={}){const n=e.unknownFields??"reject",r=(n==="reject"?Nt:Hn).safeParse(t);if(!r.success)throw new he(r.error.issues.map(pn));let a=r.data;if(n==="warn"||n==="ignore"){if(n==="warn"){const i=hr(t);if(i.length>0)try{console.warn(`[chaos-maker] unknown config fields ignored: ${i.join(", ")}`)}catch{}}a=fr(a)}let o;try{const i=new bn;i.registerAll(a.customPresets),o=vn(a,i)}catch(i){if(i instanceof he)throw i;const c=i.message;let u="custom";throw c.includes("not registered")?u="unknown_preset":c.includes("already registered")&&(u="preset_collision"),new he([{path:"presets",code:u,ruleType:"preset",message:c}])}return Kn(o)}function Rr(t,e){const n=[],s=(r,a,o)=>{const i=e[r];if(!i)return;let c;try{c=i(a,{ruleType:r,path:o})}catch(u){n.push({path:o,code:"custom",ruleType:r,message:`customValidator threw: ${u.message}`});return}Array.isArray(c)&&n.push(...c)};for(const[r,a]of Object.entries(Nr)){const o=t[r];if(o)for(const[i,c]of Object.entries(a)){if(!c)continue;const u=o[i];Array.isArray(u)&&u.forEach((v,M)=>{s(c,v,`${r}.${i}[${M}]`)})}}return Array.isArray(t.groups)&&t.groups.forEach((r,a)=>{s("group",r,`groups[${a}]`)}),e["top-level"]&&s("top-level",t,""),n}function Tt(t,e={}){if(typeof t=="object"&&t!==null){const r=t.schemaVersion;if(r!==void 0&&r!==1)throw new he([{path:"schemaVersion",code:"unknown_schema_version",ruleType:"top-level",message:`unsupported schemaVersion: ${JSON.stringify(r)} (this build supports 1)`,expected:"1",received:JSON.stringify(r)}])}if(!e.unknownFields&&!e.onDeprecation&&!e.customValidators&&Tr(t,yt))return t;const s=Xn(t,{unknownFields:e.unknownFields});if(Ys(s,e.onDeprecation),e.customValidators){const r=Rr(s,e.customValidators);if(r.length>0)throw new he(r)}return Or(s,yt)}function Ar(t){let e=t|0;return()=>{e=e+1831565813|0;let n=Math.imul(e^e>>>15,1|e);return n=n+Math.imul(n^n>>>7,61|n)^n,((n^n>>>14)>>>0)/4294967296}}function Qn(){return Math.random()*4294967296>>>0}function Jn(t){const e=t??Qn();return{random:Ar(e),seed:e}}class es{constructor(e=2e3){R(this,"listeners",new Map);R(this,"log",[]);R(this,"logger");R(this,"ruleIds");this.maxLogEntries=e}on(e,n){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(n)}off(e,n){var s;(s=this.listeners.get(e))==null||s.delete(n)}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)}setLogger(e){this.logger=e}setRuleIds(e){this.ruleIds=e}debug(e,n,s){var i;if(!this.logger)return;const r=s?(i=this.ruleIds)==null?void 0:i.get(s):void 0,a=r?{...n,ruleType:r.ruleType,ruleId:r.ruleId}:n,o=this.logger.log(e,a);o&&this.emit(o)}getLog(){return[...this.log]}clearLog(){this.log=[]}notify(e,n){if(e)for(const s of e)try{s(n)}catch{}}}function Ot(t){const e=t.replace(/#[^\r\n]*/g," "),n=/\b(?:query|mutation|subscription)\s+([A-Za-z_][A-Za-z0-9_]*)/.exec(e);return(n==null?void 0:n[1])??null}function Mr(t){try{return JSON.parse(t)}catch{return}}function ts(t){if(!t||typeof t!="object")return{isGraphQL:!1,operationName:null};if(Array.isArray(t))return t.length===0?{isGraphQL:!1,operationName:null}:ts(t[0]);const e=t,n=typeof e.query=="string",s=typeof e.operationName=="string";return!n&&!s?{isGraphQL:!1,operationName:null}:s&&e.operationName.length>0?{isGraphQL:!0,operationName:e.operationName}:n?{isGraphQL:!0,operationName:Ot(e.query)}:{isGraphQL:!0,operationName:null}}function jr(t){let e;try{e=new URL(t,"http://_chaos-maker.invalid")}catch{return{kind:"not-graphql"}}const n=e.searchParams.get("operationName"),s=e.searchParams.get("query");return n&&n.length>0?{kind:"extracted",operationName:n}:s&&s.length>0?{kind:"extracted",operationName:Ot(s)}:{kind:"not-graphql"}}function Rt(t,e,n,s){const r=t.toUpperCase();if(r==="POST"){if(n!==null){const a=Mr(n);if(a===void 0)return{kind:"not-graphql"};const{isGraphQL:o,operationName:i}=ts(a);return o?{kind:"extracted",operationName:i}:{kind:"not-graphql"}}return s?{kind:"unparseable"}:{kind:"not-graphql"}}return r==="GET"?jr(e):{kind:"not-graphql"}}function ns(t,e){return e===null?!1:typeof t=="string"?t===e:((t.global||t.sticky)&&(t.lastIndex=0),t.test(e))}function At(t,e){return t?e.kind==="not-graphql"?{kind:"no-match"}:e.kind==="unparseable"?{kind:"unparseable"}:ns(t,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 nt(t){return typeof Request<"u"&&t instanceof Request}function Pr(t){return nt(t)?t.url:t.toString()}function $r(t,e){return e!=null&&e.method?e.method.toUpperCase():nt(t)?t.method.toUpperCase():"GET"}function Lr(t,e){if(e!=null&&e.signal)return e.signal;if(nt(t))return t.signal}function Ir(){if(typeof DOMException<"u")return new DOMException("The user aborted a request.","AbortError");const t=new Error("The user aborted a request.");return t.name="AbortError",t}function Dr(t,e){if(!e)return t;const n=new AbortController,s=i=>{o(),n.signal.aborted||n.abort(i.reason)},r=()=>s(t),a=()=>s(e),o=()=>{t.removeEventListener("abort",r),e.removeEventListener("abort",a)};return t.aborted?(s(t),n.signal):e.aborted?(s(e),n.signal):(t.addEventListener("abort",r,{once:!0}),e.addEventListener("abort",a,{once:!0}),n.signal)}function Zr(t,e){return e?{...t??{},signal:e}:t}async function Gr(t,e){const n=e==null?void 0:e.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(nt(t)){if(t.body===null)return{text:null,unparseable:!1};try{return{text:await t.clone().text(),unparseable:!1}}catch{return{text:null,unparseable:!0}}}return{text:null,unparseable:!1}}function Ce(t,e,n,s,r){t==null||t.emit({type:e,timestamp:Date.now(),applied:!1,detail:{url:n,method:s,...r,reason:"graphql-body-unparseable"}})}function Ee(t,e,n,s){if(!ge(e,t.urlPattern))return{proceed:!1,outcome:null};if(t.methods&&!t.methods.includes(n))return{proceed:!1,outcome:null};const r=At(t.graphqlOperation,s);return r.kind==="no-match"?{proceed:!1,outcome:r}:{proceed:!0,outcome:r}}function Oe(t){return t?t.kind==="match"||t.kind==="skip-no-constraint"?t.operationName?{operationName:t.operationName}:{}:{}:{}}function Xt(t,e,n,s,r,a){t==null||t.emit({type:"network:abort",timestamp:Date.now(),applied:r,detail:{url:n,method:s,timeoutMs:e.timeout,...Oe(a)}})}function Ge(t,e,n,s,r,a){t==null||t.emit({type:"network:corruption",timestamp:Date.now(),applied:r,detail:{url:n,method:s,strategy:e.strategy,...Oe(a)}})}function Ur(t){return t.graphqlOperation!==void 0}function Wr(t,e,n,s,r=new Map,a){return async(o,i)=>{var S,C,N,Z,j;const c=Pr(o),u=$r(o,i),v=Lr(o,i),M=(()=>{const d=[e.failures,e.latencies,e.aborts,e.corruptions,e.cors];for(const A of d)if(A!=null&&A.some(Ur))return!0;return!1})();let P={kind:"not-graphql"};if(M){const d=await Gr(o,i);P=Rt(u,c,d.text,d.unparseable)}if(e.cors)for(const d of e.cors){s==null||s.debug("rule-evaluating",{url:c,method:u},d);const A=Ee(d,c,u,P);if(!A.proceed){s==null||s.debug("rule-skip-match",{url:c,method:u},d);continue}s==null||s.debug("rule-matched",{url:c,method:u},d);const ae=ee(d,r);if(!te(d,ae)){s==null||s.debug("rule-skip-counting",{url:c,method:u},d);continue}if(!V(d,a,s,{url:c,method:u}))continue;const G=q(d.probability,n);if(((S=A.outcome)==null?void 0:S.kind)==="unparseable"){G&&Ce(s,"network:cors",c,u,{});continue}if(s==null||s.emit({type:"network:cors",timestamp:Date.now(),applied:G,detail:{url:c,method:u,...Oe(A.outcome)}}),!G){s==null||s.debug("rule-skip-probability",{url:c,method:u},d);continue}s==null||s.debug("rule-applied",{url:c,method:u},d);const oe=new TypeError("Failed to fetch");throw oe.stack="",oe}let F=null,X=null,W,p,l=!1;const f=d=>{!F||l||(l=!0,p&&(clearTimeout(p),p=void 0),Xt(s,F,c,u,d,X))};if(e.aborts)for(const d of e.aborts){s==null||s.debug("rule-evaluating",{url:c,method:u,timeoutMs:d.timeout},d);const A=Ee(d,c,u,P);if(!A.proceed){s==null||s.debug("rule-skip-match",{url:c,method:u,timeoutMs:d.timeout},d);continue}s==null||s.debug("rule-matched",{url:c,method:u,timeoutMs:d.timeout},d);const ae=ee(d,r);if(!te(d,ae)){s==null||s.debug("rule-skip-counting",{url:c,method:u,timeoutMs:d.timeout},d);continue}if(!V(d,a,s,{url:c,method:u,timeoutMs:d.timeout}))continue;const G=q(d.probability,n);if(((C=A.outcome)==null?void 0:C.kind)==="unparseable"){G&&Ce(s,"network:abort",c,u,{timeoutMs:d.timeout});continue}if(!G){s==null||s.debug("rule-skip-probability",{url:c,method:u,timeoutMs:d.timeout},d),Xt(s,d,c,u,!1,A.outcome);continue}s==null||s.debug("rule-applied",{url:c,method:u,timeoutMs:d.timeout},d),console.warn(`CHAOS: Aborting ${u} ${c} after ${d.timeout||0}ms`),F=d,X=A.outcome;const oe=new AbortController;W=Dr(oe.signal,v);const Ze=()=>{l||(f(!0),oe.abort(Ir()))};d.timeout?p=setTimeout(Ze,d.timeout):Ze();break}if(F)try{const d=await t(o,Zr(i,W));return f(!1),d}catch(d){throw f(!1),d}if(e.failures)for(const d of e.failures){s==null||s.debug("rule-evaluating",{url:c,method:u,statusCode:d.statusCode},d);const A=Ee(d,c,u,P);if(!A.proceed){s==null||s.debug("rule-skip-match",{url:c,method:u,statusCode:d.statusCode},d);continue}s==null||s.debug("rule-matched",{url:c,method:u,statusCode:d.statusCode},d);const ae=ee(d,r);if(!te(d,ae)){s==null||s.debug("rule-skip-counting",{url:c,method:u,statusCode:d.statusCode},d);continue}if(!V(d,a,s,{url:c,method:u,statusCode:d.statusCode}))continue;const G=q(d.probability,n);if(((N=A.outcome)==null?void 0:N.kind)==="unparseable"){G&&Ce(s,"network:failure",c,u,{statusCode:d.statusCode});continue}if(s==null||s.emit({type:"network:failure",timestamp:Date.now(),applied:G,detail:{url:c,method:u,statusCode:d.statusCode,...Oe(A.outcome)}}),!G){s==null||s.debug("rule-skip-probability",{url:c,method:u,statusCode:d.statusCode},d);continue}s==null||s.debug("rule-applied",{url:c,method:u,statusCode:d.statusCode},d),console.warn(`CHAOS: Forcing ${d.statusCode} for ${u} ${c}`);const oe=d.body??JSON.stringify({error:"Chaos Maker Attack!"}),Ze=d.headers??{};return new Response(oe,{status:d.statusCode,statusText:d.statusText??"Service Unavailable (Chaos)",headers:Ze})}if(e.latencies)for(const d of e.latencies){s==null||s.debug("rule-evaluating",{url:c,method:u,delayMs:d.delayMs},d);const A=Ee(d,c,u,P);if(!A.proceed){s==null||s.debug("rule-skip-match",{url:c,method:u,delayMs:d.delayMs},d);continue}s==null||s.debug("rule-matched",{url:c,method:u,delayMs:d.delayMs},d);const ae=ee(d,r);if(!te(d,ae)){s==null||s.debug("rule-skip-counting",{url:c,method:u,delayMs:d.delayMs},d);continue}if(!V(d,a,s,{url:c,method:u,delayMs:d.delayMs}))continue;const G=q(d.probability,n);if(((Z=A.outcome)==null?void 0:Z.kind)==="unparseable"){G&&Ce(s,"network:latency",c,u,{delayMs:d.delayMs});continue}if(s==null||s.emit({type:"network:latency",timestamp:Date.now(),applied:G,detail:{url:c,method:u,delayMs:d.delayMs,...Oe(A.outcome)}}),!G){s==null||s.debug("rule-skip-probability",{url:c,method:u,delayMs:d.delayMs},d);continue}s==null||s.debug("rule-applied",{url:c,method:u,delayMs:d.delayMs},d),console.warn(`CHAOS: Adding ${d.delayMs}ms latency to ${u} ${c}`),await new Promise(oe=>setTimeout(oe,d.delayMs))}let y=null,_=null;if(e.corruptions)for(const d of e.corruptions){s==null||s.debug("rule-evaluating",{url:c,method:u,strategy:d.strategy},d);const A=Ee(d,c,u,P);if(!A.proceed){s==null||s.debug("rule-skip-match",{url:c,method:u,strategy:d.strategy},d);continue}s==null||s.debug("rule-matched",{url:c,method:u,strategy:d.strategy},d);const ae=ee(d,r);if(!te(d,ae)){s==null||s.debug("rule-skip-counting",{url:c,method:u,strategy:d.strategy},d);continue}if(!V(d,a,s,{url:c,method:u,strategy:d.strategy}))continue;const G=q(d.probability,n);if(((j=A.outcome)==null?void 0:j.kind)==="unparseable"){G&&Ce(s,"network:corruption",c,u,{strategy:d.strategy});continue}if(!G){s==null||s.debug("rule-skip-probability",{url:c,method:u,strategy:d.strategy},d),Ge(s,d,c,u,!1,A.outcome);continue}s==null||s.debug("rule-applied",{url:c,method:u,strategy:d.strategy},d),y=d,_=A.outcome;break}let k;try{k=await t(o,i)}catch(d){throw y&&Ge(s,y,c,u,!1,_),d}if(!y)return k;try{console.warn(`CHAOS: Corrupting response for ${u} ${c} with strategy: ${y.strategy}`);const d=await k.text(),A=kt(d,y.strategy);return Ge(s,y,c,u,!0,_),new Response(A,{status:k.status,statusText:k.statusText,headers:k.headers})}catch(d){throw Ge(s,y,c,u,!1,_),d}}}function qr(t){return t==null?{text:null,unparseable:!1}:typeof t=="string"?{text:t,unparseable:!1}:typeof URLSearchParams<"u"&&t instanceof URLSearchParams?{text:t.toString(),unparseable:!1}:{text:null,unparseable:!0}}function Vr(t){return t.graphqlOperation!==void 0}function zr(t){const e=[t.failures,t.latencies,t.aborts,t.corruptions,t.cors];for(const n of e)if(n!=null&&n.some(Vr))return!0;return!1}function Ne(t,e,n,s,r){t==null||t.emit({type:e,timestamp:Date.now(),applied:!1,detail:{url:n,method:s,...r,reason:"graphql-body-unparseable"}})}function Ue(t,e,n,s,r){if(!ge(e,t.urlPattern))return{proceed:!1,outcome:null};if(t.methods&&!t.methods.includes(n))return{proceed:!1,outcome:null};const a=At(t.graphqlOperation,s);if(a.kind==="no-match"||a.kind==="unparseable")return{proceed:!1,outcome:a};const o=ee(t,r);return te(t,o)?{proceed:!0,outcome:a}:{proceed:!1,outcome:a}}function Re(t){return t?t.kind==="match"||t.kind==="skip-no-constraint"?t.operationName?{operationName:t.operationName}:{}:{}:{}}function Qt(t,e,n,s,r,a){t==null||t.emit({type:"network:abort",timestamp:Date.now(),applied:r,detail:{url:n,method:s,timeoutMs:e.timeout,...Re(a)}})}function Jt(t,e,n,s,r,a){t==null||t.emit({type:"network:corruption",timestamp:Date.now(),applied:r,detail:{url:n,method:s,strategy:e.strategy,...Re(a)}})}function Fr(t,e,n,s,r=new Map,a){const o=zr(e);return function(i){var F,X,W,p;const c=this._chaos_url,u=this._chaos_method;let v={kind:"not-graphql"};if(o){const l=qr(i);v=Rt(u,c,l.text,l.unparseable)}if(e.cors)for(const l of e.cors){if(s==null||s.debug("rule-evaluating",{url:c,method:u},l),!ge(c,l.urlPattern)){s==null||s.debug("rule-skip-match",{url:c,method:u},l);continue}if(l.methods&&!l.methods.includes(u)){s==null||s.debug("rule-skip-match",{url:c,method:u},l);continue}const f=At(l.graphqlOperation,v);if(f.kind==="no-match"){s==null||s.debug("rule-skip-match",{url:c,method:u},l);continue}if(f.kind==="unparseable"){Ne(s,"network:cors",c,u,{});continue}s==null||s.debug("rule-matched",{url:c,method:u},l);const y=ee(l,r);if(!te(l,y)){s==null||s.debug("rule-skip-counting",{url:c,method:u},l);continue}if(!V(l,a,s,{url:c,method:u}))continue;const _=q(l.probability,n);if(s==null||s.emit({type:"network:cors",timestamp:Date.now(),applied:_,detail:{url:c,method:u,...Re(f)}}),!_){s==null||s.debug("rule-skip-probability",{url:c,method:u},l);continue}s==null||s.debug("rule-applied",{url:c,method:u},l),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 l of e.aborts){s==null||s.debug("rule-evaluating",{url:c,method:u,timeoutMs:l.timeout},l);const f=Ue(l,c,u,v,r);if(!f.proceed){((F=f.outcome)==null?void 0:F.kind)==="unparseable"?Ne(s,"network:abort",c,u,{timeoutMs:l.timeout}):s==null||s.debug("rule-skip-match",{url:c,method:u,timeoutMs:l.timeout},l);continue}if(s==null||s.debug("rule-matched",{url:c,method:u,timeoutMs:l.timeout},l),!V(l,a,s,{url:c,method:u,timeoutMs:l.timeout}))continue;if(!q(l.probability,n)){s==null||s.debug("rule-skip-probability",{url:c,method:u,timeoutMs:l.timeout},l),Qt(s,l,c,u,!1,f.outcome);continue}s==null||s.debug("rule-applied",{url:c,method:u,timeoutMs:l.timeout},l),console.warn(`CHAOS: Aborting ${u} ${c} after ${l.timeout||0}ms`);let _=!1,k;const S=()=>{k&&(clearTimeout(k),k=void 0),typeof this.removeEventListener=="function"&&this.removeEventListener("loadend",N)},C=j=>{_||(_=!0,S(),Qt(s,l,c,u,j,f.outcome))},N=()=>{C(!1)},Z=()=>{_||(C(!0),this.abort())};typeof this.addEventListener=="function"&&this.addEventListener("loadend",N);try{t.call(this,i)}catch(j){throw C(!1),j}if(_)return;l.timeout?k=setTimeout(Z,l.timeout):Z();return}if(e.failures)for(const l of e.failures){s==null||s.debug("rule-evaluating",{url:c,method:u,statusCode:l.statusCode},l);const f=Ue(l,c,u,v,r);if(!f.proceed){((X=f.outcome)==null?void 0:X.kind)==="unparseable"?Ne(s,"network:failure",c,u,{statusCode:l.statusCode}):s==null||s.debug("rule-skip-match",{url:c,method:u,statusCode:l.statusCode},l);continue}if(s==null||s.debug("rule-matched",{url:c,method:u,statusCode:l.statusCode},l),!V(l,a,s,{url:c,method:u,statusCode:l.statusCode}))continue;const y=q(l.probability,n);if(s==null||s.emit({type:"network:failure",timestamp:Date.now(),applied:y,detail:{url:c,method:u,statusCode:l.statusCode,...Re(f.outcome)}}),!y){s==null||s.debug("rule-skip-probability",{url:c,method:u,statusCode:l.statusCode},l);continue}s==null||s.debug("rule-applied",{url:c,method:u,statusCode:l.statusCode},l),console.warn(`CHAOS: Forcing ${l.statusCode} for ${u} ${c}`),Object.defineProperty(this,"status",{value:l.statusCode}),Object.defineProperty(this,"statusText",{value:l.statusText??"Service Unavailable (Chaos)"});const _=l.body??JSON.stringify({error:"Chaos Maker Attack!"});Object.defineProperty(this,"responseText",{value:_,configurable:!0});const k=l.headers??{};Object.defineProperty(this,"getResponseHeader",{value:S=>{const C=Object.keys(k).find(N=>N.toLowerCase()===S.toLowerCase());return C?k[C]:null},configurable:!0}),Object.defineProperty(this,"getAllResponseHeaders",{value:()=>Object.entries(k).map(([S,C])=>`${S}: ${C}`).join(`\r
4
+ `),configurable:!0}),this.dispatchEvent(new Event("load")),this.dispatchEvent(new Event("loadend"));return}let M=null,P=null;if(e.corruptions)for(const l of e.corruptions){s==null||s.debug("rule-evaluating",{url:c,method:u,strategy:l.strategy},l);const f=Ue(l,c,u,v,r);if(!f.proceed){((W=f.outcome)==null?void 0:W.kind)==="unparseable"?Ne(s,"network:corruption",c,u,{strategy:l.strategy}):s==null||s.debug("rule-skip-match",{url:c,method:u,strategy:l.strategy},l);continue}if(s==null||s.debug("rule-matched",{url:c,method:u,strategy:l.strategy},l),!V(l,a,s,{url:c,method:u,strategy:l.strategy}))continue;if(!q(l.probability,n)){s==null||s.debug("rule-skip-probability",{url:c,method:u,strategy:l.strategy},l),Jt(s,l,c,u,!1,f.outcome);continue}s==null||s.debug("rule-applied",{url:c,method:u,strategy:l.strategy},l),M=l,P=f.outcome;break}if(M){let l=!1,f=null;const y=()=>{typeof this.removeEventListener=="function"&&(this.removeEventListener("error",S),this.removeEventListener("abort",S),this.removeEventListener("loadend",C))},_=N=>{l||(l=!0,Jt(s,M,c,u,N,P),y())},k=()=>{if(f!==null)return f;delete this.responseText;try{const N=this.responseText;return typeof N!="string"?(Object.defineProperty(this,"responseText",{value:N,configurable:!0}),_(!1),N):(f=kt(N,M.strategy),Object.defineProperty(this,"responseText",{value:f,configurable:!0}),_(!0),f)}catch(N){throw _(!1),N}},S=()=>{_(!1)},C=()=>{if(!l)try{k()}catch{}};typeof this.addEventListener=="function"&&(this.addEventListener("error",S),this.addEventListener("abort",S),this.addEventListener("loadend",C)),Object.defineProperty(this,"responseText",{get(){return k()},configurable:!0})}if(e.latencies)for(const l of e.latencies){s==null||s.debug("rule-evaluating",{url:c,method:u,delayMs:l.delayMs},l);const f=Ue(l,c,u,v,r);if(!f.proceed){((p=f.outcome)==null?void 0:p.kind)==="unparseable"?Ne(s,"network:latency",c,u,{delayMs:l.delayMs}):s==null||s.debug("rule-skip-match",{url:c,method:u,delayMs:l.delayMs},l);continue}if(s==null||s.debug("rule-matched",{url:c,method:u,delayMs:l.delayMs},l),!V(l,a,s,{url:c,method:u,delayMs:l.delayMs}))continue;const y=q(l.probability,n);if(s==null||s.emit({type:"network:latency",timestamp:Date.now(),applied:y,detail:{url:c,method:u,delayMs:l.delayMs,...Re(f.outcome)}}),!y){s==null||s.debug("rule-skip-probability",{url:c,method:u,delayMs:l.delayMs},l);continue}s==null||s.debug("rule-applied",{url:c,method:u,delayMs:l.delayMs},l),console.warn(`CHAOS: Adding ${l.delayMs}ms latency to ${u} ${c}`),setTimeout(()=>{t.call(this,i)},l.delayMs);return}t.call(this,i)}}function Br(t){return function(e,n){this._chaos_url=n.toString(),this._chaos_method=e.toUpperCase(),t.call(this,e,n)}}function mt(t,e,n,s,r){if(s==null||s.debug("rule-evaluating",{selector:e.selector,action:e.action},e),s==null||s.debug("rule-matched",{selector:e.selector,action:e.action},e),!V(e,r,s,{selector:e.selector,action:e.action}))return;const a=q(e.probability,n);if(s==null||s.emit({type:"ui:assault",timestamp:Date.now(),applied:a,detail:{selector:e.selector,action:e.action}}),!a){s==null||s.debug("rule-skip-probability",{selector:e.selector,action:e.action},e);return}s==null||s.debug("rule-applied",{selector:e.selector,action:e.action},e),console.warn(`CHAOS: Applying action '${e.action}' to element:`,t);try{switch(e.action){case"disable":"disabled"in t&&(t.disabled=!0);break;case"hide":t.style.display="none";break;case"remove":t.remove();break}}catch(o){console.error("Chaos Maker failed to assault element:",o,t)}}function Hr(t,e,n,s,r){if(t.nodeType!==Node.ELEMENT_NODE||!e.assaults)return;const a=t;for(const o of e.assaults)try{a.matches(o.selector)&&mt(a,o,n,s,r),a.querySelectorAll(o.selector).forEach(i=>{mt(i,o,n,s,r)})}catch(i){console.error(`Chaos Maker: Invalid selector '${o.selector}'`,i)}}function Yr(t,e,n,s){if(t.assaults){console.log("CHAOS: Running initial DOM scan for existing elements...");for(const a of t.assaults)try{document.querySelectorAll(a.selector).forEach(o=>{mt(o,a,e,n,s)})}catch(o){console.error(`Chaos Maker: Invalid selector in initial scan '${a.selector}'`,o)}}return new MutationObserver(a=>{for(const o of a)o.type==="childList"&&o.addedNodes.forEach(i=>Hr(i,t,e,n,s))})}const en=Symbol.for("chaos-maker.websocket.intercepted");function Kr(t,e){return t==="both"?!0:t===e}function tn(t){return typeof t=="string"?"text":"binary"}function nn(t,e){switch(e){case"truncate":return t.slice(0,Math.max(0,Math.floor(t.length/2)));case"malformed-json":return`${t}"}`;case"empty":return"";case"wrong-type":return"<html><body>Unexpected HTML</body></html>"}}function sn(t,e){if(e==="malformed-json"||e==="wrong-type")return null;if(e==="empty")return typeof Blob<"u"&&t instanceof Blob?new Blob([]):t instanceof ArrayBuffer?new ArrayBuffer(0):new Uint8Array(0);if(typeof Blob<"u"&&t instanceof Blob)return t.slice(0,Math.max(0,Math.floor(t.size/2)));if(t instanceof ArrayBuffer)return t.slice(0,Math.max(0,Math.floor(t.byteLength/2)));const n=t,s=Math.max(0,Math.floor(n.byteLength/2));return new Uint8Array(n.buffer.slice(n.byteOffset,n.byteOffset+s))}function ye(t,e,n,s,r,a,o){if(!t)return null;for(const i of t){if(o==null||o.debug("rule-evaluating",{url:e,direction:n},i),!ge(e,i.urlPattern)){o==null||o.debug("rule-skip-match",{url:e,direction:n},i);continue}if(!Kr(i.direction,n)){o==null||o.debug("rule-skip-match",{url:e,direction:n},i);continue}o==null||o.debug("rule-matched",{url:e,direction:n},i);const c=ee(i,r);if(!te(i,c)){o==null||o.debug("rule-skip-counting",{url:e,direction:n},i);continue}if(V(i,a,o,{url:e,direction:n})){if(!q(i.probability,s)){o==null||o.debug("rule-skip-probability",{url:e,direction:n},i);continue}return o==null||o.debug("rule-applied",{url:e,direction:n},i),i}}return null}function We(t,e,n,s,r){t.emit({type:"websocket:drop",timestamp:Date.now(),applied:!0,detail:{url:e,direction:n,payloadType:s,...r?{reason:r}:{}}})}function rn(t,e,n,s,r){t.emit({type:"websocket:delay",timestamp:Date.now(),applied:!0,detail:{url:e,direction:n,payloadType:s,delayMs:r}})}function me(t,e,n,s,r,a,o){t.emit({type:"websocket:corrupt",timestamp:Date.now(),applied:a,detail:{url:e,direction:n,payloadType:s,strategy:r,...o?{reason:o}:{}}})}function Xr(t,e,n,s){t.emit({type:"websocket:close",timestamp:Date.now(),applied:!0,detail:{url:e,closeCode:n,closeReason:s}})}function Qr(t,e,n,s,r,a){const o=new Map;let i=!0;const c=(p,l)=>{let f=o.get(p);f||(f=new Set,o.set(p,f)),f.add(l)},u=(p,l)=>{var f;(f=o.get(p))==null||f.delete(l)},v=(p,l)=>{const f=o.get(p);if(f){for(const y of f)clearTimeout(y.handle),y.kind==="delay"&&We(n,y.url,y.direction,y.payloadType,l);o.delete(p)}},M=(p,l,f)=>{const y=new MessageEvent("message",{data:f,origin:l.origin,lastEventId:l.lastEventId,source:l.source,ports:Array.from(l.ports??[])});y[en]=!0,p.dispatchEvent(y)},P=(p,l,f,y)=>{if(!i)return{handled:!1,data:f};const _="outbound",k=tn(f);if(ye(e.drops,l,_,s,r,a,n))return We(n,l,_,k),{handled:!0,data:f};let S=f;const C=ye(e.corruptions,l,_,s,r,a,n);if(C)if(k==="text")S=nn(S,C.strategy),me(n,l,_,k,C.strategy,!0);else{const Z=sn(S,C.strategy);Z===null?me(n,l,_,k,C.strategy,!1,"incompatible-payload-type"):(S=Z,me(n,l,_,k,C.strategy,!0))}const N=ye(e.delays,l,_,s,r,a,n);if(N){rn(n,l,_,k,N.delayMs);const Z={kind:"delay",handle:setTimeout(()=>{u(p,Z);try{y(S)}catch{}},N.delayMs),url:l,direction:_,payloadType:k};return c(p,Z),{handled:!0,data:S}}return{handled:!1,data:S}},F=(p,l)=>{p.addEventListener("message",f=>{const y=f;if(y[en]||!i)return;const _="inbound",k=tn(y.data);if(ye(e.drops,l,_,s,r,a,n)){y.stopImmediatePropagation(),We(n,l,_,k);return}let S=y.data,C=!1;const N=ye(e.corruptions,l,_,s,r,a,n);if(N)if(k==="text")S=nn(S,N.strategy),C=!0,me(n,l,_,k,N.strategy,!0);else{const j=sn(S,N.strategy);j===null?me(n,l,_,k,N.strategy,!1,"incompatible-payload-type"):(S=j,C=!0,me(n,l,_,k,N.strategy,!0))}const Z=ye(e.delays,l,_,s,r,a,n);if(Z){y.stopImmediatePropagation(),rn(n,l,_,k,Z.delayMs);const j={kind:"delay",handle:setTimeout(()=>{u(p,j),M(p,y,S)},Z.delayMs),url:l,direction:_,payloadType:k};c(p,j);return}C&&(y.stopImmediatePropagation(),M(p,y,S))})},X=(p,l)=>{if(e.closes)for(const f of e.closes){if(n.debug("rule-evaluating",{url:l},f),!ge(l,f.urlPattern)){n.debug("rule-skip-match",{url:l},f);continue}n.debug("rule-matched",{url:l},f);const y=ee(f,r);if(!te(f,y)){n.debug("rule-skip-counting",{url:l},f);continue}if(!V(f,a,n,{url:l}))continue;if(!q(f.probability,s)){n.debug("rule-skip-probability",{url:l},f);continue}n.debug("rule-applied",{url:l},f);const _=f.code??1e3,k=f.reason??"Chaos Maker close",S=f.afterMs??0,C=()=>{if(i){v(p,"close-interrupt"),Xr(n,l,_,k);try{p.close(_,k)}catch{try{p.close()}catch{}}}};if(S<=0)p.readyState===p.OPEN?C():p.addEventListener("open",C,{once:!0});else{const N=()=>{const Z={kind:"close",handle:setTimeout(C,S)};c(p,Z)};p.readyState===p.OPEN?N():p.addEventListener("open",N,{once:!0})}return}};function W(p,l){const f=new t(p,l),y=typeof p=="string"?p:p.toString(),_=f.send.bind(f);return f.send=function(S){const C=P(f,y,S,_);C.handled||_(C.data)},F(f,y),X(f,y),f}Object.defineProperty(W,"prototype",{value:t.prototype,writable:!1});for(const p of["CONNECTING","OPEN","CLOSING","CLOSED"])W[p]=t[p];return{Wrapped:W,uninstall(){i=!1;for(const[,p]of o)for(const l of p)clearTimeout(l.handle),l.kind==="delay"&&We(n,l.url,l.direction,l.payloadType,"stop-during-delay");o.clear()}}}const an=Symbol.for("chaos-maker.eventsource.intercepted");function Jr(t,e){return t===void 0||t==="*"?!0:t===e}function at(t,e,n,s,r,a,o){if(!t)return null;for(const i of t){if(o==null||o.debug("rule-evaluating",{url:e,eventType:n},i),!ge(e,i.urlPattern)){o==null||o.debug("rule-skip-match",{url:e,eventType:n},i);continue}if(!Jr(i.eventType,n)){o==null||o.debug("rule-skip-match",{url:e,eventType:n},i);continue}o==null||o.debug("rule-matched",{url:e,eventType:n},i);const c=ee(i,r);if(!te(i,c)){o==null||o.debug("rule-skip-counting",{url:e,eventType:n},i);continue}if(V(i,a,o,{url:e,eventType:n})){if(!q(i.probability,s)){o==null||o.debug("rule-skip-probability",{url:e,eventType:n},i);continue}return o==null||o.debug("rule-applied",{url:e,eventType:n},i),i}}return null}function ot(t,e,n,s){t.emit({type:"sse:drop",timestamp:Date.now(),applied:!0,detail:{url:e,eventType:n,...s?{reason:s}:{}}})}function ea(t,e,n,s){t.emit({type:"sse:delay",timestamp:Date.now(),applied:!0,detail:{url:e,eventType:n,delayMs:s}})}function ta(t,e,n,s){t.emit({type:"sse:corrupt",timestamp:Date.now(),applied:!0,detail:{url:e,eventType:n,strategy:s}})}function na(t,e,n){t.emit({type:"sse:close",timestamp:Date.now(),applied:!0,detail:{url:e,reason:n}})}function sa(t,e,n,s,r,a){const o=new Map;let i=!0;const c=(p,l)=>{let f=o.get(p);f||(f=new Set,o.set(p,f)),f.add(l)},u=(p,l)=>{var f;(f=o.get(p))==null||f.delete(l)},v=(p,l)=>{const f=o.get(p);if(f){for(const y of f)clearTimeout(y.handle),y.kind==="delay"&&ot(n,y.url,y.eventType,l);o.delete(p)}},M=(p,l,f)=>{const y=new MessageEvent(l.type||"message",{data:f,origin:l.origin,lastEventId:l.lastEventId});y[an]=!0,p.dispatchEvent(y)},P=(p,l,f)=>{if(f[an]||!i)return;const y=f.type||"message";if(at(e.drops,l,y,s,r,a,n)){f.stopImmediatePropagation(),ot(n,l,y);return}let _=typeof f.data=="string"?f.data:String(f.data),k=!1;const S=at(e.corruptions,l,y,s,r,a,n);S&&(_=kt(_,S.strategy),k=!0,ta(n,l,y,S.strategy));const C=at(e.delays,l,y,s,r,a,n);if(C){f.stopImmediatePropagation(),ea(n,l,y,C.delayMs);const N={kind:"delay",handle:setTimeout(()=>{u(p,N),i&&p.readyState!==p.CLOSED&&M(p,f,_)},C.delayMs),url:l,eventType:y};c(p,N);return}k&&(f.stopImmediatePropagation(),M(p,f,_))},F=p=>{if(!e.closes)return null;for(const l of e.closes){if(n.debug("rule-evaluating",{url:p},l),!ge(p,l.urlPattern)){n.debug("rule-skip-match",{url:p},l);continue}n.debug("rule-matched",{url:p},l);const f=ee(l,r);if(!te(l,f)){n.debug("rule-skip-counting",{url:p},l);continue}if(V(l,a,n,{url:p})){if(!q(l.probability,s)){n.debug("rule-skip-probability",{url:p},l);continue}return n.debug("rule-applied",{url:p},l),l}}return null},X=(p,l)=>{const f=F(l);if(!f)return;const y=f.afterMs??0,_=()=>{if(i){v(p,"close-interrupt"),na(n,l,"chaos-maker-close");try{p.close()}catch{}try{p.dispatchEvent(new Event("error"))}catch{}}};if(y<=0){const k={kind:"close",handle:setTimeout(_,0)};c(p,k)}else{const k={kind:"close",handle:setTimeout(_,y)};c(p,k)}};function W(p,l){const f=new t(p,l),y=typeof p=="string"?p:p.toString(),_=j=>{P(f,y,j)},k=new Set,S=f.addEventListener.bind(f),C=j=>{k.has(j)||(k.add(j),S(j,_,{capture:!0}))};C("message");const N=j=>{if(j)for(const d of j)d.eventType&&d.eventType!=="*"&&d.eventType!=="message"&&C(d.eventType)};N(e.drops),N(e.delays),N(e.corruptions);const Z=(j,d,A)=>{j!=="open"&&j!=="error"&&C(j),S(j,d,A)};return f.addEventListener=Z,X(f,y),f}Object.defineProperty(W,"prototype",{value:t.prototype,writable:!1});for(const p of["CONNECTING","OPEN","CLOSED"])W[p]=t[p];return{Wrapped:W,uninstall(){i=!1;for(const[,p]of o)for(const l of p)clearTimeout(l.handle),l.kind==="delay"&&ot(n,l.url,l.eventType,"stop-during-delay");o.clear()}}}function ss(t){return t===void 0?{enabled:!1}:typeof t=="boolean"?{enabled:t}:{enabled:t.enabled}}const ra=[{pick:t=>{var e;return(e=t.network)==null?void 0:e.failures},ruleType:"failure"},{pick:t=>{var e;return(e=t.network)==null?void 0:e.latencies},ruleType:"latency"},{pick:t=>{var e;return(e=t.network)==null?void 0:e.aborts},ruleType:"abort"},{pick:t=>{var e;return(e=t.network)==null?void 0:e.corruptions},ruleType:"corruption"},{pick:t=>{var e;return(e=t.network)==null?void 0:e.cors},ruleType:"cors"},{pick:t=>{var e;return(e=t.ui)==null?void 0:e.assaults},ruleType:"ui-assault"},{pick:t=>{var e;return(e=t.websocket)==null?void 0:e.drops},ruleType:"ws-drop"},{pick:t=>{var e;return(e=t.websocket)==null?void 0:e.delays},ruleType:"ws-delay"},{pick:t=>{var e;return(e=t.websocket)==null?void 0:e.corruptions},ruleType:"ws-corrupt"},{pick:t=>{var e;return(e=t.websocket)==null?void 0:e.closes},ruleType:"ws-close"},{pick:t=>{var e;return(e=t.sse)==null?void 0:e.drops},ruleType:"sse-drop"},{pick:t=>{var e;return(e=t.sse)==null?void 0:e.delays},ruleType:"sse-delay"},{pick:t=>{var e;return(e=t.sse)==null?void 0:e.corruptions},ruleType:"sse-corrupt"},{pick:t=>{var e;return(e=t.sse)==null?void 0:e.closes},ruleType:"sse-close"}];function rs(t){const e=new WeakMap;for(const{pick:n,ruleType:s}of ra){const r=n(t);r&&r.forEach((a,o)=>{e.set(a,{ruleType:s,ruleId:`${s}#${o}`})})}return e}function as(t,e){const n=[];return e.ruleId&&n.push(`rule=${e.ruleId}`),e.phase&&n.push(e.phase),e.method&&n.push(e.method),e.url&&n.push(e.url),e.statusCode!==void 0&&n.push(`-> ${e.statusCode}`),e.delayMs!==void 0&&n.push(`+${e.delayMs}ms`),e.direction&&n.push(e.direction),e.eventType&&n.push(`event=${e.eventType}`),e.selector&&n.push(`selector=${e.selector}`),e.action&&n.push(`action=${e.action}`),e.strategy&&n.push(`strategy=${e.strategy}`),e.groupName&&n.push(`group=${e.groupName}`),e.reason&&n.push(`reason=${e.reason}`),n.length===0?t:`${t}: ${n.join(" ")}`}class os{constructor(e,n="page"){this.opts=e,this.target=n}isEnabled(){return this.opts.enabled}log(e,n){if(!this.opts.enabled)return null;const s={...n,stage:e},r={type:"debug",timestamp:Date.now(),applied:!1,detail:s};if(typeof console<"u"&&typeof console.debug=="function"){const a=this.target==="sw"?"[Chaos SW]":"[Chaos]";try{console.debug(`${a} ${as(e,s)}`)}catch{}}return r}}function be(t){const e=t.trim();if(!e)throw new Error("[chaos-maker] Group name cannot be empty");return e}class bt{constructor(e,n={}){R(this,"config");R(this,"emitter");R(this,"random");R(this,"seed");R(this,"running",!1);R(this,"target");R(this,"originalFetch");R(this,"originalXhrSend");R(this,"originalXhrOpen");R(this,"domObserver");R(this,"originalWebSocket");R(this,"webSocketHandle");R(this,"originalEventSource");R(this,"eventSourceHandle");R(this,"requestCounters",new Map);R(this,"groups");R(this,"ruleIds");R(this,"logger");this.config=Tt(e,n.validation),this.emitter=new es;const s=Jn(this.config.seed);this.random=s.random,this.seed=s.seed,this.target=n.target??globalThis,this.groups=new gn;for(const a of this.config.groups??[])this.groups.ensure(a.name,{enabled:a.enabled??!0,explicit:!0});this.seedGroupsFromRules(),this.groups.ensure(Pe,{enabled:!0});const r=ss(this.config.debug);r.enabled&&(this.ruleIds=rs(this.config),this.emitter.setRuleIds(this.ruleIds),this.logger=new os(r,"page"),this.emitter.setLogger(this.logger)),console.log(`Chaos Maker initialized (seed: ${this.seed})`)}seedGroupsFromRules(){Bt(this.config,e=>{e.group&&this.groups.ensure(e.group)})}collectReferencedGroups(){const e=new Set;return Bt(this.config,n=>{n.group&&e.add(n.group)}),e}getSeed(){return this.seed}on(e,n){this.emitter.on(e,n)}off(e,n){this.emitter.off(e,n)}getLog(){return this.emitter.getLog()}clearLog(){this.emitter.clearLog()}enableGroup(e){const n=be(e);this.groups.setEnabled(n,!0),this.emitter.emit({type:"rule-group:enabled",timestamp:Date.now(),applied:!0,detail:{groupName:n}}),this.emitter.debug("lifecycle",{phase:"engine:group-toggled",groupName:n,enabled:!0})}disableGroup(e){const n=be(e);this.groups.setEnabled(n,!1),this.emitter.emit({type:"rule-group:disabled",timestamp:Date.now(),applied:!0,detail:{groupName:n}}),this.emitter.debug("lifecycle",{phase:"engine:group-toggled",groupName:n,enabled:!1})}createGroup(e,n){const s=be(e);this.groups.ensure(s,{...n,explicit:!0})}removeGroup(e,n){const s=be(e);return this.groups.remove(s,this.collectReferencedGroups(),n)}hasGroup(e){const n=be(e);return this.groups.has(n)}getGroupState(e){const n=be(e);return this.groups.isActive(n)}getGroupsSnapshot(){return this.groups.getSnapshot()}listGroups(){return this.groups.list()}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.emitter.debug("lifecycle",{phase:"engine:start"});const e=this.target;this.config.network&&(typeof e.fetch=="function"&&(this.originalFetch=e.fetch,e.fetch=Wr(this.originalFetch.bind(e),this.config.network,this.random,this.emitter,this.requestCounters,this.groups)),typeof e.XMLHttpRequest=="function"&&(this.originalXhrOpen=e.XMLHttpRequest.prototype.open,e.XMLHttpRequest.prototype.open=Br(this.originalXhrOpen),this.originalXhrSend=e.XMLHttpRequest.prototype.send,e.XMLHttpRequest.prototype.send=Fr(this.originalXhrSend,this.config.network,this.random,this.emitter,this.requestCounters,this.groups))),this.config.ui&&(typeof document>"u"||typeof MutationObserver>"u"?console.warn("Chaos Maker: UI config ignored — no DOM available in current context."):(this.domObserver=Yr(this.config.ui,this.random,this.emitter,this.groups),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=Qr(this.originalWebSocket,this.config.websocket,this.emitter,this.random,this.requestCounters,this.groups),e.WebSocket=this.webSocketHandle.Wrapped),this.config.sse&&typeof e.EventSource<"u"&&(this.originalEventSource=e.EventSource,this.eventSourceHandle=sa(this.originalEventSource,this.config.sse,this.emitter,this.random,this.requestCounters,this.groups),e.EventSource=this.eventSourceHandle.Wrapped)}stop(){this.running=!1,console.log("🛑 Chaos Maker DISENGAGED 🛑"),this.emitter.debug("lifecycle",{phase:"engine:stop"});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 on(t){return $e(t)}function cn(t){const e=t.trim();if(!e)throw new Error("[chaos-maker] Group name cannot be empty");return e}function aa(t){const e=t.trim();if(!e)throw new Error("[chaos-maker] preset name cannot be empty");return e}class oa{constructor(e){R(this,"config");R(this,"pendingGroup");R(this,"pendingPresets",[]);this.config=e?on(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={})}inGroup(e){return this.pendingGroup=cn(e),this}defineGroup(e,n){this.config.groups||(this.config.groups=[]);const s={name:cn(e)};return(n==null?void 0:n.enabled)!==void 0&&(s.enabled=n.enabled),this.config.groups.push(s),this}withGroup(e){const n=this.pendingGroup;return this.pendingGroup=void 0,n?{...e,group:n}:e}failRequests(e,n,s,r,a,o,i){return this.config.network.failures||(this.config.network.failures=[]),this.config.network.failures.push(this.withGroup({urlPattern:e,statusCode:n,probability:s,methods:r,body:a,headers:o,...i})),this}addLatency(e,n,s,r,a){return this.config.network.latencies||(this.config.network.latencies=[]),this.config.network.latencies.push(this.withGroup({urlPattern:e,delayMs:n,probability:s,methods:r,...a})),this}abortRequests(e,n,s,r,a){return this.config.network.aborts||(this.config.network.aborts=[]),this.config.network.aborts.push(this.withGroup({urlPattern:e,probability:n,timeout:s,methods:r,...a})),this}corruptResponses(e,n,s,r,a){return this.config.network.corruptions||(this.config.network.corruptions=[]),this.config.network.corruptions.push(this.withGroup({urlPattern:e,strategy:n,probability:s,methods:r,...a})),this}simulateCors(e,n,s,r){return this.config.network.cors||(this.config.network.cors=[]),this.config.network.cors.push(this.withGroup({urlPattern:e,probability:n,methods:s,...r})),this}failRequestsOnNth(e,n,s,r){return this.failRequests(e,n,1,r,void 0,void 0,{onNth:s})}addLatencyOnNth(e,n,s,r){return this.addLatency(e,n,1,r,{onNth:s})}abortRequestsOnNth(e,n,s,r){return this.abortRequests(e,1,s,r,{onNth:n})}corruptResponsesOnNth(e,n,s,r){return this.corruptResponses(e,n,1,r,{onNth:s})}simulateCorsOnNth(e,n,s){return this.simulateCors(e,1,s,{onNth:n})}failRequestsEveryNth(e,n,s,r){return this.failRequests(e,n,1,r,void 0,void 0,{everyNth:s})}addLatencyEveryNth(e,n,s,r){return this.addLatency(e,n,1,r,{everyNth:s})}abortRequestsEveryNth(e,n,s,r){return this.abortRequests(e,1,s,r,{everyNth:n})}corruptResponsesEveryNth(e,n,s,r){return this.corruptResponses(e,n,1,r,{everyNth:s})}simulateCorsEveryNth(e,n,s){return this.simulateCors(e,1,s,{everyNth:n})}failRequestsAfterN(e,n,s,r){return this.failRequests(e,n,1,r,void 0,void 0,{afterN:s})}addLatencyAfterN(e,n,s,r){return this.addLatency(e,n,1,r,{afterN:s})}abortRequestsAfterN(e,n,s,r){return this.abortRequests(e,1,s,r,{afterN:n})}corruptResponsesAfterN(e,n,s,r){return this.corruptResponses(e,n,1,r,{afterN:s})}simulateCorsAfterN(e,n,s){return this.simulateCors(e,1,s,{afterN:n})}assaultUi(e,n,s){return this.config.ui.assaults||(this.config.ui.assaults=[]),this.config.ui.assaults.push(this.withGroup({selector:e,action:n,probability:s})),this}dropMessages(e,n,s,r){return this.config.websocket.drops||(this.config.websocket.drops=[]),this.config.websocket.drops.push(this.withGroup({urlPattern:e,direction:n,probability:s,...r})),this}delayMessages(e,n,s,r,a){return this.config.websocket.delays||(this.config.websocket.delays=[]),this.config.websocket.delays.push(this.withGroup({urlPattern:e,direction:n,delayMs:s,probability:r,...a})),this}corruptMessages(e,n,s,r,a){return this.config.websocket.corruptions||(this.config.websocket.corruptions=[]),this.config.websocket.corruptions.push(this.withGroup({urlPattern:e,direction:n,strategy:s,probability:r,...a})),this}closeConnection(e,n,s,r){return this.config.websocket.closes||(this.config.websocket.closes=[]),this.config.websocket.closes.push(this.withGroup({urlPattern:e,probability:n,...s,...r})),this}dropMessagesOnNth(e,n,s){return this.dropMessages(e,n,1,{onNth:s})}delayMessagesOnNth(e,n,s,r){return this.delayMessages(e,n,s,1,{onNth:r})}failGraphQLOperation(e,n,s,r="*"){return this.config.network.failures||(this.config.network.failures=[]),this.config.network.failures.push(this.withGroup({urlPattern:r,statusCode:n,probability:s,graphqlOperation:e})),this}delayGraphQLOperation(e,n,s,r="*"){return this.config.network.latencies||(this.config.network.latencies=[]),this.config.network.latencies.push(this.withGroup({urlPattern:r,delayMs:n,probability:s,graphqlOperation:e})),this}dropSSE(e,n,s,r){return this.config.sse.drops||(this.config.sse.drops=[]),this.config.sse.drops.push(this.withGroup({urlPattern:e,probability:n,...s?{eventType:s}:{},...r})),this}delaySSE(e,n,s,r,a){return this.config.sse.delays||(this.config.sse.delays=[]),this.config.sse.delays.push(this.withGroup({urlPattern:e,delayMs:n,probability:s,...r?{eventType:r}:{},...a})),this}corruptSSE(e,n,s,r,a){return this.config.sse.corruptions||(this.config.sse.corruptions=[]),this.config.sse.corruptions.push(this.withGroup({urlPattern:e,strategy:n,probability:s,...r?{eventType:r}:{},...a})),this}closeSSE(e,n,s,r){return this.config.sse.closes||(this.config.sse.closes=[]),this.config.sse.closes.push(this.withGroup({urlPattern:e,probability:n,...s,...r})),this}withSeed(e){return this.config.seed=e,this}withDebug(e=!0){return this.config.debug=e,this}usePreset(e){const n=aa(e);return this.pendingPresets.includes(n)||this.pendingPresets.push(n),this}build(){const e=on(this.config),n=[],s=new Set;for(const r of[...e.presets??[],...this.pendingPresets])s.has(r)||(s.add(r),n.push(r));return n.length?e.presets=n:delete e.presets,e}}const Je="__chaosMakerRegExp";function ia(t){if(t===null||typeof t!="object")return!1;const e=t,n=Object.keys(e);if(n.length!==1||n[0]!==Je)return!1;const s=e[Je];if(!s||typeof s!="object")return!1;const r=s;for(const a of Object.keys(r))if(a!=="source"&&a!=="flags")return!1;return typeof r.source=="string"&&typeof r.flags=="string"}function vt(t){if(t===null||typeof t!="object")return t;if(t instanceof RegExp)return{[Je]:{source:t.source,flags:t.flags}};if(Array.isArray(t))return t.map(n=>vt(n));const e={};for(const[n,s]of Object.entries(t))e[n]=vt(s);return e}function et(t){if(t===null||typeof t!="object"||t instanceof RegExp)return t;if(ia(t)){const{source:n,flags:s}=t[Je];try{return new RegExp(n,s)}catch(r){return console.warn(`[chaos-maker] deserializeForTransport: invalid RegExp { source: ${JSON.stringify(n)}, flags: ${JSON.stringify(s)} } — ${r.message}`),t}}if(Array.isArray(t))return t.map(n=>et(n));const e={};for(const[n,s]of Object.entries(t))e[n]=et(s);return e}const ca=`
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
+ // Defensive: page-side adapters validate before calling apply. The
80
+ // page-side bundle deliberately excludes Zod, so a null/primitive/
81
+ // array/wildly-wrong payload throws here instead of silently posting
82
+ // garbage to the SW. \`typeof [] === 'object'\` so reject arrays too.
83
+ if (!cfg || typeof cfg !== 'object' || Array.isArray(cfg)) {
84
+ return Promise.reject(new Error('[chaos-maker] bridge.apply: config must be an object'));
85
+ }
86
+ // Stash cfg BEFORE awaiting ack — intentional. If the first ack times
87
+ // out (e.g. SW still installing), the controllerchange listener above
88
+ // will retry with this config once the new SW claims the page. Caller
89
+ // still sees the rejection from this attempt and can re-throw.
90
+ lastConfig = cfg;
91
+ return postConfig(cfg, timeoutMs).then(function (ack) {
92
+ return { seed: ack && typeof ack.seed === 'number' ? ack.seed : null };
93
+ });
94
+ },
95
+ stop: function (timeoutMs) {
96
+ lastConfig = null;
97
+ if (!('serviceWorker' in navigator) || !navigator.serviceWorker.controller) {
98
+ return Promise.resolve({ running: false });
99
+ }
100
+ return postViaPort(navigator.serviceWorker.controller, { __chaosMakerStop: true }, timeoutMs);
101
+ },
102
+ toggleGroup: function (name, enabled, timeoutMs) {
103
+ if (!('serviceWorker' in navigator) || !navigator.serviceWorker.controller) {
104
+ return Promise.reject(new Error('[chaos-maker] no SW controller — call injectSWChaos before toggleGroup'));
105
+ }
106
+ var t = (typeof timeoutMs === 'number' && timeoutMs > 0) ? timeoutMs : 2000;
107
+ return postViaPort(
108
+ navigator.serviceWorker.controller,
109
+ { __chaosMakerToggleGroup: { name: String(name), enabled: !!enabled } },
110
+ t,
111
+ );
112
+ },
113
+ getLocalLog: function () { return log.slice(); },
114
+ clearLocalLog: function () { log.length = 0; },
115
+ getRemoteLog: function (timeoutMs) {
116
+ if (!('serviceWorker' in navigator) || !navigator.serviceWorker.controller) {
117
+ return Promise.resolve([]);
118
+ }
119
+ return postViaPort(navigator.serviceWorker.controller, { __chaosMakerGetLog: true }, timeoutMs)
120
+ .then(function (reply) {
121
+ return (reply && Array.isArray(reply.log)) ? reply.log : [];
122
+ });
123
+ },
124
+ };
125
+
126
+ addSwListeners();
127
+ })();
128
+ `;if(typeof window<"u"){window.ChaosMaker=bt;const t={instance:null,start:e=>{t.instance&&(t.instance.stop(),t.instance=null);try{const n=et(e),s=new bt(n);return s.start(),t.instance=s,{success:!0,message:"Chaos started"}}catch(n){return console.error("Chaos Utils Error:",n),{success:!1,message:n.message}}},stop:()=>t.instance?(t.instance.stop(),t.instance=null,{success:!0,message:"Chaos stopped"}):{success:!1,message:"No chaos instance to stop"},getLog:()=>t.instance?t.instance.getLog():[],getSeed:()=>t.instance?t.instance.getSeed():null,enableGroup:e=>{if(!t.instance)return{success:!1,message:"No chaos instance"};try{return t.instance.enableGroup(e),{success:!0,message:`Group '${e}' enabled`}}catch(n){return{success:!1,message:(n==null?void 0:n.message)??String(n)}}},disableGroup:e=>{if(!t.instance)return{success:!1,message:"No chaos instance"};try{return t.instance.disableGroup(e),{success:!0,message:`Group '${e}' disabled`}}catch(n){return{success:!1,message:(n==null?void 0:n.message)??String(n)}}},createGroup:(e,n)=>{if(!t.instance)return{success:!1,message:"No chaos instance"};try{return t.instance.createGroup(e,n),{success:!0,message:`Group '${e}' created`}}catch(s){return{success:!1,message:(s==null?void 0:s.message)??String(s)}}},getGroupState:e=>{if(!t.instance)return null;try{return t.instance.getGroupState(e)}catch{return null}},validate:(e,n)=>Tt(e,n)};if(window.chaosUtils=t,window.__CHAOS_CONFIG__)try{const e=window.__CHAOS_CONFIG__;t.start(e),delete window.__CHAOS_CONFIG__}catch(e){console.error("ChaosMaker auto-start failed:",e)}}exports.BUILT_IN_PRESETS=mn;exports.ChaosConfigBuilder=oa;exports.ChaosConfigError=he;exports.ChaosEventEmitter=es;exports.ChaosMaker=bt;exports.DEFAULT_GROUP_NAME=Pe;exports.Logger=os;exports.PresetRegistry=bn;exports.RuleGroupRegistry=gn;exports.SW_BRIDGE_SOURCE=ca;exports.VALIDATOR_BRAND_VERSION=yt;exports.buildRuleIdMap=rs;exports.chaosConfigSchemaPassthrough=Hn;exports.chaosConfigSchemaStrict=Nt;exports.createPrng=Jn;exports.deserializeForTransport=et;exports.expandPresets=vn;exports.extractGraphQLOperation=Rt;exports.formatDebugMessage=as;exports.generateSeed=Qn;exports.normalizeDebugOption=ss;exports.operationNameMatches=ns;exports.parseOperationFromQueryString=Ot;exports.prepareChaosConfig=Xn;exports.presets=Hs;exports.serializeForTransport=vt;exports.validateChaosConfig=Tt;exports.validateConfig=Kn;