@chaos-maker/core 0.2.0-rc.1 → 0.3.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.
- package/dist/chaos-maker.cjs +2 -2
- package/dist/chaos-maker.js +40 -42
- package/dist/chaos-maker.umd.js +3 -3
- package/dist/types/config.d.ts +16 -1
- package/dist/types/interceptors/domAssailant.d.ts +1 -1
- package/dist/types/interceptors/networkFetch.d.ts +1 -1
- package/dist/types/interceptors/networkXHR.d.ts +1 -1
- package/dist/types/utils.d.ts +1 -1
- package/package.json +3 -3
package/dist/chaos-maker.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
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
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=Math.random){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=Math.random,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,r);if(t==null||t.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(t,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,r)){Ke(t,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,r);if(t==null||t.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,r);t==null||t.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,r)){ye(t,d,o,l,!1);continue}m=d;break}}let p;try{p=await s(a,i)}catch(d){throw m&&ye(t,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(t,m,o,l,!0),new Response(b,{status:p.status,statusText:p.statusText,headers:p.headers})}catch(d){throw ye(t,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=Math.random,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,r);if(t==null||t.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,r)){et(t,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(t,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,r);if(t==null||t.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,r)){tt(t,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(t,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,r);if(t==null||t.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=Math.random){const n=D(e.probability,r);if(t==null||t.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=Math.random){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)}catch(i){console.error(`Chaos Maker: Invalid selector '${a.selector}'`,i)}n.querySelectorAll(a.selector).forEach(i=>{Re(i,a,t,r)})}}function ks(s,e,t=Math.random){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.emitter,this.random,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.emitter,this.random,this.requestCounters)),this.config.ui&&(this.domObserver=ks(this.config.ui,this.emitter,this.random),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;
|
|
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;
|
package/dist/chaos-maker.js
CHANGED
|
@@ -2808,7 +2808,7 @@ class us {
|
|
|
2808
2808
|
}
|
|
2809
2809
|
}
|
|
2810
2810
|
}
|
|
2811
|
-
function D(s, e
|
|
2811
|
+
function D(s, e) {
|
|
2812
2812
|
return e() < s;
|
|
2813
2813
|
}
|
|
2814
2814
|
function V(s, e) {
|
|
@@ -2886,7 +2886,7 @@ function ye(s, e, t, r, n) {
|
|
|
2886
2886
|
detail: { url: t, method: r, strategy: e.strategy }
|
|
2887
2887
|
});
|
|
2888
2888
|
}
|
|
2889
|
-
function gs(s, e, t, r
|
|
2889
|
+
function gs(s, e, t, r, n = /* @__PURE__ */ new Map()) {
|
|
2890
2890
|
return async (a, i) => {
|
|
2891
2891
|
const o = ls(a), l = fs(a, i), c = hs(a, i);
|
|
2892
2892
|
if (e.cors) {
|
|
@@ -2894,8 +2894,8 @@ function gs(s, e, t, r = Math.random, n = /* @__PURE__ */ new Map()) {
|
|
|
2894
2894
|
if (U(o, d.urlPattern) && (!d.methods || d.methods.includes(l))) {
|
|
2895
2895
|
const b = V(d, n);
|
|
2896
2896
|
if (!z(d, b)) continue;
|
|
2897
|
-
const w = D(d.probability,
|
|
2898
|
-
if (
|
|
2897
|
+
const w = D(d.probability, t);
|
|
2898
|
+
if (r == null || r.emit({
|
|
2899
2899
|
type: "network:cors",
|
|
2900
2900
|
timestamp: Date.now(),
|
|
2901
2901
|
applied: w,
|
|
@@ -2909,15 +2909,15 @@ function gs(s, e, t, r = Math.random, n = /* @__PURE__ */ new Map()) {
|
|
|
2909
2909
|
}
|
|
2910
2910
|
let g = null, O, N, M = !1;
|
|
2911
2911
|
const R = (d) => {
|
|
2912
|
-
!g || M || (M = !0, N && (clearTimeout(N), N = void 0), Qe(
|
|
2912
|
+
!g || M || (M = !0, N && (clearTimeout(N), N = void 0), Qe(r, g, o, l, d));
|
|
2913
2913
|
};
|
|
2914
2914
|
if (e.aborts) {
|
|
2915
2915
|
for (const d of e.aborts)
|
|
2916
2916
|
if (U(o, d.urlPattern) && (!d.methods || d.methods.includes(l))) {
|
|
2917
2917
|
const b = V(d, n);
|
|
2918
2918
|
if (!z(d, b)) continue;
|
|
2919
|
-
if (!D(d.probability,
|
|
2920
|
-
Qe(
|
|
2919
|
+
if (!D(d.probability, t)) {
|
|
2920
|
+
Qe(r, d, o, l, !1);
|
|
2921
2921
|
continue;
|
|
2922
2922
|
}
|
|
2923
2923
|
console.warn(`CHAOS: Aborting ${l} ${o} after ${d.timeout || 0}ms`), g = d;
|
|
@@ -2942,8 +2942,8 @@ function gs(s, e, t, r = Math.random, n = /* @__PURE__ */ new Map()) {
|
|
|
2942
2942
|
if (U(o, d.urlPattern) && (!d.methods || d.methods.includes(l))) {
|
|
2943
2943
|
const b = V(d, n);
|
|
2944
2944
|
if (!z(d, b)) continue;
|
|
2945
|
-
const w = D(d.probability,
|
|
2946
|
-
if (
|
|
2945
|
+
const w = D(d.probability, t);
|
|
2946
|
+
if (r == null || r.emit({
|
|
2947
2947
|
type: "network:failure",
|
|
2948
2948
|
timestamp: Date.now(),
|
|
2949
2949
|
applied: w,
|
|
@@ -2964,8 +2964,8 @@ function gs(s, e, t, r = Math.random, n = /* @__PURE__ */ new Map()) {
|
|
|
2964
2964
|
if (U(o, d.urlPattern) && (!d.methods || d.methods.includes(l))) {
|
|
2965
2965
|
const b = V(d, n);
|
|
2966
2966
|
if (!z(d, b)) continue;
|
|
2967
|
-
const w = D(d.probability,
|
|
2968
|
-
|
|
2967
|
+
const w = D(d.probability, t);
|
|
2968
|
+
r == null || r.emit({
|
|
2969
2969
|
type: "network:latency",
|
|
2970
2970
|
timestamp: Date.now(),
|
|
2971
2971
|
applied: w,
|
|
@@ -2979,8 +2979,8 @@ function gs(s, e, t, r = Math.random, n = /* @__PURE__ */ new Map()) {
|
|
|
2979
2979
|
if (U(o, d.urlPattern) && (!d.methods || d.methods.includes(l))) {
|
|
2980
2980
|
const b = V(d, n);
|
|
2981
2981
|
if (!z(d, b)) continue;
|
|
2982
|
-
if (!D(d.probability,
|
|
2983
|
-
ye(
|
|
2982
|
+
if (!D(d.probability, t)) {
|
|
2983
|
+
ye(r, d, o, l, !1);
|
|
2984
2984
|
continue;
|
|
2985
2985
|
}
|
|
2986
2986
|
m = d;
|
|
@@ -2991,20 +2991,20 @@ function gs(s, e, t, r = Math.random, n = /* @__PURE__ */ new Map()) {
|
|
|
2991
2991
|
try {
|
|
2992
2992
|
p = await s(a, i);
|
|
2993
2993
|
} catch (d) {
|
|
2994
|
-
throw m && ye(
|
|
2994
|
+
throw m && ye(r, m, o, l, !1), d;
|
|
2995
2995
|
}
|
|
2996
2996
|
if (!m)
|
|
2997
2997
|
return p;
|
|
2998
2998
|
try {
|
|
2999
2999
|
console.warn(`CHAOS: Corrupting response for ${l} ${o} with strategy: ${m.strategy}`);
|
|
3000
3000
|
const d = await p.text(), b = lt(d, m.strategy);
|
|
3001
|
-
return ye(
|
|
3001
|
+
return ye(r, m, o, l, !0), new Response(b, {
|
|
3002
3002
|
status: p.status,
|
|
3003
3003
|
statusText: p.statusText,
|
|
3004
3004
|
headers: p.headers
|
|
3005
3005
|
});
|
|
3006
3006
|
} catch (d) {
|
|
3007
|
-
throw ye(
|
|
3007
|
+
throw ye(r, m, o, l, !1), d;
|
|
3008
3008
|
}
|
|
3009
3009
|
};
|
|
3010
3010
|
}
|
|
@@ -3024,7 +3024,7 @@ function et(s, e, t, r, n) {
|
|
|
3024
3024
|
detail: { url: t, method: r, strategy: e.strategy }
|
|
3025
3025
|
});
|
|
3026
3026
|
}
|
|
3027
|
-
function vs(s, e, t, r
|
|
3027
|
+
function vs(s, e, t, r, n = /* @__PURE__ */ new Map()) {
|
|
3028
3028
|
return function(a) {
|
|
3029
3029
|
const i = this._chaos_url, o = this._chaos_method;
|
|
3030
3030
|
if (e.cors) {
|
|
@@ -3032,8 +3032,8 @@ function vs(s, e, t, r = Math.random, n = /* @__PURE__ */ new Map()) {
|
|
|
3032
3032
|
if (U(i, c.urlPattern) && (!c.methods || c.methods.includes(o))) {
|
|
3033
3033
|
const g = V(c, n);
|
|
3034
3034
|
if (!z(c, g)) continue;
|
|
3035
|
-
const O = D(c.probability,
|
|
3036
|
-
if (
|
|
3035
|
+
const O = D(c.probability, t);
|
|
3036
|
+
if (r == null || r.emit({
|
|
3037
3037
|
type: "network:cors",
|
|
3038
3038
|
timestamp: Date.now(),
|
|
3039
3039
|
applied: O,
|
|
@@ -3049,8 +3049,8 @@ function vs(s, e, t, r = Math.random, n = /* @__PURE__ */ new Map()) {
|
|
|
3049
3049
|
if (U(i, c.urlPattern) && (!c.methods || c.methods.includes(o))) {
|
|
3050
3050
|
const g = V(c, n);
|
|
3051
3051
|
if (!z(c, g)) continue;
|
|
3052
|
-
if (!D(c.probability,
|
|
3053
|
-
Ke(
|
|
3052
|
+
if (!D(c.probability, t)) {
|
|
3053
|
+
Ke(r, c, i, o, !1);
|
|
3054
3054
|
continue;
|
|
3055
3055
|
}
|
|
3056
3056
|
console.warn(`CHAOS: Aborting ${o} ${i} after ${c.timeout || 0}ms`);
|
|
@@ -3058,7 +3058,7 @@ function vs(s, e, t, r = Math.random, n = /* @__PURE__ */ new Map()) {
|
|
|
3058
3058
|
const R = () => {
|
|
3059
3059
|
M && (clearTimeout(M), M = void 0), typeof this.removeEventListener == "function" && this.removeEventListener("loadend", p);
|
|
3060
3060
|
}, m = (b) => {
|
|
3061
|
-
N || (N = !0, R(), Ke(
|
|
3061
|
+
N || (N = !0, R(), Ke(r, c, i, o, b));
|
|
3062
3062
|
}, p = () => {
|
|
3063
3063
|
m(!1);
|
|
3064
3064
|
}, d = () => {
|
|
@@ -3081,8 +3081,8 @@ function vs(s, e, t, r = Math.random, n = /* @__PURE__ */ new Map()) {
|
|
|
3081
3081
|
if (U(i, c.urlPattern) && (!c.methods || c.methods.includes(o))) {
|
|
3082
3082
|
const g = V(c, n);
|
|
3083
3083
|
if (!z(c, g)) continue;
|
|
3084
|
-
const O = D(c.probability,
|
|
3085
|
-
if (
|
|
3084
|
+
const O = D(c.probability, t);
|
|
3085
|
+
if (r == null || r.emit({
|
|
3086
3086
|
type: "network:failure",
|
|
3087
3087
|
timestamp: Date.now(),
|
|
3088
3088
|
applied: O,
|
|
@@ -3117,8 +3117,8 @@ function vs(s, e, t, r = Math.random, n = /* @__PURE__ */ new Map()) {
|
|
|
3117
3117
|
if (U(i, c.urlPattern) && (!c.methods || c.methods.includes(o))) {
|
|
3118
3118
|
const g = V(c, n);
|
|
3119
3119
|
if (!z(c, g)) continue;
|
|
3120
|
-
if (!D(c.probability,
|
|
3121
|
-
et(
|
|
3120
|
+
if (!D(c.probability, t)) {
|
|
3121
|
+
et(r, c, i, o, !1);
|
|
3122
3122
|
continue;
|
|
3123
3123
|
}
|
|
3124
3124
|
l = c;
|
|
@@ -3130,7 +3130,7 @@ function vs(s, e, t, r = Math.random, n = /* @__PURE__ */ new Map()) {
|
|
|
3130
3130
|
const O = () => {
|
|
3131
3131
|
typeof this.removeEventListener == "function" && (this.removeEventListener("error", R), this.removeEventListener("abort", R), this.removeEventListener("loadend", m));
|
|
3132
3132
|
}, N = (p) => {
|
|
3133
|
-
c || (c = !0, et(
|
|
3133
|
+
c || (c = !0, et(r, l, i, o, p), O());
|
|
3134
3134
|
}, M = () => {
|
|
3135
3135
|
if (g !== null)
|
|
3136
3136
|
return g;
|
|
@@ -3162,8 +3162,8 @@ function vs(s, e, t, r = Math.random, n = /* @__PURE__ */ new Map()) {
|
|
|
3162
3162
|
if (U(i, c.urlPattern) && (!c.methods || c.methods.includes(o))) {
|
|
3163
3163
|
const g = V(c, n);
|
|
3164
3164
|
if (!z(c, g)) continue;
|
|
3165
|
-
const O = D(c.probability,
|
|
3166
|
-
if (
|
|
3165
|
+
const O = D(c.probability, t);
|
|
3166
|
+
if (r == null || r.emit({
|
|
3167
3167
|
type: "network:latency",
|
|
3168
3168
|
timestamp: Date.now(),
|
|
3169
3169
|
applied: O,
|
|
@@ -3184,9 +3184,9 @@ function _s(s) {
|
|
|
3184
3184
|
this._chaos_url = t.toString(), this._chaos_method = e.toUpperCase(), s.call(this, e, t);
|
|
3185
3185
|
};
|
|
3186
3186
|
}
|
|
3187
|
-
function Re(s, e, t, r
|
|
3188
|
-
const n = D(e.probability,
|
|
3189
|
-
if (
|
|
3187
|
+
function Re(s, e, t, r) {
|
|
3188
|
+
const n = D(e.probability, t);
|
|
3189
|
+
if (r == null || r.emit({
|
|
3190
3190
|
type: "ui:assault",
|
|
3191
3191
|
timestamp: Date.now(),
|
|
3192
3192
|
applied: n,
|
|
@@ -3210,22 +3210,20 @@ function Re(s, e, t, r = Math.random) {
|
|
|
3210
3210
|
}
|
|
3211
3211
|
}
|
|
3212
3212
|
}
|
|
3213
|
-
function bs(s, e, t, r
|
|
3213
|
+
function bs(s, e, t, r) {
|
|
3214
3214
|
if (s.nodeType !== Node.ELEMENT_NODE || !e.assaults)
|
|
3215
3215
|
return;
|
|
3216
3216
|
const n = s;
|
|
3217
|
-
for (const a of e.assaults)
|
|
3217
|
+
for (const a of e.assaults)
|
|
3218
3218
|
try {
|
|
3219
|
-
n.matches(a.selector) && Re(n, a, t, r)
|
|
3219
|
+
n.matches(a.selector) && Re(n, a, t, r), n.querySelectorAll(a.selector).forEach((i) => {
|
|
3220
|
+
Re(i, a, t, r);
|
|
3221
|
+
});
|
|
3220
3222
|
} catch (i) {
|
|
3221
3223
|
console.error(`Chaos Maker: Invalid selector '${a.selector}'`, i);
|
|
3222
3224
|
}
|
|
3223
|
-
n.querySelectorAll(a.selector).forEach((i) => {
|
|
3224
|
-
Re(i, a, t, r);
|
|
3225
|
-
});
|
|
3226
|
-
}
|
|
3227
3225
|
}
|
|
3228
|
-
function ks(s, e, t
|
|
3226
|
+
function ks(s, e, t) {
|
|
3229
3227
|
if (s.assaults) {
|
|
3230
3228
|
console.log("CHAOS: Running initial DOM scan for existing elements...");
|
|
3231
3229
|
for (const n of s.assaults)
|
|
@@ -3242,7 +3240,7 @@ function ks(s, e, t = Math.random) {
|
|
|
3242
3240
|
a.type === "childList" && a.addedNodes.forEach((i) => bs(i, s, e, t));
|
|
3243
3241
|
});
|
|
3244
3242
|
}
|
|
3245
|
-
const tt = Symbol.for("chaos-maker.websocket.intercepted");
|
|
3243
|
+
const tt = /* @__PURE__ */ Symbol.for("chaos-maker.websocket.intercepted");
|
|
3246
3244
|
function ws(s, e) {
|
|
3247
3245
|
return s === "both" ? !0 : s === e;
|
|
3248
3246
|
}
|
|
@@ -3505,7 +3503,7 @@ class it {
|
|
|
3505
3503
|
console.warn("Chaos Maker is already running. Call stop() first.");
|
|
3506
3504
|
return;
|
|
3507
3505
|
}
|
|
3508
|
-
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.
|
|
3506
|
+
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, {
|
|
3509
3507
|
childList: !0,
|
|
3510
3508
|
subtree: !0
|
|
3511
3509
|
}), 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(
|
package/dist/chaos-maker.umd.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(function(E,b){typeof exports=="object"&&typeof module<"u"?b(exports):typeof define=="function"&&define.amd?define(["exports"],b):(E=typeof globalThis<"u"?globalThis:E||self,b(E.ChaosMaker={}))})(this,function(E){"use strict";var Ss=Object.defineProperty;var Ts=(E,b,re)=>b in E?Ss(E,b,{enumerable:!0,configurable:!0,writable:!0,value:re}):E[b]=re;var Z=(E,b,re)=>Ts(E,typeof b!="symbol"?b+"":b,re);var b;(function(s){s.assertEqual=n=>{};function e(n){}s.assertIs=e;function t(n){throw new Error}s.assertNever=t,s.arrayToEnum=n=>{const a={};for(const i of n)a[i]=i;return a},s.getValidEnumValues=n=>{const a=s.objectKeys(n).filter(o=>typeof n[n[o]]!="number"),i={};for(const o of a)i[o]=n[o];return s.objectValues(i)},s.objectValues=n=>s.objectKeys(n).map(function(a){return n[a]}),s.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{const a=[];for(const i in n)Object.prototype.hasOwnProperty.call(n,i)&&a.push(i);return a},s.find=(n,a)=>{for(const i of n)if(a(i))return i},s.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&Number.isFinite(n)&&Math.floor(n)===n;function r(n,a=" | "){return n.map(i=>typeof i=="string"?`'${i}'`:i).join(a)}s.joinValues=r,s.jsonStringifyReplacer=(n,a)=>typeof a=="bigint"?a.toString():a})(b||(b={}));var re;(function(s){s.mergeShapes=(e,t)=>({...e,...t})})(re||(re={}));const h=b.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ee=s=>{switch(typeof s){case"undefined":return h.undefined;case"string":return h.string;case"number":return Number.isNaN(s)?h.nan:h.number;case"boolean":return h.boolean;case"function":return h.function;case"bigint":return h.bigint;case"symbol":return h.symbol;case"object":return Array.isArray(s)?h.array:s===null?h.null:s.then&&typeof s.then=="function"&&s.catch&&typeof s.catch=="function"?h.promise:typeof Map<"u"&&s instanceof Map?h.map:typeof Set<"u"&&s instanceof Set?h.set:typeof Date<"u"&&s instanceof Date?h.date:h.object;default:return h.unknown}},u=b.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class J extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(a){return a.message},r={_errors:[]},n=a=>{for(const i of a.issues)if(i.code==="invalid_union")i.unionErrors.map(n);else if(i.code==="invalid_return_type")n(i.returnTypeError);else if(i.code==="invalid_arguments")n(i.argumentsError);else if(i.path.length===0)r._errors.push(t(i));else{let o=r,l=0;for(;l<i.path.length;){const c=i.path[l];l===i.path.length-1?(o[c]=o[c]||{_errors:[]},o[c]._errors.push(t(i))):o[c]=o[c]||{_errors:[]},o=o[c],l++}}};return n(this),r}static assert(e){if(!(e instanceof J))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,b.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},r=[];for(const n of this.issues)if(n.path.length>0){const a=n.path[0];t[a]=t[a]||[],t[a].push(e(n))}else r.push(e(n));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}J.create=s=>new J(s);const Oe=(s,e)=>{let t;switch(s.code){case u.invalid_type:s.received===h.undefined?t="Required":t=`Expected ${s.expected}, received ${s.received}`;break;case u.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(s.expected,b.jsonStringifyReplacer)}`;break;case u.unrecognized_keys:t=`Unrecognized key(s) in object: ${b.joinValues(s.keys,", ")}`;break;case u.invalid_union:t="Invalid input";break;case u.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${b.joinValues(s.options)}`;break;case u.invalid_enum_value:t=`Invalid enum value. Expected ${b.joinValues(s.options)}, received '${s.received}'`;break;case u.invalid_arguments:t="Invalid function arguments";break;case u.invalid_return_type:t="Invalid function return type";break;case u.invalid_date:t="Invalid date";break;case u.invalid_string:typeof s.validation=="object"?"includes"in s.validation?(t=`Invalid input: must include "${s.validation.includes}"`,typeof s.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${s.validation.position}`)):"startsWith"in s.validation?t=`Invalid input: must start with "${s.validation.startsWith}"`:"endsWith"in s.validation?t=`Invalid input: must end with "${s.validation.endsWith}"`:b.assertNever(s.validation):s.validation!=="regex"?t=`Invalid ${s.validation}`:t="Invalid";break;case u.too_small:s.type==="array"?t=`Array must contain ${s.exact?"exactly":s.inclusive?"at least":"more than"} ${s.minimum} element(s)`:s.type==="string"?t=`String must contain ${s.exact?"exactly":s.inclusive?"at least":"over"} ${s.minimum} character(s)`:s.type==="number"?t=`Number must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${s.minimum}`:s.type==="bigint"?t=`Number must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${s.minimum}`:s.type==="date"?t=`Date must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(s.minimum))}`:t="Invalid input";break;case u.too_big:s.type==="array"?t=`Array must contain ${s.exact?"exactly":s.inclusive?"at most":"less than"} ${s.maximum} element(s)`:s.type==="string"?t=`String must contain ${s.exact?"exactly":s.inclusive?"at most":"under"} ${s.maximum} character(s)`:s.type==="number"?t=`Number must be ${s.exact?"exactly":s.inclusive?"less than or equal to":"less than"} ${s.maximum}`:s.type==="bigint"?t=`BigInt must be ${s.exact?"exactly":s.inclusive?"less than or equal to":"less than"} ${s.maximum}`:s.type==="date"?t=`Date must be ${s.exact?"exactly":s.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(s.maximum))}`:t="Invalid input";break;case u.custom:t="Invalid input";break;case u.invalid_intersection_types:t="Intersection results could not be merged";break;case u.not_multiple_of:t=`Number must be a multiple of ${s.multipleOf}`;break;case u.not_finite:t="Number must be finite";break;default:t=e.defaultError,b.assertNever(s)}return{message:t}};let _t=Oe;function bt(){return _t}const kt=s=>{const{data:e,path:t,errorMaps:r,issueData:n}=s,a=[...t,...n.path||[]],i={...n,path:a};if(n.message!==void 0)return{...n,path:a,message:n.message};let o="";const l=r.filter(c=>!!c).slice().reverse();for(const c of l)o=c(i,{data:e,defaultError:o}).message;return{...n,path:a,message:o}};function f(s,e){const t=bt(),r=kt({issueData:e,data:s.data,path:s.path,errorMaps:[s.common.contextualErrorMap,s.schemaErrorMap,t,t===Oe?void 0:Oe].filter(n=>!!n)});s.common.issues.push(r)}class ${constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const r=[];for(const n of t){if(n.status==="aborted")return _;n.status==="dirty"&&e.dirty(),r.push(n.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const n of t){const a=await n.key,i=await n.value;r.push({key:a,value:i})}return $.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const n of t){const{key:a,value:i}=n;if(a.status==="aborted"||i.status==="aborted")return _;a.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof i.value<"u"||n.alwaysSet)&&(r[a.value]=i.value)}return{status:e.value,value:r}}}const _=Object.freeze({status:"aborted"}),pe=s=>({status:"dirty",value:s}),z=s=>({status:"valid",value:s}),Le=s=>s.status==="aborted",De=s=>s.status==="dirty",ie=s=>s.status==="valid",ve=s=>typeof Promise<"u"&&s instanceof Promise;var m;(function(s){s.errToObj=e=>typeof e=="string"?{message:e}:e||{},s.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(m||(m={}));class H{constructor(e,t,r,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=n}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Ve=(s,e)=>{if(ie(e))return{success:!0,data:e.value};if(!s.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new J(s.common.issues);return this._error=t,this._error}}};function w(s){if(!s)return{};const{errorMap:e,invalid_type_error:t,required_error:r,description:n}=s;if(e&&(t||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:n}:{errorMap:(i,o)=>{const{message:l}=s;return i.code==="invalid_enum_value"?{message:l??o.defaultError}:typeof o.data>"u"?{message:l??r??o.defaultError}:i.code!=="invalid_type"?{message:o.defaultError}:{message:l??t??o.defaultError}},description:n}}class C{get description(){return this._def.description}_getType(e){return ee(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:ee(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new $,ctx:{common:e.parent.common,data:e.data,parsedType:ee(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(ve(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){const r={common:{issues:[],async:(t==null?void 0:t.async)??!1,contextualErrorMap:t==null?void 0:t.errorMap},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ee(e)},n=this._parseSync({data:e,path:r.path,parent:r});return Ve(r,n)}"~validate"(e){var r,n;const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ee(e)};if(!this["~standard"].async)try{const a=this._parseSync({data:e,path:[],parent:t});return ie(a)?{value:a.value}:{issues:t.common.issues}}catch(a){(n=(r=a==null?void 0:a.message)==null?void 0:r.toLowerCase())!=null&&n.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(a=>ie(a)?{value:a.value}:{issues:t.common.issues})}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:t==null?void 0:t.errorMap,async:!0},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ee(e)},n=this._parse({data:e,path:r.path,parent:r}),a=await(ve(n)?n:Promise.resolve(n));return Ve(r,a)}refine(e,t){const r=n=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(n):t;return this._refinement((n,a)=>{const i=e(n),o=()=>a.addIssue({code:u.custom,...r(n)});return typeof Promise<"u"&&i instanceof Promise?i.then(l=>l?!0:(o(),!1)):i?!0:(o(),!1)})}refinement(e,t){return this._refinement((r,n)=>e(r)?!0:(n.addIssue(typeof t=="function"?t(r,n):t),!1))}_refinement(e){return new ue({schema:this,typeName:v.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return se.create(this,this._def)}nullable(){return le.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return W.create(this)}promise(){return xe.create(this,this._def)}or(e){return be.create([this,e],this._def)}and(e){return ke.create(this,e,this._def)}transform(e){return new ue({...w(this._def),schema:this,typeName:v.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new Ee({...w(this._def),innerType:this,defaultValue:t,typeName:v.ZodDefault})}brand(){return new Ft({typeName:v.ZodBranded,type:this,...w(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new Re({...w(this._def),innerType:this,catchValue:t,typeName:v.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Me.create(this,e)}readonly(){return je.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const wt=/^c[^\s-]{8,}$/i,xt=/^[0-9a-z]+$/,Ct=/^[0-9A-HJKMNP-TV-Z]{26}$/i,St=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Tt=/^[a-z0-9_-]{21}$/i,Ot=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Nt=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,At=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Et="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Ne;const Rt=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Mt=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,jt=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Pt=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Zt=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,$t=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ze="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",It=new RegExp(`^${ze}$`);function Ue(s){let e="[0-5]\\d";s.precision?e=`${e}\\.\\d{${s.precision}}`:s.precision==null&&(e=`${e}(\\.\\d+)?`);const t=s.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function Lt(s){return new RegExp(`^${Ue(s)}$`)}function Dt(s){let e=`${ze}T${Ue(s)}`;const t=[];return t.push(s.local?"Z?":"Z"),s.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Vt(s,e){return!!((e==="v4"||!e)&&Rt.test(s)||(e==="v6"||!e)&&jt.test(s))}function zt(s,e){if(!Ot.test(s))return!1;try{const[t]=s.split(".");if(!t)return!1;const r=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),n=JSON.parse(atob(r));return!(typeof n!="object"||n===null||"typ"in n&&(n==null?void 0:n.typ)!=="JWT"||!n.alg||e&&n.alg!==e)}catch{return!1}}function Ut(s,e){return!!((e==="v4"||!e)&&Mt.test(s)||(e==="v6"||!e)&&Pt.test(s))}class Y extends C{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==h.string){const a=this._getOrReturnCtx(e);return f(a,{code:u.invalid_type,expected:h.string,received:a.parsedType}),_}const r=new $;let n;for(const a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(n=this._getOrReturnCtx(e,n),f(n,{code:u.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),r.dirty());else if(a.kind==="max")e.data.length>a.value&&(n=this._getOrReturnCtx(e,n),f(n,{code:u.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),r.dirty());else if(a.kind==="length"){const i=e.data.length>a.value,o=e.data.length<a.value;(i||o)&&(n=this._getOrReturnCtx(e,n),i?f(n,{code:u.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):o&&f(n,{code:u.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),r.dirty())}else if(a.kind==="email")At.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"email",code:u.invalid_string,message:a.message}),r.dirty());else if(a.kind==="emoji")Ne||(Ne=new RegExp(Et,"u")),Ne.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"emoji",code:u.invalid_string,message:a.message}),r.dirty());else if(a.kind==="uuid")St.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"uuid",code:u.invalid_string,message:a.message}),r.dirty());else if(a.kind==="nanoid")Tt.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"nanoid",code:u.invalid_string,message:a.message}),r.dirty());else if(a.kind==="cuid")wt.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"cuid",code:u.invalid_string,message:a.message}),r.dirty());else if(a.kind==="cuid2")xt.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"cuid2",code:u.invalid_string,message:a.message}),r.dirty());else if(a.kind==="ulid")Ct.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"ulid",code:u.invalid_string,message:a.message}),r.dirty());else if(a.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),f(n,{validation:"url",code:u.invalid_string,message:a.message}),r.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"regex",code:u.invalid_string,message:a.message}),r.dirty())):a.kind==="trim"?e.data=e.data.trim():a.kind==="includes"?e.data.includes(a.value,a.position)||(n=this._getOrReturnCtx(e,n),f(n,{code:u.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),r.dirty()):a.kind==="toLowerCase"?e.data=e.data.toLowerCase():a.kind==="toUpperCase"?e.data=e.data.toUpperCase():a.kind==="startsWith"?e.data.startsWith(a.value)||(n=this._getOrReturnCtx(e,n),f(n,{code:u.invalid_string,validation:{startsWith:a.value},message:a.message}),r.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(n=this._getOrReturnCtx(e,n),f(n,{code:u.invalid_string,validation:{endsWith:a.value},message:a.message}),r.dirty()):a.kind==="datetime"?Dt(a).test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{code:u.invalid_string,validation:"datetime",message:a.message}),r.dirty()):a.kind==="date"?It.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{code:u.invalid_string,validation:"date",message:a.message}),r.dirty()):a.kind==="time"?Lt(a).test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{code:u.invalid_string,validation:"time",message:a.message}),r.dirty()):a.kind==="duration"?Nt.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"duration",code:u.invalid_string,message:a.message}),r.dirty()):a.kind==="ip"?Vt(e.data,a.version)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"ip",code:u.invalid_string,message:a.message}),r.dirty()):a.kind==="jwt"?zt(e.data,a.alg)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"jwt",code:u.invalid_string,message:a.message}),r.dirty()):a.kind==="cidr"?Ut(e.data,a.version)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"cidr",code:u.invalid_string,message:a.message}),r.dirty()):a.kind==="base64"?Zt.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"base64",code:u.invalid_string,message:a.message}),r.dirty()):a.kind==="base64url"?$t.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"base64url",code:u.invalid_string,message:a.message}),r.dirty()):b.assertNever(a);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement(n=>e.test(n),{validation:t,code:u.invalid_string,...m.errToObj(r)})}_addCheck(e){return new Y({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...m.errToObj(e)})}url(e){return this._addCheck({kind:"url",...m.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...m.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...m.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...m.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...m.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...m.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...m.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...m.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...m.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...m.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...m.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...m.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(e==null?void 0:e.offset)??!1,local:(e==null?void 0:e.local)??!1,...m.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...m.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...m.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...m.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t==null?void 0:t.position,...m.errToObj(t==null?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...m.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...m.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...m.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...m.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...m.errToObj(t)})}nonempty(e){return this.min(1,m.errToObj(e))}trim(){return new Y({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Y({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Y({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}Y.create=s=>new Y({checks:[],typeName:v.ZodString,coerce:(s==null?void 0:s.coerce)??!1,...w(s)});function qt(s,e){const t=(s.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,n=t>r?t:r,a=Number.parseInt(s.toFixed(n).replace(".","")),i=Number.parseInt(e.toFixed(n).replace(".",""));return a%i/10**n}class oe extends C{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==h.number){const a=this._getOrReturnCtx(e);return f(a,{code:u.invalid_type,expected:h.number,received:a.parsedType}),_}let r;const n=new $;for(const a of this._def.checks)a.kind==="int"?b.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{code:u.invalid_type,expected:"integer",received:"float",message:a.message}),n.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(r=this._getOrReturnCtx(e,r),f(r,{code:u.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),n.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(r=this._getOrReturnCtx(e,r),f(r,{code:u.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),n.dirty()):a.kind==="multipleOf"?qt(e.data,a.value)!==0&&(r=this._getOrReturnCtx(e,r),f(r,{code:u.not_multiple_of,multipleOf:a.value,message:a.message}),n.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{code:u.not_finite,message:a.message}),n.dirty()):b.assertNever(a);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,m.toString(t))}gt(e,t){return this.setLimit("min",e,!1,m.toString(t))}lte(e,t){return this.setLimit("max",e,!0,m.toString(t))}lt(e,t){return this.setLimit("max",e,!1,m.toString(t))}setLimit(e,t,r,n){return new oe({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:m.toString(n)}]})}_addCheck(e){return new oe({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:m.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:m.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:m.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:m.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:m.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:m.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:m.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:m.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:m.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&b.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(t===null||r.value>t)&&(t=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}}oe.create=s=>new oe({checks:[],typeName:v.ZodNumber,coerce:(s==null?void 0:s.coerce)||!1,...w(s)});class me extends C{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==h.bigint)return this._getInvalidInput(e);let r;const n=new $;for(const a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(r=this._getOrReturnCtx(e,r),f(r,{code:u.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),n.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(r=this._getOrReturnCtx(e,r),f(r,{code:u.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),n.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),f(r,{code:u.not_multiple_of,multipleOf:a.value,message:a.message}),n.dirty()):b.assertNever(a);return{status:n.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:h.bigint,received:t.parsedType}),_}gte(e,t){return this.setLimit("min",e,!0,m.toString(t))}gt(e,t){return this.setLimit("min",e,!1,m.toString(t))}lte(e,t){return this.setLimit("max",e,!0,m.toString(t))}lt(e,t){return this.setLimit("max",e,!1,m.toString(t))}setLimit(e,t,r,n){return new me({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:m.toString(n)}]})}_addCheck(e){return new me({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:m.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:m.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:m.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:m.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:m.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}me.create=s=>new me({checks:[],typeName:v.ZodBigInt,coerce:(s==null?void 0:s.coerce)??!1,...w(s)});class qe extends C{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==h.boolean){const r=this._getOrReturnCtx(e);return f(r,{code:u.invalid_type,expected:h.boolean,received:r.parsedType}),_}return z(e.data)}}qe.create=s=>new qe({typeName:v.ZodBoolean,coerce:(s==null?void 0:s.coerce)||!1,...w(s)});class _e extends C{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==h.date){const a=this._getOrReturnCtx(e);return f(a,{code:u.invalid_type,expected:h.date,received:a.parsedType}),_}if(Number.isNaN(e.data.getTime())){const a=this._getOrReturnCtx(e);return f(a,{code:u.invalid_date}),_}const r=new $;let n;for(const a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(n=this._getOrReturnCtx(e,n),f(n,{code:u.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),r.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(n=this._getOrReturnCtx(e,n),f(n,{code:u.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),r.dirty()):b.assertNever(a);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new _e({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:m.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:m.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}_e.create=s=>new _e({checks:[],coerce:(s==null?void 0:s.coerce)||!1,typeName:v.ZodDate,...w(s)});class Fe extends C{_parse(e){if(this._getType(e)!==h.symbol){const r=this._getOrReturnCtx(e);return f(r,{code:u.invalid_type,expected:h.symbol,received:r.parsedType}),_}return z(e.data)}}Fe.create=s=>new Fe({typeName:v.ZodSymbol,...w(s)});class Be extends C{_parse(e){if(this._getType(e)!==h.undefined){const r=this._getOrReturnCtx(e);return f(r,{code:u.invalid_type,expected:h.undefined,received:r.parsedType}),_}return z(e.data)}}Be.create=s=>new Be({typeName:v.ZodUndefined,...w(s)});class He extends C{_parse(e){if(this._getType(e)!==h.null){const r=this._getOrReturnCtx(e);return f(r,{code:u.invalid_type,expected:h.null,received:r.parsedType}),_}return z(e.data)}}He.create=s=>new He({typeName:v.ZodNull,...w(s)});class We extends C{constructor(){super(...arguments),this._any=!0}_parse(e){return z(e.data)}}We.create=s=>new We({typeName:v.ZodAny,...w(s)});class Xe extends C{constructor(){super(...arguments),this._unknown=!0}_parse(e){return z(e.data)}}Xe.create=s=>new Xe({typeName:v.ZodUnknown,...w(s)});class te extends C{_parse(e){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:h.never,received:t.parsedType}),_}}te.create=s=>new te({typeName:v.ZodNever,...w(s)});class Ge extends C{_parse(e){if(this._getType(e)!==h.undefined){const r=this._getOrReturnCtx(e);return f(r,{code:u.invalid_type,expected:h.void,received:r.parsedType}),_}return z(e.data)}}Ge.create=s=>new Ge({typeName:v.ZodVoid,...w(s)});class W extends C{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),n=this._def;if(t.parsedType!==h.array)return f(t,{code:u.invalid_type,expected:h.array,received:t.parsedType}),_;if(n.exactLength!==null){const i=t.data.length>n.exactLength.value,o=t.data.length<n.exactLength.value;(i||o)&&(f(t,{code:i?u.too_big:u.too_small,minimum:o?n.exactLength.value:void 0,maximum:i?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),r.dirty())}if(n.minLength!==null&&t.data.length<n.minLength.value&&(f(t,{code:u.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),r.dirty()),n.maxLength!==null&&t.data.length>n.maxLength.value&&(f(t,{code:u.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((i,o)=>n.type._parseAsync(new H(t,i,t.path,o)))).then(i=>$.mergeArray(r,i));const a=[...t.data].map((i,o)=>n.type._parseSync(new H(t,i,t.path,o)));return $.mergeArray(r,a)}get element(){return this._def.type}min(e,t){return new W({...this._def,minLength:{value:e,message:m.toString(t)}})}max(e,t){return new W({...this._def,maxLength:{value:e,message:m.toString(t)}})}length(e,t){return new W({...this._def,exactLength:{value:e,message:m.toString(t)}})}nonempty(e){return this.min(1,e)}}W.create=(s,e)=>new W({type:s,minLength:null,maxLength:null,exactLength:null,typeName:v.ZodArray,...w(e)});function ce(s){if(s instanceof N){const e={};for(const t in s.shape){const r=s.shape[t];e[t]=se.create(ce(r))}return new N({...s._def,shape:()=>e})}else return s instanceof W?new W({...s._def,type:ce(s.element)}):s instanceof se?se.create(ce(s.unwrap())):s instanceof le?le.create(ce(s.unwrap())):s instanceof ne?ne.create(s.items.map(e=>ce(e))):s}class N extends C{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),t=b.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==h.object){const c=this._getOrReturnCtx(e);return f(c,{code:u.invalid_type,expected:h.object,received:c.parsedType}),_}const{status:r,ctx:n}=this._processInputParams(e),{shape:a,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof te&&this._def.unknownKeys==="strip"))for(const c in n.data)i.includes(c)||o.push(c);const l=[];for(const c of i){const g=a[c],O=n.data[c];l.push({key:{status:"valid",value:c},value:g._parse(new H(n,O,n.path,c)),alwaysSet:c in n.data})}if(this._def.catchall instanceof te){const c=this._def.unknownKeys;if(c==="passthrough")for(const g of o)l.push({key:{status:"valid",value:g},value:{status:"valid",value:n.data[g]}});else if(c==="strict")o.length>0&&(f(n,{code:u.unrecognized_keys,keys:o}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const c=this._def.catchall;for(const g of o){const O=n.data[g];l.push({key:{status:"valid",value:g},value:c._parse(new H(n,O,n.path,g)),alwaysSet:g in n.data})}}return n.common.async?Promise.resolve().then(async()=>{const c=[];for(const g of l){const O=await g.key,A=await g.value;c.push({key:O,value:A,alwaysSet:g.alwaysSet})}return c}).then(c=>$.mergeObjectSync(r,c)):$.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(e){return m.errToObj,new N({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,r)=>{var a,i;const n=((i=(a=this._def).errorMap)==null?void 0:i.call(a,t,r).message)??r.defaultError;return t.code==="unrecognized_keys"?{message:m.errToObj(e).message??n}:{message:n}}}:{}})}strip(){return new N({...this._def,unknownKeys:"strip"})}passthrough(){return new N({...this._def,unknownKeys:"passthrough"})}extend(e){return new N({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new N({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:v.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new N({...this._def,catchall:e})}pick(e){const t={};for(const r of b.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new N({...this._def,shape:()=>t})}omit(e){const t={};for(const r of b.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new N({...this._def,shape:()=>t})}deepPartial(){return ce(this)}partial(e){const t={};for(const r of b.objectKeys(this.shape)){const n=this.shape[r];e&&!e[r]?t[r]=n:t[r]=n.optional()}return new N({...this._def,shape:()=>t})}required(e){const t={};for(const r of b.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let a=this.shape[r];for(;a instanceof se;)a=a._def.innerType;t[r]=a}return new N({...this._def,shape:()=>t})}keyof(){return Ke(b.objectKeys(this.shape))}}N.create=(s,e)=>new N({shape:()=>s,unknownKeys:"strip",catchall:te.create(),typeName:v.ZodObject,...w(e)}),N.strictCreate=(s,e)=>new N({shape:()=>s,unknownKeys:"strict",catchall:te.create(),typeName:v.ZodObject,...w(e)}),N.lazycreate=(s,e)=>new N({shape:s,unknownKeys:"strip",catchall:te.create(),typeName:v.ZodObject,...w(e)});class be extends C{_parse(e){const{ctx:t}=this._processInputParams(e),r=this._def.options;function n(a){for(const o of a)if(o.result.status==="valid")return o.result;for(const o of a)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;const i=a.map(o=>new J(o.ctx.common.issues));return f(t,{code:u.invalid_union,unionErrors:i}),_}if(t.common.async)return Promise.all(r.map(async a=>{const i={...t,common:{...t.common,issues:[]},parent:null};return{result:await a._parseAsync({data:t.data,path:t.path,parent:i}),ctx:i}})).then(n);{let a;const i=[];for(const l of r){const c={...t,common:{...t.common,issues:[]},parent:null},g=l._parseSync({data:t.data,path:t.path,parent:c});if(g.status==="valid")return g;g.status==="dirty"&&!a&&(a={result:g,ctx:c}),c.common.issues.length&&i.push(c.common.issues)}if(a)return t.common.issues.push(...a.ctx.common.issues),a.result;const o=i.map(l=>new J(l));return f(t,{code:u.invalid_union,unionErrors:o}),_}}get options(){return this._def.options}}be.create=(s,e)=>new be({options:s,typeName:v.ZodUnion,...w(e)});function Ae(s,e){const t=ee(s),r=ee(e);if(s===e)return{valid:!0,data:s};if(t===h.object&&r===h.object){const n=b.objectKeys(e),a=b.objectKeys(s).filter(o=>n.indexOf(o)!==-1),i={...s,...e};for(const o of a){const l=Ae(s[o],e[o]);if(!l.valid)return{valid:!1};i[o]=l.data}return{valid:!0,data:i}}else if(t===h.array&&r===h.array){if(s.length!==e.length)return{valid:!1};const n=[];for(let a=0;a<s.length;a++){const i=s[a],o=e[a],l=Ae(i,o);if(!l.valid)return{valid:!1};n.push(l.data)}return{valid:!0,data:n}}else return t===h.date&&r===h.date&&+s==+e?{valid:!0,data:s}:{valid:!1}}class ke extends C{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=(a,i)=>{if(Le(a)||Le(i))return _;const o=Ae(a.value,i.value);return o.valid?((De(a)||De(i))&&t.dirty(),{status:t.value,value:o.data}):(f(r,{code:u.invalid_intersection_types}),_)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([a,i])=>n(a,i)):n(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}ke.create=(s,e,t)=>new ke({left:s,right:e,typeName:v.ZodIntersection,...w(t)});class ne extends C{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==h.array)return f(r,{code:u.invalid_type,expected:h.array,received:r.parsedType}),_;if(r.data.length<this._def.items.length)return f(r,{code:u.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),_;!this._def.rest&&r.data.length>this._def.items.length&&(f(r,{code:u.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const a=[...r.data].map((i,o)=>{const l=this._def.items[o]||this._def.rest;return l?l._parse(new H(r,i,r.path,o)):null}).filter(i=>!!i);return r.common.async?Promise.all(a).then(i=>$.mergeArray(t,i)):$.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new ne({...this._def,rest:e})}}ne.create=(s,e)=>{if(!Array.isArray(s))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ne({items:s,typeName:v.ZodTuple,rest:null,...w(e)})};class we extends C{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==h.object)return f(r,{code:u.invalid_type,expected:h.object,received:r.parsedType}),_;const n=[],a=this._def.keyType,i=this._def.valueType;for(const o in r.data)n.push({key:a._parse(new H(r,o,r.path,o)),value:i._parse(new H(r,r.data[o],r.path,o)),alwaysSet:o in r.data});return r.common.async?$.mergeObjectAsync(t,n):$.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,r){return t instanceof C?new we({keyType:e,valueType:t,typeName:v.ZodRecord,...w(r)}):new we({keyType:Y.create(),valueType:e,typeName:v.ZodRecord,...w(t)})}}class Je extends C{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==h.map)return f(r,{code:u.invalid_type,expected:h.map,received:r.parsedType}),_;const n=this._def.keyType,a=this._def.valueType,i=[...r.data.entries()].map(([o,l],c)=>({key:n._parse(new H(r,o,r.path,[c,"key"])),value:a._parse(new H(r,l,r.path,[c,"value"]))}));if(r.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const l of i){const c=await l.key,g=await l.value;if(c.status==="aborted"||g.status==="aborted")return _;(c.status==="dirty"||g.status==="dirty")&&t.dirty(),o.set(c.value,g.value)}return{status:t.value,value:o}})}else{const o=new Map;for(const l of i){const c=l.key,g=l.value;if(c.status==="aborted"||g.status==="aborted")return _;(c.status==="dirty"||g.status==="dirty")&&t.dirty(),o.set(c.value,g.value)}return{status:t.value,value:o}}}}Je.create=(s,e,t)=>new Je({valueType:e,keyType:s,typeName:v.ZodMap,...w(t)});class ye extends C{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==h.set)return f(r,{code:u.invalid_type,expected:h.set,received:r.parsedType}),_;const n=this._def;n.minSize!==null&&r.data.size<n.minSize.value&&(f(r,{code:u.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()),n.maxSize!==null&&r.data.size>n.maxSize.value&&(f(r,{code:u.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());const a=this._def.valueType;function i(l){const c=new Set;for(const g of l){if(g.status==="aborted")return _;g.status==="dirty"&&t.dirty(),c.add(g.value)}return{status:t.value,value:c}}const o=[...r.data.values()].map((l,c)=>a._parse(new H(r,l,r.path,c)));return r.common.async?Promise.all(o).then(l=>i(l)):i(o)}min(e,t){return new ye({...this._def,minSize:{value:e,message:m.toString(t)}})}max(e,t){return new ye({...this._def,maxSize:{value:e,message:m.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ye.create=(s,e)=>new ye({valueType:s,minSize:null,maxSize:null,typeName:v.ZodSet,...w(e)});class Ye extends C{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}Ye.create=(s,e)=>new Ye({getter:s,typeName:v.ZodLazy,...w(e)});class Qe extends C{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return f(t,{received:t.data,code:u.invalid_literal,expected:this._def.value}),_}return{status:"valid",value:e.data}}get value(){return this._def.value}}Qe.create=(s,e)=>new Qe({value:s,typeName:v.ZodLiteral,...w(e)});function Ke(s,e){return new de({values:s,typeName:v.ZodEnum,...w(e)})}class de extends C{_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),r=this._def.values;return f(t,{expected:b.joinValues(r),received:t.parsedType,code:u.invalid_type}),_}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return f(t,{received:t.data,code:u.invalid_enum_value,options:r}),_}return z(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return de.create(e,{...this._def,...t})}exclude(e,t=this._def){return de.create(this.options.filter(r=>!e.includes(r)),{...this._def,...t})}}de.create=Ke;class et extends C{_parse(e){const t=b.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==h.string&&r.parsedType!==h.number){const n=b.objectValues(t);return f(r,{expected:b.joinValues(n),received:r.parsedType,code:u.invalid_type}),_}if(this._cache||(this._cache=new Set(b.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const n=b.objectValues(t);return f(r,{received:r.data,code:u.invalid_enum_value,options:n}),_}return z(e.data)}get enum(){return this._def.values}}et.create=(s,e)=>new et({values:s,typeName:v.ZodNativeEnum,...w(e)});class xe extends C{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==h.promise&&t.common.async===!1)return f(t,{code:u.invalid_type,expected:h.promise,received:t.parsedType}),_;const r=t.parsedType===h.promise?t.data:Promise.resolve(t.data);return z(r.then(n=>this._def.type.parseAsync(n,{path:t.path,errorMap:t.common.contextualErrorMap})))}}xe.create=(s,e)=>new xe({type:s,typeName:v.ZodPromise,...w(e)});class ue extends C{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===v.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=this._def.effect||null,a={addIssue:i=>{f(r,i),i.fatal?t.abort():t.dirty()},get path(){return r.path}};if(a.addIssue=a.addIssue.bind(a),n.type==="preprocess"){const i=n.transform(r.data,a);if(r.common.async)return Promise.resolve(i).then(async o=>{if(t.value==="aborted")return _;const l=await this._def.schema._parseAsync({data:o,path:r.path,parent:r});return l.status==="aborted"?_:l.status==="dirty"||t.value==="dirty"?pe(l.value):l});{if(t.value==="aborted")return _;const o=this._def.schema._parseSync({data:i,path:r.path,parent:r});return o.status==="aborted"?_:o.status==="dirty"||t.value==="dirty"?pe(o.value):o}}if(n.type==="refinement"){const i=o=>{const l=n.refinement(o,a);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(r.common.async===!1){const o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?_:(o.status==="dirty"&&t.dirty(),i(o.value),{status:t.value,value:o.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>o.status==="aborted"?_:(o.status==="dirty"&&t.dirty(),i(o.value).then(()=>({status:t.value,value:o.value}))))}if(n.type==="transform")if(r.common.async===!1){const i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!ie(i))return _;const o=n.transform(i.value,a);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:o}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>ie(i)?Promise.resolve(n.transform(i.value,a)).then(o=>({status:t.value,value:o})):_);b.assertNever(n)}}ue.create=(s,e,t)=>new ue({schema:s,typeName:v.ZodEffects,effect:e,...w(t)}),ue.createWithPreprocess=(s,e,t)=>new ue({schema:e,effect:{type:"preprocess",transform:s},typeName:v.ZodEffects,...w(t)});class se extends C{_parse(e){return this._getType(e)===h.undefined?z(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}se.create=(s,e)=>new se({innerType:s,typeName:v.ZodOptional,...w(e)});class le extends C{_parse(e){return this._getType(e)===h.null?z(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}le.create=(s,e)=>new le({innerType:s,typeName:v.ZodNullable,...w(e)});class Ee extends C{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===h.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Ee.create=(s,e)=>new Ee({innerType:s,typeName:v.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...w(e)});class Re extends C{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return ve(n)?n.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new J(r.common.issues)},input:r.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new J(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Re.create=(s,e)=>new Re({innerType:s,typeName:v.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...w(e)});class tt extends C{_parse(e){if(this._getType(e)!==h.nan){const r=this._getOrReturnCtx(e);return f(r,{code:u.invalid_type,expected:h.nan,received:r.parsedType}),_}return{status:"valid",value:e.data}}}tt.create=s=>new tt({typeName:v.ZodNaN,...w(s)});class Ft extends C{_parse(e){const{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class Me extends C{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{const a=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?_:a.status==="dirty"?(t.dirty(),pe(a.value)):this._def.out._parseAsync({data:a.value,path:r.path,parent:r})})();{const n=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return n.status==="aborted"?_:n.status==="dirty"?(t.dirty(),{status:"dirty",value:n.value}):this._def.out._parseSync({data:n.value,path:r.path,parent:r})}}static create(e,t){return new Me({in:e,out:t,typeName:v.ZodPipeline})}}class je extends C{_parse(e){const t=this._def.innerType._parse(e),r=n=>(ie(n)&&(n.value=Object.freeze(n.value)),n);return ve(t)?t.then(n=>r(n)):r(t)}unwrap(){return this._def.innerType}}je.create=(s,e)=>new je({innerType:s,typeName:v.ZodReadonly,...w(e)});var v;(function(s){s.ZodString="ZodString",s.ZodNumber="ZodNumber",s.ZodNaN="ZodNaN",s.ZodBigInt="ZodBigInt",s.ZodBoolean="ZodBoolean",s.ZodDate="ZodDate",s.ZodSymbol="ZodSymbol",s.ZodUndefined="ZodUndefined",s.ZodNull="ZodNull",s.ZodAny="ZodAny",s.ZodUnknown="ZodUnknown",s.ZodNever="ZodNever",s.ZodVoid="ZodVoid",s.ZodArray="ZodArray",s.ZodObject="ZodObject",s.ZodUnion="ZodUnion",s.ZodDiscriminatedUnion="ZodDiscriminatedUnion",s.ZodIntersection="ZodIntersection",s.ZodTuple="ZodTuple",s.ZodRecord="ZodRecord",s.ZodMap="ZodMap",s.ZodSet="ZodSet",s.ZodFunction="ZodFunction",s.ZodLazy="ZodLazy",s.ZodLiteral="ZodLiteral",s.ZodEnum="ZodEnum",s.ZodEffects="ZodEffects",s.ZodNativeEnum="ZodNativeEnum",s.ZodOptional="ZodOptional",s.ZodNullable="ZodNullable",s.ZodDefault="ZodDefault",s.ZodCatch="ZodCatch",s.ZodPromise="ZodPromise",s.ZodBranded="ZodBranded",s.ZodPipeline="ZodPipeline",s.ZodReadonly="ZodReadonly"})(v||(v={}));const R=Y.create,X=oe.create;te.create;const I=W.create,L=N.create;be.create,ke.create,ne.create;const Bt=we.create,Ce=de.create;xe.create,se.create,le.create;class st extends Error{constructor(t){const r=`Invalid ChaosConfig:
|
|
1
|
+
(function(E,b){typeof exports=="object"&&typeof module<"u"?b(exports):typeof define=="function"&&define.amd?define(["exports"],b):(E=typeof globalThis<"u"?globalThis:E||self,b(E.ChaosMaker={}))})(this,(function(E){"use strict";var Ss=Object.defineProperty;var Ts=(E,b,re)=>b in E?Ss(E,b,{enumerable:!0,configurable:!0,writable:!0,value:re}):E[b]=re;var Z=(E,b,re)=>Ts(E,typeof b!="symbol"?b+"":b,re);var b;(function(s){s.assertEqual=n=>{};function e(n){}s.assertIs=e;function t(n){throw new Error}s.assertNever=t,s.arrayToEnum=n=>{const a={};for(const i of n)a[i]=i;return a},s.getValidEnumValues=n=>{const a=s.objectKeys(n).filter(o=>typeof n[n[o]]!="number"),i={};for(const o of a)i[o]=n[o];return s.objectValues(i)},s.objectValues=n=>s.objectKeys(n).map(function(a){return n[a]}),s.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{const a=[];for(const i in n)Object.prototype.hasOwnProperty.call(n,i)&&a.push(i);return a},s.find=(n,a)=>{for(const i of n)if(a(i))return i},s.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&Number.isFinite(n)&&Math.floor(n)===n;function r(n,a=" | "){return n.map(i=>typeof i=="string"?`'${i}'`:i).join(a)}s.joinValues=r,s.jsonStringifyReplacer=(n,a)=>typeof a=="bigint"?a.toString():a})(b||(b={}));var re;(function(s){s.mergeShapes=(e,t)=>({...e,...t})})(re||(re={}));const h=b.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ee=s=>{switch(typeof s){case"undefined":return h.undefined;case"string":return h.string;case"number":return Number.isNaN(s)?h.nan:h.number;case"boolean":return h.boolean;case"function":return h.function;case"bigint":return h.bigint;case"symbol":return h.symbol;case"object":return Array.isArray(s)?h.array:s===null?h.null:s.then&&typeof s.then=="function"&&s.catch&&typeof s.catch=="function"?h.promise:typeof Map<"u"&&s instanceof Map?h.map:typeof Set<"u"&&s instanceof Set?h.set:typeof Date<"u"&&s instanceof Date?h.date:h.object;default:return h.unknown}},u=b.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class J extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(a){return a.message},r={_errors:[]},n=a=>{for(const i of a.issues)if(i.code==="invalid_union")i.unionErrors.map(n);else if(i.code==="invalid_return_type")n(i.returnTypeError);else if(i.code==="invalid_arguments")n(i.argumentsError);else if(i.path.length===0)r._errors.push(t(i));else{let o=r,l=0;for(;l<i.path.length;){const c=i.path[l];l===i.path.length-1?(o[c]=o[c]||{_errors:[]},o[c]._errors.push(t(i))):o[c]=o[c]||{_errors:[]},o=o[c],l++}}};return n(this),r}static assert(e){if(!(e instanceof J))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,b.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},r=[];for(const n of this.issues)if(n.path.length>0){const a=n.path[0];t[a]=t[a]||[],t[a].push(e(n))}else r.push(e(n));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}J.create=s=>new J(s);const Oe=(s,e)=>{let t;switch(s.code){case u.invalid_type:s.received===h.undefined?t="Required":t=`Expected ${s.expected}, received ${s.received}`;break;case u.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(s.expected,b.jsonStringifyReplacer)}`;break;case u.unrecognized_keys:t=`Unrecognized key(s) in object: ${b.joinValues(s.keys,", ")}`;break;case u.invalid_union:t="Invalid input";break;case u.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${b.joinValues(s.options)}`;break;case u.invalid_enum_value:t=`Invalid enum value. Expected ${b.joinValues(s.options)}, received '${s.received}'`;break;case u.invalid_arguments:t="Invalid function arguments";break;case u.invalid_return_type:t="Invalid function return type";break;case u.invalid_date:t="Invalid date";break;case u.invalid_string:typeof s.validation=="object"?"includes"in s.validation?(t=`Invalid input: must include "${s.validation.includes}"`,typeof s.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${s.validation.position}`)):"startsWith"in s.validation?t=`Invalid input: must start with "${s.validation.startsWith}"`:"endsWith"in s.validation?t=`Invalid input: must end with "${s.validation.endsWith}"`:b.assertNever(s.validation):s.validation!=="regex"?t=`Invalid ${s.validation}`:t="Invalid";break;case u.too_small:s.type==="array"?t=`Array must contain ${s.exact?"exactly":s.inclusive?"at least":"more than"} ${s.minimum} element(s)`:s.type==="string"?t=`String must contain ${s.exact?"exactly":s.inclusive?"at least":"over"} ${s.minimum} character(s)`:s.type==="number"?t=`Number must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${s.minimum}`:s.type==="bigint"?t=`Number must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${s.minimum}`:s.type==="date"?t=`Date must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(s.minimum))}`:t="Invalid input";break;case u.too_big:s.type==="array"?t=`Array must contain ${s.exact?"exactly":s.inclusive?"at most":"less than"} ${s.maximum} element(s)`:s.type==="string"?t=`String must contain ${s.exact?"exactly":s.inclusive?"at most":"under"} ${s.maximum} character(s)`:s.type==="number"?t=`Number must be ${s.exact?"exactly":s.inclusive?"less than or equal to":"less than"} ${s.maximum}`:s.type==="bigint"?t=`BigInt must be ${s.exact?"exactly":s.inclusive?"less than or equal to":"less than"} ${s.maximum}`:s.type==="date"?t=`Date must be ${s.exact?"exactly":s.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(s.maximum))}`:t="Invalid input";break;case u.custom:t="Invalid input";break;case u.invalid_intersection_types:t="Intersection results could not be merged";break;case u.not_multiple_of:t=`Number must be a multiple of ${s.multipleOf}`;break;case u.not_finite:t="Number must be finite";break;default:t=e.defaultError,b.assertNever(s)}return{message:t}};let _t=Oe;function bt(){return _t}const kt=s=>{const{data:e,path:t,errorMaps:r,issueData:n}=s,a=[...t,...n.path||[]],i={...n,path:a};if(n.message!==void 0)return{...n,path:a,message:n.message};let o="";const l=r.filter(c=>!!c).slice().reverse();for(const c of l)o=c(i,{data:e,defaultError:o}).message;return{...n,path:a,message:o}};function f(s,e){const t=bt(),r=kt({issueData:e,data:s.data,path:s.path,errorMaps:[s.common.contextualErrorMap,s.schemaErrorMap,t,t===Oe?void 0:Oe].filter(n=>!!n)});s.common.issues.push(r)}class ${constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const r=[];for(const n of t){if(n.status==="aborted")return _;n.status==="dirty"&&e.dirty(),r.push(n.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const n of t){const a=await n.key,i=await n.value;r.push({key:a,value:i})}return $.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const n of t){const{key:a,value:i}=n;if(a.status==="aborted"||i.status==="aborted")return _;a.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof i.value<"u"||n.alwaysSet)&&(r[a.value]=i.value)}return{status:e.value,value:r}}}const _=Object.freeze({status:"aborted"}),pe=s=>({status:"dirty",value:s}),z=s=>({status:"valid",value:s}),Le=s=>s.status==="aborted",De=s=>s.status==="dirty",ie=s=>s.status==="valid",ve=s=>typeof Promise<"u"&&s instanceof Promise;var m;(function(s){s.errToObj=e=>typeof e=="string"?{message:e}:e||{},s.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(m||(m={}));class H{constructor(e,t,r,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=n}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Ve=(s,e)=>{if(ie(e))return{success:!0,data:e.value};if(!s.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new J(s.common.issues);return this._error=t,this._error}}};function w(s){if(!s)return{};const{errorMap:e,invalid_type_error:t,required_error:r,description:n}=s;if(e&&(t||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:n}:{errorMap:(i,o)=>{const{message:l}=s;return i.code==="invalid_enum_value"?{message:l??o.defaultError}:typeof o.data>"u"?{message:l??r??o.defaultError}:i.code!=="invalid_type"?{message:o.defaultError}:{message:l??t??o.defaultError}},description:n}}class C{get description(){return this._def.description}_getType(e){return ee(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:ee(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new $,ctx:{common:e.parent.common,data:e.data,parsedType:ee(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(ve(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){const r={common:{issues:[],async:(t==null?void 0:t.async)??!1,contextualErrorMap:t==null?void 0:t.errorMap},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ee(e)},n=this._parseSync({data:e,path:r.path,parent:r});return Ve(r,n)}"~validate"(e){var r,n;const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ee(e)};if(!this["~standard"].async)try{const a=this._parseSync({data:e,path:[],parent:t});return ie(a)?{value:a.value}:{issues:t.common.issues}}catch(a){(n=(r=a==null?void 0:a.message)==null?void 0:r.toLowerCase())!=null&&n.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(a=>ie(a)?{value:a.value}:{issues:t.common.issues})}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:t==null?void 0:t.errorMap,async:!0},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ee(e)},n=this._parse({data:e,path:r.path,parent:r}),a=await(ve(n)?n:Promise.resolve(n));return Ve(r,a)}refine(e,t){const r=n=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(n):t;return this._refinement((n,a)=>{const i=e(n),o=()=>a.addIssue({code:u.custom,...r(n)});return typeof Promise<"u"&&i instanceof Promise?i.then(l=>l?!0:(o(),!1)):i?!0:(o(),!1)})}refinement(e,t){return this._refinement((r,n)=>e(r)?!0:(n.addIssue(typeof t=="function"?t(r,n):t),!1))}_refinement(e){return new ue({schema:this,typeName:v.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return se.create(this,this._def)}nullable(){return le.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return W.create(this)}promise(){return xe.create(this,this._def)}or(e){return be.create([this,e],this._def)}and(e){return ke.create(this,e,this._def)}transform(e){return new ue({...w(this._def),schema:this,typeName:v.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new Ee({...w(this._def),innerType:this,defaultValue:t,typeName:v.ZodDefault})}brand(){return new Ft({typeName:v.ZodBranded,type:this,...w(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new Re({...w(this._def),innerType:this,catchValue:t,typeName:v.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Me.create(this,e)}readonly(){return je.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const wt=/^c[^\s-]{8,}$/i,xt=/^[0-9a-z]+$/,Ct=/^[0-9A-HJKMNP-TV-Z]{26}$/i,St=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Tt=/^[a-z0-9_-]{21}$/i,Ot=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Nt=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,At=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Et="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Ne;const Rt=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Mt=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,jt=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Pt=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Zt=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,$t=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ze="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",It=new RegExp(`^${ze}$`);function Ue(s){let e="[0-5]\\d";s.precision?e=`${e}\\.\\d{${s.precision}}`:s.precision==null&&(e=`${e}(\\.\\d+)?`);const t=s.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function Lt(s){return new RegExp(`^${Ue(s)}$`)}function Dt(s){let e=`${ze}T${Ue(s)}`;const t=[];return t.push(s.local?"Z?":"Z"),s.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Vt(s,e){return!!((e==="v4"||!e)&&Rt.test(s)||(e==="v6"||!e)&&jt.test(s))}function zt(s,e){if(!Ot.test(s))return!1;try{const[t]=s.split(".");if(!t)return!1;const r=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),n=JSON.parse(atob(r));return!(typeof n!="object"||n===null||"typ"in n&&(n==null?void 0:n.typ)!=="JWT"||!n.alg||e&&n.alg!==e)}catch{return!1}}function Ut(s,e){return!!((e==="v4"||!e)&&Mt.test(s)||(e==="v6"||!e)&&Pt.test(s))}class Y extends C{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==h.string){const a=this._getOrReturnCtx(e);return f(a,{code:u.invalid_type,expected:h.string,received:a.parsedType}),_}const r=new $;let n;for(const a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(n=this._getOrReturnCtx(e,n),f(n,{code:u.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),r.dirty());else if(a.kind==="max")e.data.length>a.value&&(n=this._getOrReturnCtx(e,n),f(n,{code:u.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),r.dirty());else if(a.kind==="length"){const i=e.data.length>a.value,o=e.data.length<a.value;(i||o)&&(n=this._getOrReturnCtx(e,n),i?f(n,{code:u.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):o&&f(n,{code:u.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),r.dirty())}else if(a.kind==="email")At.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"email",code:u.invalid_string,message:a.message}),r.dirty());else if(a.kind==="emoji")Ne||(Ne=new RegExp(Et,"u")),Ne.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"emoji",code:u.invalid_string,message:a.message}),r.dirty());else if(a.kind==="uuid")St.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"uuid",code:u.invalid_string,message:a.message}),r.dirty());else if(a.kind==="nanoid")Tt.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"nanoid",code:u.invalid_string,message:a.message}),r.dirty());else if(a.kind==="cuid")wt.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"cuid",code:u.invalid_string,message:a.message}),r.dirty());else if(a.kind==="cuid2")xt.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"cuid2",code:u.invalid_string,message:a.message}),r.dirty());else if(a.kind==="ulid")Ct.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"ulid",code:u.invalid_string,message:a.message}),r.dirty());else if(a.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),f(n,{validation:"url",code:u.invalid_string,message:a.message}),r.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"regex",code:u.invalid_string,message:a.message}),r.dirty())):a.kind==="trim"?e.data=e.data.trim():a.kind==="includes"?e.data.includes(a.value,a.position)||(n=this._getOrReturnCtx(e,n),f(n,{code:u.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),r.dirty()):a.kind==="toLowerCase"?e.data=e.data.toLowerCase():a.kind==="toUpperCase"?e.data=e.data.toUpperCase():a.kind==="startsWith"?e.data.startsWith(a.value)||(n=this._getOrReturnCtx(e,n),f(n,{code:u.invalid_string,validation:{startsWith:a.value},message:a.message}),r.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(n=this._getOrReturnCtx(e,n),f(n,{code:u.invalid_string,validation:{endsWith:a.value},message:a.message}),r.dirty()):a.kind==="datetime"?Dt(a).test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{code:u.invalid_string,validation:"datetime",message:a.message}),r.dirty()):a.kind==="date"?It.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{code:u.invalid_string,validation:"date",message:a.message}),r.dirty()):a.kind==="time"?Lt(a).test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{code:u.invalid_string,validation:"time",message:a.message}),r.dirty()):a.kind==="duration"?Nt.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"duration",code:u.invalid_string,message:a.message}),r.dirty()):a.kind==="ip"?Vt(e.data,a.version)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"ip",code:u.invalid_string,message:a.message}),r.dirty()):a.kind==="jwt"?zt(e.data,a.alg)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"jwt",code:u.invalid_string,message:a.message}),r.dirty()):a.kind==="cidr"?Ut(e.data,a.version)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"cidr",code:u.invalid_string,message:a.message}),r.dirty()):a.kind==="base64"?Zt.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"base64",code:u.invalid_string,message:a.message}),r.dirty()):a.kind==="base64url"?$t.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"base64url",code:u.invalid_string,message:a.message}),r.dirty()):b.assertNever(a);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement(n=>e.test(n),{validation:t,code:u.invalid_string,...m.errToObj(r)})}_addCheck(e){return new Y({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...m.errToObj(e)})}url(e){return this._addCheck({kind:"url",...m.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...m.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...m.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...m.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...m.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...m.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...m.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...m.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...m.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...m.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...m.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...m.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(e==null?void 0:e.offset)??!1,local:(e==null?void 0:e.local)??!1,...m.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...m.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...m.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...m.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t==null?void 0:t.position,...m.errToObj(t==null?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...m.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...m.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...m.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...m.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...m.errToObj(t)})}nonempty(e){return this.min(1,m.errToObj(e))}trim(){return new Y({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Y({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Y({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}Y.create=s=>new Y({checks:[],typeName:v.ZodString,coerce:(s==null?void 0:s.coerce)??!1,...w(s)});function qt(s,e){const t=(s.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,n=t>r?t:r,a=Number.parseInt(s.toFixed(n).replace(".","")),i=Number.parseInt(e.toFixed(n).replace(".",""));return a%i/10**n}class oe extends C{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==h.number){const a=this._getOrReturnCtx(e);return f(a,{code:u.invalid_type,expected:h.number,received:a.parsedType}),_}let r;const n=new $;for(const a of this._def.checks)a.kind==="int"?b.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{code:u.invalid_type,expected:"integer",received:"float",message:a.message}),n.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(r=this._getOrReturnCtx(e,r),f(r,{code:u.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),n.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(r=this._getOrReturnCtx(e,r),f(r,{code:u.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),n.dirty()):a.kind==="multipleOf"?qt(e.data,a.value)!==0&&(r=this._getOrReturnCtx(e,r),f(r,{code:u.not_multiple_of,multipleOf:a.value,message:a.message}),n.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{code:u.not_finite,message:a.message}),n.dirty()):b.assertNever(a);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,m.toString(t))}gt(e,t){return this.setLimit("min",e,!1,m.toString(t))}lte(e,t){return this.setLimit("max",e,!0,m.toString(t))}lt(e,t){return this.setLimit("max",e,!1,m.toString(t))}setLimit(e,t,r,n){return new oe({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:m.toString(n)}]})}_addCheck(e){return new oe({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:m.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:m.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:m.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:m.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:m.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:m.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:m.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:m.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:m.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&b.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(t===null||r.value>t)&&(t=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}}oe.create=s=>new oe({checks:[],typeName:v.ZodNumber,coerce:(s==null?void 0:s.coerce)||!1,...w(s)});class me extends C{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==h.bigint)return this._getInvalidInput(e);let r;const n=new $;for(const a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(r=this._getOrReturnCtx(e,r),f(r,{code:u.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),n.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(r=this._getOrReturnCtx(e,r),f(r,{code:u.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),n.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),f(r,{code:u.not_multiple_of,multipleOf:a.value,message:a.message}),n.dirty()):b.assertNever(a);return{status:n.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:h.bigint,received:t.parsedType}),_}gte(e,t){return this.setLimit("min",e,!0,m.toString(t))}gt(e,t){return this.setLimit("min",e,!1,m.toString(t))}lte(e,t){return this.setLimit("max",e,!0,m.toString(t))}lt(e,t){return this.setLimit("max",e,!1,m.toString(t))}setLimit(e,t,r,n){return new me({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:m.toString(n)}]})}_addCheck(e){return new me({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:m.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:m.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:m.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:m.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:m.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}me.create=s=>new me({checks:[],typeName:v.ZodBigInt,coerce:(s==null?void 0:s.coerce)??!1,...w(s)});class qe extends C{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==h.boolean){const r=this._getOrReturnCtx(e);return f(r,{code:u.invalid_type,expected:h.boolean,received:r.parsedType}),_}return z(e.data)}}qe.create=s=>new qe({typeName:v.ZodBoolean,coerce:(s==null?void 0:s.coerce)||!1,...w(s)});class _e extends C{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==h.date){const a=this._getOrReturnCtx(e);return f(a,{code:u.invalid_type,expected:h.date,received:a.parsedType}),_}if(Number.isNaN(e.data.getTime())){const a=this._getOrReturnCtx(e);return f(a,{code:u.invalid_date}),_}const r=new $;let n;for(const a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(n=this._getOrReturnCtx(e,n),f(n,{code:u.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),r.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(n=this._getOrReturnCtx(e,n),f(n,{code:u.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),r.dirty()):b.assertNever(a);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new _e({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:m.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:m.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}_e.create=s=>new _e({checks:[],coerce:(s==null?void 0:s.coerce)||!1,typeName:v.ZodDate,...w(s)});class Fe extends C{_parse(e){if(this._getType(e)!==h.symbol){const r=this._getOrReturnCtx(e);return f(r,{code:u.invalid_type,expected:h.symbol,received:r.parsedType}),_}return z(e.data)}}Fe.create=s=>new Fe({typeName:v.ZodSymbol,...w(s)});class Be extends C{_parse(e){if(this._getType(e)!==h.undefined){const r=this._getOrReturnCtx(e);return f(r,{code:u.invalid_type,expected:h.undefined,received:r.parsedType}),_}return z(e.data)}}Be.create=s=>new Be({typeName:v.ZodUndefined,...w(s)});class He extends C{_parse(e){if(this._getType(e)!==h.null){const r=this._getOrReturnCtx(e);return f(r,{code:u.invalid_type,expected:h.null,received:r.parsedType}),_}return z(e.data)}}He.create=s=>new He({typeName:v.ZodNull,...w(s)});class We extends C{constructor(){super(...arguments),this._any=!0}_parse(e){return z(e.data)}}We.create=s=>new We({typeName:v.ZodAny,...w(s)});class Xe extends C{constructor(){super(...arguments),this._unknown=!0}_parse(e){return z(e.data)}}Xe.create=s=>new Xe({typeName:v.ZodUnknown,...w(s)});class te extends C{_parse(e){const t=this._getOrReturnCtx(e);return f(t,{code:u.invalid_type,expected:h.never,received:t.parsedType}),_}}te.create=s=>new te({typeName:v.ZodNever,...w(s)});class Ge extends C{_parse(e){if(this._getType(e)!==h.undefined){const r=this._getOrReturnCtx(e);return f(r,{code:u.invalid_type,expected:h.void,received:r.parsedType}),_}return z(e.data)}}Ge.create=s=>new Ge({typeName:v.ZodVoid,...w(s)});class W extends C{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),n=this._def;if(t.parsedType!==h.array)return f(t,{code:u.invalid_type,expected:h.array,received:t.parsedType}),_;if(n.exactLength!==null){const i=t.data.length>n.exactLength.value,o=t.data.length<n.exactLength.value;(i||o)&&(f(t,{code:i?u.too_big:u.too_small,minimum:o?n.exactLength.value:void 0,maximum:i?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),r.dirty())}if(n.minLength!==null&&t.data.length<n.minLength.value&&(f(t,{code:u.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),r.dirty()),n.maxLength!==null&&t.data.length>n.maxLength.value&&(f(t,{code:u.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((i,o)=>n.type._parseAsync(new H(t,i,t.path,o)))).then(i=>$.mergeArray(r,i));const a=[...t.data].map((i,o)=>n.type._parseSync(new H(t,i,t.path,o)));return $.mergeArray(r,a)}get element(){return this._def.type}min(e,t){return new W({...this._def,minLength:{value:e,message:m.toString(t)}})}max(e,t){return new W({...this._def,maxLength:{value:e,message:m.toString(t)}})}length(e,t){return new W({...this._def,exactLength:{value:e,message:m.toString(t)}})}nonempty(e){return this.min(1,e)}}W.create=(s,e)=>new W({type:s,minLength:null,maxLength:null,exactLength:null,typeName:v.ZodArray,...w(e)});function ce(s){if(s instanceof N){const e={};for(const t in s.shape){const r=s.shape[t];e[t]=se.create(ce(r))}return new N({...s._def,shape:()=>e})}else return s instanceof W?new W({...s._def,type:ce(s.element)}):s instanceof se?se.create(ce(s.unwrap())):s instanceof le?le.create(ce(s.unwrap())):s instanceof ne?ne.create(s.items.map(e=>ce(e))):s}class N extends C{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),t=b.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==h.object){const c=this._getOrReturnCtx(e);return f(c,{code:u.invalid_type,expected:h.object,received:c.parsedType}),_}const{status:r,ctx:n}=this._processInputParams(e),{shape:a,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof te&&this._def.unknownKeys==="strip"))for(const c in n.data)i.includes(c)||o.push(c);const l=[];for(const c of i){const g=a[c],O=n.data[c];l.push({key:{status:"valid",value:c},value:g._parse(new H(n,O,n.path,c)),alwaysSet:c in n.data})}if(this._def.catchall instanceof te){const c=this._def.unknownKeys;if(c==="passthrough")for(const g of o)l.push({key:{status:"valid",value:g},value:{status:"valid",value:n.data[g]}});else if(c==="strict")o.length>0&&(f(n,{code:u.unrecognized_keys,keys:o}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const c=this._def.catchall;for(const g of o){const O=n.data[g];l.push({key:{status:"valid",value:g},value:c._parse(new H(n,O,n.path,g)),alwaysSet:g in n.data})}}return n.common.async?Promise.resolve().then(async()=>{const c=[];for(const g of l){const O=await g.key,A=await g.value;c.push({key:O,value:A,alwaysSet:g.alwaysSet})}return c}).then(c=>$.mergeObjectSync(r,c)):$.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(e){return m.errToObj,new N({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,r)=>{var a,i;const n=((i=(a=this._def).errorMap)==null?void 0:i.call(a,t,r).message)??r.defaultError;return t.code==="unrecognized_keys"?{message:m.errToObj(e).message??n}:{message:n}}}:{}})}strip(){return new N({...this._def,unknownKeys:"strip"})}passthrough(){return new N({...this._def,unknownKeys:"passthrough"})}extend(e){return new N({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new N({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:v.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new N({...this._def,catchall:e})}pick(e){const t={};for(const r of b.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new N({...this._def,shape:()=>t})}omit(e){const t={};for(const r of b.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new N({...this._def,shape:()=>t})}deepPartial(){return ce(this)}partial(e){const t={};for(const r of b.objectKeys(this.shape)){const n=this.shape[r];e&&!e[r]?t[r]=n:t[r]=n.optional()}return new N({...this._def,shape:()=>t})}required(e){const t={};for(const r of b.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let a=this.shape[r];for(;a instanceof se;)a=a._def.innerType;t[r]=a}return new N({...this._def,shape:()=>t})}keyof(){return Ke(b.objectKeys(this.shape))}}N.create=(s,e)=>new N({shape:()=>s,unknownKeys:"strip",catchall:te.create(),typeName:v.ZodObject,...w(e)}),N.strictCreate=(s,e)=>new N({shape:()=>s,unknownKeys:"strict",catchall:te.create(),typeName:v.ZodObject,...w(e)}),N.lazycreate=(s,e)=>new N({shape:s,unknownKeys:"strip",catchall:te.create(),typeName:v.ZodObject,...w(e)});class be extends C{_parse(e){const{ctx:t}=this._processInputParams(e),r=this._def.options;function n(a){for(const o of a)if(o.result.status==="valid")return o.result;for(const o of a)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;const i=a.map(o=>new J(o.ctx.common.issues));return f(t,{code:u.invalid_union,unionErrors:i}),_}if(t.common.async)return Promise.all(r.map(async a=>{const i={...t,common:{...t.common,issues:[]},parent:null};return{result:await a._parseAsync({data:t.data,path:t.path,parent:i}),ctx:i}})).then(n);{let a;const i=[];for(const l of r){const c={...t,common:{...t.common,issues:[]},parent:null},g=l._parseSync({data:t.data,path:t.path,parent:c});if(g.status==="valid")return g;g.status==="dirty"&&!a&&(a={result:g,ctx:c}),c.common.issues.length&&i.push(c.common.issues)}if(a)return t.common.issues.push(...a.ctx.common.issues),a.result;const o=i.map(l=>new J(l));return f(t,{code:u.invalid_union,unionErrors:o}),_}}get options(){return this._def.options}}be.create=(s,e)=>new be({options:s,typeName:v.ZodUnion,...w(e)});function Ae(s,e){const t=ee(s),r=ee(e);if(s===e)return{valid:!0,data:s};if(t===h.object&&r===h.object){const n=b.objectKeys(e),a=b.objectKeys(s).filter(o=>n.indexOf(o)!==-1),i={...s,...e};for(const o of a){const l=Ae(s[o],e[o]);if(!l.valid)return{valid:!1};i[o]=l.data}return{valid:!0,data:i}}else if(t===h.array&&r===h.array){if(s.length!==e.length)return{valid:!1};const n=[];for(let a=0;a<s.length;a++){const i=s[a],o=e[a],l=Ae(i,o);if(!l.valid)return{valid:!1};n.push(l.data)}return{valid:!0,data:n}}else return t===h.date&&r===h.date&&+s==+e?{valid:!0,data:s}:{valid:!1}}class ke extends C{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=(a,i)=>{if(Le(a)||Le(i))return _;const o=Ae(a.value,i.value);return o.valid?((De(a)||De(i))&&t.dirty(),{status:t.value,value:o.data}):(f(r,{code:u.invalid_intersection_types}),_)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([a,i])=>n(a,i)):n(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}ke.create=(s,e,t)=>new ke({left:s,right:e,typeName:v.ZodIntersection,...w(t)});class ne extends C{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==h.array)return f(r,{code:u.invalid_type,expected:h.array,received:r.parsedType}),_;if(r.data.length<this._def.items.length)return f(r,{code:u.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),_;!this._def.rest&&r.data.length>this._def.items.length&&(f(r,{code:u.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const a=[...r.data].map((i,o)=>{const l=this._def.items[o]||this._def.rest;return l?l._parse(new H(r,i,r.path,o)):null}).filter(i=>!!i);return r.common.async?Promise.all(a).then(i=>$.mergeArray(t,i)):$.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new ne({...this._def,rest:e})}}ne.create=(s,e)=>{if(!Array.isArray(s))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ne({items:s,typeName:v.ZodTuple,rest:null,...w(e)})};class we extends C{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==h.object)return f(r,{code:u.invalid_type,expected:h.object,received:r.parsedType}),_;const n=[],a=this._def.keyType,i=this._def.valueType;for(const o in r.data)n.push({key:a._parse(new H(r,o,r.path,o)),value:i._parse(new H(r,r.data[o],r.path,o)),alwaysSet:o in r.data});return r.common.async?$.mergeObjectAsync(t,n):$.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,r){return t instanceof C?new we({keyType:e,valueType:t,typeName:v.ZodRecord,...w(r)}):new we({keyType:Y.create(),valueType:e,typeName:v.ZodRecord,...w(t)})}}class Je extends C{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==h.map)return f(r,{code:u.invalid_type,expected:h.map,received:r.parsedType}),_;const n=this._def.keyType,a=this._def.valueType,i=[...r.data.entries()].map(([o,l],c)=>({key:n._parse(new H(r,o,r.path,[c,"key"])),value:a._parse(new H(r,l,r.path,[c,"value"]))}));if(r.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const l of i){const c=await l.key,g=await l.value;if(c.status==="aborted"||g.status==="aborted")return _;(c.status==="dirty"||g.status==="dirty")&&t.dirty(),o.set(c.value,g.value)}return{status:t.value,value:o}})}else{const o=new Map;for(const l of i){const c=l.key,g=l.value;if(c.status==="aborted"||g.status==="aborted")return _;(c.status==="dirty"||g.status==="dirty")&&t.dirty(),o.set(c.value,g.value)}return{status:t.value,value:o}}}}Je.create=(s,e,t)=>new Je({valueType:e,keyType:s,typeName:v.ZodMap,...w(t)});class ye extends C{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==h.set)return f(r,{code:u.invalid_type,expected:h.set,received:r.parsedType}),_;const n=this._def;n.minSize!==null&&r.data.size<n.minSize.value&&(f(r,{code:u.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()),n.maxSize!==null&&r.data.size>n.maxSize.value&&(f(r,{code:u.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());const a=this._def.valueType;function i(l){const c=new Set;for(const g of l){if(g.status==="aborted")return _;g.status==="dirty"&&t.dirty(),c.add(g.value)}return{status:t.value,value:c}}const o=[...r.data.values()].map((l,c)=>a._parse(new H(r,l,r.path,c)));return r.common.async?Promise.all(o).then(l=>i(l)):i(o)}min(e,t){return new ye({...this._def,minSize:{value:e,message:m.toString(t)}})}max(e,t){return new ye({...this._def,maxSize:{value:e,message:m.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ye.create=(s,e)=>new ye({valueType:s,minSize:null,maxSize:null,typeName:v.ZodSet,...w(e)});class Ye extends C{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}Ye.create=(s,e)=>new Ye({getter:s,typeName:v.ZodLazy,...w(e)});class Qe extends C{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return f(t,{received:t.data,code:u.invalid_literal,expected:this._def.value}),_}return{status:"valid",value:e.data}}get value(){return this._def.value}}Qe.create=(s,e)=>new Qe({value:s,typeName:v.ZodLiteral,...w(e)});function Ke(s,e){return new de({values:s,typeName:v.ZodEnum,...w(e)})}class de extends C{_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),r=this._def.values;return f(t,{expected:b.joinValues(r),received:t.parsedType,code:u.invalid_type}),_}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return f(t,{received:t.data,code:u.invalid_enum_value,options:r}),_}return z(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return de.create(e,{...this._def,...t})}exclude(e,t=this._def){return de.create(this.options.filter(r=>!e.includes(r)),{...this._def,...t})}}de.create=Ke;class et extends C{_parse(e){const t=b.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==h.string&&r.parsedType!==h.number){const n=b.objectValues(t);return f(r,{expected:b.joinValues(n),received:r.parsedType,code:u.invalid_type}),_}if(this._cache||(this._cache=new Set(b.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const n=b.objectValues(t);return f(r,{received:r.data,code:u.invalid_enum_value,options:n}),_}return z(e.data)}get enum(){return this._def.values}}et.create=(s,e)=>new et({values:s,typeName:v.ZodNativeEnum,...w(e)});class xe extends C{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==h.promise&&t.common.async===!1)return f(t,{code:u.invalid_type,expected:h.promise,received:t.parsedType}),_;const r=t.parsedType===h.promise?t.data:Promise.resolve(t.data);return z(r.then(n=>this._def.type.parseAsync(n,{path:t.path,errorMap:t.common.contextualErrorMap})))}}xe.create=(s,e)=>new xe({type:s,typeName:v.ZodPromise,...w(e)});class ue extends C{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===v.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=this._def.effect||null,a={addIssue:i=>{f(r,i),i.fatal?t.abort():t.dirty()},get path(){return r.path}};if(a.addIssue=a.addIssue.bind(a),n.type==="preprocess"){const i=n.transform(r.data,a);if(r.common.async)return Promise.resolve(i).then(async o=>{if(t.value==="aborted")return _;const l=await this._def.schema._parseAsync({data:o,path:r.path,parent:r});return l.status==="aborted"?_:l.status==="dirty"||t.value==="dirty"?pe(l.value):l});{if(t.value==="aborted")return _;const o=this._def.schema._parseSync({data:i,path:r.path,parent:r});return o.status==="aborted"?_:o.status==="dirty"||t.value==="dirty"?pe(o.value):o}}if(n.type==="refinement"){const i=o=>{const l=n.refinement(o,a);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(r.common.async===!1){const o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?_:(o.status==="dirty"&&t.dirty(),i(o.value),{status:t.value,value:o.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>o.status==="aborted"?_:(o.status==="dirty"&&t.dirty(),i(o.value).then(()=>({status:t.value,value:o.value}))))}if(n.type==="transform")if(r.common.async===!1){const i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!ie(i))return _;const o=n.transform(i.value,a);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:o}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>ie(i)?Promise.resolve(n.transform(i.value,a)).then(o=>({status:t.value,value:o})):_);b.assertNever(n)}}ue.create=(s,e,t)=>new ue({schema:s,typeName:v.ZodEffects,effect:e,...w(t)}),ue.createWithPreprocess=(s,e,t)=>new ue({schema:e,effect:{type:"preprocess",transform:s},typeName:v.ZodEffects,...w(t)});class se extends C{_parse(e){return this._getType(e)===h.undefined?z(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}se.create=(s,e)=>new se({innerType:s,typeName:v.ZodOptional,...w(e)});class le extends C{_parse(e){return this._getType(e)===h.null?z(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}le.create=(s,e)=>new le({innerType:s,typeName:v.ZodNullable,...w(e)});class Ee extends C{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===h.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Ee.create=(s,e)=>new Ee({innerType:s,typeName:v.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...w(e)});class Re extends C{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return ve(n)?n.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new J(r.common.issues)},input:r.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new J(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Re.create=(s,e)=>new Re({innerType:s,typeName:v.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...w(e)});class tt extends C{_parse(e){if(this._getType(e)!==h.nan){const r=this._getOrReturnCtx(e);return f(r,{code:u.invalid_type,expected:h.nan,received:r.parsedType}),_}return{status:"valid",value:e.data}}}tt.create=s=>new tt({typeName:v.ZodNaN,...w(s)});class Ft extends C{_parse(e){const{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class Me extends C{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{const a=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?_:a.status==="dirty"?(t.dirty(),pe(a.value)):this._def.out._parseAsync({data:a.value,path:r.path,parent:r})})();{const n=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return n.status==="aborted"?_:n.status==="dirty"?(t.dirty(),{status:"dirty",value:n.value}):this._def.out._parseSync({data:n.value,path:r.path,parent:r})}}static create(e,t){return new Me({in:e,out:t,typeName:v.ZodPipeline})}}class je extends C{_parse(e){const t=this._def.innerType._parse(e),r=n=>(ie(n)&&(n.value=Object.freeze(n.value)),n);return ve(t)?t.then(n=>r(n)):r(t)}unwrap(){return this._def.innerType}}je.create=(s,e)=>new je({innerType:s,typeName:v.ZodReadonly,...w(e)});var v;(function(s){s.ZodString="ZodString",s.ZodNumber="ZodNumber",s.ZodNaN="ZodNaN",s.ZodBigInt="ZodBigInt",s.ZodBoolean="ZodBoolean",s.ZodDate="ZodDate",s.ZodSymbol="ZodSymbol",s.ZodUndefined="ZodUndefined",s.ZodNull="ZodNull",s.ZodAny="ZodAny",s.ZodUnknown="ZodUnknown",s.ZodNever="ZodNever",s.ZodVoid="ZodVoid",s.ZodArray="ZodArray",s.ZodObject="ZodObject",s.ZodUnion="ZodUnion",s.ZodDiscriminatedUnion="ZodDiscriminatedUnion",s.ZodIntersection="ZodIntersection",s.ZodTuple="ZodTuple",s.ZodRecord="ZodRecord",s.ZodMap="ZodMap",s.ZodSet="ZodSet",s.ZodFunction="ZodFunction",s.ZodLazy="ZodLazy",s.ZodLiteral="ZodLiteral",s.ZodEnum="ZodEnum",s.ZodEffects="ZodEffects",s.ZodNativeEnum="ZodNativeEnum",s.ZodOptional="ZodOptional",s.ZodNullable="ZodNullable",s.ZodDefault="ZodDefault",s.ZodCatch="ZodCatch",s.ZodPromise="ZodPromise",s.ZodBranded="ZodBranded",s.ZodPipeline="ZodPipeline",s.ZodReadonly="ZodReadonly"})(v||(v={}));const R=Y.create,X=oe.create;te.create;const I=W.create,L=N.create;be.create,ke.create,ne.create;const Bt=we.create,Ce=de.create;xe.create,se.create,le.create;class st extends Error{constructor(t){const r=`Invalid ChaosConfig:
|
|
2
2
|
${t.map(n=>` - ${n}`).join(`
|
|
3
|
-
`)}`;super(r);Z(this,"issues");this.name="ChaosConfigError",this.issues=t}}const G=X().min(0,"Probability must be >= 0").max(1,"Probability must be <= 1"),rt=X().int().min(1),Q={onNth:rt.optional(),everyNth:rt.optional(),afterN:X().int().min(0).optional()},K=[s=>[s.onNth,s.everyNth,s.afterN].filter(e=>e!==void 0).length<=1,{message:"Only one of onNth, everyNth, or afterN may be set on a single rule"}],Ht=L({urlPattern:R().min(1,"urlPattern must not be empty"),methods:I(R()).optional(),statusCode:X().int().min(100).max(599),probability:G,body:R().optional(),statusText:R().optional(),headers:Bt(R()).optional(),...Q}).strict().refine(...K),Wt=L({urlPattern:R().min(1,"urlPattern must not be empty"),methods:I(R()).optional(),delayMs:X().min(0,"delayMs must be >= 0"),probability:G,...Q}).strict().refine(...K),Xt=L({urlPattern:R().min(1,"urlPattern must not be empty"),methods:I(R()).optional(),probability:G,timeout:X().min(0,"timeout must be >= 0").optional(),...Q}).strict().refine(...K),Gt=L({urlPattern:R().min(1,"urlPattern must not be empty"),methods:I(R()).optional(),probability:G,strategy:Ce(["truncate","malformed-json","empty","wrong-type"]),...Q}).strict().refine(...K),Jt=L({urlPattern:R().min(1,"urlPattern must not be empty"),methods:I(R()).optional(),probability:G,...Q}).strict().refine(...K),Yt=L({failures:I(Ht).optional(),latencies:I(Wt).optional(),aborts:I(Xt).optional(),corruptions:I(Gt).optional(),cors:I(Jt).optional()}).strict(),Qt=L({selector:R().min(1,"selector must not be empty"),action:Ce(["disable","hide","remove"]),probability:G}).strict(),Kt=L({assaults:I(Qt).optional()}).strict(),Pe=Ce(["inbound","outbound","both"]),es=L({urlPattern:R().min(1,"urlPattern must not be empty"),direction:Pe,probability:G,...Q}).strict().refine(...K),ts=L({urlPattern:R().min(1,"urlPattern must not be empty"),direction:Pe,delayMs:X().min(0,"delayMs must be >= 0"),probability:G,...Q}).strict().refine(...K),ss=L({urlPattern:R().min(1,"urlPattern must not be empty"),direction:Pe,strategy:Ce(["truncate","malformed-json","empty","wrong-type"]),probability:G,...Q}).strict().refine(...K),rs=X().int().refine(s=>s===1e3||s>=3e3&&s<=4999,{message:"code must be 1000 or in the range 3000-4999"}),ns=R().refine(s=>new TextEncoder().encode(s).length<=123,{message:"reason must be <= 123 UTF-8 bytes"}),as=L({urlPattern:R().min(1,"urlPattern must not be empty"),code:rs.optional(),reason:ns.optional(),afterMs:X().min(0,"afterMs must be >= 0").optional(),probability:G,...Q}).strict().refine(...K),is=L({drops:I(es).optional(),delays:I(ts).optional(),corruptions:I(ss).optional(),closes:I(as).optional()}).strict(),os=L({network:Yt.optional(),ui:Kt.optional(),websocket:is.optional(),seed:X().int("Seed must be an integer").optional()}).strict();function nt(s){const e=os.safeParse(s);if(!e.success){const t=e.error.issues.map(r=>`${r.path.join(".")}: ${r.message}`);throw new st(t)}return e.data}function cs(s){let e=s|0;return()=>{e=e+1831565813|0;let t=Math.imul(e^e>>>15,1|e);return t=t+Math.imul(t^t>>>7,61|t)^t,((t^t>>>14)>>>0)/4294967296}}function at(){return Math.random()*4294967296>>>0}function it(s){const e=s??at();return{random:cs(e),seed:e}}class ot{constructor(e=2e3){Z(this,"listeners",new Map);Z(this,"log",[]);this.maxLogEntries=e}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t)}off(e,t){var r;(r=this.listeners.get(e))==null||r.delete(t)}emit(e){this.log.push(e),this.log.length>this.maxLogEntries&&this.log.shift(),this.notify(this.listeners.get(e.type),e),this.notify(this.listeners.get("*"),e)}getLog(){return[...this.log]}clearLog(){this.log=[]}notify(e,t){if(e)for(const r of e)try{r(t)}catch{}}}function D(s,e=Math.random){return e()<s}function U(s,e){const t=(e.get(s)??0)+1;return e.set(s,t),t}function q(s,e){return s.onNth!==void 0?e===s.onNth:s.everyNth!==void 0?e%s.everyNth===0:s.afterN!==void 0?e>s.afterN:!0}function F(s,e){return e==="*"?!0:s.includes(e)}function ct(s,e){switch(e){case"truncate":return s.slice(0,Math.max(0,Math.floor(s.length/2)));case"malformed-json":return`${s}"}`;case"empty":return"";case"wrong-type":return"<html><body>Unexpected HTML</body></html>"}}function Ze(s){return typeof Request<"u"&&s instanceof Request}function ds(s){return Ze(s)?s.url:s.toString()}function us(s,e){return e!=null&&e.method?e.method.toUpperCase():Ze(s)?s.method.toUpperCase():"GET"}function ls(s,e){if(e!=null&&e.signal)return e.signal;if(Ze(s))return s.signal}function fs(){if(typeof DOMException<"u")return new DOMException("The user aborted a request.","AbortError");const s=new Error("The user aborted a request.");return s.name="AbortError",s}function hs(s,e){if(!e)return s;const t=new AbortController,r=o=>{i(),t.signal.aborted||t.abort(o.reason)},n=()=>r(s),a=()=>r(e),i=()=>{s.removeEventListener("abort",n),e.removeEventListener("abort",a)};return s.aborted?(r(s),t.signal):e.aborted?(r(e),t.signal):(s.addEventListener("abort",n,{once:!0}),e.addEventListener("abort",a,{once:!0}),t.signal)}function ps(s,e){return e?{...s??{},signal:e}:s}function dt(s,e,t,r,n){s==null||s.emit({type:"network:abort",timestamp:Date.now(),applied:n,detail:{url:t,method:r,timeoutMs:e.timeout}})}function Se(s,e,t,r,n){s==null||s.emit({type:"network:corruption",timestamp:Date.now(),applied:n,detail:{url:t,method:r,strategy:e.strategy}})}function ms(s,e,t,r=Math.random,n=new Map){return async(a,i)=>{const o=ds(a),l=us(a,i),c=ls(a,i);if(e.cors){for(const d of e.cors)if(F(o,d.urlPattern)&&(!d.methods||d.methods.includes(l))){const k=U(d,n);if(!q(d,k))continue;const x=D(d.probability,r);if(t==null||t.emit({type:"network:cors",timestamp:Date.now(),applied:x,detail:{url:o,method:l}}),x){console.debug(`[chaos-maker] CORS block: ${l} ${o}`);const S=new TypeError("Failed to fetch");throw S.stack="",S}}}let g=null,O,A,j=!1;const M=d=>{!g||j||(j=!0,A&&(clearTimeout(A),A=void 0),dt(t,g,o,l,d))};if(e.aborts){for(const d of e.aborts)if(F(o,d.urlPattern)&&(!d.methods||d.methods.includes(l))){const k=U(d,n);if(!q(d,k))continue;if(!D(d.probability,r)){dt(t,d,o,l,!1);continue}console.warn(`CHAOS: Aborting ${l} ${o} after ${d.timeout||0}ms`),g=d;const S=new AbortController;O=hs(S.signal,c);const T=()=>{j||(M(!0),S.abort(fs()))};d.timeout?A=setTimeout(T,d.timeout):T();break}}if(g)try{const d=await s(a,ps(i,O));return M(!1),d}catch(d){throw M(!1),d}if(e.failures){for(const d of e.failures)if(F(o,d.urlPattern)&&(!d.methods||d.methods.includes(l))){const k=U(d,n);if(!q(d,k))continue;const x=D(d.probability,r);if(t==null||t.emit({type:"network:failure",timestamp:Date.now(),applied:x,detail:{url:o,method:l,statusCode:d.statusCode}}),x){console.warn(`CHAOS: Forcing ${d.statusCode} for ${l} ${o}`);const S=d.body??JSON.stringify({error:"Chaos Maker Attack!"}),T=d.headers??{};return new Response(S,{status:d.statusCode,statusText:d.statusText??"Service Unavailable (Chaos)",headers:T})}}}if(e.latencies){for(const d of e.latencies)if(F(o,d.urlPattern)&&(!d.methods||d.methods.includes(l))){const k=U(d,n);if(!q(d,k))continue;const x=D(d.probability,r);t==null||t.emit({type:"network:latency",timestamp:Date.now(),applied:x,detail:{url:o,method:l,delayMs:d.delayMs}}),x&&(console.warn(`CHAOS: Adding ${d.delayMs}ms latency to ${l} ${o}`),await new Promise(S=>setTimeout(S,d.delayMs)))}}let y=null;if(e.corruptions){for(const d of e.corruptions)if(F(o,d.urlPattern)&&(!d.methods||d.methods.includes(l))){const k=U(d,n);if(!q(d,k))continue;if(!D(d.probability,r)){Se(t,d,o,l,!1);continue}y=d;break}}let p;try{p=await s(a,i)}catch(d){throw y&&Se(t,y,o,l,!1),d}if(!y)return p;try{console.warn(`CHAOS: Corrupting response for ${l} ${o} with strategy: ${y.strategy}`);const d=await p.text(),k=ct(d,y.strategy);return Se(t,y,o,l,!0),new Response(k,{status:p.status,statusText:p.statusText,headers:p.headers})}catch(d){throw Se(t,y,o,l,!1),d}}}function ut(s,e,t,r,n){s==null||s.emit({type:"network:abort",timestamp:Date.now(),applied:n,detail:{url:t,method:r,timeoutMs:e.timeout}})}function lt(s,e,t,r,n){s==null||s.emit({type:"network:corruption",timestamp:Date.now(),applied:n,detail:{url:t,method:r,strategy:e.strategy}})}function ys(s,e,t,r=Math.random,n=new Map){return function(a){const i=this._chaos_url,o=this._chaos_method;if(e.cors){for(const c of e.cors)if(F(i,c.urlPattern)&&(!c.methods||c.methods.includes(o))){const g=U(c,n);if(!q(c,g))continue;const O=D(c.probability,r);if(t==null||t.emit({type:"network:cors",timestamp:Date.now(),applied:O,detail:{url:i,method:o}}),O){console.debug(`[chaos-maker] CORS block: ${o} ${i}`),Object.defineProperty(this,"status",{value:0}),Object.defineProperty(this,"statusText",{value:""}),this.dispatchEvent(new Event("error")),this.dispatchEvent(new Event("loadend"));return}}}if(e.aborts){for(const c of e.aborts)if(F(i,c.urlPattern)&&(!c.methods||c.methods.includes(o))){const g=U(c,n);if(!q(c,g))continue;if(!D(c.probability,r)){ut(t,c,i,o,!1);continue}console.warn(`CHAOS: Aborting ${o} ${i} after ${c.timeout||0}ms`);let A=!1,j;const M=()=>{j&&(clearTimeout(j),j=void 0),typeof this.removeEventListener=="function"&&this.removeEventListener("loadend",p)},y=k=>{A||(A=!0,M(),ut(t,c,i,o,k))},p=()=>{y(!1)},d=()=>{A||(y(!0),this.abort())};typeof this.addEventListener=="function"&&this.addEventListener("loadend",p);try{s.call(this,a)}catch(k){throw y(!1),k}if(A)return;c.timeout?j=setTimeout(d,c.timeout):d();return}}if(e.failures){for(const c of e.failures)if(F(i,c.urlPattern)&&(!c.methods||c.methods.includes(o))){const g=U(c,n);if(!q(c,g))continue;const O=D(c.probability,r);if(t==null||t.emit({type:"network:failure",timestamp:Date.now(),applied:O,detail:{url:i,method:o,statusCode:c.statusCode}}),O){console.warn(`CHAOS: Forcing ${c.statusCode} for ${o} ${i}`),Object.defineProperty(this,"status",{value:c.statusCode}),Object.defineProperty(this,"statusText",{value:c.statusText??"Service Unavailable (Chaos)"});const A=c.body??JSON.stringify({error:"Chaos Maker Attack!"});Object.defineProperty(this,"responseText",{value:A,configurable:!0});const j=c.headers??{};Object.defineProperty(this,"getResponseHeader",{value:M=>{const y=Object.keys(j).find(p=>p.toLowerCase()===M.toLowerCase());return y?j[y]:null},configurable:!0}),Object.defineProperty(this,"getAllResponseHeaders",{value:()=>Object.entries(j).map(([M,y])=>`${M}: ${y}`).join(`\r
|
|
4
|
-
`),configurable:!0}),this.dispatchEvent(new Event("error")),this.dispatchEvent(new Event("load")),this.dispatchEvent(new Event("loadend"));return}}}let l=null;if(e.corruptions){for(const c of e.corruptions)if(F(i,c.urlPattern)&&(!c.methods||c.methods.includes(o))){const g=U(c,n);if(!q(c,g))continue;if(!D(c.probability,r)){lt(t,c,i,o,!1);continue}l=c;break}}if(l){let c=!1,g=null;const O=()=>{typeof this.removeEventListener=="function"&&(this.removeEventListener("error",M),this.removeEventListener("abort",M),this.removeEventListener("loadend",y))},A=p=>{c||(c=!0,lt(t,l,i,o,p),O())},j=()=>{if(g!==null)return g;delete this.responseText;try{const p=this.responseText;return typeof p!="string"?(Object.defineProperty(this,"responseText",{value:p,configurable:!0}),A(!1),p):(g=ct(p,l.strategy),Object.defineProperty(this,"responseText",{value:g,configurable:!0}),A(!0),g)}catch(p){throw A(!1),p}},M=()=>{A(!1)},y=()=>{if(!c)try{j()}catch{}};typeof this.addEventListener=="function"&&(this.addEventListener("error",M),this.addEventListener("abort",M),this.addEventListener("loadend",y)),Object.defineProperty(this,"responseText",{get(){return j()},configurable:!0})}if(e.latencies){for(const c of e.latencies)if(F(i,c.urlPattern)&&(!c.methods||c.methods.includes(o))){const g=U(c,n);if(!q(c,g))continue;const O=D(c.probability,r);if(t==null||t.emit({type:"network:latency",timestamp:Date.now(),applied:O,detail:{url:i,method:o,delayMs:c.delayMs}}),O){console.warn(`CHAOS: Adding ${c.delayMs}ms latency to ${o} ${i}`),setTimeout(()=>{s.call(this,a)},c.delayMs);return}}}s.call(this,a)}}function gs(s){return function(e,t){this._chaos_url=t.toString(),this._chaos_method=e.toUpperCase(),s.call(this,e,t)}}function $e(s,e,t,r=Math.random){const n=D(e.probability,r);if(t==null||t.emit({type:"ui:assault",timestamp:Date.now(),applied:n,detail:{selector:e.selector,action:e.action}}),!!n){console.warn(`CHAOS: Applying action '${e.action}' to element:`,s);try{switch(e.action){case"disable":"disabled"in s&&(s.disabled=!0);break;case"hide":s.style.display="none";break;case"remove":s.remove();break}}catch(a){console.error("Chaos Maker failed to assault element:",a,s)}}}function vs(s,e,t,r=Math.random){if(s.nodeType!==Node.ELEMENT_NODE||!e.assaults)return;const n=s;for(const a of e.assaults){try{n.matches(a.selector)&&$e(n,a,t,r)}catch(i){console.error(`Chaos Maker: Invalid selector '${a.selector}'`,i)}n.querySelectorAll(a.selector).forEach(i=>{$e(i,a,t,r)})}}function _s(s,e,t=Math.random){if(s.assaults){console.log("CHAOS: Running initial DOM scan for existing elements...");for(const n of s.assaults)try{document.querySelectorAll(n.selector).forEach(a=>{$e(a,n,e,t)})}catch(a){console.error(`Chaos Maker: Invalid selector in initial scan '${n.selector}'`,a)}}return new MutationObserver(n=>{for(const a of n)a.type==="childList"&&a.addedNodes.forEach(i=>vs(i,s,e,t))})}const ft=Symbol.for("chaos-maker.websocket.intercepted");function bs(s,e){return s==="both"?!0:s===e}function ht(s){return typeof s=="string"?"text":"binary"}function pt(s,e){switch(e){case"truncate":return s.slice(0,Math.max(0,Math.floor(s.length/2)));case"malformed-json":return`${s}"}`;case"empty":return"";case"wrong-type":return"<html><body>Unexpected HTML</body></html>"}}function mt(s,e){if(e==="malformed-json"||e==="wrong-type")return null;if(e==="empty")return typeof Blob<"u"&&s instanceof Blob?new Blob([]):s instanceof ArrayBuffer?new ArrayBuffer(0):new Uint8Array(0);if(typeof Blob<"u"&&s instanceof Blob)return s.slice(0,Math.max(0,Math.floor(s.size/2)));if(s instanceof ArrayBuffer)return s.slice(0,Math.max(0,Math.floor(s.byteLength/2)));const t=s,r=Math.max(0,Math.floor(t.byteLength/2));return new Uint8Array(t.buffer.slice(t.byteOffset,t.byteOffset+r))}function fe(s,e,t,r,n){if(!s)return null;for(const a of s){if(!F(e,a.urlPattern)||!bs(a.direction,t))continue;const i=U(a,n);if(q(a,i)&&D(a.probability,r))return a}return null}function Te(s,e,t,r,n){s.emit({type:"websocket:drop",timestamp:Date.now(),applied:!0,detail:{url:e,direction:t,payloadType:r,...n?{reason:n}:{}}})}function yt(s,e,t,r,n){s.emit({type:"websocket:delay",timestamp:Date.now(),applied:!0,detail:{url:e,direction:t,payloadType:r,delayMs:n}})}function he(s,e,t,r,n,a,i){s.emit({type:"websocket:corrupt",timestamp:Date.now(),applied:a,detail:{url:e,direction:t,payloadType:r,strategy:n,...i?{reason:i}:{}}})}function ks(s,e,t,r){s.emit({type:"websocket:close",timestamp:Date.now(),applied:!0,detail:{url:e,closeCode:t,closeReason:r}})}function ws(s,e,t,r,n){const a=new Map;let i=!0;const o=(y,p)=>{let d=a.get(y);d||(d=new Set,a.set(y,d)),d.add(p)},l=(y,p)=>{var d;(d=a.get(y))==null||d.delete(p)},c=(y,p)=>{const d=a.get(y);if(d){for(const k of d)clearTimeout(k.handle),k.kind==="delay"&&Te(t,k.url,k.direction,k.payloadType,p);a.delete(y)}},g=(y,p,d)=>{const k=new MessageEvent("message",{data:d,origin:p.origin,lastEventId:p.lastEventId,source:p.source,ports:Array.from(p.ports??[])});k[ft]=!0,y.dispatchEvent(k)},O=(y,p,d,k)=>{if(!i)return{handled:!1,data:d};const x="outbound",S=ht(d);if(fe(e.drops,p,x,r,n))return Te(t,p,x,S),{handled:!0,data:d};let T=d;const P=fe(e.corruptions,p,x,r,n);if(P)if(S==="text")T=pt(T,P.strategy),he(t,p,x,S,P.strategy,!0);else{const B=mt(T,P.strategy);B===null?he(t,p,x,S,P.strategy,!1,"incompatible-payload-type"):(T=B,he(t,p,x,S,P.strategy,!0))}const V=fe(e.delays,p,x,r,n);if(V){yt(t,p,x,S,V.delayMs);const B={kind:"delay",handle:setTimeout(()=>{l(y,B);try{k(T)}catch{}},V.delayMs),url:p,direction:x,payloadType:S};return o(y,B),{handled:!0,data:T}}return{handled:!1,data:T}},A=(y,p)=>{y.addEventListener("message",d=>{const k=d;if(k[ft]||!i)return;const x="inbound",S=ht(k.data);if(fe(e.drops,p,x,r,n)){k.stopImmediatePropagation(),Te(t,p,x,S);return}let T=k.data,P=!1;const V=fe(e.corruptions,p,x,r,n);if(V)if(S==="text")T=pt(T,V.strategy),P=!0,he(t,p,x,S,V.strategy,!0);else{const ge=mt(T,V.strategy);ge===null?he(t,p,x,S,V.strategy,!1,"incompatible-payload-type"):(T=ge,P=!0,he(t,p,x,S,V.strategy,!0))}const B=fe(e.delays,p,x,r,n);if(B){k.stopImmediatePropagation(),yt(t,p,x,S,B.delayMs);const ge={kind:"delay",handle:setTimeout(()=>{l(y,ge),g(y,k,T)},B.delayMs),url:p,direction:x,payloadType:S};o(y,ge);return}P&&(k.stopImmediatePropagation(),g(y,k,T))})},j=(y,p)=>{if(e.closes)for(const d of e.closes){if(!F(p,d.urlPattern))continue;const k=U(d,n);if(!q(d,k)||!D(d.probability,r))continue;const x=d.code??1e3,S=d.reason??"Chaos Maker close",T=d.afterMs??0,P=()=>{if(i){c(y,"close-interrupt"),ks(t,p,x,S);try{y.close(x,S)}catch{try{y.close()}catch{}}}};if(T<=0)y.readyState===y.OPEN?P():y.addEventListener("open",P,{once:!0});else{const V=()=>{const B={kind:"close",handle:setTimeout(P,T)};o(y,B)};y.readyState===y.OPEN?V():y.addEventListener("open",V,{once:!0})}return}};function M(y,p){const d=new s(y,p),k=typeof y=="string"?y:y.toString(),x=d.send.bind(d);return d.send=function(T){const P=O(d,k,T,x);P.handled||x(P.data)},A(d,k),j(d,k),d}Object.defineProperty(M,"prototype",{value:s.prototype,writable:!1});for(const y of["CONNECTING","OPEN","CLOSING","CLOSED"])M[y]=s[y];return{Wrapped:M,uninstall(){i=!1;for(const[,y]of a)for(const p of y)clearTimeout(p.handle),p.kind==="delay"&&Te(t,p.url,p.direction,p.payloadType,"stop-during-delay");a.clear()}}}class Ie{constructor(e){Z(this,"config");Z(this,"emitter");Z(this,"random");Z(this,"seed");Z(this,"running",!1);Z(this,"originalFetch");Z(this,"originalXhrSend");Z(this,"originalXhrOpen");Z(this,"domObserver");Z(this,"originalWebSocket");Z(this,"webSocketHandle");Z(this,"requestCounters",new Map);this.config=nt(e),this.emitter=new ot;const t=it(e.seed);this.random=t.random,this.seed=t.seed,console.log(`Chaos Maker initialized (seed: ${this.seed})`)}getSeed(){return this.seed}on(e,t){this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}getLog(){return this.emitter.getLog()}clearLog(){this.emitter.clearLog()}start(){if(this.running){console.warn("Chaos Maker is already running. Call stop() first.");return}this.requestCounters.clear(),this.running=!0,console.log("🛠️ Chaos Maker ENGAGED 🛠️"),this.config.network&&(this.originalFetch=window.fetch,window.fetch=ms(this.originalFetch.bind(window),this.config.network,this.emitter,this.random,this.requestCounters),this.originalXhrOpen=window.XMLHttpRequest.prototype.open,window.XMLHttpRequest.prototype.open=gs(this.originalXhrOpen),this.originalXhrSend=window.XMLHttpRequest.prototype.send,window.XMLHttpRequest.prototype.send=ys(this.originalXhrSend,this.config.network,this.emitter,this.random,this.requestCounters)),this.config.ui&&(this.domObserver=_s(this.config.ui,this.emitter,this.random),this.domObserver.observe(document.body,{childList:!0,subtree:!0}),console.log("UI Assailant is now observing the DOM.")),this.config.websocket&&typeof window<"u"&&typeof window.WebSocket<"u"&&(this.originalWebSocket=window.WebSocket,this.webSocketHandle=ws(this.originalWebSocket,this.config.websocket,this.emitter,this.random,this.requestCounters),window.WebSocket=this.webSocketHandle.Wrapped)}stop(){this.running=!1,console.log("🛑 Chaos Maker DISENGAGED 🛑"),this.originalFetch&&(window.fetch=this.originalFetch),this.originalXhrSend&&(window.XMLHttpRequest.prototype.send=this.originalXhrSend),this.originalXhrOpen&&(window.XMLHttpRequest.prototype.open=this.originalXhrOpen),this.domObserver&&(this.domObserver.disconnect(),console.log("UI Assailant has stopped observing.")),this.originalWebSocket&&(window.WebSocket=this.originalWebSocket,this.originalWebSocket=void 0),this.webSocketHandle&&(this.webSocketHandle.uninstall(),this.webSocketHandle=void 0)}}function gt(s){return JSON.parse(JSON.stringify(s))}class xs{constructor(e){Z(this,"config");this.config=e?gt(e):{network:{},ui:{},websocket:{}},this.config.network||(this.config.network={}),this.config.ui||(this.config.ui={}),this.config.websocket||(this.config.websocket={})}failRequests(e,t,r,n,a,i,o){return this.config.network.failures||(this.config.network.failures=[]),this.config.network.failures.push({urlPattern:e,statusCode:t,probability:r,methods:n,body:a,headers:i,...o}),this}addLatency(e,t,r,n,a){return this.config.network.latencies||(this.config.network.latencies=[]),this.config.network.latencies.push({urlPattern:e,delayMs:t,probability:r,methods:n,...a}),this}abortRequests(e,t,r,n,a){return this.config.network.aborts||(this.config.network.aborts=[]),this.config.network.aborts.push({urlPattern:e,probability:t,timeout:r,methods:n,...a}),this}corruptResponses(e,t,r,n,a){return this.config.network.corruptions||(this.config.network.corruptions=[]),this.config.network.corruptions.push({urlPattern:e,strategy:t,probability:r,methods:n,...a}),this}simulateCors(e,t,r,n){return this.config.network.cors||(this.config.network.cors=[]),this.config.network.cors.push({urlPattern:e,probability:t,methods:r,...n}),this}failRequestsOnNth(e,t,r,n){return this.failRequests(e,t,1,n,void 0,void 0,{onNth:r})}addLatencyOnNth(e,t,r,n){return this.addLatency(e,t,1,n,{onNth:r})}abortRequestsOnNth(e,t,r,n){return this.abortRequests(e,1,r,n,{onNth:t})}corruptResponsesOnNth(e,t,r,n){return this.corruptResponses(e,t,1,n,{onNth:r})}simulateCorsOnNth(e,t,r){return this.simulateCors(e,1,r,{onNth:t})}failRequestsEveryNth(e,t,r,n){return this.failRequests(e,t,1,n,void 0,void 0,{everyNth:r})}addLatencyEveryNth(e,t,r,n){return this.addLatency(e,t,1,n,{everyNth:r})}abortRequestsEveryNth(e,t,r,n){return this.abortRequests(e,1,r,n,{everyNth:t})}corruptResponsesEveryNth(e,t,r,n){return this.corruptResponses(e,t,1,n,{everyNth:r})}simulateCorsEveryNth(e,t,r){return this.simulateCors(e,1,r,{everyNth:t})}failRequestsAfterN(e,t,r,n){return this.failRequests(e,t,1,n,void 0,void 0,{afterN:r})}addLatencyAfterN(e,t,r,n){return this.addLatency(e,t,1,n,{afterN:r})}abortRequestsAfterN(e,t,r,n){return this.abortRequests(e,1,r,n,{afterN:t})}corruptResponsesAfterN(e,t,r,n){return this.corruptResponses(e,t,1,n,{afterN:r})}simulateCorsAfterN(e,t,r){return this.simulateCors(e,1,r,{afterN:t})}assaultUi(e,t,r){return this.config.ui.assaults||(this.config.ui.assaults=[]),this.config.ui.assaults.push({selector:e,action:t,probability:r}),this}dropMessages(e,t,r,n){return this.config.websocket.drops||(this.config.websocket.drops=[]),this.config.websocket.drops.push({urlPattern:e,direction:t,probability:r,...n}),this}delayMessages(e,t,r,n,a){return this.config.websocket.delays||(this.config.websocket.delays=[]),this.config.websocket.delays.push({urlPattern:e,direction:t,delayMs:r,probability:n,...a}),this}corruptMessages(e,t,r,n,a){return this.config.websocket.corruptions||(this.config.websocket.corruptions=[]),this.config.websocket.corruptions.push({urlPattern:e,direction:t,strategy:r,probability:n,...a}),this}closeConnection(e,t,r,n){return this.config.websocket.closes||(this.config.websocket.closes=[]),this.config.websocket.closes.push({urlPattern:e,probability:t,...r,...n}),this}dropMessagesOnNth(e,t,r){return this.dropMessages(e,t,1,{onNth:r})}delayMessagesOnNth(e,t,r,n){return this.delayMessages(e,t,r,1,{onNth:n})}withSeed(e){return this.config.seed=e,this}build(){return gt(this.config)}}const ae="*";function vt(s){if(s&&typeof s=="object"&&!Object.isFrozen(s)){Object.freeze(s);for(const e of Object.values(s))vt(e)}return s}const Cs=vt({unstableApi:{network:{failures:[{urlPattern:"/api/",statusCode:500,probability:.1}],latencies:[{urlPattern:"/api/",delayMs:1e3,probability:.2}]}},slowNetwork:{network:{latencies:[{urlPattern:ae,delayMs:2e3,probability:1}]}},offlineMode:{network:{cors:[{urlPattern:ae,probability:1}]}},flakyConnection:{network:{aborts:[{urlPattern:ae,probability:.05}],latencies:[{urlPattern:ae,delayMs:3e3,probability:.1}]}},degradedUi:{ui:{assaults:[{selector:"button",action:"disable",probability:.2},{selector:"a",action:"hide",probability:.1}]}},unreliableWebSocket:{websocket:{drops:[{urlPattern:ae,direction:"both",probability:.1}],delays:[{urlPattern:ae,direction:"inbound",delayMs:500,probability:1}],corruptions:[{urlPattern:ae,direction:"inbound",strategy:"truncate",probability:.05}]}}});if(typeof window<"u"){window.ChaosMaker=Ie;const s={instance:null,start:e=>{try{return s.instance&&s.instance.stop(),s.instance=new Ie(e),s.instance.start(),{success:!0,message:"Chaos started"}}catch(t){return console.error("Chaos Utils Error:",t),{success:!1,message:t.message}}},stop:()=>s.instance?(s.instance.stop(),s.instance=null,{success:!0,message:"Chaos stopped"}):{success:!1,message:"No chaos instance to stop"},getLog:()=>s.instance?s.instance.getLog():[],getSeed:()=>s.instance?s.instance.getSeed():null};if(window.chaosUtils=s,window.__CHAOS_CONFIG__)try{const e=window.__CHAOS_CONFIG__;s.start(e),delete window.__CHAOS_CONFIG__}catch(e){console.error("ChaosMaker auto-start failed:",e)}}E.ChaosConfigBuilder=xs,E.ChaosConfigError=st,E.ChaosEventEmitter=ot,E.ChaosMaker=Ie,E.createPrng=it,E.generateSeed=at,E.presets=Cs,E.validateConfig=nt,Object.defineProperty(E,Symbol.toStringTag,{value:"Module"})});
|
|
3
|
+
`)}`;super(r);Z(this,"issues");this.name="ChaosConfigError",this.issues=t}}const G=X().min(0,"Probability must be >= 0").max(1,"Probability must be <= 1"),rt=X().int().min(1),Q={onNth:rt.optional(),everyNth:rt.optional(),afterN:X().int().min(0).optional()},K=[s=>[s.onNth,s.everyNth,s.afterN].filter(e=>e!==void 0).length<=1,{message:"Only one of onNth, everyNth, or afterN may be set on a single rule"}],Ht=L({urlPattern:R().min(1,"urlPattern must not be empty"),methods:I(R()).optional(),statusCode:X().int().min(100).max(599),probability:G,body:R().optional(),statusText:R().optional(),headers:Bt(R()).optional(),...Q}).strict().refine(...K),Wt=L({urlPattern:R().min(1,"urlPattern must not be empty"),methods:I(R()).optional(),delayMs:X().min(0,"delayMs must be >= 0"),probability:G,...Q}).strict().refine(...K),Xt=L({urlPattern:R().min(1,"urlPattern must not be empty"),methods:I(R()).optional(),probability:G,timeout:X().min(0,"timeout must be >= 0").optional(),...Q}).strict().refine(...K),Gt=L({urlPattern:R().min(1,"urlPattern must not be empty"),methods:I(R()).optional(),probability:G,strategy:Ce(["truncate","malformed-json","empty","wrong-type"]),...Q}).strict().refine(...K),Jt=L({urlPattern:R().min(1,"urlPattern must not be empty"),methods:I(R()).optional(),probability:G,...Q}).strict().refine(...K),Yt=L({failures:I(Ht).optional(),latencies:I(Wt).optional(),aborts:I(Xt).optional(),corruptions:I(Gt).optional(),cors:I(Jt).optional()}).strict(),Qt=L({selector:R().min(1,"selector must not be empty"),action:Ce(["disable","hide","remove"]),probability:G}).strict(),Kt=L({assaults:I(Qt).optional()}).strict(),Pe=Ce(["inbound","outbound","both"]),es=L({urlPattern:R().min(1,"urlPattern must not be empty"),direction:Pe,probability:G,...Q}).strict().refine(...K),ts=L({urlPattern:R().min(1,"urlPattern must not be empty"),direction:Pe,delayMs:X().min(0,"delayMs must be >= 0"),probability:G,...Q}).strict().refine(...K),ss=L({urlPattern:R().min(1,"urlPattern must not be empty"),direction:Pe,strategy:Ce(["truncate","malformed-json","empty","wrong-type"]),probability:G,...Q}).strict().refine(...K),rs=X().int().refine(s=>s===1e3||s>=3e3&&s<=4999,{message:"code must be 1000 or in the range 3000-4999"}),ns=R().refine(s=>new TextEncoder().encode(s).length<=123,{message:"reason must be <= 123 UTF-8 bytes"}),as=L({urlPattern:R().min(1,"urlPattern must not be empty"),code:rs.optional(),reason:ns.optional(),afterMs:X().min(0,"afterMs must be >= 0").optional(),probability:G,...Q}).strict().refine(...K),is=L({drops:I(es).optional(),delays:I(ts).optional(),corruptions:I(ss).optional(),closes:I(as).optional()}).strict(),os=L({network:Yt.optional(),ui:Kt.optional(),websocket:is.optional(),seed:X().int("Seed must be an integer").optional()}).strict();function nt(s){const e=os.safeParse(s);if(!e.success){const t=e.error.issues.map(r=>`${r.path.join(".")}: ${r.message}`);throw new st(t)}return e.data}function cs(s){let e=s|0;return()=>{e=e+1831565813|0;let t=Math.imul(e^e>>>15,1|e);return t=t+Math.imul(t^t>>>7,61|t)^t,((t^t>>>14)>>>0)/4294967296}}function at(){return Math.random()*4294967296>>>0}function it(s){const e=s??at();return{random:cs(e),seed:e}}class ot{constructor(e=2e3){Z(this,"listeners",new Map);Z(this,"log",[]);this.maxLogEntries=e}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t)}off(e,t){var r;(r=this.listeners.get(e))==null||r.delete(t)}emit(e){this.log.push(e),this.log.length>this.maxLogEntries&&this.log.shift(),this.notify(this.listeners.get(e.type),e),this.notify(this.listeners.get("*"),e)}getLog(){return[...this.log]}clearLog(){this.log=[]}notify(e,t){if(e)for(const r of e)try{r(t)}catch{}}}function D(s,e){return e()<s}function U(s,e){const t=(e.get(s)??0)+1;return e.set(s,t),t}function q(s,e){return s.onNth!==void 0?e===s.onNth:s.everyNth!==void 0?e%s.everyNth===0:s.afterN!==void 0?e>s.afterN:!0}function F(s,e){return e==="*"?!0:s.includes(e)}function ct(s,e){switch(e){case"truncate":return s.slice(0,Math.max(0,Math.floor(s.length/2)));case"malformed-json":return`${s}"}`;case"empty":return"";case"wrong-type":return"<html><body>Unexpected HTML</body></html>"}}function Ze(s){return typeof Request<"u"&&s instanceof Request}function ds(s){return Ze(s)?s.url:s.toString()}function us(s,e){return e!=null&&e.method?e.method.toUpperCase():Ze(s)?s.method.toUpperCase():"GET"}function ls(s,e){if(e!=null&&e.signal)return e.signal;if(Ze(s))return s.signal}function fs(){if(typeof DOMException<"u")return new DOMException("The user aborted a request.","AbortError");const s=new Error("The user aborted a request.");return s.name="AbortError",s}function hs(s,e){if(!e)return s;const t=new AbortController,r=o=>{i(),t.signal.aborted||t.abort(o.reason)},n=()=>r(s),a=()=>r(e),i=()=>{s.removeEventListener("abort",n),e.removeEventListener("abort",a)};return s.aborted?(r(s),t.signal):e.aborted?(r(e),t.signal):(s.addEventListener("abort",n,{once:!0}),e.addEventListener("abort",a,{once:!0}),t.signal)}function ps(s,e){return e?{...s??{},signal:e}:s}function dt(s,e,t,r,n){s==null||s.emit({type:"network:abort",timestamp:Date.now(),applied:n,detail:{url:t,method:r,timeoutMs:e.timeout}})}function Se(s,e,t,r,n){s==null||s.emit({type:"network:corruption",timestamp:Date.now(),applied:n,detail:{url:t,method:r,strategy:e.strategy}})}function ms(s,e,t,r,n=new Map){return async(a,i)=>{const o=ds(a),l=us(a,i),c=ls(a,i);if(e.cors){for(const d of e.cors)if(F(o,d.urlPattern)&&(!d.methods||d.methods.includes(l))){const k=U(d,n);if(!q(d,k))continue;const x=D(d.probability,t);if(r==null||r.emit({type:"network:cors",timestamp:Date.now(),applied:x,detail:{url:o,method:l}}),x){console.debug(`[chaos-maker] CORS block: ${l} ${o}`);const S=new TypeError("Failed to fetch");throw S.stack="",S}}}let g=null,O,A,j=!1;const M=d=>{!g||j||(j=!0,A&&(clearTimeout(A),A=void 0),dt(r,g,o,l,d))};if(e.aborts){for(const d of e.aborts)if(F(o,d.urlPattern)&&(!d.methods||d.methods.includes(l))){const k=U(d,n);if(!q(d,k))continue;if(!D(d.probability,t)){dt(r,d,o,l,!1);continue}console.warn(`CHAOS: Aborting ${l} ${o} after ${d.timeout||0}ms`),g=d;const S=new AbortController;O=hs(S.signal,c);const T=()=>{j||(M(!0),S.abort(fs()))};d.timeout?A=setTimeout(T,d.timeout):T();break}}if(g)try{const d=await s(a,ps(i,O));return M(!1),d}catch(d){throw M(!1),d}if(e.failures){for(const d of e.failures)if(F(o,d.urlPattern)&&(!d.methods||d.methods.includes(l))){const k=U(d,n);if(!q(d,k))continue;const x=D(d.probability,t);if(r==null||r.emit({type:"network:failure",timestamp:Date.now(),applied:x,detail:{url:o,method:l,statusCode:d.statusCode}}),x){console.warn(`CHAOS: Forcing ${d.statusCode} for ${l} ${o}`);const S=d.body??JSON.stringify({error:"Chaos Maker Attack!"}),T=d.headers??{};return new Response(S,{status:d.statusCode,statusText:d.statusText??"Service Unavailable (Chaos)",headers:T})}}}if(e.latencies){for(const d of e.latencies)if(F(o,d.urlPattern)&&(!d.methods||d.methods.includes(l))){const k=U(d,n);if(!q(d,k))continue;const x=D(d.probability,t);r==null||r.emit({type:"network:latency",timestamp:Date.now(),applied:x,detail:{url:o,method:l,delayMs:d.delayMs}}),x&&(console.warn(`CHAOS: Adding ${d.delayMs}ms latency to ${l} ${o}`),await new Promise(S=>setTimeout(S,d.delayMs)))}}let y=null;if(e.corruptions){for(const d of e.corruptions)if(F(o,d.urlPattern)&&(!d.methods||d.methods.includes(l))){const k=U(d,n);if(!q(d,k))continue;if(!D(d.probability,t)){Se(r,d,o,l,!1);continue}y=d;break}}let p;try{p=await s(a,i)}catch(d){throw y&&Se(r,y,o,l,!1),d}if(!y)return p;try{console.warn(`CHAOS: Corrupting response for ${l} ${o} with strategy: ${y.strategy}`);const d=await p.text(),k=ct(d,y.strategy);return Se(r,y,o,l,!0),new Response(k,{status:p.status,statusText:p.statusText,headers:p.headers})}catch(d){throw Se(r,y,o,l,!1),d}}}function ut(s,e,t,r,n){s==null||s.emit({type:"network:abort",timestamp:Date.now(),applied:n,detail:{url:t,method:r,timeoutMs:e.timeout}})}function lt(s,e,t,r,n){s==null||s.emit({type:"network:corruption",timestamp:Date.now(),applied:n,detail:{url:t,method:r,strategy:e.strategy}})}function ys(s,e,t,r,n=new Map){return function(a){const i=this._chaos_url,o=this._chaos_method;if(e.cors){for(const c of e.cors)if(F(i,c.urlPattern)&&(!c.methods||c.methods.includes(o))){const g=U(c,n);if(!q(c,g))continue;const O=D(c.probability,t);if(r==null||r.emit({type:"network:cors",timestamp:Date.now(),applied:O,detail:{url:i,method:o}}),O){console.debug(`[chaos-maker] CORS block: ${o} ${i}`),Object.defineProperty(this,"status",{value:0}),Object.defineProperty(this,"statusText",{value:""}),this.dispatchEvent(new Event("error")),this.dispatchEvent(new Event("loadend"));return}}}if(e.aborts){for(const c of e.aborts)if(F(i,c.urlPattern)&&(!c.methods||c.methods.includes(o))){const g=U(c,n);if(!q(c,g))continue;if(!D(c.probability,t)){ut(r,c,i,o,!1);continue}console.warn(`CHAOS: Aborting ${o} ${i} after ${c.timeout||0}ms`);let A=!1,j;const M=()=>{j&&(clearTimeout(j),j=void 0),typeof this.removeEventListener=="function"&&this.removeEventListener("loadend",p)},y=k=>{A||(A=!0,M(),ut(r,c,i,o,k))},p=()=>{y(!1)},d=()=>{A||(y(!0),this.abort())};typeof this.addEventListener=="function"&&this.addEventListener("loadend",p);try{s.call(this,a)}catch(k){throw y(!1),k}if(A)return;c.timeout?j=setTimeout(d,c.timeout):d();return}}if(e.failures){for(const c of e.failures)if(F(i,c.urlPattern)&&(!c.methods||c.methods.includes(o))){const g=U(c,n);if(!q(c,g))continue;const O=D(c.probability,t);if(r==null||r.emit({type:"network:failure",timestamp:Date.now(),applied:O,detail:{url:i,method:o,statusCode:c.statusCode}}),O){console.warn(`CHAOS: Forcing ${c.statusCode} for ${o} ${i}`),Object.defineProperty(this,"status",{value:c.statusCode}),Object.defineProperty(this,"statusText",{value:c.statusText??"Service Unavailable (Chaos)"});const A=c.body??JSON.stringify({error:"Chaos Maker Attack!"});Object.defineProperty(this,"responseText",{value:A,configurable:!0});const j=c.headers??{};Object.defineProperty(this,"getResponseHeader",{value:M=>{const y=Object.keys(j).find(p=>p.toLowerCase()===M.toLowerCase());return y?j[y]:null},configurable:!0}),Object.defineProperty(this,"getAllResponseHeaders",{value:()=>Object.entries(j).map(([M,y])=>`${M}: ${y}`).join(`\r
|
|
4
|
+
`),configurable:!0}),this.dispatchEvent(new Event("error")),this.dispatchEvent(new Event("load")),this.dispatchEvent(new Event("loadend"));return}}}let l=null;if(e.corruptions){for(const c of e.corruptions)if(F(i,c.urlPattern)&&(!c.methods||c.methods.includes(o))){const g=U(c,n);if(!q(c,g))continue;if(!D(c.probability,t)){lt(r,c,i,o,!1);continue}l=c;break}}if(l){let c=!1,g=null;const O=()=>{typeof this.removeEventListener=="function"&&(this.removeEventListener("error",M),this.removeEventListener("abort",M),this.removeEventListener("loadend",y))},A=p=>{c||(c=!0,lt(r,l,i,o,p),O())},j=()=>{if(g!==null)return g;delete this.responseText;try{const p=this.responseText;return typeof p!="string"?(Object.defineProperty(this,"responseText",{value:p,configurable:!0}),A(!1),p):(g=ct(p,l.strategy),Object.defineProperty(this,"responseText",{value:g,configurable:!0}),A(!0),g)}catch(p){throw A(!1),p}},M=()=>{A(!1)},y=()=>{if(!c)try{j()}catch{}};typeof this.addEventListener=="function"&&(this.addEventListener("error",M),this.addEventListener("abort",M),this.addEventListener("loadend",y)),Object.defineProperty(this,"responseText",{get(){return j()},configurable:!0})}if(e.latencies){for(const c of e.latencies)if(F(i,c.urlPattern)&&(!c.methods||c.methods.includes(o))){const g=U(c,n);if(!q(c,g))continue;const O=D(c.probability,t);if(r==null||r.emit({type:"network:latency",timestamp:Date.now(),applied:O,detail:{url:i,method:o,delayMs:c.delayMs}}),O){console.warn(`CHAOS: Adding ${c.delayMs}ms latency to ${o} ${i}`),setTimeout(()=>{s.call(this,a)},c.delayMs);return}}}s.call(this,a)}}function gs(s){return function(e,t){this._chaos_url=t.toString(),this._chaos_method=e.toUpperCase(),s.call(this,e,t)}}function $e(s,e,t,r){const n=D(e.probability,t);if(r==null||r.emit({type:"ui:assault",timestamp:Date.now(),applied:n,detail:{selector:e.selector,action:e.action}}),!!n){console.warn(`CHAOS: Applying action '${e.action}' to element:`,s);try{switch(e.action){case"disable":"disabled"in s&&(s.disabled=!0);break;case"hide":s.style.display="none";break;case"remove":s.remove();break}}catch(a){console.error("Chaos Maker failed to assault element:",a,s)}}}function vs(s,e,t,r){if(s.nodeType!==Node.ELEMENT_NODE||!e.assaults)return;const n=s;for(const a of e.assaults)try{n.matches(a.selector)&&$e(n,a,t,r),n.querySelectorAll(a.selector).forEach(i=>{$e(i,a,t,r)})}catch(i){console.error(`Chaos Maker: Invalid selector '${a.selector}'`,i)}}function _s(s,e,t){if(s.assaults){console.log("CHAOS: Running initial DOM scan for existing elements...");for(const n of s.assaults)try{document.querySelectorAll(n.selector).forEach(a=>{$e(a,n,e,t)})}catch(a){console.error(`Chaos Maker: Invalid selector in initial scan '${n.selector}'`,a)}}return new MutationObserver(n=>{for(const a of n)a.type==="childList"&&a.addedNodes.forEach(i=>vs(i,s,e,t))})}const ft=Symbol.for("chaos-maker.websocket.intercepted");function bs(s,e){return s==="both"?!0:s===e}function ht(s){return typeof s=="string"?"text":"binary"}function pt(s,e){switch(e){case"truncate":return s.slice(0,Math.max(0,Math.floor(s.length/2)));case"malformed-json":return`${s}"}`;case"empty":return"";case"wrong-type":return"<html><body>Unexpected HTML</body></html>"}}function mt(s,e){if(e==="malformed-json"||e==="wrong-type")return null;if(e==="empty")return typeof Blob<"u"&&s instanceof Blob?new Blob([]):s instanceof ArrayBuffer?new ArrayBuffer(0):new Uint8Array(0);if(typeof Blob<"u"&&s instanceof Blob)return s.slice(0,Math.max(0,Math.floor(s.size/2)));if(s instanceof ArrayBuffer)return s.slice(0,Math.max(0,Math.floor(s.byteLength/2)));const t=s,r=Math.max(0,Math.floor(t.byteLength/2));return new Uint8Array(t.buffer.slice(t.byteOffset,t.byteOffset+r))}function fe(s,e,t,r,n){if(!s)return null;for(const a of s){if(!F(e,a.urlPattern)||!bs(a.direction,t))continue;const i=U(a,n);if(q(a,i)&&D(a.probability,r))return a}return null}function Te(s,e,t,r,n){s.emit({type:"websocket:drop",timestamp:Date.now(),applied:!0,detail:{url:e,direction:t,payloadType:r,...n?{reason:n}:{}}})}function yt(s,e,t,r,n){s.emit({type:"websocket:delay",timestamp:Date.now(),applied:!0,detail:{url:e,direction:t,payloadType:r,delayMs:n}})}function he(s,e,t,r,n,a,i){s.emit({type:"websocket:corrupt",timestamp:Date.now(),applied:a,detail:{url:e,direction:t,payloadType:r,strategy:n,...i?{reason:i}:{}}})}function ks(s,e,t,r){s.emit({type:"websocket:close",timestamp:Date.now(),applied:!0,detail:{url:e,closeCode:t,closeReason:r}})}function ws(s,e,t,r,n){const a=new Map;let i=!0;const o=(y,p)=>{let d=a.get(y);d||(d=new Set,a.set(y,d)),d.add(p)},l=(y,p)=>{var d;(d=a.get(y))==null||d.delete(p)},c=(y,p)=>{const d=a.get(y);if(d){for(const k of d)clearTimeout(k.handle),k.kind==="delay"&&Te(t,k.url,k.direction,k.payloadType,p);a.delete(y)}},g=(y,p,d)=>{const k=new MessageEvent("message",{data:d,origin:p.origin,lastEventId:p.lastEventId,source:p.source,ports:Array.from(p.ports??[])});k[ft]=!0,y.dispatchEvent(k)},O=(y,p,d,k)=>{if(!i)return{handled:!1,data:d};const x="outbound",S=ht(d);if(fe(e.drops,p,x,r,n))return Te(t,p,x,S),{handled:!0,data:d};let T=d;const P=fe(e.corruptions,p,x,r,n);if(P)if(S==="text")T=pt(T,P.strategy),he(t,p,x,S,P.strategy,!0);else{const B=mt(T,P.strategy);B===null?he(t,p,x,S,P.strategy,!1,"incompatible-payload-type"):(T=B,he(t,p,x,S,P.strategy,!0))}const V=fe(e.delays,p,x,r,n);if(V){yt(t,p,x,S,V.delayMs);const B={kind:"delay",handle:setTimeout(()=>{l(y,B);try{k(T)}catch{}},V.delayMs),url:p,direction:x,payloadType:S};return o(y,B),{handled:!0,data:T}}return{handled:!1,data:T}},A=(y,p)=>{y.addEventListener("message",d=>{const k=d;if(k[ft]||!i)return;const x="inbound",S=ht(k.data);if(fe(e.drops,p,x,r,n)){k.stopImmediatePropagation(),Te(t,p,x,S);return}let T=k.data,P=!1;const V=fe(e.corruptions,p,x,r,n);if(V)if(S==="text")T=pt(T,V.strategy),P=!0,he(t,p,x,S,V.strategy,!0);else{const ge=mt(T,V.strategy);ge===null?he(t,p,x,S,V.strategy,!1,"incompatible-payload-type"):(T=ge,P=!0,he(t,p,x,S,V.strategy,!0))}const B=fe(e.delays,p,x,r,n);if(B){k.stopImmediatePropagation(),yt(t,p,x,S,B.delayMs);const ge={kind:"delay",handle:setTimeout(()=>{l(y,ge),g(y,k,T)},B.delayMs),url:p,direction:x,payloadType:S};o(y,ge);return}P&&(k.stopImmediatePropagation(),g(y,k,T))})},j=(y,p)=>{if(e.closes)for(const d of e.closes){if(!F(p,d.urlPattern))continue;const k=U(d,n);if(!q(d,k)||!D(d.probability,r))continue;const x=d.code??1e3,S=d.reason??"Chaos Maker close",T=d.afterMs??0,P=()=>{if(i){c(y,"close-interrupt"),ks(t,p,x,S);try{y.close(x,S)}catch{try{y.close()}catch{}}}};if(T<=0)y.readyState===y.OPEN?P():y.addEventListener("open",P,{once:!0});else{const V=()=>{const B={kind:"close",handle:setTimeout(P,T)};o(y,B)};y.readyState===y.OPEN?V():y.addEventListener("open",V,{once:!0})}return}};function M(y,p){const d=new s(y,p),k=typeof y=="string"?y:y.toString(),x=d.send.bind(d);return d.send=function(T){const P=O(d,k,T,x);P.handled||x(P.data)},A(d,k),j(d,k),d}Object.defineProperty(M,"prototype",{value:s.prototype,writable:!1});for(const y of["CONNECTING","OPEN","CLOSING","CLOSED"])M[y]=s[y];return{Wrapped:M,uninstall(){i=!1;for(const[,y]of a)for(const p of y)clearTimeout(p.handle),p.kind==="delay"&&Te(t,p.url,p.direction,p.payloadType,"stop-during-delay");a.clear()}}}class Ie{constructor(e){Z(this,"config");Z(this,"emitter");Z(this,"random");Z(this,"seed");Z(this,"running",!1);Z(this,"originalFetch");Z(this,"originalXhrSend");Z(this,"originalXhrOpen");Z(this,"domObserver");Z(this,"originalWebSocket");Z(this,"webSocketHandle");Z(this,"requestCounters",new Map);this.config=nt(e),this.emitter=new ot;const t=it(e.seed);this.random=t.random,this.seed=t.seed,console.log(`Chaos Maker initialized (seed: ${this.seed})`)}getSeed(){return this.seed}on(e,t){this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}getLog(){return this.emitter.getLog()}clearLog(){this.emitter.clearLog()}start(){if(this.running){console.warn("Chaos Maker is already running. Call stop() first.");return}this.requestCounters.clear(),this.running=!0,console.log("🛠️ Chaos Maker ENGAGED 🛠️"),this.config.network&&(this.originalFetch=window.fetch,window.fetch=ms(this.originalFetch.bind(window),this.config.network,this.random,this.emitter,this.requestCounters),this.originalXhrOpen=window.XMLHttpRequest.prototype.open,window.XMLHttpRequest.prototype.open=gs(this.originalXhrOpen),this.originalXhrSend=window.XMLHttpRequest.prototype.send,window.XMLHttpRequest.prototype.send=ys(this.originalXhrSend,this.config.network,this.random,this.emitter,this.requestCounters)),this.config.ui&&(this.domObserver=_s(this.config.ui,this.random,this.emitter),this.domObserver.observe(document.body,{childList:!0,subtree:!0}),console.log("UI Assailant is now observing the DOM.")),this.config.websocket&&typeof window<"u"&&typeof window.WebSocket<"u"&&(this.originalWebSocket=window.WebSocket,this.webSocketHandle=ws(this.originalWebSocket,this.config.websocket,this.emitter,this.random,this.requestCounters),window.WebSocket=this.webSocketHandle.Wrapped)}stop(){this.running=!1,console.log("🛑 Chaos Maker DISENGAGED 🛑"),this.originalFetch&&(window.fetch=this.originalFetch),this.originalXhrSend&&(window.XMLHttpRequest.prototype.send=this.originalXhrSend),this.originalXhrOpen&&(window.XMLHttpRequest.prototype.open=this.originalXhrOpen),this.domObserver&&(this.domObserver.disconnect(),console.log("UI Assailant has stopped observing.")),this.originalWebSocket&&(window.WebSocket=this.originalWebSocket,this.originalWebSocket=void 0),this.webSocketHandle&&(this.webSocketHandle.uninstall(),this.webSocketHandle=void 0)}}function gt(s){return JSON.parse(JSON.stringify(s))}class xs{constructor(e){Z(this,"config");this.config=e?gt(e):{network:{},ui:{},websocket:{}},this.config.network||(this.config.network={}),this.config.ui||(this.config.ui={}),this.config.websocket||(this.config.websocket={})}failRequests(e,t,r,n,a,i,o){return this.config.network.failures||(this.config.network.failures=[]),this.config.network.failures.push({urlPattern:e,statusCode:t,probability:r,methods:n,body:a,headers:i,...o}),this}addLatency(e,t,r,n,a){return this.config.network.latencies||(this.config.network.latencies=[]),this.config.network.latencies.push({urlPattern:e,delayMs:t,probability:r,methods:n,...a}),this}abortRequests(e,t,r,n,a){return this.config.network.aborts||(this.config.network.aborts=[]),this.config.network.aborts.push({urlPattern:e,probability:t,timeout:r,methods:n,...a}),this}corruptResponses(e,t,r,n,a){return this.config.network.corruptions||(this.config.network.corruptions=[]),this.config.network.corruptions.push({urlPattern:e,strategy:t,probability:r,methods:n,...a}),this}simulateCors(e,t,r,n){return this.config.network.cors||(this.config.network.cors=[]),this.config.network.cors.push({urlPattern:e,probability:t,methods:r,...n}),this}failRequestsOnNth(e,t,r,n){return this.failRequests(e,t,1,n,void 0,void 0,{onNth:r})}addLatencyOnNth(e,t,r,n){return this.addLatency(e,t,1,n,{onNth:r})}abortRequestsOnNth(e,t,r,n){return this.abortRequests(e,1,r,n,{onNth:t})}corruptResponsesOnNth(e,t,r,n){return this.corruptResponses(e,t,1,n,{onNth:r})}simulateCorsOnNth(e,t,r){return this.simulateCors(e,1,r,{onNth:t})}failRequestsEveryNth(e,t,r,n){return this.failRequests(e,t,1,n,void 0,void 0,{everyNth:r})}addLatencyEveryNth(e,t,r,n){return this.addLatency(e,t,1,n,{everyNth:r})}abortRequestsEveryNth(e,t,r,n){return this.abortRequests(e,1,r,n,{everyNth:t})}corruptResponsesEveryNth(e,t,r,n){return this.corruptResponses(e,t,1,n,{everyNth:r})}simulateCorsEveryNth(e,t,r){return this.simulateCors(e,1,r,{everyNth:t})}failRequestsAfterN(e,t,r,n){return this.failRequests(e,t,1,n,void 0,void 0,{afterN:r})}addLatencyAfterN(e,t,r,n){return this.addLatency(e,t,1,n,{afterN:r})}abortRequestsAfterN(e,t,r,n){return this.abortRequests(e,1,r,n,{afterN:t})}corruptResponsesAfterN(e,t,r,n){return this.corruptResponses(e,t,1,n,{afterN:r})}simulateCorsAfterN(e,t,r){return this.simulateCors(e,1,r,{afterN:t})}assaultUi(e,t,r){return this.config.ui.assaults||(this.config.ui.assaults=[]),this.config.ui.assaults.push({selector:e,action:t,probability:r}),this}dropMessages(e,t,r,n){return this.config.websocket.drops||(this.config.websocket.drops=[]),this.config.websocket.drops.push({urlPattern:e,direction:t,probability:r,...n}),this}delayMessages(e,t,r,n,a){return this.config.websocket.delays||(this.config.websocket.delays=[]),this.config.websocket.delays.push({urlPattern:e,direction:t,delayMs:r,probability:n,...a}),this}corruptMessages(e,t,r,n,a){return this.config.websocket.corruptions||(this.config.websocket.corruptions=[]),this.config.websocket.corruptions.push({urlPattern:e,direction:t,strategy:r,probability:n,...a}),this}closeConnection(e,t,r,n){return this.config.websocket.closes||(this.config.websocket.closes=[]),this.config.websocket.closes.push({urlPattern:e,probability:t,...r,...n}),this}dropMessagesOnNth(e,t,r){return this.dropMessages(e,t,1,{onNth:r})}delayMessagesOnNth(e,t,r,n){return this.delayMessages(e,t,r,1,{onNth:n})}withSeed(e){return this.config.seed=e,this}build(){return gt(this.config)}}const ae="*";function vt(s){if(s&&typeof s=="object"&&!Object.isFrozen(s)){Object.freeze(s);for(const e of Object.values(s))vt(e)}return s}const Cs=vt({unstableApi:{network:{failures:[{urlPattern:"/api/",statusCode:500,probability:.1}],latencies:[{urlPattern:"/api/",delayMs:1e3,probability:.2}]}},slowNetwork:{network:{latencies:[{urlPattern:ae,delayMs:2e3,probability:1}]}},offlineMode:{network:{cors:[{urlPattern:ae,probability:1}]}},flakyConnection:{network:{aborts:[{urlPattern:ae,probability:.05}],latencies:[{urlPattern:ae,delayMs:3e3,probability:.1}]}},degradedUi:{ui:{assaults:[{selector:"button",action:"disable",probability:.2},{selector:"a",action:"hide",probability:.1}]}},unreliableWebSocket:{websocket:{drops:[{urlPattern:ae,direction:"both",probability:.1}],delays:[{urlPattern:ae,direction:"inbound",delayMs:500,probability:1}],corruptions:[{urlPattern:ae,direction:"inbound",strategy:"truncate",probability:.05}]}}});if(typeof window<"u"){window.ChaosMaker=Ie;const s={instance:null,start:e=>{try{return s.instance&&s.instance.stop(),s.instance=new Ie(e),s.instance.start(),{success:!0,message:"Chaos started"}}catch(t){return console.error("Chaos Utils Error:",t),{success:!1,message:t.message}}},stop:()=>s.instance?(s.instance.stop(),s.instance=null,{success:!0,message:"Chaos stopped"}):{success:!1,message:"No chaos instance to stop"},getLog:()=>s.instance?s.instance.getLog():[],getSeed:()=>s.instance?s.instance.getSeed():null};if(window.chaosUtils=s,window.__CHAOS_CONFIG__)try{const e=window.__CHAOS_CONFIG__;s.start(e),delete window.__CHAOS_CONFIG__}catch(e){console.error("ChaosMaker auto-start failed:",e)}}E.ChaosConfigBuilder=xs,E.ChaosConfigError=st,E.ChaosEventEmitter=ot,E.ChaosMaker=Ie,E.createPrng=it,E.generateSeed=at,E.presets=Cs,E.validateConfig=nt,Object.defineProperty(E,Symbol.toStringTag,{value:"Module"})}));
|
package/dist/types/config.d.ts
CHANGED
|
@@ -117,6 +117,21 @@ export interface ChaosConfig {
|
|
|
117
117
|
network?: NetworkConfig;
|
|
118
118
|
ui?: UiConfig;
|
|
119
119
|
websocket?: WebSocketConfig;
|
|
120
|
-
/**
|
|
120
|
+
/**
|
|
121
|
+
* Seed for Chaos Maker's PRNG.
|
|
122
|
+
*
|
|
123
|
+
* The seed controls every probability-driven chaos decision across network,
|
|
124
|
+
* UI, and WebSocket rules. With the same seed and the same interaction
|
|
125
|
+
* sequence, Chaos Maker emits the same `ChaosEvent` decision sequence after
|
|
126
|
+
* normalizing runtime-only fields such as `timestamp`.
|
|
127
|
+
*
|
|
128
|
+
* When omitted, Chaos Maker auto-generates a seed from `Math.random()` during
|
|
129
|
+
* instance creation. Read it with the adapter's `getChaosSeed()` helper and
|
|
130
|
+
* log it on failure to replay the run.
|
|
131
|
+
*
|
|
132
|
+
* The seed does not control browser-native nondeterminism, wall-clock
|
|
133
|
+
* timestamps, network/server timing, or task-scheduler ordering in the app
|
|
134
|
+
* under test.
|
|
135
|
+
*/
|
|
121
136
|
seed?: number;
|
|
122
137
|
}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { UiConfig } from '../config';
|
|
2
2
|
import { ChaosEventEmitter } from '../events';
|
|
3
|
-
export declare function attachDomAssailant(config: UiConfig,
|
|
3
|
+
export declare function attachDomAssailant(config: UiConfig, random: () => number, emitter?: ChaosEventEmitter): MutationObserver;
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { NetworkConfig } from '../config';
|
|
2
2
|
import { ChaosEventEmitter } from '../events';
|
|
3
|
-
export declare function patchFetch(originalFetch: typeof window.fetch, config: NetworkConfig,
|
|
3
|
+
export declare function patchFetch(originalFetch: typeof window.fetch, config: NetworkConfig, random: () => number, emitter?: ChaosEventEmitter, counters?: Map<object, number>): (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import { NetworkConfig } from '../config';
|
|
2
2
|
import { ChaosEventEmitter } from '../events';
|
|
3
|
-
export declare function patchXHR(originalXhrSend: (body?: Document | XMLHttpRequestBodyInit) => void, config: NetworkConfig,
|
|
3
|
+
export declare function patchXHR(originalXhrSend: (body?: Document | XMLHttpRequestBodyInit) => void, config: NetworkConfig, random: () => number, emitter?: ChaosEventEmitter, counters?: Map<object, number>): (this: XMLHttpRequest, body?: Document | XMLHttpRequestBodyInit) => void;
|
|
4
4
|
export declare function patchXHROpen(originalXhrOpen: (method: string, url: string | URL) => void): (this: XMLHttpRequest, method: string, url: string | URL) => void;
|
package/dist/types/utils.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { CorruptionStrategy, RequestCountingOptions } from './config';
|
|
2
|
-
export declare function shouldApplyChaos(probability: number, random
|
|
2
|
+
export declare function shouldApplyChaos(probability: number, random: () => number): boolean;
|
|
3
3
|
/**
|
|
4
4
|
* Increment the per-rule request counter and return the new count.
|
|
5
5
|
* Keyed by the rule object reference so the same counter is shared across
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chaos-maker/core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "A lightweight, framework-agnostic toolkit for injecting chaos into web applications to test frontend resilience",
|
|
6
6
|
"keywords": [
|
|
@@ -52,8 +52,8 @@
|
|
|
52
52
|
"@vitejs/plugin-basic-ssl": "^1.1.0",
|
|
53
53
|
"jsdom": "^27.0.1",
|
|
54
54
|
"typescript": "^5.4.5",
|
|
55
|
-
"vite": "^
|
|
56
|
-
"vitest": "^
|
|
55
|
+
"vite": "^6.4.2",
|
|
56
|
+
"vitest": "^3.2.4"
|
|
57
57
|
},
|
|
58
58
|
"scripts": {
|
|
59
59
|
"dev": "vite build --watch",
|