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