nexsight 0.6.5 → 0.6.6
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 +1 -1
- package/insight4.nxs +6 -6
- package/package.json +1 -1
- package/insight.min.js +0 -1
- package/query-perf-full.json +0 -18313
- package/query-perf-temp.json +0 -7835
package/insight4.min.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(){var e=async(e,{fetchFn:t=globalThis.fetch,AbortControllerCtor:n=globalThis.AbortController,setTimeoutFn:r=globalThis.setTimeout,clearTimeoutFn:s=globalThis.clearTimeout,timeoutMs:i=1e4}={})=>{if("function"!=typeof t)throw new Error("fetch is not available");const a=`https://api.achaea.com/characters/${e}.json`;let o=null;try{let e;if("function"==typeof n&&i>0){const t=new n;o=r(()=>t.abort(),i),e=t.signal}const s=await t(a,{cache:"no-store",...e?{signal:e}:{}});if(404===s?.status)return null;if(!s?.ok)throw new Error(`${s?.status??"no"} response from ${a}`);return l=(await s.json())?.class,String(l??"").trim().toLowerCase().replace(/\belemental\b/g,"").replace(/[^a-z]/g,"")||null}finally{null!==o&&s(o)}var l},t=(t={})=>Object.freeze({read:n=>e(n,t)});function n(){return nexusclient.variables()}var r=["insight4"];function s(e,t){const n=`insight4.${e}`;return eventStream.registerEvent(e,t,{id:n,tags:r}),()=>{eventStream.removeListener(e,n)}}var i=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"]),directory:Object.freeze(["read"]),text:Object.freeze(["snapshot"]),clock:Object.freeze(["now","setTimer","clearTimer"])});Object.freeze(["events.onSkillMatch","events.on"]);function a(e){const t=function(e){if(null===e||"object"!=typeof e)return["adapter is not an object"];const t=[];for(const[n,r]of Object.entries(i)){const s=e[n];if(null!==s&&"object"==typeof s)for(const e of r)"function"!=typeof s[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 o,l=/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/,d="nexsight",c=`https://unpkg.com/${d}@latest/package.json`,f=e=>{const t=l.exec(String(e??"").trim());if(!t)throw new Error(`invalid version '${e??""}'`);return{core:t.slice(1,4).map(Number),prerelease:t[4]?.split(".")??[]}},u=(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},p=(e,t,n)=>{try{e?.({text:t,severity:n})}catch{}},h=async({enabled:e=!1,currentVersion:t,notice:n=null,fetchFn:r=globalThis.fetch,consoleObj:s=console,setTimeoutFn:i=setTimeout,clearTimeoutFn:a=clearTimeout,timeoutMs:o=1e4,url:l=c}={})=>{if(!e)return null;let h=null;try{if("function"!=typeof r)throw new Error("fetch is not available");f(t);const e=globalThis.AbortController;let s;if(e&&o>0){const t=new e;h=i(()=>t.abort(),o),s=t.signal}const a=await r(l,{cache:"no-store",...s?{signal:s}:{}});if(!a?.ok)throw new Error(`${a?.status??"no"} response from ${l}`);const c=(await a.json())?.version;if(f(c),((e,t)=>{const n=f(e),r=f(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=u(n.prerelease[i],r.prerelease[i]);if(0!==e)return e}return 0})(c,t)<=0)return null;const m=(e=>`https://unpkg.com/${d}@${e}/insight4.nxs`)(c);return p(n,`Update available: ${t} → ${c}. Import ${m}`,"warning"),{currentVersion:t,latestVersion:c,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}`),p(n,e,"error"),null}finally{null!==h&&a(h)}};function m(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 g=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},b=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}};(o=globalThis).__zod_globalConfig??(o.__zod_globalConfig={});var y=globalThis.__zod_globalConfig;function v(e){return e&&Object.assign(y,e),y}function k(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 w(e,t){return"bigint"==typeof t?t.toString():t}function I(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function z(e){return null==e}function _(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}var O=Symbol("evaluating");function $(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==O)return void 0===r&&(r=O,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function S(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function M(...e){const t={};for(const n of e)Object.assign(t,Object.getOwnPropertyDescriptors(n));return Object.defineProperties({},t)}function j(e){return JSON.stringify(e)}var x="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function N(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var A=I(()=>{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===N(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!==N(n)&&!1!==Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")}function E(e){return T(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}var C=new Set(["string","number","symbol"]);function P(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function D(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 B(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 L(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 F(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 G(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:s,continue:i,input:a,...o}=e;return o.path??(o.path=[]),o.message=r,t?.reportInput&&(o.input=a),o}function J(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function U(...e){const[t,n,r]=e;return"string"==typeof t?{message:t,code:"custom",input:n,inst:r}:{...t}}var H=(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,w,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},V=m("$ZodError",H),W=m("$ZodError",H,{Parent:Error});var Y=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 g;if(a.issues.length){const t=new(s?.Err??e)(a.issues.map(e=>G(e,i,v())));throw x(t,s?.callee),t}return a.value},K=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=>G(e,i,v())));throw x(t,s?.callee),t}return a.value},Q=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 g;return i.issues.length?{success:!1,error:new(e??V)(i.issues.map(e=>G(e,s,v())))}:{success:!0,data:i.value}},X=Q(W),ee=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=>G(e,s,v())))}:{success:!0,data:i.value}},te=ee(W),ne=e=>(t,n,r)=>{const s=r?{...r,direction:"backward"}:{direction:"backward"};return Y(e)(t,n,s)},re=e=>(t,n,r)=>Y(e)(t,n,r),se=e=>async(t,n,r)=>{const s=r?{...r,direction:"backward"}:{direction:"backward"};return K(e)(t,n,s)},ie=e=>async(t,n,r)=>K(e)(t,n,r),ae=e=>(t,n,r)=>{const s=r?{...r,direction:"backward"}:{direction:"backward"};return Q(e)(t,n,s)},oe=e=>(t,n,r)=>Q(e)(t,n,r),le=e=>async(t,n,r)=>{const s=r?{...r,direction:"backward"}:{direction:"backward"};return ee(e)(t,n,s)},de=e=>async(t,n,r)=>ee(e)(t,n,r),ce=/^[cC][0-9a-z]{6,}$/,fe=/^[0-9a-z]+$/,ue=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,pe=/^[0-9a-vA-V]{20}$/,he=/^[A-Za-z0-9]{27}$/,me=/^[a-zA-Z0-9_-]{21}$/,ge=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,be=/^([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)$/,ve=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var 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])$/,we=/^(([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}|:))$/,Ie=/^((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])$/,ze=/^(([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])$/,_e=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Oe=/^[A-Za-z0-9_-]*$/,$e=/^https?$/,Se=/^\+[1-9]\d{6,14}$/,Me="(?:(?:\\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])))",je=new RegExp(`^${Me}$`);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 Ne=/^-?\d+$/,Ae=/^-?\d+(?:\.\d+)?$/,Te=/^(?:true|false)$/i,Ee=/^[^A-Z]*$/,Ce=/^[^a-z]*$/,Pe=m("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),De={number:"number",bigint:"bigint",object:"date"},Re=m("$ZodCheckLessThan",(e,t)=>{Pe.init(e,t);const n=De[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=m("$ZodCheckGreaterThan",(e,t)=>{Pe.init(e,t);const n=De[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})}}),Be=m("$ZodCheckMultipleOf",(e,t)=>{Pe.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})}}),Le=m("$ZodCheckNumberFormat",(e,t)=>{Pe.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),r=n?"int":"number",[s,i]=Z[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=Ne)}),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})}}),Fe=m("$ZodCheckMaxLength",(e,t)=>{var n;Pe.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!z(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=J(r);n.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),qe=m("$ZodCheckMinLength",(e,t)=>{var n;Pe.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!z(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=J(r);n.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Ge=m("$ZodCheckLengthEquals",(e,t)=>{var n;Pe.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!z(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=J(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})}}),Je=m("$ZodCheckStringFormat",(e,t)=>{var n,r;Pe.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=()=>{})}),Ue=m("$ZodCheckRegex",(e,t)=>{Je.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})}}),He=m("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Ee),Je.init(e,t)}),Ve=m("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Ce),Je.init(e,t)}),We=m("$ZodCheckIncludes",(e,t)=>{Pe.init(e,t);const n=P(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=m("$ZodCheckStartsWith",(e,t)=>{Pe.init(e,t);const n=new RegExp(`^${P(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})}}),Ke=m("$ZodCheckEndsWith",(e,t)=>{Pe.init(e,t);const n=new RegExp(`.*${P(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})}}),Qe=m("$ZodCheckOverwrite",(e,t)=>{Pe.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}}),Xe=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"))}},et={major:4,minor:4,patch:3},tt=m("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=et;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=B(e);for(const i of t){if(i._zod.def.when){if(L(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 g;if(r||a instanceof Promise)r=(r??Promise.resolve()).then(async()=>{await a,e.issues.length!==t&&(s||(s=B(e,t)))});else{if(e.issues.length===t)continue;s||(s=B(e,t))}}return r?r.then(()=>e):e},n=(n,s,i)=>{if(B(n))return n.aborted=!0,n;const a=t(s,r,i);if(a instanceof Promise){if(!1===i.async)throw new g;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 g;return a.then(e=>t(e,r,i))}return t(a,r,i)}}$(e,"~standard",()=>({validate:t=>{try{const n=X(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch(n){return te(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}))}),nt=m("$ZodString",(e,t)=>{var n;tt.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}}),rt=m("$ZodStringFormat",(e,t)=>{Je.init(e,t),nt.init(e,t)}),st=m("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=be),rt.init(e,t)}),it=m("$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());rt.init(e,t)}),at=m("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=ve),rt.init(e,t)}),ot=m("$ZodURL",(e,t)=>{rt.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})}}}),lt=m("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),rt.init(e,t)}),dt=m("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=me),rt.init(e,t)}),ct=m("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=ce),rt.init(e,t)}),ft=m("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=fe),rt.init(e,t)}),ut=m("$ZodULID",(e,t)=>{t.pattern??(t.pattern=ue),rt.init(e,t)}),pt=m("$ZodXID",(e,t)=>{t.pattern??(t.pattern=pe),rt.init(e,t)}),ht=m("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=he),rt.init(e,t)}),mt=m("$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(`^${Me}T(?:${r})$`)}(t)),rt.init(e,t)}),gt=m("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=je),rt.init(e,t)}),bt=m("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=new RegExp(`^${xe(t)}$`)),rt.init(e,t)}),yt=m("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=ge),rt.init(e,t)}),vt=m("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=ke),rt.init(e,t),e._zod.bag.format="ipv4"}),kt=m("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=we),rt.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})}}}),wt=m("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Ie),rt.init(e,t)}),It=m("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=ze),rt.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 zt(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 _t=m("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=_e),rt.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{zt(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});var Ot=m("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Oe),rt.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{(function(e){if(!Oe.test(e))return!1;const t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return zt(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=m("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Se),rt.init(e,t)});var St=m("$ZodJWT",(e,t)=>{rt.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})}}),Mt=m("$ZodNumber",(e,t)=>{tt.init(e,t),e._zod.pattern=e._zod.bag.pattern??Ae,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}}),jt=m("$ZodNumberFormat",(e,t)=>{Le.init(e,t),Mt.init(e,t)}),xt=m("$ZodBoolean",(e,t)=>{tt.init(e,t),e._zod.pattern=Te,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}}),Nt=m("$ZodUnknown",(e,t)=>{tt.init(e,t),e._zod.parse=e=>e}),At=m("$ZodNever",(e,t)=>{tt.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(...F(n,e.issues)),t.value[n]=e.value}var Et=m("$ZodArray",(e,t)=>{tt.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=>Tt(t,n,e))):Tt(o,n,e)}return i.length?Promise.all(i).then(()=>n):n}});function Ct(e,t,n,r,s,i){const a=n in r;if(e.issues.length){if(s&&i&&!a)return;t.issues.push(...F(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 Pt(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 Dt(e,t,n,r,s,i){const a=[],o=s.keySet,l=s.catchall._zod,d=l.def.type,c="optional"===l.optin,f="optional"===l.optout;for(const u in t){if("__proto__"===u)continue;if(o.has(u))continue;if("never"===d){a.push(u);continue}const s=l.run({value:t[u],issues:[]},r);s instanceof Promise?e.push(s.then(e=>Ct(e,n,u,t,c,f))):Ct(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 Rt=m("$ZodObject",(e,t)=>{if(tt.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=I(()=>Pt(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=N,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 l=[],d=i.shape;for(const e of i.keys){const n=d[e],r="optional"===n._zod.optin,s="optional"===n._zod.optout,i=n._zod.run({value:o[e],issues:[]},a);i instanceof Promise?l.push(i.then(n=>Ct(n,t,e,o,r,s))):Ct(i,t,e,o,r,s)}return s?Dt(l,o,t,a,n.value,e):l.length?Promise.all(l).then(()=>t):t}}),Zt=m("$ZodObjectJIT",(e,t)=>{Rt.init(e,t);const n=e._zod.parse,r=I(()=>Pt(t));let s;const i=N,a=!y.jitless,o=a&&A.value,l=t.catchall;let d;e._zod.parse=(c,f)=>{d??(d=r.value);const u=c.value;return i(u)?a&&o&&!1===f?.async&&!0!==f.jitless?(s||(s=(e=>{const t=new Xe(["shape","payload","ctx"]),n=r.value,s=e=>{const t=j(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=j(r),o=e[r],l="optional"===o?._zod?.optin,d="optional"===o?._zod?.optout;t.write(`const ${n} = ${s(r)};`),l&&d?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 `):l?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),l?Dt([],u,c,f,d,e):c):n(c,f):(c.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),c)}});function Bt(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=>!B(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=>G(e,r,v())))}),t)}var Lt=m("$ZodUnion",(e,t)=>{tt.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=>_(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=>Bt(t,r,e,s)):Bt(a,r,e,s)}}),Ft=m("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Lt.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=I(()=>{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(!N(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)}}),qt=m("$ZodIntersection",(e,t)=>{tt.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])=>Jt(e,t,n)):Jt(e,s,i)}});function Gt(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)),s={...e,...t};for(const i of r){const n=Gt(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=Gt(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 Jt(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}),B(e))return e;const a=Gt(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 Ut=m("$ZodRecord",(e,t)=>{tt.init(e,t),e._zod.parse=(n,r)=>{const s=n.value;if(!T(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 d of a)if("string"==typeof d||"number"==typeof d||"symbol"==typeof d){o.add("number"==typeof d?d.toString():d);const a=t.keyType._zod.run({value:d,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=>G(e,r,v())),input:d,path:[d],inst:e});continue}const l=a.value,c=t.valueType._zod.run({value:s[d],issues:[]},r);c instanceof Promise?i.push(c.then(e=>{e.issues.length&&n.issues.push(...F(d,e.issues)),n.value[l]=e.value})):(c.issues.length&&n.issues.push(...F(d,c.issues)),n.value[l]=c.value)}let l;for(const e in s)o.has(e)||(l=l??[],l.push(e));l&&l.length>0&&n.issues.push({code:"unrecognized_keys",input:s,inst:e,keys:l})}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&&Ae.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=>G(e,r,v())),input:a,path:[a],inst:e});continue}const l=t.valueType._zod.run({value:s[a],issues:[]},r);l instanceof Promise?i.push(l.then(e=>{e.issues.length&&n.issues.push(...F(a,e.issues)),n.value[o.value]=e.value})):(l.issues.length&&n.issues.push(...F(a,l.issues)),n.value[o.value]=l.value)}}return i.length?Promise.all(i).then(()=>n):n}}),Ht=m("$ZodEnum",(e,t)=>{tt.init(e,t);const n=k(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(e=>C.has(typeof e)).map(e=>"string"==typeof e?P(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}}),Vt=m("$ZodLiteral",(e,t)=>{if(tt.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?P(e):e?P(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}}),Wt=m("$ZodTransform",(e,t)=>{tt.init(e,t),e._zod.optin="optional",e._zod.parse=(n,r)=>{if("backward"===r.direction)throw new b(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 g;return n.value=s,n.fallback=!0,n}});function Yt(e,t){return void 0===t&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}var Kt=m("$ZodOptional",(e,t)=>{tt.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(`^(${_(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=>Yt(e,r)):Yt(s,r)}return void 0===e.value?e:t.innerType._zod.run(e,n)}}),Qt=m("$ZodExactOptional",(e,t)=>{Kt.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)}),Xt=m("$ZodNullable",(e,t)=>{tt.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(`^(${_(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)}),en=m("$ZodDefault",(e,t)=>{tt.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=>tn(e,t)):tn(r,t)}});function tn(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}var nn=m("$ZodPrefault",(e,t)=>{tt.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))}),rn=m("$ZodNonOptional",(e,t)=>{tt.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=>sn(t,e)):sn(s,e)}});function sn(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 an=m("$ZodCatch",(e,t)=>{tt.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=>G(e,n,v()))},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=>G(e,n,v()))},input:e.value}),e.issues=[],e.fallback=!0),e)}}),on=m("$ZodPipe",(e,t)=>{tt.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=>ln(e,t.in,n)):ln(r,t.in,n)}const r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>ln(e,t.out,n)):ln(r,t.out,n)}});function ln(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=m("$ZodReadonly",(e,t)=>{tt.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(cn):cn(r)}});function cn(e){return e.value=Object.freeze(e.value),e}var fn,un=m("$ZodCustom",(e,t)=>{Pe.init(e,t),tt.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=>pn(t,n,r,e));pn(s,n,r,e)}});function pn(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(U(e))}}var hn=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)}};(fn=globalThis).__zod_globalRegistry??(fn.__zod_globalRegistry=new hn);var mn=globalThis.__zod_globalRegistry;function gn(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...R(t)})}function bn(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 vn(e,t){return new Ze({check:"greater_than",...R(t),value:e,inclusive:!1})}function kn(e,t){return new Ze({check:"greater_than",...R(t),value:e,inclusive:!0})}function wn(e,t){return new Be({check:"multiple_of",...R(t),value:e})}function In(e,t){return new Fe({check:"max_length",...R(t),maximum:e})}function zn(e,t){return new qe({check:"min_length",...R(t),minimum:e})}function _n(e,t){return new Ge({check:"length_equals",...R(t),length:e})}function On(e){return new Qe({check:"overwrite",tx:e})}function $n(e,t){const n=new Pe({check:"custom",...R(t)});return n._zod.check=e,n}function Sn(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??mn,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 Mn(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),Mn(i,t,r),t.seen.get(i).isParent=!0)}const l=t.metadataRegistry.get(e);return l&&Object.assign(a.schema,l),"input"===t.io&&Nn(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 jn(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 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 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 l of[...e.seen.entries()].reverse())r(l[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 l of e.seen.entries()){const e=l[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:An(t,"input",e.processors),output:An(t,"output",e.processors)}},enumerable:!1,writable:!1}),n}catch(o){throw new Error("Error converting schema to JSON.")}}function Nn(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 Nn(r.element,n);if("set"===r.type)return Nn(r.valueType,n);if("lazy"===r.type)return Nn(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 Nn(r.innerType,n);if("intersection"===r.type)return Nn(r.left,n)||Nn(r.right,n);if("record"===r.type||"map"===r.type)return Nn(r.keyType,n)||Nn(r.valueType,n);if("pipe"===r.type)return!!e._zod.traits.has("$ZodCodec")||(Nn(r.in,n)||Nn(r.out,n));if("object"===r.type){for(const e in r.shape)if(Nn(r.shape[e],n))return!0;return!1}if("union"===r.type){for(const e of r.options)if(Nn(e,n))return!0;return!1}if("tuple"===r.type){for(const e of r.items)if(Nn(e,n))return!0;return!(!r.rest||!Nn(r.rest,n))}return!1}var An=(e,t,n={})=>r=>{const{libraryOptions:s,target:i}=r??{},a=Sn({...s??{},target:i,io:t,processors:n});return Mn(e,a),jn(a,e),xn(a,e)},Tn={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},En=(e,t,n,r)=>{const s=e._zod.def;Mn(s.innerType,t,r);t.seen.get(e).ref=s.innerType},Cn=m("ZodISODateTime",(e,t)=>{mt.init(e,t),dr.init(e,t)});function Pn(e){return function(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...R(t)})}(Cn,e)}var Dn=m("ZodISODate",(e,t)=>{gt.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)})}(Dn,e)}var Zn=m("ZodISOTime",(e,t)=>{bt.init(e,t),dr.init(e,t)});function Bn(e){return function(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...R(t)})}(Zn,e)}var Ln=m("ZodISODuration",(e,t)=>{yt.init(e,t),dr.init(e,t)});function Fn(e){return function(e,t){return new e({type:"string",format:"duration",check:"string_format",...R(t)})}(Ln,e)}var qn=(e,t)=>{V.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,w,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,w,2)}},isEmpty:{get:()=>0===e.issues.length}})},Gn=m("ZodError",qn,{Parent:Error}),Jn=Y(Gn),Un=K(Gn),Hn=Q(Gn),Vn=ee(Gn),Wn=ne(Gn),Yn=re(Gn),Kn=se(Gn),Qn=ie(Gn),Xn=ae(Gn),er=oe(Gn),tr=le(Gn),nr=de(Gn),rr=new WeakMap;function sr(e,t,n){const r=Object.getPrototypeOf(e);let s=rr.get(r);if(s||(s=new Set,rr.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 ir=m("ZodType",(e,t)=>(tt.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:An(e,"input"),output:An(e,"output")}}),e.toJSONSchema=((e,t={})=>n=>{const r=Sn({...n,processors:t});return Mn(e,r),jn(r,e),xn(r,e)})(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(t,n)=>Jn(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Hn(e,t,n),e.parseAsync=async(t,n)=>Un(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Vn(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>Wn(e,t,n),e.decode=(t,n)=>Yn(e,t,n),e.encodeAsync=async(t,n)=>Kn(e,t,n),e.decodeAsync=async(t,n)=>Qn(e,t,n),e.safeEncode=(t,n)=>Xn(e,t,n),e.safeDecode=(t,n)=>er(e,t,n),e.safeEncodeAsync=async(t,n)=>tr(e,t,n),e.safeDecodeAsync=async(t,n)=>nr(e,t,n),sr(e,"ZodType",{check(...e){const t=this.def;return this.clone(M(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 D(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)})}(ps,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(U(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(U(r))}},e(t.value,t)),t);return n}(e,t)}(e,t))},overwrite(e){return this.check(On(e))},optional(){return ns(this)},exactOptional(){return new rs({type:"optional",innerType:this})},nullable(){return is(this)},nullish(){return ns(is(this))},nonoptional(e){return function(e,t){return new ls({type:"nonoptional",innerType:e,...R(t)})}(this,e)},array(){return Br(this)},or(e){return Jr([this,e])},and(e){return new Hr({type:"intersection",left:this,right:e})},transform(e){return fs(this,new es({type:"transform",transform:e}))},default(e){return t=e,new as({type:"default",innerType:this,get defaultValue(){return"function"==typeof t?t():E(t)}});var t},prefault(e){return t=e,new os({type:"prefault",innerType:this,get defaultValue(){return"function"==typeof t?t():E(t)}});var t},catch(e){return new ds({type:"catch",innerType:this,catchValue:"function"==typeof(t=e)?t:()=>t});var t},pipe(e){return fs(this,e)},readonly(){return new us({type:"readonly",innerType:this})},describe(e){const t=this.clone();return mn.add(t,{description:e}),t},meta(...e){if(0===e.length)return mn.get(this);const t=this.clone();return mn.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:()=>mn.get(e)?.description,configurable:!0}),e)),ar=m("_ZodString",(e,t)=>{nt.init(e,t),ir.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:l}=e._zod.bag;if("number"==typeof s&&(r.minLength=s),"number"==typeof i&&(r.maxLength=i),a&&(r.format=Tn[a]??a,""===r.format&&delete r.format,"time"===a&&delete r.format),l&&(r.contentEncoding=l),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,sr(e,"_ZodString",{regex(...e){return this.check(function(e,t){return new Ue({check:"string_format",format:"regex",...R(t),pattern:e})}(...e))},includes(...e){return this.check(function(e,t){return new We({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 Ke({check:"string_format",format:"ends_with",...R(t),suffix:e})}(...e))},min(...e){return this.check(zn(...e))},max(...e){return this.check(In(...e))},length(...e){return this.check(_n(...e))},nonempty(...e){return this.check(zn(1,...e))},lowercase(e){return this.check(function(e){return new He({check:"string_format",format:"lowercase",...R(e)})}(e))},uppercase(e){return this.check(function(e){return new Ve({check:"string_format",format:"uppercase",...R(e)})}(e))},trim(){return this.check(On(e=>e.trim()))},normalize(...e){return this.check(function(e){return On(t=>t.normalize(e))}(...e))},toLowerCase(){return this.check(On(e=>e.toLowerCase()))},toUpperCase(){return this.check(On(e=>e.toUpperCase()))},slugify(){return this.check(On(e=>function(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}(e)))}})}),or=m("ZodString",(e,t)=>{nt.init(e,t),ar.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)})}(cr,t)),e.url=t=>e.check(function(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...R(t)})}(pr,t)),e.jwt=t=>e.check(function(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...R(t)})}(Mr,t)),e.emoji=t=>e.check(function(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...R(t)})}(hr,t)),e.guid=t=>e.check(gn(fr,t)),e.uuid=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...R(t)})}(ur,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)})}(ur,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)})}(ur,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)})}(ur,t)),e.nanoid=t=>e.check(function(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...R(t)})}(mr,t)),e.guid=t=>e.check(gn(fr,t)),e.cuid=t=>e.check(function(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...R(t)})}(gr,t)),e.cuid2=t=>e.check(function(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...R(t)})}(br,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)})}(Or,t)),e.base64url=t=>e.check(function(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...R(t)})}($r,t)),e.xid=t=>e.check(function(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...R(t)})}(vr,t)),e.ksuid=t=>e.check(function(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...R(t)})}(kr,t)),e.ipv4=t=>e.check(function(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...R(t)})}(wr,t)),e.ipv6=t=>e.check(function(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...R(t)})}(Ir,t)),e.cidrv4=t=>e.check(function(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...R(t)})}(zr,t)),e.cidrv6=t=>e.check(function(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...R(t)})}(_r,t)),e.e164=t=>e.check(function(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...R(t)})}(Sr,t)),e.datetime=t=>e.check(Pn(t)),e.date=t=>e.check(Rn(t)),e.time=t=>e.check(Bn(t)),e.duration=t=>e.check(Fn(t))});function lr(e){return function(e,t){return new e({type:"string",...R(t)})}(or,e)}var dr=m("ZodStringFormat",(e,t)=>{rt.init(e,t),ar.init(e,t)}),cr=m("ZodEmail",(e,t)=>{at.init(e,t),dr.init(e,t)}),fr=m("ZodGUID",(e,t)=>{st.init(e,t),dr.init(e,t)}),ur=m("ZodUUID",(e,t)=>{it.init(e,t),dr.init(e,t)}),pr=m("ZodURL",(e,t)=>{ot.init(e,t),dr.init(e,t)}),hr=m("ZodEmoji",(e,t)=>{lt.init(e,t),dr.init(e,t)}),mr=m("ZodNanoID",(e,t)=>{dt.init(e,t),dr.init(e,t)}),gr=m("ZodCUID",(e,t)=>{ct.init(e,t),dr.init(e,t)}),br=m("ZodCUID2",(e,t)=>{ft.init(e,t),dr.init(e,t)}),yr=m("ZodULID",(e,t)=>{ut.init(e,t),dr.init(e,t)}),vr=m("ZodXID",(e,t)=>{pt.init(e,t),dr.init(e,t)}),kr=m("ZodKSUID",(e,t)=>{ht.init(e,t),dr.init(e,t)}),wr=m("ZodIPv4",(e,t)=>{vt.init(e,t),dr.init(e,t)}),Ir=m("ZodIPv6",(e,t)=>{kt.init(e,t),dr.init(e,t)}),zr=m("ZodCIDRv4",(e,t)=>{wt.init(e,t),dr.init(e,t)}),_r=m("ZodCIDRv6",(e,t)=>{It.init(e,t),dr.init(e,t)}),Or=m("ZodBase64",(e,t)=>{_t.init(e,t),dr.init(e,t)}),$r=m("ZodBase64URL",(e,t)=>{Ot.init(e,t),dr.init(e,t)}),Sr=m("ZodE164",(e,t)=>{$t.init(e,t),dr.init(e,t)}),Mr=m("ZodJWT",(e,t)=>{St.init(e,t),dr.init(e,t)}),jr=m("ZodNumber",(e,t)=>{Mt.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=n,{minimum:s,maximum:i,format:a,multipleOf:o,exclusiveMaximum:l,exclusiveMinimum:d}=e._zod.bag;"string"==typeof a&&a.includes("int")?r.type="integer":r.type="number";const c="number"==typeof d&&d>=(s??Number.NEGATIVE_INFINITY),f="number"==typeof l&&l<=(i??Number.POSITIVE_INFINITY),u="draft-04"===t.target||"openapi-3.0"===t.target;c?u?(r.minimum=d,r.exclusiveMinimum=!0):r.exclusiveMinimum=d:"number"==typeof s&&(r.minimum=s),f?u?(r.maximum=l,r.exclusiveMaximum=!0):r.exclusiveMaximum=l:"number"==typeof i&&(r.maximum=i),"number"==typeof o&&(r.multipleOf=o)})(e,t,n),sr(e,"ZodNumber",{gt(e,t){return this.check(vn(e,t))},gte(e,t){return this.check(kn(e,t))},min(e,t){return this.check(kn(e,t))},lt(e,t){return this.check(bn(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(Ar(e))},safe(e){return this.check(Ar(e))},positive(e){return this.check(vn(0,e))},nonnegative(e){return this.check(kn(0,e))},negative(e){return this.check(bn(0,e))},nonpositive(e){return this.check(yn(0,e))},multipleOf(e,t){return this.check(wn(e,t))},step(e,t){return this.check(wn(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)})}(jr,e)}var Nr=m("ZodNumberFormat",(e,t)=>{jt.init(e,t),jr.init(e,t)});function Ar(e){return function(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...R(t)})}(Nr,e)}var Tr=m("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 Er(e){return function(e,t){return new e({type:"boolean",...R(t)})}(Tr,e)}var Cr=m("ZodUnknown",(e,t)=>{Nt.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(e,t,n)=>{}});function Pr(){return new Cr({type:"unknown"})}var Dr=m("ZodNever",(e,t)=>{At.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)})}(Dr,e)}var Zr=m("ZodArray",(e,t)=>{Et.init(e,t),ir.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=Mn(i.element,t,{...r,path:[...r.path,"items"]})})(e,t,n,r),e.element=t.element,sr(e,"ZodArray",{min(e,t){return this.check(zn(e,t))},nonempty(e){return this.check(zn(1,e))},max(e,t){return this.check(In(e,t))},length(e,t){return this.check(_n(e,t))},unwrap(){return this.element}})});function Br(e,t){return function(e,t,n){return new e({type:"array",element:t,...R(n)})}(Zr,e,t)}var Lr=m("ZodObject",(e,t)=>{Zt.init(e,t),ir.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 d in a)s.properties[d]=Mn(a[d],t,{...r,path:[...r.path,"properties",d]});const o=new Set(Object.keys(a)),l=new Set([...o].filter(e=>{const n=i.shape[e]._zod;return"input"===t.io?void 0===n.optin:void 0===n.optout}));l.size>0&&(s.required=Array.from(l)),"never"===i.catchall?._zod.def.type?s.additionalProperties=!1:i.catchall?i.catchall&&(s.additionalProperties=Mn(i.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):"output"===t.io&&(s.additionalProperties=!1)})(e,t,n,r),$(e,"shape",()=>t.shape),sr(e,"ZodObject",{keyof(){return Kr(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:Pr()})},loose(){return this.clone({...this._zod.def,catchall:Pr()})},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 D(e,M(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return S(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 D(e,M(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return S(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 D(e,M(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return S(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 D(e,M(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 S(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 D(e,M(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 S(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 D(t,M(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 S(this,"shape",s),s},checks:[]}))}(ts,this,e[0])},required(...e){return t=ls,n=this,r=e[0],D(n,M(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 S(this,"shape",s),s}}));var t,n,r}})});function Fr(e,t){return new Lr({type:"object",shape:e??{},...R(t)})}function qr(e,t){return new Lr({type:"object",shape:e,catchall:Rr(),...R(t)})}var Gr=m("ZodUnion",(e,t)=>{Lt.init(e,t),ir.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)=>Mn(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 Jr(e,t){return new Gr({type:"union",options:e,...R(t)})}var Ur=m("ZodDiscriminatedUnion",(e,t)=>{Gr.init(e,t),Ft.init(e,t)});var Hr=m("ZodIntersection",(e,t)=>{qt.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const s=e._zod.def,i=Mn(s.left,t,{...r,path:[...r.path,"allOf",0]}),a=Mn(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 Vr=m("ZodRecord",(e,t)=>{Ut.init(e,t),ir.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=Mn(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=Mn(i.keyType,t,{...r,path:[...r.path,"propertyNames"]})),s.additionalProperties=Mn(i.valueType,t,{...r,path:[...r.path,"additionalProperties"]});const l=a._zod.values;if(l){const e=[...l].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 Wr(e,t,n){return t&&t._zod?new Vr({type:"record",keyType:e,valueType:t,...R(n)}):new Vr({type:"record",keyType:lr(),valueType:e,...R(t)})}var Yr=m("ZodEnum",(e,t)=>{Ht.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=k(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 Yr({...t,checks:[],...R(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 Yr({...t,checks:[],...R(r),entries:s})}});function Kr(e,t){return new Yr({type:"enum",entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...R(t)})}var Qr=m("ZodLiteral",(e,t)=>{Vt.init(e,t),ir.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 Xr(e,t){return new Qr({type:"literal",values:Array.isArray(e)?e:[e],...R(t)})}var es=m("ZodTransform",(e,t)=>{Wt.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 b(e.constructor.name);n.addIssue=r=>{if("string"==typeof r)n.issues.push(U(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(U(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 ts=m("ZodOptional",(e,t)=>{Kt.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>En(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});function ns(e){return new ts({type:"optional",innerType:e})}var rs=m("ZodExactOptional",(e,t)=>{Qt.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>En(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});var ss=m("ZodNullable",(e,t)=>{Xt.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const s=e._zod.def,i=Mn(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 is(e){return new ss({type:"nullable",innerType:e})}var as=m("ZodDefault",(e,t)=>{en.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const s=e._zod.def;Mn(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 os=m("ZodPrefault",(e,t)=>{nn.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const s=e._zod.def;Mn(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 ls=m("ZodNonOptional",(e,t)=>{rn.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const s=e._zod.def;Mn(s.innerType,t,r),t.seen.get(e).ref=s.innerType})(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});var ds=m("ZodCatch",(e,t)=>{an.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const s=e._zod.def;let i;Mn(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 cs=m("ZodPipe",(e,t)=>{on.init(e,t),ir.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;Mn(a,t,r),t.seen.get(e).ref=a})(e,t,0,r),e.in=t.in,e.out=t.out});function fs(e,t){return new cs({type:"pipe",in:e,out:t})}var us=m("ZodReadonly",(e,t)=>{dn.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const s=e._zod.def;Mn(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 ps=m("ZodCustom",(e,t)=>{un.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 hs,ms,gs,bs=lr().regex(/^[a-z]+$/,"aff ids are single lowercase words"),ys=lr().regex(/^[a-z][a-zA-Z]*$/,"balance ids are lowercase-led words"),vs=lr().regex(/^[a-z]+( [a-z]+)*$/,"cure ids are lowercase words separated by single spaces"),ks=lr().regex(/^[a-z]+$/,"venom ids are single lowercase words"),ws=lr().regex(/^[a-z]+$/,"profession ids are single lowercase words"),Is=qr({shortName:lr().min(1),fg:lr(),bg:lr()}),zs={id:bs,display:Is.optional(),curesTo:bs.optional(),pseudo:Er().default(!1),curedLast:Er().default(!1),gatedBy:bs.optional()},_s=qr({...zs,kind:Xr("plain")}),Os=qr({...zs,kind:Xr("timed"),durationMs:xr().int().positive(),provenance:Kr(["verified","unverified"]).default("verified")}),$s=qr({atLeast:xr().int().positive(),removes:xr().int().positive()}),Ss=qr({...zs,kind:Xr("countable"),max:xr().int().positive(),cureSteps:Br($s).default([])}).superRefine((e,t)=>{let n=0;e.cureSteps.forEach((r,s)=>{r.atLeast<=n&&t.addIssue({code:"custom",path:["cureSteps",s,"atLeast"],message:"cure-step thresholds must be strictly ascending"}),r.atLeast>e.max&&t.addIssue({code:"custom",path:["cureSteps",s,"atLeast"],message:"cure-step thresholds cannot exceed the countable max"}),n=r.atLeast})}),Ms=(hs="kind",ms=[_s,Os,Ss],new Ur({type:"union",options:ms,discriminator:hs,...R(gs)})),js=Br(Ms).min(1).refine(e=>new Set(e.map(e=>e.id)).size===e.length,{message:"aff ids must be unique"}).superRefine((e,t)=>{const n=new Map(e.map(e=>[e.id,e]));e.forEach((e,r)=>{if(void 0===e.gatedBy)return;const s=n.get(e.gatedBy);s?(void 0!==s.gatedBy&&t.addIssue({code:"custom",path:[r,"gatedBy"],message:`gate '${e.gatedBy}' is itself gated — gates may not chain`}),"countable"===s.kind&&t.addIssue({code:"custom",path:[r,"gatedBy"],message:`gate '${e.gatedBy}' is countable — a gate must be a presence aff`})):t.addIssue({code:"custom",path:[r,"gatedBy"],message:`gate '${e.gatedBy}' is not an aff`})})}),xs=qr({fg:lr(),bg:lr()}),Ns=Wr(lr().min(1),xs),As=Wr(bs,Is),Ts=qr({delimiter:xs,label:xs}),Es=qr({info:xs,warning:xs,error:xs}),Cs=qr({bracket:xs,detail:xs,tag:Ts,severity:Es}),Ps=qr({affs:As,chrome:Cs}),Ds=Ns.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"}}),Rs=Ds,Zs={addiction:{shortName:"add",...Rs.ferrum},aeon:{shortName:"ae",...Rs.cinnabar},agoraphobia:{shortName:"agor",...Rs.argentum},amnesia:{shortName:"amn",fg:"",bg:""},anorexia:{shortName:"ANO",...Rs.epidermal},asthma:{shortName:"AST",...Rs.aurum},blackout:{shortName:"bo",fg:"",bg:""},blindness:{shortName:"unb",...Rs.arsenic},bound:{shortName:"bnd",...Rs.writhe},brokenleftarm:{shortName:"la1",...Rs.mending},brokenleftleg:{shortName:"ll1",...Rs.mending},brokenrightarm:{shortName:"ra1",...Rs.mending},brokenrightleg:{shortName:"rl1",...Rs.mending},bruisedribs:{shortName:"ribs",fg:"",bg:""},burning:{shortName:"burn",...Rs.mending},calcifiedskull:{shortName:"calh",...Rs.restoration},calcifiedtorso:{shortName:"calt",...Rs.restoration},claustrophobia:{shortName:"clau",...Rs.stannum},cleanseaura:{shortName:"cleanse",fg:"",bg:""},clumsiness:{shortName:"clu",...Rs.aurum},concussion:{shortName:"conc",...Rs.restoration},confusion:{shortName:"con",...Rs.stannum},corruption:{shortName:"corr",fg:"",bg:""},crackedribs:{shortName:"cr",...Rs.health},crushedthroat:{shortName:"cru",...Rs.mending},daeggerimpale:{shortName:"daeg",...Rs.writhe},damagedleftarm:{shortName:"la2",...Rs.restoration},damagedleftleg:{shortName:"ll2",...Rs.restoration},damagedrightarm:{shortName:"ra2",...Rs.restoration},damagedrightleg:{shortName:"rl2",...Rs.restoration},damagedhead:{shortName:"hd2",...Rs.restoration},darkshade:{shortName:"dark",...Rs.ferrum},dazed:{shortName:"dzd",...Rs.cinnabar},dazzled:{shortName:"dzl",...Rs.mending},deadening:{shortName:"dea",...Rs.cinnabar},deafness:{shortName:"und",...Rs.calamine},dehydrated:{shortName:"deh",fg:"",bg:""},dementia:{shortName:"dem",...Rs.stannum},depression:{shortName:"dep",...Rs.plumbum},deteriorate:{shortName:"det",fg:"",bg:""},disloyalty:{shortName:"disl",...Rs.realgar},disrupted:{shortName:"disr",fg:"",bg:""},dissonance:{shortName:"disso",...Rs.plumbum},dizziness:{shortName:"diz",...Rs.plumbum},enmesh:{shortName:"enmsh",...Rs.writhe},ensorcelled:{shortName:"ensor",fg:"",bg:""},entangled:{shortName:"entgl",...Rs.writhe},epilepsy:{shortName:"epi",...Rs.plumbum},fear:{shortName:"fear",fg:"",bg:""},flushings:{shortName:"flush",...Rs.ferrum},frostbite:{shortName:"frost",...Rs.caloric},frozen:{shortName:"frz",...Rs.caloric},fulminated:{shortName:"fulm",...Rs.plumbum},generosity:{shortName:"gen",...Rs.cuprum},grievouswounds:{shortName:"grv",...Rs.health},guilt:{shortName:"gui",...Rs.argentum},haemophilia:{shortName:"haem",...Rs.ferrum},hallucinations:{shortName:"hall",...Rs.stannum},hamstrung:{shortName:"hms",fg:"",bg:""},healthleech:{shortName:"hthl",...Rs.aurum},heartseed:{shortName:"heart",...Rs.restoration},hellsight:{shortName:"hell",...Rs.realgar},horror:{shortName:"hor",...Rs.argentum},hypersomnia:{shortName:"hypers",...Rs.stannum},hypochondria:{shortName:"hypoch",...Rs.argentum},hypothermia:{shortName:"hypoth",...Rs.restoration},icefisted:{shortName:"ice",fg:"",bg:""},impaled:{shortName:"impl",...Rs.writhe},impatience:{shortName:"IMPAT",...Rs.plumbum},indifference:{shortName:"ind",...Rs.cuprum},itching:{shortName:"itch",...Rs.epidermal},justice:{shortName:"just",...Rs.cuprum},kkractlebrand:{shortName:"kkr",...Rs.health},laceratedthroat:{shortName:"lac2",...Rs.restoration},latched:{shortName:"latch",...Rs.health},lethargy:{shortName:"let",...Rs.ferrum},lightbind:{shortName:"light",fg:"",bg:""},loneliness:{shortName:"lon",...Rs.argentum},lovers:{shortName:"love",...Rs.cuprum},manaleech:{shortName:"man",...Rs.realgar},mangledleftarm:{shortName:"la3",...Rs.restoration},mangledleftleg:{shortName:"ll3",...Rs.restoration},mangledrightarm:{shortName:"ra3",...Rs.restoration},mangledrightleg:{shortName:"rl3",...Rs.restoration},mangledhead:{shortName:"hd3",...Rs.restoration},masochism:{shortName:"maso",...Rs.argentum},mildtrauma:{shortName:"tor1",...Rs.restoration},mycalium:{shortName:"myc",...Rs.plumbum},nausea:{shortName:"nau",...Rs.ferrum},numbedleftarm:{shortName:"nbla",fg:"",bg:""},numbedrightarm:{shortName:"nbra",fg:"",bg:""},pacified:{shortName:"pac",...Rs.cuprum},palpatarfeed:{shortName:"worm",fg:"",bg:""},paralysis:{shortName:"PAR",...Rs.magnesium},paranoia:{shortName:"prn",...Rs.stannum},parasite:{shortName:"prs",...Rs.aurum},peace:{shortName:"pea",...Rs.cuprum},phlogisticated:{shortName:"phlog",fg:"",bg:""},pinshot:{shortName:"psh",fg:"",bg:""},pressure:{shortName:"pres",...Rs.calcite},prone:{shortName:"pr",fg:"",bg:""},pyramides:{shortName:"pyra",...Rs.magnesium},pyre:{shortName:"pyre",...Rs.cuprum},rebbies:{shortName:"reb",...Rs.aurum},recklessness:{shortName:"reck",...Rs.argentum},retribution:{shortName:"retr",...Rs.cuprum},revealed:{shortName:"rev",fg:"",bg:""},sandfever:{shortName:"sand",...Rs.plumbum},scalded:{shortName:"scald",...Rs.epidermal},scytherus:{shortName:"scy",...Rs.ferrum},selarnia:{shortName:"sel",...Rs.mending},sensitivity:{shortName:"sen",...Rs.aurum},serioustrauma:{shortName:"tor2",...Rs.restoration},shadowmadness:{shortName:"shad",...Rs.plumbum},shivering:{shortName:"shiv",...Rs.caloric},shyness:{shortName:"shy",...Rs.plumbum},skullfractures:{shortName:"sf",...Rs.health},slashedthroat:{shortName:"lac1",...Rs.epidermal},sleeping:{shortName:"slp",fg:"",bg:""},slickness:{shortName:"SLI",...Rs.magnesium},slimeobscure:{shortName:"slime",fg:"",bg:""},spiritburn:{shortName:"spirB",...Rs.argentum},spiritwrack:{shortName:"spirW",fg:"",bg:""},stupidity:{shortName:"st",...Rs.plumbum},stuttering:{shortName:"stut",...Rs.epidermal},homunculusmercury:{shortName:"merc",fg:"",bg:""},temperedcholeric:{shortName:"choH",...Rs.antimony},temperedmelancholic:{shortName:"melaH",...Rs.antimony},temperedphlegmatic:{shortName:"phleH",...Rs.antimony},temperedsanguine:{shortName:"sanH",...Rs.antimony},tenderskin:{shortName:"tend",...Rs.argentum},tension:{shortName:"tens",...Rs.cinnabar},timeflux:{shortName:"tmfx",fg:"",bg:""},timeloop:{shortName:"tmlp",...Rs.cuprum},tonguetied:{shortName:"tngt",...Rs.restoration},torntendons:{shortName:"tt",...Rs.health},transfixation:{shortName:"trfx",...Rs.writhe},unweavingbody:{shortName:"unwB",...Rs.ferrum},unweavingspirit:{shortName:"unwS",...Rs.cinnabar},unweavingmind:{shortName:"unwM",...Rs.plumbum},unblind:{shortName:"unB",fg:"",bg:""},undeaf:{shortName:"unD",fg:"",bg:""},unnamable:{shortName:"unnam",fg:"",bg:""},vertigo:{shortName:"vert",...Rs.argentum},vitrified:{shortName:"vitri",fg:"",bg:""},voidfisted:{shortName:"void",fg:"",bg:""},voyria:{shortName:"voy",fg:"",bg:""},weariness:{shortName:"wea",...Rs.aurum},webbed:{shortName:"web",...Rs.writhe},whisperingmadness:{shortName:"wmad",...Rs.argentum},wristfractures:{shortName:"wf",...Rs.health}},Bs=Ps.parse({affs:Zs,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:""}}}}),Ls=Bs.affs,Fs=(Bs.chrome,new Set(["undeaf","unblind","cleanseaura","unnamable"])),qs=new Map([["sensitivity","undeaf"]]),Gs=new Set(["dissonance"]),Js=new Map([["mangledleftleg","damagedleftleg"],["mangledleftarm","damagedleftarm"],["mangledrightleg","damagedrightleg"],["mangledrightarm","damagedrightarm"],["mangledhead","damagedhead"],["serioustrauma","mildtrauma"],["damagedleftleg","brokenleftleg"],["damagedleftarm","brokenleftarm"],["damagedrightleg","brokenrightleg"],["damagedrightarm","brokenrightarm"]]),Us=(e,t,n={})=>({id:e,kind:t,...n,...Js.has(e)?{curesTo:Js.get(e)}:{},...Fs.has(e)?{pseudo:!0}:{},...Gs.has(e)?{curedLast:!0}:{},...qs.has(e)?{gatedBy:qs.get(e)}:{},...Ls[e]?{display:Ls[e]}:{}}),Hs=js.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=>Us(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])=>Us(e,"timed",t)),...Object.entries({pressure:{max:5},crescendo:{max:5},unweavingbody:{max:5},unweavingspirit:{max:5},unweavingmind:{max:5},burning:{max:5},horror:{max:5,cureSteps:[{atLeast:3,removes:2}]},pyre:{max:3},temperedcholeric:{max:8},temperedmelancholic:{max:8},temperedphlegmatic:{max:8},temperedsanguine:{max:8},torntendons:{max:6},crackedribs:{max:6},skullfractures:{max:6},wristfractures:{max:6}}).map(([e,t])=>Us(e,"countable",t))]),Vs=lr().regex(/^[a-z]+$/,"skill keys are single lowercase words"),Ws=qr({id:ws,skills:Br(Vs).default([])}),Ys=Br(Ws).min(1).refine(e=>new Set(e.map(e=>e.id)).size===e.length,{message:"profession ids must be unique"}),Ks=Ys.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:[]}]),Qs=Jr([bs,Br(bs).min(2)]),Xs=qr({id:vs,command:lr().min(1),class:Kr(["linear","tree","special"]),order:Br(bs).default([]),ordered:Er().default(!1),layered:Er().default(!1),bals_used:Br(ys).default([]),bals_req:Br(ys).default([]),blocks:Br(Qs).default([]),professions:Br(ws).optional(),bestowable:Er().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"}),ei=Br(Xs).min(1).refine(e=>new Set(e.map(e=>e.id)).size===e.length,{message:"cure ids must be unique"}),ti=["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"],ni=["death","anorexia","sleeping"],ri=["death","asthma","sleeping"],si=["death","slickness","sleeping"],ii=["death","sleeping","anorexia"],ai=[["brokenleftarm","brokenrightarm"],["brokenleftarm","damagedrightarm"],["brokenleftarm","mangledrightarm"],["damagedleftarm","brokenrightarm"],["damagedleftarm","damagedrightarm"],["damagedleftarm","mangledrightarm"],["mangledleftarm","brokenrightarm"],["mangledleftarm","damagedrightarm"],["mangledleftarm","mangledrightarm"]],oi=["entangled","transfixation","impaled","webbed","bound"],li=["darkshade","haemophilia","lethargy","addiction","scytherus","nausea","flushings","unweavingbody"],di=["paralysis","slickness","pyramides"],ci=["clumsiness","healthleech","sensitivity","weariness","asthma","rebbies","parasite"],fi=["undeaf","deafness"],ui=["horror","fratricide","masochism","loneliness","vertigo","recklessness","agoraphobia","guilt","whisperingmadness","spiritburn","tenderskin","hypochondria"],pi=["pacified","peace","lovers","justice","generosity","indifference","retribution","pyre","timeloop","diminished","stridulating"],hi=["temperedcholeric","temperedmelancholic","temperedphlegmatic","temperedsanguine"],mi=["unblind","blindness"],gi=["claustrophobia","paranoia","confusion","hypersomnia","hallucinations","dementia","crescendo"],bi=["stupidity","epilepsy","dizziness","shyness","impatience","dissonance","depression","sandfever","mycalium","shadowmadness","unweavingmind","fulminated"],yi=["pressure"],vi=["disloyalty","hellsight","manaleech","slickness"],ki=["aeon","dazed","deadening","tension","unweavingspirit","earworm"],wi=(e,t,n={})=>({id:e,command:`eat ${e}`,class:"linear",order:t,bals_used:["herb"],bals_req:["herb"],blocks:ni,prio:0,...n}),Ii=(e,t)=>({id:e,command:`smoke ${e}`,class:"linear",...t?{order:t}:{},bals_used:["smoke"],bals_req:["smoke"],blocks:ri,prio:0}),zi=(e,t,n={})=>({id:e,command:`apply ${e}`,class:"linear",order:t,bals_used:["salve"],bals_req:["salve","restoration"],blocks:si,prio:0,...n}),_i=(e,t)=>({...zi(e,t),bals_used:["restoration"],delayMs:4e3}),Oi=(e,t)=>({id:e,command:`apply ${e}`,class:"linear",order:t,bals_used:["sip"],bals_req:["sip"],prio:0}),$i=(e,t)=>({id:e,class:"tree",order:ti,prio:0,...t}),Si=ei.parse([wi("ferrum",li),wi("magnesium",di),wi("aurum",ci),wi("calamine",fi,{delayMs:2500}),wi("argentum",ui),wi("cuprum",pi),wi("antimony",hi),wi("arsenic",mi),wi("stannum",gi),wi("plumbum",bi,{class:"special"}),wi("calcite",yi),wi("ginseng",li),wi("bloodroot",di),wi("kelp",ci),wi("hawthorn",fi,{delayMs:2500}),wi("lobelia",ui),wi("bellwort",pi),wi("ginger",hi),wi("bayberry",mi),wi("ash",gi),wi("goldenseal",bi,{class:"special"}),wi("pear",yi),{...Ii("smoke",["aeon","disloyalty","hellsight","manaleech","slickness","deadening","tension","unweavingspirit","earworm"]),command:"smoke cinnabar"},Ii("cinnabar",ki),Ii("malachite"),Ii("realgar",vi),Ii("elm",ki),Ii("skullcap"),Ii("valerian",vi),zi("caloric",["frozen","shivering","frostbite"],{layered:!0}),zi("epidermal to body",["anorexia"]),zi("epidermal to head",["stuttering","blindness","deafness"]),zi("epidermal to ears",["deafness"]),zi("mending to head",["crushedthroat","dazzled"]),zi("mending to arms",["brokenleftarm","brokenrightarm"],{ordered:!0}),zi("mending to legs",["brokenleftleg","brokenrightleg"],{ordered:!0}),zi("mending to body",["burning"]),_i("restoration to head",["mangledhead","damagedhead","calcifiedskull","concussion","tonguetied"]),_i("restoration to torso",["hypothermia","heartseed","serioustrauma","mildtrauma","calcifiedtorso","internalbleeding"]),_i("restoration to arms",["mangledleftarm","mangledrightarm","damagedleftarm","damagedrightarm"]),_i("restoration to legs",["mangledleftleg","mangledrightleg","damagedleftleg","damagedrightleg"]),{id:"health",command:"sip health",class:"linear",bals_used:["sip"],bals_req:["sip"],blocks:ii,prio:0},{id:"mana",command:"sip mana",class:"linear",bals_used:["sip"],bals_req:["sip"],blocks:ii,prio:0},Oi("health to head",["skullfractures"]),Oi("health to torso",["crackedribs","grievouswounds"]),Oi("health to arms",["wristfractures"]),Oi("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},$i("bloodboil",{command:"cast bloodboil",bals_used:["equilibrium","bloodboil"],bals_req:["equilibrium","balance","bloodboil"],blocks:["death","haemophilia","sleeping",...ai,...oi],professions:["magi"]}),{id:"dragonflex",command:"dragonflex",class:"linear",order:["webbed","entangled"],bals_used:["balance"],bals_req:["balance"],professions:["dragon"],prio:0},$i("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},$i("salt",{command:"educe salt",bals_used:["salt","equilibrium"],bals_req:["equilibrium","salt"],blocks:["death","stupidity","sleeping"],professions:["alchemist"]}),$i("siphon",{command:"siphon",bals_used:["angel"],bals_req:["angel"],blocks:["death","sleeping"],professions:["apostate","priest"]}),$i("shrugging",{command:"shrugging",bals_used:["shrugging"],bals_req:["equilibrium","balance","shrugging"],blocks:["death","weariness","sleeping"],professions:["serpent"]}),$i("slough",{command:"slough impurities",bals_used:["slough","balance"],bals_req:["equilibrium","balance","slough"],blocks:["death","weariness","sleeping"],professions:["firelord"]}),$i("fool",{command:"fling fool at me",bals_used:["fool","balance"],bals_req:["equilibrium","balance","fool"],blocks:["death","prone","paralysis","sleeping",...ai,...oi],professions:["occultist"]}),$i("accelerate",{command:"chrono accelerate",bals_used:["accelerate","balance"],bals_req:["equilibrium","balance","accelerate"],blocks:["death","sleeping","recklessness"],professions:["depthswalker"]}),$i("alleviate",{command:"alleviate",bals_used:["alleviate","balance"],bals_req:["equilibrium","balance","alleviate"],blocks:["death","paralysis","sleeping"],professions:["blademaster"]}),$i("dagaz",{command:"sketch dagaz on ground",bals_used:["dagaz"],blocks:["death"],professions:["runewarden"],bestowable:!0}),$i("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:ii,prio:0},{id:"stand",command:"stand",class:"linear",order:["prone"],bals_req:["balance","equilibrium"],blocks:["death","sleeping","paralysis","brokenrightleg","brokenleftleg","damagedleftleg","damagedrightleg","mangledrightleg","mangledleftleg",...oi],prio:0},$i("tree",{command:"touch tree",bals_used:["tree"],bals_req:["tree"],blocks:["death","sleeping","paralysis",...ai,...oi]}),{id:"potash",command:"eat potash",class:"linear",bals_used:["moss"],bals_req:["moss"],blocks:ii,prio:0},{id:"moss",command:"eat moss",class:"linear",bals_used:["moss"],bals_req:["moss"],blocks:ii,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}]),Mi=lr().regex(/^[a-z]+$/,"defence ids are single lowercase words"),ji=qr({stripDelayMs:xr().int().positive(),applyDelayMs:xr().int().positive(),conservativeLeadMs:xr().int().nonnegative(),blockedBy:Br(bs).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"}),xi=Br(qr({id:Mi,default:Er().default(!1),restore:ji.optional()})).min(1).refine(e=>new Set(e.map(e=>e.id)).size===e.length,{message:"defence ids must be unique"}),Ni=xi.parse([{id:"speed",default:!0,restore:{stripDelayMs:2200,applyDelayMs:3e3,conservativeLeadMs:200,blockedBy:ii}},{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"}]),Ai=qr({affId:bs,observedDurationMs:xr().int().positive(),predictiveDurationMs:xr().int().positive()}),Ti=qr({id:ys,observedDurationMs:xr().int().positive(),predictiveDurationMs:xr().int().positive(),bufferPolicy:Kr(["buffered","exact"]),extendedBy:Br(Ai).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"}),Ei=Br(Ti).min(1).refine(e=>new Set(e.map(e=>e.id)).size===e.length,{message:"balance ids must be unique"}),Ci=e=>({predictiveDurationMs:e,observedDurationMs:Math.round(.75*e)}),Pi=(e,t,n=[])=>({id:e,...Ci(t),bufferPolicy:"buffered",extendedBy:n.map(([e,t])=>({affId:e,...Ci(t)}))}),Di=Ei.parse([Pi("balance",2e3),Pi("equilibrium",2e3),Pi("sip",4500),Pi("herb",1500),Pi("smoke",1500),Pi("salve",1e3),Pi("restoration",4e3),Pi("focus",2500,[["whisperingmadness",4e3],["weakenedmind",5e3]]),Pi("tree",15e3),Pi("moss",6e3),Pi("immunity",1e4),Pi("accelerate",1e4),Pi("alleviate",1e4),Pi("angel",1e4),Pi("bloodboil",1e4),Pi("dragonheal",2e4),Pi("fitness",1e4),Pi("fool",3e4),Pi("rage",1e4),Pi("salt",1e4),Pi("shrugging",12e3),Pi("slough",1e4),Pi("dagaz",2e4),Pi("voice",2500),Pi("generic",12e3)]),Ri=Br(qr({id:bs,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"}),Zi=(e,t)=>t.map(t=>({id:t,level:1,prio:e})),Bi=(e,t,n)=>Array.from({length:t},(t,r)=>({id:e,level:r+1,prio:n})),Li=Ri.parse([...Zi(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"]),...Zi(2,["aeon","concussion","crushedthroat","paralysis","peace"]),...Zi(3,["sleeping","grievouswounds","latched","dazzled","weariness","prone","timeloop","fulminated"]),...Bi("unweavingbody",5,3),...Bi("unweavingmind",5,3),...Bi("unweavingspirit",5,3),...Zi(4,["spiritburn","heartseed","guilt","tenderskin","pyramides","parasite","hypochondria","pacified","depression","confusion","retribution","shadowmadness","whisperingmadness","hellsight"]),...Zi(5,["anorexia","mycalium","flushings","rebbies","sandfever","asthma","healthleech"]),...Zi(6,["impatience","itching","scytherus","clumsiness","kkractlebrand","damagedleftleg","darkshade","slickness","recklessness","dementia","fratricide","icebound"]),...Zi(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},...Zi(8,["damagedrightleg","hypersomnia","earworm","diminished"]),...Bi("skullfractures",6,8),...Bi("crescendo",5,8),...Zi(9,["brokenleftleg","brokenrightleg","hallucinations"]),...Bi("torntendons",6,9),...Zi(10,["calcifiedskull","calcifiedtorso","mangledleftleg","mangledrightleg","disrupted","mangledhead","voyria"]),...Bi("crackedribs",6,10),...Zi(11,["hypothermia","impaled","brokenleftarm","brokenrightarm","indifference","addiction","nausea","deadening","frozen","shivering","mildtrauma","internalbleeding"]),...Zi(12,["stupidity","damagedleftarm","disloyalty"]),...Bi("wristfractures",6,12),...Zi(13,["tension","damagedhead","dazed"]),...Bi("burning",5,13),...Zi(14,["lovers","damagedrightarm","temperedcholeric","temperedmelancholic","temperedphlegmatic","temperedsanguine"]),...Bi("pressure",5,14),...Zi(15,["mangledleftarm","mangledrightarm"]),...Zi(16,["agoraphobia","claustrophobia","generosity","justice","loneliness","vertigo"]),...Zi(17,["paranoia"]),...Zi(18,["serioustrauma","epilepsy"]),...Zi(20,["laceratedthroat","slashedthroat","stuttering"]),...Zi(21,["selarnia","fear","masochism"]),...Zi(23,["dizziness","shyness"]),...Bi("horror",5,26),...Zi(30,["amnesia","blackout"]),...Zi(0,["insomnia","deafness","blindness"]),...Zi(100,["harmonic","bop","spiritwrack","bedevil","loki","moon","evileye","dragoncurse","swiftcurse"])]),Fi=Br(bs).min(1).refine(e=>new Set(e).size===e.length,{message:"pool affliction ids must be unique"}),qi=Br(qr({profession:ws,pools:Wr(lr().min(1),Fi)})).min(1).refine(e=>new Set(e.map(e=>e.profession)).size===e.length,{message:"professions must be unique"}),Gi=qi.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"]}}]),Ji=Br(qr({id:ks,aff:bs.nullable()})).min(1).refine(e=>new Set(e.map(e=>e.id)).size===e.length,{message:"venom ids must be unique"}),Ui=Ji.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"}]),Hi=new Map(Hs.map(e=>[e.id,e])),Vi=new Map(Si.map(e=>[e.id,e])),Wi=new Map(Di.map(e=>[e.id,e])),Yi=new Map(Ni.map(e=>[e.id,e])),Ki=Object.freeze(Object.fromEntries(Ni.filter(e=>e.default).map(({id:e})=>[e,!0]))),Qi=(()=>{const e=new Map;for(const t of Li)e.has(t.id)||e.set(t.id,new Map),e.get(t.id).set(t.level,t.prio);return e})(),Xi=(...e)=>new Set(Si.filter(t=>t.bals_used.some(t=>e.includes(t))).map(e=>e.id)),ea=Object.freeze({layers:Object.freeze(Si.filter(e=>e.layered).map(e=>Object.freeze([...e.order]))),curedLast:Object.freeze(Hs.filter(e=>e.curedLast).map(e=>Object.freeze({affId:e.id,pool:Object.freeze([...new Set(Si.filter(t=>"tree"!==t.class&&t.order.includes(e.id)).flatMap(e=>e.order).filter(t=>t!==e.id))])})))}),ta=e=>new Set(Si.filter(t=>e.has(t.id)).flatMap(e=>e.order)),na=ta(Xi("herb")),ra=ta(Xi("smoke")),sa=new Map(Ui.map(e=>[e.id,e.aff])),ia=new Map(Gi.map(e=>[e.profession,e.pools])),aa=(()=>{const e=new Map;for(const t of Ks)for(const n of t.skills)e.set(n,e.has(n)?null:t.id);return new Map([...e].filter(([,e])=>null!==e))})(),oa=Object.freeze({epsilon:1e-4,forkCap:256}),la=(e,t)=>{if(!e)throw new Error(`insight engine: ${t}`)},da=e=>Object.keys(e).sort().map(t=>`${t}=${!0===e[t]?"t":e[t]}`).join(","),ca=(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},fa=e=>Object.freeze({p:e.p,affs:Object.freeze({...e.affs})}),ua=e=>({p:e.p,affs:{...e.affs}}),pa=e=>{const t=e.reduce((e,t)=>e+t.p,0);if(la(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},ha=Object.freeze([]),ma=(e,t,{contradiction:n=!1}={})=>{la(Array.isArray(e)&&e.length>0,"finalizeForks needs at least one fork");const r=t?.growth??oa;let s=(e=>{const t=new Map;for(const n of e){const e=da(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=pa(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:pa(n),capDiagnostic:{type:"forkCapExceeded",beforeCount:e.length,afterCount:n.length,forkCap:t}}})(s,r.forkCap??oa.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=ca(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??oa.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(fa)),contradiction:n,diagnostics:a?Object.freeze([Object.freeze(a)]):ha}):{forks:s.map(ua),contradiction:n,diagnostics:a?[a]:ha}},ga=e=>!1===e.contradiction&&0===e.diagnostics.length,ba=(e,t)=>!0===t?.guards?Object.freeze({forks:Object.freeze(e.forks.map(fa)),contradiction:!0,diagnostics:e.diagnostics}):{forks:e.forks,contradiction:!0,diagnostics:e.diagnostics},ya=({guards:e=!1}={})=>{const t={forks:[{p:1,affs:{}}],contradiction:!1,diagnostics:ha};return e?Object.freeze({...t,forks:Object.freeze(t.forks.map(fa))}):t},va=e=>"countable"!==e.kind||1,ka=(e,t)=>{const n=e.affById.get(t);return la(n,`unknown affliction '${t}'`),n},wa=(e,t)=>{if("afflicted"!==e.type)return e;const n=ka(t,e.affId).gatedBy;return void 0===n?e:{type:"afflictedOneOf",pool:[n,e.affId],mode:"ordered",...void 0===e.durationMs?{}:{durationMs:e.durationMs}}},Ia=Object.freeze(["uniform","firstMissing","ordered"]),za=new Set,_a=(e,t,n,r=za)=>{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))},Oa=(e,t,n)=>{const r=ka(n,t),s={...e};if("countable"===r.kind){const e=s[t]-((e,t)=>{let n=1;for(const r of e.cureSteps){if(r.atLeast>t)break;n=r.removes}return n})(r,s[t]);e<=0?delete s[t]:s[t]=e}else delete s[t];if(r.curesTo){const e=ka(n,r.curesTo);s[e.id]=va(e)}return s},$a=Object.freeze(["=","!=","<","<=",">",">="]),Sa=(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 la(!1,`unknown comparison operator '${t}'`),!1}},Ma=Object.freeze({afflicted:(e,t,n)=>{const r=ka(n,t.affId),s="countable"!==r.kind||r.max;return ga(e)&&e.forks.every(e=>e.affs[r.id]===s)?e:ma(e.forks.map(e=>{const t={...e.affs};if("countable"===r.kind){const e=t[r.id]??0;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;la(Array.isArray(r)&&r.length>0,"afflictedOneOf needs a non-empty pool"),la(Ia.includes(s),`unknown afflictedOneOf mode '${s}'`);const i=new Map(r.map(e=>[e,ka(n,e)]));if(ga(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]=va(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]:va(i.get(t))}});continue}const t=o.p/e.length;for(const n of e)a.push({p:t,affs:{...o.affs,[n]:va(i.get(n))}})}return ma(a,n)},advanced:(e,t,n)=>{la(Array.isArray(t.rungs)&&t.rungs.length>0,"advanced needs rungs");const r=new Set,s=new Map;for(const o of t.rungs){la(o&&"string"==typeof o.affId,"advanced rungs need an affId"),la(!r.has(o.affId),`advanced has duplicate rung '${o.affId}'`),r.add(o.affId),s.set(o.affId,ka(n,o.affId));for(const e of[...o.gains??[],...o.consumes??[]])s.set(e,ka(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 l={...e.affs};for(const{affId:t}of r)delete l[t];if(!o){n>=0&&delete l[t.rungs[n].affId];const e=t.rungs[n+1];l[e.affId]=va(s.get(e.affId));for(const t of e.gains??[])l[t]=va(s.get(t));for(const t of e.consumes??[])delete l[t]}return i=!0,{p:e.p,affs:l}});return!i&&ga(e)?e:ma(a,n)},cured:(e,t,n)=>{const r=((e,t)=>{const n=e.cureById.get(t);return la(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=_a(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:Oa(o.affs,r,n)})}return a?ma(i,n):e},confirmed:(e,t,n)=>{const r=ka(n,t.affId),{present:s}=t,i=e.forks.filter(e=>Object.hasOwn(e.affs,t.affId)===s);return i.length===e.forks.length&&ga(e)?e:i.length>0?ma(i.map(e=>({p:e.p,affs:e.affs})),n):ma(e.forks.map(e=>{const t={...e.affs};return s?t[r.id]=va(r):delete t[r.id],{p:e.p,affs:t}}),n,{contradiction:!0})},confirmedBlocked:(e,t,n)=>{const r=ka(n,t.blockerId),{pool:s}=t;la(Array.isArray(s)&&s.length>0,"confirmedBlocked needs a non-empty pool");for(const a of s)ka(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&&ga(e)?e:i.length>0?ma(i.map(e=>({p:e.p,affs:e.affs})),n):ma(e.forks.map(e=>({p:e.p,affs:{...e.affs,[r.id]:e.affs[r.id]??va(r)}})),n,{contradiction:!0})},confirmedCount:(e,t,n)=>{const{pool:r,op:s,n:i}=t;la(Array.isArray(r)&&r.length>0,"confirmedCount needs a non-empty pool"),la(Number.isInteger(i)&&i>=0,"confirmedCount needs an integer n >= 0");for(const d of r)ka(n,d);const a=e.forks.filter(e=>Sa((e=>r.reduce((t,n)=>t+(Object.hasOwn(e.affs,n)?1:0),0))(e),s,i));if(a.length===e.forks.length&&ga(e))return e;if(a.length>0)return ma(a.map(e=>({p:e.p,affs:e.affs})),n);let o=-1;for(let d=0;d<=r.length;d+=1)if(Sa(d,s,i)){if(-1!==o)return ba(e,n);o=d}if(0!==o&&o!==r.length)return ba(e,n);const l=0===o;return ma(e.forks.map(e=>{const t={...e.affs};for(const s of r)l?delete t[s]:Object.hasOwn(t,s)||(t[s]=va(ka(n,s)));return{p:e.p,affs:t}}),n,{contradiction:!0})},confirmedCounts:(e,t,n)=>{const{counts:r}=t;la(Array.isArray(r)&&r.length>0,"confirmedCounts needs count entries");for(const i of r){la(i&&"object"==typeof i,"confirmedCounts needs count objects"),la(Array.isArray(i.pool)&&i.pool.length>0,"confirmedCounts needs non-empty pools"),la(Number.isInteger(i.n)&&i.n>=0,"confirmedCounts needs integer counts >= 0");for(const e of i.pool)ka(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&&ga(e)?e:s.length>0?ma(s.map(e=>({p:e.p,affs:e.affs})),n):ma([{p:1,affs:{}}],n,{contradiction:!0})},confirmedLevel:(e,t,n)=>{const{affId:r,op:s,n:i}=t,a=ka(n,r);la("countable"===a.kind,`confirmedLevel needs a countable aff, got '${r}'`),la(Number.isInteger(i)&&i>=0,"confirmedLevel needs an integer n >= 0");const o=e.forks.filter(e=>Sa((e=>Object.hasOwn(e.affs,r)?e.affs[r]:0)(e),s,i));if(o.length===e.forks.length&&ga(e))return e;if(o.length>0)return ma(o.map(e=>({p:e.p,affs:e.affs})),n);const l=((e,t)=>{switch(e){case"=":case"<=":case">=":return t;case"<":return t-1;case">":return t+1;default:return null}})(s,i);return null===l||l<0||l>a.max||!Sa(l,s,i)?ba(e,n):ma(e.forks.map(e=>{const t={...e.affs};return 0===l?delete t[r]:t[r]=l,{p:e.p,affs:t}}),n,{contradiction:!0})},converted:(e,t,n)=>{const r=ka(n,t.from),s=ka(n,t.to);return e.forks.some(e=>Object.hasOwn(e.affs,r.id))?ma(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=ka(n,t.affId);return ga(e)&&!e.forks.some(e=>Object.hasOwn(e.affs,r.id))?e:ma(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(la(Array.isArray(r),"predictedCure needs a forkBranches array"),0===r.length)return e;const s=new Map;for(const a of r)la(Number.isInteger(a?.forkIndex)&&a.forkIndex>=0&&a.forkIndex<e.forks.length,`predictedCure fork index '${a?.forkIndex}' is out of range`),la(!s.has(a.forkIndex),`predictedCure addresses fork ${a.forkIndex} twice`),la(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)la("number"==typeof n.weight&&Number.isFinite(n.weight)&&n.weight>0,`predictedCure option weight for '${n.affId}' must be a positive number`),la(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:Oa(e.affs,s.affId,n)})}),ma(i,n)}}),ja=(Object.freeze(Object.keys(Ma)),(e,t,n)=>{if(n<=0)return!0;if(n>t.length)return!1;let r=0;for(let s=0;s<t.length;s+=1){if(Object.hasOwn(e,t[s])&&(r+=1),r>=n)return!0;if(r+t.length-s-1<n)return!1}return!1}),xa=(e,t,n)=>{if(n>t.length)return!1;let r=0;for(let s=0;s<t.length;s+=1)if(Object.hasOwn(e,t[s])&&(r+=1),r>n||r+t.length-s-1<n)return!1;return r===n},Na=e=>{switch(e){case"=":return(e,t)=>e===t;case"!=":return(e,t)=>e!==t;case"<":return(e,t)=>e<t;case"<=":return(e,t)=>e<=t;case">":return(e,t)=>e>t;case">=":return(e,t)=>e>=t}},Aa=(e,t,n,r,s)=>{const i=t.cache;i[n]!==t.epoch&&(i[n]=t.epoch,i[n+1]=0,i[n+2]=0);let a=i[n+1];const o=s+1;if(a<o){let t=i[n+2];const l=r.length;for(;t<l&&a<o&&a+l-t>=s;)Object.hasOwn(e,r[t])&&(a+=1),t+=1;i[n+1]=a,i[n+2]=t}return a},Ta=Symbol("true"),Ea=Symbol("false"),Ca=()=>!0,Pa=()=>!1,Da=(e,t)=>{null===e.members&&(e.members=new Set(e.ids));for(let n=0;n<t.length;n+=1)if(!e.members.has(t[n]))return!1;return!0},Ra=(e,t,n)=>{const r=e.ids,s=n.slot,i=n.literal;if(e.cache<0){const e=(e=>{switch(e){case"=":return xa;case"!=":return(e,t,n)=>!xa(e,t,n);case"<":return(e,t,n)=>!ja(e,t,n);case"<=":return(e,t,n)=>!ja(e,t,n+1);case">":return(e,t,n)=>ja(e,t,n+1);case">=":return ja}})(t);return s<0?t=>e(t,r,i):(t,n)=>e(t,r,n.operands[s])}const a=Na(t),o=e.cache;return s<0?(e,t)=>a(Aa(e,t,o,r,i),i):(e,t)=>{const n=t.operands[s];return a(Aa(e,t,o,r,n),n)}},Za=(e,t,n,r)=>{if("all"===e.kind||"any"===e.kind){const s="any"===e.kind?Ta:Ea,i="any"===e.kind?Ea:Ta,a=t?[]:null;let o=0;for(const d of e.children){const e=Za(d,t,n,r);if(e===s)return s;e!==i&&(o+=1,t&&a.push(e))}if(0===o)return i;if(!t)return null;if(1===o)return a[0];const l=a.length;return"all"===e.kind?(e,t)=>{for(let n=0;n<l;n+=1)if(!a[n](e,t))return!1;return!0}:(e,t)=>{for(let n=0;n<l;n+=1)if(a[n](e,t))return!0;return!1}}if("not"===e.kind){const s=Za(e.child,t,n,r);return s===Ta?Ea:s===Ea?Ta:t?(e,t)=>!s(e,t):null}if("aff"===e.kind){const n=e.id;return t?e=>Object.hasOwn(e,n):null}if("count"===e.kind){const{ids:r,op:s,operand:i}=e;if(i.slot<0){const e=((e,t,n)=>{const r=Na(e);if("="===e||"!="===e)return n>t?r(0,n):null;const s=r(0,n);return s===r(t,n)?s:null})(s,r.length,i.literal);if(null!==e)return e?Ta:Ea}const a=((e,t)=>{for(const n of e)if(n.ids.length===t.length&&(n.ids===t||Da(n,t)))return n;return null})(n,r);return t?Ra(a,s,i):(null===a?n.push({ids:r,members:null,cache:-1,refs:1}):a.refs+=1,null)}const{slot:s,op:i,operand:a}=e,o=((e,t,n,r)=>{for(const s of e)if(s.slot===t&&s.op===n&&s.operand.slot===r.slot&&(r.slot>=0||s.operand.literal===r.literal))return s;return null})(r,s,i,a);return t?(l=o.index,(e,t)=>{const n=t.conditions[l];return null!==n.affId&&Object.hasOwn(e,n.affId)?n.ifPresent:n.ifAbsent}):(null===o&&r.push({slot:s,op:i,operand:a,index:r.length}),null);var l},Ba=(e,t,n)=>{const r=Sa(e.ifPresent,t,n),s=Sa(e.ifAbsent,t,n);return{affId:r===s?null:e.affId,ifPresent:r,ifAbsent:s}},La=(e,t)=>Object.hasOwn(e.affs,t),Fa=e=>{la(Array.isArray(e)&&e.length>0,"affliction projection needs a non-empty pool");const t=new Set;for(const n of e)la("string"==typeof n&&n.length>0,"affliction pool ids must be non-empty strings"),la(!t.has(n),`affliction pool contains duplicate '${n}'`),t.add(n)},qa=(e,t)=>t.reduce((t,n)=>t+(La(e,n)?1:0),0),Ga=(e,t)=>{let n=0;for(const r of e.forks)La(r,t)&&(n+=r.p);return n},Ja=(e,t)=>{let n=!1,r=!1;for(const s of e.forks)if(La(s,t)?n=!0:r=!0,n&&r)return null;return n},Ua=(e,t)=>{Fa(t);let n=0;for(const r of e.forks)t.some(e=>La(r,e))&&(n+=r.p);return n},Ha=(e,t)=>{Fa(t);let n=0;for(const r of e.forks)t.every(e=>La(r,e))&&(n+=r.p);return n},Va=(e,t)=>{Fa(t);let n=0;for(const r of e.forks)n+=r.p*qa(r,t);return n},Wa=(e,t)=>{let n=0,r=0;for(const s of e.forks)if(La(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},Ya=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"]),Qa=(e,t)=>{if(!e)throw new Error(`insight domain: ${t}`)},Xa=Object.freeze(["best","worst","distribution"]),eo=["focus","herb","smoke","salve","restoration","sip","tree","balance","equilibrium"],to=new WeakMap,no=(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)},ro=(e,t)=>t.some(t=>Array.isArray(t)?t.every(t=>Object.hasOwn(e,t)):Object.hasOwn(e,t)),so=(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)||ro(e,t.blocks))return[];for(const o of _a(e,t,r)){const n=no(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()]},io=e=>e.reduce((e,t)=>t.prio<e.prio||t.prio===e.prio&&t.affId<e.affId?t:e),ao=e=>e.reduce((e,t)=>t.prio>e.prio||t.prio===e.prio&&t.affId<e.affId?t:e),oo=(e,t,n,r)=>{Qa(Xa.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 so(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 l;l="best"===n?[{...io(o),weight:1}]:"worst"===n?[{...ao(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 l)for(const e of t.balsUsed)i.add(e);s.push({forkIndex:a,options:l.map(({affId:e,weight:t})=>({affId:e,weight:t}))})}),0===s.length?null:{event:{type:"predictedCure",forkBranches:s},consumed:i}},lo=(Object.freeze(["pendingStrip","blocked","applying"]),ia.get("occultist").unnamable),co=Object.freeze([...lo]),fo=co.length,uo=e=>(Qa(Number.isInteger(e)&&e>=0&&e<=fo,`unnamable curse count must be an integer in [0, ${fo}] (got ${e})`),[{type:"confirmedCount",pool:[...co],op:0===e?"=":"<=",n:fo-e},...Array.from({length:e},()=>({type:"afflictedOneOf",pool:[...co],mode:"firstMissing"}))]),po=new Map([["unnamable",()=>uo(0)]]),ho="whisperingmadness",mo="focus",go=({belief:e,balance:t,usedAtMs:n})=>{const r=(({belief:e,balance:t,affId:n})=>{if(null!==Ja(e,n))return null;const r=Ga(e,n);Qa(r>0&&r<1,"structurally uncertain affliction needs interior probability");const s=new Map;for(const l of t.extendedBy){if(l.affId===n)continue;const t=Ja(e,l.affId);if(null===t)return null;s.set(l.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:ho});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,l=i-500,d=i+500;if(o>l)return null;const c=n+l;return{affId:ho,...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:l,lateWindowEndMs:d}},bo=Object.freeze({stalenessHalfLifeMs:6e4,entropyScaleBits:Math.log2(oa.forkCap)}),yo=(e,t={})=>{const n=t.stalenessHalfLifeMs??bo.stalenessHalfLifeMs,r=t.entropyScaleBits??(void 0===(s=t.forkCap)?bo.entropyScaleBits:Math.max(1,Math.log2(s)));var s;const i=Math.min(1,Ya(e.belief)/r),a=Math.max(0,e.now-e.lastObservedAt);return 1-(1-i)*(1-a/(a+n))},vo=(e,t={})=>Object.freeze({affId:e,...t.gains?{gains:Object.freeze(t.gains)}:{},...t.consumes?{consumes:Object.freeze(t.consumes)}:{}}),ko=Object.freeze({head:Object.freeze([vo("damagedhead",{gains:["stupidity"]}),vo("mangledhead",{gains:["stuttering","clumsiness"]})]),torso:Object.freeze([vo("mildtrauma"),vo("serioustrauma")]),leftarm:Object.freeze([vo("damagedleftarm",{consumes:["brokenleftarm"]}),vo("mangledleftarm")]),rightarm:Object.freeze([vo("damagedrightarm",{consumes:["brokenrightarm"]}),vo("mangledrightarm")]),leftleg:Object.freeze([vo("damagedleftleg",{consumes:["brokenleftleg"]}),vo("mangledleftleg")]),rightleg:Object.freeze([vo("damagedrightleg",{consumes:["brokenrightleg"]}),vo("mangledrightleg")])}),wo=Object.freeze(Object.keys(ko)),Io=Object.freeze(new Map(Object.entries(ko).flatMap(([e,t])=>t.map(t=>[t.affId,e])))),zo=e=>{const t=ko[e];return Qa(t,`unknown limb '${e}'`),t},_o=(e,t)=>((e,t)=>{la(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)La(s,t[n].affId)&&(e=n);n[Ka[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,zo(t)),Oo=Object.freeze(["observed","simulated"]),$o=wo,So=Object.freeze(["hp","mana"]),Mo=Object.freeze({policy:"distribution",predictionEnabled:!1,focusEnabled:!0,limbResetMs:18e4}),jo=e=>{if(e&&"object"==typeof e&&!Object.isFrozen(e)){Object.freeze(e);for(const t of Object.keys(e))jo(e[t])}return e},xo=e=>{const t={};for(const[n,r]of[...e].sort(([e],[t])=>e<t?-1:e>t?1:0))t[n]=r;return t},No=(e,t,n={})=>{Qa("string"==typeof e&&e.length>0,"createOpponentModel needs an id"),Qa(t?.affById&&t?.cureById&&t?.cureMasks,"createOpponentModel needs engine tables (affById, cureById, cureMasks)"),Qa(t?.balanceById&&t?.priorityByAff,"createOpponentModel needs domain tables (balanceById, priorityByAff)"),Qa(t?.defenceById&&t?.defenceDefaults,"createOpponentModel needs defence tables (defenceById, defenceDefaults)");const r={...Mo,...n};Qa(Xa.includes(r.policy),`unknown predictive policy '${r.policy}'`);const s=!0===r.guards,i=(e=>{const t=to.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([...eo.filter(e=>n.has(e)),...[...n.keys()].filter(e=>!eo.includes(e)).sort()]),s=Object.freeze({curesByChannel:n,channelOrder:r});return to.set(e,s),s})(t);let a=ya({guards:s}),o=0,l=0,d="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($o.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},j=()=>{l!==o&&(l=o,S+=1)},x=()=>{if(_&&(_=!1,z.size>0)){const e=ie();for(const t of[...z])t(e)}},N=(({tables:e,getNow:t,isBlocked:n,onChange:r})=>{Qa(e?.defenceById&&e?.defenceDefaults,"defence state needs defence tables"),Qa("function"==typeof t,"defence state needs a clock read"),Qa("function"==typeof n,"defence state needs a blocker predicate"),Qa("function"==typeof r,"defence state needs a change callback");const s=new Map,i=new Map,a=t=>{Qa("string"==typeof t&&t.length>0,"defence operation needs a def id");const n=e.defenceById.get(t);return Qa(n,`unknown defence '${t}'`),n},o=(e,n,i=t())=>{const a={have:!0===n,atMs:i};var o,l;o=s.get(e),l=a,(o?.have!==l.have||o?.atMs!==l.atMs)&&(s.set(e,a),r())},l=(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())},d=e=>{i.delete(e)&&r()},c=e=>e.applyDelayMs-e.conservativeLeadMs,f=(e,r,s,i)=>{n(r.blockedBy)?l(e,{phase:"blocked",stripAt:s,restoreAt:null,stripConfirmed:i}):l(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,n){const r=a(e);Qa("boolean"==typeof n,"defence confirmation needs a boolean");const s=i.get(e);if("pendingStrip"===s?.phase){if(n&&t()<s.stripAt)return;if(!n)return o(e,!1),void f(e,r.restore,t(),!1)}n||"applying"!==s?.phase&&"blocked"!==s?.phase?(o(e,n),d(e)):o(e,!1)},raise(e){a(e),o(e,!0),d(e)},strip(e){const n=a(e),r=s.get(e),l=i.get(e);!1===r?.have&&!0===l?.stripConfirmed||(o(e,!1),n.restore?f(e,n.restore,t(),!0):d(e))},startStrip(e){const n=a(e);Qa(n.restore?.stripDelayMs,`defence '${e}' has no delayed-strip policy`);const r=t()+n.restore.stripDelayMs;o(e,!1),l(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)||l(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),d(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=>ro(e.affs,t)))(a,e),onChange:M}),A=e=>{const n=t.balanceById.get(e);return Qa(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)=>{Fa(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(La(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(mo);Qa(R&&Z,"focus timing needs canonical focus cure and balance rows");const B=()=>{null!==m&&(m=null,M())},L=()=>{if("observed"!==d||!0!==r.focusEnabled||!1!==Ja(a,"aeon")||!((e,t)=>e.forks.every(e=>!ro(e.affs,t.blocks)))(a,R))return!1;const e=e=>"focus"===e||(p.get(e)??1/0)<=o;return a.forks.every(n=>so(n.affs,R,{tables:t,opponentClass:u,isBalanceReady:e}).length>0)},F=()=>{!m||null===Ja(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(mo,e.usedAtMs+t);const n=[Z,...Z.extendedBy].find(e=>e.predictiveDurationMs===t);n&&E(mo,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)=>{Qa(e?.affId===ho,"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)=>{la(e&&Array.isArray(e.forks),"apply needs a Belief"),la(t&&"string"==typeof t.type,"apply needs an event with a type"),la(n?.affById&&n?.cureById&&n?.cureMasks,"apply needs tables"),la(Ma[t.type],`unknown event type '${t.type}'`);const r=wa(t,n),s=(0,Ma[r.type])(e,r,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:r.type})))}):{forks:s.forks,contradiction:s.contradiction,diagnostics:s.diagnostics.map(e=>e.eventType?e:{...e,eventType:r.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=Io.get(t);if(r){const s=Ga(e,t);s>0&&Ga(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=Io.get(t);if(r){const s=Ga(e,t);s>0&&Ga(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===Ga(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=po.get(r),i=void 0!==n&&"observed"===d&&b.has(r)&&1===Ga(a,r);if(W(r),Ga(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 l of i.channelOrder){const d=p.get(l);if(void 0===d||d>o)continue;const f=oo(a,l,c,{tables:t,context:i,opponentClass:u,isBalanceReady:r});if(!f)continue;const h=a,m=H(f.event);n.push(...m.diagnostics),"focus"===l&&B();for(const e of f.consumed)D(e,h);e.push({atMs:o,channelId:l,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:Wa(a,s)}:{probability:e[s]};const r={};for(const t of $o)r[t]={percent:k.get(t).percent,stages:_o(a,t)};return{mode:d,policy:c,predictionEnabled:f,class:u,entropy:Ya(a),forkCount:a.forks.length,affs:n,expiries:xo(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:xo([...w.entries()].map(([e,t])=>[e,{...t}])),defs:xo(N.snapshotEntries()),skillState:s?JSON.parse(JSON.stringify(I)):I}},ie=()=>{null===O&&(O=s?jo(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:l,staleness:yo(le,{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?jo(a):a},ae=e=>{if("focus"===e&&m){const e=m;return{affId:e.affId,ifPresent:Math.max(0,e.usedAtMs+e.durationIfPresentMs-o),ifAbsent:Math.max(0,e.usedAtMs+e.durationIfAbsentMs-o)}}const t=Math.max(0,(p.get(e)??0)-o);return{affId:null,ifPresent:t,ifAbsent:t}},oe=e=>{const t=k.get(e);return Qa(t,`unknown limb '${e}'`),t},le={id:e,get revision(){return $},get timeEpoch(){return S},get now(){return o},get mode(){return d},get policy(){return c},get class(){return u},get lastObservedAt(){return l},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:t,ms:n})=>(A(e),Qa("number"==typeof n&&Number.isFinite(n)&&n>=0,"balance remaining probability needs a non-negative finite ms"),((e,t,n,r)=>{const s=Ba(t,n,r);if(s.ifPresent===s.ifAbsent)return s.ifPresent?1:0;const i=Ga(e,s.affId);return s.ifPresent?i:1-i})(a,ae(e),t,n)),queryProbability:(e,t)=>{const n=e.balanceIds.map(ae);return((e,t,n,r)=>{const s=t.balanceConditions,i=new Array(s.length);for(let f=0;f<s.length;f+=1){const{slot:e,op:t,operand:a}=s[f];i[f]=Ba(r[e],t,a.slot<0?a.literal:n[a.slot])}const a=t.cacheSlots,o={operands:n,conditions:i,cache:a>0?new Int32Array(3*a):null,epoch:0},l=t.match,d=e.forks;let c=0;for(let f=0;f<d.length;f+=1)o.epoch=f+1,l(d[f].affs,o)&&(c+=d[f].p);return c})(a,e,t,n)},getBalanceTimingInference:e=>(A(e),"focus"===e&&m?m:null),haveDef:N.have,getStat:e=>{Qa(So.includes(e),`unknown stat '${e}'`);const t=w.get(e);return t?{...t}:null},limbPercent:e=>oe(e).percent,limbStages:e=>(oe(e),_o(a,e)),getSkillState:()=>s?jo(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=>{Qa(e&&"string"==typeof e.type,"apply needs an event with a type"),Qa("elapsed"!==e.type&&"predictedCure"!==e.type,`'${e.type}' is not an observation — it is produced by the simulation itself`);const n=wa(e,t),r="cured"===n.type?t.cureById.get(n.cureId):null,i=void 0!==r?.delayMs,l=[];let d=!1;"cured"===n.type&&"focus"===n.cureId?G(l):m&&((e,t)=>"cured"===e.type?!0===t?.order.includes(ho):"afflictedOneOf"===e.type?e.pool.includes(ho):"converted"===e.type?"whisperingmadness"===e.from||"whisperingmadness"===e.to:["afflicted","removed","confirmed"].includes(e.type)&&"whisperingmadness"===e.affId)(n,r)&&B();const c=a,f=i?{contradiction:!1,diagnostics:[]}:H(n);switch(d||=f.contradiction,l.push(...f.diagnostics),n.type){case"afflicted":Y(n.affId,n.durationMs),u=n.affId,po.has(u)&&g.has(u)&&1===Ga(a,u)&&b.add(u);break;case"afflictedOneOf":for(const e of n.pool)K(e,n.durationMs);break;case"confirmed":n.present&&(e=>{const n=t.affById.get(e);"timed"!==n?.kind||g.has(e)||V(e,o+n.durationMs)})(n.affId);break;case"converted":W(n.from),Y(n.to);break;case"cured":if(r){for(const e of r.bals_used)P(e,c);i&&((e,t)=>{y.push({atMs:o+t,sequence:v,event:{type:"cured",cureId:e.cureId,excludedAffs:[...e.excludedAffs??[]]}}),v+=1,M()})(n,r.delayMs),"focus"===r.id&&(e=>{if(!L())return;const t=go({belief:e,balance:Z,usedAtMs:o});t&&(m=s?jo(t):t,M())})(c)}}var u;return Q(),F(),j(),x(),{contradiction:d,diagnostics:l}},elapsed:e=>{Qa("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=[],l=[],d=[],c=[];for(;;){X(n,c),ee(s,c),N.fireDue(i,a),te(l,c),ne(d,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 x(),{expired:n,resolvedCures:s,resolvedDefenceStrips:i,restoredDefs:a,predicted:l,timingConfirmations:d,diagnostics:c}},snapshot:ie,onChange:e=>(Qa("function"==typeof e,"onChange needs a function"),z.add(e),()=>z.delete(e)),setMode(e){Qa(Oo.includes(e),`unknown observation mode '${e}'`),d!==e&&(d=e,M()),"simulated"===e&&(b.clear(),B()),"observed"===e&&j(),x()},setPolicy(e){Qa(Xa.includes(e),`unknown predictive policy '${e}'`),c!==e&&(c=e,M()),x()},enablePrediction(){f||(f=!0,M()),x()},disablePrediction(){f&&(f=!1,M()),x()},setClass(e,{source:t="observed"}={}){if("directory"===t&&null!==u)return;const n="string"==typeof e&&e.trim()?e.trim().toLowerCase():null;u!==n&&(u=n,M()),x()},consumeBalance(e,t){A(e),P(e,a,t),x()},setStat(e,t){Qa(So.includes(e),`unknown stat '${e}'`),Qa("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()),x()},confirmDef(e,t){N.confirm(e,t),x()},raiseDef(e){N.raise(e),x()},stripDef(e){N.strip(e),x()},startDefStrip(e){N.startStrip(e),x()},hitLimb(e,t){Qa("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()),x(),{advanced:r,percent:s}},resetLimb(e){const t=oe(e);0===t.percent&&null===t.lastHitAt||(t.percent=0,t.lastHitAt=null,M()),x()},updateSkillState(e){Qa(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())}x()},reset(){a=ya({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(),x()}};return Object.freeze(le)},Ao=/^[A-Za-z]+$/,To=e=>{if("string"!=typeof e)return null;const t=e.trim();return t&&Ao.test(t)?t.toLowerCase():null},Eo=(e={})=>{const{tables:t,...n}=e;Qa(t,"createRosterModel needs config.tables");const r=!0===n.guards,s=new Map,i=new Map;let a=null,o=0;const l=new Set,d=new Set,c=()=>{if(o+=1,0===l.size)return;const e={ids:[...s.keys()],targetId:a};r&&(Object.freeze(e.ids),Object.freeze(e));for(const t of[...l])t(e)},f=e=>{let r=s.get(e);return r||(r=No(e,t,n),s.set(e,r),i.set(e,r.onChange(t=>{o+=1,((e,t)=>{for(const n of[...d])n(e,t)})(e,t)})),c()),r},u={track(e){const t=To(e);if(!t)return null;const n=f(t);return n.setMode("observed"),n},untrack(e){const t=To(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=To(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=To(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=To(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&&(Qa(Xa.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=>(Qa("function"==typeof e,"onChange needs a function"),l.add(e),()=>l.delete(e)),onOpponentChange:e=>(Qa("function"==typeof e,"onOpponentChange needs a function"),d.add(e),()=>d.delete(e))};return Object.freeze(u)},Co=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\.$/}),Po=Object.freeze([Object.freeze({id:"asthma-blocks-smoke",blockerId:"asthma",balanceId:"smoke",pool:Object.freeze([...ra].sort()),evidence:/^\w+ takes a long drag off \w+ pipe\.$/}),Object.freeze({id:"anorexia-blocks-herb",blockerId:"anorexia",balanceId:"herb",pool:Object.freeze([...na].sort()),evidence:/^\w+ eats a.+\.$/})]),Do=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\.$/})]),Ro=ia.get("depthswalker"),Zo=[{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=Ro[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]}}],Bo={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"}]};Bo.plauge=Bo.plague;var Lo={disorientation:[{type:"afflicted",affId:"dizziness"}],creeps:[{type:"afflicted",affId:"shyness"}],dissonance:[{type:"afflicted",affId:"dissonance"}]},Fo=e=>(e.args.info??"").toLowerCase(),qo=[{skill:"crystalism",id:"destabilise",handler:e=>(Bo[Fo(e)]??[]).map(e=>({...e}))},{skill:"crystalism",id:"vibeTick",handler:e=>(Lo[Fo(e)]??[]).map(e=>({...e}))}],Go=e=>(t,n,r)=>"thirdPerson"===t.matchType?e(t,n,r):[],Jo=(e,t)=>t.some(t=>e.have(t)),Uo={body:e=>e.have("anorexia")?[{type:"cured",cureId:"epidermal to body"}]:Jo(e,["hypothermia","heartseed","serioustrauma","mildtrauma","calcifiedtorso"])?[{type:"cured",cureId:"restoration to torso"}]:[{type:"cured",cureId:"mending to body"}],head:e=>Jo(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=>Jo(e,["damagedleftarm","damagedrightarm","mangledleftarm","mangledrightarm"])?[{type:"cured",cureId:"restoration to arms"}]:[{type:"cured",cureId:"mending to arms"}],legs:e=>Jo(e,["damagedleftleg","damagedrightleg","mangledleftleg","mangledrightleg"])?[{type:"cured",cureId:"restoration to legs"}]:[{type:"cured",cureId:"mending to legs"}],skin:e=>Jo(e,["frozen","shivering","frostbite"])?[{type:"cured",cureId:"caloric"}]:[{type:"defRaised",defId:"insulation"}]};Uo.torso=Uo.body;var Ho=[{skill:"curing",id:"apply",handler:Go((e,t,n)=>{const r=(e.args.info??"").toLowerCase();return Uo[r]?Uo[r](n):[]})},{skill:"curing",id:"health",handler:Go(e=>{const t=`health to ${(e.args.info??"").toLowerCase()}`;return Vi.has(t)?[{type:"cured",cureId:t}]:[]})},{skill:"curing",id:"smoke",handler:Go((e,t,n)=>Jo(n,["aeon","deadening","tension","unweavingspirit"])?[{type:"cured",cureId:"cinnabar"}]:Jo(n,["disloyalty","hellsight","manaleech","slickness"])?[{type:"cured",cureId:"realgar"}]:[])},{skill:"curing",id:"focus",handler:Go(()=>[{type:"cured",cureId:"focus"}])},{skill:"tattoos",id:"tree",handler:Go(()=>[{type:"cured",cureId:"tree"}])},{skill:"tattoos",id:"shield",handler:Go(()=>[{type:"defRaised",defId:"shield"}])},{skill:"defense",id:"prismatic",handler:Go(()=>[{type:"defRaised",defId:"prismatic"}])},{skill:"venom",id:"shrugging",handler:Go(()=>[{type:"cured",cureId:"shrugging"}])}],Vo=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\.$/}),Wo=(e,t,n)=>({id:`affConfirms.${e}`,pattern:n,lifetime:"session",actor:1,handler:()=>[{type:"confirmed",affId:t,present:!0}]}),Yo=(e,t,n)=>({id:`affConfirms.${e}`,pattern:n,lifetime:"session",actor:1,handler:()=>[{type:"afflicted",affId:t}]}),Ko=[Yo("confusion","confusion",Vo.confusion),Yo("dementia","dementia",Vo.dementia),Yo("paralysis1","paralysis",/^Horror overcomes the face of (\w+?) as \w+ body locks in paralysis\.$/),Yo("paralysis2","paralysis",/^Horror overcomes (\w+)'s face as \w+ body stiffens into paralysis\.$/),Yo("hypersomnia","hypersomnia",/^(\w+) suddenly appears tired all of a sudden\.$/),Yo("impatience","impatience",/^(\w+) shuffles \w+ feet in boredom\.$/),Wo("agoraphobia","agoraphobia",Vo.agoraphobia),Wo("claustrophobia","claustrophobia",Vo.claustrophobia),Wo("darkshade","darkshade",/^(\w+) lets out a piercing scream, as if wounded by the very sunlight\.$/),Wo("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"}]},Wo("masochism1","masochism",/^(\w+) smiles as \w+ rams \w+ fist into \w+ jaw\.$/),Wo("masochism2","masochism",/^(\w+) uses \w+ right foot to stomp on \w+ left as hard as possible\.$/),Wo("masochism3","masochism",/^With the heel of \w+ palm, (\w+) smacks \w+ upside the head\.$/),Wo("nausea","nausea",/^(\w+) doubles over, vomiting violently\.$/),Wo("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"}]},Wo("shivering","shivering",/^(\w+) shivers particularly intensely\.$/),Wo("burning","burning",/^The fires consuming (\w+) diminish somewhat\.$/)],Qo=ia.get("occultist"),Xo=/^Horror overcomes \w+'s face as \w+ body stiffens into paralysis\.$/,el=["brokenrightarm","brokenleftarm","brokenrightleg","brokenleftleg"],tl=["asthma","slickness"],nl=Qo.chimera.filter(e=>"hallucinations"!==e),rl=(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 nl)if(To(Vo[e].exec(r.text)?.[1])===t)return e}return"hallucinations"},sl=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},il=[{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(Xo)}]},{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:rl(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:[...tl],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:[...el],mode:"firstMissing"}]},{skill:"domination",id:"cronePrimebond",handler:()=>[{type:"afflictedOneOf",pool:[...el],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=sl(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=sl(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:[...Qo.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"}]}],al=[{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)=>ol(n)},{skill:"dragoncraft",id:"rendUntargeted",handler:(e,t,n)=>ol(n)},{skill:"dragoncraft",id:"tailsweepHit",handler:()=>[{type:"afflicted",affId:"prone"}]},{skill:"dragoncraft",id:"dragonheal",handler:e=>"thirdPerson"===e.matchType?[{type:"cured",cureId:"dragonheal"}]:[]}],ol=e=>{const t=e.skillState.envenom;if(!t)return[];const n=sa.get(t),r=[{type:"updateSkillState",patch:{envenom:null}}];return n&&r.unshift({type:"afflicted",affId:n}),r},ll=e=>`broken${(e??"").replace(/\s/g,"").toLowerCase()}`,dl=e=>e.haveDef("insulation")?[{type:"defStripped",defId:"insulation"}]:[{type:"afflictedOneOf",pool:["shivering","frozen"],mode:"ordered"}],cl=[{skill:"elementalism",id:"shalestormTick",handler:e=>[{type:"afflicted",affId:ll(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)=>dl(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)=>dl(n)},{skill:"elementalism",id:"resonanceAirMinor",handler:()=>[{type:"afflicted",affId:"asthma"}]},{skill:"elementalism",id:"resonanceAirModerate",handler:()=>[{type:"afflicted",affId:"sensitivity"}]},{skill:"elementalism",id:"resonanceAirMajor",handler:()=>[{type:"afflicted",affId:"healthleech"}]},{skill:"elementalism",id:"resonanceEarthMinor",handler:e=>[{type:"afflicted",affId:ll(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"}]}],fl=ia.get("occultist"),ul=Object.freeze({cloak:"cloak",speed:"speed",caloric:"insulation",frost:"temperence",levitation:"levitating",insomnia:"insomnia",kola:"kola"}),pl=/^pinchaura(?:\s|$)/i,hl=/^pinchaura\s+([A-Za-z]+)\s+([A-Za-z]+)$/i,ml=/^\[System\]: Running queued (.+?) command: (.+)/,gl=e=>[{type:"confirmedCounts",source:"readaura",counts:[{label:"physical",pool:[...fl.physicals],n:e.args.physical},{label:"mental",pool:[...fl.mentals],n:e.args.mental}]}],bl=e=>{const t=[{type:"confirmedCount",pool:[...fl.physicals,...fl.mentals],op:e.args.met?">=":"<",n:5}];return e.args.met&&t.push({type:"afflicted",affId:"enlightenment"}),t},yl=[{skill:"occultism",id:"pinchaura",handler:(e,t,n)=>{if("firstPerson"!==e.matchType)return[];const r=To(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=ml.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=>pl.test(e));if(1!==t.length)return null;const n=hl.exec(t[0]);if(!n)return null;const r=ul[n[2].toLowerCase()];return r?{targetId:To(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=>{const t=[{type:"statChanged",statId:"hp",delta:-.03},{type:"statChanged",statId:"mana",delta:-.03}],n=e.args.affs?.[0];return n&&t.push({type:"afflicted",affId:n}),t}},{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:()=>fl.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"}]}],vl=ia.get("psion"),kl=(e,t)=>e.args[t]??e.args.match?.groups?.[t],wl=[{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:[...vl.blast],op:"<",n:3}]},{skill:"weaving",id:"invert",handler:e=>{const t=kl(e,"old"),n=kl(e,"new");return t&&n?[{type:"converted",from:`unweaving${t}`,to:`unweaving${n}`}]:[]}}],Il=ia.get("depthswalker"),zl=["depression","retribution","shadowmadness","parasite"],_l=e=>()=>[{type:"afflictedOneOf",pool:[...e],mode:"ordered"}],Ol=e=>()=>e.map(e=>({type:"confirmed",affId:e,present:!0})),$l=e=>{const t=e.skillState.envenom;if(!t)return[];const n=sa.get(t),r=[{type:"updateSkillState",patch:{envenom:null}}];return n&&r.unshift({type:"afflicted",affId:n}),r},Sl=[{skill:"shadowmancy",id:"reap",handler:(e,t,n)=>t.checkBlock("you corrupt the weapon's timestream.")?[]:$l(n)},{skill:"shadowmancy",id:"cull",handler:(e,t,n)=>$l(n)},{skill:"shadowmancy",id:"degeneration",handler:_l(Il.degeneration)},{skill:"shadowmancy",id:"degenerationFull",handler:Ol(Il.degeneration)},{skill:"shadowmancy",id:"depression",handler:_l(Il.depression)},{skill:"shadowmancy",id:"depressionFull",handler:()=>[...Ol(Il.depression)(),{type:"afflicted",affId:"anorexia"},{type:"afflicted",affId:"masochism"}]},{skill:"shadowmancy",id:"retribution",handler:_l(Il.retribution)},{skill:"shadowmancy",id:"retributionFull",handler:(e,t,n)=>{const r=zl.reduce((e,t)=>e+n.probability(t),0);return[...Ol(Il.retribution)(),{type:"afflicted",affId:"anorexia"},{type:"afflicted",affId:"masochism"},{type:"statChanged",statId:"mana",delta:-.05*r}]}},{skill:"shadowmancy",id:"madness",handler:_l(Il.madness)},{skill:"shadowmancy",id:"madnessFull",handler:Ol(Il.madness)},{skill:"shadowmancy",id:"leach",handler:_l(Il.leach)},{skill:"shadowmancy",id:"leachFull",handler:Ol(Il.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}]}],Ml=ia.get("occultist"),jl=Ml.moon.filter(e=>"claustrophobia"!==e&&"agoraphobia"!==e),xl=[{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")?[]:Ml.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:[...jl],mode:"firstMissing"}]}}],Nl=/^(\w+) stumbles, falling to the ground\.$/,Al=[{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(Nl)?{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"}]}],Tl=e=>String(e).toLowerCase(),El=(e,t)=>`${Tl(e)}.${String(t).toLowerCase()}`,Cl=Object.freeze([...Zo,{skill:"artificing",id:"efreeti",handler:()=>[{type:"afflicted",affId:"burning"}]},{skill:"artificing",id:"stoneback",handler:()=>[{type:"defRaised",defId:"shield"}]},...qo,...Ho,...il,...al,...cl,...yl,...wl,...Sl,...xl,...Al]),Pl=(e,t,n)=>({id:`classCures.${e}`,pattern:n,lifetime:"session",actor:1,handler:()=>[{type:"cured",cureId:t}]}),Dl=[Pl("sunTarot","dagaz",/^The globe of light illuminates (\w+) with its brilliance\.$/),Pl("runewardenSun","dagaz",/^A rune like a rising sun upon the ground flares, bathing (\w+) with healing magic\.$/),Pl("genericMist","generic",/^(\w+) is surrounded in a cool, refreshing mist\.$/),Pl("genericGlow","generic",/^A demonic crimson glow emanates from (\w+)\.$/),Pl("genericLeech","generic",/^Something pulses from within the chest of (\w+), and \w+ seems more vital\.$/)],Rl=(e,t,n)=>({id:`cureConfirms.${e}`,pattern:n,lifetime:"session",actor:1,handler:()=>[{type:"confirmed",affId:t,present:!1}]}),Zl=[{id:"cureConfirms.stand",pattern:/^(\w+) stands up\.$/,lifetime:"session",actor:1,handler:()=>[{type:"cured",cureId:"stand"}]},Rl("lovers","lovers",/^(\w+) shakes \w+ head and a look of clarity returns to \w+ eyes\.$/),Rl("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"}]},Rl("sileris","slickness",/^(\w+) applies a (?:quicksilver droplet|sileris berry) to \w+\.$/),Rl("shadowmadness","shadowmadness",/^Lucidity returns to the eyes of (\w+)\.$/),Rl("unweavingspirit","unweavingspirit",/^(\w+) seems suddenly unburdened, clarity reasserting itself upon \w+ features\.$/),Rl("unweavingmind","unweavingmind",/^The light behind the eyes of (\w+) reignites\.$/),Rl("unweavingbody","unweavingbody",/^(\w+) suddenly seems much more vital\.$/),Rl("bloodfire","bloodfire",/^The unnatural flames that burn upon the skin of (\w+) wink out\.$/)],Bl=(e,t)=>({id:`curatives.${e}`,pattern:t,lifetime:"session",actor:1,handler:()=>[{type:"cured",cureId:e}]}),Ll=[Bl("antimony",/^(\w+) eats (?:a ginger root|an antimony flake)\.$/),Bl("argentum",/^(\w+) eats (?:a lobelia seed|an argentum flake)\.$/),Bl("arsenic",/^(\w+) eats (?:some bayberry bark|an arsenic pellet)\.$/),Bl("aurum",/^(\w+) eats (?:a piece of kelp|an aurum flake)\.$/),Bl("cuprum",/^(\w+) eats a (?:bellwort flower|cuprum flake)\.$/),Bl("ferrum",/^(\w+) eats a (?:ginseng root|ferrum flake)\.$/),Bl("magnesium",/^(\w+) eats a (?:bloodroot leaf|magnesium chip)\.$/),Bl("plumbum",/^(\w+) eats a (?:goldenseal root|plumbum flake)\.$/),Bl("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"}]}],Fl=(e,t,n)=>({id:`defences.${e}`,pattern:t,lifetime:"session",actor:1,handler:n}),ql=[Fl("shieldHit1",/^A dizzying beam of energy strikes you as your attack rebounds off of (\w+)'s shield\.$/,()=>[{type:"defRaised",defId:"shield"}]),Fl("shieldHit2",/^The magical shield surrounding (\w+) makes that impossible\.$/,()=>[{type:"defRaised",defId:"shield"}]),Fl("sileris",/^A supple purple shell of sileris berry juice has formed around (\w+)\.$/,()=>[{type:"defRaised",defId:"fangbarrier"}]),Fl("silerisLost",/^The protective coating covering the skin of (\w+) sloughs off\.$/,()=>[{type:"afflicted",affId:"slickness"},{type:"defStripped",defId:"fangbarrier"}]),Fl("insomnia",/^(\w+) clenches \w+ fists and grits \w+ teeth\.$/,()=>[{type:"defRaised",defId:"insomnia"},{type:"confirmed",affId:"hypersomnia",present:!1}]),Fl("prismaticHit",/^Your attack is repelled by the prismatic barrier surrounding (\w+)\.$/,()=>[{type:"defRaised",defId:"prismatic"}]),Fl("prismaticLost",/^(\w+)'s prismatic barrier dissolves into nothing\.$/,()=>[{type:"defStripped",defId:"prismatic"}]),Fl("speedStripped",/^(\w+) suddenly seems less dexterous, \w+ reactions becoming noticeably slower\.$/,()=>[{type:"defStripped",defId:"speed"}])],Gl=e=>(e??"").replace(/\s/g,"").toLowerCase(),Jl=(e,t)=>Number(`${e}.${t}`),Ul=[{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:Gl(e[4]),percent:Jl(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:Gl(e[4]),percent:Jl(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:Gl(e[4]),percent:Jl(e[1],e[2])}]},{id:"prep.limbReset",pattern:/^(\w+) ceases to favour \w+ (.+)\.$/,lifetime:"session",actor:1,handler:e=>[{type:"limbReset",limbId:Gl(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:Gl(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"}]}],Hl=[{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\.$/}],Vl={id:"occultism.readaura",lifetime:"prompt",armedBy:{trigger:"skills.readauraStart"},initState:({actorId:e})=>({actorId:e,pendingDefs:Hl.map(({defId:e})=>e)}),captures:[...Hl.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)=>gl({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}}]},Wl=["paralysis","asthma","healthleech","haemophilia","sensitivity","clumsiness","weariness"],Yl={indigo:()=>[{type:"afflicted",affId:"stupidity"}],orange:()=>[{type:"afflicted",affId:"paralysis"}],violet:e=>e.haveDef("speed")?[{type:"defStripped",defId:"speed"}]:[{type:"afflicted",affId:"aeon"}]},Kl=e=>e.haveDef("insulation")?[{type:"defStripped",defId:"insulation"}]:[{type:"afflictedOneOf",pool:["shivering","frozen"],mode:"ordered"}],Ql=[{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 Hi.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=>Yl[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"},...uo(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)=>bl({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)=>bl({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)=>bl({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=Hi.has(t)?t:`${t}madness`;return Hi.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 Hi.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 Wl.reduce((e,t)=>e+n.probability(t),0)>=4&&(r.push(...Kl(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)=>Kl(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 Yi.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])}]}],Xl=/^(\w+) pales as the blood drains from \w+ face\.$/,ed=(e,t,n)=>({id:e,lifetime:"prompt",armedBy:{skill:"occultism",id:t},initState:({observedIds:e})=>({exposed:[...e]}),captures:[{id:"pale",pattern:Xl,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}))}),td=ed("occultism.unnamableSpeak","unnamableSpeak","undeaf"),nd=ed("occultism.unnamableVision","unnamableVision","unblind"),rd=Object.freeze([...Ll,...Dl,...Zl,...Ko,...ql,...Ql,...Ul,{id:"queues.queueTracker",pattern:/^\[System\]: Running queued (.+?) command: (.+)/,lifetime:"session",remember:e=>({queue:{name:e[1],text:e[2]}})}]),sd=Object.freeze([td,nd,Vl]),id=(e,t)=>t instanceof RegExp?t.test(e):"string"==typeof t&&e.includes(t),ad=(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=To(r);if(e&&e!==t)return e}return null},od=e=>"string"==typeof e?e:"string"==typeof e?.name?e.name:null,ld=({adapter:e,publish:t,commandMemory:n=null,skills:r=null})=>{const s=[],i=new Map;let a=!1;const o=()=>To(od(e.gmcp.read("Char.Name"))),l=(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 id(t.text,e)}return!1},checkBlock:e=>i.some(t=>null!==t.text&&id(t.text,e)),queuedCommand:e=>{const t=e??a.lastQueue;return null===t?null:a.queues[t]??null}})})({...e.text.snapshot(),actorId:To(t),timestampMs:e.clock.now(),commands:n?n.snapshot():null}),d=e=>{const n=To(od(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:l(ad(e,o()))})},f=t=>{if(a)for(const n of t){if("string"!=typeof n||""===n)continue;const t=Tl(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?Tl(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",d)),s.push(e.events.on("Room.RemovePlayer",e=>{const n=To(od(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=>To(od(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:l})},dd=new Set(["afflicted","afflictedOneOf","cured","confirmed","confirmedBlocked","confirmedCount","confirmedCounts","confirmedLevel","converted","removed"]),cd=e=>Math.min(1,Math.max(0,e)),fd=({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))},l=t=>{const n=To(t)??e.targetId;return n?e.track(n):null},d=e=>(s(e.id),c(e)),c=e=>({id:e.id,class:e.class,have:t=>Ga(e.belief,t)>0,probability:t=>Ga(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,cd(t.value)),!0;case"statChanged":{const n=e.getStat(t.statId);return n&&e.setStat(t.statId,cd(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,{source:t.source}),!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?To(s.actorId)!==e.id:To(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 l=(e=>e?Object.entries(Co).filter(([,t])=>!e.nextLine(t)).map(([e])=>e):[])(s);o(e,{type:"cured",cureId:i.id,excludedAffs:l}),n("insight.cure.observed",{id:e.id,cureId:i.id});for(const t of(({cure:e,view:t,context:n})=>{if(Qa(e&&Array.isArray(e.order),"cureInferenceEvents needs a cure row"),Qa(t&&"function"==typeof t.have&&"function"==typeof t.isBalanceReady,"cureInferenceEvents needs an opponent view"),!n)return[];const r=[];for(const s of Po)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 Do)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:zo(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=l(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(!dd.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=l(e);return t?d(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(El(t.skill,t.id),t),a.add(Tl(t.skill))}},listDefinitions:()=>[...i.keys()],listSkills:()=>[...a],dispatchAction({action:e,context:t}){const n=i.get(El(e.skill,e.id));if(!n)return;const r=l(t?.actorId);if(!r)return;if("thirdPerson"===e.matchType){const t=aa.get(Tl(e.skill));t&&(s=e.args,a=r.id,[s.player,s.player?.id,s.user].some(e=>"string"==typeof e&&To(e)===a))&&f(r,{type:"classObserved",class:t})}var s,a;const o=n.handler(e,t,d(r))??[];for(const i of o)h.observe({...i,id:r.id},t)}};return Object.freeze(h)},ud=({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)}})},pd=(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})),hd=Object.freeze({"insight.ready":pd("eventstream","locked",{},"Bootstrap reached READY."),"insight.target.changed":pd("eventstream","locked",{id:"string | null"},"The tracked target changed (null = target cleared)."),"insight.opponent.tracked":pd("eventstream","locked",{id:"string"},"An opponent entered observed tracking (new, or re-acquired after leaving the room)."),"insight.opponent.unobserved":pd("eventstream","locked",{id:"string"},"A tracked opponent left observation; simulation continues on their belief."),"insight.opponent.removed":pd("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":pd("eventstream","locked",{id:"string",affId:"string",probability:"number"},"An affliction became present (marginal probability rose above zero) for an opponent."),"insight.aff.lost":pd("eventstream","locked",{id:"string",affId:"string"},"An affliction left an opponent's belief (marginal probability returned to zero)."),"insight.def.got":pd("eventstream","locked",{id:"string",defId:"string"},"A defence was observed present on an opponent."),"insight.def.lost":pd("eventstream","locked",{id:"string",defId:"string"},"A defence was observed absent on an opponent."),"insight.affs.updated":pd("eventstream","locked",{id:"string"},"Prompt-batched per-opponent change flush: this opponent's affliction state changed since the last flush."),"insight.opponent.updated":pd("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":pd("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":pd("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":pd("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":pd("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":pd("internal","experimental",{action:"object",context:"ObservationContext"},"Normalized nexSkills match action with its ingress-captured ObservationContext."),"insight.ingress.skillError":pd("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":pd("internal","experimental",{id:"string",match:"object",context:"ObservationContext"},"A trigger-pack pattern fired, with its ingress-captured ObservationContext."),"insight.ingress.target":pd("internal","experimental",{id:"string | null"},"Normalized IRE.Target.Set."),"insight.ingress.room.entered":pd("internal","experimental",{id:"string"},"GMCP Room.AddPlayer, self excluded."),"insight.ingress.room.left":pd("internal","experimental",{id:"string"},"GMCP Room.RemovePlayer."),"insight.ingress.room.list":pd("internal","experimental",{ids:"string[]"},"GMCP Room.Info occupancy resync, self excluded."),"insight.ingress.prompt":pd("internal","experimental",{},"Host PromptEvent boundary — drives the prompt-batched flush."),"insight.display.flush":pd("internal","experimental",{ids:"string[]"},"The prompt-batched flush completed for these dirty opponents — the display coordinator renders on this boundary."),"insight.display.changed":pd("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":pd("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":pd("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":pd("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).")}),md=(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]=md(s,t);return Object.freeze(n)},gd=({adapter:e,notice:t=()=>{}})=>{const n=ud(),r=(e,n,r)=>{t({text:`${e} failed — ${n} (${r?.message??String(r)})`,severity:"error"})},s=ud({onSubscriberError:({topic:e,cause:t})=>r("public event subscriber",e,t)}),i=e=>{const t=hd[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 l=md(a);if(s.raise(t,l),"eventstream"===o.audience)try{e.events.raise(t,l)}catch(d){r("EventStream forward",t,d)}},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)}})})},bd=Object.freeze({safetyFlushMs:200}),yd=e=>`insight4.elapsed.${e}`,vd="insight4.flush.safety",kd=({adapter:e,roster:t,publisher:n,notice:r,safetyFlushMs:s=bd.safetyFlushMs})=>{const{publish:i}=n,a=new Map,o=new Set,l=new Set;let d=!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(yd(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(yd(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 l=s.elapsed(o);u(n,l.diagnostics),i("insight.scheduler.elapsed",{id:n,expired:l.expired,resolvedCures:l.resolvedCures,resolvedDefenceStrips:l.resolvedDefenceStrips,restoredDefs:l.restoredDefs,predicted:l.predicted}),p(n)}):e.clock.clearTimer(yd(n))},h=()=>{if(d=!1,e.clock.clearTimer(vd),0===o.size&&0===l.size)return;const t=[...o].sort(),n=[...l].sort();o.clear(),l.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=()=>{d||(d=!0,e.clock.setTimer(vd,s,h))},g=e=>{o.add(e),m()},b=e=>{l.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),l.delete(e),p(e)}),n.on("insight.ingress.prompt",h))},stop(){for(;f.length>0;)f.pop()();e.clock.clearTimer(vd),d=!1;for(const t of a.keys())e.clock.clearTimer(yd(t));a.clear(),o.clear(),l.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 l=r.elapsed(o);return u(n,l.diagnostics),l},getTimeEpoch:()=>c,reschedule:p,markDirty:e=>{g(e),b(e)},flush:h})},wd=({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=[],l=[],d=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=d(n),a=i.get(e);let o=!1,l=!1;a?a.mode!==s.mode&&(o=!0,l=!0,"observed"===s.mode?t("insight.opponent.tracked",{id:e}):t("insight.opponent.unobserved",{id:e})):(o=!0,l=!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,l=!0):(o=!0,l=!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,l=!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&&(l=!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&&(l=!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)&&(l=!0),a&&(f(a.stats,s.stats,e=>e.value)||f(a.limbs,s.limbs,e=>e.percent))&&(l=!0),i.set(e,s),o&&t("insight.model.changed",{id:e}),l&&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,d(n.snapshot()))}l.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(;l.length>0;)l.pop()()}})},Id=(e,t)=>"number"==typeof e?To(t?.[e]):null,zd=({adapter:e,settings:t,safetyFlushMs:n,display:r,displaySink:s,notice:i=()=>{},guards:a})=>{const o=Object.freeze({affById:Hi,cureById:Vi,cureMasks:ea,balanceById:Wi,priorityByAff:Qi,defenceById:Yi,defenceDefaults:Ki,guards:!0===a,get growth(){return t.get().pruning}}),l=gd({adapter:e,notice:i}),{publish:d}=l;let c=0;const f=e=>(c+=1,d("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=Eo({tables:o,guards:!0===a,policy:t.get().predictive.defaultPolicy,predictionEnabled:t.get().predictive.enabled}),m=kd({adapter:e,roster:h,publisher:l,notice:i,safetyFlushMs:n??t.get().display.safetyFlushMs}),g=fd({roster:h,tables:o,publish:d,notice:i,advanceToNow:m.advanceToNow}),b=wd({roster:h,publish:d,defenceDefaults:Ki}),y=r?(({publisher:e,roster:t,settings:n,display:r,sink:s})=>{const{renderTarget:i,renderRoster:a,displayTable:o}=r,l=[],d=(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(){l.push(e.on("insight.display.flush",({ids:e})=>{const r=t.snapshot(),s=n.get();r.targetId&&e.includes(r.targetId)&&d(r,s),c(r,s)}))},stop(){for(;l.length>0;)l.pop()()},refresh(){const e=t.snapshot(),r=n.get();d(e,r),c(e,r)}})})({publisher:l,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,l=[],d=e=>!0===n.get().display.notices&&t.targetId===e,c=e=>t=>{d(t.id)&&s({html:a({affId:t.affId,present:e},i,n.get())})},f=e=>t=>{d(t.id)&&s({html:o({defId:t.defId,present:e},i,n.get())})};return Object.freeze({start(){l.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(;l.length>0;)l.pop()()}})})({publisher:l,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=ld({adapter:e,publish:d,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:l}=r,d=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=El(e,t),r=f.get(n);r?r.push(z):f.set(n,[z]),u.add(Tl(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?Id(a,r):null,d=s(o);l("insight.ingress.trigger",{id:e.id,match:r,context:d});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,d,s),s.id,d)}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:Id(t.actor,r),o=s(a);l("insight.ingress.trigger",{id:`${e.id}.${t.id}`,match:r,context:o});const d=n.resolveView(a);d&&b(t.handler(r,o,d,i.state),d.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 d.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(El(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:()=>[...d.keys()],listArmed:()=>[...h.keys()],listArmingSkills:()=>[...u]})})({adapter:e,roster:h,router:g,publisher:l,capture:w.capture,commandMemory:k,sessionPacks:rd,promptPacks:sd}),z=e=>{g.addDefinitions(e),w.observeSkills(g.listSkills())};z(Cl);const _=new Set,O=new Map;let $=!1;const S=({id:n})=>{const r=h.setTarget(n);if(!r||!t.get().classLookup||null!==r.class||_.has(r.id)||O.has(r.id))return;const s=Promise.resolve().then(()=>e.directory.read(r.id));O.set(r.id,s),s.then(e=>{if(_.add(r.id),$||null===e)return;const t=h.get(r.id);t&&null===t.class&&g.observe({type:"classObserved",class:e,source:"directory",id:r.id})}).catch(()=>{}).finally(()=>{O.get(r.id)===s&&O.delete(r.id)})},M=[],j=()=>{for($=!0,O.clear(),w.stop(),I.stop(),m.stop(),b.stop(),y?.stop(),v?.stop();M.length>0;)M.pop()()};try{b.start(),m.start(),y?.start(),v?.start(),M.push(l.on("insight.ingress.skill",g.dispatchAction),l.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"})),l.on("insight.ingress.target",S),l.on("insight.ingress.room.entered",({id:e})=>h.track(e)),l.on("insight.ingress.room.left",({id:e})=>h.untrack(e)),l.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)),l.on("insight.settings.changed",({document:e})=>h.updateDefaults({policy:e.predictive.defaultPolicy,predictionEnabled:e.predictive.enabled}))),I.start(),w.start()}catch(x){throw j(),x}return Object.freeze({roster:h,router:g,scheduler:m,registrar:I,publish:d,events:l.events,settings:p,getSettingsRevision:()=>c,display:y,observe:g.observe,addDefinitions:z,capture:w.capture,dispose:j})},_d=Object.freeze({schemaVersion:3,autoUpdate:!1,classLookup:!0,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:oa.epsilon,forkCap:oa.forkCap})}),Od=Fr({threshold:xr().min(0).max(1).catch(_d.display.threshold),shortNames:Er().catch(_d.display.shortNames),colors:Er().catch(_d.display.colors),notices:Er().catch(_d.display.notices),showRoster:Er().catch(_d.display.showRoster),safetyFlushMs:xr().int().min(0).max(1e4).catch(_d.display.safetyFlushMs)}).catch({..._d.display}),$d=Fr({enabled:Er().catch(_d.predictive.enabled),defaultPolicy:Kr(Xa).catch(_d.predictive.defaultPolicy)}).catch({..._d.predictive}),Sd=Fr({presenceFloor:xr().min(0).max(1).catch(_d.queries.presenceFloor)}).catch({..._d.queries}),Md=Fr({epsilon:xr().positive().max(.1).catch(_d.pruning.epsilon),forkCap:xr().int().min(1).catch(_d.pruning.forkCap)}).catch({..._d.pruning}),jd=Fr({schemaVersion:Xr(3).catch(3),autoUpdate:Er().catch(_d.autoUpdate),classLookup:Er().catch(_d.classLookup),display:Od,predictive:$d,queries:Sd,pruning:Md}).catch({schemaVersion:3,autoUpdate:_d.autoUpdate,classLookup:_d.classLookup,display:{..._d.display},predictive:{..._d.predictive},queries:{..._d.queries},pruning:{..._d.pruning}}),xd=e=>{if(e&&"object"==typeof e&&!Object.isFrozen(e)){Object.freeze(e);for(const t of Object.keys(e))xd(e[t])}return e},Nd=e=>xd(jd.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:_d.pruning.forkCap}:{}}:e.pruning;return{...e,schemaVersion:3,pruning:t}})(e))),Ad=(e,{key:t="insightSettings"}={})=>{let n=Nd(null);const r=(r=n)=>(e.storage.set(t,JSON.stringify(r)),n=r,r);return Object.freeze({get:()=>n,load:()=>(n=Nd((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(Nd({...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(Nd({...n,display:{...n.display,...e}})),updatePredictive:(e={})=>r(Nd({...n,predictive:{...n.predictive,...e}})),replace:e=>r(Nd(e)),reset:()=>(n=Nd(null),n),clear:()=>(e.storage.clear(t),n=Nd(null),n)})},Td=Object.freeze({forks:Object.freeze([])}),Ed=({roster:e,queryCompiler:t,events:n,settings:r,observe:s,capture:i,advanceToNow:a,reschedule:o,displayRendering:l,refreshDisplay:d,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?Ga(n.belief,t):0},v=(e,t,n)=>e(b(t)?.belief??Td,n),k=(e,t)=>v(Ua,e,t),w=(e,t)=>v(Ha,e,t),I=(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),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(),s=z(_({id:r.id,class:r.class,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:s}),s};let S=null,M=null;const j=()=>{const t={rosterRevision:e.revision,settingsRevision:h(),phaseRevision:p(),timeEpoch:m()};if(M?.rosterRevision===t.rosterRevision&&M.settingsRevision===t.settingsRevision&&M.phaseRevision===t.phaseRevision&&M.timeEpoch===t.timeEpoch)return S;const n={},s=[...e.list()].sort(),i=new Set(s);for(const r of s)n[r]=$(e.get(r),t.settingsRevision);for(const e of O.keys())i.has(e)||O.delete(e);return S=Object.freeze({system:Object.freeze({phase:u(),version:g}),target:e.targetId?n[e.targetId]??null:null,opponents:Object.freeze(n),settings:r.get()}),M=t,S},x=Object.freeze({get:()=>e.targetId,set:t=>{const n=e.setTarget(t??null);return n?n.id:null},is:t=>null!==e.targetId&&To(t)===e.targetId}),N=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()}}),A=(e,t)=>String(e??"").trim().toLowerCase()===String(t??"").trim().toLowerCase(),T=Object.freeze({get:e=>b(e)?.class??null,is:(e,t)=>{if(void 0===e)return!0;if(!e)return!1;const n=b(t)?.class??"";return Array.isArray(e)?e.some(e=>A(n,e)):A(n,e)}}),E=Object.freeze({have:(e,t)=>I(y(t,e),t),haveAll:(e,t)=>I(w(t,e),t),haveAny:(e,t)=>I(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(Va,e,t))(t,e)}),C=Object.freeze({create:e=>t.create(e),probability:(e,n)=>{const r=t.prepare(e),s=t.bind(r,n?.params);return b(n)?.queryProbability(r,s)??0}}),P=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}}),D=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})}),R=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={})=>{if(t&&"object"==typeof t&&Object.hasOwn(t,"affs"))throw new TypeError("balances.remainingProbability no longer accepts affs; use queries.probability for compound questions");const n=b(t);return n?n.balanceRemainingProbability(e,{op:t?.op,ms:t?.ms}):0}}),Z=(e,t={})=>{const{id:n,...r}=t;return s({type:e,...r,id:n},i(n??null))},B=Object.freeze({afflicted:e=>Z("afflicted",e),afflictedOneOf:({mode:e="firstMissing",...t}={})=>Z("afflictedOneOf",{mode:e,...t}),advanced:e=>Z("limbAdvance",e),cured:e=>Z("cured",e),confirmed:({present:e=!0,...t}={})=>Z("confirmed",{present:e,...t}),confirmedCount:e=>Z("confirmedCount",e),confirmedCounts:e=>Z("confirmedCounts",e),confirmedLevel:e=>Z("confirmedLevel",e),converted:e=>Z("converted",e),removed:e=>Z("removed",e)}),L=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}}),F=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 l.renderAffNotice({affId:n,present:i},l.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 l.renderDefNotice({defId:s,present:i},l.displayTable,a)}if(!["target","affState","statState"].includes(e))throw new TypeError(`unknown display view '${e}'`);const o=b({id:t});if(!o)return"";const d=o.snapshot();return"target"===e?l.renderTarget(d,l.displayTable,a):"affState"===e?l.renderAffState(d,l.displayTable,a):l.renderStatState(d,l.displayTable,a)},notice:(e,t)=>{c({html:e,severity:t})},refresh:()=>{d()},openDebug:()=>{f(l.renderDebug(j()))}}),q=Object.freeze({target:x,opponents:N,class:T,affs:E,queries:C,defs:P,limbs:D,balances:R,observe:B,simulate:L,display:F,settings:r}),G=Object.freeze(Object.fromEntries(Object.entries(hd).filter(([,e])=>"internal"!==e.audience))),J=Object.freeze({on:n.on,off:n.off,topics:G});return Object.freeze({get state(){return j()},api:q,events:J})},Cd=["head","torso","leftarm","rightarm","leftleg","rightleg"],Pd=e=>String(e).replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',"""),Dd=(e,t="",n="")=>{const r=[t?`color: ${t}`:"",n?`background: ${n}`:""].filter(Boolean).join("; ");return r?`<span style="${r}">${e}</span>`:`<span>${e}</span>`},Rd=(e,t="",n="")=>Dd(Pd(e),t,n),Zd=e=>e.charAt(0).toUpperCase()+e.slice(1),Bd=(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)),Ld=(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:"",l=r.colors&&s?s.bg:"";return Rd(`${i}${a}`,o,l)},Fd=(e,t,n)=>{const r=n.display,{bracket:s}=t.chrome,i=[Rd("[",s.fg,s.bg)],a=Bd(e.affs,r.threshold);return a.forEach(([e,n],s)=>{i.push(Ld(e,n,t,r));const o=s<a.length-1?", ":"";i.push(Rd(`: ${(e=>String(Math.round(100*e)/100))(n.probability)}${o}`))}),i.push(Rd("]",s.fg,s.bg)),i},qd=[["hp","H"],["mana","M"]],Gd=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}%)`},Jd=(e,t)=>{const n=[],{detail:r}=t.chrome;for(const[s,i]of qd){const t=e.stats?.[s];if(!t)continue;n.length>0&&n.push(Rd(" "));const a=Math.round(100*Math.min(1,Math.max(0,t.value)));n.push(Rd(`${i}:`,r.fg,r.bg)),n.push(Rd(`${a}%`,Gd(t.value)))}return n},Ud=(e,t,n,r,s)=>{const i=[Rd(`${n?"+":"-"}${e} `,n?"lime":"red")];if("aff"===e){const e=r.affs[t],n=s.display;i.push(Rd(Zd(t),n.colors&&e?e.fg:"",n.colors&&e?e.bg:""))}else i.push(Rd(Zd(t)));return i},Hd=({text:e="",html:t,severity:n="info"},r)=>{const s=r.chrome.severity,i=s[n]??s.info,a="string"==typeof t?Dd(t,i.fg,i.bg):Rd(e,i.fg,i.bg);return`<span class="mono">${(e=>{const{delimiter:t,label:n}=e.chrome.tag;return[Rd("<<",t.fg,t.bg),Rd("insight",n.fg,n.bg),Rd(">> ",t.fg,t.bg)]})(r).join("")}${a}</span>`},Vd=(e,t)=>{if(!e)throw new TypeError(`insight query: ${t}`)},Wd=e=>{if(null===e||"object"!=typeof e)return!1;const t=Object.getPrototypeOf(e);return null===t||t===Object.prototype},Yd=(e,t)=>{Vd(Wd(e),"nodes and leaf payloads must be plain objects"),Vd(Reflect.ownKeys(e).length===t.length&&t.every(t=>Object.hasOwn(e,t)),`expected exactly ${t.join(", ")}`)},Kd=e=>Vd("string"==typeof e&&e.length>0,"ids and parameter names must be non-empty strings"),Qd=(e,t,n)=>Vd("number"==typeof e&&Number.isFinite(e)&&e>=0&&(!t||Number.isInteger(e)),`${n} must be a finite non-negative ${t?"integer":"number"}`),Xd=e=>{const t=new WeakMap,n=(t,n)=>{const r=[],s=[],i=[],a=e=>{Vd(Array.isArray(e)&&e.length>0,"pool must be a non-empty array");const t=new Set;for(const n of e)Kd(n),Vd(!t.has(n),`duplicate pool member '${n}'`),t.add(n);return n?[...e]:e},o=t=>{Vd(Wd(t),"node must be a plain object");const n=Reflect.ownKeys(t);Vd(1===n.length,"node must carry exactly one operator and no extra keys");const l=n[0],d=t[l];if("all"===l||"any"===l)return Vd(Array.isArray(d),`${l} requires an array`),{kind:l,children:Array.from(d,o)};if("not"===l)return{kind:l,child:o(d)};if("aff"===l)return Kd(d),{kind:l,id:d};Vd("poolCount"===l||"cureCount"===l||"balanceRemaining"===l,"unknown expression operator");const c="balanceRemaining"===l;Yd(d,"poolCount"===l?["ids","op","n"]:["id","op",c?"ms":"n"]);const f=d.op;Vd($a.includes(f),"unknown comparison operator");const u=((e,t,n)=>{if("number"==typeof e)return Qd(e,t,"literal"),{slot:-1,literal:e};Vd(Wd(e),"nodes and leaf payloads must be plain objects");const i=n&&Object.hasOwn(e,"offsetMs");Yd(e,i?["param","offsetMs"]:["param"]);const a=e.param;Kd(a);let o=0;i&&(Vd("number"==typeof e.offsetMs&&Number.isFinite(e.offsetMs),"offsetMs must be a finite number"),o=0===e.offsetMs?0:e.offsetMs);let l=r.findIndex(e=>e.name===a);l<0?(l=r.length,r.push({name:a,integer:t})):t&&(r[l].integer=!0);let d=s.findIndex(e=>e.parameter===l&&e.offsetMs===o);return d<0&&(d=s.length,s.push({parameter:l,offsetMs:o})),{slot:d,literal:0}})(d[c?"ms":"n"],!c,c);if("poolCount"===l)return{kind:"count",ids:a(d.ids),op:f,operand:u};const p=d.id;if(Kd(p),"cureCount"===l){const t=e.cureById.get(p);return Vd(void 0!==t,`unknown cure '${p}'`),{kind:"count",ids:a(t.order),op:f,operand:u}}Vd(e.balanceById.has(p),`unknown balance '${p}'`);let h=i.indexOf(p);return h<0&&(h=i.length,i.push(p)),{kind:"balance",slot:h,op:f,operand:u}};return((e,t,n,r)=>{const s=[],i=[];Za(e,!1,s,i);let a=0;for(const l of s)l.refs>1&&(l.cache=3*a,a+=1);const o=Za(e,!0,s,i);return{match:o===Ta?Ca:o===Ea?Pa:o,balanceConditions:i,cacheSlots:a,balanceIds:t,parameters:n,operands:r,plainOperands:r.every((e,t)=>0===e.offsetMs&&e.parameter===t)}})(o(t),i,r,s)};return{create(e){const r=n(e,!0),s=Object.freeze(Object.create(null));return t.set(s,r),s},prepare:e=>t.get(e)??n(e,!1),bind(e,t){const{parameters:n,operands:r}=e,s=new Array(n.length);for(let a=0;a<s.length;a+=1){const{name:e,integer:r}=n[a];Vd(null!=t&&Object.hasOwn(t,e),`missing parameter '${e}'`);const i=t[e];Qd(i,r,`parameter '${e}'`),s[a]=i}if(e.plainOperands)return s;const i=new Array(r.length);for(let a=0;a<i.length;a+=1){const{parameter:e,offsetMs:t}=r[a],o=s[e]+t;Vd(Number.isFinite(o),`parameter '${n[e].name}' with offset ${t} must resolve to a finite threshold`),i[a]=o}return i}}},ec="0.6.5",tc=Object.freeze({BOOTING:"BOOTING",LOADING_SETTINGS:"LOADING_SETTINGS",REGISTERING_TRIGGERS:"REGISTERING_TRIGGERS",READY:"READY",DEGRADED:"DEGRADED"}),nc=Object.freeze({[tc.BOOTING]:Object.freeze([tc.LOADING_SETTINGS,tc.DEGRADED]),[tc.LOADING_SETTINGS]:Object.freeze([tc.REGISTERING_TRIGGERS,tc.DEGRADED]),[tc.REGISTERING_TRIGGERS]:Object.freeze([tc.READY,tc.DEGRADED]),[tc.READY]:Object.freeze([]),[tc.DEGRADED]:Object.freeze([])});var rc="__insight4StorageProbe",sc=Object.freeze({displayTable:Bs,renderAffNotice:({affId:e,present:t},n,r)=>`<span class="mono">${Ud("aff",e,t,n,r).join("")}</span>`,renderAffState:(e,t,n)=>`<span class="mono">${Fd(e,t,n).join("")}</span>`,renderDebug:e=>`<pre class="mono">${Pd(JSON.stringify(e,null,2))}</pre>`,renderDefNotice:({defId:e,present:t},n,r)=>`<span class="mono">${Ud("def",e,t,n,r).join("")}</span>`,renderNotice:Hd,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 l=e[n];o>0&&a.push(Rd(" ")),a.push(Rd(`${Zd(n)} `),Rd("[",s.fg,s.bg));const d=Bd(l.affs,r.threshold);d.forEach(([e,n],s)=>{a.push(Ld(e,n,t,r)),s<d.length-1&&a.push(Rd(" "))}),a.push(Rd("]",s.fg,s.bg));const c=Math.round(100*l.staleness);c>0&&a.push(Rd(` ~${c}%`,i.fg,i.bg))}),`<span class="mono">${a.join("")}</span>`},renderStatState:(e,t)=>{const n=Jd(e,t);return n.length>0?`<span class="mono">${n.join("")}</span>`:""},renderTarget:(e,t,n)=>{const{detail:r}=t.chrome,s=[Rd(`${Zd(e.id)} `),...Fd(e,t,n)],i=Jd(e,t);i.length>0&&s.push(Rd(" "),...i);const a=Cd.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(Rd(` ${t}`,r.fg,r.bg))}return`<span class="mono">${s.join("")}</span>`}});function ic(e,{safetyFlushMs:t,updateNxs:n=h,guards:r}={}){const s=function({onTransition:e}={}){let t=tc.BOOTING,n=0;const r=[tc.BOOTING];return{getPhase:()=>t,getRevision:()=>n,getHistory:()=>[...r],transition(s){if(!nc[t].includes(s))throw new Error(`Invalid phase transition: ${t} → ${s}`);return t=s,n+=1,r.push(s),e?.(s),t}}}();let i,o=null,l=null,d=null,c=null,f=!1;const u={getPhase:s.getPhase,getPhaseHistory:s.getHistory,getError:()=>o,isReady:()=>s.getPhase()===tc.READY,dispose(){f||(f=!0,d?.dispose(),c&&globalThis.insight===c&&delete globalThis.insight)},get settings(){return l},get runtime(){return d},get state(){return c?c.state:null},get api(){return c?c.api:null},get events(){return c?c.events:null}},p=t=>{try{e.display.addLine(Hd(t,Bs))}catch{}},m=()=>{!0===l?.get?.().autoUpdate&&n({enabled:!0,currentVersion:ec,notice:p})},g=e=>(o=e,s.transition(tc.DEGRADED),p({text:`DEGRADED: ${e?.message??String(e)}`,severity:"error"}),m(),u);try{a(e),e.storage.clear(rc),e.storage.set(rc,"probe"),e.storage.clear(rc),i=e.display.addLine.bind(e.display)}catch(y){try{e?.storage?.clear?.(rc)}catch{}return g(y)}s.transition(tc.LOADING_SETTINGS);const b=Ad(e);l=b;try{b.load()}catch(y){b.reset(),p({text:`Settings storage is unavailable — running on default settings. (${y?.message??String(y)})`,severity:"warning"})}s.transition(tc.REGISTERING_TRIGGERS);try{d=zd({adapter:e,settings:b,safetyFlushMs:t,guards:r,displaySink:i,notice:p,display:sc}),l=d.settings,c=Ed({roster:d.roster,queryCompiler:Xd({cureById:Vi,balanceById:Wi}),events:d.events,settings:d.settings,observe:d.observe,capture:d.capture,advanceToNow:d.scheduler.advanceToNow,reschedule:d.scheduler.reschedule,displayRendering:sc,refreshDisplay:d.display.refresh,notice:p,addLine:i,getPhase:s.getPhase,getPhaseRevision:s.getRevision,getSettingsRevision:d.getSettingsRevision,getTimeEpoch:d.scheduler.getTimeEpoch,version:ec})}catch(y){return d?.dispose(),d=null,l=b,g(y)}return s.transition(tc.READY),globalThis.insight=c,d.publish("insight.ready",{}),m(),u}var ac=Symbol.for("insight4.instance");!function(e){globalThis[ac]?.dispose();const r=ic(function({fetchFn:e=globalThis.fetch,AbortControllerCtor:r=globalThis.AbortController,setTimeoutFn:i=globalThis.setTimeout,clearTimeoutFn:a=globalThis.clearTimeout,directoryTimeoutMs:o}={}){const l=new Map;let d=1;return{display:{addLine(e){nexusclient.add_html_line(e)}},directory:t({fetchFn:e,AbortControllerCtor:r,setTimeoutFn:i,clearTimeoutFn:a,...void 0===o?{}:{timeoutMs:o}}),storage:{get(e){const t=n();return"function"==typeof t?.get?t.get(e):t?.vars?.[e]},set(e,t){const r=n();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[e]=t}else r.set(e,t)},clear(e){const t=n();if("function"!=typeof t?.delete)if("function"!=typeof t?.set){if(!t?.vars)throw new Error("insight4 storage.clear failed — host variables expose neither delete()/set() nor a vars record");delete t.vars[e]}else t.set(e,void 0);else t.delete(e)}},triggers:{register(e,t,n){const r="insight4.trigger."+d++;return nexAction.triggers.add({id:r,tags:["insight4",`lifetime:${t}`],regex:e,action:n}),r},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 s(t?`nexskill.match.skill.${t}`:"nexskill.match.skill",e)},on:s,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,t,n){const r=l.get(e);void 0!==r&&clearTimeout(r),l.set(e,setTimeout(()=>{l.delete(e),n()},t))},clearTimer(e){const t=l.get(e);void 0!==t&&(clearTimeout(t),l.delete(e))}}}}(),e);globalThis[ac]=r}()}();
|
|
1
|
+
!function(){var e=async(e,{fetchFn:t=globalThis.fetch,AbortControllerCtor:n=globalThis.AbortController,setTimeoutFn:r=globalThis.setTimeout,clearTimeoutFn:s=globalThis.clearTimeout,timeoutMs:i=1e4}={})=>{if("function"!=typeof t)throw new Error("fetch is not available");const a=`https://api.achaea.com/characters/${e}.json`;let o=null;try{let e;if("function"==typeof n&&i>0){const t=new n;o=r(()=>t.abort(),i),e=t.signal}const s=await t(a,{cache:"no-store",...e?{signal:e}:{}});if(404===s?.status)return null;if(!s?.ok)throw new Error(`${s?.status??"no"} response from ${a}`);return l=(await s.json())?.class,String(l??"").trim().toLowerCase().replace(/\belemental\b/g,"").replace(/[^a-z]/g,"")||null}finally{null!==o&&s(o)}var l},t=(t={})=>Object.freeze({read:n=>e(n,t)});function n(){return nexusclient.variables()}var r=["insight4"];function s(e,t){const n=`insight4.${e}`;return eventStream.registerEvent(e,t,{id:n,tags:r}),()=>{eventStream.removeListener(e,n)}}var i=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"]),directory:Object.freeze(["read"]),text:Object.freeze(["snapshot"]),clock:Object.freeze(["now","setTimer","clearTimer"])});Object.freeze(["events.onSkillMatch","events.on"]);function a(e){const t=function(e){if(null===e||"object"!=typeof e)return["adapter is not an object"];const t=[];for(const[n,r]of Object.entries(i)){const s=e[n];if(null!==s&&"object"==typeof s)for(const e of r)"function"!=typeof s[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 o,l=/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/,d="nexsight",c=`https://unpkg.com/${d}@latest/package.json`,f=e=>{const t=l.exec(String(e??"").trim());if(!t)throw new Error(`invalid version '${e??""}'`);return{core:t.slice(1,4).map(Number),prerelease:t[4]?.split(".")??[]}},u=(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},p=(e,t,n)=>{try{e?.({text:t,severity:n})}catch{}},h=async({enabled:e=!1,currentVersion:t,notice:n=null,fetchFn:r=globalThis.fetch,consoleObj:s=console,setTimeoutFn:i=setTimeout,clearTimeoutFn:a=clearTimeout,timeoutMs:o=1e4,url:l=c}={})=>{if(!e)return null;let h=null;try{if("function"!=typeof r)throw new Error("fetch is not available");f(t);const e=globalThis.AbortController;let s;if(e&&o>0){const t=new e;h=i(()=>t.abort(),o),s=t.signal}const a=await r(l,{cache:"no-store",...s?{signal:s}:{}});if(!a?.ok)throw new Error(`${a?.status??"no"} response from ${l}`);const c=(await a.json())?.version;if(f(c),((e,t)=>{const n=f(e),r=f(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=u(n.prerelease[i],r.prerelease[i]);if(0!==e)return e}return 0})(c,t)<=0)return null;const m=(e=>`https://unpkg.com/${d}@${e}/insight4.nxs`)(c);return p(n,`Update available: ${t} → ${c}. Import ${m}`,"warning"),{currentVersion:t,latestVersion:c,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}`),p(n,e,"error"),null}finally{null!==h&&a(h)}};function m(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 g=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},b=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}};(o=globalThis).__zod_globalConfig??(o.__zod_globalConfig={});var y=globalThis.__zod_globalConfig;function v(e){return e&&Object.assign(y,e),y}function k(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 w(e,t){return"bigint"==typeof t?t.toString():t}function I(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function z(e){return null==e}function _(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}var O=Symbol("evaluating");function $(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==O)return void 0===r&&(r=O,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function S(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function M(...e){const t={};for(const n of e)Object.assign(t,Object.getOwnPropertyDescriptors(n));return Object.defineProperties({},t)}function j(e){return JSON.stringify(e)}var x="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function N(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var A=I(()=>{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===N(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!==N(n)&&!1!==Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")}function E(e){return T(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}var C=new Set(["string","number","symbol"]);function P(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function D(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 B(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 L(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 F(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 G(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:s,continue:i,input:a,...o}=e;return o.path??(o.path=[]),o.message=r,t?.reportInput&&(o.input=a),o}function J(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function U(...e){const[t,n,r]=e;return"string"==typeof t?{message:t,code:"custom",input:n,inst:r}:{...t}}var H=(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,w,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},V=m("$ZodError",H),W=m("$ZodError",H,{Parent:Error});var Y=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 g;if(a.issues.length){const t=new(s?.Err??e)(a.issues.map(e=>G(e,i,v())));throw x(t,s?.callee),t}return a.value},K=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=>G(e,i,v())));throw x(t,s?.callee),t}return a.value},Q=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 g;return i.issues.length?{success:!1,error:new(e??V)(i.issues.map(e=>G(e,s,v())))}:{success:!0,data:i.value}},X=Q(W),ee=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=>G(e,s,v())))}:{success:!0,data:i.value}},te=ee(W),ne=e=>(t,n,r)=>{const s=r?{...r,direction:"backward"}:{direction:"backward"};return Y(e)(t,n,s)},re=e=>(t,n,r)=>Y(e)(t,n,r),se=e=>async(t,n,r)=>{const s=r?{...r,direction:"backward"}:{direction:"backward"};return K(e)(t,n,s)},ie=e=>async(t,n,r)=>K(e)(t,n,r),ae=e=>(t,n,r)=>{const s=r?{...r,direction:"backward"}:{direction:"backward"};return Q(e)(t,n,s)},oe=e=>(t,n,r)=>Q(e)(t,n,r),le=e=>async(t,n,r)=>{const s=r?{...r,direction:"backward"}:{direction:"backward"};return ee(e)(t,n,s)},de=e=>async(t,n,r)=>ee(e)(t,n,r),ce=/^[cC][0-9a-z]{6,}$/,fe=/^[0-9a-z]+$/,ue=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,pe=/^[0-9a-vA-V]{20}$/,he=/^[A-Za-z0-9]{27}$/,me=/^[a-zA-Z0-9_-]{21}$/,ge=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,be=/^([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)$/,ve=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var 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])$/,we=/^(([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}|:))$/,Ie=/^((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])$/,ze=/^(([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])$/,_e=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Oe=/^[A-Za-z0-9_-]*$/,$e=/^https?$/,Se=/^\+[1-9]\d{6,14}$/,Me="(?:(?:\\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])))",je=new RegExp(`^${Me}$`);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 Ne=/^-?\d+$/,Ae=/^-?\d+(?:\.\d+)?$/,Te=/^(?:true|false)$/i,Ee=/^[^A-Z]*$/,Ce=/^[^a-z]*$/,Pe=m("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),De={number:"number",bigint:"bigint",object:"date"},Re=m("$ZodCheckLessThan",(e,t)=>{Pe.init(e,t);const n=De[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=m("$ZodCheckGreaterThan",(e,t)=>{Pe.init(e,t);const n=De[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})}}),Be=m("$ZodCheckMultipleOf",(e,t)=>{Pe.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})}}),Le=m("$ZodCheckNumberFormat",(e,t)=>{Pe.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),r=n?"int":"number",[s,i]=Z[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=Ne)}),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})}}),Fe=m("$ZodCheckMaxLength",(e,t)=>{var n;Pe.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!z(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=J(r);n.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),qe=m("$ZodCheckMinLength",(e,t)=>{var n;Pe.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!z(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=J(r);n.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Ge=m("$ZodCheckLengthEquals",(e,t)=>{var n;Pe.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!z(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=J(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})}}),Je=m("$ZodCheckStringFormat",(e,t)=>{var n,r;Pe.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=()=>{})}),Ue=m("$ZodCheckRegex",(e,t)=>{Je.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})}}),He=m("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Ee),Je.init(e,t)}),Ve=m("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Ce),Je.init(e,t)}),We=m("$ZodCheckIncludes",(e,t)=>{Pe.init(e,t);const n=P(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=m("$ZodCheckStartsWith",(e,t)=>{Pe.init(e,t);const n=new RegExp(`^${P(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})}}),Ke=m("$ZodCheckEndsWith",(e,t)=>{Pe.init(e,t);const n=new RegExp(`.*${P(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})}}),Qe=m("$ZodCheckOverwrite",(e,t)=>{Pe.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}}),Xe=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"))}},et={major:4,minor:4,patch:3},tt=m("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=et;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=B(e);for(const i of t){if(i._zod.def.when){if(L(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 g;if(r||a instanceof Promise)r=(r??Promise.resolve()).then(async()=>{await a,e.issues.length!==t&&(s||(s=B(e,t)))});else{if(e.issues.length===t)continue;s||(s=B(e,t))}}return r?r.then(()=>e):e},n=(n,s,i)=>{if(B(n))return n.aborted=!0,n;const a=t(s,r,i);if(a instanceof Promise){if(!1===i.async)throw new g;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 g;return a.then(e=>t(e,r,i))}return t(a,r,i)}}$(e,"~standard",()=>({validate:t=>{try{const n=X(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch(n){return te(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}))}),nt=m("$ZodString",(e,t)=>{var n;tt.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}}),rt=m("$ZodStringFormat",(e,t)=>{Je.init(e,t),nt.init(e,t)}),st=m("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=be),rt.init(e,t)}),it=m("$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());rt.init(e,t)}),at=m("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=ve),rt.init(e,t)}),ot=m("$ZodURL",(e,t)=>{rt.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})}}}),lt=m("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),rt.init(e,t)}),dt=m("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=me),rt.init(e,t)}),ct=m("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=ce),rt.init(e,t)}),ft=m("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=fe),rt.init(e,t)}),ut=m("$ZodULID",(e,t)=>{t.pattern??(t.pattern=ue),rt.init(e,t)}),pt=m("$ZodXID",(e,t)=>{t.pattern??(t.pattern=pe),rt.init(e,t)}),ht=m("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=he),rt.init(e,t)}),mt=m("$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(`^${Me}T(?:${r})$`)}(t)),rt.init(e,t)}),gt=m("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=je),rt.init(e,t)}),bt=m("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=new RegExp(`^${xe(t)}$`)),rt.init(e,t)}),yt=m("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=ge),rt.init(e,t)}),vt=m("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=ke),rt.init(e,t),e._zod.bag.format="ipv4"}),kt=m("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=we),rt.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})}}}),wt=m("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Ie),rt.init(e,t)}),It=m("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=ze),rt.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 zt(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 _t=m("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=_e),rt.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{zt(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});var Ot=m("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Oe),rt.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{(function(e){if(!Oe.test(e))return!1;const t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return zt(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=m("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Se),rt.init(e,t)});var St=m("$ZodJWT",(e,t)=>{rt.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})}}),Mt=m("$ZodNumber",(e,t)=>{tt.init(e,t),e._zod.pattern=e._zod.bag.pattern??Ae,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}}),jt=m("$ZodNumberFormat",(e,t)=>{Le.init(e,t),Mt.init(e,t)}),xt=m("$ZodBoolean",(e,t)=>{tt.init(e,t),e._zod.pattern=Te,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}}),Nt=m("$ZodUnknown",(e,t)=>{tt.init(e,t),e._zod.parse=e=>e}),At=m("$ZodNever",(e,t)=>{tt.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(...F(n,e.issues)),t.value[n]=e.value}var Et=m("$ZodArray",(e,t)=>{tt.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=>Tt(t,n,e))):Tt(o,n,e)}return i.length?Promise.all(i).then(()=>n):n}});function Ct(e,t,n,r,s,i){const a=n in r;if(e.issues.length){if(s&&i&&!a)return;t.issues.push(...F(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 Pt(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 Dt(e,t,n,r,s,i){const a=[],o=s.keySet,l=s.catchall._zod,d=l.def.type,c="optional"===l.optin,f="optional"===l.optout;for(const u in t){if("__proto__"===u)continue;if(o.has(u))continue;if("never"===d){a.push(u);continue}const s=l.run({value:t[u],issues:[]},r);s instanceof Promise?e.push(s.then(e=>Ct(e,n,u,t,c,f))):Ct(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 Rt=m("$ZodObject",(e,t)=>{if(tt.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=I(()=>Pt(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=N,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 l=[],d=i.shape;for(const e of i.keys){const n=d[e],r="optional"===n._zod.optin,s="optional"===n._zod.optout,i=n._zod.run({value:o[e],issues:[]},a);i instanceof Promise?l.push(i.then(n=>Ct(n,t,e,o,r,s))):Ct(i,t,e,o,r,s)}return s?Dt(l,o,t,a,n.value,e):l.length?Promise.all(l).then(()=>t):t}}),Zt=m("$ZodObjectJIT",(e,t)=>{Rt.init(e,t);const n=e._zod.parse,r=I(()=>Pt(t));let s;const i=N,a=!y.jitless,o=a&&A.value,l=t.catchall;let d;e._zod.parse=(c,f)=>{d??(d=r.value);const u=c.value;return i(u)?a&&o&&!1===f?.async&&!0!==f.jitless?(s||(s=(e=>{const t=new Xe(["shape","payload","ctx"]),n=r.value,s=e=>{const t=j(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=j(r),o=e[r],l="optional"===o?._zod?.optin,d="optional"===o?._zod?.optout;t.write(`const ${n} = ${s(r)};`),l&&d?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 `):l?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),l?Dt([],u,c,f,d,e):c):n(c,f):(c.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),c)}});function Bt(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=>!B(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=>G(e,r,v())))}),t)}var Lt=m("$ZodUnion",(e,t)=>{tt.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=>_(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=>Bt(t,r,e,s)):Bt(a,r,e,s)}}),Ft=m("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Lt.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=I(()=>{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(!N(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)}}),qt=m("$ZodIntersection",(e,t)=>{tt.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])=>Jt(e,t,n)):Jt(e,s,i)}});function Gt(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)),s={...e,...t};for(const i of r){const n=Gt(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=Gt(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 Jt(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}),B(e))return e;const a=Gt(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 Ut=m("$ZodRecord",(e,t)=>{tt.init(e,t),e._zod.parse=(n,r)=>{const s=n.value;if(!T(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 d of a)if("string"==typeof d||"number"==typeof d||"symbol"==typeof d){o.add("number"==typeof d?d.toString():d);const a=t.keyType._zod.run({value:d,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=>G(e,r,v())),input:d,path:[d],inst:e});continue}const l=a.value,c=t.valueType._zod.run({value:s[d],issues:[]},r);c instanceof Promise?i.push(c.then(e=>{e.issues.length&&n.issues.push(...F(d,e.issues)),n.value[l]=e.value})):(c.issues.length&&n.issues.push(...F(d,c.issues)),n.value[l]=c.value)}let l;for(const e in s)o.has(e)||(l=l??[],l.push(e));l&&l.length>0&&n.issues.push({code:"unrecognized_keys",input:s,inst:e,keys:l})}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&&Ae.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=>G(e,r,v())),input:a,path:[a],inst:e});continue}const l=t.valueType._zod.run({value:s[a],issues:[]},r);l instanceof Promise?i.push(l.then(e=>{e.issues.length&&n.issues.push(...F(a,e.issues)),n.value[o.value]=e.value})):(l.issues.length&&n.issues.push(...F(a,l.issues)),n.value[o.value]=l.value)}}return i.length?Promise.all(i).then(()=>n):n}}),Ht=m("$ZodEnum",(e,t)=>{tt.init(e,t);const n=k(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(e=>C.has(typeof e)).map(e=>"string"==typeof e?P(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}}),Vt=m("$ZodLiteral",(e,t)=>{if(tt.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?P(e):e?P(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}}),Wt=m("$ZodTransform",(e,t)=>{tt.init(e,t),e._zod.optin="optional",e._zod.parse=(n,r)=>{if("backward"===r.direction)throw new b(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 g;return n.value=s,n.fallback=!0,n}});function Yt(e,t){return void 0===t&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}var Kt=m("$ZodOptional",(e,t)=>{tt.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(`^(${_(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=>Yt(e,r)):Yt(s,r)}return void 0===e.value?e:t.innerType._zod.run(e,n)}}),Qt=m("$ZodExactOptional",(e,t)=>{Kt.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)}),Xt=m("$ZodNullable",(e,t)=>{tt.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(`^(${_(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)}),en=m("$ZodDefault",(e,t)=>{tt.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=>tn(e,t)):tn(r,t)}});function tn(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}var nn=m("$ZodPrefault",(e,t)=>{tt.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))}),rn=m("$ZodNonOptional",(e,t)=>{tt.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=>sn(t,e)):sn(s,e)}});function sn(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 an=m("$ZodCatch",(e,t)=>{tt.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=>G(e,n,v()))},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=>G(e,n,v()))},input:e.value}),e.issues=[],e.fallback=!0),e)}}),on=m("$ZodPipe",(e,t)=>{tt.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=>ln(e,t.in,n)):ln(r,t.in,n)}const r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>ln(e,t.out,n)):ln(r,t.out,n)}});function ln(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=m("$ZodReadonly",(e,t)=>{tt.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(cn):cn(r)}});function cn(e){return e.value=Object.freeze(e.value),e}var fn,un=m("$ZodCustom",(e,t)=>{Pe.init(e,t),tt.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=>pn(t,n,r,e));pn(s,n,r,e)}});function pn(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(U(e))}}var hn=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)}};(fn=globalThis).__zod_globalRegistry??(fn.__zod_globalRegistry=new hn);var mn=globalThis.__zod_globalRegistry;function gn(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...R(t)})}function bn(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 vn(e,t){return new Ze({check:"greater_than",...R(t),value:e,inclusive:!1})}function kn(e,t){return new Ze({check:"greater_than",...R(t),value:e,inclusive:!0})}function wn(e,t){return new Be({check:"multiple_of",...R(t),value:e})}function In(e,t){return new Fe({check:"max_length",...R(t),maximum:e})}function zn(e,t){return new qe({check:"min_length",...R(t),minimum:e})}function _n(e,t){return new Ge({check:"length_equals",...R(t),length:e})}function On(e){return new Qe({check:"overwrite",tx:e})}function $n(e,t){const n=new Pe({check:"custom",...R(t)});return n._zod.check=e,n}function Sn(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??mn,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 Mn(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),Mn(i,t,r),t.seen.get(i).isParent=!0)}const l=t.metadataRegistry.get(e);return l&&Object.assign(a.schema,l),"input"===t.io&&Nn(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 jn(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 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 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 l of[...e.seen.entries()].reverse())r(l[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 l of e.seen.entries()){const e=l[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:An(t,"input",e.processors),output:An(t,"output",e.processors)}},enumerable:!1,writable:!1}),n}catch(o){throw new Error("Error converting schema to JSON.")}}function Nn(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 Nn(r.element,n);if("set"===r.type)return Nn(r.valueType,n);if("lazy"===r.type)return Nn(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 Nn(r.innerType,n);if("intersection"===r.type)return Nn(r.left,n)||Nn(r.right,n);if("record"===r.type||"map"===r.type)return Nn(r.keyType,n)||Nn(r.valueType,n);if("pipe"===r.type)return!!e._zod.traits.has("$ZodCodec")||(Nn(r.in,n)||Nn(r.out,n));if("object"===r.type){for(const e in r.shape)if(Nn(r.shape[e],n))return!0;return!1}if("union"===r.type){for(const e of r.options)if(Nn(e,n))return!0;return!1}if("tuple"===r.type){for(const e of r.items)if(Nn(e,n))return!0;return!(!r.rest||!Nn(r.rest,n))}return!1}var An=(e,t,n={})=>r=>{const{libraryOptions:s,target:i}=r??{},a=Sn({...s??{},target:i,io:t,processors:n});return Mn(e,a),jn(a,e),xn(a,e)},Tn={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},En=(e,t,n,r)=>{const s=e._zod.def;Mn(s.innerType,t,r);t.seen.get(e).ref=s.innerType},Cn=m("ZodISODateTime",(e,t)=>{mt.init(e,t),dr.init(e,t)});function Pn(e){return function(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...R(t)})}(Cn,e)}var Dn=m("ZodISODate",(e,t)=>{gt.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)})}(Dn,e)}var Zn=m("ZodISOTime",(e,t)=>{bt.init(e,t),dr.init(e,t)});function Bn(e){return function(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...R(t)})}(Zn,e)}var Ln=m("ZodISODuration",(e,t)=>{yt.init(e,t),dr.init(e,t)});function Fn(e){return function(e,t){return new e({type:"string",format:"duration",check:"string_format",...R(t)})}(Ln,e)}var qn=(e,t)=>{V.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,w,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,w,2)}},isEmpty:{get:()=>0===e.issues.length}})},Gn=m("ZodError",qn,{Parent:Error}),Jn=Y(Gn),Un=K(Gn),Hn=Q(Gn),Vn=ee(Gn),Wn=ne(Gn),Yn=re(Gn),Kn=se(Gn),Qn=ie(Gn),Xn=ae(Gn),er=oe(Gn),tr=le(Gn),nr=de(Gn),rr=new WeakMap;function sr(e,t,n){const r=Object.getPrototypeOf(e);let s=rr.get(r);if(s||(s=new Set,rr.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 ir=m("ZodType",(e,t)=>(tt.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:An(e,"input"),output:An(e,"output")}}),e.toJSONSchema=((e,t={})=>n=>{const r=Sn({...n,processors:t});return Mn(e,r),jn(r,e),xn(r,e)})(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(t,n)=>Jn(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Hn(e,t,n),e.parseAsync=async(t,n)=>Un(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Vn(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>Wn(e,t,n),e.decode=(t,n)=>Yn(e,t,n),e.encodeAsync=async(t,n)=>Kn(e,t,n),e.decodeAsync=async(t,n)=>Qn(e,t,n),e.safeEncode=(t,n)=>Xn(e,t,n),e.safeDecode=(t,n)=>er(e,t,n),e.safeEncodeAsync=async(t,n)=>tr(e,t,n),e.safeDecodeAsync=async(t,n)=>nr(e,t,n),sr(e,"ZodType",{check(...e){const t=this.def;return this.clone(M(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 D(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)})}(ps,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(U(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(U(r))}},e(t.value,t)),t);return n}(e,t)}(e,t))},overwrite(e){return this.check(On(e))},optional(){return ns(this)},exactOptional(){return new rs({type:"optional",innerType:this})},nullable(){return is(this)},nullish(){return ns(is(this))},nonoptional(e){return function(e,t){return new ls({type:"nonoptional",innerType:e,...R(t)})}(this,e)},array(){return Br(this)},or(e){return Jr([this,e])},and(e){return new Hr({type:"intersection",left:this,right:e})},transform(e){return fs(this,new es({type:"transform",transform:e}))},default(e){return t=e,new as({type:"default",innerType:this,get defaultValue(){return"function"==typeof t?t():E(t)}});var t},prefault(e){return t=e,new os({type:"prefault",innerType:this,get defaultValue(){return"function"==typeof t?t():E(t)}});var t},catch(e){return new ds({type:"catch",innerType:this,catchValue:"function"==typeof(t=e)?t:()=>t});var t},pipe(e){return fs(this,e)},readonly(){return new us({type:"readonly",innerType:this})},describe(e){const t=this.clone();return mn.add(t,{description:e}),t},meta(...e){if(0===e.length)return mn.get(this);const t=this.clone();return mn.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:()=>mn.get(e)?.description,configurable:!0}),e)),ar=m("_ZodString",(e,t)=>{nt.init(e,t),ir.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:l}=e._zod.bag;if("number"==typeof s&&(r.minLength=s),"number"==typeof i&&(r.maxLength=i),a&&(r.format=Tn[a]??a,""===r.format&&delete r.format,"time"===a&&delete r.format),l&&(r.contentEncoding=l),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,sr(e,"_ZodString",{regex(...e){return this.check(function(e,t){return new Ue({check:"string_format",format:"regex",...R(t),pattern:e})}(...e))},includes(...e){return this.check(function(e,t){return new We({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 Ke({check:"string_format",format:"ends_with",...R(t),suffix:e})}(...e))},min(...e){return this.check(zn(...e))},max(...e){return this.check(In(...e))},length(...e){return this.check(_n(...e))},nonempty(...e){return this.check(zn(1,...e))},lowercase(e){return this.check(function(e){return new He({check:"string_format",format:"lowercase",...R(e)})}(e))},uppercase(e){return this.check(function(e){return new Ve({check:"string_format",format:"uppercase",...R(e)})}(e))},trim(){return this.check(On(e=>e.trim()))},normalize(...e){return this.check(function(e){return On(t=>t.normalize(e))}(...e))},toLowerCase(){return this.check(On(e=>e.toLowerCase()))},toUpperCase(){return this.check(On(e=>e.toUpperCase()))},slugify(){return this.check(On(e=>function(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}(e)))}})}),or=m("ZodString",(e,t)=>{nt.init(e,t),ar.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)})}(cr,t)),e.url=t=>e.check(function(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...R(t)})}(pr,t)),e.jwt=t=>e.check(function(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...R(t)})}(Mr,t)),e.emoji=t=>e.check(function(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...R(t)})}(hr,t)),e.guid=t=>e.check(gn(fr,t)),e.uuid=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...R(t)})}(ur,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)})}(ur,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)})}(ur,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)})}(ur,t)),e.nanoid=t=>e.check(function(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...R(t)})}(mr,t)),e.guid=t=>e.check(gn(fr,t)),e.cuid=t=>e.check(function(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...R(t)})}(gr,t)),e.cuid2=t=>e.check(function(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...R(t)})}(br,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)})}(Or,t)),e.base64url=t=>e.check(function(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...R(t)})}($r,t)),e.xid=t=>e.check(function(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...R(t)})}(vr,t)),e.ksuid=t=>e.check(function(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...R(t)})}(kr,t)),e.ipv4=t=>e.check(function(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...R(t)})}(wr,t)),e.ipv6=t=>e.check(function(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...R(t)})}(Ir,t)),e.cidrv4=t=>e.check(function(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...R(t)})}(zr,t)),e.cidrv6=t=>e.check(function(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...R(t)})}(_r,t)),e.e164=t=>e.check(function(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...R(t)})}(Sr,t)),e.datetime=t=>e.check(Pn(t)),e.date=t=>e.check(Rn(t)),e.time=t=>e.check(Bn(t)),e.duration=t=>e.check(Fn(t))});function lr(e){return function(e,t){return new e({type:"string",...R(t)})}(or,e)}var dr=m("ZodStringFormat",(e,t)=>{rt.init(e,t),ar.init(e,t)}),cr=m("ZodEmail",(e,t)=>{at.init(e,t),dr.init(e,t)}),fr=m("ZodGUID",(e,t)=>{st.init(e,t),dr.init(e,t)}),ur=m("ZodUUID",(e,t)=>{it.init(e,t),dr.init(e,t)}),pr=m("ZodURL",(e,t)=>{ot.init(e,t),dr.init(e,t)}),hr=m("ZodEmoji",(e,t)=>{lt.init(e,t),dr.init(e,t)}),mr=m("ZodNanoID",(e,t)=>{dt.init(e,t),dr.init(e,t)}),gr=m("ZodCUID",(e,t)=>{ct.init(e,t),dr.init(e,t)}),br=m("ZodCUID2",(e,t)=>{ft.init(e,t),dr.init(e,t)}),yr=m("ZodULID",(e,t)=>{ut.init(e,t),dr.init(e,t)}),vr=m("ZodXID",(e,t)=>{pt.init(e,t),dr.init(e,t)}),kr=m("ZodKSUID",(e,t)=>{ht.init(e,t),dr.init(e,t)}),wr=m("ZodIPv4",(e,t)=>{vt.init(e,t),dr.init(e,t)}),Ir=m("ZodIPv6",(e,t)=>{kt.init(e,t),dr.init(e,t)}),zr=m("ZodCIDRv4",(e,t)=>{wt.init(e,t),dr.init(e,t)}),_r=m("ZodCIDRv6",(e,t)=>{It.init(e,t),dr.init(e,t)}),Or=m("ZodBase64",(e,t)=>{_t.init(e,t),dr.init(e,t)}),$r=m("ZodBase64URL",(e,t)=>{Ot.init(e,t),dr.init(e,t)}),Sr=m("ZodE164",(e,t)=>{$t.init(e,t),dr.init(e,t)}),Mr=m("ZodJWT",(e,t)=>{St.init(e,t),dr.init(e,t)}),jr=m("ZodNumber",(e,t)=>{Mt.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=n,{minimum:s,maximum:i,format:a,multipleOf:o,exclusiveMaximum:l,exclusiveMinimum:d}=e._zod.bag;"string"==typeof a&&a.includes("int")?r.type="integer":r.type="number";const c="number"==typeof d&&d>=(s??Number.NEGATIVE_INFINITY),f="number"==typeof l&&l<=(i??Number.POSITIVE_INFINITY),u="draft-04"===t.target||"openapi-3.0"===t.target;c?u?(r.minimum=d,r.exclusiveMinimum=!0):r.exclusiveMinimum=d:"number"==typeof s&&(r.minimum=s),f?u?(r.maximum=l,r.exclusiveMaximum=!0):r.exclusiveMaximum=l:"number"==typeof i&&(r.maximum=i),"number"==typeof o&&(r.multipleOf=o)})(e,t,n),sr(e,"ZodNumber",{gt(e,t){return this.check(vn(e,t))},gte(e,t){return this.check(kn(e,t))},min(e,t){return this.check(kn(e,t))},lt(e,t){return this.check(bn(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(Ar(e))},safe(e){return this.check(Ar(e))},positive(e){return this.check(vn(0,e))},nonnegative(e){return this.check(kn(0,e))},negative(e){return this.check(bn(0,e))},nonpositive(e){return this.check(yn(0,e))},multipleOf(e,t){return this.check(wn(e,t))},step(e,t){return this.check(wn(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)})}(jr,e)}var Nr=m("ZodNumberFormat",(e,t)=>{jt.init(e,t),jr.init(e,t)});function Ar(e){return function(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...R(t)})}(Nr,e)}var Tr=m("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 Er(e){return function(e,t){return new e({type:"boolean",...R(t)})}(Tr,e)}var Cr=m("ZodUnknown",(e,t)=>{Nt.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(e,t,n)=>{}});function Pr(){return new Cr({type:"unknown"})}var Dr=m("ZodNever",(e,t)=>{At.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)})}(Dr,e)}var Zr=m("ZodArray",(e,t)=>{Et.init(e,t),ir.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=Mn(i.element,t,{...r,path:[...r.path,"items"]})})(e,t,n,r),e.element=t.element,sr(e,"ZodArray",{min(e,t){return this.check(zn(e,t))},nonempty(e){return this.check(zn(1,e))},max(e,t){return this.check(In(e,t))},length(e,t){return this.check(_n(e,t))},unwrap(){return this.element}})});function Br(e,t){return function(e,t,n){return new e({type:"array",element:t,...R(n)})}(Zr,e,t)}var Lr=m("ZodObject",(e,t)=>{Zt.init(e,t),ir.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 d in a)s.properties[d]=Mn(a[d],t,{...r,path:[...r.path,"properties",d]});const o=new Set(Object.keys(a)),l=new Set([...o].filter(e=>{const n=i.shape[e]._zod;return"input"===t.io?void 0===n.optin:void 0===n.optout}));l.size>0&&(s.required=Array.from(l)),"never"===i.catchall?._zod.def.type?s.additionalProperties=!1:i.catchall?i.catchall&&(s.additionalProperties=Mn(i.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):"output"===t.io&&(s.additionalProperties=!1)})(e,t,n,r),$(e,"shape",()=>t.shape),sr(e,"ZodObject",{keyof(){return Kr(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:Pr()})},loose(){return this.clone({...this._zod.def,catchall:Pr()})},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 D(e,M(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return S(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 D(e,M(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return S(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 D(e,M(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return S(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 D(e,M(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 S(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 D(e,M(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 S(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 D(t,M(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 S(this,"shape",s),s},checks:[]}))}(ts,this,e[0])},required(...e){return t=ls,n=this,r=e[0],D(n,M(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 S(this,"shape",s),s}}));var t,n,r}})});function Fr(e,t){return new Lr({type:"object",shape:e??{},...R(t)})}function qr(e,t){return new Lr({type:"object",shape:e,catchall:Rr(),...R(t)})}var Gr=m("ZodUnion",(e,t)=>{Lt.init(e,t),ir.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)=>Mn(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 Jr(e,t){return new Gr({type:"union",options:e,...R(t)})}var Ur=m("ZodDiscriminatedUnion",(e,t)=>{Gr.init(e,t),Ft.init(e,t)});var Hr=m("ZodIntersection",(e,t)=>{qt.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const s=e._zod.def,i=Mn(s.left,t,{...r,path:[...r.path,"allOf",0]}),a=Mn(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 Vr=m("ZodRecord",(e,t)=>{Ut.init(e,t),ir.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=Mn(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=Mn(i.keyType,t,{...r,path:[...r.path,"propertyNames"]})),s.additionalProperties=Mn(i.valueType,t,{...r,path:[...r.path,"additionalProperties"]});const l=a._zod.values;if(l){const e=[...l].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 Wr(e,t,n){return t&&t._zod?new Vr({type:"record",keyType:e,valueType:t,...R(n)}):new Vr({type:"record",keyType:lr(),valueType:e,...R(t)})}var Yr=m("ZodEnum",(e,t)=>{Ht.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=k(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 Yr({...t,checks:[],...R(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 Yr({...t,checks:[],...R(r),entries:s})}});function Kr(e,t){return new Yr({type:"enum",entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...R(t)})}var Qr=m("ZodLiteral",(e,t)=>{Vt.init(e,t),ir.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 Xr(e,t){return new Qr({type:"literal",values:Array.isArray(e)?e:[e],...R(t)})}var es=m("ZodTransform",(e,t)=>{Wt.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 b(e.constructor.name);n.addIssue=r=>{if("string"==typeof r)n.issues.push(U(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(U(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 ts=m("ZodOptional",(e,t)=>{Kt.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>En(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});function ns(e){return new ts({type:"optional",innerType:e})}var rs=m("ZodExactOptional",(e,t)=>{Qt.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>En(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});var ss=m("ZodNullable",(e,t)=>{Xt.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const s=e._zod.def,i=Mn(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 is(e){return new ss({type:"nullable",innerType:e})}var as=m("ZodDefault",(e,t)=>{en.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const s=e._zod.def;Mn(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 os=m("ZodPrefault",(e,t)=>{nn.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const s=e._zod.def;Mn(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 ls=m("ZodNonOptional",(e,t)=>{rn.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const s=e._zod.def;Mn(s.innerType,t,r),t.seen.get(e).ref=s.innerType})(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});var ds=m("ZodCatch",(e,t)=>{an.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const s=e._zod.def;let i;Mn(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 cs=m("ZodPipe",(e,t)=>{on.init(e,t),ir.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;Mn(a,t,r),t.seen.get(e).ref=a})(e,t,0,r),e.in=t.in,e.out=t.out});function fs(e,t){return new cs({type:"pipe",in:e,out:t})}var us=m("ZodReadonly",(e,t)=>{dn.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const s=e._zod.def;Mn(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 ps=m("ZodCustom",(e,t)=>{un.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 hs,ms,gs,bs=lr().regex(/^[a-z]+$/,"aff ids are single lowercase words"),ys=lr().regex(/^[a-z][a-zA-Z]*$/,"balance ids are lowercase-led words"),vs=lr().regex(/^[a-z]+( [a-z]+)*$/,"cure ids are lowercase words separated by single spaces"),ks=lr().regex(/^[a-z]+$/,"venom ids are single lowercase words"),ws=lr().regex(/^[a-z]+$/,"profession ids are single lowercase words"),Is=qr({shortName:lr().min(1),fg:lr(),bg:lr()}),zs={id:bs,display:Is.optional(),curesTo:bs.optional(),pseudo:Er().default(!1),curedLast:Er().default(!1),gatedBy:bs.optional()},_s=qr({...zs,kind:Xr("plain")}),Os=qr({...zs,kind:Xr("timed"),durationMs:xr().int().positive(),provenance:Kr(["verified","unverified"]).default("verified")}),$s=qr({atLeast:xr().int().positive(),removes:xr().int().positive()}),Ss=qr({...zs,kind:Xr("countable"),max:xr().int().positive(),cureSteps:Br($s).default([])}).superRefine((e,t)=>{let n=0;e.cureSteps.forEach((r,s)=>{r.atLeast<=n&&t.addIssue({code:"custom",path:["cureSteps",s,"atLeast"],message:"cure-step thresholds must be strictly ascending"}),r.atLeast>e.max&&t.addIssue({code:"custom",path:["cureSteps",s,"atLeast"],message:"cure-step thresholds cannot exceed the countable max"}),n=r.atLeast})}),Ms=(hs="kind",ms=[_s,Os,Ss],new Ur({type:"union",options:ms,discriminator:hs,...R(gs)})),js=Br(Ms).min(1).refine(e=>new Set(e.map(e=>e.id)).size===e.length,{message:"aff ids must be unique"}).superRefine((e,t)=>{const n=new Map(e.map(e=>[e.id,e]));e.forEach((e,r)=>{if(void 0===e.gatedBy)return;const s=n.get(e.gatedBy);s?(void 0!==s.gatedBy&&t.addIssue({code:"custom",path:[r,"gatedBy"],message:`gate '${e.gatedBy}' is itself gated — gates may not chain`}),"countable"===s.kind&&t.addIssue({code:"custom",path:[r,"gatedBy"],message:`gate '${e.gatedBy}' is countable — a gate must be a presence aff`})):t.addIssue({code:"custom",path:[r,"gatedBy"],message:`gate '${e.gatedBy}' is not an aff`})})}),xs=qr({fg:lr(),bg:lr()}),Ns=Wr(lr().min(1),xs),As=Wr(bs,Is),Ts=qr({delimiter:xs,label:xs}),Es=qr({info:xs,warning:xs,error:xs}),Cs=qr({up:xs,down:xs}),Ps=qr({bracket:xs,detail:xs,defence:Cs,tag:Ts,severity:Es}),Ds=qr({affs:As,chrome:Ps}),Rs=Ns.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"}}),Zs=Rs,Bs={addiction:{shortName:"add",...Zs.ferrum},aeon:{shortName:"ae",...Zs.cinnabar},agoraphobia:{shortName:"agor",...Zs.argentum},amnesia:{shortName:"amn",fg:"",bg:""},anorexia:{shortName:"ANO",...Zs.epidermal},asthma:{shortName:"AST",...Zs.aurum},blackout:{shortName:"bo",fg:"",bg:""},blindness:{shortName:"unb",...Zs.arsenic},bound:{shortName:"bnd",...Zs.writhe},brokenleftarm:{shortName:"la1",...Zs.mending},brokenleftleg:{shortName:"ll1",...Zs.mending},brokenrightarm:{shortName:"ra1",...Zs.mending},brokenrightleg:{shortName:"rl1",...Zs.mending},bruisedribs:{shortName:"ribs",fg:"",bg:""},burning:{shortName:"burn",...Zs.mending},calcifiedskull:{shortName:"calh",...Zs.restoration},calcifiedtorso:{shortName:"calt",...Zs.restoration},claustrophobia:{shortName:"clau",...Zs.stannum},cleanseaura:{shortName:"cleanse",fg:"",bg:""},clumsiness:{shortName:"clu",...Zs.aurum},concussion:{shortName:"conc",...Zs.restoration},confusion:{shortName:"con",...Zs.stannum},corruption:{shortName:"corr",fg:"",bg:""},crackedribs:{shortName:"cr",...Zs.health},crushedthroat:{shortName:"cru",...Zs.mending},daeggerimpale:{shortName:"daeg",...Zs.writhe},damagedleftarm:{shortName:"la2",...Zs.restoration},damagedleftleg:{shortName:"ll2",...Zs.restoration},damagedrightarm:{shortName:"ra2",...Zs.restoration},damagedrightleg:{shortName:"rl2",...Zs.restoration},damagedhead:{shortName:"hd2",...Zs.restoration},darkshade:{shortName:"dark",...Zs.ferrum},dazed:{shortName:"dzd",...Zs.cinnabar},dazzled:{shortName:"dzl",...Zs.mending},deadening:{shortName:"dea",...Zs.cinnabar},deafness:{shortName:"und",...Zs.calamine},dehydrated:{shortName:"deh",fg:"",bg:""},dementia:{shortName:"dem",...Zs.stannum},depression:{shortName:"dep",...Zs.plumbum},deteriorate:{shortName:"det",fg:"",bg:""},disloyalty:{shortName:"disl",...Zs.realgar},disrupted:{shortName:"disr",fg:"",bg:""},dissonance:{shortName:"disso",...Zs.plumbum},dizziness:{shortName:"diz",...Zs.plumbum},enmesh:{shortName:"enmsh",...Zs.writhe},ensorcelled:{shortName:"ensor",fg:"",bg:""},entangled:{shortName:"entgl",...Zs.writhe},epilepsy:{shortName:"epi",...Zs.plumbum},fear:{shortName:"fear",fg:"",bg:""},flushings:{shortName:"flush",...Zs.ferrum},frostbite:{shortName:"frost",...Zs.caloric},frozen:{shortName:"frz",...Zs.caloric},fulminated:{shortName:"fulm",...Zs.plumbum},generosity:{shortName:"gen",...Zs.cuprum},grievouswounds:{shortName:"grv",...Zs.health},guilt:{shortName:"gui",...Zs.argentum},haemophilia:{shortName:"haem",...Zs.ferrum},hallucinations:{shortName:"hall",...Zs.stannum},hamstrung:{shortName:"hms",fg:"",bg:""},healthleech:{shortName:"hthl",...Zs.aurum},heartseed:{shortName:"heart",...Zs.restoration},hellsight:{shortName:"hell",...Zs.realgar},horror:{shortName:"hor",...Zs.argentum},hypersomnia:{shortName:"hypers",...Zs.stannum},hypochondria:{shortName:"hypoch",...Zs.argentum},hypothermia:{shortName:"hypoth",...Zs.restoration},icefisted:{shortName:"ice",fg:"",bg:""},impaled:{shortName:"impl",...Zs.writhe},impatience:{shortName:"IMPAT",...Zs.plumbum},indifference:{shortName:"ind",...Zs.cuprum},itching:{shortName:"itch",...Zs.epidermal},justice:{shortName:"just",...Zs.cuprum},kkractlebrand:{shortName:"kkr",...Zs.health},laceratedthroat:{shortName:"lac2",...Zs.restoration},latched:{shortName:"latch",...Zs.health},lethargy:{shortName:"let",...Zs.ferrum},lightbind:{shortName:"light",fg:"",bg:""},loneliness:{shortName:"lon",...Zs.argentum},lovers:{shortName:"love",...Zs.cuprum},manaleech:{shortName:"man",...Zs.realgar},mangledleftarm:{shortName:"la3",...Zs.restoration},mangledleftleg:{shortName:"ll3",...Zs.restoration},mangledrightarm:{shortName:"ra3",...Zs.restoration},mangledrightleg:{shortName:"rl3",...Zs.restoration},mangledhead:{shortName:"hd3",...Zs.restoration},masochism:{shortName:"maso",...Zs.argentum},mildtrauma:{shortName:"tor1",...Zs.restoration},mycalium:{shortName:"myc",...Zs.plumbum},nausea:{shortName:"nau",...Zs.ferrum},numbedleftarm:{shortName:"nbla",fg:"",bg:""},numbedrightarm:{shortName:"nbra",fg:"",bg:""},pacified:{shortName:"pac",...Zs.cuprum},palpatarfeed:{shortName:"worm",fg:"",bg:""},paralysis:{shortName:"PAR",...Zs.magnesium},paranoia:{shortName:"prn",...Zs.stannum},parasite:{shortName:"prs",...Zs.aurum},peace:{shortName:"pea",...Zs.cuprum},phlogisticated:{shortName:"phlog",fg:"",bg:""},pinshot:{shortName:"psh",fg:"",bg:""},pressure:{shortName:"pres",...Zs.calcite},prone:{shortName:"pr",fg:"",bg:""},pyramides:{shortName:"pyra",...Zs.magnesium},pyre:{shortName:"pyre",...Zs.cuprum},rebbies:{shortName:"reb",...Zs.aurum},recklessness:{shortName:"reck",...Zs.argentum},retribution:{shortName:"retr",...Zs.cuprum},revealed:{shortName:"rev",fg:"",bg:""},sandfever:{shortName:"sand",...Zs.plumbum},scalded:{shortName:"scald",...Zs.epidermal},scytherus:{shortName:"scy",...Zs.ferrum},selarnia:{shortName:"sel",...Zs.mending},sensitivity:{shortName:"sen",...Zs.aurum},serioustrauma:{shortName:"tor2",...Zs.restoration},shadowmadness:{shortName:"shad",...Zs.plumbum},shivering:{shortName:"shiv",...Zs.caloric},shyness:{shortName:"shy",...Zs.plumbum},skullfractures:{shortName:"sf",...Zs.health},slashedthroat:{shortName:"lac1",...Zs.epidermal},sleeping:{shortName:"slp",fg:"",bg:""},slickness:{shortName:"SLI",...Zs.magnesium},slimeobscure:{shortName:"slime",fg:"",bg:""},spiritburn:{shortName:"spirB",...Zs.argentum},spiritwrack:{shortName:"spirW",fg:"",bg:""},stupidity:{shortName:"st",...Zs.plumbum},stuttering:{shortName:"stut",...Zs.epidermal},homunculusmercury:{shortName:"merc",fg:"",bg:""},temperedcholeric:{shortName:"choH",...Zs.antimony},temperedmelancholic:{shortName:"melaH",...Zs.antimony},temperedphlegmatic:{shortName:"phleH",...Zs.antimony},temperedsanguine:{shortName:"sanH",...Zs.antimony},tenderskin:{shortName:"tend",...Zs.argentum},tension:{shortName:"tens",...Zs.cinnabar},timeflux:{shortName:"tmfx",fg:"",bg:""},timeloop:{shortName:"tmlp",...Zs.cuprum},tonguetied:{shortName:"tngt",...Zs.restoration},torntendons:{shortName:"tt",...Zs.health},transfixation:{shortName:"trfx",...Zs.writhe},unweavingbody:{shortName:"unwB",...Zs.ferrum},unweavingspirit:{shortName:"unwS",...Zs.cinnabar},unweavingmind:{shortName:"unwM",...Zs.plumbum},unblind:{shortName:"unB",fg:"",bg:""},undeaf:{shortName:"unD",fg:"",bg:""},unnamable:{shortName:"unnam",fg:"",bg:""},vertigo:{shortName:"vert",...Zs.argentum},vitrified:{shortName:"vitri",fg:"",bg:""},voidfisted:{shortName:"void",fg:"",bg:""},voyria:{shortName:"voy",fg:"",bg:""},weariness:{shortName:"wea",...Zs.aurum},webbed:{shortName:"web",...Zs.writhe},whisperingmadness:{shortName:"wmad",...Zs.argentum},wristfractures:{shortName:"wf",...Zs.health}},Ls=Ds.parse({affs:Bs,chrome:{bracket:{fg:"LightGoldenRodYellow",bg:""},detail:{fg:"darkgray",bg:""},defence:{up:{fg:"lime",bg:""},down:{fg:"red",bg:""}},tag:{delimiter:{fg:"#784695",bg:""},label:{fg:"#CBCE91",bg:""}},severity:{info:{fg:"#FFF2D7",bg:""},warning:{fg:"orange",bg:""},error:{fg:"red",bg:""}}}}),Fs=Ls.affs,qs=(Ls.chrome,new Set(["undeaf","unblind","cleanseaura","unnamable"])),Gs=new Map([["sensitivity","undeaf"]]),Js=new Set(["dissonance"]),Us=new Map([["mangledleftleg","damagedleftleg"],["mangledleftarm","damagedleftarm"],["mangledrightleg","damagedrightleg"],["mangledrightarm","damagedrightarm"],["mangledhead","damagedhead"],["serioustrauma","mildtrauma"],["damagedleftleg","brokenleftleg"],["damagedleftarm","brokenleftarm"],["damagedrightleg","brokenrightleg"],["damagedrightarm","brokenrightarm"]]),Hs=(e,t,n={})=>({id:e,kind:t,...n,...Us.has(e)?{curesTo:Us.get(e)}:{},...qs.has(e)?{pseudo:!0}:{},...Js.has(e)?{curedLast:!0}:{},...Gs.has(e)?{gatedBy:Gs.get(e)}:{},...Fs[e]?{display:Fs[e]}:{}}),Vs=js.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=>Hs(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])=>Hs(e,"timed",t)),...Object.entries({pressure:{max:5},crescendo:{max:5},unweavingbody:{max:5},unweavingspirit:{max:5},unweavingmind:{max:5},burning:{max:5},horror:{max:5,cureSteps:[{atLeast:3,removes:2}]},pyre:{max:3},temperedcholeric:{max:8},temperedmelancholic:{max:8},temperedphlegmatic:{max:8},temperedsanguine:{max:8},torntendons:{max:6},crackedribs:{max:6},skullfractures:{max:6},wristfractures:{max:6}}).map(([e,t])=>Hs(e,"countable",t))]),Ws=lr().regex(/^[a-z]+$/,"skill keys are single lowercase words"),Ys=qr({id:ws,skills:Br(Ws).default([])}),Ks=Br(Ys).min(1).refine(e=>new Set(e.map(e=>e.id)).size===e.length,{message:"profession ids must be unique"}),Qs=Ks.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:[]}]),Xs=Jr([bs,Br(bs).min(2)]),ei=qr({id:vs,command:lr().min(1),class:Kr(["linear","tree","special"]),order:Br(bs).default([]),ordered:Er().default(!1),layered:Er().default(!1),bals_used:Br(ys).default([]),bals_req:Br(ys).default([]),blocks:Br(Xs).default([]),professions:Br(ws).optional(),bestowable:Er().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"}),ti=Br(ei).min(1).refine(e=>new Set(e.map(e=>e.id)).size===e.length,{message:"cure ids must be unique"}),ni=["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"],ri=["death","anorexia","sleeping"],si=["death","asthma","sleeping"],ii=["death","slickness","sleeping"],ai=["death","sleeping","anorexia"],oi=[["brokenleftarm","brokenrightarm"],["brokenleftarm","damagedrightarm"],["brokenleftarm","mangledrightarm"],["damagedleftarm","brokenrightarm"],["damagedleftarm","damagedrightarm"],["damagedleftarm","mangledrightarm"],["mangledleftarm","brokenrightarm"],["mangledleftarm","damagedrightarm"],["mangledleftarm","mangledrightarm"]],li=["entangled","transfixation","impaled","webbed","bound"],di=["darkshade","haemophilia","lethargy","addiction","scytherus","nausea","flushings","unweavingbody"],ci=["paralysis","slickness","pyramides"],fi=["clumsiness","healthleech","sensitivity","weariness","asthma","rebbies","parasite"],ui=["undeaf","deafness"],pi=["horror","fratricide","masochism","loneliness","vertigo","recklessness","agoraphobia","guilt","whisperingmadness","spiritburn","tenderskin","hypochondria"],hi=["pacified","peace","lovers","justice","generosity","indifference","retribution","pyre","timeloop","diminished","stridulating"],mi=["temperedcholeric","temperedmelancholic","temperedphlegmatic","temperedsanguine"],gi=["unblind","blindness"],bi=["claustrophobia","paranoia","confusion","hypersomnia","hallucinations","dementia","crescendo"],yi=["stupidity","epilepsy","dizziness","shyness","impatience","dissonance","depression","sandfever","mycalium","shadowmadness","unweavingmind","fulminated"],vi=["pressure"],ki=["disloyalty","hellsight","manaleech","slickness"],wi=["aeon","dazed","deadening","tension","unweavingspirit","earworm"],Ii=(e,t,n={})=>({id:e,command:`eat ${e}`,class:"linear",order:t,bals_used:["herb"],bals_req:["herb"],blocks:ri,prio:0,...n}),zi=(e,t)=>({id:e,command:`smoke ${e}`,class:"linear",...t?{order:t}:{},bals_used:["smoke"],bals_req:["smoke"],blocks:si,prio:0}),_i=(e,t,n={})=>({id:e,command:`apply ${e}`,class:"linear",order:t,bals_used:["salve"],bals_req:["salve","restoration"],blocks:ii,prio:0,...n}),Oi=(e,t)=>({..._i(e,t),bals_used:["restoration"],delayMs:4e3}),$i=(e,t)=>({id:e,command:`apply ${e}`,class:"linear",order:t,bals_used:["sip"],bals_req:["sip"],prio:0}),Si=(e,t)=>({id:e,class:"tree",order:ni,prio:0,...t}),Mi=ti.parse([Ii("ferrum",di),Ii("magnesium",ci),Ii("aurum",fi),Ii("calamine",ui,{delayMs:2500}),Ii("argentum",pi),Ii("cuprum",hi),Ii("antimony",mi),Ii("arsenic",gi),Ii("stannum",bi),Ii("plumbum",yi,{class:"special"}),Ii("calcite",vi),Ii("ginseng",di),Ii("bloodroot",ci),Ii("kelp",fi),Ii("hawthorn",ui,{delayMs:2500}),Ii("lobelia",pi),Ii("bellwort",hi),Ii("ginger",mi),Ii("bayberry",gi),Ii("ash",bi),Ii("goldenseal",yi,{class:"special"}),Ii("pear",vi),{...zi("smoke",["aeon","disloyalty","hellsight","manaleech","slickness","deadening","tension","unweavingspirit","earworm"]),command:"smoke cinnabar"},zi("cinnabar",wi),zi("malachite"),zi("realgar",ki),zi("elm",wi),zi("skullcap"),zi("valerian",ki),_i("caloric",["frozen","shivering","frostbite"],{layered:!0}),_i("epidermal to body",["anorexia"]),_i("epidermal to head",["stuttering","blindness","deafness"]),_i("epidermal to ears",["deafness"]),_i("mending to head",["crushedthroat","dazzled"]),_i("mending to arms",["brokenleftarm","brokenrightarm"],{ordered:!0}),_i("mending to legs",["brokenleftleg","brokenrightleg"],{ordered:!0}),_i("mending to body",["burning"]),Oi("restoration to head",["mangledhead","damagedhead","calcifiedskull","concussion","tonguetied"]),Oi("restoration to torso",["hypothermia","heartseed","serioustrauma","mildtrauma","calcifiedtorso","internalbleeding"]),Oi("restoration to arms",["mangledleftarm","mangledrightarm","damagedleftarm","damagedrightarm"]),Oi("restoration to legs",["mangledleftleg","mangledrightleg","damagedleftleg","damagedrightleg"]),{id:"health",command:"sip health",class:"linear",bals_used:["sip"],bals_req:["sip"],blocks:ai,prio:0},{id:"mana",command:"sip mana",class:"linear",bals_used:["sip"],bals_req:["sip"],blocks:ai,prio:0},$i("health to head",["skullfractures"]),$i("health to torso",["crackedribs","grievouswounds"]),$i("health to arms",["wristfractures"]),$i("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},Si("bloodboil",{command:"cast bloodboil",bals_used:["equilibrium","bloodboil"],bals_req:["equilibrium","balance","bloodboil"],blocks:["death","haemophilia","sleeping",...oi,...li],professions:["magi"]}),{id:"dragonflex",command:"dragonflex",class:"linear",order:["webbed","entangled"],bals_used:["balance"],bals_req:["balance"],professions:["dragon"],prio:0},Si("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},Si("salt",{command:"educe salt",bals_used:["salt","equilibrium"],bals_req:["equilibrium","salt"],blocks:["death","stupidity","sleeping"],professions:["alchemist"]}),Si("siphon",{command:"siphon",bals_used:["angel"],bals_req:["angel"],blocks:["death","sleeping"],professions:["apostate","priest"]}),Si("shrugging",{command:"shrugging",bals_used:["shrugging"],bals_req:["equilibrium","balance","shrugging"],blocks:["death","weariness","sleeping"],professions:["serpent"]}),Si("slough",{command:"slough impurities",bals_used:["slough","balance"],bals_req:["equilibrium","balance","slough"],blocks:["death","weariness","sleeping"],professions:["firelord"]}),Si("fool",{command:"fling fool at me",bals_used:["fool","balance"],bals_req:["equilibrium","balance","fool"],blocks:["death","prone","paralysis","sleeping",...oi,...li],professions:["occultist"]}),Si("accelerate",{command:"chrono accelerate",bals_used:["accelerate","balance"],bals_req:["equilibrium","balance","accelerate"],blocks:["death","sleeping","recklessness"],professions:["depthswalker"]}),Si("alleviate",{command:"alleviate",bals_used:["alleviate","balance"],bals_req:["equilibrium","balance","alleviate"],blocks:["death","paralysis","sleeping"],professions:["blademaster"]}),Si("dagaz",{command:"sketch dagaz on ground",bals_used:["dagaz"],blocks:["death"],professions:["runewarden"],bestowable:!0}),Si("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:ai,prio:0},{id:"stand",command:"stand",class:"linear",order:["prone"],bals_req:["balance","equilibrium"],blocks:["death","sleeping","paralysis","brokenrightleg","brokenleftleg","damagedleftleg","damagedrightleg","mangledrightleg","mangledleftleg",...li],prio:0},Si("tree",{command:"touch tree",bals_used:["tree"],bals_req:["tree"],blocks:["death","sleeping","paralysis",...oi,...li]}),{id:"potash",command:"eat potash",class:"linear",bals_used:["moss"],bals_req:["moss"],blocks:ai,prio:0},{id:"moss",command:"eat moss",class:"linear",bals_used:["moss"],bals_req:["moss"],blocks:ai,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}]),ji=lr().regex(/^[a-z]+$/,"defence ids are single lowercase words"),xi=qr({stripDelayMs:xr().int().positive(),applyDelayMs:xr().int().positive(),blockedBy:Br(bs).min(1)}).refine(e=>new Set(e.blockedBy).size===e.blockedBy.length,{message:"blockedBy ids must be unique"}),Ni=Br(qr({id:ji,default:Er().default(!1),restore:xi.optional()})).min(1).refine(e=>new Set(e.map(e=>e.id)).size===e.length,{message:"defence ids must be unique"}),Ai=Ni.parse([{id:"speed",default:!0,restore:{stripDelayMs:2200,applyDelayMs:3e3,blockedBy:ai}},{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"}]),Ti=qr({affId:bs,observedDurationMs:xr().int().positive(),predictiveDurationMs:xr().int().positive()}),Ei=qr({id:ys,observedDurationMs:xr().int().positive(),predictiveDurationMs:xr().int().positive(),bufferPolicy:Kr(["buffered","exact"]),extendedBy:Br(Ti).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"}),Ci=Br(Ei).min(1).refine(e=>new Set(e.map(e=>e.id)).size===e.length,{message:"balance ids must be unique"}),Pi=e=>({predictiveDurationMs:e,observedDurationMs:Math.round(.75*e)}),Di=(e,t,n=[])=>({id:e,...Pi(t),bufferPolicy:"buffered",extendedBy:n.map(([e,t])=>({affId:e,...Pi(t)}))}),Ri=Ci.parse([Di("balance",2e3),Di("equilibrium",2e3),Di("sip",4500),Di("herb",1500),Di("smoke",1500),Di("salve",1e3),Di("restoration",4e3),Di("focus",2500,[["whisperingmadness",4e3],["weakenedmind",5e3]]),Di("tree",15e3),Di("moss",6e3),Di("immunity",1e4),Di("accelerate",1e4),Di("alleviate",1e4),Di("angel",1e4),Di("bloodboil",1e4),Di("dragonheal",2e4),Di("fitness",1e4),Di("fool",3e4),Di("rage",1e4),Di("salt",1e4),Di("shrugging",12e3),Di("slough",1e4),Di("dagaz",2e4),Di("voice",2500),Di("generic",12e3)]),Zi=Br(qr({id:bs,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"}),Bi=(e,t)=>t.map(t=>({id:t,level:1,prio:e})),Li=(e,t,n)=>Array.from({length:t},(t,r)=>({id:e,level:r+1,prio:n})),Fi=Zi.parse([...Bi(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"]),...Bi(2,["aeon","concussion","crushedthroat","paralysis","peace"]),...Bi(3,["sleeping","grievouswounds","latched","dazzled","weariness","prone","timeloop","fulminated"]),...Li("unweavingbody",5,3),...Li("unweavingmind",5,3),...Li("unweavingspirit",5,3),...Bi(4,["spiritburn","heartseed","guilt","tenderskin","pyramides","parasite","hypochondria","pacified","depression","confusion","retribution","shadowmadness","whisperingmadness","hellsight"]),...Bi(5,["anorexia","mycalium","flushings","rebbies","sandfever","asthma","healthleech"]),...Bi(6,["impatience","itching","scytherus","clumsiness","kkractlebrand","damagedleftleg","darkshade","slickness","recklessness","dementia","fratricide","icebound"]),...Bi(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},...Bi(8,["damagedrightleg","hypersomnia","earworm","diminished"]),...Li("skullfractures",6,8),...Li("crescendo",5,8),...Bi(9,["brokenleftleg","brokenrightleg","hallucinations"]),...Li("torntendons",6,9),...Bi(10,["calcifiedskull","calcifiedtorso","mangledleftleg","mangledrightleg","disrupted","mangledhead","voyria"]),...Li("crackedribs",6,10),...Bi(11,["hypothermia","impaled","brokenleftarm","brokenrightarm","indifference","addiction","nausea","deadening","frozen","shivering","mildtrauma","internalbleeding"]),...Bi(12,["stupidity","damagedleftarm","disloyalty"]),...Li("wristfractures",6,12),...Bi(13,["tension","damagedhead","dazed"]),...Li("burning",5,13),...Bi(14,["lovers","damagedrightarm","temperedcholeric","temperedmelancholic","temperedphlegmatic","temperedsanguine"]),...Li("pressure",5,14),...Bi(15,["mangledleftarm","mangledrightarm"]),...Bi(16,["agoraphobia","claustrophobia","generosity","justice","loneliness","vertigo"]),...Bi(17,["paranoia"]),...Bi(18,["serioustrauma","epilepsy"]),...Bi(20,["laceratedthroat","slashedthroat","stuttering"]),...Bi(21,["selarnia","fear","masochism"]),...Bi(23,["dizziness","shyness"]),...Li("horror",5,26),...Bi(30,["amnesia","blackout"]),...Bi(0,["insomnia","deafness","blindness"]),...Bi(100,["harmonic","bop","spiritwrack","bedevil","loki","moon","evileye","dragoncurse","swiftcurse"])]),qi=Br(bs).min(1).refine(e=>new Set(e).size===e.length,{message:"pool affliction ids must be unique"}),Gi=Br(qr({profession:ws,pools:Wr(lr().min(1),qi)})).min(1).refine(e=>new Set(e.map(e=>e.profession)).size===e.length,{message:"professions must be unique"}),Ji=Gi.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"]}}]),Ui=Br(qr({id:ks,aff:bs.nullable()})).min(1).refine(e=>new Set(e.map(e=>e.id)).size===e.length,{message:"venom ids must be unique"}),Hi=Ui.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"}]),Vi=new Map(Vs.map(e=>[e.id,e])),Wi=new Map(Mi.map(e=>[e.id,e])),Yi=new Map(Ri.map(e=>[e.id,e])),Ki=new Map(Ai.map(e=>[e.id,e])),Qi=Object.freeze(Object.fromEntries(Ai.filter(e=>e.default).map(({id:e})=>[e,!0]))),Xi=(()=>{const e=new Map;for(const t of Fi)e.has(t.id)||e.set(t.id,new Map),e.get(t.id).set(t.level,t.prio);return e})(),ea=(...e)=>new Set(Mi.filter(t=>t.bals_used.some(t=>e.includes(t))).map(e=>e.id)),ta=Object.freeze({layers:Object.freeze(Mi.filter(e=>e.layered).map(e=>Object.freeze([...e.order]))),curedLast:Object.freeze(Vs.filter(e=>e.curedLast).map(e=>Object.freeze({affId:e.id,pool:Object.freeze([...new Set(Mi.filter(t=>"tree"!==t.class&&t.order.includes(e.id)).flatMap(e=>e.order).filter(t=>t!==e.id))])})))}),na=e=>new Set(Mi.filter(t=>e.has(t.id)).flatMap(e=>e.order)),ra=na(ea("herb")),sa=na(ea("smoke")),ia=new Map(Hi.map(e=>[e.id,e.aff])),aa=new Map(Ji.map(e=>[e.profession,e.pools])),oa=(()=>{const e=new Map;for(const t of Qs)for(const n of t.skills)e.set(n,e.has(n)?null:t.id);return new Map([...e].filter(([,e])=>null!==e))})(),la=Object.freeze({epsilon:1e-4,forkCap:256}),da=(e,t)=>{if(!e)throw new Error(`insight engine: ${t}`)},ca=e=>Object.keys(e).sort().map(t=>`${t}=${!0===e[t]?"t":e[t]}`).join(","),fa=(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},ua=e=>Object.freeze({p:e.p,affs:Object.freeze({...e.affs})}),pa=e=>({p:e.p,affs:{...e.affs}}),ha=e=>{const t=e.reduce((e,t)=>e+t.p,0);if(da(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},ma=Object.freeze([]),ga=(e,t,{contradiction:n=!1}={})=>{da(Array.isArray(e)&&e.length>0,"finalizeForks needs at least one fork");const r=t?.growth??la;let s=(e=>{const t=new Map;for(const n of e){const e=ca(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=ha(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:ha(n),capDiagnostic:{type:"forkCapExceeded",beforeCount:e.length,afterCount:n.length,forkCap:t}}})(s,r.forkCap??la.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=fa(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??la.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(ua)),contradiction:n,diagnostics:a?Object.freeze([Object.freeze(a)]):ma}):{forks:s.map(pa),contradiction:n,diagnostics:a?[a]:ma}},ba=e=>!1===e.contradiction&&0===e.diagnostics.length,ya=(e,t)=>!0===t?.guards?Object.freeze({forks:Object.freeze(e.forks.map(ua)),contradiction:!0,diagnostics:e.diagnostics}):{forks:e.forks,contradiction:!0,diagnostics:e.diagnostics},va=({guards:e=!1}={})=>{const t={forks:[{p:1,affs:{}}],contradiction:!1,diagnostics:ma};return e?Object.freeze({...t,forks:Object.freeze(t.forks.map(ua))}):t},ka=e=>"countable"!==e.kind||1,wa=(e,t)=>{const n=e.affById.get(t);return da(n,`unknown affliction '${t}'`),n},Ia=(e,t)=>{if("afflicted"!==e.type)return e;const n=wa(t,e.affId).gatedBy;return void 0===n?e:{type:"afflictedOneOf",pool:[n,e.affId],mode:"ordered",...void 0===e.durationMs?{}:{durationMs:e.durationMs}}},za=Object.freeze(["uniform","firstMissing","ordered"]),_a=new Set,Oa=(e,t,n,r=_a)=>{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))},$a=(e,t,n)=>{const r=wa(n,t),s={...e};if("countable"===r.kind){const e=s[t]-((e,t)=>{let n=1;for(const r of e.cureSteps){if(r.atLeast>t)break;n=r.removes}return n})(r,s[t]);e<=0?delete s[t]:s[t]=e}else delete s[t];if(r.curesTo){const e=wa(n,r.curesTo);s[e.id]=ka(e)}return s},Sa=Object.freeze(["=","!=","<","<=",">",">="]),Ma=(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 da(!1,`unknown comparison operator '${t}'`),!1}},ja=Object.freeze({afflicted:(e,t,n)=>{const r=wa(n,t.affId),s="countable"!==r.kind||r.max;return ba(e)&&e.forks.every(e=>e.affs[r.id]===s)?e:ga(e.forks.map(e=>{const t={...e.affs};if("countable"===r.kind){const e=t[r.id]??0;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;da(Array.isArray(r)&&r.length>0,"afflictedOneOf needs a non-empty pool"),da(za.includes(s),`unknown afflictedOneOf mode '${s}'`);const i=new Map(r.map(e=>[e,wa(n,e)]));if(ba(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]=ka(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]:ka(i.get(t))}});continue}const t=o.p/e.length;for(const n of e)a.push({p:t,affs:{...o.affs,[n]:ka(i.get(n))}})}return ga(a,n)},advanced:(e,t,n)=>{da(Array.isArray(t.rungs)&&t.rungs.length>0,"advanced needs rungs");const r=new Set,s=new Map;for(const o of t.rungs){da(o&&"string"==typeof o.affId,"advanced rungs need an affId"),da(!r.has(o.affId),`advanced has duplicate rung '${o.affId}'`),r.add(o.affId),s.set(o.affId,wa(n,o.affId));for(const e of[...o.gains??[],...o.consumes??[]])s.set(e,wa(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 l={...e.affs};for(const{affId:t}of r)delete l[t];if(!o){n>=0&&delete l[t.rungs[n].affId];const e=t.rungs[n+1];l[e.affId]=ka(s.get(e.affId));for(const t of e.gains??[])l[t]=ka(s.get(t));for(const t of e.consumes??[])delete l[t]}return i=!0,{p:e.p,affs:l}});return!i&&ba(e)?e:ga(a,n)},cured:(e,t,n)=>{const r=((e,t)=>{const n=e.cureById.get(t);return da(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=Oa(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:$a(o.affs,r,n)})}return a?ga(i,n):e},confirmed:(e,t,n)=>{const r=wa(n,t.affId),{present:s}=t,i=e.forks.filter(e=>Object.hasOwn(e.affs,t.affId)===s);return i.length===e.forks.length&&ba(e)?e:i.length>0?ga(i.map(e=>({p:e.p,affs:e.affs})),n):ga(e.forks.map(e=>{const t={...e.affs};return s?t[r.id]=ka(r):delete t[r.id],{p:e.p,affs:t}}),n,{contradiction:!0})},confirmedBlocked:(e,t,n)=>{const r=wa(n,t.blockerId),{pool:s}=t;da(Array.isArray(s)&&s.length>0,"confirmedBlocked needs a non-empty pool");for(const a of s)wa(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&&ba(e)?e:i.length>0?ga(i.map(e=>({p:e.p,affs:e.affs})),n):ga(e.forks.map(e=>({p:e.p,affs:{...e.affs,[r.id]:e.affs[r.id]??ka(r)}})),n,{contradiction:!0})},confirmedCount:(e,t,n)=>{const{pool:r,op:s,n:i}=t;da(Array.isArray(r)&&r.length>0,"confirmedCount needs a non-empty pool"),da(Number.isInteger(i)&&i>=0,"confirmedCount needs an integer n >= 0");for(const d of r)wa(n,d);const a=e.forks.filter(e=>Ma((e=>r.reduce((t,n)=>t+(Object.hasOwn(e.affs,n)?1:0),0))(e),s,i));if(a.length===e.forks.length&&ba(e))return e;if(a.length>0)return ga(a.map(e=>({p:e.p,affs:e.affs})),n);let o=-1;for(let d=0;d<=r.length;d+=1)if(Ma(d,s,i)){if(-1!==o)return ya(e,n);o=d}if(0!==o&&o!==r.length)return ya(e,n);const l=0===o;return ga(e.forks.map(e=>{const t={...e.affs};for(const s of r)l?delete t[s]:Object.hasOwn(t,s)||(t[s]=ka(wa(n,s)));return{p:e.p,affs:t}}),n,{contradiction:!0})},confirmedCounts:(e,t,n)=>{const{counts:r}=t;da(Array.isArray(r)&&r.length>0,"confirmedCounts needs count entries");for(const i of r){da(i&&"object"==typeof i,"confirmedCounts needs count objects"),da(Array.isArray(i.pool)&&i.pool.length>0,"confirmedCounts needs non-empty pools"),da(Number.isInteger(i.n)&&i.n>=0,"confirmedCounts needs integer counts >= 0");for(const e of i.pool)wa(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&&ba(e)?e:s.length>0?ga(s.map(e=>({p:e.p,affs:e.affs})),n):ga([{p:1,affs:{}}],n,{contradiction:!0})},confirmedLevel:(e,t,n)=>{const{affId:r,op:s,n:i}=t,a=wa(n,r);da("countable"===a.kind,`confirmedLevel needs a countable aff, got '${r}'`),da(Number.isInteger(i)&&i>=0,"confirmedLevel needs an integer n >= 0");const o=e.forks.filter(e=>Ma((e=>Object.hasOwn(e.affs,r)?e.affs[r]:0)(e),s,i));if(o.length===e.forks.length&&ba(e))return e;if(o.length>0)return ga(o.map(e=>({p:e.p,affs:e.affs})),n);const l=((e,t)=>{switch(e){case"=":case"<=":case">=":return t;case"<":return t-1;case">":return t+1;default:return null}})(s,i);return null===l||l<0||l>a.max||!Ma(l,s,i)?ya(e,n):ga(e.forks.map(e=>{const t={...e.affs};return 0===l?delete t[r]:t[r]=l,{p:e.p,affs:t}}),n,{contradiction:!0})},converted:(e,t,n)=>{const r=wa(n,t.from),s=wa(n,t.to);return e.forks.some(e=>Object.hasOwn(e.affs,r.id))?ga(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=wa(n,t.affId);return ba(e)&&!e.forks.some(e=>Object.hasOwn(e.affs,r.id))?e:ga(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(da(Array.isArray(r),"predictedCure needs a forkBranches array"),0===r.length)return e;const s=new Map;for(const a of r)da(Number.isInteger(a?.forkIndex)&&a.forkIndex>=0&&a.forkIndex<e.forks.length,`predictedCure fork index '${a?.forkIndex}' is out of range`),da(!s.has(a.forkIndex),`predictedCure addresses fork ${a.forkIndex} twice`),da(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)da("number"==typeof n.weight&&Number.isFinite(n.weight)&&n.weight>0,`predictedCure option weight for '${n.affId}' must be a positive number`),da(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:$a(e.affs,s.affId,n)})}),ga(i,n)}}),xa=(Object.freeze(Object.keys(ja)),(e,t,n)=>0===t?0:t===n?1:e),Na=(e,t,n)=>{if(n<=0)return!0;if(n>t.length)return!1;let r=0;for(let s=0;s<t.length;s+=1){if(Object.hasOwn(e,t[s])&&(r+=1),r>=n)return!0;if(r+t.length-s-1<n)return!1}return!1},Aa=(e,t,n)=>{if(n>t.length)return!1;let r=0;for(let s=0;s<t.length;s+=1)if(Object.hasOwn(e,t[s])&&(r+=1),r>n||r+t.length-s-1<n)return!1;return r===n},Ta=e=>{switch(e){case"=":return(e,t)=>e===t;case"!=":return(e,t)=>e!==t;case"<":return(e,t)=>e<t;case"<=":return(e,t)=>e<=t;case">":return(e,t)=>e>t;case">=":return(e,t)=>e>=t}},Ea=(e,t,n,r,s)=>{const i=t.cache;i[n]!==t.epoch&&(i[n]=t.epoch,i[n+1]=0,i[n+2]=0);let a=i[n+1];const o=s+1;if(a<o){let t=i[n+2];const l=r.length;for(;t<l&&a<o&&a+l-t>=s;)Object.hasOwn(e,r[t])&&(a+=1),t+=1;i[n+1]=a,i[n+2]=t}return a},Ca=Symbol("true"),Pa=Symbol("false"),Da=()=>!0,Ra=()=>!1,Za=(e,t)=>{null===e.members&&(e.members=new Set(e.ids));for(let n=0;n<t.length;n+=1)if(!e.members.has(t[n]))return!1;return!0},Ba=(e,t,n)=>{const r=e.ids,s=n.slot,i=n.literal;if(e.cache<0){const e=(e=>{switch(e){case"=":return Aa;case"!=":return(e,t,n)=>!Aa(e,t,n);case"<":return(e,t,n)=>!Na(e,t,n);case"<=":return(e,t,n)=>!Na(e,t,n+1);case">":return(e,t,n)=>Na(e,t,n+1);case">=":return Na}})(t);return s<0?t=>e(t,r,i):(t,n)=>e(t,r,n.operands[s])}const a=Ta(t),o=e.cache;return s<0?(e,t)=>a(Ea(e,t,o,r,i),i):(e,t)=>{const n=t.operands[s];return a(Ea(e,t,o,r,n),n)}},La=(e,t,n,r)=>{if("all"===e.kind||"any"===e.kind){const s="any"===e.kind?Ca:Pa,i="any"===e.kind?Pa:Ca,a=t?[]:null;let o=0;for(const d of e.children){const e=La(d,t,n,r);if(e===s)return s;e!==i&&(o+=1,t&&a.push(e))}if(0===o)return i;if(!t)return null;if(1===o)return a[0];const l=a.length;return"all"===e.kind?(e,t)=>{for(let n=0;n<l;n+=1)if(!a[n](e,t))return!1;return!0}:(e,t)=>{for(let n=0;n<l;n+=1)if(a[n](e,t))return!0;return!1}}if("not"===e.kind){const s=La(e.child,t,n,r);return s===Ca?Pa:s===Pa?Ca:t?(e,t)=>!s(e,t):null}if("aff"===e.kind){const n=e.id;return t?e=>Object.hasOwn(e,n):null}if("count"===e.kind){const{ids:r,op:s,operand:i}=e;if(i.slot<0){const e=((e,t,n)=>{const r=Ta(e);if("="===e||"!="===e)return n>t?r(0,n):null;const s=r(0,n);return s===r(t,n)?s:null})(s,r.length,i.literal);if(null!==e)return e?Ca:Pa}const a=((e,t)=>{for(const n of e)if(n.ids.length===t.length&&(n.ids===t||Za(n,t)))return n;return null})(n,r);return t?Ba(a,s,i):(null===a?n.push({ids:r,members:null,cache:-1,refs:1}):a.refs+=1,null)}const{slot:s,op:i,operand:a}=e,o=((e,t,n,r)=>{for(const s of e)if(s.slot===t&&s.op===n&&s.operand.slot===r.slot&&(r.slot>=0||s.operand.literal===r.literal))return s;return null})(r,s,i,a);return t?(l=o.index,(e,t)=>{const n=t.conditions[l];return null!==n.affId&&Object.hasOwn(e,n.affId)?n.ifPresent:n.ifAbsent}):(null===o&&r.push({slot:s,op:i,operand:a,index:r.length}),null);var l},Fa=(e,t,n)=>{const r=Ma(e.ifPresent,t,n),s=Ma(e.ifAbsent,t,n);return{affId:r===s?null:e.affId,ifPresent:r,ifAbsent:s}},qa=(e,t)=>Object.hasOwn(e.affs,t),Ga=e=>{da(Array.isArray(e)&&e.length>0,"affliction projection needs a non-empty pool");const t=new Set;for(const n of e)da("string"==typeof n&&n.length>0,"affliction pool ids must be non-empty strings"),da(!t.has(n),`affliction pool contains duplicate '${n}'`),t.add(n)},Ja=(e,t)=>t.reduce((t,n)=>t+(qa(e,n)?1:0),0),Ua=(e,t)=>{let n=0,r=0;for(const s of e.forks)qa(s,t)&&(n+=s.p,r+=1);return xa(n,r,e.forks.length)},Ha=(e,t)=>{let n=!1,r=!1;for(const s of e.forks)if(qa(s,t)?n=!0:r=!0,n&&r)return null;return n},Va=(e,t)=>{Ga(t);let n=0,r=0;for(const s of e.forks)t.some(e=>qa(s,e))&&(n+=s.p,r+=1);return xa(n,r,e.forks.length)},Wa=(e,t)=>{Ga(t);let n=0,r=0;for(const s of e.forks)t.every(e=>qa(s,e))&&(n+=s.p,r+=1);return xa(n,r,e.forks.length)},Ya=(e,t)=>{Ga(t);let n=0;for(const r of e.forks)n+=r.p*Ja(r,t);return n},Ka=(e,t)=>{let n=0,r=0;for(const s of e.forks)if(qa(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},Qa=e=>{let t=0;for(const n of e.forks)n.p>0&&(t-=n.p*Math.log2(n.p));return t},Xa=Object.freeze(["healthy","damaged","mangled"]),eo=(e,t)=>{if(!e)throw new Error(`insight domain: ${t}`)},to=Object.freeze(["best","worst","distribution"]),no=["focus","herb","smoke","salve","restoration","sip","tree","balance","equilibrium"],ro=new WeakMap,so=(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)},io=(e,t)=>t.some(t=>Array.isArray(t)?t.every(t=>Object.hasOwn(e,t)):Object.hasOwn(e,t)),ao=(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)||io(e,t.blocks))return[];for(const o of Oa(e,t,r)){const n=so(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()]},oo=e=>e.reduce((e,t)=>t.prio<e.prio||t.prio===e.prio&&t.affId<e.affId?t:e),lo=e=>e.reduce((e,t)=>t.prio>e.prio||t.prio===e.prio&&t.affId<e.affId?t:e),co=(e,t,n,r)=>{eo(to.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 ao(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 l;l="best"===n?[{...oo(o),weight:1}]:"worst"===n?[{...lo(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 l)for(const e of t.balsUsed)i.add(e);s.push({forkIndex:a,options:l.map(({affId:e,weight:t})=>({affId:e,weight:t}))})}),0===s.length?null:{event:{type:"predictedCure",forkBranches:s},consumed:i}},fo=(Object.freeze(["pendingStrip","blocked","applying"]),aa.get("occultist").unnamable),uo=Object.freeze([...fo]),po=uo.length,ho=e=>(eo(Number.isInteger(e)&&e>=0&&e<=po,`unnamable curse count must be an integer in [0, ${po}] (got ${e})`),[{type:"confirmedCount",pool:[...uo],op:0===e?"=":"<=",n:po-e},...Array.from({length:e},()=>({type:"afflictedOneOf",pool:[...uo],mode:"firstMissing"}))]),mo=new Map([["unnamable",()=>ho(0)]]),go="whisperingmadness",bo="focus",yo=({belief:e,balance:t,usedAtMs:n})=>{const r=(({belief:e,balance:t,affId:n})=>{if(null!==Ha(e,n))return null;const r=Ua(e,n);eo(r>0&&r<1,"structurally uncertain affliction needs interior probability");const s=new Map;for(const l of t.extendedBy){if(l.affId===n)continue;const t=Ha(e,l.affId);if(null===t)return null;s.set(l.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:go});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,l=i-500,d=i+500;if(o>l)return null;const c=n+l;return{affId:go,...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:l,lateWindowEndMs:d}},vo=Object.freeze({stalenessHalfLifeMs:6e4,entropyScaleBits:Math.log2(la.forkCap)}),ko=(e,t={})=>{const n=t.stalenessHalfLifeMs??vo.stalenessHalfLifeMs,r=t.entropyScaleBits??(void 0===(s=t.forkCap)?vo.entropyScaleBits:Math.max(1,Math.log2(s)));var s;const i=Math.min(1,Qa(e.belief)/r),a=Math.max(0,e.now-e.lastObservedAt);return 1-(1-i)*(1-a/(a+n))},wo=(e,t={})=>Object.freeze({affId:e,...t.gains?{gains:Object.freeze(t.gains)}:{},...t.consumes?{consumes:Object.freeze(t.consumes)}:{}}),Io=Object.freeze({head:Object.freeze([wo("damagedhead",{gains:["stupidity"]}),wo("mangledhead",{gains:["stuttering","clumsiness"]})]),torso:Object.freeze([wo("mildtrauma"),wo("serioustrauma")]),leftarm:Object.freeze([wo("damagedleftarm",{consumes:["brokenleftarm"]}),wo("mangledleftarm")]),rightarm:Object.freeze([wo("damagedrightarm",{consumes:["brokenrightarm"]}),wo("mangledrightarm")]),leftleg:Object.freeze([wo("damagedleftleg",{consumes:["brokenleftleg"]}),wo("mangledleftleg")]),rightleg:Object.freeze([wo("damagedrightleg",{consumes:["brokenrightleg"]}),wo("mangledrightleg")])}),zo=Object.freeze(Object.keys(Io)),_o=Object.freeze(new Map(Object.entries(Io).flatMap(([e,t])=>t.map(t=>[t.affId,e])))),Oo=e=>{const t=Io[e];return eo(t,`unknown limb '${e}'`),t},$o=(e,t)=>((e,t)=>{da(Array.isArray(t)&&2===t.length,"ladder projection needs two rungs");const n={healthy:0,damaged:0,mangled:0},r={healthy:0,damaged:0,mangled:0};for(const i of e.forks){let e=-1;for(let n=0;n<t.length;n+=1)qa(i,t[n].affId)&&(e=n);const s=Xa[e+1];n[s]+=i.p,r[s]+=1}for(const i of Xa)n[i]=xa(n[i],r[i],e.forks.length);const s=n.healthy+n.damaged+n.mangled;return 1!==s&&(n.healthy/=s,n.damaged/=s,n.mangled/=s),n})(e,Oo(t)),So=Object.freeze(["observed","simulated"]),Mo=zo,jo=Object.freeze(["hp","mana"]),xo=Object.freeze({policy:"distribution",predictionEnabled:!1,focusEnabled:!0,limbResetMs:18e4}),No=e=>{if(e&&"object"==typeof e&&!Object.isFrozen(e)){Object.freeze(e);for(const t of Object.keys(e))No(e[t])}return e},Ao=e=>{const t={};for(const[n,r]of[...e].sort(([e],[t])=>e<t?-1:e>t?1:0))t[n]=r;return t},To=(e,t,n={})=>{eo("string"==typeof e&&e.length>0,"createOpponentModel needs an id"),eo(t?.affById&&t?.cureById&&t?.cureMasks,"createOpponentModel needs engine tables (affById, cureById, cureMasks)"),eo(t?.balanceById&&t?.priorityByAff,"createOpponentModel needs domain tables (balanceById, priorityByAff)"),eo(t?.defenceById&&t?.defenceDefaults,"createOpponentModel needs defence tables (defenceById, defenceDefaults)");const r={...xo,...n};eo(to.includes(r.policy),`unknown predictive policy '${r.policy}'`);const s=!0===r.guards,i=(e=>{const t=ro.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([...no.filter(e=>n.has(e)),...[...n.keys()].filter(e=>!no.includes(e)).sort()]),s=Object.freeze({curesByChannel:n,channelOrder:r});return ro.set(e,s),s})(t);let a=va({guards:s}),o=0,l=0,d="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(Mo.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},j=()=>{l!==o&&(l=o,S+=1)},x=()=>{if(_&&(_=!1,z.size>0)){const e=ie();for(const t of[...z])t(e)}},N=(({tables:e,getNow:t,isBlocked:n,onChange:r})=>{eo(e?.defenceById&&e?.defenceDefaults,"defence state needs defence tables"),eo("function"==typeof t,"defence state needs a clock read"),eo("function"==typeof n,"defence state needs a blocker predicate"),eo("function"==typeof r,"defence state needs a change callback");const s=new Map,i=new Map,a=t=>{eo("string"==typeof t&&t.length>0,"defence operation needs a def id");const n=e.defenceById.get(t);return eo(n,`unknown defence '${t}'`),n},o=(e,n,i=t())=>{const a={have:!0===n,atMs:i};var o,l;o=s.get(e),l=a,(o?.have!==l.have||o?.atMs!==l.atMs)&&(s.set(e,a),r())},l=(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())},d=e=>{i.delete(e)&&r()},c=(e,r,s,i)=>{n(r.blockedBy)?l(e,{phase:"blocked",stripAt:s,restoreAt:null,stripConfirmed:i}):l(e,{phase:"applying",stripAt:s,restoreAt:t()+r.applyDelayMs,stripConfirmed:i})},f=()=>{s.clear(),i.clear();for(const n of Object.keys(e.defenceDefaults))s.set(n,{have:!0,atMs:t()})};return f(),Object.freeze({have:e=>(a(e),!0===s.get(e)?.have),confirm(e,n){const r=a(e);eo("boolean"==typeof n,"defence confirmation needs a boolean");const s=i.get(e);if("pendingStrip"===s?.phase){if(n&&t()<s.stripAt)return;if(!n)return o(e,!1),void c(e,r.restore,t(),!1)}n||"applying"!==s?.phase&&"blocked"!==s?.phase?(o(e,n),d(e)):o(e,!1)},raise(e){a(e),o(e,!0),d(e)},strip(e){const n=a(e),r=s.get(e),l=i.get(e);!1===r?.have&&!0===l?.stripConfirmed||(o(e,!1),n.restore?c(e,n.restore,t(),!0):d(e))},startStrip(e){const n=a(e);eo(n.restore?.stripDelayMs,`defence '${e}' has no delayed-strip policy`);const r=t()+n.restore.stripDelayMs;o(e,!1),l(e,{phase:"pendingStrip",stripAt:r,restoreAt:r+n.restore.applyDelayMs,stripConfirmed:!1})},maintain(){for(const[r,s]of i){if("blocked"!==s.phase)continue;const i=e.defenceById.get(r).restore;n(i.blockedBy)||l(r,{...s,phase:"applying",restoreAt:t()+i.applyDelayMs})}},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;c(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),d(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:f})})({tables:t,getNow:()=>o,isBlocked:e=>((e,t)=>e.forks.every(e=>io(e.affs,t)))(a,e),onChange:M}),A=e=>{const n=t.balanceById.get(e);return eo(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)=>{Ga(t);const n=new Array(t.length+1).fill(0),r=new Array(t.length+1).fill(0);for(const s of e.forks){let e=-1;for(let n=0;n<t.length;n+=1)if(qa(s,t[n])){e=n;break}const i=e+1;n[i]+=s.p,r[i]+=1}for(let s=0;s<n.length;s+=1)n[s]=xa(n[s],r[s],e.forks.length);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(bo);eo(R&&Z,"focus timing needs canonical focus cure and balance rows");const B=()=>{null!==m&&(m=null,M())},L=()=>{if("observed"!==d||!0!==r.focusEnabled||!1!==Ha(a,"aeon")||!((e,t)=>e.forks.every(e=>!io(e.affs,t.blocks)))(a,R))return!1;const e=e=>"focus"===e||(p.get(e)??1/0)<=o;return a.forks.every(n=>ao(n.affs,R,{tables:t,opponentClass:u,isBalanceReady:e}).length>0)},F=()=>{!m||null===Ha(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(bo,e.usedAtMs+t);const n=[Z,...Z.extendedBy].find(e=>e.predictiveDurationMs===t);n&&E(bo,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)=>{eo(e?.affId===go,"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)=>{da(e&&Array.isArray(e.forks),"apply needs a Belief"),da(t&&"string"==typeof t.type,"apply needs an event with a type"),da(n?.affById&&n?.cureById&&n?.cureMasks,"apply needs tables"),da(ja[t.type],`unknown event type '${t.type}'`);const r=Ia(t,n),s=(0,ja[r.type])(e,r,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:r.type})))}):{forks:s.forks,contradiction:s.contradiction,diagnostics:s.diagnostics.map(e=>e.eventType?e:{...e,eventType:r.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=_o.get(t);if(r){const s=Ua(e,t);s>0&&Ua(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=_o.get(t);if(r){const s=Ua(e,t);s>0&&Ua(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===Ua(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=mo.get(r),i=void 0!==n&&"observed"===d&&b.has(r)&&1===Ua(a,r);if(W(r),Ua(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 l of i.channelOrder){const d=p.get(l);if(void 0===d||d>o)continue;const f=co(a,l,c,{tables:t,context:i,opponentClass:u,isBalanceReady:r});if(!f)continue;const h=a,m=H(f.event);n.push(...m.diagnostics),"focus"===l&&B();for(const e of f.consumed)D(e,h);e.push({atMs:o,channelId:l,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={},n={};for(const s of e.forks)for(const e of Object.keys(s.affs))t[e]=(t[e]??0)+s.p,n[e]=(n[e]??0)+1;const r=e.forks.length;for(const s of Object.keys(t))t[s]=xa(t[s],n[s],r);return t})(a),n={};for(const s of Object.keys(e).sort())n[s]="countable"===t.affById.get(s)?.kind?{probability:e[s],count:Ka(a,s)}:{probability:e[s]};const r={};for(const t of Mo)r[t]={percent:k.get(t).percent,stages:$o(a,t)};return{mode:d,policy:c,predictionEnabled:f,class:u,entropy:Qa(a),forkCount:a.forks.length,affs:n,expiries:Ao(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:Ao([...w.entries()].map(([e,t])=>[e,{...t}])),defs:Ao(N.snapshotEntries()),skillState:s?JSON.parse(JSON.stringify(I)):I}},ie=()=>{null===O&&(O=s?No(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:l,staleness:ko(le,{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?No(a):a},ae=e=>{if("focus"===e&&m){const e=m;return{affId:e.affId,ifPresent:Math.max(0,e.usedAtMs+e.durationIfPresentMs-o),ifAbsent:Math.max(0,e.usedAtMs+e.durationIfAbsentMs-o)}}const t=Math.max(0,(p.get(e)??0)-o);return{affId:null,ifPresent:t,ifAbsent:t}},oe=e=>{const t=k.get(e);return eo(t,`unknown limb '${e}'`),t},le={id:e,get revision(){return $},get timeEpoch(){return S},get now(){return o},get mode(){return d},get policy(){return c},get class(){return u},get lastObservedAt(){return l},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:t,ms:n})=>(A(e),eo("number"==typeof n&&Number.isFinite(n)&&n>=0,"balance remaining probability needs a non-negative finite ms"),((e,t,n,r)=>{const s=Fa(t,n,r);if(s.ifPresent===s.ifAbsent)return s.ifPresent?1:0;const i=Ua(e,s.affId);return s.ifPresent?i:1-i})(a,ae(e),t,n)),queryProbability:(e,t)=>{const n=e.balanceIds.map(ae);return((e,t,n,r)=>{const s=t.balanceConditions,i=new Array(s.length);for(let u=0;u<s.length;u+=1){const{slot:e,op:t,operand:a}=s[u];i[u]=Fa(r[e],t,a.slot<0?a.literal:n[a.slot])}const a=t.cacheSlots,o={operands:n,conditions:i,cache:a>0?new Int32Array(3*a):null,epoch:0},l=t.match,d=e.forks;let c=0,f=0;for(let u=0;u<d.length;u+=1)o.epoch=u+1,l(d[u].affs,o)&&(c+=d[u].p,f+=1);return xa(c,f,d.length)})(a,e,t,n)},getBalanceTimingInference:e=>(A(e),"focus"===e&&m?m:null),haveDef:N.have,getStat:e=>{eo(jo.includes(e),`unknown stat '${e}'`);const t=w.get(e);return t?{...t}:null},limbPercent:e=>oe(e).percent,limbStages:e=>(oe(e),$o(a,e)),getSkillState:()=>s?No(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=>{eo(e&&"string"==typeof e.type,"apply needs an event with a type"),eo("elapsed"!==e.type&&"predictedCure"!==e.type,`'${e.type}' is not an observation — it is produced by the simulation itself`);const n=Ia(e,t),r="cured"===n.type?t.cureById.get(n.cureId):null,i=void 0!==r?.delayMs,l=[];let d=!1;"cured"===n.type&&"focus"===n.cureId?G(l):m&&((e,t)=>"cured"===e.type?!0===t?.order.includes(go):"afflictedOneOf"===e.type?e.pool.includes(go):"converted"===e.type?"whisperingmadness"===e.from||"whisperingmadness"===e.to:["afflicted","removed","confirmed"].includes(e.type)&&"whisperingmadness"===e.affId)(n,r)&&B();const c=a,f=i?{contradiction:!1,diagnostics:[]}:H(n);switch(d||=f.contradiction,l.push(...f.diagnostics),n.type){case"afflicted":Y(n.affId,n.durationMs),u=n.affId,mo.has(u)&&g.has(u)&&1===Ua(a,u)&&b.add(u);break;case"afflictedOneOf":for(const e of n.pool)K(e,n.durationMs);break;case"confirmed":n.present&&(e=>{const n=t.affById.get(e);"timed"!==n?.kind||g.has(e)||V(e,o+n.durationMs)})(n.affId);break;case"converted":W(n.from),Y(n.to);break;case"cured":if(r){for(const e of r.bals_used)P(e,c);i&&((e,t)=>{y.push({atMs:o+t,sequence:v,event:{type:"cured",cureId:e.cureId,excludedAffs:[...e.excludedAffs??[]]}}),v+=1,M()})(n,r.delayMs),"focus"===r.id&&(e=>{if(!L())return;const t=yo({belief:e,balance:Z,usedAtMs:o});t&&(m=s?No(t):t,M())})(c)}}var u;return Q(),F(),j(),x(),{contradiction:d,diagnostics:l}},elapsed:e=>{eo("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=[],l=[],d=[],c=[];for(;;){X(n,c),ee(s,c),N.fireDue(i,a),te(l,c),ne(d,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 x(),{expired:n,resolvedCures:s,resolvedDefenceStrips:i,restoredDefs:a,predicted:l,timingConfirmations:d,diagnostics:c}},snapshot:ie,onChange:e=>(eo("function"==typeof e,"onChange needs a function"),z.add(e),()=>z.delete(e)),setMode(e){eo(So.includes(e),`unknown observation mode '${e}'`),d!==e&&(d=e,M()),"simulated"===e&&(b.clear(),B()),"observed"===e&&j(),x()},setPolicy(e){eo(to.includes(e),`unknown predictive policy '${e}'`),c!==e&&(c=e,M()),x()},enablePrediction(){f||(f=!0,M()),x()},disablePrediction(){f&&(f=!1,M()),x()},setClass(e,{source:t="observed"}={}){if("directory"===t&&null!==u)return;const n="string"==typeof e&&e.trim()?e.trim().toLowerCase():null;u!==n&&(u=n,M()),x()},consumeBalance(e,t){A(e),P(e,a,t),x()},setStat(e,t){eo(jo.includes(e),`unknown stat '${e}'`),eo("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()),x()},confirmDef(e,t){N.confirm(e,t),x()},raiseDef(e){N.raise(e),x()},stripDef(e){N.strip(e),x()},startDefStrip(e){N.startStrip(e),x()},hitLimb(e,t){eo("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()),x(),{advanced:r,percent:s}},resetLimb(e){const t=oe(e);0===t.percent&&null===t.lastHitAt||(t.percent=0,t.lastHitAt=null,M()),x()},updateSkillState(e){eo(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())}x()},reset(){a=va({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(),x()}};return Object.freeze(le)},Eo=/^[A-Za-z]+$/,Co=e=>{if("string"!=typeof e)return null;const t=e.trim();return t&&Eo.test(t)?t.toLowerCase():null},Po=(e={})=>{const{tables:t,...n}=e;eo(t,"createRosterModel needs config.tables");const r=!0===n.guards,s=new Map,i=new Map;let a=null,o=0;const l=new Set,d=new Set,c=()=>{if(o+=1,0===l.size)return;const e={ids:[...s.keys()],targetId:a};r&&(Object.freeze(e.ids),Object.freeze(e));for(const t of[...l])t(e)},f=e=>{let r=s.get(e);return r||(r=To(e,t,n),s.set(e,r),i.set(e,r.onChange(t=>{o+=1,((e,t)=>{for(const n of[...d])n(e,t)})(e,t)})),c()),r},u={track(e){const t=Co(e);if(!t)return null;const n=f(t);return n.setMode("observed"),n},untrack(e){const t=Co(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=Co(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=Co(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=Co(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&&(eo(to.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=>(eo("function"==typeof e,"onChange needs a function"),l.add(e),()=>l.delete(e)),onOpponentChange:e=>(eo("function"==typeof e,"onOpponentChange needs a function"),d.add(e),()=>d.delete(e))};return Object.freeze(u)},Do=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\.$/}),Ro=Object.freeze([Object.freeze({id:"asthma-blocks-smoke",blockerId:"asthma",balanceId:"smoke",pool:Object.freeze([...sa].sort()),evidence:/^\w+ takes a long drag off \w+ pipe\.$/}),Object.freeze({id:"anorexia-blocks-herb",blockerId:"anorexia",balanceId:"herb",pool:Object.freeze([...ra].sort()),evidence:/^\w+ eats a.+\.$/})]),Zo=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\.$/})]),Bo=aa.get("depthswalker"),Lo=[{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=Bo[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]}}],Fo={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"}]};Fo.plauge=Fo.plague;var qo={disorientation:[{type:"afflicted",affId:"dizziness"}],creeps:[{type:"afflicted",affId:"shyness"}],dissonance:[{type:"afflicted",affId:"dissonance"}]},Go=e=>(e.args.info??"").toLowerCase(),Jo=[{skill:"crystalism",id:"destabilise",handler:e=>(Fo[Go(e)]??[]).map(e=>({...e}))},{skill:"crystalism",id:"vibeTick",handler:e=>(qo[Go(e)]??[]).map(e=>({...e}))}],Uo=e=>(t,n,r)=>"thirdPerson"===t.matchType?e(t,n,r):[],Ho=(e,t)=>t.some(t=>e.have(t)),Vo={body:e=>e.have("anorexia")?[{type:"cured",cureId:"epidermal to body"}]:Ho(e,["hypothermia","heartseed","serioustrauma","mildtrauma","calcifiedtorso"])?[{type:"cured",cureId:"restoration to torso"}]:[{type:"cured",cureId:"mending to body"}],head:e=>Ho(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=>Ho(e,["damagedleftarm","damagedrightarm","mangledleftarm","mangledrightarm"])?[{type:"cured",cureId:"restoration to arms"}]:[{type:"cured",cureId:"mending to arms"}],legs:e=>Ho(e,["damagedleftleg","damagedrightleg","mangledleftleg","mangledrightleg"])?[{type:"cured",cureId:"restoration to legs"}]:[{type:"cured",cureId:"mending to legs"}],skin:e=>Ho(e,["frozen","shivering","frostbite"])?[{type:"cured",cureId:"caloric"}]:[{type:"defRaised",defId:"insulation"}]};Vo.torso=Vo.body;var Wo=[{skill:"curing",id:"apply",handler:Uo((e,t,n)=>{const r=(e.args.info??"").toLowerCase();return Vo[r]?Vo[r](n):[]})},{skill:"curing",id:"health",handler:Uo(e=>{const t=`health to ${(e.args.info??"").toLowerCase()}`;return Wi.has(t)?[{type:"cured",cureId:t}]:[]})},{skill:"curing",id:"smoke",handler:Uo((e,t,n)=>Ho(n,["aeon","deadening","tension","unweavingspirit"])?[{type:"cured",cureId:"cinnabar"}]:Ho(n,["disloyalty","hellsight","manaleech","slickness"])?[{type:"cured",cureId:"realgar"}]:[])},{skill:"curing",id:"focus",handler:Uo(()=>[{type:"cured",cureId:"focus"}])},{skill:"tattoos",id:"tree",handler:Uo(()=>[{type:"cured",cureId:"tree"}])},{skill:"tattoos",id:"shield",handler:Uo(()=>[{type:"defRaised",defId:"shield"}])},{skill:"defense",id:"prismatic",handler:Uo(()=>[{type:"defRaised",defId:"prismatic"}])},{skill:"venom",id:"shrugging",handler:Uo(()=>[{type:"cured",cureId:"shrugging"}])}],Yo=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\.$/}),Ko=(e,t,n)=>({id:`affConfirms.${e}`,pattern:n,lifetime:"session",actor:1,handler:()=>[{type:"confirmed",affId:t,present:!0}]}),Qo=(e,t,n)=>({id:`affConfirms.${e}`,pattern:n,lifetime:"session",actor:1,handler:()=>[{type:"afflicted",affId:t}]}),Xo=[Qo("confusion","confusion",Yo.confusion),Qo("dementia","dementia",Yo.dementia),Qo("paralysis1","paralysis",/^Horror overcomes the face of (\w+?) as \w+ body locks in paralysis\.$/),Qo("paralysis2","paralysis",/^Horror overcomes (\w+)'s face as \w+ body stiffens into paralysis\.$/),Qo("hypersomnia","hypersomnia",/^(\w+) suddenly appears tired all of a sudden\.$/),Qo("impatience","impatience",/^(\w+) shuffles \w+ feet in boredom\.$/),Ko("agoraphobia","agoraphobia",Yo.agoraphobia),Ko("claustrophobia","claustrophobia",Yo.claustrophobia),Ko("darkshade","darkshade",/^(\w+) lets out a piercing scream, as if wounded by the very sunlight\.$/),Ko("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"}]},Ko("masochism1","masochism",/^(\w+) smiles as \w+ rams \w+ fist into \w+ jaw\.$/),Ko("masochism2","masochism",/^(\w+) uses \w+ right foot to stomp on \w+ left as hard as possible\.$/),Ko("masochism3","masochism",/^With the heel of \w+ palm, (\w+) smacks \w+ upside the head\.$/),Ko("nausea","nausea",/^(\w+) doubles over, vomiting violently\.$/),Ko("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"}]},Ko("shivering","shivering",/^(\w+) shivers particularly intensely\.$/),Ko("burning","burning",/^The fires consuming (\w+) diminish somewhat\.$/)],el=aa.get("occultist"),tl=/^Horror overcomes \w+'s face as \w+ body stiffens into paralysis\.$/,nl=["brokenrightarm","brokenleftarm","brokenrightleg","brokenleftleg"],rl=["asthma","slickness"],sl=el.chimera.filter(e=>"hallucinations"!==e),il=(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 sl)if(Co(Yo[e].exec(r.text)?.[1])===t)return e}return"hallucinations"},al=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},ol=[{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(tl)}]},{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:il(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:[...rl],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:[...nl],mode:"firstMissing"}]},{skill:"domination",id:"cronePrimebond",handler:()=>[{type:"afflictedOneOf",pool:[...nl],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=al(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=al(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:[...el.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"}]}],ll=[{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)=>dl(n)},{skill:"dragoncraft",id:"rendUntargeted",handler:(e,t,n)=>dl(n)},{skill:"dragoncraft",id:"tailsweepHit",handler:()=>[{type:"afflicted",affId:"prone"}]},{skill:"dragoncraft",id:"dragonheal",handler:e=>"thirdPerson"===e.matchType?[{type:"cured",cureId:"dragonheal"}]:[]}],dl=e=>{const t=e.skillState.envenom;if(!t)return[];const n=ia.get(t),r=[{type:"updateSkillState",patch:{envenom:null}}];return n&&r.unshift({type:"afflicted",affId:n}),r},cl=e=>`broken${(e??"").replace(/\s/g,"").toLowerCase()}`,fl=e=>e.haveDef("insulation")?[{type:"defStripped",defId:"insulation"}]:[{type:"afflictedOneOf",pool:["shivering","frozen"],mode:"ordered"}],ul=[{skill:"elementalism",id:"shalestormTick",handler:e=>[{type:"afflicted",affId:cl(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)=>fl(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)=>fl(n)},{skill:"elementalism",id:"resonanceAirMinor",handler:()=>[{type:"afflicted",affId:"asthma"}]},{skill:"elementalism",id:"resonanceAirModerate",handler:()=>[{type:"afflicted",affId:"sensitivity"}]},{skill:"elementalism",id:"resonanceAirMajor",handler:()=>[{type:"afflicted",affId:"healthleech"}]},{skill:"elementalism",id:"resonanceEarthMinor",handler:e=>[{type:"afflicted",affId:cl(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"}]}],pl=aa.get("occultist"),hl=Object.freeze({cloak:"cloak",speed:"speed",caloric:"insulation",frost:"temperence",levitation:"levitating",insomnia:"insomnia",kola:"kola"}),ml=/^pinchaura(?:\s|$)/i,gl=/^pinchaura\s+([A-Za-z]+)\s+([A-Za-z]+)$/i,bl=/^\[System\]: Running queued (.+?) command: (.+)/,yl=e=>[{type:"confirmedCounts",source:"readaura",counts:[{label:"physical",pool:[...pl.physicals],n:e.args.physical},{label:"mental",pool:[...pl.mentals],n:e.args.mental}]}],vl=e=>{const t=[{type:"confirmedCount",pool:[...pl.physicals,...pl.mentals],op:e.args.met?">=":"<",n:5}];return e.args.met&&t.push({type:"afflicted",affId:"enlightenment"}),t},kl=[{skill:"occultism",id:"pinchaura",handler:(e,t,n)=>{if("firstPerson"!==e.matchType)return[];const r=Co(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=bl.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=>ml.test(e));if(1!==t.length)return null;const n=gl.exec(t[0]);if(!n)return null;const r=hl[n[2].toLowerCase()];return r?{targetId:Co(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=>{const t=[{type:"statChanged",statId:"hp",delta:-.03},{type:"statChanged",statId:"mana",delta:-.03}],n=e.args.affs?.[0];return n&&t.push({type:"afflicted",affId:n}),t}},{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:()=>pl.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"}]}],wl=aa.get("psion"),Il=(e,t)=>e.args[t]??e.args.match?.groups?.[t],zl=[{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:[...wl.blast],op:"<",n:3}]},{skill:"weaving",id:"invert",handler:e=>{const t=Il(e,"old"),n=Il(e,"new");return t&&n?[{type:"converted",from:`unweaving${t}`,to:`unweaving${n}`}]:[]}}],_l=aa.get("depthswalker"),Ol=["depression","retribution","shadowmadness","parasite"],$l=e=>()=>[{type:"afflictedOneOf",pool:[...e],mode:"ordered"}],Sl=e=>()=>e.map(e=>({type:"confirmed",affId:e,present:!0})),Ml=e=>{const t=e.skillState.envenom;if(!t)return[];const n=ia.get(t),r=[{type:"updateSkillState",patch:{envenom:null}}];return n&&r.unshift({type:"afflicted",affId:n}),r},jl=[{skill:"shadowmancy",id:"reap",handler:(e,t,n)=>t.checkBlock("you corrupt the weapon's timestream.")?[]:Ml(n)},{skill:"shadowmancy",id:"cull",handler:(e,t,n)=>Ml(n)},{skill:"shadowmancy",id:"degeneration",handler:$l(_l.degeneration)},{skill:"shadowmancy",id:"degenerationFull",handler:Sl(_l.degeneration)},{skill:"shadowmancy",id:"depression",handler:$l(_l.depression)},{skill:"shadowmancy",id:"depressionFull",handler:()=>[...Sl(_l.depression)(),{type:"afflicted",affId:"anorexia"},{type:"afflicted",affId:"masochism"}]},{skill:"shadowmancy",id:"retribution",handler:$l(_l.retribution)},{skill:"shadowmancy",id:"retributionFull",handler:(e,t,n)=>{const r=Ol.reduce((e,t)=>e+n.probability(t),0);return[...Sl(_l.retribution)(),{type:"afflicted",affId:"anorexia"},{type:"afflicted",affId:"masochism"},{type:"statChanged",statId:"mana",delta:-.05*r}]}},{skill:"shadowmancy",id:"madness",handler:$l(_l.madness)},{skill:"shadowmancy",id:"madnessFull",handler:Sl(_l.madness)},{skill:"shadowmancy",id:"leach",handler:$l(_l.leach)},{skill:"shadowmancy",id:"leachFull",handler:Sl(_l.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}]}],xl=aa.get("occultist"),Nl=xl.moon.filter(e=>"claustrophobia"!==e&&"agoraphobia"!==e),Al=[{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")?[]:xl.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:[...Nl],mode:"firstMissing"}]}}],Tl=/^(\w+) stumbles, falling to the ground\.$/,El=[{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(Tl)?{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"}]}],Cl=e=>String(e).toLowerCase(),Pl=(e,t)=>`${Cl(e)}.${String(t).toLowerCase()}`,Dl=Object.freeze([...Lo,{skill:"artificing",id:"efreeti",handler:()=>[{type:"afflicted",affId:"burning"}]},{skill:"artificing",id:"stoneback",handler:()=>[{type:"defRaised",defId:"shield"}]},...Jo,...Wo,...ol,...ll,...ul,...kl,...zl,...jl,...Al,...El]),Rl=(e,t,n)=>({id:`classCures.${e}`,pattern:n,lifetime:"session",actor:1,handler:()=>[{type:"cured",cureId:t}]}),Zl=[Rl("sunTarot","dagaz",/^The globe of light illuminates (\w+) with its brilliance\.$/),Rl("runewardenSun","dagaz",/^A rune like a rising sun upon the ground flares, bathing (\w+) with healing magic\.$/),Rl("genericMist","generic",/^(\w+) is surrounded in a cool, refreshing mist\.$/),Rl("genericGlow","generic",/^A demonic crimson glow emanates from (\w+)\.$/),Rl("genericLeech","generic",/^Something pulses from within the chest of (\w+), and \w+ seems more vital\.$/)],Bl=(e,t,n)=>({id:`cureConfirms.${e}`,pattern:n,lifetime:"session",actor:1,handler:()=>[{type:"confirmed",affId:t,present:!1}]}),Ll=[{id:"cureConfirms.stand",pattern:/^(\w+) stands up\.$/,lifetime:"session",actor:1,handler:()=>[{type:"cured",cureId:"stand"}]},Bl("lovers","lovers",/^(\w+) shakes \w+ head and a look of clarity returns to \w+ eyes\.$/),Bl("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"}]},Bl("sileris","slickness",/^(\w+) applies a (?:quicksilver droplet|sileris berry) to \w+\.$/),Bl("shadowmadness","shadowmadness",/^Lucidity returns to the eyes of (\w+)\.$/),Bl("unweavingspirit","unweavingspirit",/^(\w+) seems suddenly unburdened, clarity reasserting itself upon \w+ features\.$/),Bl("unweavingmind","unweavingmind",/^The light behind the eyes of (\w+) reignites\.$/),Bl("unweavingbody","unweavingbody",/^(\w+) suddenly seems much more vital\.$/),Bl("bloodfire","bloodfire",/^The unnatural flames that burn upon the skin of (\w+) wink out\.$/)],Fl=(e,t)=>({id:`curatives.${e}`,pattern:t,lifetime:"session",actor:1,handler:()=>[{type:"cured",cureId:e}]}),ql=[Fl("antimony",/^(\w+) eats (?:a ginger root|an antimony flake)\.$/),Fl("argentum",/^(\w+) eats (?:a lobelia seed|an argentum flake)\.$/),Fl("arsenic",/^(\w+) eats (?:some bayberry bark|an arsenic pellet)\.$/),Fl("aurum",/^(\w+) eats (?:a piece of kelp|an aurum flake)\.$/),Fl("cuprum",/^(\w+) eats a (?:bellwort flower|cuprum flake)\.$/),Fl("ferrum",/^(\w+) eats a (?:ginseng root|ferrum flake)\.$/),Fl("magnesium",/^(\w+) eats a (?:bloodroot leaf|magnesium chip)\.$/),Fl("plumbum",/^(\w+) eats a (?:goldenseal root|plumbum flake)\.$/),Fl("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"}]}],Gl=(e,t,n)=>({id:`defences.${e}`,pattern:t,lifetime:"session",actor:1,handler:n}),Jl=[Gl("shieldHit1",/^A dizzying beam of energy strikes you as your attack rebounds off of (\w+)'s shield\.$/,()=>[{type:"defRaised",defId:"shield"}]),Gl("shieldHit2",/^The magical shield surrounding (\w+) makes that impossible\.$/,()=>[{type:"defRaised",defId:"shield"}]),Gl("sileris",/^A supple purple shell of sileris berry juice has formed around (\w+)\.$/,()=>[{type:"defRaised",defId:"fangbarrier"}]),Gl("silerisLost",/^The protective coating covering the skin of (\w+) sloughs off\.$/,()=>[{type:"afflicted",affId:"slickness"},{type:"defStripped",defId:"fangbarrier"}]),Gl("insomnia",/^(\w+) clenches \w+ fists and grits \w+ teeth\.$/,()=>[{type:"defRaised",defId:"insomnia"},{type:"confirmed",affId:"hypersomnia",present:!1}]),Gl("prismaticHit",/^Your attack is repelled by the prismatic barrier surrounding (\w+)\.$/,()=>[{type:"defRaised",defId:"prismatic"}]),Gl("prismaticLost",/^(\w+)'s prismatic barrier dissolves into nothing\.$/,()=>[{type:"defStripped",defId:"prismatic"}]),Gl("speedStripped",/^(\w+) suddenly seems less dexterous, \w+ reactions becoming noticeably slower\.$/,()=>[{type:"defStripped",defId:"speed"}])],Ul=e=>(e??"").replace(/\s/g,"").toLowerCase(),Hl=(e,t)=>Number(`${e}.${t}`),Vl=[{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:Ul(e[4]),percent:Hl(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:Ul(e[4]),percent:Hl(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:Ul(e[4]),percent:Hl(e[1],e[2])}]},{id:"prep.limbReset",pattern:/^(\w+) ceases to favour \w+ (.+)\.$/,lifetime:"session",actor:1,handler:e=>[{type:"limbReset",limbId:Ul(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:Ul(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"}]}],Wl=[{defId:"insomnia",pattern:/^\w+ has insomnia, and cannot easily go to sleep\.$/},{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\.$/}],Yl={id:"occultism.readaura",lifetime:"prompt",armedBy:{trigger:"skills.readauraStart"},initState:({actorId:e})=>({actorId:e,pendingDefs:Wl.map(({defId:e})=>e)}),captures:[...Wl.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)=>yl({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}}]},Kl=["paralysis","asthma","healthleech","haemophilia","sensitivity","clumsiness","weariness"],Ql={indigo:()=>[{type:"afflicted",affId:"stupidity"}],orange:()=>[{type:"afflicted",affId:"paralysis"}],violet:e=>e.haveDef("speed")?[{type:"defStripped",defId:"speed"}]:[{type:"afflicted",affId:"aeon"}]},Xl=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 Vi.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=>Ql[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"},...ho(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)=>vl({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)=>vl({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)=>vl({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=Vi.has(t)?t:`${t}madness`;return Vi.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 Vi.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 Kl.reduce((e,t)=>e+n.probability(t),0)>=4&&(r.push(...Xl(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)=>Xl(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 Ki.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])}]}],td=/^(\w+) pales as the blood drains from \w+ face\.$/,nd=(e,t,n)=>({id:e,lifetime:"prompt",armedBy:{skill:"occultism",id:t},initState:({observedIds:e})=>({exposed:[...e]}),captures:[{id:"pale",pattern:td,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}))}),rd=nd("occultism.unnamableSpeak","unnamableSpeak","undeaf"),sd=nd("occultism.unnamableVision","unnamableVision","unblind"),id=Object.freeze([...ql,...Zl,...Ll,...Xo,...Jl,...ed,...Vl,{id:"queues.queueTracker",pattern:/^\[System\]: Running queued (.+?) command: (.+)/,lifetime:"session",remember:e=>({queue:{name:e[1],text:e[2]}})}]),ad=Object.freeze([rd,sd,Yl]),od=(e,t)=>t instanceof RegExp?t.test(e):"string"==typeof t&&e.includes(t),ld=(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=Co(r);if(e&&e!==t)return e}return null},dd=e=>"string"==typeof e?e:"string"==typeof e?.name?e.name:null,cd=({adapter:e,publish:t,commandMemory:n=null,skills:r=null})=>{const s=[],i=new Map;let a=!1;const o=()=>Co(dd(e.gmcp.read("Char.Name"))),l=(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 od(t.text,e)}return!1},checkBlock:e=>i.some(t=>null!==t.text&&od(t.text,e)),queuedCommand:e=>{const t=e??a.lastQueue;return null===t?null:a.queues[t]??null}})})({...e.text.snapshot(),actorId:Co(t),timestampMs:e.clock.now(),commands:n?n.snapshot():null}),d=e=>{const n=Co(dd(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:l(ld(e,o()))})},f=t=>{if(a)for(const n of t){if("string"!=typeof n||""===n)continue;const t=Cl(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?Cl(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",d)),s.push(e.events.on("Room.RemovePlayer",e=>{const n=Co(dd(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=>Co(dd(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:l})},fd=new Set(["afflicted","afflictedOneOf","cured","confirmed","confirmedBlocked","confirmedCount","confirmedCounts","confirmedLevel","converted","removed"]),ud=e=>Math.min(1,Math.max(0,e)),pd=({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))},l=t=>{const n=Co(t)??e.targetId;return n?e.track(n):null},d=e=>(s(e.id),c(e)),c=e=>({id:e.id,class:e.class,have:t=>Ua(e.belief,t)>0,probability:t=>Ua(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,{source:t.source}),!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?Co(s.actorId)!==e.id:Co(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 l=(e=>e?Object.entries(Do).filter(([,t])=>!e.nextLine(t)).map(([e])=>e):[])(s);o(e,{type:"cured",cureId:i.id,excludedAffs:l}),n("insight.cure.observed",{id:e.id,cureId:i.id});for(const t of(({cure:e,view:t,context:n})=>{if(eo(e&&Array.isArray(e.order),"cureInferenceEvents needs a cure row"),eo(t&&"function"==typeof t.have&&"function"==typeof t.isBalanceReady,"cureInferenceEvents needs an opponent view"),!n)return[];const r=[];for(const s of Ro)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 Zo)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:Oo(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=l(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(!fd.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=l(e);return t?d(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(Pl(t.skill,t.id),t),a.add(Cl(t.skill))}},listDefinitions:()=>[...i.keys()],listSkills:()=>[...a],dispatchAction({action:e,context:t}){const n=i.get(Pl(e.skill,e.id));if(!n)return;const r=l(t?.actorId);if(!r)return;if("thirdPerson"===e.matchType){const t=oa.get(Cl(e.skill));t&&(s=e.args,a=r.id,[s.player,s.player?.id,s.user].some(e=>"string"==typeof e&&Co(e)===a))&&f(r,{type:"classObserved",class:t})}var s,a;const o=n.handler(e,t,d(r))??[];for(const i of o)h.observe({...i,id:r.id},t)}};return Object.freeze(h)},hd=({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)}})},md=(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})),gd=Object.freeze({"insight.ready":md("eventstream","locked",{},"Bootstrap reached READY."),"insight.target.changed":md("eventstream","locked",{id:"string | null"},"The tracked target changed (null = target cleared)."),"insight.opponent.tracked":md("eventstream","locked",{id:"string"},"An opponent entered observed tracking (new, or re-acquired after leaving the room)."),"insight.opponent.unobserved":md("eventstream","locked",{id:"string"},"A tracked opponent left observation; simulation continues on their belief."),"insight.opponent.removed":md("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":md("eventstream","locked",{id:"string",affId:"string",probability:"number"},"An affliction became present (marginal probability rose above zero) for an opponent."),"insight.aff.lost":md("eventstream","locked",{id:"string",affId:"string"},"An affliction left an opponent's belief (marginal probability returned to zero)."),"insight.def.got":md("eventstream","locked",{id:"string",defId:"string"},"A defence was observed present on an opponent."),"insight.def.lost":md("eventstream","locked",{id:"string",defId:"string"},"A defence was observed absent on an opponent."),"insight.affs.updated":md("eventstream","locked",{id:"string"},"Prompt-batched per-opponent change flush: this opponent's affliction state changed since the last flush."),"insight.opponent.updated":md("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":md("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":md("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":md("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":md("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":md("internal","experimental",{action:"object",context:"ObservationContext"},"Normalized nexSkills match action with its ingress-captured ObservationContext."),"insight.ingress.skillError":md("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":md("internal","experimental",{id:"string",match:"object",context:"ObservationContext"},"A trigger-pack pattern fired, with its ingress-captured ObservationContext."),"insight.ingress.target":md("internal","experimental",{id:"string | null"},"Normalized IRE.Target.Set."),"insight.ingress.room.entered":md("internal","experimental",{id:"string"},"GMCP Room.AddPlayer, self excluded."),"insight.ingress.room.left":md("internal","experimental",{id:"string"},"GMCP Room.RemovePlayer."),"insight.ingress.room.list":md("internal","experimental",{ids:"string[]"},"GMCP Room.Info occupancy resync, self excluded."),"insight.ingress.prompt":md("internal","experimental",{},"Host PromptEvent boundary — drives the prompt-batched flush."),"insight.display.flush":md("internal","experimental",{ids:"string[]"},"The prompt-batched flush completed for these dirty opponents — the display coordinator renders on this boundary."),"insight.display.changed":md("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":md("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":md("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":md("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).")}),bd=(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]=bd(s,t);return Object.freeze(n)},yd=({adapter:e,notice:t=()=>{}})=>{const n=hd(),r=(e,n,r)=>{t({text:`${e} failed — ${n} (${r?.message??String(r)})`,severity:"error"})},s=hd({onSubscriberError:({topic:e,cause:t})=>r("public event subscriber",e,t)}),i=e=>{const t=gd[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 l=bd(a);if(s.raise(t,l),"eventstream"===o.audience)try{e.events.raise(t,l)}catch(d){r("EventStream forward",t,d)}},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)}})})},vd=Object.freeze({safetyFlushMs:200}),kd=e=>`insight4.elapsed.${e}`,wd="insight4.flush.safety",Id=({adapter:e,roster:t,publisher:n,notice:r,safetyFlushMs:s=vd.safetyFlushMs})=>{const{publish:i}=n,a=new Map,o=new Set,l=new Set;let d=!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(kd(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(kd(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 l=s.elapsed(o);u(n,l.diagnostics),i("insight.scheduler.elapsed",{id:n,expired:l.expired,resolvedCures:l.resolvedCures,resolvedDefenceStrips:l.resolvedDefenceStrips,restoredDefs:l.restoredDefs,predicted:l.predicted}),p(n)}):e.clock.clearTimer(kd(n))},h=()=>{if(d=!1,e.clock.clearTimer(wd),0===o.size&&0===l.size)return;const t=[...o].sort(),n=[...l].sort();o.clear(),l.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=()=>{d||(d=!0,e.clock.setTimer(wd,s,h))},g=e=>{o.add(e),m()},b=e=>{l.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),l.delete(e),p(e)}),n.on("insight.ingress.prompt",h))},stop(){for(;f.length>0;)f.pop()();e.clock.clearTimer(wd),d=!1;for(const t of a.keys())e.clock.clearTimer(kd(t));a.clear(),o.clear(),l.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 l=r.elapsed(o);return u(n,l.diagnostics),l},getTimeEpoch:()=>c,reschedule:p,markDirty:e=>{g(e),b(e)},flush:h})},zd=({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=[],l=[],d=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=d(n),a=i.get(e);let o=!1,l=!1;a?a.mode!==s.mode&&(o=!0,l=!0,"observed"===s.mode?t("insight.opponent.tracked",{id:e}):t("insight.opponent.unobserved",{id:e})):(o=!0,l=!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,l=!0):(o=!0,l=!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,l=!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&&(l=!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&&(l=!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)&&(l=!0),a&&(f(a.stats,s.stats,e=>e.value)||f(a.limbs,s.limbs,e=>e.percent))&&(l=!0),i.set(e,s),o&&t("insight.model.changed",{id:e}),l&&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,d(n.snapshot()))}l.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(;l.length>0;)l.pop()()}})},_d=(e,t)=>"number"==typeof e?Co(t?.[e]):null,Od=({adapter:e,settings:t,safetyFlushMs:n,display:r,displaySink:s,notice:i=()=>{},guards:a})=>{const o=Object.freeze({affById:Vi,cureById:Wi,cureMasks:ta,balanceById:Yi,priorityByAff:Xi,defenceById:Ki,defenceDefaults:Qi,guards:!0===a,get growth(){return t.get().pruning}}),l=yd({adapter:e,notice:i}),{publish:d}=l;let c=0;const f=e=>(c+=1,d("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=Po({tables:o,guards:!0===a,policy:t.get().predictive.defaultPolicy,predictionEnabled:t.get().predictive.enabled}),m=Id({adapter:e,roster:h,publisher:l,notice:i,safetyFlushMs:n??t.get().display.safetyFlushMs}),g=pd({roster:h,tables:o,publish:d,notice:i,advanceToNow:m.advanceToNow}),b=zd({roster:h,publish:d,defenceDefaults:Qi}),y=r?(({publisher:e,roster:t,settings:n,display:r,sink:s})=>{const{renderTarget:i,renderRoster:a,displayTable:o}=r,l=[],d=(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(){l.push(e.on("insight.display.flush",({ids:e})=>{const r=t.snapshot(),s=n.get();r.targetId&&e.includes(r.targetId)&&d(r,s),c(r,s)}))},stop(){for(;l.length>0;)l.pop()()},refresh(){const e=t.snapshot(),r=n.get();d(e,r),c(e,r)}})})({publisher:l,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,l=[],d=e=>!0===n.get().display.notices&&t.targetId===e,c=e=>t=>{d(t.id)&&s({html:a({affId:t.affId,present:e},i,n.get())})},f=e=>t=>{d(t.id)&&s({html:o({defId:t.defId,present:e},i,n.get())})};return Object.freeze({start(){l.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(;l.length>0;)l.pop()()}})})({publisher:l,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=cd({adapter:e,publish:d,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:l}=r,d=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=Pl(e,t),r=f.get(n);r?r.push(z):f.set(n,[z]),u.add(Cl(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?_d(a,r):null,d=s(o);l("insight.ingress.trigger",{id:e.id,match:r,context:d});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,d,s),s.id,d)}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:_d(t.actor,r),o=s(a);l("insight.ingress.trigger",{id:`${e.id}.${t.id}`,match:r,context:o});const d=n.resolveView(a);d&&b(t.handler(r,o,d,i.state),d.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 d.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(Pl(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:()=>[...d.keys()],listArmed:()=>[...h.keys()],listArmingSkills:()=>[...u]})})({adapter:e,roster:h,router:g,publisher:l,capture:w.capture,commandMemory:k,sessionPacks:id,promptPacks:ad}),z=e=>{g.addDefinitions(e),w.observeSkills(g.listSkills())};z(Dl);const _=new Set,O=new Map;let $=!1;const S=({id:n})=>{const r=h.setTarget(n);if(!r||!t.get().classLookup||null!==r.class||_.has(r.id)||O.has(r.id))return;const s=Promise.resolve().then(()=>e.directory.read(r.id));O.set(r.id,s),s.then(e=>{if(_.add(r.id),$||null===e)return;const t=h.get(r.id);t&&null===t.class&&g.observe({type:"classObserved",class:e,source:"directory",id:r.id})}).catch(()=>{}).finally(()=>{O.get(r.id)===s&&O.delete(r.id)})},M=[],j=()=>{for($=!0,O.clear(),w.stop(),I.stop(),m.stop(),b.stop(),y?.stop(),v?.stop();M.length>0;)M.pop()()};try{b.start(),m.start(),y?.start(),v?.start(),M.push(l.on("insight.ingress.skill",g.dispatchAction),l.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"})),l.on("insight.ingress.target",S),l.on("insight.ingress.room.entered",({id:e})=>h.track(e)),l.on("insight.ingress.room.left",({id:e})=>h.untrack(e)),l.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)),l.on("insight.settings.changed",({document:e})=>h.updateDefaults({policy:e.predictive.defaultPolicy,predictionEnabled:e.predictive.enabled}))),I.start(),w.start()}catch(x){throw j(),x}return Object.freeze({roster:h,router:g,scheduler:m,registrar:I,publish:d,events:l.events,settings:p,getSettingsRevision:()=>c,display:y,observe:g.observe,addDefinitions:z,capture:w.capture,dispose:j})},$d=Object.freeze({schemaVersion:3,autoUpdate:!1,classLookup:!0,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:la.epsilon,forkCap:la.forkCap})}),Sd=Fr({threshold:xr().min(0).max(1).catch($d.display.threshold),shortNames:Er().catch($d.display.shortNames),colors:Er().catch($d.display.colors),notices:Er().catch($d.display.notices),showRoster:Er().catch($d.display.showRoster),safetyFlushMs:xr().int().min(0).max(1e4).catch($d.display.safetyFlushMs)}).catch({...$d.display}),Md=Fr({enabled:Er().catch($d.predictive.enabled),defaultPolicy:Kr(to).catch($d.predictive.defaultPolicy)}).catch({...$d.predictive}),jd=Fr({presenceFloor:xr().min(0).max(1).catch($d.queries.presenceFloor)}).catch({...$d.queries}),xd=Fr({epsilon:xr().positive().max(.1).catch($d.pruning.epsilon),forkCap:xr().int().min(1).catch($d.pruning.forkCap)}).catch({...$d.pruning}),Nd=Fr({schemaVersion:Xr(3).catch(3),autoUpdate:Er().catch($d.autoUpdate),classLookup:Er().catch($d.classLookup),display:Sd,predictive:Md,queries:jd,pruning:xd}).catch({schemaVersion:3,autoUpdate:$d.autoUpdate,classLookup:$d.classLookup,display:{...$d.display},predictive:{...$d.predictive},queries:{...$d.queries},pruning:{...$d.pruning}}),Ad=e=>{if(e&&"object"==typeof e&&!Object.isFrozen(e)){Object.freeze(e);for(const t of Object.keys(e))Ad(e[t])}return e},Td=e=>Ad(Nd.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:$d.pruning.forkCap}:{}}:e.pruning;return{...e,schemaVersion:3,pruning:t}})(e))),Ed=(e,{key:t="insightSettings"}={})=>{let n=Td(null);const r=(r=n)=>(e.storage.set(t,JSON.stringify(r)),n=r,r);return Object.freeze({get:()=>n,load:()=>(n=Td((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(Td({...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(Td({...n,display:{...n.display,...e}})),updatePredictive:(e={})=>r(Td({...n,predictive:{...n.predictive,...e}})),replace:e=>r(Td(e)),reset:()=>(n=Td(null),n),clear:()=>(e.storage.clear(t),n=Td(null),n)})},Cd=Object.freeze({forks:Object.freeze([])}),Pd=({roster:e,queryCompiler:t,events:n,settings:r,observe:s,capture:i,advanceToNow:a,reschedule:o,displayRendering:l,refreshDisplay:d,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?Ua(n.belief,t):0},v=(e,t,n)=>e(b(t)?.belief??Cd,n),k=(e,t)=>v(Va,e,t),w=(e,t)=>v(Wa,e,t),I=(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),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(),s=z(_({id:r.id,class:r.class,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:s}),s};let S=null,M=null;const j=()=>{const t={rosterRevision:e.revision,settingsRevision:h(),phaseRevision:p(),timeEpoch:m()};if(M?.rosterRevision===t.rosterRevision&&M.settingsRevision===t.settingsRevision&&M.phaseRevision===t.phaseRevision&&M.timeEpoch===t.timeEpoch)return S;const n={},s=[...e.list()].sort(),i=new Set(s);for(const r of s)n[r]=$(e.get(r),t.settingsRevision);for(const e of O.keys())i.has(e)||O.delete(e);return S=Object.freeze({system:Object.freeze({phase:u(),version:g}),target:e.targetId?n[e.targetId]??null:null,opponents:Object.freeze(n),settings:r.get()}),M=t,S},x=Object.freeze({get:()=>e.targetId,set:t=>{const n=e.setTarget(t??null);return n?n.id:null},is:t=>null!==e.targetId&&Co(t)===e.targetId}),N=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()}}),A=(e,t)=>String(e??"").trim().toLowerCase()===String(t??"").trim().toLowerCase(),T=Object.freeze({get:e=>b(e)?.class??null,is:(e,t)=>{if(void 0===e)return!0;if(!e)return!1;const n=b(t)?.class??"";return Array.isArray(e)?e.some(e=>A(n,e)):A(n,e)}}),E=Object.freeze({have:(e,t)=>I(y(t,e),t),haveAll:(e,t)=>I(w(t,e),t),haveAny:(e,t)=>I(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(Ya,e,t))(t,e)}),C=Object.freeze({create:e=>t.create(e),probability:(e,n)=>{const r=t.prepare(e),s=t.bind(r,n?.params);return b(n)?.queryProbability(r,s)??0}}),P=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}}),D=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})}),R=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={})=>{if(t&&"object"==typeof t&&Object.hasOwn(t,"affs"))throw new TypeError("balances.remainingProbability no longer accepts affs; use queries.probability for compound questions");const n=b(t);return n?n.balanceRemainingProbability(e,{op:t?.op,ms:t?.ms}):0}}),Z=(e,t={})=>{const{id:n,...r}=t;return s({type:e,...r,id:n},i(n??null))},B=Object.freeze({afflicted:e=>Z("afflicted",e),afflictedOneOf:({mode:e="firstMissing",...t}={})=>Z("afflictedOneOf",{mode:e,...t}),advanced:e=>Z("limbAdvance",e),cured:e=>Z("cured",e),confirmed:({present:e=!0,...t}={})=>Z("confirmed",{present:e,...t}),confirmedCount:e=>Z("confirmedCount",e),confirmedCounts:e=>Z("confirmedCounts",e),confirmedLevel:e=>Z("confirmedLevel",e),converted:e=>Z("converted",e),removed:e=>Z("removed",e)}),L=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}}),F=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 l.renderAffNotice({affId:n,present:i},l.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 l.renderDefNotice({defId:s,present:i},l.displayTable,a)}if(!["target","affState","statState"].includes(e))throw new TypeError(`unknown display view '${e}'`);const o=b({id:t});if(!o)return"";const d=o.snapshot();return"target"===e?l.renderTarget(d,l.displayTable,a):"affState"===e?l.renderAffState(d,l.displayTable,a):l.renderStatState(d,l.displayTable,a)},notice:(e,t)=>{c({html:e,severity:t})},refresh:()=>{d()},openDebug:()=>{f(l.renderDebug(j()))}}),q=Object.freeze({target:x,opponents:N,class:T,affs:E,queries:C,defs:P,limbs:D,balances:R,observe:B,simulate:L,display:F,settings:r}),G=Object.freeze(Object.fromEntries(Object.entries(gd).filter(([,e])=>"internal"!==e.audience))),J=Object.freeze({on:n.on,off:n.off,topics:G});return Object.freeze({get state(){return j()},api:q,events:J})},Dd=["head","torso","leftarm","rightarm","leftleg","rightleg"],Rd=e=>String(e).replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',"""),Zd=(e,t="",n="")=>{const r=[t?`color: ${t}`:"",n?`background: ${n}`:""].filter(Boolean).join("; ");return r?`<span style="${r}">${e}</span>`:`<span>${e}</span>`},Bd=(e,t="",n="")=>Zd(Rd(e),t,n),Ld=e=>e.charAt(0).toUpperCase()+e.slice(1),Fd=(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)),qd=(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:"",l=r.colors&&s?s.bg:"";return Bd(`${i}${a}`,o,l)},Gd=(e,t,n)=>{const r=n.display,{bracket:s}=t.chrome,i=[Bd("[",s.fg,s.bg)],a=Fd(e.affs,r.threshold);return a.forEach(([e,n],s)=>{i.push(qd(e,n,t,r));const o=s<a.length-1?", ":"";i.push(Bd(`: ${(e=>String(Math.round(100*e)/100))(n.probability)}${o}`))}),i.push(Bd("]",s.fg,s.bg)),i},Jd=[["hp","H"],["mana","M"]],Ud=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}%)`},Hd=(e,t)=>{const n=[],{detail:r}=t.chrome;for(const[s,i]of Jd){const t=e.stats?.[s];if(!t)continue;n.length>0&&n.push(Bd(" "));const a=Math.round(100*Math.min(1,Math.max(0,t.value)));n.push(Bd(`${i}:`,r.fg,r.bg)),n.push(Bd(`${a}%`,Ud(t.value)))}return n},Vd=(e,t,n,r,s)=>{const i=[Bd(`${n?"+":"-"}${e} `,n?"lime":"red")];if("aff"===e){const e=r.affs[t],n=s.display;i.push(Bd(Ld(t),n.colors&&e?e.fg:"",n.colors&&e?e.bg:""))}else i.push(Bd(Ld(t)));return i},Wd=({text:e="",html:t,severity:n="info"},r)=>{const s=r.chrome.severity,i=s[n]??s.info,a="string"==typeof t?Zd(t,i.fg,i.bg):Bd(e,i.fg,i.bg);return`<span class="mono">${(e=>{const{delimiter:t,label:n}=e.chrome.tag;return[Bd("<<",t.fg,t.bg),Bd("insight",n.fg,n.bg),Bd(">> ",t.fg,t.bg)]})(r).join("")}${a}</span>`},Yd=(e,t)=>{if(!e)throw new TypeError(`insight query: ${t}`)},Kd=e=>{if(null===e||"object"!=typeof e)return!1;const t=Object.getPrototypeOf(e);return null===t||t===Object.prototype},Qd=(e,t)=>{Yd(Kd(e),"nodes and leaf payloads must be plain objects"),Yd(Reflect.ownKeys(e).length===t.length&&t.every(t=>Object.hasOwn(e,t)),`expected exactly ${t.join(", ")}`)},Xd=e=>Yd("string"==typeof e&&e.length>0,"ids and parameter names must be non-empty strings"),ec=(e,t,n)=>Yd("number"==typeof e&&Number.isFinite(e)&&e>=0&&(!t||Number.isInteger(e)),`${n} must be a finite non-negative ${t?"integer":"number"}`),tc=e=>{const t=new WeakMap,n=(t,n)=>{const r=[],s=[],i=[],a=e=>{Yd(Array.isArray(e)&&e.length>0,"pool must be a non-empty array");const t=new Set;for(const n of e)Xd(n),Yd(!t.has(n),`duplicate pool member '${n}'`),t.add(n);return n?[...e]:e},o=t=>{Yd(Kd(t),"node must be a plain object");const n=Reflect.ownKeys(t);Yd(1===n.length,"node must carry exactly one operator and no extra keys");const l=n[0],d=t[l];if("all"===l||"any"===l)return Yd(Array.isArray(d),`${l} requires an array`),{kind:l,children:Array.from(d,o)};if("not"===l)return{kind:l,child:o(d)};if("aff"===l)return Xd(d),{kind:l,id:d};Yd("poolCount"===l||"cureCount"===l||"balanceRemaining"===l,"unknown expression operator");const c="balanceRemaining"===l;Qd(d,"poolCount"===l?["ids","op","n"]:["id","op",c?"ms":"n"]);const f=d.op;Yd(Sa.includes(f),"unknown comparison operator");const u=((e,t,n)=>{if("number"==typeof e)return ec(e,t,"literal"),{slot:-1,literal:e};Yd(Kd(e),"nodes and leaf payloads must be plain objects");const i=n&&Object.hasOwn(e,"offsetMs");Qd(e,i?["param","offsetMs"]:["param"]);const a=e.param;Xd(a);let o=0;i&&(Yd("number"==typeof e.offsetMs&&Number.isFinite(e.offsetMs),"offsetMs must be a finite number"),o=0===e.offsetMs?0:e.offsetMs);let l=r.findIndex(e=>e.name===a);l<0?(l=r.length,r.push({name:a,integer:t})):t&&(r[l].integer=!0);let d=s.findIndex(e=>e.parameter===l&&e.offsetMs===o);return d<0&&(d=s.length,s.push({parameter:l,offsetMs:o})),{slot:d,literal:0}})(d[c?"ms":"n"],!c,c);if("poolCount"===l)return{kind:"count",ids:a(d.ids),op:f,operand:u};const p=d.id;if(Xd(p),"cureCount"===l){const t=e.cureById.get(p);return Yd(void 0!==t,`unknown cure '${p}'`),{kind:"count",ids:a(t.order),op:f,operand:u}}Yd(e.balanceById.has(p),`unknown balance '${p}'`);let h=i.indexOf(p);return h<0&&(h=i.length,i.push(p)),{kind:"balance",slot:h,op:f,operand:u}};return((e,t,n,r)=>{const s=[],i=[];La(e,!1,s,i);let a=0;for(const l of s)l.refs>1&&(l.cache=3*a,a+=1);const o=La(e,!0,s,i);return{match:o===Ca?Da:o===Pa?Ra:o,balanceConditions:i,cacheSlots:a,balanceIds:t,parameters:n,operands:r,plainOperands:r.every((e,t)=>0===e.offsetMs&&e.parameter===t)}})(o(t),i,r,s)};return{create(e){const r=n(e,!0),s=Object.freeze(Object.create(null));return t.set(s,r),s},prepare:e=>t.get(e)??n(e,!1),bind(e,t){const{parameters:n,operands:r}=e,s=new Array(n.length);for(let a=0;a<s.length;a+=1){const{name:e,integer:r}=n[a];Yd(null!=t&&Object.hasOwn(t,e),`missing parameter '${e}'`);const i=t[e];ec(i,r,`parameter '${e}'`),s[a]=i}if(e.plainOperands)return s;const i=new Array(r.length);for(let a=0;a<i.length;a+=1){const{parameter:e,offsetMs:t}=r[a],o=s[e]+t;Yd(Number.isFinite(o),`parameter '${n[e].name}' with offset ${t} must resolve to a finite threshold`),i[a]=o}return i}}},nc="0.6.6",rc=Object.freeze({BOOTING:"BOOTING",LOADING_SETTINGS:"LOADING_SETTINGS",REGISTERING_TRIGGERS:"REGISTERING_TRIGGERS",READY:"READY",DEGRADED:"DEGRADED"}),sc=Object.freeze({[rc.BOOTING]:Object.freeze([rc.LOADING_SETTINGS,rc.DEGRADED]),[rc.LOADING_SETTINGS]:Object.freeze([rc.REGISTERING_TRIGGERS,rc.DEGRADED]),[rc.REGISTERING_TRIGGERS]:Object.freeze([rc.READY,rc.DEGRADED]),[rc.READY]:Object.freeze([]),[rc.DEGRADED]:Object.freeze([])});var ic="__insight4StorageProbe",ac=Object.freeze({displayTable:Ls,renderAffNotice:({affId:e,present:t},n,r)=>`<span class="mono">${Vd("aff",e,t,n,r).join("")}</span>`,renderAffState:(e,t,n)=>`<span class="mono">${Gd(e,t,n).join("")}</span>`,renderDebug:e=>`<pre class="mono">${Rd(JSON.stringify(e,null,2))}</pre>`,renderDefNotice:({defId:e,present:t},n,r)=>`<span class="mono">${Vd("def",e,t,n,r).join("")}</span>`,renderNotice:Wd,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 l=e[n];o>0&&a.push(Bd(" ")),a.push(Bd(`${Ld(n)} `),Bd("[",s.fg,s.bg));const d=Fd(l.affs,r.threshold);d.forEach(([e,n],s)=>{a.push(qd(e,n,t,r)),s<d.length-1&&a.push(Bd(" "))}),a.push(Bd("]",s.fg,s.bg));const c=Math.round(100*l.staleness);c>0&&a.push(Bd(` ~${c}%`,i.fg,i.bg))}),`<span class="mono">${a.join("")}</span>`},renderStatState:(e,t)=>{const n=Hd(e,t);return n.length>0?`<span class="mono">${n.join("")}</span>`:""},renderTarget:(e,t,n)=>{const{detail:r}=t.chrome,s=[Bd(`${Ld(e.id)} `),...Gd(e,t,n)],i=Hd(e,t);i.length>0&&s.push(Bd(" "),...i);const a=((e,t)=>{const n=e.defs?.speed;if(!n)return[];const{defence:r}=t.chrome,s=n.have?r.up:r.down;return[Bd("speed",s.fg,s.bg)]})(e,t);a.length>0&&s.push(Bd(" "),...a);const o=Dd.filter(t=>e.limbs[t]?.percent>0);if(o.length>0){const t=o.map(t=>{const n=e.limbs[t];return`${t}:${Math.round(n.percent)}%`}).join(" ");s.push(Bd(` ${t}`,r.fg,r.bg))}return`<span class="mono">${s.join("")}</span>`}});function oc(e,{safetyFlushMs:t,updateNxs:n=h,guards:r}={}){const s=function({onTransition:e}={}){let t=rc.BOOTING,n=0;const r=[rc.BOOTING];return{getPhase:()=>t,getRevision:()=>n,getHistory:()=>[...r],transition(s){if(!sc[t].includes(s))throw new Error(`Invalid phase transition: ${t} → ${s}`);return t=s,n+=1,r.push(s),e?.(s),t}}}();let i,o=null,l=null,d=null,c=null,f=!1;const u={getPhase:s.getPhase,getPhaseHistory:s.getHistory,getError:()=>o,isReady:()=>s.getPhase()===rc.READY,dispose(){f||(f=!0,d?.dispose(),c&&globalThis.insight===c&&delete globalThis.insight)},get settings(){return l},get runtime(){return d},get state(){return c?c.state:null},get api(){return c?c.api:null},get events(){return c?c.events:null}},p=t=>{try{e.display.addLine(Wd(t,Ls))}catch{}},m=()=>{!0===l?.get?.().autoUpdate&&n({enabled:!0,currentVersion:nc,notice:p})},g=e=>(o=e,s.transition(rc.DEGRADED),p({text:`DEGRADED: ${e?.message??String(e)}`,severity:"error"}),m(),u);try{a(e),e.storage.clear(ic),e.storage.set(ic,"probe"),e.storage.clear(ic),i=e.display.addLine.bind(e.display)}catch(y){try{e?.storage?.clear?.(ic)}catch{}return g(y)}s.transition(rc.LOADING_SETTINGS);const b=Ed(e);l=b;try{b.load()}catch(y){b.reset(),p({text:`Settings storage is unavailable — running on default settings. (${y?.message??String(y)})`,severity:"warning"})}s.transition(rc.REGISTERING_TRIGGERS);try{d=Od({adapter:e,settings:b,safetyFlushMs:t,guards:r,displaySink:i,notice:p,display:ac}),l=d.settings,c=Pd({roster:d.roster,queryCompiler:tc({cureById:Wi,balanceById:Yi}),events:d.events,settings:d.settings,observe:d.observe,capture:d.capture,advanceToNow:d.scheduler.advanceToNow,reschedule:d.scheduler.reschedule,displayRendering:ac,refreshDisplay:d.display.refresh,notice:p,addLine:i,getPhase:s.getPhase,getPhaseRevision:s.getRevision,getSettingsRevision:d.getSettingsRevision,getTimeEpoch:d.scheduler.getTimeEpoch,version:nc})}catch(y){return d?.dispose(),d=null,l=b,g(y)}return s.transition(rc.READY),globalThis.insight=c,d.publish("insight.ready",{}),m(),u}var lc=Symbol.for("insight4.instance");!function(e){globalThis[lc]?.dispose();const r=oc(function({fetchFn:e=globalThis.fetch,AbortControllerCtor:r=globalThis.AbortController,setTimeoutFn:i=globalThis.setTimeout,clearTimeoutFn:a=globalThis.clearTimeout,directoryTimeoutMs:o}={}){const l=new Map;let d=1;return{display:{addLine(e){nexusclient.add_html_line(e)}},directory:t({fetchFn:e,AbortControllerCtor:r,setTimeoutFn:i,clearTimeoutFn:a,...void 0===o?{}:{timeoutMs:o}}),storage:{get(e){const t=n();return"function"==typeof t?.get?t.get(e):t?.vars?.[e]},set(e,t){const r=n();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[e]=t}else r.set(e,t)},clear(e){const t=n();if("function"!=typeof t?.delete)if("function"!=typeof t?.set){if(!t?.vars)throw new Error("insight4 storage.clear failed — host variables expose neither delete()/set() nor a vars record");delete t.vars[e]}else t.set(e,void 0);else t.delete(e)}},triggers:{register(e,t,n){const r="insight4.trigger."+d++;return nexAction.triggers.add({id:r,tags:["insight4",`lifetime:${t}`],regex:e,action:n}),r},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 s(t?`nexskill.match.skill.${t}`:"nexskill.match.skill",e)},on:s,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,t,n){const r=l.get(e);void 0!==r&&clearTimeout(r),l.set(e,setTimeout(()=>{l.delete(e),n()},t))},clearTimer(e){const t=l.get(e);void 0!==t&&(clearTimeout(t),l.delete(e))}}}}(),e);globalThis[lc]=r}()}();
|