nexsight 0.6.1 → 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/insight4.min.js CHANGED
@@ -1 +1 @@
1
- !function(){function e(){return nexusclient.variables()}var t=["insight4"];function n(e,n){const r=`insight4.${e}`;return eventStream.registerEvent(e,n,{id:r,tags:t}),()=>{eventStream.removeListener(e,r)}}var r=Object.freeze({display:Object.freeze(["addLine"]),storage:Object.freeze(["get","set","clear"]),triggers:Object.freeze(["register","unregister"]),events:Object.freeze(["onSkillMatch","on","raise"]),gmcp:Object.freeze(["read"]),text:Object.freeze(["snapshot"]),clock:Object.freeze(["now","setTimer","clearTimer"])}),i={display:["addStream"]};Object.freeze(["events.onSkillMatch","events.on"]);function s(e){const t=function(e){if(null===e||"object"!=typeof e)return["adapter is not an object"];const t=[];for(const[n,i]of Object.entries(r)){const r=e[n];if(null!==r&&"object"==typeof r)for(const e of i)"function"!=typeof r[e]&&t.push(`${n}.${e} is not a function`);else t.push(`${n} is missing`)}for(const[n,r]of Object.entries(i)){const i=e[n];if(null!==i&&"object"==typeof i)for(const e of r)void 0!==i[e]&&"function"!=typeof i[e]&&t.push(`${n}.${e} is not a function`)}return t}(e);if(t.length>0)throw new Error(`Adapter contract violation: ${t.join("; ")}`);return e}var a,o=/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/,d="nexsight",l=`https://unpkg.com/${d}@latest/package.json`,c=e=>{const t=o.exec(String(e??"").trim());if(!t)throw new Error(`invalid version '${e??""}'`);return{core:t.slice(1,4).map(Number),prerelease:t[4]?.split(".")??[]}},f=(e,t)=>{const n=/^\d+$/.test(e)?Number(e):null,r=/^\d+$/.test(t)?Number(t):null;return null!==n&&null!==r?Math.sign(n-r):null!==n?-1:null!==r?1:e===t?0:e<t?-1:1},u=(e,t,n)=>{try{e?.({text:t,severity:n})}catch{}},p=async({enabled:e=!1,currentVersion:t,notice:n=null,fetchFn:r=globalThis.fetch,consoleObj:i=console,setTimeoutFn:s=setTimeout,clearTimeoutFn:a=clearTimeout,timeoutMs:o=1e4,url:p=l}={})=>{if(!e)return null;let h=null;try{if("function"!=typeof r)throw new Error("fetch is not available");c(t);const e=globalThis.AbortController;let i;if(e&&o>0){const t=new e;h=s(()=>t.abort(),o),i=t.signal}const a=await r(p,{cache:"no-store",...i?{signal:i}:{}});if(!a?.ok)throw new Error(`${a?.status??"no"} response from ${p}`);const l=(await a.json())?.version;if(c(l),((e,t)=>{const n=c(e),r=c(t);for(let s=0;s<n.core.length;s+=1)if(n.core[s]!==r.core[s])return Math.sign(n.core[s]-r.core[s]);if(0===n.prerelease.length||0===r.prerelease.length)return n.prerelease.length===r.prerelease.length?0:0===n.prerelease.length?1:-1;const i=Math.max(n.prerelease.length,r.prerelease.length);for(let s=0;s<i;s+=1){if(void 0===n.prerelease[s])return-1;if(void 0===r.prerelease[s])return 1;const e=f(n.prerelease[s],r.prerelease[s]);if(0!==e)return e}return 0})(l,t)<=0)return null;const m=(e=>`https://unpkg.com/${d}@${e}/insight4.nxs`)(l);return u(n,`Update available: ${t} → ${l}. Import ${m}`,"warning"),{currentVersion:t,latestVersion:l,url:m}}catch(m){const e="AbortError"===m?.name?"Update check timed out — check your connection.":`Update check failed: ${m?.message??String(m)}`;return i.error(`[insight4] ${e}`),u(n,e,"error"),null}finally{null!==h&&a(h)}};function h(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,"_zod",{value:{def:r,constr:a,traits:new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);const i=a.prototype,s=Object.keys(i);for(let e=0;e<s.length;e++){const t=s[e];t in n||(n[t]=i[t].bind(n))}}const i=n?.Parent??Object;class s extends i{}function a(e){var t;const i=n?.Parent?new s:this;r(i,e),(t=i._zod).deferred??(t.deferred=[]);for(const n of i._zod.deferred)n();return i}return Object.defineProperty(s,"name",{value:e}),Object.defineProperty(a,"init",{value:r}),Object.defineProperty(a,Symbol.hasInstance,{value:t=>!!(n?.Parent&&t instanceof n.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(a,"name",{value:e}),a}var m=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},g=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}};(a=globalThis).__zod_globalConfig??(a.__zod_globalConfig={});var y=globalThis.__zod_globalConfig;function b(e){return e&&Object.assign(y,e),y}function v(e){const t=Object.values(e).filter(e=>"number"==typeof e);return Object.entries(e).filter(([e,n])=>-1===t.indexOf(+e)).map(([e,t])=>t)}function k(e,t){return"bigint"==typeof t?t.toString():t}function w(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function I(e){return null==e}function z(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}var _=Symbol("evaluating");function O(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==_)return void 0===r&&(r=_,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function $(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function S(...e){const t={};for(const n of e)Object.assign(t,Object.getOwnPropertyDescriptors(n));return Object.defineProperties({},t)}function N(e){return JSON.stringify(e)}var x="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function j(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var M=w(()=>{if(y.jitless)return!1;if("undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function T(e){if(!1===j(e))return!1;const t=e.constructor;if(void 0===t)return!0;if("function"!=typeof t)return!0;const n=t.prototype;return!1!==j(n)&&!1!==Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")}function A(e){return T(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}var E=new Set(["string","number","symbol"]);function C(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function P(e,t,n){const r=new e._zod.constr(t??e._zod.def);return t&&!n?.parent||(r._zod.parent=e),r}function R(e){const t=e;if(!t)return{};if("string"==typeof t)return{error:()=>t};if(void 0!==t?.message){if(void 0!==t?.error)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,"string"==typeof t.error?{...t,error:()=>t.error}:t}var Z={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function D(e,t=0){if(!0===e.aborted)return!0;for(let n=t;n<e.issues.length;n++)if(!0!==e.issues[n]?.continue)return!0;return!1}function F(e,t=0){if(!0===e.aborted)return!0;for(let n=t;n<e.issues.length;n++)if(!1===e.issues[n]?.continue)return!0;return!1}function L(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function q(e){return"string"==typeof e?e:e?.message}function B(e,t,n){const r=e.message?e.message:q(e.inst?._zod.def?.error?.(e))??q(t?.error?.(e))??q(n.customError?.(e))??q(n.localeError?.(e))??"Invalid input",{inst:i,continue:s,input:a,...o}=e;return o.path??(o.path=[]),o.message=r,t?.reportInput&&(o.input=a),o}function G(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function J(...e){const[t,n,r]=e;return"string"==typeof t?{message:t,code:"custom",input:n,inst:r}:{...t}}var U=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,k,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},H=h("$ZodError",U),V=h("$ZodError",U,{Parent:Error});var Y=e=>(t,n,r,i)=>{const s=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},s);if(a instanceof Promise)throw new m;if(a.issues.length){const t=new(i?.Err??e)(a.issues.map(e=>B(e,s,b())));throw x(t,i?.callee),t}return a.value},W=e=>async(t,n,r,i)=>{const s=r?{...r,async:!0}:{async:!0};let a=t._zod.run({value:n,issues:[]},s);if(a instanceof Promise&&(a=await a),a.issues.length){const t=new(i?.Err??e)(a.issues.map(e=>B(e,s,b())));throw x(t,i?.callee),t}return a.value},K=e=>(t,n,r)=>{const i=r?{...r,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw new m;return s.issues.length?{success:!1,error:new(e??H)(s.issues.map(e=>B(e,i,b())))}:{success:!0,data:s.value}},Q=K(V),X=e=>async(t,n,r)=>{const i=r?{...r,async:!0}:{async:!0};let s=t._zod.run({value:n,issues:[]},i);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(e=>B(e,i,b())))}:{success:!0,data:s.value}},ee=X(V),te=e=>(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return Y(e)(t,n,i)},ne=e=>(t,n,r)=>Y(e)(t,n,r),re=e=>async(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return W(e)(t,n,i)},ie=e=>async(t,n,r)=>W(e)(t,n,r),se=e=>(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return K(e)(t,n,i)},ae=e=>(t,n,r)=>K(e)(t,n,r),oe=e=>async(t,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return X(e)(t,n,i)},de=e=>async(t,n,r)=>X(e)(t,n,r),le=/^[cC][0-9a-z]{6,}$/,ce=/^[0-9a-z]+$/,fe=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,ue=/^[0-9a-vA-V]{20}$/,pe=/^[A-Za-z0-9]{27}$/,he=/^[a-zA-Z0-9_-]{21}$/,me=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,ge=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,ye=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,be=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var ve=/^(?:(?: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])$/,ke=/^(([0-9a-fA-F]{1,4}:){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}|:))$/,we=/^((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])\/([0-9]|[1-2][0-9]|3[0-2])$/,Ie=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,ze=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,_e=/^[A-Za-z0-9_-]*$/,Oe=/^https?$/,$e=/^\+[1-9]\d{6,14}$/,Se="(?:(?:\\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])))",Ne=new RegExp(`^${Se}$`);function xe(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof e.precision?-1===e.precision?`${t}`:0===e.precision?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}var je=/^-?\d+$/,Me=/^-?\d+(?:\.\d+)?$/,Te=/^(?:true|false)$/i,Ae=/^[^A-Z]*$/,Ee=/^[^a-z]*$/,Ce=h("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Pe={number:"number",bigint:"bigint",object:"date"},Re=h("$ZodCheckLessThan",(e,t)=>{Ce.init(e,t);const n=Pe[typeof t.value];e._zod.onattach.push(e=>{const n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:"too_big",maximum:"object"==typeof t.value?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Ze=h("$ZodCheckGreaterThan",(e,t)=>{Ce.init(e,t);const n=Pe[typeof t.value];e._zod.onattach.push(e=>{const n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:"object"==typeof t.value?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),De=h("$ZodCheckMultipleOf",(e,t)=>{Ce.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof n.value?n.value%t.value!==BigInt(0):0!==function(e,t){const n=e/t,r=Math.round(n),i=Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-r)<i?0:n-r}(n.value,t.value))&&n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Fe=h("$ZodCheckNumberFormat",(e,t)=>{Ce.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),r=n?"int":"number",[i,s]=Z[t.format];e._zod.onattach.push(e=>{const r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=s,n&&(r.pattern=je)}),e._zod.check=a=>{const o=a.value;if(n){if(!Number.isInteger(o))return void a.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:o,inst:e});if(!Number.isSafeInteger(o))return void(o>0?a.issues.push({input:o,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort}):a.issues.push({input:o,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort}))}o<i&&a.issues.push({origin:"number",input:o,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),o>s&&a.issues.push({origin:"number",input:o,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}}),Le=h("$ZodCheckMaxLength",(e,t)=>{var n;Ce.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!I(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{const r=n.value;if(r.length<=t.maximum)return;const i=G(r);n.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),qe=h("$ZodCheckMinLength",(e,t)=>{var n;Ce.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!I(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{const r=n.value;if(r.length>=t.minimum)return;const i=G(r);n.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Be=h("$ZodCheckLengthEquals",(e,t)=>{var n;Ce.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!I(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{const r=n.value,i=r.length;if(i===t.length)return;const s=G(r),a=i>t.length;n.issues.push({origin:s,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Ge=h("$ZodCheckStringFormat",(e,t)=>{var n,r;Ce.init(e,t),e._zod.onattach.push(e=>{const n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??(n.patterns=new Set),n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),Je=h("$ZodCheckRegex",(e,t)=>{Ge.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Ue=h("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Ae),Ge.init(e,t)}),He=h("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Ee),Ge.init(e,t)}),Ve=h("$ZodCheckIncludes",(e,t)=>{Ce.init(e,t);const n=C(t.includes),r=new RegExp("number"==typeof t.position?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),Ye=h("$ZodCheckStartsWith",(e,t)=>{Ce.init(e,t);const n=new RegExp(`^${C(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),We=h("$ZodCheckEndsWith",(e,t)=>{Ce.init(e,t);const n=new RegExp(`.*${C(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),Ke=h("$ZodCheckOverwrite",(e,t)=>{Ce.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}}),Qe=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if("function"==typeof e)return e(this,{execution:"sync"}),void e(this,{execution:"async"});const t=e.split("\n").filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>" ".repeat(2*this.indent)+e);for(const i of r)this.content.push(i)}compile(){const e=Function,t=this?.args;return new e(...t,[...(this?.content??[""]).map(e=>` ${e}`)].join("\n"))}},Xe={major:4,minor:4,patch:3},et=h("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Xe;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const i of r)for(const t of i._zod.onattach)t(e);if(0===r.length)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const t=(e,t,n)=>{let r,i=D(e);for(const s of t){if(s._zod.def.when){if(F(e))continue;if(!s._zod.def.when(e))continue}else if(i)continue;const t=e.issues.length,a=s._zod.check(e);if(a instanceof Promise&&!1===n?.async)throw new m;if(r||a instanceof Promise)r=(r??Promise.resolve()).then(async()=>{await a,e.issues.length!==t&&(i||(i=D(e,t)))});else{if(e.issues.length===t)continue;i||(i=D(e,t))}}return r?r.then(()=>e):e},n=(n,i,s)=>{if(D(n))return n.aborted=!0,n;const a=t(i,r,s);if(a instanceof Promise){if(!1===s.async)throw new m;return a.then(t=>e._zod.parse(t,s))}return e._zod.parse(a,s)};e._zod.run=(i,s)=>{if(s.skipChecks)return e._zod.parse(i,s);if("backward"===s.direction){const t=e._zod.parse({value:i.value,issues:[]},{...s,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,i,s)):n(t,i,s)}const a=e._zod.parse(i,s);if(a instanceof Promise){if(!1===s.async)throw new m;return a.then(e=>t(e,r,s))}return t(a,r,s)}}O(e,"~standard",()=>({validate:t=>{try{const n=Q(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch(n){return ee(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}))}),tt=h("$ZodString",(e,t)=>{var n;et.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??(n=e._zod.bag,new RegExp(`^${n?`[\\s\\S]{${n?.minimum??0},${n?.maximum??""}}`:"[\\s\\S]*"}$`)),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch(r){}return"string"==typeof n.value||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),nt=h("$ZodStringFormat",(e,t)=>{Ge.init(e,t),tt.init(e,t)}),rt=h("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=ge),nt.init(e,t)}),it=h("$ZodUUID",(e,t)=>{if(t.version){const e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(void 0===e)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=ye(e))}else t.pattern??(t.pattern=ye());nt.init(e,t)}),st=h("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=be),nt.init(e,t)}),at=h("$ZodURL",(e,t)=>{nt.init(e,t),e._zod.check=n=>{try{const r=n.value.trim();if(!t.normalize&&t.protocol?.source===Oe.source&&!/^https?:\/\//i.test(r))return void n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});const i=new URL(r);return t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),void(t.normalize?n.value=i.href:n.value=r)}catch(r){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),ot=h("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),nt.init(e,t)}),dt=h("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=he),nt.init(e,t)}),lt=h("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=le),nt.init(e,t)}),ct=h("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=ce),nt.init(e,t)}),ft=h("$ZodULID",(e,t)=>{t.pattern??(t.pattern=fe),nt.init(e,t)}),ut=h("$ZodXID",(e,t)=>{t.pattern??(t.pattern=ue),nt.init(e,t)}),pt=h("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=pe),nt.init(e,t)}),ht=h("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=function(e){const t=xe({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${Se}T(?:${r})$`)}(t)),nt.init(e,t)}),mt=h("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Ne),nt.init(e,t)}),gt=h("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=new RegExp(`^${xe(t)}$`)),nt.init(e,t)}),yt=h("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=me),nt.init(e,t)}),bt=h("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=ve),nt.init(e,t),e._zod.bag.format="ipv4"}),vt=h("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=ke),nt.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),kt=h("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=we),nt.init(e,t)}),wt=h("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Ie),nt.init(e,t),e._zod.check=n=>{const r=n.value.split("/");try{if(2!==r.length)throw new Error;const[e,t]=r;if(!t)throw new Error;const n=Number(t);if(`${n}`!==t)throw new Error;if(n<0||n>128)throw new Error;new URL(`http://[${e}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function It(e){if(""===e)return!0;if(/\s/.test(e))return!1;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}var zt=h("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=ze),nt.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{It(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});var _t=h("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=_e),nt.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{(function(e){if(!_e.test(e))return!1;const t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return It(t.padEnd(4*Math.ceil(t.length/4),"="))})(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),Ot=h("$ZodE164",(e,t)=>{t.pattern??(t.pattern=$e),nt.init(e,t)});var $t=h("$ZodJWT",(e,t)=>{nt.init(e,t),e._zod.check=n=>{(function(e,t=null){try{const n=e.split(".");if(3!==n.length)return!1;const[r]=n;if(!r)return!1;const i=JSON.parse(atob(r));return!("typ"in i&&"JWT"!==i?.typ||!i.alg||t&&(!("alg"in i)||i.alg!==t))}catch{return!1}})(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),St=h("$ZodNumber",(e,t)=>{et.init(e,t),e._zod.pattern=e._zod.bag.pattern??Me,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch(a){}const i=n.value;if("number"==typeof i&&!Number.isNaN(i)&&Number.isFinite(i))return n;const s="number"==typeof i?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...s?{received:s}:{}}),n}}),Nt=h("$ZodNumberFormat",(e,t)=>{Fe.init(e,t),St.init(e,t)}),xt=h("$ZodBoolean",(e,t)=>{et.init(e,t),e._zod.pattern=Te,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Boolean(n.value)}catch(s){}const i=n.value;return"boolean"==typeof i||n.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),n}}),jt=h("$ZodUnknown",(e,t)=>{et.init(e,t),e._zod.parse=e=>e}),Mt=h("$ZodNever",(e,t)=>{et.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)});function Tt(e,t,n){e.issues.length&&t.issues.push(...L(n,e.issues)),t.value[n]=e.value}var At=h("$ZodArray",(e,t)=>{et.init(e,t),e._zod.parse=(n,r)=>{const i=n.value;if(!Array.isArray(i))return n.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),n;n.value=Array(i.length);const s=[];for(let e=0;e<i.length;e++){const a=i[e],o=t.element._zod.run({value:a,issues:[]},r);o instanceof Promise?s.push(o.then(t=>Tt(t,n,e))):Tt(o,n,e)}return s.length?Promise.all(s).then(()=>n):n}});function Et(e,t,n,r,i,s){const a=n in r;if(e.issues.length){if(i&&s&&!a)return;t.issues.push(...L(n,e.issues))}a||i?void 0===e.value?a&&(t.value[n]=void 0):t.value[n]=e.value:e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]})}function Ct(e){const t=Object.keys(e.shape);for(const i of t)if(!e.shape?.[i]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${i}": expected a Zod schema`);const n=(r=e.shape,Object.keys(r).filter(e=>"optional"===r[e]._zod.optin&&"optional"===r[e]._zod.optout));var r;return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function Pt(e,t,n,r,i,s){const a=[],o=i.keySet,d=i.catchall._zod,l=d.def.type,c="optional"===d.optin,f="optional"===d.optout;for(const u in t){if("__proto__"===u)continue;if(o.has(u))continue;if("never"===l){a.push(u);continue}const i=d.run({value:t[u],issues:[]},r);i instanceof Promise?e.push(i.then(e=>Et(e,n,u,t,c,f))):Et(i,n,u,t,c,f)}return a.length&&n.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:s}),e.length?Promise.all(e).then(()=>n):n}var Rt=h("$ZodObject",(e,t)=>{if(et.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const e=t.shape;Object.defineProperty(t,"shape",{get:()=>{const n={...e};return Object.defineProperty(t,"shape",{value:n}),n}})}const n=w(()=>Ct(t));O(e._zod,"propValues",()=>{const e=t.shape,n={};for(const t in e){const r=e[t]._zod;if(r.values){n[t]??(n[t]=new Set);for(const e of r.values)n[t].add(e)}}return n});const r=j,i=t.catchall;let s;e._zod.parse=(t,a)=>{s??(s=n.value);const o=t.value;if(!r(o))return t.issues.push({expected:"object",code:"invalid_type",input:o,inst:e}),t;t.value={};const d=[],l=s.shape;for(const e of s.keys){const n=l[e],r="optional"===n._zod.optin,i="optional"===n._zod.optout,s=n._zod.run({value:o[e],issues:[]},a);s instanceof Promise?d.push(s.then(n=>Et(n,t,e,o,r,i))):Et(s,t,e,o,r,i)}return i?Pt(d,o,t,a,n.value,e):d.length?Promise.all(d).then(()=>t):t}}),Zt=h("$ZodObjectJIT",(e,t)=>{Rt.init(e,t);const n=e._zod.parse,r=w(()=>Ct(t));let i;const s=j,a=!y.jitless,o=a&&M.value,d=t.catchall;let l;e._zod.parse=(c,f)=>{l??(l=r.value);const u=c.value;return s(u)?a&&o&&!1===f?.async&&!0!==f.jitless?(i||(i=(e=>{const t=new Qe(["shape","payload","ctx"]),n=r.value,i=e=>{const t=N(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");const s=Object.create(null);let a=0;for(const r of n.keys)s[r]="key_"+a++;t.write("const newResult = {};");for(const r of n.keys){const n=s[r],a=N(r),o=e[r],d="optional"===o?._zod?.optin,l="optional"===o?._zod?.optout;t.write(`const ${n} = ${i(r)};`),d&&l?t.write(`\n if (${n}.issues.length) {\n if (${a} in input) {\n payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${a}, ...iss.path] : [${a}]\n })));\n }\n }\n \n if (${n}.value === undefined) {\n if (${a} in input) {\n newResult[${a}] = undefined;\n }\n } else {\n newResult[${a}] = ${n}.value;\n }\n \n `):d?t.write(`\n if (${n}.issues.length) {\n payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${a}, ...iss.path] : [${a}]\n })));\n }\n \n if (${n}.value === undefined) {\n if (${a} in input) {\n newResult[${a}] = undefined;\n }\n } else {\n newResult[${a}] = ${n}.value;\n }\n \n `):t.write(`\n const ${n}_present = ${a} in input;\n if (${n}.issues.length) {\n payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${a}, ...iss.path] : [${a}]\n })));\n }\n if (!${n}_present && !${n}.issues.length) {\n payload.issues.push({\n code: "invalid_type",\n expected: "nonoptional",\n input: undefined,\n path: [${a}]\n });\n }\n\n if (${n}_present) {\n if (${n}.value === undefined) {\n newResult[${a}] = undefined;\n } else {\n newResult[${a}] = ${n}.value;\n }\n }\n\n `)}t.write("payload.value = newResult;"),t.write("return payload;");const o=t.compile();return(t,n)=>o(e,t,n)})(t.shape)),c=i(c,f),d?Pt([],u,c,f,l,e):c):n(c,f):(c.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),c)}});function Dt(e,t,n,r){for(const s of e)if(0===s.issues.length)return t.value=s.value,t;const i=e.filter(e=>!D(e));return 1===i.length?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>B(e,r,b())))}),t)}var Ft=h("$ZodUnion",(e,t)=>{et.init(e,t),O(e._zod,"optin",()=>t.options.some(e=>"optional"===e._zod.optin)?"optional":void 0),O(e._zod,"optout",()=>t.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),O(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),O(e._zod,"pattern",()=>{if(t.options.every(e=>e._zod.pattern)){const e=t.options.map(e=>e._zod.pattern);return new RegExp(`^(${e.map(e=>z(e.source)).join("|")})$`)}});const n=1===t.options.length?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let s=!1;const a=[];for(const e of t.options){const t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)a.push(t),s=!0;else{if(0===t.issues.length)return t;a.push(t)}}return s?Promise.all(a).then(t=>Dt(t,r,e,i)):Dt(a,r,e,i)}}),Lt=h("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Ft.init(e,t);const n=e._zod.parse;O(e._zod,"propValues",()=>{const e={};for(const n of t.options){const r=n._zod.propValues;if(!r||0===Object.keys(r).length)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(n)}"`);for(const[t,n]of Object.entries(r)){e[t]||(e[t]=new Set);for(const r of n)e[t].add(r)}}return e});const r=w(()=>{const e=t.options,n=new Map;for(const r of e){const e=r._zod.propValues?.[t.discriminator];if(!e||0===e.size)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(const t of e){if(n.has(t))throw new Error(`Duplicate discriminator value "${String(t)}"`);n.set(t,r)}}return n});e._zod.parse=(i,s)=>{const a=i.value;if(!j(a))return i.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),i;const o=r.value.get(a?.[t.discriminator]);return o?o._zod.run(i,s):t.unionFallback||"backward"===s.direction?n(i,s):(i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(r.value.keys()),input:a,path:[t.discriminator],inst:e}),i)}}),qt=h("$ZodIntersection",(e,t)=>{et.init(e,t),e._zod.parse=(e,n)=>{const r=e.value,i=t.left._zod.run({value:r,issues:[]},n),s=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||s instanceof Promise?Promise.all([i,s]).then(([t,n])=>Gt(e,t,n)):Gt(e,i,s)}});function Bt(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(T(e)&&T(t)){const n=Object.keys(t),r=Object.keys(e).filter(e=>-1!==n.indexOf(e)),i={...e,...t};for(const s of r){const n=Bt(e[s],t[s]);if(!n.valid)return{valid:!1,mergeErrorPath:[s,...n.mergeErrorPath]};i[s]=n.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<e.length;r++){const i=Bt(e[r],t[r]);if(!i.valid)return{valid:!1,mergeErrorPath:[r,...i.mergeErrorPath]};n.push(i.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Gt(e,t,n){const r=new Map;let i;for(const o of t.issues)if("unrecognized_keys"===o.code){i??(i=o);for(const e of o.keys)r.has(e)||r.set(e,{}),r.get(e).l=!0}else e.issues.push(o);for(const o of n.issues)if("unrecognized_keys"===o.code)for(const e of o.keys)r.has(e)||r.set(e,{}),r.get(e).r=!0;else e.issues.push(o);const s=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(s.length&&i&&e.issues.push({...i,keys:s}),D(e))return e;const a=Bt(t.value,n.value);if(!a.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(a.mergeErrorPath)}`);return e.value=a.data,e}var Jt=h("$ZodRecord",(e,t)=>{et.init(e,t),e._zod.parse=(n,r)=>{const i=n.value;if(!T(i))return n.issues.push({expected:"record",code:"invalid_type",input:i,inst:e}),n;const s=[],a=t.keyType._zod.values;if(a){n.value={};const o=new Set;for(const l of a)if("string"==typeof l||"number"==typeof l||"symbol"==typeof l){o.add("number"==typeof l?l.toString():l);const a=t.keyType._zod.run({value:l,issues:[]},r);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:a.issues.map(e=>B(e,r,b())),input:l,path:[l],inst:e});continue}const d=a.value,c=t.valueType._zod.run({value:i[l],issues:[]},r);c instanceof Promise?s.push(c.then(e=>{e.issues.length&&n.issues.push(...L(l,e.issues)),n.value[d]=e.value})):(c.issues.length&&n.issues.push(...L(l,c.issues)),n.value[d]=c.value)}let d;for(const e in i)o.has(e)||(d=d??[],d.push(e));d&&d.length>0&&n.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:d})}else{n.value={};for(const a of Reflect.ownKeys(i)){if("__proto__"===a)continue;if(!Object.prototype.propertyIsEnumerable.call(i,a))continue;let o=t.keyType._zod.run({value:a,issues:[]},r);if(o instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if("string"==typeof a&&Me.test(a)&&o.issues.length){const e=t.keyType._zod.run({value:Number(a),issues:[]},r);if(e instanceof Promise)throw new Error("Async schemas not supported in object keys currently");0===e.issues.length&&(o=e)}if(o.issues.length){"loose"===t.mode?n.value[a]=i[a]:n.issues.push({code:"invalid_key",origin:"record",issues:o.issues.map(e=>B(e,r,b())),input:a,path:[a],inst:e});continue}const d=t.valueType._zod.run({value:i[a],issues:[]},r);d instanceof Promise?s.push(d.then(e=>{e.issues.length&&n.issues.push(...L(a,e.issues)),n.value[o.value]=e.value})):(d.issues.length&&n.issues.push(...L(a,d.issues)),n.value[o.value]=d.value)}}return s.length?Promise.all(s).then(()=>n):n}}),Ut=h("$ZodEnum",(e,t)=>{et.init(e,t);const n=v(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(e=>E.has(typeof e)).map(e=>"string"==typeof e?C(e):e.toString()).join("|")})$`),e._zod.parse=(t,i)=>{const s=t.value;return r.has(s)||t.issues.push({code:"invalid_value",values:n,input:s,inst:e}),t}}),Ht=h("$ZodLiteral",(e,t)=>{if(et.init(e,t),0===t.values.length)throw new Error("Cannot create literal schema with no valid values");const n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map(e=>"string"==typeof e?C(e):e?C(e.toString()):String(e)).join("|")})$`),e._zod.parse=(r,i)=>{const s=r.value;return n.has(s)||r.issues.push({code:"invalid_value",values:t.values,input:s,inst:e}),r}}),Vt=h("$ZodTransform",(e,t)=>{et.init(e,t),e._zod.optin="optional",e._zod.parse=(n,r)=>{if("backward"===r.direction)throw new g(e.constructor.name);const i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n.fallback=!0,n));if(i instanceof Promise)throw new m;return n.value=i,n.fallback=!0,n}});function Yt(e,t){return void 0===t&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}var Wt=h("$ZodOptional",(e,t)=>{et.init(e,t),e._zod.optin="optional",e._zod.optout="optional",O(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),O(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${z(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if("optional"===t.innerType._zod.optin){const r=e.value,i=t.innerType._zod.run(e,n);return i instanceof Promise?i.then(e=>Yt(e,r)):Yt(i,r)}return void 0===e.value?e:t.innerType._zod.run(e,n)}}),Kt=h("$ZodExactOptional",(e,t)=>{Wt.init(e,t),O(e._zod,"values",()=>t.innerType._zod.values),O(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),Qt=h("$ZodNullable",(e,t)=>{et.init(e,t),O(e._zod,"optin",()=>t.innerType._zod.optin),O(e._zod,"optout",()=>t.innerType._zod.optout),O(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${z(e.source)}|null)$`):void 0}),O(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>null===e.value?e:t.innerType._zod.run(e,n)}),Xt=h("$ZodDefault",(e,t)=>{et.init(e,t),e._zod.optin="optional",O(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);if(void 0===e.value)return e.value=t.defaultValue,e;const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>en(e,t)):en(r,t)}});function en(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}var tn=h("$ZodPrefault",(e,t)=>{et.init(e,t),e._zod.optin="optional",O(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>("backward"===n.direction||void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),nn=h("$ZodNonOptional",(e,t)=>{et.init(e,t),O(e._zod,"values",()=>{const e=t.innerType._zod.values;return e?new Set([...e].filter(e=>void 0!==e)):void 0}),e._zod.parse=(n,r)=>{const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>rn(t,e)):rn(i,e)}});function rn(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}var sn=h("$ZodCatch",(e,t)=>{et.init(e,t),e._zod.optin="optional",O(e._zod,"optout",()=>t.innerType._zod.optout),O(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>B(e,n,b()))},input:e.value}),e.issues=[],e.fallback=!0),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>B(e,n,b()))},input:e.value}),e.issues=[],e.fallback=!0),e)}}),an=h("$ZodPipe",(e,t)=>{et.init(e,t),O(e._zod,"values",()=>t.in._zod.values),O(e._zod,"optin",()=>t.in._zod.optin),O(e._zod,"optout",()=>t.out._zod.optout),O(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if("backward"===n.direction){const r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>on(e,t.in,n)):on(r,t.in,n)}const r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>on(e,t.out,n)):on(r,t.out,n)}});function on(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}var dn=h("$ZodReadonly",(e,t)=>{et.init(e,t),O(e._zod,"propValues",()=>t.innerType._zod.propValues),O(e._zod,"values",()=>t.innerType._zod.values),O(e._zod,"optin",()=>t.innerType?._zod?.optin),O(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(ln):ln(r)}});function ln(e){return e.value=Object.freeze(e.value),e}var cn,fn=h("$ZodCustom",(e,t)=>{Ce.init(e,t),et.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{const r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>un(t,n,r,e));un(i,n,r,e)}});function un(e,t,n,r){if(!e){const e={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(J(e))}}var pn=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){const n=t[0];return this._map.set(e,n),n&&"object"==typeof n&&"id"in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const n={...this.get(t)??{}};delete n.id;const r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};(cn=globalThis).__zod_globalRegistry??(cn.__zod_globalRegistry=new pn);var hn=globalThis.__zod_globalRegistry;function mn(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...R(t)})}function gn(e,t){return new Re({check:"less_than",...R(t),value:e,inclusive:!1})}function yn(e,t){return new Re({check:"less_than",...R(t),value:e,inclusive:!0})}function bn(e,t){return new Ze({check:"greater_than",...R(t),value:e,inclusive:!1})}function vn(e,t){return new Ze({check:"greater_than",...R(t),value:e,inclusive:!0})}function kn(e,t){return new De({check:"multiple_of",...R(t),value:e})}function wn(e,t){return new Le({check:"max_length",...R(t),maximum:e})}function In(e,t){return new qe({check:"min_length",...R(t),minimum:e})}function zn(e,t){return new Be({check:"length_equals",...R(t),length:e})}function _n(e){return new Ke({check:"overwrite",tx:e})}function On(e,t){const n=new Ce({check:"custom",...R(t)});return n._zod.check=e,n}function $n(e){let t=e?.target??"draft-2020-12";return"draft-4"===t&&(t="draft-04"),"draft-7"===t&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??hn,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function Sn(e,t,n={path:[],schemaPath:[]}){var r;const i=e._zod.def,s=t.seen.get(e);if(s)return s.count++,n.schemaPath.includes(e)&&(s.cycle=n.path),s.schema;const a={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,a);const o=e._zod.toJSONSchema?.();if(o)a.schema=o;else{const r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,a.schema,r);else{const n=a.schema,s=t.processors[i.type];if(!s)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);s(e,t,n,r)}const s=e._zod.parent;s&&(a.ref||(a.ref=s),Sn(s,t,r),t.seen.get(s).isParent=!0)}const d=t.metadataRegistry.get(e);return d&&Object.assign(a.schema,d),"input"===t.io&&jn(e)&&(delete a.schema.examples,delete a.schema.default),"input"===t.io&&"_prefault"in a.schema&&((r=a.schema).default??(r.default=a.schema._prefault)),delete a.schema._prefault,t.seen.get(e).schema}function Nn(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=new Map;for(const s of e.seen.entries()){const t=e.metadataRegistry.get(s[0])?.id;if(t){const e=r.get(t);if(e&&e!==s[0])throw new Error(`Duplicate schema id "${t}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(t,s[0])}}const i=t=>{if(t[1].schema.$ref)return;const r=t[1],{ref:i,defId:s}=(t=>{const r="draft-2020-12"===e.target?"$defs":"definitions";if(e.external){const n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};const s=t[1].defId??t[1].schema.id??"schema"+e.counter++;return t[1].defId=s,{defId:s,ref:`${i("__shared")}#/${r}/${s}`}}if(t[1]===n)return{ref:"#"};const i=`#/${r}/`,s=t[1].schema.id??"__schema"+e.counter++;return{defId:s,ref:i+s}})(t);r.def={...r.schema},s&&(r.defId=s);const a=r.schema;for(const e in a)delete a[e];a.$ref=i};if("throw"===e.cycles)for(const s of e.seen.entries()){const e=s[1];if(e.cycle)throw new Error(`Cycle detected: #/${e.cycle?.join("/")}/<root>\n\nSet the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const s of e.seen.entries()){const n=s[1];if(t!==s[0]){if(e.external){const n=e.external.registry.get(s[0])?.id;if(t!==s[0]&&n){i(s);continue}}(e.metadataRegistry.get(s[0])?.id||n.cycle||n.count>1&&"ref"===e.reused)&&i(s)}else i(s)}}function xn(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=t=>{const n=e.seen.get(t);if(null===n.ref)return;const i=n.def??n.schema,s={...i},a=n.ref;if(n.ref=null,a){r(a);const n=e.seen.get(a),o=n.schema;if(!o.$ref||"draft-07"!==e.target&&"draft-04"!==e.target&&"openapi-3.0"!==e.target?Object.assign(i,o):(i.allOf=i.allOf??[],i.allOf.push(o)),Object.assign(i,s),t._zod.parent===a)for(const e in i)"$ref"!==e&&"allOf"!==e&&(e in s||delete i[e]);if(o.$ref&&n.def)for(const e in i)"$ref"!==e&&"allOf"!==e&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}const o=t._zod.parent;if(o&&o!==a){r(o);const t=e.seen.get(o);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(const e in i)"$ref"!==e&&"allOf"!==e&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};for(const d of[...e.seen.entries()].reverse())r(d[0]);const i={};if("draft-2020-12"===e.target?i.$schema="https://json-schema.org/draft/2020-12/schema":"draft-07"===e.target?i.$schema="http://json-schema.org/draft-07/schema#":"draft-04"===e.target?i.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const n=e.external.registry.get(t)?.id;if(!n)throw new Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Object.assign(i,n.def??n.schema);const s=e.metadataRegistry.get(t)?.id;void 0!==s&&i.id===s&&delete i.id;const a=e.external?.defs??{};for(const d of e.seen.entries()){const e=d[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,a[e.defId]=e.def)}e.external||Object.keys(a).length>0&&("draft-2020-12"===e.target?i.$defs=a:i.definitions=a);try{const n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t["~standard"],jsonSchema:{input:Mn(t,"input",e.processors),output:Mn(t,"output",e.processors)}},enumerable:!1,writable:!1}),n}catch(o){throw new Error("Error converting schema to JSON.")}}function jn(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const r=e._zod.def;if("transform"===r.type)return!0;if("array"===r.type)return jn(r.element,n);if("set"===r.type)return jn(r.valueType,n);if("lazy"===r.type)return jn(r.getter(),n);if("promise"===r.type||"optional"===r.type||"nonoptional"===r.type||"nullable"===r.type||"readonly"===r.type||"default"===r.type||"prefault"===r.type)return jn(r.innerType,n);if("intersection"===r.type)return jn(r.left,n)||jn(r.right,n);if("record"===r.type||"map"===r.type)return jn(r.keyType,n)||jn(r.valueType,n);if("pipe"===r.type)return!!e._zod.traits.has("$ZodCodec")||(jn(r.in,n)||jn(r.out,n));if("object"===r.type){for(const e in r.shape)if(jn(r.shape[e],n))return!0;return!1}if("union"===r.type){for(const e of r.options)if(jn(e,n))return!0;return!1}if("tuple"===r.type){for(const e of r.items)if(jn(e,n))return!0;return!(!r.rest||!jn(r.rest,n))}return!1}var Mn=(e,t,n={})=>r=>{const{libraryOptions:i,target:s}=r??{},a=$n({...i??{},target:s,io:t,processors:n});return Sn(e,a),Nn(a,e),xn(a,e)},Tn={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},An=(e,t,n,r)=>{const i=e._zod.def;Sn(i.innerType,t,r);t.seen.get(e).ref=i.innerType},En=h("ZodISODateTime",(e,t)=>{ht.init(e,t),dr.init(e,t)});function Cn(e){return function(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...R(t)})}(En,e)}var Pn=h("ZodISODate",(e,t)=>{mt.init(e,t),dr.init(e,t)});function Rn(e){return function(e,t){return new e({type:"string",format:"date",check:"string_format",...R(t)})}(Pn,e)}var Zn=h("ZodISOTime",(e,t)=>{gt.init(e,t),dr.init(e,t)});function Dn(e){return function(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...R(t)})}(Zn,e)}var Fn=h("ZodISODuration",(e,t)=>{yt.init(e,t),dr.init(e,t)});function Ln(e){return function(e,t){return new e({type:"string",format:"duration",check:"string_format",...R(t)})}(Fn,e)}var qn=(e,t)=>{H.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:t=>function(e,t=e=>e.message){const n={_errors:[]},r=(e,i=[])=>{for(const s of e.issues)if("invalid_union"===s.code&&s.errors.length)s.errors.map(e=>r({issues:e},[...i,...s.path]));else if("invalid_key"===s.code)r({issues:s.issues},[...i,...s.path]);else if("invalid_element"===s.code)r({issues:s.issues},[...i,...s.path]);else{const e=[...i,...s.path];if(0===e.length)n._errors.push(t(s));else{let r=n,i=0;for(;i<e.length;){const n=e[i];i!==e.length-1?r[n]=r[n]||{_errors:[]}:(r[n]=r[n]||{_errors:[]},r[n]._errors.push(t(s))),r=r[n],i++}}}};return r(e),n}(e,t)},flatten:{value:t=>function(e,t=e=>e.message){const n={},r=[];for(const i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,k,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,k,2)}},isEmpty:{get:()=>0===e.issues.length}})},Bn=h("ZodError",qn,{Parent:Error}),Gn=Y(Bn),Jn=W(Bn),Un=K(Bn),Hn=X(Bn),Vn=te(Bn),Yn=ne(Bn),Wn=re(Bn),Kn=ie(Bn),Qn=se(Bn),Xn=ae(Bn),er=oe(Bn),tr=de(Bn),nr=new WeakMap;function rr(e,t,n){const r=Object.getPrototypeOf(e);let i=nr.get(r);if(i||(i=new Set,nr.set(r,i)),!i.has(t)){i.add(t);for(const e in n){const t=n[e];Object.defineProperty(r,e,{configurable:!0,enumerable:!1,get(){const n=t.bind(this);return Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:n}),n},set(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t})}})}}}var ir=h("ZodType",(e,t)=>(et.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Mn(e,"input"),output:Mn(e,"output")}}),e.toJSONSchema=((e,t={})=>n=>{const r=$n({...n,processors:t});return Sn(e,r),Nn(r,e),xn(r,e)})(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(t,n)=>Gn(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Un(e,t,n),e.parseAsync=async(t,n)=>Jn(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Hn(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>Vn(e,t,n),e.decode=(t,n)=>Yn(e,t,n),e.encodeAsync=async(t,n)=>Wn(e,t,n),e.decodeAsync=async(t,n)=>Kn(e,t,n),e.safeEncode=(t,n)=>Qn(e,t,n),e.safeDecode=(t,n)=>Xn(e,t,n),e.safeEncodeAsync=async(t,n)=>er(e,t,n),e.safeDecodeAsync=async(t,n)=>tr(e,t,n),rr(e,"ZodType",{check(...e){const t=this.def;return this.clone(S(t,{checks:[...t.checks??[],...e.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return P(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(function(e,t={}){return function(e,t,n){return new e({type:"custom",check:"custom",fn:t,...R(n)})}(ui,e,t)}(e,t))},superRefine(e,t){return this.check(function(e,t){return function(e,t){const n=On(t=>(t.addIssue=e=>{if("string"==typeof e)t.issues.push(J(e,t.value,n._zod.def));else{const r=e;r.fatal&&(r.continue=!1),r.code??(r.code="custom"),r.input??(r.input=t.value),r.inst??(r.inst=n),r.continue??(r.continue=!n._zod.def.abort),t.issues.push(J(r))}},e(t.value,t)),t);return n}(e,t)}(e,t))},overwrite(e){return this.check(_n(e))},optional(){return ti(this)},exactOptional(){return new ni({type:"optional",innerType:this})},nullable(){return ii(this)},nullish(){return ti(ii(this))},nonoptional(e){return function(e,t){return new oi({type:"nonoptional",innerType:e,...R(t)})}(this,e)},array(){return Dr(this)},or(e){return Gr([this,e])},and(e){return new Ur({type:"intersection",left:this,right:e})},transform(e){return ci(this,new Xr({type:"transform",transform:e}))},default(e){return t=e,new si({type:"default",innerType:this,get defaultValue(){return"function"==typeof t?t():A(t)}});var t},prefault(e){return t=e,new ai({type:"prefault",innerType:this,get defaultValue(){return"function"==typeof t?t():A(t)}});var t},catch(e){return new di({type:"catch",innerType:this,catchValue:"function"==typeof(t=e)?t:()=>t});var t},pipe(e){return ci(this,e)},readonly(){return new fi({type:"readonly",innerType:this})},describe(e){const t=this.clone();return hn.add(t,{description:e}),t},meta(...e){if(0===e.length)return hn.get(this);const t=this.clone();return hn.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e){return e(this)}}),Object.defineProperty(e,"description",{get:()=>hn.get(e)?.description,configurable:!0}),e)),sr=h("_ZodString",(e,t)=>{tt.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=n;r.type="string";const{minimum:i,maximum:s,format:a,patterns:o,contentEncoding:d}=e._zod.bag;if("number"==typeof i&&(r.minLength=i),"number"==typeof s&&(r.maxLength=s),a&&(r.format=Tn[a]??a,""===r.format&&delete r.format,"time"===a&&delete r.format),d&&(r.contentEncoding=d),o&&o.size>0){const e=[...o];1===e.length?r.pattern=e[0].source:e.length>1&&(r.allOf=[...e.map(e=>({..."draft-07"===t.target||"draft-04"===t.target||"openapi-3.0"===t.target?{type:"string"}:{},pattern:e.source}))])}})(e,t,n);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,rr(e,"_ZodString",{regex(...e){return this.check(function(e,t){return new Je({check:"string_format",format:"regex",...R(t),pattern:e})}(...e))},includes(...e){return this.check(function(e,t){return new Ve({check:"string_format",format:"includes",...R(t),includes:e})}(...e))},startsWith(...e){return this.check(function(e,t){return new Ye({check:"string_format",format:"starts_with",...R(t),prefix:e})}(...e))},endsWith(...e){return this.check(function(e,t){return new We({check:"string_format",format:"ends_with",...R(t),suffix:e})}(...e))},min(...e){return this.check(In(...e))},max(...e){return this.check(wn(...e))},length(...e){return this.check(zn(...e))},nonempty(...e){return this.check(In(1,...e))},lowercase(e){return this.check(function(e){return new Ue({check:"string_format",format:"lowercase",...R(e)})}(e))},uppercase(e){return this.check(function(e){return new He({check:"string_format",format:"uppercase",...R(e)})}(e))},trim(){return this.check(_n(e=>e.trim()))},normalize(...e){return this.check(function(e){return _n(t=>t.normalize(e))}(...e))},toLowerCase(){return this.check(_n(e=>e.toLowerCase()))},toUpperCase(){return this.check(_n(e=>e.toUpperCase()))},slugify(){return this.check(_n(e=>function(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}(e)))}})}),ar=h("ZodString",(e,t)=>{tt.init(e,t),sr.init(e,t),e.email=t=>e.check(function(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...R(t)})}(lr,t)),e.url=t=>e.check(function(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...R(t)})}(ur,t)),e.jwt=t=>e.check(function(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...R(t)})}(Sr,t)),e.emoji=t=>e.check(function(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...R(t)})}(pr,t)),e.guid=t=>e.check(mn(cr,t)),e.uuid=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...R(t)})}(fr,t)),e.uuidv4=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...R(t)})}(fr,t)),e.uuidv6=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...R(t)})}(fr,t)),e.uuidv7=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...R(t)})}(fr,t)),e.nanoid=t=>e.check(function(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...R(t)})}(hr,t)),e.guid=t=>e.check(mn(cr,t)),e.cuid=t=>e.check(function(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...R(t)})}(mr,t)),e.cuid2=t=>e.check(function(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...R(t)})}(gr,t)),e.ulid=t=>e.check(function(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...R(t)})}(yr,t)),e.base64=t=>e.check(function(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...R(t)})}(_r,t)),e.base64url=t=>e.check(function(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...R(t)})}(Or,t)),e.xid=t=>e.check(function(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...R(t)})}(br,t)),e.ksuid=t=>e.check(function(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...R(t)})}(vr,t)),e.ipv4=t=>e.check(function(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...R(t)})}(kr,t)),e.ipv6=t=>e.check(function(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...R(t)})}(wr,t)),e.cidrv4=t=>e.check(function(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...R(t)})}(Ir,t)),e.cidrv6=t=>e.check(function(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...R(t)})}(zr,t)),e.e164=t=>e.check(function(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...R(t)})}($r,t)),e.datetime=t=>e.check(Cn(t)),e.date=t=>e.check(Rn(t)),e.time=t=>e.check(Dn(t)),e.duration=t=>e.check(Ln(t))});function or(e){return function(e,t){return new e({type:"string",...R(t)})}(ar,e)}var dr=h("ZodStringFormat",(e,t)=>{nt.init(e,t),sr.init(e,t)}),lr=h("ZodEmail",(e,t)=>{st.init(e,t),dr.init(e,t)}),cr=h("ZodGUID",(e,t)=>{rt.init(e,t),dr.init(e,t)}),fr=h("ZodUUID",(e,t)=>{it.init(e,t),dr.init(e,t)}),ur=h("ZodURL",(e,t)=>{at.init(e,t),dr.init(e,t)}),pr=h("ZodEmoji",(e,t)=>{ot.init(e,t),dr.init(e,t)}),hr=h("ZodNanoID",(e,t)=>{dt.init(e,t),dr.init(e,t)}),mr=h("ZodCUID",(e,t)=>{lt.init(e,t),dr.init(e,t)}),gr=h("ZodCUID2",(e,t)=>{ct.init(e,t),dr.init(e,t)}),yr=h("ZodULID",(e,t)=>{ft.init(e,t),dr.init(e,t)}),br=h("ZodXID",(e,t)=>{ut.init(e,t),dr.init(e,t)}),vr=h("ZodKSUID",(e,t)=>{pt.init(e,t),dr.init(e,t)}),kr=h("ZodIPv4",(e,t)=>{bt.init(e,t),dr.init(e,t)}),wr=h("ZodIPv6",(e,t)=>{vt.init(e,t),dr.init(e,t)}),Ir=h("ZodCIDRv4",(e,t)=>{kt.init(e,t),dr.init(e,t)}),zr=h("ZodCIDRv6",(e,t)=>{wt.init(e,t),dr.init(e,t)}),_r=h("ZodBase64",(e,t)=>{zt.init(e,t),dr.init(e,t)}),Or=h("ZodBase64URL",(e,t)=>{_t.init(e,t),dr.init(e,t)}),$r=h("ZodE164",(e,t)=>{Ot.init(e,t),dr.init(e,t)}),Sr=h("ZodJWT",(e,t)=>{$t.init(e,t),dr.init(e,t)}),Nr=h("ZodNumber",(e,t)=>{St.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=n,{minimum:i,maximum:s,format:a,multipleOf:o,exclusiveMaximum:d,exclusiveMinimum:l}=e._zod.bag;"string"==typeof a&&a.includes("int")?r.type="integer":r.type="number";const c="number"==typeof l&&l>=(i??Number.NEGATIVE_INFINITY),f="number"==typeof d&&d<=(s??Number.POSITIVE_INFINITY),u="draft-04"===t.target||"openapi-3.0"===t.target;c?u?(r.minimum=l,r.exclusiveMinimum=!0):r.exclusiveMinimum=l:"number"==typeof i&&(r.minimum=i),f?u?(r.maximum=d,r.exclusiveMaximum=!0):r.exclusiveMaximum=d:"number"==typeof s&&(r.maximum=s),"number"==typeof o&&(r.multipleOf=o)})(e,t,n),rr(e,"ZodNumber",{gt(e,t){return this.check(bn(e,t))},gte(e,t){return this.check(vn(e,t))},min(e,t){return this.check(vn(e,t))},lt(e,t){return this.check(gn(e,t))},lte(e,t){return this.check(yn(e,t))},max(e,t){return this.check(yn(e,t))},int(e){return this.check(Mr(e))},safe(e){return this.check(Mr(e))},positive(e){return this.check(bn(0,e))},nonnegative(e){return this.check(vn(0,e))},negative(e){return this.check(gn(0,e))},nonpositive(e){return this.check(yn(0,e))},multipleOf(e,t){return this.check(kn(e,t))},step(e,t){return this.check(kn(e,t))},finite(){return this}});const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function xr(e){return function(e,t){return new e({type:"number",checks:[],...R(t)})}(Nr,e)}var jr=h("ZodNumberFormat",(e,t)=>{Nt.init(e,t),Nr.init(e,t)});function Mr(e){return function(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...R(t)})}(jr,e)}var Tr=h("ZodBoolean",(e,t)=>{xt.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.type="boolean"})(0,0,t)});function Ar(e){return function(e,t){return new e({type:"boolean",...R(t)})}(Tr,e)}var Er=h("ZodUnknown",(e,t)=>{jt.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(e,t,n)=>{}});function Cr(){return new Er({type:"unknown"})}var Pr=h("ZodNever",(e,t)=>{Mt.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.not={}})(0,0,t)});function Rr(e){return function(e,t){return new e({type:"never",...R(t)})}(Pr,e)}var Zr=h("ZodArray",(e,t)=>{At.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=n,s=e._zod.def,{minimum:a,maximum:o}=e._zod.bag;"number"==typeof a&&(i.minItems=a),"number"==typeof o&&(i.maxItems=o),i.type="array",i.items=Sn(s.element,t,{...r,path:[...r.path,"items"]})})(e,t,n,r),e.element=t.element,rr(e,"ZodArray",{min(e,t){return this.check(In(e,t))},nonempty(e){return this.check(In(1,e))},max(e,t){return this.check(wn(e,t))},length(e,t){return this.check(zn(e,t))},unwrap(){return this.element}})});function Dr(e,t){return function(e,t,n){return new e({type:"array",element:t,...R(n)})}(Zr,e,t)}var Fr=h("ZodObject",(e,t)=>{Zt.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=n,s=e._zod.def;i.type="object",i.properties={};const a=s.shape;for(const l in a)i.properties[l]=Sn(a[l],t,{...r,path:[...r.path,"properties",l]});const o=new Set(Object.keys(a)),d=new Set([...o].filter(e=>{const n=s.shape[e]._zod;return"input"===t.io?void 0===n.optin:void 0===n.optout}));d.size>0&&(i.required=Array.from(d)),"never"===s.catchall?._zod.def.type?i.additionalProperties=!1:s.catchall?s.catchall&&(i.additionalProperties=Sn(s.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):"output"===t.io&&(i.additionalProperties=!1)})(e,t,n,r),O(e,"shape",()=>t.shape),rr(e,"ZodObject",{keyof(){return Wr(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:Cr()})},loose(){return this.clone({...this._zod.def,catchall:Cr()})},strict(){return this.clone({...this._zod.def,catchall:Rr()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return function(e,t){if(!T(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const n=e._zod.def.shape;for(const e in t)if(void 0!==Object.getOwnPropertyDescriptor(n,e))throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return P(e,S(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return $(this,"shape",n),n}}))}(this,e)},safeExtend(e){return function(e,t){if(!T(t))throw new Error("Invalid input to safeExtend: expected a plain object");return P(e,S(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return $(this,"shape",n),n}}))}(this,e)},merge(e){return function(e,t){if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");return P(e,S(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return $(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}(this,e)},pick(e){return function(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");return P(e,S(e._zod.def,{get shape(){const e={};for(const r in t){if(!(r in n.shape))throw new Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return $(this,"shape",e),e},checks:[]}))}(this,e)},omit(e){return function(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");return P(e,S(e._zod.def,{get shape(){const r={...e._zod.def.shape};for(const e in t){if(!(e in n.shape))throw new Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return $(this,"shape",r),r},checks:[]}))}(this,e)},partial(...e){return function(e,t,n){const r=t._zod.def.checks;if(r&&r.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");return P(t,S(t._zod.def,{get shape(){const r=t._zod.def.shape,i={...r};if(n)for(const t in n){if(!(t in r))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:"optional",innerType:r[t]}):r[t])}else for(const t in r)i[t]=e?new e({type:"optional",innerType:r[t]}):r[t];return $(this,"shape",i),i},checks:[]}))}(ei,this,e[0])},required(...e){return t=oi,n=this,r=e[0],P(n,S(n._zod.def,{get shape(){const e=n._zod.def.shape,i={...e};if(r)for(const n in r){if(!(n in i))throw new Error(`Unrecognized key: "${n}"`);r[n]&&(i[n]=new t({type:"nonoptional",innerType:e[n]}))}else for(const n in e)i[n]=new t({type:"nonoptional",innerType:e[n]});return $(this,"shape",i),i}}));var t,n,r}})});function Lr(e,t){return new Fr({type:"object",shape:e??{},...R(t)})}function qr(e,t){return new Fr({type:"object",shape:e,catchall:Rr(),...R(t)})}var Br=h("ZodUnion",(e,t)=>{Ft.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def,s=!1===i.inclusive,a=i.options.map((e,n)=>Sn(e,t,{...r,path:[...r.path,s?"oneOf":"anyOf",n]}));s?n.oneOf=a:n.anyOf=a})(e,t,n,r),e.options=t.options});function Gr(e,t){return new Br({type:"union",options:e,...R(t)})}var Jr=h("ZodDiscriminatedUnion",(e,t)=>{Br.init(e,t),Lt.init(e,t)});var Ur=h("ZodIntersection",(e,t)=>{qt.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def,s=Sn(i.left,t,{...r,path:[...r.path,"allOf",0]}),a=Sn(i.right,t,{...r,path:[...r.path,"allOf",1]}),o=e=>"allOf"in e&&1===Object.keys(e).length;n.allOf=[...o(s)?s.allOf:[s],...o(a)?a.allOf:[a]]})(e,t,n,r)});var Hr=h("ZodRecord",(e,t)=>{Jt.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=n,s=e._zod.def;i.type="object";const a=s.keyType,o=a._zod.bag?.patterns;if("loose"===s.mode&&o&&o.size>0){const e=Sn(s.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});i.patternProperties={};for(const t of o)i.patternProperties[t.source]=e}else"draft-07"!==t.target&&"draft-2020-12"!==t.target||(i.propertyNames=Sn(s.keyType,t,{...r,path:[...r.path,"propertyNames"]})),i.additionalProperties=Sn(s.valueType,t,{...r,path:[...r.path,"additionalProperties"]});const d=a._zod.values;if(d){const e=[...d].filter(e=>"string"==typeof e||"number"==typeof e);e.length>0&&(i.required=e)}})(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function Vr(e,t,n){return t&&t._zod?new Hr({type:"record",keyType:e,valueType:t,...R(n)}):new Hr({type:"record",keyType:or(),valueType:e,...R(t)})}var Yr=h("ZodEnum",(e,t)=>{Ut.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=v(e._zod.def.entries);r.every(e=>"number"==typeof e)&&(n.type="number"),r.every(e=>"string"==typeof e)&&(n.type="string"),n.enum=r})(e,0,n),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{const i={};for(const s of e){if(!n.has(s))throw new Error(`Key ${s} not found in enum`);i[s]=t.entries[s]}return new Yr({...t,checks:[],...R(r),entries:i})},e.exclude=(e,r)=>{const i={...t.entries};for(const t of e){if(!n.has(t))throw new Error(`Key ${t} not found in enum`);delete i[t]}return new Yr({...t,checks:[],...R(r),entries:i})}});function Wr(e,t){return new Yr({type:"enum",entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...R(t)})}var Kr=h("ZodLiteral",(e,t)=>{Ht.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=e._zod.def,i=[];for(const s of r.values)if(void 0===s){if("throw"===t.unrepresentable)throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if("bigint"==typeof s){if("throw"===t.unrepresentable)throw new Error("BigInt literals cannot be represented in JSON Schema");i.push(Number(s))}else i.push(s);if(0===i.length);else if(1===i.length){const e=i[0];n.type=null===e?"null":typeof e,"draft-04"===t.target||"openapi-3.0"===t.target?n.enum=[e]:n.const=e}else i.every(e=>"number"==typeof e)&&(n.type="number"),i.every(e=>"string"==typeof e)&&(n.type="string"),i.every(e=>"boolean"==typeof e)&&(n.type="boolean"),i.every(e=>null===e)&&(n.type="null"),n.enum=i})(e,t,n),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function Qr(e,t){return new Kr({type:"literal",values:Array.isArray(e)?e:[e],...R(t)})}var Xr=h("ZodTransform",(e,t)=>{Vt.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Transforms cannot be represented in JSON Schema")})(0,e),e._zod.parse=(n,r)=>{if("backward"===r.direction)throw new g(e.constructor.name);n.addIssue=r=>{if("string"==typeof r)n.issues.push(J(r,n.value,t));else{const t=r;t.fatal&&(t.continue=!1),t.code??(t.code="custom"),t.input??(t.input=n.value),t.inst??(t.inst=e),n.issues.push(J(t))}};const i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});var ei=h("ZodOptional",(e,t)=>{Wt.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>An(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});function ti(e){return new ei({type:"optional",innerType:e})}var ni=h("ZodExactOptional",(e,t)=>{Kt.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>An(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});var ri=h("ZodNullable",(e,t)=>{Qt.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def,s=Sn(i.innerType,t,r),a=t.seen.get(e);"openapi-3.0"===t.target?(a.ref=i.innerType,n.nullable=!0):n.anyOf=[s,{type:"null"}]})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function ii(e){return new ri({type:"nullable",innerType:e})}var si=h("ZodDefault",(e,t)=>{Xt.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def;Sn(i.innerType,t,r),t.seen.get(e).ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});var ai=h("ZodPrefault",(e,t)=>{tn.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def;Sn(i.innerType,t,r),t.seen.get(e).ref=i.innerType,"input"===t.io&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});var oi=h("ZodNonOptional",(e,t)=>{nn.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def;Sn(i.innerType,t,r),t.seen.get(e).ref=i.innerType})(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});var di=h("ZodCatch",(e,t)=>{sn.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def;let s;Sn(i.innerType,t,r),t.seen.get(e).ref=i.innerType;try{s=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=s})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});var li=h("ZodPipe",(e,t)=>{an.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def,s=i.in._zod.traits.has("$ZodTransform"),a="input"===t.io?s?i.out:i.in:i.out;Sn(a,t,r),t.seen.get(e).ref=a})(e,t,0,r),e.in=t.in,e.out=t.out});function ci(e,t){return new li({type:"pipe",in:e,out:t})}var fi=h("ZodReadonly",(e,t)=>{dn.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def;Sn(i.innerType,t,r),t.seen.get(e).ref=i.innerType,n.readOnly=!0})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});var ui=h("ZodCustom",(e,t)=>{fn.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Custom types cannot be represented in JSON Schema")})(0,e)});var pi,hi=or().regex(/^[a-z]+$/,"aff ids are single lowercase words"),mi=or().regex(/^[a-z][a-zA-Z]*$/,"balance ids are lowercase-led words"),gi=or().regex(/^[a-z]+( [a-z]+)*$/,"cure ids are lowercase words separated by single spaces"),yi=or().regex(/^[a-z]+$/,"venom ids are single lowercase words"),bi=or().regex(/^[a-z]+$/,"profession ids are single lowercase words"),vi=qr({shortName:or().min(1),fg:or(),bg:or()}),ki={id:hi,display:vi.optional(),curesTo:hi.optional(),pseudo:Ar().default(!1),curedLast:Ar().default(!1)},wi=qr({...ki,kind:Qr("plain")}),Ii=qr({...ki,kind:Qr("timed"),durationMs:xr().int().positive(),provenance:Wr(["verified","unverified"]).default("verified")}),zi=qr({...ki,kind:Qr("countable"),min:xr().int().min(0),max:xr().int().positive()}).refine(e=>e.max>e.min,{message:"countable affs need max > min"}),_i=Dr(new Jr({type:"union",options:[wi,Ii,zi],discriminator:"kind",...R(pi)})).min(1).refine(e=>new Set(e.map(e=>e.id)).size===e.length,{message:"aff ids must be unique"}),Oi=qr({fg:or(),bg:or()}),$i=Vr(or().min(1),Oi),Si=Vr(hi,vi),Ni=qr({delimiter:Oi,label:Oi}),xi=qr({info:Oi,warning:Oi,error:Oi}),ji=qr({bracket:Oi,detail:Oi,tag:Ni,severity:xi}),Mi=qr({affs:Si,chrome:ji}),Ti=$i.parse({antimony:{fg:"olive",bg:""},argentum:{fg:"royalblue",bg:""},arsenic:{fg:"",bg:""},aurum:{fg:"ForestGreen",bg:""},azurite:{fg:"",bg:""},calamine:{fg:"",bg:""},calcite:{fg:"slategray",bg:""},cinnabar:{fg:"greenyellow",bg:""},cuprum:{fg:"DeepSkyBlue",bg:""},ferrum:{fg:"DarkOrange",bg:""},gypsum:{fg:"",bg:""},magnesium:{fg:"Red",bg:""},plumbum:{fg:"Gold",bg:""},quartz:{fg:"",bg:""},quicksilver:{fg:"",bg:""},realgar:{fg:"firebrick",bg:""},stannum:{fg:"Tan",bg:""},caloric:{fg:"darkseagreen",bg:""},mending:{fg:"orchid",bg:""},epidermal:{fg:"sienna",bg:""},restoration:{fg:"darkviolet",bg:""},health:{fg:"lightpink",bg:""},writhe:{fg:"paleyellow",bg:"darkslategray"}}),Ai={addiction:{shortName:"add",...Ti.ferrum},aeon:{shortName:"ae",...Ti.cinnabar},agoraphobia:{shortName:"agor",...Ti.argentum},amnesia:{shortName:"amn",fg:"",bg:""},anorexia:{shortName:"ANO",...Ti.epidermal},asthma:{shortName:"AST",...Ti.aurum},blackout:{shortName:"bo",fg:"",bg:""},blindness:{shortName:"unb",...Ti.arsenic},bound:{shortName:"bnd",...Ti.writhe},brokenleftarm:{shortName:"la1",...Ti.mending},brokenleftleg:{shortName:"ll1",...Ti.mending},brokenrightarm:{shortName:"ra1",...Ti.mending},brokenrightleg:{shortName:"rl1",...Ti.mending},bruisedribs:{shortName:"ribs",fg:"",bg:""},burning:{shortName:"burn",...Ti.mending},calcifiedskull:{shortName:"calh",...Ti.restoration},calcifiedtorso:{shortName:"calt",...Ti.restoration},claustrophobia:{shortName:"clau",...Ti.stannum},cleanseaura:{shortName:"cleanse",fg:"",bg:""},clumsiness:{shortName:"clu",...Ti.aurum},concussion:{shortName:"conc",...Ti.restoration},confusion:{shortName:"con",...Ti.stannum},corruption:{shortName:"corr",fg:"",bg:""},crackedribs:{shortName:"cr",...Ti.health},crushedthroat:{shortName:"cru",...Ti.mending},daeggerimpale:{shortName:"daeg",...Ti.writhe},damagedleftarm:{shortName:"la2",...Ti.restoration},damagedleftleg:{shortName:"ll2",...Ti.restoration},damagedrightarm:{shortName:"ra2",...Ti.restoration},damagedrightleg:{shortName:"rl2",...Ti.restoration},damagedhead:{shortName:"hd2",...Ti.restoration},darkshade:{shortName:"dark",...Ti.ferrum},dazed:{shortName:"dzd",...Ti.cinnabar},dazzled:{shortName:"dzl",...Ti.mending},deadening:{shortName:"dea",...Ti.cinnabar},deafness:{shortName:"und",...Ti.calamine},dehydrated:{shortName:"deh",fg:"",bg:""},dementia:{shortName:"dem",...Ti.stannum},depression:{shortName:"dep",...Ti.plumbum},deteriorate:{shortName:"det",fg:"",bg:""},disloyalty:{shortName:"disl",...Ti.realgar},disrupted:{shortName:"disr",fg:"",bg:""},dissonance:{shortName:"disso",...Ti.plumbum},dizziness:{shortName:"diz",...Ti.plumbum},enmesh:{shortName:"enmsh",...Ti.writhe},ensorcelled:{shortName:"ensor",fg:"",bg:""},entangled:{shortName:"entgl",...Ti.writhe},epilepsy:{shortName:"epi",...Ti.plumbum},fear:{shortName:"fear",fg:"",bg:""},flushings:{shortName:"flush",...Ti.ferrum},frostbite:{shortName:"frost",...Ti.caloric},frozen:{shortName:"frz",...Ti.caloric},fulminated:{shortName:"fulm",...Ti.plumbum},generosity:{shortName:"gen",...Ti.cuprum},grievouswounds:{shortName:"grv",...Ti.health},guilt:{shortName:"gui",...Ti.argentum},haemophilia:{shortName:"haem",...Ti.ferrum},hallucinations:{shortName:"hall",...Ti.stannum},hamstrung:{shortName:"hms",fg:"",bg:""},healthleech:{shortName:"hthl",...Ti.aurum},heartseed:{shortName:"heart",...Ti.restoration},hellsight:{shortName:"hell",...Ti.realgar},horror:{shortName:"hor",...Ti.argentum},hypersomnia:{shortName:"hypers",...Ti.stannum},hypochondria:{shortName:"hypoch",...Ti.aurum},hypothermia:{shortName:"hypoth",...Ti.restoration},icefisted:{shortName:"ice",fg:"",bg:""},impaled:{shortName:"impl",...Ti.writhe},impatience:{shortName:"IMPAT",...Ti.plumbum},indifference:{shortName:"ind",...Ti.cuprum},itching:{shortName:"itch",...Ti.epidermal},justice:{shortName:"just",...Ti.cuprum},kkractlebrand:{shortName:"kkr",...Ti.health},laceratedthroat:{shortName:"lac2",...Ti.restoration},latched:{shortName:"latch",...Ti.health},lethargy:{shortName:"let",...Ti.ferrum},lightbind:{shortName:"light",fg:"",bg:""},loneliness:{shortName:"lon",...Ti.argentum},lovers:{shortName:"love",...Ti.cuprum},manaleech:{shortName:"man",...Ti.realgar},mangledleftarm:{shortName:"la3",...Ti.restoration},mangledleftleg:{shortName:"ll3",...Ti.restoration},mangledrightarm:{shortName:"ra3",...Ti.restoration},mangledrightleg:{shortName:"rl3",...Ti.restoration},mangledhead:{shortName:"hd3",...Ti.restoration},masochism:{shortName:"maso",...Ti.argentum},mildtrauma:{shortName:"tor1",...Ti.restoration},mycalium:{shortName:"myc",...Ti.plumbum},nausea:{shortName:"nau",...Ti.ferrum},numbedleftarm:{shortName:"nbla",fg:"",bg:""},numbedrightarm:{shortName:"nbra",fg:"",bg:""},pacified:{shortName:"pac",...Ti.cuprum},palpatarfeed:{shortName:"worm",fg:"",bg:""},paralysis:{shortName:"PAR",...Ti.magnesium},paranoia:{shortName:"prn",...Ti.stannum},parasite:{shortName:"prs",...Ti.aurum},peace:{shortName:"pea",...Ti.cuprum},phlogisticated:{shortName:"phlog",fg:"",bg:""},pinshot:{shortName:"psh",fg:"",bg:""},pressure:{shortName:"pres",...Ti.calcite},prone:{shortName:"pr",fg:"",bg:""},pyramides:{shortName:"pyra",...Ti.magnesium},pyre:{shortName:"pyre",...Ti.cuprum},rebbies:{shortName:"reb",...Ti.aurum},recklessness:{shortName:"reck",...Ti.argentum},retribution:{shortName:"retr",...Ti.cuprum},revealed:{shortName:"rev",fg:"",bg:""},sandfever:{shortName:"sand",...Ti.plumbum},scalded:{shortName:"scald",...Ti.epidermal},scytherus:{shortName:"scy",...Ti.ferrum},selarnia:{shortName:"sel",...Ti.mending},sensitivity:{shortName:"sen",...Ti.aurum},serioustrauma:{shortName:"tor2",...Ti.restoration},shadowmadness:{shortName:"shad",...Ti.plumbum},shivering:{shortName:"shiv",...Ti.caloric},shyness:{shortName:"shy",...Ti.plumbum},skullfractures:{shortName:"sf",...Ti.health},slashedthroat:{shortName:"lac1",...Ti.epidermal},sleeping:{shortName:"slp",fg:"",bg:""},slickness:{shortName:"SLI",...Ti.magnesium},slimeobscure:{shortName:"slime",fg:"",bg:""},spiritburn:{shortName:"spirB",...Ti.argentum},spiritwrack:{shortName:"spirW",fg:"",bg:""},stupidity:{shortName:"st",...Ti.plumbum},stuttering:{shortName:"stut",...Ti.epidermal},homunculusmercury:{shortName:"merc",fg:"",bg:""},temperedcholeric:{shortName:"choH",...Ti.antimony},temperedmelancholic:{shortName:"melaH",...Ti.antimony},temperedphlegmatic:{shortName:"phleH",...Ti.antimony},temperedsanguine:{shortName:"sanH",...Ti.antimony},tenderskin:{shortName:"tend",...Ti.argentum},tension:{shortName:"tens",...Ti.cinnabar},timeflux:{shortName:"tmfx",fg:"",bg:""},timeloop:{shortName:"tmlp",...Ti.cuprum},tonguetied:{shortName:"tngt",...Ti.restoration},torntendons:{shortName:"tt",...Ti.health},transfixation:{shortName:"trfx",...Ti.writhe},unweavingbody:{shortName:"unwB",...Ti.ferrum},unweavingspirit:{shortName:"unwS",...Ti.cinnabar},unweavingmind:{shortName:"unwM",...Ti.plumbum},unblind:{shortName:"unB",fg:"",bg:""},undeaf:{shortName:"unD",fg:"",bg:""},vertigo:{shortName:"vert",...Ti.argentum},vitrified:{shortName:"vitri",fg:"",bg:""},voidfisted:{shortName:"void",fg:"",bg:""},voyria:{shortName:"voy",fg:"",bg:""},weariness:{shortName:"wea",...Ti.aurum},webbed:{shortName:"web",...Ti.writhe},whisperingmadness:{shortName:"wmad",...Ti.argentum},wristfractures:{shortName:"wf",...Ti.health}},Ei=Mi.parse({affs:Ai,chrome:{bracket:{fg:"LightGoldenRodYellow",bg:""},detail:{fg:"darkgray",bg:""},tag:{delimiter:{fg:"#784695",bg:""},label:{fg:"#CBCE91",bg:""}},severity:{info:{fg:"#FFF2D7",bg:""},warning:{fg:"orange",bg:""},error:{fg:"red",bg:""}}}}),Ci=Ei.affs,Pi=(Ei.chrome,new Set(["undeaf","unblind","cleanseaura"])),Ri=new Set(["dissonance"]),Zi=new Map([["mangledleftleg","damagedleftleg"],["mangledleftarm","damagedleftarm"],["mangledrightleg","damagedrightleg"],["mangledrightarm","damagedrightarm"],["mangledhead","damagedhead"],["serioustrauma","mildtrauma"],["damagedleftleg","brokenleftleg"],["damagedleftarm","brokenleftarm"],["damagedrightleg","brokenrightleg"],["damagedrightarm","brokenrightarm"]]),Di=(e,t,n={})=>({id:e,kind:t,...n,...Zi.has(e)?{curesTo:Zi.get(e)}:{},...Pi.has(e)?{pseudo:!0}:{},...Ri.has(e)?{curedLast:!0}:{},...Ci[e]?{display:Ci[e]}:{}}),Fi=_i.parse([...["undeaf","unblind","cleanseaura","addiction","agoraphobia","amnesia","anorexia","asphyxiating","asthma","blindness","bloodfire","bound","brokenleftarm","brokenrightarm","brokenleftleg","brokenrightleg","calcifiedskull","calcifiedtorso","claustrophobia","clumsiness","coldfate","concussion","conflagration","confusion","convergence","cremated","crushedthroat","daeggerimpale","damagedhead","damagedleftarm","damagedleftleg","damagedrightarm","damagedrightleg","darkshade","dazed","deadening","deafness","death","deathsickness","deepsleep","degenerate","dementia","depression","deteriorate","diminished","disloyalty","disrupted","dissonance","dizziness","earworm","enlightenment","entangled","epilepsy","fear","flushings","fratricide","frostbite","frozen","fulminated","generosity","grievouswounds","guilt","haemophilia","hallucinations","hatred","healthleech","hellsight","hindered","homunculusmercury","hypersomnia","hypochondria","hypothermia","icebound","impaled","impatience","indifference","insomnia","isolation","itching","justice","kkractlebrand","laceratedthroat","lapsingconsciousness","latched","lethargy","loneliness","lovers","lullaby","manaleech","masochism","mildtrauma","mangledleftarm","mangledleftleg","mangledrightarm","mangledrightleg","mangledhead","mindclamp","mycalium","nausea","pacified","paralysis","paranoia","parasite","peace","penitence","prone","pyramides","rebbies","recklessness","retribution","sandfever","scytherus","selarnia","sensitivity","serioustrauma","shadowmadness","shivering","shyness","slashedthroat","sleeping","slickness","spiritburn","stupidity","stuttering","tenderskin","tension","timeloop","tonguetied","transfixation","vertigo","vitiated","voyria","weariness","webbed","whisperingmadness","harmonic","bop","spiritwrack","bedevil","loki","moon","evileye","dragoncurse","swiftcurse"].map(e=>Di(e,"plain")),...Object.entries({accentato:{durationMs:2e4,provenance:"unverified"},aeon:{durationMs:16e3},airfisted:{durationMs:16e3},betrayal:{durationMs:15e3},blackout:{durationMs:4e3,provenance:"unverified"},blistered:{durationMs:15e3,provenance:"unverified"},breathless:{durationMs:3e3},bruisedribs:{durationMs:3e4},cadmuscurse:{durationMs:2e4},condemned:{durationMs:2e4},constricted:{durationMs:3e4},corruption:{durationMs:45e3},dazzled:{durationMs:6e4},dehydrated:{durationMs:6e4},demonstain:{durationMs:12e4},empoweredloshre:{durationMs:12e3},empoweredmannaz:{durationMs:2e4},enmesh:{durationMs:5e3},ensorcelled:{durationMs:2e4},flamefisted:{durationMs:3e4},hamstrung:{durationMs:9e3},heartseed:{durationMs:11e3},hecatecurse:{durationMs:16e3},icefisted:{durationMs:3e4},internalbleeding:{durationMs:3e4},inquisition:{durationMs:3e4},kaisurge:{durationMs:15e3,provenance:"unverified"},lightbind:{durationMs:22e3},lovestruck:{durationMs:5e3},mindravaged:{durationMs:2e4,provenance:"unverified"},muddled:{durationMs:12e3},numbedleftarm:{durationMs:7500},numbedrightarm:{durationMs:7500},petrified:{durationMs:1e4,provenance:"unverified"},palpatarfeed:{durationMs:19e3,provenance:"unverified"},phlogisticated:{durationMs:45e3},pinshot:{durationMs:18e3},reeling:{durationMs:2e4},revealed:{durationMs:6e4},scalded:{durationMs:2e4},scrambledbrains:{durationMs:6e4},silenced:{durationMs:2e4,provenance:"unverified"},silver:{durationMs:18e4},slimeobscure:{durationMs:6e4},solarburn:{durationMs:5e3},snared:{durationMs:2e4},speechless:{durationMs:3e5},stridulating:{durationMs:15e3},stun:{durationMs:3e3,provenance:"unverified"},succumbed:{durationMs:3e4},timeflux:{durationMs:6e4},trueblind:{durationMs:6e3},unconsciousness:{durationMs:1e4},vinewreathed:{durationMs:3e4},vitrified:{durationMs:45e3},voidfisted:{durationMs:5e3},waterbonds:{durationMs:3e4},weakenedmind:{durationMs:6e4},woeconstrained:{durationMs:3e4}}).map(([e,t])=>Di(e,"timed",t)),...Object.entries({pressure:{min:0,max:5},crescendo:{min:0,max:5},unweavingbody:{min:0,max:5},unweavingspirit:{min:0,max:5},unweavingmind:{min:0,max:5},burning:{min:0,max:5},horror:{min:0,max:5},pyre:{min:0,max:3},temperedcholeric:{min:0,max:8},temperedmelancholic:{min:0,max:8},temperedphlegmatic:{min:0,max:8},temperedsanguine:{min:0,max:8},torntendons:{min:0,max:6},crackedribs:{min:0,max:6},skullfractures:{min:0,max:6},wristfractures:{min:0,max:6}}).map(([e,t])=>Di(e,"countable",t))]),Li=qr({id:bi,skills:Dr(or().regex(/^[a-z]+$/,"skill keys are single lowercase words")).default([])}),qi=Dr(Li).min(1).refine(e=>new Set(e.map(e=>e.id)).size===e.length,{message:"profession ids must be unique"}),Bi=qi.parse([{id:"alchemist",skills:[]},{id:"apostate",skills:[]},{id:"bard",skills:[]},{id:"blademaster",skills:[]},{id:"depthswalker",skills:["aeonics","shadowmancy"]},{id:"dragon",skills:["dragoncraft"]},{id:"firelord",skills:[]},{id:"jester",skills:["tarot"]},{id:"magi",skills:["elementalism","crystalism","artificing"]},{id:"monk",skills:[]},{id:"occultist",skills:["occultism","domination","tarot"]},{id:"priest",skills:[]},{id:"psion",skills:["weaving"]},{id:"runewarden",skills:[]},{id:"serpent",skills:["venom"]},{id:"shikudo",skills:[]}]),Gi=Gr([hi,Dr(hi).min(2)]),Ji=qr({id:gi,command:or().min(1),class:Wr(["linear","tree","special"]),order:Dr(hi).default([]),ordered:Ar().default(!1),layered:Ar().default(!1),bals_used:Dr(mi).default([]),bals_req:Dr(mi).default([]),blocks:Dr(Gi).default([]),professions:Dr(bi).optional(),bestowable:Ar().default(!1),prio:xr().int().min(0),delayMs:xr().int().positive().optional()}).refine(e=>!e.bestowable||void 0!==e.professions,{message:"bestowable is a class-cure trait — it requires a professions gate"}),Ui=Dr(Ji).min(1).refine(e=>new Set(e.map(e=>e.id)).size===e.length,{message:"cure ids must be unique"}),Hi=["itching","paralysis","fear","brokenrightarm","brokenleftarm","brokenrightleg","brokenleftleg","lapsingconsciousness","aeon","lovers","confusion","epilepsy","pacified","blackout","dazed","justice","slashedthroat","hellsight","peace","dazzled","shyness","dizziness","slickness","asthma","nausea","selarnia","weariness","scytherus","fratricide","haemophilia","clumsiness","hallucinations","healthleech","dementia","recklessness","anorexia","masochism","impatience","stupidity","generosity","addiction","deadening","manaleech","stuttering","paranoia","agoraphobia","loneliness","claustrophobia","vertigo","hypersomnia","shivering","frozen","burning","sensitivity","hypochondria","lethargy","disloyalty","darkshade","voyria","dissonance","phlogisticated","silver","spiritburn","tenderskin","guilt","skullfractures","wristfractures","crackedribs","torntendons","indifference","retribution","shadowmadness","parasite","depression","timeloop","crushedthroat","tension","unweavingspirit","grievouswounds","pyramides","flushings","rebbies","mycalium","sandfever","crescendo","fulminated","frostbite"],Vi=["death","anorexia","sleeping"],Yi=["death","asthma","sleeping"],Wi=["death","slickness","sleeping"],Ki=["death","sleeping","anorexia"],Qi=[["brokenleftarm","brokenrightarm"],["brokenleftarm","damagedrightarm"],["brokenleftarm","mangledrightarm"],["damagedleftarm","brokenrightarm"],["damagedleftarm","damagedrightarm"],["damagedleftarm","mangledrightarm"],["mangledleftarm","brokenrightarm"],["mangledleftarm","damagedrightarm"],["mangledleftarm","mangledrightarm"]],Xi=["entangled","transfixation","impaled","webbed","bound"],es=["darkshade","haemophilia","lethargy","addiction","scytherus","nausea","flushings","unweavingbody"],ts=["paralysis","slickness","pyramides"],ns=["clumsiness","healthleech","sensitivity","weariness","asthma","hypochondria","rebbies","parasite"],rs=["undeaf","deafness"],is=["horror","fratricide","masochism","loneliness","vertigo","recklessness","agoraphobia","guilt","whisperingmadness","spiritburn","tenderskin"],ss=["pacified","peace","lovers","justice","generosity","indifference","retribution","pyre","timeloop","diminished","stridulating"],as=["temperedcholeric","temperedmelancholic","temperedphlegmatic","temperedsanguine"],os=["unblind","blindness"],ds=["claustrophobia","paranoia","confusion","hypersomnia","hallucinations","dementia","crescendo"],ls=["stupidity","epilepsy","dizziness","shyness","impatience","dissonance","depression","sandfever","mycalium","shadowmadness","unweavingmind","fulminated"],cs=["pressure"],fs=["disloyalty","hellsight","manaleech","slickness"],us=["aeon","deadening","tension","unweavingspirit","earworm"],ps=(e,t,n={})=>({id:e,command:`eat ${e}`,class:"linear",order:t,bals_used:["herb"],bals_req:["herb"],blocks:Vi,prio:0,...n}),hs=(e,t)=>({id:e,command:`smoke ${e}`,class:"linear",...t?{order:t}:{},bals_used:["smoke"],bals_req:["smoke"],blocks:Yi,prio:0}),ms=(e,t,n={})=>({id:e,command:`apply ${e}`,class:"linear",order:t,bals_used:["salve"],bals_req:["salve","restoration"],blocks:Wi,prio:0,...n}),gs=(e,t)=>({...ms(e,t),bals_used:["restoration"],delayMs:4e3}),ys=(e,t)=>({id:e,command:`apply ${e}`,class:"linear",order:t,bals_used:["sip"],bals_req:["sip"],prio:0}),bs=(e,t)=>({id:e,class:"tree",order:Hi,prio:0,...t}),vs=Ui.parse([ps("ferrum",es),ps("magnesium",ts),ps("aurum",ns),ps("calamine",rs,{delayMs:2500}),ps("argentum",is),ps("cuprum",ss),ps("antimony",as),ps("arsenic",os),ps("stannum",ds),ps("plumbum",ls,{class:"special"}),ps("calcite",cs),ps("ginseng",es),ps("bloodroot",ts),ps("kelp",ns),ps("hawthorn",rs,{delayMs:2500}),ps("lobelia",is),ps("bellwort",ss),ps("ginger",as),ps("bayberry",os),ps("ash",ds),ps("goldenseal",ls,{class:"special"}),ps("pear",cs),{...hs("smoke",["aeon","disloyalty","hellsight","manaleech","slickness","deadening","tension","unweavingspirit","earworm"]),command:"smoke cinnabar"},hs("cinnabar",us),hs("malachite"),hs("realgar",fs),hs("elm",us),hs("skullcap"),hs("valerian",fs),ms("caloric",["frozen","shivering","frostbite"],{layered:!0}),ms("epidermal to body",["anorexia"]),ms("epidermal to head",["stuttering","blindness","deafness"]),ms("epidermal to ears",["deafness"]),ms("mending to head",["crushedthroat","dazzled"]),ms("mending to arms",["brokenleftarm","brokenrightarm"],{ordered:!0}),ms("mending to legs",["brokenleftleg","brokenrightleg"],{ordered:!0}),ms("mending to body",["burning"]),gs("restoration to head",["mangledhead","damagedhead","calcifiedskull","concussion","tonguetied"]),gs("restoration to torso",["hypothermia","heartseed","serioustrauma","mildtrauma","calcifiedtorso","internalbleeding"]),gs("restoration to arms",["mangledleftarm","mangledrightarm","damagedleftarm","damagedrightarm"]),gs("restoration to legs",["mangledleftleg","mangledrightleg","damagedleftleg","damagedrightleg"]),{id:"health",command:"sip health",class:"linear",bals_used:["sip"],bals_req:["sip"],blocks:Ki,prio:0},{id:"mana",command:"sip mana",class:"linear",bals_used:["sip"],bals_req:["sip"],blocks:Ki,prio:0},ys("health to head",["skullfractures"]),ys("health to torso",["crackedribs","grievouswounds"]),ys("health to arms",["wristfractures"]),ys("health to legs",["torntendons","latched","kkractlebrand"]),{id:"fitness",command:"fitness",class:"linear",order:["asthma"],bals_used:["balance","fitness"],bals_req:["equilibrium","balance","fitness"],blocks:["death","weariness","sleeping"],professions:["monk","shikudo","runewarden"],prio:0},bs("bloodboil",{command:"cast bloodboil",bals_used:["equilibrium","bloodboil"],bals_req:["equilibrium","balance","bloodboil"],blocks:["death","haemophilia","sleeping",...Qi,...Xi],professions:["magi"]}),{id:"dragonflex",command:"dragonflex",class:"linear",order:["webbed","entangled"],bals_used:["balance"],bals_req:["balance"],professions:["dragon"],prio:0},bs("dragonheal",{command:"dragonheal",bals_used:["dragonheal","equilibrium"],bals_req:["balance","equilibrium"],blocks:["death","sleeping",["recklessness","weariness"]],professions:["dragon"]}),{id:"dwinnu",command:"chant dwinnu",class:"linear",order:["webbed","entangled"],bals_used:["voice"],bals_req:["voice"],professions:["bard"],prio:0},{id:"rage",command:"rage",class:"linear",order:["pacified","peace","lovers","generosity","stridulating"],bals_used:["rage"],bals_req:["rage"],professions:["runewarden"],prio:95},bs("salt",{command:"educe salt",bals_used:["salt","equilibrium"],bals_req:["equilibrium","salt"],blocks:["death","stupidity","sleeping"],professions:["alchemist"]}),bs("siphon",{command:"siphon",bals_used:["angel"],bals_req:["angel"],blocks:["death","sleeping"],professions:["apostate","priest"]}),bs("shrugging",{command:"shrugging",bals_used:["shrugging"],bals_req:["equilibrium","balance","shrugging"],blocks:["death","weariness","sleeping"],professions:["serpent"]}),bs("slough",{command:"slough impurities",bals_used:["slough","balance"],bals_req:["equilibrium","balance","slough"],blocks:["death","weariness","sleeping"],professions:["firelord"]}),bs("fool",{command:"fling fool at me",bals_used:["fool","balance"],bals_req:["equilibrium","balance","fool"],blocks:["death","prone","paralysis","sleeping",...Qi,...Xi],professions:["occultist"]}),bs("accelerate",{command:"chrono accelerate",bals_used:["accelerate","balance"],bals_req:["equilibrium","balance","accelerate"],blocks:["death","sleeping","recklessness"],professions:["depthswalker"]}),bs("alleviate",{command:"alleviate",bals_used:["alleviate","balance"],bals_req:["equilibrium","balance","alleviate"],blocks:["death","paralysis","sleeping"],professions:["blademaster"]}),bs("dagaz",{command:"sketch dagaz on ground",bals_used:["dagaz"],blocks:["death"],professions:["runewarden"],bestowable:!0}),bs("generic",{command:"classcure",bals_used:["generic"],bals_req:["equilibrium","balance","generic"],blocks:["death"],professions:[]}),{id:"insomnia",command:"insomnia",class:"linear",order:["insomnia"],blocks:["death","hypersomnia","sleeping"],prio:0},{id:"focus",command:"focus",class:"linear",order:["stupidity","epilepsy","dizziness","shyness","claustrophobia","paranoia","confusion","hallucinations","dementia","pacified","peace","lovers","generosity","masochism","loneliness","vertigo","recklessness","agoraphobia","anorexia","stuttering"],bals_used:["focus"],bals_req:["focus"],blocks:["death","impatience","sleeping"],prio:0},{id:"concentrate",command:"concentrate",class:"linear",order:["disrupted"],blocks:["death","sleeping","confusion"],prio:0},{id:"immunity",command:"sip immunity",class:"linear",order:["voyria"],bals_used:["immunity"],bals_req:["immunity"],blocks:Ki,prio:0},{id:"stand",command:"stand",class:"linear",order:["prone"],bals_req:["balance","equilibrium"],blocks:["death","sleeping","paralysis","brokenrightleg","brokenleftleg","damagedleftleg","damagedrightleg","mangledrightleg","mangledleftleg",...Xi],prio:0},bs("tree",{command:"touch tree",bals_used:["tree"],bals_req:["tree"],blocks:["death","sleeping","paralysis",...Qi,...Xi]}),{id:"potash",command:"eat potash",class:"linear",bals_used:["moss"],bals_req:["moss"],blocks:Ki,prio:0},{id:"moss",command:"eat moss",class:"linear",bals_used:["moss"],bals_req:["moss"],blocks:Ki,prio:0},{id:"restore",command:"restore",class:"linear",order:["brokenleftarm","brokenrightarm","brokenleftleg","brokenrightleg","skullfractures","torntendons","wristfractures","crackedribs"],bals_used:["equilibrium"],bals_req:["balance","equilibrium"],prio:0},{id:"touch soul",command:"touch soul",class:"linear",order:["amnesia"],blocks:["death"],prio:101}]),ks=Dr(qr({id:mi,observedDurationMs:xr().int().positive(),predictiveDurationMs:xr().int().positive(),bufferPolicy:Wr(["buffered","exact"])}).refine(e=>"buffered"===e.bufferPolicy?e.observedDurationMs===Math.round(.75*e.predictiveDurationMs):e.observedDurationMs===e.predictiveDurationMs,{message:"observedDurationMs must follow the declared bufferPolicy"})).min(1).refine(e=>new Set(e.map(e=>e.id)).size===e.length,{message:"balance ids must be unique"}),ws=(e,t)=>({id:e,predictiveDurationMs:t,observedDurationMs:Math.round(.75*t),bufferPolicy:"buffered"}),Is=ks.parse([ws("balance",2e3),ws("equilibrium",2e3),ws("sip",4500),ws("herb",1500),ws("smoke",1500),ws("salve",1e3),ws("restoration",4e3),ws("focus",2500),ws("tree",15e3),ws("moss",6e3),ws("immunity",1e4),ws("accelerate",1e4),ws("alleviate",1e4),ws("angel",1e4),ws("bloodboil",1e4),ws("dragonheal",2e4),ws("fitness",1e4),ws("fool",3e4),ws("rage",1e4),ws("salt",1e4),ws("shrugging",12e3),ws("slough",1e4),ws("dagaz",2e4),ws("voice",2500),ws("generic",12e3)]),zs=Dr(qr({id:hi,level:xr().int().min(1),prio:xr().int().min(0)})).min(1).refine(e=>new Set(e.map(e=>`${e.id}:${e.level}`)).size===e.length,{message:"priority (id, level) pairs must be unique"}),_s=(e,t)=>t.map(t=>({id:t,level:1,prio:e})),Os=(e,t,n)=>Array.from({length:t},(t,r)=>({id:e,level:r+1,prio:n})),$s=zs.parse([..._s(0,["accentato","airfisted","asphyxiating","blistered","bloodfire","bruisedribs","cadmuscurse","coldfate","condemned","conflagration","constricted","convergence","corruption","cremated","death","deathsickness","deepsleep","degenerate","dehydrated","demonstain","deteriorate","empoweredloshre","empoweredmannaz","enlightenment","enmesh","ensorcelled","flamefisted","hamstrung","hatred","hecatecurse","hindered","homunculusmercury","icefisted","inquisition","isolation","kaisurge","lightbind","lullaby","mindclamp","mindravaged","muddled","numbedleftarm","numbedrightarm","palpatarfeed","petrified","phlogisticated","pinshot","revealed","scalded","scrambledbrains","silenced","silver","slimeobscure","solarburn","stun","timeflux","trueblind","vinewreathed","vitiated","vitrified","voidfisted","waterbonds","weakenedmind","unconsciousness"]),..._s(2,["aeon","concussion","crushedthroat","paralysis","peace"]),..._s(3,["sleeping","grievouswounds","latched","dazzled","weariness","prone","timeloop","fulminated"]),...Os("unweavingbody",5,3),...Os("unweavingmind",5,3),...Os("unweavingspirit",5,3),..._s(4,["spiritburn","heartseed","guilt","tenderskin","pyramides","parasite","hypochondria","pacified","depression","confusion","retribution","shadowmadness","whisperingmadness","hellsight"]),..._s(5,["anorexia","mycalium","flushings","rebbies","sandfever","asthma","healthleech"]),..._s(6,["impatience","itching","scytherus","clumsiness","kkractlebrand","damagedleftleg","darkshade","slickness","recklessness","dementia","fratricide","icebound"]),..._s(7,["bound","daeggerimpale","entangled","sensitivity","transfixation","webbed","tonguetied","haemophilia","lethargy","manaleech","dissonance"]),{id:"pyre",level:1,prio:7},{id:"pyre",level:2,prio:6},{id:"pyre",level:3,prio:5},..._s(8,["damagedrightleg","hypersomnia","earworm","diminished"]),...Os("skullfractures",6,8),...Os("crescendo",5,8),..._s(9,["brokenleftleg","brokenrightleg","hallucinations"]),...Os("torntendons",6,9),..._s(10,["calcifiedskull","calcifiedtorso","mangledleftleg","mangledrightleg","disrupted","mangledhead","voyria"]),...Os("crackedribs",6,10),..._s(11,["hypothermia","impaled","brokenleftarm","brokenrightarm","indifference","addiction","nausea","deadening","frozen","shivering","mildtrauma","internalbleeding"]),..._s(12,["stupidity","damagedleftarm","disloyalty"]),...Os("wristfractures",6,12),..._s(13,["tension","damagedhead","dazed"]),...Os("burning",5,13),..._s(14,["lovers","damagedrightarm","temperedcholeric","temperedmelancholic","temperedphlegmatic","temperedsanguine"]),...Os("pressure",5,14),..._s(15,["mangledleftarm","mangledrightarm"]),..._s(16,["agoraphobia","claustrophobia","generosity","justice","loneliness","vertigo"]),..._s(17,["paranoia"]),..._s(18,["serioustrauma","epilepsy"]),..._s(20,["laceratedthroat","slashedthroat","stuttering"]),..._s(21,["selarnia","fear","masochism"]),..._s(23,["dizziness","shyness"]),...Os("horror",5,26),..._s(30,["amnesia","blackout"]),..._s(0,["insomnia","deafness","blindness"]),..._s(100,["harmonic","bop","spiritwrack","bedevil","loki","moon","evileye","dragoncurse","swiftcurse"])]),Ss=qr({profession:bi,pools:Vr(or().min(1),Dr(hi).min(1))}),Ns=Dr(Ss).min(1).refine(e=>new Set(e.map(e=>e.profession)).size===e.length,{message:"professions must be unique"}),xs=Ns.parse([{profession:"occultist",pools:{mentals:["claustrophobia","agoraphobia","lovers","dementia","epilepsy","hallucinations","confusion","stupidity","paranoia","vertigo","shyness","addiction","recklessness","masochism"],physicals:["asthma","paralysis","slickness","haemophilia","clumsiness","healthleech","sensitivity","darkshade"],bubonis:["vertigo","recklessness","confusion","masochism","paranoia","shyness","claustrophobia"],chimera:["confusion","hallucinations","agoraphobia","claustrophobia","dementia"],moon:["stupidity","masochism","hallucinations","hypersomnia","confusion","epilepsy","claustrophobia","agoraphobia"],whisperingmadness:["dementia","stupidity","confusion","hypersomnia","paranoia","hallucinations","impatience","addiction","agoraphobia","lovers","loneliness","recklessness","masochism"],justice:["paralysis","sensitivity","healthleech","haemophilia","weariness","asthma","clumsiness"]}},{profession:"psion",pools:{blast:["impatience","stupidity","blackout","dizziness","epilepsy","unweavingmind"]}},{profession:"depthswalker",pools:{leach:["parasite","healthleech","manaleech"],madness:["shadowmadness","vertigo","hallucinations"],retribution:["retribution","justice"],degeneration:["clumsiness","weariness","paralysis"],depression:["depression","nausea","hypochondria"]}}]),js=Dr(qr({id:yi,aff:hi.nullable()})).min(1).refine(e=>new Set(e.map(e=>e.id)).size===e.length,{message:"venom ids must be unique"}),Ms=js.parse([{id:"xentio",aff:"clumsiness"},{id:"eurypteria",aff:"recklessness"},{id:"kalmia",aff:"asthma"},{id:"digitalis",aff:"shyness"},{id:"darkshade",aff:"darkshade"},{id:"curare",aff:"paralysis"},{id:"epteth",aff:null},{id:"prefarar",aff:"sensitivity"},{id:"monkshood",aff:"disloyalty"},{id:"euphorbia",aff:"nausea"},{id:"oculus",aff:"unblind"},{id:"vernalius",aff:"weariness"},{id:"epseth",aff:null},{id:"larkspur",aff:"dizziness"},{id:"slike",aff:"anorexia"},{id:"delphinium",aff:"sleeping"},{id:"notechis",aff:"haemophilia"},{id:"vardrax",aff:"addiction"},{id:"loki",aff:"loki"},{id:"aconite",aff:"stupidity"},{id:"selarnia",aff:null},{id:"gecko",aff:"slickness"},{id:"scytherus",aff:"scytherus"},{id:"nechamadra",aff:"shivering"}]),Ts=new Map(Fi.map(e=>[e.id,e])),As=new Map(vs.map(e=>[e.id,e])),Es=new Map(Is.map(e=>[e.id,e])),Cs=(()=>{const e=new Map;for(const t of $s)e.has(t.id)||e.set(t.id,new Map),e.get(t.id).set(t.level,t.prio);return e})(),Ps=(...e)=>new Set(vs.filter(t=>t.bals_used.some(t=>e.includes(t))).map(e=>e.id)),Rs=Object.freeze({layers:Object.freeze(vs.filter(e=>e.layered).map(e=>Object.freeze([...e.order]))),curedLast:Object.freeze(Fi.filter(e=>e.curedLast).map(e=>Object.freeze({affId:e.id,pool:Object.freeze([...new Set(vs.filter(t=>"tree"!==t.class&&t.order.includes(e.id)).flatMap(e=>e.order).filter(t=>t!==e.id))])})))}),Zs=e=>new Set(vs.filter(t=>e.has(t.id)).flatMap(e=>e.order)),Ds=Zs(Ps("herb")),Fs=Zs(Ps("smoke")),Ls=new Map(Ms.map(e=>[e.id,e.aff])),qs=new Map(xs.map(e=>[e.profession,e.pools])),Bs=(()=>{const e=new Map;for(const t of Bi)for(const n of t.skills)e.set(n,e.has(n)?null:t.id);return new Map([...e].filter(([,e])=>null!==e))})(),Gs=Object.freeze({epsilon:1e-4,forkCap:128}),Js=(e,t)=>{if(!e)throw new Error(`insight engine: ${t}`)},Us=e=>Object.keys(e).sort().map(t=>`${t}=${!0===e[t]?"t":e[t]}`).join(","),Hs=(e,t)=>{let n=0;for(const r of Object.keys(e))if(Object.hasOwn(t,r)){if(e[r]!==t[r]){const i=!0===e[r]?1:e[r],s=!0===t[r]?1:t[r];n+=Math.abs(i-s)}}else n+=1;for(const r of Object.keys(t))Object.hasOwn(e,r)||(n+=1);return n},Vs=e=>Object.freeze({p:e.p,affs:Object.freeze({...e.affs})}),Ys=e=>({p:e.p,affs:{...e.affs}}),Ws=e=>{const t=e.reduce((e,t)=>e+t.p,0);if(Js(t>0,"cannot normalize a belief with zero total mass"),Math.abs(t-1)>1e-12)for(const n of e)n.p/=t;return e},Ks=Object.freeze([]),Qs=(e,t,{contradiction:n=!1}={})=>{Js(Array.isArray(e)&&e.length>0,"finalizeForks needs at least one fork");const r=t?.growth??Gs;let i=(e=>{const t=new Map;for(const n of e){const e=Us(n.affs),r=t.get(e);r?r.p+=n.p:t.set(e,{p:n.p,affs:n.affs,encoding:e})}return[...t.values()]})(e);i=Ws(i);const{forks:s,capDiagnostic:a}=((e,t)=>{if(t<=0||e.length<=t)return{forks:e,capDiagnostic:null};const n=[...e].sort((e,t)=>t.p-e.p||(e.encoding<t.encoding?-1:1)).slice(0,t);return{forks:Ws(n),capDiagnostic:{type:"forkCapExceeded",beforeCount:e.length,afterCount:n.length,forkCap:t}}})(i,r.forkCap??Gs.forkCap);return i=((e,t)=>{if(t<=0||e.length<2)return e;const n=e.filter(e=>e.p>=t);if(0===n.length||n.length===e.length)return e;for(const r of e){if(r.p>=t)continue;let e=null,i=1/0;for(const t of n){const n=Hs(r.affs,t.affs);(n<i||n===i&&(t.p>e.p||t.p===e.p&&t.encoding<e.encoding))&&(e=t,i=n)}e.p+=r.p}return n})(s,r.epsilon??Gs.epsilon),i.sort((e,t)=>e.encoding<t.encoding?-1:e.encoding>t.encoding?1:0),!0===t?.guards?Object.freeze({forks:Object.freeze(i.map(Vs)),contradiction:n,diagnostics:a?Object.freeze([Object.freeze(a)]):Ks}):{forks:i.map(Ys),contradiction:n,diagnostics:a?[a]:Ks}},Xs=e=>!1===e.contradiction&&0===e.diagnostics.length,ea=(e,t)=>!0===t?.guards?Object.freeze({forks:Object.freeze(e.forks.map(Vs)),contradiction:!0,diagnostics:e.diagnostics}):{forks:e.forks,contradiction:!0,diagnostics:e.diagnostics},ta=({guards:e=!1}={})=>{const t={forks:[{p:1,affs:{}}],contradiction:!1,diagnostics:Ks};return e?Object.freeze({...t,forks:Object.freeze(t.forks.map(Vs))}):t},na=e=>"countable"!==e.kind||1,ra=(e,t)=>{const n=e.affById.get(t);return Js(n,`unknown affliction '${t}'`),n},ia=Object.freeze(["uniform","firstMissing","ordered"]),sa=new Set,aa=(e,t,n,r=sa)=>{let i=((e,t)=>{let n=e;for(const r of t.layers){const e=r.find(e=>n.includes(e));e&&(n=n.filter(t=>!r.includes(t)||t===e))}for(const r of t.curedLast)n.includes(r.affId)&&r.pool.some(e=>n.includes(e))&&(n=n.filter(e=>e!==r.affId));return n})(Object.keys(e),n.cureMasks);if(t.ordered){const e=t.order.find(e=>i.includes(e));i=i.filter(n=>!t.order.includes(n)||n===e)}return t.order.filter(e=>i.includes(e)&&!r.has(e))},oa=(e,t,n)=>{const r=ra(n,t),i={...e};if("countable"===r.kind){const e=i[t]-1;e<=r.min?delete i[t]:i[t]=e}else delete i[t];if(r.curesTo){const e=ra(n,r.curesTo);i[e.id]=na(e)}return i},da=Object.freeze(["=","!=","<","<=",">",">="]),la=(e,t,n)=>{switch(t){case"=":return e===n;case"!=":return e!==n;case"<":return e<n;case"<=":return e<=n;case">":return e>n;case">=":return e>=n;default:return Js(!1,`unknown comparison operator '${t}'`),!1}},ca=Object.freeze({afflicted:(e,t,n)=>{const r=ra(n,t.affId),i="countable"!==r.kind||r.max;return Xs(e)&&e.forks.every(e=>e.affs[r.id]===i)?e:Qs(e.forks.map(e=>{const t={...e.affs};if("countable"===r.kind){const e=t[r.id]??r.min;t[r.id]=Math.min(e+1,r.max)}else t[r.id]=!0;return{p:e.p,affs:t}}),n)},afflictedOneOf:(e,t,n)=>{const{pool:r,mode:i}=t;Js(Array.isArray(r)&&r.length>0,"afflictedOneOf needs a non-empty pool"),Js(ia.includes(i),`unknown afflictedOneOf mode '${i}'`);const s=new Map(r.map(e=>[e,ra(n,e)]));if(Xs(e)&&e.forks.every(e=>r.every(t=>Object.hasOwn(e.affs,t))))return e;const a=[];for(const o of e.forks){if("uniform"===i){const e=o.p/r.length;for(const t of r){const n={...o.affs};Object.hasOwn(n,t)||(n[t]=na(s.get(t))),a.push({p:e,affs:n})}continue}const e=r.filter(e=>!Object.hasOwn(o.affs,e));if(0===e.length){a.push({p:o.p,affs:o.affs});continue}if("ordered"===i){const t=e[0];a.push({p:o.p,affs:{...o.affs,[t]:na(s.get(t))}});continue}const t=o.p/e.length;for(const n of e)a.push({p:t,affs:{...o.affs,[n]:na(s.get(n))}})}return Qs(a,n)},advanced:(e,t,n)=>{Js(Array.isArray(t.rungs)&&t.rungs.length>0,"advanced needs rungs");const r=new Set,i=new Map;for(const o of t.rungs){Js(o&&"string"==typeof o.affId,"advanced rungs need an affId"),Js(!r.has(o.affId),`advanced has duplicate rung '${o.affId}'`),r.add(o.affId),i.set(o.affId,ra(n,o.affId));for(const e of[...o.gains??[],...o.consumes??[]])i.set(e,ra(n,e))}let s=!1;const a=e.forks.map(e=>{let n=-1;for(let i=0;i<t.rungs.length;i+=1)Object.hasOwn(e.affs,t.rungs[i].affId)&&(n=i);const r=t.rungs.slice(0,Math.max(0,n)),a=r.some(({affId:t})=>Object.hasOwn(e.affs,t)),o=n===t.rungs.length-1;if(o&&!a)return{p:e.p,affs:e.affs};const d={...e.affs};for(const{affId:t}of r)delete d[t];if(!o){n>=0&&delete d[t.rungs[n].affId];const e=t.rungs[n+1];d[e.affId]=na(i.get(e.affId));for(const t of e.gains??[])d[t]=na(i.get(t));for(const t of e.consumes??[])delete d[t]}return s=!0,{p:e.p,affs:d}});return!s&&Xs(e)?e:Qs(a,n)},cured:(e,t,n)=>{const r=((e,t)=>{const n=e.cureById.get(t);return Js(n,`unknown cure '${t}'`),n})(n,t.cureId);if(0===r.order.length)return e;const i=new Set(t.excludedAffs??[]),s=[];let a=!1;for(const o of e.forks){const e=aa(o.affs,r,n,i);if(0===e.length)continue;a=!0;const t=o.p/e.length;for(const r of e)s.push({p:t,affs:oa(o.affs,r,n)})}return a?Qs(s,n):e},confirmed:(e,t,n)=>{const r=ra(n,t.affId),{present:i}=t,s=e.forks.filter(e=>Object.hasOwn(e.affs,t.affId)===i);return s.length===e.forks.length&&Xs(e)?e:s.length>0?Qs(s.map(e=>({p:e.p,affs:e.affs})),n):Qs(e.forks.map(e=>{const t={...e.affs};return i?t[r.id]=na(r):delete t[r.id],{p:e.p,affs:t}}),n,{contradiction:!0})},confirmedBlocked:(e,t,n)=>{const r=ra(n,t.blockerId),{pool:i}=t;Js(Array.isArray(i)&&i.length>0,"confirmedBlocked needs a non-empty pool");for(const a of i)ra(n,a);const s=e.forks.filter(e=>Object.hasOwn(e.affs,r.id)||!i.some(t=>Object.hasOwn(e.affs,t)));return s.length===e.forks.length&&Xs(e)?e:s.length>0?Qs(s.map(e=>({p:e.p,affs:e.affs})),n):Qs(e.forks.map(e=>({p:e.p,affs:{...e.affs,[r.id]:e.affs[r.id]??na(r)}})),n,{contradiction:!0})},confirmedCount:(e,t,n)=>{const{pool:r,op:i,n:s}=t;Js(Array.isArray(r)&&r.length>0,"confirmedCount needs a non-empty pool"),Js(Number.isInteger(s)&&s>=0,"confirmedCount needs an integer n >= 0");for(const o of r)ra(n,o);const a=e.forks.filter(e=>la((e=>r.reduce((t,n)=>t+(Object.hasOwn(e.affs,n)?1:0),0))(e),i,s));return a.length===e.forks.length&&Xs(e)?e:a.length>0?Qs(a.map(e=>({p:e.p,affs:e.affs})),n):"="===i&&0===s||"<"===i&&s<=1||"<="===i&&0===s?Qs(e.forks.map(e=>{const t={...e.affs};for(const n of r)delete t[n];return{p:e.p,affs:t}}),n,{contradiction:!0}):ea(e,n)},confirmedLevel:(e,t,n)=>{const{affId:r,op:i,n:s}=t,a=ra(n,r);Js("countable"===a.kind,`confirmedLevel needs a countable aff, got '${r}'`),Js(Number.isInteger(s)&&s>=0,"confirmedLevel needs an integer n >= 0");const o=e.forks.filter(e=>la((e=>Object.hasOwn(e.affs,r)?e.affs[r]:0)(e),i,s));if(o.length===e.forks.length&&Xs(e))return e;if(o.length>0)return Qs(o.map(e=>({p:e.p,affs:e.affs})),n);const d=((e,t)=>{switch(e){case"=":case"<=":case">=":return t;case"<":return t-1;case">":return t+1;default:return null}})(i,s);return null===d||d<0||d>a.max||!la(d,i,s)?ea(e,n):Qs(e.forks.map(e=>{const t={...e.affs};return 0===d?delete t[r]:t[r]=d,{p:e.p,affs:t}}),n,{contradiction:!0})},converted:(e,t,n)=>{const r=ra(n,t.from),i=ra(n,t.to);return e.forks.some(e=>Object.hasOwn(e.affs,r.id))?Qs(e.forks.map(e=>{if(!Object.hasOwn(e.affs,r.id))return{p:e.p,affs:e.affs};const t={...e.affs},n=t[r.id];if(delete t[r.id],"countable"===i.kind){const e=!0===n?1:n;t[i.id]=Math.min(Math.max(e,1),i.max)}else t[i.id]=!0;return{p:e.p,affs:t}}),n):e},removed:(e,t,n)=>{const r=ra(n,t.affId);return Xs(e)&&!e.forks.some(e=>Object.hasOwn(e.affs,r.id))?e:Qs(e.forks.map(e=>{if(!Object.hasOwn(e.affs,r.id))return{p:e.p,affs:e.affs};const t={...e.affs};return delete t[r.id],{p:e.p,affs:t}}),n)},predictedCure:(e,t,n)=>{const{forkBranches:r}=t;if(Js(Array.isArray(r),"predictedCure needs a forkBranches array"),0===r.length)return e;const i=new Map;for(const a of r)Js(Number.isInteger(a?.forkIndex)&&a.forkIndex>=0&&a.forkIndex<e.forks.length,`predictedCure fork index '${a?.forkIndex}' is out of range`),Js(!i.has(a.forkIndex),`predictedCure addresses fork ${a.forkIndex} twice`),Js(Array.isArray(a.options)&&a.options.length>0,`predictedCure fork ${a.forkIndex} needs at least one option`),i.set(a.forkIndex,a.options);const s=[];return e.forks.forEach((e,t)=>{const r=i.get(t);if(!r)return void s.push({p:e.p,affs:e.affs});let a=0;for(const n of r)Js("number"==typeof n.weight&&Number.isFinite(n.weight)&&n.weight>0,`predictedCure option weight for '${n.affId}' must be a positive number`),Js(Object.hasOwn(e.affs,n.affId),`predictedCure option '${n.affId}' is absent from fork ${t}`),a+=n.weight;for(const i of r)s.push({p:e.p*(i.weight/a),affs:oa(e.affs,i.affId,n)})}),Qs(s,n)}}),fa=(Object.freeze(Object.keys(ca)),(e,t)=>Object.hasOwn(e.affs,t)),ua=e=>{Js(Array.isArray(e)&&e.length>0,"affliction projection needs a non-empty pool");const t=new Set;for(const n of e)Js("string"==typeof n&&n.length>0,"affliction pool ids must be non-empty strings"),Js(!t.has(n),`affliction pool contains duplicate '${n}'`),t.add(n)},pa=(e,t)=>t.reduce((t,n)=>t+(fa(e,n)?1:0),0),ha=(e,t)=>{let n=0;for(const r of e.forks)fa(r,t)&&(n+=r.p);return n},ma=(e,t)=>{ua(t);let n=0;for(const r of e.forks)t.some(e=>fa(r,e))&&(n+=r.p);return n},ga=(e,t)=>{ua(t);let n=0;for(const r of e.forks)t.every(e=>fa(r,e))&&(n+=r.p);return n},ya=(e,t)=>{ua(t);let n=0;for(const r of e.forks)n+=r.p*pa(r,t);return n},ba=(e,t)=>{let n=0,r=0;for(const i of e.forks)if(fa(i,t)){const e=!0===i.affs[t]?1:i.affs[t];n+=i.p,r+=e*i.p}return 0===n?0:r/n},va=e=>{let t=0;for(const n of e.forks)n.p>0&&(t-=n.p*Math.log2(n.p));return t},ka=Object.freeze(["healthy","damaged","mangled"]),wa=(e,t)=>{if(!e)throw new Error(`insight domain: ${t}`)},Ia=Object.freeze(["best","worst","distribution"]),za=["focus","herb","smoke","salve","restoration","sip","tree","balance","equilibrium"],_a=new WeakMap,Oa=(e,t,n=1)=>{const r=e.priorityByAff.get(t);if(!r)return null;const i=r.get(n);if(void 0!==i)return i;let s=null,a=null;for(const o of r.keys())o<=n&&(null===s||o>s)&&(s=o),(null===a||o<a)&&(a=o);return r.get(s??a)},$a=(e,t)=>t.some(t=>Array.isArray(t)?t.every(t=>Object.hasOwn(e,t)):Object.hasOwn(e,t)),Sa=(e,t)=>!e.professions||null!==t&&e.professions.includes(t),Na=e=>e.reduce((e,t)=>t.prio<e.prio||t.prio===e.prio&&t.affId<e.affId?t:e),xa=e=>e.reduce((e,t)=>t.prio>e.prio||t.prio===e.prio&&t.affId<e.affId?t:e),ja=(e,t,n,r)=>{wa(Ia.includes(n),`unknown predictive policy '${n}'`);const i=[],s=new Set;return e.forks.forEach((e,a)=>{const o=((e,t,n)=>{const{tables:r,context:i,opponentClass:s,isBalanceReady:a}=n,o=i.curesByChannel.get(t);if(!o)return[];const d=new Map;for(const l of o)if(Sa(l,s)&&l.bals_req.every(a)&&!$a(e,l.blocks))for(const t of aa(e,l,r)){const n=Oa(r,t,!0===e[t]?1:e[t]);if(null===n||n<1||n>25)continue;const i=d.get(t);(!i||l.id<i.cureId)&&d.set(t,{affId:t,prio:n,cureId:l.id,balsUsed:l.bals_used})}return[...d.values()]})(e.affs,t,r);if(0===o.length)return;let d;d="best"===n?[{...Na(o),weight:1}]:"worst"===n?[{...xa(o),weight:1}]:(e=>{const t=[...e].sort((e,t)=>e.prio-t.prio||(e.affId<t.affId?-1:1));let n=0,r=null;return t.map(e=>(e.prio!==r&&(n+=1,r=e.prio),{...e,weight:1/n}))})(o);for(const t of d)for(const e of t.balsUsed)s.add(e);i.push({forkIndex:a,options:d.map(({affId:e,weight:t})=>({affId:e,weight:t}))})}),0===i.length?null:{event:{type:"predictedCure",forkBranches:i},consumed:s}},Ma=Object.freeze({stalenessHalfLifeMs:6e4,entropyScaleBits:Math.log2(Gs.forkCap)}),Ta=(e,t={})=>{const n=t.stalenessHalfLifeMs??Ma.stalenessHalfLifeMs,r=t.entropyScaleBits??(void 0===(i=t.forkCap)?Ma.entropyScaleBits:Math.max(1,Math.log2(i)));var i;const s=Math.min(1,va(e.belief)/r),a=Math.max(0,e.now-e.lastObservedAt);return 1-(1-s)*(1-a/(a+n))},Aa=(e,t={})=>Object.freeze({affId:e,...t.gains?{gains:Object.freeze(t.gains)}:{},...t.consumes?{consumes:Object.freeze(t.consumes)}:{}}),Ea=Object.freeze({head:Object.freeze([Aa("damagedhead",{gains:["stupidity"]}),Aa("mangledhead",{gains:["stuttering","clumsiness"]})]),torso:Object.freeze([Aa("mildtrauma"),Aa("serioustrauma")]),leftarm:Object.freeze([Aa("damagedleftarm",{consumes:["brokenleftarm"]}),Aa("mangledleftarm")]),rightarm:Object.freeze([Aa("damagedrightarm",{consumes:["brokenrightarm"]}),Aa("mangledrightarm")]),leftleg:Object.freeze([Aa("damagedleftleg",{consumes:["brokenleftleg"]}),Aa("mangledleftleg")]),rightleg:Object.freeze([Aa("damagedrightleg",{consumes:["brokenrightleg"]}),Aa("mangledrightleg")])}),Ca=Object.freeze(Object.keys(Ea)),Pa=Object.freeze(new Map(Object.entries(Ea).flatMap(([e,t])=>t.map(t=>[t.affId,e])))),Ra=e=>{const t=Ea[e];return wa(t,`unknown limb '${e}'`),t},Za=(e,t)=>((e,t)=>{Js(Array.isArray(t)&&2===t.length,"ladder projection needs two rungs");const n={healthy:0,damaged:0,mangled:0};for(const i of e.forks){let e=-1;for(let n=0;n<t.length;n+=1)fa(i,t[n].affId)&&(e=n);n[ka[e+1]]+=i.p}const r=n.healthy+n.damaged+n.mangled;return 1!==r&&(n.healthy/=r,n.damaged/=r,n.mangled/=r),n})(e,Ra(t)),Da=Object.freeze(["observed","simulated"]),Fa=Ca,La=Object.freeze(["hp","mana"]),qa=Object.freeze({policy:"distribution",predictionEnabled:!1,limbResetMs:18e4}),Ba=e=>{if(e&&"object"==typeof e&&!Object.isFrozen(e)){Object.freeze(e);for(const t of Object.keys(e))Ba(e[t])}return e},Ga=e=>{const t={};for(const[n,r]of[...e].sort(([e],[t])=>e<t?-1:e>t?1:0))t[n]=r;return t},Ja=(e,t,n={})=>{wa("string"==typeof e&&e.length>0,"createOpponentModel needs an id"),wa(t?.affById&&t?.cureById&&t?.cureMasks,"createOpponentModel needs engine tables (affById, cureById, cureMasks)"),wa(t?.balanceById&&t?.priorityByAff,"createOpponentModel needs domain tables (balanceById, priorityByAff)");const r={...qa,...n};wa(Ia.includes(r.policy),`unknown predictive policy '${r.policy}'`);const i=!0===r.guards,s=(e=>{const t=_a.get(e);if(t)return t;const n=new Map;for(const s of e.cureById.values()){if(0===s.bals_used.length||0===s.order.length)continue;const e=s.bals_used[0];n.has(e)||n.set(e,[]),n.get(e).push(s)}const r=Object.freeze([...za.filter(e=>n.has(e)),...[...n.keys()].filter(e=>!za.includes(e)).sort()]),i=Object.freeze({curesByChannel:n,channelOrder:r});return _a.set(e,i),i})(t);let a=ta({guards:i}),o=0,d=0,l="observed",c=r.policy,f=!0===r.predictionEnabled,u=null;const p=new Map([...t.balanceById.keys()].map(e=>[e,0])),h=new Map,m=[];let g=0;const y=new Map(Fa.map(e=>[e,{percent:0,lastHitAt:null}])),b=new Map,v=new Map;let k={shadowInstill:null,timeloop:{count:0,max:3}};const w=new Set;let I=!1,z=null,_=0,O=0;const $=()=>{I||(_+=1),I=!0,z=null},S=()=>{d!==o&&(d=o,O+=1)},N=()=>{if(I&&(I=!1,w.size>0)){const e=U();for(const t of[...w])t(e)}},x=e=>{const n=t.balanceById.get(e);return wa(n,`unknown balance '${e}'`),n},j=(e,t)=>{p.get(e)!==t&&(p.set(e,t),$())},M=(e,t)=>{j(e,o+(t??x(e).observedDurationMs))},T=e=>{j(e,o+x(e).predictiveDurationMs)},A=e=>{const t=H(e);0===t.percent&&null===t.lastHitAt||(t.percent=0,t.lastHitAt=null,$())},E=new Set(["cured","removed","converted","confirmed"]),C=e=>{const n=a,r=((e,t,n)=>{Js(e&&Array.isArray(e.forks),"apply needs a Belief"),Js(t&&"string"==typeof t.type,"apply needs an event with a type"),Js(n?.affById&&n?.cureById&&n?.cureMasks,"apply needs tables");const r=ca[t.type];Js(r,`unknown event type '${t.type}'`);const i=r(e,t,n);return 0===i.diagnostics.length?i:!0===n.guards?Object.freeze({forks:i.forks,contradiction:i.contradiction,diagnostics:Object.freeze(i.diagnostics.map(e=>e.eventType?e:Object.freeze({...e,eventType:t.type})))}):{forks:i.forks,contradiction:i.contradiction,diagnostics:i.diagnostics.map(e=>e.eventType?e:{...e,eventType:t.type})}})(a,e,t);return r!==a&&(a=r,((e,n,r)=>{if(!E.has(r.type))return;if("confirmed"===r.type&&!1!==r.present)return;let i=!1;for(const t of y.values())if(0!==t.percent||null!==t.lastHitAt){i=!0;break}if(i){if("removed"===r.type||"converted"===r.type||"confirmed"===r.type){const t="converted"===r.type?r.from:r.affId;if(t){const r=Pa.get(t);if(r){const i=ha(e,t);i>0&&ha(n,t)<i&&A(r)}}return}if("cured"===r.type){const i=t.cureById.get(r.cureId);if(!i||!i.order)return;for(const t of i.order){const r=Pa.get(t);if(r){const i=ha(e,t);i>0&&ha(n,t)<i&&A(r)}}}}})(n,r,e),$()),r},P=(e,t)=>{h.get(e)!==t&&(h.set(e,t),$())},R=e=>{h.delete(e)&&$()},Z=(e,n)=>{const r=t.affById.get(e);"timed"===r?.kind&&P(e,o+(n??r.durationMs))},D=(e,n)=>{const r=t.affById.get(e);if("timed"===r?.kind){const t=o+(n??r.durationMs),i=h.get(e);P(e,void 0===i?t:Math.max(i,t))}},F=()=>{for(const e of[...h.keys()])0===ha(a,e)&&R(e)},L=(e,t)=>{const n=[...h.entries()].filter(([,e])=>e<=o).sort((e,t)=>e[1]-t[1]||(e[0]<t[0]?-1:1));for(const[r,i]of n)if(R(r),ha(a,r)>0){const n=C({type:"removed",affId:r});t.push(...n.diagnostics),e.push({affId:r,atMs:i})}},q=(e,t)=>{const n=m.filter(({atMs:e})=>e<=o).sort((e,t)=>e.atMs-t.atMs||e.sequence-t.sequence);for(const r of n){m.splice(m.indexOf(r),1),$();const n=C(r.event);t.push(...n.diagnostics),F(),e.push({atMs:r.atMs,cureId:r.event.cureId})}},B=(e,n)=>{if(!f)return;const r=e=>(p.get(e)??1/0)<=o;let i=!0;for(;i;){i=!1;for(const d of s.channelOrder){const l=p.get(d);if(void 0===l||l>o)continue;const f=ja(a,d,c,{tables:t,context:s,opponentClass:u,isBalanceReady:r});if(!f)continue;const h=C(f.event);n.push(...h.diagnostics);for(const e of f.consumed)T(e);e.push({atMs:o,channelId:d,policy:c,event:f.event,consumed:[...f.consumed].sort()}),i=!0}}F()},G=(e,t)=>{let n=1/0;for(const[,r]of h)r>o&&r<=e&&r<n&&(n=r);for(const{atMs:r}of m)r>o&&r<=e&&r<n&&(n=r);for(const i of y.values()){const t=null===i.lastHitAt?null:i.lastHitAt+r.limbResetMs;null!==t&&t>o&&t<=e&&t<n&&(n=t)}if(t)for(const r of s.channelOrder){const t=p.get(r);void 0!==t&&t>o&&t<=e&&t<n&&(n=t)}return n},J=()=>{const e=(e=>{const t={};for(const n of e.forks)for(const e of Object.keys(n.affs))t[e]=(t[e]??0)+n.p;return t})(a),n={};for(const i of Object.keys(e).sort())n[i]="countable"===t.affById.get(i)?.kind?{probability:e[i],count:ba(a,i)}:{probability:e[i]};const r={};for(const t of Fa)r[t]={percent:y.get(t).percent,stages:Za(a,t)};return{mode:l,policy:c,predictionEnabled:f,class:u,entropy:va(a),forkCount:a.forks.length,affs:n,expiries:Ga(h.entries()),pendingCures:m.slice().sort((e,t)=>e.atMs-t.atMs||e.sequence-t.sequence).map(({atMs:e,event:t})=>({atMs:e,cureId:t.cureId,excludedAffs:[...t.excludedAffs]})),limbs:r,stats:Ga([...b.entries()].map(([e,t])=>[e,{...t}])),defs:Ga([...v.entries()].map(([e,t])=>[e,{...t}])),skillState:i?JSON.parse(JSON.stringify(k)):k}},U=()=>{null===z&&(z=i?Ba(J()):J());const n=z,s={};for(const[e,t]of[...p.entries()].sort(([e],[t])=>e<t?-1:e>t?1:0))s[e]={readyAtMs:t,remainingMs:Math.max(0,t-o)};const a={id:e,mode:n.mode,policy:n.policy,predictionEnabled:n.predictionEnabled,class:n.class,now:o,lastObservedAt:d,staleness:Ta(V,{stalenessHalfLifeMs:r.stalenessHalfLifeMs,forkCap:t.growth?.forkCap}),entropy:n.entropy,forkCount:n.forkCount,affs:n.affs,balances:s,expiries:n.expiries,pendingCures:n.pendingCures,limbs:n.limbs,stats:n.stats,defs:n.defs,skillState:n.skillState};return i?Ba(a):a},H=e=>{const t=y.get(e);return wa(t,`unknown limb '${e}'`),t},V={id:e,get revision(){return _},get timeEpoch(){return O},get now(){return o},get mode(){return l},get policy(){return c},get class(){return u},get lastObservedAt(){return d},get belief(){return a},isPredictionEnabled:()=>f,isBalanceReady:e=>(x(e),(p.get(e)??0)<=o),haveDef:e=>!0===v.get(e)?.have,getStat:e=>{wa(La.includes(e),`unknown stat '${e}'`);const t=b.get(e);return t?{...t}:null},limbPercent:e=>H(e).percent,limbStages:e=>(H(e),Za(a,e)),getSkillState:()=>i?Ba(JSON.parse(JSON.stringify(k))):k,nextInterestingAt({prediction:e=f,includeDue:t=!1}={}){if(t&&e)for(const r of s.channelOrder){const e=p.get(r);if(void 0!==e&&e<=o)return o}const n=G(1/0,e);return Number.isFinite(n)?n:null},apply:e=>{wa(e&&"string"==typeof e.type,"apply needs an event with a type"),wa("elapsed"!==e.type&&"predictedCure"!==e.type,`'${e.type}' is not an observation — it is produced by the simulation itself`);const n="cured"===e.type?t.cureById.get(e.cureId):null,r=void 0!==n?.delayMs,i=r?{contradiction:!1,diagnostics:[]}:C(e);switch(e.type){case"afflicted":Z(e.affId,e.durationMs);break;case"afflictedOneOf":for(const t of e.pool)D(t,e.durationMs);break;case"confirmed":e.present&&(e=>{const n=t.affById.get(e);"timed"!==n?.kind||h.has(e)||P(e,o+n.durationMs)})(e.affId);break;case"converted":R(e.from),Z(e.to);break;case"cured":if(n){for(const e of n.bals_used)M(e);r&&((e,t)=>{m.push({atMs:o+t,sequence:g,event:{type:"cured",cureId:e.cureId,excludedAffs:[...e.excludedAffs??[]]}}),g+=1,$()})(e,n.delayMs)}}return F(),S(),N(),{contradiction:i.contradiction,diagnostics:i.diagnostics}},elapsed:e=>{wa("number"==typeof e&&Number.isFinite(e)&&e>=0,"elapsed needs a non-negative dtMs");const t=o+e;e>0&&(O+=1);const n=[],i=[],s=[],a=[];for(;;){L(n,a),q(i,a),B(s,a);const e=G(t,f);if(!Number.isFinite(e))break;o=e}o=t;for(const d of y.values())null!==d.lastHitAt&&o-d.lastHitAt>=r.limbResetMs&&(d.percent=0,d.lastHitAt=null,$());return N(),{expired:n,resolvedCures:i,predicted:s,diagnostics:a}},snapshot:U,onChange:e=>(wa("function"==typeof e,"onChange needs a function"),w.add(e),()=>w.delete(e)),setMode(e){wa(Da.includes(e),`unknown observation mode '${e}'`),l!==e&&(l=e,$()),"observed"===e&&S(),N()},setPolicy(e){wa(Ia.includes(e),`unknown predictive policy '${e}'`),c!==e&&(c=e,$()),N()},enablePrediction(){f||(f=!0,$()),N()},disablePrediction(){f&&(f=!1,$()),N()},setClass(e){const t="string"==typeof e&&e.trim()?e.trim().toLowerCase():null;u!==t&&(u=t,$()),N()},consumeBalance(e,t){x(e),M(e,t),N()},setStat(e,t){wa(La.includes(e),`unknown stat '${e}'`),wa("number"==typeof t&&Number.isFinite(t),"setStat needs a number");const n=b.get(e);n&&n.value===t&&n.atMs===o||(b.set(e,{value:t,atMs:o}),$()),N()},setDef(e,t){wa("string"==typeof e&&e.length>0,"setDef needs a def id");const n=!0===t,r=v.get(e);r&&r.have===n&&r.atMs===o||(v.set(e,{have:n,atMs:o}),$()),N()},hitLimb(e,t){wa("number"==typeof t&&Number.isFinite(t)&&t>=0,"hitLimb needs a non-negative percent");const n=H(e),r=n.percent+t>=100,i=r?0:n.percent+t,s=r?null:o;return n.percent===i&&n.lastHitAt===s||(n.percent=i,n.lastHitAt=s,$()),N(),{advanced:r,percent:i}},resetLimb(e){const t=H(e);0===t.percent&&null===t.lastHitAt||(t.percent=0,t.lastHitAt=null,$()),N()},updateSkillState(e){wa(e&&"object"==typeof e,"updateSkillState needs a patch object");for(const[t,n]of Object.entries(e)){const e=k[t];null===n||"object"!=typeof n||Array.isArray(n)||null===e||"object"!=typeof e||Array.isArray(e)?e!==n&&(k[t]=n,$()):Object.entries(n).some(([t,n])=>e[t]!==n)&&(k[t]={...e,...n},$())}N()},reset(){a=ta({guards:i}),h.clear(),m.length=0;for(const e of p.keys())p.set(e,o);for(const e of y.values())e.percent=0,e.lastHitAt=null;b.clear(),v.clear(),k={shadowInstill:null,timeloop:{count:0,max:3}},$(),N()}};return Object.freeze(V)},Ua=/^[A-Za-z]+$/,Ha=e=>{if("string"!=typeof e)return null;const t=e.trim();return t&&Ua.test(t)?t.toLowerCase():null},Va=(e={})=>{const{tables:t,...n}=e;wa(t,"createRosterModel needs config.tables");const r=!0===n.guards,i=new Map,s=new Map;let a=null,o=0;const d=new Set,l=new Set,c=()=>{if(o+=1,0===d.size)return;const e={ids:[...i.keys()],targetId:a};r&&(Object.freeze(e.ids),Object.freeze(e));for(const t of[...d])t(e)},f=e=>{let r=i.get(e);return r||(r=Ja(e,t,n),i.set(e,r),s.set(e,r.onChange(t=>{o+=1,((e,t)=>{for(const n of[...l])n(e,t)})(e,t)})),c()),r},u={track(e){const t=Ha(e);if(!t)return null;const n=f(t);return n.setMode("observed"),n},untrack(e){const t=Ha(e),n=t?i.get(t):null;return!!n&&(n.setMode("simulated"),!0)},setTarget(e){if(null===e)return null!==a&&(a=null,c()),null;const t=Ha(e);if(!t)return null;const n=f(t);return a!==t&&(a=t,c()),n},get targetId(){return a},get revision(){return o},getTarget:()=>a?i.get(a)??null:null,get(e){const t=Ha(e);return t?i.get(t)??null:null},list:()=>[...i.keys()],listObserved(){const e=[];for(const[t,n]of i)"observed"===n.mode&&e.push(t);return e},remove(e){const t=Ha(e);return!(!t||!i.has(t))&&(s.get(t)(),s.delete(t),i.delete(t),a===t&&(a=null),c(),!0)},updateDefaults(e={}){const{policy:t,predictionEnabled:r}=e;void 0!==t&&(wa(Ia.includes(t),`unknown predictive policy '${t}'`),n.policy=t),void 0!==r&&(n.predictionEnabled=!0===r);for(const n of i.values())void 0!==t&&n.setPolicy(t),void 0!==r&&(!0===r?n.enablePrediction():n.disablePrediction())},reset(e){const t=u.get(e);return!!t&&(t.reset(),!0)},resetAll(){for(const e of i.values())e.reset()},elapsed(e){const t={};for(const[n,r]of i)t[n]=r.elapsed(e);return t},snapshot(){const e={};for(const t of[...i.keys()].sort())e[t]=i.get(t).snapshot();return r?Object.freeze({targetId:a,opponents:Object.freeze(e)}):{targetId:a,opponents:e}},onChange:e=>(wa("function"==typeof e,"onChange needs a function"),d.add(e),()=>d.delete(e)),onOpponentChange:e=>(wa("function"==typeof e,"onOpponentChange needs a function"),l.add(e),()=>l.delete(e))};return Object.freeze(u)},Ya=Object.freeze({lovers:/^(\w+) shakes \w+ head and a look of clarity returns to \w+ eyes\.$/,shadowmadness:/^Lucidity returns to the eyes of (\w+)\.$/,whisperingmadness:/^(\w+) ceases \w+ violent trembling\.$/}),Wa=Object.freeze([Object.freeze({id:"asthma-blocks-smoke",blockerId:"asthma",balanceId:"smoke",pool:Object.freeze([...Fs].sort()),evidence:/^\w+ takes a long drag off \w+ pipe\.$/}),Object.freeze({id:"anorexia-blocks-herb",blockerId:"anorexia",balanceId:"herb",pool:Object.freeze([...Ds].sort()),evidence:/^\w+ eats a.+\.$/})]),Ka=Object.freeze([Object.freeze({id:"fulminate-paralysis-on-focus",cureId:"focus",affId:"fulminated",absentAffId:"paralysis",evidence:/^Horror overcomes \w+'s face as \w+ body stiffens into paralysis\.$/})]),Qa=qs.get("depthswalker"),Xa=[{skill:"aeonics",id:"timeloop",handler:(e,t)=>[{type:"afflicted",affId:"timeloop"},{type:"updateSkillState",patch:{timeloop:{max:t.checkBlock("You have now aged yourself")?4:3,count:0}}}]},{skill:"aeonics",id:"timeloopProc",handler:(e,t,n)=>{const r=[],i=Qa[n.skillState.shadowInstill];i&&r.push({type:"afflictedOneOf",pool:[...i],mode:"ordered"});const{count:s=0,max:a=3}=n.skillState.timeloop??{},o=s+1;return o>=a?r.push({type:"removed",affId:"timeloop"},{type:"updateSkillState",patch:{timeloop:{count:0}}}):r.push({type:"updateSkillState",patch:{timeloop:{count:o}}}),r}},{skill:"aeonics",id:"accelerate",handler:(e,t)=>{const n={type:"cured",cureId:"accelerate"};return t.nextLine("grows older before your eyes.")?[n,{...n}]:[n]}}],eo={dissipate:[{type:"statChanged",statId:"mana",delta:-.15}],palpitation:[{type:"statChanged",statId:"hp",delta:-.15}],heat:[{type:"afflicted",affId:"burning"}],creeps:[{type:"afflicted",affId:"agoraphobia"},{type:"afflicted",affId:"claustrophobia"}],oscillate:[{type:"afflicted",affId:"stupidity"},{type:"afflicted",affId:"epilepsy"}],disorientation:[{type:"afflicted",affId:"prone"},{type:"afflicted",affId:"dizziness"}],dissonance:[{type:"defStripped",defId:"shield"}],plague:[{type:"afflicted",affId:"brokenrightarm"},{type:"afflicted",affId:"brokenrightleg"},{type:"afflicted",affId:"brokenleftleg"}],lullaby:[{type:"defStripped",defId:"insomnia"}],retardation:[{type:"defStripped",defId:"speed"},{type:"afflicted",affId:"aeon"}]};eo.plauge=eo.plague;var to={disorientation:[{type:"afflicted",affId:"dizziness"}],creeps:[{type:"afflicted",affId:"shyness"}],dissonance:[{type:"afflicted",affId:"dissonance"}]},no=e=>(e.args.info??"").toLowerCase(),ro=[{skill:"crystalism",id:"destabilise",handler:e=>(eo[no(e)]??[]).map(e=>({...e}))},{skill:"crystalism",id:"vibeTick",handler:e=>(to[no(e)]??[]).map(e=>({...e}))}],io=e=>(t,n,r)=>"thirdPerson"===t.matchType?e(t,n,r):[],so=(e,t)=>t.some(t=>e.have(t)),ao={body:e=>e.have("anorexia")?[{type:"cured",cureId:"epidermal to body"}]:so(e,["hypothermia","heartseed","serioustrauma","mildtrauma","calcifiedtorso"])?[{type:"cured",cureId:"restoration to torso"}]:[{type:"cured",cureId:"mending to body"}],head:e=>so(e,["damagedhead","mangledhead","calcifiedskull"])?[{type:"cured",cureId:"restoration to head"}]:e.have("stuttering")?[{type:"cured",cureId:"epidermal to head"}]:e.have("unblind")||e.have("undeaf")?[{type:"afflicted",affId:"undeaf"}]:[],arms:e=>so(e,["damagedleftarm","damagedrightarm","mangledleftarm","mangledrightarm"])?[{type:"cured",cureId:"restoration to arms"}]:[{type:"cured",cureId:"mending to arms"}],legs:e=>so(e,["damagedleftleg","damagedrightleg","mangledleftleg","mangledrightleg"])?[{type:"cured",cureId:"restoration to legs"}]:[{type:"cured",cureId:"mending to legs"}],skin:e=>so(e,["frozen","shivering","frostbite"])?[{type:"cured",cureId:"caloric"}]:[{type:"defRaised",defId:"insulation"}]};ao.torso=ao.body;var oo=[{skill:"curing",id:"apply",handler:io((e,t,n)=>{const r=(e.args.info??"").toLowerCase();return ao[r]?ao[r](n):[]})},{skill:"curing",id:"health",handler:io(e=>{const t=`health to ${(e.args.info??"").toLowerCase()}`;return As.has(t)?[{type:"cured",cureId:t}]:[]})},{skill:"curing",id:"smoke",handler:io((e,t,n)=>so(n,["aeon","deadening","tension","unweavingspirit"])?[{type:"cured",cureId:"cinnabar"}]:so(n,["disloyalty","hellsight","manaleech","slickness"])?[{type:"cured",cureId:"realgar"}]:[])},{skill:"curing",id:"focus",handler:io(()=>[{type:"cured",cureId:"focus"}])},{skill:"tattoos",id:"tree",handler:io(()=>[{type:"cured",cureId:"tree"}])},{skill:"tattoos",id:"shield",handler:io(()=>[{type:"defRaised",defId:"shield"}])},{skill:"defense",id:"prismatic",handler:io(()=>[{type:"defRaised",defId:"prismatic"}])},{skill:"venom",id:"shrugging",handler:io(()=>[{type:"cured",cureId:"shrugging"}])}],lo=qs.get("occultist"),co=/^Horror overcomes \w+'s face as \w+ body stiffens into paralysis\.$/,fo=["brokenrightarm","brokenleftarm","brokenrightleg","brokenleftleg"],uo=e=>{const t=e.queuedCommand("c!p!w!t"),n=t?t.match(/COMMAND FIRELORD AT \w+ (\w+)/):null;return n?n[1].toLowerCase():null},po=[{skill:"domination",id:"humbugCommand",handler:()=>[{type:"afflicted",affId:"addiction"}]},{skill:"domination",id:"houndCommand",handler:()=>[{type:"afflicted",affId:"weariness"}]},{skill:"domination",id:"stormCommand",handler:()=>[{type:"afflicted",affId:"clumsiness"}]},{skill:"domination",id:"stormCommand2",handler:()=>[{type:"confirmed",affId:"clumsiness",present:!0}]},{skill:"domination",id:"bloodleechCommand",handler:()=>[{type:"afflicted",affId:"haemophilia"}]},{skill:"domination",id:"sycophantCommand",handler:()=>[{type:"afflicted",affId:"weakenedmind"}]},{skill:"domination",id:"slimeCommand",handler:(e,t)=>[{type:"afflicted",affId:"slimeobscure"},{type:"confirmed",affId:"asthma",present:t.checkBlock(co)}]},{skill:"domination",id:"chimeraCommandDeaf",handler:()=>[{type:"confirmed",affId:"undeaf",present:!1}]},{skill:"domination",id:"chimeraCommand",handler:(e,t,n)=>{const r=[{type:"confirmed",affId:"undeaf",present:!0}];var i;return t.checkBlock((i=n.id).charAt(0).toUpperCase()+i.slice(1))||r.push({type:"afflicted",affId:"hallucinations"}),r}},{skill:"domination",id:"bubonisCommand",handler:(e,t,n)=>n.haveDef("fangbarrier")?t.nextLine("The protective coating covering the skin of")?[{type:"confirmed",affId:"asthma",present:!0},{type:"afflicted",affId:"slickness"}]:[{type:"afflicted",affId:"asthma"}]:n.probability("asthma")>.49?[{type:"afflicted",affId:"slickness"}]:[{type:"afflicted",affId:"asthma"}]},{skill:"domination",id:"wormCommand",handler:()=>[{type:"afflicted",affId:"palpatarfeed"}]},{skill:"domination",id:"wormTick",handler:()=>[{type:"afflicted",affId:"healthleech"}]},{skill:"domination",id:"croneCommand",handler:()=>[{type:"afflictedOneOf",pool:[...fo],mode:"firstMissing"}]},{skill:"domination",id:"cronePrimebond",handler:()=>[{type:"afflictedOneOf",pool:[...fo],mode:"firstMissing"}]},{skill:"domination",id:"abominationCommandFail",handler:()=>[{type:"removed",affId:"cleanseaura"}]},{skill:"domination",id:"gremlinCommand",handler:()=>[{type:"defStripped",defId:"shield"}]},{skill:"domination",id:"gremlinCommandFail",handler:()=>[{type:"defStripped",defId:"shield"}]},{skill:"domination",id:"firelordCommand",handler:(e,t)=>{const n=uo(t);return"manaleech"===n?[{type:"confirmed",affId:"manaleech",present:!0},{type:"removed",affId:"manaleech"},{type:"afflicted",affId:"anorexia"}]:"healthleech"===n?[{type:"confirmed",affId:"healthleech",present:!0}]:"whisperingmadness"===n?[{type:"confirmed",affId:"whisperingmadness",present:!0},{type:"removed",affId:"whisperingmadness"},{type:"afflicted",affId:"recklessness"}]:[]}},{skill:"domination",id:"firelordCommandFail",handler:(e,t)=>{const n=uo(t);return n?[{type:"confirmed",affId:n,present:!1}]:[]}},{skill:"domination",id:"wormPrimebond",handler:()=>[{type:"afflicted",affId:"nausea"}]},{skill:"domination",id:"gremlinPrimebond",handler:()=>[{type:"afflicted",affId:"dizziness"}]},{skill:"domination",id:"gremlinPrimebond2",handler:()=>[{type:"confirmed",affId:"dizziness",present:!0}]},{skill:"domination",id:"humbugPrimebond",handler:(e,t,n)=>{const r=n.probability("addiction")>.49?-.1:-.05;return[{type:"statChanged",statId:"hp",delta:r},{type:"statChanged",statId:"mana",delta:r}]}},{skill:"domination",id:"bubonisPrimebond",handler:()=>[{type:"afflictedOneOf",pool:[...lo.bubonis],mode:"firstMissing"}]},{skill:"domination",id:"chimeraPrimebondGas",handler:()=>[{type:"defStripped",defId:"insomnia"}]},{skill:"domination",id:"chimeraPrimebondRam",handler:()=>[{type:"afflicted",affId:"prone"}]},{skill:"domination",id:"chimeraPrimebondRoar",handler:()=>[{type:"afflicted",affId:"undeaf"},{type:"afflicted",affId:"prone"}]},{skill:"domination",id:"chimeraPrimebondUndeaf",handler:()=>[{type:"afflicted",affId:"undeaf"}]}],ho=[{skill:"dragoncraft",id:"gust",handler:()=>[{type:"afflicted",affId:"prone"}]},{skill:"dragoncraft",id:"dragonroar",handler:(e,t)=>{if("thirdPerson"===e.matchType)return[{type:"afflicted",affId:"undeaf"}];const n=t.queuedCommand();return n&&/DRAGONROAR \w+/.test(n)?[{type:"afflicted",affId:"undeaf"}]:[]}},{skill:"dragoncraft",id:"rendTargeted",handler:(e,t,n)=>mo(n)},{skill:"dragoncraft",id:"rendUntargeted",handler:(e,t,n)=>mo(n)},{skill:"dragoncraft",id:"tailsweepHit",handler:()=>[{type:"afflicted",affId:"prone"}]},{skill:"dragoncraft",id:"dragonheal",handler:e=>"thirdPerson"===e.matchType?[{type:"cured",cureId:"dragonheal"}]:[]}],mo=e=>{const t=e.skillState.envenom;if(!t)return[];const n=Ls.get(t),r=[{type:"updateSkillState",patch:{envenom:null}}];return n&&r.unshift({type:"afflicted",affId:n}),r},go=e=>`broken${(e??"").replace(/\s/g,"").toLowerCase()}`,yo=e=>e.haveDef("insulation")?[{type:"defStripped",defId:"insulation"}]:[{type:"afflictedOneOf",pool:["shivering","frozen"],mode:"ordered"}],bo=[{skill:"elementalism",id:"shalestormTick",handler:e=>[{type:"afflicted",affId:go(e.args.limb)}]},{skill:"elementalism",id:"shalestormRaze",handler:()=>[{type:"defStripped",defId:"shield"}]},{skill:"elementalism",id:"firelash",handler:()=>[{type:"afflicted",affId:"burning"}]},{skill:"elementalism",id:"firelashLOS",handler:()=>[{type:"afflicted",affId:"burning"}]},{skill:"elementalism",id:"freeze",handler:(e,t,n)=>yo(n)},{skill:"elementalism",id:"dehydrate",handler:()=>[{type:"afflicted",affId:"nausea"},{type:"afflicted",affId:"weariness"}]},{skill:"elementalism",id:"fulminate",handler:()=>[{type:"afflictedOneOf",pool:["fulminated","epilepsy","paralysis"],mode:"ordered"}]},{skill:"elementalism",id:"bombard",handler:()=>[{type:"afflicted",affId:"clumsiness"}]},{skill:"elementalism",id:"mudslide",handler:()=>[{type:"afflicted",affId:"slickness"},{type:"afflicted",affId:"prone"}]},{skill:"elementalism",id:"magma",handler:()=>[{type:"afflicted",affId:"scalded"}]},{skill:"elementalism",id:"emanationFire",handler:()=>[{type:"afflicted",affId:"burning"},{type:"afflicted",affId:"burning"}]},{skill:"elementalism",id:"emanationAir",handler:()=>[{type:"afflicted",affId:"paralysis"},{type:"afflicted",affId:"dizziness"}]},{skill:"elementalism",id:"emanationEarth",handler:()=>[{type:"afflicted",affId:"calcifiedtorso"}]},{skill:"elementalism",id:"emanationWater",handler:(e,t,n)=>yo(n)},{skill:"elementalism",id:"resonanceAirMinor",handler:()=>[{type:"afflicted",affId:"asthma"}]},{skill:"elementalism",id:"resonanceAirModerate",handler:(e,t,n)=>n.have("undeaf")?[{type:"afflicted",affId:"sensitivity"}]:[{type:"afflicted",affId:"undeaf"}]},{skill:"elementalism",id:"resonanceAirMajor",handler:()=>[{type:"afflicted",affId:"healthleech"}]},{skill:"elementalism",id:"resonanceEarthMinor",handler:e=>[{type:"afflicted",affId:go(e.args.limb)}]},{skill:"elementalism",id:"resonanceEarthModerate",handler:()=>[{type:"afflicted",affId:"paralysis"}]},{skill:"elementalism",id:"resonanceEarthMajor",handler:()=>[{type:"afflicted",affId:"crackedribs"}]},{skill:"elementalism",id:"resonanceFireMinor",handler:()=>[{type:"defStripped",defId:"temperence"}]},{skill:"elementalism",id:"resonanceFireModerate",handler:(e,t,n)=>n.have("scalded")?[{type:"afflicted",affId:"burning"}]:[{type:"afflicted",affId:"scalded"}]},{skill:"elementalism",id:"resonanceFireMajor",handler:(e,t,n)=>n.have("blistered")?[{type:"afflicted",affId:"burning"}]:[{type:"afflicted",affId:"blistered"}]},{skill:"elementalism",id:"resonanceWaterMinor",handler:()=>[{type:"afflicted",affId:"frostbite"}]},{skill:"elementalism",id:"resonanceWaterModerate",handler:()=>[{type:"afflicted",affId:"stuttering"}]},{skill:"elementalism",id:"resonanceWaterMajor",handler:()=>[{type:"afflicted",affId:"anorexia"}]}],vo=qs.get("occultist"),ko=e=>[{type:"confirmedCount",pool:[...vo.physicals],op:"=",n:e.args.physical},{type:"confirmedCount",pool:[...vo.mentals],op:"=",n:e.args.mental}],wo=e=>{const t=[{type:"confirmedCount",pool:[...vo.physicals,...vo.mentals],op:e.args.met?">=":"<",n:5}];return e.args.met&&t.push({type:"afflicted",affId:"enlightenment"}),t},Io=[{skill:"occultism",id:"ague",handler:(e,t,n)=>n.haveDef("insulation")?[{type:"defStripped",defId:"insulation"}]:[{type:"afflictedOneOf",pool:["shivering","frozen"],mode:"ordered"}]},{skill:"occultism",id:"instill",handler:(e,t,n)=>{const r=[{type:"statChanged",statId:"hp",delta:-.03},{type:"statChanged",statId:"mana",delta:-.03}],i=e.args.affs?.[0];return"sensitivity"===i?r.push(n.have("undeaf")?{type:"afflicted",affId:"sensitivity"}:{type:"afflicted",affId:"undeaf"}):i&&r.push({type:"afflicted",affId:i}),r}},{skill:"occultism",id:"enervate",handler:()=>[{type:"statChanged",statId:"mana",delta:-.2}]},{skill:"occultism",id:"attend",handler:()=>[{type:"afflicted",affId:"undeaf"},{type:"afflicted",affId:"unblind"}]},{skill:"occultism",id:"shrivelTargeted",handler:e=>e.args.affs?.[0]?[{type:"afflicted",affId:e.args.affs[0]}]:[]},{skill:"occultism",id:"shrivelArms",handler:()=>[{type:"afflictedOneOf",pool:["brokenrightarm","brokenleftarm"],mode:"firstMissing"}]},{skill:"occultism",id:"shrivelLegs",handler:()=>[{type:"afflictedOneOf",pool:["brokenrightleg","brokenleftleg"],mode:"firstMissing"}]},{skill:"occultism",id:"shrivelRehit",handler:e=>{return"arm"===(t=(e.args.groups?.limb??"").replace(/\s/g,"").toLowerCase())?[{type:"confirmed",affId:"brokenleftarm",present:!0},{type:"confirmed",affId:"brokenrightarm",present:!0}]:"leg"===t?[{type:"confirmed",affId:"brokenleftleg",present:!0},{type:"confirmed",affId:"brokenrightleg",present:!0}]:[{type:"confirmed",affId:`broken${t}`,present:!0}];var t}},{skill:"occultism",id:"unnamableSpeak",handler:()=>[]},{skill:"occultism",id:"unnamableVision",handler:()=>[]},{skill:"occultism",id:"regress",handler:()=>[{type:"afflicted",affId:"prone"}]},{skill:"occultism",id:"devolve",handler:()=>[{type:"afflicted",affId:"shyness"},{type:"afflicted",affId:"disloyalty"}]},{skill:"occultism",id:"whisperingmadness",handler:()=>[{type:"afflicted",affId:"whisperingmadness"}]},{skill:"occultism",id:"whisperingmadnessMiss",handler:()=>vo.whisperingmadness.map(e=>({type:"removed",affId:e}))},{skill:"occultism",id:"cleanseaura",handler:(e,t)=>t.checkBlock("A look of sudden concern")?[{type:"afflicted",affId:"cleanseaura"}]:[{type:"removed",affId:"cleanseaura"}]}],zo=qs.get("psion"),_o=(e,t)=>e.args[t]??e.args.match?.groups?.[t],Oo=[{skill:"psionics",id:"splinterHit",handler:()=>[{type:"defStripped",defId:"shield"}]},{skill:"psionics",id:"splinterMiss",handler:()=>[{type:"defStripped",defId:"shield"}]},{skill:"psionics",id:"expand",handler:()=>[{type:"statChanged",statId:"mana",delta:.15}]},{skill:"psionics",id:"combustion",handler:()=>[{type:"afflicted",affId:"bloodfire"}]},{skill:"psionics",id:"blastMiss",handler:()=>[{type:"confirmedCount",pool:[...zo.blast],op:"<",n:3}]},{skill:"weaving",id:"invert",handler:e=>{const t=_o(e,"old"),n=_o(e,"new");return t&&n?[{type:"converted",from:`unweaving${t}`,to:`unweaving${n}`}]:[]}}],$o=qs.get("depthswalker"),So=["depression","retribution","shadowmadness","parasite"],No=e=>()=>[{type:"afflictedOneOf",pool:[...e],mode:"ordered"}],xo=e=>()=>e.map(e=>({type:"confirmed",affId:e,present:!0})),jo=e=>{const t=e.skillState.envenom;if(!t)return[];const n=Ls.get(t),r=[{type:"updateSkillState",patch:{envenom:null}}];return n&&r.unshift({type:"afflicted",affId:n}),r},Mo=[{skill:"shadowmancy",id:"reap",handler:(e,t,n)=>t.checkBlock("you corrupt the weapon's timestream.")?[]:jo(n)},{skill:"shadowmancy",id:"cull",handler:(e,t,n)=>jo(n)},{skill:"shadowmancy",id:"degeneration",handler:No($o.degeneration)},{skill:"shadowmancy",id:"degenerationFull",handler:xo($o.degeneration)},{skill:"shadowmancy",id:"depression",handler:No($o.depression)},{skill:"shadowmancy",id:"depressionFull",handler:()=>[...xo($o.depression)(),{type:"afflicted",affId:"anorexia"},{type:"afflicted",affId:"masochism"}]},{skill:"shadowmancy",id:"retribution",handler:No($o.retribution)},{skill:"shadowmancy",id:"retributionFull",handler:(e,t,n)=>{const r=So.reduce((e,t)=>e+n.probability(t),0);return[...xo($o.retribution)(),{type:"afflicted",affId:"anorexia"},{type:"afflicted",affId:"masochism"},{type:"statChanged",statId:"mana",delta:-.05*r}]}},{skill:"shadowmancy",id:"madness",handler:No($o.madness)},{skill:"shadowmancy",id:"madnessFull",handler:xo($o.madness)},{skill:"shadowmancy",id:"leach",handler:No($o.leach)},{skill:"shadowmancy",id:"leachFull",handler:xo($o.leach)},{skill:"shadowmancy",id:"consume",handler:()=>[{type:"statChanged",statId:"mana",delta:-.1}]},{skill:"shadowmancy",id:"mutilate",handler:()=>[{type:"statChanged",statId:"mana",delta:-.4},{type:"statChanged",statId:"hp",delta:-.4}]}],To=qs.get("occultist"),Ao=To.moon.filter(e=>"claustrophobia"!==e&&"agoraphobia"!==e),Eo=[{skill:"tarot",id:"magician",handler:()=>[{type:"statChanged",statId:"mana",delta:.25}]},{skill:"tarot",id:"priestess",handler:()=>[{type:"statChanged",statId:"hp",delta:.25}]},{skill:"tarot",id:"lovers",handler:()=>[{type:"afflicted",affId:"lovers"}]},{skill:"tarot",id:"aeon",handler:()=>[{type:"defStripped",defId:"speed"},{type:"afflicted",affId:"aeon"}]},{skill:"tarot",id:"aeonStrip",handler:()=>[{type:"defStripped",defId:"speed"}]},{skill:"tarot",id:"justice",handler:()=>[{type:"afflicted",affId:"justice"}]},{skill:"tarot",id:"deathRub",handler:(e,t,n)=>n.haveDef("insulation")?[{type:"defStripped",defId:"insulation"}]:[{type:"afflicted",affId:"shivering"}]},{skill:"tarot",id:"ruinateLovers",handler:()=>[{type:"afflicted",affId:"manaleech"}]},{skill:"tarot",id:"ruinateJustice",handler:(e,t)=>t.nextLine("violently spasms")?[]:To.justice.map(e=>({type:"confirmed",affId:e,present:!1}))},{skill:"tarot",id:"moon",handler:(e,t)=>{const n=t.queuedCommand(),r=n?n.match(/FLING MOON AT \w+ (\w+)/):null;return r?[{type:"afflicted",affId:r[1].toLowerCase()}]:[{type:"afflictedOneOf",pool:[...Ao],mode:"firstMissing"}]}}],Co=/^(\w+) stumbles, falling to the ground\.$/,Po=[{skill:"weaving",id:"cleaveHit",handler:()=>[{type:"afflicted",affId:"prone"},{type:"defStripped",defId:"shield"}]},{skill:"weaving",id:"cleaveMiss",handler:()=>[{type:"defStripped",defId:"shield"}]},{skill:"weaving",id:"overhand",handler:(e,t,n)=>n.have("prone")||n.limbPercent("head")>=87.6?[{type:"afflicted",affId:"impatience"}]:[{type:"afflicted",affId:"stupidity"},{type:"afflicted",affId:"prone"}]},{skill:"weaving",id:"hamstring",handler:(e,t)=>{const n=(e=>(e??"").replace(/\s/g,"").toLowerCase())(e.args.limb),r=[{type:"afflicted",affId:`broken${n}`}];return"thirdPerson"===e.matchType&&r.push(t.checkBlock(Co)?{type:"limbAdvance",limbId:n}:{type:"limbHit",limbId:n,percent:22.1}),r}},{skill:"weaving",id:"entwineProne",handler:()=>[{type:"afflicted",affId:"prone"}]},{skill:"weaving",id:"entwineEntangle",handler:()=>[{type:"afflicted",affId:"entangled"}]},{skill:"weaving",id:"puncture",handler:()=>[{type:"afflicted",affId:"weariness"}]},{skill:"weaving",id:"sever",handler:()=>[{type:"afflicted",affId:"clumsiness"}]},{skill:"weaving",id:"unweave",handler:e=>e.args.info?[{type:"afflicted",affId:`unweaving${e.args.info}`}]:[]},{skill:"weaving",id:"deathblow",handler:()=>[{type:"afflicted",affId:"asthma"}]},{skill:"weaving",id:"backhand",handler:()=>[{type:"afflicted",affId:"stupidity"},{type:"afflicted",affId:"dizziness"}]},{skill:"weaving",id:"exsanguinate",handler:()=>[{type:"afflicted",affId:"nausea"}]},{skill:"weaving",id:"disruption",handler:()=>[{type:"afflicted",affId:"paralysis"}]},{skill:"weaving",id:"disruption2",handler:()=>[{type:"afflicted",affId:"paralysis"}]},{skill:"weaving",id:"laceration",handler:()=>[{type:"afflicted",affId:"haemophilia"}]},{skill:"weaving",id:"laceration2",handler:()=>[{type:"afflicted",affId:"haemophilia"}]},{skill:"weaving",id:"dazzle",handler:()=>[{type:"afflicted",affId:"clumsiness"}]},{skill:"weaving",id:"rattle",handler:()=>[{type:"afflicted",affId:"epilepsy"}]},{skill:"weaving",id:"vapours",handler:()=>[{type:"afflicted",affId:"asthma"}]}],Ro=e=>String(e).toLowerCase(),Zo=(e,t)=>`${Ro(e)}.${String(t).toLowerCase()}`,Do=Object.freeze([...Xa,{skill:"artificing",id:"efreeti",handler:()=>[{type:"afflicted",affId:"burning"}]},{skill:"artificing",id:"stoneback",handler:()=>[{type:"defRaised",defId:"shield"}]},...ro,...oo,...po,...ho,...bo,...Io,...Oo,...Mo,...Eo,...Po]),Fo=(e,t,n)=>({id:`affConfirms.${e}`,pattern:n,lifetime:"session",actor:1,handler:()=>[{type:"confirmed",affId:t,present:!0}]}),Lo=[Fo("agoraphobia","agoraphobia",/^(\w+) is gripped with fear, staring out with terrified eyes\.$/),Fo("claustrophobia","claustrophobia",/^(\w+) begins to pant in terror\.$/),Fo("confusion","confusion",/^(\w+) looks about bemusedly\.$/),Fo("darkshade","darkshade",/^(\w+) lets out a piercing scream, as if wounded by the very sunlight\.$/),Fo("dementia","dementia",/^(\w+) stares about \w+ frenziedly, wild-eyed\.$/),Fo("epilepsy","epilepsy",/^(\w+) begins to jerk and shake violently, foaming at the mouth\.$/),{id:"affConfirms.hallucinations",pattern:/^(\w+) leaps up in what is apparently an attempt at a graceful swan dive\. \w+ smacks headfirst into the ground\.$/,lifetime:"session",actor:1,handler:()=>[{type:"confirmed",affId:"hallucinations",present:!0},{type:"afflicted",affId:"prone"}]},Fo("hypersomnia","hypersomnia",/^(\w+) suddenly appears tired all of a sudden\.$/),Fo("impatience","impatience",/^(\w+) shuffles \w+ feet in boredom\.$/),Fo("masochism1","masochism",/^(\w+) smiles as \w+ rams \w+ fist into \w+ jaw\.$/),Fo("masochism2","masochism",/^(\w+) uses \w+ right foot to stomp on \w+ left as hard as possible\.$/),Fo("masochism3","masochism",/^With the heel of \w+ palm, (\w+) smacks \w+ upside the head\.$/),Fo("nausea","nausea",/^(\w+) doubles over, vomiting violently\.$/),Fo("paralysis1","paralysis",/^Horror overcomes the face of (\w+?) as \w+ body locks in paralysis\.$/),Fo("paralysis2","paralysis",/^Horror overcomes (\w+)'s face as \w+ body stiffens into paralysis\.$/),Fo("shyness","shyness",/^(\w+) trembles with fear\.$/),{id:"affConfirms.sleep",pattern:/^(\w+)'s eyes close suddenly as \w+ falls asleep\.$/,lifetime:"session",actor:1,handler:()=>[{type:"afflicted",affId:"prone"}]},Fo("shivering","shivering",/^(\w+) shivers particularly intensely\.$/),Fo("burning","burning",/^The fires consuming (\w+) diminish somewhat\.$/)],qo=(e,t,n)=>({id:`classCures.${e}`,pattern:n,lifetime:"session",actor:1,handler:()=>[{type:"cured",cureId:t}]}),Bo=[qo("sunTarot","dagaz",/^The globe of light illuminates (\w+) with its brilliance\.$/),qo("runewardenSun","dagaz",/^A rune like a rising sun upon the ground flares, bathing (\w+) with healing magic\.$/),qo("genericMist","generic",/^(\w+) is surrounded in a cool, refreshing mist\.$/),qo("genericGlow","generic",/^A demonic crimson glow emanates from (\w+)\.$/),qo("genericLeech","generic",/^Something pulses from within the chest of (\w+), and \w+ seems more vital\.$/)],Go=(e,t,n)=>({id:`cureConfirms.${e}`,pattern:n,lifetime:"session",actor:1,handler:()=>[{type:"confirmed",affId:t,present:!1}]}),Jo=[{id:"cureConfirms.stand",pattern:/^(\w+) stands up\.$/,lifetime:"session",actor:1,handler:()=>[{type:"cured",cureId:"stand"}]},Go("lovers","lovers",/^(\w+) shakes \w+ head and a look of clarity returns to \w+ eyes\.$/),Go("whisperingmadness","whisperingmadness",/^(\w+) ceases \w+ violent trembling\.$/),{id:"cureConfirms.slimeLost",pattern:/^(\w+) finally rids \w+ of the slime covering \w+\.$/,lifetime:"session",actor:1,handler:()=>[{type:"removed",affId:"slimeobscure"}]},Go("sileris","slickness",/^(\w+) applies a (?:quicksilver droplet|sileris berry) to \w+\.$/),Go("shadowmadness","shadowmadness",/^Lucidity returns to the eyes of (\w+)\.$/),Go("unweavingspirit","unweavingspirit",/^(\w+) seems suddenly unburdened, clarity reasserting itself upon \w+ features\.$/),Go("unweavingmind","unweavingmind",/^The light behind the eyes of (\w+) reignites\.$/),Go("unweavingbody","unweavingbody",/^(\w+) suddenly seems much more vital\.$/),Go("bloodfire","bloodfire",/^The unnatural flames that burn upon the skin of (\w+) wink out\.$/)],Uo=(e,t)=>({id:`curatives.${e}`,pattern:t,lifetime:"session",actor:1,handler:()=>[{type:"cured",cureId:e}]}),Ho=[Uo("antimony",/^(\w+) eats (?:a ginger root|an antimony flake)\.$/),Uo("argentum",/^(\w+) eats (?:a lobelia seed|an argentum flake)\.$/),Uo("arsenic",/^(\w+) eats (?:some bayberry bark|an arsenic pellet)\.$/),Uo("aurum",/^(\w+) eats (?:a piece of kelp|an aurum flake)\.$/),Uo("cuprum",/^(\w+) eats a (?:bellwort flower|cuprum flake)\.$/),Uo("ferrum",/^(\w+) eats a (?:ginseng root|ferrum flake)\.$/),Uo("magnesium",/^(\w+) eats a (?:bloodroot leaf|magnesium chip)\.$/),Uo("plumbum",/^(\w+) eats a (?:goldenseal root|plumbum flake)\.$/),Uo("stannum",/^(\w+) eats (?:some prickly ash bark|a stannum flake)\.$/),{id:"curatives.calamine",pattern:/^(\w+) eats a (?:hawthorn berry|calamine crystal)\.$/,lifetime:"session",actor:1,handler:()=>[{type:"removed",affId:"undeaf"}]},{id:"curatives.potash",pattern:/^(\w+) eats (?:some irid moss|a potash crystal)\.$/,lifetime:"session",actor:1,handler:()=>[{type:"cured",cureId:"potash"},{type:"statChanged",statId:"hp",delta:.08},{type:"statChanged",statId:"mana",delta:.08}]},{id:"curatives.restore",pattern:/^(\w+) crackles with blue energy that wreathes itself about \w+ limbs\.$/,lifetime:"session",actor:1,handler:()=>[{type:"removed",affId:"brokenrightarm"},{type:"removed",affId:"brokenrightleg"},{type:"removed",affId:"brokenleftarm"},{type:"removed",affId:"brokenleftleg"}]}],Vo=(e,t,n)=>({id:`defences.${e}`,pattern:t,lifetime:"session",actor:1,handler:n}),Yo=[Vo("shieldHit1",/^A dizzying beam of energy strikes you as your attack rebounds off of (\w+)'s shield\.$/,()=>[{type:"defRaised",defId:"shield"}]),Vo("shieldHit2",/^The magical shield surrounding (\w+) makes that impossible\.$/,()=>[{type:"defRaised",defId:"shield"}]),Vo("sileris",/^A supple purple shell of sileris berry juice has formed around (\w+)\.$/,()=>[{type:"defRaised",defId:"fangbarrier"}]),Vo("silerisLost",/^The protective coating covering the skin of (\w+) sloughs off\.$/,()=>[{type:"afflicted",affId:"slickness"},{type:"defStripped",defId:"fangbarrier"}]),Vo("insomnia",/^(\w+) clenches \w+ fists and grits \w+ teeth\.$/,()=>[{type:"defRaised",defId:"insomnia"}]),Vo("prismaticHit",/^Your attack is repelled by the prismatic barrier surrounding (\w+)\.$/,()=>[{type:"defRaised",defId:"prismatic"}]),Vo("prismaticLost",/^(\w+)'s prismatic barrier dissolves into nothing\.$/,()=>[{type:"defStripped",defId:"prismatic"}]),Vo("speedStripped",/^(\w+) suddenly seems less dexterous, \w+ reactions becoming noticeably slower\.$/,()=>[{type:"defStripped",defId:"speed"}])],Wo=e=>(e??"").replace(/\s/g,"").toLowerCase(),Ko=(e,t)=>Number(`${e}.${t}`),Qo=[{id:"prep.limbDamage",pattern:/^As you carve into (\w+), you perceive that you have dealt (\d+)\.(\d+)% damage to \w+ (.+)\.$/,lifetime:"session",actor:1,handler:e=>[{type:"limbHit",limbId:Wo(e[4]),percent:Ko(e[2],e[3])}]},{id:"prep.limbDamage2",pattern:/^As your blow lands with a crunch, you perceive that you have dealt (\d+)\.(\d+)% damage to (\w+)'s (.+)\.$/,lifetime:"session",actor:3,handler:e=>[{type:"limbHit",limbId:Wo(e[4]),percent:Ko(e[1],e[2])}]},{id:"prep.interlinkDamage",pattern:/^As the immaterial cleaves the material, you perceive that you have dealt (\d+)\.(\d+)% damage to (\w+)'s (.+)\.$/,lifetime:"session",actor:3,handler:e=>[{type:"limbHit",limbId:Wo(e[4]),percent:Ko(e[1],e[2])}]},{id:"prep.limbReset",pattern:/^(\w+) ceases to favour \w+ (.+)\.$/,lifetime:"session",actor:1,handler:e=>[{type:"limbReset",limbId:Wo(e[2])}]},{id:"prep.limbMangle",pattern:/^(\w+)'s ((?:left|right) (?:arm|leg)) has been beaten into uselessness\.$/,lifetime:"session",actor:1,handler:e=>[{type:"limbAdvance",limbId:Wo(e[2])}]},{id:"prep.calcifiedskullResolve",pattern:/^A look of pain comes over (\w+) and the bones seem to shift beneath the skin stretched across \w+ skull\.$/,lifetime:"session",actor:1,handler:()=>[{type:"converted",from:"calcifiedskull",to:"damagedhead"}]}],Xo=[{defId:"insomnia",pattern:/^\w+ has insomnia, and cannot easily go to sleep\.$/},{defId:"speed",pattern:/^\w+ sense of time is heightened, and \w+ reactions are speeded\.$/},{defId:"kola",pattern:/^\w+ is feeling extremely energetic\.$/},{defId:"cloak",pattern:/^\w+ is surrounded by a cloak of protection\.$/},{defId:"insulation",pattern:/^\w+ is coated in an insulating unguent\.$/},{defId:"fangbarrier",pattern:/^\w+ is protected from the fangs of serpents\.$/},{defId:"rebounding",pattern:/^\w+ is protected from hand-held weapons with an aura of rebounding\.$/},{defId:"curseward",pattern:/^A curseward has been established about \w+ person\.$/},{defId:"selfishness",pattern:/^\w+ is feeling quite selfish\.$/},{defId:"shield",pattern:/^\w+ is surrounded by a nearly invisible magical shield\.$/}],ed={id:"occultism.readaura",lifetime:"prompt",armedBy:{trigger:"skills.readauraStart"},initState:({actorId:e})=>({actorId:e,pendingDefs:Xo.map(({defId:e})=>e)}),captures:[...Xo.map(({defId:e,pattern:t})=>({id:`def.${e}`,pattern:t,actor:"armed",handler:(t,n,r,i)=>(i.pendingDefs=i.pendingDefs.filter(t=>t!==e),[{type:"defRaised",defId:e}])})),{id:"deaf",pattern:/^\w+ is deaf\.$/,actor:"armed",handler:()=>[{type:"removed",affId:"undeaf"}]},{id:"blind",pattern:/^\w+ is blind\.$/,actor:"armed",handler:()=>[{type:"removed",affId:"unblind"}]},{id:"counts",pattern:/^You perceive that (\w+) suffers from (\d+) physical afflictions and (\d+) mental afflictions\.$/,actor:1,handler:(e,t,n)=>ko({args:{physical:Number(e[2]),mental:Number(e[3])}},t,n)},{id:"mana",pattern:/^You sense that the mana of (\w+) stands at (\d+) of a maximum (\d+)\.$/,actor:1,handler:(e,t,n,r)=>{const i=r.pendingDefs.map(e=>({type:"defStripped",defId:e}));return r.pendingDefs=[],i.push({type:"statObserved",statId:"mana",value:Number(e[2])/Number(e[3])}),i}}]},td=["paralysis","asthma","healthleech","haemophilia","sensitivity","clumsiness","weariness"],nd={indigo:()=>[{type:"afflicted",affId:"stupidity"}],orange:()=>[{type:"afflicted",affId:"paralysis"}],violet:e=>e.haveDef("speed")?[{type:"defStripped",defId:"speed"}]:[{type:"afflicted",affId:"aeon"}]},rd=e=>e.haveDef("insulation")?[{type:"defStripped",defId:"insulation"}]:[{type:"afflictedOneOf",pool:["shivering","frozen"],mode:"ordered"}],id=[{id:"skills.earworm",pattern:/^Your rapier sings out with a high, piercing note\.$/,lifetime:"session",actor:null,handler:()=>[{type:"confirmed",affId:"earworm",present:!0}]},{id:"skills.commandMinionMiss",pattern:/^A minion of chaos thrusts a hand in the direction of (\w+), but nothing seems to happen\.$/,lifetime:"session",actor:1,handler:()=>[{type:"confirmed",affId:"enlightenment",present:!1}]},{id:"skills.firelordPrimebond",pattern:/^(\w+) cries out in horror as \w+ body erupts into flames!$/,lifetime:"session",actor:1,handler:()=>[{type:"afflicted",affId:"burning"}]},{id:"skills.rendVenom",pattern:/^You rub some (\w+) on your wickedly sharp claws\.$/,lifetime:"session",actor:"tracked",handler:e=>[{type:"updateSkillState",patch:{envenom:e[1].toLowerCase()}}]},{id:"skills.dragoncurseAff",pattern:/^You summon your ancient power and direct the curse of (\w+) to strike down (\w+) in (\d+) seconds\.$/,lifetime:"session",actor:2,handler:e=>[{type:"updateSkillState",patch:{dragoncurse:e[1].toLowerCase()}}]},{id:"skills.dragoncurseHit",pattern:/^(\w+) convulses under the influence of some invisible force\.$/,lifetime:"session",actor:1,handler:(e,t,n)=>{const r=n.skillState.dragoncurse;if(!r)return[];const i=[{type:"updateSkillState",patch:{dragoncurse:null}}];return Ts.has(r)&&i.unshift({type:"afflicted",affId:r}),i}},{id:"skills.readauraStart",pattern:/^Studying the aura of (\w+), you look for traces of anything that may be protecting it\.$/,lifetime:"session",actor:1,handler:()=>[]},{id:"skills.whisperingmadnessTick",pattern:/^(\w+) trembles and \w+ eyes widen in terror\. \w+ looks around \w+ as if searching for something that isn't there\.$/,lifetime:"session",actor:1,handler:()=>[{type:"confirmed",affId:"whisperingmadness",present:!0}]},{id:"skills.chaosrays",pattern:/^(\w+) is hit by a (.+) ray\.$/,lifetime:"session",actor:1,handler:(e,t,n)=>e[2].replace(/ and /g,",").replace(/\s/g,"").replace(/,,/g,",").split(",").filter(Boolean).flatMap(e=>nd[e]?.(n)??[])},{id:"skills.truename",pattern:/^Drawing back with a knowing smirk, you utter the truename of (\w+), who suddenly becomes very still and bleeds from \w+ eyes and ears\.$/,lifetime:"session",actor:1,handler:()=>[{type:"defStripped",defId:"speed"},{type:"afflicted",affId:"aeon"}]},{id:"skills.unnamableHits",pattern:/^(\w+) has been struck down by (\d) curses of the unnamable\.$/,lifetime:"session",actor:1,handler:e=>Array.from({length:Number(e[2])},()=>({type:"afflictedOneOf",pool:["confusion","stupidity","dementia"],mode:"firstMissing"}))},{id:"skills.enlighten",pattern:/^You place both hands on either side of (\w+)'s head and stare straight into \w+ eyes\. Summoning all your knowledge of the occult mysteries, you will your knowledge into \w+'s mind\.$/,lifetime:"session",actor:1,handler:(e,t,n)=>wo({args:{met:t.nextLine("You see")}},t,n)},{id:"skills.enlightenYell",pattern:/^You see (.+) yell, "No, it cannot be true! I cannot accept it! I beg of you to make it stop!"$/,lifetime:"session",actor:1,handler:(e,t,n)=>wo({args:{met:!0}},t,n)},{id:"skills.enlightenShout",pattern:/^You see (.+) shout, "No, it cannot be true! I cannot accept it! I beg of you to make it stop!"$/,lifetime:"session",actor:1,handler:(e,t,n)=>wo({args:{met:!0}},t,n)},{id:"skills.regressAnorexia",pattern:/^The face of (\w+) turns a particularly vibrant shade of green\.$/,lifetime:"session",actor:1,handler:()=>[{type:"afflicted",affId:"anorexia"},{type:"confirmed",affId:"prone",present:!0}]},{id:"skills.compelDiscord",pattern:/^(\w+) clutches at \w+ head as \w+ begins to mutter gibberish over and over under his breath\.$/,lifetime:"session",actor:1,handler:()=>[{type:"confirmed",affId:"healthleech",present:!0},{type:"confirmed",affId:"asthma",present:!0},{type:"afflicted",affId:"loneliness"},{type:"afflicted",affId:"dizziness"}]},{id:"skills.compelEntropyAeon",pattern:/^(\w+) twists and writhes in the grip of an unnatural force, parts of \w+ body flickering as if seen through a veil of mist\.$/,lifetime:"session",actor:1,handler:()=>[{type:"defStripped",defId:"speed"},{type:"afflicted",affId:"aeon"}]},{id:"skills.compelPotentialLimbs",pattern:/^The body of (\w+) goes slack, \w+ eyes rolling almost completely back in \w+ head as \w+ face goes a ghostly white\.$/,lifetime:"session",actor:1,handler:(e,t,n)=>["leftarm","leftleg","rightarm","rightleg"].flatMap(e=>{for(const t of["mangled","damaged","broken"])if(n.probability(`${t}${e}`)>.25)return[{type:"confirmed",affId:`${t}${e}`,present:!0}];return[]})},{id:"skills.compelPotentialFrozen",pattern:/^(\w+) twitches in the grip of some terrible power, skin splitting and cracking under its unforgiving grasp\.$/,lifetime:"session",actor:1,handler:()=>[{type:"confirmed",affId:"shivering",present:!0},{type:"confirmed",affId:"frozen",present:!0},{type:"defStripped",defId:"insulation"}]},{id:"skills.shadowInstill",pattern:/^Focusing upon .+?, you instill it with the directive of (\w+)\.$/,lifetime:"session",actor:"tracked",handler:e=>[{type:"updateSkillState",patch:{shadowInstill:e[1].toLowerCase()}}]},{id:"skills.shadowEnvenom",pattern:/^You rub some (\w+) on .+?\.$/,lifetime:"session",actor:"tracked",handler:e=>[{type:"updateSkillState",patch:{envenom:e[1].toLowerCase()}}]},{id:"skills.attuneMadness",pattern:/^You sense that (\w+) has been struck down with the (\w+) madness\.$/,lifetime:"session",actor:1,handler:e=>{const t=e[2].toLowerCase(),n=Ts.has(t)?t:`${t}madness`;return Ts.has(n)?[{type:"afflicted",affId:n}]:[]}},{id:"skills.attuneDegeneration",pattern:/^You determine that (\w+) is suffering from (\w+)\.$/,lifetime:"session",actor:1,handler:e=>{const t=e[2].toLowerCase();return Ts.has(t)?[{type:"afflicted",affId:t}]:[]}},{id:"skills.shadowstrikeMiss",pattern:/^(\w+) is not surrounded by a magical shield\.$/,lifetime:"session",actor:1,handler:()=>[{type:"defStripped",defId:"shield"}]},{id:"skills.ruinateJusticeBreak",pattern:/^An audible crack emanates from the bones in the (.+) of (\w+)\.$/,lifetime:"session",actor:2,handler:(e,t,n)=>{const r=(i=e[1],i.replace(/ and /g,",").replace(/,,/g,",").replace(/\s/g,"").split(",").filter(Boolean)).map(e=>({type:"afflicted",affId:`broken${e}`}));var i;return td.reduce((e,t)=>e+n.probability(t),0)>=4&&(r.push(...rd(n)),r.push({type:"afflictedOneOf",pool:["shivering","frozen"],mode:"ordered"})),r}},{id:"skills.ruinateJusticeProne",pattern:/^The broken legs of (\w+) give way, and \w+ collapses to the ground\.$/,lifetime:"session",actor:1,handler:()=>[{type:"afflicted",affId:"prone"},{type:"confirmed",affId:"brokenleftleg",present:!0},{type:"confirmed",affId:"brokenrightleg",present:!0}]},{id:"skills.wheelAgue",pattern:/^Rays of cold blue light lash out from the Wheel of Chaos, irradiating the location\.$/,lifetime:"session",actor:"room",handler:(e,t,n)=>rd(n)},{id:"skills.wheelStuttering",pattern:/^Vibrant indigo rays of light lash out from the Wheel of Chaos\.$/,lifetime:"session",actor:"room",handler:()=>[{type:"afflicted",affId:"stuttering"}]},{id:"skills.wheelBlackout",pattern:/^Rays of orange light lash out at the location from the Wheel of Chaos\.$/,lifetime:"session",actor:"room",handler:()=>[{type:"afflicted",affId:"blackout",durationMs:3e3}]},{id:"skills.stumbleProne",pattern:/^(\w+) stumbles, falling to the ground\.$/,lifetime:"session",actor:1,handler:()=>[{type:"afflicted",affId:"prone"}]},{id:"skills.erodeDefence",pattern:/^(?:His|Her|Faen) (\w+) defence is eroded away\.$/,lifetime:"session",actor:null,handler:e=>[{type:"defStripped",defId:e[1].toLowerCase()}]},{id:"skills.scintillaBurn",pattern:/^Flames ignite all over the body of (\w+), fanned to intensity in an instant\.$/,lifetime:"session",actor:1,handler:()=>[{type:"afflicted",affId:"burning"}]},{id:"skills.conflagrateFail",pattern:/^You bend your will upon (\w+), attempting to rouse a conflagration to consume \w+, but to no avail\.$/,lifetime:"session",actor:1,handler:()=>[{type:"confirmedLevel",affId:"burning",op:"<",n:2}]},{id:"skills.assess",pattern:/^You glance over (\w+) and see that \w+ health is at (\d+)\/(\d+)\.$/,lifetime:"session",actor:1,handler:e=>[{type:"statObserved",statId:"hp",value:Number(e[2])/Number(e[3])}]},{id:"skills.contemplate",pattern:/^(\w+)'s mana stands at (\d+)\/(\d+)\.$/,lifetime:"session",actor:1,handler:e=>[{type:"statObserved",statId:"mana",value:Number(e[2])/Number(e[3])}]}],sd=/^(\w+) pales as the blood drains from \w+ face\.$/,ad=(e,t,n)=>({id:e,lifetime:"prompt",armedBy:{skill:"occultism",id:t},initState:({observedIds:e})=>({exposed:[...e]}),captures:[{id:"pale",pattern:sd,actor:1,handler:(e,t,r,i)=>(i.exposed=i.exposed.filter(e=>e!==r.id),[{type:"afflicted",affId:n}])}],finalize:e=>e.exposed.map(e=>({id:e,type:"removed",affId:n}))}),od=ad("occultism.unnamableSpeak","unnamableSpeak","undeaf"),dd=ad("occultism.unnamableVision","unnamableVision","unblind"),ld=Object.freeze([...Ho,...Bo,...Jo,...Lo,...Yo,...id,...Qo,{id:"queues.queueTracker",pattern:/^\[System\]: Running queued (.+?) command: (.+)/,lifetime:"session",remember:e=>({queue:{name:e[1],text:e[2]}})}]),cd=Object.freeze([od,dd,ed]),fd=(e,t)=>t instanceof RegExp?t.test(e):"string"==typeof t&&e.includes(t),ud=(e,t)=>{const n=[e?.target,e?.target?.id,e?.victim,e?.player,e?.player?.id,e?.user];for(const r of n)if("string"==typeof r&&""!==r&&"self"!==r.toLowerCase()){const e=Ha(r);if(e&&e!==t)return e}return null},pd=e=>"string"==typeof e?e:"string"==typeof e?.name?e.name:null,hd=({adapter:e,publish:t,commandMemory:n=null,skills:r=null})=>{const i=[],s=new Map;let a=!1;const o=()=>Ha(pd(e.gmcp.read("Char.Name"))),d=(t=null)=>(({lines:e=[],currentLineIndex:t=-1,actorId:n=null,timestampMs:r=0,commands:i=null}={})=>{const s=Object.freeze(e.map(e=>Object.freeze({text:"string"==typeof e.text?e.text:null,isPrompt:!0===e.isPrompt,isHtml:!0===e.isHtml}))),a=Object.freeze({queues:Object.freeze({...i?.queues??{}}),lastQueue:i?.lastQueue??null});return Object.freeze({lines:s,currentLineIndex:t,actorId:n,timestampMs:r,commands:a,nextLine:e=>{for(let n=t+1;n<s.length;n+=1){const t=s[n];if(!t.isHtml&&!t.isPrompt&&null!==t.text)return fd(t.text,e)}return!1},checkBlock:e=>s.some(t=>null!==t.text&&fd(t.text,e)),queuedCommand:e=>{const t=e??a.lastQueue;return null===t?null:a.queues[t]??null}})})({...e.text.snapshot(),actorId:Ha(t),timestampMs:e.clock.now(),commands:n?n.snapshot():null}),l=e=>{const n=Ha(pd(e));n&&n!==o()&&t("insight.ingress.room.entered",{id:n})},c=e=>{const n=(e=>{const{skill:t,id:n,matchType:r,match:i,...s}=e??{};return"string"!=typeof t||""===t||"string"!=typeof n||""===n?null:{skill:t,id:n,matchType:r??i,args:s}})(e);n&&"secondPerson"!==n.matchType&&t("insight.ingress.skill",{action:n,context:d(ud(e,o()))})},f=t=>{if(a)for(const n of t){if("string"!=typeof n||""===n)continue;const t=Ro(n);s.has(t)||s.set(t,e.events.onSkillMatch(c,t))}};return Object.freeze({start(){a=!0,r?f(r()):i.push(e.events.onSkillMatch(c)),i.push(e.events.on("nexskill.error.reaction",e=>{const n=e?.action,i="string"==typeof n?.skill&&""!==n.skill?Ro(n.skill):null;r&&!s.has(i)||t("insight.ingress.skillError",{skill:i,id:"string"==typeof n?.id&&""!==n.id?n.id:null,line:"string"==typeof n?.originalLine?n.originalLine:null,message:e?.error?.message??String(e?.error)})})),i.push(e.events.on("IRE.Target.Set",e=>{"number"!=typeof e&&t("insight.ingress.target",{id:"string"==typeof e?e:null})})),i.push(e.events.on("Room.AddPlayer",l)),i.push(e.events.on("Room.RemovePlayer",e=>{const n=Ha(pd(e));n&&n!==o()&&t("insight.ingress.room.left",{id:n})})),i.push(e.events.on("Room.Info",()=>{const n=e.gmcp.read("RoomPlayers"),r=o();t("insight.ingress.room.list",{ids:(Array.isArray(n)?n:[]).map(e=>Ha(pd(e))).filter(e=>null!==e&&e!==r)})})),i.push(e.events.on("PromptEvent",()=>{t("insight.ingress.prompt",{})}))},observeSkills:f,stop(){for(a=!1;i.length>0;)i.pop()();for(const e of s.values())e();s.clear()},capture:d})},md=new Set(["afflicted","afflictedOneOf","cured","confirmed","confirmedBlocked","confirmedCount","confirmedLevel","converted","removed"]),gd=e=>Math.min(1,Math.max(0,e)),yd=({roster:e,tables:t,publish:n,notice:r,advanceToNow:i})=>{const s=new Map,a=new Set,o=(e,t)=>{((e,t,i)=>{i.contradiction&&n("insight.belief.contradiction",{id:e,event:t});for(const s of i.diagnostics)"forkCapExceeded"===s.type&&(n("insight.belief.growthCapped",{id:e,event:s.eventType??t.type,beforeCount:s.beforeCount,afterCount:s.afterCount,forkCap:s.forkCap}),r({text:`fork cap hit for ${e} — ${s.beforeCount} → ${s.afterCount} forks (cap ${s.forkCap}) on '${t.type}'. Belief detail was discarded; this is a red-flag condition.`,severity:"error"}))})(e.id,t,e.apply(t))},d=t=>{const n=Ha(t)??e.targetId;return n?e.track(n):null},l=e=>(i(e.id),c(e)),c=e=>({id:e.id,class:e.class,have:t=>ha(e.belief,t)>0,probability:t=>ha(e.belief,t),isBalanceReady:t=>e.isBalanceReady(t),haveDef:t=>e.haveDef(t),limbPercent:t=>e.limbPercent(t),limbStages:t=>e.limbStages(t),skillState:e.getSkillState()}),f=(e,t)=>{switch(t.type){case"defRaised":return e.setDef(t.defId,!0),!0;case"defStripped":return e.setDef(t.defId,!1),!0;case"statObserved":return e.setStat(t.statId,gd(t.value)),!0;case"statChanged":{const n=e.getStat(t.statId);return n&&e.setStat(t.statId,gd(n.value+t.delta)),!0}case"limbHit":return 1===e.limbStages(t.limbId).mangled||e.hitLimb(t.limbId,t.percent).advanced&&p(e,t),!0;case"limbReset":return e.resetLimb(t.limbId),!0;case"updateSkillState":return e.updateSkillState(t.patch),!0;case"classObserved":return e.setClass(t.class),!0;default:return!1}},u=(e,r,i)=>{const s=t.cureById.get(r.cureId);if(!s)return;if(!s.bals_req.every(t=>e.isBalanceReady(t)))return;(i?Ha(i.actorId)!==e.id:Ha(r.id)!==e.id)||1!==s.professions?.length||s.bestowable||f(e,{type:"classObserved",class:s.professions[0]});const a=c(e);for(const t of s.blocks)Array.isArray(t)?o(e,{type:"confirmedCount",pool:t,op:"<",n:t.length}):a.have(t)&&o(e,{type:"confirmed",affId:t,present:!1});const d=(e=>e?Object.entries(Ya).filter(([,t])=>!e.nextLine(t)).map(([e])=>e):[])(i);o(e,{type:"cured",cureId:s.id,excludedAffs:d}),n("insight.cure.observed",{id:e.id,cureId:s.id});for(const t of(({cure:e,view:t,context:n})=>{if(wa(e&&Array.isArray(e.order),"cureInferenceEvents needs a cure row"),wa(t&&"function"==typeof t.have&&"function"==typeof t.isBalanceReady,"cureInferenceEvents needs an opponent view"),!n)return[];const r=[];for(const i of Wa)e.order.includes(i.blockerId)&&t.have(i.blockerId)&&t.isBalanceReady(i.balanceId)&&i.pool.some(e=>t.have(e))&&(n.checkBlock(i.evidence)||r.push({type:"confirmedBlocked",pool:[...i.pool],blockerId:i.blockerId}));for(const i of Ka)e.id===i.cureId&&t.have(i.affId)&&!t.have(i.absentAffId)&&n.checkBlock(i.evidence)&&r.push({type:"confirmed",affId:i.affId,present:!0});return r})({cure:s,view:c(e),context:i}))o(e,t)},p=(e,t)=>{const r=e.belief;return o(e,(e=>({type:"advanced",rungs:Ra(e)}))(t.limbId)),e.belief!==r&&(e.resetLimb(t.limbId),n("insight.limb.advanced",{id:e.id,limb:t.limbId,stages:e.limbStages(t.limbId)}),!0)},h={observe(e,t=null){if(!e||"string"!=typeof e.type)return!1;const n=d(e.id);if(!n)return!1;if(i(n.id),"limbAdvance"===e.type)return p(n,e),!0;if(f(n,e))return!0;if("cured"===e.type)return u(n,e,t),!0;if(!md.has(e.type))throw new Error(`unknown observation type '${e.type}'`);return o(n,(e=>{switch(e.type){case"afflicted":case"removed":return{type:e.type,affId:e.affId};case"afflictedOneOf":return{type:e.type,pool:e.pool,mode:e.mode};case"confirmed":return{type:e.type,affId:e.affId,present:e.present};case"confirmedBlocked":return{type:e.type,pool:e.pool,blockerId:e.blockerId};case"confirmedCount":return{type:e.type,pool:e.pool,op:e.op,n:e.n};case"confirmedLevel":return{type:e.type,affId:e.affId,op:e.op,n:e.n};case"converted":return{type:e.type,from:e.from,to:e.to};case"cured":return{type:e.type,cureId:e.cureId,excludedAffs:e.excludedAffs};default:throw new Error(`cannot construct engine event '${e.type}'`)}})(e)),!0},resolveView(e){const t=d(e);return t?l(t):null},addDefinitions(e){for(const t of e){if("string"!=typeof t?.skill||"string"!=typeof t?.id||"function"!=typeof t?.handler)throw new Error("skill definitions need { skill, id, handler }");s.set(Zo(t.skill,t.id),t),a.add(Ro(t.skill))}},listDefinitions:()=>[...s.keys()],listSkills:()=>[...a],dispatchAction({action:e,context:t}){const n=s.get(Zo(e.skill,e.id));if(!n)return;const r=d(t?.actorId);if(!r)return;if("thirdPerson"===e.matchType){const t=Bs.get(Ro(e.skill));t&&(i=e.args,a=r.id,[i.player,i.player?.id,i.user].some(e=>"string"==typeof e&&Ha(e)===a))&&f(r,{type:"classObserved",class:t})}var i,a;const o=n.handler(e,t,l(r))??[];for(const s of o)h.observe({...s,id:r.id},t)}};return Object.freeze(h)},bd=({onSubscriberError:e=null}={})=>{const t=new Map,n="function"==typeof e;return Object.freeze({on:(e,n)=>(t.has(e)||t.set(e,new Set),t.get(e).add(n),()=>{t.get(e)?.delete(n)}),off(e,n){t.get(e)?.delete(n)},raise(r,i){const s=t.get(r);if(s)for(const t of[...s])if(n)try{t(i)}catch(a){try{e({topic:r,handler:t,cause:a})}catch{}}else t(i)}})},vd=(Object.freeze(["internal","js","eventstream"]),Object.freeze(["locked","experimental"]),(e,t,n,r)=>Object.freeze({audience:e,stability:t,payload:Object.freeze(n),description:r})),kd=Object.freeze({"insight.ready":vd("eventstream","locked",{},"Bootstrap reached READY."),"insight.target.changed":vd("eventstream","locked",{id:"string | null"},"The tracked target changed (null = target cleared)."),"insight.opponent.tracked":vd("eventstream","locked",{id:"string"},"An opponent entered observed tracking (new, or re-acquired after leaving the room)."),"insight.opponent.unobserved":vd("eventstream","locked",{id:"string"},"A tracked opponent left observation; simulation continues on their belief."),"insight.opponent.removed":vd("eventstream","experimental",{id:"string"},"A tracked opponent was removed from the roster. Roster lifecycle, not belief evolution: removal deliberately emits no per-aff insight.aff.lost sweep. Experimental until Phase 6 locks it."),"insight.aff.got":vd("eventstream","locked",{id:"string",affId:"string",probability:"number"},"An affliction became present (marginal probability rose above zero) for an opponent."),"insight.aff.lost":vd("eventstream","locked",{id:"string",affId:"string"},"An affliction left an opponent's belief (marginal probability returned to zero)."),"insight.def.got":vd("eventstream","locked",{id:"string",defId:"string"},"A defence was observed present on an opponent."),"insight.def.lost":vd("eventstream","locked",{id:"string",defId:"string"},"A defence was observed absent on an opponent."),"insight.affs.updated":vd("eventstream","locked",{id:"string"},"Prompt-batched per-opponent change flush: this opponent's affliction state changed since the last flush."),"insight.opponent.updated":vd("eventstream","locked",{id:"string"},"Prompt-batched signal that an opponent's display-visible state changed; consumers should re-read insight.state.opponents[id]."),"insight.cure.observed":vd("eventstream","locked",{id:"string",cureId:"string"},"An opponent was observed using a cure after balance gating. Emitted at application time; a cure with delayMs changes affliction state only at resolution."),"insight.limb.advanced":vd("eventstream","locked",{id:"string",limb:"string",stages:"{ healthy: number, damaged: number, mangled: number }"},"A limb damage ladder advanced; stages is the normalized post-transition distribution."),"insight.belief.growthCapped":vd("js","locked",{id:"string",event:"string",beforeCount:"number",afterCount:"number",forkCap:"number"},"Red flag: fork-cap enforcement discarded hypotheses (charter §5.4). Accompanied by a high-visibility notice."),"insight.belief.contradiction":vd("js","locked",{id:"string",event:"object"},"Evidence contradicted every hypothesis; the belief was repaired, not reset (charter §5.3)."),"insight.ingress.skill":vd("internal","experimental",{action:"object",context:"ObservationContext"},"Normalized nexSkills match action with its ingress-captured ObservationContext."),"insight.ingress.skillError":vd("internal","experimental",{skill:"string | null",id:"string | null",line:"string | null",message:"string"},"nexSkills reported a definition reaction that threw (nexskill.error.reaction). The match still raises, so the action insight observes may carry a stale id or missing affs; the composition renders a warning notice."),"insight.ingress.trigger":vd("internal","experimental",{id:"string",match:"object",context:"ObservationContext"},"A trigger-pack pattern fired, with its ingress-captured ObservationContext."),"insight.ingress.target":vd("internal","experimental",{id:"string | null"},"Normalized IRE.Target.Set."),"insight.ingress.room.entered":vd("internal","experimental",{id:"string"},"GMCP Room.AddPlayer, self excluded."),"insight.ingress.room.left":vd("internal","experimental",{id:"string"},"GMCP Room.RemovePlayer."),"insight.ingress.room.list":vd("internal","experimental",{ids:"string[]"},"GMCP Room.Info occupancy resync, self excluded."),"insight.ingress.prompt":vd("internal","experimental",{},"Host PromptEvent boundary — drives the prompt-batched flush."),"insight.display.flush":vd("internal","experimental",{ids:"string[]"},"The prompt-batched flush completed for these dirty opponents — the display coordinator renders on this boundary."),"insight.display.changed":vd("internal","experimental",{id:"string"},"An opponent's display-visible state changed or the opponent became the target; drives the prompt-batched display/opponent.updated flush."),"insight.model.changed":vd("internal","experimental",{id:"string"},"An opponent's aff marginals or observation mode changed — deliberately aff/mode-scoped, driving insight.affs.updated only (the scheduler reschedules from the roster's full per-opponent change surface)."),"insight.scheduler.elapsed":vd("internal","experimental",{id:"string",expired:"object[]",resolvedCures:"object[]",predicted:"object[]"},"A scheduler timer delivered an elapsed window to an opponent model."),"insight.settings.changed":vd("internal","experimental",{document:"SettingsDocument"},"The settings document changed through the composition's settings surface (every document-mutating verb) — carries the new frozen document; runtime subscribers apply the change live (SETTINGS_AUTHORITY.md §5).")}),wd=(e,t=new WeakMap)=>{if(!e||"object"!=typeof e)return e;if(t.has(e))return t.get(e);const n=Array.isArray(e)?[]:{};t.set(e,n);for(const[r,i]of Object.entries(e))n[r]=wd(i,t);return Object.freeze(n)},Id=({adapter:e,notice:t=()=>{}})=>{const n=bd(),r=(e,n,r)=>{t({text:`${e} failed — ${n} (${r?.message??String(r)})`,severity:"error"})},i=bd({onSubscriberError:({topic:e,cause:t})=>r("public event subscriber",e,t)}),s=e=>{const t=kd[e];if(!t)throw new Error(`Undeclared topic '${e}' — every emitted topic must be declared in topicRegistry.js (charter §8)`);return t},a=e=>{if("internal"===s(e).audience)throw new Error(`Topic '${e}' is internal — not part of the public contract`)};return Object.freeze({publish(t,a={}){const o=s(t);if("internal"===o.audience)return void n.raise(t,a);const d=wd(a);if(i.raise(t,d),"eventstream"===o.audience)try{e.events.raise(t,d)}catch(l){r("EventStream forward",t,l)}},on:(e,t)=>(e=>"internal"===s(e).audience?n:i)(e).on(e,t),events:Object.freeze({on(e,t){if(a(e),"function"!=typeof t)throw new TypeError("insight.events.on needs a function");return i.on(e,t)},off(e,t){if(a(e),"function"!=typeof t)throw new TypeError("insight.events.off needs a function");i.off(e,t)}})})},zd=Object.freeze({safetyFlushMs:200}),_d=e=>`insight4.elapsed.${e}`,Od="insight4.flush.safety",$d=({adapter:e,roster:t,publisher:n,notice:r,safetyFlushMs:i=zd.safetyFlushMs})=>{const{publish:s}=n,a=new Map,o=new Set,d=new Set;let l=!1,c=0;const f=[],u=(e,t)=>{for(const n of t)"forkCapExceeded"===n.type&&(s("insight.belief.growthCapped",{id:e,event:n.eventType??"elapsed",beforeCount:n.beforeCount,afterCount:n.afterCount,forkCap:n.forkCap}),r({text:`fork cap hit for ${e} — ${n.beforeCount} → ${n.afterCount} forks (cap ${n.forkCap}) during simulation. Belief detail was discarded; this is a red-flag condition.`,severity:"error"}))},p=(n,{includeDue:r=!1}={})=>{const i=t.get(n);if(!i)return a.delete(n),void e.clock.clearTimer(_d(n));a.has(n)||a.set(n,e.clock.now());const o=((t,n)=>{const r=t.nextInterestingAt({includeDue:n});if(null===r)return null;const i=e.clock.now(),s=a.get(t.id)??i;return Math.max(0,r-t.now-(i-s))})(i,r);null!==o?e.clock.setTimer(_d(n),o,()=>{const t=e.clock.now(),r=a.get(n)??t;a.set(n,t);const o=Math.max(0,t-r);o>0&&(c+=1);const d=i.elapsed(o);u(n,d.diagnostics),s("insight.scheduler.elapsed",{id:n,expired:d.expired,resolvedCures:d.resolvedCures,predicted:d.predicted}),p(n)}):e.clock.clearTimer(_d(n))},h=()=>{if(l=!1,e.clock.clearTimer(Od),0===o.size&&0===d.size)return;const t=[...o].sort(),n=[...d].sort();o.clear(),d.clear();for(const e of t)s("insight.affs.updated",{id:e});for(const e of n)s("insight.opponent.updated",{id:e});n.length>0&&s("insight.display.flush",{ids:n})},m=()=>{l||(l=!0,e.clock.setTimer(Od,i,h))},g=e=>{o.add(e),m()},y=e=>{d.add(e),m()};return Object.freeze({start(){f.push(t.onOpponentChange(e=>p(e,{includeDue:!0})),n.on("insight.model.changed",({id:e})=>g(e)),n.on("insight.display.changed",({id:e})=>y(e)),n.on("insight.opponent.removed",({id:e})=>{o.delete(e),d.delete(e),p(e)}),n.on("insight.ingress.prompt",h))},stop(){for(;f.length>0;)f.pop()();e.clock.clearTimer(Od),l=!1;for(const t of a.keys())e.clock.clearTimer(_d(t));a.clear(),o.clear(),d.clear()},advanceToNow:n=>{const r=t.get(n);if(!r)return null;const i=e.clock.now(),s=a.get(n)??i;a.set(n,i);const o=i-s;if(o<=0)return null;c+=1;const d=r.elapsed(o);return u(n,d.diagnostics),d},getTimeEpoch:()=>c,reschedule:p,markDirty:e=>{g(e),y(e)},flush:h})},Sd=({roster:e,publish:t})=>{let n=null;const r=new Map;let i=!1;const s=[],a=[],o=e=>({mode:e.mode,affs:e.affs??{},defs:e.defs??{},stats:e.stats??{},limbs:e.limbs??{}}),d=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),l=(e,t,n)=>{const r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!0;for(const s of i)if(!d(e,s)||n(e[s])!==n(t[s]))return!0;return!1},c=(e,n)=>{const i=o(n),s=r.get(e);let a=!1,c=!1;s?s.mode!==i.mode&&(a=!0,c=!0,"observed"===i.mode?t("insight.opponent.tracked",{id:e}):t("insight.opponent.unobserved",{id:e})):(a=!0,c=!0,t("insight.opponent.tracked",{id:e}));for(const[r,o]of Object.entries(i.affs)){const n=o.probability;s&&d(s.affs,r)?s.affs[r].probability!==n&&(a=!0,c=!0):(a=!0,c=!0,t("insight.aff.got",{id:e,affId:r,probability:n}))}for(const r of Object.keys(s?.affs??{}))d(i.affs,r)||(a=!0,c=!0,t("insight.aff.lost",{id:e,affId:r}));for(const[r,o]of Object.entries(i.defs))!0===o.have&&!0!==s?.defs[r]?.have&&(c=!0,t("insight.def.got",{id:e,defId:r}));for(const[r,o]of Object.entries(s?.defs??{}))!0===o.have&&!0!==i.defs[r]?.have&&(c=!0,t("insight.def.lost",{id:e,defId:r}));s&&(l(s.stats,i.stats,e=>e.value)||l(s.limbs,i.limbs,e=>e.percent))&&(c=!0),r.set(e,i),a&&t("insight.model.changed",{id:e}),c&&t("insight.display.changed",{id:e})},f=e=>{if(s.push(e),!i){i=!0;try{for(;s.length>0;)s.shift()()}finally{i=!1}}};return Object.freeze({start(){n=e.targetId;for(const t of e.list()){const n=e.get(t);n&&r.set(t,o(n.snapshot()))}a.push(e.onOpponentChange((e,t)=>f(()=>c(e,t))),e.onChange(i=>f(()=>(({ids:i,targetId:s})=>{const a=new Set(i);for(const t of i)if(!r.has(t)){const n=e.get(t);n&&c(t,n.snapshot())}for(const e of[...r.keys()])a.has(e)||(r.delete(e),t("insight.opponent.removed",{id:e}));s!==n&&(n=s,t("insight.target.changed",{id:n}),n&&t("insight.display.changed",{id:n}))})(i))))},stop(){for(;a.length>0;)a.pop()()}})},Nd=(e,t)=>"number"==typeof e?Ha(t?.[e]):null,xd=({adapter:e,settings:t,safetyFlushMs:n,display:r,displaySink:i,notice:s=()=>{},guards:a})=>{const o=Object.freeze({affById:Ts,cureById:As,cureMasks:Rs,balanceById:Es,priorityByAff:Cs,guards:!0===a,get growth(){return t.get().pruning}}),d=Id({adapter:e,notice:s}),{publish:l}=d;let c=0;const f=e=>(c+=1,l("insight.settings.changed",{document:e}),e),u=(e,t)=>{try{return e()}catch(n){throw s({text:`Settings storage ${t} failed: ${n?.message??String(n)}`,severity:"error"}),n}},p=Object.freeze({get:t.get,save:()=>u(t.save,"write"),load:()=>f(u(t.load,"read")),update:e=>f(u(()=>t.update(e),"write")),updateDisplay:e=>f(u(()=>t.updateDisplay(e),"write")),updatePredictive:e=>f(u(()=>t.updatePredictive(e),"write")),replace:e=>f(u(()=>t.replace(e),"write")),reset:()=>f(t.reset()),clear:()=>f(u(t.clear,"clear"))}),h=Va({tables:o,guards:!0===a,policy:t.get().predictive.defaultPolicy,predictionEnabled:t.get().predictive.enabled}),m=$d({adapter:e,roster:h,publisher:d,notice:s,safetyFlushMs:n??t.get().display.safetyFlushMs}),g=yd({roster:h,tables:o,publish:l,notice:s,advanceToNow:m.advanceToNow}),y=Sd({roster:h,publish:l}),b=r?(({publisher:e,roster:t,settings:n,display:r,sink:i})=>{const{renderTarget:s,renderRoster:a,displayTable:o}=r,d=[],l=(e,t)=>{const n=e.targetId?e.opponents[e.targetId]:null;n&&i(s(n,o,t))},c=(e,t)=>{t.display.showRoster&&Object.keys(e.opponents).length>0&&i(a(e.opponents,o,t))};return Object.freeze({start(){d.push(e.on("insight.display.flush",({ids:e})=>{const r=t.snapshot(),i=n.get();r.targetId&&e.includes(r.targetId)&&l(r,i),c(r,i)}))},stop(){for(;d.length>0;)d.pop()()},refresh(){const e=t.snapshot(),r=n.get();l(e,r),c(e,r)}})})({publisher:d,roster:h,settings:p,display:r,sink:i??(t=>e.display.addLine(t))}):null,v=r?(({publisher:e,roster:t,settings:n,display:r,notice:i})=>{const{displayTable:s,renderAffNotice:a,renderDefNotice:o}=r,d=[],l=e=>!0===n.get().display.notices&&t.targetId===e,c=e=>t=>{l(t.id)&&i({html:a({affId:t.affId,present:e},s,n.get())})},f=e=>t=>{l(t.id)&&i({html:o({defId:t.defId,present:e},s,n.get())})};return Object.freeze({start(){d.push(e.on("insight.aff.got",c(!0)),e.on("insight.aff.lost",c(!1)),e.on("insight.def.got",f(!0)),e.on("insight.def.lost",f(!1)))},stop(){for(;d.length>0;)d.pop()()}})})({publisher:d,roster:h,settings:p,display:r,notice:s}):null,k=(()=>{const e=new Map;let t=null;return Object.freeze({rememberQueue(n,r){"string"==typeof n&&n&&"string"==typeof r&&(e.set(n,r),t=n)},snapshot:()=>({queues:Object.fromEntries(e),lastQueue:t}),clear(){e.clear(),t=null}})})(),w=hd({adapter:e,publish:l,commandMemory:k,skills:()=>[...g.listSkills(),...I.listArmingSkills()]}),I=(({adapter:e,roster:t,router:n,publisher:r,capture:i,commandMemory:s,sessionPacks:a=[],promptPacks:o=[]})=>{const{publish:d}=r,l=new Map(a.map(e=>[e.id,e])),c=new Map(o.map(e=>[e.id,e])),f=new Map,u=new Set;for(const z of c.values()){const{skill:e,id:t}=z.armedBy??{};if("string"!=typeof e||""===e||"string"!=typeof t||""===t)continue;const n=Zo(e,t),r=f.get(n);r?r.push(z):f.set(n,[z]),u.add(Ro(e))}const p=new Map,h=new Map,m=[],g=()=>t.listObserved(),y=(e,t,r)=>{for(const i of e??[])n.observe({...i,id:i.id??t},r)},b=(e,r)=>{if(e.remember){const t=e.remember(r);return void(t?.queue&&s.rememberQueue(t.queue.name,t.queue.text))}const a=e.actor??null,o="number"==typeof a?Nd(a,r):null,l=i(o);d("insight.ingress.trigger",{id:e.id,match:r,context:l});const f="room"===a?g():"tracked"===a?t.list():[o];for(const t of f){const i=n.resolveView(t);i&&y(e.handler(r,l,i),i.id,l)}for(const t of c.values())t.armedBy?.trigger===e.id&&w(t,o)},v=(e,t,r)=>{const s=h.get(e.id);if(!s)return;const a="armed"===t.actor?s.state.actorId:Nd(t.actor,r),o=i(a);d("insight.ingress.trigger",{id:`${e.id}.${t.id}`,match:r,context:o});const l=n.resolveView(a);l&&y(t.handler(r,o,l,s.state),l.id,o)},k=t=>{const n=h.get(t);if(!n)return null;for(const r of n.captureIds.values())e.triggers.unregister(r);return h.delete(t),n},w=(n,r=null)=>{k(n.id);const i=n.initState?n.initState({actorId:r,observedIds:g(),targetId:t.targetId}):{actorId:r},s=new Map;for(const t of n.captures)s.set(t.id,e.triggers.register(t.pattern,"prompt",e=>v(n,t,e)));h.set(n.id,{pack:n,state:i,captureIds:s})},I=()=>{for(const e of[...h.keys()]){const t=k(e);if(t?.pack.finalize){const e=i(t.state.actorId??null);y(t.pack.finalize(t.state),t.state.actorId??null,e)}}};return Object.freeze({start(){for(const t of l.values())p.set(t.id,e.triggers.register(t.pattern,"session",e=>b(t,e)));m.push(r.on("insight.ingress.skill",({action:e})=>{const t=f.get(Zo(e.skill,e.id));for(const n of t??[])w(n,null)}),r.on("insight.ingress.prompt",I))},stop(){for(;m.length>0;)m.pop()();for(const e of[...h.keys()])k(e);for(const t of p.values())e.triggers.unregister(t);p.clear()},listSession:()=>[...l.keys()],listArmed:()=>[...h.keys()],listArmingSkills:()=>[...u]})})({adapter:e,roster:h,router:g,publisher:d,capture:w.capture,commandMemory:k,sessionPacks:ld,promptPacks:cd}),z=e=>{g.addDefinitions(e),w.observeSkills(g.listSkills())};z(Do);const _=[],O=()=>{for(w.stop(),I.stop(),m.stop(),y.stop(),b?.stop(),v?.stop();_.length>0;)_.pop()()};try{y.start(),m.start(),b?.start(),v?.start(),_.push(d.on("insight.ingress.skill",g.dispatchAction),d.on("insight.ingress.skillError",({skill:e,id:t,message:n})=>s({text:`nexSkills reaction failed for ${e??"?"}.${t??"?"} — ${n}. Observations from that line may be incomplete.`,severity:"warning"})),d.on("insight.ingress.target",({id:e})=>h.setTarget(e)),d.on("insight.ingress.room.entered",({id:e})=>h.track(e)),d.on("insight.ingress.room.left",({id:e})=>h.untrack(e)),d.on("insight.ingress.room.list",({ids:e})=>(e=>{const t=new Set(e);for(const n of e)h.track(n);for(const n of h.list())t.has(n)||h.untrack(n)})(e)),d.on("insight.settings.changed",({document:e})=>h.updateDefaults({policy:e.predictive.defaultPolicy,predictionEnabled:e.predictive.enabled}))),I.start(),w.start()}catch($){throw O(),$}return Object.freeze({roster:h,router:g,scheduler:m,registrar:I,publish:l,events:d.events,settings:p,getSettingsRevision:()=>c,display:b,observe:g.observe,addDefinitions:z,capture:w.capture,dispose:O})},jd=Object.freeze({schemaVersion:2,autoUpdate:!1,display:Object.freeze({threshold:0,shortNames:!0,colors:!0,notices:!0,showRoster:!1,safetyFlushMs:200}),predictive:Object.freeze({enabled:!1,defaultPolicy:"distribution"}),queries:Object.freeze({presenceFloor:.01}),pruning:Object.freeze({epsilon:Gs.epsilon,forkCap:Gs.forkCap})}),Md=Lr({threshold:xr().min(0).max(1).catch(jd.display.threshold),shortNames:Ar().catch(jd.display.shortNames),colors:Ar().catch(jd.display.colors),notices:Ar().catch(jd.display.notices),showRoster:Ar().catch(jd.display.showRoster),safetyFlushMs:xr().int().min(0).max(1e4).catch(jd.display.safetyFlushMs)}).catch({...jd.display}),Td=Lr({enabled:Ar().catch(jd.predictive.enabled),defaultPolicy:Wr(Ia).catch(jd.predictive.defaultPolicy)}).catch({...jd.predictive}),Ad=Lr({presenceFloor:xr().min(0).max(1).catch(jd.queries.presenceFloor)}).catch({...jd.queries}),Ed=Lr({epsilon:xr().positive().max(.1).catch(jd.pruning.epsilon),forkCap:xr().int().min(1).catch(jd.pruning.forkCap)}).catch({...jd.pruning}),Cd=Lr({schemaVersion:Qr(2).catch(2),autoUpdate:Ar().catch(jd.autoUpdate),display:Md,predictive:Td,queries:Ad,pruning:Ed}).catch({schemaVersion:2,autoUpdate:jd.autoUpdate,display:{...jd.display},predictive:{...jd.predictive},queries:{...jd.queries},pruning:{...jd.pruning}}),Pd=e=>{if(e&&"object"==typeof e&&!Object.isFrozen(e)){Object.freeze(e);for(const t of Object.keys(e))Pd(e[t])}return e},Rd=e=>Pd(Cd.parse(e)),Zd=(e,{key:t="insightSettings"}={})=>{let n=Rd(null);const r=(r=n)=>(e.storage.set(t,JSON.stringify(r)),n=r,r);return Object.freeze({get:()=>n,load:()=>(n=Rd((e=>{if("string"==typeof e)try{return JSON.parse(e)}catch{return null}return e??null})(e.storage.get(t))),n),save:()=>r(),update:(e={})=>r(Rd({...n,...e,display:{...n.display,...e.display},predictive:{...n.predictive,...e.predictive},queries:{...n.queries,...e.queries},pruning:{...n.pruning,...e.pruning}})),updateDisplay:(e={})=>r(Rd({...n,display:{...n.display,...e}})),updatePredictive:(e={})=>r(Rd({...n,predictive:{...n.predictive,...e}})),replace:e=>r(Rd(e)),reset:()=>(n=Rd(null),n),clear:()=>(e.storage.clear(t),n=Rd(null),n)})},Dd=Object.freeze({forks:Object.freeze([])}),Fd=({roster:e,events:t,settings:n,observe:r,capture:i,advanceToNow:s,reschedule:a,displayRendering:o,refreshDisplay:d,notice:l,addLine:c,getPhase:f,getPhaseRevision:u,getSettingsRevision:p,getTimeEpoch:h,version:m})=>{const g=t=>{const n=t?.id;return null==n?e.getTarget():e.get(n)},y=(e,t)=>{const n=g(e);return n?ha(n.belief,t):0},b=(e,t,n)=>e(g(t)?.belief??Dd,n),v=(e,t)=>b(ma,e,t),k=(e,t)=>b(ga,e,t),w=(e,t)=>((e,t,n,r)=>{ua(t),Js(da.includes(n),`unknown comparison operator '${n}'`),Js(Number.isInteger(r)&&r>=0,"pool count probability needs an integer n >= 0");let i=0;for(const s of e.forks)la(pa(s,t),n,r)&&(i+=s.p);return i})(g(e)?.belief??Dd,t,e?.op,e?.n),I=(e,t)=>e>n.get().queries.presenceFloor&&e>=(e=>{const t="number"==typeof e?.threshold?e.threshold:0;return t>1?t/100:t})(t),z=e=>{if(e&&"object"==typeof e&&!Object.isFrozen(e)){Object.freeze(e);for(const t of Object.keys(e))z(e[t])}return e},_=e=>e&&"object"==typeof e?Array.isArray(e)?e.map(_):Object.fromEntries(Object.entries(e).map(([e,t])=>[e,_(t)])):e,O=new Map,$=(e,t)=>{const n=O.get(e.id);if(n?.model===e&&n.revision===e.revision&&n.timeEpoch===e.timeEpoch&&n.settingsRevision===t)return n.branch;const r=e.snapshot(),i=z(_({id:r.id,affs:r.affs,limbs:r.limbs,balances:r.balances,stats:r.stats,defs:r.defs,staleness:r.staleness}));return O.set(e.id,{model:e,revision:e.revision,timeEpoch:e.timeEpoch,settingsRevision:t,branch:i}),i};let S=null,N=null;const x=()=>{const t={rosterRevision:e.revision,settingsRevision:p(),phaseRevision:u(),timeEpoch:h()};if(N?.rosterRevision===t.rosterRevision&&N.settingsRevision===t.settingsRevision&&N.phaseRevision===t.phaseRevision&&N.timeEpoch===t.timeEpoch)return S;const r={},i=[...e.list()].sort(),s=new Set(i);for(const n of i)r[n]=$(e.get(n),t.settingsRevision);for(const e of O.keys())s.has(e)||O.delete(e);return S=Object.freeze({system:Object.freeze({phase:f(),version:m}),target:e.targetId?r[e.targetId]??null:null,opponents:Object.freeze(r),settings:n.get()}),N=t,S},j=Object.freeze({get:()=>e.targetId,set:t=>{const n=e.setTarget(t??null);return n?n.id:null},is:t=>null!==e.targetId&&Ha(t)===e.targetId}),M=Object.freeze({track:t=>{const n=e.track(t);return n?n.id:null},remove:t=>e.remove(t),list:()=>e.list(),reset:t=>e.reset(t),resetAll:()=>{e.resetAll()}}),T=Object.freeze({have:(e,t)=>I(y(t,e),t),haveAll:(e,t)=>I(k(t,e),t),haveAny:(e,t)=>I(v(t,e),t),probability:(e,t)=>y(t,e),probabilityAll:(e,t)=>k(t,e),probabilityAny:(e,t)=>v(t,e),expectedPoolCount:(e,t)=>((e,t)=>b(ya,e,t))(t,e),poolCountProbability:(e,t)=>w(t,e)}),A=Object.freeze({have:(e,t)=>!0===g(t)?.haveDef(e)}),E=Object.freeze({get:(e,t)=>{const n=g(t);return n?Object.freeze({percent:n.limbPercent(e),stages:Object.freeze(n.limbStages(e))}):null},hit:(e,t)=>r({type:"limbHit",limbId:e,percent:t?.percent,id:t?.id}),advance:(e,t)=>r({type:"limbAdvance",limbId:e,id:t?.id}),reset:(e,t)=>r({type:"limbReset",limbId:e,id:t?.id})}),C=Object.freeze({have:(e,t)=>{const n=g(t);return!!n&&n.isBalanceReady(e)},remainingMs:(e,t)=>{const n=g(t);return n?n.snapshot().balances[e]?.remainingMs??null:null}}),P=(e,t={})=>{const{id:n,...s}=t;return r({type:e,...s,id:n},i(n??null))},R=Object.freeze({afflicted:e=>P("afflicted",e),afflictedOneOf:({mode:e="firstMissing",...t}={})=>P("afflictedOneOf",{mode:e,...t}),advanced:e=>P("limbAdvance",e),cured:e=>P("cured",e),confirmed:({present:e=!0,...t}={})=>P("confirmed",{present:e,...t}),confirmedCount:e=>P("confirmedCount",e),confirmedLevel:e=>P("confirmedLevel",e),converted:e=>P("converted",e),removed:e=>P("removed",e)}),Z=Object.freeze({enable:e=>{const t=g({id:e});return!!t&&(t.enablePrediction(),!0)},disable:e=>{const t=g({id:e});return!!t&&(t.disablePrediction(),!0)},setPolicy:(e,t)=>{const n=g({id:t});return!!n&&(n.setPolicy(e),!0)},isEnabled:e=>{const t=g({id:e});return!!t&&t.isPredictionEnabled()},stepNow:e=>{const t=g({id:e});if(!t)return null;const n=s(t.id)??{expired:[],predicted:[],diagnostics:[]};return a(t.id),n}}),D=Object.freeze({get:({view:e="target",id:t,affId:r,defId:i,present:s}={})=>{const a=n.get();if("affNotice"===e){if("string"!=typeof r||0===r.length||"boolean"!=typeof s)throw new TypeError("display.get affNotice needs affId and boolean present");return o.renderAffNotice({affId:r,present:s},o.displayTable,a)}if("defNotice"===e){if("string"!=typeof i||0===i.length||"boolean"!=typeof s)throw new TypeError("display.get defNotice needs defId and boolean present");return o.renderDefNotice({defId:i,present:s},o.displayTable,a)}if(!["target","affState","statState"].includes(e))throw new TypeError(`unknown display view '${e}'`);const d=g({id:t});if(!d)return"";const l=d.snapshot();return"target"===e?o.renderTarget(l,o.displayTable,a):"affState"===e?o.renderAffState(l,o.displayTable,a):o.renderStatState(l,o.displayTable,a)},notice:(e,t)=>{l({html:e,severity:t})},refresh:()=>{d()},openDebug:()=>{c(o.renderDebug(x()))}}),F=Object.freeze({target:j,opponents:M,affs:T,defs:A,limbs:E,balances:C,observe:R,simulate:Z,display:D,settings:n}),L=Object.freeze(Object.fromEntries(Object.entries(kd).filter(([,e])=>"internal"!==e.audience))),q=Object.freeze({on:t.on,off:t.off,topics:L});return Object.freeze({get state(){return x()},api:F,events:q})},Ld=["head","torso","leftarm","rightarm","leftleg","rightleg"],qd=e=>String(e).replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;"),Bd=(e,t="",n="")=>{const r=[t?`color: ${t}`:"",n?`background: ${n}`:""].filter(Boolean).join("; ");return r?`<span style="${r}">${e}</span>`:`<span>${e}</span>`},Gd=(e,t="",n="")=>Bd(qd(e),t,n),Jd=e=>e.charAt(0).toUpperCase()+e.slice(1),Ud=(e,t)=>Object.entries(e).filter(([,e])=>e.probability>0&&e.probability>=t).sort(([e,t],[n,r])=>r.probability-t.probability||(e<n?-1:1)),Hd=(e,t,n,r)=>{const i=n.affs[e],s=r.shortNames&&i?i.shortName:e,a=void 0!==t.count?(e=>String(parseFloat(e.toFixed(1))))(t.count):"",o=r.colors&&i?i.fg:"",d=r.colors&&i?i.bg:"";return Gd(`${s}${a}`,o,d)},Vd=(e,t,n)=>{const r=n.display,{bracket:i}=t.chrome,s=[Gd("[",i.fg,i.bg)],a=Ud(e.affs,r.threshold);return a.forEach(([e,n],i)=>{s.push(Hd(e,n,t,r));const o=i<a.length-1?", ":"";s.push(Gd(`: ${(e=>String(Math.round(100*e)/100))(n.probability)}${o}`))}),s.push(Gd("]",i.fg,i.bg)),s},Yd=[["hp","H"],["mana","M"]],Wd=e=>{const t=Math.round(100*Math.min(1,Math.max(0,e)));return`hsl(${1.2*t}, 100%, ${t<75?50:Math.abs(t-100)/2+25}%)`},Kd=(e,t)=>{const n=[],{detail:r}=t.chrome;for(const[i,s]of Yd){const t=e.stats?.[i];if(!t)continue;n.length>0&&n.push(Gd(" "));const a=Math.round(100*Math.min(1,Math.max(0,t.value)));n.push(Gd(`${s}:`,r.fg,r.bg)),n.push(Gd(`${a}%`,Wd(t.value)))}return n},Qd=(e,t,n,r,i)=>{const s=[Gd(`${n?"+":"-"}${e} `,n?"lime":"red")];if("aff"===e){const e=r.affs[t],n=i.display;s.push(Gd(Jd(t),n.colors&&e?e.fg:"",n.colors&&e?e.bg:""))}else s.push(Gd(Jd(t)));return s},Xd=({text:e="",html:t,severity:n="info"},r)=>{const i=r.chrome.severity,s=i[n]??i.info,a="string"==typeof t?Bd(t,s.fg,s.bg):Gd(e,s.fg,s.bg);return`<span class="mono">${(e=>{const{delimiter:t,label:n}=e.chrome.tag;return[Gd("<<",t.fg,t.bg),Gd("insight",n.fg,n.bg),Gd(">> ",t.fg,t.bg)]})(r).join("")}${a}</span>`},el="0.6.1",tl=Object.freeze({BOOTING:"BOOTING",LOADING_SETTINGS:"LOADING_SETTINGS",REGISTERING_TRIGGERS:"REGISTERING_TRIGGERS",READY:"READY",DEGRADED:"DEGRADED"}),nl=Object.freeze({[tl.BOOTING]:Object.freeze([tl.LOADING_SETTINGS,tl.DEGRADED]),[tl.LOADING_SETTINGS]:Object.freeze([tl.REGISTERING_TRIGGERS,tl.DEGRADED]),[tl.REGISTERING_TRIGGERS]:Object.freeze([tl.READY,tl.DEGRADED]),[tl.READY]:Object.freeze([]),[tl.DEGRADED]:Object.freeze([])});var rl="__insight4StorageProbe",il=Object.freeze({displayTable:Ei,renderAffNotice:({affId:e,present:t},n,r)=>`<span class="mono">${Qd("aff",e,t,n,r).join("")}</span>`,renderAffState:(e,t,n)=>`<span class="mono">${Vd(e,t,n).join("")}</span>`,renderDebug:e=>`<pre class="mono">${qd(JSON.stringify(e,null,2))}</pre>`,renderDefNotice:({defId:e,present:t},n,r)=>`<span class="mono">${Qd("def",e,t,n,r).join("")}</span>`,renderNotice:Xd,renderRoster:(e,t,n)=>{const r=n.display;if(!r.showRoster)return"";const{bracket:i,detail:s}=t.chrome,a=[];return Object.keys(e).sort().forEach((n,o)=>{const d=e[n];o>0&&a.push(Gd(" ")),a.push(Gd(`${Jd(n)} `),Gd("[",i.fg,i.bg));const l=Ud(d.affs,r.threshold);l.forEach(([e,n],i)=>{a.push(Hd(e,n,t,r)),i<l.length-1&&a.push(Gd(" "))}),a.push(Gd("]",i.fg,i.bg));const c=Math.round(100*d.staleness);c>0&&a.push(Gd(` ~${c}%`,s.fg,s.bg))}),`<span class="mono">${a.join("")}</span>`},renderStatState:(e,t)=>{const n=Kd(e,t);return n.length>0?`<span class="mono">${n.join("")}</span>`:""},renderTarget:(e,t,n)=>{const{detail:r}=t.chrome,i=[Gd(`${Jd(e.id)} `),...Vd(e,t,n)],s=Kd(e,t);s.length>0&&i.push(Gd(" "),...s);const a=Ld.filter(t=>e.limbs[t]?.percent>0);if(a.length>0){const t=a.map(t=>{const n=e.limbs[t];return`${t}:${Math.round(n.percent)}%`}).join(" ");i.push(Gd(` ${t}`,r.fg,r.bg))}return`<span class="mono">${i.join("")}</span>`}});function sl(e,{safetyFlushMs:t,updateNxs:n=p,guards:r}={}){const i=function({onTransition:e}={}){let t=tl.BOOTING,n=0;const r=[tl.BOOTING];return{getPhase:()=>t,getRevision:()=>n,getHistory:()=>[...r],transition(i){if(!nl[t].includes(i))throw new Error(`Invalid phase transition: ${t} → ${i}`);return t=i,n+=1,r.push(i),e?.(i),t}}}();let a,o=null,d=null,l=null,c=null,f=!1;const u={getPhase:i.getPhase,getPhaseHistory:i.getHistory,getError:()=>o,isReady:()=>i.getPhase()===tl.READY,dispose(){f||(f=!0,l?.dispose(),c&&globalThis.insight===c&&delete globalThis.insight)},get settings(){return d},get runtime(){return l},get state(){return c?c.state:null},get api(){return c?c.api:null},get events(){return c?c.events:null}},h=t=>{try{e.display.addLine(Xd(t,Ei))}catch{}},m=()=>{!0===d?.get?.().autoUpdate&&n({enabled:!0,currentVersion:el,notice:h})},g=e=>(o=e,i.transition(tl.DEGRADED),h({text:`DEGRADED: ${e?.message??String(e)}`,severity:"error"}),m(),u);try{if(s(e),e.storage.clear(rl),e.storage.set(rl,"probe"),e.storage.clear(rl),"function"==typeof e.display.addStream){const t=e.display.addStream.bind(e.display);a=e=>t(e,"combat")}else{const t=e.display.addLine.bind(e.display);a=e=>t(e)}}catch(b){try{e?.storage?.clear?.(rl)}catch{}return g(b)}i.transition(tl.LOADING_SETTINGS);const y=Zd(e);d=y;try{y.load()}catch(b){y.reset(),h({text:`Settings storage is unavailable — running on default settings. (${b?.message??String(b)})`,severity:"warning"})}i.transition(tl.REGISTERING_TRIGGERS);try{l=xd({adapter:e,settings:y,safetyFlushMs:t,guards:r,displaySink:a,notice:h,display:il}),d=l.settings,c=Fd({roster:l.roster,events:l.events,settings:l.settings,observe:l.observe,capture:l.capture,advanceToNow:l.scheduler.advanceToNow,reschedule:l.scheduler.reschedule,displayRendering:il,refreshDisplay:l.display.refresh,notice:h,addLine:a,getPhase:i.getPhase,getPhaseRevision:i.getRevision,getSettingsRevision:l.getSettingsRevision,getTimeEpoch:l.scheduler.getTimeEpoch,version:el})}catch(b){return l?.dispose(),l=null,d=y,g(b)}return i.transition(tl.READY),globalThis.insight=c,l.publish("insight.ready",{}),m(),u}var al=Symbol.for("insight4.instance");!function(t){globalThis[al]?.dispose();const r=sl(function(){const t=new Map;let r=1;const i="undefined"!=typeof nexGui&&"function"==typeof nexGui?.api?.stream?.add?{receiver:nexGui.api.stream,add:nexGui.api.stream.add}:null,s={addLine(e){nexusclient.add_html_line(e)}};return i&&(s.addStream=(e,t)=>{i.add.call(i.receiver,{html:e,stream:t})}),{display:s,storage:{get(t){const n=e();return"function"==typeof n?.get?n.get(t):n?.vars?.[t]},set(t,n){const r=e();if("function"!=typeof r?.set){if(!r?.vars)throw new Error("insight4 storage.set failed — host variables expose neither set() nor a vars record");r.vars[t]=n}else r.set(t,n)},clear(t){const n=e();if("function"!=typeof n?.delete)if("function"!=typeof n?.set){if(!n?.vars)throw new Error("insight4 storage.clear failed — host variables expose neither delete()/set() nor a vars record");delete n.vars[t]}else n.set(t,void 0);else n.delete(t)}},triggers:{register(e,t,n){const i="insight4.trigger."+r++;return nexAction.triggers.add({id:i,tags:["insight4",`lifetime:${t}`],regex:e,action:n}),i},unregister(e){nexAction.triggers.remove(e)}},events:{onSkillMatch(e,t=null){if("undefined"==typeof nexSkills||!nexSkills)throw new Error("nexSkills is unavailable — insight cannot observe skill events");return n(t?`nexskill.match.skill.${t}`:"nexskill.match.skill",e)},on:n,raise(e,t){eventStream.raiseEvent(e,t)}},gmcp:{read:e=>String(e).split(".").reduce((e,t)=>null==e?e:e[t],GMCP)},text:{snapshot:()=>({lines:(nexusclient.current_block??[]).map(e=>({text:"string"==typeof e.line?"function"==typeof e.parsed_line?.text?e.parsed_line.text():e.line:null,isPrompt:!0===e.is_prompt,isHtml:Boolean(e.html_text)})),currentLineIndex:nexusclient.current_line?.index??-1})},clock:{now:()=>Date.now(),setTimer(e,n,r){const i=t.get(e);void 0!==i&&clearTimeout(i),t.set(e,setTimeout(()=>{t.delete(e),r()},n))},clearTimer(e){const n=t.get(e);void 0!==n&&(clearTimeout(n),t.delete(e))}}}}(),t);globalThis[al]=r}()}();
1
+ !function(){function e(){return nexusclient.variables()}var t=["insight4"];function n(e,n){const r=`insight4.${e}`;return eventStream.registerEvent(e,n,{id:r,tags:t}),()=>{eventStream.removeListener(e,r)}}var r=Object.freeze({display:Object.freeze(["addLine"]),storage:Object.freeze(["get","set","clear"]),triggers:Object.freeze(["register","unregister"]),events:Object.freeze(["onSkillMatch","on","raise"]),gmcp:Object.freeze(["read"]),text:Object.freeze(["snapshot"]),clock:Object.freeze(["now","setTimer","clearTimer"])});Object.freeze(["events.onSkillMatch","events.on"]);function s(e){const t=function(e){if(null===e||"object"!=typeof e)return["adapter is not an object"];const t=[];for(const[n,s]of Object.entries(r)){const r=e[n];if(null!==r&&"object"==typeof r)for(const e of s)"function"!=typeof r[e]&&t.push(`${n}.${e} is not a function`);else t.push(`${n} is missing`)}return t}(e);if(t.length>0)throw new Error(`Adapter contract violation: ${t.join("; ")}`);return e}var i,a=/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/,o="nexsight",d=`https://unpkg.com/${o}@latest/package.json`,l=e=>{const t=a.exec(String(e??"").trim());if(!t)throw new Error(`invalid version '${e??""}'`);return{core:t.slice(1,4).map(Number),prerelease:t[4]?.split(".")??[]}},c=(e,t)=>{const n=/^\d+$/.test(e)?Number(e):null,r=/^\d+$/.test(t)?Number(t):null;return null!==n&&null!==r?Math.sign(n-r):null!==n?-1:null!==r?1:e===t?0:e<t?-1:1},f=(e,t,n)=>{try{e?.({text:t,severity:n})}catch{}},u=async({enabled:e=!1,currentVersion:t,notice:n=null,fetchFn:r=globalThis.fetch,consoleObj:s=console,setTimeoutFn:i=setTimeout,clearTimeoutFn:a=clearTimeout,timeoutMs:u=1e4,url:p=d}={})=>{if(!e)return null;let h=null;try{if("function"!=typeof r)throw new Error("fetch is not available");l(t);const e=globalThis.AbortController;let s;if(e&&u>0){const t=new e;h=i(()=>t.abort(),u),s=t.signal}const a=await r(p,{cache:"no-store",...s?{signal:s}:{}});if(!a?.ok)throw new Error(`${a?.status??"no"} response from ${p}`);const d=(await a.json())?.version;if(l(d),((e,t)=>{const n=l(e),r=l(t);for(let i=0;i<n.core.length;i+=1)if(n.core[i]!==r.core[i])return Math.sign(n.core[i]-r.core[i]);if(0===n.prerelease.length||0===r.prerelease.length)return n.prerelease.length===r.prerelease.length?0:0===n.prerelease.length?1:-1;const s=Math.max(n.prerelease.length,r.prerelease.length);for(let i=0;i<s;i+=1){if(void 0===n.prerelease[i])return-1;if(void 0===r.prerelease[i])return 1;const e=c(n.prerelease[i],r.prerelease[i]);if(0!==e)return e}return 0})(d,t)<=0)return null;const m=(e=>`https://unpkg.com/${o}@${e}/insight4.nxs`)(d);return f(n,`Update available: ${t} → ${d}. Import ${m}`,"warning"),{currentVersion:t,latestVersion:d,url:m}}catch(m){const e="AbortError"===m?.name?"Update check timed out — check your connection.":`Update check failed: ${m?.message??String(m)}`;return s.error(`[insight4] ${e}`),f(n,e,"error"),null}finally{null!==h&&a(h)}};function p(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,"_zod",{value:{def:r,constr:a,traits:new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);const s=a.prototype,i=Object.keys(s);for(let e=0;e<i.length;e++){const t=i[e];t in n||(n[t]=s[t].bind(n))}}const s=n?.Parent??Object;class i extends s{}function a(e){var t;const s=n?.Parent?new i:this;r(s,e),(t=s._zod).deferred??(t.deferred=[]);for(const n of s._zod.deferred)n();return s}return Object.defineProperty(i,"name",{value:e}),Object.defineProperty(a,"init",{value:r}),Object.defineProperty(a,Symbol.hasInstance,{value:t=>!!(n?.Parent&&t instanceof n.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(a,"name",{value:e}),a}var h=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},m=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}};(i=globalThis).__zod_globalConfig??(i.__zod_globalConfig={});var g=globalThis.__zod_globalConfig;function b(e){return e&&Object.assign(g,e),g}function y(e){const t=Object.values(e).filter(e=>"number"==typeof e);return Object.entries(e).filter(([e,n])=>-1===t.indexOf(+e)).map(([e,t])=>t)}function v(e,t){return"bigint"==typeof t?t.toString():t}function k(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function w(e){return null==e}function I(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}var z=Symbol("evaluating");function _(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==z)return void 0===r&&(r=z,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function O(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function $(...e){const t={};for(const n of e)Object.assign(t,Object.getOwnPropertyDescriptors(n));return Object.defineProperties({},t)}function S(e){return JSON.stringify(e)}var M="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function x(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var j=k(()=>{if(g.jitless)return!1;if("undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function N(e){if(!1===x(e))return!1;const t=e.constructor;if(void 0===t)return!0;if("function"!=typeof t)return!0;const n=t.prototype;return!1!==x(n)&&!1!==Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")}function A(e){return N(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}var T=new Set(["string","number","symbol"]);function E(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function C(e,t,n){const r=new e._zod.constr(t??e._zod.def);return t&&!n?.parent||(r._zod.parent=e),r}function P(e){const t=e;if(!t)return{};if("string"==typeof t)return{error:()=>t};if(void 0!==t?.message){if(void 0!==t?.error)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,"string"==typeof t.error?{...t,error:()=>t.error}:t}var D={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function R(e,t=0){if(!0===e.aborted)return!0;for(let n=t;n<e.issues.length;n++)if(!0!==e.issues[n]?.continue)return!0;return!1}function Z(e,t=0){if(!0===e.aborted)return!0;for(let n=t;n<e.issues.length;n++)if(!1===e.issues[n]?.continue)return!0;return!1}function B(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function L(e){return"string"==typeof e?e:e?.message}function F(e,t,n){const r=e.message?e.message:L(e.inst?._zod.def?.error?.(e))??L(t?.error?.(e))??L(n.customError?.(e))??L(n.localeError?.(e))??"Invalid input",{inst:s,continue:i,input:a,...o}=e;return o.path??(o.path=[]),o.message=r,t?.reportInput&&(o.input=a),o}function q(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function G(...e){const[t,n,r]=e;return"string"==typeof t?{message:t,code:"custom",input:n,inst:r}:{...t}}var J=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,v,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},U=p("$ZodError",J),H=p("$ZodError",J,{Parent:Error});var V=e=>(t,n,r,s)=>{const i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new h;if(a.issues.length){const t=new(s?.Err??e)(a.issues.map(e=>F(e,i,b())));throw M(t,s?.callee),t}return a.value},W=e=>async(t,n,r,s)=>{const i=r?{...r,async:!0}:{async:!0};let a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise&&(a=await a),a.issues.length){const t=new(s?.Err??e)(a.issues.map(e=>F(e,i,b())));throw M(t,s?.callee),t}return a.value},Y=e=>(t,n,r)=>{const s=r?{...r,async:!1}:{async:!1},i=t._zod.run({value:n,issues:[]},s);if(i instanceof Promise)throw new h;return i.issues.length?{success:!1,error:new(e??U)(i.issues.map(e=>F(e,s,b())))}:{success:!0,data:i.value}},K=Y(H),Q=e=>async(t,n,r)=>{const s=r?{...r,async:!0}:{async:!0};let i=t._zod.run({value:n,issues:[]},s);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(e=>F(e,s,b())))}:{success:!0,data:i.value}},X=Q(H),ee=e=>(t,n,r)=>{const s=r?{...r,direction:"backward"}:{direction:"backward"};return V(e)(t,n,s)},te=e=>(t,n,r)=>V(e)(t,n,r),ne=e=>async(t,n,r)=>{const s=r?{...r,direction:"backward"}:{direction:"backward"};return W(e)(t,n,s)},re=e=>async(t,n,r)=>W(e)(t,n,r),se=e=>(t,n,r)=>{const s=r?{...r,direction:"backward"}:{direction:"backward"};return Y(e)(t,n,s)},ie=e=>(t,n,r)=>Y(e)(t,n,r),ae=e=>async(t,n,r)=>{const s=r?{...r,direction:"backward"}:{direction:"backward"};return Q(e)(t,n,s)},oe=e=>async(t,n,r)=>Q(e)(t,n,r),de=/^[cC][0-9a-z]{6,}$/,le=/^[0-9a-z]+$/,ce=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,fe=/^[0-9a-vA-V]{20}$/,ue=/^[A-Za-z0-9]{27}$/,pe=/^[a-zA-Z0-9_-]{21}$/,he=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,me=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,ge=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,be=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var ye=/^(?:(?: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])$/,ve=/^(([0-9a-fA-F]{1,4}:){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}|:))$/,ke=/^((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])\/([0-9]|[1-2][0-9]|3[0-2])$/,we=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ie=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,ze=/^[A-Za-z0-9_-]*$/,_e=/^https?$/,Oe=/^\+[1-9]\d{6,14}$/,$e="(?:(?:\\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])))",Se=new RegExp(`^${$e}$`);function Me(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof e.precision?-1===e.precision?`${t}`:0===e.precision?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}var xe=/^-?\d+$/,je=/^-?\d+(?:\.\d+)?$/,Ne=/^(?:true|false)$/i,Ae=/^[^A-Z]*$/,Te=/^[^a-z]*$/,Ee=p("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Ce={number:"number",bigint:"bigint",object:"date"},Pe=p("$ZodCheckLessThan",(e,t)=>{Ee.init(e,t);const n=Ce[typeof t.value];e._zod.onattach.push(e=>{const n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:"too_big",maximum:"object"==typeof t.value?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),De=p("$ZodCheckGreaterThan",(e,t)=>{Ee.init(e,t);const n=Ce[typeof t.value];e._zod.onattach.push(e=>{const n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:"object"==typeof t.value?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Re=p("$ZodCheckMultipleOf",(e,t)=>{Ee.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof n.value?n.value%t.value!==BigInt(0):0!==function(e,t){const n=e/t,r=Math.round(n),s=Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-r)<s?0:n-r}(n.value,t.value))&&n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Ze=p("$ZodCheckNumberFormat",(e,t)=>{Ee.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),r=n?"int":"number",[s,i]=D[t.format];e._zod.onattach.push(e=>{const r=e._zod.bag;r.format=t.format,r.minimum=s,r.maximum=i,n&&(r.pattern=xe)}),e._zod.check=a=>{const o=a.value;if(n){if(!Number.isInteger(o))return void a.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:o,inst:e});if(!Number.isSafeInteger(o))return void(o>0?a.issues.push({input:o,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort}):a.issues.push({input:o,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort}))}o<s&&a.issues.push({origin:"number",input:o,code:"too_small",minimum:s,inclusive:!0,inst:e,continue:!t.abort}),o>i&&a.issues.push({origin:"number",input:o,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}}),Be=p("$ZodCheckMaxLength",(e,t)=>{var n;Ee.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!w(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{const r=n.value;if(r.length<=t.maximum)return;const s=q(r);n.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Le=p("$ZodCheckMinLength",(e,t)=>{var n;Ee.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!w(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{const r=n.value;if(r.length>=t.minimum)return;const s=q(r);n.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Fe=p("$ZodCheckLengthEquals",(e,t)=>{var n;Ee.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!w(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{const r=n.value,s=r.length;if(s===t.length)return;const i=q(r),a=s>t.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),qe=p("$ZodCheckStringFormat",(e,t)=>{var n,r;Ee.init(e,t),e._zod.onattach.push(e=>{const n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??(n.patterns=new Set),n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),Ge=p("$ZodCheckRegex",(e,t)=>{qe.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Je=p("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Ae),qe.init(e,t)}),Ue=p("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Te),qe.init(e,t)}),He=p("$ZodCheckIncludes",(e,t)=>{Ee.init(e,t);const n=E(t.includes),r=new RegExp("number"==typeof t.position?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),Ve=p("$ZodCheckStartsWith",(e,t)=>{Ee.init(e,t);const n=new RegExp(`^${E(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),We=p("$ZodCheckEndsWith",(e,t)=>{Ee.init(e,t);const n=new RegExp(`.*${E(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),Ye=p("$ZodCheckOverwrite",(e,t)=>{Ee.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}}),Ke=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if("function"==typeof e)return e(this,{execution:"sync"}),void e(this,{execution:"async"});const t=e.split("\n").filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>" ".repeat(2*this.indent)+e);for(const s of r)this.content.push(s)}compile(){const e=Function,t=this?.args;return new e(...t,[...(this?.content??[""]).map(e=>` ${e}`)].join("\n"))}},Qe={major:4,minor:4,patch:3},Xe=p("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Qe;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const s of r)for(const t of s._zod.onattach)t(e);if(0===r.length)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const t=(e,t,n)=>{let r,s=R(e);for(const i of t){if(i._zod.def.when){if(Z(e))continue;if(!i._zod.def.when(e))continue}else if(s)continue;const t=e.issues.length,a=i._zod.check(e);if(a instanceof Promise&&!1===n?.async)throw new h;if(r||a instanceof Promise)r=(r??Promise.resolve()).then(async()=>{await a,e.issues.length!==t&&(s||(s=R(e,t)))});else{if(e.issues.length===t)continue;s||(s=R(e,t))}}return r?r.then(()=>e):e},n=(n,s,i)=>{if(R(n))return n.aborted=!0,n;const a=t(s,r,i);if(a instanceof Promise){if(!1===i.async)throw new h;return a.then(t=>e._zod.parse(t,i))}return e._zod.parse(a,i)};e._zod.run=(s,i)=>{if(i.skipChecks)return e._zod.parse(s,i);if("backward"===i.direction){const t=e._zod.parse({value:s.value,issues:[]},{...i,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,s,i)):n(t,s,i)}const a=e._zod.parse(s,i);if(a instanceof Promise){if(!1===i.async)throw new h;return a.then(e=>t(e,r,i))}return t(a,r,i)}}_(e,"~standard",()=>({validate:t=>{try{const n=K(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch(n){return X(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}))}),et=p("$ZodString",(e,t)=>{var n;Xe.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??(n=e._zod.bag,new RegExp(`^${n?`[\\s\\S]{${n?.minimum??0},${n?.maximum??""}}`:"[\\s\\S]*"}$`)),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch(r){}return"string"==typeof n.value||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),tt=p("$ZodStringFormat",(e,t)=>{qe.init(e,t),et.init(e,t)}),nt=p("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=me),tt.init(e,t)}),rt=p("$ZodUUID",(e,t)=>{if(t.version){const e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(void 0===e)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=ge(e))}else t.pattern??(t.pattern=ge());tt.init(e,t)}),st=p("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=be),tt.init(e,t)}),it=p("$ZodURL",(e,t)=>{tt.init(e,t),e._zod.check=n=>{try{const r=n.value.trim();if(!t.normalize&&t.protocol?.source===_e.source&&!/^https?:\/\//i.test(r))return void n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});const s=new URL(r);return t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(s.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(s.protocol.endsWith(":")?s.protocol.slice(0,-1):s.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),void(t.normalize?n.value=s.href:n.value=r)}catch(r){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),at=p("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),tt.init(e,t)}),ot=p("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=pe),tt.init(e,t)}),dt=p("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=de),tt.init(e,t)}),lt=p("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=le),tt.init(e,t)}),ct=p("$ZodULID",(e,t)=>{t.pattern??(t.pattern=ce),tt.init(e,t)}),ft=p("$ZodXID",(e,t)=>{t.pattern??(t.pattern=fe),tt.init(e,t)}),ut=p("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=ue),tt.init(e,t)}),pt=p("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=function(e){const t=Me({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${$e}T(?:${r})$`)}(t)),tt.init(e,t)}),ht=p("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Se),tt.init(e,t)}),mt=p("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=new RegExp(`^${Me(t)}$`)),tt.init(e,t)}),gt=p("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=he),tt.init(e,t)}),bt=p("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=ye),tt.init(e,t),e._zod.bag.format="ipv4"}),yt=p("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=ve),tt.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),vt=p("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=ke),tt.init(e,t)}),kt=p("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=we),tt.init(e,t),e._zod.check=n=>{const r=n.value.split("/");try{if(2!==r.length)throw new Error;const[e,t]=r;if(!t)throw new Error;const n=Number(t);if(`${n}`!==t)throw new Error;if(n<0||n>128)throw new Error;new URL(`http://[${e}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function wt(e){if(""===e)return!0;if(/\s/.test(e))return!1;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}var It=p("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Ie),tt.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{wt(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});var zt=p("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=ze),tt.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{(function(e){if(!ze.test(e))return!1;const t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return wt(t.padEnd(4*Math.ceil(t.length/4),"="))})(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),_t=p("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Oe),tt.init(e,t)});var Ot=p("$ZodJWT",(e,t)=>{tt.init(e,t),e._zod.check=n=>{(function(e,t=null){try{const n=e.split(".");if(3!==n.length)return!1;const[r]=n;if(!r)return!1;const s=JSON.parse(atob(r));return!("typ"in s&&"JWT"!==s?.typ||!s.alg||t&&(!("alg"in s)||s.alg!==t))}catch{return!1}})(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),$t=p("$ZodNumber",(e,t)=>{Xe.init(e,t),e._zod.pattern=e._zod.bag.pattern??je,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch(a){}const s=n.value;if("number"==typeof s&&!Number.isNaN(s)&&Number.isFinite(s))return n;const i="number"==typeof s?Number.isNaN(s)?"NaN":Number.isFinite(s)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:s,inst:e,...i?{received:i}:{}}),n}}),St=p("$ZodNumberFormat",(e,t)=>{Ze.init(e,t),$t.init(e,t)}),Mt=p("$ZodBoolean",(e,t)=>{Xe.init(e,t),e._zod.pattern=Ne,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Boolean(n.value)}catch(i){}const s=n.value;return"boolean"==typeof s||n.issues.push({expected:"boolean",code:"invalid_type",input:s,inst:e}),n}}),xt=p("$ZodUnknown",(e,t)=>{Xe.init(e,t),e._zod.parse=e=>e}),jt=p("$ZodNever",(e,t)=>{Xe.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)});function Nt(e,t,n){e.issues.length&&t.issues.push(...B(n,e.issues)),t.value[n]=e.value}var At=p("$ZodArray",(e,t)=>{Xe.init(e,t),e._zod.parse=(n,r)=>{const s=n.value;if(!Array.isArray(s))return n.issues.push({expected:"array",code:"invalid_type",input:s,inst:e}),n;n.value=Array(s.length);const i=[];for(let e=0;e<s.length;e++){const a=s[e],o=t.element._zod.run({value:a,issues:[]},r);o instanceof Promise?i.push(o.then(t=>Nt(t,n,e))):Nt(o,n,e)}return i.length?Promise.all(i).then(()=>n):n}});function Tt(e,t,n,r,s,i){const a=n in r;if(e.issues.length){if(s&&i&&!a)return;t.issues.push(...B(n,e.issues))}a||s?void 0===e.value?a&&(t.value[n]=void 0):t.value[n]=e.value:e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]})}function Et(e){const t=Object.keys(e.shape);for(const s of t)if(!e.shape?.[s]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${s}": expected a Zod schema`);const n=(r=e.shape,Object.keys(r).filter(e=>"optional"===r[e]._zod.optin&&"optional"===r[e]._zod.optout));var r;return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function Ct(e,t,n,r,s,i){const a=[],o=s.keySet,d=s.catchall._zod,l=d.def.type,c="optional"===d.optin,f="optional"===d.optout;for(const u in t){if("__proto__"===u)continue;if(o.has(u))continue;if("never"===l){a.push(u);continue}const s=d.run({value:t[u],issues:[]},r);s instanceof Promise?e.push(s.then(e=>Tt(e,n,u,t,c,f))):Tt(s,n,u,t,c,f)}return a.length&&n.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:i}),e.length?Promise.all(e).then(()=>n):n}var Pt=p("$ZodObject",(e,t)=>{if(Xe.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const e=t.shape;Object.defineProperty(t,"shape",{get:()=>{const n={...e};return Object.defineProperty(t,"shape",{value:n}),n}})}const n=k(()=>Et(t));_(e._zod,"propValues",()=>{const e=t.shape,n={};for(const t in e){const r=e[t]._zod;if(r.values){n[t]??(n[t]=new Set);for(const e of r.values)n[t].add(e)}}return n});const r=x,s=t.catchall;let i;e._zod.parse=(t,a)=>{i??(i=n.value);const o=t.value;if(!r(o))return t.issues.push({expected:"object",code:"invalid_type",input:o,inst:e}),t;t.value={};const d=[],l=i.shape;for(const e of i.keys){const n=l[e],r="optional"===n._zod.optin,s="optional"===n._zod.optout,i=n._zod.run({value:o[e],issues:[]},a);i instanceof Promise?d.push(i.then(n=>Tt(n,t,e,o,r,s))):Tt(i,t,e,o,r,s)}return s?Ct(d,o,t,a,n.value,e):d.length?Promise.all(d).then(()=>t):t}}),Dt=p("$ZodObjectJIT",(e,t)=>{Pt.init(e,t);const n=e._zod.parse,r=k(()=>Et(t));let s;const i=x,a=!g.jitless,o=a&&j.value,d=t.catchall;let l;e._zod.parse=(c,f)=>{l??(l=r.value);const u=c.value;return i(u)?a&&o&&!1===f?.async&&!0!==f.jitless?(s||(s=(e=>{const t=new Ke(["shape","payload","ctx"]),n=r.value,s=e=>{const t=S(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");const i=Object.create(null);let a=0;for(const r of n.keys)i[r]="key_"+a++;t.write("const newResult = {};");for(const r of n.keys){const n=i[r],a=S(r),o=e[r],d="optional"===o?._zod?.optin,l="optional"===o?._zod?.optout;t.write(`const ${n} = ${s(r)};`),d&&l?t.write(`\n if (${n}.issues.length) {\n if (${a} in input) {\n payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${a}, ...iss.path] : [${a}]\n })));\n }\n }\n \n if (${n}.value === undefined) {\n if (${a} in input) {\n newResult[${a}] = undefined;\n }\n } else {\n newResult[${a}] = ${n}.value;\n }\n \n `):d?t.write(`\n if (${n}.issues.length) {\n payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${a}, ...iss.path] : [${a}]\n })));\n }\n \n if (${n}.value === undefined) {\n if (${a} in input) {\n newResult[${a}] = undefined;\n }\n } else {\n newResult[${a}] = ${n}.value;\n }\n \n `):t.write(`\n const ${n}_present = ${a} in input;\n if (${n}.issues.length) {\n payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${a}, ...iss.path] : [${a}]\n })));\n }\n if (!${n}_present && !${n}.issues.length) {\n payload.issues.push({\n code: "invalid_type",\n expected: "nonoptional",\n input: undefined,\n path: [${a}]\n });\n }\n\n if (${n}_present) {\n if (${n}.value === undefined) {\n newResult[${a}] = undefined;\n } else {\n newResult[${a}] = ${n}.value;\n }\n }\n\n `)}t.write("payload.value = newResult;"),t.write("return payload;");const o=t.compile();return(t,n)=>o(e,t,n)})(t.shape)),c=s(c,f),d?Ct([],u,c,f,l,e):c):n(c,f):(c.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),c)}});function Rt(e,t,n,r){for(const i of e)if(0===i.issues.length)return t.value=i.value,t;const s=e.filter(e=>!R(e));return 1===s.length?(t.value=s[0].value,s[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>F(e,r,b())))}),t)}var Zt=p("$ZodUnion",(e,t)=>{Xe.init(e,t),_(e._zod,"optin",()=>t.options.some(e=>"optional"===e._zod.optin)?"optional":void 0),_(e._zod,"optout",()=>t.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),_(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),_(e._zod,"pattern",()=>{if(t.options.every(e=>e._zod.pattern)){const e=t.options.map(e=>e._zod.pattern);return new RegExp(`^(${e.map(e=>I(e.source)).join("|")})$`)}});const n=1===t.options.length?t.options[0]._zod.run:null;e._zod.parse=(r,s)=>{if(n)return n(r,s);let i=!1;const a=[];for(const e of t.options){const t=e._zod.run({value:r.value,issues:[]},s);if(t instanceof Promise)a.push(t),i=!0;else{if(0===t.issues.length)return t;a.push(t)}}return i?Promise.all(a).then(t=>Rt(t,r,e,s)):Rt(a,r,e,s)}}),Bt=p("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Zt.init(e,t);const n=e._zod.parse;_(e._zod,"propValues",()=>{const e={};for(const n of t.options){const r=n._zod.propValues;if(!r||0===Object.keys(r).length)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(n)}"`);for(const[t,n]of Object.entries(r)){e[t]||(e[t]=new Set);for(const r of n)e[t].add(r)}}return e});const r=k(()=>{const e=t.options,n=new Map;for(const r of e){const e=r._zod.propValues?.[t.discriminator];if(!e||0===e.size)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(const t of e){if(n.has(t))throw new Error(`Duplicate discriminator value "${String(t)}"`);n.set(t,r)}}return n});e._zod.parse=(s,i)=>{const a=s.value;if(!x(a))return s.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),s;const o=r.value.get(a?.[t.discriminator]);return o?o._zod.run(s,i):t.unionFallback||"backward"===i.direction?n(s,i):(s.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(r.value.keys()),input:a,path:[t.discriminator],inst:e}),s)}}),Lt=p("$ZodIntersection",(e,t)=>{Xe.init(e,t),e._zod.parse=(e,n)=>{const r=e.value,s=t.left._zod.run({value:r,issues:[]},n),i=t.right._zod.run({value:r,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([t,n])=>qt(e,t,n)):qt(e,s,i)}});function Ft(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(N(e)&&N(t)){const n=Object.keys(t),r=Object.keys(e).filter(e=>-1!==n.indexOf(e)),s={...e,...t};for(const i of r){const n=Ft(e[i],t[i]);if(!n.valid)return{valid:!1,mergeErrorPath:[i,...n.mergeErrorPath]};s[i]=n.data}return{valid:!0,data:s}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<e.length;r++){const s=Ft(e[r],t[r]);if(!s.valid)return{valid:!1,mergeErrorPath:[r,...s.mergeErrorPath]};n.push(s.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function qt(e,t,n){const r=new Map;let s;for(const o of t.issues)if("unrecognized_keys"===o.code){s??(s=o);for(const e of o.keys)r.has(e)||r.set(e,{}),r.get(e).l=!0}else e.issues.push(o);for(const o of n.issues)if("unrecognized_keys"===o.code)for(const e of o.keys)r.has(e)||r.set(e,{}),r.get(e).r=!0;else e.issues.push(o);const i=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(i.length&&s&&e.issues.push({...s,keys:i}),R(e))return e;const a=Ft(t.value,n.value);if(!a.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(a.mergeErrorPath)}`);return e.value=a.data,e}var Gt=p("$ZodRecord",(e,t)=>{Xe.init(e,t),e._zod.parse=(n,r)=>{const s=n.value;if(!N(s))return n.issues.push({expected:"record",code:"invalid_type",input:s,inst:e}),n;const i=[],a=t.keyType._zod.values;if(a){n.value={};const o=new Set;for(const l of a)if("string"==typeof l||"number"==typeof l||"symbol"==typeof l){o.add("number"==typeof l?l.toString():l);const a=t.keyType._zod.run({value:l,issues:[]},r);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:a.issues.map(e=>F(e,r,b())),input:l,path:[l],inst:e});continue}const d=a.value,c=t.valueType._zod.run({value:s[l],issues:[]},r);c instanceof Promise?i.push(c.then(e=>{e.issues.length&&n.issues.push(...B(l,e.issues)),n.value[d]=e.value})):(c.issues.length&&n.issues.push(...B(l,c.issues)),n.value[d]=c.value)}let d;for(const e in s)o.has(e)||(d=d??[],d.push(e));d&&d.length>0&&n.issues.push({code:"unrecognized_keys",input:s,inst:e,keys:d})}else{n.value={};for(const a of Reflect.ownKeys(s)){if("__proto__"===a)continue;if(!Object.prototype.propertyIsEnumerable.call(s,a))continue;let o=t.keyType._zod.run({value:a,issues:[]},r);if(o instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if("string"==typeof a&&je.test(a)&&o.issues.length){const e=t.keyType._zod.run({value:Number(a),issues:[]},r);if(e instanceof Promise)throw new Error("Async schemas not supported in object keys currently");0===e.issues.length&&(o=e)}if(o.issues.length){"loose"===t.mode?n.value[a]=s[a]:n.issues.push({code:"invalid_key",origin:"record",issues:o.issues.map(e=>F(e,r,b())),input:a,path:[a],inst:e});continue}const d=t.valueType._zod.run({value:s[a],issues:[]},r);d instanceof Promise?i.push(d.then(e=>{e.issues.length&&n.issues.push(...B(a,e.issues)),n.value[o.value]=e.value})):(d.issues.length&&n.issues.push(...B(a,d.issues)),n.value[o.value]=d.value)}}return i.length?Promise.all(i).then(()=>n):n}}),Jt=p("$ZodEnum",(e,t)=>{Xe.init(e,t);const n=y(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(e=>T.has(typeof e)).map(e=>"string"==typeof e?E(e):e.toString()).join("|")})$`),e._zod.parse=(t,s)=>{const i=t.value;return r.has(i)||t.issues.push({code:"invalid_value",values:n,input:i,inst:e}),t}}),Ut=p("$ZodLiteral",(e,t)=>{if(Xe.init(e,t),0===t.values.length)throw new Error("Cannot create literal schema with no valid values");const n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map(e=>"string"==typeof e?E(e):e?E(e.toString()):String(e)).join("|")})$`),e._zod.parse=(r,s)=>{const i=r.value;return n.has(i)||r.issues.push({code:"invalid_value",values:t.values,input:i,inst:e}),r}}),Ht=p("$ZodTransform",(e,t)=>{Xe.init(e,t),e._zod.optin="optional",e._zod.parse=(n,r)=>{if("backward"===r.direction)throw new m(e.constructor.name);const s=t.transform(n.value,n);if(r.async)return(s instanceof Promise?s:Promise.resolve(s)).then(e=>(n.value=e,n.fallback=!0,n));if(s instanceof Promise)throw new h;return n.value=s,n.fallback=!0,n}});function Vt(e,t){return void 0===t&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}var Wt=p("$ZodOptional",(e,t)=>{Xe.init(e,t),e._zod.optin="optional",e._zod.optout="optional",_(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),_(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${I(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if("optional"===t.innerType._zod.optin){const r=e.value,s=t.innerType._zod.run(e,n);return s instanceof Promise?s.then(e=>Vt(e,r)):Vt(s,r)}return void 0===e.value?e:t.innerType._zod.run(e,n)}}),Yt=p("$ZodExactOptional",(e,t)=>{Wt.init(e,t),_(e._zod,"values",()=>t.innerType._zod.values),_(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),Kt=p("$ZodNullable",(e,t)=>{Xe.init(e,t),_(e._zod,"optin",()=>t.innerType._zod.optin),_(e._zod,"optout",()=>t.innerType._zod.optout),_(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${I(e.source)}|null)$`):void 0}),_(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>null===e.value?e:t.innerType._zod.run(e,n)}),Qt=p("$ZodDefault",(e,t)=>{Xe.init(e,t),e._zod.optin="optional",_(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);if(void 0===e.value)return e.value=t.defaultValue,e;const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>Xt(e,t)):Xt(r,t)}});function Xt(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}var en=p("$ZodPrefault",(e,t)=>{Xe.init(e,t),e._zod.optin="optional",_(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>("backward"===n.direction||void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),tn=p("$ZodNonOptional",(e,t)=>{Xe.init(e,t),_(e._zod,"values",()=>{const e=t.innerType._zod.values;return e?new Set([...e].filter(e=>void 0!==e)):void 0}),e._zod.parse=(n,r)=>{const s=t.innerType._zod.run(n,r);return s instanceof Promise?s.then(t=>nn(t,e)):nn(s,e)}});function nn(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}var rn=p("$ZodCatch",(e,t)=>{Xe.init(e,t),e._zod.optin="optional",_(e._zod,"optout",()=>t.innerType._zod.optout),_(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>F(e,n,b()))},input:e.value}),e.issues=[],e.fallback=!0),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>F(e,n,b()))},input:e.value}),e.issues=[],e.fallback=!0),e)}}),sn=p("$ZodPipe",(e,t)=>{Xe.init(e,t),_(e._zod,"values",()=>t.in._zod.values),_(e._zod,"optin",()=>t.in._zod.optin),_(e._zod,"optout",()=>t.out._zod.optout),_(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if("backward"===n.direction){const r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>an(e,t.in,n)):an(r,t.in,n)}const r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>an(e,t.out,n)):an(r,t.out,n)}});function an(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}var on=p("$ZodReadonly",(e,t)=>{Xe.init(e,t),_(e._zod,"propValues",()=>t.innerType._zod.propValues),_(e._zod,"values",()=>t.innerType._zod.values),_(e._zod,"optin",()=>t.innerType?._zod?.optin),_(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(dn):dn(r)}});function dn(e){return e.value=Object.freeze(e.value),e}var ln,cn=p("$ZodCustom",(e,t)=>{Ee.init(e,t),Xe.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{const r=n.value,s=t.fn(r);if(s instanceof Promise)return s.then(t=>fn(t,n,r,e));fn(s,n,r,e)}});function fn(e,t,n,r){if(!e){const e={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(G(e))}}var un=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){const n=t[0];return this._map.set(e,n),n&&"object"==typeof n&&"id"in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const n={...this.get(t)??{}};delete n.id;const r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};(ln=globalThis).__zod_globalRegistry??(ln.__zod_globalRegistry=new un);var pn=globalThis.__zod_globalRegistry;function hn(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...P(t)})}function mn(e,t){return new Pe({check:"less_than",...P(t),value:e,inclusive:!1})}function gn(e,t){return new Pe({check:"less_than",...P(t),value:e,inclusive:!0})}function bn(e,t){return new De({check:"greater_than",...P(t),value:e,inclusive:!1})}function yn(e,t){return new De({check:"greater_than",...P(t),value:e,inclusive:!0})}function vn(e,t){return new Re({check:"multiple_of",...P(t),value:e})}function kn(e,t){return new Be({check:"max_length",...P(t),maximum:e})}function wn(e,t){return new Le({check:"min_length",...P(t),minimum:e})}function In(e,t){return new Fe({check:"length_equals",...P(t),length:e})}function zn(e){return new Ye({check:"overwrite",tx:e})}function _n(e,t){const n=new Ee({check:"custom",...P(t)});return n._zod.check=e,n}function On(e){let t=e?.target??"draft-2020-12";return"draft-4"===t&&(t="draft-04"),"draft-7"===t&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??pn,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function $n(e,t,n={path:[],schemaPath:[]}){var r;const s=e._zod.def,i=t.seen.get(e);if(i)return i.count++,n.schemaPath.includes(e)&&(i.cycle=n.path),i.schema;const a={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,a);const o=e._zod.toJSONSchema?.();if(o)a.schema=o;else{const r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,a.schema,r);else{const n=a.schema,i=t.processors[s.type];if(!i)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${s.type}`);i(e,t,n,r)}const i=e._zod.parent;i&&(a.ref||(a.ref=i),$n(i,t,r),t.seen.get(i).isParent=!0)}const d=t.metadataRegistry.get(e);return d&&Object.assign(a.schema,d),"input"===t.io&&xn(e)&&(delete a.schema.examples,delete a.schema.default),"input"===t.io&&"_prefault"in a.schema&&((r=a.schema).default??(r.default=a.schema._prefault)),delete a.schema._prefault,t.seen.get(e).schema}function Sn(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=new Map;for(const i of e.seen.entries()){const t=e.metadataRegistry.get(i[0])?.id;if(t){const e=r.get(t);if(e&&e!==i[0])throw new Error(`Duplicate schema id "${t}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(t,i[0])}}const s=t=>{if(t[1].schema.$ref)return;const r=t[1],{ref:s,defId:i}=(t=>{const r="draft-2020-12"===e.target?"$defs":"definitions";if(e.external){const n=e.external.registry.get(t[0])?.id,s=e.external.uri??(e=>e);if(n)return{ref:s(n)};const i=t[1].defId??t[1].schema.id??"schema"+e.counter++;return t[1].defId=i,{defId:i,ref:`${s("__shared")}#/${r}/${i}`}}if(t[1]===n)return{ref:"#"};const s=`#/${r}/`,i=t[1].schema.id??"__schema"+e.counter++;return{defId:i,ref:s+i}})(t);r.def={...r.schema},i&&(r.defId=i);const a=r.schema;for(const e in a)delete a[e];a.$ref=s};if("throw"===e.cycles)for(const i of e.seen.entries()){const e=i[1];if(e.cycle)throw new Error(`Cycle detected: #/${e.cycle?.join("/")}/<root>\n\nSet the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const i of e.seen.entries()){const n=i[1];if(t!==i[0]){if(e.external){const n=e.external.registry.get(i[0])?.id;if(t!==i[0]&&n){s(i);continue}}(e.metadataRegistry.get(i[0])?.id||n.cycle||n.count>1&&"ref"===e.reused)&&s(i)}else s(i)}}function Mn(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=t=>{const n=e.seen.get(t);if(null===n.ref)return;const s=n.def??n.schema,i={...s},a=n.ref;if(n.ref=null,a){r(a);const n=e.seen.get(a),o=n.schema;if(!o.$ref||"draft-07"!==e.target&&"draft-04"!==e.target&&"openapi-3.0"!==e.target?Object.assign(s,o):(s.allOf=s.allOf??[],s.allOf.push(o)),Object.assign(s,i),t._zod.parent===a)for(const e in s)"$ref"!==e&&"allOf"!==e&&(e in i||delete s[e]);if(o.$ref&&n.def)for(const e in s)"$ref"!==e&&"allOf"!==e&&e in n.def&&JSON.stringify(s[e])===JSON.stringify(n.def[e])&&delete s[e]}const o=t._zod.parent;if(o&&o!==a){r(o);const t=e.seen.get(o);if(t?.schema.$ref&&(s.$ref=t.schema.$ref,t.def))for(const e in s)"$ref"!==e&&"allOf"!==e&&e in t.def&&JSON.stringify(s[e])===JSON.stringify(t.def[e])&&delete s[e]}e.override({zodSchema:t,jsonSchema:s,path:n.path??[]})};for(const d of[...e.seen.entries()].reverse())r(d[0]);const s={};if("draft-2020-12"===e.target?s.$schema="https://json-schema.org/draft/2020-12/schema":"draft-07"===e.target?s.$schema="http://json-schema.org/draft-07/schema#":"draft-04"===e.target?s.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const n=e.external.registry.get(t)?.id;if(!n)throw new Error("Schema is missing an `id` property");s.$id=e.external.uri(n)}Object.assign(s,n.def??n.schema);const i=e.metadataRegistry.get(t)?.id;void 0!==i&&s.id===i&&delete s.id;const a=e.external?.defs??{};for(const d of e.seen.entries()){const e=d[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,a[e.defId]=e.def)}e.external||Object.keys(a).length>0&&("draft-2020-12"===e.target?s.$defs=a:s.definitions=a);try{const n=JSON.parse(JSON.stringify(s));return Object.defineProperty(n,"~standard",{value:{...t["~standard"],jsonSchema:{input:jn(t,"input",e.processors),output:jn(t,"output",e.processors)}},enumerable:!1,writable:!1}),n}catch(o){throw new Error("Error converting schema to JSON.")}}function xn(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const r=e._zod.def;if("transform"===r.type)return!0;if("array"===r.type)return xn(r.element,n);if("set"===r.type)return xn(r.valueType,n);if("lazy"===r.type)return xn(r.getter(),n);if("promise"===r.type||"optional"===r.type||"nonoptional"===r.type||"nullable"===r.type||"readonly"===r.type||"default"===r.type||"prefault"===r.type)return xn(r.innerType,n);if("intersection"===r.type)return xn(r.left,n)||xn(r.right,n);if("record"===r.type||"map"===r.type)return xn(r.keyType,n)||xn(r.valueType,n);if("pipe"===r.type)return!!e._zod.traits.has("$ZodCodec")||(xn(r.in,n)||xn(r.out,n));if("object"===r.type){for(const e in r.shape)if(xn(r.shape[e],n))return!0;return!1}if("union"===r.type){for(const e of r.options)if(xn(e,n))return!0;return!1}if("tuple"===r.type){for(const e of r.items)if(xn(e,n))return!0;return!(!r.rest||!xn(r.rest,n))}return!1}var jn=(e,t,n={})=>r=>{const{libraryOptions:s,target:i}=r??{},a=On({...s??{},target:i,io:t,processors:n});return $n(e,a),Sn(a,e),Mn(a,e)},Nn={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},An=(e,t,n,r)=>{const s=e._zod.def;$n(s.innerType,t,r);t.seen.get(e).ref=s.innerType},Tn=p("ZodISODateTime",(e,t)=>{pt.init(e,t),or.init(e,t)});function En(e){return function(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...P(t)})}(Tn,e)}var Cn=p("ZodISODate",(e,t)=>{ht.init(e,t),or.init(e,t)});function Pn(e){return function(e,t){return new e({type:"string",format:"date",check:"string_format",...P(t)})}(Cn,e)}var Dn=p("ZodISOTime",(e,t)=>{mt.init(e,t),or.init(e,t)});function Rn(e){return function(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...P(t)})}(Dn,e)}var Zn=p("ZodISODuration",(e,t)=>{gt.init(e,t),or.init(e,t)});function Bn(e){return function(e,t){return new e({type:"string",format:"duration",check:"string_format",...P(t)})}(Zn,e)}var Ln=(e,t)=>{U.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:t=>function(e,t=e=>e.message){const n={_errors:[]},r=(e,s=[])=>{for(const i of e.issues)if("invalid_union"===i.code&&i.errors.length)i.errors.map(e=>r({issues:e},[...s,...i.path]));else if("invalid_key"===i.code)r({issues:i.issues},[...s,...i.path]);else if("invalid_element"===i.code)r({issues:i.issues},[...s,...i.path]);else{const e=[...s,...i.path];if(0===e.length)n._errors.push(t(i));else{let r=n,s=0;for(;s<e.length;){const n=e[s];s!==e.length-1?r[n]=r[n]||{_errors:[]}:(r[n]=r[n]||{_errors:[]},r[n]._errors.push(t(i))),r=r[n],s++}}}};return r(e),n}(e,t)},flatten:{value:t=>function(e,t=e=>e.message){const n={},r=[];for(const s of e.issues)s.path.length>0?(n[s.path[0]]=n[s.path[0]]||[],n[s.path[0]].push(t(s))):r.push(t(s));return{formErrors:r,fieldErrors:n}}(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,v,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,v,2)}},isEmpty:{get:()=>0===e.issues.length}})},Fn=p("ZodError",Ln,{Parent:Error}),qn=V(Fn),Gn=W(Fn),Jn=Y(Fn),Un=Q(Fn),Hn=ee(Fn),Vn=te(Fn),Wn=ne(Fn),Yn=re(Fn),Kn=se(Fn),Qn=ie(Fn),Xn=ae(Fn),er=oe(Fn),tr=new WeakMap;function nr(e,t,n){const r=Object.getPrototypeOf(e);let s=tr.get(r);if(s||(s=new Set,tr.set(r,s)),!s.has(t)){s.add(t);for(const e in n){const t=n[e];Object.defineProperty(r,e,{configurable:!0,enumerable:!1,get(){const n=t.bind(this);return Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:n}),n},set(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t})}})}}}var rr=p("ZodType",(e,t)=>(Xe.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:jn(e,"input"),output:jn(e,"output")}}),e.toJSONSchema=((e,t={})=>n=>{const r=On({...n,processors:t});return $n(e,r),Sn(r,e),Mn(r,e)})(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(t,n)=>qn(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Jn(e,t,n),e.parseAsync=async(t,n)=>Gn(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Un(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>Hn(e,t,n),e.decode=(t,n)=>Vn(e,t,n),e.encodeAsync=async(t,n)=>Wn(e,t,n),e.decodeAsync=async(t,n)=>Yn(e,t,n),e.safeEncode=(t,n)=>Kn(e,t,n),e.safeDecode=(t,n)=>Qn(e,t,n),e.safeEncodeAsync=async(t,n)=>Xn(e,t,n),e.safeDecodeAsync=async(t,n)=>er(e,t,n),nr(e,"ZodType",{check(...e){const t=this.def;return this.clone($(t,{checks:[...t.checks??[],...e.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return C(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(function(e,t={}){return function(e,t,n){return new e({type:"custom",check:"custom",fn:t,...P(n)})}(fs,e,t)}(e,t))},superRefine(e,t){return this.check(function(e,t){return function(e,t){const n=_n(t=>(t.addIssue=e=>{if("string"==typeof e)t.issues.push(G(e,t.value,n._zod.def));else{const r=e;r.fatal&&(r.continue=!1),r.code??(r.code="custom"),r.input??(r.input=t.value),r.inst??(r.inst=n),r.continue??(r.continue=!n._zod.def.abort),t.issues.push(G(r))}},e(t.value,t)),t);return n}(e,t)}(e,t))},overwrite(e){return this.check(zn(e))},optional(){return es(this)},exactOptional(){return new ts({type:"optional",innerType:this})},nullable(){return rs(this)},nullish(){return es(rs(this))},nonoptional(e){return function(e,t){return new as({type:"nonoptional",innerType:e,...P(t)})}(this,e)},array(){return Rr(this)},or(e){return qr([this,e])},and(e){return new Jr({type:"intersection",left:this,right:e})},transform(e){return ls(this,new Qr({type:"transform",transform:e}))},default(e){return t=e,new ss({type:"default",innerType:this,get defaultValue(){return"function"==typeof t?t():A(t)}});var t},prefault(e){return t=e,new is({type:"prefault",innerType:this,get defaultValue(){return"function"==typeof t?t():A(t)}});var t},catch(e){return new os({type:"catch",innerType:this,catchValue:"function"==typeof(t=e)?t:()=>t});var t},pipe(e){return ls(this,e)},readonly(){return new cs({type:"readonly",innerType:this})},describe(e){const t=this.clone();return pn.add(t,{description:e}),t},meta(...e){if(0===e.length)return pn.get(this);const t=this.clone();return pn.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e){return e(this)}}),Object.defineProperty(e,"description",{get:()=>pn.get(e)?.description,configurable:!0}),e)),sr=p("_ZodString",(e,t)=>{et.init(e,t),rr.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=n;r.type="string";const{minimum:s,maximum:i,format:a,patterns:o,contentEncoding:d}=e._zod.bag;if("number"==typeof s&&(r.minLength=s),"number"==typeof i&&(r.maxLength=i),a&&(r.format=Nn[a]??a,""===r.format&&delete r.format,"time"===a&&delete r.format),d&&(r.contentEncoding=d),o&&o.size>0){const e=[...o];1===e.length?r.pattern=e[0].source:e.length>1&&(r.allOf=[...e.map(e=>({..."draft-07"===t.target||"draft-04"===t.target||"openapi-3.0"===t.target?{type:"string"}:{},pattern:e.source}))])}})(e,t,n);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,nr(e,"_ZodString",{regex(...e){return this.check(function(e,t){return new Ge({check:"string_format",format:"regex",...P(t),pattern:e})}(...e))},includes(...e){return this.check(function(e,t){return new He({check:"string_format",format:"includes",...P(t),includes:e})}(...e))},startsWith(...e){return this.check(function(e,t){return new Ve({check:"string_format",format:"starts_with",...P(t),prefix:e})}(...e))},endsWith(...e){return this.check(function(e,t){return new We({check:"string_format",format:"ends_with",...P(t),suffix:e})}(...e))},min(...e){return this.check(wn(...e))},max(...e){return this.check(kn(...e))},length(...e){return this.check(In(...e))},nonempty(...e){return this.check(wn(1,...e))},lowercase(e){return this.check(function(e){return new Je({check:"string_format",format:"lowercase",...P(e)})}(e))},uppercase(e){return this.check(function(e){return new Ue({check:"string_format",format:"uppercase",...P(e)})}(e))},trim(){return this.check(zn(e=>e.trim()))},normalize(...e){return this.check(function(e){return zn(t=>t.normalize(e))}(...e))},toLowerCase(){return this.check(zn(e=>e.toLowerCase()))},toUpperCase(){return this.check(zn(e=>e.toUpperCase()))},slugify(){return this.check(zn(e=>function(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}(e)))}})}),ir=p("ZodString",(e,t)=>{et.init(e,t),sr.init(e,t),e.email=t=>e.check(function(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...P(t)})}(dr,t)),e.url=t=>e.check(function(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...P(t)})}(fr,t)),e.jwt=t=>e.check(function(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...P(t)})}($r,t)),e.emoji=t=>e.check(function(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...P(t)})}(ur,t)),e.guid=t=>e.check(hn(lr,t)),e.uuid=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...P(t)})}(cr,t)),e.uuidv4=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...P(t)})}(cr,t)),e.uuidv6=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...P(t)})}(cr,t)),e.uuidv7=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...P(t)})}(cr,t)),e.nanoid=t=>e.check(function(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...P(t)})}(pr,t)),e.guid=t=>e.check(hn(lr,t)),e.cuid=t=>e.check(function(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...P(t)})}(hr,t)),e.cuid2=t=>e.check(function(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...P(t)})}(mr,t)),e.ulid=t=>e.check(function(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...P(t)})}(gr,t)),e.base64=t=>e.check(function(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...P(t)})}(zr,t)),e.base64url=t=>e.check(function(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...P(t)})}(_r,t)),e.xid=t=>e.check(function(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...P(t)})}(br,t)),e.ksuid=t=>e.check(function(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...P(t)})}(yr,t)),e.ipv4=t=>e.check(function(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...P(t)})}(vr,t)),e.ipv6=t=>e.check(function(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...P(t)})}(kr,t)),e.cidrv4=t=>e.check(function(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...P(t)})}(wr,t)),e.cidrv6=t=>e.check(function(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...P(t)})}(Ir,t)),e.e164=t=>e.check(function(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...P(t)})}(Or,t)),e.datetime=t=>e.check(En(t)),e.date=t=>e.check(Pn(t)),e.time=t=>e.check(Rn(t)),e.duration=t=>e.check(Bn(t))});function ar(e){return function(e,t){return new e({type:"string",...P(t)})}(ir,e)}var or=p("ZodStringFormat",(e,t)=>{tt.init(e,t),sr.init(e,t)}),dr=p("ZodEmail",(e,t)=>{st.init(e,t),or.init(e,t)}),lr=p("ZodGUID",(e,t)=>{nt.init(e,t),or.init(e,t)}),cr=p("ZodUUID",(e,t)=>{rt.init(e,t),or.init(e,t)}),fr=p("ZodURL",(e,t)=>{it.init(e,t),or.init(e,t)}),ur=p("ZodEmoji",(e,t)=>{at.init(e,t),or.init(e,t)}),pr=p("ZodNanoID",(e,t)=>{ot.init(e,t),or.init(e,t)}),hr=p("ZodCUID",(e,t)=>{dt.init(e,t),or.init(e,t)}),mr=p("ZodCUID2",(e,t)=>{lt.init(e,t),or.init(e,t)}),gr=p("ZodULID",(e,t)=>{ct.init(e,t),or.init(e,t)}),br=p("ZodXID",(e,t)=>{ft.init(e,t),or.init(e,t)}),yr=p("ZodKSUID",(e,t)=>{ut.init(e,t),or.init(e,t)}),vr=p("ZodIPv4",(e,t)=>{bt.init(e,t),or.init(e,t)}),kr=p("ZodIPv6",(e,t)=>{yt.init(e,t),or.init(e,t)}),wr=p("ZodCIDRv4",(e,t)=>{vt.init(e,t),or.init(e,t)}),Ir=p("ZodCIDRv6",(e,t)=>{kt.init(e,t),or.init(e,t)}),zr=p("ZodBase64",(e,t)=>{It.init(e,t),or.init(e,t)}),_r=p("ZodBase64URL",(e,t)=>{zt.init(e,t),or.init(e,t)}),Or=p("ZodE164",(e,t)=>{_t.init(e,t),or.init(e,t)}),$r=p("ZodJWT",(e,t)=>{Ot.init(e,t),or.init(e,t)}),Sr=p("ZodNumber",(e,t)=>{$t.init(e,t),rr.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=n,{minimum:s,maximum:i,format:a,multipleOf:o,exclusiveMaximum:d,exclusiveMinimum:l}=e._zod.bag;"string"==typeof a&&a.includes("int")?r.type="integer":r.type="number";const c="number"==typeof l&&l>=(s??Number.NEGATIVE_INFINITY),f="number"==typeof d&&d<=(i??Number.POSITIVE_INFINITY),u="draft-04"===t.target||"openapi-3.0"===t.target;c?u?(r.minimum=l,r.exclusiveMinimum=!0):r.exclusiveMinimum=l:"number"==typeof s&&(r.minimum=s),f?u?(r.maximum=d,r.exclusiveMaximum=!0):r.exclusiveMaximum=d:"number"==typeof i&&(r.maximum=i),"number"==typeof o&&(r.multipleOf=o)})(e,t,n),nr(e,"ZodNumber",{gt(e,t){return this.check(bn(e,t))},gte(e,t){return this.check(yn(e,t))},min(e,t){return this.check(yn(e,t))},lt(e,t){return this.check(mn(e,t))},lte(e,t){return this.check(gn(e,t))},max(e,t){return this.check(gn(e,t))},int(e){return this.check(jr(e))},safe(e){return this.check(jr(e))},positive(e){return this.check(bn(0,e))},nonnegative(e){return this.check(yn(0,e))},negative(e){return this.check(mn(0,e))},nonpositive(e){return this.check(gn(0,e))},multipleOf(e,t){return this.check(vn(e,t))},step(e,t){return this.check(vn(e,t))},finite(){return this}});const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function Mr(e){return function(e,t){return new e({type:"number",checks:[],...P(t)})}(Sr,e)}var xr=p("ZodNumberFormat",(e,t)=>{St.init(e,t),Sr.init(e,t)});function jr(e){return function(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...P(t)})}(xr,e)}var Nr=p("ZodBoolean",(e,t)=>{Mt.init(e,t),rr.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.type="boolean"})(0,0,t)});function Ar(e){return function(e,t){return new e({type:"boolean",...P(t)})}(Nr,e)}var Tr=p("ZodUnknown",(e,t)=>{xt.init(e,t),rr.init(e,t),e._zod.processJSONSchema=(e,t,n)=>{}});function Er(){return new Tr({type:"unknown"})}var Cr=p("ZodNever",(e,t)=>{jt.init(e,t),rr.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.not={}})(0,0,t)});function Pr(e){return function(e,t){return new e({type:"never",...P(t)})}(Cr,e)}var Dr=p("ZodArray",(e,t)=>{At.init(e,t),rr.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const s=n,i=e._zod.def,{minimum:a,maximum:o}=e._zod.bag;"number"==typeof a&&(s.minItems=a),"number"==typeof o&&(s.maxItems=o),s.type="array",s.items=$n(i.element,t,{...r,path:[...r.path,"items"]})})(e,t,n,r),e.element=t.element,nr(e,"ZodArray",{min(e,t){return this.check(wn(e,t))},nonempty(e){return this.check(wn(1,e))},max(e,t){return this.check(kn(e,t))},length(e,t){return this.check(In(e,t))},unwrap(){return this.element}})});function Rr(e,t){return function(e,t,n){return new e({type:"array",element:t,...P(n)})}(Dr,e,t)}var Zr=p("ZodObject",(e,t)=>{Dt.init(e,t),rr.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const s=n,i=e._zod.def;s.type="object",s.properties={};const a=i.shape;for(const l in a)s.properties[l]=$n(a[l],t,{...r,path:[...r.path,"properties",l]});const o=new Set(Object.keys(a)),d=new Set([...o].filter(e=>{const n=i.shape[e]._zod;return"input"===t.io?void 0===n.optin:void 0===n.optout}));d.size>0&&(s.required=Array.from(d)),"never"===i.catchall?._zod.def.type?s.additionalProperties=!1:i.catchall?i.catchall&&(s.additionalProperties=$n(i.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):"output"===t.io&&(s.additionalProperties=!1)})(e,t,n,r),_(e,"shape",()=>t.shape),nr(e,"ZodObject",{keyof(){return Wr(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:Er()})},loose(){return this.clone({...this._zod.def,catchall:Er()})},strict(){return this.clone({...this._zod.def,catchall:Pr()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return function(e,t){if(!N(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const n=e._zod.def.shape;for(const e in t)if(void 0!==Object.getOwnPropertyDescriptor(n,e))throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return C(e,$(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return O(this,"shape",n),n}}))}(this,e)},safeExtend(e){return function(e,t){if(!N(t))throw new Error("Invalid input to safeExtend: expected a plain object");return C(e,$(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return O(this,"shape",n),n}}))}(this,e)},merge(e){return function(e,t){if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");return C(e,$(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return O(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}(this,e)},pick(e){return function(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");return C(e,$(e._zod.def,{get shape(){const e={};for(const r in t){if(!(r in n.shape))throw new Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return O(this,"shape",e),e},checks:[]}))}(this,e)},omit(e){return function(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");return C(e,$(e._zod.def,{get shape(){const r={...e._zod.def.shape};for(const e in t){if(!(e in n.shape))throw new Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return O(this,"shape",r),r},checks:[]}))}(this,e)},partial(...e){return function(e,t,n){const r=t._zod.def.checks;if(r&&r.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");return C(t,$(t._zod.def,{get shape(){const r=t._zod.def.shape,s={...r};if(n)for(const t in n){if(!(t in r))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(s[t]=e?new e({type:"optional",innerType:r[t]}):r[t])}else for(const t in r)s[t]=e?new e({type:"optional",innerType:r[t]}):r[t];return O(this,"shape",s),s},checks:[]}))}(Xr,this,e[0])},required(...e){return t=as,n=this,r=e[0],C(n,$(n._zod.def,{get shape(){const e=n._zod.def.shape,s={...e};if(r)for(const n in r){if(!(n in s))throw new Error(`Unrecognized key: "${n}"`);r[n]&&(s[n]=new t({type:"nonoptional",innerType:e[n]}))}else for(const n in e)s[n]=new t({type:"nonoptional",innerType:e[n]});return O(this,"shape",s),s}}));var t,n,r}})});function Br(e,t){return new Zr({type:"object",shape:e??{},...P(t)})}function Lr(e,t){return new Zr({type:"object",shape:e,catchall:Pr(),...P(t)})}var Fr=p("ZodUnion",(e,t)=>{Zt.init(e,t),rr.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const s=e._zod.def,i=!1===s.inclusive,a=s.options.map((e,n)=>$n(e,t,{...r,path:[...r.path,i?"oneOf":"anyOf",n]}));i?n.oneOf=a:n.anyOf=a})(e,t,n,r),e.options=t.options});function qr(e,t){return new Fr({type:"union",options:e,...P(t)})}var Gr=p("ZodDiscriminatedUnion",(e,t)=>{Fr.init(e,t),Bt.init(e,t)});var Jr=p("ZodIntersection",(e,t)=>{Lt.init(e,t),rr.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const s=e._zod.def,i=$n(s.left,t,{...r,path:[...r.path,"allOf",0]}),a=$n(s.right,t,{...r,path:[...r.path,"allOf",1]}),o=e=>"allOf"in e&&1===Object.keys(e).length;n.allOf=[...o(i)?i.allOf:[i],...o(a)?a.allOf:[a]]})(e,t,n,r)});var Ur=p("ZodRecord",(e,t)=>{Gt.init(e,t),rr.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const s=n,i=e._zod.def;s.type="object";const a=i.keyType,o=a._zod.bag?.patterns;if("loose"===i.mode&&o&&o.size>0){const e=$n(i.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});s.patternProperties={};for(const t of o)s.patternProperties[t.source]=e}else"draft-07"!==t.target&&"draft-2020-12"!==t.target||(s.propertyNames=$n(i.keyType,t,{...r,path:[...r.path,"propertyNames"]})),s.additionalProperties=$n(i.valueType,t,{...r,path:[...r.path,"additionalProperties"]});const d=a._zod.values;if(d){const e=[...d].filter(e=>"string"==typeof e||"number"==typeof e);e.length>0&&(s.required=e)}})(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function Hr(e,t,n){return t&&t._zod?new Ur({type:"record",keyType:e,valueType:t,...P(n)}):new Ur({type:"record",keyType:ar(),valueType:e,...P(t)})}var Vr=p("ZodEnum",(e,t)=>{Jt.init(e,t),rr.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=y(e._zod.def.entries);r.every(e=>"number"==typeof e)&&(n.type="number"),r.every(e=>"string"==typeof e)&&(n.type="string"),n.enum=r})(e,0,n),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{const s={};for(const i of e){if(!n.has(i))throw new Error(`Key ${i} not found in enum`);s[i]=t.entries[i]}return new Vr({...t,checks:[],...P(r),entries:s})},e.exclude=(e,r)=>{const s={...t.entries};for(const t of e){if(!n.has(t))throw new Error(`Key ${t} not found in enum`);delete s[t]}return new Vr({...t,checks:[],...P(r),entries:s})}});function Wr(e,t){return new Vr({type:"enum",entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...P(t)})}var Yr=p("ZodLiteral",(e,t)=>{Ut.init(e,t),rr.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=e._zod.def,s=[];for(const i of r.values)if(void 0===i){if("throw"===t.unrepresentable)throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if("bigint"==typeof i){if("throw"===t.unrepresentable)throw new Error("BigInt literals cannot be represented in JSON Schema");s.push(Number(i))}else s.push(i);if(0===s.length);else if(1===s.length){const e=s[0];n.type=null===e?"null":typeof e,"draft-04"===t.target||"openapi-3.0"===t.target?n.enum=[e]:n.const=e}else s.every(e=>"number"==typeof e)&&(n.type="number"),s.every(e=>"string"==typeof e)&&(n.type="string"),s.every(e=>"boolean"==typeof e)&&(n.type="boolean"),s.every(e=>null===e)&&(n.type="null"),n.enum=s})(e,t,n),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function Kr(e,t){return new Yr({type:"literal",values:Array.isArray(e)?e:[e],...P(t)})}var Qr=p("ZodTransform",(e,t)=>{Ht.init(e,t),rr.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Transforms cannot be represented in JSON Schema")})(0,e),e._zod.parse=(n,r)=>{if("backward"===r.direction)throw new m(e.constructor.name);n.addIssue=r=>{if("string"==typeof r)n.issues.push(G(r,n.value,t));else{const t=r;t.fatal&&(t.continue=!1),t.code??(t.code="custom"),t.input??(t.input=n.value),t.inst??(t.inst=e),n.issues.push(G(t))}};const s=t.transform(n.value,n);return s instanceof Promise?s.then(e=>(n.value=e,n.fallback=!0,n)):(n.value=s,n.fallback=!0,n)}});var Xr=p("ZodOptional",(e,t)=>{Wt.init(e,t),rr.init(e,t),e._zod.processJSONSchema=(t,n,r)=>An(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});function es(e){return new Xr({type:"optional",innerType:e})}var ts=p("ZodExactOptional",(e,t)=>{Yt.init(e,t),rr.init(e,t),e._zod.processJSONSchema=(t,n,r)=>An(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});var ns=p("ZodNullable",(e,t)=>{Kt.init(e,t),rr.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const s=e._zod.def,i=$n(s.innerType,t,r),a=t.seen.get(e);"openapi-3.0"===t.target?(a.ref=s.innerType,n.nullable=!0):n.anyOf=[i,{type:"null"}]})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function rs(e){return new ns({type:"nullable",innerType:e})}var ss=p("ZodDefault",(e,t)=>{Qt.init(e,t),rr.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const s=e._zod.def;$n(s.innerType,t,r),t.seen.get(e).ref=s.innerType,n.default=JSON.parse(JSON.stringify(s.defaultValue))})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});var is=p("ZodPrefault",(e,t)=>{en.init(e,t),rr.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const s=e._zod.def;$n(s.innerType,t,r),t.seen.get(e).ref=s.innerType,"input"===t.io&&(n._prefault=JSON.parse(JSON.stringify(s.defaultValue)))})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});var as=p("ZodNonOptional",(e,t)=>{tn.init(e,t),rr.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const s=e._zod.def;$n(s.innerType,t,r),t.seen.get(e).ref=s.innerType})(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});var os=p("ZodCatch",(e,t)=>{rn.init(e,t),rr.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const s=e._zod.def;let i;$n(s.innerType,t,r),t.seen.get(e).ref=s.innerType;try{i=s.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=i})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});var ds=p("ZodPipe",(e,t)=>{sn.init(e,t),rr.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const s=e._zod.def,i=s.in._zod.traits.has("$ZodTransform"),a="input"===t.io?i?s.out:s.in:s.out;$n(a,t,r),t.seen.get(e).ref=a})(e,t,0,r),e.in=t.in,e.out=t.out});function ls(e,t){return new ds({type:"pipe",in:e,out:t})}var cs=p("ZodReadonly",(e,t)=>{on.init(e,t),rr.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const s=e._zod.def;$n(s.innerType,t,r),t.seen.get(e).ref=s.innerType,n.readOnly=!0})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});var fs=p("ZodCustom",(e,t)=>{cn.init(e,t),rr.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Custom types cannot be represented in JSON Schema")})(0,e)});var us,ps,hs,ms=ar().regex(/^[a-z]+$/,"aff ids are single lowercase words"),gs=ar().regex(/^[a-z][a-zA-Z]*$/,"balance ids are lowercase-led words"),bs=ar().regex(/^[a-z]+( [a-z]+)*$/,"cure ids are lowercase words separated by single spaces"),ys=ar().regex(/^[a-z]+$/,"venom ids are single lowercase words"),vs=ar().regex(/^[a-z]+$/,"profession ids are single lowercase words"),ks=Lr({shortName:ar().min(1),fg:ar(),bg:ar()}),ws={id:ms,display:ks.optional(),curesTo:ms.optional(),pseudo:Ar().default(!1),curedLast:Ar().default(!1)},Is=Lr({...ws,kind:Kr("plain")}),zs=Lr({...ws,kind:Kr("timed"),durationMs:Mr().int().positive(),provenance:Wr(["verified","unverified"]).default("verified")}),_s=Lr({...ws,kind:Kr("countable"),min:Mr().int().min(0),max:Mr().int().positive()}).refine(e=>e.max>e.min,{message:"countable affs need max > min"}),Os=(us="kind",ps=[Is,zs,_s],new Gr({type:"union",options:ps,discriminator:us,...P(hs)})),$s=Rr(Os).min(1).refine(e=>new Set(e.map(e=>e.id)).size===e.length,{message:"aff ids must be unique"}),Ss=Lr({fg:ar(),bg:ar()}),Ms=Hr(ar().min(1),Ss),xs=Hr(ms,ks),js=Lr({delimiter:Ss,label:Ss}),Ns=Lr({info:Ss,warning:Ss,error:Ss}),As=Lr({bracket:Ss,detail:Ss,tag:js,severity:Ns}),Ts=Lr({affs:xs,chrome:As}),Es=Ms.parse({antimony:{fg:"olive",bg:""},argentum:{fg:"royalblue",bg:""},arsenic:{fg:"",bg:""},aurum:{fg:"ForestGreen",bg:""},azurite:{fg:"",bg:""},calamine:{fg:"",bg:""},calcite:{fg:"slategray",bg:""},cinnabar:{fg:"greenyellow",bg:""},cuprum:{fg:"DeepSkyBlue",bg:""},ferrum:{fg:"DarkOrange",bg:""},gypsum:{fg:"",bg:""},magnesium:{fg:"Red",bg:""},plumbum:{fg:"Gold",bg:""},quartz:{fg:"",bg:""},quicksilver:{fg:"",bg:""},realgar:{fg:"firebrick",bg:""},stannum:{fg:"Tan",bg:""},caloric:{fg:"darkseagreen",bg:""},mending:{fg:"orchid",bg:""},epidermal:{fg:"sienna",bg:""},restoration:{fg:"darkviolet",bg:""},health:{fg:"lightpink",bg:""},writhe:{fg:"paleyellow",bg:"darkslategray"}}),Cs=Es,Ps={addiction:{shortName:"add",...Cs.ferrum},aeon:{shortName:"ae",...Cs.cinnabar},agoraphobia:{shortName:"agor",...Cs.argentum},amnesia:{shortName:"amn",fg:"",bg:""},anorexia:{shortName:"ANO",...Cs.epidermal},asthma:{shortName:"AST",...Cs.aurum},blackout:{shortName:"bo",fg:"",bg:""},blindness:{shortName:"unb",...Cs.arsenic},bound:{shortName:"bnd",...Cs.writhe},brokenleftarm:{shortName:"la1",...Cs.mending},brokenleftleg:{shortName:"ll1",...Cs.mending},brokenrightarm:{shortName:"ra1",...Cs.mending},brokenrightleg:{shortName:"rl1",...Cs.mending},bruisedribs:{shortName:"ribs",fg:"",bg:""},burning:{shortName:"burn",...Cs.mending},calcifiedskull:{shortName:"calh",...Cs.restoration},calcifiedtorso:{shortName:"calt",...Cs.restoration},claustrophobia:{shortName:"clau",...Cs.stannum},cleanseaura:{shortName:"cleanse",fg:"",bg:""},clumsiness:{shortName:"clu",...Cs.aurum},concussion:{shortName:"conc",...Cs.restoration},confusion:{shortName:"con",...Cs.stannum},corruption:{shortName:"corr",fg:"",bg:""},crackedribs:{shortName:"cr",...Cs.health},crushedthroat:{shortName:"cru",...Cs.mending},daeggerimpale:{shortName:"daeg",...Cs.writhe},damagedleftarm:{shortName:"la2",...Cs.restoration},damagedleftleg:{shortName:"ll2",...Cs.restoration},damagedrightarm:{shortName:"ra2",...Cs.restoration},damagedrightleg:{shortName:"rl2",...Cs.restoration},damagedhead:{shortName:"hd2",...Cs.restoration},darkshade:{shortName:"dark",...Cs.ferrum},dazed:{shortName:"dzd",...Cs.cinnabar},dazzled:{shortName:"dzl",...Cs.mending},deadening:{shortName:"dea",...Cs.cinnabar},deafness:{shortName:"und",...Cs.calamine},dehydrated:{shortName:"deh",fg:"",bg:""},dementia:{shortName:"dem",...Cs.stannum},depression:{shortName:"dep",...Cs.plumbum},deteriorate:{shortName:"det",fg:"",bg:""},disloyalty:{shortName:"disl",...Cs.realgar},disrupted:{shortName:"disr",fg:"",bg:""},dissonance:{shortName:"disso",...Cs.plumbum},dizziness:{shortName:"diz",...Cs.plumbum},enmesh:{shortName:"enmsh",...Cs.writhe},ensorcelled:{shortName:"ensor",fg:"",bg:""},entangled:{shortName:"entgl",...Cs.writhe},epilepsy:{shortName:"epi",...Cs.plumbum},fear:{shortName:"fear",fg:"",bg:""},flushings:{shortName:"flush",...Cs.ferrum},frostbite:{shortName:"frost",...Cs.caloric},frozen:{shortName:"frz",...Cs.caloric},fulminated:{shortName:"fulm",...Cs.plumbum},generosity:{shortName:"gen",...Cs.cuprum},grievouswounds:{shortName:"grv",...Cs.health},guilt:{shortName:"gui",...Cs.argentum},haemophilia:{shortName:"haem",...Cs.ferrum},hallucinations:{shortName:"hall",...Cs.stannum},hamstrung:{shortName:"hms",fg:"",bg:""},healthleech:{shortName:"hthl",...Cs.aurum},heartseed:{shortName:"heart",...Cs.restoration},hellsight:{shortName:"hell",...Cs.realgar},horror:{shortName:"hor",...Cs.argentum},hypersomnia:{shortName:"hypers",...Cs.stannum},hypochondria:{shortName:"hypoch",...Cs.argentum},hypothermia:{shortName:"hypoth",...Cs.restoration},icefisted:{shortName:"ice",fg:"",bg:""},impaled:{shortName:"impl",...Cs.writhe},impatience:{shortName:"IMPAT",...Cs.plumbum},indifference:{shortName:"ind",...Cs.cuprum},itching:{shortName:"itch",...Cs.epidermal},justice:{shortName:"just",...Cs.cuprum},kkractlebrand:{shortName:"kkr",...Cs.health},laceratedthroat:{shortName:"lac2",...Cs.restoration},latched:{shortName:"latch",...Cs.health},lethargy:{shortName:"let",...Cs.ferrum},lightbind:{shortName:"light",fg:"",bg:""},loneliness:{shortName:"lon",...Cs.argentum},lovers:{shortName:"love",...Cs.cuprum},manaleech:{shortName:"man",...Cs.realgar},mangledleftarm:{shortName:"la3",...Cs.restoration},mangledleftleg:{shortName:"ll3",...Cs.restoration},mangledrightarm:{shortName:"ra3",...Cs.restoration},mangledrightleg:{shortName:"rl3",...Cs.restoration},mangledhead:{shortName:"hd3",...Cs.restoration},masochism:{shortName:"maso",...Cs.argentum},mildtrauma:{shortName:"tor1",...Cs.restoration},mycalium:{shortName:"myc",...Cs.plumbum},nausea:{shortName:"nau",...Cs.ferrum},numbedleftarm:{shortName:"nbla",fg:"",bg:""},numbedrightarm:{shortName:"nbra",fg:"",bg:""},pacified:{shortName:"pac",...Cs.cuprum},palpatarfeed:{shortName:"worm",fg:"",bg:""},paralysis:{shortName:"PAR",...Cs.magnesium},paranoia:{shortName:"prn",...Cs.stannum},parasite:{shortName:"prs",...Cs.aurum},peace:{shortName:"pea",...Cs.cuprum},phlogisticated:{shortName:"phlog",fg:"",bg:""},pinshot:{shortName:"psh",fg:"",bg:""},pressure:{shortName:"pres",...Cs.calcite},prone:{shortName:"pr",fg:"",bg:""},pyramides:{shortName:"pyra",...Cs.magnesium},pyre:{shortName:"pyre",...Cs.cuprum},rebbies:{shortName:"reb",...Cs.aurum},recklessness:{shortName:"reck",...Cs.argentum},retribution:{shortName:"retr",...Cs.cuprum},revealed:{shortName:"rev",fg:"",bg:""},sandfever:{shortName:"sand",...Cs.plumbum},scalded:{shortName:"scald",...Cs.epidermal},scytherus:{shortName:"scy",...Cs.ferrum},selarnia:{shortName:"sel",...Cs.mending},sensitivity:{shortName:"sen",...Cs.aurum},serioustrauma:{shortName:"tor2",...Cs.restoration},shadowmadness:{shortName:"shad",...Cs.plumbum},shivering:{shortName:"shiv",...Cs.caloric},shyness:{shortName:"shy",...Cs.plumbum},skullfractures:{shortName:"sf",...Cs.health},slashedthroat:{shortName:"lac1",...Cs.epidermal},sleeping:{shortName:"slp",fg:"",bg:""},slickness:{shortName:"SLI",...Cs.magnesium},slimeobscure:{shortName:"slime",fg:"",bg:""},spiritburn:{shortName:"spirB",...Cs.argentum},spiritwrack:{shortName:"spirW",fg:"",bg:""},stupidity:{shortName:"st",...Cs.plumbum},stuttering:{shortName:"stut",...Cs.epidermal},homunculusmercury:{shortName:"merc",fg:"",bg:""},temperedcholeric:{shortName:"choH",...Cs.antimony},temperedmelancholic:{shortName:"melaH",...Cs.antimony},temperedphlegmatic:{shortName:"phleH",...Cs.antimony},temperedsanguine:{shortName:"sanH",...Cs.antimony},tenderskin:{shortName:"tend",...Cs.argentum},tension:{shortName:"tens",...Cs.cinnabar},timeflux:{shortName:"tmfx",fg:"",bg:""},timeloop:{shortName:"tmlp",...Cs.cuprum},tonguetied:{shortName:"tngt",...Cs.restoration},torntendons:{shortName:"tt",...Cs.health},transfixation:{shortName:"trfx",...Cs.writhe},unweavingbody:{shortName:"unwB",...Cs.ferrum},unweavingspirit:{shortName:"unwS",...Cs.cinnabar},unweavingmind:{shortName:"unwM",...Cs.plumbum},unblind:{shortName:"unB",fg:"",bg:""},undeaf:{shortName:"unD",fg:"",bg:""},unnamable:{shortName:"unnam",fg:"",bg:""},vertigo:{shortName:"vert",...Cs.argentum},vitrified:{shortName:"vitri",fg:"",bg:""},voidfisted:{shortName:"void",fg:"",bg:""},voyria:{shortName:"voy",fg:"",bg:""},weariness:{shortName:"wea",...Cs.aurum},webbed:{shortName:"web",...Cs.writhe},whisperingmadness:{shortName:"wmad",...Cs.argentum},wristfractures:{shortName:"wf",...Cs.health}},Ds=Ts.parse({affs:Ps,chrome:{bracket:{fg:"LightGoldenRodYellow",bg:""},detail:{fg:"darkgray",bg:""},tag:{delimiter:{fg:"#784695",bg:""},label:{fg:"#CBCE91",bg:""}},severity:{info:{fg:"#FFF2D7",bg:""},warning:{fg:"orange",bg:""},error:{fg:"red",bg:""}}}}),Rs=Ds.affs,Zs=(Ds.chrome,new Set(["undeaf","unblind","cleanseaura","unnamable"])),Bs=new Set(["dissonance"]),Ls=new Map([["mangledleftleg","damagedleftleg"],["mangledleftarm","damagedleftarm"],["mangledrightleg","damagedrightleg"],["mangledrightarm","damagedrightarm"],["mangledhead","damagedhead"],["serioustrauma","mildtrauma"],["damagedleftleg","brokenleftleg"],["damagedleftarm","brokenleftarm"],["damagedrightleg","brokenrightleg"],["damagedrightarm","brokenrightarm"]]),Fs=(e,t,n={})=>({id:e,kind:t,...n,...Ls.has(e)?{curesTo:Ls.get(e)}:{},...Zs.has(e)?{pseudo:!0}:{},...Bs.has(e)?{curedLast:!0}:{},...Rs[e]?{display:Rs[e]}:{}}),qs=$s.parse([...["undeaf","unblind","cleanseaura","addiction","agoraphobia","amnesia","anorexia","asphyxiating","asthma","blindness","bloodfire","bound","brokenleftarm","brokenrightarm","brokenleftleg","brokenrightleg","calcifiedskull","calcifiedtorso","claustrophobia","clumsiness","coldfate","concussion","conflagration","confusion","convergence","cremated","crushedthroat","daeggerimpale","damagedhead","damagedleftarm","damagedleftleg","damagedrightarm","damagedrightleg","darkshade","dazed","deadening","deafness","death","deathsickness","deepsleep","degenerate","dementia","depression","deteriorate","diminished","disloyalty","disrupted","dissonance","dizziness","earworm","enlightenment","entangled","epilepsy","fear","flushings","fratricide","frostbite","frozen","fulminated","generosity","grievouswounds","guilt","haemophilia","hallucinations","hatred","healthleech","hellsight","hindered","homunculusmercury","hypersomnia","hypochondria","hypothermia","icebound","impaled","impatience","indifference","insomnia","isolation","itching","justice","kkractlebrand","laceratedthroat","lapsingconsciousness","latched","lethargy","loneliness","lovers","lullaby","manaleech","masochism","mildtrauma","mangledleftarm","mangledleftleg","mangledrightarm","mangledrightleg","mangledhead","mindclamp","mycalium","nausea","pacified","paralysis","paranoia","parasite","peace","penitence","prone","pyramides","rebbies","recklessness","retribution","sandfever","scytherus","selarnia","sensitivity","serioustrauma","shadowmadness","shivering","shyness","slashedthroat","sleeping","slickness","spiritburn","stupidity","stuttering","tenderskin","tension","timeloop","tonguetied","transfixation","vertigo","vitiated","voyria","weariness","webbed","whisperingmadness","harmonic","bop","spiritwrack","bedevil","loki","moon","evileye","dragoncurse","swiftcurse"].map(e=>Fs(e,"plain")),...Object.entries({accentato:{durationMs:2e4,provenance:"unverified"},aeon:{durationMs:16e3},airfisted:{durationMs:16e3},betrayal:{durationMs:15e3},blackout:{durationMs:4e3,provenance:"unverified"},blistered:{durationMs:15e3,provenance:"unverified"},breathless:{durationMs:3e3},bruisedribs:{durationMs:3e4},cadmuscurse:{durationMs:2e4},condemned:{durationMs:2e4},constricted:{durationMs:3e4},corruption:{durationMs:45e3},dazzled:{durationMs:6e4},dehydrated:{durationMs:6e4},demonstain:{durationMs:12e4},empoweredloshre:{durationMs:12e3},empoweredmannaz:{durationMs:2e4},enmesh:{durationMs:5e3},ensorcelled:{durationMs:2e4},flamefisted:{durationMs:3e4},hamstrung:{durationMs:9e3},heartseed:{durationMs:11e3},hecatecurse:{durationMs:16e3},icefisted:{durationMs:3e4},internalbleeding:{durationMs:3e4},inquisition:{durationMs:3e4},kaisurge:{durationMs:15e3,provenance:"unverified"},lightbind:{durationMs:22e3},lovestruck:{durationMs:5e3},mindravaged:{durationMs:2e4,provenance:"unverified"},muddled:{durationMs:12e3},numbedleftarm:{durationMs:7500},numbedrightarm:{durationMs:7500},petrified:{durationMs:1e4,provenance:"unverified"},palpatarfeed:{durationMs:19e3,provenance:"unverified"},phlogisticated:{durationMs:45e3},pinshot:{durationMs:18e3},reeling:{durationMs:2e4},revealed:{durationMs:6e4},scalded:{durationMs:2e4},scrambledbrains:{durationMs:6e4},silenced:{durationMs:2e4,provenance:"unverified"},silver:{durationMs:18e4},slimeobscure:{durationMs:6e4},solarburn:{durationMs:5e3},snared:{durationMs:2e4},speechless:{durationMs:3e5},stridulating:{durationMs:15e3},stun:{durationMs:3e3,provenance:"unverified"},succumbed:{durationMs:3e4},timeflux:{durationMs:6e4},trueblind:{durationMs:6e3},unconsciousness:{durationMs:1e4},unnamable:{durationMs:4800},vinewreathed:{durationMs:3e4},vitrified:{durationMs:45e3},voidfisted:{durationMs:5e3},waterbonds:{durationMs:3e4},weakenedmind:{durationMs:6e4},woeconstrained:{durationMs:3e4}}).map(([e,t])=>Fs(e,"timed",t)),...Object.entries({pressure:{min:0,max:5},crescendo:{min:0,max:5},unweavingbody:{min:0,max:5},unweavingspirit:{min:0,max:5},unweavingmind:{min:0,max:5},burning:{min:0,max:5},horror:{min:0,max:5},pyre:{min:0,max:3},temperedcholeric:{min:0,max:8},temperedmelancholic:{min:0,max:8},temperedphlegmatic:{min:0,max:8},temperedsanguine:{min:0,max:8},torntendons:{min:0,max:6},crackedribs:{min:0,max:6},skullfractures:{min:0,max:6},wristfractures:{min:0,max:6}}).map(([e,t])=>Fs(e,"countable",t))]),Gs=Lr({id:vs,skills:Rr(ar().regex(/^[a-z]+$/,"skill keys are single lowercase words")).default([])}),Js=Rr(Gs).min(1).refine(e=>new Set(e.map(e=>e.id)).size===e.length,{message:"profession ids must be unique"}),Us=Js.parse([{id:"alchemist",skills:[]},{id:"apostate",skills:[]},{id:"bard",skills:[]},{id:"blademaster",skills:[]},{id:"depthswalker",skills:["aeonics","shadowmancy"]},{id:"dragon",skills:["dragoncraft"]},{id:"firelord",skills:[]},{id:"jester",skills:["tarot"]},{id:"magi",skills:["elementalism","crystalism","artificing"]},{id:"monk",skills:[]},{id:"occultist",skills:["occultism","domination","tarot"]},{id:"priest",skills:[]},{id:"psion",skills:["weaving"]},{id:"runewarden",skills:[]},{id:"serpent",skills:["venom"]},{id:"shikudo",skills:[]}]),Hs=qr([ms,Rr(ms).min(2)]),Vs=Lr({id:bs,command:ar().min(1),class:Wr(["linear","tree","special"]),order:Rr(ms).default([]),ordered:Ar().default(!1),layered:Ar().default(!1),bals_used:Rr(gs).default([]),bals_req:Rr(gs).default([]),blocks:Rr(Hs).default([]),professions:Rr(vs).optional(),bestowable:Ar().default(!1),prio:Mr().int().min(0),delayMs:Mr().int().positive().optional()}).refine(e=>!e.bestowable||void 0!==e.professions,{message:"bestowable is a class-cure trait — it requires a professions gate"}),Ws=Rr(Vs).min(1).refine(e=>new Set(e.map(e=>e.id)).size===e.length,{message:"cure ids must be unique"}),Ys=["itching","paralysis","fear","brokenrightarm","brokenleftarm","brokenrightleg","brokenleftleg","lapsingconsciousness","aeon","lovers","confusion","epilepsy","pacified","blackout","dazed","justice","slashedthroat","hellsight","peace","dazzled","shyness","dizziness","slickness","asthma","nausea","selarnia","weariness","scytherus","fratricide","haemophilia","clumsiness","hallucinations","healthleech","dementia","recklessness","anorexia","masochism","impatience","stupidity","generosity","addiction","deadening","manaleech","stuttering","paranoia","agoraphobia","loneliness","claustrophobia","vertigo","hypersomnia","shivering","frozen","burning","sensitivity","hypochondria","lethargy","disloyalty","darkshade","voyria","dissonance","phlogisticated","silver","spiritburn","tenderskin","guilt","skullfractures","wristfractures","crackedribs","torntendons","indifference","retribution","shadowmadness","parasite","depression","timeloop","crushedthroat","tension","unweavingspirit","grievouswounds","pyramides","flushings","rebbies","mycalium","sandfever","crescendo","fulminated","frostbite"],Ks=["death","anorexia","sleeping"],Qs=["death","asthma","sleeping"],Xs=["death","slickness","sleeping"],ei=["death","sleeping","anorexia"],ti=[["brokenleftarm","brokenrightarm"],["brokenleftarm","damagedrightarm"],["brokenleftarm","mangledrightarm"],["damagedleftarm","brokenrightarm"],["damagedleftarm","damagedrightarm"],["damagedleftarm","mangledrightarm"],["mangledleftarm","brokenrightarm"],["mangledleftarm","damagedrightarm"],["mangledleftarm","mangledrightarm"]],ni=["entangled","transfixation","impaled","webbed","bound"],ri=["darkshade","haemophilia","lethargy","addiction","scytherus","nausea","flushings","unweavingbody"],si=["paralysis","slickness","pyramides"],ii=["clumsiness","healthleech","sensitivity","weariness","asthma","rebbies","parasite"],ai=["undeaf","deafness"],oi=["horror","fratricide","masochism","loneliness","vertigo","recklessness","agoraphobia","guilt","whisperingmadness","spiritburn","tenderskin","hypochondria"],di=["pacified","peace","lovers","justice","generosity","indifference","retribution","pyre","timeloop","diminished","stridulating"],li=["temperedcholeric","temperedmelancholic","temperedphlegmatic","temperedsanguine"],ci=["unblind","blindness"],fi=["claustrophobia","paranoia","confusion","hypersomnia","hallucinations","dementia","crescendo"],ui=["stupidity","epilepsy","dizziness","shyness","impatience","dissonance","depression","sandfever","mycalium","shadowmadness","unweavingmind","fulminated"],pi=["pressure"],hi=["disloyalty","hellsight","manaleech","slickness"],mi=["aeon","dazed","deadening","tension","unweavingspirit","earworm"],gi=(e,t,n={})=>({id:e,command:`eat ${e}`,class:"linear",order:t,bals_used:["herb"],bals_req:["herb"],blocks:Ks,prio:0,...n}),bi=(e,t)=>({id:e,command:`smoke ${e}`,class:"linear",...t?{order:t}:{},bals_used:["smoke"],bals_req:["smoke"],blocks:Qs,prio:0}),yi=(e,t,n={})=>({id:e,command:`apply ${e}`,class:"linear",order:t,bals_used:["salve"],bals_req:["salve","restoration"],blocks:Xs,prio:0,...n}),vi=(e,t)=>({...yi(e,t),bals_used:["restoration"],delayMs:4e3}),ki=(e,t)=>({id:e,command:`apply ${e}`,class:"linear",order:t,bals_used:["sip"],bals_req:["sip"],prio:0}),wi=(e,t)=>({id:e,class:"tree",order:Ys,prio:0,...t}),Ii=Ws.parse([gi("ferrum",ri),gi("magnesium",si),gi("aurum",ii),gi("calamine",ai,{delayMs:2500}),gi("argentum",oi),gi("cuprum",di),gi("antimony",li),gi("arsenic",ci),gi("stannum",fi),gi("plumbum",ui,{class:"special"}),gi("calcite",pi),gi("ginseng",ri),gi("bloodroot",si),gi("kelp",ii),gi("hawthorn",ai,{delayMs:2500}),gi("lobelia",oi),gi("bellwort",di),gi("ginger",li),gi("bayberry",ci),gi("ash",fi),gi("goldenseal",ui,{class:"special"}),gi("pear",pi),{...bi("smoke",["aeon","disloyalty","hellsight","manaleech","slickness","deadening","tension","unweavingspirit","earworm"]),command:"smoke cinnabar"},bi("cinnabar",mi),bi("malachite"),bi("realgar",hi),bi("elm",mi),bi("skullcap"),bi("valerian",hi),yi("caloric",["frozen","shivering","frostbite"],{layered:!0}),yi("epidermal to body",["anorexia"]),yi("epidermal to head",["stuttering","blindness","deafness"]),yi("epidermal to ears",["deafness"]),yi("mending to head",["crushedthroat","dazzled"]),yi("mending to arms",["brokenleftarm","brokenrightarm"],{ordered:!0}),yi("mending to legs",["brokenleftleg","brokenrightleg"],{ordered:!0}),yi("mending to body",["burning"]),vi("restoration to head",["mangledhead","damagedhead","calcifiedskull","concussion","tonguetied"]),vi("restoration to torso",["hypothermia","heartseed","serioustrauma","mildtrauma","calcifiedtorso","internalbleeding"]),vi("restoration to arms",["mangledleftarm","mangledrightarm","damagedleftarm","damagedrightarm"]),vi("restoration to legs",["mangledleftleg","mangledrightleg","damagedleftleg","damagedrightleg"]),{id:"health",command:"sip health",class:"linear",bals_used:["sip"],bals_req:["sip"],blocks:ei,prio:0},{id:"mana",command:"sip mana",class:"linear",bals_used:["sip"],bals_req:["sip"],blocks:ei,prio:0},ki("health to head",["skullfractures"]),ki("health to torso",["crackedribs","grievouswounds"]),ki("health to arms",["wristfractures"]),ki("health to legs",["torntendons","latched","kkractlebrand"]),{id:"fitness",command:"fitness",class:"linear",order:["asthma"],bals_used:["balance","fitness"],bals_req:["equilibrium","balance","fitness"],blocks:["death","weariness","sleeping"],professions:["monk","shikudo","runewarden"],prio:0},wi("bloodboil",{command:"cast bloodboil",bals_used:["equilibrium","bloodboil"],bals_req:["equilibrium","balance","bloodboil"],blocks:["death","haemophilia","sleeping",...ti,...ni],professions:["magi"]}),{id:"dragonflex",command:"dragonflex",class:"linear",order:["webbed","entangled"],bals_used:["balance"],bals_req:["balance"],professions:["dragon"],prio:0},wi("dragonheal",{command:"dragonheal",bals_used:["dragonheal","equilibrium"],bals_req:["balance","equilibrium"],blocks:["death","sleeping",["recklessness","weariness"]],professions:["dragon"]}),{id:"dwinnu",command:"chant dwinnu",class:"linear",order:["webbed","entangled"],bals_used:["voice"],bals_req:["voice"],professions:["bard"],prio:0},{id:"rage",command:"rage",class:"linear",order:["pacified","peace","lovers","generosity","stridulating"],bals_used:["rage"],bals_req:["rage"],professions:["runewarden"],prio:95},wi("salt",{command:"educe salt",bals_used:["salt","equilibrium"],bals_req:["equilibrium","salt"],blocks:["death","stupidity","sleeping"],professions:["alchemist"]}),wi("siphon",{command:"siphon",bals_used:["angel"],bals_req:["angel"],blocks:["death","sleeping"],professions:["apostate","priest"]}),wi("shrugging",{command:"shrugging",bals_used:["shrugging"],bals_req:["equilibrium","balance","shrugging"],blocks:["death","weariness","sleeping"],professions:["serpent"]}),wi("slough",{command:"slough impurities",bals_used:["slough","balance"],bals_req:["equilibrium","balance","slough"],blocks:["death","weariness","sleeping"],professions:["firelord"]}),wi("fool",{command:"fling fool at me",bals_used:["fool","balance"],bals_req:["equilibrium","balance","fool"],blocks:["death","prone","paralysis","sleeping",...ti,...ni],professions:["occultist"]}),wi("accelerate",{command:"chrono accelerate",bals_used:["accelerate","balance"],bals_req:["equilibrium","balance","accelerate"],blocks:["death","sleeping","recklessness"],professions:["depthswalker"]}),wi("alleviate",{command:"alleviate",bals_used:["alleviate","balance"],bals_req:["equilibrium","balance","alleviate"],blocks:["death","paralysis","sleeping"],professions:["blademaster"]}),wi("dagaz",{command:"sketch dagaz on ground",bals_used:["dagaz"],blocks:["death"],professions:["runewarden"],bestowable:!0}),wi("generic",{command:"classcure",bals_used:["generic"],bals_req:["equilibrium","balance","generic"],blocks:["death"],professions:[]}),{id:"insomnia",command:"insomnia",class:"linear",order:["insomnia"],blocks:["death","hypersomnia","sleeping"],prio:0},{id:"focus",command:"focus",class:"linear",order:["stupidity","epilepsy","dizziness","shyness","claustrophobia","paranoia","confusion","hallucinations","dementia","pacified","lovers","generosity","masochism","loneliness","vertigo","recklessness","agoraphobia","anorexia","stuttering"],bals_used:["focus"],bals_req:["focus"],blocks:["death","impatience","sleeping"],prio:0},{id:"concentrate",command:"concentrate",class:"linear",order:["disrupted"],blocks:["death","sleeping","confusion"],prio:0},{id:"immunity",command:"sip immunity",class:"linear",order:["voyria"],bals_used:["immunity"],bals_req:["immunity"],blocks:ei,prio:0},{id:"stand",command:"stand",class:"linear",order:["prone"],bals_req:["balance","equilibrium"],blocks:["death","sleeping","paralysis","brokenrightleg","brokenleftleg","damagedleftleg","damagedrightleg","mangledrightleg","mangledleftleg",...ni],prio:0},wi("tree",{command:"touch tree",bals_used:["tree"],bals_req:["tree"],blocks:["death","sleeping","paralysis",...ti,...ni]}),{id:"potash",command:"eat potash",class:"linear",bals_used:["moss"],bals_req:["moss"],blocks:ei,prio:0},{id:"moss",command:"eat moss",class:"linear",bals_used:["moss"],bals_req:["moss"],blocks:ei,prio:0},{id:"restore",command:"restore",class:"linear",order:["brokenleftarm","brokenrightarm","brokenleftleg","brokenrightleg","skullfractures","torntendons","wristfractures","crackedribs"],bals_used:["equilibrium"],bals_req:["balance","equilibrium"],prio:0},{id:"touch soul",command:"touch soul",class:"linear",order:["amnesia"],blocks:["death"],prio:101}]),zi=ar().regex(/^[a-z]+$/,"defence ids are single lowercase words"),_i=Lr({stripDelayMs:Mr().int().positive(),applyDelayMs:Mr().int().positive(),conservativeLeadMs:Mr().int().nonnegative(),blockedBy:Rr(ms).min(1)}).refine(e=>e.conservativeLeadMs<e.applyDelayMs,{message:"conservativeLeadMs must leave a positive effective application delay"}).refine(e=>new Set(e.blockedBy).size===e.blockedBy.length,{message:"blockedBy ids must be unique"}),Oi=Rr(Lr({id:zi,default:Ar().default(!1),restore:_i.optional()})).min(1).refine(e=>new Set(e.map(e=>e.id)).size===e.length,{message:"defence ids must be unique"}),$i=Oi.parse([{id:"speed",default:!0,restore:{stripDelayMs:2200,applyDelayMs:3e3,conservativeLeadMs:200,blockedBy:ei}},{id:"insulation",default:!0},{id:"temperence",default:!0},{id:"kola",default:!0},{id:"insomnia",default:!0},{id:"cloak",default:!0},{id:"fangbarrier",default:!0},{id:"levitating",default:!0},{id:"selfishness",default:!0},{id:"curseward"},{id:"prismatic"},{id:"rebounding"},{id:"shield"}]),Si=Lr({affId:ms,observedDurationMs:Mr().int().positive(),predictiveDurationMs:Mr().int().positive()}),Mi=Lr({id:gs,observedDurationMs:Mr().int().positive(),predictiveDurationMs:Mr().int().positive(),bufferPolicy:Wr(["buffered","exact"]),extendedBy:Rr(Si).default([])}).refine(e=>[e,...e.extendedBy].every(t=>((e,{observedDurationMs:t,predictiveDurationMs:n})=>"buffered"===e?t===Math.round(.75*n):t===n)(e.bufferPolicy,t)),{message:"observedDurationMs must follow the declared bufferPolicy"}).refine(e=>e.extendedBy.every(t=>t.predictiveDurationMs>e.predictiveDurationMs),{message:"an extension must be longer than the base duration"}).refine(e=>new Set(e.extendedBy.map(e=>e.affId)).size===e.extendedBy.length,{message:"extension aff ids must be unique within a balance"}),xi=Rr(Mi).min(1).refine(e=>new Set(e.map(e=>e.id)).size===e.length,{message:"balance ids must be unique"}),ji=e=>({predictiveDurationMs:e,observedDurationMs:Math.round(.75*e)}),Ni=(e,t,n=[])=>({id:e,...ji(t),bufferPolicy:"buffered",extendedBy:n.map(([e,t])=>({affId:e,...ji(t)}))}),Ai=xi.parse([Ni("balance",2e3),Ni("equilibrium",2e3),Ni("sip",4500),Ni("herb",1500),Ni("smoke",1500),Ni("salve",1e3),Ni("restoration",4e3),Ni("focus",2500,[["whisperingmadness",4e3],["weakenedmind",5e3]]),Ni("tree",15e3),Ni("moss",6e3),Ni("immunity",1e4),Ni("accelerate",1e4),Ni("alleviate",1e4),Ni("angel",1e4),Ni("bloodboil",1e4),Ni("dragonheal",2e4),Ni("fitness",1e4),Ni("fool",3e4),Ni("rage",1e4),Ni("salt",1e4),Ni("shrugging",12e3),Ni("slough",1e4),Ni("dagaz",2e4),Ni("voice",2500),Ni("generic",12e3)]),Ti=Rr(Lr({id:ms,level:Mr().int().min(1),prio:Mr().int().min(0)})).min(1).refine(e=>new Set(e.map(e=>`${e.id}:${e.level}`)).size===e.length,{message:"priority (id, level) pairs must be unique"}),Ei=(e,t)=>t.map(t=>({id:t,level:1,prio:e})),Ci=(e,t,n)=>Array.from({length:t},(t,r)=>({id:e,level:r+1,prio:n})),Pi=Ti.parse([...Ei(0,["accentato","airfisted","asphyxiating","blistered","bloodfire","bruisedribs","cadmuscurse","coldfate","condemned","conflagration","constricted","convergence","corruption","cremated","death","deathsickness","deepsleep","degenerate","dehydrated","demonstain","deteriorate","empoweredloshre","empoweredmannaz","enlightenment","enmesh","ensorcelled","flamefisted","hamstrung","hatred","hecatecurse","hindered","homunculusmercury","icefisted","inquisition","isolation","kaisurge","lightbind","lullaby","mindclamp","mindravaged","muddled","numbedleftarm","numbedrightarm","palpatarfeed","petrified","phlogisticated","pinshot","revealed","scalded","scrambledbrains","silenced","silver","slimeobscure","solarburn","stun","timeflux","trueblind","vinewreathed","vitiated","vitrified","voidfisted","waterbonds","weakenedmind","unconsciousness"]),...Ei(2,["aeon","concussion","crushedthroat","paralysis","peace"]),...Ei(3,["sleeping","grievouswounds","latched","dazzled","weariness","prone","timeloop","fulminated"]),...Ci("unweavingbody",5,3),...Ci("unweavingmind",5,3),...Ci("unweavingspirit",5,3),...Ei(4,["spiritburn","heartseed","guilt","tenderskin","pyramides","parasite","hypochondria","pacified","depression","confusion","retribution","shadowmadness","whisperingmadness","hellsight"]),...Ei(5,["anorexia","mycalium","flushings","rebbies","sandfever","asthma","healthleech"]),...Ei(6,["impatience","itching","scytherus","clumsiness","kkractlebrand","damagedleftleg","darkshade","slickness","recklessness","dementia","fratricide","icebound"]),...Ei(7,["bound","daeggerimpale","entangled","sensitivity","transfixation","webbed","tonguetied","haemophilia","lethargy","manaleech","dissonance"]),{id:"pyre",level:1,prio:7},{id:"pyre",level:2,prio:6},{id:"pyre",level:3,prio:5},...Ei(8,["damagedrightleg","hypersomnia","earworm","diminished"]),...Ci("skullfractures",6,8),...Ci("crescendo",5,8),...Ei(9,["brokenleftleg","brokenrightleg","hallucinations"]),...Ci("torntendons",6,9),...Ei(10,["calcifiedskull","calcifiedtorso","mangledleftleg","mangledrightleg","disrupted","mangledhead","voyria"]),...Ci("crackedribs",6,10),...Ei(11,["hypothermia","impaled","brokenleftarm","brokenrightarm","indifference","addiction","nausea","deadening","frozen","shivering","mildtrauma","internalbleeding"]),...Ei(12,["stupidity","damagedleftarm","disloyalty"]),...Ci("wristfractures",6,12),...Ei(13,["tension","damagedhead","dazed"]),...Ci("burning",5,13),...Ei(14,["lovers","damagedrightarm","temperedcholeric","temperedmelancholic","temperedphlegmatic","temperedsanguine"]),...Ci("pressure",5,14),...Ei(15,["mangledleftarm","mangledrightarm"]),...Ei(16,["agoraphobia","claustrophobia","generosity","justice","loneliness","vertigo"]),...Ei(17,["paranoia"]),...Ei(18,["serioustrauma","epilepsy"]),...Ei(20,["laceratedthroat","slashedthroat","stuttering"]),...Ei(21,["selarnia","fear","masochism"]),...Ei(23,["dizziness","shyness"]),...Ci("horror",5,26),...Ei(30,["amnesia","blackout"]),...Ei(0,["insomnia","deafness","blindness"]),...Ei(100,["harmonic","bop","spiritwrack","bedevil","loki","moon","evileye","dragoncurse","swiftcurse"])]),Di=Rr(ms).min(1).refine(e=>new Set(e).size===e.length,{message:"pool affliction ids must be unique"}),Ri=Rr(Lr({profession:vs,pools:Hr(ar().min(1),Di)})).min(1).refine(e=>new Set(e.map(e=>e.profession)).size===e.length,{message:"professions must be unique"}),Zi=Ri.parse([{profession:"occultist",pools:{mentals:["claustrophobia","agoraphobia","lovers","dementia","epilepsy","hallucinations","confusion","stupidity","paranoia","vertigo","shyness","addiction","recklessness","masochism"],physicals:["asthma","paralysis","slickness","haemophilia","clumsiness","healthleech","sensitivity","darkshade"],bubonis:["vertigo","recklessness","confusion","masochism","paranoia","shyness","claustrophobia"],chimera:["confusion","hallucinations","agoraphobia","claustrophobia","dementia"],moon:["stupidity","masochism","hallucinations","hypersomnia","confusion","epilepsy","claustrophobia","agoraphobia"],whisperingmadness:["dementia","stupidity","confusion","hypersomnia","paranoia","hallucinations","impatience","addiction","agoraphobia","lovers","loneliness","recklessness","masochism"],justice:["paralysis","sensitivity","healthleech","haemophilia","weariness","asthma","clumsiness"],unnamable:["confusion","stupidity","dementia"]}},{profession:"psion",pools:{blast:["impatience","stupidity","blackout","dizziness","epilepsy","unweavingmind"]}},{profession:"depthswalker",pools:{leach:["parasite","healthleech","manaleech"],madness:["shadowmadness","vertigo","hallucinations"],retribution:["retribution","justice"],degeneration:["clumsiness","weariness","paralysis"],depression:["depression","nausea","hypochondria"]}}]),Bi=Rr(Lr({id:ys,aff:ms.nullable()})).min(1).refine(e=>new Set(e.map(e=>e.id)).size===e.length,{message:"venom ids must be unique"}),Li=Bi.parse([{id:"xentio",aff:"clumsiness"},{id:"eurypteria",aff:"recklessness"},{id:"kalmia",aff:"asthma"},{id:"digitalis",aff:"shyness"},{id:"darkshade",aff:"darkshade"},{id:"curare",aff:"paralysis"},{id:"epteth",aff:null},{id:"prefarar",aff:"sensitivity"},{id:"monkshood",aff:"disloyalty"},{id:"euphorbia",aff:"nausea"},{id:"oculus",aff:"unblind"},{id:"vernalius",aff:"weariness"},{id:"epseth",aff:null},{id:"larkspur",aff:"dizziness"},{id:"slike",aff:"anorexia"},{id:"delphinium",aff:"sleeping"},{id:"notechis",aff:"haemophilia"},{id:"vardrax",aff:"addiction"},{id:"loki",aff:"loki"},{id:"aconite",aff:"stupidity"},{id:"selarnia",aff:null},{id:"gecko",aff:"slickness"},{id:"scytherus",aff:"scytherus"},{id:"nechamadra",aff:"shivering"}]),Fi=new Map(qs.map(e=>[e.id,e])),qi=new Map(Ii.map(e=>[e.id,e])),Gi=new Map(Ai.map(e=>[e.id,e])),Ji=new Map($i.map(e=>[e.id,e])),Ui=Object.freeze(Object.fromEntries($i.filter(e=>e.default).map(({id:e})=>[e,!0]))),Hi=(()=>{const e=new Map;for(const t of Pi)e.has(t.id)||e.set(t.id,new Map),e.get(t.id).set(t.level,t.prio);return e})(),Vi=(...e)=>new Set(Ii.filter(t=>t.bals_used.some(t=>e.includes(t))).map(e=>e.id)),Wi=Object.freeze({layers:Object.freeze(Ii.filter(e=>e.layered).map(e=>Object.freeze([...e.order]))),curedLast:Object.freeze(qs.filter(e=>e.curedLast).map(e=>Object.freeze({affId:e.id,pool:Object.freeze([...new Set(Ii.filter(t=>"tree"!==t.class&&t.order.includes(e.id)).flatMap(e=>e.order).filter(t=>t!==e.id))])})))}),Yi=e=>new Set(Ii.filter(t=>e.has(t.id)).flatMap(e=>e.order)),Ki=Yi(Vi("herb")),Qi=Yi(Vi("smoke")),Xi=new Map(Li.map(e=>[e.id,e.aff])),ea=new Map(Zi.map(e=>[e.profession,e.pools])),ta=(()=>{const e=new Map;for(const t of Us)for(const n of t.skills)e.set(n,e.has(n)?null:t.id);return new Map([...e].filter(([,e])=>null!==e))})(),na=Object.freeze({epsilon:1e-4,forkCap:256}),ra=(e,t)=>{if(!e)throw new Error(`insight engine: ${t}`)},sa=e=>Object.keys(e).sort().map(t=>`${t}=${!0===e[t]?"t":e[t]}`).join(","),ia=(e,t)=>{let n=0;for(const r of Object.keys(e))if(Object.hasOwn(t,r)){if(e[r]!==t[r]){const s=!0===e[r]?1:e[r],i=!0===t[r]?1:t[r];n+=Math.abs(s-i)}}else n+=1;for(const r of Object.keys(t))Object.hasOwn(e,r)||(n+=1);return n},aa=e=>Object.freeze({p:e.p,affs:Object.freeze({...e.affs})}),oa=e=>({p:e.p,affs:{...e.affs}}),da=e=>{const t=e.reduce((e,t)=>e+t.p,0);if(ra(t>0,"cannot normalize a belief with zero total mass"),Math.abs(t-1)>1e-12)for(const n of e)n.p/=t;return e},la=Object.freeze([]),ca=(e,t,{contradiction:n=!1}={})=>{ra(Array.isArray(e)&&e.length>0,"finalizeForks needs at least one fork");const r=t?.growth??na;let s=(e=>{const t=new Map;for(const n of e){const e=sa(n.affs),r=t.get(e);r?r.p+=n.p:t.set(e,{p:n.p,affs:n.affs,encoding:e})}return[...t.values()]})(e);s=da(s);const{forks:i,capDiagnostic:a}=((e,t)=>{if(t<=0||e.length<=t)return{forks:e,capDiagnostic:null};const n=[...e].sort((e,t)=>t.p-e.p||(e.encoding<t.encoding?-1:1)).slice(0,t);return{forks:da(n),capDiagnostic:{type:"forkCapExceeded",beforeCount:e.length,afterCount:n.length,forkCap:t}}})(s,r.forkCap??na.forkCap);return s=((e,t)=>{if(t<=0||e.length<2)return e;const n=e.filter(e=>e.p>=t);if(0===n.length||n.length===e.length)return e;for(const r of e){if(r.p>=t)continue;let e=null,s=1/0;for(const t of n){const n=ia(r.affs,t.affs);(n<s||n===s&&(t.p>e.p||t.p===e.p&&t.encoding<e.encoding))&&(e=t,s=n)}e.p+=r.p}return n})(i,r.epsilon??na.epsilon),s.sort((e,t)=>e.encoding<t.encoding?-1:e.encoding>t.encoding?1:0),!0===t?.guards?Object.freeze({forks:Object.freeze(s.map(aa)),contradiction:n,diagnostics:a?Object.freeze([Object.freeze(a)]):la}):{forks:s.map(oa),contradiction:n,diagnostics:a?[a]:la}},fa=e=>!1===e.contradiction&&0===e.diagnostics.length,ua=(e,t)=>!0===t?.guards?Object.freeze({forks:Object.freeze(e.forks.map(aa)),contradiction:!0,diagnostics:e.diagnostics}):{forks:e.forks,contradiction:!0,diagnostics:e.diagnostics},pa=({guards:e=!1}={})=>{const t={forks:[{p:1,affs:{}}],contradiction:!1,diagnostics:la};return e?Object.freeze({...t,forks:Object.freeze(t.forks.map(aa))}):t},ha=e=>"countable"!==e.kind||1,ma=(e,t)=>{const n=e.affById.get(t);return ra(n,`unknown affliction '${t}'`),n},ga=Object.freeze(["uniform","firstMissing","ordered"]),ba=new Set,ya=(e,t,n,r=ba)=>{let s=((e,t)=>{let n=e;for(const r of t.layers){const e=r.find(e=>n.includes(e));e&&(n=n.filter(t=>!r.includes(t)||t===e))}for(const r of t.curedLast)n.includes(r.affId)&&r.pool.some(e=>n.includes(e))&&(n=n.filter(e=>e!==r.affId));return n})(Object.keys(e),n.cureMasks);if(t.ordered){const e=t.order.find(e=>s.includes(e));s=s.filter(n=>!t.order.includes(n)||n===e)}return t.order.filter(e=>s.includes(e)&&!r.has(e))},va=(e,t,n)=>{const r=ma(n,t),s={...e};if("countable"===r.kind){const e=s[t]-1;e<=r.min?delete s[t]:s[t]=e}else delete s[t];if(r.curesTo){const e=ma(n,r.curesTo);s[e.id]=ha(e)}return s},ka=Object.freeze(["=","!=","<","<=",">",">="]),wa=(e,t,n)=>{switch(t){case"=":return e===n;case"!=":return e!==n;case"<":return e<n;case"<=":return e<=n;case">":return e>n;case">=":return e>=n;default:return ra(!1,`unknown comparison operator '${t}'`),!1}},Ia=Object.freeze({afflicted:(e,t,n)=>{const r=ma(n,t.affId),s="countable"!==r.kind||r.max;return fa(e)&&e.forks.every(e=>e.affs[r.id]===s)?e:ca(e.forks.map(e=>{const t={...e.affs};if("countable"===r.kind){const e=t[r.id]??r.min;t[r.id]=Math.min(e+1,r.max)}else t[r.id]=!0;return{p:e.p,affs:t}}),n)},afflictedOneOf:(e,t,n)=>{const{pool:r,mode:s}=t;ra(Array.isArray(r)&&r.length>0,"afflictedOneOf needs a non-empty pool"),ra(ga.includes(s),`unknown afflictedOneOf mode '${s}'`);const i=new Map(r.map(e=>[e,ma(n,e)]));if(fa(e)&&e.forks.every(e=>r.every(t=>Object.hasOwn(e.affs,t))))return e;const a=[];for(const o of e.forks){if("uniform"===s){const e=o.p/r.length;for(const t of r){const n={...o.affs};Object.hasOwn(n,t)||(n[t]=ha(i.get(t))),a.push({p:e,affs:n})}continue}const e=r.filter(e=>!Object.hasOwn(o.affs,e));if(0===e.length){a.push({p:o.p,affs:o.affs});continue}if("ordered"===s){const t=e[0];a.push({p:o.p,affs:{...o.affs,[t]:ha(i.get(t))}});continue}const t=o.p/e.length;for(const n of e)a.push({p:t,affs:{...o.affs,[n]:ha(i.get(n))}})}return ca(a,n)},advanced:(e,t,n)=>{ra(Array.isArray(t.rungs)&&t.rungs.length>0,"advanced needs rungs");const r=new Set,s=new Map;for(const o of t.rungs){ra(o&&"string"==typeof o.affId,"advanced rungs need an affId"),ra(!r.has(o.affId),`advanced has duplicate rung '${o.affId}'`),r.add(o.affId),s.set(o.affId,ma(n,o.affId));for(const e of[...o.gains??[],...o.consumes??[]])s.set(e,ma(n,e))}let i=!1;const a=e.forks.map(e=>{let n=-1;for(let s=0;s<t.rungs.length;s+=1)Object.hasOwn(e.affs,t.rungs[s].affId)&&(n=s);const r=t.rungs.slice(0,Math.max(0,n)),a=r.some(({affId:t})=>Object.hasOwn(e.affs,t)),o=n===t.rungs.length-1;if(o&&!a)return{p:e.p,affs:e.affs};const d={...e.affs};for(const{affId:t}of r)delete d[t];if(!o){n>=0&&delete d[t.rungs[n].affId];const e=t.rungs[n+1];d[e.affId]=ha(s.get(e.affId));for(const t of e.gains??[])d[t]=ha(s.get(t));for(const t of e.consumes??[])delete d[t]}return i=!0,{p:e.p,affs:d}});return!i&&fa(e)?e:ca(a,n)},cured:(e,t,n)=>{const r=((e,t)=>{const n=e.cureById.get(t);return ra(n,`unknown cure '${t}'`),n})(n,t.cureId);if(0===r.order.length)return e;const s=new Set(t.excludedAffs??[]),i=[];let a=!1;for(const o of e.forks){const e=ya(o.affs,r,n,s);if(0===e.length)continue;a=!0;const t=o.p/e.length;for(const r of e)i.push({p:t,affs:va(o.affs,r,n)})}return a?ca(i,n):e},confirmed:(e,t,n)=>{const r=ma(n,t.affId),{present:s}=t,i=e.forks.filter(e=>Object.hasOwn(e.affs,t.affId)===s);return i.length===e.forks.length&&fa(e)?e:i.length>0?ca(i.map(e=>({p:e.p,affs:e.affs})),n):ca(e.forks.map(e=>{const t={...e.affs};return s?t[r.id]=ha(r):delete t[r.id],{p:e.p,affs:t}}),n,{contradiction:!0})},confirmedBlocked:(e,t,n)=>{const r=ma(n,t.blockerId),{pool:s}=t;ra(Array.isArray(s)&&s.length>0,"confirmedBlocked needs a non-empty pool");for(const a of s)ma(n,a);const i=e.forks.filter(e=>Object.hasOwn(e.affs,r.id)||!s.some(t=>Object.hasOwn(e.affs,t)));return i.length===e.forks.length&&fa(e)?e:i.length>0?ca(i.map(e=>({p:e.p,affs:e.affs})),n):ca(e.forks.map(e=>({p:e.p,affs:{...e.affs,[r.id]:e.affs[r.id]??ha(r)}})),n,{contradiction:!0})},confirmedCount:(e,t,n)=>{const{pool:r,op:s,n:i}=t;ra(Array.isArray(r)&&r.length>0,"confirmedCount needs a non-empty pool"),ra(Number.isInteger(i)&&i>=0,"confirmedCount needs an integer n >= 0");for(const l of r)ma(n,l);const a=e.forks.filter(e=>wa((e=>r.reduce((t,n)=>t+(Object.hasOwn(e.affs,n)?1:0),0))(e),s,i));if(a.length===e.forks.length&&fa(e))return e;if(a.length>0)return ca(a.map(e=>({p:e.p,affs:e.affs})),n);let o=-1;for(let l=0;l<=r.length;l+=1)if(wa(l,s,i)){if(-1!==o)return ua(e,n);o=l}if(0!==o&&o!==r.length)return ua(e,n);const d=0===o;return ca(e.forks.map(e=>{const t={...e.affs};for(const s of r)d?delete t[s]:Object.hasOwn(t,s)||(t[s]=ha(ma(n,s)));return{p:e.p,affs:t}}),n,{contradiction:!0})},confirmedCounts:(e,t,n)=>{const{counts:r}=t;ra(Array.isArray(r)&&r.length>0,"confirmedCounts needs count entries");for(const i of r){ra(i&&"object"==typeof i,"confirmedCounts needs count objects"),ra(Array.isArray(i.pool)&&i.pool.length>0,"confirmedCounts needs non-empty pools"),ra(Number.isInteger(i.n)&&i.n>=0,"confirmedCounts needs integer counts >= 0");for(const e of i.pool)ma(n,e)}const s=e.forks.filter(e=>r.every(t=>((e,t)=>t.pool.reduce((t,n)=>t+(Object.hasOwn(e.affs,n)?1:0),0)===t.n)(e,t)));return s.length===e.forks.length&&fa(e)?e:s.length>0?ca(s.map(e=>({p:e.p,affs:e.affs})),n):ca([{p:1,affs:{}}],n,{contradiction:!0})},confirmedLevel:(e,t,n)=>{const{affId:r,op:s,n:i}=t,a=ma(n,r);ra("countable"===a.kind,`confirmedLevel needs a countable aff, got '${r}'`),ra(Number.isInteger(i)&&i>=0,"confirmedLevel needs an integer n >= 0");const o=e.forks.filter(e=>wa((e=>Object.hasOwn(e.affs,r)?e.affs[r]:0)(e),s,i));if(o.length===e.forks.length&&fa(e))return e;if(o.length>0)return ca(o.map(e=>({p:e.p,affs:e.affs})),n);const d=((e,t)=>{switch(e){case"=":case"<=":case">=":return t;case"<":return t-1;case">":return t+1;default:return null}})(s,i);return null===d||d<0||d>a.max||!wa(d,s,i)?ua(e,n):ca(e.forks.map(e=>{const t={...e.affs};return 0===d?delete t[r]:t[r]=d,{p:e.p,affs:t}}),n,{contradiction:!0})},converted:(e,t,n)=>{const r=ma(n,t.from),s=ma(n,t.to);return e.forks.some(e=>Object.hasOwn(e.affs,r.id))?ca(e.forks.map(e=>{if(!Object.hasOwn(e.affs,r.id))return{p:e.p,affs:e.affs};const t={...e.affs},n=t[r.id];if(delete t[r.id],"countable"===s.kind){const e=!0===n?1:n;t[s.id]=Math.min(Math.max(e,1),s.max)}else t[s.id]=!0;return{p:e.p,affs:t}}),n):e},removed:(e,t,n)=>{const r=ma(n,t.affId);return fa(e)&&!e.forks.some(e=>Object.hasOwn(e.affs,r.id))?e:ca(e.forks.map(e=>{if(!Object.hasOwn(e.affs,r.id))return{p:e.p,affs:e.affs};const t={...e.affs};return delete t[r.id],{p:e.p,affs:t}}),n)},predictedCure:(e,t,n)=>{const{forkBranches:r}=t;if(ra(Array.isArray(r),"predictedCure needs a forkBranches array"),0===r.length)return e;const s=new Map;for(const a of r)ra(Number.isInteger(a?.forkIndex)&&a.forkIndex>=0&&a.forkIndex<e.forks.length,`predictedCure fork index '${a?.forkIndex}' is out of range`),ra(!s.has(a.forkIndex),`predictedCure addresses fork ${a.forkIndex} twice`),ra(Array.isArray(a.options)&&a.options.length>0,`predictedCure fork ${a.forkIndex} needs at least one option`),s.set(a.forkIndex,a.options);const i=[];return e.forks.forEach((e,t)=>{const r=s.get(t);if(!r)return void i.push({p:e.p,affs:e.affs});let a=0;for(const n of r)ra("number"==typeof n.weight&&Number.isFinite(n.weight)&&n.weight>0,`predictedCure option weight for '${n.affId}' must be a positive number`),ra(Object.hasOwn(e.affs,n.affId),`predictedCure option '${n.affId}' is absent from fork ${t}`),a+=n.weight;for(const s of r)i.push({p:e.p*(s.weight/a),affs:va(e.affs,s.affId,n)})}),ca(i,n)}}),za=(Object.freeze(Object.keys(Ia)),(e,t)=>Object.hasOwn(e.affs,t)),_a=e=>{ra(Array.isArray(e)&&e.length>0,"affliction projection needs a non-empty pool");const t=new Set;for(const n of e)ra("string"==typeof n&&n.length>0,"affliction pool ids must be non-empty strings"),ra(!t.has(n),`affliction pool contains duplicate '${n}'`),t.add(n)},Oa=(e,t)=>t.reduce((t,n)=>t+(za(e,n)?1:0),0),$a=(e,t)=>{let n=0;for(const r of e.forks)za(r,t)&&(n+=r.p);return n},Sa=(e,t)=>{let n=!1,r=!1;for(const s of e.forks)if(za(s,t)?n=!0:r=!0,n&&r)return null;return n},Ma=(e,t)=>{_a(t);let n=0;for(const r of e.forks)t.some(e=>za(r,e))&&(n+=r.p);return n},xa=(e,t)=>{_a(t);let n=0;for(const r of e.forks)t.every(e=>za(r,e))&&(n+=r.p);return n},ja=(e,t)=>{_a(t);let n=0;for(const r of e.forks)n+=r.p*Oa(r,t);return n},Na=(e,t)=>{let n=0,r=0;for(const s of e.forks)if(za(s,t)){const e=!0===s.affs[t]?1:s.affs[t];n+=s.p,r+=e*s.p}return 0===n?0:r/n},Aa=e=>{let t=0;for(const n of e.forks)n.p>0&&(t-=n.p*Math.log2(n.p));return t},Ta=Object.freeze(["healthy","damaged","mangled"]),Ea=(e,t)=>{if(!e)throw new Error(`insight domain: ${t}`)},Ca=Object.freeze(["best","worst","distribution"]),Pa=["focus","herb","smoke","salve","restoration","sip","tree","balance","equilibrium"],Da=new WeakMap,Ra=(e,t,n=1)=>{const r=e.priorityByAff.get(t);if(!r)return null;const s=r.get(n);if(void 0!==s)return s;let i=null,a=null;for(const o of r.keys())o<=n&&(null===i||o>i)&&(i=o),(null===a||o<a)&&(a=o);return r.get(i??a)},Za=(e,t)=>t.some(t=>Array.isArray(t)?t.every(t=>Object.hasOwn(e,t)):Object.hasOwn(e,t)),Ba=(e,t,n)=>{const{tables:r,opponentClass:s,isBalanceReady:i}=n,a=new Map;if(!((e,t)=>!e.professions||null!==t&&e.professions.includes(t))(t,s)||!t.bals_req.every(i)||Za(e,t.blocks))return[];for(const o of ya(e,t,r)){const n=Ra(r,o,!0===e[o]?1:e[o]);null===n||n<1||n>25||a.set(o,{affId:o,prio:n,cureId:t.id,balsUsed:t.bals_used})}return[...a.values()]},La=e=>e.reduce((e,t)=>t.prio<e.prio||t.prio===e.prio&&t.affId<e.affId?t:e),Fa=e=>e.reduce((e,t)=>t.prio>e.prio||t.prio===e.prio&&t.affId<e.affId?t:e),qa=(e,t,n,r)=>{Ea(Ca.includes(n),`unknown predictive policy '${n}'`);const s=[],i=new Set;return e.forks.forEach((e,a)=>{const o=((e,t,n)=>{const r=n.context.curesByChannel.get(t);if(!r)return[];const s=new Map;for(const i of r)for(const t of Ba(e,i,n)){const e=s.get(t.affId);(!e||t.cureId<e.cureId)&&s.set(t.affId,t)}return[...s.values()]})(e.affs,t,r);if(0===o.length)return;let d;d="best"===n?[{...La(o),weight:1}]:"worst"===n?[{...Fa(o),weight:1}]:(e=>{const t=[...e].sort((e,t)=>e.prio-t.prio||(e.affId<t.affId?-1:1));let n=0,r=null;return t.map(e=>(e.prio!==r&&(n+=1,r=e.prio),{...e,weight:1/n}))})(o);for(const t of d)for(const e of t.balsUsed)i.add(e);s.push({forkIndex:a,options:d.map(({affId:e,weight:t})=>({affId:e,weight:t}))})}),0===s.length?null:{event:{type:"predictedCure",forkBranches:s},consumed:i}},Ga=(Object.freeze(["pendingStrip","blocked","applying"]),ea.get("occultist").unnamable),Ja=Object.freeze([...Ga]),Ua=Ja.length,Ha=e=>(Ea(Number.isInteger(e)&&e>=0&&e<=Ua,`unnamable curse count must be an integer in [0, ${Ua}] (got ${e})`),[{type:"confirmedCount",pool:[...Ja],op:0===e?"=":"<=",n:Ua-e},...Array.from({length:e},()=>({type:"afflictedOneOf",pool:[...Ja],mode:"firstMissing"}))]),Va=new Map([["unnamable",()=>Ha(0)]]),Wa="whisperingmadness",Ya="focus",Ka=({belief:e,balance:t,usedAtMs:n})=>{const r=(({belief:e,balance:t,affId:n})=>{if(null!==Sa(e,n))return null;const r=$a(e,n);Ea(r>0&&r<1,"structurally uncertain affliction needs interior probability");const s=new Map;for(const d of t.extendedBy){if(d.affId===n)continue;const t=Sa(e,d.affId);if(null===t)return null;s.set(d.affId,t)}const i=e=>((e,t)=>e.extendedBy.find(e=>t(e.affId))??e)(t,t=>t===n?e:!0===s.get(t)).predictiveDurationMs,a=i(!0),o=i(!1);return a===o?null:{probabilityAtUse:r,durationIfPresentMs:a,durationIfAbsentMs:o}})({belief:e,balance:t,affId:Wa});if(!r)return null;const s=Math.min(r.durationIfPresentMs,r.durationIfAbsentMs),i=Math.max(r.durationIfPresentMs,r.durationIfAbsentMs),a=s-500,o=s+500,d=i-500,l=i+500;if(o>d)return null;const c=n+d;return{affId:Wa,...r,usedAtMs:n,probeAtMs:n+s,resolveAbsenceAtMs:c,settleSilenceAtMs:c+1,presentIfFocusObserved:r.durationIfPresentMs<r.durationIfAbsentMs,earlyMs:s,lateMs:i,earlyWindowStartMs:a,earlyWindowEndMs:o,lateWindowStartMs:d,lateWindowEndMs:l}},Qa=Object.freeze({stalenessHalfLifeMs:6e4,entropyScaleBits:Math.log2(na.forkCap)}),Xa=(e,t={})=>{const n=t.stalenessHalfLifeMs??Qa.stalenessHalfLifeMs,r=t.entropyScaleBits??(void 0===(s=t.forkCap)?Qa.entropyScaleBits:Math.max(1,Math.log2(s)));var s;const i=Math.min(1,Aa(e.belief)/r),a=Math.max(0,e.now-e.lastObservedAt);return 1-(1-i)*(1-a/(a+n))},eo=(e,t={})=>Object.freeze({affId:e,...t.gains?{gains:Object.freeze(t.gains)}:{},...t.consumes?{consumes:Object.freeze(t.consumes)}:{}}),to=Object.freeze({head:Object.freeze([eo("damagedhead",{gains:["stupidity"]}),eo("mangledhead",{gains:["stuttering","clumsiness"]})]),torso:Object.freeze([eo("mildtrauma"),eo("serioustrauma")]),leftarm:Object.freeze([eo("damagedleftarm",{consumes:["brokenleftarm"]}),eo("mangledleftarm")]),rightarm:Object.freeze([eo("damagedrightarm",{consumes:["brokenrightarm"]}),eo("mangledrightarm")]),leftleg:Object.freeze([eo("damagedleftleg",{consumes:["brokenleftleg"]}),eo("mangledleftleg")]),rightleg:Object.freeze([eo("damagedrightleg",{consumes:["brokenrightleg"]}),eo("mangledrightleg")])}),no=Object.freeze(Object.keys(to)),ro=Object.freeze(new Map(Object.entries(to).flatMap(([e,t])=>t.map(t=>[t.affId,e])))),so=e=>{const t=to[e];return Ea(t,`unknown limb '${e}'`),t},io=(e,t)=>((e,t)=>{ra(Array.isArray(t)&&2===t.length,"ladder projection needs two rungs");const n={healthy:0,damaged:0,mangled:0};for(const s of e.forks){let e=-1;for(let n=0;n<t.length;n+=1)za(s,t[n].affId)&&(e=n);n[Ta[e+1]]+=s.p}const r=n.healthy+n.damaged+n.mangled;return 1!==r&&(n.healthy/=r,n.damaged/=r,n.mangled/=r),n})(e,so(t)),ao=Object.freeze(["observed","simulated"]),oo=no,lo=Object.freeze(["hp","mana"]),co=Object.freeze({policy:"distribution",predictionEnabled:!1,focusEnabled:!0,limbResetMs:18e4}),fo=e=>{if(e&&"object"==typeof e&&!Object.isFrozen(e)){Object.freeze(e);for(const t of Object.keys(e))fo(e[t])}return e},uo=e=>{const t={};for(const[n,r]of[...e].sort(([e],[t])=>e<t?-1:e>t?1:0))t[n]=r;return t},po=(e,t,n={})=>{Ea("string"==typeof e&&e.length>0,"createOpponentModel needs an id"),Ea(t?.affById&&t?.cureById&&t?.cureMasks,"createOpponentModel needs engine tables (affById, cureById, cureMasks)"),Ea(t?.balanceById&&t?.priorityByAff,"createOpponentModel needs domain tables (balanceById, priorityByAff)"),Ea(t?.defenceById&&t?.defenceDefaults,"createOpponentModel needs defence tables (defenceById, defenceDefaults)");const r={...co,...n};Ea(Ca.includes(r.policy),`unknown predictive policy '${r.policy}'`);const s=!0===r.guards,i=(e=>{const t=Da.get(e);if(t)return t;const n=new Map;for(const i of e.cureById.values()){if(0===i.bals_used.length||0===i.order.length)continue;const e=i.bals_used[0];n.has(e)||n.set(e,[]),n.get(e).push(i)}const r=Object.freeze([...Pa.filter(e=>n.has(e)),...[...n.keys()].filter(e=>!Pa.includes(e)).sort()]),s=Object.freeze({curesByChannel:n,channelOrder:r});return Da.set(e,s),s})(t);let a=pa({guards:s}),o=0,d=0,l="observed",c=r.policy,f=!0===r.predictionEnabled,u=null;const p=new Map([...t.balanceById.keys()].map(e=>[e,0])),h=new Map([...t.balanceById.keys()].map(e=>[e,0]));let m=null;const g=new Map,b=new Set,y=[];let v=0;const k=new Map(oo.map(e=>[e,{percent:0,lastHitAt:null}])),w=new Map;let I={shadowInstill:null,timeloop:{count:0,max:3}};const z=new Set;let _=!1,O=null,$=0,S=0;const M=()=>{_||($+=1),_=!0,O=null},x=()=>{d!==o&&(d=o,S+=1)},j=()=>{if(_&&(_=!1,z.size>0)){const e=ie();for(const t of[...z])t(e)}},N=(({tables:e,getNow:t,isBlocked:n,onChange:r})=>{Ea(e?.defenceById&&e?.defenceDefaults,"defence state needs defence tables"),Ea("function"==typeof t,"defence state needs a clock read"),Ea("function"==typeof n,"defence state needs a blocker predicate"),Ea("function"==typeof r,"defence state needs a change callback");const s=new Map,i=new Map,a=t=>{Ea("string"==typeof t&&t.length>0,"defence operation needs a def id");const n=e.defenceById.get(t);return Ea(n,`unknown defence '${t}'`),n},o=(e,n,i=t())=>{const a={have:!0===n,atMs:i};var o,d;o=s.get(e),d=a,(o?.have!==d.have||o?.atMs!==d.atMs)&&(s.set(e,a),r())},d=(e,t)=>{var n,s;n=i.get(e),s=t,(n?.phase!==s.phase||n?.stripAt!==s.stripAt||n?.restoreAt!==s.restoreAt||n?.stripConfirmed!==s.stripConfirmed)&&(i.set(e,t),r())},l=e=>{i.delete(e)&&r()},c=e=>e.applyDelayMs-e.conservativeLeadMs,f=(e,r,s,i)=>{n(r.blockedBy)?d(e,{phase:"blocked",stripAt:s,restoreAt:null,stripConfirmed:i}):d(e,{phase:"applying",stripAt:s,restoreAt:t()+c(r),stripConfirmed:i})},u=()=>{s.clear(),i.clear();for(const n of Object.keys(e.defenceDefaults))s.set(n,{have:!0,atMs:t()})};return u(),Object.freeze({have:e=>(a(e),!0===s.get(e)?.have),confirm(e,t){a(e),Ea("boolean"==typeof t,"defence confirmation needs a boolean"),o(e,t),l(e)},raise(e){a(e),o(e,!0),l(e)},strip(e){const n=a(e),r=s.get(e),d=i.get(e);!1===r?.have&&!0===d?.stripConfirmed||(o(e,!1),n.restore?f(e,n.restore,t(),!0):l(e))},startStrip(e){const n=a(e);Ea(n.restore?.stripDelayMs,`defence '${e}' has no delayed-strip policy`);const r=t()+n.restore.stripDelayMs;o(e,!1),d(e,{phase:"pendingStrip",stripAt:r,restoreAt:r+c(n.restore),stripConfirmed:!1})},maintain(){for(const[r,s]of i){if("blocked"!==s.phase)continue;const i=e.defenceById.get(r).restore;n(i.blockedBy)||d(r,{...s,phase:"applying",restoreAt:t()+c(i)})}},fireDue(n,r){const s=[...i.entries()].filter(([,e])=>"pendingStrip"===e.phase&&e.stripAt<=t()).sort((e,t)=>e[1].stripAt-t[1].stripAt||(e[0]<t[0]?-1:1));for(const[t,i]of s){const r=e.defenceById.get(t).restore;f(t,r,i.stripAt,!1),n.push({atMs:i.stripAt,defId:t})}const a=[...i.entries()].filter(([,e])=>"applying"===e.phase&&e.restoreAt<=t()).sort((e,t)=>e[1].restoreAt-t[1].restoreAt||(e[0]<t[0]?-1:1));for(const[e,t]of a)o(e,!0,t.restoreAt),l(e),r.push({atMs:t.restoreAt,defId:e})},nextInstantWithin(e){let n=1/0;for(const r of i.values()){const s="pendingStrip"===r.phase?r.stripAt:"applying"===r.phase?r.restoreAt:null;"number"==typeof s&&s>t()&&s<=e&&s<n&&(n=s)}return n},snapshotEntries:()=>[...s.entries()].map(([e,t])=>{const n=i.get(e);return[e,{...t,phase:n?.phase??null,stripAt:n?.stripAt??null,restoreAt:n?.restoreAt??null}]}),reset:u})})({tables:t,getNow:()=>o,isBlocked:e=>((e,t)=>e.forks.every(e=>Za(e.affs,t)))(a,e),onChange:M}),A=e=>{const n=t.balanceById.get(e);return Ea(n,`unknown balance '${e}'`),n},T=(e,t)=>{p.get(e)!==t&&(p.set(e,t),M())},E=(e,t)=>{h.get(e)!==t&&(h.set(e,t),M())},C=(e,t)=>{const n=A(e);if(0===n.extendedBy.length)return n;const[r,...s]=((e,t)=>{_a(t);const n=new Array(t.length+1).fill(0);for(const r of e.forks){let e=-1;for(let n=0;n<t.length;n+=1)if(za(r,t[n])){e=n;break}n[e+1]+=r.p}return n})(t,n.extendedBy.map(e=>e.affId));return r>0?n:n.extendedBy.filter((e,t)=>s[t]>0).reduce((e,t)=>t.predictiveDurationMs<e.predictiveDurationMs?t:e)},P=(e,t,n)=>{const r=C(e,t);T(e,o+(n??r.predictiveDurationMs)),E(e,o+(n??r.observedDurationMs))},D=(e,t)=>{T(e,o+C(e,t).predictiveDurationMs)},R=t.cureById.get("focus"),Z=t.balanceById.get(Ya);Ea(R&&Z,"focus timing needs canonical focus cure and balance rows");const B=()=>{null!==m&&(m=null,M())},L=()=>{if("observed"!==l||!0!==r.focusEnabled||!1!==Sa(a,"aeon")||!((e,t)=>e.forks.every(e=>!Za(e.affs,t.blocks)))(a,R))return!1;const e=e=>"focus"===e||(p.get(e)??1/0)<=o;return a.forks.every(n=>Ba(n.affs,R,{tables:t,opponentClass:u,isBalanceReady:e}).length>0)},F=()=>{!m||null===Sa(a,"whisperingmadness")&&L()||B()},q=(e,t)=>{B();const n={type:"confirmed",affId:e.affId,present:t.present},r=H(n);return((e,t)=>{T(Ya,e.usedAtMs+t);const n=[Z,...Z.extendedBy].find(e=>e.predictiveDurationMs===t);n&&E(Ya,e.usedAtMs+n.observedDurationMs)})(e,t.resolvedDurationMs),{event:n,result:r}},G=e=>{if(!m)return;if(F(),!m)return;const t=m,n=((e,t)=>{Ea(e?.affId===Wa,"focus timing classification needs an episode");const n=t-e.usedAtMs,r=n>=e.earlyWindowStartMs&&n<=e.earlyWindowEndMs;if(r===(n>=e.lateWindowStartMs&&n<=e.lateWindowEndMs))return{type:"cancelled"};const s=r?e.earlyMs:e.lateMs;return{type:"confirmed",present:s===e.durationIfPresentMs,resolvedDurationMs:s}})(t,o);if("confirmed"!==n.type)return void B();const{result:r}=q(t,n);e.push(...r.diagnostics)},J=e=>{const t=oe(e);0===t.percent&&null===t.lastHitAt||(t.percent=0,t.lastHitAt=null,M())},U=new Set(["cured","removed","converted","confirmed"]),H=e=>{const n=a,r=((e,t,n)=>{ra(e&&Array.isArray(e.forks),"apply needs a Belief"),ra(t&&"string"==typeof t.type,"apply needs an event with a type"),ra(n?.affById&&n?.cureById&&n?.cureMasks,"apply needs tables");const r=Ia[t.type];ra(r,`unknown event type '${t.type}'`);const s=r(e,t,n);return 0===s.diagnostics.length?s:!0===n.guards?Object.freeze({forks:s.forks,contradiction:s.contradiction,diagnostics:Object.freeze(s.diagnostics.map(e=>e.eventType?e:Object.freeze({...e,eventType:t.type})))}):{forks:s.forks,contradiction:s.contradiction,diagnostics:s.diagnostics.map(e=>e.eventType?e:{...e,eventType:t.type})}})(a,e,t);return r!==a&&(a=r,((e,n,r)=>{if(!U.has(r.type))return;if("confirmed"===r.type&&!1!==r.present)return;let s=!1;for(const t of k.values())if(0!==t.percent||null!==t.lastHitAt){s=!0;break}if(s){if("removed"===r.type||"converted"===r.type||"confirmed"===r.type){const t="converted"===r.type?r.from:r.affId;if(t){const r=ro.get(t);if(r){const s=$a(e,t);s>0&&$a(n,t)<s&&J(r)}}return}if("cured"===r.type){const s=t.cureById.get(r.cureId);if(!s||!s.order)return;for(const t of s.order){const r=ro.get(t);if(r){const s=$a(e,t);s>0&&$a(n,t)<s&&J(r)}}}}})(n,r,e),N.maintain(),M()),r},V=(e,t)=>{g.get(e)!==t&&(g.set(e,t),M())},W=e=>{b.delete(e),g.delete(e)&&M()},Y=(e,n)=>{const r=t.affById.get(e);"timed"===r?.kind&&V(e,o+(n??r.durationMs))},K=(e,n)=>{const r=t.affById.get(e);if("timed"===r?.kind){const t=o+(n??r.durationMs),s=g.get(e);V(e,void 0===s?t:Math.max(s,t))}},Q=()=>{for(const e of[...g.keys()])0===$a(a,e)&&W(e)},X=(e,t)=>{const n=[...g.entries()].filter(([,e])=>e<=o).sort((e,t)=>e[1]-t[1]||(e[0]<t[0]?-1:1));for(const[r,s]of n){const n=Va.get(r),i=void 0!==n&&"observed"===l&&b.has(r)&&1===$a(a,r);if(W(r),$a(a,r)>0){const n=H({type:"removed",affId:r});t.push(...n.diagnostics),e.push({affId:r,atMs:s}),F()}if(i)for(const e of n()){const n=H(e);t.push(...n.diagnostics),n.contradiction&&t.push({type:"contradiction",event:e})}}},ee=(e,t)=>{const n=y.filter(({atMs:e})=>e<=o).sort((e,t)=>e.atMs-t.atMs||e.sequence-t.sequence);for(const r of n){y.splice(y.indexOf(r),1),M();const n=H(r.event);t.push(...n.diagnostics),Q(),F(),e.push({atMs:r.atMs,cureId:r.event.cureId})}},te=(e,n)=>{if(!f)return;const r=e=>(p.get(e)??1/0)<=o;let s=!0;for(;s;){s=!1;for(const d of i.channelOrder){const l=p.get(d);if(void 0===l||l>o)continue;const f=qa(a,d,c,{tables:t,context:i,opponentClass:u,isBalanceReady:r});if(!f)continue;const h=a,m=H(f.event);n.push(...m.diagnostics),"focus"===d&&B();for(const e of f.consumed)D(e,h);e.push({atMs:o,channelId:d,policy:c,event:f.event,consumed:[...f.consumed].sort()}),F(),s=!0}}Q()},ne=(e,t)=>{if(!m)return;if(F(),!m)return;const n=m,r=((e,t)=>t<e.settleSilenceAtMs?null:{type:"confirmed",present:e.durationIfPresentMs===e.lateMs,resolvedDurationMs:e.lateMs})(n,o);if(!r)return;const{event:s,result:i}=q(n,r);t.push(...i.diagnostics),i.contradiction&&t.push({type:"contradiction",event:s}),e.push({atMs:o,event:s})},re=(e,t)=>{let n=1/0;for(const[,r]of g)r>o&&r<=e&&r<n&&(n=r);for(const{atMs:r}of y)r>o&&r<=e&&r<n&&(n=r);const s=N.nextInstantWithin(e);s<n&&(n=s);for(const i of k.values()){const t=null===i.lastHitAt?null:i.lastHitAt+r.limbResetMs;null!==t&&t>o&&t<=e&&t<n&&(n=t)}if(t)for(const r of i.channelOrder){const t=p.get(r);void 0!==t&&t>o&&t<=e&&t<n&&(n=t)}return m&&m.settleSilenceAtMs>o&&m.settleSilenceAtMs<=e&&m.settleSilenceAtMs<n&&(n=m.settleSilenceAtMs),n},se=()=>{const e=(e=>{const t={};for(const n of e.forks)for(const e of Object.keys(n.affs))t[e]=(t[e]??0)+n.p;return t})(a),n={};for(const s of Object.keys(e).sort())n[s]="countable"===t.affById.get(s)?.kind?{probability:e[s],count:Na(a,s)}:{probability:e[s]};const r={};for(const t of oo)r[t]={percent:k.get(t).percent,stages:io(a,t)};return{mode:l,policy:c,predictionEnabled:f,class:u,entropy:Aa(a),forkCount:a.forks.length,affs:n,expiries:uo(g.entries()),pendingCures:y.slice().sort((e,t)=>e.atMs-t.atMs||e.sequence-t.sequence).map(({atMs:e,event:t})=>({atMs:e,cureId:t.cureId,excludedAffs:[...t.excludedAffs]})),limbs:r,stats:uo([...w.entries()].map(([e,t])=>[e,{...t}])),defs:uo(N.snapshotEntries()),skillState:s?JSON.parse(JSON.stringify(I)):I}},ie=()=>{null===O&&(O=s?fo(se()):se());const n=O,i={};for(const[e,t]of[...p.entries()].sort(([e],[t])=>e<t?-1:e>t?1:0))i[e]={readyAtMs:t,remainingMs:Math.max(0,t-o)};const a={id:e,mode:n.mode,policy:n.policy,predictionEnabled:n.predictionEnabled,class:n.class,now:o,lastObservedAt:d,staleness:Xa(de,{stalenessHalfLifeMs:r.stalenessHalfLifeMs,forkCap:t.growth?.forkCap}),entropy:n.entropy,forkCount:n.forkCount,affs:n.affs,balances:i,expiries:n.expiries,pendingCures:n.pendingCures,limbs:n.limbs,stats:n.stats,defs:n.defs,skillState:n.skillState};return s?fo(a):a},ae=(e,t,n)=>{switch(t){case"=":return e===n;case"!=":return e!==n;case"<":return e<n;case"<=":return e<=n;case">":return e>n;case">=":return e>=n;default:Ea(!1,`unknown balance remaining comparison '${t}'`)}},oe=e=>{const t=k.get(e);return Ea(t,`unknown limb '${e}'`),t},de={id:e,get revision(){return $},get timeEpoch(){return S},get now(){return o},get mode(){return l},get policy(){return c},get class(){return u},get lastObservedAt(){return d},get belief(){return a},isPredictionEnabled:()=>f,isBalanceReady:e=>(A(e),(p.get(e)??0)<=o),isObservationBalanceReady:e=>(A(e),(h.get(e)??0)<=o),balanceRemainingProbability:(e,{op:n,ms:r,affIds:s=[]})=>{A(e),Ea("number"==typeof r&&Number.isFinite(r)&&r>=0,"balance remaining probability needs a non-negative finite ms"),Ea(Array.isArray(s),"balance remaining probability affIds must be an array");const i=new Set;for(const a of s)Ea(t.affById.has(a),`unknown affliction '${a}'`),Ea(!i.has(a),`balance remaining probability repeats '${a}'`),i.add(a);let d=0;for(const t of a.forks){if(!s.every(e=>Object.hasOwn(t.affs,e)))continue;let i=p.get(e)??0;if("focus"===e&&m){const e=Object.hasOwn(t.affs,m.affId)?m.durationIfPresentMs:m.durationIfAbsentMs;i=m.usedAtMs+e}ae(Math.max(0,i-o),n,r)&&(d+=t.p)}return d},getBalanceTimingInference:e=>(A(e),"focus"===e&&m?m:null),haveDef:N.have,getStat:e=>{Ea(lo.includes(e),`unknown stat '${e}'`);const t=w.get(e);return t?{...t}:null},limbPercent:e=>oe(e).percent,limbStages:e=>(oe(e),io(a,e)),getSkillState:()=>s?fo(JSON.parse(JSON.stringify(I))):I,nextInterestingAt({prediction:e=f,includeDue:t=!1}={}){if(t&&e)for(const r of i.channelOrder){const e=p.get(r);if(void 0!==e&&e<=o)return o}const n=re(1/0,e);return Number.isFinite(n)?n:null},apply:e=>{Ea(e&&"string"==typeof e.type,"apply needs an event with a type"),Ea("elapsed"!==e.type&&"predictedCure"!==e.type,`'${e.type}' is not an observation — it is produced by the simulation itself`);const n="cured"===e.type?t.cureById.get(e.cureId):null,r=void 0!==n?.delayMs,i=[];let d=!1;"cured"===e.type&&"focus"===e.cureId?G(i):m&&((e,t)=>"cured"===e.type?!0===t?.order.includes(Wa):"afflictedOneOf"===e.type?e.pool.includes(Wa):"converted"===e.type?"whisperingmadness"===e.from||"whisperingmadness"===e.to:["afflicted","removed","confirmed"].includes(e.type)&&"whisperingmadness"===e.affId)(e,n)&&B();const l=a,c=r?{contradiction:!1,diagnostics:[]}:H(e);switch(d||=c.contradiction,i.push(...c.diagnostics),e.type){case"afflicted":Y(e.affId,e.durationMs),f=e.affId,Va.has(f)&&g.has(f)&&1===$a(a,f)&&b.add(f);break;case"afflictedOneOf":for(const t of e.pool)K(t,e.durationMs);break;case"confirmed":e.present&&(e=>{const n=t.affById.get(e);"timed"!==n?.kind||g.has(e)||V(e,o+n.durationMs)})(e.affId);break;case"converted":W(e.from),Y(e.to);break;case"cured":if(n){for(const e of n.bals_used)P(e,l);r&&((e,t)=>{y.push({atMs:o+t,sequence:v,event:{type:"cured",cureId:e.cureId,excludedAffs:[...e.excludedAffs??[]]}}),v+=1,M()})(e,n.delayMs),"focus"===n.id&&(e=>{if(!L())return;const t=Ka({belief:e,balance:Z,usedAtMs:o});t&&(m=s?fo(t):t,M())})(l)}}var f;return Q(),F(),x(),j(),{contradiction:d,diagnostics:i}},elapsed:e=>{Ea("number"==typeof e&&Number.isFinite(e)&&e>=0,"elapsed needs a non-negative dtMs");const t=o+e;e>0&&(S+=1);const n=[],s=[],i=[],a=[],d=[],l=[],c=[];for(;;){X(n,c),ee(s,c),N.fireDue(i,a),te(d,c),ne(l,c);const e=re(t,f);if(!Number.isFinite(e))break;o=e}o=t;for(const f of k.values())null!==f.lastHitAt&&o-f.lastHitAt>=r.limbResetMs&&(f.percent=0,f.lastHitAt=null,M());return j(),{expired:n,resolvedCures:s,resolvedDefenceStrips:i,restoredDefs:a,predicted:d,timingConfirmations:l,diagnostics:c}},snapshot:ie,onChange:e=>(Ea("function"==typeof e,"onChange needs a function"),z.add(e),()=>z.delete(e)),setMode(e){Ea(ao.includes(e),`unknown observation mode '${e}'`),l!==e&&(l=e,M()),"simulated"===e&&(b.clear(),B()),"observed"===e&&x(),j()},setPolicy(e){Ea(Ca.includes(e),`unknown predictive policy '${e}'`),c!==e&&(c=e,M()),j()},enablePrediction(){f||(f=!0,M()),j()},disablePrediction(){f&&(f=!1,M()),j()},setClass(e){const t="string"==typeof e&&e.trim()?e.trim().toLowerCase():null;u!==t&&(u=t,M()),j()},consumeBalance(e,t){A(e),P(e,a,t),j()},setStat(e,t){Ea(lo.includes(e),`unknown stat '${e}'`),Ea("number"==typeof t&&Number.isFinite(t),"setStat needs a number");const n=w.get(e);n&&n.value===t&&n.atMs===o||(w.set(e,{value:t,atMs:o}),M()),j()},confirmDef(e,t){N.confirm(e,t),j()},raiseDef(e){N.raise(e),j()},stripDef(e){N.strip(e),j()},startDefStrip(e){N.startStrip(e),j()},hitLimb(e,t){Ea("number"==typeof t&&Number.isFinite(t)&&t>=0,"hitLimb needs a non-negative percent");const n=oe(e),r=n.percent+t>=100,s=r?0:n.percent+t,i=r?null:o;return n.percent===s&&n.lastHitAt===i||(n.percent=s,n.lastHitAt=i,M()),j(),{advanced:r,percent:s}},resetLimb(e){const t=oe(e);0===t.percent&&null===t.lastHitAt||(t.percent=0,t.lastHitAt=null,M()),j()},updateSkillState(e){Ea(e&&"object"==typeof e,"updateSkillState needs a patch object");for(const[t,n]of Object.entries(e)){const e=I[t];null===n||"object"!=typeof n||Array.isArray(n)||null===e||"object"!=typeof e||Array.isArray(e)?e!==n&&(I[t]=n,M()):Object.entries(n).some(([t,n])=>e[t]!==n)&&(I[t]={...e,...n},M())}j()},reset(){a=pa({guards:s}),g.clear(),b.clear(),y.length=0,B();for(const e of p.keys())p.set(e,o),h.set(e,o);for(const e of k.values())e.percent=0,e.lastHitAt=null;w.clear(),N.reset(),I={shadowInstill:null,timeloop:{count:0,max:3}},M(),j()}};return Object.freeze(de)},ho=/^[A-Za-z]+$/,mo=e=>{if("string"!=typeof e)return null;const t=e.trim();return t&&ho.test(t)?t.toLowerCase():null},go=(e={})=>{const{tables:t,...n}=e;Ea(t,"createRosterModel needs config.tables");const r=!0===n.guards,s=new Map,i=new Map;let a=null,o=0;const d=new Set,l=new Set,c=()=>{if(o+=1,0===d.size)return;const e={ids:[...s.keys()],targetId:a};r&&(Object.freeze(e.ids),Object.freeze(e));for(const t of[...d])t(e)},f=e=>{let r=s.get(e);return r||(r=po(e,t,n),s.set(e,r),i.set(e,r.onChange(t=>{o+=1,((e,t)=>{for(const n of[...l])n(e,t)})(e,t)})),c()),r},u={track(e){const t=mo(e);if(!t)return null;const n=f(t);return n.setMode("observed"),n},untrack(e){const t=mo(e),n=t?s.get(t):null;return!!n&&(n.setMode("simulated"),!0)},setTarget(e){if(null===e)return null!==a&&(a=null,c()),null;const t=mo(e);if(!t)return null;const n=f(t);return a!==t&&(a=t,c()),n},get targetId(){return a},get revision(){return o},getTarget:()=>a?s.get(a)??null:null,get(e){const t=mo(e);return t?s.get(t)??null:null},list:()=>[...s.keys()],listObserved(){const e=[];for(const[t,n]of s)"observed"===n.mode&&e.push(t);return e},remove(e){const t=mo(e);return!(!t||!s.has(t))&&(i.get(t)(),i.delete(t),s.delete(t),a===t&&(a=null),c(),!0)},updateDefaults(e={}){const{policy:t,predictionEnabled:r}=e;void 0!==t&&(Ea(Ca.includes(t),`unknown predictive policy '${t}'`),n.policy=t),void 0!==r&&(n.predictionEnabled=!0===r);for(const n of s.values())void 0!==t&&n.setPolicy(t),void 0!==r&&(!0===r?n.enablePrediction():n.disablePrediction())},reset(e){const t=u.get(e);return!!t&&(t.reset(),!0)},resetAll(){for(const e of s.values())e.reset()},elapsed(e){const t={};for(const[n,r]of s)t[n]=r.elapsed(e);return t},snapshot(){const e={};for(const t of[...s.keys()].sort())e[t]=s.get(t).snapshot();return r?Object.freeze({targetId:a,opponents:Object.freeze(e)}):{targetId:a,opponents:e}},onChange:e=>(Ea("function"==typeof e,"onChange needs a function"),d.add(e),()=>d.delete(e)),onOpponentChange:e=>(Ea("function"==typeof e,"onOpponentChange needs a function"),l.add(e),()=>l.delete(e))};return Object.freeze(u)},bo=Object.freeze({lovers:/^(\w+) shakes \w+ head and a look of clarity returns to \w+ eyes\.$/,shadowmadness:/^Lucidity returns to the eyes of (\w+)\.$/,whisperingmadness:/^(\w+) ceases \w+ violent trembling\.$/}),yo=Object.freeze([Object.freeze({id:"asthma-blocks-smoke",blockerId:"asthma",balanceId:"smoke",pool:Object.freeze([...Qi].sort()),evidence:/^\w+ takes a long drag off \w+ pipe\.$/}),Object.freeze({id:"anorexia-blocks-herb",blockerId:"anorexia",balanceId:"herb",pool:Object.freeze([...Ki].sort()),evidence:/^\w+ eats a.+\.$/})]),vo=Object.freeze([Object.freeze({id:"fulminate-paralysis-on-focus",cureId:"focus",affId:"fulminated",absentAffId:"paralysis",evidence:/^Horror overcomes \w+'s face as \w+ body stiffens into paralysis\.$/})]),ko=ea.get("depthswalker"),wo=[{skill:"aeonics",id:"timeloop",handler:(e,t)=>[{type:"afflicted",affId:"timeloop"},{type:"updateSkillState",patch:{timeloop:{max:t.checkBlock("You have now aged yourself")?4:3,count:0}}}]},{skill:"aeonics",id:"timeloopProc",handler:(e,t,n)=>{const r=[],s=ko[n.skillState.shadowInstill];s&&r.push({type:"afflictedOneOf",pool:[...s],mode:"ordered"});const{count:i=0,max:a=3}=n.skillState.timeloop??{},o=i+1;return o>=a?r.push({type:"removed",affId:"timeloop"},{type:"updateSkillState",patch:{timeloop:{count:0}}}):r.push({type:"updateSkillState",patch:{timeloop:{count:o}}}),r}},{skill:"aeonics",id:"accelerate",handler:(e,t)=>{const n={type:"cured",cureId:"accelerate"};return t.nextLine("grows older before your eyes.")?[n,{...n}]:[n]}}],Io={dissipate:[{type:"statChanged",statId:"mana",delta:-.15}],palpitation:[{type:"statChanged",statId:"hp",delta:-.15}],heat:[{type:"afflicted",affId:"burning"}],creeps:[{type:"afflicted",affId:"agoraphobia"},{type:"afflicted",affId:"claustrophobia"}],oscillate:[{type:"afflicted",affId:"stupidity"},{type:"afflicted",affId:"epilepsy"}],disorientation:[{type:"afflicted",affId:"prone"},{type:"afflicted",affId:"dizziness"}],dissonance:[{type:"defStripped",defId:"shield"}],plague:[{type:"afflicted",affId:"brokenrightarm"},{type:"afflicted",affId:"brokenrightleg"},{type:"afflicted",affId:"brokenleftleg"}],lullaby:[{type:"defStripped",defId:"insomnia"}],retardation:[{type:"defStripped",defId:"speed"},{type:"afflicted",affId:"aeon"}]};Io.plauge=Io.plague;var zo={disorientation:[{type:"afflicted",affId:"dizziness"}],creeps:[{type:"afflicted",affId:"shyness"}],dissonance:[{type:"afflicted",affId:"dissonance"}]},_o=e=>(e.args.info??"").toLowerCase(),Oo=[{skill:"crystalism",id:"destabilise",handler:e=>(Io[_o(e)]??[]).map(e=>({...e}))},{skill:"crystalism",id:"vibeTick",handler:e=>(zo[_o(e)]??[]).map(e=>({...e}))}],$o=e=>(t,n,r)=>"thirdPerson"===t.matchType?e(t,n,r):[],So=(e,t)=>t.some(t=>e.have(t)),Mo={body:e=>e.have("anorexia")?[{type:"cured",cureId:"epidermal to body"}]:So(e,["hypothermia","heartseed","serioustrauma","mildtrauma","calcifiedtorso"])?[{type:"cured",cureId:"restoration to torso"}]:[{type:"cured",cureId:"mending to body"}],head:e=>So(e,["damagedhead","mangledhead","calcifiedskull"])?[{type:"cured",cureId:"restoration to head"}]:e.have("stuttering")?[{type:"cured",cureId:"epidermal to head"}]:e.have("unblind")||e.have("undeaf")?[{type:"afflicted",affId:"undeaf"}]:[],arms:e=>So(e,["damagedleftarm","damagedrightarm","mangledleftarm","mangledrightarm"])?[{type:"cured",cureId:"restoration to arms"}]:[{type:"cured",cureId:"mending to arms"}],legs:e=>So(e,["damagedleftleg","damagedrightleg","mangledleftleg","mangledrightleg"])?[{type:"cured",cureId:"restoration to legs"}]:[{type:"cured",cureId:"mending to legs"}],skin:e=>So(e,["frozen","shivering","frostbite"])?[{type:"cured",cureId:"caloric"}]:[{type:"defRaised",defId:"insulation"}]};Mo.torso=Mo.body;var xo=[{skill:"curing",id:"apply",handler:$o((e,t,n)=>{const r=(e.args.info??"").toLowerCase();return Mo[r]?Mo[r](n):[]})},{skill:"curing",id:"health",handler:$o(e=>{const t=`health to ${(e.args.info??"").toLowerCase()}`;return qi.has(t)?[{type:"cured",cureId:t}]:[]})},{skill:"curing",id:"smoke",handler:$o((e,t,n)=>So(n,["aeon","deadening","tension","unweavingspirit"])?[{type:"cured",cureId:"cinnabar"}]:So(n,["disloyalty","hellsight","manaleech","slickness"])?[{type:"cured",cureId:"realgar"}]:[])},{skill:"curing",id:"focus",handler:$o(()=>[{type:"cured",cureId:"focus"}])},{skill:"tattoos",id:"tree",handler:$o(()=>[{type:"cured",cureId:"tree"}])},{skill:"tattoos",id:"shield",handler:$o(()=>[{type:"defRaised",defId:"shield"}])},{skill:"defense",id:"prismatic",handler:$o(()=>[{type:"defRaised",defId:"prismatic"}])},{skill:"venom",id:"shrugging",handler:$o(()=>[{type:"cured",cureId:"shrugging"}])}],jo=Object.freeze({agoraphobia:/^(\w+) is gripped with fear, staring out with terrified eyes\.$/,claustrophobia:/^(\w+) begins to pant in terror\.$/,confusion:/^(\w+) looks about bemusedly\.$/,dementia:/^(\w+) stares about \w+ frenziedly, wild-eyed\.$/}),No=(e,t,n)=>({id:`affConfirms.${e}`,pattern:n,lifetime:"session",actor:1,handler:()=>[{type:"confirmed",affId:t,present:!0}]}),Ao=(e,t,n)=>({id:`affConfirms.${e}`,pattern:n,lifetime:"session",actor:1,handler:()=>[{type:"afflicted",affId:t}]}),To=[Ao("confusion","confusion",jo.confusion),Ao("dementia","dementia",jo.dementia),Ao("paralysis1","paralysis",/^Horror overcomes the face of (\w+?) as \w+ body locks in paralysis\.$/),Ao("paralysis2","paralysis",/^Horror overcomes (\w+)'s face as \w+ body stiffens into paralysis\.$/),Ao("hypersomnia","hypersomnia",/^(\w+) suddenly appears tired all of a sudden\.$/),Ao("impatience","impatience",/^(\w+) shuffles \w+ feet in boredom\.$/),No("agoraphobia","agoraphobia",jo.agoraphobia),No("claustrophobia","claustrophobia",jo.claustrophobia),No("darkshade","darkshade",/^(\w+) lets out a piercing scream, as if wounded by the very sunlight\.$/),No("epilepsy","epilepsy",/^(\w+) begins to jerk and shake violently, foaming at the mouth\.$/),{id:"affConfirms.hallucinations",pattern:/^(\w+) leaps up in what is apparently an attempt at a graceful swan dive\. \w+ smacks headfirst into the ground\.$/,lifetime:"session",actor:1,handler:()=>[{type:"confirmed",affId:"hallucinations",present:!0},{type:"afflicted",affId:"prone"}]},No("masochism1","masochism",/^(\w+) smiles as \w+ rams \w+ fist into \w+ jaw\.$/),No("masochism2","masochism",/^(\w+) uses \w+ right foot to stomp on \w+ left as hard as possible\.$/),No("masochism3","masochism",/^With the heel of \w+ palm, (\w+) smacks \w+ upside the head\.$/),No("nausea","nausea",/^(\w+) doubles over, vomiting violently\.$/),No("shyness","shyness",/^(\w+) trembles with fear\.$/),{id:"affConfirms.sleep",pattern:/^(\w+)'s eyes close suddenly as \w+ falls asleep\.$/,lifetime:"session",actor:1,handler:()=>[{type:"afflicted",affId:"prone"}]},No("shivering","shivering",/^(\w+) shivers particularly intensely\.$/),No("burning","burning",/^The fires consuming (\w+) diminish somewhat\.$/)],Eo=ea.get("occultist"),Co=/^Horror overcomes \w+'s face as \w+ body stiffens into paralysis\.$/,Po=["brokenrightarm","brokenleftarm","brokenrightleg","brokenleftleg"],Do=["asthma","slickness"],Ro=Eo.chimera.filter(e=>"hallucinations"!==e),Zo=(e,t)=>{for(let n=Math.max(0,e.currentLineIndex+1);n<e.lines.length;n+=1){const r=e.lines[n];if(r.isPrompt)break;if(!r.isHtml&&null!==r.text)for(const e of Ro)if(mo(jo[e].exec(r.text)?.[1])===t)return e}return"hallucinations"},Bo=e=>{const t=e.queuedCommand("c!p!w!t"),n=t?t.match(/COMMAND FIRELORD AT \w+ (\w+)/):null;return n?n[1].toLowerCase():null},Lo=[{skill:"domination",id:"humbugCommand",handler:()=>[{type:"afflicted",affId:"addiction"}]},{skill:"domination",id:"houndCommand",handler:()=>[{type:"afflicted",affId:"weariness"}]},{skill:"domination",id:"stormCommand",handler:()=>[{type:"afflicted",affId:"clumsiness"}]},{skill:"domination",id:"stormCommand2",handler:()=>[{type:"confirmed",affId:"clumsiness",present:!0}]},{skill:"domination",id:"bloodleechCommand",handler:()=>[{type:"afflicted",affId:"haemophilia"}]},{skill:"domination",id:"sycophantCommand",handler:()=>[{type:"afflicted",affId:"weakenedmind"}]},{skill:"domination",id:"slimeCommand",handler:(e,t)=>[{type:"afflicted",affId:"slimeobscure"},{type:"confirmed",affId:"asthma",present:t.checkBlock(Co)}]},{skill:"domination",id:"chimeraCommandDeaf",handler:()=>[{type:"confirmed",affId:"undeaf",present:!1}]},{skill:"domination",id:"chimeraCommand",handler:(e,t,n)=>[{type:"confirmed",affId:"undeaf",present:!0},{type:"afflicted",affId:Zo(t,n.id)}]},{skill:"domination",id:"bubonisCommand",handler:(e,t,n)=>n.haveDef("fangbarrier")?t.nextLine("The protective coating covering the skin of")?[{type:"confirmed",affId:"asthma",present:!0},{type:"afflicted",affId:"slickness"}]:[{type:"afflicted",affId:"asthma"}]:[{type:"afflictedOneOf",pool:[...Do],mode:"ordered"}]},{skill:"domination",id:"wormCommand",handler:()=>[{type:"afflicted",affId:"palpatarfeed"}]},{skill:"domination",id:"wormTick",handler:()=>[{type:"afflicted",affId:"healthleech"}]},{skill:"domination",id:"croneCommand",handler:()=>[{type:"afflictedOneOf",pool:[...Po],mode:"firstMissing"}]},{skill:"domination",id:"cronePrimebond",handler:()=>[{type:"afflictedOneOf",pool:[...Po],mode:"firstMissing"}]},{skill:"domination",id:"abominationCommandFail",handler:()=>[{type:"removed",affId:"cleanseaura"}]},{skill:"domination",id:"gremlinCommand",handler:()=>[{type:"defStripped",defId:"shield"}]},{skill:"domination",id:"gremlinCommandFail",handler:()=>[{type:"defStripped",defId:"shield"}]},{skill:"domination",id:"firelordCommand",handler:(e,t)=>{const n=Bo(t);return"manaleech"===n?[{type:"confirmed",affId:"manaleech",present:!0},{type:"removed",affId:"manaleech"},{type:"afflicted",affId:"anorexia"}]:"healthleech"===n?[{type:"confirmed",affId:"healthleech",present:!0}]:"whisperingmadness"===n?[{type:"confirmed",affId:"whisperingmadness",present:!0},{type:"removed",affId:"whisperingmadness"},{type:"afflicted",affId:"recklessness"}]:[]}},{skill:"domination",id:"firelordCommandFail",handler:(e,t)=>{const n=Bo(t);return n?[{type:"confirmed",affId:n,present:!1}]:[]}},{skill:"domination",id:"wormPrimebond",handler:()=>[{type:"afflicted",affId:"nausea"}]},{skill:"domination",id:"gremlinPrimebond",handler:()=>[{type:"afflicted",affId:"dizziness"}]},{skill:"domination",id:"gremlinPrimebond2",handler:()=>[{type:"confirmed",affId:"dizziness",present:!0}]},{skill:"domination",id:"humbugPrimebond",handler:(e,t,n)=>{const r=n.probability("addiction")>.49?-.1:-.05;return[{type:"statChanged",statId:"hp",delta:r},{type:"statChanged",statId:"mana",delta:r}]}},{skill:"domination",id:"bubonisPrimebond",handler:()=>[{type:"afflictedOneOf",pool:[...Eo.bubonis],mode:"firstMissing"}]},{skill:"domination",id:"chimeraPrimebondGas",handler:()=>[{type:"defStripped",defId:"insomnia"}]},{skill:"domination",id:"chimeraPrimebondRam",handler:()=>[{type:"afflicted",affId:"prone"}]},{skill:"domination",id:"chimeraPrimebondRoar",handler:()=>[{type:"afflicted",affId:"undeaf"},{type:"afflicted",affId:"prone"}]},{skill:"domination",id:"chimeraPrimebondUndeaf",handler:()=>[{type:"afflicted",affId:"undeaf"}]}],Fo=[{skill:"dragoncraft",id:"gust",handler:()=>[{type:"afflicted",affId:"prone"}]},{skill:"dragoncraft",id:"dragonroar",handler:(e,t)=>{if("thirdPerson"===e.matchType)return[{type:"afflicted",affId:"undeaf"}];const n=t.queuedCommand();return n&&/DRAGONROAR \w+/.test(n)?[{type:"afflicted",affId:"undeaf"}]:[]}},{skill:"dragoncraft",id:"rendTargeted",handler:(e,t,n)=>qo(n)},{skill:"dragoncraft",id:"rendUntargeted",handler:(e,t,n)=>qo(n)},{skill:"dragoncraft",id:"tailsweepHit",handler:()=>[{type:"afflicted",affId:"prone"}]},{skill:"dragoncraft",id:"dragonheal",handler:e=>"thirdPerson"===e.matchType?[{type:"cured",cureId:"dragonheal"}]:[]}],qo=e=>{const t=e.skillState.envenom;if(!t)return[];const n=Xi.get(t),r=[{type:"updateSkillState",patch:{envenom:null}}];return n&&r.unshift({type:"afflicted",affId:n}),r},Go=e=>`broken${(e??"").replace(/\s/g,"").toLowerCase()}`,Jo=e=>e.haveDef("insulation")?[{type:"defStripped",defId:"insulation"}]:[{type:"afflictedOneOf",pool:["shivering","frozen"],mode:"ordered"}],Uo=[{skill:"elementalism",id:"shalestormTick",handler:e=>[{type:"afflicted",affId:Go(e.args.limb)}]},{skill:"elementalism",id:"shalestormRaze",handler:()=>[{type:"defStripped",defId:"shield"}]},{skill:"elementalism",id:"firelash",handler:()=>[{type:"afflicted",affId:"burning"}]},{skill:"elementalism",id:"firelashLOS",handler:()=>[{type:"afflicted",affId:"burning"}]},{skill:"elementalism",id:"freeze",handler:(e,t,n)=>Jo(n)},{skill:"elementalism",id:"dehydrate",handler:()=>[{type:"afflicted",affId:"nausea"},{type:"afflicted",affId:"weariness"}]},{skill:"elementalism",id:"fulminate",handler:()=>[{type:"afflictedOneOf",pool:["fulminated","epilepsy","paralysis"],mode:"ordered"}]},{skill:"elementalism",id:"bombard",handler:()=>[{type:"afflicted",affId:"clumsiness"}]},{skill:"elementalism",id:"mudslide",handler:()=>[{type:"afflicted",affId:"slickness"},{type:"afflicted",affId:"prone"}]},{skill:"elementalism",id:"magma",handler:()=>[{type:"afflicted",affId:"scalded"}]},{skill:"elementalism",id:"emanationFire",handler:()=>[{type:"afflicted",affId:"burning"},{type:"afflicted",affId:"burning"}]},{skill:"elementalism",id:"emanationAir",handler:()=>[{type:"afflicted",affId:"paralysis"},{type:"afflicted",affId:"dizziness"}]},{skill:"elementalism",id:"emanationEarth",handler:()=>[{type:"afflicted",affId:"calcifiedtorso"}]},{skill:"elementalism",id:"emanationWater",handler:(e,t,n)=>Jo(n)},{skill:"elementalism",id:"resonanceAirMinor",handler:()=>[{type:"afflicted",affId:"asthma"}]},{skill:"elementalism",id:"resonanceAirModerate",handler:(e,t,n)=>n.have("undeaf")?[{type:"afflicted",affId:"sensitivity"}]:[{type:"afflicted",affId:"undeaf"}]},{skill:"elementalism",id:"resonanceAirMajor",handler:()=>[{type:"afflicted",affId:"healthleech"}]},{skill:"elementalism",id:"resonanceEarthMinor",handler:e=>[{type:"afflicted",affId:Go(e.args.limb)}]},{skill:"elementalism",id:"resonanceEarthModerate",handler:()=>[{type:"afflicted",affId:"paralysis"}]},{skill:"elementalism",id:"resonanceEarthMajor",handler:()=>[{type:"afflicted",affId:"crackedribs"}]},{skill:"elementalism",id:"resonanceFireMinor",handler:()=>[{type:"defStripped",defId:"temperence"}]},{skill:"elementalism",id:"resonanceFireModerate",handler:(e,t,n)=>n.have("scalded")?[{type:"afflicted",affId:"burning"}]:[{type:"afflicted",affId:"scalded"}]},{skill:"elementalism",id:"resonanceFireMajor",handler:(e,t,n)=>n.have("blistered")?[{type:"afflicted",affId:"burning"}]:[{type:"afflicted",affId:"blistered"}]},{skill:"elementalism",id:"resonanceWaterMinor",handler:()=>[{type:"afflicted",affId:"frostbite"}]},{skill:"elementalism",id:"resonanceWaterModerate",handler:()=>[{type:"afflicted",affId:"stuttering"}]},{skill:"elementalism",id:"resonanceWaterMajor",handler:()=>[{type:"afflicted",affId:"anorexia"}]}],Ho=ea.get("occultist"),Vo=Object.freeze({cloak:"cloak",speed:"speed",caloric:"insulation",frost:"temperence",levitation:"levitating",insomnia:"insomnia",kola:"kola"}),Wo=/^pinchaura(?:\s|$)/i,Yo=/^pinchaura\s+([A-Za-z]+)\s+([A-Za-z]+)$/i,Ko=/^\[System\]: Running queued (.+?) command: (.+)/,Qo=e=>[{type:"confirmedCounts",source:"readaura",counts:[{label:"physical",pool:[...Ho.physicals],n:e.args.physical},{label:"mental",pool:[...Ho.mentals],n:e.args.mental}]}],Xo=e=>{const t=[{type:"confirmedCount",pool:[...Ho.physicals,...Ho.mentals],op:e.args.met?">=":"<",n:5}];return e.args.met&&t.push({type:"afflicted",affId:"enlightenment"}),t},ed=[{skill:"occultism",id:"pinchaura",handler:(e,t,n)=>{if("firstPerson"!==e.matchType)return[];const r=mo(e.args.target);if(!r||r!==n.id)return[];const s=t.queuedCommand();if(!s||!((e,t)=>{const n=e.commands?.lastQueue;if("string"!=typeof n||!Number.isInteger(e.currentLineIndex)||e.currentLineIndex<=0)return!1;for(let r=0;r<e.currentLineIndex;r+=1){const s=e.lines[r];if(s?.isHtml||"string"!=typeof s?.text)continue;const i=Ko.exec(s.text);if(i?.[1]===n&&i[2]===t)return!0}return!1})(t,s))return[];const i=(e=>{if("string"!=typeof e)return null;const t=e.split("|").map(e=>e.trim()).filter(e=>Wo.test(e));if(1!==t.length)return null;const n=Yo.exec(t[0]);if(!n)return null;const r=Vo[n[2].toLowerCase()];return r?{targetId:mo(n[1]),defId:r}:null})(s);return i?.targetId&&i.targetId===r?[{type:"speed"===i.defId?"defStripStarted":"defStripped",defId:i.defId}]:[]}},{skill:"occultism",id:"ague",handler:(e,t,n)=>n.haveDef("insulation")?[{type:"defStripped",defId:"insulation"}]:[{type:"afflictedOneOf",pool:["shivering","frozen"],mode:"ordered"}]},{skill:"occultism",id:"instill",handler:(e,t,n)=>{const r=[{type:"statChanged",statId:"hp",delta:-.03},{type:"statChanged",statId:"mana",delta:-.03}],s=e.args.affs?.[0];return"sensitivity"===s?r.push(n.have("undeaf")?{type:"afflicted",affId:"sensitivity"}:{type:"afflicted",affId:"undeaf"}):s&&r.push({type:"afflicted",affId:s}),r}},{skill:"occultism",id:"enervate",handler:()=>[{type:"statChanged",statId:"mana",delta:-.2}]},{skill:"occultism",id:"attend",handler:()=>[{type:"afflicted",affId:"undeaf"},{type:"afflicted",affId:"unblind"}]},{skill:"occultism",id:"shrivelTargeted",handler:e=>e.args.affs?.[0]?[{type:"afflicted",affId:e.args.affs[0]}]:[]},{skill:"occultism",id:"shrivelArms",handler:()=>[{type:"afflictedOneOf",pool:["brokenrightarm","brokenleftarm"],mode:"firstMissing"}]},{skill:"occultism",id:"shrivelLegs",handler:()=>[{type:"afflictedOneOf",pool:["brokenrightleg","brokenleftleg"],mode:"firstMissing"}]},{skill:"occultism",id:"shrivelRehit",handler:e=>{return"arm"===(t=(e.args.groups?.limb??"").replace(/\s/g,"").toLowerCase())?[{type:"confirmed",affId:"brokenleftarm",present:!0},{type:"confirmed",affId:"brokenrightarm",present:!0}]:"leg"===t?[{type:"confirmed",affId:"brokenleftleg",present:!0},{type:"confirmed",affId:"brokenrightleg",present:!0}]:[{type:"confirmed",affId:`broken${t}`,present:!0}];var t}},{skill:"occultism",id:"unnamableSpeak",handler:()=>[]},{skill:"occultism",id:"unnamableVision",handler:()=>[]},{skill:"occultism",id:"regress",handler:()=>[{type:"afflicted",affId:"prone"}]},{skill:"occultism",id:"devolve",handler:()=>[{type:"afflicted",affId:"shyness"},{type:"afflicted",affId:"disloyalty"}]},{skill:"occultism",id:"whisperingmadness",handler:()=>[{type:"afflicted",affId:"whisperingmadness"}]},{skill:"occultism",id:"whisperingmadnessMiss",handler:()=>Ho.whisperingmadness.map(e=>({type:"removed",affId:e}))},{skill:"occultism",id:"cleanseaura",handler:(e,t)=>t.checkBlock("A look of sudden concern")?[{type:"afflicted",affId:"cleanseaura"}]:[{type:"removed",affId:"cleanseaura"}]}],td=ea.get("psion"),nd=(e,t)=>e.args[t]??e.args.match?.groups?.[t],rd=[{skill:"psionics",id:"splinterHit",handler:()=>[{type:"defStripped",defId:"shield"}]},{skill:"psionics",id:"splinterMiss",handler:()=>[{type:"defStripped",defId:"shield"}]},{skill:"psionics",id:"expand",handler:()=>[{type:"statChanged",statId:"mana",delta:.15}]},{skill:"psionics",id:"combustion",handler:()=>[{type:"afflicted",affId:"bloodfire"}]},{skill:"psionics",id:"blastMiss",handler:()=>[{type:"confirmedCount",pool:[...td.blast],op:"<",n:3}]},{skill:"weaving",id:"invert",handler:e=>{const t=nd(e,"old"),n=nd(e,"new");return t&&n?[{type:"converted",from:`unweaving${t}`,to:`unweaving${n}`}]:[]}}],sd=ea.get("depthswalker"),id=["depression","retribution","shadowmadness","parasite"],ad=e=>()=>[{type:"afflictedOneOf",pool:[...e],mode:"ordered"}],od=e=>()=>e.map(e=>({type:"confirmed",affId:e,present:!0})),dd=e=>{const t=e.skillState.envenom;if(!t)return[];const n=Xi.get(t),r=[{type:"updateSkillState",patch:{envenom:null}}];return n&&r.unshift({type:"afflicted",affId:n}),r},ld=[{skill:"shadowmancy",id:"reap",handler:(e,t,n)=>t.checkBlock("you corrupt the weapon's timestream.")?[]:dd(n)},{skill:"shadowmancy",id:"cull",handler:(e,t,n)=>dd(n)},{skill:"shadowmancy",id:"degeneration",handler:ad(sd.degeneration)},{skill:"shadowmancy",id:"degenerationFull",handler:od(sd.degeneration)},{skill:"shadowmancy",id:"depression",handler:ad(sd.depression)},{skill:"shadowmancy",id:"depressionFull",handler:()=>[...od(sd.depression)(),{type:"afflicted",affId:"anorexia"},{type:"afflicted",affId:"masochism"}]},{skill:"shadowmancy",id:"retribution",handler:ad(sd.retribution)},{skill:"shadowmancy",id:"retributionFull",handler:(e,t,n)=>{const r=id.reduce((e,t)=>e+n.probability(t),0);return[...od(sd.retribution)(),{type:"afflicted",affId:"anorexia"},{type:"afflicted",affId:"masochism"},{type:"statChanged",statId:"mana",delta:-.05*r}]}},{skill:"shadowmancy",id:"madness",handler:ad(sd.madness)},{skill:"shadowmancy",id:"madnessFull",handler:od(sd.madness)},{skill:"shadowmancy",id:"leach",handler:ad(sd.leach)},{skill:"shadowmancy",id:"leachFull",handler:od(sd.leach)},{skill:"shadowmancy",id:"consume",handler:()=>[{type:"statChanged",statId:"mana",delta:-.1}]},{skill:"shadowmancy",id:"mutilate",handler:()=>[{type:"statChanged",statId:"mana",delta:-.4},{type:"statChanged",statId:"hp",delta:-.4}]}],cd=ea.get("occultist"),fd=cd.moon.filter(e=>"claustrophobia"!==e&&"agoraphobia"!==e),ud=[{skill:"tarot",id:"magician",handler:()=>[{type:"statChanged",statId:"mana",delta:.25}]},{skill:"tarot",id:"priestess",handler:()=>[{type:"statChanged",statId:"hp",delta:.25}]},{skill:"tarot",id:"lovers",handler:()=>[{type:"afflicted",affId:"lovers"}]},{skill:"tarot",id:"aeon",handler:()=>[{type:"defStripStarted",defId:"speed"},{type:"afflicted",affId:"aeon"}]},{skill:"tarot",id:"aeonStrip",handler:()=>[{type:"defStripStarted",defId:"speed"}]},{skill:"tarot",id:"justice",handler:()=>[{type:"afflicted",affId:"justice"}]},{skill:"tarot",id:"deathRub",handler:(e,t,n)=>n.haveDef("insulation")?[{type:"defStripped",defId:"insulation"}]:[{type:"afflicted",affId:"shivering"}]},{skill:"tarot",id:"ruinateLovers",handler:()=>[{type:"afflicted",affId:"manaleech"}]},{skill:"tarot",id:"ruinateJustice",handler:(e,t)=>t.nextLine("violently spasms")?[]:cd.justice.map(e=>({type:"confirmed",affId:e,present:!1}))},{skill:"tarot",id:"moon",handler:(e,t)=>{const n=t.queuedCommand(),r=n?n.match(/FLING MOON AT \w+ (\w+)/):null;return r?[{type:"afflicted",affId:r[1].toLowerCase()}]:[{type:"afflictedOneOf",pool:[...fd],mode:"firstMissing"}]}}],pd=/^(\w+) stumbles, falling to the ground\.$/,hd=[{skill:"weaving",id:"cleaveHit",handler:()=>[{type:"afflicted",affId:"prone"},{type:"defStripped",defId:"shield"}]},{skill:"weaving",id:"cleaveMiss",handler:()=>[{type:"defStripped",defId:"shield"}]},{skill:"weaving",id:"overhand",handler:(e,t,n)=>n.have("prone")||n.limbPercent("head")>=87.6?[{type:"afflicted",affId:"impatience"}]:[{type:"afflicted",affId:"stupidity"},{type:"afflicted",affId:"prone"}]},{skill:"weaving",id:"hamstring",handler:(e,t)=>{const n=(e=>(e??"").replace(/\s/g,"").toLowerCase())(e.args.limb),r=[{type:"afflicted",affId:`broken${n}`}];return"thirdPerson"===e.matchType&&r.push(t.checkBlock(pd)?{type:"limbAdvance",limbId:n}:{type:"limbHit",limbId:n,percent:22.1}),r}},{skill:"weaving",id:"entwineProne",handler:()=>[{type:"afflicted",affId:"prone"}]},{skill:"weaving",id:"entwineEntangle",handler:()=>[{type:"afflicted",affId:"entangled"}]},{skill:"weaving",id:"puncture",handler:()=>[{type:"afflicted",affId:"weariness"}]},{skill:"weaving",id:"sever",handler:()=>[{type:"afflicted",affId:"clumsiness"}]},{skill:"weaving",id:"unweave",handler:e=>e.args.info?[{type:"afflicted",affId:`unweaving${e.args.info}`}]:[]},{skill:"weaving",id:"deathblow",handler:()=>[{type:"afflicted",affId:"asthma"}]},{skill:"weaving",id:"backhand",handler:()=>[{type:"afflicted",affId:"stupidity"},{type:"afflicted",affId:"dizziness"}]},{skill:"weaving",id:"exsanguinate",handler:()=>[{type:"afflicted",affId:"nausea"}]},{skill:"weaving",id:"disruption",handler:()=>[{type:"afflicted",affId:"paralysis"}]},{skill:"weaving",id:"disruption2",handler:()=>[{type:"afflicted",affId:"paralysis"}]},{skill:"weaving",id:"laceration",handler:()=>[{type:"afflicted",affId:"haemophilia"}]},{skill:"weaving",id:"laceration2",handler:()=>[{type:"afflicted",affId:"haemophilia"}]},{skill:"weaving",id:"dazzle",handler:()=>[{type:"afflicted",affId:"clumsiness"}]},{skill:"weaving",id:"rattle",handler:()=>[{type:"afflicted",affId:"epilepsy"}]},{skill:"weaving",id:"vapours",handler:()=>[{type:"afflicted",affId:"asthma"}]}],md=e=>String(e).toLowerCase(),gd=(e,t)=>`${md(e)}.${String(t).toLowerCase()}`,bd=Object.freeze([...wo,{skill:"artificing",id:"efreeti",handler:()=>[{type:"afflicted",affId:"burning"}]},{skill:"artificing",id:"stoneback",handler:()=>[{type:"defRaised",defId:"shield"}]},...Oo,...xo,...Lo,...Fo,...Uo,...ed,...rd,...ld,...ud,...hd]),yd=(e,t,n)=>({id:`classCures.${e}`,pattern:n,lifetime:"session",actor:1,handler:()=>[{type:"cured",cureId:t}]}),vd=[yd("sunTarot","dagaz",/^The globe of light illuminates (\w+) with its brilliance\.$/),yd("runewardenSun","dagaz",/^A rune like a rising sun upon the ground flares, bathing (\w+) with healing magic\.$/),yd("genericMist","generic",/^(\w+) is surrounded in a cool, refreshing mist\.$/),yd("genericGlow","generic",/^A demonic crimson glow emanates from (\w+)\.$/),yd("genericLeech","generic",/^Something pulses from within the chest of (\w+), and \w+ seems more vital\.$/)],kd=(e,t,n)=>({id:`cureConfirms.${e}`,pattern:n,lifetime:"session",actor:1,handler:()=>[{type:"confirmed",affId:t,present:!1}]}),wd=[{id:"cureConfirms.stand",pattern:/^(\w+) stands up\.$/,lifetime:"session",actor:1,handler:()=>[{type:"cured",cureId:"stand"}]},kd("lovers","lovers",/^(\w+) shakes \w+ head and a look of clarity returns to \w+ eyes\.$/),kd("whisperingmadness","whisperingmadness",/^(\w+) ceases \w+ violent trembling\.$/),{id:"cureConfirms.slimeLost",pattern:/^(\w+) finally rids \w+ of the slime covering \w+\.$/,lifetime:"session",actor:1,handler:()=>[{type:"removed",affId:"slimeobscure"}]},kd("sileris","slickness",/^(\w+) applies a (?:quicksilver droplet|sileris berry) to \w+\.$/),kd("shadowmadness","shadowmadness",/^Lucidity returns to the eyes of (\w+)\.$/),kd("unweavingspirit","unweavingspirit",/^(\w+) seems suddenly unburdened, clarity reasserting itself upon \w+ features\.$/),kd("unweavingmind","unweavingmind",/^The light behind the eyes of (\w+) reignites\.$/),kd("unweavingbody","unweavingbody",/^(\w+) suddenly seems much more vital\.$/),kd("bloodfire","bloodfire",/^The unnatural flames that burn upon the skin of (\w+) wink out\.$/)],Id=(e,t)=>({id:`curatives.${e}`,pattern:t,lifetime:"session",actor:1,handler:()=>[{type:"cured",cureId:e}]}),zd=[Id("antimony",/^(\w+) eats (?:a ginger root|an antimony flake)\.$/),Id("argentum",/^(\w+) eats (?:a lobelia seed|an argentum flake)\.$/),Id("arsenic",/^(\w+) eats (?:some bayberry bark|an arsenic pellet)\.$/),Id("aurum",/^(\w+) eats (?:a piece of kelp|an aurum flake)\.$/),Id("cuprum",/^(\w+) eats a (?:bellwort flower|cuprum flake)\.$/),Id("ferrum",/^(\w+) eats a (?:ginseng root|ferrum flake)\.$/),Id("magnesium",/^(\w+) eats a (?:bloodroot leaf|magnesium chip)\.$/),Id("plumbum",/^(\w+) eats a (?:goldenseal root|plumbum flake)\.$/),Id("stannum",/^(\w+) eats (?:some prickly ash bark|a stannum flake)\.$/),{id:"curatives.calamine",pattern:/^(\w+) eats a (?:hawthorn berry|calamine crystal)\.$/,lifetime:"session",actor:1,handler:()=>[{type:"removed",affId:"undeaf"}]},{id:"curatives.potash",pattern:/^(\w+) eats (?:some irid moss|a potash crystal)\.$/,lifetime:"session",actor:1,handler:()=>[{type:"cured",cureId:"potash"},{type:"statChanged",statId:"hp",delta:.08},{type:"statChanged",statId:"mana",delta:.08}]},{id:"curatives.restore",pattern:/^(\w+) crackles with blue energy that wreathes itself about \w+ limbs\.$/,lifetime:"session",actor:1,handler:()=>[{type:"removed",affId:"brokenrightarm"},{type:"removed",affId:"brokenrightleg"},{type:"removed",affId:"brokenleftarm"},{type:"removed",affId:"brokenleftleg"}]}],_d=(e,t,n)=>({id:`defences.${e}`,pattern:t,lifetime:"session",actor:1,handler:n}),Od=[_d("shieldHit1",/^A dizzying beam of energy strikes you as your attack rebounds off of (\w+)'s shield\.$/,()=>[{type:"defRaised",defId:"shield"}]),_d("shieldHit2",/^The magical shield surrounding (\w+) makes that impossible\.$/,()=>[{type:"defRaised",defId:"shield"}]),_d("sileris",/^A supple purple shell of sileris berry juice has formed around (\w+)\.$/,()=>[{type:"defRaised",defId:"fangbarrier"}]),_d("silerisLost",/^The protective coating covering the skin of (\w+) sloughs off\.$/,()=>[{type:"afflicted",affId:"slickness"},{type:"defStripped",defId:"fangbarrier"}]),_d("insomnia",/^(\w+) clenches \w+ fists and grits \w+ teeth\.$/,()=>[{type:"defRaised",defId:"insomnia"},{type:"confirmed",affId:"hypersomnia",present:!1}]),_d("prismaticHit",/^Your attack is repelled by the prismatic barrier surrounding (\w+)\.$/,()=>[{type:"defRaised",defId:"prismatic"}]),_d("prismaticLost",/^(\w+)'s prismatic barrier dissolves into nothing\.$/,()=>[{type:"defStripped",defId:"prismatic"}]),_d("speedStripped",/^(\w+) suddenly seems less dexterous, \w+ reactions becoming noticeably slower\.$/,()=>[{type:"defStripped",defId:"speed"}])],$d=e=>(e??"").replace(/\s/g,"").toLowerCase(),Sd=(e,t)=>Number(`${e}.${t}`),Md=[{id:"prep.limbDamage",pattern:/^As you carve into (\w+), you perceive that you have dealt (\d+)\.(\d+)% damage to \w+ (.+)\.$/,lifetime:"session",actor:1,handler:e=>[{type:"limbHit",limbId:$d(e[4]),percent:Sd(e[2],e[3])}]},{id:"prep.limbDamage2",pattern:/^As your blow lands with a crunch, you perceive that you have dealt (\d+)\.(\d+)% damage to (\w+)'s (.+)\.$/,lifetime:"session",actor:3,handler:e=>[{type:"limbHit",limbId:$d(e[4]),percent:Sd(e[1],e[2])}]},{id:"prep.interlinkDamage",pattern:/^As the immaterial cleaves the material, you perceive that you have dealt (\d+)\.(\d+)% damage to (\w+)'s (.+)\.$/,lifetime:"session",actor:3,handler:e=>[{type:"limbHit",limbId:$d(e[4]),percent:Sd(e[1],e[2])}]},{id:"prep.limbReset",pattern:/^(\w+) ceases to favour \w+ (.+)\.$/,lifetime:"session",actor:1,handler:e=>[{type:"limbReset",limbId:$d(e[2])}]},{id:"prep.limbMangle",pattern:/^(\w+)'s ((?:left|right) (?:arm|leg)) has been beaten into uselessness\.$/,lifetime:"session",actor:1,handler:e=>[{type:"limbAdvance",limbId:$d(e[2])}]},{id:"prep.calcifiedskullResolve",pattern:/^A look of pain comes over (\w+) and the bones seem to shift beneath the skin stretched across \w+ skull\.$/,lifetime:"session",actor:1,handler:()=>[{type:"converted",from:"calcifiedskull",to:"damagedhead"}]}],xd=[{defId:"insomnia",pattern:/^\w+ has insomnia, and cannot easily go to sleep\.$/},{defId:"speed",pattern:/^\w+ sense of time is heightened, and \w+ reactions are speeded\.$/},{defId:"kola",pattern:/^\w+ is feeling extremely energetic\.$/},{defId:"cloak",pattern:/^\w+ is surrounded by a cloak of protection\.$/},{defId:"insulation",pattern:/^\w+ is coated in an insulating unguent\.$/},{defId:"fangbarrier",pattern:/^\w+ is protected from the fangs of serpents\.$/},{defId:"rebounding",pattern:/^\w+ is protected from hand-held weapons with an aura of rebounding\.$/},{defId:"curseward",pattern:/^A curseward has been established about \w+ person\.$/},{defId:"selfishness",pattern:/^\w+ is feeling quite selfish\.$/},{defId:"shield",pattern:/^\w+ is surrounded by a nearly invisible magical shield\.$/}],jd={id:"occultism.readaura",lifetime:"prompt",armedBy:{trigger:"skills.readauraStart"},initState:({actorId:e})=>({actorId:e,pendingDefs:xd.map(({defId:e})=>e)}),captures:[...xd.map(({defId:e,pattern:t})=>({id:`def.${e}`,pattern:t,actor:"armed",handler:(t,n,r,s)=>(s.pendingDefs=s.pendingDefs.filter(t=>t!==e),[{type:"defConfirmed",defId:e,have:!0}])})),{id:"deaf",pattern:/^\w+ is deaf\.$/,actor:"armed",handler:()=>[{type:"removed",affId:"undeaf"}]},{id:"blind",pattern:/^\w+ is blind\.$/,actor:"armed",handler:()=>[{type:"removed",affId:"unblind"}]},{id:"counts",pattern:/^You perceive that (\w+) suffers from (\d+) physical afflictions and (\d+) mental afflictions\.$/,actor:1,handler:(e,t,n)=>Qo({args:{physical:Number(e[2]),mental:Number(e[3])}},t,n)},{id:"mana",pattern:/^You sense that the mana of (\w+) stands at (\d+) of a maximum (\d+)\.$/,actor:1,handler:(e,t,n,r)=>{const s=r.pendingDefs.map(e=>({type:"defConfirmed",defId:e,have:!1}));return r.pendingDefs=[],s.push({type:"statObserved",statId:"mana",value:Number(e[2])/Number(e[3])}),s}}]},Nd=["paralysis","asthma","healthleech","haemophilia","sensitivity","clumsiness","weariness"],Ad={indigo:()=>[{type:"afflicted",affId:"stupidity"}],orange:()=>[{type:"afflicted",affId:"paralysis"}],violet:e=>e.haveDef("speed")?[{type:"defStripped",defId:"speed"}]:[{type:"afflicted",affId:"aeon"}]},Td=e=>e.haveDef("insulation")?[{type:"defStripped",defId:"insulation"}]:[{type:"afflictedOneOf",pool:["shivering","frozen"],mode:"ordered"}],Ed=[{id:"skills.earworm",pattern:/^Your rapier sings out with a high, piercing note\.$/,lifetime:"session",actor:null,handler:()=>[{type:"confirmed",affId:"earworm",present:!0}]},{id:"skills.commandMinionMiss",pattern:/^A minion of chaos thrusts a hand in the direction of (\w+), but nothing seems to happen\.$/,lifetime:"session",actor:1,handler:()=>[{type:"confirmed",affId:"enlightenment",present:!1}]},{id:"skills.firelordPrimebond",pattern:/^(\w+) cries out in horror as \w+ body erupts into flames!$/,lifetime:"session",actor:1,handler:()=>[{type:"afflicted",affId:"burning"}]},{id:"skills.rendVenom",pattern:/^You rub some (\w+) on your wickedly sharp claws\.$/,lifetime:"session",actor:"tracked",handler:e=>[{type:"updateSkillState",patch:{envenom:e[1].toLowerCase()}}]},{id:"skills.dragoncurseAff",pattern:/^You summon your ancient power and direct the curse of (\w+) to strike down (\w+) in (\d+) seconds\.$/,lifetime:"session",actor:2,handler:e=>[{type:"updateSkillState",patch:{dragoncurse:e[1].toLowerCase()}}]},{id:"skills.dragoncurseHit",pattern:/^(\w+) convulses under the influence of some invisible force\.$/,lifetime:"session",actor:1,handler:(e,t,n)=>{const r=n.skillState.dragoncurse;if(!r)return[];const s=[{type:"updateSkillState",patch:{dragoncurse:null}}];return Fi.has(r)&&s.unshift({type:"afflicted",affId:r}),s}},{id:"skills.readauraStart",pattern:/^Studying the aura of (\w+), you look for traces of anything that may be protecting it\.$/,lifetime:"session",actor:1,handler:()=>[]},{id:"skills.whisperingmadnessTick",pattern:/^(\w+) trembles and \w+ eyes widen in terror\. \w+ looks around \w+ as if searching for something that isn't there\.$/,lifetime:"session",actor:1,handler:()=>[{type:"confirmed",affId:"whisperingmadness",present:!0}]},{id:"skills.chaosrays",pattern:/^(\w+) is hit by a (.+) ray\.$/,lifetime:"session",actor:1,handler:(e,t,n)=>e[2].replace(/ and /g,",").replace(/\s/g,"").replace(/,,/g,",").split(",").filter(Boolean).flatMap(e=>Ad[e]?.(n)??[])},{id:"skills.truename",pattern:/^Drawing back with a knowing smirk, you utter the truename of (\w+), who suddenly becomes very still and bleeds from \w+ eyes and ears\.$/,lifetime:"session",actor:1,handler:()=>[{type:"defStripped",defId:"speed"},{type:"afflicted",affId:"aeon"}]},{id:"skills.unnamableHits",pattern:/^(\w+) has been struck down by (\d) curses of the unnamable\.$/,lifetime:"session",actor:1,handler:e=>[{type:"removed",affId:"unnamable"},...Ha(Number(e[2]))]},{id:"skills.enlighten",pattern:/^You place both hands on either side of (\w+)'s head and stare straight into \w+ eyes\. Summoning all your knowledge of the occult mysteries, you will your knowledge into \w+'s mind\.$/,lifetime:"session",actor:1,handler:(e,t,n)=>Xo({args:{met:t.nextLine("You see")}},t,n)},{id:"skills.enlightenYell",pattern:/^You see (.+) yell, "No, it cannot be true! I cannot accept it! I beg of you to make it stop!"$/,lifetime:"session",actor:1,handler:(e,t,n)=>Xo({args:{met:!0}},t,n)},{id:"skills.enlightenShout",pattern:/^You see (.+) shout, "No, it cannot be true! I cannot accept it! I beg of you to make it stop!"$/,lifetime:"session",actor:1,handler:(e,t,n)=>Xo({args:{met:!0}},t,n)},{id:"skills.regressAnorexia",pattern:/^The face of (\w+) turns a particularly vibrant shade of green\.$/,lifetime:"session",actor:1,handler:()=>[{type:"afflicted",affId:"anorexia"},{type:"confirmed",affId:"prone",present:!0}]},{id:"skills.compelDiscord",pattern:/^(\w+) clutches at \w+ head as \w+ begins to mutter gibberish over and over under his breath\.$/,lifetime:"session",actor:1,handler:()=>[{type:"confirmed",affId:"healthleech",present:!0},{type:"confirmed",affId:"asthma",present:!0},{type:"afflicted",affId:"loneliness"},{type:"afflicted",affId:"dizziness"}]},{id:"skills.compelEntropyAeon",pattern:/^(\w+) twists and writhes in the grip of an unnatural force, parts of \w+ body flickering as if seen through a veil of mist\.$/,lifetime:"session",actor:1,handler:()=>[{type:"defStripped",defId:"speed"},{type:"afflicted",affId:"aeon"}]},{id:"skills.compelPotentialLimbs",pattern:/^The body of (\w+) goes slack, \w+ eyes rolling almost completely back in \w+ head as \w+ face goes a ghostly white\.$/,lifetime:"session",actor:1,handler:(e,t,n)=>["leftarm","leftleg","rightarm","rightleg"].flatMap(e=>{for(const t of["mangled","damaged","broken"])if(n.probability(`${t}${e}`)>.25)return[{type:"confirmed",affId:`${t}${e}`,present:!0}];return[]})},{id:"skills.compelPotentialFrozen",pattern:/^(\w+) twitches in the grip of some terrible power, skin splitting and cracking under its unforgiving grasp\.$/,lifetime:"session",actor:1,handler:()=>[{type:"confirmed",affId:"shivering",present:!0},{type:"confirmed",affId:"frozen",present:!0},{type:"defStripped",defId:"insulation"}]},{id:"skills.shadowInstill",pattern:/^Focusing upon .+?, you instill it with the directive of (\w+)\.$/,lifetime:"session",actor:"tracked",handler:e=>[{type:"updateSkillState",patch:{shadowInstill:e[1].toLowerCase()}}]},{id:"skills.shadowEnvenom",pattern:/^You rub some (\w+) on .+?\.$/,lifetime:"session",actor:"tracked",handler:e=>[{type:"updateSkillState",patch:{envenom:e[1].toLowerCase()}}]},{id:"skills.attuneMadness",pattern:/^You sense that (\w+) has been struck down with the (\w+) madness\.$/,lifetime:"session",actor:1,handler:e=>{const t=e[2].toLowerCase(),n=Fi.has(t)?t:`${t}madness`;return Fi.has(n)?[{type:"afflicted",affId:n}]:[]}},{id:"skills.attuneDegeneration",pattern:/^You determine that (\w+) is suffering from (\w+)\.$/,lifetime:"session",actor:1,handler:e=>{const t=e[2].toLowerCase();return Fi.has(t)?[{type:"afflicted",affId:t}]:[]}},{id:"skills.shadowstrikeMiss",pattern:/^(\w+) is not surrounded by a magical shield\.$/,lifetime:"session",actor:1,handler:()=>[{type:"defStripped",defId:"shield"}]},{id:"skills.ruinateJusticeBreak",pattern:/^An audible crack emanates from the bones in the (.+) of (\w+)\.$/,lifetime:"session",actor:2,handler:(e,t,n)=>{const r=(s=e[1],s.replace(/ and /g,",").replace(/,,/g,",").replace(/\s/g,"").split(",").filter(Boolean)).map(e=>({type:"afflicted",affId:`broken${e}`}));var s;return Nd.reduce((e,t)=>e+n.probability(t),0)>=4&&(r.push(...Td(n)),r.push({type:"afflictedOneOf",pool:["shivering","frozen"],mode:"ordered"})),r}},{id:"skills.ruinateJusticeProne",pattern:/^The broken legs of (\w+) give way, and \w+ collapses to the ground\.$/,lifetime:"session",actor:1,handler:()=>[{type:"afflicted",affId:"prone"},{type:"confirmed",affId:"brokenleftleg",present:!0},{type:"confirmed",affId:"brokenrightleg",present:!0}]},{id:"skills.wheelAgue",pattern:/^Rays of cold blue light lash out from the Wheel of Chaos, irradiating the location\.$/,lifetime:"session",actor:"room",handler:(e,t,n)=>Td(n)},{id:"skills.wheelStuttering",pattern:/^Vibrant indigo rays of light lash out from the Wheel of Chaos\.$/,lifetime:"session",actor:"room",handler:()=>[{type:"afflicted",affId:"stuttering"}]},{id:"skills.wheelBlackout",pattern:/^Rays of orange light lash out at the location from the Wheel of Chaos\.$/,lifetime:"session",actor:"room",handler:()=>[{type:"afflicted",affId:"blackout",durationMs:3e3}]},{id:"skills.stumbleProne",pattern:/^(\w+) stumbles, falling to the ground\.$/,lifetime:"session",actor:1,handler:()=>[{type:"afflicted",affId:"prone"}]},{id:"skills.namedDefenceRemoved",pattern:/^(?:His|Her|Faen) (\w+) defence is eroded away\.$/,lifetime:"session",actor:null,handler:e=>{const t=e[1].toLowerCase();return Ji.has(t)?[{type:"defStripped",defId:t}]:[]}},{id:"skills.scintillaBurn",pattern:/^Flames ignite all over the body of (\w+), fanned to intensity in an instant\.$/,lifetime:"session",actor:1,handler:()=>[{type:"afflicted",affId:"burning"}]},{id:"skills.conflagrateFail",pattern:/^You bend your will upon (\w+), attempting to rouse a conflagration to consume \w+, but to no avail\.$/,lifetime:"session",actor:1,handler:()=>[{type:"confirmedLevel",affId:"burning",op:"<",n:2}]},{id:"skills.assess",pattern:/^You glance over (\w+) and see that \w+ health is at (\d+)\/(\d+)\.$/,lifetime:"session",actor:1,handler:e=>[{type:"statObserved",statId:"hp",value:Number(e[2])/Number(e[3])}]},{id:"skills.contemplate",pattern:/^(\w+)'s mana stands at (\d+)\/(\d+)\.$/,lifetime:"session",actor:1,handler:e=>[{type:"statObserved",statId:"mana",value:Number(e[2])/Number(e[3])}]}],Cd=/^(\w+) pales as the blood drains from \w+ face\.$/,Pd=(e,t,n)=>({id:e,lifetime:"prompt",armedBy:{skill:"occultism",id:t},initState:({observedIds:e})=>({exposed:[...e]}),captures:[{id:"pale",pattern:Cd,actor:1,handler:(e,t,r,s)=>(s.exposed=s.exposed.filter(e=>e!==r.id),[{type:"afflicted",affId:n},{type:"afflicted",affId:"unnamable"}])}],finalize:e=>e.exposed.map(e=>({id:e,type:"removed",affId:n}))}),Dd=Pd("occultism.unnamableSpeak","unnamableSpeak","undeaf"),Rd=Pd("occultism.unnamableVision","unnamableVision","unblind"),Zd=Object.freeze([...zd,...vd,...wd,...To,...Od,...Ed,...Md,{id:"queues.queueTracker",pattern:/^\[System\]: Running queued (.+?) command: (.+)/,lifetime:"session",remember:e=>({queue:{name:e[1],text:e[2]}})}]),Bd=Object.freeze([Dd,Rd,jd]),Ld=(e,t)=>t instanceof RegExp?t.test(e):"string"==typeof t&&e.includes(t),Fd=(e,t)=>{const n=[e?.target,e?.target?.id,e?.victim,e?.player,e?.player?.id,e?.user];for(const r of n)if("string"==typeof r&&""!==r&&"self"!==r.toLowerCase()){const e=mo(r);if(e&&e!==t)return e}return null},qd=e=>"string"==typeof e?e:"string"==typeof e?.name?e.name:null,Gd=({adapter:e,publish:t,commandMemory:n=null,skills:r=null})=>{const s=[],i=new Map;let a=!1;const o=()=>mo(qd(e.gmcp.read("Char.Name"))),d=(t=null)=>(({lines:e=[],currentLineIndex:t=-1,actorId:n=null,timestampMs:r=0,commands:s=null}={})=>{const i=Object.freeze(e.map(e=>Object.freeze({text:"string"==typeof e.text?e.text:null,isPrompt:!0===e.isPrompt,isHtml:!0===e.isHtml}))),a=Object.freeze({queues:Object.freeze({...s?.queues??{}}),lastQueue:s?.lastQueue??null});return Object.freeze({lines:i,currentLineIndex:t,actorId:n,timestampMs:r,commands:a,nextLine:e=>{for(let n=t+1;n<i.length;n+=1){const t=i[n];if(!t.isHtml&&!t.isPrompt&&null!==t.text)return Ld(t.text,e)}return!1},checkBlock:e=>i.some(t=>null!==t.text&&Ld(t.text,e)),queuedCommand:e=>{const t=e??a.lastQueue;return null===t?null:a.queues[t]??null}})})({...e.text.snapshot(),actorId:mo(t),timestampMs:e.clock.now(),commands:n?n.snapshot():null}),l=e=>{const n=mo(qd(e));n&&n!==o()&&t("insight.ingress.room.entered",{id:n})},c=e=>{const n=(e=>{const{skill:t,id:n,matchType:r,match:s,...i}=e??{};return"string"!=typeof t||""===t||"string"!=typeof n||""===n?null:{skill:t,id:n,matchType:r??s,args:i}})(e);n&&"secondPerson"!==n.matchType&&t("insight.ingress.skill",{action:n,context:d(Fd(e,o()))})},f=t=>{if(a)for(const n of t){if("string"!=typeof n||""===n)continue;const t=md(n);i.has(t)||i.set(t,e.events.onSkillMatch(c,t))}};return Object.freeze({start(){a=!0,r?f(r()):s.push(e.events.onSkillMatch(c)),s.push(e.events.on("nexskill.error.reaction",e=>{const n=e?.action,s="string"==typeof n?.skill&&""!==n.skill?md(n.skill):null;r&&!i.has(s)||t("insight.ingress.skillError",{skill:s,id:"string"==typeof n?.id&&""!==n.id?n.id:null,line:"string"==typeof n?.originalLine?n.originalLine:null,message:e?.error?.message??String(e?.error)})})),s.push(e.events.on("IRE.Target.Set",e=>{"number"!=typeof e&&t("insight.ingress.target",{id:"string"==typeof e?e:null})})),s.push(e.events.on("Room.AddPlayer",l)),s.push(e.events.on("Room.RemovePlayer",e=>{const n=mo(qd(e));n&&n!==o()&&t("insight.ingress.room.left",{id:n})})),s.push(e.events.on("Room.Info",()=>{const n=e.gmcp.read("RoomPlayers"),r=o();t("insight.ingress.room.list",{ids:(Array.isArray(n)?n:[]).map(e=>mo(qd(e))).filter(e=>null!==e&&e!==r)})})),s.push(e.events.on("PromptEvent",()=>{t("insight.ingress.prompt",{})}))},observeSkills:f,stop(){for(a=!1;s.length>0;)s.pop()();for(const e of i.values())e();i.clear()},capture:d})},Jd=new Set(["afflicted","afflictedOneOf","cured","confirmed","confirmedBlocked","confirmedCount","confirmedCounts","confirmedLevel","converted","removed"]),Ud=e=>Math.min(1,Math.max(0,e)),Hd=({roster:e,tables:t,publish:n,notice:r,advanceToNow:s})=>{const i=new Map,a=new Set,o=(e,t)=>{((e,t,s)=>{if(s.contradiction&&(n("insight.belief.contradiction",{id:e,event:t}),"confirmedCounts"===t.type)){const n=t.counts.map((e,t)=>`${e.n} ${e.label??`pool ${t+1}`}`).join(" and ");r({text:`${"readaura"===t.source?"Readaura":"Hard count"} validation failed for ${e} — no tracked fork matched ${n}. The belief was reset. This indicates tracking drift; inspect the preceding inference.`,severity:"error"})}for(const i of s.diagnostics)"forkCapExceeded"===i.type&&(n("insight.belief.growthCapped",{id:e,event:i.eventType??t.type,beforeCount:i.beforeCount,afterCount:i.afterCount,forkCap:i.forkCap}),r({text:`fork cap hit for ${e} — ${i.beforeCount} → ${i.afterCount} forks (cap ${i.forkCap}) on '${t.type}'. Belief detail was discarded; this is a red-flag condition.`,severity:"error"}))})(e.id,t,e.apply(t))},d=t=>{const n=mo(t)??e.targetId;return n?e.track(n):null},l=e=>(s(e.id),c(e)),c=e=>({id:e.id,class:e.class,have:t=>$a(e.belief,t)>0,probability:t=>$a(e.belief,t),isBalanceReady:t=>e.isBalanceReady(t),haveDef:t=>e.haveDef(t),limbPercent:t=>e.limbPercent(t),limbStages:t=>e.limbStages(t),skillState:e.getSkillState()}),f=(e,t)=>{switch(t.type){case"defRaised":return e.raiseDef(t.defId),!0;case"defStripped":return e.stripDef(t.defId),!0;case"defStripStarted":return e.startDefStrip(t.defId),!0;case"defConfirmed":return e.confirmDef(t.defId,t.have),!0;case"statObserved":return e.setStat(t.statId,Ud(t.value)),!0;case"statChanged":{const n=e.getStat(t.statId);return n&&e.setStat(t.statId,Ud(n.value+t.delta)),!0}case"limbHit":return 1===e.limbStages(t.limbId).mangled||e.hitLimb(t.limbId,t.percent).advanced&&p(e,t),!0;case"limbReset":return e.resetLimb(t.limbId),!0;case"updateSkillState":return e.updateSkillState(t.patch),!0;case"classObserved":return e.setClass(t.class),!0;default:return!1}},u=(e,r,s)=>{const i=t.cureById.get(r.cureId);if(!i)return;if(!i.bals_req.every(t=>e.isObservationBalanceReady(t)))return;(s?mo(s.actorId)!==e.id:mo(r.id)!==e.id)||1!==i.professions?.length||i.bestowable||f(e,{type:"classObserved",class:i.professions[0]});const a=c(e);for(const t of i.blocks)Array.isArray(t)?o(e,{type:"confirmedCount",pool:t,op:"<",n:t.length}):a.have(t)&&o(e,{type:"confirmed",affId:t,present:!1});const d=(e=>e?Object.entries(bo).filter(([,t])=>!e.nextLine(t)).map(([e])=>e):[])(s);o(e,{type:"cured",cureId:i.id,excludedAffs:d}),n("insight.cure.observed",{id:e.id,cureId:i.id});for(const t of(({cure:e,view:t,context:n})=>{if(Ea(e&&Array.isArray(e.order),"cureInferenceEvents needs a cure row"),Ea(t&&"function"==typeof t.have&&"function"==typeof t.isBalanceReady,"cureInferenceEvents needs an opponent view"),!n)return[];const r=[];for(const s of yo)e.order.includes(s.blockerId)&&t.have(s.blockerId)&&t.isBalanceReady(s.balanceId)&&s.pool.some(e=>t.have(e))&&(n.checkBlock(s.evidence)||r.push({type:"confirmedBlocked",pool:[...s.pool],blockerId:s.blockerId}));for(const s of vo)e.id===s.cureId&&t.have(s.affId)&&!t.have(s.absentAffId)&&n.checkBlock(s.evidence)&&r.push({type:"confirmed",affId:s.affId,present:!0});return r})({cure:i,view:c(e),context:s}))o(e,t)},p=(e,t)=>{const r=e.belief;return o(e,(e=>({type:"advanced",rungs:so(e)}))(t.limbId)),e.belief!==r&&(e.resetLimb(t.limbId),n("insight.limb.advanced",{id:e.id,limb:t.limbId,stages:e.limbStages(t.limbId)}),!0)},h={observe(e,t=null){if(!e||"string"!=typeof e.type)return!1;const n=d(e.id);if(!n)return!1;if(s(n.id),"limbAdvance"===e.type)return p(n,e),!0;if(f(n,e))return!0;if("cured"===e.type)return u(n,e,t),!0;if(!Jd.has(e.type))throw new Error(`unknown observation type '${e.type}'`);return o(n,(e=>{switch(e.type){case"afflicted":case"removed":return{type:e.type,affId:e.affId};case"afflictedOneOf":return{type:e.type,pool:e.pool,mode:e.mode};case"confirmed":return{type:e.type,affId:e.affId,present:e.present};case"confirmedBlocked":return{type:e.type,pool:e.pool,blockerId:e.blockerId};case"confirmedCount":return{type:e.type,pool:e.pool,op:e.op,n:e.n};case"confirmedCounts":return{type:e.type,counts:e.counts,...e.source?{source:e.source}:{}};case"confirmedLevel":return{type:e.type,affId:e.affId,op:e.op,n:e.n};case"converted":return{type:e.type,from:e.from,to:e.to};case"cured":return{type:e.type,cureId:e.cureId,excludedAffs:e.excludedAffs};default:throw new Error(`cannot construct engine event '${e.type}'`)}})(e)),!0},resolveView(e){const t=d(e);return t?l(t):null},addDefinitions(e){for(const t of e){if("string"!=typeof t?.skill||"string"!=typeof t?.id||"function"!=typeof t?.handler)throw new Error("skill definitions need { skill, id, handler }");i.set(gd(t.skill,t.id),t),a.add(md(t.skill))}},listDefinitions:()=>[...i.keys()],listSkills:()=>[...a],dispatchAction({action:e,context:t}){const n=i.get(gd(e.skill,e.id));if(!n)return;const r=d(t?.actorId);if(!r)return;if("thirdPerson"===e.matchType){const t=ta.get(md(e.skill));t&&(s=e.args,a=r.id,[s.player,s.player?.id,s.user].some(e=>"string"==typeof e&&mo(e)===a))&&f(r,{type:"classObserved",class:t})}var s,a;const o=n.handler(e,t,l(r))??[];for(const i of o)h.observe({...i,id:r.id},t)}};return Object.freeze(h)},Vd=({onSubscriberError:e=null}={})=>{const t=new Map,n="function"==typeof e;return Object.freeze({on:(e,n)=>(t.has(e)||t.set(e,new Set),t.get(e).add(n),()=>{t.get(e)?.delete(n)}),off(e,n){t.get(e)?.delete(n)},raise(r,s){const i=t.get(r);if(i)for(const t of[...i])if(n)try{t(s)}catch(a){try{e({topic:r,handler:t,cause:a})}catch{}}else t(s)}})},Wd=(Object.freeze(["internal","js","eventstream"]),Object.freeze(["locked","experimental"]),(e,t,n,r)=>Object.freeze({audience:e,stability:t,payload:Object.freeze(n),description:r})),Yd=Object.freeze({"insight.ready":Wd("eventstream","locked",{},"Bootstrap reached READY."),"insight.target.changed":Wd("eventstream","locked",{id:"string | null"},"The tracked target changed (null = target cleared)."),"insight.opponent.tracked":Wd("eventstream","locked",{id:"string"},"An opponent entered observed tracking (new, or re-acquired after leaving the room)."),"insight.opponent.unobserved":Wd("eventstream","locked",{id:"string"},"A tracked opponent left observation; simulation continues on their belief."),"insight.opponent.removed":Wd("eventstream","experimental",{id:"string"},"A tracked opponent was removed from the roster. Roster lifecycle, not belief evolution: removal deliberately emits no per-aff insight.aff.lost sweep. Experimental until Phase 6 locks it."),"insight.aff.got":Wd("eventstream","locked",{id:"string",affId:"string",probability:"number"},"An affliction became present (marginal probability rose above zero) for an opponent."),"insight.aff.lost":Wd("eventstream","locked",{id:"string",affId:"string"},"An affliction left an opponent's belief (marginal probability returned to zero)."),"insight.def.got":Wd("eventstream","locked",{id:"string",defId:"string"},"A defence was observed present on an opponent."),"insight.def.lost":Wd("eventstream","locked",{id:"string",defId:"string"},"A defence was observed absent on an opponent."),"insight.affs.updated":Wd("eventstream","locked",{id:"string"},"Prompt-batched per-opponent change flush: this opponent's affliction state changed since the last flush."),"insight.opponent.updated":Wd("eventstream","locked",{id:"string"},"Prompt-batched signal that an opponent's display-visible state changed; consumers should re-read insight.state.opponents[id]."),"insight.cure.observed":Wd("eventstream","locked",{id:"string",cureId:"string"},"An opponent was observed using a cure after balance gating. Emitted at application time; a cure with delayMs changes affliction state only at resolution."),"insight.limb.advanced":Wd("eventstream","locked",{id:"string",limb:"string",stages:"{ healthy: number, damaged: number, mangled: number }"},"A limb damage ladder advanced; stages is the normalized post-transition distribution."),"insight.belief.growthCapped":Wd("js","locked",{id:"string",event:"string",beforeCount:"number",afterCount:"number",forkCap:"number"},"Red flag: fork-cap enforcement discarded hypotheses (charter §5.4). Accompanied by a high-visibility notice."),"insight.belief.contradiction":Wd("js","locked",{id:"string",event:"object"},"Evidence contradicted every hypothesis; the belief was repaired or hard-validation reset under its declared policy (charter §5.3, ADR-0035)."),"insight.ingress.skill":Wd("internal","experimental",{action:"object",context:"ObservationContext"},"Normalized nexSkills match action with its ingress-captured ObservationContext."),"insight.ingress.skillError":Wd("internal","experimental",{skill:"string | null",id:"string | null",line:"string | null",message:"string"},"nexSkills reported a definition reaction that threw (nexskill.error.reaction). The match still raises, so the action insight observes may carry a stale id or missing affs; the composition renders a warning notice."),"insight.ingress.trigger":Wd("internal","experimental",{id:"string",match:"object",context:"ObservationContext"},"A trigger-pack pattern fired, with its ingress-captured ObservationContext."),"insight.ingress.target":Wd("internal","experimental",{id:"string | null"},"Normalized IRE.Target.Set."),"insight.ingress.room.entered":Wd("internal","experimental",{id:"string"},"GMCP Room.AddPlayer, self excluded."),"insight.ingress.room.left":Wd("internal","experimental",{id:"string"},"GMCP Room.RemovePlayer."),"insight.ingress.room.list":Wd("internal","experimental",{ids:"string[]"},"GMCP Room.Info occupancy resync, self excluded."),"insight.ingress.prompt":Wd("internal","experimental",{},"Host PromptEvent boundary — drives the prompt-batched flush."),"insight.display.flush":Wd("internal","experimental",{ids:"string[]"},"The prompt-batched flush completed for these dirty opponents — the display coordinator renders on this boundary."),"insight.display.changed":Wd("internal","experimental",{id:"string"},"An opponent's display-visible state changed or the opponent became the target; drives the prompt-batched display/opponent.updated flush."),"insight.model.changed":Wd("internal","experimental",{id:"string"},"An opponent's aff marginals or observation mode changed — deliberately aff/mode-scoped, driving insight.affs.updated only (the scheduler reschedules from the roster's full per-opponent change surface)."),"insight.scheduler.elapsed":Wd("internal","experimental",{id:"string",expired:"object[]",resolvedCures:"object[]",resolvedDefenceStrips:"object[]",restoredDefs:"object[]",predicted:"object[]"},"A scheduler timer delivered an elapsed window to an opponent model."),"insight.settings.changed":Wd("internal","experimental",{document:"SettingsDocument"},"The settings document changed through the composition's settings surface (every document-mutating verb) — carries the new frozen document; runtime subscribers apply the change live (SETTINGS_AUTHORITY.md §5).")}),Kd=(e,t=new WeakMap)=>{if(!e||"object"!=typeof e)return e;if(t.has(e))return t.get(e);const n=Array.isArray(e)?[]:{};t.set(e,n);for(const[r,s]of Object.entries(e))n[r]=Kd(s,t);return Object.freeze(n)},Qd=({adapter:e,notice:t=()=>{}})=>{const n=Vd(),r=(e,n,r)=>{t({text:`${e} failed — ${n} (${r?.message??String(r)})`,severity:"error"})},s=Vd({onSubscriberError:({topic:e,cause:t})=>r("public event subscriber",e,t)}),i=e=>{const t=Yd[e];if(!t)throw new Error(`Undeclared topic '${e}' — every emitted topic must be declared in topicRegistry.js (charter §8)`);return t},a=e=>{if("internal"===i(e).audience)throw new Error(`Topic '${e}' is internal — not part of the public contract`)};return Object.freeze({publish(t,a={}){const o=i(t);if("internal"===o.audience)return void n.raise(t,a);const d=Kd(a);if(s.raise(t,d),"eventstream"===o.audience)try{e.events.raise(t,d)}catch(l){r("EventStream forward",t,l)}},on:(e,t)=>(e=>"internal"===i(e).audience?n:s)(e).on(e,t),events:Object.freeze({on(e,t){if(a(e),"function"!=typeof t)throw new TypeError("insight.events.on needs a function");return s.on(e,t)},off(e,t){if(a(e),"function"!=typeof t)throw new TypeError("insight.events.off needs a function");s.off(e,t)}})})},Xd=Object.freeze({safetyFlushMs:200}),el=e=>`insight4.elapsed.${e}`,tl="insight4.flush.safety",nl=({adapter:e,roster:t,publisher:n,notice:r,safetyFlushMs:s=Xd.safetyFlushMs})=>{const{publish:i}=n,a=new Map,o=new Set,d=new Set;let l=!1,c=0;const f=[],u=(e,t)=>{for(const n of t)"contradiction"===n.type&&i("insight.belief.contradiction",{id:e,event:n.event}),"forkCapExceeded"===n.type&&(i("insight.belief.growthCapped",{id:e,event:n.eventType??"elapsed",beforeCount:n.beforeCount,afterCount:n.afterCount,forkCap:n.forkCap}),r({text:`fork cap hit for ${e} — ${n.beforeCount} → ${n.afterCount} forks (cap ${n.forkCap}) during simulation. Belief detail was discarded; this is a red-flag condition.`,severity:"error"}))},p=(n,{includeDue:r=!1}={})=>{const s=t.get(n);if(!s)return a.delete(n),void e.clock.clearTimer(el(n));a.has(n)||a.set(n,e.clock.now());const o=((t,n)=>{const r=t.nextInterestingAt({includeDue:n});if(null===r)return null;const s=e.clock.now(),i=a.get(t.id)??s;return Math.max(0,r-t.now-(s-i))})(s,r);null!==o?e.clock.setTimer(el(n),o,()=>{const t=e.clock.now(),r=a.get(n)??t;a.set(n,t);const o=Math.max(0,t-r);o>0&&(c+=1);const d=s.elapsed(o);u(n,d.diagnostics),i("insight.scheduler.elapsed",{id:n,expired:d.expired,resolvedCures:d.resolvedCures,resolvedDefenceStrips:d.resolvedDefenceStrips,restoredDefs:d.restoredDefs,predicted:d.predicted}),p(n)}):e.clock.clearTimer(el(n))},h=()=>{if(l=!1,e.clock.clearTimer(tl),0===o.size&&0===d.size)return;const t=[...o].sort(),n=[...d].sort();o.clear(),d.clear();for(const e of t)i("insight.affs.updated",{id:e});for(const e of n)i("insight.opponent.updated",{id:e});n.length>0&&i("insight.display.flush",{ids:n})},m=()=>{l||(l=!0,e.clock.setTimer(tl,s,h))},g=e=>{o.add(e),m()},b=e=>{d.add(e),m()};return Object.freeze({start(){f.push(t.onOpponentChange(e=>p(e,{includeDue:!0})),n.on("insight.model.changed",({id:e})=>g(e)),n.on("insight.display.changed",({id:e})=>b(e)),n.on("insight.opponent.removed",({id:e})=>{o.delete(e),d.delete(e),p(e)}),n.on("insight.ingress.prompt",h))},stop(){for(;f.length>0;)f.pop()();e.clock.clearTimer(tl),l=!1;for(const t of a.keys())e.clock.clearTimer(el(t));a.clear(),o.clear(),d.clear()},advanceToNow:n=>{const r=t.get(n);if(!r)return null;const s=e.clock.now(),i=a.get(n)??s;a.set(n,s);const o=s-i;if(o<=0)return null;c+=1;const d=r.elapsed(o);return u(n,d.diagnostics),d},getTimeEpoch:()=>c,reschedule:p,markDirty:e=>{g(e),b(e)},flush:h})},rl=({roster:e,publish:t,defenceDefaults:n={}})=>{const r=Object.freeze(Object.fromEntries(Object.entries(n).map(([e,t])=>[e,Object.freeze({have:t,atMs:0,phase:null,stripAt:null,restoreAt:null})])));let s=null;const i=new Map;let a=!1;const o=[],d=[],l=e=>({mode:e.mode,affs:e.affs??{},defs:e.defs??{},stats:e.stats??{},limbs:e.limbs??{}}),c=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),f=(e,t,n)=>{const r=Object.keys(e),s=Object.keys(t);if(r.length!==s.length)return!0;for(const i of s)if(!c(e,i)||n(e[i])!==n(t[i]))return!0;return!1},u=(e,n)=>{const s=l(n),a=i.get(e);let o=!1,d=!1;a?a.mode!==s.mode&&(o=!0,d=!0,"observed"===s.mode?t("insight.opponent.tracked",{id:e}):t("insight.opponent.unobserved",{id:e})):(o=!0,d=!0,t("insight.opponent.tracked",{id:e}));for(const[r,i]of Object.entries(s.affs)){const n=i.probability;a&&c(a.affs,r)?a.affs[r].probability!==n&&(o=!0,d=!0):(o=!0,d=!0,t("insight.aff.got",{id:e,affId:r,probability:n}))}for(const r of Object.keys(a?.affs??{}))c(s.affs,r)||(o=!0,d=!0,t("insight.aff.lost",{id:e,affId:r}));const u=a?.defs??r;for(const[r,i]of Object.entries(s.defs))!0===i.have&&!0!==u[r]?.have&&(d=!0,t("insight.def.got",{id:e,defId:r}));for(const[r,i]of Object.entries(u))!0===i.have&&!0!==s.defs[r]?.have&&(d=!0,t("insight.def.lost",{id:e,defId:r}));a&&((e,t)=>{const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!0;for(const s of r){const n=e[s],r=t[s];if(!n||n.have!==r.have||n.atMs!==r.atMs||n.phase!==r.phase||n.stripAt!==r.stripAt||n.restoreAt!==r.restoreAt)return!0}return!1})(a.defs,s.defs)&&(d=!0),a&&(f(a.stats,s.stats,e=>e.value)||f(a.limbs,s.limbs,e=>e.percent))&&(d=!0),i.set(e,s),o&&t("insight.model.changed",{id:e}),d&&t("insight.display.changed",{id:e})},p=e=>{if(o.push(e),!a){a=!0;try{for(;o.length>0;)o.shift()()}finally{a=!1}}};return Object.freeze({start(){s=e.targetId;for(const t of e.list()){const n=e.get(t);n&&i.set(t,l(n.snapshot()))}d.push(e.onOpponentChange((e,t)=>p(()=>u(e,t))),e.onChange(n=>p(()=>(({ids:n,targetId:r})=>{const a=new Set(n);for(const t of n)if(!i.has(t)){const n=e.get(t);n&&u(t,n.snapshot())}for(const e of[...i.keys()])a.has(e)||(i.delete(e),t("insight.opponent.removed",{id:e}));r!==s&&(s=r,t("insight.target.changed",{id:s}),s&&t("insight.display.changed",{id:s}))})(n))))},stop(){for(;d.length>0;)d.pop()()}})},sl=(e,t)=>"number"==typeof e?mo(t?.[e]):null,il=({adapter:e,settings:t,safetyFlushMs:n,display:r,displaySink:s,notice:i=()=>{},guards:a})=>{const o=Object.freeze({affById:Fi,cureById:qi,cureMasks:Wi,balanceById:Gi,priorityByAff:Hi,defenceById:Ji,defenceDefaults:Ui,guards:!0===a,get growth(){return t.get().pruning}}),d=Qd({adapter:e,notice:i}),{publish:l}=d;let c=0;const f=e=>(c+=1,l("insight.settings.changed",{document:e}),e),u=(e,t)=>{try{return e()}catch(n){throw i({text:`Settings storage ${t} failed: ${n?.message??String(n)}`,severity:"error"}),n}},p=Object.freeze({get:t.get,save:()=>u(t.save,"write"),load:()=>f(u(t.load,"read")),update:e=>f(u(()=>t.update(e),"write")),updateDisplay:e=>f(u(()=>t.updateDisplay(e),"write")),updatePredictive:e=>f(u(()=>t.updatePredictive(e),"write")),replace:e=>f(u(()=>t.replace(e),"write")),reset:()=>f(t.reset()),clear:()=>f(u(t.clear,"clear"))}),h=go({tables:o,guards:!0===a,policy:t.get().predictive.defaultPolicy,predictionEnabled:t.get().predictive.enabled}),m=nl({adapter:e,roster:h,publisher:d,notice:i,safetyFlushMs:n??t.get().display.safetyFlushMs}),g=Hd({roster:h,tables:o,publish:l,notice:i,advanceToNow:m.advanceToNow}),b=rl({roster:h,publish:l,defenceDefaults:Ui}),y=r?(({publisher:e,roster:t,settings:n,display:r,sink:s})=>{const{renderTarget:i,renderRoster:a,displayTable:o}=r,d=[],l=(e,t)=>{const n=e.targetId?e.opponents[e.targetId]:null;n&&s(i(n,o,t))},c=(e,t)=>{t.display.showRoster&&Object.keys(e.opponents).length>0&&s(a(e.opponents,o,t))};return Object.freeze({start(){d.push(e.on("insight.display.flush",({ids:e})=>{const r=t.snapshot(),s=n.get();r.targetId&&e.includes(r.targetId)&&l(r,s),c(r,s)}))},stop(){for(;d.length>0;)d.pop()()},refresh(){const e=t.snapshot(),r=n.get();l(e,r),c(e,r)}})})({publisher:d,roster:h,settings:p,display:r,sink:s??(t=>e.display.addLine(t))}):null,v=r?(({publisher:e,roster:t,settings:n,display:r,notice:s})=>{const{displayTable:i,renderAffNotice:a,renderDefNotice:o}=r,d=[],l=e=>!0===n.get().display.notices&&t.targetId===e,c=e=>t=>{l(t.id)&&s({html:a({affId:t.affId,present:e},i,n.get())})},f=e=>t=>{l(t.id)&&s({html:o({defId:t.defId,present:e},i,n.get())})};return Object.freeze({start(){d.push(e.on("insight.aff.got",c(!0)),e.on("insight.aff.lost",c(!1)),e.on("insight.def.got",f(!0)),e.on("insight.def.lost",f(!1)))},stop(){for(;d.length>0;)d.pop()()}})})({publisher:d,roster:h,settings:p,display:r,notice:i}):null,k=(()=>{const e=new Map;let t=null;return Object.freeze({rememberQueue(n,r){"string"==typeof n&&n&&"string"==typeof r&&(e.set(n,r),t=n)},snapshot:()=>({queues:Object.fromEntries(e),lastQueue:t}),clear(){e.clear(),t=null}})})(),w=Gd({adapter:e,publish:l,commandMemory:k,skills:()=>[...g.listSkills(),...I.listArmingSkills()]}),I=(({adapter:e,roster:t,router:n,publisher:r,capture:s,commandMemory:i,sessionPacks:a=[],promptPacks:o=[]})=>{const{publish:d}=r,l=new Map(a.map(e=>[e.id,e])),c=new Map(o.map(e=>[e.id,e])),f=new Map,u=new Set;for(const z of c.values()){const{skill:e,id:t}=z.armedBy??{};if("string"!=typeof e||""===e||"string"!=typeof t||""===t)continue;const n=gd(e,t),r=f.get(n);r?r.push(z):f.set(n,[z]),u.add(md(e))}const p=new Map,h=new Map,m=[],g=()=>t.listObserved(),b=(e,t,r)=>{for(const s of e??[])n.observe({...s,id:s.id??t},r)},y=(e,r)=>{if(e.remember){const t=e.remember(r);return void(t?.queue&&i.rememberQueue(t.queue.name,t.queue.text))}const a=e.actor??null,o="number"==typeof a?sl(a,r):null,l=s(o);d("insight.ingress.trigger",{id:e.id,match:r,context:l});const f="room"===a?g():"tracked"===a?t.list():[o];for(const t of f){const s=n.resolveView(t);s&&b(e.handler(r,l,s),s.id,l)}for(const t of c.values())t.armedBy?.trigger===e.id&&w(t,o)},v=(e,t,r)=>{const i=h.get(e.id);if(!i)return;const a="armed"===t.actor?i.state.actorId:sl(t.actor,r),o=s(a);d("insight.ingress.trigger",{id:`${e.id}.${t.id}`,match:r,context:o});const l=n.resolveView(a);l&&b(t.handler(r,o,l,i.state),l.id,o)},k=t=>{const n=h.get(t);if(!n)return null;for(const r of n.captureIds.values())e.triggers.unregister(r);return h.delete(t),n},w=(n,r=null)=>{k(n.id);const s=n.initState?n.initState({actorId:r,observedIds:g(),targetId:t.targetId}):{actorId:r},i=new Map;for(const t of n.captures)i.set(t.id,e.triggers.register(t.pattern,"prompt",e=>v(n,t,e)));h.set(n.id,{pack:n,state:s,captureIds:i})},I=()=>{for(const e of[...h.keys()]){const t=k(e);if(t?.pack.finalize){const e=s(t.state.actorId??null);b(t.pack.finalize(t.state),t.state.actorId??null,e)}}};return Object.freeze({start(){for(const t of l.values())p.set(t.id,e.triggers.register(t.pattern,"session",e=>y(t,e)));m.push(r.on("insight.ingress.skill",({action:e})=>{const t=f.get(gd(e.skill,e.id));for(const n of t??[])w(n,null)}),r.on("insight.ingress.prompt",I))},stop(){for(;m.length>0;)m.pop()();for(const e of[...h.keys()])k(e);for(const t of p.values())e.triggers.unregister(t);p.clear()},listSession:()=>[...l.keys()],listArmed:()=>[...h.keys()],listArmingSkills:()=>[...u]})})({adapter:e,roster:h,router:g,publisher:d,capture:w.capture,commandMemory:k,sessionPacks:Zd,promptPacks:Bd}),z=e=>{g.addDefinitions(e),w.observeSkills(g.listSkills())};z(bd);const _=[],O=()=>{for(w.stop(),I.stop(),m.stop(),b.stop(),y?.stop(),v?.stop();_.length>0;)_.pop()()};try{b.start(),m.start(),y?.start(),v?.start(),_.push(d.on("insight.ingress.skill",g.dispatchAction),d.on("insight.ingress.skillError",({skill:e,id:t,message:n})=>i({text:`nexSkills reaction failed for ${e??"?"}.${t??"?"} — ${n}. Observations from that line may be incomplete.`,severity:"warning"})),d.on("insight.ingress.target",({id:e})=>h.setTarget(e)),d.on("insight.ingress.room.entered",({id:e})=>h.track(e)),d.on("insight.ingress.room.left",({id:e})=>h.untrack(e)),d.on("insight.ingress.room.list",({ids:e})=>(e=>{const t=new Set(e);for(const n of e)h.track(n);for(const n of h.list())t.has(n)||h.untrack(n)})(e)),d.on("insight.settings.changed",({document:e})=>h.updateDefaults({policy:e.predictive.defaultPolicy,predictionEnabled:e.predictive.enabled}))),I.start(),w.start()}catch($){throw O(),$}return Object.freeze({roster:h,router:g,scheduler:m,registrar:I,publish:l,events:d.events,settings:p,getSettingsRevision:()=>c,display:y,observe:g.observe,addDefinitions:z,capture:w.capture,dispose:O})},al=Object.freeze({schemaVersion:3,autoUpdate:!1,display:Object.freeze({threshold:0,shortNames:!0,colors:!0,notices:!0,showRoster:!1,safetyFlushMs:200}),predictive:Object.freeze({enabled:!1,defaultPolicy:"distribution"}),queries:Object.freeze({presenceFloor:.01}),pruning:Object.freeze({epsilon:na.epsilon,forkCap:na.forkCap})}),ol=Br({threshold:Mr().min(0).max(1).catch(al.display.threshold),shortNames:Ar().catch(al.display.shortNames),colors:Ar().catch(al.display.colors),notices:Ar().catch(al.display.notices),showRoster:Ar().catch(al.display.showRoster),safetyFlushMs:Mr().int().min(0).max(1e4).catch(al.display.safetyFlushMs)}).catch({...al.display}),dl=Br({enabled:Ar().catch(al.predictive.enabled),defaultPolicy:Wr(Ca).catch(al.predictive.defaultPolicy)}).catch({...al.predictive}),ll=Br({presenceFloor:Mr().min(0).max(1).catch(al.queries.presenceFloor)}).catch({...al.queries}),cl=Br({epsilon:Mr().positive().max(.1).catch(al.pruning.epsilon),forkCap:Mr().int().min(1).catch(al.pruning.forkCap)}).catch({...al.pruning}),fl=Br({schemaVersion:Kr(3).catch(3),autoUpdate:Ar().catch(al.autoUpdate),display:ol,predictive:dl,queries:ll,pruning:cl}).catch({schemaVersion:3,autoUpdate:al.autoUpdate,display:{...al.display},predictive:{...al.predictive},queries:{...al.queries},pruning:{...al.pruning}}),ul=e=>{if(e&&"object"==typeof e&&!Object.isFrozen(e)){Object.freeze(e);for(const t of Object.keys(e))ul(e[t])}return e},pl=e=>ul(fl.parse((e=>{if(!e||"object"!=typeof e||Array.isArray(e)||!Number.isInteger(e.schemaVersion)||e.schemaVersion>=3)return e;const t=e.pruning&&"object"==typeof e.pruning&&!Array.isArray(e.pruning)?{...e.pruning,...128===e.pruning.forkCap?{forkCap:al.pruning.forkCap}:{}}:e.pruning;return{...e,schemaVersion:3,pruning:t}})(e))),hl=(e,{key:t="insightSettings"}={})=>{let n=pl(null);const r=(r=n)=>(e.storage.set(t,JSON.stringify(r)),n=r,r);return Object.freeze({get:()=>n,load:()=>(n=pl((e=>{if("string"==typeof e)try{return JSON.parse(e)}catch{return null}return e??null})(e.storage.get(t))),n),save:()=>r(),update:(e={})=>r(pl({...n,...e,display:{...n.display,...e.display},predictive:{...n.predictive,...e.predictive},queries:{...n.queries,...e.queries},pruning:{...n.pruning,...e.pruning}})),updateDisplay:(e={})=>r(pl({...n,display:{...n.display,...e}})),updatePredictive:(e={})=>r(pl({...n,predictive:{...n.predictive,...e}})),replace:e=>r(pl(e)),reset:()=>(n=pl(null),n),clear:()=>(e.storage.clear(t),n=pl(null),n)})},ml=Object.freeze({forks:Object.freeze([])}),gl=({roster:e,resolveCure:t,events:n,settings:r,observe:s,capture:i,advanceToNow:a,reschedule:o,displayRendering:d,refreshDisplay:l,notice:c,addLine:f,getPhase:u,getPhaseRevision:p,getSettingsRevision:h,getTimeEpoch:m,version:g})=>{const b=t=>{const n=t?.id;return null==n?e.getTarget():e.get(n)},y=(e,t)=>{const n=b(e);return n?$a(n.belief,t):0},v=(e,t,n)=>e(b(t)?.belief??ml,n),k=(e,t)=>v(Ma,e,t),w=(e,t)=>v(xa,e,t),I=(e,t)=>((e,t,n,r)=>{_a(t),ra(ka.includes(n),`unknown comparison operator '${n}'`),ra(Number.isInteger(r)&&r>=0,"pool count probability needs an integer n >= 0");let s=0;for(const i of e.forks)wa(Oa(i,t),n,r)&&(s+=i.p);return s})(b(e)?.belief??ml,t,e?.op,e?.n),z=(e,t)=>e>r.get().queries.presenceFloor&&e>=(e=>{const t="number"==typeof e?.threshold?e.threshold:0;return t>1?t/100:t})(t),_=e=>{if(e&&"object"==typeof e&&!Object.isFrozen(e)){Object.freeze(e);for(const t of Object.keys(e))_(e[t])}return e},O=e=>e&&"object"==typeof e?Array.isArray(e)?e.map(O):Object.fromEntries(Object.entries(e).map(([e,t])=>[e,O(t)])):e,$=new Map,S=(e,t)=>{const n=$.get(e.id);if(n?.model===e&&n.revision===e.revision&&n.timeEpoch===e.timeEpoch&&n.settingsRevision===t)return n.branch;const r=e.snapshot(),s=_(O({id:r.id,affs:r.affs,limbs:r.limbs,balances:r.balances,stats:r.stats,defs:r.defs,staleness:r.staleness}));return $.set(e.id,{model:e,revision:e.revision,timeEpoch:e.timeEpoch,settingsRevision:t,branch:s}),s};let M=null,x=null;const j=()=>{const t={rosterRevision:e.revision,settingsRevision:h(),phaseRevision:p(),timeEpoch:m()};if(x?.rosterRevision===t.rosterRevision&&x.settingsRevision===t.settingsRevision&&x.phaseRevision===t.phaseRevision&&x.timeEpoch===t.timeEpoch)return M;const n={},s=[...e.list()].sort(),i=new Set(s);for(const r of s)n[r]=S(e.get(r),t.settingsRevision);for(const e of $.keys())i.has(e)||$.delete(e);return M=Object.freeze({system:Object.freeze({phase:u(),version:g}),target:e.targetId?n[e.targetId]??null:null,opponents:Object.freeze(n),settings:r.get()}),x=t,M},N=Object.freeze({get:()=>e.targetId,set:t=>{const n=e.setTarget(t??null);return n?n.id:null},is:t=>null!==e.targetId&&mo(t)===e.targetId}),A=Object.freeze({track:t=>{const n=e.track(t);return n?n.id:null},remove:t=>e.remove(t),list:()=>e.list(),reset:t=>e.reset(t),resetAll:()=>{e.resetAll()}}),T=Object.freeze({have:(e,t)=>z(y(t,e),t),haveAll:(e,t)=>z(w(t,e),t),haveAny:(e,t)=>z(k(t,e),t),probability:(e,t)=>y(t,e),probabilityAll:(e,t)=>w(t,e),probabilityAny:(e,t)=>k(t,e),expectedPoolCount:(e,t)=>((e,t)=>v(ja,e,t))(t,e),poolCountProbability:(e,t)=>I(t,e)}),E=Object.freeze({poolCountProbability:(e,n)=>I(n,(e=>{const n=t(e);if(!n)throw new Error(`insight api: unknown cure '${String(e)}'`);return n.order})(e))}),C=Object.freeze({have:(e,t)=>!0===b(t)?.haveDef(e),get:(e,t)=>{const n=b(t)?.snapshot().defs[e];return n?Object.freeze({...n}):null}}),P=Object.freeze({get:(e,t)=>{const n=b(t);return n?Object.freeze({percent:n.limbPercent(e),stages:Object.freeze(n.limbStages(e))}):null},hit:(e,t)=>s({type:"limbHit",limbId:e,percent:t?.percent,id:t?.id}),advance:(e,t)=>s({type:"limbAdvance",limbId:e,id:t?.id}),reset:(e,t)=>s({type:"limbReset",limbId:e,id:t?.id})}),D=Object.freeze({have:(e,t)=>{const n=b(t);return!!n&&n.isBalanceReady(e)},remainingMs:(e,t)=>{const n=b(t);return n?n.snapshot().balances[e]?.remainingMs??null:null},remainingProbability:(e,t={})=>{const n=b(t);return n?n.balanceRemainingProbability(e,{op:t?.op,ms:t?.ms,affIds:t?.affs??[]}):0}}),R=(e,t={})=>{const{id:n,...r}=t;return s({type:e,...r,id:n},i(n??null))},Z=Object.freeze({afflicted:e=>R("afflicted",e),afflictedOneOf:({mode:e="firstMissing",...t}={})=>R("afflictedOneOf",{mode:e,...t}),advanced:e=>R("limbAdvance",e),cured:e=>R("cured",e),confirmed:({present:e=!0,...t}={})=>R("confirmed",{present:e,...t}),confirmedCount:e=>R("confirmedCount",e),confirmedCounts:e=>R("confirmedCounts",e),confirmedLevel:e=>R("confirmedLevel",e),converted:e=>R("converted",e),removed:e=>R("removed",e)}),B=Object.freeze({enable:e=>{const t=b({id:e});return!!t&&(t.enablePrediction(),!0)},disable:e=>{const t=b({id:e});return!!t&&(t.disablePrediction(),!0)},setPolicy:(e,t)=>{const n=b({id:t});return!!n&&(n.setPolicy(e),!0)},isEnabled:e=>{const t=b({id:e});return!!t&&t.isPredictionEnabled()},stepNow:e=>{const t=b({id:e});if(!t)return null;const n=a(t.id)??{expired:[],resolvedCures:[],predicted:[],timingConfirmations:[],diagnostics:[]};return o(t.id),n}}),L=Object.freeze({get:({view:e="target",id:t,affId:n,defId:s,present:i}={})=>{const a=r.get();if("affNotice"===e){if("string"!=typeof n||0===n.length||"boolean"!=typeof i)throw new TypeError("display.get affNotice needs affId and boolean present");return d.renderAffNotice({affId:n,present:i},d.displayTable,a)}if("defNotice"===e){if("string"!=typeof s||0===s.length||"boolean"!=typeof i)throw new TypeError("display.get defNotice needs defId and boolean present");return d.renderDefNotice({defId:s,present:i},d.displayTable,a)}if(!["target","affState","statState"].includes(e))throw new TypeError(`unknown display view '${e}'`);const o=b({id:t});if(!o)return"";const l=o.snapshot();return"target"===e?d.renderTarget(l,d.displayTable,a):"affState"===e?d.renderAffState(l,d.displayTable,a):d.renderStatState(l,d.displayTable,a)},notice:(e,t)=>{c({html:e,severity:t})},refresh:()=>{l()},openDebug:()=>{f(d.renderDebug(j()))}}),F=Object.freeze({target:N,opponents:A,affs:T,cures:E,defs:C,limbs:P,balances:D,observe:Z,simulate:B,display:L,settings:r}),q=Object.freeze(Object.fromEntries(Object.entries(Yd).filter(([,e])=>"internal"!==e.audience))),G=Object.freeze({on:n.on,off:n.off,topics:q});return Object.freeze({get state(){return j()},api:F,events:G})},bl=["head","torso","leftarm","rightarm","leftleg","rightleg"],yl=e=>String(e).replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;"),vl=(e,t="",n="")=>{const r=[t?`color: ${t}`:"",n?`background: ${n}`:""].filter(Boolean).join("; ");return r?`<span style="${r}">${e}</span>`:`<span>${e}</span>`},kl=(e,t="",n="")=>vl(yl(e),t,n),wl=e=>e.charAt(0).toUpperCase()+e.slice(1),Il=(e,t)=>Object.entries(e).filter(([,e])=>e.probability>0&&e.probability>=t).sort(([e,t],[n,r])=>r.probability-t.probability||(e<n?-1:1)),zl=(e,t,n,r)=>{const s=n.affs[e],i=r.shortNames&&s?s.shortName:e,a=void 0!==t.count?(e=>String(parseFloat(e.toFixed(1))))(t.count):"",o=r.colors&&s?s.fg:"",d=r.colors&&s?s.bg:"";return kl(`${i}${a}`,o,d)},_l=(e,t,n)=>{const r=n.display,{bracket:s}=t.chrome,i=[kl("[",s.fg,s.bg)],a=Il(e.affs,r.threshold);return a.forEach(([e,n],s)=>{i.push(zl(e,n,t,r));const o=s<a.length-1?", ":"";i.push(kl(`: ${(e=>String(Math.round(100*e)/100))(n.probability)}${o}`))}),i.push(kl("]",s.fg,s.bg)),i},Ol=[["hp","H"],["mana","M"]],$l=e=>{const t=Math.round(100*Math.min(1,Math.max(0,e)));return`hsl(${1.2*t}, 100%, ${t<75?50:Math.abs(t-100)/2+25}%)`},Sl=(e,t)=>{const n=[],{detail:r}=t.chrome;for(const[s,i]of Ol){const t=e.stats?.[s];if(!t)continue;n.length>0&&n.push(kl(" "));const a=Math.round(100*Math.min(1,Math.max(0,t.value)));n.push(kl(`${i}:`,r.fg,r.bg)),n.push(kl(`${a}%`,$l(t.value)))}return n},Ml=(e,t,n,r,s)=>{const i=[kl(`${n?"+":"-"}${e} `,n?"lime":"red")];if("aff"===e){const e=r.affs[t],n=s.display;i.push(kl(wl(t),n.colors&&e?e.fg:"",n.colors&&e?e.bg:""))}else i.push(kl(wl(t)));return i},xl=({text:e="",html:t,severity:n="info"},r)=>{const s=r.chrome.severity,i=s[n]??s.info,a="string"==typeof t?vl(t,i.fg,i.bg):kl(e,i.fg,i.bg);return`<span class="mono">${(e=>{const{delimiter:t,label:n}=e.chrome.tag;return[kl("<<",t.fg,t.bg),kl("insight",n.fg,n.bg),kl(">> ",t.fg,t.bg)]})(r).join("")}${a}</span>`},jl="0.6.2",Nl=Object.freeze({BOOTING:"BOOTING",LOADING_SETTINGS:"LOADING_SETTINGS",REGISTERING_TRIGGERS:"REGISTERING_TRIGGERS",READY:"READY",DEGRADED:"DEGRADED"}),Al=Object.freeze({[Nl.BOOTING]:Object.freeze([Nl.LOADING_SETTINGS,Nl.DEGRADED]),[Nl.LOADING_SETTINGS]:Object.freeze([Nl.REGISTERING_TRIGGERS,Nl.DEGRADED]),[Nl.REGISTERING_TRIGGERS]:Object.freeze([Nl.READY,Nl.DEGRADED]),[Nl.READY]:Object.freeze([]),[Nl.DEGRADED]:Object.freeze([])});var Tl="__insight4StorageProbe",El=Object.freeze({displayTable:Ds,renderAffNotice:({affId:e,present:t},n,r)=>`<span class="mono">${Ml("aff",e,t,n,r).join("")}</span>`,renderAffState:(e,t,n)=>`<span class="mono">${_l(e,t,n).join("")}</span>`,renderDebug:e=>`<pre class="mono">${yl(JSON.stringify(e,null,2))}</pre>`,renderDefNotice:({defId:e,present:t},n,r)=>`<span class="mono">${Ml("def",e,t,n,r).join("")}</span>`,renderNotice:xl,renderRoster:(e,t,n)=>{const r=n.display;if(!r.showRoster)return"";const{bracket:s,detail:i}=t.chrome,a=[];return Object.keys(e).sort().forEach((n,o)=>{const d=e[n];o>0&&a.push(kl(" ")),a.push(kl(`${wl(n)} `),kl("[",s.fg,s.bg));const l=Il(d.affs,r.threshold);l.forEach(([e,n],s)=>{a.push(zl(e,n,t,r)),s<l.length-1&&a.push(kl(" "))}),a.push(kl("]",s.fg,s.bg));const c=Math.round(100*d.staleness);c>0&&a.push(kl(` ~${c}%`,i.fg,i.bg))}),`<span class="mono">${a.join("")}</span>`},renderStatState:(e,t)=>{const n=Sl(e,t);return n.length>0?`<span class="mono">${n.join("")}</span>`:""},renderTarget:(e,t,n)=>{const{detail:r}=t.chrome,s=[kl(`${wl(e.id)} `),..._l(e,t,n)],i=Sl(e,t);i.length>0&&s.push(kl(" "),...i);const a=bl.filter(t=>e.limbs[t]?.percent>0);if(a.length>0){const t=a.map(t=>{const n=e.limbs[t];return`${t}:${Math.round(n.percent)}%`}).join(" ");s.push(kl(` ${t}`,r.fg,r.bg))}return`<span class="mono">${s.join("")}</span>`}}),Cl=e=>qi.get(e);function Pl(e,{safetyFlushMs:t,updateNxs:n=u,guards:r}={}){const i=function({onTransition:e}={}){let t=Nl.BOOTING,n=0;const r=[Nl.BOOTING];return{getPhase:()=>t,getRevision:()=>n,getHistory:()=>[...r],transition(s){if(!Al[t].includes(s))throw new Error(`Invalid phase transition: ${t} → ${s}`);return t=s,n+=1,r.push(s),e?.(s),t}}}();let a,o=null,d=null,l=null,c=null,f=!1;const p={getPhase:i.getPhase,getPhaseHistory:i.getHistory,getError:()=>o,isReady:()=>i.getPhase()===Nl.READY,dispose(){f||(f=!0,l?.dispose(),c&&globalThis.insight===c&&delete globalThis.insight)},get settings(){return d},get runtime(){return l},get state(){return c?c.state:null},get api(){return c?c.api:null},get events(){return c?c.events:null}},h=t=>{try{e.display.addLine(xl(t,Ds))}catch{}},m=()=>{!0===d?.get?.().autoUpdate&&n({enabled:!0,currentVersion:jl,notice:h})},g=e=>(o=e,i.transition(Nl.DEGRADED),h({text:`DEGRADED: ${e?.message??String(e)}`,severity:"error"}),m(),p);try{s(e),e.storage.clear(Tl),e.storage.set(Tl,"probe"),e.storage.clear(Tl),a=e.display.addLine.bind(e.display)}catch(y){try{e?.storage?.clear?.(Tl)}catch{}return g(y)}i.transition(Nl.LOADING_SETTINGS);const b=hl(e);d=b;try{b.load()}catch(y){b.reset(),h({text:`Settings storage is unavailable — running on default settings. (${y?.message??String(y)})`,severity:"warning"})}i.transition(Nl.REGISTERING_TRIGGERS);try{l=il({adapter:e,settings:b,safetyFlushMs:t,guards:r,displaySink:a,notice:h,display:El}),d=l.settings,c=gl({roster:l.roster,resolveCure:Cl,events:l.events,settings:l.settings,observe:l.observe,capture:l.capture,advanceToNow:l.scheduler.advanceToNow,reschedule:l.scheduler.reschedule,displayRendering:El,refreshDisplay:l.display.refresh,notice:h,addLine:a,getPhase:i.getPhase,getPhaseRevision:i.getRevision,getSettingsRevision:l.getSettingsRevision,getTimeEpoch:l.scheduler.getTimeEpoch,version:jl})}catch(y){return l?.dispose(),l=null,d=b,g(y)}return i.transition(Nl.READY),globalThis.insight=c,l.publish("insight.ready",{}),m(),p}var Dl=Symbol.for("insight4.instance");!function(t){globalThis[Dl]?.dispose();const r=Pl(function(){const t=new Map;let r=1;return{display:{addLine(e){nexusclient.add_html_line(e)}},storage:{get(t){const n=e();return"function"==typeof n?.get?n.get(t):n?.vars?.[t]},set(t,n){const r=e();if("function"!=typeof r?.set){if(!r?.vars)throw new Error("insight4 storage.set failed — host variables expose neither set() nor a vars record");r.vars[t]=n}else r.set(t,n)},clear(t){const n=e();if("function"!=typeof n?.delete)if("function"!=typeof n?.set){if(!n?.vars)throw new Error("insight4 storage.clear failed — host variables expose neither delete()/set() nor a vars record");delete n.vars[t]}else n.set(t,void 0);else n.delete(t)}},triggers:{register(e,t,n){const s="insight4.trigger."+r++;return nexAction.triggers.add({id:s,tags:["insight4",`lifetime:${t}`],regex:e,action:n}),s},unregister(e){nexAction.triggers.remove(e)}},events:{onSkillMatch(e,t=null){if("undefined"==typeof nexSkills||!nexSkills)throw new Error("nexSkills is unavailable — insight cannot observe skill events");return n(t?`nexskill.match.skill.${t}`:"nexskill.match.skill",e)},on:n,raise(e,t){eventStream.raiseEvent(e,t)}},gmcp:{read:e=>String(e).split(".").reduce((e,t)=>null==e?e:e[t],GMCP)},text:{snapshot:()=>({lines:(nexusclient.current_block??[]).map(e=>({text:"string"==typeof e.line?"function"==typeof e.parsed_line?.text?e.parsed_line.text():e.line:null,isPrompt:!0===e.is_prompt,isHtml:Boolean(e.html_text)})),currentLineIndex:nexusclient.current_line?.index??-1})},clock:{now:()=>Date.now(),setTimer(e,n,r){const s=t.get(e);void 0!==s&&clearTimeout(s),t.set(e,setTimeout(()=>{t.delete(e),r()},n))},clearTimer(e){const n=t.get(e);void 0!==n&&(clearTimeout(n),t.delete(e))}}}}(),t);globalThis[Dl]=r}()}();