@datamoc/mw_games 0.30.0 → 0.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- var mw_games=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var t=Object.create,n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.getPrototypeOf,o=Object.prototype.hasOwnProperty,s=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},c=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),l=(e,t)=>{let r={};for(var i in e)n(r,i,{get:e[i],enumerable:!0});return t||n(r,Symbol.toStringTag,{value:`Module`}),r},u=(e,t,a,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var c=i(t),l=0,u=c.length,d;l<u;l++)d=c[l],!o.call(e,d)&&d!==a&&n(e,d,{get:(e=>t[e]).bind(null,d),enumerable:!(s=r(t,d))||s.enumerable});return e},d=(e,r,i)=>(i=e==null?{}:t(a(e)),u(r||!e||!e.__esModule||!o.call(e,`default`)?n(i,`default`,{value:e,enumerable:!0}):i,e)),f=`0.30.0`,p=class{constructor(e=!1){this.listeners=[],this.stackMode=e}add(e){this.listeners.includes(e)||(this.stackMode?this.listeners.unshift(e):this.listeners.push(e))}remove(e){let t=this.listeners.indexOf(e);t!==-1&&this.listeners.splice(t,1)}removeAll(){this.listeners.length=0}get size(){return this.listeners.length}dispatch(e){let t=this.listeners.slice();for(let n of t)if(this.listeners.includes(n)&&n(e)===!0)return!0;return!1}},m=class{constructor(){this.onDestroy=new p,this.destroyed=!1}update(e){}resize(e,t){}onSuspend(){}onResume(e){}destroy(){this.destroyed||(this.destroyed=!0,this.onDestroy.dispatch(),this.onDestroy.removeAll(),this.teardown())}teardown(){}get isDestroyed(){return this.destroyed}},h=class{constructor(){this.scenes=[]}get current(){return this.scenes.length===0?null:this.scenes[this.scenes.length-1]}get depth(){return this.scenes.length}replace(e){for(let e of this.scenes)e.destroy();this.scenes=[e],e.create()}push(e){this.current?.onSuspend(),this.scenes.push(e),e.create()}pop(e){if(this.scenes.length<=1)throw Error(`cannot pop the last scene off the stack - switchScene somewhere instead`);this.scenes.pop()?.destroy(),this.current?.onResume(e)}update(e){this.current?.update(e)}resize(e,t){for(let n of this.scenes)n.resize(e,t)}destroy(){for(let e of this.scenes)e.destroy();this.scenes=[]}},g=class{constructor(){this.items=new Map}register(e,t){if(this.items.has(e))throw Error(`"${e}" is already registered`);this.items.set(e,t)}get(e){let t=this.items.get(e);if(t===void 0)throw Error(`no registration named "${e}"`);return t}has(e){return this.items.has(e)}list(){return[...this.items.keys()]}};function _(){let e=1,t=new Map;return{get size(){return t.size},put(n){let r=e++;return t.set(r,n),r},get(e){let n=t.get(e);if(n===void 0)throw Error(`unknown handle ${e}`);return n},drop(e){t.delete(e)},clear(){t.clear()},with(n,r){let i=e++;t.set(i,n);try{return r(i)}finally{t.delete(i)}}}}var v=class{constructor(){this.order=[],this.registry=new g}add(e,t){this.registry.register(e.name,e),this.order.push(e),e.create?.(t)}has(e){return this.registry.has(e)}get(e){return this.registry.get(e)}update(e,t){for(let n of this.order)n.update?.(e,t)}resize(e,t,n){for(let r of this.order)r.resize?.(e,t,n)}onSuspend(e){for(let t of this.order)t.onSuspend?.(e)}onResume(e,t){for(let n of this.order)n.onResume?.(e,t)}destroy(e){for(let t=this.order.length-1;t>=0;t--)this.order[t].destroy?.(e);this.order=[],this.registry=new g}},y={debug:0,info:1,warn:2,error:3},b=class{constructor(e,t={}){if(!e)throw Error(`a logger needs a category`);this.category=e,this.level=t.level??`debug`,this.sink=t.sink??x}setLevel(e){this.level=e}debug(e,t){this.write(`debug`,e,t)}info(e,t){this.write(`info`,e,t)}warn(e,t){this.write(`warn`,e,t)}error(e,t){this.write(`error`,e,t)}write(e,t,n){y[e]<y[this.level]||this.sink({level:e,category:this.category,message:t,data:n,time:Date.now()})}};function x(e){let t=`[${e.category}] ${e.message}`;e.level===`debug`?console.debug(t,e.data??``):e.level===`info`?console.info(t,e.data??``):e.level===`warn`?console.warn(t,e.data??``):console.error(t,e.data??``)}var S=class{constructor(){this.hooks=[]}on(e,t,n){this.hooks.push({event:e,handler:t,source:n})}off(e){this.hooks=this.hooks.filter(t=>t.handler!==e)}offSource(e){this.hooks=this.hooks.filter(t=>t.source!==e)}emit(e,...t){for(let n of[...this.hooks])n.event===e&&n.handler(...t)}get size(){return this.hooks.length}clear(){this.hooks=[]}},C=l({Generator:()=>j,MersenneTwister:()=>he,RandomStreams:()=>ge,active:()=>ee,chance:()=>A,element:()=>re,float:()=>O,int:()=>te,normalRange:()=>k,pop:()=>T,push:()=>w,range:()=>ne,reset:()=>D,shuffle:()=>oe,weighted:()=>ie,weightedKey:()=>ae,withSeed:()=>E});function ee(){return le()}function w(e){let t=new j(e);return ce.push(t),t}function T(){if(ce.length===1)throw Error(`the base random generator cannot be popped`);ce.pop()}function E(e,t){w(e);try{return t()}finally{T()}}function D(){ce.length=0,ce.push(new j)}function O(e,t,n){let r=n??le();return e===void 0?r.float():t===void 0?r.float()*e:e+r.float()*(t-e)}function te(e,t,n){let r=n??le();return t===void 0?r.int(e):e+r.int(t-e)}function ne(e,t,n){return e+(n??le()).int(t-e+1)}function k(e,t,n){let r=n??le();return e+Math.floor((r.float()+r.float())*(t-e+1)/2)}function A(e,t){return(t??le()).float()<e}function re(e,t){return e.length>0?e[(t??le()).int(e.length)]:null}function ie(e,t){let n=0;for(let t of e)n+=t;if(n<=0)return null;let r=(t??le()).float()*n;for(let t=0;t<e.length;t++)if(r-=e[t],r<0)return t;return e.length-1}function ae(e,t){let n=[...e.keys()],r=ie(n.map(t=>e.get(t)??0),t);return r===null?null:n[r]}function oe(e,t){for(let n=e.length-1;n>0;n--){let r=(t??le()).int(n+1);[e[n],e[r]]=[e[r],e[n]]}return e}function se(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return t>>>0}var j,ce,le,ue,de,fe,pe,me,he,ge,_e=s((()=>{j=class{constructor(e){this.s0=0,this.s1=0,this.s2=0,this.s3=0,this.seed=e===void 0?Math.random()*4294967296>>>0:e>>>0;let t=this.seed,n=()=>{t=t+2654435769>>>0;let e=t;return e=Math.imul(e^e>>>16,569420461),e=Math.imul(e^e>>>15,1935289751),(e^e>>>15)>>>0};this.s0=n(),this.s1=n(),this.s2=n(),this.s3=n(),(this.s0|this.s1|this.s2|this.s3)===0&&(this.s0=1)}nextUint32(){let e=Math.imul(this.rotl(Math.imul(this.s1,5),7),9)>>>0>>>0,t=this.s1<<9>>>0;return this.s2^=this.s0,this.s3^=this.s1,this.s1^=this.s2,this.s0^=this.s3,this.s2^=t,this.s3=this.rotl(this.s3,11),e}float(){return this.nextUint32()/4294967296}int(e){if(e<=0)return 0;let t=4294967296-4294967296%e,n=this.nextUint32();for(;n>=t;)n=this.nextUint32();return n%e}getState(){return[this.s0,this.s1,this.s2,this.s3]}setState(e){[this.s0,this.s1,this.s2,this.s3]=e}rotl(e,t){return(e<<t|e>>>32-t)>>>0}},ce=[new j],le=()=>ce[ce.length-1],ue=624,de=397,fe=2567483615,pe=2147483648,me=2147483647,he=class{constructor(e=5489){this.state=new Uint32Array(ue),this.index=ue,this.seedValue=5489,this.produced=0,this.seed(e)}seed(e){this.seedValue=e>>>0,this.state[0]=this.seedValue;for(let e=1;e<ue;e++){let t=this.state[e-1]^this.state[e-1]>>>30;this.state[e]=Math.imul(1812433253,t)+e>>>0}this.index=ue,this.produced=0}generate(){for(let e=0;e<ue;e++){let t=this.state[e]&pe|this.state[(e+1)%ue]&me,n=this.state[(e+de)%ue]^t>>>1;t&1&&(n^=fe),this.state[e]=n>>>0}this.index=0}nextUint32(){this.index>=ue&&this.generate();let e=this.state[this.index++];return e^=e>>>11,e^=e<<7&2636928640,e^=e<<15&4022730752,e^=e>>>18,this.produced++,e>>>0}float(){return this.nextUint32()/4294967296}int(e){if(e<=0)return 0;let t=4294967296-4294967296%e,n=this.nextUint32();for(;n>=t;)n=this.nextUint32();return n%e}discard(e){for(let t=0;t<e;t++)this.nextUint32()}get discardCount(){return this.produced}getState(){return{seed:this.seedValue,state:[...this.state],index:this.index,discard:this.produced}}setState(e){this.seedValue=e.seed>>>0;for(let t=0;t<ue;t++)this.state[t]=(e.state[t]??0)>>>0;this.index=e.index,this.produced=e.discard}},ge=class{constructor(e=0){this.streams=new Map,this.baseSeed=e>>>0}stream(e){let t=this.streams.get(e);if(!t){let n=(this.baseSeed^se(e))>>>0;t={seed:n,engine:new he(n)},this.streams.set(e,t)}return t.engine}seedOf(e){return this.streams.get(e)?.seed}reseed(e){this.baseSeed=e>>>0,this.streams.clear()}names(){return[...this.streams.keys()]}getState(){let e={};for(let[t,n]of this.streams)e[t]=n.engine.getState();return e}setState(e){for(let[t,n]of Object.entries(e)){let e=new he(n.seed);e.setState(n),this.streams.set(t,{seed:n.seed,engine:e})}}}})),ve=l({DEFAULT_BINDINGS:()=>je,actionsForKey:()=>Pe,attach:()=>ht,attachSwipe:()=>mt,bind:()=>Me,bindAxis:()=>at,bindButton:()=>it,bindTouch:()=>lt,detach:()=>gt,dispatchAction:()=>Te,dispatchComposition:()=>Ee,dispatchText:()=>we,endFrame:()=>Ke,exportBindings:()=>Le,gamepadAxisCode:()=>rt,gamepadButtonCode:()=>nt,importBindings:()=>Re,isDown:()=>Ue,justPressed:()=>We,justReleased:()=>Ge,keysFor:()=>Ie,onAction:()=>P,onComposition:()=>F,onKey:()=>xe,onText:()=>Se,onWheel:()=>De,pollGamepads:()=>ot,pressTouch:()=>ut,releaseTouch:()=>dt,resetBindings:()=>ze,rumble:()=>st,textFromKey:()=>Ce,touchCode:()=>ct,unbind:()=>Fe,wheelActionFor:()=>Oe}),M=new Map,N=new Set,ye=new Set,be=new Set,P=new p(!0),xe=new p(!0),Se=new p(!0),F=new p(!0);function Ce(e){return e.isComposing||e.ctrlKey||e.metaKey||e.altKey?null:e.key.length===1?e.key:null}function we(e){e.length>0&&Se.dispatch(e)}function Te(e){P.dispatch(e)}function Ee(e){F.dispatch({phase:e.phase,text:e.text})}var De=new p(!0);function Oe(e){return e.ctrlKey||e.metaKey?`zoom`:e.shiftKey?`scrollHorizontal`:`scroll`}function ke(e){let t=Oe(e);t===`zoom`&&e.preventDefault();let n=t===`scrollHorizontal`&&e.deltaX!==0?e.deltaX:e.deltaY;De.dispatch({action:t,delta:n})}var Ae=!1,je={up:[`ArrowUp`,`KeyW`,`Numpad8`],down:[`ArrowDown`,`KeyS`,`Numpad2`],left:[`ArrowLeft`,`KeyA`,`Numpad4`],right:[`ArrowRight`,`KeyD`,`Numpad6`],upLeft:[`Numpad7`],upRight:[`Numpad9`],downLeft:[`Numpad1`],downRight:[`Numpad3`],wait:[`Numpad5`,`Period`],confirm:[`Enter`,`Space`,`NumpadEnter`],cancel:[`Escape`,`Backspace`],menu:[`KeyI`,`Tab`]};function Me(e,t){M.set(e,new Set(t))}function Ne(e,t){let n=M.get(e)??new Set;for(let e of t)n.add(e);M.set(e,n)}function Pe(e){return Be(e)}function Fe(e){M.delete(e)}function Ie(e){return[...M.get(e)??[]]}function Le(){let e={};for(let[t,n]of M)e[t]=[...n];return e}function Re(e){M.clear();for(let[t,n]of Object.entries(e))Me(t,n)}function ze(){Re(je)}ze();function Be(e){let t=[];for(let[n,r]of M)r.has(e)&&t.push(n);return t}function Ve(e){if(!N.has(e)){N.add(e);for(let t of Be(e))ye.add(t),P.dispatch(t)}}function He(e){if(N.has(e)){N.delete(e);for(let t of Be(e))be.add(t)}}function Ue(e){let t=M.get(e);if(!t)return!1;for(let e of t)if(N.has(e))return!0;return!1}function We(e){return ye.has(e)}function Ge(e){return be.has(e)}function Ke(){ye.clear(),be.clear()}function qe(e){let t=Ce(e);t!==null&&we(t)}function Je(e){if(e.repeat){xe.dispatch(e),qe(e);return}Ve(e.code),xe.dispatch(e),qe(e)}function Ye(e){He(e.code)}function Xe(e){Ee({phase:`start`,text:e.data??``})}function Ze(e){Ee({phase:`update`,text:e.data??``})}function Qe(e){Ee({phase:`end`,text:e.data??``})}function $e(){N.clear(),ye.clear(),be.clear()}var et=.5,tt=new Set;function nt(e,t){return`Gamepad${e}Button${t}`}function rt(e,t,n){return`Gamepad${e}Axis${t}${n>0?`+`:`-`}`}function it(e,t,n){Ne(e,n.map(e=>nt(t,e)))}function at(e,t,n,r){Ne(e,[rt(t,n,r)])}function ot(e=typeof navigator?.getGamepads==`function`?navigator.getGamepads():[]){tt.clear();for(let t of e)if(t){for(let e=0;e<t.buttons.length;e++)t.buttons[e].pressed&&tt.add(nt(t.index,e));for(let e=0;e<t.axes.length;e++){let n=t.axes[e];n>=et?tt.add(rt(t.index,e,1)):n<=-.5&&tt.add(rt(t.index,e,-1))}}for(let e of tt)Ve(e);for(let e of N)!tt.has(e)&&e.startsWith(`Gamepad`)&&He(e)}function st(e,t,n=typeof navigator?.getGamepads==`function`?navigator.getGamepads():[]){(n[e]?.vibrationActuator)?.playEffect(`dual-rumble`,{duration:t.duration,weakMagnitude:t.weakMagnitude??1,strongMagnitude:t.strongMagnitude??1})}function ct(e){return`Touch:${e}`}function lt(e,t=e){Ne(e,[ct(t)])}function ut(e){Ve(ct(e))}function dt(e){He(ct(e))}var ft={up:`up`,down:`down`,left:`left`,right:`right`,upLeft:`upLeft`,upRight:`upRight`,downLeft:`downLeft`,downRight:`downRight`},pt=[`right`,`downRight`,`down`,`downLeft`,`left`,`upLeft`,`up`,`upRight`];function mt(e,t={}){let n={...ft,...t.actions},r=t.minDistance??24;for(let e of[...pt,`tap`]){let t=n[e];t&&lt(t,`swipe:${e}`)}let i=!1,a=-1,o=0,s=0;function c(e){ut(`swipe:${e}`),dt(`swipe:${e}`)}function l(e){i=!0,a=e.pointerId,o=e.clientX,s=e.clientY}function u(e){if(!i||e.pointerId!==a)return;i=!1;let t=e.clientX-o,l=e.clientY-s;if(Math.hypot(t,l)<r){n.tap&&c(`tap`);return}let u=pt[(Math.round(Math.atan2(l,t)/(Math.PI/4))%8+8)%8];n[u]&&c(u)}return e.addEventListener(`pointerdown`,l),e.addEventListener(`pointerup`,u),e.addEventListener(`pointercancel`,u),()=>{e.removeEventListener(`pointerdown`,l),e.removeEventListener(`pointerup`,u),e.removeEventListener(`pointercancel`,u)}}function ht(e=window){Ae||(Ae=!0,e.addEventListener(`keydown`,Je),e.addEventListener(`keyup`,Ye),e.addEventListener(`compositionstart`,Xe),e.addEventListener(`compositionupdate`,Ze),e.addEventListener(`compositionend`,Qe),window.addEventListener(`blur`,$e),e.addEventListener(`wheel`,ke,{passive:!1}))}function gt(e=window){Ae&&(Ae=!1,e.removeEventListener(`keydown`,Je),e.removeEventListener(`keyup`,Ye),e.removeEventListener(`compositionstart`,Xe),e.removeEventListener(`compositionupdate`,Ze),e.removeEventListener(`compositionend`,Qe),e.removeEventListener(`wheel`,ke),window.removeEventListener(`blur`,$e),$e())}var _t=class{constructor(e,t={}){if(!e)throw Error(`a player needs a non-empty id`);this.id=e,this.padIndex=t.padIndex}scoped(e){return`${this.id}:${e}`}bind(e,t){Me(this.scoped(e),t)}bindButton(e,t){if(this.padIndex===void 0)throw Error(`player "${this.id}" has no padIndex to bind a gamepad button to`);it(this.scoped(e),this.padIndex,t)}bindAxis(e,t,n){if(this.padIndex===void 0)throw Error(`player "${this.id}" has no padIndex to bind a gamepad axis to`);at(this.scoped(e),this.padIndex,t,n)}bindTouch(e,t=e){lt(this.scoped(e),`${this.id}:${t}`)}pressTouch(e){ut(`${this.id}:${e}`)}releaseTouch(e){dt(`${this.id}:${e}`)}isDown(e){return Ue(this.scoped(e))}justPressed(e){return We(this.scoped(e))}justReleased(e){return Ge(this.scoped(e))}keysFor(e){return Ie(this.scoped(e))}},vt=25214903917n,yt=11n,bt=(1n<<48n)-1n,xt=class{constructor(e=0,t={}){this.state=0n,this.onDraw=t.onDraw,this.setSeed(e)}setSeed(e){this.state=(BigInt.asIntN(64,BigInt(e))^vt)&bt}next(e){if(!Number.isInteger(e)||e<1||e>32)throw Error(`next needs 1 to 32 bits, got ${e}`);this.state=this.state*vt+yt&bt;let t=Number(this.state>>BigInt(48-e)),n=e===32?t|0:t;return this.onDraw?.({bits:e,value:n}),n}nextInt(e){if(e===void 0)return this.next(32);if(!Number.isInteger(e)||e<=0||e>2147483647)throw Error(`nextInt needs a bound from 1 to 2147483647, got ${e}`);if((e&-e)===e)return Math.floor(e*this.next(31)/2147483648);let t,n;do t=this.next(31),n=t%e;while(t-n+(e-1)>2147483647);return n}nextLong(){let e=BigInt(this.next(32)),t=BigInt(this.next(32));return BigInt.asIntN(64,(e<<32n)+t)}nextDouble(){return(this.next(26)*134217728+this.next(27))/2**53}nextFloat(){return this.next(24)/16777216}nextBoolean(){return this.next(1)!==0}};_e();function St(e,t){if(!t)throw Error(`scramble needs a non-empty key`);let n=new TextEncoder().encode(e),r=new TextEncoder().encode(t),i=new Uint8Array(n.length);for(let e=0;e<n.length;e++)i[e]=n[e]^r[e%r.length];return wt(i)}function Ct(e,t){if(!t)throw Error(`scramble needs a non-empty key`);let n=Tt(e),r=new TextEncoder().encode(t),i=new Uint8Array(n.length);for(let e=0;e<n.length;e++)i[e]=n[e]^r[e%r.length];return new TextDecoder(`utf-8`,{fatal:!0}).decode(i)}function wt(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t)}function Tt(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}var Et=10485760;function Dt(e,t={}){let n=t.maxBytes??Et,r=typeof e==`string`?new TextEncoder().encode(e).length:e.length;if(r>n)throw Error(`inbound data exceeds the ${n}-byte limit (${r} bytes)`)}function Ot(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n!==9&&n!==10&&n!==13&&(n<=31||n===127))throw Error(`inbound data contains a control character (0x${n.toString(16).padStart(2,`0`)}) at index ${t}`)}}function kt(e,t={}){return Dt(e,t),Ot(e),e}var At=new Set([`__proto__`,`constructor`,`prototype`]);function jt(e,t=`$`){if(Array.isArray(e)){e.forEach((e,n)=>jt(e,`${t}[${n}]`));return}if(typeof e==`object`&&e)for(let n of Object.keys(e)){if(At.has(n))throw Error(`${t} contains a forbidden key "${n}"`);jt(e[n],`${t}.${n}`)}}function Mt(e,t,n=`$`){if(e===void 0){if(t.optional)return;throw Error(`${n} is required`)}switch(t.type){case`string`:if(typeof e!=`string`)throw Error(`${n} must be a string`);return;case`number`:if(typeof e!=`number`||!Number.isFinite(e))throw Error(`${n} must be a finite number`);if(t.min!==void 0&&e<t.min)throw Error(`${n} must be >= ${t.min}`);if(t.max!==void 0&&e>t.max)throw Error(`${n} must be <= ${t.max}`);return;case`boolean`:if(typeof e!=`boolean`)throw Error(`${n} must be a boolean`);return;case`array`:if(!Array.isArray(e))throw Error(`${n} must be an array`);if(t.maxLength!==void 0&&e.length>t.maxLength)throw Error(`${n} exceeds its maximum length of ${t.maxLength}`);e.forEach((e,r)=>Mt(e,t.items,`${n}[${r}]`));return;case`object`:if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`${n} must be an object`);for(let t of Object.keys(e))if(At.has(t))throw Error(`${n} contains a forbidden key "${t}"`);for(let[r,i]of Object.entries(t.fields))Mt(e[r],i,`${n}.${r}`);return}}function Nt(e,t={}){let n=t.label??`inbound data`;kt(e,t);try{return JSON.parse(e,(e,t)=>{if(At.has(e))throw new Pt(e);return t})}catch(e){throw e instanceof Pt?Error(`${n} contains a forbidden key "${e.key}"`):Error(`${n} is not valid JSON (${e instanceof Error?e.message:String(e)})`)}}var Pt=class{constructor(e){this.key=e}};function Ft(e,t){let n=Nt(e,{label:t}),r=n?.meta;if(typeof n!=`object`||!n||Array.isArray(n)||!(`state`in n))throw Error(`${t} is not save data (expected { meta, state })`);if(typeof r!=`object`||!r||!Number.isSafeInteger(r.version)||r.version<0)throw Error(`${t} has no valid meta.version`);if(typeof r.savedAt!=`number`||!Number.isFinite(r.savedAt))throw Error(`${t} has no valid meta.savedAt`);return n}var It=class{constructor(){this.data=new Map}read(e){return this.data.get(e)??null}write(e,t){this.data.set(e,t)}remove(e){this.data.delete(e)}keys(){return[...this.data.keys()]}};function Lt(){return typeof localStorage>`u`?new It:{read:e=>localStorage.getItem(e),write:(e,t)=>localStorage.setItem(e,t),remove:e=>localStorage.removeItem(e),keys:()=>Object.keys(localStorage)}}var Rt=class{constructor(e){this.namespace=e.namespace,this.version=e.version,this.migrations=e.migrations??{},this.storage=e.storage??Lt()}key(e){return`mwg-save:${this.namespace}:${e}`}save(e,t,n){let r={meta:{version:this.version,savedAt:Date.now(),preview:n},state:t};this.storage.write(this.key(e),JSON.stringify(r))}load(e){let t=this.storage.read(this.key(e));if(!t)return null;try{let n=Ft(t,`save slot "${e}"`),r=n.state;for(let e=n.meta.version;e<this.version;e++)r=(this.migrations[e]??(e=>e))(r);return{meta:{...n.meta,version:this.version},state:r}}catch{return null}}importExternal(e,t,n,r){Dt(t);let i=n(t);for(let e=0;e<this.version;e++)i=(this.migrations[e]??(e=>e))(i);let a={meta:{version:this.version,savedAt:Date.now(),preview:r},state:i};this.storage.write(this.key(e),JSON.stringify(a))}delete(e){this.storage.remove(this.key(e))}exportSlot(e,t){let n=this.storage.read(this.key(e));return n===null?null:t?St(n,t):n}importSlot(e,t,n){Dt(t);let r=Ft(n?Ct(t,n):t,`SaveSystem.importSlot: payload`),i=r.state;for(let e=r.meta.version;e<this.version;e++)i=(this.migrations[e]??(e=>e))(i);let a={meta:{...r.meta,version:this.version},state:i};this.storage.write(this.key(e),JSON.stringify(a))}list(){let e=`mwg-save:${this.namespace}:`,t=[];for(let n of this.storage.keys()){if(!n.startsWith(e))continue;let r=this.storage.read(n);if(r)try{t.push({slot:n.slice(e.length),meta:Ft(r,n).meta})}catch{}}return t}};function zt(e,t=`value`){return Bt(e,t,new Set)}function Bt(e,t,n){if(typeof e==`function`||typeof e==`symbol`)return t;if(typeof e!=`object`||!e||n.has(e)||(n.add(e),Vt(e)))return null;let r=[];if(e instanceof Map)for(let[n,i]of e)r.push([`${t}.get(${JSON.stringify(n)??String(n)})`,i]);else if(e instanceof Set)for(let n of e)r.push([`${t}.item`,n]);else if(Array.isArray(e))e.forEach((e,n)=>r.push([`${t}[${n}]`,e]));else for(let[n,i]of Object.entries(e))r.push([`${t}.${n}`,i]);for(let[e,t]of r){let r=Bt(t,e,n);if(r)return r}return t}function Vt(e){try{return structuredClone(e),!0}catch{return!1}}function Ht(e,t){try{return structuredClone(e)}catch(n){let r=zt(e,t)??t;throw TypeError(`${r} cannot be structured-cloned (${n instanceof Error?n.message:String(n)}). Journals, snapshots and undo checkpoints copy their contents with structuredClone, so they must hold plain data: refer to a live object (an actor, anything carrying callbacks such as a ReactionTable) by its id and resolve it inside the rule.`,{cause:n})}}var Ut=class{constructor(e,t={}){this._state=Ht(e,`initial state`),this.version=t.version??1,this.migrations=t.migrations??{},this.extensions=t.extensions??new Wt}get state(){return structuredClone(this._state)}set(e){this._state=Ht(e,`state`)}update(e){let t=e(this.state);return this.set(t),this.state}snapshot(){let e=this.extensions.snapshot();return{version:this.version,state:this.state,extensions:e.extensions,extensionVersions:e.versions}}restore(e,t={}){if(!Number.isSafeInteger(e.version)||e.version<1)throw Error(`canonical state snapshot version must be a positive integer`);if(e.version>this.version)throw Error(`canonical state snapshot version ${e.version} is newer than ${this.version}`);let n=this.snapshot();try{let n=Ht(e.state,`snapshot.state`);for(let t=e.version;t<this.version;t++){let e=this.migrations[t+1];if(!e)throw Error(`missing canonical state migration to version ${t+1}`);n=e(n)}return this._state=Ht(n,`migrated state`),this.extensions.restore({extensions:e.extensions,versions:e.extensionVersions},t)}catch(e){throw this._state=structuredClone(n.state),this.extensions.restore({extensions:n.extensions,versions:n.extensionVersions},{missing:`keep`}),e}}transaction(e){let t=this.snapshot();try{return e(this)}catch(e){throw this.restore(t),e}}},Wt=class{constructor(){this.extensions=new Map}register(e){if(!/^[A-Za-z_][A-Za-z0-9_.-]*$/.test(e.id))throw Error(`invalid state extension id: ${e.id}`);if(this.extensions.has(e.id))throw Error(`state extension already registered: ${e.id}`);return this.extensions.set(e.id,{id:e.id,capture:()=>e.capture(),restore:t=>e.restore(t),version:e.version??1,migrations:e.migrations,reset:e.reset,remove:e.remove}),()=>this.extensions.delete(e.id)}snapshot(){let e={};for(let[t,n]of this.extensions)e[t]=Ht(n.capture(),`extension ${t}`);let t={};for(let[e,n]of this.extensions)t[e]=n.version??1;return{extensions:e,versions:t}}restore(e,t={}){let n=this.snapshot(),r=[];try{for(let[n,i]of this.extensions){if(!(n in e.extensions)){t.missing===`reset`?(i.reset&&i.reset(),r.push({extension:n,from:0,to:i.version??1,status:`reset`})):t.missing===`remove`&&(i.remove&&i.remove(),r.push({extension:n,from:0,to:i.version??1,status:`removed`}));continue}let a=e.versions?.[n]??1,o=i.version??1,s=Ht(e.extensions[n],`snapshot.extensions.${n}`);for(let e=a;e<o;e++){let t=i.migrations?.[e+1];if(!t)throw Error(`missing state migration for ${n} to version ${e+1}`);s=t(s)}i.restore(Ht(s,`migrated extension ${n}`)),r.push({extension:n,from:a,to:o,status:a===o?`unchanged`:`migrated`})}}catch(e){for(let[e,t]of this.extensions)e in n.extensions&&t.restore(structuredClone(n.extensions[e]));throw e}for(let e of r)t.onDiagnostic?.(e);return r}transaction(e){let t=this.snapshot();try{return e()}catch(e){throw this.restore(t),e}}},Gt=new Set([`localhost`,`127.0.0.1`,`[::1]`]);function Kt(e,t,n=!1){if(n||!/^[a-z][a-z0-9+.-]*:/i.test(e))return;let r=new URL(e);if(r.protocol!==`https:`&&r.protocol!==`wss:`&&(r.protocol!==`http:`&&r.protocol!==`ws:`||!Gt.has(r.hostname)))throw Error(`${t} url must use https: or wss: (got ${r.protocol}//${r.host}); pass allowInsecure: true to accept it`)}var qt=class{constructor(e,t){if(!e.endpoint)throw Error(`${t} endpoint is required`);if(Kt(e.endpoint,`${t} endpoint`,e.allowInsecure),this.endpoint=e.endpoint,this.label=t,this.maxResponseBytes=e.maxResponseBytes??10485760,this.timeoutMs=e.timeoutMs??1e4,!(this.timeoutMs>0))throw Error(`${t} timeout must be positive`);if(this.fetchFn=e.fetch??globalThis.fetch,!this.fetchFn)throw Error(`fetch is unavailable; provide ${t}Options.fetch`)}async withTimeout(e){let t=new AbortController,n=setTimeout(()=>t.abort(),this.timeoutMs);try{return await e(t.signal)}finally{clearTimeout(n)}}async readText(e){let t=this.maxResponseBytes,n=Number(e.headers?.get?.(`content-length`));if(n>t)throw Error(`${this.label} response exceeds the ${t}-byte limit (${n} bytes)`);if(!e.body){let n=await e.text();return Dt(n,{maxBytes:t}),n}let r=e.body.getReader(),i=[],a=0;for(;;){let{done:e,value:n}=await r.read();if(e)break;if(a+=n.byteLength,a>t)throw await r.cancel(),Error(`${this.label} response exceeds the ${t}-byte limit`);i.push(n)}let o=new Uint8Array(a),s=0;for(let e of i)o.set(e,s),s+=e.byteLength;return new TextDecoder().decode(o)}async readJson(e,t){return Nt(await this.readText(e),{maxBytes:this.maxResponseBytes,label:`${this.label} ${t}`})}},Jt=class extends qt{constructor(e){super(e,`save sync`)}async upload(e,t){if(!e)throw Error(`save sync slot name is required`);if(!t)throw Error(`save sync payload cannot be empty`);return this.withTimeout(async n=>{let r=await this.fetchFn(this.slotUrl(e),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({payload:t}),signal:n});if(!r.ok)throw Error(`save upload failed with HTTP ${r.status}`);return{ok:!0,status:r.status}})}async download(e){if(!e)throw Error(`save sync slot name is required`);return this.withTimeout(async t=>{let n=await this.fetchFn(this.slotUrl(e),{signal:t});if(!n.ok)throw Error(`save download failed with HTTP ${n.status}`);let r=await this.readJson(n,`download`);if(typeof r?.payload!=`string`)throw Error(`save download response missing a string payload`);return r.payload})}async list(){return this.withTimeout(async e=>{let t=await this.fetchFn(this.endpoint,{signal:e});if(!t.ok)throw Error(`save slot list failed with HTTP ${t.status}`);let n=await this.readJson(t,`slot list`);if(!Array.isArray(n?.slots)||!n.slots.every(e=>typeof e==`string`))throw Error(`save slot list response missing a string array of slots`);return n.slots})}slotUrl(e){let t=this.endpoint.includes(`?`)?`&`:`?`;return`${this.endpoint}${t}slot=${encodeURIComponent(e)}`}},Yt=1,Xt=class{constructor(e){if(this.onWelcome=new p,this.onTick=new p,this.onReject=new p,this.onDesync=new p,this.onClose=new p,this.onProtocolError=new p,this.socket=null,this._id=null,!e.url)throw Error(`lockstep client url is required`);Kt(e.url,`lockstep client`,e.allowInsecure),this.url=e.url,this.createSocket=e.create??(e=>new WebSocket(e)),this.validateInput=e.validateInput,this.maxMessageBytes=e.maxMessageBytes??1048576}get id(){return this._id}get connected(){return this.socket!==null&&this.socket.readyState===Yt}connect(){if(this.socket)throw Error(`lockstep client is already connected`);let e=this.createSocket(this.url);e.onmessage=e=>this.handleMessage(e.data),e.onclose=()=>{this.socket=null,this._id=null,this.onClose.dispatch()},this.socket=e}submitInput(e,t){if(!this.connected)return;let n=this.validateInput?.(e);if(n===!1||typeof n==`string`){this.onReject.dispatch({reason:n===!1?`input rejected by client validation`:n});return}this.socket?.send(JSON.stringify({type:`input`,payload:e,...t===void 0?{}:{checksum:t}}))}close(){this.socket?.close()}handleMessage(e){let t;try{if(typeof e!=`string`)throw Error(`lockstep message is not text`);t=Qt(Nt(e,{maxBytes:this.maxMessageBytes,label:`lockstep message`}))}catch(e){this.onProtocolError.dispatch({reason:e instanceof Error?e.message:String(e)});return}if(t.type===`welcome`)this._id=t.id,this.onWelcome.dispatch({id:t.id,...t.seed===void 0?{}:{seed:t.seed},...t.initialState===void 0?{}:{initialState:t.initialState}});else if(t.type===`tick`){let e={tick:t.tick,inputs:t.inputs,...t.checksums===void 0?{}:{checksums:t.checksums}};if(this.onTick.dispatch(e),t.checksums){let e=Object.values(t.checksums);e.some(t=>t!==e[0])&&this.onDesync.dispatch({tick:t.tick,checksums:t.checksums})}}else this.onReject.dispatch({reason:t.reason??`input rejected by server`})}},Zt=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function Qt(e){if(!Zt(e)||typeof e.type!=`string`)throw Error(`lockstep message has no type`);switch(e.type){case`welcome`:if(typeof e.id!=`string`||e.id===``)throw Error(`welcome needs a string id`);if(e.seed!==void 0&&!Number.isSafeInteger(e.seed))throw Error(`welcome seed must be an integer`);return e;case`tick`:if(!Number.isSafeInteger(e.tick)||e.tick<0)throw Error(`tick needs a non-negative integer tick`);if(!Zt(e.inputs))throw Error(`tick needs an inputs object`);if(e.checksums!==void 0&&(!Zt(e.checksums)||Object.values(e.checksums).some(e=>typeof e!=`number`)))throw Error(`tick checksums must map ids to numbers`);return e;case`rejected`:if(e.reason!==void 0&&typeof e.reason!=`string`)throw Error(`rejected reason must be a string`);return e;default:throw Error(`unknown lockstep message type "${e.type}"`)}}var $t=class{constructor(e,t){this.storage=e,this.key=t}read(e){let t=this.storage.read(this.key);return t?Nt(t,{label:`stored value "${this.key}"`}):e}write(e){this.storage.write(this.key,JSON.stringify(e))}remove(){this.storage.remove(this.key)}},en=class{constructor(e){this.store=new $t(e.storage??Lt(),`mwg-runs:${e.namespace}`),this.limit=e.limit}readAll(){return this.store.read([])}record(e){let t=this.readAll(),n={id:`${Date.now()}-${t.length}`,endedAt:Date.now(),summary:e};return t.push(n),this.limit!==void 0&&t.length>this.limit&&t.splice(0,t.length-this.limit),this.store.write(t),n}all(){return this.readAll()}ranked(e,t=`desc`){let n=this.readAll(),r=t===`desc`?-1:1;return n.sort((t,n)=>r*(e(t.summary)-e(n.summary)))}clear(){this.store.remove()}},tn=class{constructor(e){this.store=new $t(e.storage??Lt(),`mwg-stats:${e.namespace}`),this.initial=e.initial,this.combine=e.combine}get(){return this.store.read(this.initial)}record(e){let t=this.combine(this.get(),e);return this.store.write(t),t}reset(){this.store.remove()}},nn=class extends qt{constructor(e){super(e,`telemetry`),this.consented=!1,this.maxStringLength=e.maxStringLength??256,this.maxProperties=e.maxProperties??32,this.allowed=e.allowedProperties?new Set(e.allowedProperties):null}get hasConsent(){return this.consented}setConsent(e){this.consented=e}async send(e){if(!e.name)throw Error(`telemetry event needs a name`);return this.consented?this.withTimeout(async t=>{let n=await this.fetchFn(this.endpoint,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(this.bounded(e)),signal:t});if(!n.ok)throw Error(`telemetry request failed with HTTP ${n.status}`);return{ok:!0,status:n.status}}):null}bounded(e){let t=e=>e.length>this.maxStringLength?e.slice(0,this.maxStringLength):e;if(!e.properties)return{name:t(e.name)};let n={},r=0;for(let[i,a]of Object.entries(e.properties))if(!this.allowed||this.allowed.has(i)){if(r++>=this.maxProperties)break;n[t(i)]=typeof a==`string`?t(a):a}return{name:t(e.name),properties:n}}},rn=class extends qt{constructor(e){super(e,`news`)}async fetchItems(){return this.withTimeout(async e=>{let t=await this.fetchFn(this.endpoint,{signal:e});if(!t.ok)throw Error(`news request failed with HTTP ${t.status}`);let n=await this.readJson(t,`response`);if(!Array.isArray(n))throw Error(`news response was not an array`);return n.map((e,t)=>an(e,t))})}};function an(e,t){if(typeof e!=`object`||!e)throw Error(`news item ${t} was not an object`);let n=e;if(typeof n.id!=`string`||!n.id)throw Error(`news item ${t} is missing a string id`);if(typeof n.title!=`string`)throw Error(`news item ${t} is missing a string title`);if(typeof n.body!=`string`)throw Error(`news item ${t} is missing a string body`);return{id:n.id,title:n.title,body:n.body,publishedAt:typeof n.publishedAt==`number`?n.publishedAt:void 0}}var on=class{constructor(e){this.store=new $t(e.storage??Lt(),`mwg-news-seen:${e.namespace}`)}readSeen(){return new Set(this.store.read([]))}isSeen(e){return this.readSeen().has(e)}markSeen(e){let t=this.readSeen();t.add(e),this.store.write([...t])}unseen(e){let t=this.readSeen();return e.filter(e=>!t.has(e.id))}},sn=class{constructor(e,t={}){if(!e)throw Error(`a collection needs a name`);this.prefix=`mwg-db:${t.namespace??`default`}:${e}:`,this.storage=t.storage??Lt()}get size(){return this.keys().length}all(){return this.keys().map(e=>this.read(e))}get(e){let t=this.storage.read(this.prefix+e);return t===null?void 0:this.parse(t,this.prefix+e)}put(e){if(typeof e!=`object`||!e||Array.isArray(e)||typeof e.id!=`string`||e.id===``)throw Error(`a record must be an object with a string id`);this.storage.write(this.prefix+e.id,JSON.stringify(e))}remove(e){this.storage.remove(this.prefix+e)}where(e){return this.all().filter(e)}clear(){for(let e of this.keys())this.storage.remove(e)}keys(){return this.storage.keys().filter(e=>e.startsWith(this.prefix))}read(e){return this.parse(this.storage.read(e),e)}parse(e,t){return Nt(e,{label:`record "${t}"`})}},cn=class{constructor(e,t,n){if(this.recorded=[],this.fromFrame=n?.fromFrame??0,!Number.isInteger(this.fromFrame)||this.fromFrame<0)throw RangeError(`a resumed recorder needs a non-negative fromFrame`);this.frameStamp=this.fromFrame,this.actions=e,this.frames=t,this.onAction=e=>{this.recorded.push({frame:this.frameStamp,action:e})},this.onFrame=()=>{this.frameStamp++},e.add(this.onAction),t.add(this.onFrame)}get events(){return this.recorded}get frame(){return this.frameStamp}toJSON(){return this.recorded.map(e=>({frame:e.frame,action:e.action}))}stop(){this.actions.remove(this.onAction),this.frames.remove(this.onFrame)}},ln=class{constructor(e,t,n,r){if(this.events=e,this.dispatch=t,this.frames=n,this.fromFrame=r?.fromFrame??0,!Number.isInteger(this.fromFrame)||this.fromFrame<0)throw RangeError(`a resumed player needs a non-negative fromFrame`);this.index=this.events.findIndex(e=>e.frame>=this.fromFrame),this.index<0&&(this.index=this.events.length),this.frame=this.fromFrame,this.onFrame=()=>this.pump(),n.add(this.onFrame)}get done(){return this.index>=this.events.length}stop(){this.frames.remove(this.onFrame)}pump(){for(;this.index<this.events.length&&this.events[this.index].frame<=this.frame;)this.dispatch(this.events[this.index].action),this.index++;this.frame++}};function un(e){return JSON.stringify(e)}function dn(e){return fn(JSON.parse(e))}function fn(e){if(!Array.isArray(e))throw Error(`a replay must be an array of {frame, action}`);return e.map(e=>{if(typeof e!=`object`||!e||!Number.isInteger(e.frame)||e.frame<0||typeof e.action!=`string`)throw Error(`a replay entry must be {frame: a non-negative integer, action: a string}`);return{frame:e.frame,action:e.action}})}function pn(e,t){if(typeof t!=`string`||!t.length)throw TypeError(`a replay file needs a non-empty ${e}`);return t}function mn(e){let t=e;if(!Number.isInteger(t)||t<0||t>4294967295)throw RangeError(`a replay seed must be uint32`);return t}function hn(e,t){let n={format:`mwg-replay`,version:1,framework:pn(`framework`,t.framework),game:pn(`game`,t.game),events:fn(e)};if(t.seed!==void 0&&(n.seed=mn(t.seed)),t.recordedAt!==void 0){if(typeof t.recordedAt!=`number`||!Number.isFinite(t.recordedAt))throw TypeError(`recordedAt must be a finite number`);n.recordedAt=t.recordedAt}return JSON.stringify(n)}function gn(e,t){let n=Nt(e,{label:`replay file`});if(typeof n!=`object`||!n||Array.isArray(n))throw Error(`a replay file must be a JSON object`);if(n.format!==`mwg-replay`)throw Error(`not a replay file: expected format "mwg-replay", found ${JSON.stringify(n.format)}`);if(n.version!==1)throw Error(`replay file version ${JSON.stringify(n.version)} is not supported (this build reads 1)`);if(n.game!==t.game)throw Error(`a replay of ${JSON.stringify(n.game)} cannot be imported into ${JSON.stringify(t.game)}`);if(n.framework!==t.framework)throw Error(`a replay recorded against mwg ${JSON.stringify(n.framework)} cannot be imported into ${JSON.stringify(t.framework)}`);let r=fn(n.events);return{format:`mwg-replay`,version:1,framework:n.framework,game:n.game,...n.seed===void 0?{}:{seed:mn(n.seed)},...n.recordedAt===void 0?{}:{recordedAt:n.recordedAt},events:r}}var _n=class{constructor(e){if(typeof e.namespace!=`string`||!e.namespace.length)throw TypeError(`a last-run store needs a non-empty namespace`);let t=e.maxEvents??1e4;if(!Number.isInteger(t)||t<1||t>1e6)throw RangeError(`last-run maxEvents must be in 1..1000000`);this.maxEvents=t,this.store=new $t(e.storage??Lt(),`mwg-last-run:${e.namespace}`)}keep(e,t){let n=fn(e);n.length>this.maxEvents&&(n=n.slice(n.length-this.maxEvents));let r=t===void 0?{version:1,events:n}:{version:1,seed:mn(t),events:n};Dt(JSON.stringify(r)),this.store.write(r)}load(){let e=this.store.read(null);if(e===null)return null;if(e?.version!==1)throw Error(`the kept last-run recording is not version 1; clear() it and record again`);return{version:1,...e.seed===void 0?{}:{seed:mn(e.seed)},events:fn(e.events)}}clear(){this.store.remove()}};function vn(e,t){return{version:1,frame:e.frame,events:e.toJSON(),state:t}}function yn(e,t,n){if(typeof e!=`object`||!e||e.version!==1)throw Error(`a run checkpoint must be { version: 1, frame, events, state }`);return new ln(fn(e.events),t,n,{fromFrame:e.frame})}function bn(e,t){if(typeof document>`u`)throw Error(`downloadReplayFile needs a browser document`);let n=document.createElement(`a`);n.href=URL.createObjectURL(new Blob([e],{type:`application/json`})),n.download=t,document.body.appendChild(n),n.click(),n.remove(),setTimeout(()=>URL.revokeObjectURL(n.href),0)}async function xn(e){return await e.text()}async function Sn(e=`.json`){if(typeof document>`u`)throw Error(`pickReplayFile needs a browser document`);return await new Promise(t=>{let n=document.createElement(`input`);n.type=`file`,n.accept=e,n.style.display=`none`;let r=!1,i=e=>{r||(r=!0,n.remove(),t(e))};n.addEventListener(`change`,()=>i(n.files?.[0]??null)),n.addEventListener(`cancel`,()=>i(null)),document.body.appendChild(n),n.click()})}var Cn=class e{constructor(){this.entries=[],this.nextSequence=0}append(e,t=[]){let n={sequence:this.nextSequence,action:Ht(e,`action`),events:Ht([...t],`events`)};return this.nextSequence++,this.entries.push(n),structuredClone(n)}get size(){return this.entries.length}get all(){return structuredClone(this.entries)}mark(){return this.nextSequence}since(e){return structuredClone(this.entries.filter(t=>t.sequence>=e))}truncate(e){this.entries=this.entries.filter(t=>t.sequence<e),this.nextSequence=e}toJSON(){return this.all}replace(t){let n=e.fromJSON(t);this.entries=n.entries,this.nextSequence=n.nextSequence}static fromJSON(t){let n=new e,r=0;for(let e of t){if(!Number.isSafeInteger(e.sequence)||e.sequence!==r)throw Error(`action journal sequences must be contiguous from zero`);n.entries.push(structuredClone({sequence:e.sequence,action:e.action,events:[...e.events]})),r++}return n.nextSequence=r,n}};function wn(e){if(e.criteria)return e.criteria;if(e.counter===void 0||e.target===void 0)throw Error(`achievement "${e.id}" needs either counter/target or criteria`);return[{counter:e.counter,target:e.target}]}var Tn=class e{constructor(){this.definitions=new Map,this.counts=new Map,this.fresh=[]}define(e){this.definitions.set(e.id,e)}count(e){return this.counts.get(e)??0}increment(e,t=1){let n=this.count(e);this.counts.set(e,n+t);let r=[];for(let t of this.definitions.values()){let i=wn(t);i.some(t=>t.counter===e)&&(i.every(t=>t.counter===e?n>=t.target:this.count(t.counter)>=t.target)||i.every(e=>this.count(e.counter)>=e.target)&&(r.push(t.id),this.fresh.push(t.id)))}return r}unlocked(e){let t=this.definitions.get(e);if(!t)throw Error(`no such achievement: "${e}"`);return wn(t).every(e=>this.count(e.counter)>=e.target)}progress(e){let t=this.definitions.get(e);if(!t)throw Error(`no such achievement: "${e}"`);let n=wn(t);if(n.length!==1)throw Error(`achievement "${e}" has several criteria - use subProgress`);return{count:this.count(n[0].counter),target:n[0].target}}subProgress(e){let t=this.definitions.get(e);if(!t)throw Error(`no such achievement: "${e}"`);return wn(t).map(e=>{let t=this.count(e.counter);return{counter:e.counter,count:t,target:e.target,met:t>=e.target}})}drainNew(){let e=this.fresh;return this.fresh=[],e}toJSON(){return{counts:[...this.counts]}}static fromJSON(t,n){let r=new e;for(let e of t)r.define(e);for(let[e,t]of n.counts)r.counts.set(e,t);return r}},En=class e{constructor(e=[]){this.active=new Set,this.spent=new Set,this.rules=[...e]}add(e){this.rules.push(e)}remove(e){this.rules=this.rules.filter(t=>t.id!==e),this.active.delete(e)}check(e){let t=[];for(let n of this.rules){if(n.once&&this.spent.has(n.id))continue;let r=n.when(e);r&&!this.active.has(n.id)&&(n.action(e),t.push(n.id),n.once&&this.spent.add(n.id)),r?this.active.add(n.id):this.active.delete(n.id)}return t}isActive(e){return this.active.has(e)}reset(){this.active.clear(),this.spent.clear()}toJSON(){return{active:[...this.active],spent:[...this.spent]}}static fromJSON(t,n){let r=new e(t);for(let e of n.active)r.active.add(e);for(let e of n.spent)r.spent.add(e);return r}},Dn=class{constructor(e={}){let t=e.storage??Lt(),n=`mwg-session:${e.namespace??`default`}`,r=Number(t.read(n)??`0`);this.launches=(Number.isFinite(r)?r:0)+1,t.write(n,String(this.launches))}};function On(e,t,n){return e<t?t:e>n?n:e}function kn(){return{musicVolume:1,sfxVolume:1,muted:!1,zoom:1,bindings:Fn(je),custom:{}}}function An(e){return e.muted?0:e.musicVolume}function jn(e){return e.muted?0:e.sfxVolume}var Mn=class{constructor(e={}){this.storage=e.storage??Lt(),this.key=`mwg-settings:${e.namespace??`default`}`,this.value=Bn(this.storage,this.key),Re(this.value.bindings)}get current(){return{...this.value,bindings:Fn(this.value.bindings),custom:{...this.value.custom}}}getCustom(e,t){return this.value.custom[e]??t}setCustom(e,t){this.value.custom[e]=t,Vn(this.storage,this.key,this.value)}setMusicVolume(e){this.update({musicVolume:e})}setSfxVolume(e){this.update({sfxVolume:e})}setMuted(e){this.update({muted:e})}setZoom(e){this.update({zoom:e})}setBindings(e){this.update({bindings:e})}update(e){e.musicVolume!==void 0&&(this.value.musicVolume=Nn(e.musicVolume)),e.sfxVolume!==void 0&&(this.value.sfxVolume=Nn(e.sfxVolume)),e.muted!==void 0&&(this.value.muted=e.muted),e.zoom!==void 0&&(this.value.zoom=Pn(e.zoom)),e.bindings!==void 0&&(this.value.bindings=In(e.bindings),Re(this.value.bindings)),e.custom!==void 0&&(this.value.custom=Rn(e.custom)),Vn(this.storage,this.key,this.value)}applyBindings(){Re(this.value.bindings)}reset(){this.value=kn(),Re(this.value.bindings),Vn(this.storage,this.key,this.value)}};function Nn(e){return Number.isFinite(e)?On(e,0,1):1}function Pn(e){return Number.isFinite(e)?Math.max(.01,e):1}function Fn(e){let t={};for(let[n,r]of Object.entries(e))t[n]=[...r];return t}function In(e){if(typeof e!=`object`||!e||Array.isArray(e))return Fn(je);let t={};for(let[n,r]of Object.entries(e)){if(!Array.isArray(r))continue;let e=r.filter(e=>typeof e==`string`);e.length>0&&(t[n]=e)}return Object.keys(t).length>0?t:Fn(je)}function Ln(e){let t=typeof e;return t===`string`||t===`number`||t===`boolean`}function Rn(e){if(typeof e!=`object`||!e||Array.isArray(e))return{};let t={};for(let[n,r]of Object.entries(e))Ln(r)&&(t[n]=r);return t}function zn(e){let t=kn();if(typeof e!=`object`||!e||Array.isArray(e))return t;let n=e;return{musicVolume:typeof n.musicVolume==`number`?Nn(n.musicVolume):t.musicVolume,sfxVolume:typeof n.sfxVolume==`number`?Nn(n.sfxVolume):t.sfxVolume,muted:typeof n.muted==`boolean`?n.muted:t.muted,zoom:typeof n.zoom==`number`?Pn(n.zoom):t.zoom,bindings:In(n.bindings),custom:Rn(n.custom)}}function Bn(e,t){let n=e.read(t);if(!n)return kn();try{return zn(Nt(n,{label:`settings`}))}catch{return kn()}}function Vn(e,t,n){e.write(t,JSON.stringify(n))}var Hn=class extends qt{constructor(e){super(e,`feedback`)}async submit(e){if(!e.message?.trim())throw Error(`feedback message cannot be empty`);return this.withTimeout(async t=>{let n=await this.fetchFn(this.endpoint,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e),signal:t});if(!n.ok)throw Error(`feedback request failed with HTTP ${n.status}`);return{ok:!0,status:n.status}})}},Un=class{constructor(e){this.schedule=[],this.cursor=0,this.elapsed=0,this.startedWaves=new Set,this.completed=!1,this.onSpawn=e.onSpawn,this.onWaveStart=e.onWaveStart,this.onComplete=e.onComplete,e.waves.forEach((e,t)=>{let n=e.entries.reduce((e,t)=>e+t.count,0),r=e.duration??0,i=0;for(let a of e.entries)for(let o=0;o<a.count;o++,i++){let o=n>1&&r>0?i/(n-1)*r:0;this.schedule.push({time:e.delay+o,kind:a.kind,waveIndex:t})}}),this.schedule.sort((e,t)=>e.time-t.time),this.schedule.length===0&&(this.completed=!0,this.onComplete?.())}update(e){if(!this.completed){for(this.elapsed+=e;this.cursor<this.schedule.length&&this.schedule[this.cursor].time<=this.elapsed;){let e=this.schedule[this.cursor];this.startedWaves.has(e.waveIndex)||(this.startedWaves.add(e.waveIndex),this.onWaveStart?.(e.waveIndex)),this.onSpawn(e.kind),this.cursor++}this.cursor>=this.schedule.length&&(this.completed=!0,this.onComplete?.())}}get isComplete(){return this.completed}};function Wn(e,t){let n=e,r=t-(e-(e&1))/2;return{x:n,y:-n-r,z:r}}function Gn(e){return{x:e.x,y:e.z+(e.x-(e.x&1))/2}}var Kn=[{x:1,y:-1,z:0},{x:1,y:0,z:-1},{x:0,y:1,z:-1},{x:-1,y:1,z:0},{x:-1,y:0,z:1},{x:0,y:-1,z:1}];function qn(e,t){let n=Wn(e,t);return Kn.map(e=>Gn({x:n.x+e.x,y:n.y+e.y,z:n.z+e.z}))}function Jn(e,t){let n=Wn(e.x,e.y),r=Wn(t.x,t.y);return Math.max(Math.abs(n.x-r.x),Math.abs(n.y-r.y),Math.abs(n.z-r.z))}function Yn(e){let t=Math.round(e.x),n=Math.round(e.y),r=Math.round(e.z),i=Math.abs(t-e.x),a=Math.abs(n-e.y),o=Math.abs(r-e.z);return i>a&&i>o?t=-n-r:a>o?n=-t-r:r=-t-n,{x:t,y:n,z:r}}function Xn(e,t){let n=Jn(e,t);if(n===0)return[{x:e.x,y:e.y}];let r=Wn(e.x,e.y),i=Wn(t.x,t.y),a=[];for(let e=0;e<=n;e++){let t=e/n;a.push(Gn(Yn({x:r.x+(i.x-r.x)*t,y:r.y+(i.y-r.y)*t,z:r.z+(i.z-r.z)*t})))}return a}function Zn(e,t){let n=Wn(e.x,e.y),r=[];for(let e=-t;e<=t;e++)for(let i=Math.max(-t,-e-t);i<=Math.min(t,-e+t);i++){let t=-e-i;r.push(Gn({x:n.x+e,y:n.y+i,z:n.z+t}))}return r}function Qn(e,t,n,r,i={}){let a=+((i.offset??`odd`)===`odd`);return(i.orientation??`flat-top`)===`pointy-top`?{x:e*n+((t&1)===a?n/2:0)+n/2,y:t*r*.75+r/2}:{x:e*n*.75+n/2,y:t*r+((e&1)===a?r/2:0)+r/2}}function $n(e,t,n,r,i={}){let a=(i.orientation??`flat-top`)===`pointy-top`,o=a?n:n*.75,s=a?r*.75:r,c=Math.round((e-n/2)/o),l=Math.round((t-r/2)/s),u={x:c,y:l},d=1/0;for(let a=-2;a<=2;a++)for(let o=-2;o<=2;o++){let s={x:c+a,y:l+o},f=Qn(s.x,s.y,n,r,i),p=(f.x-e)**2+(f.y-t)**2;p<d&&(d=p,u=s)}return u}function er(e,t,n,r){return n>=0&&r>=0&&n<e&&r<t}function tr(e,t,n){return n*e+t}function nr(e,t){return t%e}function rr(e,t){return Math.floor(t/e)}function ir(e,t){return`${e},${t}`}function ar(e){let t=/^(-?\d+),(-?\d+)$/.exec(e);return t?{x:Number(t[1]),y:Number(t[2])}:null}var or=[[0,-1],[1,0],[0,1],[-1,0]],sr=[[-1,-1],[0,-1],[1,-1],[-1,0],[1,0],[-1,1],[0,1],[1,1]],cr=[[0,-1],[1,-1],[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1]];function lr(e,t){return Math.hypot(e.x-t.x,e.y-t.y)}function ur(e,t){return Math.max(Math.abs(e.x-t.x),Math.abs(e.y-t.y))}function dr(e,t){return Math.abs(e.x-t.x)+Math.abs(e.y-t.y)}function fr(e,t,n){switch(e){case`euclidean`:return lr(t,n);case`manhattan`:return dr(t,n);case`chebyshev`:return ur(t,n);default:throw RangeError(`unknown distance metric: ${e}`)}}var pr=.12,mr=null,hr,gr=new p;function _r(){if(hr===void 0&&(hr=typeof matchMedia==`function`?matchMedia(`(prefers-reduced-motion: reduce)`):null,hr)){let e=()=>{gr.dispatch(yr())};typeof hr.addEventListener==`function`?hr.addEventListener(`change`,e):typeof hr.addListener==`function`&&hr.addListener(e)}return hr}function vr(){return _r()?.matches??!1}function yr(){return mr??vr()}function br(e){mr=e,gr.dispatch(yr())}function xr(e){return _r(),gr.add(e),()=>gr.remove(e)}function Sr(e,t=`decorative`){return yr()?t===`meaningful`?Math.min(e,pr):0:e}var Cr=class e{constructor(e,t){this.width=e,this.height=t,this.volume=new Float32Array(e*t)}index(e,t){return e<0||t<0||e>=this.width||t>=this.height?-1:t*this.width+e}volumeAt(e,t){let n=this.index(e,t);return n<0?0:this.volume[n]}total(){let e=0;for(let t=0;t<this.volume.length;t++)e+=this.volume[t];return e}seed(e,t,n){let r=this.index(e,t);r>=0&&(this.volume[r]+=n)}clear(e,t){let n=this.index(e,t);n>=0&&(this.volume[n]=0)}spread(e,t=.25,n=.9){let r=new Float32Array(this.volume.length);for(let n=0;n<this.height;n++)for(let i=0;i<this.width;i++){let a=n*this.width+i,o=this.volume[a];if(o<=0)continue;let s=[];for(let[t,r]of or){let a=i+t,o=n+r,c=this.index(a,o);c>=0&&e(a,o)&&s.push(c)}if(s.length===0)r[a]+=o;else{let e=o*t/s.length;r[a]+=o-e*s.length;for(let t of s)r[t]+=e}}let i=[];for(let e=0;e<r.length;e++){let t=r[e]*n,a=t<.001?0:t;a===0&&this.volume[e]>0&&i.push({x:e%this.width,y:Math.floor(e/this.width)}),this.volume[e]=a}return i}cellsAbove(e){let t=[];for(let n=0;n<this.height;n++)for(let r=0;r<this.width;r++){let i=this.volume[n*this.width+r];i>=e&&t.push({x:r,y:n,volume:i})}return t}toJSON(){return{width:this.width,height:this.height,volume:[...this.volume]}}static fromJSON(t){let n=new e(t.width,t.height);return n.volume.set(t.volume.slice(0,n.volume.length)),n}},wr={linear:e=>e,easeInQuad:e=>e*e,easeOutQuad:e=>e*(2-e),easeInOutQuad:e=>e<.5?2*e*e:1-(-2*e+2)**2/2,easeInCubic:e=>e*e*e,easeOutCubic:e=>1-(1-e)**3,easeInOutCubic:e=>e<.5?4*e*e*e:1-(-2*e+2)**3/2},Tr=class{constructor(){this.tweens=[]}tween(e,t,n=wr.linear){let{ease:r=wr.linear,intent:i=`decorative`,alternate:a}=typeof n==`function`?{ease:n}:n,o=yr()&&a!==void 0,s=o?a:t,c=Sr(e,o?`meaningful`:i);return c>0?new Promise(e=>{this.tweens.push({elapsed:0,duration:c,ease:r,apply:s,resolve:e,finishOnReduced:!o&&i===`decorative`})}):(s(1),Promise.resolve())}update(e){if(this.tweens.length!==0)for(let t of[...this.tweens]){if(t.finishOnReduced&&yr()){this.tweens.splice(this.tweens.indexOf(t),1),t.apply(1),t.resolve();continue}t.elapsed+=e;let n=Math.min(1,t.elapsed/t.duration);t.apply(t.ease(n)),n>=1&&(this.tweens.splice(this.tweens.indexOf(t),1),t.resolve())}}get isBusy(){return this.tweens.length>0}clear(){this.tweens=[]}},Er=class{constructor(e={}){this.history=[],this.cursor=-1,this.limit=Math.max(1,e.limit??50)}push(e){this.history.length=this.cursor+1,this.history.push(e),this.history.length>this.limit&&this.history.shift(),this.cursor=this.history.length-1}get canUndo(){return this.cursor>0}get canRedo(){return this.cursor<this.history.length-1}undo(){return this.canUndo?(this.cursor--,this.history[this.cursor]):null}redo(){return this.canRedo?(this.cursor++,this.history[this.cursor]):null}get current(){return this.cursor>=0?this.history[this.cursor]:null}clear(){this.history=[],this.cursor=-1}};function Dr(e,t){if(!Number.isFinite(t.maxCost)||t.maxCost<0)return new Map;let n=t.key(e),r=new Map([[n,{cell:e,cost:0}]]),i=[{cell:e,key:n,cost:0}];for(;i.length>0;){let e=kr(i),n=r.get(e.key);if(n&&e.cost===n.cost&&!t.stop?.(e.cell,e.cost))for(let n of t.neighbors(e.cell)){let a=t.cost(e.cell,n);if(!Number.isFinite(a)||a<0)continue;let o=e.cost+a;if(o>t.maxCost||t.canEnter&&!t.canEnter(n,e.cell,o))continue;let s=t.key(n);if(o>=(r.get(s)?.cost??1/0))continue;let c={cell:n,key:s,cost:o};r.set(s,c),Or(i,c)}}return r}function Or(e,t){e.push(t);let n=e.length-1;for(;n>0;){let t=Math.floor((n-1)/2);if(e[t].cost<=e[n].cost)break;[e[t],e[n]]=[e[n],e[t]],n=t}}function kr(e){let t=e[0],n=e.pop();if(!t||!n||e.length===0)return t;e[0]=n;let r=0;for(;;){let t=r*2+1,n=t+1,i=r;if(t<e.length&&e[t].cost<e[i].cost&&(i=t),n<e.length&&e[n].cost<e[i].cost&&(i=n),i===r)break;[e[r],e[i]]=[e[i],e[r]],r=i}return t}var Ar=class{constructor(){this.changed=new p,this.tasks=[],this.progress=new Map,this.status_=`idle`,this.current_=null,this.error_=null,this.cancelled=!1}add(e){if(!e.id)throw Error(`load task needs an id`);if(this.tasks.some(t=>t.id===e.id))throw Error(`duplicate load task "${e.id}"`);if(e.weight!==void 0&&!(e.weight>0))throw Error(`load task weight must be positive`);if(this.status_===`loading`)throw Error(`cannot add a task while loading`);return this.tasks.push(e),this.progress.set(e.id,0),this.emit(),this}get snapshot(){let e=this.tasks.reduce((e,t)=>e+(t.weight??1),0),t=this.tasks.reduce((e,t)=>e+(t.weight??1)*(this.progress.get(t.id)??0),0);return{status:this.status_,completed:t,total:e,current:this.current_,error:this.error_}}async start(){if(this.status_===`loading`)throw Error(`load queue is already running`);this.status_=`loading`,this.cancelled=!1,this.error_=null,this.emit();try{for(let e of this.tasks){if(this.cancelled)break;this.current_=e.id,this.emit();let t=this;await e.run({get cancelled(){return t.cancelled},report:t=>this.report(e.id,t)}),this.cancelled||this.report(e.id,1)}this.current_=null,this.status_=this.cancelled?`cancelled`:`ready`,this.emit()}catch(e){throw this.current_=null,this.error_=e,this.status_=`failed`,this.emit(),e}}cancel(){this.status_===`loading`&&(this.cancelled=!0)}retry(){if(this.status_===`loading`)throw Error(`cannot retry while loading`);this.status_=`idle`,this.current_=null,this.error_=null,this.cancelled=!1;for(let e of this.tasks)this.progress.set(e.id,0);this.emit()}report(e,t){if(!Number.isFinite(t))throw Error(`load progress must be finite`);this.progress.set(e,Math.max(0,Math.min(1,t))),this.emit()}emit(){this.changed.dispatch(this.snapshot)}},jr=class{constructor(){this.entities=new Map,this.ids=new Map,this.sequence=0}add(e,t){let n=this.ids.get(e);if(n!==void 0){if(t!==void 0&&t!==n)throw Error(`entity already has id ${n}`);return n}let r=t;if(r!==void 0){if(r.length===0)throw Error(`entity id must not be empty`);if(this.entities.has(r))throw Error(`entity id already exists: ${r}`)}else do r=`e${this.sequence++}`;while(this.entities.has(r));return this.entities.set(r,e),this.ids.set(e,r),r}get(e){return this.entities.get(e)}idOf(e){return this.ids.get(e)}has(e){return this.entities.has(e)}remove(e){let t=this.entities.get(e);return t!==void 0&&(this.entities.delete(e),this.ids.delete(t),!0)}get size(){return this.entities.size}},Mr=class{constructor(e){this.queue=[],this.busy=!1,this.remaining=0,this.play=e.play}enqueue(e){this.queue.push(...e),this.busy||this.advance()}update(e){this.busy&&(this.remaining-=e,this.remaining<=0&&this.advance())}get isBusy(){return this.busy}clear(){this.queue=[],this.busy=!1,this.remaining=0}advance(){let e=this.queue.shift();if(e===void 0){this.busy=!1,this.remaining=0;return}this.busy=!0;let t=this.play(e)||0;t>0?this.remaining=t:this.advance()}},Nr=2166136261,Pr=16777619;function Fr(e,t=!1){if(e==null)return`null`;switch(typeof e){case`boolean`:return e?`true`:`false`;case`number`:return Number.isFinite(e)?String(e):`null`;case`string`:return JSON.stringify(e);case`bigint`:return JSON.stringify(e.toString());case`function`:case`symbol`:return t?`null`:`undefined`}return Array.isArray(e)?`[${e.map(e=>Fr(e,!0)).join(`,`)}]`:`{${Object.entries(e).filter(([,e])=>e!==void 0&&typeof e!=`function`&&typeof e!=`symbol`).sort(([e],[t])=>e<t?-1:+(e>t)).map(([e,t])=>`${JSON.stringify(e)}:${Fr(t)}`).join(`,`)}}`}function Ir(e){let t=Fr(e),n=Nr;for(let e=0;e<t.length;e++)n^=t.charCodeAt(e),n=Math.imul(n,Pr)>>>0;return n>>>0}var Lr=class{constructor(){this.reference=new Map,this.desyncTick=null}observe(e,t){let n=this.reference.get(e);return n===void 0?(this.reference.set(e,t),!0):n===t||(this.desyncTick===null&&(this.desyncTick=e),!1)}get divergent(){return this.desyncTick!==null}get atTick(){return this.desyncTick}reset(){this.reference.clear(),this.desyncTick=null}};function Rr(e,t={}){let n=Vr(e);if(n.length===0)return[];let[r,...i]=n,a=t.listDelimiter??`;`,o=t.mapDelimiter??`=`;return i.map((e,n)=>{let i={};return r.forEach((r,s)=>{let c=e[s]??``;c!==``&&(i[r]=zr(c,t.columns?.[r]??`string`,r,n,a,o))}),i})}function zr(e,t,n,r,i,a){return Br(e,t,{column:n,rowIndex:r,listDelimiter:i,mapDelimiter:a,error:()=>t===`number`?`CSV row ${r+1}, column "${n}": "${e}" is not a number`:t===`boolean`?`CSV row ${r+1}, column "${n}": "${e}" is not "true" or "false"`:t===`map`?`CSV row ${r+1}, column "${n}": "${e.split(i).map(e=>e.trim()).find(e=>e&&!e.includes(a))??e}" has no "${a}" to split a key from its value`:`CSV row ${r+1}, column "${n}": "${e}" is invalid`})}function Br(e,t,n={}){let r=n.column??`value`,i=n.listDelimiter??`;`,a=n.mapDelimiter??`=`,o=e=>{throw Error(n.error?.(e)??e)};switch(t){case`string`:return e;case`number`:{let t=Number(e);return Number.isFinite(t)||o(`${r} must be a number`),t}case`boolean`:{let t=e.toLowerCase();if(t===`true`)return!0;if(t===`false`)return!1;if(n.acceptYesNo&&t===`yes`)return!0;if(n.acceptYesNo&&t===`no`)return!1;o(`${r} must be true, false${n.acceptYesNo?`, yes, or no`:``}`)}case`list`:return e.split(i).map(e=>e.trim()).filter(e=>e.length>0);case`map`:{let t={};for(let n of e.split(i).map(e=>e.trim()).filter(e=>e.length>0)){let e=n.indexOf(a);e===-1&&o(`${r} map entry must contain ${a}`),t[n.slice(0,e).trim()]=n.slice(e+a.length).trim()}return t}}}function Vr(e){let t=[],n=[],r=``,i=!1,a=0;for(;a<e.length;){let o=e[a];if(i){if(o===`"`){if(e[a+1]===`"`){r+=`"`,a+=2;continue}i=!1,a++;continue}r+=o,a++;continue}if(o===`"`){i=!0,a++;continue}if(o===`,`){n.push(r),r=``,a++;continue}if(o===`\r`){a++;continue}if(o===`
1
+ var mw_games=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var t=Object.create,n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.getPrototypeOf,o=Object.prototype.hasOwnProperty,s=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},c=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),l=(e,t)=>{let r={};for(var i in e)n(r,i,{get:e[i],enumerable:!0});return t||n(r,Symbol.toStringTag,{value:`Module`}),r},u=(e,t,a,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var c=i(t),l=0,u=c.length,d;l<u;l++)d=c[l],!o.call(e,d)&&d!==a&&n(e,d,{get:(e=>t[e]).bind(null,d),enumerable:!(s=r(t,d))||s.enumerable});return e},d=(e,r,i)=>(i=e==null?{}:t(a(e)),u(r||!e||!e.__esModule||!o.call(e,`default`)?n(i,`default`,{value:e,enumerable:!0}):i,e)),f=`0.31.0`,p=class{constructor(e=!1){this.listeners=[],this.stackMode=e}add(e){this.listeners.includes(e)||(this.stackMode?this.listeners.unshift(e):this.listeners.push(e))}remove(e){let t=this.listeners.indexOf(e);t!==-1&&this.listeners.splice(t,1)}removeAll(){this.listeners.length=0}get size(){return this.listeners.length}dispatch(e){let t=this.listeners.slice();for(let n of t)if(this.listeners.includes(n)&&n(e)===!0)return!0;return!1}},m=class{constructor(){this.onDestroy=new p,this.destroyed=!1}update(e){}resize(e,t){}onSuspend(){}onResume(e){}destroy(){this.destroyed||(this.destroyed=!0,this.onDestroy.dispatch(),this.onDestroy.removeAll(),this.teardown())}teardown(){}get isDestroyed(){return this.destroyed}},h=class{constructor(){this.scenes=[]}get current(){return this.scenes.length===0?null:this.scenes[this.scenes.length-1]}get depth(){return this.scenes.length}replace(e){for(let e of this.scenes)e.destroy();this.scenes=[e],e.create()}push(e){this.current?.onSuspend(),this.scenes.push(e),e.create()}pop(e){if(this.scenes.length<=1)throw Error(`cannot pop the last scene off the stack - switchScene somewhere instead`);this.scenes.pop()?.destroy(),this.current?.onResume(e)}update(e){this.current?.update(e)}resize(e,t){for(let n of this.scenes)n.resize(e,t)}destroy(){for(let e of this.scenes)e.destroy();this.scenes=[]}},g=class{constructor(){this.items=new Map}register(e,t){if(this.items.has(e))throw Error(`"${e}" is already registered`);this.items.set(e,t)}get(e){let t=this.items.get(e);if(t===void 0)throw Error(`no registration named "${e}"`);return t}has(e){return this.items.has(e)}list(){return[...this.items.keys()]}};function _(){let e=1,t=new Map;return{get size(){return t.size},put(n){let r=e++;return t.set(r,n),r},get(e){let n=t.get(e);if(n===void 0)throw Error(`unknown handle ${e}`);return n},drop(e){t.delete(e)},clear(){t.clear()},with(n,r){let i=e++;t.set(i,n);try{return r(i)}finally{t.delete(i)}}}}var v=class{constructor(){this.order=[],this.registry=new g}add(e,t){this.registry.register(e.name,e),this.order.push(e),e.create?.(t)}has(e){return this.registry.has(e)}get(e){return this.registry.get(e)}update(e,t){for(let n of this.order)n.update?.(e,t)}resize(e,t,n){for(let r of this.order)r.resize?.(e,t,n)}onSuspend(e){for(let t of this.order)t.onSuspend?.(e)}onResume(e,t){for(let n of this.order)n.onResume?.(e,t)}destroy(e){for(let t=this.order.length-1;t>=0;t--)this.order[t].destroy?.(e);this.order=[],this.registry=new g}},y={debug:0,info:1,warn:2,error:3},b=class{constructor(e,t={}){if(!e)throw Error(`a logger needs a category`);this.category=e,this.level=t.level??`debug`,this.sink=t.sink??x}setLevel(e){this.level=e}debug(e,t){this.write(`debug`,e,t)}info(e,t){this.write(`info`,e,t)}warn(e,t){this.write(`warn`,e,t)}error(e,t){this.write(`error`,e,t)}write(e,t,n){y[e]<y[this.level]||this.sink({level:e,category:this.category,message:t,data:n,time:Date.now()})}};function x(e){let t=`[${e.category}] ${e.message}`;e.level===`debug`?console.debug(t,e.data??``):e.level===`info`?console.info(t,e.data??``):e.level===`warn`?console.warn(t,e.data??``):console.error(t,e.data??``)}var S=class{constructor(){this.hooks=[]}on(e,t,n){this.hooks.push({event:e,handler:t,source:n})}off(e){this.hooks=this.hooks.filter(t=>t.handler!==e)}offSource(e){this.hooks=this.hooks.filter(t=>t.source!==e)}emit(e,...t){for(let n of[...this.hooks])n.event===e&&n.handler(...t)}get size(){return this.hooks.length}clear(){this.hooks=[]}},C=l({Generator:()=>j,MersenneTwister:()=>he,RandomStreams:()=>ge,active:()=>ee,chance:()=>A,element:()=>re,float:()=>O,int:()=>te,normalRange:()=>k,pop:()=>T,push:()=>w,range:()=>ne,reset:()=>D,shuffle:()=>oe,weighted:()=>ie,weightedKey:()=>ae,withSeed:()=>E});function ee(){return le()}function w(e){let t=new j(e);return ce.push(t),t}function T(){if(ce.length===1)throw Error(`the base random generator cannot be popped`);ce.pop()}function E(e,t){w(e);try{return t()}finally{T()}}function D(){ce.length=0,ce.push(new j)}function O(e,t,n){let r=n??le();return e===void 0?r.float():t===void 0?r.float()*e:e+r.float()*(t-e)}function te(e,t,n){let r=n??le();return t===void 0?r.int(e):e+r.int(t-e)}function ne(e,t,n){return e+(n??le()).int(t-e+1)}function k(e,t,n){let r=n??le();return e+Math.floor((r.float()+r.float())*(t-e+1)/2)}function A(e,t){return(t??le()).float()<e}function re(e,t){return e.length>0?e[(t??le()).int(e.length)]:null}function ie(e,t){let n=0;for(let t of e)n+=t;if(n<=0)return null;let r=(t??le()).float()*n;for(let t=0;t<e.length;t++)if(r-=e[t],r<0)return t;return e.length-1}function ae(e,t){let n=[...e.keys()],r=ie(n.map(t=>e.get(t)??0),t);return r===null?null:n[r]}function oe(e,t){for(let n=e.length-1;n>0;n--){let r=(t??le()).int(n+1);[e[n],e[r]]=[e[r],e[n]]}return e}function se(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return t>>>0}var j,ce,le,ue,de,fe,pe,me,he,ge,_e=s((()=>{j=class{constructor(e){this.s0=0,this.s1=0,this.s2=0,this.s3=0,this.seed=e===void 0?Math.random()*4294967296>>>0:e>>>0;let t=this.seed,n=()=>{t=t+2654435769>>>0;let e=t;return e=Math.imul(e^e>>>16,569420461),e=Math.imul(e^e>>>15,1935289751),(e^e>>>15)>>>0};this.s0=n(),this.s1=n(),this.s2=n(),this.s3=n(),(this.s0|this.s1|this.s2|this.s3)===0&&(this.s0=1)}nextUint32(){let e=Math.imul(this.rotl(Math.imul(this.s1,5),7),9)>>>0>>>0,t=this.s1<<9>>>0;return this.s2^=this.s0,this.s3^=this.s1,this.s1^=this.s2,this.s0^=this.s3,this.s2^=t,this.s3=this.rotl(this.s3,11),e}float(){return this.nextUint32()/4294967296}int(e){if(e<=0)return 0;let t=4294967296-4294967296%e,n=this.nextUint32();for(;n>=t;)n=this.nextUint32();return n%e}getState(){return[this.s0,this.s1,this.s2,this.s3]}setState(e){[this.s0,this.s1,this.s2,this.s3]=e}rotl(e,t){return(e<<t|e>>>32-t)>>>0}},ce=[new j],le=()=>ce[ce.length-1],ue=624,de=397,fe=2567483615,pe=2147483648,me=2147483647,he=class{constructor(e=5489){this.state=new Uint32Array(ue),this.index=ue,this.seedValue=5489,this.produced=0,this.seed(e)}seed(e){this.seedValue=e>>>0,this.state[0]=this.seedValue;for(let e=1;e<ue;e++){let t=this.state[e-1]^this.state[e-1]>>>30;this.state[e]=Math.imul(1812433253,t)+e>>>0}this.index=ue,this.produced=0}generate(){for(let e=0;e<ue;e++){let t=this.state[e]&pe|this.state[(e+1)%ue]&me,n=this.state[(e+de)%ue]^t>>>1;t&1&&(n^=fe),this.state[e]=n>>>0}this.index=0}nextUint32(){this.index>=ue&&this.generate();let e=this.state[this.index++];return e^=e>>>11,e^=e<<7&2636928640,e^=e<<15&4022730752,e^=e>>>18,this.produced++,e>>>0}float(){return this.nextUint32()/4294967296}int(e){if(e<=0)return 0;let t=4294967296-4294967296%e,n=this.nextUint32();for(;n>=t;)n=this.nextUint32();return n%e}discard(e){for(let t=0;t<e;t++)this.nextUint32()}get discardCount(){return this.produced}getState(){return{seed:this.seedValue,state:[...this.state],index:this.index,discard:this.produced}}setState(e){this.seedValue=e.seed>>>0;for(let t=0;t<ue;t++)this.state[t]=(e.state[t]??0)>>>0;this.index=e.index,this.produced=e.discard}},ge=class{constructor(e=0){this.streams=new Map,this.baseSeed=e>>>0}stream(e){let t=this.streams.get(e);if(!t){let n=(this.baseSeed^se(e))>>>0;t={seed:n,engine:new he(n)},this.streams.set(e,t)}return t.engine}seedOf(e){return this.streams.get(e)?.seed}reseed(e){this.baseSeed=e>>>0,this.streams.clear()}names(){return[...this.streams.keys()]}getState(){let e={};for(let[t,n]of this.streams)e[t]=n.engine.getState();return e}setState(e){for(let[t,n]of Object.entries(e)){let e=new he(n.seed);e.setState(n),this.streams.set(t,{seed:n.seed,engine:e})}}}})),ve=l({DEFAULT_BINDINGS:()=>je,actionsForKey:()=>Pe,attach:()=>ht,attachSwipe:()=>mt,bind:()=>Me,bindAxis:()=>at,bindButton:()=>it,bindTouch:()=>lt,detach:()=>gt,dispatchAction:()=>Te,dispatchComposition:()=>Ee,dispatchText:()=>we,endFrame:()=>Ke,exportBindings:()=>Le,gamepadAxisCode:()=>rt,gamepadButtonCode:()=>nt,importBindings:()=>Re,isDown:()=>Ue,justPressed:()=>We,justReleased:()=>Ge,keysFor:()=>Ie,onAction:()=>P,onComposition:()=>F,onKey:()=>xe,onText:()=>Se,onWheel:()=>De,pollGamepads:()=>ot,pressTouch:()=>ut,releaseTouch:()=>dt,resetBindings:()=>ze,rumble:()=>st,textFromKey:()=>Ce,touchCode:()=>ct,unbind:()=>Fe,wheelActionFor:()=>Oe}),M=new Map,N=new Set,ye=new Set,be=new Set,P=new p(!0),xe=new p(!0),Se=new p(!0),F=new p(!0);function Ce(e){return e.isComposing||e.ctrlKey||e.metaKey||e.altKey?null:e.key.length===1?e.key:null}function we(e){e.length>0&&Se.dispatch(e)}function Te(e){P.dispatch(e)}function Ee(e){F.dispatch({phase:e.phase,text:e.text})}var De=new p(!0);function Oe(e){return e.ctrlKey||e.metaKey?`zoom`:e.shiftKey?`scrollHorizontal`:`scroll`}function ke(e){let t=Oe(e);t===`zoom`&&e.preventDefault();let n=t===`scrollHorizontal`&&e.deltaX!==0?e.deltaX:e.deltaY;De.dispatch({action:t,delta:n})}var Ae=!1,je={up:[`ArrowUp`,`KeyW`,`Numpad8`],down:[`ArrowDown`,`KeyS`,`Numpad2`],left:[`ArrowLeft`,`KeyA`,`Numpad4`],right:[`ArrowRight`,`KeyD`,`Numpad6`],upLeft:[`Numpad7`],upRight:[`Numpad9`],downLeft:[`Numpad1`],downRight:[`Numpad3`],wait:[`Numpad5`,`Period`],confirm:[`Enter`,`Space`,`NumpadEnter`],cancel:[`Escape`,`Backspace`],menu:[`KeyI`,`Tab`]};function Me(e,t){M.set(e,new Set(t))}function Ne(e,t){let n=M.get(e)??new Set;for(let e of t)n.add(e);M.set(e,n)}function Pe(e){return Be(e)}function Fe(e){M.delete(e)}function Ie(e){return[...M.get(e)??[]]}function Le(){let e={};for(let[t,n]of M)e[t]=[...n];return e}function Re(e){M.clear();for(let[t,n]of Object.entries(e))Me(t,n)}function ze(){Re(je)}ze();function Be(e){let t=[];for(let[n,r]of M)r.has(e)&&t.push(n);return t}function Ve(e){if(!N.has(e)){N.add(e);for(let t of Be(e))ye.add(t),P.dispatch(t)}}function He(e){if(N.has(e)){N.delete(e);for(let t of Be(e))be.add(t)}}function Ue(e){let t=M.get(e);if(!t)return!1;for(let e of t)if(N.has(e))return!0;return!1}function We(e){return ye.has(e)}function Ge(e){return be.has(e)}function Ke(){ye.clear(),be.clear()}function qe(e){let t=Ce(e);t!==null&&we(t)}function Je(e){if(e.repeat){xe.dispatch(e),qe(e);return}Ve(e.code),xe.dispatch(e),qe(e)}function Ye(e){He(e.code)}function Xe(e){Ee({phase:`start`,text:e.data??``})}function Ze(e){Ee({phase:`update`,text:e.data??``})}function Qe(e){Ee({phase:`end`,text:e.data??``})}function $e(){N.clear(),ye.clear(),be.clear()}var et=.5,tt=new Set;function nt(e,t){return`Gamepad${e}Button${t}`}function rt(e,t,n){return`Gamepad${e}Axis${t}${n>0?`+`:`-`}`}function it(e,t,n){Ne(e,n.map(e=>nt(t,e)))}function at(e,t,n,r){Ne(e,[rt(t,n,r)])}function ot(e=typeof navigator?.getGamepads==`function`?navigator.getGamepads():[]){tt.clear();for(let t of e)if(t){for(let e=0;e<t.buttons.length;e++)t.buttons[e].pressed&&tt.add(nt(t.index,e));for(let e=0;e<t.axes.length;e++){let n=t.axes[e];n>=et?tt.add(rt(t.index,e,1)):n<=-.5&&tt.add(rt(t.index,e,-1))}}for(let e of tt)Ve(e);for(let e of N)!tt.has(e)&&e.startsWith(`Gamepad`)&&He(e)}function st(e,t,n=typeof navigator?.getGamepads==`function`?navigator.getGamepads():[]){(n[e]?.vibrationActuator)?.playEffect(`dual-rumble`,{duration:t.duration,weakMagnitude:t.weakMagnitude??1,strongMagnitude:t.strongMagnitude??1})}function ct(e){return`Touch:${e}`}function lt(e,t=e){Ne(e,[ct(t)])}function ut(e){Ve(ct(e))}function dt(e){He(ct(e))}var ft={up:`up`,down:`down`,left:`left`,right:`right`,upLeft:`upLeft`,upRight:`upRight`,downLeft:`downLeft`,downRight:`downRight`},pt=[`right`,`downRight`,`down`,`downLeft`,`left`,`upLeft`,`up`,`upRight`];function mt(e,t={}){let n={...ft,...t.actions},r=t.minDistance??24;for(let e of[...pt,`tap`]){let t=n[e];t&&lt(t,`swipe:${e}`)}let i=!1,a=-1,o=0,s=0;function c(e){ut(`swipe:${e}`),dt(`swipe:${e}`)}function l(e){i=!0,a=e.pointerId,o=e.clientX,s=e.clientY}function u(e){if(!i||e.pointerId!==a)return;i=!1;let t=e.clientX-o,l=e.clientY-s;if(Math.hypot(t,l)<r){n.tap&&c(`tap`);return}let u=pt[(Math.round(Math.atan2(l,t)/(Math.PI/4))%8+8)%8];n[u]&&c(u)}return e.addEventListener(`pointerdown`,l),e.addEventListener(`pointerup`,u),e.addEventListener(`pointercancel`,u),()=>{e.removeEventListener(`pointerdown`,l),e.removeEventListener(`pointerup`,u),e.removeEventListener(`pointercancel`,u)}}function ht(e=window){Ae||(Ae=!0,e.addEventListener(`keydown`,Je),e.addEventListener(`keyup`,Ye),e.addEventListener(`compositionstart`,Xe),e.addEventListener(`compositionupdate`,Ze),e.addEventListener(`compositionend`,Qe),window.addEventListener(`blur`,$e),e.addEventListener(`wheel`,ke,{passive:!1}))}function gt(e=window){Ae&&(Ae=!1,e.removeEventListener(`keydown`,Je),e.removeEventListener(`keyup`,Ye),e.removeEventListener(`compositionstart`,Xe),e.removeEventListener(`compositionupdate`,Ze),e.removeEventListener(`compositionend`,Qe),e.removeEventListener(`wheel`,ke),window.removeEventListener(`blur`,$e),$e())}var _t=class{constructor(e,t={}){if(!e)throw Error(`a player needs a non-empty id`);this.id=e,this.padIndex=t.padIndex}scoped(e){return`${this.id}:${e}`}bind(e,t){Me(this.scoped(e),t)}bindButton(e,t){if(this.padIndex===void 0)throw Error(`player "${this.id}" has no padIndex to bind a gamepad button to`);it(this.scoped(e),this.padIndex,t)}bindAxis(e,t,n){if(this.padIndex===void 0)throw Error(`player "${this.id}" has no padIndex to bind a gamepad axis to`);at(this.scoped(e),this.padIndex,t,n)}bindTouch(e,t=e){lt(this.scoped(e),`${this.id}:${t}`)}pressTouch(e){ut(`${this.id}:${e}`)}releaseTouch(e){dt(`${this.id}:${e}`)}isDown(e){return Ue(this.scoped(e))}justPressed(e){return We(this.scoped(e))}justReleased(e){return Ge(this.scoped(e))}keysFor(e){return Ie(this.scoped(e))}},vt=25214903917n,yt=11n,bt=(1n<<48n)-1n,xt=class{constructor(e=0,t={}){this.state=0n,this.onDraw=t.onDraw,this.setSeed(e)}setSeed(e){this.state=(BigInt.asIntN(64,BigInt(e))^vt)&bt}next(e){if(!Number.isInteger(e)||e<1||e>32)throw Error(`next needs 1 to 32 bits, got ${e}`);this.state=this.state*vt+yt&bt;let t=Number(this.state>>BigInt(48-e)),n=e===32?t|0:t;return this.onDraw?.({bits:e,value:n}),n}nextInt(e){if(e===void 0)return this.next(32);if(!Number.isInteger(e)||e<=0||e>2147483647)throw Error(`nextInt needs a bound from 1 to 2147483647, got ${e}`);if((e&-e)===e)return Math.floor(e*this.next(31)/2147483648);let t,n;do t=this.next(31),n=t%e;while(t-n+(e-1)>2147483647);return n}nextLong(){let e=BigInt(this.next(32)),t=BigInt(this.next(32));return BigInt.asIntN(64,(e<<32n)+t)}nextDouble(){return(this.next(26)*134217728+this.next(27))/2**53}nextFloat(){return this.next(24)/16777216}nextBoolean(){return this.next(1)!==0}};_e();function St(e,t){if(!t)throw Error(`scramble needs a non-empty key`);let n=new TextEncoder().encode(e),r=new TextEncoder().encode(t),i=new Uint8Array(n.length);for(let e=0;e<n.length;e++)i[e]=n[e]^r[e%r.length];return wt(i)}function Ct(e,t){if(!t)throw Error(`scramble needs a non-empty key`);let n=Tt(e),r=new TextEncoder().encode(t),i=new Uint8Array(n.length);for(let e=0;e<n.length;e++)i[e]=n[e]^r[e%r.length];return new TextDecoder(`utf-8`,{fatal:!0}).decode(i)}function wt(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t)}function Tt(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}var Et=10485760;function Dt(e,t={}){let n=t.maxBytes??Et,r=typeof e==`string`?new TextEncoder().encode(e).length:e.length;if(r>n)throw Error(`inbound data exceeds the ${n}-byte limit (${r} bytes)`)}function Ot(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n!==9&&n!==10&&n!==13&&(n<=31||n===127))throw Error(`inbound data contains a control character (0x${n.toString(16).padStart(2,`0`)}) at index ${t}`)}}function kt(e,t={}){return Dt(e,t),Ot(e),e}var At=new Set([`__proto__`,`constructor`,`prototype`]);function jt(e,t=`$`){if(Array.isArray(e)){e.forEach((e,n)=>jt(e,`${t}[${n}]`));return}if(typeof e==`object`&&e)for(let n of Object.keys(e)){if(At.has(n))throw Error(`${t} contains a forbidden key "${n}"`);jt(e[n],`${t}.${n}`)}}function Mt(e,t,n=`$`){if(e===void 0){if(t.optional)return;throw Error(`${n} is required`)}switch(t.type){case`string`:if(typeof e!=`string`)throw Error(`${n} must be a string`);return;case`number`:if(typeof e!=`number`||!Number.isFinite(e))throw Error(`${n} must be a finite number`);if(t.min!==void 0&&e<t.min)throw Error(`${n} must be >= ${t.min}`);if(t.max!==void 0&&e>t.max)throw Error(`${n} must be <= ${t.max}`);return;case`boolean`:if(typeof e!=`boolean`)throw Error(`${n} must be a boolean`);return;case`array`:if(!Array.isArray(e))throw Error(`${n} must be an array`);if(t.maxLength!==void 0&&e.length>t.maxLength)throw Error(`${n} exceeds its maximum length of ${t.maxLength}`);e.forEach((e,r)=>Mt(e,t.items,`${n}[${r}]`));return;case`object`:if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`${n} must be an object`);for(let t of Object.keys(e))if(At.has(t))throw Error(`${n} contains a forbidden key "${t}"`);for(let[r,i]of Object.entries(t.fields))Mt(e[r],i,`${n}.${r}`);return}}function Nt(e,t={}){let n=t.label??`inbound data`;kt(e,t);try{return JSON.parse(e,(e,t)=>{if(At.has(e))throw new Pt(e);return t})}catch(e){throw e instanceof Pt?Error(`${n} contains a forbidden key "${e.key}"`):Error(`${n} is not valid JSON (${e instanceof Error?e.message:String(e)})`)}}var Pt=class{constructor(e){this.key=e}};function Ft(e,t){let n=Nt(e,{label:t}),r=n?.meta;if(typeof n!=`object`||!n||Array.isArray(n)||!(`state`in n))throw Error(`${t} is not save data (expected { meta, state })`);if(typeof r!=`object`||!r||!Number.isSafeInteger(r.version)||r.version<0)throw Error(`${t} has no valid meta.version`);if(typeof r.savedAt!=`number`||!Number.isFinite(r.savedAt))throw Error(`${t} has no valid meta.savedAt`);return n}var It=class{constructor(){this.data=new Map}read(e){return this.data.get(e)??null}write(e,t){this.data.set(e,t)}remove(e){this.data.delete(e)}keys(){return[...this.data.keys()]}};function Lt(){return typeof localStorage>`u`?new It:{read:e=>localStorage.getItem(e),write:(e,t)=>localStorage.setItem(e,t),remove:e=>localStorage.removeItem(e),keys:()=>Object.keys(localStorage)}}var Rt=class{constructor(e){this.namespace=e.namespace,this.version=e.version,this.migrations=e.migrations??{},this.storage=e.storage??Lt()}key(e){return`mwg-save:${this.namespace}:${e}`}save(e,t,n){let r={meta:{version:this.version,savedAt:Date.now(),preview:n},state:t};this.storage.write(this.key(e),JSON.stringify(r))}load(e){let t=this.storage.read(this.key(e));if(!t)return null;try{let n=Ft(t,`save slot "${e}"`),r=n.state;for(let e=n.meta.version;e<this.version;e++)r=(this.migrations[e]??(e=>e))(r);return{meta:{...n.meta,version:this.version},state:r}}catch{return null}}importExternal(e,t,n,r){Dt(t);let i=n(t);for(let e=0;e<this.version;e++)i=(this.migrations[e]??(e=>e))(i);let a={meta:{version:this.version,savedAt:Date.now(),preview:r},state:i};this.storage.write(this.key(e),JSON.stringify(a))}delete(e){this.storage.remove(this.key(e))}exportSlot(e,t){let n=this.storage.read(this.key(e));return n===null?null:t?St(n,t):n}importSlot(e,t,n){Dt(t);let r=Ft(n?Ct(t,n):t,`SaveSystem.importSlot: payload`),i=r.state;for(let e=r.meta.version;e<this.version;e++)i=(this.migrations[e]??(e=>e))(i);let a={meta:{...r.meta,version:this.version},state:i};this.storage.write(this.key(e),JSON.stringify(a))}list(){let e=`mwg-save:${this.namespace}:`,t=[];for(let n of this.storage.keys()){if(!n.startsWith(e))continue;let r=this.storage.read(n);if(r)try{t.push({slot:n.slice(e.length),meta:Ft(r,n).meta})}catch{}}return t}};function zt(e,t=`value`){return Bt(e,t,new Set)}function Bt(e,t,n){if(typeof e==`function`||typeof e==`symbol`)return t;if(typeof e!=`object`||!e||n.has(e)||(n.add(e),Vt(e)))return null;let r=[];if(e instanceof Map)for(let[n,i]of e)r.push([`${t}.get(${JSON.stringify(n)??String(n)})`,i]);else if(e instanceof Set)for(let n of e)r.push([`${t}.item`,n]);else if(Array.isArray(e))e.forEach((e,n)=>r.push([`${t}[${n}]`,e]));else for(let[n,i]of Object.entries(e))r.push([`${t}.${n}`,i]);for(let[e,t]of r){let r=Bt(t,e,n);if(r)return r}return t}function Vt(e){try{return structuredClone(e),!0}catch{return!1}}function Ht(e,t){try{return structuredClone(e)}catch(n){let r=zt(e,t)??t;throw TypeError(`${r} cannot be structured-cloned (${n instanceof Error?n.message:String(n)}). Journals, snapshots and undo checkpoints copy their contents with structuredClone, so they must hold plain data: refer to a live object (an actor, anything carrying callbacks such as a ReactionTable) by its id and resolve it inside the rule.`,{cause:n})}}var Ut=class{constructor(e,t={}){this._state=Ht(e,`initial state`),this.version=t.version??1,this.migrations=t.migrations??{},this.extensions=t.extensions??new Wt}get state(){return structuredClone(this._state)}set(e){this._state=Ht(e,`state`)}update(e){let t=e(this.state);return this.set(t),this.state}snapshot(){let e=this.extensions.snapshot();return{version:this.version,state:this.state,extensions:e.extensions,extensionVersions:e.versions}}restore(e,t={}){if(!Number.isSafeInteger(e.version)||e.version<1)throw Error(`canonical state snapshot version must be a positive integer`);if(e.version>this.version)throw Error(`canonical state snapshot version ${e.version} is newer than ${this.version}`);let n=this.snapshot();try{let n=Ht(e.state,`snapshot.state`);for(let t=e.version;t<this.version;t++){let e=this.migrations[t+1];if(!e)throw Error(`missing canonical state migration to version ${t+1}`);n=e(n)}return this._state=Ht(n,`migrated state`),this.extensions.restore({extensions:e.extensions,versions:e.extensionVersions},t)}catch(e){throw this._state=structuredClone(n.state),this.extensions.restore({extensions:n.extensions,versions:n.extensionVersions},{missing:`keep`}),e}}transaction(e){let t=this.snapshot();try{return e(this)}catch(e){throw this.restore(t),e}}},Wt=class{constructor(){this.extensions=new Map}register(e){if(!/^[A-Za-z_][A-Za-z0-9_.-]*$/.test(e.id))throw Error(`invalid state extension id: ${e.id}`);if(this.extensions.has(e.id))throw Error(`state extension already registered: ${e.id}`);return this.extensions.set(e.id,{id:e.id,capture:()=>e.capture(),restore:t=>e.restore(t),version:e.version??1,migrations:e.migrations,reset:e.reset,remove:e.remove}),()=>this.extensions.delete(e.id)}snapshot(){let e={};for(let[t,n]of this.extensions)e[t]=Ht(n.capture(),`extension ${t}`);let t={};for(let[e,n]of this.extensions)t[e]=n.version??1;return{extensions:e,versions:t}}restore(e,t={}){let n=this.snapshot(),r=[];try{for(let[n,i]of this.extensions){if(!(n in e.extensions)){t.missing===`reset`?(i.reset&&i.reset(),r.push({extension:n,from:0,to:i.version??1,status:`reset`})):t.missing===`remove`&&(i.remove&&i.remove(),r.push({extension:n,from:0,to:i.version??1,status:`removed`}));continue}let a=e.versions?.[n]??1,o=i.version??1,s=Ht(e.extensions[n],`snapshot.extensions.${n}`);for(let e=a;e<o;e++){let t=i.migrations?.[e+1];if(!t)throw Error(`missing state migration for ${n} to version ${e+1}`);s=t(s)}i.restore(Ht(s,`migrated extension ${n}`)),r.push({extension:n,from:a,to:o,status:a===o?`unchanged`:`migrated`})}}catch(e){for(let[e,t]of this.extensions)e in n.extensions&&t.restore(structuredClone(n.extensions[e]));throw e}for(let e of r)t.onDiagnostic?.(e);return r}transaction(e){let t=this.snapshot();try{return e()}catch(e){throw this.restore(t),e}}},Gt=new Set([`localhost`,`127.0.0.1`,`[::1]`]);function Kt(e,t,n=!1){if(n||!/^[a-z][a-z0-9+.-]*:/i.test(e))return;let r=new URL(e);if(r.protocol!==`https:`&&r.protocol!==`wss:`&&(r.protocol!==`http:`&&r.protocol!==`ws:`||!Gt.has(r.hostname)))throw Error(`${t} url must use https: or wss: (got ${r.protocol}//${r.host}); pass allowInsecure: true to accept it`)}var qt=class{constructor(e,t){if(!e.endpoint)throw Error(`${t} endpoint is required`);if(Kt(e.endpoint,`${t} endpoint`,e.allowInsecure),this.endpoint=e.endpoint,this.label=t,this.maxResponseBytes=e.maxResponseBytes??10485760,this.timeoutMs=e.timeoutMs??1e4,!(this.timeoutMs>0))throw Error(`${t} timeout must be positive`);if(this.fetchFn=e.fetch??globalThis.fetch,!this.fetchFn)throw Error(`fetch is unavailable; provide ${t}Options.fetch`)}async withTimeout(e){let t=new AbortController,n=setTimeout(()=>t.abort(),this.timeoutMs);try{return await e(t.signal)}finally{clearTimeout(n)}}async readText(e){let t=this.maxResponseBytes,n=Number(e.headers?.get?.(`content-length`));if(n>t)throw Error(`${this.label} response exceeds the ${t}-byte limit (${n} bytes)`);if(!e.body){let n=await e.text();return Dt(n,{maxBytes:t}),n}let r=e.body.getReader(),i=[],a=0;for(;;){let{done:e,value:n}=await r.read();if(e)break;if(a+=n.byteLength,a>t)throw await r.cancel(),Error(`${this.label} response exceeds the ${t}-byte limit`);i.push(n)}let o=new Uint8Array(a),s=0;for(let e of i)o.set(e,s),s+=e.byteLength;return new TextDecoder().decode(o)}async readJson(e,t){return Nt(await this.readText(e),{maxBytes:this.maxResponseBytes,label:`${this.label} ${t}`})}},Jt=class extends qt{constructor(e){super(e,`save sync`)}async upload(e,t){if(!e)throw Error(`save sync slot name is required`);if(!t)throw Error(`save sync payload cannot be empty`);return this.withTimeout(async n=>{let r=await this.fetchFn(this.slotUrl(e),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({payload:t}),signal:n});if(!r.ok)throw Error(`save upload failed with HTTP ${r.status}`);return{ok:!0,status:r.status}})}async download(e){if(!e)throw Error(`save sync slot name is required`);return this.withTimeout(async t=>{let n=await this.fetchFn(this.slotUrl(e),{signal:t});if(!n.ok)throw Error(`save download failed with HTTP ${n.status}`);let r=await this.readJson(n,`download`);if(typeof r?.payload!=`string`)throw Error(`save download response missing a string payload`);return r.payload})}async list(){return this.withTimeout(async e=>{let t=await this.fetchFn(this.endpoint,{signal:e});if(!t.ok)throw Error(`save slot list failed with HTTP ${t.status}`);let n=await this.readJson(t,`slot list`);if(!Array.isArray(n?.slots)||!n.slots.every(e=>typeof e==`string`))throw Error(`save slot list response missing a string array of slots`);return n.slots})}slotUrl(e){let t=this.endpoint.includes(`?`)?`&`:`?`;return`${this.endpoint}${t}slot=${encodeURIComponent(e)}`}},Yt=1,Xt=class{constructor(e){if(this.onWelcome=new p,this.onTick=new p,this.onReject=new p,this.onDesync=new p,this.onClose=new p,this.onProtocolError=new p,this.socket=null,this._id=null,!e.url)throw Error(`lockstep client url is required`);Kt(e.url,`lockstep client`,e.allowInsecure),this.url=e.url,this.createSocket=e.create??(e=>new WebSocket(e)),this.validateInput=e.validateInput,this.maxMessageBytes=e.maxMessageBytes??1048576}get id(){return this._id}get connected(){return this.socket!==null&&this.socket.readyState===Yt}connect(){if(this.socket)throw Error(`lockstep client is already connected`);let e=this.createSocket(this.url);e.onmessage=e=>this.handleMessage(e.data),e.onclose=()=>{this.socket=null,this._id=null,this.onClose.dispatch()},this.socket=e}submitInput(e,t){if(!this.connected)return;let n=this.validateInput?.(e);if(n===!1||typeof n==`string`){this.onReject.dispatch({reason:n===!1?`input rejected by client validation`:n});return}this.socket?.send(JSON.stringify({type:`input`,payload:e,...t===void 0?{}:{checksum:t}}))}close(){this.socket?.close()}handleMessage(e){let t;try{if(typeof e!=`string`)throw Error(`lockstep message is not text`);t=Qt(Nt(e,{maxBytes:this.maxMessageBytes,label:`lockstep message`}))}catch(e){this.onProtocolError.dispatch({reason:e instanceof Error?e.message:String(e)});return}if(t.type===`welcome`)this._id=t.id,this.onWelcome.dispatch({id:t.id,...t.seed===void 0?{}:{seed:t.seed},...t.initialState===void 0?{}:{initialState:t.initialState}});else if(t.type===`tick`){let e={tick:t.tick,inputs:t.inputs,...t.checksums===void 0?{}:{checksums:t.checksums}};if(this.onTick.dispatch(e),t.checksums){let e=Object.values(t.checksums);e.some(t=>t!==e[0])&&this.onDesync.dispatch({tick:t.tick,checksums:t.checksums})}}else this.onReject.dispatch({reason:t.reason??`input rejected by server`})}},Zt=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function Qt(e){if(!Zt(e)||typeof e.type!=`string`)throw Error(`lockstep message has no type`);switch(e.type){case`welcome`:if(typeof e.id!=`string`||e.id===``)throw Error(`welcome needs a string id`);if(e.seed!==void 0&&!Number.isSafeInteger(e.seed))throw Error(`welcome seed must be an integer`);return e;case`tick`:if(!Number.isSafeInteger(e.tick)||e.tick<0)throw Error(`tick needs a non-negative integer tick`);if(!Zt(e.inputs))throw Error(`tick needs an inputs object`);if(e.checksums!==void 0&&(!Zt(e.checksums)||Object.values(e.checksums).some(e=>typeof e!=`number`)))throw Error(`tick checksums must map ids to numbers`);return e;case`rejected`:if(e.reason!==void 0&&typeof e.reason!=`string`)throw Error(`rejected reason must be a string`);return e;default:throw Error(`unknown lockstep message type "${e.type}"`)}}var $t=class{constructor(e,t){this.storage=e,this.key=t}read(e){let t=this.storage.read(this.key);return t?Nt(t,{label:`stored value "${this.key}"`}):e}write(e){this.storage.write(this.key,JSON.stringify(e))}remove(){this.storage.remove(this.key)}},en=class{constructor(e){this.store=new $t(e.storage??Lt(),`mwg-runs:${e.namespace}`),this.limit=e.limit}readAll(){return this.store.read([])}record(e){let t=this.readAll(),n={id:`${Date.now()}-${t.length}`,endedAt:Date.now(),summary:e};return t.push(n),this.limit!==void 0&&t.length>this.limit&&t.splice(0,t.length-this.limit),this.store.write(t),n}all(){return this.readAll()}ranked(e,t=`desc`){let n=this.readAll(),r=t===`desc`?-1:1;return n.sort((t,n)=>r*(e(t.summary)-e(n.summary)))}clear(){this.store.remove()}},tn=class{constructor(e){this.store=new $t(e.storage??Lt(),`mwg-stats:${e.namespace}`),this.initial=e.initial,this.combine=e.combine}get(){return this.store.read(this.initial)}record(e){let t=this.combine(this.get(),e);return this.store.write(t),t}reset(){this.store.remove()}},nn=class extends qt{constructor(e){super(e,`telemetry`),this.consented=!1,this.maxStringLength=e.maxStringLength??256,this.maxProperties=e.maxProperties??32,this.allowed=e.allowedProperties?new Set(e.allowedProperties):null}get hasConsent(){return this.consented}setConsent(e){this.consented=e}async send(e){if(!e.name)throw Error(`telemetry event needs a name`);return this.consented?this.withTimeout(async t=>{let n=await this.fetchFn(this.endpoint,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(this.bounded(e)),signal:t});if(!n.ok)throw Error(`telemetry request failed with HTTP ${n.status}`);return{ok:!0,status:n.status}}):null}bounded(e){let t=e=>e.length>this.maxStringLength?e.slice(0,this.maxStringLength):e;if(!e.properties)return{name:t(e.name)};let n={},r=0;for(let[i,a]of Object.entries(e.properties))if(!this.allowed||this.allowed.has(i)){if(r++>=this.maxProperties)break;n[t(i)]=typeof a==`string`?t(a):a}return{name:t(e.name),properties:n}}},rn=class extends qt{constructor(e){super(e,`news`)}async fetchItems(){return this.withTimeout(async e=>{let t=await this.fetchFn(this.endpoint,{signal:e});if(!t.ok)throw Error(`news request failed with HTTP ${t.status}`);let n=await this.readJson(t,`response`);if(!Array.isArray(n))throw Error(`news response was not an array`);return n.map((e,t)=>an(e,t))})}};function an(e,t){if(typeof e!=`object`||!e)throw Error(`news item ${t} was not an object`);let n=e;if(typeof n.id!=`string`||!n.id)throw Error(`news item ${t} is missing a string id`);if(typeof n.title!=`string`)throw Error(`news item ${t} is missing a string title`);if(typeof n.body!=`string`)throw Error(`news item ${t} is missing a string body`);return{id:n.id,title:n.title,body:n.body,publishedAt:typeof n.publishedAt==`number`?n.publishedAt:void 0}}var on=class{constructor(e){this.store=new $t(e.storage??Lt(),`mwg-news-seen:${e.namespace}`)}readSeen(){return new Set(this.store.read([]))}isSeen(e){return this.readSeen().has(e)}markSeen(e){let t=this.readSeen();t.add(e),this.store.write([...t])}unseen(e){let t=this.readSeen();return e.filter(e=>!t.has(e.id))}},sn=class{constructor(e,t={}){if(!e)throw Error(`a collection needs a name`);this.prefix=`mwg-db:${t.namespace??`default`}:${e}:`,this.storage=t.storage??Lt()}get size(){return this.keys().length}all(){return this.keys().map(e=>this.read(e))}get(e){let t=this.storage.read(this.prefix+e);return t===null?void 0:this.parse(t,this.prefix+e)}put(e){if(typeof e!=`object`||!e||Array.isArray(e)||typeof e.id!=`string`||e.id===``)throw Error(`a record must be an object with a string id`);this.storage.write(this.prefix+e.id,JSON.stringify(e))}remove(e){this.storage.remove(this.prefix+e)}where(e){return this.all().filter(e)}clear(){for(let e of this.keys())this.storage.remove(e)}keys(){return this.storage.keys().filter(e=>e.startsWith(this.prefix))}read(e){return this.parse(this.storage.read(e),e)}parse(e,t){return Nt(e,{label:`record "${t}"`})}},cn=class{constructor(e,t,n){if(this.recorded=[],this.fromFrame=n?.fromFrame??0,!Number.isInteger(this.fromFrame)||this.fromFrame<0)throw RangeError(`a resumed recorder needs a non-negative fromFrame`);this.frameStamp=this.fromFrame,this.actions=e,this.frames=t,this.onAction=e=>{this.recorded.push({frame:this.frameStamp,action:e})},this.onFrame=()=>{this.frameStamp++},e.add(this.onAction),t.add(this.onFrame)}get events(){return this.recorded}get frame(){return this.frameStamp}toJSON(){return this.recorded.map(e=>({frame:e.frame,action:e.action}))}stop(){this.actions.remove(this.onAction),this.frames.remove(this.onFrame)}},ln=class{constructor(e,t,n,r){if(this.events=e,this.dispatch=t,this.frames=n,this.fromFrame=r?.fromFrame??0,!Number.isInteger(this.fromFrame)||this.fromFrame<0)throw RangeError(`a resumed player needs a non-negative fromFrame`);this.index=this.events.findIndex(e=>e.frame>=this.fromFrame),this.index<0&&(this.index=this.events.length),this.frame=this.fromFrame,this.onFrame=()=>this.pump(),n.add(this.onFrame)}get done(){return this.index>=this.events.length}stop(){this.frames.remove(this.onFrame)}pump(){for(;this.index<this.events.length&&this.events[this.index].frame<=this.frame;)this.dispatch(this.events[this.index].action),this.index++;this.frame++}};function un(e){return JSON.stringify(e)}function dn(e){return fn(JSON.parse(e))}function fn(e){if(!Array.isArray(e))throw Error(`a replay must be an array of {frame, action}`);return e.map(e=>{if(typeof e!=`object`||!e||!Number.isInteger(e.frame)||e.frame<0||typeof e.action!=`string`)throw Error(`a replay entry must be {frame: a non-negative integer, action: a string}`);return{frame:e.frame,action:e.action}})}function pn(e,t){if(typeof t!=`string`||!t.length)throw TypeError(`a replay file needs a non-empty ${e}`);return t}function mn(e){let t=e;if(!Number.isInteger(t)||t<0||t>4294967295)throw RangeError(`a replay seed must be uint32`);return t}function hn(e,t){let n={format:`mwg-replay`,version:1,framework:pn(`framework`,t.framework),game:pn(`game`,t.game),events:fn(e)};if(t.seed!==void 0&&(n.seed=mn(t.seed)),t.recordedAt!==void 0){if(typeof t.recordedAt!=`number`||!Number.isFinite(t.recordedAt))throw TypeError(`recordedAt must be a finite number`);n.recordedAt=t.recordedAt}return JSON.stringify(n)}function gn(e,t){let n=Nt(e,{label:`replay file`});if(typeof n!=`object`||!n||Array.isArray(n))throw Error(`a replay file must be a JSON object`);if(n.format!==`mwg-replay`)throw Error(`not a replay file: expected format "mwg-replay", found ${JSON.stringify(n.format)}`);if(n.version!==1)throw Error(`replay file version ${JSON.stringify(n.version)} is not supported (this build reads 1)`);if(n.game!==t.game)throw Error(`a replay of ${JSON.stringify(n.game)} cannot be imported into ${JSON.stringify(t.game)}`);if(n.framework!==t.framework)throw Error(`a replay recorded against mwg ${JSON.stringify(n.framework)} cannot be imported into ${JSON.stringify(t.framework)}`);let r=fn(n.events);return{format:`mwg-replay`,version:1,framework:n.framework,game:n.game,...n.seed===void 0?{}:{seed:mn(n.seed)},...n.recordedAt===void 0?{}:{recordedAt:n.recordedAt},events:r}}var _n=class{constructor(e){if(typeof e.namespace!=`string`||!e.namespace.length)throw TypeError(`a last-run store needs a non-empty namespace`);let t=e.maxEvents??1e4;if(!Number.isInteger(t)||t<1||t>1e6)throw RangeError(`last-run maxEvents must be in 1..1000000`);this.maxEvents=t,this.store=new $t(e.storage??Lt(),`mwg-last-run:${e.namespace}`)}keep(e,t){let n=fn(e);n.length>this.maxEvents&&(n=n.slice(n.length-this.maxEvents));let r=t===void 0?{version:1,events:n}:{version:1,seed:mn(t),events:n};Dt(JSON.stringify(r)),this.store.write(r)}load(){let e=this.store.read(null);if(e===null)return null;if(e?.version!==1)throw Error(`the kept last-run recording is not version 1; clear() it and record again`);return{version:1,...e.seed===void 0?{}:{seed:mn(e.seed)},events:fn(e.events)}}clear(){this.store.remove()}};function vn(e,t){return{version:1,frame:e.frame,events:e.toJSON(),state:t}}function yn(e,t,n){if(typeof e!=`object`||!e||e.version!==1)throw Error(`a run checkpoint must be { version: 1, frame, events, state }`);return new ln(fn(e.events),t,n,{fromFrame:e.frame})}function bn(e,t){if(typeof document>`u`)throw Error(`downloadReplayFile needs a browser document`);let n=document.createElement(`a`);n.href=URL.createObjectURL(new Blob([e],{type:`application/json`})),n.download=t,document.body.appendChild(n),n.click(),n.remove(),setTimeout(()=>URL.revokeObjectURL(n.href),0)}async function xn(e){return await e.text()}async function Sn(e=`.json`){if(typeof document>`u`)throw Error(`pickReplayFile needs a browser document`);return await new Promise(t=>{let n=document.createElement(`input`);n.type=`file`,n.accept=e,n.style.display=`none`;let r=!1,i=e=>{r||(r=!0,n.remove(),t(e))};n.addEventListener(`change`,()=>i(n.files?.[0]??null)),n.addEventListener(`cancel`,()=>i(null)),document.body.appendChild(n),n.click()})}var Cn=class e{constructor(){this.entries=[],this.nextSequence=0}append(e,t=[]){let n={sequence:this.nextSequence,action:Ht(e,`action`),events:Ht([...t],`events`)};return this.nextSequence++,this.entries.push(n),structuredClone(n)}get size(){return this.entries.length}get all(){return structuredClone(this.entries)}mark(){return this.nextSequence}since(e){return structuredClone(this.entries.filter(t=>t.sequence>=e))}truncate(e){this.entries=this.entries.filter(t=>t.sequence<e),this.nextSequence=e}toJSON(){return this.all}replace(t){let n=e.fromJSON(t);this.entries=n.entries,this.nextSequence=n.nextSequence}static fromJSON(t){let n=new e,r=0;for(let e of t){if(!Number.isSafeInteger(e.sequence)||e.sequence!==r)throw Error(`action journal sequences must be contiguous from zero`);n.entries.push(structuredClone({sequence:e.sequence,action:e.action,events:[...e.events]})),r++}return n.nextSequence=r,n}};function wn(e){if(e.criteria)return e.criteria;if(e.counter===void 0||e.target===void 0)throw Error(`achievement "${e.id}" needs either counter/target or criteria`);return[{counter:e.counter,target:e.target}]}var Tn=class e{constructor(){this.definitions=new Map,this.counts=new Map,this.fresh=[]}define(e){this.definitions.set(e.id,e)}count(e){return this.counts.get(e)??0}increment(e,t=1){let n=this.count(e);this.counts.set(e,n+t);let r=[];for(let t of this.definitions.values()){let i=wn(t);i.some(t=>t.counter===e)&&(i.every(t=>t.counter===e?n>=t.target:this.count(t.counter)>=t.target)||i.every(e=>this.count(e.counter)>=e.target)&&(r.push(t.id),this.fresh.push(t.id)))}return r}unlocked(e){let t=this.definitions.get(e);if(!t)throw Error(`no such achievement: "${e}"`);return wn(t).every(e=>this.count(e.counter)>=e.target)}progress(e){let t=this.definitions.get(e);if(!t)throw Error(`no such achievement: "${e}"`);let n=wn(t);if(n.length!==1)throw Error(`achievement "${e}" has several criteria - use subProgress`);return{count:this.count(n[0].counter),target:n[0].target}}subProgress(e){let t=this.definitions.get(e);if(!t)throw Error(`no such achievement: "${e}"`);return wn(t).map(e=>{let t=this.count(e.counter);return{counter:e.counter,count:t,target:e.target,met:t>=e.target}})}drainNew(){let e=this.fresh;return this.fresh=[],e}toJSON(){return{counts:[...this.counts]}}static fromJSON(t,n){let r=new e;for(let e of t)r.define(e);for(let[e,t]of n.counts)r.counts.set(e,t);return r}},En=class e{constructor(e=[]){this.active=new Set,this.spent=new Set,this.rules=[...e]}add(e){this.rules.push(e)}remove(e){this.rules=this.rules.filter(t=>t.id!==e),this.active.delete(e)}check(e){let t=[];for(let n of this.rules){if(n.once&&this.spent.has(n.id))continue;let r=n.when(e);r&&!this.active.has(n.id)&&(n.action(e),t.push(n.id),n.once&&this.spent.add(n.id)),r?this.active.add(n.id):this.active.delete(n.id)}return t}isActive(e){return this.active.has(e)}reset(){this.active.clear(),this.spent.clear()}toJSON(){return{active:[...this.active],spent:[...this.spent]}}static fromJSON(t,n){let r=new e(t);for(let e of n.active)r.active.add(e);for(let e of n.spent)r.spent.add(e);return r}},Dn=class{constructor(e={}){let t=e.storage??Lt(),n=`mwg-session:${e.namespace??`default`}`,r=Number(t.read(n)??`0`);this.launches=(Number.isFinite(r)?r:0)+1,t.write(n,String(this.launches))}};function On(e,t,n){return e<t?t:e>n?n:e}function kn(){return{musicVolume:1,sfxVolume:1,muted:!1,zoom:1,bindings:Fn(je),custom:{}}}function An(e){return e.muted?0:e.musicVolume}function jn(e){return e.muted?0:e.sfxVolume}var Mn=class{constructor(e={}){this.storage=e.storage??Lt(),this.key=`mwg-settings:${e.namespace??`default`}`,this.value=Bn(this.storage,this.key),Re(this.value.bindings)}get current(){return{...this.value,bindings:Fn(this.value.bindings),custom:{...this.value.custom}}}getCustom(e,t){return this.value.custom[e]??t}setCustom(e,t){this.value.custom[e]=t,Vn(this.storage,this.key,this.value)}setMusicVolume(e){this.update({musicVolume:e})}setSfxVolume(e){this.update({sfxVolume:e})}setMuted(e){this.update({muted:e})}setZoom(e){this.update({zoom:e})}setBindings(e){this.update({bindings:e})}update(e){e.musicVolume!==void 0&&(this.value.musicVolume=Nn(e.musicVolume)),e.sfxVolume!==void 0&&(this.value.sfxVolume=Nn(e.sfxVolume)),e.muted!==void 0&&(this.value.muted=e.muted),e.zoom!==void 0&&(this.value.zoom=Pn(e.zoom)),e.bindings!==void 0&&(this.value.bindings=In(e.bindings),Re(this.value.bindings)),e.custom!==void 0&&(this.value.custom=Rn(e.custom)),Vn(this.storage,this.key,this.value)}applyBindings(){Re(this.value.bindings)}reset(){this.value=kn(),Re(this.value.bindings),Vn(this.storage,this.key,this.value)}};function Nn(e){return Number.isFinite(e)?On(e,0,1):1}function Pn(e){return Number.isFinite(e)?Math.max(.01,e):1}function Fn(e){let t={};for(let[n,r]of Object.entries(e))t[n]=[...r];return t}function In(e){if(typeof e!=`object`||!e||Array.isArray(e))return Fn(je);let t={};for(let[n,r]of Object.entries(e)){if(!Array.isArray(r))continue;let e=r.filter(e=>typeof e==`string`);e.length>0&&(t[n]=e)}return Object.keys(t).length>0?t:Fn(je)}function Ln(e){let t=typeof e;return t===`string`||t===`number`||t===`boolean`}function Rn(e){if(typeof e!=`object`||!e||Array.isArray(e))return{};let t={};for(let[n,r]of Object.entries(e))Ln(r)&&(t[n]=r);return t}function zn(e){let t=kn();if(typeof e!=`object`||!e||Array.isArray(e))return t;let n=e;return{musicVolume:typeof n.musicVolume==`number`?Nn(n.musicVolume):t.musicVolume,sfxVolume:typeof n.sfxVolume==`number`?Nn(n.sfxVolume):t.sfxVolume,muted:typeof n.muted==`boolean`?n.muted:t.muted,zoom:typeof n.zoom==`number`?Pn(n.zoom):t.zoom,bindings:In(n.bindings),custom:Rn(n.custom)}}function Bn(e,t){let n=e.read(t);if(!n)return kn();try{return zn(Nt(n,{label:`settings`}))}catch{return kn()}}function Vn(e,t,n){e.write(t,JSON.stringify(n))}var Hn=class extends qt{constructor(e){super(e,`feedback`)}async submit(e){if(!e.message?.trim())throw Error(`feedback message cannot be empty`);return this.withTimeout(async t=>{let n=await this.fetchFn(this.endpoint,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e),signal:t});if(!n.ok)throw Error(`feedback request failed with HTTP ${n.status}`);return{ok:!0,status:n.status}})}},Un=class{constructor(e){this.schedule=[],this.cursor=0,this.elapsed=0,this.startedWaves=new Set,this.completed=!1,this.onSpawn=e.onSpawn,this.onWaveStart=e.onWaveStart,this.onComplete=e.onComplete,e.waves.forEach((e,t)=>{let n=e.entries.reduce((e,t)=>e+t.count,0),r=e.duration??0,i=0;for(let a of e.entries)for(let o=0;o<a.count;o++,i++){let o=n>1&&r>0?i/(n-1)*r:0;this.schedule.push({time:e.delay+o,kind:a.kind,waveIndex:t})}}),this.schedule.sort((e,t)=>e.time-t.time),this.schedule.length===0&&(this.completed=!0,this.onComplete?.())}update(e){if(!this.completed){for(this.elapsed+=e;this.cursor<this.schedule.length&&this.schedule[this.cursor].time<=this.elapsed;){let e=this.schedule[this.cursor];this.startedWaves.has(e.waveIndex)||(this.startedWaves.add(e.waveIndex),this.onWaveStart?.(e.waveIndex)),this.onSpawn(e.kind),this.cursor++}this.cursor>=this.schedule.length&&(this.completed=!0,this.onComplete?.())}}get isComplete(){return this.completed}};function Wn(e,t){let n=e,r=t-(e-(e&1))/2;return{x:n,y:-n-r,z:r}}function Gn(e){return{x:e.x,y:e.z+(e.x-(e.x&1))/2}}var Kn=[{x:1,y:-1,z:0},{x:1,y:0,z:-1},{x:0,y:1,z:-1},{x:-1,y:1,z:0},{x:-1,y:0,z:1},{x:0,y:-1,z:1}];function qn(e,t){let n=Wn(e,t);return Kn.map(e=>Gn({x:n.x+e.x,y:n.y+e.y,z:n.z+e.z}))}function Jn(e,t){let n=Wn(e.x,e.y),r=Wn(t.x,t.y);return Math.max(Math.abs(n.x-r.x),Math.abs(n.y-r.y),Math.abs(n.z-r.z))}function Yn(e){let t=Math.round(e.x),n=Math.round(e.y),r=Math.round(e.z),i=Math.abs(t-e.x),a=Math.abs(n-e.y),o=Math.abs(r-e.z);return i>a&&i>o?t=-n-r:a>o?n=-t-r:r=-t-n,{x:t,y:n,z:r}}function Xn(e,t){let n=Jn(e,t);if(n===0)return[{x:e.x,y:e.y}];let r=Wn(e.x,e.y),i=Wn(t.x,t.y),a=[];for(let e=0;e<=n;e++){let t=e/n;a.push(Gn(Yn({x:r.x+(i.x-r.x)*t,y:r.y+(i.y-r.y)*t,z:r.z+(i.z-r.z)*t})))}return a}function Zn(e,t){let n=Wn(e.x,e.y),r=[];for(let e=-t;e<=t;e++)for(let i=Math.max(-t,-e-t);i<=Math.min(t,-e+t);i++){let t=-e-i;r.push(Gn({x:n.x+e,y:n.y+i,z:n.z+t}))}return r}function Qn(e,t,n,r,i={}){let a=+((i.offset??`odd`)===`odd`);return(i.orientation??`flat-top`)===`pointy-top`?{x:e*n+((t&1)===a?n/2:0)+n/2,y:t*r*.75+r/2}:{x:e*n*.75+n/2,y:t*r+((e&1)===a?r/2:0)+r/2}}function $n(e,t,n,r,i={}){let a=(i.orientation??`flat-top`)===`pointy-top`,o=a?n:n*.75,s=a?r*.75:r,c=Math.round((e-n/2)/o),l=Math.round((t-r/2)/s),u={x:c,y:l},d=1/0;for(let a=-2;a<=2;a++)for(let o=-2;o<=2;o++){let s={x:c+a,y:l+o},f=Qn(s.x,s.y,n,r,i),p=(f.x-e)**2+(f.y-t)**2;p<d&&(d=p,u=s)}return u}function er(e,t,n,r){return n>=0&&r>=0&&n<e&&r<t}function tr(e,t,n){return n*e+t}function nr(e,t){return t%e}function rr(e,t){return Math.floor(t/e)}function ir(e,t){return`${e},${t}`}function ar(e){let t=/^(-?\d+),(-?\d+)$/.exec(e);return t?{x:Number(t[1]),y:Number(t[2])}:null}var or=[[0,-1],[1,0],[0,1],[-1,0]],sr=[[-1,-1],[0,-1],[1,-1],[-1,0],[1,0],[-1,1],[0,1],[1,1]],cr=[[0,-1],[1,-1],[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1]];function lr(e,t){return Math.hypot(e.x-t.x,e.y-t.y)}function ur(e,t){return Math.max(Math.abs(e.x-t.x),Math.abs(e.y-t.y))}function dr(e,t){return Math.abs(e.x-t.x)+Math.abs(e.y-t.y)}function fr(e,t,n){switch(e){case`euclidean`:return lr(t,n);case`manhattan`:return dr(t,n);case`chebyshev`:return ur(t,n);default:throw RangeError(`unknown distance metric: ${e}`)}}var pr=.12,mr=null,hr,gr=new p;function _r(){if(hr===void 0&&(hr=typeof matchMedia==`function`?matchMedia(`(prefers-reduced-motion: reduce)`):null,hr)){let e=()=>{gr.dispatch(yr())};typeof hr.addEventListener==`function`?hr.addEventListener(`change`,e):typeof hr.addListener==`function`&&hr.addListener(e)}return hr}function vr(){return _r()?.matches??!1}function yr(){return mr??vr()}function br(e){mr=e,gr.dispatch(yr())}function xr(e){return _r(),gr.add(e),()=>gr.remove(e)}function Sr(e,t=`decorative`){return yr()?t===`meaningful`?Math.min(e,pr):0:e}var Cr=class e{constructor(e,t){this.width=e,this.height=t,this.volume=new Float32Array(e*t)}index(e,t){return e<0||t<0||e>=this.width||t>=this.height?-1:t*this.width+e}volumeAt(e,t){let n=this.index(e,t);return n<0?0:this.volume[n]}total(){let e=0;for(let t=0;t<this.volume.length;t++)e+=this.volume[t];return e}seed(e,t,n){let r=this.index(e,t);r>=0&&(this.volume[r]+=n)}clear(e,t){let n=this.index(e,t);n>=0&&(this.volume[n]=0)}spread(e,t=.25,n=.9){let r=new Float32Array(this.volume.length);for(let n=0;n<this.height;n++)for(let i=0;i<this.width;i++){let a=n*this.width+i,o=this.volume[a];if(o<=0)continue;let s=[];for(let[t,r]of or){let a=i+t,o=n+r,c=this.index(a,o);c>=0&&e(a,o)&&s.push(c)}if(s.length===0)r[a]+=o;else{let e=o*t/s.length;r[a]+=o-e*s.length;for(let t of s)r[t]+=e}}let i=[];for(let e=0;e<r.length;e++){let t=r[e]*n,a=t<.001?0:t;a===0&&this.volume[e]>0&&i.push({x:e%this.width,y:Math.floor(e/this.width)}),this.volume[e]=a}return i}cellsAbove(e){let t=[];for(let n=0;n<this.height;n++)for(let r=0;r<this.width;r++){let i=this.volume[n*this.width+r];i>=e&&t.push({x:r,y:n,volume:i})}return t}toJSON(){return{width:this.width,height:this.height,volume:[...this.volume]}}static fromJSON(t){let n=new e(t.width,t.height);return n.volume.set(t.volume.slice(0,n.volume.length)),n}},wr={linear:e=>e,easeInQuad:e=>e*e,easeOutQuad:e=>e*(2-e),easeInOutQuad:e=>e<.5?2*e*e:1-(-2*e+2)**2/2,easeInCubic:e=>e*e*e,easeOutCubic:e=>1-(1-e)**3,easeInOutCubic:e=>e<.5?4*e*e*e:1-(-2*e+2)**3/2},Tr=class{constructor(){this.tweens=[]}tween(e,t,n=wr.linear){let{ease:r=wr.linear,intent:i=`decorative`,alternate:a}=typeof n==`function`?{ease:n}:n,o=yr()&&a!==void 0,s=o?a:t,c=Sr(e,o?`meaningful`:i);return c>0?new Promise(e=>{this.tweens.push({elapsed:0,duration:c,ease:r,apply:s,resolve:e,finishOnReduced:!o&&i===`decorative`})}):(s(1),Promise.resolve())}update(e){if(this.tweens.length!==0)for(let t of[...this.tweens]){if(t.finishOnReduced&&yr()){this.tweens.splice(this.tweens.indexOf(t),1),t.apply(1),t.resolve();continue}t.elapsed+=e;let n=Math.min(1,t.elapsed/t.duration);t.apply(t.ease(n)),n>=1&&(this.tweens.splice(this.tweens.indexOf(t),1),t.resolve())}}get isBusy(){return this.tweens.length>0}clear(){this.tweens=[]}},Er=class{constructor(e={}){this.history=[],this.cursor=-1,this.limit=Math.max(1,e.limit??50)}push(e){this.history.length=this.cursor+1,this.history.push(e),this.history.length>this.limit&&this.history.shift(),this.cursor=this.history.length-1}get canUndo(){return this.cursor>0}get canRedo(){return this.cursor<this.history.length-1}undo(){return this.canUndo?(this.cursor--,this.history[this.cursor]):null}redo(){return this.canRedo?(this.cursor++,this.history[this.cursor]):null}get current(){return this.cursor>=0?this.history[this.cursor]:null}clear(){this.history=[],this.cursor=-1}};function Dr(e,t){if(!Number.isFinite(t.maxCost)||t.maxCost<0)return new Map;let n=t.key(e),r=new Map([[n,{cell:e,cost:0}]]),i=[{cell:e,key:n,cost:0}];for(;i.length>0;){let e=kr(i),n=r.get(e.key);if(n&&e.cost===n.cost&&!t.stop?.(e.cell,e.cost))for(let n of t.neighbors(e.cell)){let a=t.cost(e.cell,n);if(!Number.isFinite(a)||a<0)continue;let o=e.cost+a;if(o>t.maxCost||t.canEnter&&!t.canEnter(n,e.cell,o))continue;let s=t.key(n);if(o>=(r.get(s)?.cost??1/0))continue;let c={cell:n,key:s,cost:o};r.set(s,c),Or(i,c)}}return r}function Or(e,t){e.push(t);let n=e.length-1;for(;n>0;){let t=Math.floor((n-1)/2);if(e[t].cost<=e[n].cost)break;[e[t],e[n]]=[e[n],e[t]],n=t}}function kr(e){let t=e[0],n=e.pop();if(!t||!n||e.length===0)return t;e[0]=n;let r=0;for(;;){let t=r*2+1,n=t+1,i=r;if(t<e.length&&e[t].cost<e[i].cost&&(i=t),n<e.length&&e[n].cost<e[i].cost&&(i=n),i===r)break;[e[r],e[i]]=[e[i],e[r]],r=i}return t}var Ar=class{constructor(){this.changed=new p,this.tasks=[],this.progress=new Map,this.status_=`idle`,this.current_=null,this.error_=null,this.cancelled=!1}add(e){if(!e.id)throw Error(`load task needs an id`);if(this.tasks.some(t=>t.id===e.id))throw Error(`duplicate load task "${e.id}"`);if(e.weight!==void 0&&!(e.weight>0))throw Error(`load task weight must be positive`);if(this.status_===`loading`)throw Error(`cannot add a task while loading`);return this.tasks.push(e),this.progress.set(e.id,0),this.emit(),this}get snapshot(){let e=this.tasks.reduce((e,t)=>e+(t.weight??1),0),t=this.tasks.reduce((e,t)=>e+(t.weight??1)*(this.progress.get(t.id)??0),0);return{status:this.status_,completed:t,total:e,current:this.current_,error:this.error_}}async start(){if(this.status_===`loading`)throw Error(`load queue is already running`);this.status_=`loading`,this.cancelled=!1,this.error_=null,this.emit();try{for(let e of this.tasks){if(this.cancelled)break;this.current_=e.id,this.emit();let t=this;await e.run({get cancelled(){return t.cancelled},report:t=>this.report(e.id,t)}),this.cancelled||this.report(e.id,1)}this.current_=null,this.status_=this.cancelled?`cancelled`:`ready`,this.emit()}catch(e){throw this.current_=null,this.error_=e,this.status_=`failed`,this.emit(),e}}cancel(){this.status_===`loading`&&(this.cancelled=!0)}retry(){if(this.status_===`loading`)throw Error(`cannot retry while loading`);this.status_=`idle`,this.current_=null,this.error_=null,this.cancelled=!1;for(let e of this.tasks)this.progress.set(e.id,0);this.emit()}report(e,t){if(!Number.isFinite(t))throw Error(`load progress must be finite`);this.progress.set(e,Math.max(0,Math.min(1,t))),this.emit()}emit(){this.changed.dispatch(this.snapshot)}},jr=class{constructor(){this.entities=new Map,this.ids=new Map,this.sequence=0}add(e,t){let n=this.ids.get(e);if(n!==void 0){if(t!==void 0&&t!==n)throw Error(`entity already has id ${n}`);return n}let r=t;if(r!==void 0){if(r.length===0)throw Error(`entity id must not be empty`);if(this.entities.has(r))throw Error(`entity id already exists: ${r}`)}else do r=`e${this.sequence++}`;while(this.entities.has(r));return this.entities.set(r,e),this.ids.set(e,r),r}get(e){return this.entities.get(e)}idOf(e){return this.ids.get(e)}has(e){return this.entities.has(e)}remove(e){let t=this.entities.get(e);return t!==void 0&&(this.entities.delete(e),this.ids.delete(t),!0)}get size(){return this.entities.size}},Mr=class{constructor(e){this.queue=[],this.busy=!1,this.remaining=0,this.play=e.play}enqueue(e){this.queue.push(...e),this.busy||this.advance()}update(e){this.busy&&(this.remaining-=e,this.remaining<=0&&this.advance())}get isBusy(){return this.busy}clear(){this.queue=[],this.busy=!1,this.remaining=0}advance(){let e=this.queue.shift();if(e===void 0){this.busy=!1,this.remaining=0;return}this.busy=!0;let t=this.play(e)||0;t>0?this.remaining=t:this.advance()}},Nr=2166136261,Pr=16777619;function Fr(e,t=!1){if(e==null)return`null`;switch(typeof e){case`boolean`:return e?`true`:`false`;case`number`:return Number.isFinite(e)?String(e):`null`;case`string`:return JSON.stringify(e);case`bigint`:return JSON.stringify(e.toString());case`function`:case`symbol`:return t?`null`:`undefined`}return Array.isArray(e)?`[${e.map(e=>Fr(e,!0)).join(`,`)}]`:`{${Object.entries(e).filter(([,e])=>e!==void 0&&typeof e!=`function`&&typeof e!=`symbol`).sort(([e],[t])=>e<t?-1:+(e>t)).map(([e,t])=>`${JSON.stringify(e)}:${Fr(t)}`).join(`,`)}}`}function Ir(e){let t=Fr(e),n=Nr;for(let e=0;e<t.length;e++)n^=t.charCodeAt(e),n=Math.imul(n,Pr)>>>0;return n>>>0}var Lr=class{constructor(){this.reference=new Map,this.desyncTick=null}observe(e,t){let n=this.reference.get(e);return n===void 0?(this.reference.set(e,t),!0):n===t||(this.desyncTick===null&&(this.desyncTick=e),!1)}get divergent(){return this.desyncTick!==null}get atTick(){return this.desyncTick}reset(){this.reference.clear(),this.desyncTick=null}};function Rr(e,t={}){let n=Vr(e);if(n.length===0)return[];let[r,...i]=n,a=t.listDelimiter??`;`,o=t.mapDelimiter??`=`;return i.map((e,n)=>{let i={};return r.forEach((r,s)=>{let c=e[s]??``;c!==``&&(i[r]=zr(c,t.columns?.[r]??`string`,r,n,a,o))}),i})}function zr(e,t,n,r,i,a){return Br(e,t,{column:n,rowIndex:r,listDelimiter:i,mapDelimiter:a,error:()=>t===`number`?`CSV row ${r+1}, column "${n}": "${e}" is not a number`:t===`boolean`?`CSV row ${r+1}, column "${n}": "${e}" is not "true" or "false"`:t===`map`?`CSV row ${r+1}, column "${n}": "${e.split(i).map(e=>e.trim()).find(e=>e&&!e.includes(a))??e}" has no "${a}" to split a key from its value`:`CSV row ${r+1}, column "${n}": "${e}" is invalid`})}function Br(e,t,n={}){let r=n.column??`value`,i=n.listDelimiter??`;`,a=n.mapDelimiter??`=`,o=e=>{throw Error(n.error?.(e)??e)};switch(t){case`string`:return e;case`number`:{let t=Number(e);return Number.isFinite(t)||o(`${r} must be a number`),t}case`boolean`:{let t=e.toLowerCase();if(t===`true`)return!0;if(t===`false`)return!1;if(n.acceptYesNo&&t===`yes`)return!0;if(n.acceptYesNo&&t===`no`)return!1;o(`${r} must be true, false${n.acceptYesNo?`, yes, or no`:``}`)}case`list`:return e.split(i).map(e=>e.trim()).filter(e=>e.length>0);case`map`:{let t={};for(let n of e.split(i).map(e=>e.trim()).filter(e=>e.length>0)){let e=n.indexOf(a);e===-1&&o(`${r} map entry must contain ${a}`),t[n.slice(0,e).trim()]=n.slice(e+a.length).trim()}return t}}}function Vr(e){let t=[],n=[],r=``,i=!1,a=0;for(;a<e.length;){let o=e[a];if(i){if(o===`"`){if(e[a+1]===`"`){r+=`"`,a+=2;continue}i=!1,a++;continue}r+=o,a++;continue}if(o===`"`){i=!0,a++;continue}if(o===`,`){n.push(r),r=``,a++;continue}if(o===`\r`){a++;continue}if(o===`
2
2
  `){n.push(r),t.push(n),n=[],r=``,a++;continue}r+=o,a++}return(r.length>0||n.length>0)&&(n.push(r),t.push(n)),t.filter(e=>e.length!==1||e[0]!==``)}function Hr(e){let t=[],n=[],r,i=e=>{if(!n.includes(e)){if(n.length>=2)throw Error(`dialogue text supports at most two speakers for the "-" shorthand; found a third speaker "${e}" after "${n[0]}" and "${n[1]}" were already established`);n.push(e)}};for(let a of e.split(`
3
3
  `)){let e=a.trim();if(e===``)continue;let o=/^@(\S+)(?:\s+(.*))?$/.exec(e);if(o){let[,e,n]=o;i(e),n&&(t.push({text:n.trim(),speaker:e}),r=e);continue}if(e.startsWith(`-`)){if(n.length<2)throw Error(`a "-" line needs two established speakers first (write two "@id text" lines before it)`);let i=e.slice(1).trim(),a=n.find(e=>e!==r)??n[0];t.push({text:i,speaker:a}),r=a;continue}t.push({text:e}),r=void 0}return t}function Ur(e){let t=Wr(e);if(t.length===0)throw Error(`this twee source has no passages - passages start with ":: Name"`);let n={},r,i;for(let e of t){if(e.name===`StoryTitle`){r=e.body.trim()||void 0;continue}if(e.name===`StoryData`){i=Kr(e.body);continue}if(Object.prototype.hasOwnProperty.call(n,e.name))throw Error(`this twee source defines "${e.name}" twice`);n[e.name]=qr(e.name,e.body)}let a=Object.keys(n);if(a.length===0)throw Error(`this twee source has no story passages, only StoryTitle/StoryData`);if(i!==void 0&&!Object.prototype.hasOwnProperty.call(n,i))throw Error(`StoryData starts at "${i}", which is not a passage in this file`);for(let[e,t]of Object.entries(n))for(let r of t)if(`ask`in r){for(let t of r.choices)if(t.goto!==void 0&&!Object.prototype.hasOwnProperty.call(n,t.goto))throw Error(`passage "${e}" links to "${t.goto}", which is not a passage in this file`)}return{story:n,start:i??a[0],title:r}}function Wr(e){let t=[],n=null,r=[],i=()=>{n!==null&&t.push({name:n,body:r.join(`
4
4
  `)})};for(let t of e.split(`
@@ -1366,24 +1366,24 @@ fn mainFragment(
1366
1366
  `,end:`
1367
1367
  let addedAlpha = finalColor.a + vColorAdd.a;
1368
1368
  finalColor = vec4<f32>(finalColor.rgb + vColorAdd.rgb * addedAlpha, addedAlpha);
1369
- `}},Pj=class extends Zd{constructor(e){super({glProgram:Wm({name:`color-transform-batch`,bits:[qm,Mj,$m(e),ch]}),gpuProgram:Um({name:`color-transform-batch`,bits:[Km,Nj,Zm(e),sh]}),resources:{batchSamplers:Eg(e)}}),this.maxTextures=e}},Fj=7,Ij=class extends jf{constructor(){let e=new wf({data:new Float32Array(1),label:`mwg-color-transform-attribute-buffer`,usage:Sf.VERTEX|Sf.COPY_DST,shrinkToFit:!1}),t=new wf({data:new Uint32Array(1),label:`mwg-color-transform-index-buffer`,usage:Sf.INDEX|Sf.COPY_DST,shrinkToFit:!1});super({attributes:{aPosition:{buffer:e,format:`float32x2`,stride:28,offset:0},aUV:{buffer:e,format:`float32x2`,stride:28,offset:8},aColor:{buffer:e,format:`unorm8x4`,stride:28,offset:16},aTextureIdAndRound:{buffer:e,format:`uint16x2`,stride:28,offset:20},aColorAdd:{buffer:e,format:`unorm8x4`,stride:28,offset:24}},indexBuffer:t})}},Lj=0,Rj=e=>e.colorAdd??Lj;function zj(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){e[n]=r*l+a*u+s,e[n+1]=o*u+i*l+c,e[n+2]=d,e[n+3]=f,t[n+4]=p,t[n+5]=m,t[n+6]=h}var Bj=class e extends bg{static{this.extension={type:[I.Batcher],name:`mwg-color-transform`}}constructor(t){super(t),this.geometry=new Ij,this.name=e.extension.name,this.vertexSize=Fj,this.shader=new Pj(t.maxTextures)}packAttributes(e,t,n,r,i){let a=i<<16|e.roundPixels&65535,{a:o,b:s,c,d:l,tx:u,ty:d}=e.transform,{positions:f,uvs:p}=e,m=e.color,h=Rj(e),g=e.attributeOffset,_=g+e.attributeSize;for(let e=g;e<_;e++){let i=e*2,g=f[i],_=f[i+1];t[r++]=o*g+c*_+u,t[r++]=l*_+s*g+d,t[r++]=p[i],t[r++]=p[i+1],n[r++]=m,n[r++]=a,n[r++]=h}}packQuadAttributes(e,t,n,r,i){let{a,b:o,c:s,d:c,tx:l,ty:u}=e.transform,{bounds:d}=e,f=e.texture.uvs,p=d.maxX,m=d.minX,h=d.maxY,g=d.minY,_=e.color,v=Rj(e),y=i<<16|e.roundPixels&65535;zj(t,n,r,a,o,s,c,l,u,m,g,f.x0,f.y0,_,y,v),r+=Fj,zj(t,n,r,a,o,s,c,l,u,p,g,f.x1,f.y1,_,y,v),r+=Fj,zj(t,n,r,a,o,s,c,l,u,p,h,f.x2,f.y2,_,y,v),r+=Fj,zj(t,n,r,a,o,s,c,l,u,m,h,f.x3,f.y3,_,y,v)}_updateMaxTextures(e){this.shader.maxTextures!==e&&(this.shader.destroy(),this.shader=new Pj(e))}destroy(){this.shader.destroy(),super.destroy()}},Vj=`mwg-tinted-sprite`;function Hj(e){e.renderPipeId=Vj}var Uj=class{static{this.extension={type:[I.WebGLPipes,I.WebGPUPipes,I.CanvasPipes],name:Vj}}constructor(e){this.renderer=e}addRenderable(e,t){let n=this.element(e);e.didViewUpdate&&this.sync(e,n),this.renderer.renderPipes.batch.addToBatch(n,t)}updateRenderable(e){let t=this.element(e);e.didViewUpdate&&this.sync(e,t),t._batcher.updateElement(t)}validateRenderable(e){let t=this.element(e);return!t._batcher.checkAndUpdateTexture(t,e.texture)}sync(e,t){t.bounds=e.visualBounds,t.texture=e.texture,t.colorAdd=e.colorAdd}element(e){let t=e._gpuData;return t[this.renderer.uid]??this.create(e,t)}create(e,t){let n=new Wj;return n.renderable=e,n.transform=e.groupTransform,n.texture=e.texture,n.bounds=e.visualBounds,n.roundPixels=this.renderer._roundPixels|e._roundPixels,n.colorAdd=e.colorAdd,t[this.renderer.uid]=n,n}destroy(){this.renderer=null}},Wj=class{constructor(){this.batcherName=Bj.extension.name,this.topology=`triangle-list`,this.attributeSize=4,this.indexSize=6,this.packAsQuad=!0,this.roundPixels=0,this.colorAdd=0,this._attributeStart=0,this._textureId=0,this._indexStart=0,this._batcher=null,this._batch=null}get blendMode(){return this.renderable.groupBlendMode}get color(){return this.renderable.groupColorAlpha}reset(){this.renderable=null,this.texture=null,this._batcher=null,this._batch=null,this.bounds=null,this.colorAdd=0}destroy(){this.reset()}},Gj=!1;function Kj(){Gj||(Gj=!0,L.add(Bj),L.add(Uj))}function qj(e,t,n,r=0){return(Yj(r)<<24|Yj(n)<<16|Yj(t)<<8|Yj(e))>>>0}function Jj(e,t){return qj((e>>16&255)/255*t,(e>>8&255)/255*t,(e&255)/255*t)}function Yj(e){return Math.max(0,Math.min(255,Math.round(e*255)))}var Xj=Lj;Kj();var Zj=class extends xl{constructor(e){super(e),this._colorAdd=0,Hj(this)}get colorAdd(){return this._colorAdd}set colorAdd(e){this._colorAdd!==e&&(this._colorAdd=e,this.onViewUpdate())}setColorAdd(e,t,n,r=0){this.colorAdd=qj(e,t,n,r)}lerpTint(e,t){let n=Math.round((1-t)*255);this.tint=n<<16|n<<8|n,this.colorAdd=Jj(e,t)}silhouette(e){this.tint=0,this.colorAdd=Jj(e,1)}resetColor(){this.tint=16777215,this.colorAdd=0}};function Qj(e){return[e>>16&255,e>>8&255,e&255]}function $j(e){let[t,n,r]=Qj(e);return Math.floor((t+n+r)/3)}function eM(e,t,n){return Math.trunc(n*e+(1-n)*t)}function tM(e,t,n){let[r,i,a]=Qj(e),[o,s,c]=Qj(t);return eM(r,o,n)<<16|eM(i,s,n)<<8|eM(a,c,n)}function nM(e,t){let n=e.length>0?$j(e[0]):255;return{from:e,to:e.map(e=>{let r=$j(e);return n!==0&&r<=n?tM(t.mid,t.min,r/n):tM(t.mid,t.max,(255-r)/(255-n))})}}function rM(e,t,n=`exact`){let r=t.from.map(Qj),i=new Uint8ClampedArray(e.length);for(let a=0;a<e.length;a+=4){let o=e[a+3],s=e[a],c=e[a+1],l=e[a+2];if(i[a]=s,i[a+1]=c,i[a+2]=l,i[a+3]=o,o===0||r.length===0)continue;if(n===`exact`){let e=r.findIndex(([e,t,n])=>e===s&&t===c&&n===l);if(e<0)continue;let[n,o,u]=Qj(t.to[e]??t.from[e]);i[a]=n,i[a+1]=o,i[a+2]=u;continue}let u=0,d=1/0;for(let e=0;e<r.length;e+=1){let[t,n,i]=r[e],a=s-t,o=c-n,f=l-i,p=a*a+o*o+f*f;p<d&&(d=p,u=e)}let[f,p,m]=Qj(t.to[u]??t.from[u]);i[a]=f,i[a+1]=p,i[a+2]=m}return i}function iM(e,t,n){let r=e.width,i=e.height;if(r<=0||i<=0||!e.source)return e;let a=!t.createCanvas,o=t.createCanvas?.(r,i)??(typeof document>`u`?null:document.createElement(`canvas`));if(!o)return e;o.width=r,o.height=i;let s=o.getContext(`2d`);if(!s)return e;let c=a?{drawImage:s.drawImage.bind(s),getImageData:s.getImageData.bind(s),putImageData:(e,t,n)=>s.putImageData(new ImageData(new Uint8ClampedArray(e.data),e.width,e.height),t,n)}:s;return s.drawImage(e.source.resource,0,0),n(c,r,i),J.from(o)}function aM(e,t,n={},r=`exact`){return iM(e,n,(e,n,i)=>{let a=rM(e.getImageData(0,0,n,i).data,t,r);e.putImageData({data:a,width:n,height:i},0,0)})}function oM(e){e=e.replace(/^"|"$/g,``);let t=[],n=0,r=0;for(let i=0;i<e.length;i+=1)e[i]===`(`?r+=1:e[i]===`)`?r=Math.max(0,r-1):e[i]===`~`&&r===0&&(t.push(e.slice(n,i)),n=i+1);t.push(e.slice(n));let i=(t.shift()??``).trim(),a=[];for(let e of t){let t=/^([A-Za-z][A-Za-z0-9_-]*)(?:\((.*)\))?$/.exec(e.trim());t&&a.push({name:t[1].toUpperCase(),args:t[2]===void 0?[]:t[2].split(`,`).map(e=>e.trim())})}return{path:i,modifiers:a}}function sM(e,t){return e.modifiers.find(e=>e.name===t.toUpperCase())}function cM(e){return e!==void 0&&/^(linear|smooth)$/i.test(e)?`linear`:`nearest`}function lM(e,t,n){return[1,0,0,0,e/255,0,1,0,0,t/255,0,0,1,0,n/255,0,0,0,1,0]}function uM(e){return[(e.red??100)/100,0,0,0,0,0,(e.green??100)/100,0,0,0,0,0,(e.blue??100)/100,0,0,0,0,0,1,0]}function dM(e,t){let n=1-t,r=(e>>16&255)/255,i=(e>>8&255)/255,a=(e&255)/255;return[n,0,0,0,r*t,0,n,0,0,i*t,0,0,n,0,a*t,0,0,0,1,0]}function fM(e){let t=[`R`,`G`,`B`,`A`].map((t,n)=>e[n]??t),n=e=>{switch(e){case`R`:return[1,0,0,0,0];case`G`:return[0,1,0,0,0];case`B`:return[0,0,1,0,0];case`A`:return[0,0,0,1,0];case`0`:return[0,0,0,0,0];case`1`:return[0,0,0,0,1]}};return t.flatMap(e=>n(e))}function pM(e,t){let n=new Ik;n.matrix=t,e.filters=[n]}function mM(e){if(e===void 0)return;let t=e.trim(),n=t.endsWith(`%`),r=Number(n?t.slice(0,-1):t);if(Number.isFinite(r))return n||r>1?r/100:r}function hM(e){if(e===void 0)return;let t=Number.parseInt(e.replace(/^#/,``),16);return Number.isFinite(t)?t:void 0}function gM(e,t,n=1){let r=sM(t,`FL`);r&&(r.args.length===0||r.args.some(e=>/horiz|horizontal|x/i.test(e)))&&(e.scale.x*=-1),r?.args.some(e=>/vert|vertical|y/i.test(e))&&(e.scale.y*=-1);let i=sM(t,`SCALE`);if(i){let t=Number(i.args[0]),r=Number(i.args[1]??i.args[0]);Number.isFinite(t)&&t>0&&(e.width=t*n),Number.isFinite(r)&&r>0&&(e.height=r*n)}if(sM(t,`GS`)){let t=new Ik;t.greyscale(1,!1),e.filters=[...e.filters??[],t]}let a=sM(t,`CS`);if(a){let t=a.args.slice(0,3).map(Number);if(t.length===3&&t.every(e=>Number.isFinite(e))){let n=new Ik;n.matrix=lM(t[0],t[1],t[2]),e.filters=[...e.filters??[],n]}}let o=sM(t,`R`),s=sM(t,`G`),c=sM(t,`B`);if(o||s||c){let t=o?Number(o.args[0]):void 0,n=s?Number(s.args[0]):void 0,r=c?Number(c.args[0]):void 0,i=new Ik;i.matrix=uM({red:Number.isFinite(t)?t:void 0,green:Number.isFinite(n)?n:void 0,blue:Number.isFinite(r)?r:void 0}),e.filters=[...e.filters??[],i]}let l=sM(t,`CHAN`);if(l&&l.args.length>0){let t=l.args.map(e=>e.trim().toUpperCase()),n=new Ik;n.matrix=fM(t),e.filters=[...e.filters??[],n]}let u=sM(t,`O`);if(u){let t=mM(u.args[0]);t!==void 0&&(e.alpha*=Math.min(1,Math.max(0,t)))}}function _M(e,t,n={},r=1){e.texture=SM(e.texture,t,n),gM(e,t,r)}function vM(e,t){let n=sM(t,`CROP`);if(!n||n.args.length<4||!e.source)return e;let r=n.args.slice(0,4).map(Number);if(r.some(e=>!Number.isFinite(e))||r[2]<=0||r[3]<=0)return e;let i=Math.max(0,r[0]),a=Math.max(0,r[1]),o=Math.min(r[2],Math.max(0,e.width-i)),s=Math.min(r[3],Math.max(0,e.height-a));return o>0&&s>0?new J({source:e.source,frame:new K(i,a,o,s)}):e}function yM(e,t){let n=e.trim();return hM(n)??t?.(n)}function bM(e,t){let n=[],r=[];for(let i of e){let[e,a]=i.split(`>`);if(e===void 0||a===void 0)continue;let o=yM(e,t),s=yM(a,t);o!==void 0&&s!==void 0&&(n.push(o),r.push(s))}return{from:n,to:r}}function xM(e,t){let n=e.join(`,`),r=n.indexOf(`>`);if(r<0)return{from:[],to:[]};let i=e=>e.split(`,`).map(e=>yM(e,t)).filter(e=>e!==void 0);return{from:i(n.slice(0,r)),to:i(n.slice(r+1))}}function SM(e,t,n={}){let r=e,i=sM(t,`RC`);if(i&&i.args.length>0){let e=bM(i.args,n.resolveColor);e.from.length>0&&(r=aM(r,e,n,`exact`))}let a=sM(t,`PAL`);if(a){let e=xM(a.args,n.resolveColor);e.from.length>0&&e.from.length===e.to.length&&(r=aM(r,e,n,`exact`))}let o=sM(t,`BLIT`);if(o&&o.args.length>0&&n.resolveTexture){let e=n.resolveTexture(o.args[0]);if(e){let t=Number(o.args[1]??0)||0,i=Number(o.args[2]??0)||0;r=iM(r,n,n=>{n.drawImage(e.source.resource,t,i)})}}let s=sM(t,`MASK`);if(s&&s.args.length>0&&n.resolveTexture){let e=n.resolveTexture(s.args[0]);if(e){let t=Number(s.args[1]??0)||0,i=Number(s.args[2]??0)||0;r=iM(r,n,(r,a,o)=>{let s=r.getImageData(0,0,a,o),c=CM(e.width,e.height,n);if(!c)return;let l=c.getContext(`2d`);if(!l)return;l.drawImage(e.source.resource,0,0);let u=l.getImageData(0,0,e.width,e.height),d=wM(s.data,a,o,u.data,e.width,e.height,t,i);r.putImageData({data:d,width:a,height:o},0,0)})}}let c=sM(t,`BLEND`);if(c){let e=yM(c.args[0]??``,n.resolveColor),t=mM(c.args[1]);e!==void 0&&t!==void 0&&(r=iM(r,n,(n,r,i)=>{let a=TM(n.getImageData(0,0,r,i).data,e,t);n.putImageData({data:a,width:r,height:i},0,0)}))}let l=sM(t,`ROTATE`);if(l){let e=Number(l.args[0]);if(Number.isFinite(e)&&e%360!=0){let t=r.width,i=r.height;if(t>0&&i>0&&r.source){let a=CM(t,i,n),o=a?.getContext(`2d`);if(a&&o){o.drawImage(r.source.resource,0,0);let a=EM(o.getImageData(0,0,t,i).data,t,i,e,cM(l.args[1])),s=CM(a.width,a.height,n),c=s?.getContext(`2d`);s&&c&&(c.putImageData({data:a.data,width:a.width,height:a.height},0,0),r=J.from(s))}}}}return r}function CM(e,t,n){let r=n.createCanvas?.(e,t)??(typeof document>`u`?null:document.createElement(`canvas`));return r?(r.width=e,r.height=t,r):null}function wM(e,t,n,r,i,a,o,s){let c=new Uint8ClampedArray(e.length);for(let l=0;l<n;l+=1)for(let n=0;n<t;n+=1){let u=(l*t+n)*4,d=n-o,f=l-s,p=d>=0&&d<i&&f>=0&&f<a?r[(f*i+d)*4+3]:0;c[u]=e[u],c[u+1]=e[u+1],c[u+2]=e[u+2],c[u+3]=Math.round(e[u+3]*p/255)}return c}function TM(e,t,n){let r=Math.min(1,Math.max(0,n)),i=t>>16&255,a=t>>8&255,o=t&255,s=new Uint8ClampedArray(e.length);for(let t=0;t<e.length;t+=4){let n=e[t+3];if(s[t+3]=n,n===0){s[t]=e[t],s[t+1]=e[t+1],s[t+2]=e[t+2];continue}s[t]=e[t]*(1-r)+i*r,s[t+1]=e[t+1]*(1-r)+a*r,s[t+2]=e[t+2]*(1-r)+o*r}return s}function EM(e,t,n,r,i=`nearest`){let a=r*Math.PI/180,o=Math.cos(a),s=Math.sin(a),c=t/2,l=n/2,u=0,d=0;for(let[e,t]of[[-c,-l],[c,-l],[c,l],[-c,l]])u=Math.max(u,Math.abs(e*o-t*s)),d=Math.max(d,Math.abs(e*s+t*o));let f=Math.max(1,Math.round(u*2)),p=Math.max(1,Math.round(d*2)),m=new Uint8ClampedArray(f*p*4),h=t/2-.5,g=n/2-.5,_=f/2-.5,v=p/2-.5,y=i===`linear`&&r%90!=0;for(let r=0;r<p;r+=1)for(let i=0;i<f;i+=1){let a=i-_,c=r-v,l=a*o+c*s+h,u=-a*s+c*o+g,d=(r*f+i)*4;if(!y){let r=Math.round(l),i=Math.round(u);if(r<0||r>=t||i<0||i>=n)continue;let a=(i*t+r)*4;m[d]=e[a],m[d+1]=e[a+1],m[d+2]=e[a+2],m[d+3]=e[a+3];continue}DM(e,t,n,l,u,m,d)}return{data:m,width:f,height:p}}function DM(e,t,n,r,i,a,o){if(r<-.5||i<-.5||r>t-.5||i>n-.5)return;let s=Math.floor(r),c=Math.floor(i),l=r-s,u=i-c,d=0,f=0,p=0,m=0;for(let r=0;r<=1;r+=1)for(let i=0;i<=1;i+=1){let a=(i===0?1-l:l)*(r===0?1-u:u);if(a===0)continue;let o=On(s+i,0,t-1),h=(On(c+r,0,n-1)*t+o)*4,g=e[h+3];d+=g*a,f+=e[h]*g*a,p+=e[h+1]*g*a,m+=e[h+2]*g*a}d<=0||(a[o]=f/d,a[o+1]=p/d,a[o+2]=m/d,a[o+3]=d)}var OM=class{constructor(e,{fps:t=10,loop:n=!0,startTime:r=0}={}){if(e.length===0)throw Error(`an animation needs at least one frame`);if(!(t>0))throw Error(`an animation needs a positive fps, got ${t}`);this.frameDuration=1/t,this.frames=e.map(e=>kM(e)?e:{texture:e}),this.times=this.frames.map(e=>e.duration??this.frameDuration),this.loop=n,this.startTime=r;let i=0,a=0;for(let e of this.frames)e.duration===void 0?i++:a+=e.duration;this.duration=i*this.frameDuration+a}frameAt(e){return this.frames[this.frameIndexAt(e)]}frameIndexAt(e){let t=e-this.startTime;if(t<=0)return 0;let n=this.duration;if(n<=0)return this.frames.length-1;let r=this.loop?t%n:Math.min(t,n);for(let e=0;e<this.times.length;e++){if(r<this.times[e])return e;r-=this.times[e]}return this.frames.length-1}};function kM(e){return e.texture!==void 0}var AM=class extends Zj{constructor(...e){super(...e),this.animations=new Map,this.current=null,this.currentName=null,this.elapsed=0,this.finished=!1,this.offset={x:0,y:0},this.onFinish=null,this.paused=!1}add(e,t,n){return this.animations.set(e,new OM(t,n)),this}has(e){return this.animations.has(e)}get playing(){return this.currentName}get isFinished(){return this.finished}get frameOffset(){return this.offset}get elapsedTime(){return this.elapsed}play(e,t=!1){if(!t&&this.currentName===e&&!this.finished)return this;let n=this.animations.get(e);if(!n)throw Error(`no animation named "${e}" on this sprite`);return this.current=n,this.currentName=e,this.elapsed=0,this.finished=!1,this.show(n.frameAt(0)),this}stop(){this.current=null,this.currentName=null}update(e){let t=this.current;!t||this.paused||this.finished||(this.elapsed+=e,this.show(t.frameAt(this.elapsed)),!t.loop&&this.elapsed>=t.startTime+t.duration&&(this.finished=!0,this.onFinish?.(this.currentName)))}show(e){this.texture=e.texture,this.offset.x=e.offsetX??0,this.offset.y=e.offsetY??0}};function jM(e,t,n,r){return t>=e.x-r&&t<=e.x+e.width+r&&n>=e.y-r&&n<=e.y+e.height+r}function MM(e,t,n,r=0){return jM(e.view,t,n,r)}var NM=class{constructor(){this.members=[]}get size(){return this.members.length}add(e){return this.members.includes(e)||this.members.push(e),this}remove(e){let t=this.members.indexOf(e);return t<0?!1:(this.members.splice(t,1),!0)}clear(){this.members.length=0}update(e,t,n=0){let r=e.view;for(let e of[...this.members])jM(r,e.x,e.y,n)&&e.update(t)}},PM=``;function FM(e){PM=e.endsWith(`/`)||e===``?e:e+`/`}var IM;function LM(e){IM=e}function RM(){return IM||(typeof window>`u`?void 0:window.__MWG_ASSETS__)}function zM(){return RM()!==void 0}function BM(){return Object.keys(RM()??{})}function VM(e){let t=RM();return!t||e in t}function HM(e){let t=RM();if(!t)return PM+e;let n=t[e];if(n===void 0)throw Error(`asset "${e}" is not in this build - check it is under the folder passed to compile-resources`);return n}var UM={"image/png":`png`,"image/jpeg":`jpg`,"image/webp":`webp`,"image/gif":`gif`,"image/svg+xml":`svg`};async function WM(e,t={}){let{onProgress:n,resolution:r,optional:i,onMissing:a}=typeof t==`function`?{onProgress:t,resolution:void 0,optional:void 0,onMissing:void 0}:t,o=new Set(i??[]),s=e.filter(e=>!Mk.cache.has(e)),c=s.filter(e=>!o.has(e)),l=s.filter(e=>o.has(e)),u=e=>{let t=HM(e),n={alias:e,src:t};if(r!==void 0&&(n.data={resolution:r}),t.startsWith(`data:`)){let r=/^data:([^;,]+)/.exec(t)?.[1],i=(r&&UM[r])??/\.([a-z0-9]+)$/i.exec(e)?.[1];i&&(n.format=i)}Mk.add(n)};if(l.length===0&&c.length===0){n?.(1);return}for(let e of c)u(e);let d=c.length>0?Mk.load(c,n):Promise.resolve(),f=l.map(async e=>{u(e);try{await Mk.load(e)}catch(t){a?.(e,t)}});await Promise.all([d,...f]),l.length>0&&c.length===0&&n?.(1)}function GM(e,t){if(!Mk.cache.has(e)){if(t!==void 0)return t;throw Error(`texture "${e}" has not been loaded - pass it to load() first`)}return Mk.get(e)}function KM(e,t){if(!Mk.cache.has(e)){if(t!==void 0)return t;throw Error(`asset "${e}" has not been loaded - pass it to load() first`)}return Mk.get(e)}function qM(e){return Mk.cache.has(e)}async function JM(e){let t=e.filter(e=>Mk.cache.has(e));t.length!==0&&await Mk.unload(t)}var YM=new Map;async function XM(e,t,n={}){let r=n.fetch??globalThis.fetch;if(!r)throw Error(`fetch is unavailable; provide LoadBinaryOptions.fetch`);let i=e.filter(e=>!YM.has(e));if(i.length===0){t?.(1);return}let a=0;await Promise.all(i.map(async e=>{let n=await r(HM(e));if(!n.ok)throw Error(`failed to load binary asset "${e}": ${n.status}`);YM.set(e,await n.arrayBuffer()),a++,t?.(a/i.length)}))}function ZM(e){let t=YM.get(e);if(!t)throw Error(`binary asset "${e}" has not been loaded - pass it to loadBinary() first`);return t}function QM(e){return YM.has(e)}function $M(e){for(let t of e)YM.delete(t)}var eN=class{constructor(e={}){if(this.entries=new Map,this.clock=0,this.budgetBytes=e.budgetBytes??1/0,!(this.budgetBytes>=0))throw Error(`asset stream budget must not be negative`);this.loadAssets=e.load??WM,this.releaseAssets=e.release??JM}async preload(e,t){if(!e.id)throw Error(`asset bundle needs an id`);if(e.estimatedBytes!==void 0&&e.estimatedBytes<0)throw Error(`asset bundle size must not be negative`);let n=this.entries.get(e.id);if(n?.ready){n.lastUsed=++this.clock,t?.(1);return}let r=e.paths.filter(e=>!this.isRetained(e));r.length>0?await this.loadAssets([...r],t):t?.(1),this.entries.set(e.id,{...e,lastUsed:++this.clock,ready:!0}),await this.enforceBudget(e.id)}async preloadLikely(e,t){let n=[...e].sort((e,t)=>(t.priority??0)-(e.priority??0));for(let[e,r]of n.entries())await this.preload(r,t&&(r=>t((e+r)/n.length)));t?.(1)}use(e){let t=this.entries.get(e);return t?.ready?(t.lastUsed=++this.clock,!0):!1}isReady(e){return this.entries.get(e)?.ready??!1}async unload(e){let t=this.entries.get(e);if(!t)return;this.entries.delete(e);let n=t.paths.filter(e=>!this.isRetained(e));n.length>0&&await this.releaseAssets(n)}get estimatedBytes(){return[...this.entries.values()].reduce((e,t)=>e+(t.estimatedBytes??0),0)}async enforceBudget(e){for(;this.estimatedBytes>this.budgetBytes;){let t=[...this.entries.values()].filter(t=>t.id!==e).sort((e,t)=>e.lastUsed-t.lastUsed)[0];if(!t)return;await this.unload(t.id)}}isRetained(e){return[...this.entries.values()].some(t=>t.ready&&t.paths.includes(e))}};async function tN(e,t,n=fetch){let r=await n(e);if(!r.ok)throw Error(`fetchWithByteProgress: ${e} responded ${r.status}`);let i=r.headers.get(`content-length`),a=i!==null&&i!==``?Number(i):null;if(!r.body){let e=await r.blob();return t?.({loaded:e.size,total:a??e.size}),e}let o=r.body.getReader(),s=[],c=0;for(;;){let{done:e,value:n}=await o.read();if(e)break;s.push(n),c+=n.byteLength,t?.({loaded:c,total:a})}return new Blob(s)}var nN=l({AssetStream:()=>eN,fetchWithByteProgress:()=>tN,get:()=>KM,getBinary:()=>ZM,has:()=>VM,isBinaryLoaded:()=>QM,isCompiled:()=>zM,isLoaded:()=>qM,load:()=>WM,loadBinary:()=>XM,paths:()=>BM,release:()=>JM,releaseBinary:()=>$M,resolve:()=>HM,setAssetMap:()=>LM,setBase:()=>FM,texture:()=>GM});function rN(e){return{x:e.x,y:e.y,width:e.width,height:e.height}}var iN=class e{constructor(e,t,n){this.frames=new Map,this.names=new Map,this.texture=e,this.frameWidth=t,this.frameHeight=n,this.columns=t>0?Math.floor(e.width/t):0,this.rows=n>0?Math.floor(e.height/n):0}static grid(t,n=0,r=n){return new e(GM(t),n,r)}static fromTexture(t,n=0,r=n){return new e(t,n,r)}get count(){return this.columns*this.rows}name(e,t){return this.names.set(e,t),this}nameAll(e){for(let[t,n]of Object.entries(e))this.names.set(t,n);return this}indexOf(e){let t=this.names.get(e);if(t===void 0)throw Error(`this sheet has no frame named "${e}"`);return t}get(e){let t=typeof e==`string`?this.indexOf(e):e,n=this.frames.get(t);if(n)return n;if(t<0||t>=this.count)throw Error(`frame ${t} is outside this sheet, which holds ${this.count}`);let r=new J({source:this.texture.source,frame:new K(t%this.columns*this.frameWidth,Math.floor(t/this.columns)*this.frameHeight,this.frameWidth,this.frameHeight)});return this.frames.set(t,r),r}rect(e,t,n,r,i){if(r<=0||i<=0)throw Error(`a sprite sheet rect needs a positive width and height`);return this.frames.set(e,new J({source:this.texture.source,frame:new K(t,n,r,i)})),this}region(e){let t=this.get(e);return{texture:t,frame:rN(t.frame)}}range(e,t){let n=[];for(let r=e;r<=t;r++)n.push(this.get(r));return n}pick(...e){return e.map(e=>this.get(e))}},aN=class{constructor(e={}){if(this.world=new Y,this.x=0,this.y=0,this.viewWidth=0,this.viewHeight=0,this.screenX=0,this.screenY=0,this.followTarget=null,this.followIntensity=0,this.shakeMagnitude=0,this.shakeRemaining=0,this.shakeDuration=1,this.shakeX=0,this.shakeY=0,this.bounds=null,this.step=0,this._angle=0,this.targetAngle=null,this.angleIntensity=0,e.grid!==void 0&&e.grid!==`square`&&e.grid!==`hex`)throw Error(`camera grid must be "square" or "hex", not "${e.grid}"`);this.stepsPerTurn=e.grid===`hex`?6:4,this.deadzone=e.deadzone??0,this.pixelPerfectTileSize=e.pixelPerfectTileSize,this._zoom=1,this.zoom=e.zoom??1}get rotationSteps(){return this.step}get rotation(){return this._angle}get uprightRotation(){return-this.rotation}setRotationStep(e){if(!Number.isInteger(e))throw Error(`camera rotation step must be an integer`);this.step=(e%this.stepsPerTurn+this.stepsPerTurn)%this.stepsPerTurn,this._angle=this.step/this.stepsPerTurn*Math.PI*2,this.targetAngle=null,this.apply()}rotate(e=1){this.setRotationStep(this.step+e)}rotateTo(e){this._angle=e,this.targetAngle=null,this.angleIntensity=0,this.apply()}animateRotationTo(e,t=4){this.targetAngle=e,this.angleIntensity=t}get spin(){let e=this.rotation;return{cos:Math.cos(e),sin:Math.sin(e)}}get zoom(){return this._zoom}set zoom(e){let t=Math.max(.01,e);this._zoom=this.pixelPerfectTileSize?sN(t,this.pixelPerfectTileSize):t}setViewport(e,t,n=0,r=0){this.viewWidth=e,this.viewHeight=t,this.screenX=n,this.screenY=r}get view(){let e=this.viewWidth/this._zoom,t=this.viewHeight/this._zoom,{x:n,y:r}=this.clampedCentre(this.x,this.y);if(this._angle===0)return{x:n-e/2,y:r-t/2,width:e,height:t};let i=[this.toWorld(this.screenX,this.screenY),this.toWorld(this.screenX+this.viewWidth,this.screenY),this.toWorld(this.screenX+this.viewWidth,this.screenY+this.viewHeight),this.toWorld(this.screenX,this.screenY+this.viewHeight)],a=i.map(e=>e.x),o=i.map(e=>e.y),s=Math.min(...a),c=Math.min(...o);return{x:s,y:c,width:Math.max(...a)-s,height:Math.max(...o)-c}}setBounds(e){this.bounds=e}snapTo(e,t){this.x=e,this.y=t,this.followTarget=null,this.followIntensity=0,this.apply()}panTo(e,t,n=4){this.followTarget={x:e,y:t},this.followIntensity=n}follow(e,t=8){this.followTarget=e,this.followIntensity=t}stopFollowing(){this.followTarget=null,this.followIntensity=0}shake(e,t=.4){yr()||(this.shakeMagnitude=e,this.shakeRemaining=this.shakeDuration=t)}shakeScreen(e,t=.4){this.shake(e/this._zoom,t)}update(e){if(this.followTarget&&this.followIntensity>0){let t=this.viewWidth/this._zoom*this.deadzone/2,n=this.viewHeight/this._zoom*this.deadzone/2,r=this.followTarget.x-this.x,i=this.followTarget.y-this.y;r=r>t?r-t:r<-t?r+t:0,i=i>n?i-n:i<-n?i+n:0;let a=yr()?1:1-Math.exp(-this.followIntensity*e);this.x+=r*a,this.y+=i*a}if(this.targetAngle!==null&&this.angleIntensity>0){let t=oN(this._angle,this.targetAngle),n=yr()?1:1-Math.exp(-this.angleIntensity*e);this._angle+=t*n}if(this.shakeRemaining>0){this.shakeRemaining-=e;let t=Math.max(0,this.shakeRemaining/this.shakeDuration);this.shakeX=O(-this.shakeMagnitude,this.shakeMagnitude)*t,this.shakeY=O(-this.shakeMagnitude,this.shakeMagnitude)*t}else this.shakeX=this.shakeY=0;this.apply()}toScreen(e,t){let{x:n,y:r}=this.clampedCentre(this.x+this.shakeX,this.y+this.shakeY),{cos:i,sin:a}=this.spin,o=e-n,s=t-r;return{x:(o*i-s*a)*this._zoom+this.screenX+this.viewWidth/2,y:(o*a+s*i)*this._zoom+this.screenY+this.viewHeight/2}}toWorld(e,t){let{x:n,y:r}=this.clampedCentre(this.x+this.shakeX,this.y+this.shakeY),{cos:i,sin:a}=this.spin,o=(e-this.screenX-this.viewWidth/2)/this._zoom,s=(t-this.screenY-this.viewHeight/2)/this._zoom;return{x:n+o*i+s*a,y:r-o*a+s*i}}clampedCentre(e,t){if(!this.bounds)return{x:e,y:t};let n=this.viewWidth/this._zoom/2,r=this.viewHeight/this._zoom/2,{minX:i,minY:a,maxX:o,maxY:s}=this.bounds;return{x:o-i<n*2?(i+o)/2:On(e,i+n,o-n),y:s-a<r*2?(a+s)/2:On(t,a+r,s-r)}}apply(){let{x:e,y:t}=this.clampedCentre(this.x+this.shakeX,this.y+this.shakeY);if(this.world.scale.set(this._zoom),this._angle===0){this.world.rotation=0,this.world.pivot.set(0,0),this.world.x=Math.round(this.screenX+this.viewWidth/2-e*this._zoom),this.world.y=Math.round(this.screenY+this.viewHeight/2-t*this._zoom);return}this.world.rotation=this.rotation,this.world.pivot.set(e,t),this.world.x=Math.round(this.screenX+this.viewWidth/2),this.world.y=Math.round(this.screenY+this.viewHeight/2)}};function oN(e,t){let n=Math.PI*2,r=(t-e)%n;return r>Math.PI&&(r-=n),r<-Math.PI&&(r+=n),r}function sN(e,t){return Math.max(1,Math.round(e*t))/t}function cN(e={}){let t=new aN(e),n=Aj.current;return t.setViewport(n.width,n.height),t}var lN=class{constructor(e){this.container=new Y,this.clip=new bE,this.camera=new aN(e),this.container.addChild(this.camera.world),this.container.addChild(this.clip),this.container.mask=this.clip,this.resize(e.x,e.y,e.width,e.height)}resize(e,t,n,r){this.camera.setViewport(n,r,e,t),this.clip.clear().rect(e,t,n,r).fill(16777215)}update(e){this.camera.update(e)}};function uN(e,t){if(e>=t){let n=Math.floor(e/2);return[{x:0,y:0,width:n,height:t},{x:n,y:0,width:e-n,height:t}]}let n=Math.floor(t/2);return[{x:0,y:0,width:e,height:n},{x:0,y:n,width:e,height:t-n}]}var dN={protanopia:[.567,.433,0,0,0,.558,.442,0,0,0,0,.242,.758,0,0,0,0,0,1,0],deuteranopia:[.625,.375,0,0,0,.7,.3,0,0,0,0,.3,.7,0,0,0,0,0,1,0],tritanopia:[.95,.05,0,0,0,0,.433,.567,0,0,0,.475,.525,0,0,0,0,0,1,0]};function fN(e){let t=new Ik;return t.matrix=dN[e],t}function pN(e,t){let n=[];for(let r of e)t.has(r)||n.push(r);return n}function mN(e,t,n,r=`square`){return r===`hex`?Qn(e,t,n,n):{x:(e+.5)*n,y:(t+.5)*n}}var hN=class extends Y{constructor(e){super(),this.drawn=new Set,this.marker=new bE,this.widthInCells=e.widthInCells,this.cellSize=e.cellSize??2,this.shape=e.shape??`square`,this.renderTexture=u_.create({width:this.shape===`hex`?Math.ceil((e.widthInCells-1)*this.cellSize*.75+this.cellSize):e.widthInCells*this.cellSize,height:this.shape===`hex`?e.heightInCells*this.cellSize+this.cellSize/2:e.heightInCells*this.cellSize}),this.sprite=new xl(this.renderTexture),this.addChild(this.sprite),this.addChild(this.marker)}get exploredCount(){return this.drawn.size}sync(e,t){let n=pN(e,this.drawn);if(n.length===0)return;let r=new bE;for(let e of n){this.drawn.add(e);let n=e%this.widthInCells,i=Math.floor(e/this.widthInCells),a=mN(n,i,this.cellSize,this.shape);if(this.shape===`hex`){let e=this.cellSize/2,o=[];for(let t=0;t<6;t++){let n=Math.PI/3*t;o.push(a.x+Math.cos(n)*e,a.y+Math.sin(n)*e)}r.poly(o).fill({color:t(n,i)})}else r.rect(a.x-this.cellSize/2,a.y-this.cellSize/2,this.cellSize,this.cellSize).fill({color:t(n,i)})}Aj.current.app.renderer.render({container:r,target:this.renderTexture,clear:!1}),r.destroy()}setMarker(e,t,n,r=16777215){this.setMarkers([{x:e,y:t,facing:n,color:r}])}setMarkers(e){this.marker.clear();for(let t of e){let e=t.color??16777215,n=mN(t.x,t.y,this.cellSize,this.shape);if(this.marker.circle(n.x,n.y,Math.max(1,this.cellSize)).fill({color:e}),t.facing!==void 0){let r=this.cellSize*2;this.marker.moveTo(n.x,n.y).lineTo(n.x+Math.cos(t.facing)*r,n.y+Math.sin(t.facing)*r).stroke({color:e,width:1})}}}reset(){this.drawn.clear(),Aj.current.app.renderer.render({container:new Y,target:this.renderTexture,clear:!0})}destroy(e){this.renderTexture.destroy(!0),super.destroy(e)}},gN=24,_N=48,vN=[0,16,48,80];function yN(e,t){if(!Number.isInteger(t))throw Error(`${e} must be an integer, got ${t}`)}function bN(e){if(e!==0&&e!==1&&e!==2&&e!==3)throw Error(`RPG Maker autotile slot must be 0, 1, 2, or 3, got ${e}`)}function xN(e){if(e.length===0)throw Error(`RPG Maker autotile shape table cannot be empty`);for(let t=0;t<e.length;t++){if(e[t].length!==4)throw Error(`RPG Maker autotile shape ${t} needs exactly 4 quadrants`);for(let n of e[t])if(n.length!==2||!n.every(Number.isInteger)||n.some(e=>e<0))throw Error(`RPG Maker autotile shape ${t} has an invalid quadrant offset`)}}function SN(e,t){let n=vN[t]+Math.floor(e/48),r=n%8,i=Math.floor(n/8);return t===0?[Math.floor(r/4)*8,i*6+Math.floor(r/2)%2*3]:t===1?[r*2,(i-2)*3]:t===2?[r*2,(i-6)*2]:[r*2,Math.floor((i-10)*2.5+(i%2==1?.5:0))]}function CN(e,t,n,r){if(yN(`RPG Maker autotile tileId`,e),e<0)throw Error(`RPG Maker autotile tileId must be non-negative, got ${e}`);if(bN(t),yN(`RPG Maker autotile shape`,n),xN(r),n<0||n>=r.length)throw Error(`RPG Maker autotile shape ${n} is outside the table, which holds ${r.length}`);let[i,a]=SN(e,t);return{tileId:e,slot:t,shape:n,destinationX:e%16*_N,destinationY:Math.floor(e/16)*_N,quadrants:r[n].map(([e,t],n)=>({sourceX:(i*2+e)*gN,sourceY:(a*2+t)*gN,destinationX:n%2*gN,destinationY:Math.floor(n/2)*gN}))}}var wN=class{constructor(e){this.cache=new Map,this.table=e,xN(e)}get(e,t,n){let r=`${e}:${t}:${n}`,i=this.cache.get(r);if(i)return i;let a=CN(e,t,n,this.table);return this.cache.set(r,a),a}clear(){this.cache.clear()}},TN=[2048,2816,4352,5888],EN=[768,1536,1536,2304];function DN(e){if(!Number.isInteger(e))return null;for(let t=0;t<4;t++)if(e>=TN[t]&&e<TN[t]+EN[t])return t;return null}var ON=[[[2,4],[1,4],[2,3],[1,3]],[[2,0],[1,4],[2,3],[1,3]],[[2,4],[3,0],[2,3],[1,3]],[[2,0],[3,0],[2,3],[1,3]],[[2,4],[1,4],[2,3],[3,1]],[[2,0],[1,4],[2,3],[3,1]],[[2,4],[3,0],[2,3],[3,1]],[[2,0],[3,0],[2,3],[3,1]],[[2,4],[1,4],[2,1],[1,3]],[[2,0],[1,4],[2,1],[1,3]],[[2,4],[3,0],[2,1],[1,3]],[[2,0],[3,0],[2,1],[1,3]],[[2,4],[1,4],[2,1],[3,1]],[[2,0],[1,4],[2,1],[3,1]],[[2,4],[3,0],[2,1],[3,1]],[[2,0],[3,0],[2,1],[3,1]],[[0,4],[1,4],[0,3],[1,3]],[[0,4],[3,0],[0,3],[1,3]],[[0,4],[1,4],[0,3],[3,1]],[[0,4],[3,0],[0,3],[3,1]],[[2,2],[1,2],[2,3],[1,3]],[[2,2],[1,2],[2,3],[3,1]],[[2,2],[1,2],[2,1],[1,3]],[[2,2],[1,2],[2,1],[3,1]],[[2,4],[3,4],[2,3],[3,3]],[[2,4],[3,4],[2,1],[3,3]],[[2,0],[3,4],[2,3],[3,3]],[[2,0],[3,4],[2,1],[3,3]],[[2,4],[1,4],[2,5],[1,5]],[[2,0],[1,4],[2,5],[1,5]],[[2,4],[3,0],[2,5],[1,5]],[[2,0],[3,0],[2,5],[1,5]],[[0,4],[3,4],[0,3],[3,3]],[[2,2],[1,2],[2,5],[1,5]],[[0,2],[1,2],[0,3],[1,3]],[[0,2],[1,2],[0,3],[3,1]],[[2,2],[3,2],[2,3],[3,3]],[[2,2],[3,2],[2,1],[3,3]],[[2,4],[3,4],[2,5],[3,5]],[[2,0],[3,4],[2,5],[3,5]],[[0,4],[1,4],[0,5],[1,5]],[[0,4],[3,0],[0,5],[1,5]],[[0,2],[3,2],[0,3],[3,3]],[[0,2],[1,2],[0,5],[1,5]],[[0,4],[3,4],[0,5],[3,5]],[[2,2],[3,2],[2,5],[3,5]],[[0,2],[3,2],[0,5],[3,5]],[[0,0],[1,0],[0,1],[1,1]]],kN=[[[2,2],[1,2],[2,1],[1,1]],[[0,2],[1,2],[0,1],[1,1]],[[2,0],[1,0],[2,1],[1,1]],[[0,0],[1,0],[0,1],[1,1]],[[2,2],[3,2],[2,1],[3,1]],[[0,2],[3,2],[0,1],[3,1]],[[2,0],[3,0],[2,1],[3,1]],[[0,0],[3,0],[0,1],[3,1]],[[2,2],[1,2],[2,3],[1,3]],[[0,2],[1,2],[0,3],[1,3]],[[2,0],[1,0],[2,3],[1,3]],[[0,0],[1,0],[0,3],[1,3]],[[2,2],[3,2],[2,3],[3,3]],[[0,2],[3,2],[0,3],[3,3]],[[2,0],[3,0],[2,3],[3,3]],[[0,0],[3,0],[0,3],[3,3]]],AN=[[26,27,32,33],[4,27,32,33],[26,5,32,33],[4,5,32,33],[26,27,32,11],[4,27,32,11],[26,5,32,11],[4,5,32,11],[26,27,10,33],[4,27,10,33],[26,5,10,33],[4,5,10,33],[26,27,10,11],[4,27,10,11],[26,5,10,11],[4,5,10,11],[24,25,30,31],[24,5,30,31],[24,25,30,11],[24,5,30,11],[14,15,20,21],[14,15,20,11],[14,15,10,21],[14,15,10,11],[28,29,34,35],[28,29,10,35],[4,29,34,35],[4,29,10,35],[38,39,44,45],[4,39,44,45],[38,5,44,45],[4,5,44,45],[24,29,30,35],[14,15,44,45],[12,13,18,19],[12,13,18,11],[16,17,22,23],[16,17,10,23],[40,41,46,47],[4,41,46,47],[36,37,42,43],[36,5,42,43],[12,17,18,23],[12,13,42,43],[36,41,42,47],[16,17,46,47],[12,17,42,47],[0,1,6,7]],jN=[46,44,46,44,43,41,43,40,46,44,46,44,43,41,43,40,42,32,42,32,35,19,35,18,42,32,42,32,34,17,34,16,46,44,46,44,43,41,43,40,46,44,46,44,43,41,43,40,42,32,42,32,35,19,35,18,42,32,42,32,34,17,34,16,45,39,45,39,33,31,33,29,45,39,45,39,33,31,33,29,37,27,37,27,23,15,23,13,37,27,37,27,22,11,22,9,45,39,45,39,33,31,33,29,45,39,45,39,33,31,33,29,36,26,36,26,21,7,21,5,36,26,36,26,20,3,20,1,46,44,46,44,43,41,43,40,46,44,46,44,43,41,43,40,42,32,42,32,35,19,35,18,42,32,42,32,34,17,34,16,46,44,46,44,43,41,43,40,46,44,46,44,43,41,43,40,42,32,42,32,35,19,35,18,42,32,42,32,34,17,34,16,45,38,45,38,33,30,33,28,45,38,45,38,33,30,33,28,37,25,37,25,23,14,23,12,37,25,37,25,22,10,22,8,45,38,45,38,33,30,33,28,45,38,45,38,33,30,33,28,36,24,36,24,21,6,21,4,36,24,36,24,20,2,20,0];function MN(e){return!Number.isInteger(e)||e<=0||e>=384?null:{index:Math.floor(e/48),pattern:e%48}}function NN(e){let t=0;return e(0,-1)&&(t|=1),e(1,-1)&&(t|=2),e(1,0)&&(t|=4),e(1,1)&&(t|=8),e(0,1)&&(t|=16),e(-1,1)&&(t|=32),e(-1,0)&&(t|=64),e(-1,-1)&&(t|=128),jN[t]}var PN=[16,32,32,48];function FN(e){if(e.format===`rpgm-mv`){if(bN(e.slot),xN(e.table),e.tableEdge&&e.slot!==1)throw Error(`a table-edge layout needs slot 1 (A2), got slot ${e.slot}`);let t=PN[e.slot],n=vN[e.slot];for(let r of e.cycles){if(r.length===0)throw Error(`an autotile animation cycle needs at least one kind`);for(let i of r)if(!Number.isInteger(i)||i<n||i>=n+t)throw Error(`animation cycle kind ${i} is outside slot ${e.slot}'s kinds ${n}-${n+t-1}`)}return}if(!Number.isInteger(e.index)||e.index<0||e.index>7)throw Error(`an XP autotile index must be 0-7, got ${e.index}`);if(!Number.isInteger(e.frames)||e.frames<1)throw Error(`an XP autotile frame count must be at least 1, got ${e.frames}`)}var IN=24,LN=16,RN=6,zN=96,BN=32;function VN(e,t,n){if(t<=0)return null;if(!Number.isInteger(n)||n<0)throw Error(`an autotile animation frame must be an integer at or above zero, got ${n}`);return e.format===`rpgm-mv`?UN(e,t,n):WN(e,t,n)}function HN(e,t){let n=vN[e.slot]+Math.floor(t/48),r=t%48%e.table.length,i=n%8*2,a=(Math.floor(n/8)-2)*3,o=IN/2;return[2,3].map((t,n)=>{let[s,c]=e.table[r][t];return{sourceX:(i*2+s)*IN,sourceY:(a*2+c)*IN+o,sourceWidth:IN,sourceHeight:o,destX:n/2,destY:0,destWidth:1/2,destHeight:1/4}})}function UN(e,t,n){let r=TN[e.slot],i=EN[e.slot];if(!Number.isInteger(t)||t<r||t>=r+i)throw Error(`tile ${t} is outside slot ${e.slot}'s ids ${r}-${r+i-1}`);let a=t-r;if(e.tableEdge)return HN(e,a);let o=vN[e.slot]+Math.floor(a/48),s=e.tableFor?e.tableFor(o):e.table,c=a%48%s.length;for(let t of e.cycles){let e=t.indexOf(o);if(e>=0){o=t[(e+n)%t.length];break}}return CN((o-vN[e.slot])*48+a%48,e.slot,c,s).quadrants.map((e,t)=>({sourceX:e.sourceX,sourceY:e.sourceY,sourceWidth:IN,sourceHeight:IN,destX:t%2/2,destY:Math.floor(t/2)/2,destWidth:1/2,destHeight:1/2}))}function WN(e,t,n){if(!Number.isInteger(t)||t<e.index*48||t>=e.index*48+48||t<=0)throw Error(`tile ${t} is outside XP autotile ${e.index}'s ids ${e.index*48}-${e.index*48+47}`);if(e.single)return[{sourceX:n%e.frames*BN,sourceY:0,sourceWidth:BN,sourceHeight:BN,destX:0,destY:0,destWidth:1,destHeight:1}];let r=AN[t%48],i=n%e.frames*zN;return r.map((e,t)=>({sourceX:e%RN*LN+i,sourceY:Math.floor(e/RN)*LN,sourceWidth:LN,sourceHeight:LN,destX:t%2/2,destY:Math.floor(t/2)/2,destWidth:1/2,destHeight:1/2}))}var GN=128;function KN(e){let t=new Int32Array(e.width*e.height),n=t=>DN(t)===1&&((e.flags[t]??0)&GN)!==0;for(let r=1;r<e.height;r++)for(let i=0;i<e.width;i++){let a=r*e.width+i,o=e.objects[a-e.width]??0;if(!n(o)||n(e.objects[a]??0))continue;let s=DN(e.ground[a]??0);s!==2&&s!==3&&(t[a]=o)}return t}var qN=-1,JN=7237230,YN=10132122;function XN(e,t){if(!Number.isInteger(e)||e<0||e>=4096)throw Error(`tileFrame needs a sheet index from 0 to 4095, got ${e}`);if(!Number.isInteger(t)||t<0||t>=1<<20)throw Error(`tileFrame needs a frame index from 0 to ${(1<<20)-1}, got ${t}`);return e<<20|t}function ZN(e){return e>>>20}function QN(e){return e&(1<<20)-1}var $N=class extends Y{constructor(e){if(super(),this.layers=[],this.layersByName=new Map,this.chunks=[],this.widthInTiles=e.width,this.heightInTiles=e.height,this.sheets=Array.isArray(e.sheet)?[...e.sheet]:[e.sheet],this.sheets.length===0)throw Error(`a TileMap needs at least one sheet`);if(this.tileWidth=e.tileWidth??this.sheets[0].frameWidth,this.tileHeight=e.tileHeight??this.sheets[0].frameHeight,this.shape=e.shape??`square`,this.heightStep=e.heightStep??this.tileHeight/2,!(this.heightStep>0))throw Error(`a TileMap's heightStep must be a positive number, got ${e.heightStep}`);this.chunkSize=e.chunkSize??16,this.chunkColumns=Math.ceil(this.widthInTiles/this.chunkSize),this.chunkRows=Math.ceil(this.heightInTiles/this.chunkSize);let t=this.widthInTiles*this.heightInTiles;this.cellTint=new Uint32Array(t).fill(16777215),this.cellAdd=new Uint32Array(t),this.cellHeight=new Int32Array(t),this.faces=Array(t).fill(null)}get layerCount(){return this.layers.length}get worldWidth(){switch(this.shape){case`square`:return this.widthInTiles*this.tileWidth;case`hex`:return this.widthInTiles<=0?0:(this.widthInTiles-1)*this.tileWidth*.75+this.tileWidth;case`isometric`:return(this.widthInTiles+this.heightInTiles)*(this.tileWidth/2);case`staggered`:return this.widthInTiles*this.tileWidth+this.tileWidth/2}}get worldHeight(){switch(this.shape){case`square`:return this.heightInTiles*this.tileHeight;case`hex`:return this.heightInTiles*this.tileHeight+this.tileHeight/2;case`isometric`:return(this.widthInTiles+this.heightInTiles)*(this.tileHeight/2);case`staggered`:return this.heightInTiles*(this.tileHeight/2)+this.tileHeight/2}}inside(e,t){return e>=0&&t>=0&&e<this.widthInTiles&&t<this.heightInTiles}index(e,t){return t*this.widthInTiles+e}addLayer(e,t){let{cells:n,container:r,chunks:i}=this.beginLayer(e,t?.length),a={kind:`tiles`,name:e,data:t?Int32Array.from(t):new Int32Array(n).fill(-1),sprites:Array(n).fill(null),container:r};this.layers.push(a),this.layersByName.set(e,a),this.chunks.push(i),this.addChild(r);let o=this.layers.length===1;for(let e=0;e<this.heightInTiles;e++)for(let t=0;t<this.widthInTiles;t++){let n=a.data[this.index(t,e)];n!==-1&&this.buildSprite(a,t,e,n),o&&this.syncFaces(t,e)}return this}beginLayer(e,t){if(this.layersByName.has(e))throw Error(`this map already has a layer named "${e}"`);let n=this.widthInTiles*this.heightInTiles;if(t!==void 0&&t!==n)throw Error(`layer "${e}" has ${t} cells, but the map has ${n}`);let r=new Y,i=[];for(let e=0;e<this.chunkColumns*this.chunkRows;e++){let e=new Y;i.push(e),r.addChild(e)}return{cells:n,container:r,chunks:i}}addAutotileLayer(e,t,n){let r=Array.isArray(n)?n:[n];if(r.length===0)throw Error(`autotile layer "${e}" needs at least one set`);let{cells:i,container:a,chunks:o}=this.beginLayer(e,t.length),s=r.map((t,n)=>this.resolveAutotileSet(e,t,n)),c=new Set;for(let t of s){let n=t.layout.format===`rpgm-mv`?`slot ${t.layout.slot}`:`autotile ${t.layout.index}`;if(c.has(n))throw Error(`autotile layer "${e}" has two sets for ${n}`);c.add(n)}let l=0;r.forEach((t,n)=>{let r=t.animationFrame??0;if(!Number.isInteger(r)||r<0)throw Error(`autotile layer "${e}" set ${n} starts at an invalid animation frame, got ${t.animationFrame}`);if(n===0)l=r;else if(r!==l)throw Error(`autotile layer "${e}" sets disagree on their initial animation frame (${l} vs ${r})`)});let u=Int32Array.from(t);for(let t=0;t<i;t++)u[t]>0&&this.claimAutotileSets(s,e,u[t]);let d={kind:`autotile`,name:e,data:u,sprites:Array(i).fill(null),container:a,sets:s,frame:l};this.layers.push(d),this.layersByName.set(e,d),this.chunks.push(o),this.addChild(a);let f=this.layers.length===1;for(let t=0;t<this.heightInTiles;t++)for(let n=0;n<this.widthInTiles;n++){let r=this.index(n,t),i=u[r];i<=0||(d.sprites[r]=this.makeAutotileSprites(d,this.claimAutotileSets(s,e,i),n,t,i),f&&this.syncFaces(n,t))}return this}setAutotileFrame(e,t){let n=this.layerAt(e);if(n.kind!==`autotile`)throw Error(`layer "${n.name}" is not an autotile layer`);if(!Number.isInteger(t)||t<0)throw Error(`an autotile animation frame must be an integer at or above zero, got ${t}`);if(n.frame!==t){n.frame=t;for(let e=0;e<this.heightInTiles;e++)for(let r=0;r<this.widthInTiles;r++){let i=this.index(r,e),a=n.data[i];if(a<=0)continue;let o=this.claimAutotileSets(n.sets,n.name,a),s=this.autotilePieces(o,a,t),c=n.sprites[i];if(c)for(let e=0;e<c.length;e++)c[e].texture=s.textures[e]}}}addShadowLayer(e,t,n={}){let{cells:r,container:i,chunks:a}=this.beginLayer(e,t.length),o=n.color??0,s=n.alpha??.5;if(!Number.isFinite(s)||s<0||s>1)throw Error(`shadow layer "${e}" alpha must be between 0 and 1, got ${n.alpha}`);let c=Int32Array.from(t,e=>e>0?e&15:0),l={kind:`shadow`,name:e,data:c,sprites:Array(r).fill(null),container:i,color:o,alpha:s};this.layers.push(l),this.layersByName.set(e,l),this.chunks.push(a),this.addChild(i);for(let e=0;e<this.heightInTiles;e++)for(let t=0;t<this.widthInTiles;t++)c[this.index(t,e)]>0&&this.buildShadowSprites(l,t,e);return this}buildShadowSprites(e,t,n){let r=this.index(t,n),i=this.cellOrigin(t,n),a=this.cellHeight[r]*this.heightStep,o=this.tileWidth/2,s=this.tileHeight/2,c=this.chunks[this.layers.indexOf(e)][this.chunkIndex(t,n)],l=[];for(let t=0;t<4;t++){if(!(e.data[r]&1<<t))continue;let n=new Zj(J.WHITE);n.x=i.x+t%2*o,n.y=i.y-a+Math.floor(t/2)*s,n.width=o,n.height=s,n.tint=e.color,n.alpha=e.alpha,c.addChild(n),l.push(n)}e.sprites[r]=l}setShadowCell(e,t,n,r){let i=this.index(t,n);e.data[i]=r>0?r&15:0;for(let t of e.sprites[i]??[])t.destroy();e.sprites[i]=null,e.data[i]>0&&this.buildShadowSprites(e,t,n)}getAutotileFrame(e){let t=this.layerAt(e);if(t.kind!==`autotile`)throw Error(`layer "${t.name}" is not an autotile layer`);return t.frame}resolveAutotileSet(e,t,n){let r=`autotile layer "${e}" set ${n}`;if(!t||!t.sheet)throw Error(`${r} needs a source sheet`);let i=t.format??`rpgm-mv`;if(i!==`rpgm-mv`&&i!==`rpgm-xp`)throw Error(`${r} has an unknown format "${t.format}"`);return i===`rpgm-mv`?this.resolveRpgmSet(r,t):this.resolveXpSet(r,t)}resolveRpgmSet(e,t){if(t.slot===void 0)throw Error(`${e} needs a slot (0-3) for its MV sheet`);if(t.mode!==void 0&&t.mode!==`floor`&&t.mode!==`wall`&&t.mode!==`mixed`)throw Error(`${e} has an unknown mode "${t.mode}"`);if(t.animation!==void 0&&!Array.isArray(t.animation))throw Error(`${e} animation must list kind runs, got ${typeof t.animation}`);let n=t.mode??(t.slot<2?`floor`:`wall`),r=n===`mixed`&&t.slot===3&&t.table===void 0,i={format:`rpgm-mv`,slot:t.slot,table:t.table??(n===`floor`||t.tableEdge||n===`mixed`&&t.slot<2?ON:kN),...r?{tableFor:e=>Math.floor(e/8)%2==0?ON:kN}:{},...t.tableEdge?{tableEdge:!0}:{},cycles:t.animation??[]};return FN(i),{sheet:t.sheet,layout:i,cache:new Map,claims:e=>DN(e)===t.slot}}resolveXpSet(e,t){let n=t.index??0,r=t.sheet.texture,i=r.height===32;if(r.height!==32&&r.height!==128)throw Error(`${e} is ${r.height}px tall - XP autotile images are 128px templates or 32px single-tile strips`);let a=i?32:96,o=t.frames??Math.max(1,Math.floor(r.width/a)),s={format:`rpgm-xp`,index:n,frames:o,single:i};if(FN(s),o>Math.floor(r.width/a))throw Error(`${e} asks for ${o} frames but its sheet fits ${Math.floor(r.width/a)}`);return{sheet:t.sheet,layout:s,cache:new Map,claims:e=>{let t=MN(e);return t!==null&&t.index===n}}}claimAutotileSets(e,t,n){for(let t of e)if(t.claims(n))return t;throw Error(`tile ${n} in autotile layer "${t}" matches none of its sets`)}autotilePieces(e,t,n){let r=`${t}:${n}`,i=e.cache.get(r);if(i)return i;let a=VN(e.layout,t,n),o={parts:a,textures:a.map(t=>new J({source:e.sheet.texture.source,frame:new K(t.sourceX,t.sourceY,t.sourceWidth,t.sourceHeight)}))};return e.cache.set(r,o),o}makeAutotileSprites(e,t,n,r,i){let a=this.index(n,r),o=this.autotilePieces(t,i,e.frame),s=this.cellOrigin(n,r),c=this.cellHeight[a]*this.heightStep,l=o.textures.map((e,t)=>{let n=o.parts[t],r=new Zj(e);return r.x=s.x+n.destX*this.tileWidth,r.y=s.y-c+n.destY*this.tileHeight,r.scale.set(n.destWidth*this.tileWidth/n.sourceWidth,n.destHeight*this.tileHeight/n.sourceHeight),r.tint=this.cellTint[a],r.colorAdd=this.cellAdd[a],r}),u=this.chunks[this.layers.indexOf(e)][this.chunkIndex(n,r)];for(let e of l)u.addChild(e);return l}setAutotileCell(e,t,n,r){let i=this.index(t,n);e.data[i]=r;let a=e.sprites[i];if(r<=0){if(a)for(let e of a)e.destroy();e.sprites[i]=null;return}let o=this.claimAutotileSets(e.sets,e.name,r),s=this.autotilePieces(o,r,e.frame);if(a&&a.length===s.textures.length){for(let e=0;e<a.length;e++)a[e].texture=s.textures[e];return}if(a)for(let e of a)e.destroy();e.sprites[i]=this.makeAutotileSprites(e,o,t,n,r)}eachCellSprite(e,t,n){let r=e.sprites[t];if(r){if(Array.isArray(r))for(let e of r)n(e);else n(r)}}firstCellSprite(e,t){let n=e.sprites[t];return n?Array.isArray(n)?n[0]:n:null}layerAt(e){let t=typeof e==`number`?this.layers[e]:this.layersByName.get(e);if(!t)throw Error(`no such layer: ${e}`);return t}chunkIndex(e,t){return Math.floor(t/this.chunkSize)*this.chunkColumns+Math.floor(e/this.chunkSize)}projectedCenter(e,t){switch(this.shape){case`square`:return{x:(e+.5)*this.tileWidth,y:(t+.5)*this.tileHeight};case`hex`:return Qn(e,t,this.tileWidth,this.tileHeight);case`isometric`:return{x:(e-t+(this.heightInTiles-1))*(this.tileWidth/2)+this.tileWidth/2,y:(e+t)*(this.tileHeight/2)+this.tileHeight/2};case`staggered`:return{x:e*this.tileWidth+(t&1)*(this.tileWidth/2)+this.tileWidth/2,y:t*(this.tileHeight/2)+this.tileHeight/2}}}projectedTile(e,t){switch(this.shape){case`square`:return{x:Math.floor(e/this.tileWidth),y:Math.floor(t/this.tileHeight)};case`hex`:return $n(e,t,this.tileWidth,this.tileHeight);case`isometric`:{let n=(e-this.tileWidth/2)/(this.tileWidth/2)-(this.heightInTiles-1),r=(t-this.tileHeight/2)/(this.tileHeight/2);return{x:Math.round((n+r)/2),y:Math.round((r-n)/2)}}case`staggered`:{let n=Math.round((t-this.tileHeight/2)/(this.tileHeight/2));return{x:Math.round((e-this.tileWidth/2-(n&1)*(this.tileWidth/2))/this.tileWidth),y:n}}}}cellOrigin(e,t){let n=this.projectedCenter(e,t);return{x:n.x-this.tileWidth/2,y:n.y-this.tileHeight/2}}textureFor(e){let t=ZN(e);if(t>=this.sheets.length)throw Error(`frame ${e} names sheet ${t}, but this map has ${this.sheets.length}`);return this.sheets[t].get(QN(e))}buildSprite(e,t,n,r){let i=new Zj(this.textureFor(r)),a=this.cellOrigin(t,n);i.x=a.x,i.y=a.y-this.cellHeight[this.index(t,n)]*this.heightStep;let o=this.index(t,n);return i.tint=this.cellTint[o],i.colorAdd=this.cellAdd[o],e.sprites[o]=i,this.chunks[this.layers.indexOf(e)][this.chunkIndex(t,n)].addChild(i),i}getTile(e,t,n){return this.inside(t,n)?this.layerAt(e).data[this.index(t,n)]:-1}setTile(e,t,n,r){if(!this.inside(t,n))return;let i=this.layerAt(e),a=this.index(t,n);if(i.data[a]!==r){if(i.kind===`autotile`)this.setAutotileCell(i,t,n,r);else if(i.kind===`shadow`)this.setShadowCell(i,t,n,r);else{i.data[a]=r;let e=i.sprites[a];r===-1?(e?.destroy(),i.sprites[a]=null):e?e.texture=this.textureFor(r):this.buildSprite(i,t,n,r)}this.layers[0]===i&&this.syncFaces(t,n)}}setLayerData(e,t){this.layerAt(e);for(let n=0;n<this.heightInTiles;n++)for(let r=0;r<this.widthInTiles;r++)this.setTile(e,r,n,t[this.index(r,n)]??-1)}stampRect(e,t,n,r,i,a){if(this.layerAt(e),a.length!==r*i)throw Error(`a ${r}x${i} stamp needs ${r*i} frames, got ${a.length}`);if(t<0||n<0||t+r>this.widthInTiles||n+i>this.heightInTiles)throw Error(`a ${r}x${i} stamp at (${t},${n}) does not fit the ${this.widthInTiles}x${this.heightInTiles} map`);for(let o=0;o<i;o++)for(let i=0;i<r;i++)this.setTile(e,t+i,n+o,a[o*r+i])}setCellColor(e,t,n,r=0){if(!this.inside(e,t))return;let i=this.index(e,t);if(this.cellTint[i]===n&&this.cellAdd[i]===r)return;this.cellTint[i]=n,this.cellAdd[i]=r;for(let e of this.layers)e.kind!==`shadow`&&this.eachCellSprite(e,i,e=>{e.tint=n,e.colorAdd=r});let a=this.faces[i];a&&(a.tint=n)}getCellTint(e,t){return this.inside(e,t)?this.cellTint[this.index(e,t)]:0}clearColors(){for(let e=0;e<this.heightInTiles;e++)for(let t=0;t<this.widthInTiles;t++)this.setCellColor(t,e,16777215,0)}setCellHeight(e,t,n){if(!this.inside(e,t))return;if(!Number.isInteger(n))throw Error(`a cell's height must be a whole number, got ${n}`);let r=this.index(e,t);if(this.cellHeight[r]===n)return;let i=(n-this.cellHeight[r])*this.heightStep;this.cellHeight[r]=n;for(let e of this.layers)this.eachCellSprite(e,r,e=>{e.y-=i});this.syncFaces(e,t)}getCellHeight(e,t){return this.inside(e,t)?this.cellHeight[this.index(e,t)]:0}get faceCount(){return this.faces.filter(e=>e!==null).length}syncFaces(e,t){if(this.layers.length===0)return;let n=this.index(e,t),r=(this.shape===`isometric`||this.shape===`staggered`)&&this.cellHeight[n]>0&&this.layers[0].data[n]!==-1,i=this.faces[n];if(!r){i&&(i.destroy(),this.faces[n]=null);return}let a=i??new bE;if(this.drawFaces(a,e,t),a.tint=this.cellTint[n],!i){this.faces[n]=a;let r=this.chunks[0][this.chunkIndex(e,t)],i=this.firstCellSprite(this.layers[0],n);i?r.addChildAt(a,r.getChildIndex(i)):r.addChild(a)}}drawFaces(e,t,n){let r=this.cellOrigin(t,n),i=r.x,a=r.y,o=this.tileWidth/2,s=this.tileHeight/2,c=this.heightStep,l=this.cellHeight[this.index(t,n)];e.clear();for(let t=1;t<=l;t++){let n=t*c,r=(t-1)*c;e.poly([i,a+s-n,i+o,a+s*2-n,i+o,a+s*2-r,i,a+s-r]).fill(JN),e.poly([i+o,a+s*2-n,i+o*2,a+s-n,i+o*2,a+s-r,i+o,a+s*2-r]).fill(YN)}}toTile(e,t){return this.projectedTile(e,t)}tileCenter(e,t){let n=this.projectedCenter(e,t);return n.y-=this.getCellHeight(e,t)*this.heightStep,n}cull(e){let t=e.view,n=this.projectedTile(t.x,t.y),r=this.projectedTile(t.x+t.width,t.y),i=this.projectedTile(t.x,t.y+t.height),a=this.projectedTile(t.x+t.width,t.y+t.height),o=Math.min(n.x,r.x,i.x,a.x),s=Math.max(n.x,r.x,i.x,a.x),c=Math.min(n.y,r.y,i.y,a.y),l=Math.max(n.y,r.y,i.y,a.y),u=Math.floor(o/this.chunkSize)-1,d=Math.floor(s/this.chunkSize)+1,f=Math.floor(c/this.chunkSize)-1,p=Math.floor(l/this.chunkSize)+1;for(let e=0;e<this.chunkRows;e++){let t=e>=f&&e<=p;for(let n=0;n<this.chunkColumns;n++){let r=t&&n>=u&&n<=d,i=e*this.chunkColumns+n;for(let e of this.chunks)e[i].renderable=r}}}get visibleChunks(){return this.chunks.length===0?0:this.chunks[0].filter(e=>e.renderable).length}},eP=class extends Y{constructor(...e){super(...e),this.layers=new Map}addLayer(e,t,n=0){this.removeLayer(e);let r=new Zj(t);return this.layers.set(e,{sprite:r,order:n}),this.addChild(r),this.resort(),r}removeLayer(e){let t=this.layers.get(e);t&&(this.layers.delete(e),t.sprite.destroy())}layer(e){return this.layers.get(e)?.sprite}hasLayer(e){return this.layers.has(e)}setTexture(e,t){let n=this.layers.get(e);n&&(n.sprite.texture=t)}resort(){[...this.layers.values()].sort((e,t)=>e.order-t.order).forEach((e,t)=>this.setChildIndex(e.sprite,t))}},tP=class{constructor(e,t,n,r={}){this.elapsed=0,this.arrived=!1,this.sprite=e,this.fromX=t.x,this.fromY=t.y,this.toX=n.x,this.toY=n.y,this.animation=r.animation;let i=Math.hypot(n.x-t.x,n.y-t.y);this.duration=r.duration??i/(r.speed??400),this.duration<=0&&(this.duration=1e-6),e.x=t.x,e.y=t.y}get done(){return this.arrived}get progress(){return Math.min(1,this.elapsed/this.duration)}get frame(){return this.animation?.frameAt(this.elapsed)}get frameOffset(){let e=this.frame;return{x:e?.offsetX??0,y:e?.offsetY??0}}update(e){if(this.arrived)return!1;this.elapsed+=e;let t=this.progress;return this.sprite.x=this.fromX+(this.toX-this.fromX)*t,this.sprite.y=this.fromY+(this.toY-this.fromY)*t,t>=1&&(this.arrived=!0,!0)}};function nP(e){return e===!0||e===`progress`?`progress`:typeof e==`number`&&e>0?`seconds`:`none`}var rP=class extends Y{constructor(...e){super(...e),this.live=[]}add(e,t,n,r={}){let i,a;e instanceof J?(a=new xl(e),this.addChild(a),i=a):i=e,r.tint!==void 0&&typeof i.tint==`number`&&(i.tint=r.tint);let o=nP(r.fadeIn),s=typeof r.fadeIn==`number`?r.fadeIn:0,c=typeof i.alpha==`number`?i.alpha:1;o!==`none`&&(i.alpha=0);let l={projectile:new tP(i,t,n,r),sprite:i,built:a,onArrive:r.onArrive,spin:r.spin??(r.spinDegrees===void 0?void 0:r.spinDegrees*Math.PI/180),fadeMode:o,fadeIn:s,baseAlpha:c,elapsed:0};return this.live.push(l),{projectile:l.projectile,get done(){return l.projectile.done},cancel:()=>{let e=this.live.indexOf(l);e!==-1&&(this.live.splice(e,1),this.release(l))}}}update(e){for(let t=this.live.length-1;t>=0;t--){let n=this.live[t];n.elapsed+=e,n.spin!==void 0&&(n.sprite.rotation=(n.sprite.rotation??0)+n.spin*e),n.fadeMode===`seconds`&&(n.sprite.alpha=n.baseAlpha*Math.min(1,n.elapsed/n.fadeIn));let r=n.projectile.update(e);n.fadeMode===`progress`&&(n.sprite.alpha=n.baseAlpha*n.projectile.progress),r&&(this.live.splice(t,1),this.release(n),n.onArrive?.())}}get count(){return this.live.length}clear(){for(let e of this.live.splice(0))this.release(e)}destroy(){this.clear(),super.destroy()}release(e){e.built&&(this.removeChild(e.built),e.built.destroy())}},iP=class extends Y{constructor(e,t,n={}){super(),this.elapsed=0,this.expired=!1,this.lifeFraction=1,this.from={...e},this.to={...t},this.colour=n.colour??16777215,this.thin=n.thin??!1;let r=n.texture;if(r===void 0?(this.texture=void 0,this.stretch=!1,this.textureAnchor=0):r instanceof J?(this.texture=r,this.stretch=!1,this.textureAnchor=0):(this.texture=r.source,this.stretch=r.stretch??!1,this.textureAnchor=r.anchor??.5),this.thickness=n.width??2,this.duration=Math.max(1e-6,n.duration??.2),this.texture&&this.stretch)this.body=new xl(this.texture),this.body.anchor.set(0,this.textureAnchor);else if(this.texture){let e=new iA({texture:this.texture,width:1,height:this.thickness});e.anchor.set(0,this.textureAnchor),this.body=e}else this.body=new bE;(n.additive??!0)&&(this.body.blendMode=`add`),this.addChild(this.body),this.redraw()}get progress(){return Math.min(1,this.elapsed/this.duration)}get done(){return this.expired}retarget(e,t){e&&(this.from={...e}),t&&(this.to={...t}),this.redraw()}update(e){return!this.expired&&(this.elapsed+=e,this.alpha=1-this.progress,this.lifeFraction=this.thin?1-this.progress:1,this.thin&&this.redraw(),this.elapsed>=this.duration&&(this.expired=!0,!0))}destroy(){this.removeChild(this.body),this.body.destroy(),super.destroy()}redraw(){let e=this.to.x-this.from.x,t=this.to.y-this.from.y,n=Math.hypot(e,t);if(this.position.set(this.from.x,this.from.y),this.rotation=n>0?Math.atan2(t,e):0,this.body instanceof iA)this.body.width=n,this.body.height=this.thickness*this.lifeFraction;else if(this.body instanceof xl){let e=this.texture?.width||1,t=this.texture?.height||1;this.body.scale.x=n/e,this.body.scale.y=this.thickness/t*this.lifeFraction}else{let e=this.body;e.clear(),e.moveTo(0,0),e.lineTo(n,0),e.stroke({width:this.thickness*this.lifeFraction,color:this.colour})}}},aP=class extends Y{constructor(...e){super(...e),this.live=[]}add(e,t,n){let r=new iP(e,t,n);return this.addChild(r),this.live.push(r),r}update(e){for(let t=this.live.length-1;t>=0;t--)if(this.live[t].update(e)){let[e]=this.live.splice(t,1);this.removeChild(e),e.destroy()}}get count(){return this.live.length}clear(){for(let e of this.live.splice(0))this.removeChild(e),e.destroy()}destroy(){this.clear(),super.destroy()}},oP=class{constructor(e,t,n={}){this.elapsed=0,this.sinceFlicker=0,this.expired=!1,this.current=[],this.from={...e},this.to={...t},this.segments=Math.max(0,Math.floor(n.segments??6)),this.jitter=n.jitter??12,this.flickerInterval=n.flickerInterval,this.random=n.random??Math.random,this.duration=n.duration,this.reroll()}get points(){return this.current}get done(){return this.expired}retarget(e,t){e&&(this.from={...e}),t&&(this.to={...t}),this.flickerInterval===void 0&&this.reroll()}update(e){return!this.expired&&(this.elapsed+=e,this.flickerInterval!==void 0&&(this.sinceFlicker+=e,this.sinceFlicker>=this.flickerInterval&&(this.sinceFlicker=0,this.reroll())),this.duration!==void 0&&this.elapsed>=this.duration&&(this.expired=!0,!0))}reroll(){let e=this.to.x-this.from.x,t=this.to.y-this.from.y,n=Math.hypot(e,t),r=n>0?-t/n:0,i=n>0?e/n:0,a=[{...this.from}],o=this.segments+1;for(let n=1;n<o;n+=1){let s=n/o,c=Math.sin(Math.PI*s),l=(this.random()*2-1)*this.jitter*c;a.push({x:this.from.x+e*s+r*l,y:this.from.y+t*s+i*l})}a.push({...this.to}),this.current=a}},sP=class{constructor(e,t={}){this.elapsed=0,this.expired=!1,this.child=e,this.offsetX=t.offsetX??0,this.offsetY=t.offsetY??0,this.duration=t.duration}get done(){return this.expired}follow(e,t){return this.child.x=e+this.offsetX,this.child.y=t+this.offsetY,this}update(e){return this.expired||this.duration===void 0?!1:(this.elapsed+=e,this.elapsed>=this.duration&&(this.expired=!0,!0))}},cP=class extends Y{constructor(e){super(),this.cells=new Map,this.ripples=[],this.offset=0,this.eventMode=`none`,this.columns=e.width,this.tileSize=e.tileSize??16,this.speed=e.speed??5,this.rippleTexture=e.rippleTexture,this.rippleDuration=e.rippleDuration??.5;for(let t=0;t<e.height;t++)for(let n=0;n<e.width;n++){if(!e.isLiquid(n,t))continue;let r=new iA({texture:e.texture,width:this.tileSize,height:this.tileSize});r.eventMode=`none`,r.position.set(n*this.tileSize,t*this.tileSize),r.tilePosition.set(-r.x,-r.y),r.visible=!1,this.cells.set(n+t*this.columns,r),this.addChild(r)}}setCellColor(e,t,n){let r=this.cells.get(e+t*this.columns);r&&(r.tint=n,r.visible=n!==0)}ripple(e,t){if(!this.rippleTexture||!this.cells.get(e+t*this.columns)?.visible)return;let n=new xl(this.rippleTexture);n.eventMode=`none`,n.anchor.set(.5),n.position.set((e+.5)*this.tileSize,(t+.5)*this.tileSize),n.scale.set(0),this.addChild(n),this.ripples.push({sprite:n,age:0})}get rippleCount(){return this.ripples.length}update(e){this.offset+=this.speed*e;for(let e of this.cells.values())e.visible&&(e.tilePosition.y=-e.y+this.offset);for(let t=this.ripples.length-1;t>=0;t--){let n=this.ripples[t];if(n.age+=e,n.age>=this.rippleDuration)n.sprite.destroy(),this.ripples.splice(t,1);else{let e=n.age/this.rippleDuration;n.sprite.scale.set(e),n.sprite.alpha=1-e}}}};function lP(e,t,n,r,i,a){let o=t*r;for(let s=0;s<n;s++)for(let n=0;n<t;n++){let t=i(n,s);for(let i=0;i<r;i++)for(let c=0;c<r;c++){let l=a[typeof t==`number`?t:t[i*r+c]??0]??[0,0,0,0];e.set(l,((s*r+i)*o+n*r+c)*4)}}}var uP=class extends xl{constructor(e){let t=e.resolution??2,n=document.createElement(`canvas`);n.width=e.width*t,n.height=e.height*t;let r=n.getContext(`2d`);if(!r)throw Error(`FogLayer needs a 2D canvas context`);super(J.from(n)),this.context=r,this.image=r.createImageData(n.width,n.height),this.columns=e.width,this.rows=e.height,this.cellResolution=t,this.palette=e.palette,this.texture.source.scaleMode=`linear`,this.scale.set((e.tileSize??16)/t),this.eventMode=`none`}setPalette(e){this.palette=e}refresh(e){lP(this.image.data,this.columns,this.rows,this.cellResolution,e,this.palette),this.context.putImageData(this.image,0,0),this.texture.source.update()}destroy(){super.destroy({texture:!0,textureSource:!0})}},dP=`halo`,fP=class extends AM{constructor(e){super(),this.offsetX=e.offsetX??0,this.offsetY=e.offsetY??0,this.blendMode=e.blendMode??`add`,this.add(dP,e.frames,e.animation),this.play(dP)}follow(e,t){return this.position.set(e+this.offsetX,t+this.offsetY),this}};_e();function pP(e){return typeof e==`number`?e:O(e[0],e[1])}function mP(e){if(typeof e==`number`)return e;let t=O(),n=n=>{let r=e[0]>>n&255,i=e[1]>>n&255;return Math.round(r+(i-r)*t)<<n};return n(16)|n(8)|n(0)}function hP(e){return typeof e==`function`?e:t=>e[0]+(e[1]-e[0])*t}var gP=class extends Y{constructor(e={}){super(),this.pool=[],this.sprites=[],this.emitting=!1,this.followTarget=null,this.followOffsetX=0,this.followOffsetY=0,this.followEnabled=null,this.followVisible=null,this.poolCursor=0,this.debt=0;let t=Math.max(1,Math.floor(e.max??200));this.rate=e.rate??0,this.life=e.life??[.4,.9],this.speed=e.speed??[20,60],this.angleRange=e.angle??[0,Math.PI*2],this.gravityX=e.gravity?.x??0,this.gravityY=e.gravity?.y??0,this.scaleOf=hP(e.scale??[1,1]),this.alphaOf=hP(e.alpha??[1,0]),this.flicker=Math.min(1,Math.max(0,e.flicker??0)),this.spin=e.spin??0,this.tintRange=e.tint??16777215,this.frames=e.frames,this.spawnArea=e.spawn??null;for(let n=0;n<t;n++){this.pool.push({x:0,y:0,vx:0,vy:0,age:0,life:0,rotation:0,spin:0,scale:1,alpha:1,tint:16777215,frame:0,active:!1});let t=this.frames?.[0]??e.texture;if(t){let n=new xl(t);n.anchor.set(.5),n.visible=!1,typeof e.tint==`number`&&(n.tint=e.tint),this.sprites.push(n),this.addChild(n)}}}start(){this.emitting=!0}stop(){this.emitting=!1,this.debt=0}attach(e,t={}){this.followTarget=e,this.followOffsetX=t.offsetX??0,this.followOffsetY=t.offsetY??0,this.followEnabled=t.enabled??null,this.followVisible=t.visible??null,this.syncFollow()}detach(){this.followTarget=null,this.followEnabled=null,this.followVisible!==null&&(this.visible=!0),this.followVisible=null,this.followOffsetX=0,this.followOffsetY=0}get attachedTo(){return this.followTarget}syncFollow(){let e=this.followTarget;if(!e)return;if(typeof e!=`function`&&e.destroyed){this.detach();return}let t=typeof e==`function`?e():e;this.x=t.x+this.followOffsetX,this.y=t.y+this.followOffsetY,this.followVisible!==null&&(this.visible=this.followVisible())}followEmissionAllowed(){return this.followEnabled?.()??!0}get isEmitting(){return this.emitting}get activeCount(){let e=0;for(let t of this.pool)t.active&&e++;return e}get particles(){return this.pool}burst(e){this.syncFollow();let t=0;for(let n=0;n<e&&this.spawn();n++)t++;return t}spawn(){let e=null;for(let t=0;t<this.pool.length;t++){let t=this.pool[this.poolCursor];if(this.poolCursor=(this.poolCursor+1)%this.pool.length,!t.active){e=t;break}}if(!e)return!1;let t=pP(this.angleRange),n=pP(this.speed),r=+!yr(),i=this.spawnOffset();return e.x=this.x+i.x,e.y=this.y+i.y,e.vx=Math.cos(t)*n*r,e.vy=Math.sin(t)*n*r,e.age=0,e.life=Math.max(1e-6,pP(this.life)),e.rotation=0,e.spin=pP(this.spin)*r,e.scale=this.scaleOf(0),e.alpha=this.alphaOf(0),e.tint=mP(this.tintRange),e.frame=0,e.active=!0,!0}spawnOffset(){let e=this.spawnArea;if(!e)return{x:0,y:0};let t=e.height??e.width;if(e.shape===`rect`)return{x:(O()-.5)*e.width,y:(O()-.5)*t};let n=Math.sqrt(O()),r=O()*Math.PI*2;return{x:Math.cos(r)*n*(e.width/2),y:Math.sin(r)*n*(t/2)}}update(e){if(this.syncFollow(),this.emitting&&this.rate>0&&this.followEmissionAllowed()){for(this.debt+=this.rate*e;this.debt>=1;)if(--this.debt,!this.spawn()){this.debt=0;break}}let t=yr();for(let n of this.pool){if(!n.active)continue;if(n.age+=e,n.age>=n.life){n.active=!1;continue}t?(n.vx=0,n.vy=0,n.spin=0):(n.vx+=this.gravityX*e,n.vy+=this.gravityY*e),n.x+=n.vx*e,n.y+=n.vy*e,n.rotation+=n.spin*e;let r=n.age/n.life;n.scale=this.scaleOf(r),n.alpha=this.alphaOf(r),this.flicker>0&&!t&&(n.scale*=1-this.flicker*O()),this.frames&&(n.frame=Math.min(this.frames.length-1,Math.floor(r*this.frames.length)))}this.draw()}draw(){if(this.sprites.length===0)return;let e=typeof this.tintRange!=`number`;for(let t=0;t<this.pool.length;t++){let n=this.pool[t],r=this.sprites[t];r.visible=n.active,n.active&&(r.x=n.x-this.x,r.y=n.y-this.y,r.rotation=n.rotation,r.alpha=n.alpha,r.scale.set(n.scale),e&&(r.tint=n.tint),this.frames&&(r.texture=this.frames[n.frame]??r.texture))}}clear(){for(let e of this.pool)e.active=!1;this.debt=0,this.draw()}},_P=class extends Y{constructor(e={}){super(),this.overlay=new bE,this.phase=`idle`,this.elapsed=0,this.duration=0,this.fromAlpha=0,this.toAlpha=0,this.queue=[],this.defaultColor=e.color??0,this.viewWidth=e.width??0,this.viewHeight=e.height??0,this.overlay.alpha=0,this.overlay.tint=this.defaultColor,this.addChild(this.overlay),this.redraw()}setViewport(e,t){this.viewWidth=e,this.viewHeight=t,this.redraw()}redraw(){this.overlay.clear(),this.viewWidth>0&&this.viewHeight>0&&this.overlay.rect(0,0,this.viewWidth,this.viewHeight).fill({color:16777215})}get isBusy(){return this.phase!==`idle`}get washAlpha(){return this.overlay.alpha}fadeOut(e,t){this.begin(`fadeOut`,e,this.overlay.alpha,1,t)}fadeIn(e,t){this.begin(`fadeIn`,e,this.overlay.alpha,0,t)}flash(e,t,n=1){this.begin(`flash`,e,0,n,t)}sequence(e){if(this.queue=e.slice(1),e.length===0){this.phase=`idle`;return}this.beginStep(e[0])}setTint(e,t){this.queue=[],this.phase=`idle`,this.elapsed=0,this.overlay.tint=e,this.overlay.alpha=Math.max(0,Math.min(1,t))}clear(){this.queue=[],this.phase=`idle`,this.elapsed=0,this.overlay.alpha=0,this.overlay.tint=this.defaultColor}beginStep(e){switch(e.kind){case`fadeOut`:return this.begin(`fadeOut`,e.duration,this.overlay.alpha,1,e.color);case`fadeIn`:return this.begin(`fadeIn`,e.duration,this.overlay.alpha,0,e.color);case`flash`:return this.begin(`flash`,e.duration,0,e.peak??1,e.color);case`hold`:return this.begin(`hold`,e.duration,this.overlay.alpha,this.overlay.alpha,e.color??this.overlay.tint)}}advance(){let e=this.queue.shift();return e?this.beginStep(e):(this.phase=`idle`,!0)}begin(e,t,n,r,i){return yr()&&(t=0),this.overlay.tint=i??this.defaultColor,this.fromAlpha=n,this.toAlpha=r,this.elapsed=0,this.duration=t,t>0?(this.phase=e,this.overlay.alpha=e===`flash`?0:n,!1):(this.overlay.alpha=e===`flash`?0:r,this.advance())}update(e){if(this.phase===`idle`)return!1;if(yr())return this.overlay.alpha=this.phase===`flash`?0:this.toAlpha,this.advance();this.elapsed+=e;let t=Math.min(1,this.elapsed/this.duration);if(this.phase===`flash`){let e=t<.5?wr.easeOutQuad(t*2):1-wr.easeInQuad((t-.5)*2);this.overlay.alpha=this.toAlpha*e}else{let e=wr.easeInOutQuad(t);this.overlay.alpha=this.fromAlpha+(this.toAlpha-this.fromAlpha)*e}return t>=1&&(this.overlay.alpha=this.phase===`flash`?0:this.toAlpha,this.advance())}},vP=class{constructor(e,t){this.idleOrMove=`idle`,this.inAction=!1,this.sprite=e,this.animationName=t.animationName,this.variant=t.variant??``,this.sprite.onFinish=()=>this.onSpriteFinish(),this.apply(this.idleOrMove)}get state(){return this.inAction?`action`:this.idleOrMove}get variantName(){return this.variant}setMoving(e,t){t!==void 0&&(this.variant=t),this.idleOrMove=e?`move`:`idle`,this.inAction||this.apply(this.idleOrMove)}playAction(e,t=!1){(!this.inAction||t)&&(e!==void 0&&(this.variant=e),this.inAction=!0,this.apply(`action`))}onSpriteFinish(){this.inAction&&(this.inAction=!1,this.apply(this.idleOrMove))}apply(e){let t=this.animationName(e,this.variant);this.sprite.has(t)&&this.sprite.play(t,e===`action`)}},yP=class{constructor(e,t){this.active=new Set,this.elapsed=0,this.flashColor=0,this.flashStrength=0,this.flashDuration=0,this.flashRemaining=0,this.target=e,this.styles=t.styles}set(e,t){t?this.active.add(e):this.active.delete(e)}has(e){return this.active.has(e)}flash(e,t,n){this.flashColor=e,this.flashStrength=t,this.flashDuration=Math.max(n,1e-6),this.flashRemaining=this.flashDuration}update(e){this.elapsed+=e,this.flashRemaining>0&&(this.flashRemaining=Math.max(0,this.flashRemaining-e));let t=0,n=0,r=0;for(let e of this.active){let i=this.styles[e];if(!i)continue;let a=i.strength??.5,o=i.pulseRate?a*(.5+.5*Math.sin(this.elapsed*i.pulseRate*Math.PI*2)):a;t+=(i.color>>16&255)/255*o,n+=(i.color>>8&255)/255*o,r+=(i.color&255)/255*o}if(this.flashRemaining>0){let e=this.flashRemaining/this.flashDuration,i=this.flashStrength*e;t+=(this.flashColor>>16&255)/255*i,n+=(this.flashColor>>8&255)/255*i,r+=(this.flashColor&255)/255*i}this.target.colorAdd=qj(Math.min(1,t),Math.min(1,n),Math.min(1,r))}},bP=CP(),xP=new Map(bP.map((e,t)=>[SP(e),t]));function SP(e){let t=e.ne&&e.n&&e.e,n=e.se&&e.s&&e.e,r=e.sw&&e.s&&e.w,i=e.nw&&e.n&&e.w;return+!!e.n|(e.e?2:0)|(e.s?4:0)|(e.w?8:0)|(t?16:0)|(n?32:0)|(r?64:0)|(i?128:0)}function CP(){let e=new Set,t=[];for(let n=0;n<256;n++){let r={n:!!(n&1),e:!!(n&2),s:!!(n&4),w:!!(n&8),ne:!!(n&16),se:!!(n&32),sw:!!(n&64),nw:!!(n&128)},i=SP(r);e.has(i)||(e.add(i),t.push({mask:i,shape:{n:r.n,e:r.e,s:r.s,w:r.w,ne:r.ne&&r.n&&r.e,se:r.se&&r.s&&r.e,sw:r.sw&&r.s&&r.w,nw:r.nw&&r.n&&r.w}}))}return t.sort((e,t)=>e.mask-t.mask),t.map(e=>e.shape)}function wP(e){return xP.get(SP(e))}function TP(e,t,n,r){if(r.length!==bP.length)throw Error(`autotileFrames needs exactly ${bP.length} frames, got ${r.length}`);let i=new Int32Array(e*t);for(let a=0;a<t;a++)for(let t=0;t<e;t++){let o=a*e+t;if(!n(t,a)){i[o]=-1;continue}i[o]=r[wP({n:n(t,a-1),e:n(t+1,a),s:n(t,a+1),w:n(t-1,a),ne:n(t+1,a-1),se:n(t+1,a+1),sw:n(t-1,a+1),nw:n(t-1,a-1)})]}return i}_e();function EP(e,t,n,r){let i=n*4/r,a=e,o=t;for(let e=0;e<i;e+=1)[a,o]=[-o,a];return{dx:a||0,dy:o||0}}function DP(e,t,n,r){let i=n*6/r,a=e,o=t;for(let e=0;e<i;e+=1){let e=-a-o;[a,o]=[-o,-e]}return{dx:a||0,dy:o||0}}function OP(e,t){let n=t??new Set;return!(e.hasAll&&!e.hasAll.every(e=>n.has(e))||e.hasAny&&!e.hasAny.some(e=>n.has(e))||e.hasNone&&e.hasNone.some(e=>n.has(e)))}function kP(e,t,n,r,i=EP,a=0){let o=e.rotations??0;return e.conditions.every(e=>{let s=o>0?i(e.dx,e.dy,a,o):e;return OP(e,r(t+s.dx,n+s.dy))})}function AP(e,t,n,r,i={}){let a=i.rotate??EP,o=i.random??new j,s=[];for(let i=0;i<t;i+=1)for(let t=0;t<e;t+=1){let e=-1,c=[];for(let o of n){let n=o.rotations??0,s=n>0?n:1;for(let n=0;n<s;n+=1){if(!kP(o,t,i,r,a,n))continue;let s=o.conditions.length;s>e?(e=s,c=[{rule:o,rotationIndex:n}]):s===e&&c.push({rule:o,rotationIndex:n})}}if(c.length===0)continue;let l=c.length===1?c[0]:c[jP(c.map(e=>e.rule.probability??1),o)],u=l.rule.rotations??0;for(let e of l.rule.images){let n=u>0?a(e.dx??0,e.dy??0,l.rotationIndex,u):{dx:e.dx??0,dy:e.dy??0};s.push({x:t,y:i,ruleId:l.rule.id,image:e.image,dx:n.dx,dy:n.dy,layer:e.layer??0})}}return s}function jP(e,t){let n=e.reduce((e,t)=>e+Math.max(0,t),0);if(n<=0)return 0;let r=t.float()*n;for(let t=0;t<e.length;t+=1)if(r-=Math.max(0,e[t]),r<0)return t;return e.length-1}var MP=class extends Y{};function NP(e,t){let n={};for(let r of t){let t=new MP;t.label=r,e.addChild(t),n[r]=t}return n}var PP=class extends bE{},FP=class extends wA{},IP=class extends xl{},LP=class extends iA{},RP=yC,zP=class extends MP{constructor(e){super(),this.placements=e.placements,this.project=e.project,this.resolveImage=e.resolveImage??(e=>GM(e,J.EMPTY)),this.rebuild()}setPlacements(e){this.placements=e,this.rebuild()}rebuild(){for(let e of this.removeChildren())e.destroy();for(let e of[...this.placements].sort((e,t)=>e.layer-t.layer)){let t=this.project(e.x,e.y,e.dx,e.dy),n=new IP(this.resolveImage(e.image));n.x=t.x,n.y=t.y,this.addChild(n)}}},BP=[{workload:`sprites`,preferred:`PixiJS WebGL/WebGPU batcher`,fallback:`PixiJS WebGL`,reason:`high-volume textured 2D batches`},{workload:`ui`,preferred:`PixiJS display tree`,fallback:`PixiJS display tree`,reason:`themeable 2D layout and text`},{workload:`custom-shaders`,preferred:`backend-specific GLSL/WGSL only when profiled`,fallback:`PixiJS filters`,reason:`avoid maintaining paired shader sources without a measured gain`},{workload:`particles`,preferred:`PixiJS for 2D, Babylon.js for 3D`,fallback:`instanced sprites/meshes`,reason:`match simulation and depth to the scene`},{workload:`instanced-terrain`,preferred:`Babylon.js thin instances`,fallback:`PixiJS TileMap for 2D`,reason:`depth-tested repeated 3D geometry`},{workload:`voxels`,preferred:`Babylon.js thin instances`,fallback:`batched meshes`,reason:`color-grouped 3D voxels`},{workload:`animated-models`,preferred:`Babylon.js glTF animation groups`,fallback:`billboard sprites`,reason:`standard 3D interchange and animation support`},{workload:`large-3d-worlds`,preferred:`Babylon.js with streaming/culling`,fallback:`partitioned scenes`,reason:`scene graph, depth, and instancing`}];function VP(e={}){let t=e.createCanvas?.()??(typeof document>`u`?null:document.createElement(`canvas`)),n=!!t?.getContext(`webgl2`);return{webgl1:n||!!(t?.getContext(`webgl`)??t?.getContext(`experimental-webgl`)),webgl2:n,webgpu:e.webgpu??!!globalThis.navigator?.gpu,wgsl:e.wgsl??!1}}async function HP(){let e=globalThis.navigator?.gpu;if(!e)return{webgpu:!1,wgsl:!1};try{let t=await(await e.requestAdapter())?.requestDevice();return t?{webgpu:!0,wgsl:(await t.createShaderModule({code:`@compute @workgroup_size(1) fn main() {}`}).getCompilationInfo()).messages.length===0}:{webgpu:!1,wgsl:!1}}catch{return{webgpu:!1,wgsl:!1}}}var UP=536870911,WP={orthogonal:`square`,isometric:`isometric`,staggered:`staggered`};function GP(e,t,n){if(e.frameWidth!==t.tilewidth||e.frameHeight!==t.tileheight)throw Error(`the tileset at firstgid ${n} is cut to ${e.frameWidth}x${e.frameHeight}, but the map is ${t.tilewidth}x${t.tileheight}`)}function KP(e,t,n){let r=-1;for(let n=0;n<t.length&&t[n]<=e;n++)r=n;if(r===-1)throw Error(`layer "${n}" uses gid ${e}, below every tileset's firstgid (${t.join(`, `)})`);return r}function qP(e,t){let n=e.orientation??`orthogonal`,r=WP[n];if(!r)throw Error(`loadTiledMap does not read "${n}" maps yet`);if(r===`staggered`&&(e.staggeraxis??`y`)!==`y`)throw Error(`loadTiledMap only reads Y-axis staggered maps right now, this one is staggered on "${e.staggeraxis}"`);if(r===`staggered`&&(e.staggerindex??`odd`)!==`odd`)throw Error(`loadTiledMap only reads odd-index staggered maps right now, this one staggers "${e.staggerindex}"`);if(e.tilesets.length===0)throw Error(`loadTiledMap needs at least one tileset, this map has none`);let i=[...e.tilesets].sort((e,t)=>e.firstgid-t.firstgid),a,o;if(t instanceof iN){if(e.tilesets.length!==1)throw Error(`loadTiledMap was given one sheet but this map has ${e.tilesets.length} tilesets - pass one sheet per tileset`);GP(t,e,i[0].firstgid),a=[t],o=[i[0].firstgid]}else{if(t.length!==e.tilesets.length)throw Error(`loadTiledMap was given ${t.length} sheets but this map has ${e.tilesets.length} tilesets - pass one sheet per tileset`);a=i.map(n=>{let r=t.find(e=>e.firstgid===n.firstgid);if(!r)throw Error(`loadTiledMap was given no sheet for the tileset at firstgid ${n.firstgid}`);return GP(r.sheet,e,n.firstgid),r.sheet}),o=i.map(e=>e.firstgid)}let s=new $N({width:e.width,height:e.height,sheet:a,shape:r}),c=[];for(let t of e.layers)if(t.type===`tilelayer`){if(t.encoding&&t.encoding!==`csv`)throw Error(`layer "${t.name}" uses "${t.encoding}" encoding - export tile layers as CSV/plain, not compressed`);let e=(t.data??[]).map(e=>{let n=e&UP;if(n===0)return-1;let r=KP(n,o,t.name);return o.length===1?n-o[0]:XN(r,n-o[r])});s.addLayer(t.name,e)}else if(t.type===`objectgroup`)for(let n of t.objects??[])c.push({...n,tileX:Math.floor(n.x/e.tilewidth),tileY:Math.floor(n.y/e.tileheight)});return{map:s,objects:c}}var JP={panelBorder:4,padding:8,spacing:2,direction:`ltr`,font:{family:`ui-monospace, Consolas, "DejaVu Sans Mono", monospace`,size:12,lineHeight:1.4},color:{text:15263984,textDim:9079446,textHighlight:16770688,panelFill:1842214,panelBorder:4868702,selection:3820154,overlay:0},overlayAlpha:.5},YP={panelBorder:6,padding:10,spacing:4,direction:`ltr`,font:{family:JP.font.family,size:14,lineHeight:1.5},color:{text:16777215,textDim:13421772,textHighlight:16776960,panelFill:0,panelBorder:16777215,selection:16776960,overlay:0},overlayAlpha:.85},XP=JP;function Q(){return XP}var $=new p;function ZP(e){XP={...JP,...e,font:{...JP.font,...e.font},color:{...JP.color,...e.color}},$.dispatch(XP)}function QP(e){return typeof e==`string`?{text:e}:e}function $P(e,t){return e.align??(t.direction===`rtl`?`right`:`left`)}function eF(e,t=40){let n=Math.max(0,e);return{total:n,speed:Math.max(0,t),revealed:t===0?n:0}}function tF(e,t){return e.revealed=Math.min(e.total,Math.max(0,e.revealed+e.speed*t)),rF(e)}function nF(e){e.revealed=e.total}function rF(e){return e.revealed>=e.total}var iF=class extends wA{constructor(e={}){let t=QP(e),n=Q();super({text:t.text??``,resolution:t.resolution,roundPixels:t.roundPixels,style:new tO({fontFamily:n.font.family,stroke:t.stroke,fontSize:t.size??n.font.size,fontWeight:t.bold?`bold`:`normal`,fill:t.color??n.color.text,lineHeight:(t.size??n.font.size)*n.font.lineHeight,align:$P(t,n),wordWrap:t.wrapWidth!==void 0,wordWrapWidth:t.wrapWidth??0,breakWords:!0})}),this.themeListener=e=>this.restyle(e),this.revealSource=null,this.reveal=null,this.opts=t,$.add(this.themeListener)}setColor(e){this.destroyed||(this.style.fill=e)}setText(e){this.destroyed||(this.revealSource=null,this.reveal=null,this.text!==e&&(this.text=e))}showProgressive(e,t){this.destroyed||(this.revealSource=e,this.reveal=eF(e.length,t),this.renderRevealed())}updateReveal(e){if(this.destroyed||!this.reveal)return!0;let t=tF(this.reveal,e);return this.renderRevealed(),t}completeReveal(){!this.destroyed&&this.reveal&&(nF(this.reveal),this.renderRevealed())}renderRevealed(){if(!this.reveal||this.revealSource===null)return;let e=this.revealSource.slice(0,Math.floor(this.reveal.revealed));this.text!==e&&(this.text=e)}restyle(e){this.destroyed||(this.style.fontFamily=e.font.family,this.opts.color===void 0&&(this.style.fill=e.color.text),this.opts.size===void 0&&(this.style.fontSize=e.font.size,this.style.lineHeight=e.font.size*e.font.lineHeight),this.opts.align===void 0&&(this.style.align=$P(this.opts,e)))}destroy(e){$.remove(this.themeListener),super.destroy(e)}},aF={positive:5627255,negative:16733525,warning:16757575};function oF(e,t){return t>0?e.slice(Math.max(0,e.length-Math.floor(t))):[]}function sF(e,t){let n=0;for(let t of e)n+=t;let r=0;for(;n>t&&r<e.length-1;)n-=e[r++];return r}var cF=class extends Y{constructor(e){super(),this.blocks=[],this.options=e,this.maxLines=e.maxLines??3}get entryCount(){return this.blocks.length}get contentHeight(){return this.blocks.reduce((e,t)=>e+t.label.height,0)}lastEntries(e){return oF(this.blocks.map(e=>({text:e.text,level:e.level})),e)}add(e,t=`info`){let n=new iF({text:e,size:this.options.size,color:this.colorOf(t),wrapWidth:this.options.wrapWidth,resolution:this.options.resolution});this.addChild(n),this.blocks.push({label:n,level:t,text:e}),this.trim(),this.layout()}setMaxLines(e){this.maxLines=Math.max(1,Math.floor(e)),this.trim(),this.layout()}setWrapWidth(e){this.options.wrapWidth=e;for(let t of this.blocks)t.label.style.wordWrapWidth=e;this.trim(),this.layout()}clear(){for(let e of this.blocks.splice(0))e.label.destroy()}colorOf(e){let t=this.options.colors?.[e];return t===void 0?e===`info`?Q().color.text:e===`highlight`?Q().color.textHighlight:aF[e]:t}linesOf(e){let t=Number(e.style.lineHeight)||Number(e.style.fontSize)||1;return Math.max(1,Math.round(e.height/t))}trim(){let e=sF(this.blocks.map(e=>this.linesOf(e.label)),this.maxLines);for(let t of this.blocks.splice(0,e))t.label.destroy()}layout(){let e=0;for(let t of this.blocks)t.label.position.set(0,e),e+=t.label.height}};function lF(e,t,n){let r=Math.max(1,Math.floor(e));for(;r>1&&t*r>n;)r--;return r}function uF(e){let t=1;for(let n=e;n;n=n.parent)t*=Math.abs(n.scale.x);return t}function dF(e,t){let n=(e,r)=>{if(e instanceof wA){let n=t*Math.max(1,Math.round(r));e.resolution!==n&&(e.resolution=n)}for(let t of e.children)n(t,r*Math.abs(t.scale.x))};n(e,uF(e))}var fF=``,pF=``,mF=``;function hF(e){let t=``;for(let n=0;n<e.length;n++)if(e[n]===`\\`&&n+1<e.length&&(e[n+1]===`*`||e[n+1]===`_`||e[n+1]===`\\`)){let r=e[n+1];t+=r===`*`?fF:r===`_`?pF:mF,n++}else t+=e[n];return t}function gF(e){return e.replaceAll(fF,`*`).replaceAll(pF,`_`).replaceAll(mF,`\\`)}function _F(e){return e!==void 0&&/[\p{L}\p{N}_]/u.test(e)}function vF(e,t,n){let r=[],i=0;for(;i<e.length;){if(e[i]!==t){i++;continue}let a=0;for(;e[i+a]===t;)a++;if(!(t===`_`&&_F(e[i-1])&&_F(e[i+a]))){if(n)for(let e=0;e<Math.floor(a/2);e++)r.push(i+e*2);else a%2==1&&r.push(i+a-1)}i+=a}return r}function yF(e,t,n,r,i,a){let o=vF(e,t,n),s=n?2:1;for(let e=0;e+1<o.length;e+=2){let t=o[e],n=o[e+1];i.push({from:t+s,to:n,style:r}),a.push({from:t,to:t+s},{from:n,to:n+s})}}function bF(e){let t=[];for(let n of e){if(!n.text)continue;let e=t[t.length-1];e&&e.bold===n.bold&&e.italic===n.italic?e.text+=n.text:t.push({...n})}return t}function xF(e){let t=hF(e),n=[],r=[];yF(t,`*`,!0,`bold`,n,r),yF(t,`_`,!0,`bold`,n,r),yF(t,`*`,!1,`italic`,n,r),yF(t,`_`,!1,`italic`,n,r);let i=new Set([0,t.length]);for(let e of n)i.add(e.from),i.add(e.to);for(let e of r)i.add(e.from),i.add(e.to);let a=[...i].sort((e,t)=>e-t),o=[];for(let e=0;e+1<a.length;e++){let i=a[e],s=a[e+1];i>=s||r.some(e=>e.from<=i&&s<=e.to)||o.push({text:t.slice(i,s),bold:n.some(e=>e.style===`bold`&&e.from<=i&&s<=e.to),italic:n.some(e=>e.style===`italic`&&e.from<=i&&s<=e.to)})}return bF(o).map(e=>({...e,text:gF(e.text)}))}function SF(e){return xF(e).map(e=>e.text).join(``)}function CF(e,t){let n=[],r=Math.max(0,Math.floor(t));for(let t of e){if(r<=0)break;let e=Math.min(t.text.length,r);n.push({...t,text:t.text.slice(0,e)}),r-=e}return n}var wF=class extends sj{constructor(e={}){let t=QP(e),n=Q(),r=t.tagStyles===void 0?[]:Object.keys(t.tagStyles);super({text:TF(t.text??``,r),resolution:t.resolution,style:new WA({fontFamily:n.font.family,fontSize:t.size??n.font.size,fontWeight:t.bold?`bold`:`normal`,fill:t.color??n.color.text,lineHeight:(t.size??n.font.size)*n.font.lineHeight,align:$P(t,n),wordWrap:t.wrapWidth!==void 0,wordWrapWidth:t.wrapWidth??0,breakWords:!0,tagStyles:t.tagStyles})}),this.themeListener=e=>this.restyle(e),this.revealSpans=null,this.reveal=null,this.opts=t,this.tags=r,$.add(this.themeListener)}setText(e){this.revealSpans=null,this.reveal=null;let t=TF(e,this.tags);this.text!==t&&(this.text=t)}showProgressive(e,t){this.revealSpans=xF(e),this.reveal=eF(SF(e).length,t),this.renderRevealed()}updateReveal(e){if(!this.reveal)return!0;let t=tF(this.reveal,e);return this.renderRevealed(),t}completeReveal(){this.reveal&&(nF(this.reveal),this.renderRevealed())}renderRevealed(){if(!this.reveal||!this.revealSpans)return;let e=EF(CF(this.revealSpans,this.reveal.revealed),this.tags);this.text!==e&&(this.text=e)}restyle(e){this.style.fontFamily=e.font.family,this.opts.color===void 0&&(this.style.fill=e.color.text),this.opts.size===void 0&&(this.style.fontSize=e.font.size,this.style.lineHeight=e.font.size*e.font.lineHeight),this.opts.align===void 0&&(this.style.align=$P(this.opts,e))}destroy(e){$.remove(this.themeListener),super.destroy(e)}};function TF(e,t){return EF(xF(e),t)}function EF(e,t){return e.map(e=>{let n=DF(e.text,t);return e.italic&&(n=`<i>${n}</i>`),e.bold&&(n=`<b>${n}</b>`),n}).join(``)}function DF(e,t){let n=e.replaceAll(`&`,`&amp;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`);for(let e of t)n=n.replaceAll(`&lt;${e}&gt;`,`<${e}>`).replaceAll(`&lt;/${e}&gt;`,`</${e}>`);return n}var OF=new Set([`b`,`i`,`span`,`br`,`img`]);function kF(e,t={}){let n=t.variables??{},r=t.tags,i=[],a=[],o={bold:!1,italic:!1},s=``,c=()=>{if(!s)return;let e={text:s,bold:o.bold,italic:o.italic};o.color!==void 0&&(e.color=o.color),o.size!==void 0&&(e.size=o.size),o.tag!==void 0&&(e.tag=o.tag),i.push(e),s=``};for(let t=0;t<e.length;t++){let l=e[t];if(l===`&`){let n=VF(e,t);if(n){s+=n.text,t=n.end;continue}}if(l===`$`){let r=HF(e,t),i=r?n[r.name]:void 0;if(r&&i!==void 0){s+=i,t=r.end;continue}}if(l===`<`){let n=zF(e,t);if(n&&(OF.has(n.name)||r?.has(n.name))){if(n.name===`img`){let r=BF(e,n);if(r){c(),i.push({text:``,bold:!1,italic:!1,image:r.src}),t=r.end;continue}}else if(n.name===`br`){s+=`
1370
- `,t=n.end;continue}else if(n.closing){let e=a[a.length-1];if(e?.tag===n.name){c(),o=e.style,a.pop(),t=n.end;continue}}else{c(),a.push({tag:n.name,style:o}),o=LF(o,n.name,n.body),t=n.end;continue}}}s+=l}return c(),i}function AF(e,t={}){return kF(e,t).map(e=>e.image??e.text).join(``)}function jF(e){return e.map(e=>{if(e.image!==void 0)return``;let t=IF(e.text);e.italic&&(t=`<i>${t}</i>`),e.bold&&(t=`<b>${t}</b>`);let n=[e.color===void 0?void 0:`color:${e.color}`,e.size===void 0?void 0:`font-size:${e.size}px`].filter(e=>e!==void 0);return n.length>0&&(t=`<span style="${n.join(`;`)}">${t}</span>`),e.tag!==void 0&&(t=`<${e.tag}>${t}</${e.tag}>`),t}).join(``)}function MF(e,t={}){let n=t.describeImage??(()=>`[image]`);return e.map(e=>e.image===void 0?e.text:n(e.image)).join(``)}function NF(e,t,n){let r=[];for(let t of e){if(t.image!==void 0){r.push({...t});continue}t.text.split(`
1371
- `).forEach((e,n)=>{n>0&&r.push({text:``,bold:t.bold,italic:t.italic,hardBreak:!0});for(let n of e.match(/\S+|\s+/g)??[])r.push({text:n,bold:t.bold,italic:t.italic,color:t.color,size:t.size,tag:t.tag})})}let i=[],a=[],o=0,s=()=>{for(;a.length>0&&a[a.length-1].text.trim()===``&&!a[a.length-1].image;)o-=t(a[a.length-1]),a.pop();i.push({spans:PF(a),width:Math.max(0,o)}),a=[],o=0};for(let e of r){if(e.hardBreak){s();continue}let r=t(e),i=e.image===void 0&&e.text.trim()===``;o>0&&!i&&o+r>n&&s(),a.push(e),o+=r}return(a.length>0||i.length===0)&&s(),i}function PF(e){let t=[];for(let n of e){let e=t[t.length-1];e&&n.image===void 0&&e.image===void 0&&e.bold===n.bold&&e.italic===n.italic&&e.color===n.color&&e.size===n.size&&e.tag===n.tag?e.text+=n.text:t.push({...n})}return t}function FF(e,t){let n=t.direction??`ltr`,r=t.align??(n===`rtl`?`right`:`left`),i=[];for(let a=0;a<e.length;a++){let o=e[a],s=a*t.lineHeight,c=o.spans.map(e=>t.measure(e)),l=c.reduce((e,t)=>e+t,0),u=r===`left`?0:r===`right`?t.maxWidth-l:(t.maxWidth-l)/2,d=n===`rtl`?u+l:u;for(let e=0;e<o.spans.length;e++){let t=c[e],r=n===`rtl`?d-t:d;d=n===`rtl`?d-t:d+t,i.push({span:o.spans[e],x:r,y:s,width:t})}}return i}function IF(e){return e.replaceAll(`&`,`&amp;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`).replaceAll(`"`,`&quot;`).replaceAll(`'`,`&#39;`)}function LF(e,t,n){if(t===`b`)return{...e,bold:!0};if(t===`i`)return{...e,italic:!0};if(t!==`span`)return{...e,tag:t};let r=RF(n,`color`),i=Number(RF(n,`size`)??``),a={...e};return r&&(a.color=r),Number.isFinite(i)&&i>0&&(a.size=i),a}function RF(e,t){let n=RegExp(`(?:^|\\s)${t}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s"'>]+))`).exec(e);return n?n[1]??n[2]??n[3]:void 0}function zF(e,t){let n=/^<(\/?)([a-zA-Z]+)([^>]*)>/.exec(e.slice(t));if(!n)return null;let r=n[3].trimEnd();return{name:n[2].toLowerCase(),closing:n[1]===`/`,selfClosing:r.endsWith(`/`)&&n[1]===``,body:r.replace(/\/$/,``).trim(),end:t+n[0].length-1}}function BF(e,t){if(t.selfClosing){let e=RF(t.body,`src`);return e?{src:e,end:t.end}:null}let n=e.indexOf(`</img>`,t.end+1);if(n<0)return null;let r=e.slice(t.end+1,n).trim();return r?{src:r,end:n+6-1}:null}function VF(e,t){let n={lt:`<`,gt:`>`,amp:`&`,quot:`"`,apos:`'`},r=/^&(lt|gt|amp|quot|apos);/.exec(e.slice(t));if(r)return{text:n[r[1]],end:t+r[0].length-1};let i=/^&#(\d+);/.exec(e.slice(t));return i?{text:String.fromCodePoint(Number(i[1])),end:t+i[0].length-1}:null}function HF(e,t){let n=/^\$([A-Za-z_][A-Za-z0-9_]*)/.exec(e.slice(t));return n?{name:n[1],end:t+n[0].length-1}:null}var UF=class extends Y{constructor(e={}){super(),this.themeListener=e=>this.rebuild(e),this.opts=e,this.rebuild(Q()),$.add(this.themeListener)}setText(e){this.opts.text=e,this.rebuild(Q())}rebuild(e){for(let e of this.removeChildren())e.destroy();let t=this.opts.lineHeight??e.font.size*e.font.lineHeight,n=this.opts.maxWidth??1/0,r=this.opts.maxWidth??0,i=this.opts.direction??e.direction,a=this.opts.resolveImage??(e=>GM(e,J.EMPTY)),o=GF(),s=n=>this.measurePiece(n,e,t,a,o),c=this.opts.tagStyles,l=FF(NF(kF(this.opts.text??``,{variables:this.opts.variables,tags:c===void 0?void 0:new Set(Object.keys(c))}),s,n),{measure:s,maxWidth:r,lineHeight:t,direction:i,align:this.opts.align??(this.opts.maxWidth===void 0?`left`:void 0)});for(let n of l){let r=n.span.image===void 0?this.textFor(n.span,e,t):this.spriteFor(n.span.image,t,a);r.x=n.x,r.y=n.y,this.addChild(r)}}measurePiece(e,t,n,r,i){if(e.image!==void 0)return JF(r(e.image),n).width;let a=this.resolvedFont(e,t);return i?(i.font=`${a.italic?`italic `:``}${a.bold?`bold `:``}${a.size}px ${a.family}`,i.measureText(e.text).width):e.text.length*a.size}tagStyle(e){return e===void 0||this.opts.tagStyles===void 0?void 0:this.opts.tagStyles[e]}resolvedFont(e,t){let n=this.tagStyle(e.tag);return{family:typeof n?.fontFamily==`string`?n.fontFamily:t.font.family,size:typeof n?.fontSize==`number`?n.fontSize:e.size??t.font.size,bold:n?.fontWeight===void 0?e.bold:KF(n.fontWeight),italic:n?.fontStyle===void 0?e.italic:qF(n.fontStyle)}}textFor(e,t,n){let r=this.resolvedFont(e,t),i=this.tagStyle(e.tag);return new FP({text:e.text,resolution:this.opts.resolution,style:{fontFamily:r.family,fontSize:r.size,fontWeight:r.bold?`bold`:`normal`,fontStyle:r.italic?`italic`:`normal`,fill:e.color??t.color.text,lineHeight:n,...i}})}spriteFor(e,t,n){let r=n(e),i=JF(r,t),a=new IP(r);return a.width=i.width,a.height=i.height,a}destroy(e){$.remove(this.themeListener),super.destroy(e)}},WF=null;function GF(){return typeof document>`u`?null:(WF??=document.createElement(`canvas`).getContext(`2d`),WF)}function KF(e){if(e===`bold`||e===`bolder`)return!0;if(e===`normal`||e===`lighter`)return!1;let t=Number(e);return Number.isFinite(t)&&t>=600}function qF(e){return e===`italic`||e===`oblique`}function JF(e,t){return{width:(e.width>0?e.width:t)*(t/(e.height>0?e.height:t)),height:t}}var YF=class extends LA{constructor(e={}){let t=QP(e),n=Q();super({text:t.text??``,style:XF(t,n)}),this.themeListener=e=>this.restyle(e),this.opts=t,$.add(this.themeListener)}setText(e){this.text!==e&&(this.text=e)}restyle(e){this.style=XF(this.opts,e)}destroy(e){$.remove(this.themeListener),super.destroy(e)}};function XF(e,t){return{fontFamily:t.font.family,fontSize:e.size??t.font.size,fontWeight:e.bold?`bold`:`normal`,fill:e.color??t.color.text,align:$P(e,t),wordWrap:e.wrapWidth!==void 0,wordWrapWidth:e.wrapWidth??0,breakWords:!0}}var ZF=class extends Y{constructor(e,t){super();let n=typeof t.border==`number`?{left:t.border,top:t.border,right:t.border,bottom:t.border}:t.border;this.sprite=new xj({texture:e,leftWidth:n.left,topHeight:n.top,rightWidth:n.right,bottomHeight:n.bottom}),this.addChild(this.sprite)}get border(){return{left:this.sprite.leftWidth,top:this.sprite.topHeight,right:this.sprite.rightWidth,bottom:this.sprite.bottomHeight}}resize(e,t){let n=this.border;this.sprite.width=Math.max(e,n.left+n.right),this.sprite.height=Math.max(t,n.top+n.bottom)}},QF=`position:absolute;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0;`,$F=class{constructor(){this.polite=null,this.assertive=null}region(e){if(typeof document>`u`||!document.body)return null;let t=e?this.assertive:this.polite;if(t)return t;let n=document.createElement(`div`);return n.setAttribute(`aria-live`,e?`assertive`:`polite`),n.setAttribute(`aria-atomic`,`true`),n.setAttribute(`role`,`status`),n.setAttribute(`style`,QF),document.body.appendChild(n),e?this.assertive=n:this.polite=n,n}announce(e,t={}){let n=this.region(t.assertive??!1);n&&(n.textContent=``,n.appendChild(document.createTextNode(e)))}clear(){this.polite&&(this.polite.textContent=``),this.assertive&&(this.assertive.textContent=``)}destroy(){this.polite?.remove(),this.assertive?.remove(),this.polite=null,this.assertive=null}},eI=new $F,tI=class extends Y{constructor(e){super(),this.content=new Y,this.onClose=new p,this.titleLabel=null,this.innerWidth=0,this.innerHeight=0,this.currentWidth=0,this.currentHeight=0,this.blocker=null,this.themeListener=()=>this.restyle(),this.isClosed=!1,this.delegate=null,this.onBlockerDown=e=>{e.stopPropagation();let t=e.getLocalPosition(this);this.handleOutsideClick(t.x,t.y)};let t=Q();this.modal=e.modal??!0,this.closable=e.closable??!0,this.dims=e.dims??this.modal,this.anchor=e.anchor??`center`,e.blocker===!0&&(this.blocker=new Y,this.blocker.eventMode=`static`,this.blocker.on(`pointerdown`,this.onBlockerDown),this.addChild(this.blocker)),this.background=t.panel?new ZF(t.panel,{border:t.panelBorder}):new bE,this.addChild(this.background),e.title!==void 0&&(this.titleLabel=new iF({text:e.title,color:t.color.textHighlight,bold:!0}),this.addChild(this.titleLabel),eI.announce(e.title)),this.addChild(this.content),this.resize(e.width,e.height),$.add(this.themeListener)}restyle(){this.titleLabel?.setColor(Q().color.textHighlight),this.resize(this.currentWidth,this.currentHeight)}resize(e,t){this.currentWidth=e,this.currentHeight=t;let n=Q(),r=(this.background instanceof ZF?this.background.border.left:2)+n.padding;this.background instanceof ZF?this.background.resize(e,t):this.background.clear().roundRect(0,0,e,t,4).fill({color:n.color.panelFill}).stroke({color:n.color.panelBorder,width:1});let i=r;this.titleLabel&&(this.titleLabel.x=n.direction===`rtl`?e-r-this.titleLabel.width:r,this.titleLabel.y=r,i=r+this.titleLabel.height+n.padding),this.content.x=r,this.content.y=i,this.innerWidth=Math.max(0,e-r*2),this.innerHeight=Math.max(0,t-i-r)}get contentWidth(){return this.innerWidth}get contentHeight(){return this.innerHeight}setTitle(e){this.titleLabel?.setText(e)}handleAction(e){return this.isClosed?!1:this.delegate?.handleAction(e)?!0:e===`cancel`&&this.closable?(this.close(),!0):!1}get closed(){return this.isClosed}update(e){}close(){this.isClosed||(this.isClosed=!0,this.onClose.dispatch(),this.parent?.removeChild(this),this.destroy({children:!0}))}place(e,t){if(this.isClosed)return;let n=this.getLocalBounds(),r=Q().padding*2;this.x=Math.round((e-n.width)/2),this.y=this.anchor===`bottom`?Math.round(t-n.height-r):this.anchor===`top`?r:Math.round((t-n.height)/2),this.fitBlocker(e,t)}fitBlocker(e,t){this.blocker&&(this.blocker.hitArea=new K(-this.x,-this.y,e,t))}handleOutsideClick(e,t){return this.isClosed||e>=0&&t>=0&&e<this.currentWidth&&t<this.currentHeight||!this.closable?!1:(this.close(),!0)}destroy(e){this.isClosed=!0,$.remove(this.themeListener),super.destroy(e)}},nI=class extends Y{constructor(){super(),this.windows=[],this.overlay=new bE,this.viewportWidth=0,this.viewportHeight=0,this.listener=e=>this.handleAction(e),this.themeListener=()=>this.drawOverlay(),this.overlay.visible=!1,this.addChild(this.overlay),P.add(this.listener),$.add(this.themeListener)}setViewport(e,t){this.viewportWidth=e,this.viewportHeight=t,this.drawOverlay();for(let n of this.windows)n.place(e,t)}get top(){return this.windows[this.windows.length-1]??null}get isEmpty(){return this.windows.length===0}get depth(){return this.windows.length}push(e){if(e.closed)throw Error(`cannot open a window that was already closed`);return this.windows.push(e),this.addChild(e),e.onClose.add(()=>(this.forget(e),!1)),e.place(this.viewportWidth,this.viewportHeight),this.updateOverlay(),e}pop(){this.top?.close()}closeAll(){for(let e of[...this.windows].reverse())e.close()}forget(e){let t=this.windows.indexOf(e);t!==-1&&this.windows.splice(t,1),this.updateOverlay()}updateOverlay(){let e=this.windows.findIndex(e=>e.dims);if(e===-1){this.overlay.visible=!1;return}this.overlay.visible=!0,this.setChildIndex(this.overlay,Math.max(0,this.getChildIndex(this.windows[e])-1))}drawOverlay(){let e=Q();this.overlay.clear().rect(0,0,this.viewportWidth,this.viewportHeight).fill({color:e.color.overlay,alpha:e.overlayAlpha})}handleAction(e){return this.top?.handleAction(e)??!1}get blocksWorld(){return this.windows.some(e=>e.modal)}update(e){this.top?.update(e)}destroy(e){P.remove(this.listener),$.remove(this.themeListener),super.destroy(e)}},rI=class{constructor(e){this.list=[],this.current=0,this.hooks=e}get items(){return this.list}get selectedIndex(){return this.current}get selected(){return this.list[this.current]??null}get length(){return this.list.length}reset(e){this.list=e,this.current=e.findIndex(e=>!e.disabled),this.current===-1&&(this.current=0)}swap(e,t){[this.list[e],this.list[t]]=[this.list[t],this.list[e]]}land(e){this.current=e,this.hooks.onChange();let t=this.list[e];t&&this.hooks.onHighlight(t,e)}select(e){e<0||e>=this.list.length||this.list[e].disabled||this.land(e)}confirm(e){let t=this.selected;return!t||t.disabled?!1:(e?.(t,this.current),!0)}step(e,t){if(this.list.length===0)return!1;let n=this.current;for(let r=0;r<t;r++){let t=e(n,this.list.length);if(n=t,!(t<0||t>=this.list.length)&&!this.list[t].disabled)return this.land(t),!0}return!1}},iI=class extends Y{constructor(e){super(),this.selection=new rI({onChange:()=>this.refresh(),onHighlight:(e,t)=>this.onHighlight?.(e,t)}),this.rows=[],this.rowsLayer=new Y,this.highlight=new bE,this.mask_=new bE,this.scroll=0,this.themeListener=()=>this.restyle(),this.checked=new Set,this.ticks=[];let t=Q();this.viewWidth=e.width,this.viewHeight=e.height,this.explicitRowHeight=e.rowHeight!==void 0,this.rowHeight=e.rowHeight??Math.ceil(t.font.size*t.font.lineHeight)+t.spacing,this.onSelect=e.onSelect??null,this.onHighlight=e.onHighlight??null,this.onToggle=e.onToggle??null,this.multiple=e.multiple??!1,this.addChild(this.highlight),this.addChild(this.rowsLayer),this.addChild(this.mask_),this.rowsLayer.mask=this.mask_,this.drawMask(),this.eventMode=`static`,this.on(`wheel`,e=>this.move(e.deltaY>0?1:-1)),this.setItems(e.items??[]),$.add(this.themeListener)}restyle(){let e=Q();this.explicitRowHeight||(this.rowHeight=Math.ceil(e.font.size*e.font.lineHeight)+e.spacing);let t=e.direction===`rtl`,n=this.selection.items;this.rows.forEach((r,i)=>{r.y=i*this.rowHeight;let a=n[i],o=r.children.find(e=>e instanceof iF);if(o){o.setColor(a.disabled?e.color.textDim:e.color.text);let n=e.spacing+this.checkAdvance()+(a.icon?this.rowHeight:0);o.x=t?this.viewWidth-n-o.width:n,o.y=Math.round((this.rowHeight-o.height)/2)}a.icon&&(a.icon.x=t?this.viewWidth-e.spacing-this.checkAdvance()-this.rowHeight:e.spacing+this.checkAdvance())}),this.updateTicks(),this.refresh()}destroy(e){$.remove(this.themeListener),super.destroy(e)}drawMask(){this.mask_.clear().rect(0,0,this.viewWidth,this.viewHeight).fill({color:16777215})}get visibleRows(){return Math.max(1,Math.floor(this.viewHeight/this.rowHeight))}get selectedIndex(){return this.selection.selectedIndex}get selected(){return this.selection.selected}get length(){return this.selection.length}setItems(e){for(let e of this.rows)e.destroy({children:!0});this.rows=[],this.rowsLayer.removeChildren();let t=Q(),n=t.direction===`rtl`;e.forEach((e,r)=>{let i=new Y;i.y=r*this.rowHeight,i.eventMode=`static`,i.cursor=e.disabled?`default`:`pointer`,i.on(`pointerdown`,()=>this.tapRow(r)),e.icon&&(e.icon.x=n?this.viewWidth-t.spacing-this.checkAdvance()-this.rowHeight:t.spacing+this.checkAdvance(),i.addChild(e.icon));let a=new iF({text:e.text,color:e.disabled?t.color.textDim:t.color.text}),o=t.spacing+this.checkAdvance()+(e.icon?this.rowHeight:0);a.x=n?this.viewWidth-o-a.width:o,a.y=Math.round((this.rowHeight-a.height)/2),i.addChild(a),this.rows.push(i),this.rowsLayer.addChild(i)}),this.selection.reset(e),this.checked.clear(),this.rebuildTicks(),this.scroll=0,this.refresh()}resize(e,t){this.viewWidth=e,this.viewHeight=t,this.drawMask(),this.refresh()}move(e){return this.selection.step((t,n)=>(t+e+n)%n,this.selection.length)}select(e){this.selection.select(e)}confirm(){return this.multiple?this.toggleChecked(this.selection.selectedIndex):this.selection.confirm(this.onSelect)}tapRow(e){let t=this.selection.items;e<0||e>=t.length||t[e].disabled||(this.select(e),this.confirm())}handleAction(e){switch(e){case`up`:return this.move(-1);case`down`:return this.move(1);case`confirm`:return this.confirm();default:return!1}}get checkedIndexes(){return[...this.checked].sort((e,t)=>e-t)}isChecked(e){return this.checked.has(e)}setChecked(e,t){let n=this.selection.items[e];n&&!n.disabled&&this.checked.has(e)!==t&&(t?this.checked.add(e):this.checked.delete(e),this.updateTicks(),this.onToggle?.(n,e,t))}toggleChecked(e){let t=this.selection.items[e];return!t||t.disabled?!1:(this.setChecked(e,!this.checked.has(e)),!0)}clearChecked(){this.checked.size!==0&&(this.checked.clear(),this.updateTicks())}checkAdvance(){return this.multiple?this.checkBox()+Q().spacing:0}checkBox(){return Math.max(12,this.rowHeight-8)}rebuildTicks(){if(this.ticks=[],this.multiple){for(let e of this.rows){let t=new bE;e.addChildAt(t,0),this.ticks.push(t)}this.updateTicks()}}updateTicks(){let e=Q(),t=e.direction===`rtl`,n=this.checkBox(),r=Math.round((this.rowHeight-n)/2);this.ticks.forEach((i,a)=>{let o=this.selection.items[a]?.disabled??!0;if(i.clear().rect(0,0,n,n).fill({color:e.color.panelFill}).stroke({color:o?e.color.textDim:e.color.panelBorder,width:2}),this.checked.has(a)){let t=n*.25;i.moveTo(t,n*.55).lineTo(n*.45,n-t).lineTo(n-t,t).stroke({color:o?e.color.textDim:e.color.textHighlight,width:Math.max(2,n*.12),cap:`round`,join:`round`})}i.x=t?this.viewWidth-e.spacing-n:e.spacing,i.y=r})}refresh(){let e=this.visibleRows,t=this.selection.selectedIndex,n=this.selection.length;t<this.scroll?this.scroll=t:t>=this.scroll+e&&(this.scroll=t-e+1),this.scroll=Math.max(0,Math.min(this.scroll,Math.max(0,n-e))),this.rowsLayer.y=-this.scroll*this.rowHeight;let r=Q();if(n===0){this.highlight.clear();return}this.highlight.clear().rect(0,(t-this.scroll)*this.rowHeight,this.viewWidth,this.rowHeight).fill({color:r.color.selection})}},aI=class extends Y{columnX(e){return(Q().direction===`rtl`?this.columns-1-e:e)*this.cellSize}constructor(e){super(),this.selection=new rI({onChange:()=>this.refresh(),onHighlight:(e,t)=>this.onHighlight?.(e,t)}),this.cells=[],this.cellsLayer=new Y,this.highlight=new bE,this.pickupHighlight=new bE,this.mask_=new bE,this.scrollRow=0,this.pickedUp=null,this.pressedIndex=null,this.pressTimer=0,this.themeListener=()=>{let e=Q();this.selection.items.forEach((t,n)=>{let r=this.cells[n];r&&(r.x=this.columnX(n%this.columns),!((t.quantity??1)<=1)&&r.children.find(e=>e instanceof iF)?.setColor(e.color.textHighlight))}),this.refresh()},this.viewWidth=e.width,this.viewHeight=e.height,this.columns=Math.max(1,e.columns),this.cellSize=e.cellSize??Math.floor(this.viewWidth/this.columns),this.longPressDuration=e.longPressDuration??.6,this.onSelect=e.onSelect??null,this.onHighlight=e.onHighlight??null,this.onQuickslot=e.onQuickslot??null,this.onReorder=e.onReorder??null,this.addChild(this.highlight),this.addChild(this.pickupHighlight),this.addChild(this.cellsLayer),this.addChild(this.mask_),this.cellsLayer.mask=this.mask_,this.drawMask(),this.eventMode=`static`,this.on(`wheel`,e=>this.move(0,e.deltaY>0?1:-1)),this.setItems(e.items??[]),$.add(this.themeListener)}destroy(e){$.remove(this.themeListener),super.destroy(e)}drawMask(){this.mask_.clear().rect(0,0,this.viewWidth,this.viewHeight).fill({color:16777215})}get visibleRows(){return Math.max(1,Math.floor(this.viewHeight/this.cellSize))}get rows(){return Math.max(1,Math.ceil(this.selection.length/this.columns))}get selectedIndex(){return this.selection.selectedIndex}get selected(){return this.selection.selected}get length(){return this.selection.length}setItems(e){this.pickedUp=null,this.pressedIndex=null;for(let e of this.cells)e.destroy({children:!0});this.cells=[],this.cellsLayer.removeChildren();let t=Q();e.forEach((e,n)=>{let r=Math.floor(n/this.columns),i=n%this.columns,a=new Y;if(a.x=this.columnX(i),a.y=r*this.cellSize,a.eventMode=`static`,a.cursor=e.disabled?`default`:`pointer`,e.icon.x=Math.round((this.cellSize-e.icon.width)/2),e.icon.y=Math.round((this.cellSize-e.icon.height)/2),e.disabled&&(e.icon.alpha=.4),a.addChild(e.icon),(e.quantity??1)>1){let n=new iF({text:String(e.quantity),size:10,color:t.color.textHighlight});n.x=this.cellSize-n.width-2,n.y=this.cellSize-n.height-1,a.addChild(n)}a.on(`pointerdown`,()=>{this.pressedIndex=n,this.pressTimer=0}),a.on(`pointerup`,()=>this.releaseCell(n)),a.on(`pointerupoutside`,()=>this.releaseCell(n)),this.cells.push(a),this.cellsLayer.addChild(a)}),this.selection.reset(e),this.scrollRow=0,this.refresh()}releaseCell(e){this.pressedIndex===e&&(this.pressedIndex=null,this.selection.items[e]?.disabled||this.tapCell(e))}resize(e,t){this.viewWidth=e,this.viewHeight=t,this.drawMask(),this.refresh()}update(e){if(this.pressedIndex===null||(this.pressTimer+=e,this.pressTimer<this.longPressDuration))return;let t=this.pressedIndex;this.pressedIndex=null;let n=this.selection.items[t];n&&!n.disabled&&this.onQuickslot?.(n,t)}tapCell(e){let t=this.selection.items;if(e<0||e>=t.length)return;if(this.pickedUp===null){if(t[e].disabled)return;this.pickedUp=e,this.refresh();return}let n=this.pickedUp;this.pickedUp=null,n!==e&&(this.swapCells(n,e),this.onReorder?.(n,e)),this.refresh()}swapCells(e,t){let n=this.selection.items;this.selection.swap(e,t);let r=this.cells[e],i=this.cells[t],a=r.removeChildren(),o=i.removeChildren();for(let e of o)r.addChild(e);for(let e of a)i.addChild(e);r.cursor=n[e].disabled?`default`:`pointer`,i.cursor=n[t].disabled?`default`:`pointer`}cancelPickup(){this.pickedUp=null,this.refresh()}move(e,t){let n=this.rows,r=this.columns;return this.selection.step(i=>{let a=(Math.floor(i/r)+t+n)%n,o=(i%r+e+r)%r;return a*r+o},n*r)}select(e){this.selection.select(e)}confirm(){return this.selection.confirm(this.onSelect)}handleAction(e){switch(e){case`up`:return this.move(0,-1);case`down`:return this.move(0,1);case`left`:return this.move(Q().direction===`rtl`?1:-1,0);case`right`:return this.move(Q().direction===`rtl`?-1:1,0);case`confirm`:return this.confirm();case`cancel`:return this.pickedUp!==null&&(this.cancelPickup(),!0);default:return!1}}cellRect(e){return{x:this.columnX(e%this.columns),y:Math.floor(e/this.columns)*this.cellSize}}refresh(){let e=this.visibleRows,t=this.selection.selectedIndex,n=Math.floor(t/this.columns);n<this.scrollRow?this.scrollRow=n:n>=this.scrollRow+e&&(this.scrollRow=n-e+1),this.scrollRow=Math.max(0,Math.min(this.scrollRow,Math.max(0,this.rows-e))),this.cellsLayer.y=-this.scrollRow*this.cellSize;let r=Q();if(this.pickupHighlight.clear(),this.pickedUp!==null){let{x:e,y:t}=this.cellRect(this.pickedUp);this.pickupHighlight.rect(e,t,this.cellSize,this.cellSize).stroke({color:r.color.textHighlight,width:2})}if(this.highlight.clear(),this.selection.length>0){let{x:e,y:n}=this.cellRect(t);this.highlight.rect(e,n,this.cellSize,this.cellSize).fill({color:r.color.selection})}}},oI=class{constructor(e){if(this.onChange=new p,this.currentTabIndex=0,this.currentQuery=``,this.rows_=[],this.currentSelectedIndex=0,this.detail=!1,e.tabs.length===0)throw Error(`TabbedList needs at least one tab`);this.tabList=[...e.tabs],this.rowsFor=e.rowsFor,this.pageSize=Math.max(0,Math.floor(e.pageSize??0)),this.labelOf=e.label??(e=>String(e)),this.filterOf=e.filter??((e,t)=>t===``||this.labelOf(e).toLowerCase().includes(t.toLowerCase())),this.disabledOf=e.disabled??(()=>!1),this.recompute()}get tabs(){return this.tabList}get tab(){return this.tabList[this.currentTabIndex]}get query(){return this.currentQuery}get rows(){return this.rows_}get pageCount(){return this.pageSize<=0?1:Math.max(1,Math.ceil(this.rows_.length/this.pageSize))}get page(){return this.pageSize<=0?0:Math.floor(this.currentSelectedIndex/this.pageSize)}get pageRows(){if(this.pageSize<=0)return this.rows_;let e=this.page*this.pageSize;return this.rows_.slice(e,e+this.pageSize)}get selectedIndex(){return this.currentSelectedIndex}get selected(){return this.rows_[this.currentSelectedIndex]??null}get detailOpen(){return this.detail}selectTab(e){let t=this.tabList.findIndex(t=>t.id===e);t===-1||this.tabList[t].disabled||t!==this.currentTabIndex&&(this.currentTabIndex=t,this.recompute(),this.emit())}nextTab(e=1){if(e===0)return;let t=e>0?1:-1,n=this.currentTabIndex;for(let r=0;r<Math.abs(e);r++)do n=(n+t+this.tabList.length)%this.tabList.length;while(this.tabList[n].disabled&&n!==this.currentTabIndex);n!==this.currentTabIndex&&(this.currentTabIndex=n,this.recompute(),this.emit())}setQuery(e){e!==this.currentQuery&&(this.currentQuery=e,this.recompute(),this.emit())}move(e){if(e===0||this.rows_.length===0)return;let t=e>0?1:-1,n=this.currentSelectedIndex;for(let r=0;r<Math.abs(e);r++){let e=n;do e+=t;while(e>=0&&e<this.rows_.length&&this.disabledOf(this.rows_[e]));if(e<0||e>=this.rows_.length)break;n=e}n!==this.currentSelectedIndex&&(this.currentSelectedIndex=n,this.emit())}setPage(e){let t=Math.max(0,Math.min(this.pageCount-1,Math.floor(e)));if(this.pageSize<=0)return;let n=this.firstSelectableOnPage(t);n!==this.currentSelectedIndex&&(this.currentSelectedIndex=n,this.emit())}nextPage(e){this.setPage(this.page+e)}openDetail(){return this.selected===null||this.disabledOf(this.selected)?!1:(this.detail||(this.detail=!0,this.emit()),!0)}closeDetail(){this.detail&&(this.detail=!1,this.emit())}firstSelectableOnPage(e){let t=e*this.pageSize,n=Math.min(this.rows_.length,t+this.pageSize);for(let e=t;e<n;e++)if(!this.disabledOf(this.rows_[e]))return e;return Math.min(t,Math.max(0,this.rows_.length-1))}firstSelectable(e){for(let t=e;t<this.rows_.length;t++)if(!this.disabledOf(this.rows_[t]))return t;return 0}recompute(){let e=this.rowsFor(this.tab.id).filter(e=>this.filterOf(e,this.currentQuery));this.rows_=e,this.currentSelectedIndex=e.length===0?0:this.firstSelectable(0),this.detail=!1}emit(){this.onChange.dispatch()}};function sI(e,t,n={}){let r={},i=t.replace(/\r/g,``).split(`
1372
- `),a=null,o=``,s=[],c=!1,l=()=>{if(a){if(r[a]!==void 0)throw Error(`Duplicate FTL message: ${a}`);if(s.length){if(!c)throw Error(`FTL select expression is not closed: ${a}`);let t=o.trim().match(/^\{\s*\$([\w-]+)\s*->\s*$/)?.[1];if(!t)throw Error(`Invalid FTL selector: ${o}`);r[a]=lI(e,t,s)}else r[a]=cI(o);a=null,o=``,s=[],c=!1}};for(let e of i){if(!e.trim()||e.trimStart().startsWith(`#`))continue;let t=e.match(/^([\w-]+)\s*=\s*(.*)$/);if(t){l(),a=t[1],o=t[2];continue}if(!a)throw Error(`FTL continuation has no message: ${e}`);if(e.trim()===`}`){if(!s.length||c)throw Error(`Unexpected FTL select terminator: ${e}`);c=!0;continue}if(c)throw Error(`FTL content follows a closed select expression: ${e}`);let n=e.match(/^\s*(\*)?\[([^\]]+)\]\s*(.*)$/);if(n){s.push({key:n[2],value:n[3],default:!!n[1]});continue}if(/^\s+/.test(e)){s.length?s[s.length-1].value+=` ${e.trim()}`:o+=` ${e.trim()}`;continue}throw Error(`Invalid FTL line: ${e}`)}return l(),{locale:e,direction:n.direction??(/^(ar|he|fa|ur)(?:-|$)/i.test(e)?`rtl`:`ltr`),messages:r}}function cI(e){return e.replace(/\{\s*\$([\w-]+)\s*(?:!([sra]))?\s*(?::\s*([^{}]*?))?\s*\}/g,(e,t,n,r)=>`{${t}${n?`!${n}`:``}${r===void 0?``:`:${r.trim()}`}}`).trim()}function lI(e,t,n){let r=n.filter(e=>e.default);if(r.length!==1)throw Error(`FTL select expressions need exactly one default variant`);let i=r[0],a=new Intl.PluralRules(e);return{format(e={}){let r=e[t],o=n.find(e=>e.key===String(r)),s=typeof r==`number`?a.select(r):``;return cI((o??n.find(e=>e.key===s)??i).value)}}}function uI(e,t,n={}){let r=n.domain??`messages`,i=r===`messages`?``:`${r}:`,a={},o=t.replace(/\r\n?/g,`
1369
+ `}},Pj=class extends Zd{constructor(e){super({glProgram:Wm({name:`color-transform-batch`,bits:[qm,Mj,$m(e),ch]}),gpuProgram:Um({name:`color-transform-batch`,bits:[Km,Nj,Zm(e),sh]}),resources:{batchSamplers:Eg(e)}}),this.maxTextures=e}},Fj=7,Ij=class extends jf{constructor(){let e=new wf({data:new Float32Array(1),label:`mwg-color-transform-attribute-buffer`,usage:Sf.VERTEX|Sf.COPY_DST,shrinkToFit:!1}),t=new wf({data:new Uint32Array(1),label:`mwg-color-transform-index-buffer`,usage:Sf.INDEX|Sf.COPY_DST,shrinkToFit:!1});super({attributes:{aPosition:{buffer:e,format:`float32x2`,stride:28,offset:0},aUV:{buffer:e,format:`float32x2`,stride:28,offset:8},aColor:{buffer:e,format:`unorm8x4`,stride:28,offset:16},aTextureIdAndRound:{buffer:e,format:`uint16x2`,stride:28,offset:20},aColorAdd:{buffer:e,format:`unorm8x4`,stride:28,offset:24}},indexBuffer:t})}},Lj=0,Rj=e=>e.colorAdd??Lj;function zj(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){e[n]=r*l+a*u+s,e[n+1]=o*u+i*l+c,e[n+2]=d,e[n+3]=f,t[n+4]=p,t[n+5]=m,t[n+6]=h}var Bj=class e extends bg{static{this.extension={type:[I.Batcher],name:`mwg-color-transform`}}constructor(t){super(t),this.geometry=new Ij,this.name=e.extension.name,this.vertexSize=Fj,this.shader=new Pj(t.maxTextures)}packAttributes(e,t,n,r,i){let a=i<<16|e.roundPixels&65535,{a:o,b:s,c,d:l,tx:u,ty:d}=e.transform,{positions:f,uvs:p}=e,m=e.color,h=Rj(e),g=e.attributeOffset,_=g+e.attributeSize;for(let e=g;e<_;e++){let i=e*2,g=f[i],_=f[i+1];t[r++]=o*g+c*_+u,t[r++]=l*_+s*g+d,t[r++]=p[i],t[r++]=p[i+1],n[r++]=m,n[r++]=a,n[r++]=h}}packQuadAttributes(e,t,n,r,i){let{a,b:o,c:s,d:c,tx:l,ty:u}=e.transform,{bounds:d}=e,f=e.texture.uvs,p=d.maxX,m=d.minX,h=d.maxY,g=d.minY,_=e.color,v=Rj(e),y=i<<16|e.roundPixels&65535;zj(t,n,r,a,o,s,c,l,u,m,g,f.x0,f.y0,_,y,v),r+=Fj,zj(t,n,r,a,o,s,c,l,u,p,g,f.x1,f.y1,_,y,v),r+=Fj,zj(t,n,r,a,o,s,c,l,u,p,h,f.x2,f.y2,_,y,v),r+=Fj,zj(t,n,r,a,o,s,c,l,u,m,h,f.x3,f.y3,_,y,v)}_updateMaxTextures(e){this.shader.maxTextures!==e&&(this.shader.destroy(),this.shader=new Pj(e))}destroy(){this.shader.destroy(),super.destroy()}},Vj=`mwg-tinted-sprite`;function Hj(e){e.renderPipeId=Vj}var Uj=class{static{this.extension={type:[I.WebGLPipes,I.WebGPUPipes,I.CanvasPipes],name:Vj}}constructor(e){this.renderer=e}addRenderable(e,t){let n=this.element(e);e.didViewUpdate&&this.sync(e,n),this.renderer.renderPipes.batch.addToBatch(n,t)}updateRenderable(e){let t=this.element(e);e.didViewUpdate&&this.sync(e,t),t._batcher.updateElement(t)}validateRenderable(e){let t=this.element(e);return!t._batcher.checkAndUpdateTexture(t,e.texture)}sync(e,t){t.bounds=e.visualBounds,t.texture=e.texture,t.colorAdd=e.colorAdd}element(e){let t=e._gpuData;return t[this.renderer.uid]??this.create(e,t)}create(e,t){let n=new Wj;return n.renderable=e,n.transform=e.groupTransform,n.texture=e.texture,n.bounds=e.visualBounds,n.roundPixels=this.renderer._roundPixels|e._roundPixels,n.colorAdd=e.colorAdd,t[this.renderer.uid]=n,n}destroy(){this.renderer=null}},Wj=class{constructor(){this.batcherName=Bj.extension.name,this.topology=`triangle-list`,this.attributeSize=4,this.indexSize=6,this.packAsQuad=!0,this.roundPixels=0,this.colorAdd=0,this._attributeStart=0,this._textureId=0,this._indexStart=0,this._batcher=null,this._batch=null}get blendMode(){return this.renderable.groupBlendMode}get color(){return this.renderable.groupColorAlpha}reset(){this.renderable=null,this.texture=null,this._batcher=null,this._batch=null,this.bounds=null,this.colorAdd=0}destroy(){this.reset()}},Gj=!1;function Kj(){Gj||(Gj=!0,L.add(Bj),L.add(Uj))}function qj(e,t,n,r=0){return(Yj(r)<<24|Yj(n)<<16|Yj(t)<<8|Yj(e))>>>0}function Jj(e,t){return qj((e>>16&255)/255*t,(e>>8&255)/255*t,(e&255)/255*t)}function Yj(e){return Math.max(0,Math.min(255,Math.round(e*255)))}var Xj=Lj;Kj();var Zj=class extends xl{constructor(e){super(e),this._colorAdd=0,Hj(this)}get colorAdd(){return this._colorAdd}set colorAdd(e){this._colorAdd!==e&&(this._colorAdd=e,this.onViewUpdate())}setColorAdd(e,t,n,r=0){this.colorAdd=qj(e,t,n,r)}lerpTint(e,t){let n=Math.round((1-t)*255);this.tint=n<<16|n<<8|n,this.colorAdd=Jj(e,t)}silhouette(e){this.tint=0,this.colorAdd=Jj(e,1)}resetColor(){this.tint=16777215,this.colorAdd=0}};function Qj(e){return[e>>16&255,e>>8&255,e&255]}function $j(e){let[t,n,r]=Qj(e);return Math.floor((t+n+r)/3)}function eM(e,t,n){return Math.trunc(n*e+(1-n)*t)}function tM(e,t,n){let[r,i,a]=Qj(e),[o,s,c]=Qj(t);return eM(r,o,n)<<16|eM(i,s,n)<<8|eM(a,c,n)}function nM(e,t){let n=e.length>0?$j(e[0]):255;return{from:e,to:e.map(e=>{let r=$j(e);return n!==0&&r<=n?tM(t.mid,t.min,r/n):tM(t.mid,t.max,(255-r)/(255-n))})}}function rM(e,t,n=`exact`){let r=t.from.map(Qj),i=new Uint8ClampedArray(e.length);for(let a=0;a<e.length;a+=4){let o=e[a+3],s=e[a],c=e[a+1],l=e[a+2];if(i[a]=s,i[a+1]=c,i[a+2]=l,i[a+3]=o,o===0||r.length===0)continue;if(n===`exact`){let e=r.findIndex(([e,t,n])=>e===s&&t===c&&n===l);if(e<0)continue;let[n,o,u]=Qj(t.to[e]??t.from[e]);i[a]=n,i[a+1]=o,i[a+2]=u;continue}let u=0,d=1/0;for(let e=0;e<r.length;e+=1){let[t,n,i]=r[e],a=s-t,o=c-n,f=l-i,p=a*a+o*o+f*f;p<d&&(d=p,u=e)}let[f,p,m]=Qj(t.to[u]??t.from[u]);i[a]=f,i[a+1]=p,i[a+2]=m}return i}function iM(e,t,n){let r=e.width,i=e.height;if(r<=0||i<=0||!e.source)return e;let a=!t.createCanvas,o=t.createCanvas?.(r,i)??(typeof document>`u`?null:document.createElement(`canvas`));if(!o)return e;o.width=r,o.height=i;let s=o.getContext(`2d`);if(!s)return e;let c=a?{drawImage:s.drawImage.bind(s),getImageData:s.getImageData.bind(s),putImageData:(e,t,n)=>s.putImageData(new ImageData(new Uint8ClampedArray(e.data),e.width,e.height),t,n)}:s;return s.drawImage(e.source.resource,0,0),n(c,r,i),J.from(o)}function aM(e,t,n={},r=`exact`){return iM(e,n,(e,n,i)=>{let a=rM(e.getImageData(0,0,n,i).data,t,r);e.putImageData({data:a,width:n,height:i},0,0)})}function oM(e){e=e.replace(/^"|"$/g,``);let t=[],n=0,r=0;for(let i=0;i<e.length;i+=1)e[i]===`(`?r+=1:e[i]===`)`?r=Math.max(0,r-1):e[i]===`~`&&r===0&&(t.push(e.slice(n,i)),n=i+1);t.push(e.slice(n));let i=(t.shift()??``).trim(),a=[];for(let e of t){let t=/^([A-Za-z][A-Za-z0-9_-]*)(?:\((.*)\))?$/.exec(e.trim());t&&a.push({name:t[1].toUpperCase(),args:t[2]===void 0?[]:t[2].split(`,`).map(e=>e.trim())})}return{path:i,modifiers:a}}function sM(e,t){return e.modifiers.find(e=>e.name===t.toUpperCase())}function cM(e){return e!==void 0&&/^(linear|smooth)$/i.test(e)?`linear`:`nearest`}function lM(e,t,n){return[1,0,0,0,e/255,0,1,0,0,t/255,0,0,1,0,n/255,0,0,0,1,0]}function uM(e){return[(e.red??100)/100,0,0,0,0,0,(e.green??100)/100,0,0,0,0,0,(e.blue??100)/100,0,0,0,0,0,1,0]}function dM(e,t){let n=1-t,r=(e>>16&255)/255,i=(e>>8&255)/255,a=(e&255)/255;return[n,0,0,0,r*t,0,n,0,0,i*t,0,0,n,0,a*t,0,0,0,1,0]}function fM(e){let t=[`R`,`G`,`B`,`A`].map((t,n)=>e[n]??t),n=e=>{switch(e){case`R`:return[1,0,0,0,0];case`G`:return[0,1,0,0,0];case`B`:return[0,0,1,0,0];case`A`:return[0,0,0,1,0];case`0`:return[0,0,0,0,0];case`1`:return[0,0,0,0,1]}};return t.flatMap(e=>n(e))}function pM(e,t){let n=new Ik;n.matrix=t,e.filters=[n]}function mM(e){if(e===void 0)return;let t=e.trim(),n=t.endsWith(`%`),r=Number(n?t.slice(0,-1):t);if(Number.isFinite(r))return n||r>1?r/100:r}function hM(e){if(e===void 0)return;let t=Number.parseInt(e.replace(/^#/,``),16);return Number.isFinite(t)?t:void 0}function gM(e,t,n=1){let r=sM(t,`FL`);r&&(r.args.length===0||r.args.some(e=>/horiz|horizontal|x/i.test(e)))&&(e.scale.x*=-1),r?.args.some(e=>/vert|vertical|y/i.test(e))&&(e.scale.y*=-1);let i=sM(t,`SCALE`);if(i){let t=Number(i.args[0]),r=Number(i.args[1]??i.args[0]);Number.isFinite(t)&&t>0&&(e.width=t*n),Number.isFinite(r)&&r>0&&(e.height=r*n)}if(sM(t,`GS`)){let t=new Ik;t.greyscale(1,!1),e.filters=[...e.filters??[],t]}let a=sM(t,`CS`);if(a){let t=a.args.slice(0,3).map(Number);if(t.length===3&&t.every(e=>Number.isFinite(e))){let n=new Ik;n.matrix=lM(t[0],t[1],t[2]),e.filters=[...e.filters??[],n]}}let o=sM(t,`R`),s=sM(t,`G`),c=sM(t,`B`);if(o||s||c){let t=o?Number(o.args[0]):void 0,n=s?Number(s.args[0]):void 0,r=c?Number(c.args[0]):void 0,i=new Ik;i.matrix=uM({red:Number.isFinite(t)?t:void 0,green:Number.isFinite(n)?n:void 0,blue:Number.isFinite(r)?r:void 0}),e.filters=[...e.filters??[],i]}let l=sM(t,`CHAN`);if(l&&l.args.length>0){let t=l.args.map(e=>e.trim().toUpperCase()),n=new Ik;n.matrix=fM(t),e.filters=[...e.filters??[],n]}let u=sM(t,`O`);if(u){let t=mM(u.args[0]);t!==void 0&&(e.alpha*=Math.min(1,Math.max(0,t)))}}function _M(e,t,n={},r=1){e.texture=SM(e.texture,t,n),gM(e,t,r)}function vM(e,t){let n=sM(t,`CROP`);if(!n||n.args.length<4||!e.source)return e;let r=n.args.slice(0,4).map(Number);if(r.some(e=>!Number.isFinite(e))||r[2]<=0||r[3]<=0)return e;let i=Math.max(0,r[0]),a=Math.max(0,r[1]),o=Math.min(r[2],Math.max(0,e.width-i)),s=Math.min(r[3],Math.max(0,e.height-a));return o>0&&s>0?new J({source:e.source,frame:new K(i,a,o,s)}):e}function yM(e,t){let n=e.trim();return hM(n)??t?.(n)}function bM(e,t){let n=[],r=[];for(let i of e){let[e,a]=i.split(`>`);if(e===void 0||a===void 0)continue;let o=yM(e,t),s=yM(a,t);o!==void 0&&s!==void 0&&(n.push(o),r.push(s))}return{from:n,to:r}}function xM(e,t){let n=e.join(`,`),r=n.indexOf(`>`);if(r<0)return{from:[],to:[]};let i=e=>e.split(`,`).map(e=>yM(e,t)).filter(e=>e!==void 0);return{from:i(n.slice(0,r)),to:i(n.slice(r+1))}}function SM(e,t,n={}){let r=e,i=sM(t,`RC`);if(i&&i.args.length>0){let e=bM(i.args,n.resolveColor);e.from.length>0&&(r=aM(r,e,n,`exact`))}let a=sM(t,`PAL`);if(a){let e=xM(a.args,n.resolveColor);e.from.length>0&&e.from.length===e.to.length&&(r=aM(r,e,n,`exact`))}let o=sM(t,`BLIT`);if(o&&o.args.length>0&&n.resolveTexture){let e=n.resolveTexture(o.args[0]);if(e){let t=Number(o.args[1]??0)||0,i=Number(o.args[2]??0)||0;r=iM(r,n,n=>{n.drawImage(e.source.resource,t,i)})}}let s=sM(t,`MASK`);if(s&&s.args.length>0&&n.resolveTexture){let e=n.resolveTexture(s.args[0]);if(e){let t=Number(s.args[1]??0)||0,i=Number(s.args[2]??0)||0;r=iM(r,n,(r,a,o)=>{let s=r.getImageData(0,0,a,o),c=CM(e.width,e.height,n);if(!c)return;let l=c.getContext(`2d`);if(!l)return;l.drawImage(e.source.resource,0,0);let u=l.getImageData(0,0,e.width,e.height),d=wM(s.data,a,o,u.data,e.width,e.height,t,i);r.putImageData({data:d,width:a,height:o},0,0)})}}let c=sM(t,`BLEND`);if(c){let e=yM(c.args[0]??``,n.resolveColor),t=mM(c.args[1]);e!==void 0&&t!==void 0&&(r=iM(r,n,(n,r,i)=>{let a=TM(n.getImageData(0,0,r,i).data,e,t);n.putImageData({data:a,width:r,height:i},0,0)}))}let l=sM(t,`ROTATE`);if(l){let e=Number(l.args[0]);if(Number.isFinite(e)&&e%360!=0){let t=r.width,i=r.height;if(t>0&&i>0&&r.source){let a=CM(t,i,n),o=a?.getContext(`2d`);if(a&&o){o.drawImage(r.source.resource,0,0);let a=EM(o.getImageData(0,0,t,i).data,t,i,e,cM(l.args[1])),s=CM(a.width,a.height,n),c=s?.getContext(`2d`);s&&c&&(c.putImageData({data:a.data,width:a.width,height:a.height},0,0),r=J.from(s))}}}}return r}function CM(e,t,n){let r=n.createCanvas?.(e,t)??(typeof document>`u`?null:document.createElement(`canvas`));return r?(r.width=e,r.height=t,r):null}function wM(e,t,n,r,i,a,o,s){let c=new Uint8ClampedArray(e.length);for(let l=0;l<n;l+=1)for(let n=0;n<t;n+=1){let u=(l*t+n)*4,d=n-o,f=l-s,p=d>=0&&d<i&&f>=0&&f<a?r[(f*i+d)*4+3]:0;c[u]=e[u],c[u+1]=e[u+1],c[u+2]=e[u+2],c[u+3]=Math.round(e[u+3]*p/255)}return c}function TM(e,t,n){let r=Math.min(1,Math.max(0,n)),i=t>>16&255,a=t>>8&255,o=t&255,s=new Uint8ClampedArray(e.length);for(let t=0;t<e.length;t+=4){let n=e[t+3];if(s[t+3]=n,n===0){s[t]=e[t],s[t+1]=e[t+1],s[t+2]=e[t+2];continue}s[t]=e[t]*(1-r)+i*r,s[t+1]=e[t+1]*(1-r)+a*r,s[t+2]=e[t+2]*(1-r)+o*r}return s}function EM(e,t,n,r,i=`nearest`){let a=r*Math.PI/180,o=Math.cos(a),s=Math.sin(a),c=t/2,l=n/2,u=0,d=0;for(let[e,t]of[[-c,-l],[c,-l],[c,l],[-c,l]])u=Math.max(u,Math.abs(e*o-t*s)),d=Math.max(d,Math.abs(e*s+t*o));let f=Math.max(1,Math.round(u*2)),p=Math.max(1,Math.round(d*2)),m=new Uint8ClampedArray(f*p*4),h=t/2-.5,g=n/2-.5,_=f/2-.5,v=p/2-.5,y=i===`linear`&&r%90!=0;for(let r=0;r<p;r+=1)for(let i=0;i<f;i+=1){let a=i-_,c=r-v,l=a*o+c*s+h,u=-a*s+c*o+g,d=(r*f+i)*4;if(!y){let r=Math.round(l),i=Math.round(u);if(r<0||r>=t||i<0||i>=n)continue;let a=(i*t+r)*4;m[d]=e[a],m[d+1]=e[a+1],m[d+2]=e[a+2],m[d+3]=e[a+3];continue}DM(e,t,n,l,u,m,d)}return{data:m,width:f,height:p}}function DM(e,t,n,r,i,a,o){if(r<-.5||i<-.5||r>t-.5||i>n-.5)return;let s=Math.floor(r),c=Math.floor(i),l=r-s,u=i-c,d=0,f=0,p=0,m=0;for(let r=0;r<=1;r+=1)for(let i=0;i<=1;i+=1){let a=(i===0?1-l:l)*(r===0?1-u:u);if(a===0)continue;let o=On(s+i,0,t-1),h=(On(c+r,0,n-1)*t+o)*4,g=e[h+3];d+=g*a,f+=e[h]*g*a,p+=e[h+1]*g*a,m+=e[h+2]*g*a}d<=0||(a[o]=f/d,a[o+1]=p/d,a[o+2]=m/d,a[o+3]=d)}var OM=class{constructor(e,{fps:t=10,loop:n=!0,startTime:r=0}={}){if(e.length===0)throw Error(`an animation needs at least one frame`);if(!(t>0))throw Error(`an animation needs a positive fps, got ${t}`);this.frameDuration=1/t,this.frames=e.map(e=>kM(e)?e:{texture:e}),this.times=this.frames.map(e=>e.duration??this.frameDuration),this.loop=n,this.startTime=r;let i=0,a=0;for(let e of this.frames)e.duration===void 0?i++:a+=e.duration;this.duration=i*this.frameDuration+a}frameAt(e){return this.frames[this.frameIndexAt(e)]}frameIndexAt(e){let t=e-this.startTime;if(t<=0)return 0;let n=this.duration;if(n<=0)return this.frames.length-1;let r=this.loop?t%n:Math.min(t,n);for(let e=0;e<this.times.length;e++){if(r<this.times[e])return e;r-=this.times[e]}return this.frames.length-1}};function kM(e){return e.texture!==void 0}var AM=class extends Zj{constructor(...e){super(...e),this.animations=new Map,this.current=null,this.currentName=null,this.elapsed=0,this.finished=!1,this.offset={x:0,y:0},this.onFinish=null,this.paused=!1}add(e,t,n){return this.animations.set(e,new OM(t,n)),this}has(e){return this.animations.has(e)}get playing(){return this.currentName}get isFinished(){return this.finished}get frameOffset(){return this.offset}get elapsedTime(){return this.elapsed}play(e,t=!1){if(!t&&this.currentName===e&&!this.finished)return this;let n=this.animations.get(e);if(!n)throw Error(`no animation named "${e}" on this sprite`);return this.current=n,this.currentName=e,this.elapsed=0,this.finished=!1,this.show(n.frameAt(0)),this}stop(){this.current=null,this.currentName=null}update(e){let t=this.current;!t||this.paused||this.finished||(this.elapsed+=e,this.show(t.frameAt(this.elapsed)),!t.loop&&this.elapsed>=t.startTime+t.duration&&(this.finished=!0,this.onFinish?.(this.currentName)))}show(e){this.texture=e.texture,this.offset.x=e.offsetX??0,this.offset.y=e.offsetY??0}};function jM(e,t,n,r){return t>=e.x-r&&t<=e.x+e.width+r&&n>=e.y-r&&n<=e.y+e.height+r}function MM(e,t,n,r=0){return jM(e.view,t,n,r)}var NM=class{constructor(){this.members=[]}get size(){return this.members.length}add(e){return this.members.includes(e)||this.members.push(e),this}remove(e){let t=this.members.indexOf(e);return t<0?!1:(this.members.splice(t,1),!0)}clear(){this.members.length=0}update(e,t,n=0){let r=e.view;for(let e of[...this.members])jM(r,e.x,e.y,n)&&e.update(t)}},PM=``;function FM(e){PM=e.endsWith(`/`)||e===``?e:e+`/`}var IM;function LM(e){IM=e}function RM(){return IM||(typeof window>`u`?void 0:window.__MWG_ASSETS__)}function zM(){return RM()!==void 0}function BM(){return Object.keys(RM()??{})}function VM(e){let t=RM();return!t||e in t}function HM(e){let t=RM();if(!t)return PM+e;let n=t[e];if(n===void 0)throw Error(`asset "${e}" is not in this build - check it is under the folder passed to compile-resources`);return n}var UM={"image/png":`png`,"image/jpeg":`jpg`,"image/webp":`webp`,"image/gif":`gif`,"image/svg+xml":`svg`};async function WM(e,t={}){let{onProgress:n,resolution:r,optional:i,onMissing:a}=typeof t==`function`?{onProgress:t,resolution:void 0,optional:void 0,onMissing:void 0}:t,o=new Set(i??[]),s=e.filter(e=>!Mk.cache.has(e)),c=s.filter(e=>!o.has(e)),l=s.filter(e=>o.has(e)),u=e=>{let t=HM(e),n={alias:e,src:t};if(r!==void 0&&(n.data={resolution:r}),t.startsWith(`data:`)){let r=/^data:([^;,]+)/.exec(t)?.[1],i=(r&&UM[r])??/\.([a-z0-9]+)$/i.exec(e)?.[1];i&&(n.format=i)}Mk.add(n)};if(l.length===0&&c.length===0){n?.(1);return}for(let e of c)u(e);let d=c.length>0?Mk.load(c,n):Promise.resolve(),f=l.map(async e=>{u(e);try{await Mk.load(e)}catch(t){a?.(e,t)}});await Promise.all([d,...f]),l.length>0&&c.length===0&&n?.(1)}function GM(e,t){if(!Mk.cache.has(e)){if(t!==void 0)return t;throw Error(`texture "${e}" has not been loaded - pass it to load() first`)}return Mk.get(e)}function KM(e,t){if(!Mk.cache.has(e)){if(t!==void 0)return t;throw Error(`asset "${e}" has not been loaded - pass it to load() first`)}return Mk.get(e)}function qM(e){return Mk.cache.has(e)}async function JM(e){let t=e.filter(e=>Mk.cache.has(e));t.length!==0&&await Mk.unload(t)}var YM=new Map;async function XM(e,t,n={}){let r=n.fetch??globalThis.fetch;if(!r)throw Error(`fetch is unavailable; provide LoadBinaryOptions.fetch`);let i=e.filter(e=>!YM.has(e));if(i.length===0){t?.(1);return}let a=0;await Promise.all(i.map(async e=>{let n=await r(HM(e));if(!n.ok)throw Error(`failed to load binary asset "${e}": ${n.status}`);YM.set(e,await n.arrayBuffer()),a++,t?.(a/i.length)}))}function ZM(e){let t=YM.get(e);if(!t)throw Error(`binary asset "${e}" has not been loaded - pass it to loadBinary() first`);return t}function QM(e){return YM.has(e)}function $M(e){for(let t of e)YM.delete(t)}var eN=class{constructor(e={}){if(this.entries=new Map,this.clock=0,this.budgetBytes=e.budgetBytes??1/0,!(this.budgetBytes>=0))throw Error(`asset stream budget must not be negative`);this.loadAssets=e.load??WM,this.releaseAssets=e.release??JM}async preload(e,t){if(!e.id)throw Error(`asset bundle needs an id`);if(e.estimatedBytes!==void 0&&e.estimatedBytes<0)throw Error(`asset bundle size must not be negative`);let n=this.entries.get(e.id);if(n?.ready){n.lastUsed=++this.clock,t?.(1);return}let r=e.paths.filter(e=>!this.isRetained(e));r.length>0?await this.loadAssets([...r],t):t?.(1),this.entries.set(e.id,{...e,lastUsed:++this.clock,ready:!0}),await this.enforceBudget(e.id)}async preloadLikely(e,t){let n=[...e].sort((e,t)=>(t.priority??0)-(e.priority??0));for(let[e,r]of n.entries())await this.preload(r,t&&(r=>t((e+r)/n.length)));t?.(1)}use(e){let t=this.entries.get(e);return t?.ready?(t.lastUsed=++this.clock,!0):!1}isReady(e){return this.entries.get(e)?.ready??!1}async unload(e){let t=this.entries.get(e);if(!t)return;this.entries.delete(e);let n=t.paths.filter(e=>!this.isRetained(e));n.length>0&&await this.releaseAssets(n)}get estimatedBytes(){return[...this.entries.values()].reduce((e,t)=>e+(t.estimatedBytes??0),0)}async enforceBudget(e){for(;this.estimatedBytes>this.budgetBytes;){let t=[...this.entries.values()].filter(t=>t.id!==e).sort((e,t)=>e.lastUsed-t.lastUsed)[0];if(!t)return;await this.unload(t.id)}}isRetained(e){return[...this.entries.values()].some(t=>t.ready&&t.paths.includes(e))}};async function tN(e,t,n=fetch){let r=await n(e);if(!r.ok)throw Error(`fetchWithByteProgress: ${e} responded ${r.status}`);let i=r.headers.get(`content-length`),a=i!==null&&i!==``?Number(i):null;if(!r.body){let e=await r.blob();return t?.({loaded:e.size,total:a??e.size}),e}let o=r.body.getReader(),s=[],c=0;for(;;){let{done:e,value:n}=await o.read();if(e)break;s.push(n),c+=n.byteLength,t?.({loaded:c,total:a})}return new Blob(s)}var nN=l({AssetStream:()=>eN,fetchWithByteProgress:()=>tN,get:()=>KM,getBinary:()=>ZM,has:()=>VM,isBinaryLoaded:()=>QM,isCompiled:()=>zM,isLoaded:()=>qM,load:()=>WM,loadBinary:()=>XM,paths:()=>BM,release:()=>JM,releaseBinary:()=>$M,resolve:()=>HM,setAssetMap:()=>LM,setBase:()=>FM,texture:()=>GM});function rN(e){return{x:e.x,y:e.y,width:e.width,height:e.height}}var iN=class e{constructor(e,t,n){this.frames=new Map,this.names=new Map,this.texture=e,this.frameWidth=t,this.frameHeight=n,this.columns=t>0?Math.floor(e.width/t):0,this.rows=n>0?Math.floor(e.height/n):0}static grid(t,n=0,r=n){return new e(GM(t),n,r)}static fromTexture(t,n=0,r=n){return new e(t,n,r)}get count(){return this.columns*this.rows}name(e,t){return this.names.set(e,t),this}nameAll(e){for(let[t,n]of Object.entries(e))this.names.set(t,n);return this}indexOf(e){let t=this.names.get(e);if(t===void 0)throw Error(`this sheet has no frame named "${e}"`);return t}get(e){let t=typeof e==`string`?this.indexOf(e):e,n=this.frames.get(t);if(n)return n;if(t<0||t>=this.count)throw Error(`frame ${t} is outside this sheet, which holds ${this.count}`);let r=new J({source:this.texture.source,frame:new K(t%this.columns*this.frameWidth,Math.floor(t/this.columns)*this.frameHeight,this.frameWidth,this.frameHeight)});return this.frames.set(t,r),r}rect(e,t,n,r,i){if(r<=0||i<=0)throw Error(`a sprite sheet rect needs a positive width and height`);return this.frames.set(e,new J({source:this.texture.source,frame:new K(t,n,r,i)})),this}region(e){let t=this.get(e);return{texture:t,frame:rN(t.frame)}}range(e,t){let n=[];for(let r=e;r<=t;r++)n.push(this.get(r));return n}pick(...e){return e.map(e=>this.get(e))}},aN=class{constructor(e={}){if(this.world=new Y,this.x=0,this.y=0,this.requestedZoom=1,this.viewWidth=0,this.viewHeight=0,this.screenX=0,this.screenY=0,this.followTarget=null,this.followIntensity=0,this.shakeMagnitude=0,this.shakeRemaining=0,this.shakeDuration=1,this.shakeX=0,this.shakeY=0,this.bounds=null,this.step=0,this._angle=0,this.targetAngle=null,this.angleIntensity=0,e.grid!==void 0&&e.grid!==`square`&&e.grid!==`hex`)throw Error(`camera grid must be "square" or "hex", not "${e.grid}"`);this.stepsPerTurn=e.grid===`hex`?6:4,this.deadzone=e.deadzone??0,this.pixelPerfectTileSize=e.pixelPerfectTileSize,this.resolution=e.resolution??(()=>1),this.zoom=e.zoom??1}get rotationSteps(){return this.step}get rotation(){return this._angle}get uprightRotation(){return-this.rotation}setRotationStep(e){if(!Number.isInteger(e))throw Error(`camera rotation step must be an integer`);this.step=(e%this.stepsPerTurn+this.stepsPerTurn)%this.stepsPerTurn,this._angle=this.step/this.stepsPerTurn*Math.PI*2,this.targetAngle=null,this.apply()}rotate(e=1){this.setRotationStep(this.step+e)}rotateTo(e){this._angle=e,this.targetAngle=null,this.angleIntensity=0,this.apply()}animateRotationTo(e,t=4){this.targetAngle=e,this.angleIntensity=t}get spin(){let e=this.rotation;return{cos:Math.cos(e),sin:Math.sin(e)}}get zoom(){return this.pixelPerfectTileSize?sN(this.requestedZoom,this.pixelPerfectTileSize,this.resolution()):this.requestedZoom}set zoom(e){this.requestedZoom=Math.max(.01,e)}setViewport(e,t,n=0,r=0){this.viewWidth=e,this.viewHeight=t,this.screenX=n,this.screenY=r}get view(){let e=this.viewWidth/this.zoom,t=this.viewHeight/this.zoom,{x:n,y:r}=this.clampedCentre(this.x,this.y);if(this._angle===0)return{x:n-e/2,y:r-t/2,width:e,height:t};let i=[this.toWorld(this.screenX,this.screenY),this.toWorld(this.screenX+this.viewWidth,this.screenY),this.toWorld(this.screenX+this.viewWidth,this.screenY+this.viewHeight),this.toWorld(this.screenX,this.screenY+this.viewHeight)],a=i.map(e=>e.x),o=i.map(e=>e.y),s=Math.min(...a),c=Math.min(...o);return{x:s,y:c,width:Math.max(...a)-s,height:Math.max(...o)-c}}setBounds(e){this.bounds=e}snapTo(e,t){this.x=e,this.y=t,this.followTarget=null,this.followIntensity=0,this.apply()}panTo(e,t,n=4){this.followTarget={x:e,y:t},this.followIntensity=n}follow(e,t=8){this.followTarget=e,this.followIntensity=t}stopFollowing(){this.followTarget=null,this.followIntensity=0}shake(e,t=.4){yr()||(this.shakeMagnitude=e,this.shakeRemaining=this.shakeDuration=t)}shakeScreen(e,t=.4){this.shake(e/this.zoom,t)}update(e){if(this.followTarget&&this.followIntensity>0){let t=this.viewWidth/this.zoom*this.deadzone/2,n=this.viewHeight/this.zoom*this.deadzone/2,r=this.followTarget.x-this.x,i=this.followTarget.y-this.y;r=r>t?r-t:r<-t?r+t:0,i=i>n?i-n:i<-n?i+n:0;let a=yr()?1:1-Math.exp(-this.followIntensity*e);this.x+=r*a,this.y+=i*a}if(this.targetAngle!==null&&this.angleIntensity>0){let t=oN(this._angle,this.targetAngle),n=yr()?1:1-Math.exp(-this.angleIntensity*e);this._angle+=t*n}if(this.shakeRemaining>0){this.shakeRemaining-=e;let t=Math.max(0,this.shakeRemaining/this.shakeDuration);this.shakeX=O(-this.shakeMagnitude,this.shakeMagnitude)*t,this.shakeY=O(-this.shakeMagnitude,this.shakeMagnitude)*t}else this.shakeX=this.shakeY=0;this.apply()}toScreen(e,t){let{x:n,y:r}=this.clampedCentre(this.x+this.shakeX,this.y+this.shakeY),{cos:i,sin:a}=this.spin,o=e-n,s=t-r;return{x:(o*i-s*a)*this.zoom+this.screenX+this.viewWidth/2,y:(o*a+s*i)*this.zoom+this.screenY+this.viewHeight/2}}toWorld(e,t){let{x:n,y:r}=this.clampedCentre(this.x+this.shakeX,this.y+this.shakeY),{cos:i,sin:a}=this.spin,o=(e-this.screenX-this.viewWidth/2)/this.zoom,s=(t-this.screenY-this.viewHeight/2)/this.zoom;return{x:n+o*i+s*a,y:r-o*a+s*i}}clampedCentre(e,t){if(!this.bounds)return{x:e,y:t};let n=this.viewWidth/this.zoom/2,r=this.viewHeight/this.zoom/2,{minX:i,minY:a,maxX:o,maxY:s}=this.bounds;return{x:o-i<n*2?(i+o)/2:On(e,i+n,o-n),y:s-a<r*2?(a+s)/2:On(t,a+r,s-r)}}apply(){let{x:e,y:t}=this.clampedCentre(this.x+this.shakeX,this.y+this.shakeY);if(this.world.scale.set(this.zoom),this._angle===0){this.world.rotation=0,this.world.pivot.set(0,0),this.world.x=this.snapToDevice(this.screenX+this.viewWidth/2-e*this.zoom),this.world.y=this.snapToDevice(this.screenY+this.viewHeight/2-t*this.zoom);return}this.world.rotation=this.rotation,this.world.pivot.set(e,t),this.world.x=this.snapToDevice(this.screenX+this.viewWidth/2),this.world.y=this.snapToDevice(this.screenY+this.viewHeight/2)}snapToDevice(e){let t=this.resolution();return Math.round(e*t)/t}};function oN(e,t){let n=Math.PI*2,r=(t-e)%n;return r>Math.PI&&(r-=n),r<-Math.PI&&(r+=n),r}function sN(e,t,n=1){return Math.max(1,Math.round(e*t*n))/(t*n)}function cN(e={}){let t=Aj.current,n=new aN({resolution:()=>t.app.renderer.resolution,...e});return n.setViewport(t.width,t.height),n}var lN=class{constructor(e){this.container=new Y,this.clip=new bE,this.camera=new aN(e),this.container.addChild(this.camera.world),this.container.addChild(this.clip),this.container.mask=this.clip,this.resize(e.x,e.y,e.width,e.height)}resize(e,t,n,r){this.camera.setViewport(n,r,e,t),this.clip.clear().rect(e,t,n,r).fill(16777215)}update(e){this.camera.update(e)}};function uN(e,t){if(e>=t){let n=Math.floor(e/2);return[{x:0,y:0,width:n,height:t},{x:n,y:0,width:e-n,height:t}]}let n=Math.floor(t/2);return[{x:0,y:0,width:e,height:n},{x:0,y:n,width:e,height:t-n}]}var dN={protanopia:[.567,.433,0,0,0,.558,.442,0,0,0,0,.242,.758,0,0,0,0,0,1,0],deuteranopia:[.625,.375,0,0,0,.7,.3,0,0,0,0,.3,.7,0,0,0,0,0,1,0],tritanopia:[.95,.05,0,0,0,0,.433,.567,0,0,0,.475,.525,0,0,0,0,0,1,0]};function fN(e){let t=new Ik;return t.matrix=dN[e],t}function pN(e,t){let n=[];for(let r of e)t.has(r)||n.push(r);return n}function mN(e,t,n,r=`square`){return r===`hex`?Qn(e,t,n,n):{x:(e+.5)*n,y:(t+.5)*n}}var hN=class extends Y{constructor(e){super(),this.drawn=new Set,this.marker=new bE,this.widthInCells=e.widthInCells,this.cellSize=e.cellSize??2,this.shape=e.shape??`square`,this.renderTexture=u_.create({width:this.shape===`hex`?Math.ceil((e.widthInCells-1)*this.cellSize*.75+this.cellSize):e.widthInCells*this.cellSize,height:this.shape===`hex`?e.heightInCells*this.cellSize+this.cellSize/2:e.heightInCells*this.cellSize}),this.sprite=new xl(this.renderTexture),this.addChild(this.sprite),this.addChild(this.marker)}get exploredCount(){return this.drawn.size}sync(e,t){let n=pN(e,this.drawn);if(n.length===0)return;let r=new bE;for(let e of n){this.drawn.add(e);let n=e%this.widthInCells,i=Math.floor(e/this.widthInCells),a=mN(n,i,this.cellSize,this.shape);if(this.shape===`hex`){let e=this.cellSize/2,o=[];for(let t=0;t<6;t++){let n=Math.PI/3*t;o.push(a.x+Math.cos(n)*e,a.y+Math.sin(n)*e)}r.poly(o).fill({color:t(n,i)})}else r.rect(a.x-this.cellSize/2,a.y-this.cellSize/2,this.cellSize,this.cellSize).fill({color:t(n,i)})}Aj.current.app.renderer.render({container:r,target:this.renderTexture,clear:!1}),r.destroy()}setMarker(e,t,n,r=16777215){this.setMarkers([{x:e,y:t,facing:n,color:r}])}setMarkers(e){this.marker.clear();for(let t of e){let e=t.color??16777215,n=mN(t.x,t.y,this.cellSize,this.shape);if(this.marker.circle(n.x,n.y,Math.max(1,this.cellSize)).fill({color:e}),t.facing!==void 0){let r=this.cellSize*2;this.marker.moveTo(n.x,n.y).lineTo(n.x+Math.cos(t.facing)*r,n.y+Math.sin(t.facing)*r).stroke({color:e,width:1})}}}reset(){this.drawn.clear(),Aj.current.app.renderer.render({container:new Y,target:this.renderTexture,clear:!0})}destroy(e){this.renderTexture.destroy(!0),super.destroy(e)}},gN=24,_N=48,vN=[0,16,48,80];function yN(e,t){if(!Number.isInteger(t))throw Error(`${e} must be an integer, got ${t}`)}function bN(e){if(e!==0&&e!==1&&e!==2&&e!==3)throw Error(`RPG Maker autotile slot must be 0, 1, 2, or 3, got ${e}`)}function xN(e){if(e.length===0)throw Error(`RPG Maker autotile shape table cannot be empty`);for(let t=0;t<e.length;t++){if(e[t].length!==4)throw Error(`RPG Maker autotile shape ${t} needs exactly 4 quadrants`);for(let n of e[t])if(n.length!==2||!n.every(Number.isInteger)||n.some(e=>e<0))throw Error(`RPG Maker autotile shape ${t} has an invalid quadrant offset`)}}function SN(e,t){let n=vN[t]+Math.floor(e/48),r=n%8,i=Math.floor(n/8);return t===0?[Math.floor(r/4)*8,i*6+Math.floor(r/2)%2*3]:t===1?[r*2,(i-2)*3]:t===2?[r*2,(i-6)*2]:[r*2,Math.floor((i-10)*2.5+(i%2==1?.5:0))]}function CN(e,t,n,r){if(yN(`RPG Maker autotile tileId`,e),e<0)throw Error(`RPG Maker autotile tileId must be non-negative, got ${e}`);if(bN(t),yN(`RPG Maker autotile shape`,n),xN(r),n<0||n>=r.length)throw Error(`RPG Maker autotile shape ${n} is outside the table, which holds ${r.length}`);let[i,a]=SN(e,t);return{tileId:e,slot:t,shape:n,destinationX:e%16*_N,destinationY:Math.floor(e/16)*_N,quadrants:r[n].map(([e,t],n)=>({sourceX:(i*2+e)*gN,sourceY:(a*2+t)*gN,destinationX:n%2*gN,destinationY:Math.floor(n/2)*gN}))}}var wN=class{constructor(e){this.cache=new Map,this.table=e,xN(e)}get(e,t,n){let r=`${e}:${t}:${n}`,i=this.cache.get(r);if(i)return i;let a=CN(e,t,n,this.table);return this.cache.set(r,a),a}clear(){this.cache.clear()}},TN=[2048,2816,4352,5888],EN=[768,1536,1536,2304];function DN(e){if(!Number.isInteger(e))return null;for(let t=0;t<4;t++)if(e>=TN[t]&&e<TN[t]+EN[t])return t;return null}var ON=[[[2,4],[1,4],[2,3],[1,3]],[[2,0],[1,4],[2,3],[1,3]],[[2,4],[3,0],[2,3],[1,3]],[[2,0],[3,0],[2,3],[1,3]],[[2,4],[1,4],[2,3],[3,1]],[[2,0],[1,4],[2,3],[3,1]],[[2,4],[3,0],[2,3],[3,1]],[[2,0],[3,0],[2,3],[3,1]],[[2,4],[1,4],[2,1],[1,3]],[[2,0],[1,4],[2,1],[1,3]],[[2,4],[3,0],[2,1],[1,3]],[[2,0],[3,0],[2,1],[1,3]],[[2,4],[1,4],[2,1],[3,1]],[[2,0],[1,4],[2,1],[3,1]],[[2,4],[3,0],[2,1],[3,1]],[[2,0],[3,0],[2,1],[3,1]],[[0,4],[1,4],[0,3],[1,3]],[[0,4],[3,0],[0,3],[1,3]],[[0,4],[1,4],[0,3],[3,1]],[[0,4],[3,0],[0,3],[3,1]],[[2,2],[1,2],[2,3],[1,3]],[[2,2],[1,2],[2,3],[3,1]],[[2,2],[1,2],[2,1],[1,3]],[[2,2],[1,2],[2,1],[3,1]],[[2,4],[3,4],[2,3],[3,3]],[[2,4],[3,4],[2,1],[3,3]],[[2,0],[3,4],[2,3],[3,3]],[[2,0],[3,4],[2,1],[3,3]],[[2,4],[1,4],[2,5],[1,5]],[[2,0],[1,4],[2,5],[1,5]],[[2,4],[3,0],[2,5],[1,5]],[[2,0],[3,0],[2,5],[1,5]],[[0,4],[3,4],[0,3],[3,3]],[[2,2],[1,2],[2,5],[1,5]],[[0,2],[1,2],[0,3],[1,3]],[[0,2],[1,2],[0,3],[3,1]],[[2,2],[3,2],[2,3],[3,3]],[[2,2],[3,2],[2,1],[3,3]],[[2,4],[3,4],[2,5],[3,5]],[[2,0],[3,4],[2,5],[3,5]],[[0,4],[1,4],[0,5],[1,5]],[[0,4],[3,0],[0,5],[1,5]],[[0,2],[3,2],[0,3],[3,3]],[[0,2],[1,2],[0,5],[1,5]],[[0,4],[3,4],[0,5],[3,5]],[[2,2],[3,2],[2,5],[3,5]],[[0,2],[3,2],[0,5],[3,5]],[[0,0],[1,0],[0,1],[1,1]]],kN=[[[2,2],[1,2],[2,1],[1,1]],[[0,2],[1,2],[0,1],[1,1]],[[2,0],[1,0],[2,1],[1,1]],[[0,0],[1,0],[0,1],[1,1]],[[2,2],[3,2],[2,1],[3,1]],[[0,2],[3,2],[0,1],[3,1]],[[2,0],[3,0],[2,1],[3,1]],[[0,0],[3,0],[0,1],[3,1]],[[2,2],[1,2],[2,3],[1,3]],[[0,2],[1,2],[0,3],[1,3]],[[2,0],[1,0],[2,3],[1,3]],[[0,0],[1,0],[0,3],[1,3]],[[2,2],[3,2],[2,3],[3,3]],[[0,2],[3,2],[0,3],[3,3]],[[2,0],[3,0],[2,3],[3,3]],[[0,0],[3,0],[0,3],[3,3]]],AN=[[26,27,32,33],[4,27,32,33],[26,5,32,33],[4,5,32,33],[26,27,32,11],[4,27,32,11],[26,5,32,11],[4,5,32,11],[26,27,10,33],[4,27,10,33],[26,5,10,33],[4,5,10,33],[26,27,10,11],[4,27,10,11],[26,5,10,11],[4,5,10,11],[24,25,30,31],[24,5,30,31],[24,25,30,11],[24,5,30,11],[14,15,20,21],[14,15,20,11],[14,15,10,21],[14,15,10,11],[28,29,34,35],[28,29,10,35],[4,29,34,35],[4,29,10,35],[38,39,44,45],[4,39,44,45],[38,5,44,45],[4,5,44,45],[24,29,30,35],[14,15,44,45],[12,13,18,19],[12,13,18,11],[16,17,22,23],[16,17,10,23],[40,41,46,47],[4,41,46,47],[36,37,42,43],[36,5,42,43],[12,17,18,23],[12,13,42,43],[36,41,42,47],[16,17,46,47],[12,17,42,47],[0,1,6,7]],jN=[46,44,46,44,43,41,43,40,46,44,46,44,43,41,43,40,42,32,42,32,35,19,35,18,42,32,42,32,34,17,34,16,46,44,46,44,43,41,43,40,46,44,46,44,43,41,43,40,42,32,42,32,35,19,35,18,42,32,42,32,34,17,34,16,45,39,45,39,33,31,33,29,45,39,45,39,33,31,33,29,37,27,37,27,23,15,23,13,37,27,37,27,22,11,22,9,45,39,45,39,33,31,33,29,45,39,45,39,33,31,33,29,36,26,36,26,21,7,21,5,36,26,36,26,20,3,20,1,46,44,46,44,43,41,43,40,46,44,46,44,43,41,43,40,42,32,42,32,35,19,35,18,42,32,42,32,34,17,34,16,46,44,46,44,43,41,43,40,46,44,46,44,43,41,43,40,42,32,42,32,35,19,35,18,42,32,42,32,34,17,34,16,45,38,45,38,33,30,33,28,45,38,45,38,33,30,33,28,37,25,37,25,23,14,23,12,37,25,37,25,22,10,22,8,45,38,45,38,33,30,33,28,45,38,45,38,33,30,33,28,36,24,36,24,21,6,21,4,36,24,36,24,20,2,20,0];function MN(e){return!Number.isInteger(e)||e<=0||e>=384?null:{index:Math.floor(e/48),pattern:e%48}}function NN(e){let t=0;return e(0,-1)&&(t|=1),e(1,-1)&&(t|=2),e(1,0)&&(t|=4),e(1,1)&&(t|=8),e(0,1)&&(t|=16),e(-1,1)&&(t|=32),e(-1,0)&&(t|=64),e(-1,-1)&&(t|=128),jN[t]}var PN=[16,32,32,48];function FN(e){if(e.format===`rpgm-mv`){if(bN(e.slot),xN(e.table),e.tableEdge&&e.slot!==1)throw Error(`a table-edge layout needs slot 1 (A2), got slot ${e.slot}`);let t=PN[e.slot],n=vN[e.slot];for(let r of e.cycles){if(r.length===0)throw Error(`an autotile animation cycle needs at least one kind`);for(let i of r)if(!Number.isInteger(i)||i<n||i>=n+t)throw Error(`animation cycle kind ${i} is outside slot ${e.slot}'s kinds ${n}-${n+t-1}`)}return}if(!Number.isInteger(e.index)||e.index<0||e.index>7)throw Error(`an XP autotile index must be 0-7, got ${e.index}`);if(!Number.isInteger(e.frames)||e.frames<1)throw Error(`an XP autotile frame count must be at least 1, got ${e.frames}`)}var IN=24,LN=16,RN=6,zN=96,BN=32;function VN(e,t,n){if(t<=0)return null;if(!Number.isInteger(n)||n<0)throw Error(`an autotile animation frame must be an integer at or above zero, got ${n}`);return e.format===`rpgm-mv`?UN(e,t,n):WN(e,t,n)}function HN(e,t){let n=vN[e.slot]+Math.floor(t/48),r=t%48%e.table.length,i=n%8*2,a=(Math.floor(n/8)-2)*3,o=IN/2;return[2,3].map((t,n)=>{let[s,c]=e.table[r][t];return{sourceX:(i*2+s)*IN,sourceY:(a*2+c)*IN+o,sourceWidth:IN,sourceHeight:o,destX:n/2,destY:0,destWidth:1/2,destHeight:1/4}})}function UN(e,t,n){let r=TN[e.slot],i=EN[e.slot];if(!Number.isInteger(t)||t<r||t>=r+i)throw Error(`tile ${t} is outside slot ${e.slot}'s ids ${r}-${r+i-1}`);let a=t-r;if(e.tableEdge)return HN(e,a);let o=vN[e.slot]+Math.floor(a/48),s=e.tableFor?e.tableFor(o):e.table,c=a%48%s.length;for(let t of e.cycles){let e=t.indexOf(o);if(e>=0){o=t[(e+n)%t.length];break}}return CN((o-vN[e.slot])*48+a%48,e.slot,c,s).quadrants.map((e,t)=>({sourceX:e.sourceX,sourceY:e.sourceY,sourceWidth:IN,sourceHeight:IN,destX:t%2/2,destY:Math.floor(t/2)/2,destWidth:1/2,destHeight:1/2}))}function WN(e,t,n){if(!Number.isInteger(t)||t<e.index*48||t>=e.index*48+48||t<=0)throw Error(`tile ${t} is outside XP autotile ${e.index}'s ids ${e.index*48}-${e.index*48+47}`);if(e.single)return[{sourceX:n%e.frames*BN,sourceY:0,sourceWidth:BN,sourceHeight:BN,destX:0,destY:0,destWidth:1,destHeight:1}];let r=AN[t%48],i=n%e.frames*zN;return r.map((e,t)=>({sourceX:e%RN*LN+i,sourceY:Math.floor(e/RN)*LN,sourceWidth:LN,sourceHeight:LN,destX:t%2/2,destY:Math.floor(t/2)/2,destWidth:1/2,destHeight:1/2}))}var GN=128;function KN(e){let t=new Int32Array(e.width*e.height),n=t=>DN(t)===1&&((e.flags[t]??0)&GN)!==0;for(let r=1;r<e.height;r++)for(let i=0;i<e.width;i++){let a=r*e.width+i,o=e.objects[a-e.width]??0;if(!n(o)||n(e.objects[a]??0))continue;let s=DN(e.ground[a]??0);s!==2&&s!==3&&(t[a]=o)}return t}var qN=-1,JN=7237230,YN=10132122;function XN(e,t){if(!Number.isInteger(e)||e<0||e>=4096)throw Error(`tileFrame needs a sheet index from 0 to 4095, got ${e}`);if(!Number.isInteger(t)||t<0||t>=1<<20)throw Error(`tileFrame needs a frame index from 0 to ${(1<<20)-1}, got ${t}`);return e<<20|t}function ZN(e){return e>>>20}function QN(e){return e&(1<<20)-1}var $N=class extends Y{constructor(e){if(super(),this.layers=[],this.layersByName=new Map,this.chunks=[],this.widthInTiles=e.width,this.heightInTiles=e.height,this.sheets=Array.isArray(e.sheet)?[...e.sheet]:[e.sheet],this.sheets.length===0)throw Error(`a TileMap needs at least one sheet`);if(this.tileWidth=e.tileWidth??this.sheets[0].frameWidth,this.tileHeight=e.tileHeight??this.sheets[0].frameHeight,this.shape=e.shape??`square`,this.heightStep=e.heightStep??this.tileHeight/2,!(this.heightStep>0))throw Error(`a TileMap's heightStep must be a positive number, got ${e.heightStep}`);this.chunkSize=e.chunkSize??16,this.chunkColumns=Math.ceil(this.widthInTiles/this.chunkSize),this.chunkRows=Math.ceil(this.heightInTiles/this.chunkSize);let t=this.widthInTiles*this.heightInTiles;this.cellTint=new Uint32Array(t).fill(16777215),this.cellAdd=new Uint32Array(t),this.cellHeight=new Int32Array(t),this.faces=Array(t).fill(null)}get layerCount(){return this.layers.length}get worldWidth(){switch(this.shape){case`square`:return this.widthInTiles*this.tileWidth;case`hex`:return this.widthInTiles<=0?0:(this.widthInTiles-1)*this.tileWidth*.75+this.tileWidth;case`isometric`:return(this.widthInTiles+this.heightInTiles)*(this.tileWidth/2);case`staggered`:return this.widthInTiles*this.tileWidth+this.tileWidth/2}}get worldHeight(){switch(this.shape){case`square`:return this.heightInTiles*this.tileHeight;case`hex`:return this.heightInTiles*this.tileHeight+this.tileHeight/2;case`isometric`:return(this.widthInTiles+this.heightInTiles)*(this.tileHeight/2);case`staggered`:return this.heightInTiles*(this.tileHeight/2)+this.tileHeight/2}}inside(e,t){return e>=0&&t>=0&&e<this.widthInTiles&&t<this.heightInTiles}index(e,t){return t*this.widthInTiles+e}addLayer(e,t){let{cells:n,container:r,chunks:i}=this.beginLayer(e,t?.length),a={kind:`tiles`,name:e,data:t?Int32Array.from(t):new Int32Array(n).fill(-1),sprites:Array(n).fill(null),container:r};this.layers.push(a),this.layersByName.set(e,a),this.chunks.push(i),this.addChild(r);let o=this.layers.length===1;for(let e=0;e<this.heightInTiles;e++)for(let t=0;t<this.widthInTiles;t++){let n=a.data[this.index(t,e)];n!==-1&&this.buildSprite(a,t,e,n),o&&this.syncFaces(t,e)}return this}beginLayer(e,t){if(this.layersByName.has(e))throw Error(`this map already has a layer named "${e}"`);let n=this.widthInTiles*this.heightInTiles;if(t!==void 0&&t!==n)throw Error(`layer "${e}" has ${t} cells, but the map has ${n}`);let r=new Y,i=[];for(let e=0;e<this.chunkColumns*this.chunkRows;e++){let e=new Y;i.push(e),r.addChild(e)}return{cells:n,container:r,chunks:i}}addAutotileLayer(e,t,n){let r=Array.isArray(n)?n:[n];if(r.length===0)throw Error(`autotile layer "${e}" needs at least one set`);let{cells:i,container:a,chunks:o}=this.beginLayer(e,t.length),s=r.map((t,n)=>this.resolveAutotileSet(e,t,n)),c=new Set;for(let t of s){let n=t.layout.format===`rpgm-mv`?`slot ${t.layout.slot}`:`autotile ${t.layout.index}`;if(c.has(n))throw Error(`autotile layer "${e}" has two sets for ${n}`);c.add(n)}let l=0;r.forEach((t,n)=>{let r=t.animationFrame??0;if(!Number.isInteger(r)||r<0)throw Error(`autotile layer "${e}" set ${n} starts at an invalid animation frame, got ${t.animationFrame}`);if(n===0)l=r;else if(r!==l)throw Error(`autotile layer "${e}" sets disagree on their initial animation frame (${l} vs ${r})`)});let u=Int32Array.from(t);for(let t=0;t<i;t++)u[t]>0&&this.claimAutotileSets(s,e,u[t]);let d={kind:`autotile`,name:e,data:u,sprites:Array(i).fill(null),container:a,sets:s,frame:l};this.layers.push(d),this.layersByName.set(e,d),this.chunks.push(o),this.addChild(a);let f=this.layers.length===1;for(let t=0;t<this.heightInTiles;t++)for(let n=0;n<this.widthInTiles;n++){let r=this.index(n,t),i=u[r];i<=0||(d.sprites[r]=this.makeAutotileSprites(d,this.claimAutotileSets(s,e,i),n,t,i),f&&this.syncFaces(n,t))}return this}setAutotileFrame(e,t){let n=this.layerAt(e);if(n.kind!==`autotile`)throw Error(`layer "${n.name}" is not an autotile layer`);if(!Number.isInteger(t)||t<0)throw Error(`an autotile animation frame must be an integer at or above zero, got ${t}`);if(n.frame!==t){n.frame=t;for(let e=0;e<this.heightInTiles;e++)for(let r=0;r<this.widthInTiles;r++){let i=this.index(r,e),a=n.data[i];if(a<=0)continue;let o=this.claimAutotileSets(n.sets,n.name,a),s=this.autotilePieces(o,a,t),c=n.sprites[i];if(c)for(let e=0;e<c.length;e++)c[e].texture=s.textures[e]}}}addShadowLayer(e,t,n={}){let{cells:r,container:i,chunks:a}=this.beginLayer(e,t.length),o=n.color??0,s=n.alpha??.5;if(!Number.isFinite(s)||s<0||s>1)throw Error(`shadow layer "${e}" alpha must be between 0 and 1, got ${n.alpha}`);let c=Int32Array.from(t,e=>e>0?e&15:0),l={kind:`shadow`,name:e,data:c,sprites:Array(r).fill(null),container:i,color:o,alpha:s};this.layers.push(l),this.layersByName.set(e,l),this.chunks.push(a),this.addChild(i);for(let e=0;e<this.heightInTiles;e++)for(let t=0;t<this.widthInTiles;t++)c[this.index(t,e)]>0&&this.buildShadowSprites(l,t,e);return this}buildShadowSprites(e,t,n){let r=this.index(t,n),i=this.cellOrigin(t,n),a=this.cellHeight[r]*this.heightStep,o=this.tileWidth/2,s=this.tileHeight/2,c=this.chunks[this.layers.indexOf(e)][this.chunkIndex(t,n)],l=[];for(let t=0;t<4;t++){if(!(e.data[r]&1<<t))continue;let n=new Zj(J.WHITE);n.x=i.x+t%2*o,n.y=i.y-a+Math.floor(t/2)*s,n.width=o,n.height=s,n.tint=e.color,n.alpha=e.alpha,c.addChild(n),l.push(n)}e.sprites[r]=l}setShadowCell(e,t,n,r){let i=this.index(t,n);e.data[i]=r>0?r&15:0;for(let t of e.sprites[i]??[])t.destroy();e.sprites[i]=null,e.data[i]>0&&this.buildShadowSprites(e,t,n)}getAutotileFrame(e){let t=this.layerAt(e);if(t.kind!==`autotile`)throw Error(`layer "${t.name}" is not an autotile layer`);return t.frame}resolveAutotileSet(e,t,n){let r=`autotile layer "${e}" set ${n}`;if(!t||!t.sheet)throw Error(`${r} needs a source sheet`);let i=t.format??`rpgm-mv`;if(i!==`rpgm-mv`&&i!==`rpgm-xp`)throw Error(`${r} has an unknown format "${t.format}"`);return i===`rpgm-mv`?this.resolveRpgmSet(r,t):this.resolveXpSet(r,t)}resolveRpgmSet(e,t){if(t.slot===void 0)throw Error(`${e} needs a slot (0-3) for its MV sheet`);if(t.mode!==void 0&&t.mode!==`floor`&&t.mode!==`wall`&&t.mode!==`mixed`)throw Error(`${e} has an unknown mode "${t.mode}"`);if(t.animation!==void 0&&!Array.isArray(t.animation))throw Error(`${e} animation must list kind runs, got ${typeof t.animation}`);let n=t.mode??(t.slot<2?`floor`:`wall`),r=n===`mixed`&&t.slot===3&&t.table===void 0,i={format:`rpgm-mv`,slot:t.slot,table:t.table??(n===`floor`||t.tableEdge||n===`mixed`&&t.slot<2?ON:kN),...r?{tableFor:e=>Math.floor(e/8)%2==0?ON:kN}:{},...t.tableEdge?{tableEdge:!0}:{},cycles:t.animation??[]};return FN(i),{sheet:t.sheet,layout:i,cache:new Map,claims:e=>DN(e)===t.slot}}resolveXpSet(e,t){let n=t.index??0,r=t.sheet.texture,i=r.height===32;if(r.height!==32&&r.height!==128)throw Error(`${e} is ${r.height}px tall - XP autotile images are 128px templates or 32px single-tile strips`);let a=i?32:96,o=t.frames??Math.max(1,Math.floor(r.width/a)),s={format:`rpgm-xp`,index:n,frames:o,single:i};if(FN(s),o>Math.floor(r.width/a))throw Error(`${e} asks for ${o} frames but its sheet fits ${Math.floor(r.width/a)}`);return{sheet:t.sheet,layout:s,cache:new Map,claims:e=>{let t=MN(e);return t!==null&&t.index===n}}}claimAutotileSets(e,t,n){for(let t of e)if(t.claims(n))return t;throw Error(`tile ${n} in autotile layer "${t}" matches none of its sets`)}autotilePieces(e,t,n){let r=`${t}:${n}`,i=e.cache.get(r);if(i)return i;let a=VN(e.layout,t,n),o={parts:a,textures:a.map(t=>new J({source:e.sheet.texture.source,frame:new K(t.sourceX,t.sourceY,t.sourceWidth,t.sourceHeight)}))};return e.cache.set(r,o),o}makeAutotileSprites(e,t,n,r,i){let a=this.index(n,r),o=this.autotilePieces(t,i,e.frame),s=this.cellOrigin(n,r),c=this.cellHeight[a]*this.heightStep,l=o.textures.map((e,t)=>{let n=o.parts[t],r=new Zj(e);return r.x=s.x+n.destX*this.tileWidth,r.y=s.y-c+n.destY*this.tileHeight,r.scale.set(n.destWidth*this.tileWidth/n.sourceWidth,n.destHeight*this.tileHeight/n.sourceHeight),r.tint=this.cellTint[a],r.colorAdd=this.cellAdd[a],r}),u=this.chunks[this.layers.indexOf(e)][this.chunkIndex(n,r)];for(let e of l)u.addChild(e);return l}setAutotileCell(e,t,n,r){let i=this.index(t,n);e.data[i]=r;let a=e.sprites[i];if(r<=0){if(a)for(let e of a)e.destroy();e.sprites[i]=null;return}let o=this.claimAutotileSets(e.sets,e.name,r),s=this.autotilePieces(o,r,e.frame);if(a&&a.length===s.textures.length){for(let e=0;e<a.length;e++)a[e].texture=s.textures[e];return}if(a)for(let e of a)e.destroy();e.sprites[i]=this.makeAutotileSprites(e,o,t,n,r)}eachCellSprite(e,t,n){let r=e.sprites[t];if(r){if(Array.isArray(r))for(let e of r)n(e);else n(r)}}firstCellSprite(e,t){let n=e.sprites[t];return n?Array.isArray(n)?n[0]:n:null}layerAt(e){let t=typeof e==`number`?this.layers[e]:this.layersByName.get(e);if(!t)throw Error(`no such layer: ${e}`);return t}chunkIndex(e,t){return Math.floor(t/this.chunkSize)*this.chunkColumns+Math.floor(e/this.chunkSize)}projectedCenter(e,t){switch(this.shape){case`square`:return{x:(e+.5)*this.tileWidth,y:(t+.5)*this.tileHeight};case`hex`:return Qn(e,t,this.tileWidth,this.tileHeight);case`isometric`:return{x:(e-t+(this.heightInTiles-1))*(this.tileWidth/2)+this.tileWidth/2,y:(e+t)*(this.tileHeight/2)+this.tileHeight/2};case`staggered`:return{x:e*this.tileWidth+(t&1)*(this.tileWidth/2)+this.tileWidth/2,y:t*(this.tileHeight/2)+this.tileHeight/2}}}projectedTile(e,t){switch(this.shape){case`square`:return{x:Math.floor(e/this.tileWidth),y:Math.floor(t/this.tileHeight)};case`hex`:return $n(e,t,this.tileWidth,this.tileHeight);case`isometric`:{let n=(e-this.tileWidth/2)/(this.tileWidth/2)-(this.heightInTiles-1),r=(t-this.tileHeight/2)/(this.tileHeight/2);return{x:Math.round((n+r)/2),y:Math.round((r-n)/2)}}case`staggered`:{let n=Math.round((t-this.tileHeight/2)/(this.tileHeight/2));return{x:Math.round((e-this.tileWidth/2-(n&1)*(this.tileWidth/2))/this.tileWidth),y:n}}}}cellOrigin(e,t){let n=this.projectedCenter(e,t);return{x:n.x-this.tileWidth/2,y:n.y-this.tileHeight/2}}textureFor(e){let t=ZN(e);if(t>=this.sheets.length)throw Error(`frame ${e} names sheet ${t}, but this map has ${this.sheets.length}`);return this.sheets[t].get(QN(e))}buildSprite(e,t,n,r){let i=new Zj(this.textureFor(r)),a=this.cellOrigin(t,n);i.x=a.x,i.y=a.y-this.cellHeight[this.index(t,n)]*this.heightStep;let o=this.index(t,n);return i.tint=this.cellTint[o],i.colorAdd=this.cellAdd[o],e.sprites[o]=i,this.chunks[this.layers.indexOf(e)][this.chunkIndex(t,n)].addChild(i),i}getTile(e,t,n){return this.inside(t,n)?this.layerAt(e).data[this.index(t,n)]:-1}setTile(e,t,n,r){if(!this.inside(t,n))return;let i=this.layerAt(e),a=this.index(t,n);if(i.data[a]!==r){if(i.kind===`autotile`)this.setAutotileCell(i,t,n,r);else if(i.kind===`shadow`)this.setShadowCell(i,t,n,r);else{i.data[a]=r;let e=i.sprites[a];r===-1?(e?.destroy(),i.sprites[a]=null):e?e.texture=this.textureFor(r):this.buildSprite(i,t,n,r)}this.layers[0]===i&&this.syncFaces(t,n)}}setLayerData(e,t){this.layerAt(e);for(let n=0;n<this.heightInTiles;n++)for(let r=0;r<this.widthInTiles;r++)this.setTile(e,r,n,t[this.index(r,n)]??-1)}stampRect(e,t,n,r,i,a){if(this.layerAt(e),a.length!==r*i)throw Error(`a ${r}x${i} stamp needs ${r*i} frames, got ${a.length}`);if(t<0||n<0||t+r>this.widthInTiles||n+i>this.heightInTiles)throw Error(`a ${r}x${i} stamp at (${t},${n}) does not fit the ${this.widthInTiles}x${this.heightInTiles} map`);for(let o=0;o<i;o++)for(let i=0;i<r;i++)this.setTile(e,t+i,n+o,a[o*r+i])}setCellColor(e,t,n,r=0){if(!this.inside(e,t))return;let i=this.index(e,t);if(this.cellTint[i]===n&&this.cellAdd[i]===r)return;this.cellTint[i]=n,this.cellAdd[i]=r;for(let e of this.layers)e.kind!==`shadow`&&this.eachCellSprite(e,i,e=>{e.tint=n,e.colorAdd=r});let a=this.faces[i];a&&(a.tint=n)}getCellTint(e,t){return this.inside(e,t)?this.cellTint[this.index(e,t)]:0}clearColors(){for(let e=0;e<this.heightInTiles;e++)for(let t=0;t<this.widthInTiles;t++)this.setCellColor(t,e,16777215,0)}setCellHeight(e,t,n){if(!this.inside(e,t))return;if(!Number.isInteger(n))throw Error(`a cell's height must be a whole number, got ${n}`);let r=this.index(e,t);if(this.cellHeight[r]===n)return;let i=(n-this.cellHeight[r])*this.heightStep;this.cellHeight[r]=n;for(let e of this.layers)this.eachCellSprite(e,r,e=>{e.y-=i});this.syncFaces(e,t)}getCellHeight(e,t){return this.inside(e,t)?this.cellHeight[this.index(e,t)]:0}get faceCount(){return this.faces.filter(e=>e!==null).length}syncFaces(e,t){if(this.layers.length===0)return;let n=this.index(e,t),r=(this.shape===`isometric`||this.shape===`staggered`)&&this.cellHeight[n]>0&&this.layers[0].data[n]!==-1,i=this.faces[n];if(!r){i&&(i.destroy(),this.faces[n]=null);return}let a=i??new bE;if(this.drawFaces(a,e,t),a.tint=this.cellTint[n],!i){this.faces[n]=a;let r=this.chunks[0][this.chunkIndex(e,t)],i=this.firstCellSprite(this.layers[0],n);i?r.addChildAt(a,r.getChildIndex(i)):r.addChild(a)}}drawFaces(e,t,n){let r=this.cellOrigin(t,n),i=r.x,a=r.y,o=this.tileWidth/2,s=this.tileHeight/2,c=this.heightStep,l=this.cellHeight[this.index(t,n)];e.clear();for(let t=1;t<=l;t++){let n=t*c,r=(t-1)*c;e.poly([i,a+s-n,i+o,a+s*2-n,i+o,a+s*2-r,i,a+s-r]).fill(JN),e.poly([i+o,a+s*2-n,i+o*2,a+s-n,i+o*2,a+s-r,i+o,a+s*2-r]).fill(YN)}}toTile(e,t){return this.projectedTile(e,t)}tileCenter(e,t){let n=this.projectedCenter(e,t);return n.y-=this.getCellHeight(e,t)*this.heightStep,n}cull(e){let t=e.view,n=this.projectedTile(t.x,t.y),r=this.projectedTile(t.x+t.width,t.y),i=this.projectedTile(t.x,t.y+t.height),a=this.projectedTile(t.x+t.width,t.y+t.height),o=Math.min(n.x,r.x,i.x,a.x),s=Math.max(n.x,r.x,i.x,a.x),c=Math.min(n.y,r.y,i.y,a.y),l=Math.max(n.y,r.y,i.y,a.y),u=Math.floor(o/this.chunkSize)-1,d=Math.floor(s/this.chunkSize)+1,f=Math.floor(c/this.chunkSize)-1,p=Math.floor(l/this.chunkSize)+1;for(let e=0;e<this.chunkRows;e++){let t=e>=f&&e<=p;for(let n=0;n<this.chunkColumns;n++){let r=t&&n>=u&&n<=d,i=e*this.chunkColumns+n;for(let e of this.chunks)e[i].renderable=r}}}get visibleChunks(){return this.chunks.length===0?0:this.chunks[0].filter(e=>e.renderable).length}},eP=class extends Y{constructor(...e){super(...e),this.layers=new Map}addLayer(e,t,n=0){this.removeLayer(e);let r=new Zj(t);return this.layers.set(e,{sprite:r,order:n}),this.addChild(r),this.resort(),r}removeLayer(e){let t=this.layers.get(e);t&&(this.layers.delete(e),t.sprite.destroy())}layer(e){return this.layers.get(e)?.sprite}hasLayer(e){return this.layers.has(e)}setTexture(e,t){let n=this.layers.get(e);n&&(n.sprite.texture=t)}resort(){[...this.layers.values()].sort((e,t)=>e.order-t.order).forEach((e,t)=>this.setChildIndex(e.sprite,t))}},tP=class{constructor(e,t,n,r={}){this.elapsed=0,this.arrived=!1,this.sprite=e,this.fromX=t.x,this.fromY=t.y,this.toX=n.x,this.toY=n.y,this.animation=r.animation;let i=Math.hypot(n.x-t.x,n.y-t.y);this.duration=r.duration??i/(r.speed??400),this.duration<=0&&(this.duration=1e-6),e.x=t.x,e.y=t.y}get done(){return this.arrived}get progress(){return Math.min(1,this.elapsed/this.duration)}get frame(){return this.animation?.frameAt(this.elapsed)}get frameOffset(){let e=this.frame;return{x:e?.offsetX??0,y:e?.offsetY??0}}update(e){if(this.arrived)return!1;this.elapsed+=e;let t=this.progress;return this.sprite.x=this.fromX+(this.toX-this.fromX)*t,this.sprite.y=this.fromY+(this.toY-this.fromY)*t,t>=1&&(this.arrived=!0,!0)}};function nP(e){return e===!0||e===`progress`?`progress`:typeof e==`number`&&e>0?`seconds`:`none`}var rP=class extends Y{constructor(...e){super(...e),this.live=[]}add(e,t,n,r={}){let i,a;e instanceof J?(a=new xl(e),this.addChild(a),i=a):i=e,r.tint!==void 0&&typeof i.tint==`number`&&(i.tint=r.tint);let o=nP(r.fadeIn),s=typeof r.fadeIn==`number`?r.fadeIn:0,c=typeof i.alpha==`number`?i.alpha:1;o!==`none`&&(i.alpha=0);let l={projectile:new tP(i,t,n,r),sprite:i,built:a,onArrive:r.onArrive,spin:r.spin??(r.spinDegrees===void 0?void 0:r.spinDegrees*Math.PI/180),fadeMode:o,fadeIn:s,baseAlpha:c,elapsed:0};return this.live.push(l),{projectile:l.projectile,get done(){return l.projectile.done},cancel:()=>{let e=this.live.indexOf(l);e!==-1&&(this.live.splice(e,1),this.release(l))}}}update(e){for(let t=this.live.length-1;t>=0;t--){let n=this.live[t];n.elapsed+=e,n.spin!==void 0&&(n.sprite.rotation=(n.sprite.rotation??0)+n.spin*e),n.fadeMode===`seconds`&&(n.sprite.alpha=n.baseAlpha*Math.min(1,n.elapsed/n.fadeIn));let r=n.projectile.update(e);n.fadeMode===`progress`&&(n.sprite.alpha=n.baseAlpha*n.projectile.progress),r&&(this.live.splice(t,1),this.release(n),n.onArrive?.())}}get count(){return this.live.length}clear(){for(let e of this.live.splice(0))this.release(e)}destroy(){this.clear(),super.destroy()}release(e){e.built&&(this.removeChild(e.built),e.built.destroy())}},iP=class extends Y{constructor(e,t,n={}){super(),this.elapsed=0,this.expired=!1,this.lifeFraction=1,this.from={...e},this.to={...t},this.colour=n.colour??16777215,this.thin=n.thin??!1;let r=n.texture;if(r===void 0?(this.texture=void 0,this.stretch=!1,this.textureAnchor=0):r instanceof J?(this.texture=r,this.stretch=!1,this.textureAnchor=0):(this.texture=r.source,this.stretch=r.stretch??!1,this.textureAnchor=r.anchor??.5),this.thickness=n.width??2,this.duration=Math.max(1e-6,n.duration??.2),this.texture&&this.stretch)this.body=new xl(this.texture),this.body.anchor.set(0,this.textureAnchor);else if(this.texture){let e=new iA({texture:this.texture,width:1,height:this.thickness});e.anchor.set(0,this.textureAnchor),this.body=e}else this.body=new bE;(n.additive??!0)&&(this.body.blendMode=`add`),this.addChild(this.body),this.redraw()}get progress(){return Math.min(1,this.elapsed/this.duration)}get done(){return this.expired}retarget(e,t){e&&(this.from={...e}),t&&(this.to={...t}),this.redraw()}update(e){return!this.expired&&(this.elapsed+=e,this.alpha=1-this.progress,this.lifeFraction=this.thin?1-this.progress:1,this.thin&&this.redraw(),this.elapsed>=this.duration&&(this.expired=!0,!0))}destroy(){this.removeChild(this.body),this.body.destroy(),super.destroy()}redraw(){let e=this.to.x-this.from.x,t=this.to.y-this.from.y,n=Math.hypot(e,t);if(this.position.set(this.from.x,this.from.y),this.rotation=n>0?Math.atan2(t,e):0,this.body instanceof iA)this.body.width=n,this.body.height=this.thickness*this.lifeFraction;else if(this.body instanceof xl){let e=this.texture?.width||1,t=this.texture?.height||1;this.body.scale.x=n/e,this.body.scale.y=this.thickness/t*this.lifeFraction}else{let e=this.body;e.clear(),e.moveTo(0,0),e.lineTo(n,0),e.stroke({width:this.thickness*this.lifeFraction,color:this.colour})}}},aP=class extends Y{constructor(...e){super(...e),this.live=[]}add(e,t,n){let r=new iP(e,t,n);return this.addChild(r),this.live.push(r),r}update(e){for(let t=this.live.length-1;t>=0;t--)if(this.live[t].update(e)){let[e]=this.live.splice(t,1);this.removeChild(e),e.destroy()}}get count(){return this.live.length}clear(){for(let e of this.live.splice(0))this.removeChild(e),e.destroy()}destroy(){this.clear(),super.destroy()}},oP=class{constructor(e,t,n={}){this.elapsed=0,this.sinceFlicker=0,this.expired=!1,this.current=[],this.from={...e},this.to={...t},this.segments=Math.max(0,Math.floor(n.segments??6)),this.jitter=n.jitter??12,this.flickerInterval=n.flickerInterval,this.random=n.random??Math.random,this.duration=n.duration,this.reroll()}get points(){return this.current}get done(){return this.expired}retarget(e,t){e&&(this.from={...e}),t&&(this.to={...t}),this.flickerInterval===void 0&&this.reroll()}update(e){return!this.expired&&(this.elapsed+=e,this.flickerInterval!==void 0&&(this.sinceFlicker+=e,this.sinceFlicker>=this.flickerInterval&&(this.sinceFlicker=0,this.reroll())),this.duration!==void 0&&this.elapsed>=this.duration&&(this.expired=!0,!0))}reroll(){let e=this.to.x-this.from.x,t=this.to.y-this.from.y,n=Math.hypot(e,t),r=n>0?-t/n:0,i=n>0?e/n:0,a=[{...this.from}],o=this.segments+1;for(let n=1;n<o;n+=1){let s=n/o,c=Math.sin(Math.PI*s),l=(this.random()*2-1)*this.jitter*c;a.push({x:this.from.x+e*s+r*l,y:this.from.y+t*s+i*l})}a.push({...this.to}),this.current=a}},sP=class{constructor(e,t={}){this.elapsed=0,this.expired=!1,this.child=e,this.offsetX=t.offsetX??0,this.offsetY=t.offsetY??0,this.duration=t.duration}get done(){return this.expired}follow(e,t){return this.child.x=e+this.offsetX,this.child.y=t+this.offsetY,this}update(e){return this.expired||this.duration===void 0?!1:(this.elapsed+=e,this.elapsed>=this.duration&&(this.expired=!0,!0))}},cP=class extends Y{constructor(e){super(),this.cells=new Map,this.ripples=[],this.offset=0,this.eventMode=`none`,this.columns=e.width,this.tileSize=e.tileSize??16,this.speed=e.speed??5,this.rippleTexture=e.rippleTexture,this.rippleDuration=e.rippleDuration??.5;for(let t=0;t<e.height;t++)for(let n=0;n<e.width;n++){if(!e.isLiquid(n,t))continue;let r=new iA({texture:e.texture,width:this.tileSize,height:this.tileSize});r.eventMode=`none`,r.position.set(n*this.tileSize,t*this.tileSize),r.tilePosition.set(-r.x,-r.y),r.visible=!1,this.cells.set(n+t*this.columns,r),this.addChild(r)}}setCellColor(e,t,n){let r=this.cells.get(e+t*this.columns);r&&(r.tint=n,r.visible=n!==0)}ripple(e,t){if(!this.rippleTexture||!this.cells.get(e+t*this.columns)?.visible)return;let n=new xl(this.rippleTexture);n.eventMode=`none`,n.anchor.set(.5),n.position.set((e+.5)*this.tileSize,(t+.5)*this.tileSize),n.scale.set(0),this.addChild(n),this.ripples.push({sprite:n,age:0})}get rippleCount(){return this.ripples.length}update(e){this.offset+=this.speed*e;for(let e of this.cells.values())e.visible&&(e.tilePosition.y=-e.y+this.offset);for(let t=this.ripples.length-1;t>=0;t--){let n=this.ripples[t];if(n.age+=e,n.age>=this.rippleDuration)n.sprite.destroy(),this.ripples.splice(t,1);else{let e=n.age/this.rippleDuration;n.sprite.scale.set(e),n.sprite.alpha=1-e}}}};function lP(e,t,n,r,i,a){let o=t*r;for(let s=0;s<n;s++)for(let n=0;n<t;n++){let t=i(n,s);for(let i=0;i<r;i++)for(let c=0;c<r;c++){let l=a[typeof t==`number`?t:t[i*r+c]??0]??[0,0,0,0];e.set(l,((s*r+i)*o+n*r+c)*4)}}}var uP=class extends xl{constructor(e){let t=e.resolution??2,n=document.createElement(`canvas`);n.width=e.width*t,n.height=e.height*t;let r=n.getContext(`2d`);if(!r)throw Error(`FogLayer needs a 2D canvas context`);super(J.from(n)),this.context=r,this.image=r.createImageData(n.width,n.height),this.columns=e.width,this.rows=e.height,this.cellResolution=t,this.palette=e.palette,this.texture.source.scaleMode=`linear`,this.scale.set((e.tileSize??16)/t),this.eventMode=`none`}setPalette(e){this.palette=e}refresh(e){lP(this.image.data,this.columns,this.rows,this.cellResolution,e,this.palette),this.context.putImageData(this.image,0,0),this.texture.source.update()}destroy(){super.destroy({texture:!0,textureSource:!0})}},dP=`halo`,fP=class extends AM{constructor(e){super(),this.offsetX=e.offsetX??0,this.offsetY=e.offsetY??0,this.blendMode=e.blendMode??`add`,this.add(dP,e.frames,e.animation),this.play(dP)}follow(e,t){return this.position.set(e+this.offsetX,t+this.offsetY),this}};_e();function pP(e){return typeof e==`number`?e:O(e[0],e[1])}function mP(e){if(typeof e==`number`)return e;let t=O(),n=n=>{let r=e[0]>>n&255,i=e[1]>>n&255;return Math.round(r+(i-r)*t)<<n};return n(16)|n(8)|n(0)}function hP(e){return typeof e==`function`?e:t=>e[0]+(e[1]-e[0])*t}var gP=class extends Y{constructor(e={}){super(),this.pool=[],this.sprites=[],this.emitting=!1,this.followTarget=null,this.followOffsetX=0,this.followOffsetY=0,this.followEnabled=null,this.followVisible=null,this.poolCursor=0,this.debt=0;let t=Math.max(1,Math.floor(e.max??200));this.rate=e.rate??0,this.life=e.life??[.4,.9],this.speed=e.speed??[20,60],this.angleRange=e.angle??[0,Math.PI*2],this.gravityX=e.gravity?.x??0,this.gravityY=e.gravity?.y??0,this.scaleOf=hP(e.scale??[1,1]),this.alphaOf=hP(e.alpha??[1,0]),this.flicker=Math.min(1,Math.max(0,e.flicker??0)),this.spin=e.spin??0,this.tintRange=e.tint??16777215,this.frames=e.frames,this.spawnArea=e.spawn??null;for(let n=0;n<t;n++){this.pool.push({x:0,y:0,vx:0,vy:0,age:0,life:0,rotation:0,spin:0,scale:1,alpha:1,tint:16777215,frame:0,active:!1});let t=this.frames?.[0]??e.texture;if(t){let n=new xl(t);n.anchor.set(.5),n.visible=!1,typeof e.tint==`number`&&(n.tint=e.tint),this.sprites.push(n),this.addChild(n)}}}start(){this.emitting=!0}stop(){this.emitting=!1,this.debt=0}attach(e,t={}){this.followTarget=e,this.followOffsetX=t.offsetX??0,this.followOffsetY=t.offsetY??0,this.followEnabled=t.enabled??null,this.followVisible=t.visible??null,this.syncFollow()}detach(){this.followTarget=null,this.followEnabled=null,this.followVisible!==null&&(this.visible=!0),this.followVisible=null,this.followOffsetX=0,this.followOffsetY=0}get attachedTo(){return this.followTarget}syncFollow(){let e=this.followTarget;if(!e)return;if(typeof e!=`function`&&e.destroyed){this.detach();return}let t=typeof e==`function`?e():e;this.x=t.x+this.followOffsetX,this.y=t.y+this.followOffsetY,this.followVisible!==null&&(this.visible=this.followVisible())}followEmissionAllowed(){return this.followEnabled?.()??!0}get isEmitting(){return this.emitting}get activeCount(){let e=0;for(let t of this.pool)t.active&&e++;return e}get particles(){return this.pool}burst(e){this.syncFollow();let t=0;for(let n=0;n<e&&this.spawn();n++)t++;return t}spawn(){let e=null;for(let t=0;t<this.pool.length;t++){let t=this.pool[this.poolCursor];if(this.poolCursor=(this.poolCursor+1)%this.pool.length,!t.active){e=t;break}}if(!e)return!1;let t=pP(this.angleRange),n=pP(this.speed),r=+!yr(),i=this.spawnOffset();return e.x=this.x+i.x,e.y=this.y+i.y,e.vx=Math.cos(t)*n*r,e.vy=Math.sin(t)*n*r,e.age=0,e.life=Math.max(1e-6,pP(this.life)),e.rotation=0,e.spin=pP(this.spin)*r,e.scale=this.scaleOf(0),e.alpha=this.alphaOf(0),e.tint=mP(this.tintRange),e.frame=0,e.active=!0,!0}spawnOffset(){let e=this.spawnArea;if(!e)return{x:0,y:0};let t=e.height??e.width;if(e.shape===`rect`)return{x:(O()-.5)*e.width,y:(O()-.5)*t};let n=Math.sqrt(O()),r=O()*Math.PI*2;return{x:Math.cos(r)*n*(e.width/2),y:Math.sin(r)*n*(t/2)}}update(e){if(this.syncFollow(),this.emitting&&this.rate>0&&this.followEmissionAllowed()){for(this.debt+=this.rate*e;this.debt>=1;)if(--this.debt,!this.spawn()){this.debt=0;break}}let t=yr();for(let n of this.pool){if(!n.active)continue;if(n.age+=e,n.age>=n.life){n.active=!1;continue}t?(n.vx=0,n.vy=0,n.spin=0):(n.vx+=this.gravityX*e,n.vy+=this.gravityY*e),n.x+=n.vx*e,n.y+=n.vy*e,n.rotation+=n.spin*e;let r=n.age/n.life;n.scale=this.scaleOf(r),n.alpha=this.alphaOf(r),this.flicker>0&&!t&&(n.scale*=1-this.flicker*O()),this.frames&&(n.frame=Math.min(this.frames.length-1,Math.floor(r*this.frames.length)))}this.draw()}draw(){if(this.sprites.length===0)return;let e=typeof this.tintRange!=`number`;for(let t=0;t<this.pool.length;t++){let n=this.pool[t],r=this.sprites[t];r.visible=n.active,n.active&&(r.x=n.x-this.x,r.y=n.y-this.y,r.rotation=n.rotation,r.alpha=n.alpha,r.scale.set(n.scale),e&&(r.tint=n.tint),this.frames&&(r.texture=this.frames[n.frame]??r.texture))}}clear(){for(let e of this.pool)e.active=!1;this.debt=0,this.draw()}},_P=class extends Y{constructor(e={}){super(),this.overlay=new bE,this.phase=`idle`,this.elapsed=0,this.duration=0,this.fromAlpha=0,this.toAlpha=0,this.queue=[],this.defaultColor=e.color??0,this.viewWidth=e.width??0,this.viewHeight=e.height??0,this.overlay.alpha=0,this.overlay.tint=this.defaultColor,this.addChild(this.overlay),this.redraw()}setViewport(e,t){this.viewWidth=e,this.viewHeight=t,this.redraw()}redraw(){this.overlay.clear(),this.viewWidth>0&&this.viewHeight>0&&this.overlay.rect(0,0,this.viewWidth,this.viewHeight).fill({color:16777215})}get isBusy(){return this.phase!==`idle`}get washAlpha(){return this.overlay.alpha}fadeOut(e,t){this.begin(`fadeOut`,e,this.overlay.alpha,1,t)}fadeIn(e,t){this.begin(`fadeIn`,e,this.overlay.alpha,0,t)}flash(e,t,n=1){this.begin(`flash`,e,0,n,t)}sequence(e){if(this.queue=e.slice(1),e.length===0){this.phase=`idle`;return}this.beginStep(e[0])}setTint(e,t){this.queue=[],this.phase=`idle`,this.elapsed=0,this.overlay.tint=e,this.overlay.alpha=Math.max(0,Math.min(1,t))}clear(){this.queue=[],this.phase=`idle`,this.elapsed=0,this.overlay.alpha=0,this.overlay.tint=this.defaultColor}beginStep(e){switch(e.kind){case`fadeOut`:return this.begin(`fadeOut`,e.duration,this.overlay.alpha,1,e.color);case`fadeIn`:return this.begin(`fadeIn`,e.duration,this.overlay.alpha,0,e.color);case`flash`:return this.begin(`flash`,e.duration,0,e.peak??1,e.color);case`hold`:return this.begin(`hold`,e.duration,this.overlay.alpha,this.overlay.alpha,e.color??this.overlay.tint)}}advance(){let e=this.queue.shift();return e?this.beginStep(e):(this.phase=`idle`,!0)}begin(e,t,n,r,i){return yr()&&(t=0),this.overlay.tint=i??this.defaultColor,this.fromAlpha=n,this.toAlpha=r,this.elapsed=0,this.duration=t,t>0?(this.phase=e,this.overlay.alpha=e===`flash`?0:n,!1):(this.overlay.alpha=e===`flash`?0:r,this.advance())}update(e){if(this.phase===`idle`)return!1;if(yr())return this.overlay.alpha=this.phase===`flash`?0:this.toAlpha,this.advance();this.elapsed+=e;let t=Math.min(1,this.elapsed/this.duration);if(this.phase===`flash`){let e=t<.5?wr.easeOutQuad(t*2):1-wr.easeInQuad((t-.5)*2);this.overlay.alpha=this.toAlpha*e}else{let e=wr.easeInOutQuad(t);this.overlay.alpha=this.fromAlpha+(this.toAlpha-this.fromAlpha)*e}return t>=1&&(this.overlay.alpha=this.phase===`flash`?0:this.toAlpha,this.advance())}},vP=class{constructor(e,t){this.idleOrMove=`idle`,this.inAction=!1,this.sprite=e,this.animationName=t.animationName,this.variant=t.variant??``,this.sprite.onFinish=()=>this.onSpriteFinish(),this.apply(this.idleOrMove)}get state(){return this.inAction?`action`:this.idleOrMove}get variantName(){return this.variant}setMoving(e,t){t!==void 0&&(this.variant=t),this.idleOrMove=e?`move`:`idle`,this.inAction||this.apply(this.idleOrMove)}playAction(e,t=!1){(!this.inAction||t)&&(e!==void 0&&(this.variant=e),this.inAction=!0,this.apply(`action`))}onSpriteFinish(){this.inAction&&(this.inAction=!1,this.apply(this.idleOrMove))}apply(e){let t=this.animationName(e,this.variant);this.sprite.has(t)&&this.sprite.play(t,e===`action`)}},yP=class{constructor(e,t){this.active=new Set,this.elapsed=0,this.flashColor=0,this.flashStrength=0,this.flashDuration=0,this.flashRemaining=0,this.target=e,this.styles=t.styles}set(e,t){t?this.active.add(e):this.active.delete(e)}has(e){return this.active.has(e)}flash(e,t,n){this.flashColor=e,this.flashStrength=t,this.flashDuration=Math.max(n,1e-6),this.flashRemaining=this.flashDuration}update(e){this.elapsed+=e,this.flashRemaining>0&&(this.flashRemaining=Math.max(0,this.flashRemaining-e));let t=0,n=0,r=0;for(let e of this.active){let i=this.styles[e];if(!i)continue;let a=i.strength??.5,o=i.pulseRate?a*(.5+.5*Math.sin(this.elapsed*i.pulseRate*Math.PI*2)):a;t+=(i.color>>16&255)/255*o,n+=(i.color>>8&255)/255*o,r+=(i.color&255)/255*o}if(this.flashRemaining>0){let e=this.flashRemaining/this.flashDuration,i=this.flashStrength*e;t+=(this.flashColor>>16&255)/255*i,n+=(this.flashColor>>8&255)/255*i,r+=(this.flashColor&255)/255*i}this.target.colorAdd=qj(Math.min(1,t),Math.min(1,n),Math.min(1,r))}},bP={scaleX:1,scaleY:1,dy:0,rotation:0,skewX:0},xP={done:Promise.resolve(),cancel(){}},SP=class{constructor(e,t={}){this.contributions=new Map,this.loops=new Set,this.nextId=0,this.flipX=!1,this.flipY=!1,this.destroyed=!1,this.target=e,this.tweener=t.tweener??new Tr,this.ownsTweener=t.tweener===void 0,this.intent=t.intent??`decorative`,this.rest={y:e.y,rotation:e.rotation,scaleX:e.scale.x,scaleY:e.scale.y,skewX:e.skew.x}}squash(e){let{amount:t,duration:n}=e;return this.run(n,e=>{let n=Math.sin(Math.PI*e)*t;return{scaleX:1+n,scaleY:1-n}})}hop(e){let{height:t,duration:n}=e;return this.run(n,e=>({dy:-Math.sin(Math.PI*e)*t}))}bob(e){let{amplitude:t,period:n,cycles:r}=e;return r===void 0?this.loop(e=>({dy:Math.sin(2*Math.PI*e/n)*t})):this.run(n*r,e=>({dy:Math.sin(2*Math.PI*r*e)*t}))}wobble(e){let{angle:t,duration:n}=e;return this.run(n,e=>({rotation:Math.sin(4*Math.PI*e)*(1-e)*t}))}spin(e){let{turns:t,duration:n}=e;return this.run(n,e=>({rotation:Math.PI*2*t*e}),wr.easeInOutQuad)}shear(e){let{amount:t,duration:n}=e;return this.run(n,e=>({skewX:Math.sin(Math.PI*e)*t}))}flip(e,t){return e===`x`?this.flipX=t??!this.flipX:this.flipY=t??!this.flipY,this.write(),e===`x`?this.flipX:this.flipY}update(e){this.ownsTweener&&this.tweener.update(e);for(let t of[...this.loops])t(e)}get isBusy(){return this.contributions.size>0}destroy(){this.destroyed=!0,this.contributions.clear(),this.loops.clear(),this.flipX=this.flipY=!1,this.write()}run(e,t,n=wr.linear){if(this.destroyed)return xP;let r=this.nextId++,i=()=>{this.contributions.delete(r),this.write()};return this.contributions.set(r,bP),{done:this.tweener.tween(e,e=>{this.contributions.has(r)&&(this.contributions.set(r,{...bP,...t(e)}),this.write())},{ease:n,intent:this.intent}).then(i),cancel:i}}loop(e){if(this.destroyed)return xP;let t=this.nextId++,n=0,r,i=new Promise(e=>r=e),a=r=>{n+=r;let i=yr()&&this.intent===`decorative`;this.contributions.set(t,i?bP:{...bP,...e(n)}),this.write()};return this.contributions.set(t,bP),this.loops.add(a),{done:i,cancel:()=>{this.loops.delete(a),this.contributions.delete(t),this.write(),r()}}}write(){let e=1,t=1,n=0,r=0,i=0;for(let a of this.contributions.values())e*=a.scaleX,t*=a.scaleY,n+=a.dy,r+=a.rotation,i+=a.skewX;let{rest:a,target:o}=this;o.y=a.y+n,o.rotation=a.rotation+r,o.scale.x=a.scaleX*e*(this.flipX?-1:1),o.scale.y=a.scaleY*t*(this.flipY?-1:1),o.skew.x=a.skewX+i}},CP=EP(),wP=new Map(CP.map((e,t)=>[TP(e),t]));function TP(e){let t=e.ne&&e.n&&e.e,n=e.se&&e.s&&e.e,r=e.sw&&e.s&&e.w,i=e.nw&&e.n&&e.w;return+!!e.n|(e.e?2:0)|(e.s?4:0)|(e.w?8:0)|(t?16:0)|(n?32:0)|(r?64:0)|(i?128:0)}function EP(){let e=new Set,t=[];for(let n=0;n<256;n++){let r={n:!!(n&1),e:!!(n&2),s:!!(n&4),w:!!(n&8),ne:!!(n&16),se:!!(n&32),sw:!!(n&64),nw:!!(n&128)},i=TP(r);e.has(i)||(e.add(i),t.push({mask:i,shape:{n:r.n,e:r.e,s:r.s,w:r.w,ne:r.ne&&r.n&&r.e,se:r.se&&r.s&&r.e,sw:r.sw&&r.s&&r.w,nw:r.nw&&r.n&&r.w}}))}return t.sort((e,t)=>e.mask-t.mask),t.map(e=>e.shape)}function DP(e){return wP.get(TP(e))}function OP(e,t,n,r){if(r.length!==CP.length)throw Error(`autotileFrames needs exactly ${CP.length} frames, got ${r.length}`);let i=new Int32Array(e*t);for(let a=0;a<t;a++)for(let t=0;t<e;t++){let o=a*e+t;if(!n(t,a)){i[o]=-1;continue}i[o]=r[DP({n:n(t,a-1),e:n(t+1,a),s:n(t,a+1),w:n(t-1,a),ne:n(t+1,a-1),se:n(t+1,a+1),sw:n(t-1,a+1),nw:n(t-1,a-1)})]}return i}_e();function kP(e,t,n,r){let i=n*4/r,a=e,o=t;for(let e=0;e<i;e+=1)[a,o]=[-o,a];return{dx:a||0,dy:o||0}}function AP(e,t,n,r){let i=n*6/r,a=e,o=t;for(let e=0;e<i;e+=1){let e=-a-o;[a,o]=[-o,-e]}return{dx:a||0,dy:o||0}}function jP(e,t){let n=t??new Set;return!(e.hasAll&&!e.hasAll.every(e=>n.has(e))||e.hasAny&&!e.hasAny.some(e=>n.has(e))||e.hasNone&&e.hasNone.some(e=>n.has(e)))}function MP(e,t,n,r,i=kP,a=0){let o=e.rotations??0;return e.conditions.every(e=>{let s=o>0?i(e.dx,e.dy,a,o):e;return jP(e,r(t+s.dx,n+s.dy))})}function NP(e,t,n,r,i={}){let a=i.rotate??kP,o=i.random??new j,s=[];for(let i=0;i<t;i+=1)for(let t=0;t<e;t+=1){let e=-1,c=[];for(let o of n){let n=o.rotations??0,s=n>0?n:1;for(let n=0;n<s;n+=1){if(!MP(o,t,i,r,a,n))continue;let s=o.conditions.length;s>e?(e=s,c=[{rule:o,rotationIndex:n}]):s===e&&c.push({rule:o,rotationIndex:n})}}if(c.length===0)continue;let l=c.length===1?c[0]:c[PP(c.map(e=>e.rule.probability??1),o)],u=l.rule.rotations??0;for(let e of l.rule.images){let n=u>0?a(e.dx??0,e.dy??0,l.rotationIndex,u):{dx:e.dx??0,dy:e.dy??0};s.push({x:t,y:i,ruleId:l.rule.id,image:e.image,dx:n.dx,dy:n.dy,layer:e.layer??0})}}return s}function PP(e,t){let n=e.reduce((e,t)=>e+Math.max(0,t),0);if(n<=0)return 0;let r=t.float()*n;for(let t=0;t<e.length;t+=1)if(r-=Math.max(0,e[t]),r<0)return t;return e.length-1}var FP=class extends Y{};function IP(e,t){let n={};for(let r of t){let t=new FP;t.label=r,e.addChild(t),n[r]=t}return n}var LP=class extends bE{},RP=class extends wA{},zP=class extends xl{},BP=class extends iA{},VP=yC,HP=class extends FP{constructor(e){super(),this.placements=e.placements,this.project=e.project,this.resolveImage=e.resolveImage??(e=>GM(e,J.EMPTY)),this.rebuild()}setPlacements(e){this.placements=e,this.rebuild()}rebuild(){for(let e of this.removeChildren())e.destroy();for(let e of[...this.placements].sort((e,t)=>e.layer-t.layer)){let t=this.project(e.x,e.y,e.dx,e.dy),n=new zP(this.resolveImage(e.image));n.x=t.x,n.y=t.y,this.addChild(n)}}},UP=[{workload:`sprites`,preferred:`PixiJS WebGL/WebGPU batcher`,fallback:`PixiJS WebGL`,reason:`high-volume textured 2D batches`},{workload:`ui`,preferred:`PixiJS display tree`,fallback:`PixiJS display tree`,reason:`themeable 2D layout and text`},{workload:`custom-shaders`,preferred:`backend-specific GLSL/WGSL only when profiled`,fallback:`PixiJS filters`,reason:`avoid maintaining paired shader sources without a measured gain`},{workload:`particles`,preferred:`PixiJS for 2D, Babylon.js for 3D`,fallback:`instanced sprites/meshes`,reason:`match simulation and depth to the scene`},{workload:`instanced-terrain`,preferred:`Babylon.js thin instances`,fallback:`PixiJS TileMap for 2D`,reason:`depth-tested repeated 3D geometry`},{workload:`voxels`,preferred:`Babylon.js thin instances`,fallback:`batched meshes`,reason:`color-grouped 3D voxels`},{workload:`animated-models`,preferred:`Babylon.js glTF animation groups`,fallback:`billboard sprites`,reason:`standard 3D interchange and animation support`},{workload:`large-3d-worlds`,preferred:`Babylon.js with streaming/culling`,fallback:`partitioned scenes`,reason:`scene graph, depth, and instancing`}];function WP(e={}){let t=e.createCanvas?.()??(typeof document>`u`?null:document.createElement(`canvas`)),n=!!t?.getContext(`webgl2`);return{webgl1:n||!!(t?.getContext(`webgl`)??t?.getContext(`experimental-webgl`)),webgl2:n,webgpu:e.webgpu??!!globalThis.navigator?.gpu,wgsl:e.wgsl??!1}}async function GP(){let e=globalThis.navigator?.gpu;if(!e)return{webgpu:!1,wgsl:!1};try{let t=await(await e.requestAdapter())?.requestDevice();return t?{webgpu:!0,wgsl:(await t.createShaderModule({code:`@compute @workgroup_size(1) fn main() {}`}).getCompilationInfo()).messages.length===0}:{webgpu:!1,wgsl:!1}}catch{return{webgpu:!1,wgsl:!1}}}var KP=536870911,qP={orthogonal:`square`,isometric:`isometric`,staggered:`staggered`};function JP(e,t,n){if(e.frameWidth!==t.tilewidth||e.frameHeight!==t.tileheight)throw Error(`the tileset at firstgid ${n} is cut to ${e.frameWidth}x${e.frameHeight}, but the map is ${t.tilewidth}x${t.tileheight}`)}function YP(e,t,n){let r=-1;for(let n=0;n<t.length&&t[n]<=e;n++)r=n;if(r===-1)throw Error(`layer "${n}" uses gid ${e}, below every tileset's firstgid (${t.join(`, `)})`);return r}function XP(e,t){let n=e.orientation??`orthogonal`,r=qP[n];if(!r)throw Error(`loadTiledMap does not read "${n}" maps yet`);if(r===`staggered`&&(e.staggeraxis??`y`)!==`y`)throw Error(`loadTiledMap only reads Y-axis staggered maps right now, this one is staggered on "${e.staggeraxis}"`);if(r===`staggered`&&(e.staggerindex??`odd`)!==`odd`)throw Error(`loadTiledMap only reads odd-index staggered maps right now, this one staggers "${e.staggerindex}"`);if(e.tilesets.length===0)throw Error(`loadTiledMap needs at least one tileset, this map has none`);let i=[...e.tilesets].sort((e,t)=>e.firstgid-t.firstgid),a,o;if(t instanceof iN){if(e.tilesets.length!==1)throw Error(`loadTiledMap was given one sheet but this map has ${e.tilesets.length} tilesets - pass one sheet per tileset`);JP(t,e,i[0].firstgid),a=[t],o=[i[0].firstgid]}else{if(t.length!==e.tilesets.length)throw Error(`loadTiledMap was given ${t.length} sheets but this map has ${e.tilesets.length} tilesets - pass one sheet per tileset`);a=i.map(n=>{let r=t.find(e=>e.firstgid===n.firstgid);if(!r)throw Error(`loadTiledMap was given no sheet for the tileset at firstgid ${n.firstgid}`);return JP(r.sheet,e,n.firstgid),r.sheet}),o=i.map(e=>e.firstgid)}let s=new $N({width:e.width,height:e.height,sheet:a,shape:r}),c=[];for(let t of e.layers)if(t.type===`tilelayer`){if(t.encoding&&t.encoding!==`csv`)throw Error(`layer "${t.name}" uses "${t.encoding}" encoding - export tile layers as CSV/plain, not compressed`);let e=(t.data??[]).map(e=>{let n=e&KP;if(n===0)return-1;let r=YP(n,o,t.name);return o.length===1?n-o[0]:XN(r,n-o[r])});s.addLayer(t.name,e)}else if(t.type===`objectgroup`)for(let n of t.objects??[])c.push({...n,tileX:Math.floor(n.x/e.tilewidth),tileY:Math.floor(n.y/e.tileheight)});return{map:s,objects:c}}var ZP={panelBorder:4,padding:8,spacing:2,direction:`ltr`,font:{family:`ui-monospace, Consolas, "DejaVu Sans Mono", monospace`,size:12,lineHeight:1.4},color:{text:15263984,textDim:9079446,textHighlight:16770688,panelFill:1842214,panelBorder:4868702,selection:3820154,overlay:0},overlayAlpha:.5},QP={panelBorder:6,padding:10,spacing:4,direction:`ltr`,font:{family:ZP.font.family,size:14,lineHeight:1.5},color:{text:16777215,textDim:13421772,textHighlight:16776960,panelFill:0,panelBorder:16777215,selection:16776960,overlay:0},overlayAlpha:.85},$P=ZP;function Q(){return $P}var $=new p;function eF(e){$P={...ZP,...e,font:{...ZP.font,...e.font},color:{...ZP.color,...e.color}},$.dispatch($P)}function tF(e){return typeof e==`string`?{text:e}:e}function nF(e,t){return e.align??(t.direction===`rtl`?`right`:`left`)}function rF(e,t=40){let n=Math.max(0,e);return{total:n,speed:Math.max(0,t),revealed:t===0?n:0}}function iF(e,t){return e.revealed=Math.min(e.total,Math.max(0,e.revealed+e.speed*t)),oF(e)}function aF(e){e.revealed=e.total}function oF(e){return e.revealed>=e.total}var sF=class extends wA{constructor(e={}){let t=tF(e),n=Q();super({text:t.text??``,resolution:t.resolution,roundPixels:t.roundPixels,style:new tO({fontFamily:n.font.family,stroke:t.stroke,fontSize:t.size??n.font.size,fontWeight:t.bold?`bold`:`normal`,fill:t.color??n.color.text,lineHeight:(t.size??n.font.size)*n.font.lineHeight,align:nF(t,n),wordWrap:t.wrapWidth!==void 0,wordWrapWidth:t.wrapWidth??0,breakWords:!0})}),this.themeListener=e=>this.restyle(e),this.revealSource=null,this.reveal=null,this.opts=t,$.add(this.themeListener)}setColor(e){this.destroyed||(this.style.fill=e)}setText(e){this.destroyed||(this.revealSource=null,this.reveal=null,this.text!==e&&(this.text=e))}showProgressive(e,t){this.destroyed||(this.revealSource=e,this.reveal=rF(e.length,t),this.renderRevealed())}updateReveal(e){if(this.destroyed||!this.reveal)return!0;let t=iF(this.reveal,e);return this.renderRevealed(),t}completeReveal(){!this.destroyed&&this.reveal&&(aF(this.reveal),this.renderRevealed())}renderRevealed(){if(!this.reveal||this.revealSource===null)return;let e=this.revealSource.slice(0,Math.floor(this.reveal.revealed));this.text!==e&&(this.text=e)}restyle(e){this.destroyed||(this.style.fontFamily=e.font.family,this.opts.color===void 0&&(this.style.fill=e.color.text),this.opts.size===void 0&&(this.style.fontSize=e.font.size,this.style.lineHeight=e.font.size*e.font.lineHeight),this.opts.align===void 0&&(this.style.align=nF(this.opts,e)))}destroy(e){$.remove(this.themeListener),super.destroy(e)}},cF={positive:5627255,negative:16733525,warning:16757575};function lF(e,t){return t>0?e.slice(Math.max(0,e.length-Math.floor(t))):[]}function uF(e,t){let n=0;for(let t of e)n+=t;let r=0;for(;n>t&&r<e.length-1;)n-=e[r++];return r}var dF=class extends Y{constructor(e){super(),this.blocks=[],this.options=e,this.maxLines=e.maxLines??3}get entryCount(){return this.blocks.length}get contentHeight(){return this.blocks.reduce((e,t)=>e+t.label.height,0)}lastEntries(e){return lF(this.blocks.map(e=>({text:e.text,level:e.level})),e)}add(e,t=`info`){let n=new sF({text:e,size:this.options.size,color:this.colorOf(t),wrapWidth:this.options.wrapWidth,resolution:this.options.resolution});this.addChild(n),this.blocks.push({label:n,level:t,text:e}),this.trim(),this.layout()}setMaxLines(e){this.maxLines=Math.max(1,Math.floor(e)),this.trim(),this.layout()}setWrapWidth(e){this.options.wrapWidth=e;for(let t of this.blocks)t.label.style.wordWrapWidth=e;this.trim(),this.layout()}clear(){for(let e of this.blocks.splice(0))e.label.destroy()}colorOf(e){let t=this.options.colors?.[e];return t===void 0?e===`info`?Q().color.text:e===`highlight`?Q().color.textHighlight:cF[e]:t}linesOf(e){let t=Number(e.style.lineHeight)||Number(e.style.fontSize)||1;return Math.max(1,Math.round(e.height/t))}trim(){let e=uF(this.blocks.map(e=>this.linesOf(e.label)),this.maxLines);for(let t of this.blocks.splice(0,e))t.label.destroy()}layout(){let e=0;for(let t of this.blocks)t.label.position.set(0,e),e+=t.label.height}};function fF(e,t,n){let r=Math.max(1,Math.floor(e));for(;r>1&&t*r>n;)r--;return r}function pF(e){let t=1;for(let n=e;n;n=n.parent)t*=Math.abs(n.scale.x);return t}function mF(e,t){let n=(e,r)=>{if(e instanceof wA){let n=t*Math.max(1,Math.round(r));e.resolution!==n&&(e.resolution=n)}for(let t of e.children)n(t,r*Math.abs(t.scale.x))};n(e,pF(e))}var hF=``,gF=``,_F=``;function vF(e){let t=``;for(let n=0;n<e.length;n++)if(e[n]===`\\`&&n+1<e.length&&(e[n+1]===`*`||e[n+1]===`_`||e[n+1]===`\\`)){let r=e[n+1];t+=r===`*`?hF:r===`_`?gF:_F,n++}else t+=e[n];return t}function yF(e){return e.replaceAll(hF,`*`).replaceAll(gF,`_`).replaceAll(_F,`\\`)}function bF(e){return e!==void 0&&/[\p{L}\p{N}_]/u.test(e)}function xF(e,t,n){let r=[],i=0;for(;i<e.length;){if(e[i]!==t){i++;continue}let a=0;for(;e[i+a]===t;)a++;if(!(t===`_`&&bF(e[i-1])&&bF(e[i+a]))){if(n)for(let e=0;e<Math.floor(a/2);e++)r.push(i+e*2);else a%2==1&&r.push(i+a-1)}i+=a}return r}function SF(e,t,n,r,i,a){let o=xF(e,t,n),s=n?2:1;for(let e=0;e+1<o.length;e+=2){let t=o[e],n=o[e+1];i.push({from:t+s,to:n,style:r}),a.push({from:t,to:t+s},{from:n,to:n+s})}}function CF(e){let t=[];for(let n of e){if(!n.text)continue;let e=t[t.length-1];e&&e.bold===n.bold&&e.italic===n.italic?e.text+=n.text:t.push({...n})}return t}function wF(e){let t=vF(e),n=[],r=[];SF(t,`*`,!0,`bold`,n,r),SF(t,`_`,!0,`bold`,n,r),SF(t,`*`,!1,`italic`,n,r),SF(t,`_`,!1,`italic`,n,r);let i=new Set([0,t.length]);for(let e of n)i.add(e.from),i.add(e.to);for(let e of r)i.add(e.from),i.add(e.to);let a=[...i].sort((e,t)=>e-t),o=[];for(let e=0;e+1<a.length;e++){let i=a[e],s=a[e+1];i>=s||r.some(e=>e.from<=i&&s<=e.to)||o.push({text:t.slice(i,s),bold:n.some(e=>e.style===`bold`&&e.from<=i&&s<=e.to),italic:n.some(e=>e.style===`italic`&&e.from<=i&&s<=e.to)})}return CF(o).map(e=>({...e,text:yF(e.text)}))}function TF(e){return wF(e).map(e=>e.text).join(``)}function EF(e,t){let n=[],r=Math.max(0,Math.floor(t));for(let t of e){if(r<=0)break;let e=Math.min(t.text.length,r);n.push({...t,text:t.text.slice(0,e)}),r-=e}return n}var DF=class extends sj{constructor(e={}){let t=tF(e),n=Q(),r=t.tagStyles===void 0?[]:Object.keys(t.tagStyles);super({text:OF(t.text??``,r),resolution:t.resolution,style:new WA({fontFamily:n.font.family,fontSize:t.size??n.font.size,fontWeight:t.bold?`bold`:`normal`,fill:t.color??n.color.text,lineHeight:(t.size??n.font.size)*n.font.lineHeight,align:nF(t,n),wordWrap:t.wrapWidth!==void 0,wordWrapWidth:t.wrapWidth??0,breakWords:!0,tagStyles:t.tagStyles})}),this.themeListener=e=>this.restyle(e),this.revealSpans=null,this.reveal=null,this.opts=t,this.tags=r,$.add(this.themeListener)}setText(e){this.revealSpans=null,this.reveal=null;let t=OF(e,this.tags);this.text!==t&&(this.text=t)}showProgressive(e,t){this.revealSpans=wF(e),this.reveal=rF(TF(e).length,t),this.renderRevealed()}updateReveal(e){if(!this.reveal)return!0;let t=iF(this.reveal,e);return this.renderRevealed(),t}completeReveal(){this.reveal&&(aF(this.reveal),this.renderRevealed())}renderRevealed(){if(!this.reveal||!this.revealSpans)return;let e=kF(EF(this.revealSpans,this.reveal.revealed),this.tags);this.text!==e&&(this.text=e)}restyle(e){this.style.fontFamily=e.font.family,this.opts.color===void 0&&(this.style.fill=e.color.text),this.opts.size===void 0&&(this.style.fontSize=e.font.size,this.style.lineHeight=e.font.size*e.font.lineHeight),this.opts.align===void 0&&(this.style.align=nF(this.opts,e))}destroy(e){$.remove(this.themeListener),super.destroy(e)}};function OF(e,t){return kF(wF(e),t)}function kF(e,t){return e.map(e=>{let n=AF(e.text,t);return e.italic&&(n=`<i>${n}</i>`),e.bold&&(n=`<b>${n}</b>`),n}).join(``)}function AF(e,t){let n=e.replaceAll(`&`,`&amp;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`);for(let e of t)n=n.replaceAll(`&lt;${e}&gt;`,`<${e}>`).replaceAll(`&lt;/${e}&gt;`,`</${e}>`);return n}var jF=new Set([`b`,`i`,`span`,`br`,`img`]);function MF(e,t={}){let n=t.variables??{},r=t.tags,i=[],a=[],o={bold:!1,italic:!1},s=``,c=()=>{if(!s)return;let e={text:s,bold:o.bold,italic:o.italic};o.color!==void 0&&(e.color=o.color),o.size!==void 0&&(e.size=o.size),o.tag!==void 0&&(e.tag=o.tag),i.push(e),s=``};for(let t=0;t<e.length;t++){let l=e[t];if(l===`&`){let n=WF(e,t);if(n){s+=n.text,t=n.end;continue}}if(l===`$`){let r=GF(e,t),i=r?n[r.name]:void 0;if(r&&i!==void 0){s+=i,t=r.end;continue}}if(l===`<`){let n=HF(e,t);if(n&&(jF.has(n.name)||r?.has(n.name))){if(n.name===`img`){let r=UF(e,n);if(r){c(),i.push({text:``,bold:!1,italic:!1,image:r.src}),t=r.end;continue}}else if(n.name===`br`){s+=`
1370
+ `,t=n.end;continue}else if(n.closing){let e=a[a.length-1];if(e?.tag===n.name){c(),o=e.style,a.pop(),t=n.end;continue}}else{c(),a.push({tag:n.name,style:o}),o=BF(o,n.name,n.body),t=n.end;continue}}}s+=l}return c(),i}function NF(e,t={}){return MF(e,t).map(e=>e.image??e.text).join(``)}function PF(e){return e.map(e=>{if(e.image!==void 0)return``;let t=zF(e.text);e.italic&&(t=`<i>${t}</i>`),e.bold&&(t=`<b>${t}</b>`);let n=[e.color===void 0?void 0:`color:${e.color}`,e.size===void 0?void 0:`font-size:${e.size}px`].filter(e=>e!==void 0);return n.length>0&&(t=`<span style="${n.join(`;`)}">${t}</span>`),e.tag!==void 0&&(t=`<${e.tag}>${t}</${e.tag}>`),t}).join(``)}function FF(e,t={}){let n=t.describeImage??(()=>`[image]`);return e.map(e=>e.image===void 0?e.text:n(e.image)).join(``)}function IF(e,t,n){let r=[];for(let t of e){if(t.image!==void 0){r.push({...t});continue}t.text.split(`
1371
+ `).forEach((e,n)=>{n>0&&r.push({text:``,bold:t.bold,italic:t.italic,hardBreak:!0});for(let n of e.match(/\S+|\s+/g)??[])r.push({text:n,bold:t.bold,italic:t.italic,color:t.color,size:t.size,tag:t.tag})})}let i=[],a=[],o=0,s=()=>{for(;a.length>0&&a[a.length-1].text.trim()===``&&!a[a.length-1].image;)o-=t(a[a.length-1]),a.pop();i.push({spans:LF(a),width:Math.max(0,o)}),a=[],o=0};for(let e of r){if(e.hardBreak){s();continue}let r=t(e),i=e.image===void 0&&e.text.trim()===``;o>0&&!i&&o+r>n&&s(),a.push(e),o+=r}return(a.length>0||i.length===0)&&s(),i}function LF(e){let t=[];for(let n of e){let e=t[t.length-1];e&&n.image===void 0&&e.image===void 0&&e.bold===n.bold&&e.italic===n.italic&&e.color===n.color&&e.size===n.size&&e.tag===n.tag?e.text+=n.text:t.push({...n})}return t}function RF(e,t){let n=t.direction??`ltr`,r=t.align??(n===`rtl`?`right`:`left`),i=[];for(let a=0;a<e.length;a++){let o=e[a],s=a*t.lineHeight,c=o.spans.map(e=>t.measure(e)),l=c.reduce((e,t)=>e+t,0),u=r===`left`?0:r===`right`?t.maxWidth-l:(t.maxWidth-l)/2,d=n===`rtl`?u+l:u;for(let e=0;e<o.spans.length;e++){let t=c[e],r=n===`rtl`?d-t:d;d=n===`rtl`?d-t:d+t,i.push({span:o.spans[e],x:r,y:s,width:t})}}return i}function zF(e){return e.replaceAll(`&`,`&amp;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`).replaceAll(`"`,`&quot;`).replaceAll(`'`,`&#39;`)}function BF(e,t,n){if(t===`b`)return{...e,bold:!0};if(t===`i`)return{...e,italic:!0};if(t!==`span`)return{...e,tag:t};let r=VF(n,`color`),i=Number(VF(n,`size`)??``),a={...e};return r&&(a.color=r),Number.isFinite(i)&&i>0&&(a.size=i),a}function VF(e,t){let n=RegExp(`(?:^|\\s)${t}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s"'>]+))`).exec(e);return n?n[1]??n[2]??n[3]:void 0}function HF(e,t){let n=/^<(\/?)([a-zA-Z]+)([^>]*)>/.exec(e.slice(t));if(!n)return null;let r=n[3].trimEnd();return{name:n[2].toLowerCase(),closing:n[1]===`/`,selfClosing:r.endsWith(`/`)&&n[1]===``,body:r.replace(/\/$/,``).trim(),end:t+n[0].length-1}}function UF(e,t){if(t.selfClosing){let e=VF(t.body,`src`);return e?{src:e,end:t.end}:null}let n=e.indexOf(`</img>`,t.end+1);if(n<0)return null;let r=e.slice(t.end+1,n).trim();return r?{src:r,end:n+6-1}:null}function WF(e,t){let n={lt:`<`,gt:`>`,amp:`&`,quot:`"`,apos:`'`},r=/^&(lt|gt|amp|quot|apos);/.exec(e.slice(t));if(r)return{text:n[r[1]],end:t+r[0].length-1};let i=/^&#(\d+);/.exec(e.slice(t));return i?{text:String.fromCodePoint(Number(i[1])),end:t+i[0].length-1}:null}function GF(e,t){let n=/^\$([A-Za-z_][A-Za-z0-9_]*)/.exec(e.slice(t));return n?{name:n[1],end:t+n[0].length-1}:null}var KF=class extends Y{constructor(e={}){super(),this.themeListener=e=>this.rebuild(e),this.opts=e,this.rebuild(Q()),$.add(this.themeListener)}setText(e){this.opts.text=e,this.rebuild(Q())}rebuild(e){for(let e of this.removeChildren())e.destroy();let t=this.opts.lineHeight??e.font.size*e.font.lineHeight,n=this.opts.maxWidth??1/0,r=this.opts.maxWidth??0,i=this.opts.direction??e.direction,a=this.opts.resolveImage??(e=>GM(e,J.EMPTY)),o=JF(),s=n=>this.measurePiece(n,e,t,a,o),c=this.opts.tagStyles,l=RF(IF(MF(this.opts.text??``,{variables:this.opts.variables,tags:c===void 0?void 0:new Set(Object.keys(c))}),s,n),{measure:s,maxWidth:r,lineHeight:t,direction:i,align:this.opts.align??(this.opts.maxWidth===void 0?`left`:void 0)});for(let n of l){let r=n.span.image===void 0?this.textFor(n.span,e,t):this.spriteFor(n.span.image,t,a);r.x=n.x,r.y=n.y,this.addChild(r)}}measurePiece(e,t,n,r,i){if(e.image!==void 0)return ZF(r(e.image),n).width;let a=this.resolvedFont(e,t);return i?(i.font=`${a.italic?`italic `:``}${a.bold?`bold `:``}${a.size}px ${a.family}`,i.measureText(e.text).width):e.text.length*a.size}tagStyle(e){return e===void 0||this.opts.tagStyles===void 0?void 0:this.opts.tagStyles[e]}resolvedFont(e,t){let n=this.tagStyle(e.tag);return{family:typeof n?.fontFamily==`string`?n.fontFamily:t.font.family,size:typeof n?.fontSize==`number`?n.fontSize:e.size??t.font.size,bold:n?.fontWeight===void 0?e.bold:YF(n.fontWeight),italic:n?.fontStyle===void 0?e.italic:XF(n.fontStyle)}}textFor(e,t,n){let r=this.resolvedFont(e,t),i=this.tagStyle(e.tag);return new RP({text:e.text,resolution:this.opts.resolution,style:{fontFamily:r.family,fontSize:r.size,fontWeight:r.bold?`bold`:`normal`,fontStyle:r.italic?`italic`:`normal`,fill:e.color??t.color.text,lineHeight:n,...i}})}spriteFor(e,t,n){let r=n(e),i=ZF(r,t),a=new zP(r);return a.width=i.width,a.height=i.height,a}destroy(e){$.remove(this.themeListener),super.destroy(e)}},qF=null;function JF(){return typeof document>`u`?null:(qF??=document.createElement(`canvas`).getContext(`2d`),qF)}function YF(e){if(e===`bold`||e===`bolder`)return!0;if(e===`normal`||e===`lighter`)return!1;let t=Number(e);return Number.isFinite(t)&&t>=600}function XF(e){return e===`italic`||e===`oblique`}function ZF(e,t){return{width:(e.width>0?e.width:t)*(t/(e.height>0?e.height:t)),height:t}}var QF=class extends LA{constructor(e={}){let t=tF(e),n=Q();super({text:t.text??``,style:$F(t,n)}),this.themeListener=e=>this.restyle(e),this.opts=t,$.add(this.themeListener)}setText(e){this.text!==e&&(this.text=e)}restyle(e){this.style=$F(this.opts,e)}destroy(e){$.remove(this.themeListener),super.destroy(e)}};function $F(e,t){return{fontFamily:t.font.family,fontSize:e.size??t.font.size,fontWeight:e.bold?`bold`:`normal`,fill:e.color??t.color.text,align:nF(e,t),wordWrap:e.wrapWidth!==void 0,wordWrapWidth:e.wrapWidth??0,breakWords:!0}}var eI=class extends Y{constructor(e,t){super();let n=typeof t.border==`number`?{left:t.border,top:t.border,right:t.border,bottom:t.border}:t.border;this.sprite=new xj({texture:e,leftWidth:n.left,topHeight:n.top,rightWidth:n.right,bottomHeight:n.bottom}),this.addChild(this.sprite)}get border(){return{left:this.sprite.leftWidth,top:this.sprite.topHeight,right:this.sprite.rightWidth,bottom:this.sprite.bottomHeight}}resize(e,t){let n=this.border;this.sprite.width=Math.max(e,n.left+n.right),this.sprite.height=Math.max(t,n.top+n.bottom)}},tI=`position:absolute;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0;`,nI=class{constructor(){this.polite=null,this.assertive=null}region(e){if(typeof document>`u`||!document.body)return null;let t=e?this.assertive:this.polite;if(t)return t;let n=document.createElement(`div`);return n.setAttribute(`aria-live`,e?`assertive`:`polite`),n.setAttribute(`aria-atomic`,`true`),n.setAttribute(`role`,`status`),n.setAttribute(`style`,tI),document.body.appendChild(n),e?this.assertive=n:this.polite=n,n}announce(e,t={}){let n=this.region(t.assertive??!1);n&&(n.textContent=``,n.appendChild(document.createTextNode(e)))}clear(){this.polite&&(this.polite.textContent=``),this.assertive&&(this.assertive.textContent=``)}destroy(){this.polite?.remove(),this.assertive?.remove(),this.polite=null,this.assertive=null}},rI=new nI,iI=class extends Y{constructor(e){super(),this.content=new Y,this.onClose=new p,this.titleLabel=null,this.innerWidth=0,this.innerHeight=0,this.currentWidth=0,this.currentHeight=0,this.blocker=null,this.themeListener=()=>this.restyle(),this.isClosed=!1,this.delegate=null,this.onBlockerDown=e=>{e.stopPropagation();let t=e.getLocalPosition(this);this.handleOutsideClick(t.x,t.y)};let t=Q();this.modal=e.modal??!0,this.closable=e.closable??!0,this.dims=e.dims??this.modal,this.anchor=e.anchor??`center`,e.blocker===!0&&(this.blocker=new Y,this.blocker.eventMode=`static`,this.blocker.on(`pointerdown`,this.onBlockerDown),this.addChild(this.blocker)),this.background=t.panel?new eI(t.panel,{border:t.panelBorder}):new bE,this.addChild(this.background),e.title!==void 0&&(this.titleLabel=new sF({text:e.title,color:t.color.textHighlight,bold:!0}),this.addChild(this.titleLabel),rI.announce(e.title)),this.addChild(this.content),this.resize(e.width,e.height),$.add(this.themeListener)}restyle(){this.titleLabel?.setColor(Q().color.textHighlight),this.resize(this.currentWidth,this.currentHeight)}resize(e,t){this.currentWidth=e,this.currentHeight=t;let n=Q(),r=(this.background instanceof eI?this.background.border.left:2)+n.padding;this.background instanceof eI?this.background.resize(e,t):this.background.clear().roundRect(0,0,e,t,4).fill({color:n.color.panelFill}).stroke({color:n.color.panelBorder,width:1});let i=r;this.titleLabel&&(this.titleLabel.x=n.direction===`rtl`?e-r-this.titleLabel.width:r,this.titleLabel.y=r,i=r+this.titleLabel.height+n.padding),this.content.x=r,this.content.y=i,this.innerWidth=Math.max(0,e-r*2),this.innerHeight=Math.max(0,t-i-r)}get contentWidth(){return this.innerWidth}get contentHeight(){return this.innerHeight}setTitle(e){this.titleLabel?.setText(e)}handleAction(e){return this.isClosed?!1:this.delegate?.handleAction(e)?!0:e===`cancel`&&this.closable?(this.close(),!0):!1}get closed(){return this.isClosed}update(e){}close(){this.isClosed||(this.isClosed=!0,this.onClose.dispatch(),this.parent?.removeChild(this),this.destroy({children:!0}))}place(e,t){if(this.isClosed)return;let n=this.getLocalBounds(),r=Q().padding*2;this.x=Math.round((e-n.width)/2),this.y=this.anchor===`bottom`?Math.round(t-n.height-r):this.anchor===`top`?r:Math.round((t-n.height)/2),this.fitBlocker(e,t)}fitBlocker(e,t){this.blocker&&(this.blocker.hitArea=new K(-this.x,-this.y,e,t))}handleOutsideClick(e,t){return this.isClosed||e>=0&&t>=0&&e<this.currentWidth&&t<this.currentHeight||!this.closable?!1:(this.close(),!0)}destroy(e){this.isClosed=!0,$.remove(this.themeListener),super.destroy(e)}},aI=class extends Y{constructor(){super(),this.windows=[],this.overlay=new bE,this.viewportWidth=0,this.viewportHeight=0,this.listener=e=>this.handleAction(e),this.themeListener=()=>this.drawOverlay(),this.overlay.visible=!1,this.addChild(this.overlay),P.add(this.listener),$.add(this.themeListener)}setViewport(e,t){this.viewportWidth=e,this.viewportHeight=t,this.drawOverlay();for(let n of this.windows)n.place(e,t)}get top(){return this.windows[this.windows.length-1]??null}get isEmpty(){return this.windows.length===0}get depth(){return this.windows.length}push(e){if(e.closed)throw Error(`cannot open a window that was already closed`);return this.windows.push(e),this.addChild(e),e.onClose.add(()=>(this.forget(e),!1)),e.place(this.viewportWidth,this.viewportHeight),this.updateOverlay(),e}pop(){this.top?.close()}closeAll(){for(let e of[...this.windows].reverse())e.close()}forget(e){let t=this.windows.indexOf(e);t!==-1&&this.windows.splice(t,1),this.updateOverlay()}updateOverlay(){let e=this.windows.findIndex(e=>e.dims);if(e===-1){this.overlay.visible=!1;return}this.overlay.visible=!0,this.setChildIndex(this.overlay,Math.max(0,this.getChildIndex(this.windows[e])-1))}drawOverlay(){let e=Q();this.overlay.clear().rect(0,0,this.viewportWidth,this.viewportHeight).fill({color:e.color.overlay,alpha:e.overlayAlpha})}handleAction(e){return this.top?.handleAction(e)??!1}get blocksWorld(){return this.windows.some(e=>e.modal)}update(e){this.top?.update(e)}destroy(e){P.remove(this.listener),$.remove(this.themeListener),super.destroy(e)}},oI=class{constructor(e){this.list=[],this.current=0,this.hooks=e}get items(){return this.list}get selectedIndex(){return this.current}get selected(){return this.list[this.current]??null}get length(){return this.list.length}reset(e){this.list=e,this.current=e.findIndex(e=>!e.disabled),this.current===-1&&(this.current=0)}swap(e,t){[this.list[e],this.list[t]]=[this.list[t],this.list[e]]}land(e){this.current=e,this.hooks.onChange();let t=this.list[e];t&&this.hooks.onHighlight(t,e)}select(e){e<0||e>=this.list.length||this.list[e].disabled||this.land(e)}confirm(e){let t=this.selected;return!t||t.disabled?!1:(e?.(t,this.current),!0)}step(e,t){if(this.list.length===0)return!1;let n=this.current;for(let r=0;r<t;r++){let t=e(n,this.list.length);if(n=t,!(t<0||t>=this.list.length)&&!this.list[t].disabled)return this.land(t),!0}return!1}},sI=class extends Y{constructor(e){super(),this.selection=new oI({onChange:()=>this.refresh(),onHighlight:(e,t)=>this.onHighlight?.(e,t)}),this.rows=[],this.rowsLayer=new Y,this.highlight=new bE,this.mask_=new bE,this.scroll=0,this.themeListener=()=>this.restyle(),this.checked=new Set,this.ticks=[];let t=Q();this.viewWidth=e.width,this.viewHeight=e.height,this.explicitRowHeight=e.rowHeight!==void 0,this.rowHeight=e.rowHeight??Math.ceil(t.font.size*t.font.lineHeight)+t.spacing,this.onSelect=e.onSelect??null,this.onHighlight=e.onHighlight??null,this.onToggle=e.onToggle??null,this.multiple=e.multiple??!1,this.addChild(this.highlight),this.addChild(this.rowsLayer),this.addChild(this.mask_),this.rowsLayer.mask=this.mask_,this.drawMask(),this.eventMode=`static`,this.on(`wheel`,e=>this.move(e.deltaY>0?1:-1)),this.setItems(e.items??[]),$.add(this.themeListener)}restyle(){let e=Q();this.explicitRowHeight||(this.rowHeight=Math.ceil(e.font.size*e.font.lineHeight)+e.spacing);let t=e.direction===`rtl`,n=this.selection.items;this.rows.forEach((r,i)=>{r.y=i*this.rowHeight;let a=n[i],o=r.children.find(e=>e instanceof sF);if(o){o.setColor(a.disabled?e.color.textDim:e.color.text);let n=e.spacing+this.checkAdvance()+(a.icon?this.rowHeight:0);o.x=t?this.viewWidth-n-o.width:n,o.y=Math.round((this.rowHeight-o.height)/2)}a.icon&&(a.icon.x=t?this.viewWidth-e.spacing-this.checkAdvance()-this.rowHeight:e.spacing+this.checkAdvance())}),this.updateTicks(),this.refresh()}destroy(e){$.remove(this.themeListener),super.destroy(e)}drawMask(){this.mask_.clear().rect(0,0,this.viewWidth,this.viewHeight).fill({color:16777215})}get visibleRows(){return Math.max(1,Math.floor(this.viewHeight/this.rowHeight))}get selectedIndex(){return this.selection.selectedIndex}get selected(){return this.selection.selected}get length(){return this.selection.length}setItems(e){for(let e of this.rows)e.destroy({children:!0});this.rows=[],this.rowsLayer.removeChildren();let t=Q(),n=t.direction===`rtl`;e.forEach((e,r)=>{let i=new Y;i.y=r*this.rowHeight,i.eventMode=`static`,i.cursor=e.disabled?`default`:`pointer`,i.on(`pointerdown`,()=>this.tapRow(r)),e.icon&&(e.icon.x=n?this.viewWidth-t.spacing-this.checkAdvance()-this.rowHeight:t.spacing+this.checkAdvance(),i.addChild(e.icon));let a=new sF({text:e.text,color:e.disabled?t.color.textDim:t.color.text}),o=t.spacing+this.checkAdvance()+(e.icon?this.rowHeight:0);a.x=n?this.viewWidth-o-a.width:o,a.y=Math.round((this.rowHeight-a.height)/2),i.addChild(a),this.rows.push(i),this.rowsLayer.addChild(i)}),this.selection.reset(e),this.checked.clear(),this.rebuildTicks(),this.scroll=0,this.refresh()}resize(e,t){this.viewWidth=e,this.viewHeight=t,this.drawMask(),this.refresh()}move(e){return this.selection.step((t,n)=>(t+e+n)%n,this.selection.length)}select(e){this.selection.select(e)}confirm(){return this.multiple?this.toggleChecked(this.selection.selectedIndex):this.selection.confirm(this.onSelect)}tapRow(e){let t=this.selection.items;e<0||e>=t.length||t[e].disabled||(this.select(e),this.confirm())}handleAction(e){switch(e){case`up`:return this.move(-1);case`down`:return this.move(1);case`confirm`:return this.confirm();default:return!1}}get checkedIndexes(){return[...this.checked].sort((e,t)=>e-t)}isChecked(e){return this.checked.has(e)}setChecked(e,t){let n=this.selection.items[e];n&&!n.disabled&&this.checked.has(e)!==t&&(t?this.checked.add(e):this.checked.delete(e),this.updateTicks(),this.onToggle?.(n,e,t))}toggleChecked(e){let t=this.selection.items[e];return!t||t.disabled?!1:(this.setChecked(e,!this.checked.has(e)),!0)}clearChecked(){this.checked.size!==0&&(this.checked.clear(),this.updateTicks())}checkAdvance(){return this.multiple?this.checkBox()+Q().spacing:0}checkBox(){return Math.max(12,this.rowHeight-8)}rebuildTicks(){if(this.ticks=[],this.multiple){for(let e of this.rows){let t=new bE;e.addChildAt(t,0),this.ticks.push(t)}this.updateTicks()}}updateTicks(){let e=Q(),t=e.direction===`rtl`,n=this.checkBox(),r=Math.round((this.rowHeight-n)/2);this.ticks.forEach((i,a)=>{let o=this.selection.items[a]?.disabled??!0;if(i.clear().rect(0,0,n,n).fill({color:e.color.panelFill}).stroke({color:o?e.color.textDim:e.color.panelBorder,width:2}),this.checked.has(a)){let t=n*.25;i.moveTo(t,n*.55).lineTo(n*.45,n-t).lineTo(n-t,t).stroke({color:o?e.color.textDim:e.color.textHighlight,width:Math.max(2,n*.12),cap:`round`,join:`round`})}i.x=t?this.viewWidth-e.spacing-n:e.spacing,i.y=r})}refresh(){let e=this.visibleRows,t=this.selection.selectedIndex,n=this.selection.length;t<this.scroll?this.scroll=t:t>=this.scroll+e&&(this.scroll=t-e+1),this.scroll=Math.max(0,Math.min(this.scroll,Math.max(0,n-e))),this.rowsLayer.y=-this.scroll*this.rowHeight;let r=Q();if(n===0){this.highlight.clear();return}this.highlight.clear().rect(0,(t-this.scroll)*this.rowHeight,this.viewWidth,this.rowHeight).fill({color:r.color.selection})}},cI=class extends Y{columnX(e){return(Q().direction===`rtl`?this.columns-1-e:e)*this.cellSize}constructor(e){super(),this.selection=new oI({onChange:()=>this.refresh(),onHighlight:(e,t)=>this.onHighlight?.(e,t)}),this.cells=[],this.cellsLayer=new Y,this.highlight=new bE,this.pickupHighlight=new bE,this.mask_=new bE,this.scrollRow=0,this.pickedUp=null,this.pressedIndex=null,this.pressTimer=0,this.themeListener=()=>{let e=Q();this.selection.items.forEach((t,n)=>{let r=this.cells[n];r&&(r.x=this.columnX(n%this.columns),!((t.quantity??1)<=1)&&r.children.find(e=>e instanceof sF)?.setColor(e.color.textHighlight))}),this.refresh()},this.viewWidth=e.width,this.viewHeight=e.height,this.columns=Math.max(1,e.columns),this.cellSize=e.cellSize??Math.floor(this.viewWidth/this.columns),this.longPressDuration=e.longPressDuration??.6,this.onSelect=e.onSelect??null,this.onHighlight=e.onHighlight??null,this.onQuickslot=e.onQuickslot??null,this.onReorder=e.onReorder??null,this.addChild(this.highlight),this.addChild(this.pickupHighlight),this.addChild(this.cellsLayer),this.addChild(this.mask_),this.cellsLayer.mask=this.mask_,this.drawMask(),this.eventMode=`static`,this.on(`wheel`,e=>this.move(0,e.deltaY>0?1:-1)),this.setItems(e.items??[]),$.add(this.themeListener)}destroy(e){$.remove(this.themeListener),super.destroy(e)}drawMask(){this.mask_.clear().rect(0,0,this.viewWidth,this.viewHeight).fill({color:16777215})}get visibleRows(){return Math.max(1,Math.floor(this.viewHeight/this.cellSize))}get rows(){return Math.max(1,Math.ceil(this.selection.length/this.columns))}get selectedIndex(){return this.selection.selectedIndex}get selected(){return this.selection.selected}get length(){return this.selection.length}setItems(e){this.pickedUp=null,this.pressedIndex=null;for(let e of this.cells)e.destroy({children:!0});this.cells=[],this.cellsLayer.removeChildren();let t=Q();e.forEach((e,n)=>{let r=Math.floor(n/this.columns),i=n%this.columns,a=new Y;if(a.x=this.columnX(i),a.y=r*this.cellSize,a.eventMode=`static`,a.cursor=e.disabled?`default`:`pointer`,e.icon.x=Math.round((this.cellSize-e.icon.width)/2),e.icon.y=Math.round((this.cellSize-e.icon.height)/2),e.disabled&&(e.icon.alpha=.4),a.addChild(e.icon),(e.quantity??1)>1){let n=new sF({text:String(e.quantity),size:10,color:t.color.textHighlight});n.x=this.cellSize-n.width-2,n.y=this.cellSize-n.height-1,a.addChild(n)}a.on(`pointerdown`,()=>{this.pressedIndex=n,this.pressTimer=0}),a.on(`pointerup`,()=>this.releaseCell(n)),a.on(`pointerupoutside`,()=>this.releaseCell(n)),this.cells.push(a),this.cellsLayer.addChild(a)}),this.selection.reset(e),this.scrollRow=0,this.refresh()}releaseCell(e){this.pressedIndex===e&&(this.pressedIndex=null,this.selection.items[e]?.disabled||this.tapCell(e))}resize(e,t){this.viewWidth=e,this.viewHeight=t,this.drawMask(),this.refresh()}update(e){if(this.pressedIndex===null||(this.pressTimer+=e,this.pressTimer<this.longPressDuration))return;let t=this.pressedIndex;this.pressedIndex=null;let n=this.selection.items[t];n&&!n.disabled&&this.onQuickslot?.(n,t)}tapCell(e){let t=this.selection.items;if(e<0||e>=t.length)return;if(this.pickedUp===null){if(t[e].disabled)return;this.pickedUp=e,this.refresh();return}let n=this.pickedUp;this.pickedUp=null,n!==e&&(this.swapCells(n,e),this.onReorder?.(n,e)),this.refresh()}swapCells(e,t){let n=this.selection.items;this.selection.swap(e,t);let r=this.cells[e],i=this.cells[t],a=r.removeChildren(),o=i.removeChildren();for(let e of o)r.addChild(e);for(let e of a)i.addChild(e);r.cursor=n[e].disabled?`default`:`pointer`,i.cursor=n[t].disabled?`default`:`pointer`}cancelPickup(){this.pickedUp=null,this.refresh()}move(e,t){let n=this.rows,r=this.columns;return this.selection.step(i=>{let a=(Math.floor(i/r)+t+n)%n,o=(i%r+e+r)%r;return a*r+o},n*r)}select(e){this.selection.select(e)}confirm(){return this.selection.confirm(this.onSelect)}handleAction(e){switch(e){case`up`:return this.move(0,-1);case`down`:return this.move(0,1);case`left`:return this.move(Q().direction===`rtl`?1:-1,0);case`right`:return this.move(Q().direction===`rtl`?-1:1,0);case`confirm`:return this.confirm();case`cancel`:return this.pickedUp!==null&&(this.cancelPickup(),!0);default:return!1}}cellRect(e){return{x:this.columnX(e%this.columns),y:Math.floor(e/this.columns)*this.cellSize}}refresh(){let e=this.visibleRows,t=this.selection.selectedIndex,n=Math.floor(t/this.columns);n<this.scrollRow?this.scrollRow=n:n>=this.scrollRow+e&&(this.scrollRow=n-e+1),this.scrollRow=Math.max(0,Math.min(this.scrollRow,Math.max(0,this.rows-e))),this.cellsLayer.y=-this.scrollRow*this.cellSize;let r=Q();if(this.pickupHighlight.clear(),this.pickedUp!==null){let{x:e,y:t}=this.cellRect(this.pickedUp);this.pickupHighlight.rect(e,t,this.cellSize,this.cellSize).stroke({color:r.color.textHighlight,width:2})}if(this.highlight.clear(),this.selection.length>0){let{x:e,y:n}=this.cellRect(t);this.highlight.rect(e,n,this.cellSize,this.cellSize).fill({color:r.color.selection})}}},lI=class{constructor(e){if(this.onChange=new p,this.currentTabIndex=0,this.currentQuery=``,this.rows_=[],this.currentSelectedIndex=0,this.detail=!1,e.tabs.length===0)throw Error(`TabbedList needs at least one tab`);this.tabList=[...e.tabs],this.rowsFor=e.rowsFor,this.pageSize=Math.max(0,Math.floor(e.pageSize??0)),this.labelOf=e.label??(e=>String(e)),this.filterOf=e.filter??((e,t)=>t===``||this.labelOf(e).toLowerCase().includes(t.toLowerCase())),this.disabledOf=e.disabled??(()=>!1),this.recompute()}get tabs(){return this.tabList}get tab(){return this.tabList[this.currentTabIndex]}get query(){return this.currentQuery}get rows(){return this.rows_}get pageCount(){return this.pageSize<=0?1:Math.max(1,Math.ceil(this.rows_.length/this.pageSize))}get page(){return this.pageSize<=0?0:Math.floor(this.currentSelectedIndex/this.pageSize)}get pageRows(){if(this.pageSize<=0)return this.rows_;let e=this.page*this.pageSize;return this.rows_.slice(e,e+this.pageSize)}get selectedIndex(){return this.currentSelectedIndex}get selected(){return this.rows_[this.currentSelectedIndex]??null}get detailOpen(){return this.detail}selectTab(e){let t=this.tabList.findIndex(t=>t.id===e);t===-1||this.tabList[t].disabled||t!==this.currentTabIndex&&(this.currentTabIndex=t,this.recompute(),this.emit())}nextTab(e=1){if(e===0)return;let t=e>0?1:-1,n=this.currentTabIndex;for(let r=0;r<Math.abs(e);r++)do n=(n+t+this.tabList.length)%this.tabList.length;while(this.tabList[n].disabled&&n!==this.currentTabIndex);n!==this.currentTabIndex&&(this.currentTabIndex=n,this.recompute(),this.emit())}setQuery(e){e!==this.currentQuery&&(this.currentQuery=e,this.recompute(),this.emit())}move(e){if(e===0||this.rows_.length===0)return;let t=e>0?1:-1,n=this.currentSelectedIndex;for(let r=0;r<Math.abs(e);r++){let e=n;do e+=t;while(e>=0&&e<this.rows_.length&&this.disabledOf(this.rows_[e]));if(e<0||e>=this.rows_.length)break;n=e}n!==this.currentSelectedIndex&&(this.currentSelectedIndex=n,this.emit())}setPage(e){let t=Math.max(0,Math.min(this.pageCount-1,Math.floor(e)));if(this.pageSize<=0)return;let n=this.firstSelectableOnPage(t);n!==this.currentSelectedIndex&&(this.currentSelectedIndex=n,this.emit())}nextPage(e){this.setPage(this.page+e)}openDetail(){return this.selected===null||this.disabledOf(this.selected)?!1:(this.detail||(this.detail=!0,this.emit()),!0)}closeDetail(){this.detail&&(this.detail=!1,this.emit())}firstSelectableOnPage(e){let t=e*this.pageSize,n=Math.min(this.rows_.length,t+this.pageSize);for(let e=t;e<n;e++)if(!this.disabledOf(this.rows_[e]))return e;return Math.min(t,Math.max(0,this.rows_.length-1))}firstSelectable(e){for(let t=e;t<this.rows_.length;t++)if(!this.disabledOf(this.rows_[t]))return t;return 0}recompute(){let e=this.rowsFor(this.tab.id).filter(e=>this.filterOf(e,this.currentQuery));this.rows_=e,this.currentSelectedIndex=e.length===0?0:this.firstSelectable(0),this.detail=!1}emit(){this.onChange.dispatch()}};function uI(e,t,n={}){let r={},i=t.replace(/\r/g,``).split(`
1372
+ `),a=null,o=``,s=[],c=!1,l=()=>{if(a){if(r[a]!==void 0)throw Error(`Duplicate FTL message: ${a}`);if(s.length){if(!c)throw Error(`FTL select expression is not closed: ${a}`);let t=o.trim().match(/^\{\s*\$([\w-]+)\s*->\s*$/)?.[1];if(!t)throw Error(`Invalid FTL selector: ${o}`);r[a]=fI(e,t,s)}else r[a]=dI(o);a=null,o=``,s=[],c=!1}};for(let e of i){if(!e.trim()||e.trimStart().startsWith(`#`))continue;let t=e.match(/^([\w-]+)\s*=\s*(.*)$/);if(t){l(),a=t[1],o=t[2];continue}if(!a)throw Error(`FTL continuation has no message: ${e}`);if(e.trim()===`}`){if(!s.length||c)throw Error(`Unexpected FTL select terminator: ${e}`);c=!0;continue}if(c)throw Error(`FTL content follows a closed select expression: ${e}`);let n=e.match(/^\s*(\*)?\[([^\]]+)\]\s*(.*)$/);if(n){s.push({key:n[2],value:n[3],default:!!n[1]});continue}if(/^\s+/.test(e)){s.length?s[s.length-1].value+=` ${e.trim()}`:o+=` ${e.trim()}`;continue}throw Error(`Invalid FTL line: ${e}`)}return l(),{locale:e,direction:n.direction??(/^(ar|he|fa|ur)(?:-|$)/i.test(e)?`rtl`:`ltr`),messages:r}}function dI(e){return e.replace(/\{\s*\$([\w-]+)\s*(?:!([sra]))?\s*(?::\s*([^{}]*?))?\s*\}/g,(e,t,n,r)=>`{${t}${n?`!${n}`:``}${r===void 0?``:`:${r.trim()}`}}`).trim()}function fI(e,t,n){let r=n.filter(e=>e.default);if(r.length!==1)throw Error(`FTL select expressions need exactly one default variant`);let i=r[0],a=new Intl.PluralRules(e);return{format(e={}){let r=e[t],o=n.find(e=>e.key===String(r)),s=typeof r==`number`?a.select(r):``;return dI((o??n.find(e=>e.key===s)??i).value)}}}function pI(e,t,n={}){let r=n.domain??`messages`,i=r===`messages`?``:`${r}:`,a={},o=t.replace(/\r\n?/g,`
1373
1373
  `).split(`
1374
- `),s=null,c=``,l=()=>{if(s){if(s.id===void 0){if(s.str!==void 0||s.plurals.size>0||s.context!==void 0)throw Error(`PO entry has a translation but no msgid`);s=null,c=``;return}u(s),s=null,c=``}},u=t=>{let n=t.id;if(n===``||/(^|,)\s*fuzzy\s*(,|$)/.test(c))return;if(t.plural!==void 0&&t.plurals.size===0)throw Error(`PO message "${n}" has a plural but no msgstr[N] forms`);let r=i+(t.context?`${t.context}\u0004${n}`:n);if(a[r]!==void 0)throw Error(`Duplicate PO message: ${r}`);if(t.plurals.size>0){if([...t.plurals.values()].every(e=>e===``))return;let i=new Intl.PluralRules(e).resolvedOptions().pluralCategories,o={};for(let[r,a]of[...t.plurals].sort((e,t)=>e[0]-t[0])){let t=i[r];if(t===void 0)throw Error(`PO message "${n}" has plural form ${r}, but ${e} declares only ${i.length}`);o[t]=a}a[r]=o;return}t.str!==void 0&&t.str!==``&&(a[r]=t.str)};for(let e=0;e<o.length;e++){let t=o[e],n=t.trim();if(n===``){l();continue}if(n.startsWith(`#,`)){c+=`${c===``?``:`,`}${n.slice(2).trim()}`;continue}if(n.startsWith(`#`))continue;let r=t.match(/^(msgctxt|msgid_plural|msgid|msgstr(?:\[(\d+)\])?)\s+(.*)$/);if(!r)throw Error(`Invalid PO line ${e+1}: ${t}`);let i=r[1],a=r[2]===void 0?void 0:Number(r[2]),u=dI(o,e,r[3]);if(e=u.next-1,s?(i===`msgctxt`||i===`msgid`)&&s.id!==void 0&&(l(),s={plurals:new Map}):s={plurals:new Map},i===`msgctxt`)s.context=u.text;else if(i===`msgid`)s.id=u.text;else if(i===`msgid_plural`)s.plural=u.text;else if(i===`msgstr`)s.str=u.text;else if(a!==void 0)s.plurals.set(a,u.text);else throw Error(`Invalid PO keyword on line ${e+1}: ${i}`)}return l(),{locale:e,direction:n.direction??(/^(ar|he|fa|ur)(?:-|$)/i.test(e)?`rtl`:`ltr`),messages:a}}function dI(e,t,n){if(!n.trim().startsWith(`"`))throw Error(`PO string must start with a quote on line ${t+1}: ${n}`);let r=fI(n.trim(),t),i=t+1;for(;i<e.length&&e[i].trim().startsWith(`"`);)r+=fI(e[i].trim(),i),i++;return{text:r,next:i}}function fI(e,t){let n=e.match(/^"((?:[^"\\]|\\.)*)"/);if(!n)throw Error(`Invalid PO string on line ${t+1}: ${e}`);return pI(n[1])}function pI(e){return e.replace(/\\(.)/g,(e,t)=>{switch(t){case`n`:return`
1375
- `;case`t`:return` `;case`r`:return`\r`;case`"`:return`"`;case`\\`:return`\\`;case`a`:return`\x07`;case`b`:return`\b`;case`f`:return`\f`;case`v`:return`\v`;default:return t}})}var mI=/\{sound:([^{}\r\n]+)\}/g;function hI(e){let t=[],n=``,r=0,i;for(mI.lastIndex=0;(i=mI.exec(e))!==null;){n+=e.slice(r,i.index);let a=i[1].trim();a===``?n+=i[0]:t.push({path:a,index:n.length}),r=i.index+i[0].length}return n+=e.slice(r),{text:n,cues:t}}function gI(e){return hI(e).text}function _I(){return{format(e,t){let n=e.params;if(t===`audio`){let t=`${e.type}.audio`;return ML(t)?bL(t,n):``}let r=`${e.type}.${t}`;return ML(r)?xL(r,n):xL(e.type,n)}}}function vI(e,t){return new Intl.NumberFormat(vL(),t).format(e)}function yI(e,t){return new Intl.DateTimeFormat(vL(),t).format(e)}function bI(e,t){return new Intl.ListFormat(vL(),t).format(e)}var xI=/\{(?!sound:)(\w+(?:\.\w+)*)(=)?(?:!([sra]))?(?::([^{}]*))?\}/g;function SI(e){let t=[];xI.lastIndex=0;let n=0,r;for(;(r=xI.exec(e))!==null;){r.index>n&&t.push(e.slice(n,r.index));let i=r[1],a=r[3],o=r[4];t.push({raw:r[0],token:i,debug:r[2]===`=`,conv:a,spec:o}),n=r.index+r[0].length}return n<e.length&&t.push(e.slice(n)),t}function CI(e){return`${e.debug?`=`:``}${e.conv?`!${e.conv}`:``}${e.spec===void 0?``:`:${e.spec}`}`}function wI(e,t){let n=new Map,r=new Map;for(let t of SI(e))typeof t!=`string`&&n.set(t.token,CI(t));for(let e of SI(t))typeof e!=`string`&&r.set(e.token,CI(e));return{missing:[...n.keys()].filter(e=>!r.has(e)),extra:[...r.keys()].filter(e=>!n.has(e)),changed:[...n].flatMap(([e,t])=>{let n=r.get(e);return n!==void 0&&n!==t?[{token:e,base:t,target:n}]:[]})}}var TI=/^(?:(.)?([<>=^]))?([+\- ])?(z)?(#)?(0)?(\d+)?([,_])?(?:\.(\d+))?([bcdeEfFgGnosxX%])?$/,EI={b:2,o:8,x:16,X:16},DI={b:`0b`,o:`0o`,x:`0x`,X:`0X`},OI=new Set([`f`,`F`,`e`,`E`,`g`,`G`,`%`,`n`]);function kI(e){return Number.isNaN(e)?`nan`:e===1/0?`inf`:e===-1/0?`-inf`:Object.is(e,-0)?`-0.0`:String(e)}function AI(e,t,n=3,r=`\\d`){return e.replace(RegExp(`\\B(?=(${r}{${n}})+(?!${r}))`,`g`),t)}function jI(e,t){let n=/^(\d+)/.exec(e);return n?AI(n[1],t)+e.slice(n[1].length):e}function MI(e,t,n,r){if(e.length>=t)return e;let i=n.repeat(t-e.length);return r===`<`?e+i:r===`^`?i.slice(0,Math.floor(i.length/2))+e+i.slice(Math.floor(i.length/2)):i+e}function NI(e){return e.replace(/([eE][+-])(\d)$/,`$10$2`)}function PI(e,t,n,r,i){let a=t===0?1:t;if(e===0)return r?`0.${`0`.repeat(a-1)}`:`0`;let o=Math.floor(Math.log10(e)),s;return o>=-4&&o<(i??a)?(s=e.toFixed(a-1-o),r||(s=s.replace(/(\.\d*?)0+$/,`$1`).replace(/\.$/,``))):(s=NI(e.toExponential(a-1)),r||(s=s.replace(/(\.\d*?)0+(e|$)/,`$1$2`).replace(/\.e/i,`e`))),n?s.toUpperCase():s}function FI(e){let t=`,`,n=`.`;for(let r of new Intl.NumberFormat(e).formatToParts(1000.5))r.type===`group`&&(t=r.value),r.type===`decimal`&&(n=r.value);return{group:t,decimal:n}}function II(e,t,n,r,i,a){return MI(a===void 0?e:e.slice(0,a),i,t??(r?`0`:` `),n??`<`)}function LI(e,t,n=`en`){if(t===``)return typeof e==`number`?kI(e):e;let r=TI.exec(t);if(!r)return;let[i,a,o,s,c,l,u,d,f,p]=r.slice(1),m=f===void 0?void 0:Number(f),h=u===void 0?0:Number(u);if(typeof e==`string`)return o||s||c||d||a===`=`||p!==void 0&&p!==`s`?void 0:II(e,i,a,l,h,m);if(p===`s`)return;if(p===`c`){if(o||c||l||d||m!==void 0)return;let t=Math.trunc(e);return t<0||t>1114111?void 0:MI(String.fromCodePoint(t),h,i??` `,a??`>`)}if(!Number.isFinite(e)){if(p!==void 0&&!OI.has(p))return;let t=Number.isNaN(e)?`nan`:`inf`;return(p===`F`||p===`E`||p===`G`)&&(t=t.toUpperCase()),p===`%`&&(t+=`%`),MI((e<0?`-`:o===`+`?`+`:o===` `?` `:``)+t,h,i??` `,a??`>`)}let g=e<0||Object.is(e,-0);s&&e===0&&(g=!1);let _=Math.abs(e),v=d===`,`?`,`:d===`_`?`_`:``,y;if(p===void 0){if(m!==void 0){if(Number.isInteger(_))return;y=PI(_,m,!1,!!c,m-1)}else y=kI(_);v&&(y=jI(y,v))}else if(p===`d`){if(m!==void 0||!Number.isInteger(_))return;y=String(Math.trunc(_)),v&&(y=AI(y,v))}else if(p in EI){if(m!==void 0||!Number.isInteger(_)||d===`,`)return;y=Math.trunc(_).toString(EI[p]),p===`X`&&(y=y.toUpperCase()),v&&(y=AI(y,v,4,`[0-9a-fA-F]`)),c&&(y=DI[p]+y)}else if(p===`n`){if(d||m!==void 0&&Number.isInteger(_))return;if(Number.isInteger(_))y=new Intl.NumberFormat(n).format(Math.trunc(_));else{let{group:e,decimal:t}=FI(n),r=PI(_,m??6,!1,!!c),i=r.split(`e`)[0],a=r.slice(i.length);y=jI(i,e).replace(`.`,t)+a}}else if(p===`f`||p===`F`)y=_.toFixed(m??6),v&&(y=jI(y,v));else if(p===`e`||p===`E`)y=NI(_.toExponential(m??6)),p===`E`&&(y=y.toUpperCase()),v&&(y=jI(y,v));else if(p===`g`||p===`G`)y=PI(_,m??6,p===`G`,!!c),v&&(y=jI(y,v));else{let e=_*100;y=(Number.isFinite(e)?e.toFixed(m??6):`inf`)+`%`,v&&Number.isFinite(e)&&(y=jI(y,v))}let b=g?`-`:o===`+`?`+`:o===` `?` `:``,x=i??(l&&!a?`0`:` `),S=a??(l&&!a?`=`:`>`);return S===`=`?b+MI(y,h-b.length,x,`>`):MI(b+y,h,x,S)}function RI(e,t){let n=new Set(Object.keys(e.messages)),r=new Set(Object.keys(t.messages));return{missing:[...n].filter(e=>!r.has(e)),extra:[...r].filter(e=>!n.has(e))}}function zI(e){let t=[];for(let[n,r]of Object.entries(e.messages)){if(typeof r==`string`){r===``&&t.push({key:n,kind:`empty-message`,detail:`message resolves to an empty string`});continue}BI(r)&&r.other===void 0&&t.push({key:n,kind:`plural-missing-other`,detail:`plural forms have no "other" branch`})}return t}function BI(e){return typeof e==`object`&&!!e&&!(`format`in e)}function VI(e){let t=[];for(let[n,r]of Object.entries(e.messages))n.endsWith(`.audio`)&&(typeof r==`string`?r===``&&t.push({key:n,kind:`empty-audio-path`,detail:`an empty audio entry already means "no sound"; remove the key instead`}):t.push({key:n,kind:`audio-not-a-path`,detail:`an audio entry must be a plain path string, not plural forms or a select message`}));return t}function HI(e){if(typeof e==`string`)return e;if(typeof e==`object`&&e&&`format`in e)try{return e.format()}catch{return``}let t=e;return t.other??Object.values(t)[0]??``}function UI(e,t){if(e===t)return 0;if(e.length===0)return t.length;if(t.length===0)return e.length;let n=Array.from({length:t.length+1},(e,t)=>t),r=Array(t.length+1);for(let i=1;i<=e.length;i++){r[0]=i;for(let a=1;a<=t.length;a++){let o=e[i-1]===t[a-1]?0:1;r[a]=Math.min(n[a]+1,r[a-1]+1,n[a-1]+o)}[n,r]=[r,n]}return n[t.length]}function WI(e,t=.8){let n=Object.entries(e.messages).map(([e,t])=>[e,HI(t)]).filter(([,e])=>e.length>0),r=[];for(let e=0;e<n.length;e++)for(let i=e+1;i<n.length;i++){let[a,o]=n[e],[s,c]=n[i],l=Math.max(o.length,c.length),u=UI(o,c),d=l===0?1:1-u/l;d>=t&&r.push({a,b:s,distance:u,similarity:d})}return r.sort((e,t)=>t.similarity-e.similarity)}function GI(e,t){let n=new Set(t),r=Object.keys(e.messages),i=r.filter(e=>!n.has(e));return{totalKeys:r.length,usedKeys:r.length-i.length,unusedKeys:i}}function KI(e,t){let n=Object.keys(e.messages);if(n.length===0)return 1;let{missing:r}=RI(e,t);return(n.length-r.length)/n.length}function qI(e){let t={},n=0;for(let r of Object.values(e.messages))if(!(typeof r==`string`||typeof r==`object`&&r&&`format`in r)){n++;for(let e of Object.keys(r))t[e]=(t[e]??0)+1}return{pluralKeys:n,formsPresent:t}}function JI(e,t,n){if(!(t in e.messages))throw Error(`mergeCatalogKeys: "${t}" is not a key in this catalog`);if(!(n in e.messages))throw Error(`mergeCatalogKeys: "${n}" is not a key in this catalog`);if(t===n)throw Error(`mergeCatalogKeys: survivingKey and mergedKey must be different keys`);let r={...e.messages};return delete r[n],{...e,messages:r}}function YI(e,t){return{base:e,target:t}}var XI=`.audio`;function ZI(e){return e.endsWith(XI)}function QI(e){return[...new Set([...Object.keys(e.base.messages),...Object.keys(e.target.messages)])].filter(e=>!ZI(e)).sort()}function $I(e){if(e===void 0)return;let t=HI(e);return t===``?void 0:t}var eL=[`log`,`compact`,`accessibility`,`debug`];function tL(e){let t=e.lastIndexOf(`.`);if(!(t<=0||!eL.includes(e.slice(t+1))))return`${e.slice(0,t)}${XI}`}function nL(e,t){let n=e.base.messages[t],r=e.target.messages[t],i=n!==void 0&&r!==void 0?`ok`:n===void 0?`extra`:`missing`,a=[`${t}${XI}`],o=tL(t);o&&a.push(o);let s,c,l=!1;for(let t of a){let n=$I(e.target.messages[t]);if(n!==void 0){s=n,c=t;break}let r=$I(e.base.messages[t]);if(r!==void 0){s=r,c=t,l=!0;break}}return{key:t,baseText:n===void 0?``:HI(n),targetText:r===void 0?``:HI(r),status:i,sound:s,soundKey:c,soundInherited:l}}function rL(e,t){let n=`${t}${XI}`;return n in e.target.messages||n in e.base.messages?n:tL(t)??n}function iL(e,t={}){let n=t.query?.toLowerCase()??``;return QI(e).map(t=>nL(e,t)).filter(e=>!t.missingOnly||e.status===`missing`).filter(e=>n===``||e.key.toLowerCase().includes(n)||e.baseText.toLowerCase().includes(n)||e.targetText.toLowerCase().includes(n))}function aL(e,t,n){let r=e.target.messages[t]??e.base.messages[t],i=n;if(r!==void 0&&typeof r==`object`&&!(`format`in r))try{let e=JSON.parse(n);typeof e==`object`&&e&&!Array.isArray(e)&&(i=e)}catch{}return{...e,target:{...e.target,messages:{...e.target.messages,[t]:i}}}}function oL(e,t){let n=e.base.messages[t];if(n===void 0)throw Error(`copyFromBase: "${t}" is not a key in the base catalog`);return{...e,target:{...e.target,messages:{...e.target.messages,[t]:n}}}}function sL(e,t){if(!(t in e.target.messages))throw Error(`deleteTargetKey: "${t}" is not a key in the target catalog`);let n={...e.target.messages};return delete n[t],{...e,target:{...e.target,messages:n}}}function cL(e,t,n){let r={...e.target.messages},i=rL(e,t);return n===``?delete r[i]:r[i]=n,{...e,target:{...e.target,messages:r}}}function lL(e){let t=e=>({...e,messages:Object.fromEntries(Object.entries(e.messages).filter(([e])=>!ZI(e)))});return KI(t(e.base),t(e.target))}function uL(e){return{base:e.target,target:e.base}}var dL=l({AUDIO_SUFFIX:()=>XI,catalogCompleteness:()=>KI,catalogUsage:()=>GI,copyFromBase:()=>oL,createCatalogFormatter:()=>_I,createEditSession:()=>YI,cueKeyFor:()=>rL,deleteTargetKey:()=>sL,diffCatalogKeys:()=>RI,diffPlaceholders:()=>wI,direction:()=>yL,findSimilarMessages:()=>WI,formatDate:()=>yI,formatList:()=>bI,formatNumber:()=>vI,formatSpec:()=>LI,has:()=>ML,isAudioKey:()=>ZI,levenshteinDistance:()=>UI,locale:()=>vL,mergeCatalogKeys:()=>JI,messageText:()=>HI,nonBreakingUnit:()=>OL,parseFTL:()=>sI,parsePo:()=>uI,parseSoundMarkers:()=>hI,pluralFormCoverage:()=>qI,reset:()=>BL,sessionCompleteness:()=>lL,sessionKeys:()=>QI,sessionRow:()=>nL,sessionRows:()=>iL,setActive:()=>_L,setBase:()=>gL,setTargetSound:()=>cL,setTargetText:()=>aL,stripSoundMarkers:()=>gI,swapSession:()=>uL,t:()=>xL,tRaw:()=>bL,tokenizeMessage:()=>SI,typographic:()=>DL,validateCatalog:()=>zI,validateMessageAudio:()=>VI}),fL=null,pL=null,mL=null,hL=null;function gL(e){fL=e}function _L(e){pL=e,mL=e?new Intl.PluralRules(e.locale):null}function vL(){return(pL??fL)?.locale??`en`}function yL(){return(pL??fL)?.direction??`ltr`}function bL(e,t){let n=pL?.messages[e]??fL?.messages[e];if(n===void 0)return e;let r=typeof n==`string`?n:PL(n)?n.format(t):NL(n,t?.count);return t?FL(r,t):r}function xL(e,t){if(!ML(e))return e;let n=bL(e,t),r=(pL??fL)?.typography===!1?n:DL(n,vL());return yL()===`rtl`?`⁧${r}⁩`:r}var SL=` `,CL=`\xA0`,wL=[`Chapitre`,`Tome`,`Livre`,`Partie`,`Section`,`Article`,`Acte`,`Scène`,`Niveau`,`Manche`,`Round`,`Étape`,`Volume`,`Figure`,`Page`,`Numéro`],TL=[`Nr`,`Dr`,`Bd`,`Kap`,`Art`,`Abb`,`Str`,`Tel`],EL=[`kg`,`g`,`mg`,`t`,`km`,`m`,`cm`,`mm`,`l`,`ml`,`h`,`min`,`s`,`%`,`°C`,`€`];function DL(e,t=vL()){let n=t.split(`-`)[0].toLowerCase(),r=e;return(n===`fr`||n===`it`||n===`nl`)&&(r=r.replace(/([\p{L}])'(?=[\p{L}])/gu,`$1’`)),n===`fr`&&(r=kL(r)),n===`de`&&(r=AL(r)),r}function OL(e,t,n=vL()){let r=n.split(`-`)[0].toLowerCase();return`${e}${r===`fr`?SL:r===`de`?CL:` `}${t}`}function kL(e){let t=e.replace(/\s?([;!?])/g,`${SL}$1`).replace(/«\s?/g,`«${SL}`).replace(/\s?»/g,`${SL}»`);t=t.replace(/(?<!\{soun)(\p{L})\s?:/gu,`$1${SL}:`);let n=RegExp(`\\b(${wL.join(`|`)})\\s+(?=\\d)`,`g`);return t.replace(n,`$1${CL}`)}function AL(e){let t=RegExp(`(\\d)\\s+(?=(?:${EL.map(jL).join(`|`)})(?![\\p{L}\\p{N}]))`,`gu`),n=RegExp(`\\b(${TL.join(`|`)})\\.\\s+`,`g`);return e.replace(t,`$1${CL}`).replace(n,`$1.${CL}`)}function jL(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function ML(e){return pL?.messages[e]!==void 0||fL?.messages[e]!==void 0}function NL(e,t){return t===void 0?e.other??Object.values(e)[0]??``:e[(mL??(hL??=new Intl.PluralRules(`en`))).select(t)]??e.other??``}function PL(e){return`format`in e}function FL(e,t){return SI(e).map(e=>typeof e==`string`?e:LL(e,t)).join(``)}function IL(e,t){let n=e[t];if(typeof n==`string`||typeof n==`number`)return n;let r=e;for(let e of t.split(`.`)){if(typeof r!=`object`)return;r=r[e]}return typeof r==`string`||typeof r==`number`?r:void 0}function LL(e,t){let n=IL(t,e.token);if(n===void 0)return e.raw;try{let t=e.conv===void 0?n:RL(n,e.conv),r=e.spec===void 0?String(t):LI(t,e.spec,vL());return r===void 0?e.raw:e.debug?`${e.token}=${r}`:r}catch{return e.raw}}function RL(e,t){if(t===`s`)return String(e);if(typeof e==`number`){let n=LI(e,``,`en`)??String(e);return t===`a`?zL(n):n}let n=`'${e.replace(/\\/g,`\\\\`).replace(/'/g,`\\'`).replace(/\n/g,`\\n`).replace(/\r/g,`\\r`).replace(/\t/g,`\\t`)}'`;return t===`a`?zL(n):n}function zL(e){let t=``;for(let n of e){let e=n.codePointAt(0)??0;t+=e>127?e>65535?`\\U${e.toString(16).padStart(8,`0`)}`:`\\u${e.toString(16).padStart(4,`0`)}`:n}return t}function BL(){fL=null,pL=null,mL=null}var VL=class extends tI{constructor(e){super({width:e.width,height:e.height,modal:!0,closable:!1,dims:e.dims,blocker:e.blocker??!0,anchor:e.anchor??`bottom`}),this.pageIndex=0,this.reveal=eF(0),this.pageText=``,this.pageCues=[],this.nextCue=0,this.portrait=null,this.portraitLayer=new Y,this.choiceList=null,this.finished=!1,this.autoAdvanceElapsed=0,this.messageThemeListener=()=>this.restyleMessage(),this.pages=e.pages.map(e=>typeof e==`string`?{text:e}:e),this.speed=e.speed??40,this.mode=e.mode??`adv`,this.autoAdvance=e.autoAdvance,this.choices=e.choices??[],this.onDone=e.onDone??null,this.onSound=e.onSound??null,this.announce=e.announce??!0;let t=Q();this.content.addChild(this.portraitLayer),this.speakerLabel=new iF({color:t.color.textHighlight,bold:!0}),this.content.addChild(this.speakerLabel),this.body=new iF({wrapWidth:this.contentWidth}),this.content.addChild(this.body),this.prompt=new iF({text:`▼`,color:t.color.textDim}),this.prompt.visible=!1,this.content.addChild(this.prompt),this.showPage(0),$.add(this.messageThemeListener)}restyleMessage(){let e=Q();this.speakerLabel.setColor(e.color.textHighlight),this.prompt.setColor(e.color.textDim)}destroy(e){$.remove(this.messageThemeListener),super.destroy(e)}showPage(e){let t=this.pages[e],n=Q(),r=n.direction===`rtl`;this.portraitLayer.removeChildren(),this.portrait=null;let i=0,a=this.contentWidth;t.portrait&&(this.portrait=new xl(t.portrait),r&&(this.portrait.x=this.contentWidth-this.portrait.width),this.portraitLayer.addChild(this.portrait),a=this.contentWidth-this.portrait.width-n.padding,i=r?0:this.portrait.width+n.padding),this.speakerLabel.visible=this.mode===`adv`&&t.speaker!==void 0,this.speakerLabel.x=i,this.speakerLabel.setText(t.speaker??``),this.body.x=i,this.body.y=this.mode===`adv`&&t.speaker!==void 0?this.speakerLabel.height+n.spacing:0,this.body.style.wordWrapWidth=Math.max(16,a);let o=hI(t.text);this.pageText=o.text,this.pageCues=o.cues,this.nextCue=0,this.announce&&eI.announce(t.speaker===void 0?this.pageText:`${t.speaker}: ${this.pageText}`),this.reveal=eF(this.pageText.length,this.speed),this.autoAdvanceElapsed=0,this.playRevealedSounds(),this.renderBody(),this.prompt.visible=!1,this.prompt.x=r?0:this.contentWidth-this.prompt.width,this.prompt.y=this.contentHeight-this.prompt.height}renderBody(){if(this.mode===`adv`){this.body.setText(this.pageText.slice(0,Math.floor(this.reveal.revealed)));return}let e=this.pages.slice(0,this.pageIndex).map(e=>this.formatLine(e,hI(e.text).text)),t=this.pages[this.pageIndex];e.push(this.formatLine(t,this.pageText.slice(0,Math.floor(this.reveal.revealed)))),this.body.setText(e.join(`
1374
+ `),s=null,c=``,l=()=>{if(s){if(s.id===void 0){if(s.str!==void 0||s.plurals.size>0||s.context!==void 0)throw Error(`PO entry has a translation but no msgid`);s=null,c=``;return}u(s),s=null,c=``}},u=t=>{let n=t.id;if(n===``||/(^|,)\s*fuzzy\s*(,|$)/.test(c))return;if(t.plural!==void 0&&t.plurals.size===0)throw Error(`PO message "${n}" has a plural but no msgstr[N] forms`);let r=i+(t.context?`${t.context}\u0004${n}`:n);if(a[r]!==void 0)throw Error(`Duplicate PO message: ${r}`);if(t.plurals.size>0){if([...t.plurals.values()].every(e=>e===``))return;let i=new Intl.PluralRules(e).resolvedOptions().pluralCategories,o={};for(let[r,a]of[...t.plurals].sort((e,t)=>e[0]-t[0])){let t=i[r];if(t===void 0)throw Error(`PO message "${n}" has plural form ${r}, but ${e} declares only ${i.length}`);o[t]=a}a[r]=o;return}t.str!==void 0&&t.str!==``&&(a[r]=t.str)};for(let e=0;e<o.length;e++){let t=o[e],n=t.trim();if(n===``){l();continue}if(n.startsWith(`#,`)){c+=`${c===``?``:`,`}${n.slice(2).trim()}`;continue}if(n.startsWith(`#`))continue;let r=t.match(/^(msgctxt|msgid_plural|msgid|msgstr(?:\[(\d+)\])?)\s+(.*)$/);if(!r)throw Error(`Invalid PO line ${e+1}: ${t}`);let i=r[1],a=r[2]===void 0?void 0:Number(r[2]),u=mI(o,e,r[3]);if(e=u.next-1,s?(i===`msgctxt`||i===`msgid`)&&s.id!==void 0&&(l(),s={plurals:new Map}):s={plurals:new Map},i===`msgctxt`)s.context=u.text;else if(i===`msgid`)s.id=u.text;else if(i===`msgid_plural`)s.plural=u.text;else if(i===`msgstr`)s.str=u.text;else if(a!==void 0)s.plurals.set(a,u.text);else throw Error(`Invalid PO keyword on line ${e+1}: ${i}`)}return l(),{locale:e,direction:n.direction??(/^(ar|he|fa|ur)(?:-|$)/i.test(e)?`rtl`:`ltr`),messages:a}}function mI(e,t,n){if(!n.trim().startsWith(`"`))throw Error(`PO string must start with a quote on line ${t+1}: ${n}`);let r=hI(n.trim(),t),i=t+1;for(;i<e.length&&e[i].trim().startsWith(`"`);)r+=hI(e[i].trim(),i),i++;return{text:r,next:i}}function hI(e,t){let n=e.match(/^"((?:[^"\\]|\\.)*)"/);if(!n)throw Error(`Invalid PO string on line ${t+1}: ${e}`);return gI(n[1])}function gI(e){return e.replace(/\\(.)/g,(e,t)=>{switch(t){case`n`:return`
1375
+ `;case`t`:return` `;case`r`:return`\r`;case`"`:return`"`;case`\\`:return`\\`;case`a`:return`\x07`;case`b`:return`\b`;case`f`:return`\f`;case`v`:return`\v`;default:return t}})}var _I=/\{sound:([^{}\r\n]+)\}/g;function vI(e){let t=[],n=``,r=0,i;for(_I.lastIndex=0;(i=_I.exec(e))!==null;){n+=e.slice(r,i.index);let a=i[1].trim();a===``?n+=i[0]:t.push({path:a,index:n.length}),r=i.index+i[0].length}return n+=e.slice(r),{text:n,cues:t}}function yI(e){return vI(e).text}function bI(){return{format(e,t){let n=e.params;if(t===`audio`){let t=`${e.type}.audio`;return FL(t)?CL(t,n):``}let r=`${e.type}.${t}`;return FL(r)?wL(r,n):wL(e.type,n)}}}function xI(e,t){return new Intl.NumberFormat(xL(),t).format(e)}function SI(e,t){return new Intl.DateTimeFormat(xL(),t).format(e)}function CI(e,t){return new Intl.ListFormat(xL(),t).format(e)}var wI=/\{(?!sound:)(\w+(?:\.\w+)*)(=)?(?:!([sra]))?(?::([^{}]*))?\}/g;function TI(e){let t=[];wI.lastIndex=0;let n=0,r;for(;(r=wI.exec(e))!==null;){r.index>n&&t.push(e.slice(n,r.index));let i=r[1],a=r[3],o=r[4];t.push({raw:r[0],token:i,debug:r[2]===`=`,conv:a,spec:o}),n=r.index+r[0].length}return n<e.length&&t.push(e.slice(n)),t}function EI(e){return`${e.debug?`=`:``}${e.conv?`!${e.conv}`:``}${e.spec===void 0?``:`:${e.spec}`}`}function DI(e,t){let n=new Map,r=new Map;for(let t of TI(e))typeof t!=`string`&&n.set(t.token,EI(t));for(let e of TI(t))typeof e!=`string`&&r.set(e.token,EI(e));return{missing:[...n.keys()].filter(e=>!r.has(e)),extra:[...r.keys()].filter(e=>!n.has(e)),changed:[...n].flatMap(([e,t])=>{let n=r.get(e);return n!==void 0&&n!==t?[{token:e,base:t,target:n}]:[]})}}var OI=/^(?:(.)?([<>=^]))?([+\- ])?(z)?(#)?(0)?(\d+)?([,_])?(?:\.(\d+))?([bcdeEfFgGnosxX%])?$/,kI={b:2,o:8,x:16,X:16},AI={b:`0b`,o:`0o`,x:`0x`,X:`0X`},jI=new Set([`f`,`F`,`e`,`E`,`g`,`G`,`%`,`n`]);function MI(e){return Number.isNaN(e)?`nan`:e===1/0?`inf`:e===-1/0?`-inf`:Object.is(e,-0)?`-0.0`:String(e)}function NI(e,t,n=3,r=`\\d`){return e.replace(RegExp(`\\B(?=(${r}{${n}})+(?!${r}))`,`g`),t)}function PI(e,t){let n=/^(\d+)/.exec(e);return n?NI(n[1],t)+e.slice(n[1].length):e}function FI(e,t,n,r){if(e.length>=t)return e;let i=n.repeat(t-e.length);return r===`<`?e+i:r===`^`?i.slice(0,Math.floor(i.length/2))+e+i.slice(Math.floor(i.length/2)):i+e}function II(e){return e.replace(/([eE][+-])(\d)$/,`$10$2`)}function LI(e,t,n,r,i){let a=t===0?1:t;if(e===0)return r?`0.${`0`.repeat(a-1)}`:`0`;let o=Math.floor(Math.log10(e)),s;return o>=-4&&o<(i??a)?(s=e.toFixed(a-1-o),r||(s=s.replace(/(\.\d*?)0+$/,`$1`).replace(/\.$/,``))):(s=II(e.toExponential(a-1)),r||(s=s.replace(/(\.\d*?)0+(e|$)/,`$1$2`).replace(/\.e/i,`e`))),n?s.toUpperCase():s}function RI(e){let t=`,`,n=`.`;for(let r of new Intl.NumberFormat(e).formatToParts(1000.5))r.type===`group`&&(t=r.value),r.type===`decimal`&&(n=r.value);return{group:t,decimal:n}}function zI(e,t,n,r,i,a){return FI(a===void 0?e:e.slice(0,a),i,t??(r?`0`:` `),n??`<`)}function BI(e,t,n=`en`){if(t===``)return typeof e==`number`?MI(e):e;let r=OI.exec(t);if(!r)return;let[i,a,o,s,c,l,u,d,f,p]=r.slice(1),m=f===void 0?void 0:Number(f),h=u===void 0?0:Number(u);if(typeof e==`string`)return o||s||c||d||a===`=`||p!==void 0&&p!==`s`?void 0:zI(e,i,a,l,h,m);if(p===`s`)return;if(p===`c`){if(o||c||l||d||m!==void 0)return;let t=Math.trunc(e);return t<0||t>1114111?void 0:FI(String.fromCodePoint(t),h,i??` `,a??`>`)}if(!Number.isFinite(e)){if(p!==void 0&&!jI.has(p))return;let t=Number.isNaN(e)?`nan`:`inf`;return(p===`F`||p===`E`||p===`G`)&&(t=t.toUpperCase()),p===`%`&&(t+=`%`),FI((e<0?`-`:o===`+`?`+`:o===` `?` `:``)+t,h,i??` `,a??`>`)}let g=e<0||Object.is(e,-0);s&&e===0&&(g=!1);let _=Math.abs(e),v=d===`,`?`,`:d===`_`?`_`:``,y;if(p===void 0){if(m!==void 0){if(Number.isInteger(_))return;y=LI(_,m,!1,!!c,m-1)}else y=MI(_);v&&(y=PI(y,v))}else if(p===`d`){if(m!==void 0||!Number.isInteger(_))return;y=String(Math.trunc(_)),v&&(y=NI(y,v))}else if(p in kI){if(m!==void 0||!Number.isInteger(_)||d===`,`)return;y=Math.trunc(_).toString(kI[p]),p===`X`&&(y=y.toUpperCase()),v&&(y=NI(y,v,4,`[0-9a-fA-F]`)),c&&(y=AI[p]+y)}else if(p===`n`){if(d||m!==void 0&&Number.isInteger(_))return;if(Number.isInteger(_))y=new Intl.NumberFormat(n).format(Math.trunc(_));else{let{group:e,decimal:t}=RI(n),r=LI(_,m??6,!1,!!c),i=r.split(`e`)[0],a=r.slice(i.length);y=PI(i,e).replace(`.`,t)+a}}else if(p===`f`||p===`F`)y=_.toFixed(m??6),v&&(y=PI(y,v));else if(p===`e`||p===`E`)y=II(_.toExponential(m??6)),p===`E`&&(y=y.toUpperCase()),v&&(y=PI(y,v));else if(p===`g`||p===`G`)y=LI(_,m??6,p===`G`,!!c),v&&(y=PI(y,v));else{let e=_*100;y=(Number.isFinite(e)?e.toFixed(m??6):`inf`)+`%`,v&&Number.isFinite(e)&&(y=PI(y,v))}let b=g?`-`:o===`+`?`+`:o===` `?` `:``,x=i??(l&&!a?`0`:` `),S=a??(l&&!a?`=`:`>`);return S===`=`?b+FI(y,h-b.length,x,`>`):FI(b+y,h,x,S)}function VI(e,t){let n=new Set(Object.keys(e.messages)),r=new Set(Object.keys(t.messages));return{missing:[...n].filter(e=>!r.has(e)),extra:[...r].filter(e=>!n.has(e))}}function HI(e){let t=[];for(let[n,r]of Object.entries(e.messages)){if(typeof r==`string`){r===``&&t.push({key:n,kind:`empty-message`,detail:`message resolves to an empty string`});continue}UI(r)&&r.other===void 0&&t.push({key:n,kind:`plural-missing-other`,detail:`plural forms have no "other" branch`})}return t}function UI(e){return typeof e==`object`&&!!e&&!(`format`in e)}function WI(e){let t=[];for(let[n,r]of Object.entries(e.messages))n.endsWith(`.audio`)&&(typeof r==`string`?r===``&&t.push({key:n,kind:`empty-audio-path`,detail:`an empty audio entry already means "no sound"; remove the key instead`}):t.push({key:n,kind:`audio-not-a-path`,detail:`an audio entry must be a plain path string, not plural forms or a select message`}));return t}function GI(e){if(typeof e==`string`)return e;if(typeof e==`object`&&e&&`format`in e)try{return e.format()}catch{return``}let t=e;return t.other??Object.values(t)[0]??``}function KI(e,t){if(e===t)return 0;if(e.length===0)return t.length;if(t.length===0)return e.length;let n=Array.from({length:t.length+1},(e,t)=>t),r=Array(t.length+1);for(let i=1;i<=e.length;i++){r[0]=i;for(let a=1;a<=t.length;a++){let o=e[i-1]===t[a-1]?0:1;r[a]=Math.min(n[a]+1,r[a-1]+1,n[a-1]+o)}[n,r]=[r,n]}return n[t.length]}function qI(e,t=.8){let n=Object.entries(e.messages).map(([e,t])=>[e,GI(t)]).filter(([,e])=>e.length>0),r=[];for(let e=0;e<n.length;e++)for(let i=e+1;i<n.length;i++){let[a,o]=n[e],[s,c]=n[i],l=Math.max(o.length,c.length),u=KI(o,c),d=l===0?1:1-u/l;d>=t&&r.push({a,b:s,distance:u,similarity:d})}return r.sort((e,t)=>t.similarity-e.similarity)}function JI(e,t){let n=new Set(t),r=Object.keys(e.messages),i=r.filter(e=>!n.has(e));return{totalKeys:r.length,usedKeys:r.length-i.length,unusedKeys:i}}function YI(e,t){let n=Object.keys(e.messages);if(n.length===0)return 1;let{missing:r}=VI(e,t);return(n.length-r.length)/n.length}function XI(e){let t={},n=0;for(let r of Object.values(e.messages))if(!(typeof r==`string`||typeof r==`object`&&r&&`format`in r)){n++;for(let e of Object.keys(r))t[e]=(t[e]??0)+1}return{pluralKeys:n,formsPresent:t}}function ZI(e,t,n){if(!(t in e.messages))throw Error(`mergeCatalogKeys: "${t}" is not a key in this catalog`);if(!(n in e.messages))throw Error(`mergeCatalogKeys: "${n}" is not a key in this catalog`);if(t===n)throw Error(`mergeCatalogKeys: survivingKey and mergedKey must be different keys`);let r={...e.messages};return delete r[n],{...e,messages:r}}function QI(e,t){return{base:e,target:t}}var $I=`.audio`;function eL(e){return e.endsWith($I)}function tL(e){return[...new Set([...Object.keys(e.base.messages),...Object.keys(e.target.messages)])].filter(e=>!eL(e)).sort()}function nL(e){if(e===void 0)return;let t=GI(e);return t===``?void 0:t}var rL=[`log`,`compact`,`accessibility`,`debug`];function iL(e){let t=e.lastIndexOf(`.`);if(!(t<=0||!rL.includes(e.slice(t+1))))return`${e.slice(0,t)}${$I}`}function aL(e,t){let n=e.base.messages[t],r=e.target.messages[t],i=n!==void 0&&r!==void 0?`ok`:n===void 0?`extra`:`missing`,a=[`${t}${$I}`],o=iL(t);o&&a.push(o);let s,c,l=!1;for(let t of a){let n=nL(e.target.messages[t]);if(n!==void 0){s=n,c=t;break}let r=nL(e.base.messages[t]);if(r!==void 0){s=r,c=t,l=!0;break}}return{key:t,baseText:n===void 0?``:GI(n),targetText:r===void 0?``:GI(r),status:i,sound:s,soundKey:c,soundInherited:l}}function oL(e,t){let n=`${t}${$I}`;return n in e.target.messages||n in e.base.messages?n:iL(t)??n}function sL(e,t={}){let n=t.query?.toLowerCase()??``;return tL(e).map(t=>aL(e,t)).filter(e=>!t.missingOnly||e.status===`missing`).filter(e=>n===``||e.key.toLowerCase().includes(n)||e.baseText.toLowerCase().includes(n)||e.targetText.toLowerCase().includes(n))}function cL(e,t,n){let r=e.target.messages[t]??e.base.messages[t],i=n;if(r!==void 0&&typeof r==`object`&&!(`format`in r))try{let e=JSON.parse(n);typeof e==`object`&&e&&!Array.isArray(e)&&(i=e)}catch{}return{...e,target:{...e.target,messages:{...e.target.messages,[t]:i}}}}function lL(e,t){let n=e.base.messages[t];if(n===void 0)throw Error(`copyFromBase: "${t}" is not a key in the base catalog`);return{...e,target:{...e.target,messages:{...e.target.messages,[t]:n}}}}function uL(e,t){if(!(t in e.target.messages))throw Error(`deleteTargetKey: "${t}" is not a key in the target catalog`);let n={...e.target.messages};return delete n[t],{...e,target:{...e.target,messages:n}}}function dL(e,t,n){let r={...e.target.messages},i=oL(e,t);return n===``?delete r[i]:r[i]=n,{...e,target:{...e.target,messages:r}}}function fL(e){let t=e=>({...e,messages:Object.fromEntries(Object.entries(e.messages).filter(([e])=>!eL(e)))});return YI(t(e.base),t(e.target))}function pL(e){return{base:e.target,target:e.base}}var mL=l({AUDIO_SUFFIX:()=>$I,catalogCompleteness:()=>YI,catalogUsage:()=>JI,copyFromBase:()=>lL,createCatalogFormatter:()=>bI,createEditSession:()=>QI,cueKeyFor:()=>oL,deleteTargetKey:()=>uL,diffCatalogKeys:()=>VI,diffPlaceholders:()=>DI,direction:()=>SL,findSimilarMessages:()=>qI,formatDate:()=>SI,formatList:()=>CI,formatNumber:()=>xI,formatSpec:()=>BI,has:()=>FL,isAudioKey:()=>eL,levenshteinDistance:()=>KI,locale:()=>xL,mergeCatalogKeys:()=>ZI,messageText:()=>GI,nonBreakingUnit:()=>jL,parseFTL:()=>uI,parsePo:()=>pI,parseSoundMarkers:()=>vI,pluralFormCoverage:()=>XI,reset:()=>UL,sessionCompleteness:()=>fL,sessionKeys:()=>tL,sessionRow:()=>aL,sessionRows:()=>sL,setActive:()=>bL,setBase:()=>yL,setTargetSound:()=>dL,setTargetText:()=>cL,stripSoundMarkers:()=>yI,swapSession:()=>pL,t:()=>wL,tRaw:()=>CL,tokenizeMessage:()=>TI,typographic:()=>AL,validateCatalog:()=>HI,validateMessageAudio:()=>WI}),hL=null,gL=null,_L=null,vL=null;function yL(e){hL=e}function bL(e){gL=e,_L=e?new Intl.PluralRules(e.locale):null}function xL(){return(gL??hL)?.locale??`en`}function SL(){return(gL??hL)?.direction??`ltr`}function CL(e,t){let n=gL?.messages[e]??hL?.messages[e];if(n===void 0)return e;let r=typeof n==`string`?n:LL(n)?n.format(t):IL(n,t?.count);return t?RL(r,t):r}function wL(e,t){if(!FL(e))return e;let n=CL(e,t),r=(gL??hL)?.typography===!1?n:AL(n,xL());return SL()===`rtl`?`⁧${r}⁩`:r}var TL=` `,EL=`\xA0`,DL=[`Chapitre`,`Tome`,`Livre`,`Partie`,`Section`,`Article`,`Acte`,`Scène`,`Niveau`,`Manche`,`Round`,`Étape`,`Volume`,`Figure`,`Page`,`Numéro`],OL=[`Nr`,`Dr`,`Bd`,`Kap`,`Art`,`Abb`,`Str`,`Tel`],kL=[`kg`,`g`,`mg`,`t`,`km`,`m`,`cm`,`mm`,`l`,`ml`,`h`,`min`,`s`,`%`,`°C`,`€`];function AL(e,t=xL()){let n=t.split(`-`)[0].toLowerCase(),r=e;return(n===`fr`||n===`it`||n===`nl`)&&(r=r.replace(/([\p{L}])'(?=[\p{L}])/gu,`$1’`)),n===`fr`&&(r=ML(r)),n===`de`&&(r=NL(r)),r}function jL(e,t,n=xL()){let r=n.split(`-`)[0].toLowerCase();return`${e}${r===`fr`?TL:r===`de`?EL:` `}${t}`}function ML(e){let t=e.replace(/\s?([;!?])/g,`${TL}$1`).replace(/«\s?/g,`«${TL}`).replace(/\s?»/g,`${TL}»`);t=t.replace(/(?<!\{soun)(\p{L})\s?:/gu,`$1${TL}:`);let n=RegExp(`\\b(${DL.join(`|`)})\\s+(?=\\d)`,`g`);return t.replace(n,`$1${EL}`)}function NL(e){let t=RegExp(`(\\d)\\s+(?=(?:${kL.map(PL).join(`|`)})(?![\\p{L}\\p{N}]))`,`gu`),n=RegExp(`\\b(${OL.join(`|`)})\\.\\s+`,`g`);return e.replace(t,`$1${EL}`).replace(n,`$1.${EL}`)}function PL(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function FL(e){return gL?.messages[e]!==void 0||hL?.messages[e]!==void 0}function IL(e,t){return t===void 0?e.other??Object.values(e)[0]??``:e[(_L??(vL??=new Intl.PluralRules(`en`))).select(t)]??e.other??``}function LL(e){return`format`in e}function RL(e,t){return TI(e).map(e=>typeof e==`string`?e:BL(e,t)).join(``)}function zL(e,t){let n=e[t];if(typeof n==`string`||typeof n==`number`)return n;let r=e;for(let e of t.split(`.`)){if(typeof r!=`object`)return;r=r[e]}return typeof r==`string`||typeof r==`number`?r:void 0}function BL(e,t){let n=zL(t,e.token);if(n===void 0)return e.raw;try{let t=e.conv===void 0?n:VL(n,e.conv),r=e.spec===void 0?String(t):BI(t,e.spec,xL());return r===void 0?e.raw:e.debug?`${e.token}=${r}`:r}catch{return e.raw}}function VL(e,t){if(t===`s`)return String(e);if(typeof e==`number`){let n=BI(e,``,`en`)??String(e);return t===`a`?HL(n):n}let n=`'${e.replace(/\\/g,`\\\\`).replace(/'/g,`\\'`).replace(/\n/g,`\\n`).replace(/\r/g,`\\r`).replace(/\t/g,`\\t`)}'`;return t===`a`?HL(n):n}function HL(e){let t=``;for(let n of e){let e=n.codePointAt(0)??0;t+=e>127?e>65535?`\\U${e.toString(16).padStart(8,`0`)}`:`\\u${e.toString(16).padStart(4,`0`)}`:n}return t}function UL(){hL=null,gL=null,_L=null}var WL=class extends iI{constructor(e){super({width:e.width,height:e.height,modal:!0,closable:!1,dims:e.dims,blocker:e.blocker??!0,anchor:e.anchor??`bottom`}),this.pageIndex=0,this.reveal=rF(0),this.pageText=``,this.pageCues=[],this.nextCue=0,this.portrait=null,this.portraitLayer=new Y,this.choiceList=null,this.finished=!1,this.autoAdvanceElapsed=0,this.messageThemeListener=()=>this.restyleMessage(),this.pages=e.pages.map(e=>typeof e==`string`?{text:e}:e),this.speed=e.speed??40,this.mode=e.mode??`adv`,this.autoAdvance=e.autoAdvance,this.choices=e.choices??[],this.onDone=e.onDone??null,this.onSound=e.onSound??null,this.announce=e.announce??!0;let t=Q();this.content.addChild(this.portraitLayer),this.speakerLabel=new sF({color:t.color.textHighlight,bold:!0}),this.content.addChild(this.speakerLabel),this.body=new sF({wrapWidth:this.contentWidth}),this.content.addChild(this.body),this.prompt=new sF({text:`▼`,color:t.color.textDim}),this.prompt.visible=!1,this.content.addChild(this.prompt),this.showPage(0),$.add(this.messageThemeListener)}restyleMessage(){let e=Q();this.speakerLabel.setColor(e.color.textHighlight),this.prompt.setColor(e.color.textDim)}destroy(e){$.remove(this.messageThemeListener),super.destroy(e)}showPage(e){let t=this.pages[e],n=Q(),r=n.direction===`rtl`;this.portraitLayer.removeChildren(),this.portrait=null;let i=0,a=this.contentWidth;t.portrait&&(this.portrait=new xl(t.portrait),r&&(this.portrait.x=this.contentWidth-this.portrait.width),this.portraitLayer.addChild(this.portrait),a=this.contentWidth-this.portrait.width-n.padding,i=r?0:this.portrait.width+n.padding),this.speakerLabel.visible=this.mode===`adv`&&t.speaker!==void 0,this.speakerLabel.x=i,this.speakerLabel.setText(t.speaker??``),this.body.x=i,this.body.y=this.mode===`adv`&&t.speaker!==void 0?this.speakerLabel.height+n.spacing:0,this.body.style.wordWrapWidth=Math.max(16,a);let o=vI(t.text);this.pageText=o.text,this.pageCues=o.cues,this.nextCue=0,this.announce&&rI.announce(t.speaker===void 0?this.pageText:`${t.speaker}: ${this.pageText}`),this.reveal=rF(this.pageText.length,this.speed),this.autoAdvanceElapsed=0,this.playRevealedSounds(),this.renderBody(),this.prompt.visible=!1,this.prompt.x=r?0:this.contentWidth-this.prompt.width,this.prompt.y=this.contentHeight-this.prompt.height}renderBody(){if(this.mode===`adv`){this.body.setText(this.pageText.slice(0,Math.floor(this.reveal.revealed)));return}let e=this.pages.slice(0,this.pageIndex).map(e=>this.formatLine(e,vI(e.text).text)),t=this.pages[this.pageIndex];e.push(this.formatLine(t,this.pageText.slice(0,Math.floor(this.reveal.revealed)))),this.body.setText(e.join(`
1376
1376
 
1377
- `))}formatLine(e,t){return e.speaker===void 0?t:`${e.speaker}: ${t}`}playRevealedSounds(){let e=Math.floor(this.reveal.revealed);for(;this.nextCue<this.pageCues.length&&this.pageCues[this.nextCue].index<=e;)this.onSound?.(this.pageCues[this.nextCue].path),this.nextCue++}get pageComplete(){return rF(this.reveal)}update(e){if(!this.finished){if(!this.pageComplete){tF(this.reveal,e),this.playRevealedSounds(),this.renderBody();return}this.prompt.visible=!this.choiceList,!(this.autoAdvance===void 0||this.choiceList)&&(this.autoAdvanceElapsed+=e,this.autoAdvanceElapsed>=this.autoAdvance&&(this.autoAdvanceElapsed=0,this.advance()))}}handleAction(e){return this.delegate?super.handleAction(e):e===`confirm`?this.pageComplete?(this.advance(),!0):(nF(this.reveal),this.playRevealedSounds(),this.renderBody(),!0):!1}advance(){if(this.pageIndex<this.pages.length-1){this.pageIndex++,this.showPage(this.pageIndex);return}if(this.choices.length>0){this.showChoices();return}this.finish(void 0)}showChoices(){let e=Q(),t=this.choices.map(e=>({text:e.text,disabled:e.disabled,value:e.value??e.text}));this.announce&&eI.announce(this.choices.map(e=>e.text).join(`, `));let n=Math.ceil(e.font.size*e.font.lineHeight)+e.spacing,r=t.length*n,i=this.body.y+this.body.height+e.padding,a=i+r-this.contentHeight;a>0&&this.grow(a),this.choiceList=new iI({width:this.contentWidth,height:r,items:t,onSelect:e=>this.finish(e.value)}),this.choiceList.y=i,this.content.addChild(this.choiceList),this.delegate=this.choiceList,this.prompt.visible=!1}grow(e){let t=this.getLocalBounds();this.resize(t.width,t.height+e),this.y=Math.max(0,this.y-e)}finish(e){this.finished||(this.finished=!0,this.onDone?.(e),this.close())}},HL=class{constructor(e={}){this.goalColumn=null,this.multiline=e.multiline??!1,this.text=this.limit(this.shape(e.value??``)),this.maxLength=e.maxLength,this.mask=e.mask??!1,this.maskCharacter=e.maskCharacter??`•`,this.caretIndex=this.text.length,this.anchor=this.caretIndex}get value(){return this.text}get maskedValue(){return this.mask?this.text.split(``).map(e=>e===`
1377
+ `))}formatLine(e,t){return e.speaker===void 0?t:`${e.speaker}: ${t}`}playRevealedSounds(){let e=Math.floor(this.reveal.revealed);for(;this.nextCue<this.pageCues.length&&this.pageCues[this.nextCue].index<=e;)this.onSound?.(this.pageCues[this.nextCue].path),this.nextCue++}get pageComplete(){return oF(this.reveal)}update(e){if(!this.finished){if(!this.pageComplete){iF(this.reveal,e),this.playRevealedSounds(),this.renderBody();return}this.prompt.visible=!this.choiceList,!(this.autoAdvance===void 0||this.choiceList)&&(this.autoAdvanceElapsed+=e,this.autoAdvanceElapsed>=this.autoAdvance&&(this.autoAdvanceElapsed=0,this.advance()))}}handleAction(e){return this.delegate?super.handleAction(e):e===`confirm`?this.pageComplete?(this.advance(),!0):(aF(this.reveal),this.playRevealedSounds(),this.renderBody(),!0):!1}advance(){if(this.pageIndex<this.pages.length-1){this.pageIndex++,this.showPage(this.pageIndex);return}if(this.choices.length>0){this.showChoices();return}this.finish(void 0)}showChoices(){let e=Q(),t=this.choices.map(e=>({text:e.text,disabled:e.disabled,value:e.value??e.text}));this.announce&&rI.announce(this.choices.map(e=>e.text).join(`, `));let n=Math.ceil(e.font.size*e.font.lineHeight)+e.spacing,r=t.length*n,i=this.body.y+this.body.height+e.padding,a=i+r-this.contentHeight;a>0&&this.grow(a),this.choiceList=new sI({width:this.contentWidth,height:r,items:t,onSelect:e=>this.finish(e.value)}),this.choiceList.y=i,this.content.addChild(this.choiceList),this.delegate=this.choiceList,this.prompt.visible=!1}grow(e){let t=this.getLocalBounds();this.resize(t.width,t.height+e),this.y=Math.max(0,this.y-e)}finish(e){this.finished||(this.finished=!0,this.onDone?.(e),this.close())}},GL=class{constructor(e={}){this.goalColumn=null,this.multiline=e.multiline??!1,this.text=this.limit(this.shape(e.value??``)),this.maxLength=e.maxLength,this.mask=e.mask??!1,this.maskCharacter=e.maskCharacter??`•`,this.caretIndex=this.text.length,this.anchor=this.caretIndex}get value(){return this.text}get maskedValue(){return this.mask?this.text.split(``).map(e=>e===`
1378
1378
  `?`
1379
1379
  `:this.maskCharacter).join(``):this.text}get length(){return this.text.length}get caret(){return this.caretIndex}get selectionStart(){return Math.min(this.caretIndex,this.anchor)}get selectionEnd(){return Math.max(this.caretIndex,this.anchor)}get hasSelection(){return this.caretIndex!==this.anchor}get selectedText(){return this.text.slice(this.selectionStart,this.selectionEnd)}setValue(e){this.text=this.limit(this.shape(e)),this.caretIndex=this.text.length,this.anchor=this.caretIndex,this.goalColumn=null}setCaret(e,t=!1){this.caretIndex=Math.max(0,Math.min(this.text.length,e)),this.goalColumn=null,t||(this.anchor=this.caretIndex)}insert(e){e.length!==0&&this.replaceSelection(e)}backspace(){if(this.hasSelection){this.replaceSelection(``);return}this.caretIndex!==0&&(this.text=this.text.slice(0,this.caretIndex-1)+this.text.slice(this.caretIndex),this.setCaret(this.caretIndex-1))}deleteForward(){if(this.hasSelection){this.replaceSelection(``);return}this.caretIndex>=this.text.length||(this.text=this.text.slice(0,this.caretIndex)+this.text.slice(this.caretIndex+1),this.setCaret(this.caretIndex))}moveCaret(e,t=!1){this.setCaret(this.caretIndex+e,t)}moveToStart(e=!1){this.setCaret(0,e)}moveToEnd(e=!1){this.setCaret(this.text.length,e)}selectAll(){this.anchor=0,this.caretIndex=this.text.length,this.goalColumn=null}clearSelection(){this.anchor=this.caretIndex}replaceSelection(e){let t=this.selectionStart,n=this.selectionEnd,r=this.text.slice(0,t)+this.text.slice(n),i=this.shape(e),a=this.maxLength!==void 0&&r.length+i.length>this.maxLength?i.slice(0,Math.max(0,this.maxLength-r.length)):i;this.text=this.text.slice(0,t)+a+this.text.slice(n),this.setCaret(t+a.length)}shape(e){return e.replace(/\r\n|\r|\n/g,this.multiline?`
1380
1380
  `:``)}get lineCount(){return this.multiline?this.text.split(`
1381
1381
  `).length:1}get caretLine(){return this.text.slice(0,this.caretIndex).split(`
1382
1382
  `).length-1}lineRange(e){let t=Math.max(0,Math.min(this.lineCount-1,e)),n=0;for(let e=0;e<t;e++)n=this.text.indexOf(`
1383
1383
  `,n)+1;let r=this.text.indexOf(`
1384
- `,n);return[n,r===-1?this.text.length:r]}moveCaretLine(e,t=!1){let[n]=this.lineRange(this.caretLine),r=this.goalColumn??this.caretIndex-n,[i,a]=this.lineRange(this.caretLine+e);this.setCaret(i+Math.min(r,a-i),t),this.goalColumn=r}limit(e){return this.maxLength!==void 0&&e.length>this.maxLength?e.slice(0,this.maxLength):e}},UL=class e extends Y{constructor(t){super(),this.onClick=new p,this.onPress=new p,this.onRelease=new p,this.state=`idle`,this.themeListener=()=>this.draw(),this.width_=t.width,this.height_=t.height,this.disabled_=t.disabled??!1,this.skin=t.skin,this.labelOptions=t.label??{};let n=Q();this.background=e.createBackground(this.skin,n),this.addChild(this.background),this.icon=t.icon??null,this.icon&&this.addChild(this.icon),this.labelText=t.text===void 0?null:new iF({align:`center`,...this.labelOptions,text:t.text}),this.labelText&&this.addChild(this.labelText),t.onClick&&this.onClick.add(t.onClick),t.onPress&&this.onPress.add(t.onPress),t.onRelease&&this.onRelease.add(t.onRelease),this.eventMode=`static`,this.on(`pointerover`,()=>this.setState(`hover`)),this.on(`pointerout`,()=>this.setState(`idle`)),this.on(`pointerdown`,()=>{this.setState(`pressed`),this.onPress.dispatch()}),this.on(`pointerup`,()=>{let e=this.state===`pressed`;this.setState(`hover`),e&&(this.onRelease.dispatch(),this.onClick.dispatch())}),this.on(`pointerupoutside`,()=>{let e=this.state===`pressed`;this.setState(`idle`),e&&this.onRelease.dispatch()}),this.setState(this.disabled_?`disabled`:`idle`),$.add(this.themeListener)}static createBackground(e,t){return e?new ZF(e.texture,{border:e.border}):t.panel?new ZF(t.panel,{border:t.panelBorder}):new bE}resize(e,t){this.width_=e,this.height_=t,this.draw()}setText(e){e===void 0?(this.labelText?.destroy(),this.labelText=null):this.labelText?this.labelText.setText(e):(this.labelText=new iF({align:`center`,...this.labelOptions,text:e}),this.addChild(this.labelText)),this.layoutContent()}get disabled(){return this.disabled_}setDisabled(e){this.disabled_=e,this.setState(e?`disabled`:`idle`)}setState(e){this.disabled_&&e!==`disabled`||(this.state=e,this.cursor=this.disabled_?`default`:`pointer`,this.eventMode=this.disabled_?`none`:`static`,this.draw())}layoutContent(){let e=Q().direction===`rtl`;if(this.icon&&!this.labelText){this.icon.x=Math.round((this.width_-this.icon.width)/2),this.icon.y=Math.round((this.height_-this.icon.height)/2);return}if(this.icon&&this.labelText){let t=Q().spacing,n=this.icon.width+t+this.labelText.width,r=Math.round((this.width_-n)/2);this.icon.x=e?r+this.labelText.width+t:r,this.icon.y=Math.round((this.height_-this.icon.height)/2),this.labelText.x=e?r:r+this.icon.width+t,this.labelText.y=Math.round((this.height_-this.labelText.height)/2);return}this.labelText&&(this.labelText.x=Math.round((this.width_-this.labelText.width)/2),this.labelText.y=Math.round((this.height_-this.labelText.height)/2))}draw(){let e=Q(),t=this.state===`pressed`?10066329:this.state===`hover`?14540253:this.state===`disabled`?7829367:16777215;if(this.background instanceof ZF)this.background.resize(this.width_,this.height_),this.background.tint=this.skin?.tints?.[this.state]??t;else{let t=this.state===`pressed`?e.color.selection:e.color.panelFill;this.background.clear().roundRect(0,0,this.width_,this.height_,4).fill({color:t,alpha:this.state===`disabled`?.5:1}).stroke({color:e.color.panelBorder,width:1})}this.labelText?.setColor(this.disabled_?e.color.textDim:this.labelOptions.color??e.color.text),this.icon&&(this.icon.alpha=this.disabled_?.4:1),this.layoutContent()}destroy(e){$.remove(this.themeListener),super.destroy(e)}},WL=e=>e.split(``).map(e=>({label:e})),GL={rows:[WL(`QWERTYUIOP`),WL(`ASDFGHJKL`),WL(`ZXCVBNM`),WL(`1234567890`),[{label:`Bksp`,action:`backspace`},{label:`Left`,action:`left`},{label:`Right`,action:`right`},{label:`Space`,text:` `,span:3},{label:`OK`,action:`confirm`},{label:`Esc`,action:`cancel`}]]};function KL(e){e.action===void 0?we(e.text??e.label):Te(e.action)}function qL(e,t){let n=[],r=0;for(let i of e.rows){let e=i.reduce((e,t)=>e+(t.span??1),0),a=(t.width-t.gap*(e-1))/e,o=0;for(let e of i){let i=e.span??1,s=a*i+t.gap*(i-1);n.push({key:e,x:o,y:r,width:s,height:t.keyHeight}),o+=s+t.gap}r+=t.keyHeight+t.gap}return n}var JL=class extends Y{constructor(e,t){super();let n=Q().spacing,r=Math.max(Q().font.size*2,18),i=0;for(let a of qL(e,{width:t.width,keyHeight:r,gap:n})){let e=new UL({width:a.width,height:a.height,text:a.key.label,onClick:()=>KL(a.key)});e.position.set(a.x,a.y),this.addChild(e),i=Math.max(i,a.y+a.height)}this.laidOutHeight=i}get contentHeight(){return this.laidOutHeight}},YL=.5,XL=class extends tI{constructor(e){super({width:e.width,height:e.height,title:e.title,modal:!0,closable:!1,dims:e.dims,blocker:e.blocker??!0,anchor:e.anchor??`center`}),this.preview=``,this.promptError=null,this.keyboard=null,this.messageLabel=null,this.caretBar=new bE,this.measurer=new iF,this.canMeasureCaret=typeof document<`u`,this.blinkOn=!0,this.blinkElapsed=0,this.promptThemeListener=()=>this.restylePrompt(),this.textListener=e=>!this.closed&&(this.edit(()=>this.model.insert(e)),!0),this.compositionListener=e=>!this.closed&&(e.phase===`end`?this.edit(()=>{this.preview=``,this.model.insert(e.text)}):(this.preview=e.phase===`start`?``:e.text,this.render()),!0),this.model=new HL({value:e.initialValue??``,maxLength:e.maxLength}),this.validate=e.validate,this.onConfirm=e.onConfirm,this.onCancel=e.onCancel,this.announce=e.announce??!0,this.announcer=e.announcer??eI;let t=Q();this.lineHeight=t.font.size*t.font.lineHeight;let n=t.spacing;e.message!==void 0&&(this.messageLabel=new iF({text:e.message}),this.content.addChild(this.messageLabel)),this.valueY=this.messageLabel?this.lineHeight+n:0,this.valueLabel=new iF,this.valueLabel.y=this.valueY,this.content.addChild(this.valueLabel),this.previewLabel=new iF({color:t.color.textDim}),this.previewLabel.y=this.valueY+this.lineHeight+n,this.content.addChild(this.previewLabel),this.errorLabel=new iF({color:t.color.textHighlight}),this.errorLabel.y=this.previewLabel.y+this.lineHeight+n,this.content.addChild(this.errorLabel),this.content.addChild(this.caretBar),e.keyboard&&(this.keyboard=new JL(e.keyboard,{width:this.contentWidth}),this.keyboard.y=this.errorLabel.y+this.lineHeight+n,this.content.addChild(this.keyboard),this.resize(e.width,e.height+this.keyboard.contentHeight+n)),Se.add(this.textListener),F.add(this.compositionListener),$.add(this.promptThemeListener),this.render(),this.announce&&e.message!==void 0&&this.announcer.announce(e.message)}get value(){return this.model.value}get caretIndex(){return this.model.caret}get error(){return this.promptError}handleAction(e){if(this.delegate)return super.handleAction(e);if(this.closed)return!1;switch(e){case`left`:return this.model.moveCaret(-1),this.render(),!0;case`right`:return this.model.moveCaret(1),this.render(),!0;case`backspace`:return this.edit(()=>this.model.backspace()),!0;case`delete`:return this.edit(()=>this.model.deleteForward()),!0;case`confirm`:return this.confirm(),!0;case`cancel`:return this.onCancel?.(),this.close(),!0;default:return!1}}update(e){this.blinkElapsed+=e,!(this.blinkElapsed<YL)&&(this.blinkElapsed=0,this.blinkOn=!this.blinkOn,this.caretBar.visible=this.blinkOn&&this.canMeasureCaret)}destroy(e){Se.remove(this.textListener),F.remove(this.compositionListener),$.remove(this.promptThemeListener),this.measurer.destroy(),super.destroy(e)}edit(e){let t=this.model.value;e(),this.model.value!==t&&(this.promptError=null),this.render()}confirm(){let e=this.validate?.(this.model.value)??null;if(e){this.promptError=e,this.render(),this.announce&&this.announcer.announce(e,{assertive:!0});return}this.onConfirm(this.model.value),this.close()}restylePrompt(){let e=Q();this.previewLabel.setColor(e.color.textDim),this.errorLabel.setColor(e.color.textHighlight),this.render()}render(){this.valueLabel.setText(this.model.value),this.measurer.setText(this.model.value.slice(0,this.model.caret));let e=0;if(this.canMeasureCaret)try{e=this.measurer.width}catch{this.canMeasureCaret=!1}this.caretBar.clear().rect(this.valueLabel.x+e,this.valueY,2,this.lineHeight).fill({color:Q().color.text}),this.caretBar.visible=this.blinkOn&&this.canMeasureCaret,this.previewLabel.setText(this.preview),this.previewLabel.visible=this.preview.length>0,this.errorLabel.setText(this.promptError??``),this.errorLabel.visible=this.promptError!==null}},ZL=/[A-Za-z0-9]/;function QL(e,t){let{lineHeight:n,columnHeight:r}=t,i=t.rotate??ZL,a=[],o=0,s=0;for(let t of e){if(t===`
1385
- `){o++,s=0;continue}s*n>=r&&(o++,s=0);let e=i.test(t),c=o===0?0:-o*n;a.push({char:t,x:e?c-n/2:c,y:e?s*n+n/2:s*n,rotate:e}),s++}return a}var $L=class extends Y{constructor(e){super(),this.themeListener=e=>this.build(e),this.opts=e,this.build(Q()),$.add(this.themeListener)}build(e){this.removeChildren().forEach(e=>e.destroy());let t=this.opts.size??e.font.size,n=Math.ceil(t*e.font.lineHeight),r=QL(this.opts.text,{lineHeight:n,columnHeight:this.opts.columnHeight,rotate:this.opts.rotate});for(let n of r){let r=new wA({text:n.char,style:{fontFamily:e.font.family,fontSize:t,fill:this.opts.color??e.color.text}});n.rotate&&(r.anchor.set(.5),r.rotation=Math.PI/2),r.x=n.x,r.y=n.y,this.addChild(r)}}destroy(e){$.remove(this.themeListener),super.destroy(e)}};function eR(e,t=0,n=1){return n>t?Math.max(0,Math.min(1,(e-t)/(n-t))):0}function tR(e,t=0,n=1,r=0){let i=t+Math.max(0,Math.min(1,e))*(n-t);if(!(r>0))return i;let a=(String(r).split(`.`)[1]??``).length,o=t+Math.round((i-t)/r)*r;return Number(Math.max(t,Math.min(n,o)).toFixed(a))}var nR=class extends Y{constructor(e){super(),this.onChange=new p,this.track=new bE,this.fill=new bE,this.knob=new bE,this.dragging=!1,this.themeListener=()=>this.draw(),this.handleDown=e=>{this.disabled_||(this.dragging=!0,this.setFraction(this.fractionAt(this.toLocal(e.global).x)))},this.handleMove=e=>{this.dragging&&!this.disabled_&&this.setFraction(this.fractionAt(this.toLocal(e.global).x))},this.handleUp=()=>{this.dragging=!1},this.width_=e.width,this.height_=e.height??6,this.knobSize=e.knobSize??Math.max(12,this.height_*2),this.min=e.min??0,this.max=e.max??1,this.step=e.step??0,this.value_=this.snap(e.value??this.min),this.disabled_=e.disabled??!1,this.addChild(this.track),this.addChild(this.fill),this.addChild(this.knob),this.draw(),this.eventMode=`static`,this.cursor=`pointer`,this.on(`pointerdown`,this.handleDown),this.on(`pointermove`,this.handleMove),this.on(`pointerup`,this.handleUp),this.on(`pointerupoutside`,this.handleUp),$.add(this.themeListener)}get value(){return this.value_}get fraction(){return eR(this.value_,this.min,this.max)}get disabled(){return this.disabled_}setDisabled(e){this.disabled_=e,this.cursor=e?`default`:`pointer`,this.draw()}setValue(e){let t=this.snap(e);if(t===this.value_){this.draw();return}this.value_=t,this.draw(),this.onChange.dispatch(t)}setFraction(e){this.setValue(tR(e,this.min,this.max,this.step))}resize(e,t){this.width_=e,this.height_=t,this.draw()}get trackLength(){return Math.max(0,this.width_-this.knobSize)}snap(e){return tR(eR(e,this.min,this.max),this.min,this.max,this.step)}fractionAt(e){return this.trackLength>0?Math.max(0,Math.min(1,(e-this.knobSize/2)/this.trackLength)):0}draw(){let e=Q(),t=this.disabled_?e.color.textDim:e.color.textHighlight,n=e.color.panelFill,r=(this.knobSize-this.height_)/2;this.track.clear().roundRect(0,r,this.width_,this.height_,this.height_/2).fill({color:n});let i=this.knobSize/2+this.fraction*this.trackLength;this.fill.clear(),i>this.knobSize/2&&this.fill.roundRect(this.knobSize/2,r,i-this.knobSize/2,this.height_,this.height_/2).fill({color:t}),this.knob.clear().circle(i,this.knobSize/2,this.knobSize/2).fill({color:t})}destroy(e){$.remove(this.themeListener),super.destroy(e)}},rR=class extends Y{constructor(e={}){super(),this.onChange=new p,this.box=new bE,this.themeListener=()=>this.draw(),this.handleTap=()=>{this.disabled_||this.toggle()},this.size_=e.size??20,this.checked_=e.checked??!1,this.disabled_=e.disabled??!1,this.addChild(this.box),this.draw(),this.eventMode=`static`,this.cursor=`pointer`,this.on(`pointertap`,this.handleTap),$.add(this.themeListener)}get checked(){return this.checked_}get disabled(){return this.disabled_}setDisabled(e){this.disabled_=e,this.cursor=e?`default`:`pointer`,this.draw()}setChecked(e){if(e===this.checked_){this.draw();return}this.checked_=e,this.draw(),this.onChange.dispatch(e)}toggle(){this.setChecked(!this.checked_)}resize(e){this.size_=e,this.draw()}draw(){let e=Q(),t=this.disabled_?e.color.textDim:e.color.textHighlight;if(this.box.clear().roundRect(0,0,this.size_,this.size_,4).fill({color:e.color.panelFill}).stroke({color:this.disabled_?e.color.textDim:e.color.panelBorder,width:2}),this.checked_){let e=this.size_*.25;this.box.moveTo(e,this.size_*.55).lineTo(this.size_*.45,this.size_-e).lineTo(this.size_-e,e).stroke({color:t,width:Math.max(2,this.size_*.12),cap:`round`,join:`round`})}}destroy(e){$.remove(this.themeListener),super.destroy(e)}},iR=class extends Y{constructor(e={}){super(),this.onChange=new p,this.options_=[],this.rows=[],this.circles=[],this.selected_=-1,this.themeListener=()=>this.draw(),this.size_=e.size??20,this.gap_=e.gap??8,this.buildRows(e.options??[]),this.selected_=this.defaultSelection(e.selected),this.draw(),$.add(this.themeListener)}get selected(){return this.selected_}get selectedOption(){return this.options_[this.selected_]??null}get length(){return this.options_.length}get rowHeight(){return this.size_+this.gap_}setOptions(e,t){this.buildRows(e),this.selected_=this.defaultSelection(t),this.draw()}select(e){let t=this.options_[e];if(t&&!t.disabled){if(e===this.selected_){this.draw();return}this.selected_=e,this.draw(),this.onChange.dispatch(e)}}move(e){let t=this.options_.length;if(t===0)return!1;let n=this.selected_;for(let r=0;r<t;r++){n=(n+e+t)%t;let r=this.options_[n];if(r&&!r.disabled)return this.select(n),!0}return!1}handleAction(e){switch(e){case`up`:case`left`:return this.move(-1);case`down`:case`right`:return this.move(1);default:return!1}}tapRow(e){this.select(e)}defaultSelection(e){if(e!==void 0){let t=this.options_[e];if(t&&!t.disabled)return e}let t=this.options_.findIndex(e=>!e.disabled);return t===-1?-1:t}buildRows(e){for(let e of this.rows)e.destroy({children:!0});this.rows=[],this.circles=[],this.options_=[...e],this.removeChildren(),e.forEach((e,t)=>{let n=new Y;n.y=t*this.rowHeight,n.eventMode=`static`,n.cursor=e.disabled?`default`:`pointer`,n.on(`pointertap`,()=>this.tapRow(t));let r=new bE;n.addChild(r),this.circles.push(r);let i=new iF({text:e.text});n.addChild(i),this.rows.push(n),this.addChild(n)})}draw(){let e=Q(),t=e.direction===`rtl`;this.rows.forEach((n,r)=>{let i=this.options_[r].disabled,a=this.circles[r];a.clear().circle(this.size_/2,this.size_/2,this.size_/2-1).fill({color:e.color.panelFill}).stroke({color:i?e.color.textDim:e.color.panelBorder,width:2}),r===this.selected_&&a.circle(this.size_/2,this.size_/2,Math.max(2,this.size_*.28)).fill({color:i?e.color.textDim:e.color.textHighlight});let o=this.size_+e.spacing,s=n.children.find(e=>e instanceof iF),c=s?.width??0;s&&(s.setColor(i?e.color.textDim:e.color.text),s.y=Math.round((this.size_-s.height)/2)),t?(s&&(s.x=0),a.x=c+e.spacing):(a.x=0,s&&(s.x=o))})}destroy(e){$.remove(this.themeListener),super.destroy(e)}};function aR(e,t,n,r,i=1,a=!1){if(!(r>n))return n;let o=i>0?i:1,s=(String(o).split(`.`)[1]??``).length,c=Math.round((e-n)/o)+Math.round(t),l=Math.round((r-n)/o)+1,u=c;return u=a?(u%l+l)%l:Math.max(0,Math.min(l-1,u)),Number((n+u*o).toFixed(s))}var oR=class extends Y{constructor(e={}){super(),this.onChange=new p,this.face=new bE,this.themeListener=()=>this.draw(),this.handleTap=e=>{this.disabled_||(this.toLocal(e.global).y<this.height_/2?this.increment():this.decrement())},this.width_=e.width??24,this.height_=e.height??32,this.min=e.min??0,this.max=e.max??9,this.step=e.step??1,this.wrap=e.wrap??!1,this.disabled_=e.disabled??!1,this.value_=aR(e.value??this.min,0,this.min,this.max,this.step,!1),this.addChild(this.face),this.draw(),this.eventMode=`static`,this.cursor=`pointer`,this.on(`pointertap`,this.handleTap),$.add(this.themeListener)}get value(){return this.value_}get disabled(){return this.disabled_}setDisabled(e){this.disabled_=e,this.cursor=e?`default`:`pointer`,this.draw()}setValue(e){this.commit(aR(e,0,this.min,this.max,this.step,this.wrap))}increment(){this.commit(aR(this.value_,1,this.min,this.max,this.step,this.wrap))}decrement(){this.commit(aR(this.value_,-1,this.min,this.max,this.step,this.wrap))}resize(e,t){this.width_=e,this.height_=t,this.draw()}commit(e){if(e===this.value_){this.draw();return}this.value_=e,this.draw(),this.onChange.dispatch(e)}draw(){let e=Q(),t=this.disabled_?e.color.textDim:e.color.textHighlight;this.face.clear().roundRect(0,0,this.width_,this.height_,4).fill({color:e.color.panelFill}).stroke({color:e.color.panelBorder,width:1});let n=this.width_/2,r=Math.min(this.width_/4,this.height_/5);this.face.moveTo(n-r,r*1.6).lineTo(n,r*.6).lineTo(n+r,r*1.6).closePath().fill({color:t}),this.face.moveTo(n-r,this.height_-r*1.6).lineTo(n,this.height_-r*.6).lineTo(n+r,this.height_-r*1.6).closePath().fill({color:t})}destroy(e){$.remove(this.themeListener),super.destroy(e)}},sR=class{constructor(e){this.onChange=new p,this.open_=!1,this.options_=[...e.options],this.disabled_=e.disabled??!1;let t=e.selectedIndex??this.firstEnabled();this.current=this.options_[t]?.disabled?this.firstEnabled():t,this.highlight_=this.current}get options(){return this.options_}get selectedIndex(){return this.current}get selected(){return this.options_[this.current]??null}get isOpen(){return this.open_}get disabled(){return this.disabled_}get highlight(){return this.highlight_}setDisabled(e){this.disabled_=e,e&&(this.open_=!1)}setOptions(e){this.options_=[...e],this.current=this.firstEnabled(),this.highlight_=this.current,this.open_=!1}open(){this.disabled_||this.open_||(this.open_=!0,this.highlight_=this.current)}close(){this.open_=!1}toggleOpen(){this.open_?this.close():this.open()}move(e){if(!this.open_||this.options_.length===0)return;let t=this.options_.length,n=this.highlight_;for(let r=0;r<t;r++)if(n=((n+e)%t+t)%t,!this.options_[n].disabled){this.highlight_=n;return}}setHighlight(e){e<0||e>=this.options_.length||this.options_[e].disabled||(this.highlight_=e)}confirm(){if(!this.open_)return!1;let e=this.options_[this.highlight_];return!e||e.disabled?!1:(this.open_=!1,this.highlight_!==this.current&&(this.current=this.highlight_,this.onChange.dispatch({option:e,index:this.current})),!0)}cancel(){this.open_=!1,this.highlight_=this.current}firstEnabled(){let e=this.options_.findIndex(e=>!e.disabled);return e===-1?0:e}},cR=class{constructor(e){this.onChange=new p,this.current=0,this.sortKey_=null,this.ascending=!0,this.columns_=[...e.columns],this.rows_=[...e.rows??[]],this.pageSize_=e.pageSize??0,this.disabledOf=e.disabled??(()=>!1),this.current=this.firstEnabled()}get columns(){return this.columns_}get rows(){return this.rows_}get pageSize(){return this.pageSize_}get sortKey(){return this.sortKey_}get sortAscending(){return this.ascending}get selectedIndex(){return this.current}get selected(){return this.rows_[this.current]??null}get page(){return this.pageSize_>0?Math.floor(this.current/this.pageSize_):0}get pageCount(){return this.pageSize_>0?Math.max(1,Math.ceil(this.rows_.length/this.pageSize_)):1}get pageRows(){if(this.pageSize_<=0)return this.rows_;let e=this.page*this.pageSize_;return this.rows_.slice(e,e+this.pageSize_)}setRows(e){this.rows_=[...e],this.current=this.firstEnabled(),this.onChange.dispatch()}setColumns(e){this.columns_=[...e],this.sortKey_&&!this.columns_.some(e=>e.key===this.sortKey_)&&(this.sortKey_=null),this.onChange.dispatch()}setPageSize(e){this.pageSize_=Math.max(0,e),this.onChange.dispatch()}sortBy(e){let t=this.columns_.find(t=>t.key===e);if(!t)return;this.sortKey_===e?this.ascending=!this.ascending:(this.sortKey_=e,this.ascending=!0);let n=t.compare??((t,n)=>uR(lR(t,e),lR(n,e)));this.rows_.sort((e,t)=>(this.ascending?1:-1)*n(e,t)),this.current=this.firstEnabled(),this.onChange.dispatch()}select(e){e<0||e>=this.rows_.length||this.disabledOf(this.rows_[e])||(this.current=e,this.onChange.dispatch())}move(e){let t=this.rows_.length;if(t===0)return;let n=this.current;for(let r=0;r<t;r++){if(n+=e,n<0||n>=t)return;if(!this.disabledOf(this.rows_[n])){this.current=n,this.onChange.dispatch();return}}}setPage(e){if(this.pageSize_<=0)return;let t=Math.max(0,Math.min(this.pageCount-1,e))*this.pageSize_,n=Math.min(t+this.pageSize_,this.rows_.length);for(let e=t;e<n;e++)if(!this.disabledOf(this.rows_[e])){this.current=e,this.onChange.dispatch();return}}nextPage(e=1){this.setPage(this.page+e)}firstEnabled(){let e=this.rows_.findIndex(e=>!this.disabledOf(e));return e===-1?0:e}};function lR(e,t){return e&&typeof e==`object`?e[t]:void 0}function uR(e,t){return e===t?0:e===void 0?-1:t===void 0?1:typeof e==`number`&&typeof t==`number`?e-t:String(e).localeCompare(String(t))}var dR=class{constructor(e){this.onChange=new p,this.expanded=new Set,this.current=0,this.roots_=e.roots;for(let t of e.expanded??[])this.expanded.add(t);this.disabledOf=e.disabled??(()=>!1),this.current=this.firstEnabled()}get roots(){return this.roots_}get rows(){let e=[],t=(n,r)=>{for(let i of n){let n=(i.children?.length??0)>0,a=n&&this.expanded.has(i.id);e.push({node:i,depth:r,expanded:a,hasChildren:n}),a&&t(i.children,r+1)}};return t(this.roots_,0),e}get selectedIndex(){return this.current}get selected(){return this.rows[this.current]?.node??null}isExpanded(e){return this.expanded.has(e)}expand(e){this.expanded.has(e)||(this.expanded.add(e),this.onChange.dispatch())}collapse(e){if(!this.expanded.has(e))return;let t=this.rows[this.current]?.node.id;if(this.expanded.delete(e),t!==void 0&&!this.rows.some(e=>e.node.id===t)){let t=this.rows.findIndex(t=>t.node.id===e);t>=0&&(this.current=t)}this.onChange.dispatch()}toggle(e){this.expanded.has(e)?this.collapse(e):this.expand(e)}expandAll(){let e=t=>{for(let n of t)n.children?.length&&(this.expanded.add(n.id),e(n.children))};e(this.roots_),this.onChange.dispatch()}collapseAll(){this.expanded.clear(),this.select(0),this.onChange.dispatch()}select(e){let t=this.rows[e];t&&!this.disabledOf(t.node)&&(this.current=e,this.onChange.dispatch())}move(e){let t=this.rows.length;if(t===0)return;let n=this.current;for(let r=0;r<t;r++){if(n+=e,n<0||n>=t)return;if(!this.disabledOf(this.rows[n].node)){this.current=n,this.onChange.dispatch();return}}}firstEnabled(){let e=this.rows.findIndex(e=>!this.disabledOf(e.node));return e===-1?0:e}};function fR(e,t,n){return Math.max(0,Math.min(Math.max(0,t-n),e))}var pR=class extends Y{constructor(e){super(),this.onChange=new p,this.content=new Y,this.maskShape=new bE,this.track=new bE,this.thumb=new bE,this.themeListener=()=>this.draw(),this.handleWheel=e=>{this.scrollBy(e.deltaY)},this.width_=e.width,this.height_=e.height,this.contentHeight_=Math.max(0,e.contentHeight??0),this.offset_=fR(e.offset??0,this.contentHeight_,this.height_),this.addChild(this.content),this.addChild(this.maskShape),this.addChild(this.track),this.addChild(this.thumb),this.content.mask=this.maskShape,this.eventMode=`static`,this.on(`wheel`,this.handleWheel),this.draw(),$.add(this.themeListener)}get offset(){return this.offset_}get contentHeight(){return this.contentHeight_}get viewportHeight(){return this.height_}get maxOffset(){return Math.max(0,this.contentHeight_-this.height_)}get scrollable(){return this.maxOffset>0}setContentHeight(e){this.contentHeight_=Math.max(0,e),this.setOffset(fR(this.offset_,this.contentHeight_,this.height_))}resize(e,t){this.width_=e,this.height_=t,this.setOffset(fR(this.offset_,this.contentHeight_,this.height_))}scrollBy(e){this.setOffset(fR(this.offset_+e,this.contentHeight_,this.height_))}scrollTo(e){this.setOffset(fR(e,this.contentHeight_,this.height_))}scrollIntoView(e,t){e<this.offset_?this.scrollTo(e):e+t>this.offset_+this.height_&&this.scrollTo(e+t-this.height_)}setOffset(e){if(e===this.offset_){this.draw();return}this.offset_=e,this.draw(),this.onChange.dispatch(e)}draw(){let e=Q();if(this.content.y=-this.offset_,this.maskShape.clear().rect(0,0,this.width_,this.height_).fill({color:16777215}),this.track.clear(),this.thumb.clear(),!this.scrollable)return;let t=this.width_-6;this.track.roundRect(t,0,6,this.height_,3).fill({color:e.color.panelFill});let n=Math.max(6,this.height_/this.contentHeight_*this.height_),r=this.offset_/this.maxOffset*(this.height_-n);this.thumb.roundRect(t,r,6,n,3).fill({color:e.color.textHighlight})}destroy(e){$.remove(this.themeListener),super.destroy(e)}};function mR(e){switch(e){case`top`:case`bottom`:return{x:.5,y:e===`top`?0:1};case`left`:case`right`:return{x:e===`left`?0:1,y:.5};case`top-left`:return{x:0,y:0};case`top-right`:return{x:1,y:0};case`bottom-left`:return{x:0,y:1};case`bottom-right`:return{x:1,y:1};default:return{x:.5,y:.5}}}function hR(e,t,n={width:0,height:0}){let r=e.margin??0,i=t.x+r,a=t.y+r,o=Math.max(0,t.width-r*2),s=Math.max(0,t.height-r*2);if(e.anchor===`fill`){let t=i+(e.offsetX??0),n=a+(e.offsetY??0);return{x:t,y:n,width:e.width??Math.max(0,i+o-t),height:e.height??Math.max(0,a+s-n)}}let c=mR(e.anchor??`center`),l=e.alignX??c.x,u=e.alignY??c.y,d=e.width??n.width,f=e.height??n.height;return{x:i+l*Math.max(0,o-d)+(e.offsetX??0),y:a+u*Math.max(0,s-f)+(e.offsetY??0),width:d,height:f}}var gR=class{constructor(e){this.spec=e}get columns(){return this.spec.columns}get rows(){return this.spec.rows}columnSizes(e){return _R(this.spec.columns,e,this.gap)}rowSizes(e){return _R(this.spec.rows,e,this.gap)}rect(e,t,n,r={}){let i=this.columnSizes(n.width),a=this.rowSizes(n.height),o=r.columnSpan??1,s=r.rowSpan??1;return{x:n.x+yR(i,t,this.gap),y:n.y+yR(a,e,this.gap),width:bR(i,t,o,this.gap),height:bR(a,e,s,this.gap)}}get gap(){return this.spec.gap??0}};function _R(e,t,n){let r=n*Math.max(0,e.length-1),i=Math.max(0,t-r),a=e.reduce((e,t)=>e+(t.size??0),0),o=e.reduce((e,t)=>e+(t.grow??0),0),s=Math.max(0,i-a),c=0;return e.map((t,n)=>{if(t.size!==void 0)return t.size;if(!t.grow||o===0)return 0;let r=n===vR(e)?s-c:Math.floor(s*t.grow/o);return c+=r,r})}function vR(e){for(let t=e.length-1;t>=0;t--)if(e[t].grow)return t;return-1}function yR(e,t,n){let r=0;for(let i=0;i<t&&i<e.length;i++)r+=e[i]+n;return r}function bR(e,t,n,r){let i=0;for(let a=t;a<t+n&&a<e.length;a++)i+=e[a],a>t&&(i+=r);return Math.max(0,i)}var xR=[`idle`,`hover`,`pressed`,`disabled`,`selected`,`focused`],SR=class e{constructor(){this.map=new Map}static{this.ANY=`*`}define(e,t,n){let r=this.map.get(e)??{};r[t]={...r[t],...n},this.map.set(e,r)}has(e){return this.map.has(e)}widgets(){return[...this.map.keys()]}resolve(t,n=`idle`){return this.map.get(t)?.[n]??this.map.get(t)?.idle??this.map.get(e.ANY)?.[n]??this.map.get(e.ANY)?.idle??{}}statesOf(e){let t=this.map.get(e);return t?xR.filter(e=>t[e]!==void 0):[]}static from(t){let n=new e;for(let[e,r]of Object.entries(t))if(CR(r))for(let t of xR){let i=r[t];i&&n.define(e,t,i)}else n.define(e,`idle`,r);return n}};function CR(e){return xR.some(t=>e[t]!==void 0)}var wR=class extends Y{constructor(e){super(),this.capturing=null,this.onKeyCaptured=e=>this.capturing?(e.preventDefault(),e.code===`Escape`?this.cancelCapture():this.finishCapture(this.capturing,e.code),!0):!1,this.actions=[...e.actions],this.labelFor=e.label??(e=>e),this.onConflict=e.onConflict??(()=>!0),this.list=new iI({width:e.width,height:e.height,rowHeight:e.rowHeight,items:this.rows()}),this.addChild(this.list)}rows(){return this.actions.map(e=>({text:this.rowText(e),value:e,disabled:this.capturing!==null&&this.capturing!==e}))}rowText(e){if(this.capturing===e)return`${this.labelFor(e)}: press a key...`;let t=Ie(e);return`${this.labelFor(e)}: ${t.length?t.join(`, `):`(unbound)`}`}refresh(){let e=this.list.selectedIndex;this.list.setItems(this.rows()),this.list.select(e)}startCapture(e){this.capturing=e,this.refresh(),queueMicrotask(()=>{this.capturing===e&&xe.add(this.onKeyCaptured)})}cancelCapture(){xe.remove(this.onKeyCaptured),this.capturing=null,this.refresh()}finishCapture(e,t){xe.remove(this.onKeyCaptured),this.capturing=null;let n=Pe(t).filter(t=>t!==e);if(n.length>0&&!this.onConflict(t,e,n)){this.refresh();return}for(let e of n)Me(e,Ie(e).filter(e=>e!==t));Me(e,[t]),this.refresh()}get isCapturing(){return this.capturing!==null}handleAction(e){if(this.capturing)return!0;if(e===`confirm`){let e=this.list.selected?.value;return e&&this.startCapture(e),!0}return this.list.handleAction(e)}destroy(e){xe.remove(this.onKeyCaptured),super.destroy(e)}},TR=class extends Y{constructor(e){super(),this.highlight=new bE,this.main=new Y,this.rebindLayer=new Y,this.rows=[],this.selected=0,this.rebind=null,this.themeListener=()=>this.drawHighlight(),this.settings=e.settings,this.width_=e.width??320,this.rowHeight=e.rowHeight??36,this.labels={music:`Music`,sfx:`Sound effects`,muted:`Mute`,zoom:`Zoom`,controls:`Controls...`,reset:`Reset to defaults`,rebindHint:`Keys (cancel: back)`,...e.labels},this.zoomMin=e.zoomMin??.5,this.zoomMax=e.zoomMax??4,this.zoomStep=e.zoomStep??.25,this.customRows=e.custom??[],this.actionsOption=e.actions,this.onConflict=e.onConflict,this.addChild(this.highlight),this.addChild(this.main),this.addChild(this.rebindLayer),this.rebindLayer.visible=!1,this.buildMain(),this.refresh(),this.drawHighlight(),$.add(this.themeListener)}get selectedRow(){return this.rows[this.selected]?.id??``}get isRebinding(){return this.rebind!==null}handleAction(e){if(this.rebind)return e===`cancel`&&!this.rebind.isCapturing?(this.closeRebind(),!0):this.rebind.handleAction(e);let t=this.rows[this.selected];if(!t)return!1;switch(e){case`up`:return this.select((this.selected+this.rows.length-1)%this.rows.length),!0;case`down`:return this.select((this.selected+1)%this.rows.length),!0;case`left`:return t.adjust(-1),!0;case`right`:return t.adjust(1),!0;case`confirm`:return t.activate(),!0;default:return!1}}refresh(){for(let e of this.rows)e.refresh()}select(e){this.selected=e,this.drawHighlight()}drawHighlight(){if(this.rows.length===0){this.highlight.clear();return}this.highlight.clear().rect(0,this.selected*this.rowHeight,this.width_,this.rowHeight).fill({color:Q().color.selection})}buildMain(){let e=this.settings.current;this.addSliderRow(`music`,this.labels.music,0,100,1,10,Math.round(e.musicVolume*100),e=>this.settings.setMusicVolume(e/100)),this.addSliderRow(`sfx`,this.labels.sfx,0,100,1,10,Math.round(e.sfxVolume*100),e=>this.settings.setSfxVolume(e/100)),this.addToggleRow(`muted`,this.labels.muted,e.muted,e=>this.settings.setMuted(e)),this.addSliderRow(`zoom`,this.labels.zoom,this.zoomMin,this.zoomMax,this.zoomStep,this.zoomStep,e.zoom,e=>this.settings.setZoom(e));for(let e of this.customRows)this.addCustomRow(e);this.addActionRow(`controls`,this.labels.controls,()=>this.openRebind()),this.addActionRow(`reset`,this.labels.reset,()=>{this.settings.reset(),this.refresh()}),this.main.children.forEach((e,t)=>{e.y=t*this.rowHeight})}addSliderRow(e,t,n,r,i,a,o,s){let c=new Y,l=new iF({text:t});l.y=10;let u=new nR({width:140,min:n,max:r,step:i,value:o});u.x=this.width_-148,u.y=10,c.addChild(l,u),this.main.addChild(c);let d=()=>{l.setText(`${t}: ${u.value}`)};d(),u.onChange.add(e=>{s(e),d()}),this.rows.push({id:e,root:c,adjust:e=>u.setValue(u.value+e*a),activate:()=>{},refresh:()=>{u.setValue(this.readSlider(e)),d()}})}readSlider(e){let t=this.settings.current;switch(e){case`music`:return Math.round(t.musicVolume*100);case`sfx`:return Math.round(t.sfxVolume*100);case`zoom`:return t.zoom;default:return 0}}addToggleRow(e,t,n,r){let i=new Y,a=new iF({text:t});a.y=10;let o=new rR({checked:n});o.x=this.width_-28,o.y=8,i.addChild(a,o),this.main.addChild(i),o.onChange.add(r),this.rows.push({id:e,root:i,adjust:()=>o.toggle(),activate:()=>o.toggle(),refresh:()=>o.setChecked(this.readToggle(e))})}readToggle(e){return e===`muted`?this.settings.current.muted:this.settings.getCustom(e.slice(7),!1)===!0}addCustomRow(e){let t=`custom:${e.key}`;if(e.kind===`boolean`){let n=this.settings.getCustom(e.key,!1);this.addToggleRow(t,e.label,n===!0,t=>this.settings.setCustom(e.key,t))}else if(e.kind===`number`){let n=this.settings.getCustom(e.key,e.min),r=typeof n==`number`?n:e.min,i=e.step??0,a=i>0?i:(e.max-e.min)/20,o=new Y,s=new iF({text:e.label});s.y=10;let c=new nR({width:140,min:e.min,max:e.max,step:e.step??0,value:r});c.x=this.width_-148,c.y=10,o.addChild(s,c),this.main.addChild(o);let l=()=>{s.setText(`${e.label}: ${c.value}`)};l(),c.onChange.add(t=>{this.settings.setCustom(e.key,t),l()}),this.rows.push({id:t,root:o,adjust:e=>c.setValue(c.value+e*a),activate:()=>{},refresh:()=>{let t=this.settings.getCustom(e.key,e.min);c.setValue(typeof t==`number`?t:e.min),l()}})}else{let n=e.options,r=new Y,i=new iF({text:e.label});i.y=10;let a=new oR({min:0,max:n.length-1,step:1,value:0,wrap:!0});a.x=this.width_-32,a.y=2,r.addChild(i,a),this.main.addChild(r);let o=e=>{let t=typeof e==`string`?n.indexOf(e):-1;return t>=0?t:0},s=()=>{i.setText(`${e.label}: ${n[a.value]}`)};a.setValue(o(this.settings.getCustom(e.key,n[0]))),s(),a.onChange.add(t=>{this.settings.setCustom(e.key,n[t]),s()}),this.rows.push({id:t,root:r,adjust:e=>e>0?a.increment():a.decrement(),activate:()=>a.increment(),refresh:()=>{a.setValue(o(this.settings.getCustom(e.key,n[0]))),s()}})}}addActionRow(e,t,n){let r=new Y,i=new UL({width:this.width_-16,height:28,text:t,onClick:n});i.x=8,i.y=4,r.addChild(i),this.main.addChild(r),this.rows.push({id:e,root:r,adjust:()=>{},activate:n,refresh:()=>{}})}openRebind(){let e=this.actionsOption??Object.keys(this.settings.current.bindings),t=new iF({text:this.labels.rebindHint}),n=new wR({width:this.width_,height:Math.max(1,e.length)*this.rowHeight,actions:e,onConflict:this.onConflict});t.y=0,n.y=this.rowHeight,this.rebindLayer.addChild(t,n),this.rebindLayer.visible=!0,this.main.visible=!1,this.highlight.visible=!1,this.rebind=n}closeRebind(){this.settings.setBindings(Le()),this.rebindLayer.removeChildren(),this.rebind?.destroy(),this.rebind=null,this.rebindLayer.visible=!1,this.main.visible=!0,this.highlight.visible=!0}destroy(e){$.remove(this.themeListener),this.rebind?.destroy(),this.rebind=null,super.destroy(e)}},ER=class extends Y{constructor(e){if(super(),this.emptyLayer=new Y,this.filledLayer=new Y,this.maskShape=new bE,this.themeListener=()=>this.draw(),e.filledTexture===void 0!=(e.emptyTexture===void 0))throw Error(`a Meter takes filledTexture and emptyTexture together, or neither`);this.count_=OR(e.count),this.size_=e.size??16,this.gap_=e.gap??4,this.value_=DR(e.value??this.count_,this.count_),this.explicitColor=e.color!==void 0,this.fillColor=e.color??Q().color.textHighlight,this.emptyColor_=e.emptyColor,this.filledTexture=e.filledTexture,this.emptyTexture=e.emptyTexture,this.addChild(this.emptyLayer),this.addChild(this.filledLayer),this.addChild(this.maskShape),this.filledLayer.mask=this.maskShape,this.draw(),$.add(this.themeListener)}get value(){return this.value_}get count(){return this.count_}get color(){return this.fillColor}setValue(e,t=this.count_){this.count_=OR(t),this.value_=DR(e,this.count_),this.draw()}setColor(e){this.explicitColor=!0,this.fillColor=e,this.draw()}resize(e,t=this.gap_){this.size_=e,this.gap_=t,this.draw()}get totalWidth(){return this.count_*this.size_+(this.count_-1)*this.gap_}iconX(e){let t=e*(this.size_+this.gap_);return Q().direction===`rtl`?this.totalWidth-t-this.size_:t}draw(){let e=Q();this.explicitColor||(this.fillColor=e.color.textHighlight);let t=this.emptyColor_??e.color.panelFill;this.emptyLayer.removeChildren(),this.filledLayer.removeChildren();for(let e=0;e<this.count_;e++){let n=this.iconX(e);this.emptyLayer.addChild(this.icon(n,t,this.emptyTexture,!1)),this.filledLayer.addChild(this.icon(n,this.fillColor,this.filledTexture,!0))}let n=this.totalWidth*(this.count_>0?this.value_/this.count_:0),r=e.direction===`rtl`?this.totalWidth-n:0;this.maskShape.clear().rect(r,0,n,this.size_).fill({color:16777215})}icon(e,t,n,r){if(n){let i=new xl(n);return i.x=e,i.width=this.size_,i.height=this.size_,r&&this.explicitColor&&(i.tint=t),i}let i=new bE,a=this.size_/2;return i.circle(e+a,a,a).fill({color:t}),i}destroy(e){$.remove(this.themeListener),super.destroy(e)}};function DR(e,t){return Number.isFinite(e)?Math.max(0,Math.min(t,e)):t}function OR(e){return Number.isFinite(e)?Math.max(1,Math.floor(e)):1}var kR=class extends Y{constructor(e){super(),this.track=new bE,this.fill=new bE,this.themeListener=()=>this.draw(),this.width_=e.width,this.height_=e.height,this.explicitColor=e.color!==void 0,this.fillColor=e.color??Q().color.textHighlight,this.fraction=AR((e.value??1)/(e.max??1)),this.fillTexture=e.fillTexture,this.backgroundTexture=e.backgroundTexture,this.background_=e.background,this.roundUpToPixel=e.roundUpToPixel??!1,this.addChild(this.track),this.addChild(this.fill),this.draw(),$.add(this.themeListener)}get value(){return this.fraction}setValue(e,t=1){this.fraction=AR(t>0?e/t:0),this.draw()}get color(){return this.fillColor}setColor(e){this.explicitColor=!0,this.fillColor=e,this.draw()}get background(){return this.background_??Q().color.panelFill}resize(e,t){this.width_=e,this.height_=t,this.draw()}draw(){let e=Q();if(this.explicitColor||(this.fillColor=e.color.textHighlight),this.track.clear().rect(0,0,this.width_,this.height_),this.track.fill(this.backgroundTexture?{texture:this.backgroundTexture}:{color:this.background}),this.fill.clear(),this.fraction>0){let t=this.width_*this.fraction,n=this.roundUpToPixel?Math.ceil(t):t,r=e.direction===`rtl`?this.width_-n:0;this.fill.rect(r,0,n,this.height_),this.fill.fill(this.fillTexture?this.explicitColor?{texture:this.fillTexture,color:this.fillColor}:{texture:this.fillTexture}:{color:this.fillColor})}}destroy(e){$.remove(this.themeListener),super.destroy(e)}};function AR(e){return Math.max(0,Math.min(1,e))}function jR(e,t){return t<=0?1-e:t>=1||e<=t?1:1-(e-t)/(1-t)}function MR(e,t,n=!1){return n||e<=0?0:-t*e}function NR(e,t,n){return n<=0?e:Math.max(e,Math.min(n,t))}var PR=class extends Y{constructor(e){super(),this.rising=new Y,this.elapsed=0,this.done=!1,this.duration=e.duration??.8,this.rise=e.rise??24,this.hold=Math.min(1,Math.max(0,e.hold??0));let t=new iF({text:e.text,color:e.color,size:e.size});t.anchor.set(.5),this.rising.addChild(t),this.addChild(this.rising)}get finished(){return this.done}get riseOffset(){return this.rising.y}ageAtLeast(e){this.elapsed=NR(this.elapsed,this.duration,e)}update(e){if(this.done)return;this.elapsed=Math.min(this.duration,this.elapsed+e);let t=this.duration>0?this.elapsed/this.duration:1;this.rising.y=MR(t,this.rise,yr()),this.alpha=jR(t,this.hold),t>=1&&(this.done=!0,this.parent?.removeChild(this),this.destroy({children:!0}))}},FR=4;function IR(e){return Math.max(0,e)/5}function LR(e,t,n=4){let r=t.y-t.height/2;return e.y+e.height/2+n<=r?e.y:r-e.height/2-n}function RR(e,t,n=4){let r=[];if(t.key===void 0)return r;let i=t;for(let a=e.length-1;a>=0;a--){let o=e[a];if(o.key!==t.key)continue;let s=LR(o,i,n);if(s===o.y)break;r.push({index:a,y:s,ageAtLeast:IR(r.length+1)}),i={...o,y:s}}return r}var zR=class extends Y{constructor(...e){super(...e),this.live=[]}push(e){let t=new PR({text:e.text,color:e.color,size:e.size,duration:e.duration,rise:e.rise,hold:e.hold});e.scale!==void 0&&t.scale.set(e.scale);let n={key:e.key,x:e.x,y:e.y,height:t.height};for(let e of RR(this.live.map(e=>e.entry),n)){let t=this.live[e.index];t.entry.y=e.y,t.popup.y=e.y,t.popup.ageAtLeast(e.ageAtLeast)}return t.position.set(e.x,e.y),this.addChild(t),this.live.push({popup:t,entry:n}),t}update(e){for(let{popup:t}of this.live)t.update(e);for(let e=this.live.length-1;e>=0;e--)this.live[e].popup.finished&&this.live.splice(e,1)}get count(){return this.live.length}clear(){for(let{popup:e}of this.live)this.removeChild(e),e.destroy({children:!0});this.live.length=0}},BR=class extends Y{constructor(e={}){super(),this.queue=[],this.current=null,this.phase=`fadeIn`,this.elapsed=0,this.fadeIn=e.fadeIn??.25,this.hold=e.hold??1,this.fadeOut=e.fadeOut??1.75,this.scaleFrom=e.scaleFrom??2}show(e){this.queue.push(e),this.current||this.start(this.queue.shift())}get isBusy(){return this.current!==null||this.queue.length>0}start(e){this.current=e,this.phase=`fadeIn`,this.elapsed=0,this.addChild(e),e.alpha=this.fadeIn>0?0:1,e.scale.set(this.fadeIn>0?this.scaleFrom:1)}update(e){let t=this.current;if(!t)return;if(this.elapsed+=e,this.phase===`fadeIn`){let e=this.fadeIn,n=e>0?Math.min(1,this.elapsed/e):1,r=wr.easeOutCubic(n);t.alpha=r,t.scale.set(this.scaleFrom+(1-this.scaleFrom)*r),n>=1&&this.advance();return}if(this.phase===`hold`){this.elapsed>=this.hold&&this.advance();return}let n=this.fadeOut,r=n>0?Math.min(1,this.elapsed/n):1;t.alpha=1-r,r>=1&&this.finish()}advance(){this.phase=this.phase===`fadeIn`?`hold`:`fadeOut`,this.elapsed=0}finish(){let e=this.current;if(!e)return;this.removeChild(e),e.destroy({children:!0}),this.current=null;let t=this.queue.shift();t&&this.start(t)}},VR=class extends Y{constructor(e={}){super(),this.viewWidth=0,this.viewHeight=0,this.panelWidth=0,this.panelHeight=0,this.pending=null,this.waited=0,this.delay=e.delay??.4,this.maxWidth=e.maxWidth??200,this.offsetX=e.offset?.x??12,this.offsetY=e.offset?.y??16,this.margin=e.margin??4,this.panel=new tI({width:0,height:0,modal:!1,closable:!1,dims:!1}),this.body=new iF({text:``,wrapWidth:this.maxWidth}),this.panel.content.addChild(this.body),this.addChild(this.panel),this.visible=!1}setViewport(e,t){this.viewWidth=e,this.viewHeight=t,this.visible&&this.place()}hover(e,t,n){if(this.pending&&this.pending.text===e){this.pending.x=t,this.pending.y=n,this.visible&&this.place();return}this.pending={text:e,x:t,y:n},this.waited=0,this.visible=!1}leave(){this.pending=null,this.waited=0,this.visible=!1}get isShowing(){return this.visible}get text(){return this.pending?.text??null}get panelPosition(){return{x:this.panel.x,y:this.panel.y}}get size(){return{width:this.panelWidth,height:this.panelHeight}}update(e){if(!this.pending||this.visible||(this.waited+=e,this.waited<this.delay))return!1;this.body.setText(this.pending.text);let t=Q(),n=(t.panel?t.panelBorder:2)+t.padding,r=this.measureBody();return this.panelWidth=Math.ceil(r.width)+n*2,this.panelHeight=Math.ceil(r.height)+n*2,this.panel.resize(this.panelWidth,this.panelHeight),this.visible=!0,this.place(),!0}measureBody(){return{width:this.body.width,height:this.body.height}}place(){let e=this.pending;if(!e)return;let t=this.panelWidth,n=this.panelHeight,r=e.x+this.offsetX,i=e.y+this.offsetY;this.viewWidth>0&&(r+t+this.margin>this.viewWidth&&(r=e.x-this.offsetX-t),r=Math.max(this.margin,Math.min(r,Math.max(this.margin,this.viewWidth-t-this.margin)))),this.viewHeight>0&&(i+n+this.margin>this.viewHeight&&(i=e.y-this.offsetY-n),i=Math.max(this.margin,Math.min(i,Math.max(this.margin,this.viewHeight-n-this.margin)))),this.panel.x=r,this.panel.y=i}},HR=class extends Y{constructor(e){super(),this.topics=e.topics;let t=e.listWidth??Math.floor(e.width/3),n=e.width-t-Q().spacing,r=Q().direction===`rtl`;this.list=new iI({width:t,height:e.height,items:this.topics.map(e=>({text:e.title})),onHighlight:(e,t)=>this.showBody(t),onSelect:(e,t)=>this.showBody(t)}),this.list.x=r?e.width-t:0,this.addChild(this.list),this.body=new iF({wrapWidth:n}),this.body.x=r?0:t+Q().spacing,this.addChild(this.body),this.topics.length>0&&this.showBody(this.list.selectedIndex)}showBody(e){this.body.setText(this.topics[e]?.body??``)}handleAction(e){return this.list.handleAction(e)}},UR=class e extends Y{constructor(t){super(),this.text=new iF({text:e.format(t.stats),wrapWidth:t.width}),this.addChild(this.text)}setStats(t,n){this.text.setText(e.format(t)),n!==void 0&&(this.text.style.wordWrapWidth=n)}static format(e){return e.map(e=>`${e.label}: ${e.value}`).join(`
1386
- `)}},WR=class extends Y{constructor(e){super(),this.backdrop=new bE,this.progress=new kR({width:240,height:10,value:0}),this.width_=e.width,this.height_=e.height,this.onRetry=e.onRetry,this.onCancel=e.onCancel,this.title=new iF({text:e.title??`Loading`,size:18,bold:!0,align:`center`}),this.status=new iF({text:`Preparing...`,align:`center`}),this.addChild(this.backdrop,this.title,this.status,this.progress),this.layout()}setSnapshot(e){let t=e.total>0?e.completed/e.total:0;this.progress.setValue(t),e.status===`failed`?this.status.setText(`Loading failed. Retry or cancel.`):e.status===`cancelled`?this.status.setText(`Loading cancelled.`):e.status===`ready`?this.status.setText(`Ready`):this.status.setText(e.current?`Loading ${e.current}...`:`Preparing...`)}bind(e){this.setSnapshot(e.snapshot);let t=e=>this.setSnapshot(e);return e.changed.add(t),()=>e.changed.remove(t)}retry(){this.onRetry?.()}cancel(){this.onCancel?.()}resize(e,t){this.width_=e,this.height_=t,this.layout()}layout(){let e=Q().color;this.backdrop.clear().rect(0,0,this.width_,this.height_).fill({color:e.overlay,alpha:.92});let t=this.width_/2,n=this.height_/2;this.title.anchor.set(.5),this.status.anchor.set(.5),this.title.position.set(t,n-36),this.status.position.set(t,n-8),this.progress.position.set(t-120,n+16)}};function GR(e,t={}){return n=>new Promise(r=>{e.push(new VL({width:t.width??480,height:t.height??120,speed:t.speed??45,pages:[{text:n.text,speaker:n.speaker,portrait:n.portrait}],choices:n.choices,anchor:t.anchor??`bottom`,onDone:e=>r(e)}))})}function KR(e){let t=e/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4}function qR(e){return .2126*KR(e>>16&255)+.7152*KR(e>>8&255)+.0722*KR(e&255)}function JR(e,t){let[n,r]=[qR(e),qR(t)].sort((e,t)=>t-e);return(n+.05)/(r+.05)}function YR(e,t,n=`AA`,r=!1){let i=n===`AAA`?r?4.5:7:r?3:4.5;return JR(e,t)>=i}var XR={farLeft:.12,left:.28,center:.5,right:.72,farRight:.88},ZR=class extends Y{constructor(e,t){super(),this.backdropLayer=new Y,this.actorLayer=new Y,this.backdrop=null,this.outgoingBackdrop=null,this.actors=new Map,this.definitions=new Map,this.focused=null,this.tweener=new Tr,this.dimAmount=.45,this.stageWidth=e,this.stageHeight=t,this.addChild(this.backdropLayer),this.addChild(this.actorLayer)}defineCharacter(e,t){this.definitions.set(e,t)}resize(e,t){this.stageWidth=e,this.stageHeight=t;for(let e of[this.backdrop,this.outgoingBackdrop])e&&this.fitBackdrop(e);for(let e of this.actors.values())this.placeActor(e)}setBackdrop(e,t=.4){this.outgoingBackdrop?.destroy();let n=this.backdrop;this.outgoingBackdrop=n;let r=new xl(e);this.fitBackdrop(r),this.backdrop=r,this.backdropLayer.addChild(r);let i=()=>{this.outgoingBackdrop===n&&(n?.destroy(),this.outgoingBackdrop=null)};return t<=0?(i(),Promise.resolve()):(r.alpha=0,this.tweener.tween(t,e=>{r.alpha=e}).then(i))}fitBackdrop(e){let t=e.texture,n=Math.max(this.stageWidth/t.width,this.stageHeight/t.height);e.scale.set(n),e.x=Math.round((this.stageWidth-t.width*n)/2),e.y=Math.round((this.stageHeight-t.height*n)/2)}show(e,t={}){let n=this.definitions.get(e);if(!n)throw Error(`no character defined as "${e}"`);let r=t.expression??Object.keys(n.expressions)[0],i=this.actors.get(e);if(i)return t.at!==void 0&&(i.slot=this.slotOf(t.at)),this.setExpression(e,r),this.placeActor(i),Promise.resolve();let a=new Zj(n.sheet.get(n.expressions[r])),o={id:e,sprite:a,definition:n,slot:this.slotOf(t.at??`center`),expression:r};this.actors.set(e,o),this.actorLayer.addChild(a),this.placeActor(o),this.applyFocus();let s=t.fade??.25;return s<=0?Promise.resolve():(a.alpha=0,this.tweener.tween(s,e=>{a.alpha=e}))}hide(e,t=.25){let n=this.actors.get(e);return n?(this.actors.delete(e),this.focused===e&&(this.focused=null),this.applyFocus(),t<=0?(n.sprite.destroy(),Promise.resolve()):this.tweener.tween(t,e=>{n.sprite.alpha=1-e}).then(()=>n.sprite.destroy())):Promise.resolve()}hideAll(e=.25){return Promise.all([...this.actors.keys()].map(t=>this.hide(t,e))).then(()=>void 0)}setExpression(e,t){let n=this.actors.get(e);if(!n)return;let r=n.definition.expressions[t];if(r===void 0)throw Error(`character "${e}" has no expression "${t}"`);n.expression=t,n.sprite.texture=n.definition.sheet.get(r)}focus(e){this.focused=e,this.applyFocus()}applyFocus(){let e=Math.round(255*(1-this.dimAmount)),t=e<<16|e<<8|e;for(let e of this.actors.values()){let n=this.focused!==null&&e.id!==this.focused;e.sprite.tint=n?t:16777215}}slotOf(e){return typeof e==`number`?e:XR[e]}placeActor(e){let t=e.definition,n=(t.height??.7)*this.stageHeight,r=n/t.sheet.frameHeight;e.sprite.scale.set(r),e.sprite.x=Math.round(e.slot*this.stageWidth-t.sheet.frameWidth*r/2),e.sprite.y=Math.round((t.baseline??.92)*this.stageHeight-n)}update(e){this.tweener.update(e)}get isBusy(){return this.tweener.isBusy}},QR=class{constructor(e){this.state={answers:{}},this.cancelled=!1,this.historyLog=[],this.seenLines=new Set,this.skipSeen=!1,this.options=e}cancel(){this.cancelled=!0}get history(){return this.historyLog}async showLast(){let e=this.historyLog.at(-1);if(!e)return!1;let{windows:t}=this.options;return await new Promise(n=>{t.push(new VL({width:this.options.boxWidth??480,height:this.options.boxHeight??120,speed:0,pages:[{text:e.text,speaker:e.speaker}],dims:!1,anchor:`bottom`,onDone:()=>n()}))}),!0}async run(e){for(let t of e){if(this.cancelled)break;let e=await this.step(t);if(e!==void 0)throw Error(`a "goto ${e}" only runs inside runStory, not a straight run`)}return this.state}async runStory(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw Error(`this story has no passage named "${t}"`);let n=e[t],r=0;for(;r<n.length&&!this.cancelled;){let t=await this.step(n[r]);if(r++,t!==void 0){if(!Object.prototype.hasOwnProperty.call(e,t))throw Error(`this story has no passage named "${t}"`);n=e[t],r=0}}return this.state}async step(e){let{stage:t}=this.options;if(`backdrop`in e){await t.setBackdrop(this.options.backdrop(e.backdrop),e.fade);return}if(`show`in e){await t.show(e.show,{at:e.at,expression:e.expression,fade:e.fade});return}if(`hide`in e){await t.hide(e.hide,e.fade);return}if(`hideAll`in e){await t.hideAll(e.fade);return}if(`expression`in e){t.setExpression(e.of,e.expression);return}if(`say`in e){await this.speak(e.say,e.as,e.speaker),this.recordHistory(e.say,e.as,e.speaker);return}if(`ask`in e){let t=await this.speak(e.ask,e.as,e.speaker,e.choices);return this.recordHistory(e.ask,e.as,e.speaker,t),e.store&&(this.state.answers[e.store]=t),e.choices.find(e=>(e.value??e.text)===t)?.goto}if(`goto`in e)return e.goto;if(`wait`in e){await new Promise(t=>setTimeout(t,e.wait*1e3));return}`call`in e&&await e.call(this.state)}recordHistory(e,t,n,r){let i=n??(t?this.options.displayName?.(t)??t:void 0);this.seenLines.add($R(t,e)),this.historyLog.push({text:e,speaker:i,chosen:r})}speak(e,t,n,r){let{stage:i,windows:a}=this.options;i.focus(t??null);let o=n??(t?this.options.displayName?.(t)??t:void 0),s=this.skipSeen&&!r&&this.seenLines.has($R(t,e));return new Promise(t=>{a.push(new VL({width:this.options.boxWidth??480,height:this.options.boxHeight??120,speed:s?0:this.options.speed??45,autoAdvance:s?0:void 0,mode:this.options.mode,pages:[{text:e,speaker:o}],choices:r,dims:!1,anchor:`bottom`,onDone:e=>t(e)}))})}};function $R(e,t){return`${e??``}\u0000${t}`}function ez(e){let{story:t,start:n,title:r}=Ur(e);return r===void 0?{story:t,start:n}:{story:t,start:n,title:r}}function tz(e){return Hr(e).map(e=>e.speaker===void 0?{say:e.text}:{say:e.text,as:e.speaker})}function nz(e,t={}){let n={},r=e=>{for(let t of e)`say`in t?n[t.say]=t.say:`ask`in t&&(n[t.ask]=t.ask)};if(Array.isArray(e))r(e);else for(let t of Object.values(e))r(t);return{locale:t.locale??`en`,direction:t.direction??`ltr`,messages:n}}var rz=class{constructor(e){this.onChange=new p,this.onMusic=new p,this.index=0,this.beats=e}get length(){return this.beats.length}get position(){return this.index}get current(){return this.beats[this.index]??null}get done(){return this.beats.length===0||this.index>=this.beats.length-1}get music(){return this.current?.music??null}goTo(e){let t=Math.max(0,Math.min(this.beats.length-1,e));this.index=t,this.report()}advance(){return!this.done&&(this.goTo(this.index+1),!0)}back(){return this.index!==0&&(this.goTo(this.index-1),!0)}skip(){this.goTo(this.beats.length-1)}restart(){this.goTo(0)}report(){let e=this.current;e&&this.onChange.dispatch(e),this.onMusic.dispatch(this.music)}},iz=class extends Y{constructor(e){super(),this.backdrop=new xl(J.EMPTY),this.handleAdvance=()=>{this.advance()},this.handleBeat=e=>{this.applyBeat(e)},this.sequence=e.sequence,this.textureFor=e.textureFor??(()=>null),this.playMusic=e.playMusic??(()=>{}),this.width_=e.width,this.height_=e.height,this.titleLabel=new iF({text:``,color:Q().color.textHighlight}),this.textLabel=new iF({text:``,wrapWidth:this.width_*.8}),this.addChild(this.backdrop),this.addChild(this.titleLabel),this.addChild(this.textLabel),this.eventMode=`static`,this.on(`pointertap`,this.handleAdvance),this.sequence.onChange.add(this.handleBeat),this.sequence.onMusic.add(this.playMusic),this.applyBeat(this.sequence.current)}get current(){return this.sequence.current}advance(){return this.sequence.advance()}skip(){this.sequence.skip()}resize(e,t){this.width_=e,this.height_=t,this.applyBeat(this.current)}applyBeat(e){if(!e){this.backdrop.visible=!1;return}let t=e.image?this.textureFor(e.image):null;if(this.backdrop.visible=t!==null,t){this.backdrop.texture=t;let e=Math.max(this.width_/t.width,this.height_/t.height);this.backdrop.scale.set(e),this.backdrop.x=(this.width_-t.width*e)/2,this.backdrop.y=(this.height_-t.height*e)/2}this.titleLabel.setText(e.title??``),this.titleLabel.x=this.width_*.1,this.titleLabel.y=this.height_*.12,this.textLabel.setText(e.text),this.textLabel.x=this.width_*.1,this.textLabel.y=this.height_*.24,this.textLabel.style.wordWrapWidth=this.width_*.8}destroy(e){this.sequence.onChange.remove(this.handleBeat),this.sequence.onMusic.remove(this.playMusic),super.destroy(e)}},az=[[1,0],[1,-1],[0,-1],[-1,-1],[-1,0],[0,1]],oz=[[1,1],[1,0],[0,-1],[-1,0],[-1,1],[0,1]];function sz(e){return e===4?or:cr}var cz={passable:!1,transparent:!1},lz={passable:!0,transparent:!0},uz=class e{constructor(e,t,n,r=0,i=`square`,a){if(this.rooms=[],this.width=e,this.shape=i,this.height=t,a!==void 0&&(!Number.isFinite(a)||a<0))throw Error(`viewDistance must be a finite non-negative number`);this.viewDistance=a,this.kinds=n,this.terrain=new Uint8Array(e*t).fill(r)}get cellCount(){return this.width*this.height}index(e,t){return tr(this.width,e,t)}xOf(e){return nr(this.width,e)}yOf(e){return rr(this.width,e)}inside(e,t){return er(this.width,this.height,e,t)}neighbors(e,t,n=8){return this.shape===`hex`?qn(e,t):sz(n).map(([n,r])=>({x:e+n,y:t+r}))}forEachNeighbor(e,t,n,r){let i=this.shape===`hex`?e&1?oz:az:sz(n);for(let[n,a]of i)r(e+n,t+a)}insideWithBorder(e,t){return e>0&&t>0&&e<this.width-1&&t<this.height-1}get(e,t){return this.inside(e,t)?this.terrain[this.index(e,t)]:0}set(e,t,n){this.inside(e,t)&&(this.terrain[this.index(e,t)]=n)}kindAt(e,t){return this.kinds[this.get(e,t)]??cz}passable(e,t){return this.inside(e,t)&&this.kindAt(e,t).passable}transparent(e,t){return this.inside(e,t)&&this.kindAt(e,t).transparent}fillRect(e,t){for(let n=e.top;n<=e.bottom;n++)for(let r=e.left;r<=e.right;r++)this.set(r,n,t)}passableCells(){let e=[];for(let t=0;t<this.terrain.length;t++)this.kinds[this.terrain[t]]?.passable&&e.push(t);return e}toJSON(){return{width:this.width,height:this.height,shape:this.shape,terrain:[...this.terrain],rooms:this.rooms.map(e=>({...e})),...this.viewDistance===void 0?{}:{viewDistance:this.viewDistance}}}static fromJSON(t,n){let r=new e(n.width,n.height,t,0,n.shape,n.viewDistance);return r.terrain.set(n.terrain.slice(0,r.terrain.length)),r.rooms=n.rooms.map(e=>({...e})),r}};function dz(e){return{x:Math.floor((e.left+e.right)/2),y:Math.floor((e.top+e.bottom)/2)}}function fz(e,t,n=0){return!(e.right+n<t.left||t.right+n<e.left||e.bottom+n<t.top||t.bottom+n<e.top)}_e();var pz={id:`hall`,paint:(e,t,n)=>e.fillRect(t,n)};function mz(e){return Math.min(e.right-e.left+1,e.bottom-e.top+1)}function hz(e){return Math.max(e.right-e.left+1,e.bottom-e.top+1)}function gz(e,t){let n=mz(t),r=hz(t);return e.filter(e=>n>=(e.minSize??0)&&r<=(e.maxSize??1/0))}function _z(e,t){let n=gz(e,t);if(n.length===0)return null;let r=ie(n.map(e=>e.weight??1));return r===null?null:n[r]}_e();var vz=[{passable:!1,transparent:!1},{passable:!0,transparent:!0}];function yz(e){let{width:t,height:n,rooms:r=14,minRoomSize:i=4,maxRoomSize:a=10,extraCorridors:o=3,wall:s=0,floor:c=1,kinds:l=[],hooks:u,builders:d}=e,f=new uz(t,n,[...vz,...l],s),p=[],m=[],h=[],g=0;for(let e=0;e<r*6&&p.length<r;e++){let e=ne(i,a),r=ne(i,a),o=te(1,Math.max(2,t-e-1)),s=te(1,Math.max(2,n-r-1)),l={left:o,top:s,right:o+e-1,bottom:s+r-1};if(l.right>=t-1||l.bottom>=n-1){g++;continue}if(p.some(e=>fz(l,e,2))){g++;continue}p.push(l);let m=(d?.length?_z(d,l):null)??pz;m.paint(f,l,c),h.push(m.id),u?.onRoomPlaced?.(l,p.length-1)}for(let e=1;e<p.length;e++){xz(f,dz(p[e-1]),dz(p[e]),c);let t={a:e-1,b:e,extra:!1};m.push(t),u?.onCorridorCarved?.(t,p[e-1],p[e])}for(let e=0;e<o&&p.length>2;e++){let e=te(p.length),t=te(p.length);if(e!==t){xz(f,dz(p[e]),dz(p[t]),c);let n={a:e,b:t,extra:!0};m.push(n),u?.onCorridorCarved?.(n,p[e],p[t])}}return f.rooms=p,{level:f,graph:m,retries:g,roomBuilders:h}}function bz(e){return yz(e).level}function xz(e,t,n,r){A(.5)?(Sz(e,t.x,n.x,t.y,!0,r),Sz(e,t.y,n.y,n.x,!1,r)):(Sz(e,t.y,n.y,t.x,!1,r),Sz(e,t.x,n.x,n.y,!0,r))}function Sz(e,t,n,r,i,a){let o=t<=n?1:-1;for(let s=t;s!==n+o;s+=o){let t=i?s:r,n=i?r:s;e.insideWithBorder(t,n)&&e.set(t,n,a)}}function Cz(e,t=new Set){let n=e.passableCells().filter(e=>!t.has(e));return n.length>0?n[te(n.length)]:null}function wz(e,t){let n=null,r=-1;for(let i of e.rooms){let e=dz(i),a=(e.x-t.x)**2+(e.y-t.y)**2;a>r&&(r=a,n=i)}return n}var Tz=class e{constructor(){this.defs=new Map,this.placed=new Map}define(e,t){this.defs.set(e,t)}place(e,t){if(!this.defs.has(t))throw Error(`FeatureLayer.place: no definition for kind "${t}"`);this.placed.set(e,t)}has(e){return this.placed.has(e)}kindAt(e){return this.placed.get(e)}remove(e){this.placed.delete(e)}inspect(e,t){this.defAt(e)?.inspect?.(e,t)}interact(e,t){let n=this.defAt(e);n&&(n.interact&&n.interact(e,t)===!1||(n.consequence?.(e,t),n.persistent===!1&&this.remove(e)))}defAt(e){let t=this.placed.get(e);return t===void 0?void 0:this.defs.get(t)}toJSON(){return{cells:[...this.placed.entries()]}}static fromJSON(t,n){let r=new e;for(let[e,n]of t)r.define(e,n);for(let[e,t]of n.cells)r.place(e,t);return r}};_e();function Ez(e,t=[],n=!0){let r=[],i=e.map(e=>e.value);t.forEach((e,t)=>{if(e.enabled===!1){r.push({step:`rare`,index:t,outcome:`deferred`});return}let n=A(e.chance);r.push({step:`rare`,index:t,outcome:n?`added`:`skipped`}),n&&i.push(e.value)});for(let t=0;t<e.length;t++){let n=e[t].alternative;if(!n)continue;let a=A(n.chance);r.push({step:`alternative`,index:t,outcome:a?`swapped`:`kept`}),a&&(i[t]=n.value)}return n&&(oe(i),r.push({step:`shuffle`,index:-1,outcome:`shuffled`})),{roster:i,trace:r}}function Dz(e,t){return e.length===t.length&&e.every((e,n)=>e.a===t[n].a&&e.b===t[n].b&&e.extra===t[n].extra)}function Oz(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function kz(e,t){if(e.length!==t.length)return!1;let n=[...e].sort((e,t)=>e[0]-t[0]),r=[...t].sort((e,t)=>e[0]-t[0]);return n.every(([e,t],n)=>e===r[n][0]&&t===r[n][1])}function Az(e,t){let n=[];return e.retries!==t.retries&&n.push({stage:`graph`,field:`retries`,expected:e.retries,actual:t.retries}),Dz(e.graph,t.graph)||n.push({stage:`graph`,field:`graph`,expected:e.graph,actual:t.graph}),(e.width!==t.width||e.height!==t.height||!Oz(e.terrain,t.terrain))&&n.push({stage:`paint`,field:`terrain`,expected:e.terrain,actual:t.terrain}),(e.roomBuilders.length!==t.roomBuilders.length||e.roomBuilders.some((e,n)=>e!==t.roomBuilders[n]))&&n.push({stage:`paint`,field:`roomBuilders`,expected:e.roomBuilders,actual:t.roomBuilders}),kz(e.features,t.features)||n.push({stage:`paint`,field:`features`,expected:e.features,actual:t.features}),JSON.stringify(e.content)!==JSON.stringify(t.content)&&n.push({stage:`paint`,field:`content`,expected:e.content,actual:t.content}),e.rngDraws!==t.rngDraws&&n.push({stage:`paint`,field:`rngDraws`,expected:e.rngDraws,actual:t.rngDraws}),n}function jz(e,t=2){let n=e(),r=[];for(let i=1;i<t;i++)r.push(...Az(n,e()));return r}var Mz=23283064365386963e-26;new class e{constructor(){this._seed=0,this._s0=0,this._s1=0,this._s2=0,this._c=0}getSeed(){return this._seed}setSeed(e){return e=e<1?1/e:e,this._seed=e,this._s0=(e>>>0)*Mz,e=e*69069+1>>>0,this._s1=e*Mz,e=e*69069+1>>>0,this._s2=e*Mz,this._c=1,this}getUniform(){let e=2091639*this._s0+this._c*Mz;return this._s0=this._s1,this._s1=this._s2,this._c=e|0,this._s2=e-this._c,this._s2}getUniformInt(e,t){let n=Math.max(e,t),r=Math.min(e,t);return Math.floor(this.getUniform()*(n-r+1))+r}getNormal(e=0,t=1){let n,r,i;do n=2*this.getUniform()-1,r=2*this.getUniform()-1,i=n*n+r*r;while(i>1||i==0);return e+n*Math.sqrt(-2*Math.log(i)/i)*t}getPercentage(){return 1+Math.floor(this.getUniform()*100)}getItem(e){return e.length?e[Math.floor(this.getUniform()*e.length)]:null}shuffle(e){let t=[],n=e.slice();for(;n.length;){let e=n.indexOf(this.getItem(n));t.push(n.splice(e,1)[0])}return t}getWeightedValue(e){let t=0;for(let n in e)t+=e[n];let n=this.getUniform()*t,r,i=0;for(r in e)if(i+=e[r],n<i)return r;return r}getState(){return[this._s0,this._s1,this._s2,this._c]}setState(e){return this._s0=e[0],this._s1=e[1],this._s2=e[2],this._c=e[3],this}clone(){return new e().setState(this.getState())}}().setSeed(Date.now());var Nz=class{getContainer(){return null}setOptions(e){this._options=e}},Pz=class extends Nz{constructor(){super(),this._ctx=document.createElement(`canvas`).getContext(`2d`)}schedule(e){requestAnimationFrame(e)}getContainer(){return this._ctx.canvas}setOptions(e){super.setOptions(e);let t=`${e.fontStyle?`${e.fontStyle} `:``} ${e.fontSize}px ${e.fontFamily}`;this._ctx.font=t,this._updateSize(),this._ctx.font=t,this._ctx.textAlign=`center`,this._ctx.textBaseline=`middle`}clear(){let e=this._ctx.globalCompositeOperation;this._ctx.globalCompositeOperation=`copy`,this._ctx.fillStyle=this._options.bg,this._ctx.fillRect(0,0,this._ctx.canvas.width,this._ctx.canvas.height),this._ctx.globalCompositeOperation=e}eventToPosition(e,t){let n=this._ctx.canvas,r=n.getBoundingClientRect();return e-=r.left,t-=r.top,e*=n.width/r.width,t*=n.height/r.height,e<0||t<0||e>=n.width||t>=n.height?[-1,-1]:this._normalizedEventToPosition(e,t)}};function Fz(e){return e.charAt(0).toUpperCase()+e.substring(1)}function Iz(e,...t){let n=Iz.map;return e.replace(/%(?:([a-z]+)|(?:{([^}]+)}))/gi,function(r,i,a,o){if(e.charAt(o-1)==`%`)return r.substring(1);if(!t.length)return r;let s=t[0],c=(i||a).split(`,`),l=c.shift()||``,u=n[l.toLowerCase()];if(!u)return r;s=t.shift();let d=s[u].apply(s,c),f=l.charAt(0);return f!=f.toLowerCase()&&(d=Fz(d)),d})}Iz.map={s:`toString`};var Lz=class e extends Pz{constructor(){super(),this._spacingX=0,this._spacingY=0,this._canvasCache={}}setOptions(e){super.setOptions(e),this._canvasCache={}}draw(t,n){e.cache?this._drawWithCache(t):this._drawNoCache(t,n)}_drawWithCache(e){let[t,n,r,i,a]=e,o=``+r+i+a,s;if(o in this._canvasCache)s=this._canvasCache[o];else{let e=this._options.border;s=document.createElement(`canvas`);let t=s.getContext(`2d`);if(s.width=this._spacingX,s.height=this._spacingY,t.fillStyle=a,t.fillRect(e,e,s.width-e,s.height-e),r){t.fillStyle=i,t.font=this._ctx.font,t.textAlign=`center`,t.textBaseline=`middle`;let e=[].concat(r);for(let n=0;n<e.length;n++)t.fillText(e[n],this._spacingX/2,Math.ceil(this._spacingY/2))}this._canvasCache[o]=s}this._ctx.drawImage(s,t*this._spacingX,n*this._spacingY)}_drawNoCache(e,t){let[n,r,i,a,o]=e;if(t){let e=this._options.border;this._ctx.fillStyle=o,this._ctx.fillRect(n*this._spacingX+e,r*this._spacingY+e,this._spacingX-e,this._spacingY-e)}if(!i)return;this._ctx.fillStyle=a;let s=[].concat(i);for(let e=0;e<s.length;e++)this._ctx.fillText(s[e],(n+.5)*this._spacingX,Math.ceil((r+.5)*this._spacingY))}computeSize(e,t){return[Math.floor(e/this._spacingX),Math.floor(t/this._spacingY)]}computeFontSize(e,t){let n=Math.floor(e/this._options.width),r=Math.floor(t/this._options.height),i=this._ctx.font;this._ctx.font=`100px `+this._options.fontFamily;let a=Math.ceil(this._ctx.measureText(`W`).width);this._ctx.font=i;let o=a/100*r/n;return o>1&&(r=Math.floor(r/o)),Math.floor(r/this._options.spacing)}_normalizedEventToPosition(e,t){return[Math.floor(e/this._spacingX),Math.floor(t/this._spacingY)]}_updateSize(){let e=this._options,t=Math.ceil(this._ctx.measureText(`W`).width);this._spacingX=Math.ceil(e.spacing*t),this._spacingY=Math.ceil(e.spacing*e.fontSize),e.forceSquareRatio&&(this._spacingX=this._spacingY=Math.max(this._spacingX,this._spacingY)),this._ctx.canvas.width=e.width*this._spacingX,this._ctx.canvas.height=e.height*this._spacingY}};Lz.cache=!1;var Rz={4:[[0,-1],[1,0],[0,1],[-1,0]],8:[[0,-1],[1,-1],[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1]],6:[[-1,-1],[1,-1],[2,0],[1,1],[-1,1],[-2,0]]},zz=class{constructor(e,t={}){this._lightPasses=e,this._options=Object.assign({topology:8},t)}_getCircle(e,t,n){let r=[],i,a,o;switch(this._options.topology){case 4:a=1,o=[0,1],i=[Rz[8][7],Rz[8][1],Rz[8][3],Rz[8][5]];break;case 6:i=Rz[6],a=1,o=[-1,1];break;case 8:i=Rz[4],a=2,o=[-1,1];break;default:throw Error(`Incorrect topology for FOV computation`)}let s=e+o[0]*n,c=t+o[1]*n;for(let e=0;e<i.length;e++)for(let t=0;t<n*a;t++)r.push([s,c]),s+=i[e][0],c+=i[e][1];return r}},Bz=class extends zz{compute(e,t,n,r){if(r(e,t,0,1),!this._lightPasses(e,t))return;let i=[],a,o,s,c,l;for(let u=1;u<=n;u++){let n=this._getCircle(e,t,u),d=360/n.length;for(let e=0;e<n.length;e++)if(s=n[e][0],c=n[e][1],a=d*(e-.5),o=a+d,l=!this._lightPasses(s,c),this._visibleCoords(Math.floor(a),Math.ceil(o),l,i)&&r(s,c,u,1),i.length==2&&i[0]==0&&i[1]==360)return}}_visibleCoords(e,t,n,r){if(e<0){let i=this._visibleCoords(0,t,n,r),a=this._visibleCoords(360+e,360,n,r);return i||a}let i=0;for(;i<r.length&&r[i]<e;)i++;if(i==r.length)return n&&r.push(e,t),!0;let a=0;if(i%2){for(;i<r.length&&r[i]<t;)i++,a++;return a!=0&&(n&&(a%2?r.splice(i-a,a,t):r.splice(i-a,a)),!0)}for(;i<r.length&&r[i]<t;)i++,a++;return e==r[i-a]&&a==1?!1:(n&&(a%2?r.splice(i-a,a,e):r.splice(i-a,a,e,t)),!0)}},Vz=class extends zz{compute(e,t,n,r){if(r(e,t,0,1),!this._lightPasses(e,t))return;let i=[],a,o,s,c,l,u;for(let d=1;d<=n;d++){let n=this._getCircle(e,t,d),f=n.length;for(let e=0;e<f;e++)if(a=n[e][0],o=n[e][1],c=[e?2*e-1:2*f-1,2*f],l=[2*e+1,2*f],s=!this._lightPasses(a,o),u=this._checkVisibility(c,l,s,i),u&&r(a,o,d,u),i.length==2&&i[0][0]==0&&i[1][0]==i[1][1])return}}_checkVisibility(e,t,n,r){if(e[0]>t[0])return(this._checkVisibility(e,[e[1],e[1]],n,r)+this._checkVisibility([0,1],t,n,r))/2;let i=0,a=!1;for(;i<r.length;){let t=r[i],n=t[0]*e[1]-e[0]*t[1];if(n>=0){n==0&&!(i%2)&&(a=!0);break}i++}let o=r.length,s=!1;for(;o--;){let e=r[o],n=t[0]*e[1]-e[0]*t[1];if(n>=0){n==0&&o%2&&(s=!0);break}}let c=!0;if((i==o&&(a||s)||a&&s&&i+1==o&&o%2||i>o&&i%2)&&(c=!1),!c)return 0;let l,u=o-i+1;if(u%2){if(i%2){let e=r[i];l=(t[0]*e[1]-e[0]*t[1])/(e[1]*t[1]),n&&r.splice(i,u,t)}else{let t=r[o];l=(t[0]*e[1]-e[0]*t[1])/(e[1]*t[1]),n&&r.splice(i,u,e)}}else if(i%2){let e=r[i],t=r[o];l=(t[0]*e[1]-e[0]*t[1])/(e[1]*t[1]),n&&r.splice(i,u)}else return n&&r.splice(i,u,e,t),1;let d=(t[0]*e[1]-e[0]*t[1])/(e[1]*t[1]);return l/d}},Hz=[[-1,0,0,1],[0,-1,1,0],[0,-1,-1,0],[-1,0,0,-1],[1,0,0,-1],[0,1,-1,0],[0,1,1,0],[1,0,0,1]],Uz={DiscreteShadowcasting:Bz,PreciseShadowcasting:Vz,RecursiveShadowcasting:class extends zz{compute(e,t,n,r){r(e,t,0,1);for(let i=0;i<Hz.length;i++)this._renderOctant(e,t,Hz[i],n,r)}compute180(e,t,n,r,i){i(e,t,0,1);let a=(r-1+8)%8,o=(r-2+8)%8,s=(r+1+8)%8;this._renderOctant(e,t,Hz[o],n,i),this._renderOctant(e,t,Hz[a],n,i),this._renderOctant(e,t,Hz[r],n,i),this._renderOctant(e,t,Hz[s],n,i)}compute90(e,t,n,r,i){i(e,t,0,1);let a=(r-1+8)%8;this._renderOctant(e,t,Hz[r],n,i),this._renderOctant(e,t,Hz[a],n,i)}_renderOctant(e,t,n,r,i){this._castVisibility(e,t,1,1,0,r+1,n[0],n[1],n[2],n[3],i)}_castVisibility(e,t,n,r,i,a,o,s,c,l,u){if(!(r<i))for(let d=n;d<=a;d++){let n=-d-1,f=-d,p=!1,m=0;for(;n<=0;){n+=1;let h=e+n*o+f*s,g=t+n*c+f*l,_=(n-.5)/(f+.5),v=(n+.5)/(f-.5);if(!(v>r)){if(_<i)break;if(n*n+f*f<a*a&&u(h,g,d,1),!p)!this._lightPasses(h,g)&&d<a&&(p=!0,this._castVisibility(e,t,d+1,r,_,a,o,s,c,l,u),m=v);else{if(!this._lightPasses(h,g)){m=v;continue}p=!1,r=m}}}if(p)break}}}};.5*(Math.sqrt(3)-1),(3-Math.sqrt(3))/6;var Wz=class{constructor(e,t,n,r={}){this._toX=e,this._toY=t,this._passableCallback=n,this._options=Object.assign({topology:8},r),this._dirs=Rz[this._options.topology],this._options.topology==8&&(this._dirs=[this._dirs[0],this._dirs[2],this._dirs[4],this._dirs[6],this._dirs[1],this._dirs[3],this._dirs[5],this._dirs[7]])}_getNeighbors(e,t){let n=[];for(let r=0;r<this._dirs.length;r++){let i=this._dirs[r],a=e+i[0],o=t+i[1];this._passableCallback(a,o)&&n.push([a,o])}return n}},Gz={Dijkstra:class extends Wz{constructor(e,t,n,r){super(e,t,n,r),this._computed={},this._todo=[],this._add(e,t,null)}compute(e,t,n){let r=e+`,`+t;if(r in this._computed||this._compute(e,t),!(r in this._computed))return;let i=this._computed[r];for(;i;)n(i.x,i.y),i=i.prev}_compute(e,t){for(;this._todo.length;){let n=this._todo.shift();if(n.x==e&&n.y==t)return;let r=this._getNeighbors(n.x,n.y);for(let e=0;e<r.length;e++){let t=r[e],i=t[0],a=t[1];i+`,`+a in this._computed||this._add(i,a,n)}}}_add(e,t,n){let r={x:e,y:t,prev:n};this._computed[e+`,`+t]=r,this._todo.push(r)}},AStar:class extends Wz{constructor(e,t,n,r={}){super(e,t,n,r),this._todo=[],this._done={}}compute(e,t,n){for(this._todo=[],this._done={},this._fromX=e,this._fromY=t,this._add(this._toX,this._toY,null);this._todo.length;){let n=this._todo.shift(),r=n.x+`,`+n.y;if(r in this._done)continue;if(this._done[r]=n,n.x==e&&n.y==t)break;let i=this._getNeighbors(n.x,n.y);for(let e=0;e<i.length;e++){let t=i[e],r=t[0],a=t[1];r+`,`+a in this._done||this._add(r,a,n)}}let r=this._done[e+`,`+t];if(r)for(;r;)n(r.x,r.y),r=r.prev}_add(e,t,n){let r=this._distance(e,t),i={x:e,y:t,prev:n,g:n?n.g+1:0,h:r},a=i.g+i.h;for(let e=0;e<this._todo.length;e++){let t=this._todo[e],n=t.g+t.h;if(a<n||a==n&&r<t.h){this._todo.splice(e,0,i);return}}this._todo.push(i)}_distance(e,t){switch(this._options.topology){case 4:return Math.abs(e-this._fromX)+Math.abs(t-this._fromY);case 6:let n=Math.abs(e-this._fromX),r=Math.abs(t-this._fromY);return r+Math.max(0,(n-r)/2);case 8:return Math.max(Math.abs(e-this._fromX),Math.abs(t-this._fromY))}}}};function Kz(e,t){return ur(e,t)}function qz(e,t){let n=[],r=e.x,i=e.y,a=Math.abs(t.x-e.x),o=-Math.abs(t.y-e.y),s=e.x<t.x?1:-1,c=e.y<t.y?1:-1,l=a+o;for(;n.push({x:r,y:i}),r!==t.x||i!==t.y;){let e=l*2;e>=o&&(l+=o,r+=s),e<=a&&(l+=a,i+=c)}return n}function Jz(e,t,n,r={}){let i=e.shape===`hex`?Xn(t,n):qz(t,n),a=r.stop??`opaque`,o=[],s=null;for(let t of i)if(o.push(t),o.length!==1&&a!==`none`&&(a===`outside`&&!e.inside(t.x,t.y)||a===`opaque`&&e.inside(t.x,t.y)&&!e.transparent(t.x,t.y)||a===`impassable`&&e.inside(t.x,t.y)&&!e.passable(t.x,t.y))){s=t;break}return{cells:o,stop:s}}function Yz(e,t,n){let r=e.shape===`hex`?Xn(t,n):qz(t,n);for(let t=1;t<r.length-1;t++)if(!e.transparent(r[t].x,r[t].y))return!1;return!0}function Xz(e,t,n,r){return!((e.shape===`hex`?Jn(t,n):Kz(t,n))>r.range||(r.requireLineOfSight??!0)&&!Yz(e,t,n))}function Zz(e,t,n){switch(n.kind){case`single`:return[t];case`line`:return qz(e,t);case`cone`:return eB(e,t,n.width);case`burst`:{let e=[],r=n.radius;for(let n=-r;n<=r;n++)for(let i=-r;i<=r;i++)i*i+n*n>r*r||e.push({x:t.x+i,y:t.y+n});return e}}}function Qz(e,t,n,r){return e.shape===`hex`?r.kind===`single`?[{...n}]:r.kind===`line`?Xn(t,n):r.kind===`burst`?Zn(n,r.radius):$z(t,n,r.width):Zz(t,n,r)}function $z(e,t,n){let r=Jn(e,t);if(r===0)return[{...e}];let i=Xn(e,t),a=[];for(let t=1;t<=r;t++){let o=i[t],s=Math.round(t/r*n);for(let n of Zn(o,s))Jn(e,n)===t&&a.push(n)}return a}function eB(e,t,n){let r=t.x-e.x,i=t.y-e.y,a=Math.max(Math.abs(r),Math.abs(i));if(a===0)return[{...e}];let o=Math.sign(r),s=Math.sign(i),c=r!==0&&i!==0?o:s,l=r!==0&&i!==0?-s:o,u=[];for(let t=1;t<=a;t++){let r=e.x+o*t,i=e.y+s*t,d=Math.round(t/a*n);for(let e=-d;e<=d;e++)u.push({x:r+c*e,y:i+l*e})}return u}var tB=.5;function nB(e){return e<0?-Math.round(-e):Math.round(e)}function rB(e,t,n,r){if(!Number.isFinite(r.degrees)||r.degrees<0)throw Error(`a cone sector needs a finite non-negative angle in degrees`);if(!Number.isFinite(r.range)||r.range<0)throw Error(`a cone sector needs a finite non-negative range`);let i=n.x-t.x,a=n.y-t.y;if(i===0&&a===0)return[{...t}];let o=Math.atan2(a,i),s=r.degrees*Math.PI/360,c=Math.max(1,Math.round(r.degrees/tB)),l=r.stop??`opaque`,u=new Set,d=[];for(let n=0;n<=c;n++){let i=o-s+2*s*n/c,a={x:t.x+nB(Math.cos(i)*r.range),y:t.y+nB(Math.sin(i)*r.range)};for(let n of Jz(e,t,a,{stop:l}).cells){if(n.x===t.x&&n.y===t.y||!e.inside(n.x,n.y))continue;let r=e.index(n.x,n.y);u.has(r)||(u.add(r),d.push({x:n.x,y:n.y}))}}return d}function iB(e,t,n,r){let i=new Set,a=[],o=t;for(let t=0;t<n;t++){let t=-1,n=r+1;for(let a=0;a<e.length;a++){if(i.has(a))continue;let s=Kz(o,e[a]);s<=r&&s<n&&(n=s,t=a)}if(t===-1)break;i.add(t),a.push(e[t]),o=e[t]}return a}function aB(e,t,n=1){for(let n of t)if(e<=n.max)return n.multiplier;return n}function oB(e,t){return t.length===0?1:t[Math.min(e,t.length-1)]}function sB(e,t,n,r){let i=[];for(let a=1;a<=r;a++){let r={x:t.x+n.x*a,y:t.y+n.y*a};if(!e.passable(r.x,r.y))break;i.push(r)}return i}var cB=class{constructor(e,t){if(this.onMove=new p,this.onConfirm=new p,this.onCancel=new p,!Number.isFinite(t.range)||t.range<0)throw Error(`targeting range must be a finite non-negative number`);this.level=e,this.origin={...t.origin},this.range=t.range,this.requireLineOfSight=t.requireLineOfSight??!0,this.validate=t.validate,this.shape=t.shape??{kind:`single`},this.cursor={...t.cursor??t.origin}}get target(){return{...this.cursor}}get distance(){return this.level.shape===`hex`?Jn(this.origin,this.cursor):Kz(this.origin,this.cursor)}get inRange(){return this.distance<=this.range}get inSight(){return Yz(this.level,this.origin,this.cursor)}get valid(){return!this.inRange||this.requireLineOfSight&&!this.inSight?!1:!this.validate||this.validate(this.cursor)}move(e,t){if(this.level.shape===`hex`){let n=this.level.neighbors(this.cursor.x,this.cursor.y).find(n=>n.x-this.cursor.x===e&&n.y-this.cursor.y===t);n&&this.moveTo(n);return}this.moveTo({x:this.cursor.x+e,y:this.cursor.y+t})}moveTo(e){this.level.inside(e.x,e.y)&&(this.cursor={x:e.x,y:e.y},this.onMove.dispatch({...this.cursor}))}setShape(e){this.shape=e}preview(){return this.valid?Qz(this.level,this.origin,this.cursor,this.shape):[]}confirm(){if(!this.valid)return null;let e={origin:{...this.origin},target:{...this.cursor},shape:this.shape,cells:this.preview()};return this.onConfirm.dispatch(e),e}cancel(){this.onCancel.dispatch()}},lB=class{constructor(e){this.visible=new Set,this.explored=new Set,this.light=new Map,this.level=e,this.fov=e.shape===`hex`?null:new Uz.PreciseShadowcasting((t,n)=>e.transparent(t,n))}update(e,t,n=this.level.viewDistance??Math.max(this.level.width,this.level.height),r){if(this.visible.clear(),this.light.clear(),r){this.updateFromHeight(e,t,n,r);return}if(this.fov){this.fov.compute(e,t,n,(e,t,n,r)=>{if(!this.level.inside(e,t))return;let i=this.level.index(e,t);this.visible.add(i),this.explored.add(i),this.light.set(i,r)});return}let i={x:e,y:t};for(let e of Zn(i,n)){if(!this.level.inside(e.x,e.y))continue;let t=Xn(i,e);t.slice(1,-1).some(e=>!this.level.inside(e.x,e.y)||!this.level.transparent(e.x,e.y))||this.lightCell(e.x,e.y,t.length-1,n)}}lightCell(e,t,n,r){let i=this.level.index(e,t);this.visible.add(i),this.explored.add(i),this.light.set(i,r===0?1:Math.max(0,1-n/(r+1)))}updateFromHeight(e,t,n,r){let i=r.height??r.heights.heightAt(e,t),a={x:e,y:t};if(this.level.shape===`hex`){for(let e of Zn(a,n)){if(!this.level.inside(e.x,e.y))continue;let t=Xn(a,e);this.heightBlocked(t,r.heights,i,r.heights.heightAt(e.x,e.y))||this.lightCell(e.x,e.y,t.length-1,n)}return}for(let o=t-n;o<=t+n;o++)for(let t=e-n;t<=e+n;t++){if(!this.level.inside(t,o)||Kz(a,{x:t,y:o})>n)continue;let e=qz(a,{x:t,y:o});this.heightBlocked(e,r.heights,i,r.heights.heightAt(t,o))||this.lightCell(t,o,e.length-1,n)}}heightBlocked(e,t,n,r){let i=Math.max(n,r);for(let n=1;n<e.length-1;n++){let r=e[n];if(!this.level.inside(r.x,r.y)||!this.level.transparent(r.x,r.y)||t.heightAt(r.x,r.y)>i)return!0}return!1}isVisible(e,t){return this.visible.has(this.level.index(e,t))}isExplored(e,t){return this.explored.has(this.level.index(e,t))}lightAt(e,t){return this.light.get(this.level.index(e,t))??0}reset(){this.visible.clear(),this.explored.clear(),this.light.clear()}revealAll(){for(let e=0;e<this.level.cellCount;e++)this.explored.add(e)}},uB=class{constructor(e){this.level=e,this.heights=new Int32Array(e.cellCount)}heightAt(e,t){return this.level.inside(e,t)?this.heights[this.level.index(e,t)]:0}set(e,t,n){if(!Number.isInteger(n))throw Error(`a cell's height must be a whole number, got ${n}`);this.level.inside(e,t)&&(this.heights[this.level.index(e,t)]=n)}},dB=class{constructor(e){this.level=e}passable(e){let t=e.blocked;return(e,n)=>this.level.passable(e,n)?!t?.has(this.level.index(e,n)):!1}stepper(e){let t=this.passable(e),n=e.heights;if(!n)return(e,n,r,i)=>this.level.inside(e,n)&&this.level.inside(r,i)&&t(r,i);let r=e.climb??1;if(!Number.isInteger(r)||r<0)throw Error(`a climb limit must be a non-negative whole number, got ${e.climb}`);return(e,i,a,o)=>this.level.inside(e,i)&&this.level.inside(a,o)&&t(a,o)&&n.heightAt(a,o)-n.heightAt(e,i)<=r}find(e,t,n={}){if(this.level.shape===`hex`||n.heights){let r=this.distanceMap(t,n),i=[],a=e;for(let e=0;e<this.level.cellCount;e++){let e=this.descend(a,r,n);if(!e||(i.push(e),e.x===t.x&&e.y===t.y))break;a=e}return i}let r=new Gz.AStar(t.x,t.y,this.passable(n),{topology:n.topology??8}),i=[];return r.compute(e.x,e.y,(e,t)=>i.push({x:e,y:t})),i.slice(1)}step(e,t,n={}){return this.find(e,t,n)[0]??null}distanceMap(e,t={}){let n=new Int32Array(this.level.cellCount).fill(-1),r=this.passable(t),i=this.stepper(t);if(!r(e.x,e.y))return n;let a=[this.level.index(e.x,e.y)];n[a[0]]=0;for(let e=0;e<a.length;e++){let r=a[e],o=this.level.xOf(r),s=this.level.yOf(r),c=n[r]+1;this.level.forEachNeighbor(o,s,t.topology??8,(e,t)=>{if(!i(e,t,o,s))return;let r=this.level.index(e,t);n[r]===-1&&(n[r]=c,a.push(r))})}return n}descend(e,t,n={}){let r=this.stepper(n),i=t[this.level.index(e.x,e.y)];if(i<=0)return null;let a=null,o=i;return this.level.forEachNeighbor(e.x,e.y,n.topology??8,(n,i)=>{if(!r(e.x,e.y,n,i))return;let s=t[this.level.index(n,i)];s!==-1&&s<o&&(o=s,a={x:n,y:i})}),a}autoExplore(e,t,n={}){let r=this.passable(n),i=this.stepper(n);if(!r(e.x,e.y))return[];let a=new Map,o=new Set([this.level.index(e.x,e.y)]),s=[e];for(let e=0;e<s.length;e++){let r=s[e];if(e>0&&!t.isExplored(r.x,r.y))return this.reconstruct(a,r);this.level.forEachNeighbor(r.x,r.y,n.topology??8,(e,t)=>{if(!i(r.x,r.y,e,t))return;let n=this.level.index(e,t);o.has(n)||(o.add(n),a.set(n,r),s.push({x:e,y:t}))})}return[]}reconstruct(e,t){let n=[t],r=e.get(this.level.index(t.x,t.y));for(;r;)n.push(r),r=e.get(this.level.index(r.x,r.y));return n.reverse()}},fB=class e{constructor(){this.entries=[],this.sequence=0,this.now=0}get size(){return this.entries.length}get actors(){return this.entries.map(e=>e.actor)}has(e){return this.entries.some(t=>t.actor===e)}add(e,t=0,n=e.priority??0){if(!Number.isFinite(t)||t<0)throw Error(`scheduler delay must be finite and non-negative`);if(!Number.isFinite(n))throw Error(`scheduler priority must be finite`);this.entries.push({actor:e,time:this.now+t,sequence:this.sequence++,priority:n}),this.sort()}remove(e){let t=this.entries.findIndex(t=>t.actor===e);t!==-1&&this.entries.splice(t,1)}clear(){this.entries.length=0,this.now=0,this.sequence=0}peek(){let e=this.entries[0];return e?(this.now=Math.max(this.now,e.time),e.actor):null}spend(e){let t=this.entries[0];if(!t)return;let n=t.actor.speed??1;t.time=this.now+e/(n>0?n:1),t.sequence=this.sequence++,this.sort()}postpone(e,t){let n=this.entries.find(t=>t.actor===e);n&&(n.time+=t,n.sequence=this.sequence++,this.sort())}timeOf(e){return this.entries.find(t=>t.actor===e)?.time??null}toJSON(e){return{now:this.now,sequence:this.sequence,entries:this.entries.map(t=>({id:e(t.actor),time:t.time,sequence:t.sequence,...t.priority===0?{}:{priority:t.priority}}))}}static restore(t,n){let r=new e;return r.now=t.now,r.sequence=t.sequence,r.entries=t.entries.map(e=>({actor:n(e.id),time:e.time,sequence:e.sequence,priority:e.priority??0})),r.sort(),r}sort(){this.entries.sort((e,t)=>e.time-t.time||t.priority-e.priority||e.sequence-t.sequence)}};_e();function pB(e,t,n,r,i,a={}){let o=a.sightRadius??6,s=a.fleeBelow??0;if((a.disposition??`hostile`)!==`hostile`&&a.provoked!==!0)return{state:`wander`,step:mB(e,n,a)};let c=new lB(e);return c.update(n.x,n.y,o),c.isVisible(i.x,i.y)?r<=s?{state:`flee`,step:hB(e,n,i,a)}:{state:`hunt`,step:t.step(n,i,a)}:{state:`wander`,step:mB(e,n,a)}}function mB(e,t,n){return re(gB(e,t,n))}function hB(e,t,n,r){let i=gB(e,t,r),a=null,o=_B(t,n);for(let e of i){let t=_B(e,n);t>o&&(o=t,a=e)}return a}function gB(e,t,n){let r=n.blocked,i=[];for(let[a,o]of sz(n.topology??8)){let n={x:t.x+a,y:t.y+o};e.passable(n.x,n.y)&&(r?.has(e.index(n.x,n.y))||i.push(n))}return i}function _B(e,t){return(e.x-t.x)**2+(e.y-t.y)**2}var vB=class e{constructor(e){this.revealedKind=new Map,this.discovered=new Set,this.level=e}conceal(e,t,n,r){let i=this.level.index(e,t);this.revealedKind.set(i,r),this.discovered.delete(i),this.level.set(e,t,n)}isSecret(e,t){let n=this.level.index(e,t);return this.revealedKind.has(n)&&!this.discovered.has(n)}isDiscovered(e,t){return this.discovered.has(this.level.index(e,t))}discover(e,t){if(!this.isSecret(e,t))return!1;let n=this.level.index(e,t);return this.discovered.add(n),this.level.set(e,t,this.revealedKind.get(n)),!0}toJSON(){return{revealed:[...this.revealedKind],discovered:[...this.discovered]}}static fromJSON(t,n){let r=new e(t);for(let[e,t]of n.revealed)r.revealedKind.set(e,t);for(let e of n.discovered)r.discovered.add(e);return r}},yB=class e{constructor(e){this.openKind=new Map,this.closedKind=new Map,this.lockedBy=new Map,this.open_=new Map,this.level=e}place(e,t,n){let r=this.level.index(e,t);this.openKind.set(r,n.open),this.closedKind.set(r,n.closed),this.open_.set(r,n.startOpen??!1),n.locked===void 0?this.lockedBy.delete(r):this.lockedBy.set(r,n.locked),this.level.set(e,t,this.open_.get(r)?n.open:n.closed)}isDoor(e,t){return this.open_.has(this.level.index(e,t))}isOpen(e,t){return this.open_.get(this.level.index(e,t))===!0}isLocked(e,t){return this.lockedBy.has(this.level.index(e,t))}requiredKey(e,t){return this.lockedBy.get(this.level.index(e,t))}open(e,t){let n=this.level.index(e,t);return!this.open_.has(n)||this.open_.get(n)||this.lockedBy.has(n)?!1:(this.open_.set(n,!0),this.level.set(e,t,this.openKind.get(n)),!0)}close(e,t){let n=this.level.index(e,t);return!this.open_.has(n)||!this.open_.get(n)?!1:(this.open_.set(n,!1),this.level.set(e,t,this.closedKind.get(n)),!0)}unlock(e,t){let n=this.level.index(e,t);return this.lockedBy.has(n)?(this.lockedBy.delete(n),!0):!1}toJSON(){let e=[];for(let[t,n]of this.openKind)e.push({cell:t,open:n,closed:this.closedKind.get(t),locked:this.lockedBy.get(t),isOpen:this.open_.get(t)===!0});return{doors:e}}static fromJSON(t,n){let r=new e(t);for(let e of n.doors){let n=t.xOf(e.cell),i=t.yOf(e.cell);r.place(n,i,{open:e.open,closed:e.closed,locked:e.locked,startOpen:e.isOpen})}return r}},bB=class e{constructor(e=[]){this.current=0;for(let t=1;t<e.length;t++)if(e[t]>=e[t-1])throw Error(`boss phase thresholds must descend`);this.thresholds=e}get phase(){return this.current}check(e){let t=0;for(;t<this.thresholds.length&&e<=this.thresholds[t];)t++;let n=[];for(;this.current<t;)this.current++,n.push(this.current);return n}reset(){this.current=0}toJSON(){return{phase:this.current}}static fromJSON(t,n){let r=new e(t);return r.current=n.phase,r}},xB=class e{constructor(e){this.remaining=new Map,this.cooldowns=new Map(Object.entries(e))}advance(e=1){for(let[t,n]of this.remaining)n<=e?this.remaining.delete(t):this.remaining.set(t,n-e)}ready(){let e=[];for(let t of this.cooldowns.keys())this.remaining.has(t)||e.push(t);return e}use(e){let t=this.cooldowns.get(e);return t===void 0||this.remaining.has(e)?!1:(t>0&&this.remaining.set(e,t),!0)}toJSON(){return{remaining:[...this.remaining]}}static fromJSON(t,n){let r=new e(t);for(let[e,t]of n.remaining)r.remaining.set(e,t);return r}},SB=class extends S{modifyDamage(e,t,n){let r={attacker:e,defender:t,amount:n,prevented:!1};return this.emit(`beforeDamage`,r),r.amount=Math.max(0,r.amount),r.amount===0&&(r.prevented=!0),r}},CB=class{constructor(e){this.detected=!1,this.radius=e.radius}get isDetected(){return this.detected}checkDetection(e,t){if(this.detected)return!1;let n=t.some(t=>Kz(e,t)<=this.radius);return n&&(this.detected=!0),n}reset(){this.detected=!1}},wB=class e{constructor(e){this.streak=0,this.lastTurn=-1/0,this.window=e}get count(){return this.streak}trigger(e){return this.streak=e-this.lastTurn<=this.window?this.streak+1:1,this.lastTurn=e,this.streak}isActive(e){return e-this.lastTurn<=this.window}reset(){this.streak=0,this.lastTurn=-1/0}toJSON(){return{streak:this.streak,lastTurn:this.lastTurn}}static fromJSON(t,n){let r=new e(t);return r.streak=n.streak,r.lastTurn=n.lastTurn,r}},TB=class e{constructor(e){if(this.index=-1,this.remaining=0,e.length===0)throw Error(`a multi-stage ability needs at least one stage`);this.stages=e}get active(){return this.index>=0}get stage(){return this.index>=0?this.stages[this.index]:null}start(){return!this.active&&(this.index=0,this.remaining=this.stages[0].duration,!0)}advance(){return!this.active||(this.remaining--,this.remaining>0)?null:(this.index++,this.index>=this.stages.length?(this.index=-1,`done`):(this.remaining=this.stages[this.index].duration,this.stages[this.index].name))}cancel(){this.index=-1,this.remaining=0}toJSON(){return{index:this.index,remaining:this.remaining}}static fromJSON(t,n){let r=new e(t);return r.index=n.index,r.remaining=n.remaining,r}},EB=class e{constructor(e){if(this.index=0,this.state=`idle`,typeof e.damage!=`function`&&!Number.isFinite(e.damage))throw Error(`beam damage must be a finite number or a function`);if(typeof e.damage==`number`&&e.damage<0)throw Error(`beam damage must be non-negative`);if(this.options=e,this.shape=e.shape??(e.fronts?`fronts`:`line`),e.fronts){let t=e.fronts([{...e.from}],0);this.fronts=t.length?[t.map(e=>({...e}))]:[]}else this.fronts=Qz(e.level,e.from,e.target,{kind:`line`}).slice(1).map(e=>[{...e}])}get active(){return this.state===`active`}get done(){return this.state===`done`||this.state===`blocked`||this.state===`cancelled`}get beamShape(){return this.shape}get currentPath(){return this.fronts.flat().map(e=>({...e}))}start(){return this.state===`idle`&&(this.state=this.fronts.length===0?`done`:`active`,!0)}advance(){if(this.state!==`active`)return this.inactiveStep();let e=this.fronts[this.index]??[],t=Math.max(0,this.fronts.length-this.index-1),n=[],r=[],i=0;for(let a of e){let e={cell:{...a},step:this.index,remaining:t};if(!this.blocked(a,e)){n.push({...a}),this.options.onCell?.({...a},e);for(let t of this.options.targetsAt?.(a)??[]){let n=typeof this.options.damage==`function`?this.options.damage(t,e):this.options.damage;if(!Number.isFinite(n)||n<0)throw Error(`beam damage callback must return a non-negative finite number`);i+=n,r.push(t),this.options.applyDamage?.(t,n,e)}}}let a=this.index;if(this.index++,this.options.fronts&&n.length>0){let e=this.options.fronts(n.map(e=>({...e})),this.index);e.length&&this.fronts.push(e.map(e=>({...e})))}return n.length===0?this.state=`blocked`:this.index>=this.fronts.length&&(this.state=`done`),{status:n.length===0?`blocked`:this.state,cell:n[0]?{...n[0]}:null,cells:n.map(e=>({...e})),step:a,remaining:t,targets:[...r],damage:i}}cancel(){(this.state===`active`||this.state===`idle`)&&(this.state=`cancelled`)}toJSON(){return{state:this.state,fronts:this.fronts.map(e=>e.map(e=>({...e}))),index:this.index,shape:this.shape}}static fromJSON(t,n){let r=n.shape??(t.fronts?`fronts`:`line`);if(t.shape!==void 0&&t.shape!==r)throw Error(`beam save is shape "${r}", not "${t.shape}"`);let i=Object.create(e.prototype);return i.options=t,i.shape=r,i.fronts=n.fronts?n.fronts.map(e=>e.map(e=>({...e}))):(n.path??[]).map(e=>[{...e}]),i.index=n.index,i.state=n.state,i}blocked(e,t){let n=this.options.blocker??(this.options.stopAtOpaque===!1?`none`:`terrain`),r=!1;return n===`terrain`?r=!this.options.level.inside(e.x,e.y)||!this.options.level.transparent(e.x,e.y):n!==`none`&&(r=n({...e},t)===!0),r||this.options.isBlocked?.({...e},t)===!0}inactiveStep(){return{status:this.state,cell:null,cells:[],step:this.index,remaining:Math.max(0,this.fronts.length-this.index),targets:[],damage:0}}};_e();function DB(e,t={}){return(t.within?[...t.within]:AB(e.cellCount)).filter(n=>!(t.occupied?.has(n)||t.terrain&&!t.terrain.has(e.terrain[n])))}function OB(e,t,n){let r=new Set([t]),i=[t];for(let t=0;t<Math.max(0,n);t++){let t=[];for(let n of i)e.forEachNeighbor(e.xOf(n),e.yOf(n),8,(n,i)=>{if(!e.inside(n,i))return;let a=e.index(n,i);r.has(a)||(r.add(a),t.push(a))});i=t}return r.delete(t),[...r]}function kB(e,t){let n=[...new Set(e)];oe(n);let r=n.slice(0,Math.max(0,t));return{cells:r,trace:{requested:t,available:n.length,selected:r}}}function AB(e){let t=Array(e);for(let n=0;n<e;n++)t[n]=n;return t}var jB=l({AbilityCycle:()=>xB,BossPhases:()=>bB,CombatHooks:()=>SB,DUNGEON_KINDS:()=>vz,Doors:()=>yB,Elevation:()=>uB,FLOOR:()=>lz,FeatureLayer:()=>Tz,FieldOfView:()=>lB,Level:()=>uz,MultiStageAbility:()=>TB,MultiTurnBeam:()=>EB,Pathfinder:()=>dB,Scheduler:()=>fB,Secrets:()=>vB,Stealth:()=>CB,TargetingController:()=>cB,TriggerTracker:()=>wB,WALL:()=>cz,areaFalloffMultiplier:()=>oB,ballistica:()=>Jz,canTarget:()=>Xz,candidateCells:()=>DB,cellsNear:()=>OB,chainTargets:()=>iB,chebyshevDistance:()=>Kz,checkDeterminism:()=>jz,compareDungeonArtifacts:()=>Az,coneCells:()=>eB,coneSector:()=>rB,decideMonsterAI:()=>pB,eligibleBuilders:()=>gz,findFreeCell:()=>Cz,furthestRoom:()=>wz,generateDungeon:()=>bz,generateDungeonGraph:()=>yz,hallBuilder:()=>pz,hasLineOfSight:()=>Yz,hexConeCells:()=>$z,knockbackPath:()=>sB,neighbourOffsets:()=>sz,pickBuilder:()=>_z,rangeMultiplier:()=>aB,rectCenter:()=>dz,rectsOverlap:()=>fz,resolveArea:()=>Zz,resolveAreaOnLevel:()=>Qz,rollRoster:()=>Ez,selectDistinctCells:()=>kB,traceLine:()=>qz});function MB(e,t){let n=e=>t.filter(t=>t.op===e).sort((e,t)=>(e.order??0)-(t.order??0)),r=e;for(let e of n(`add`))r+=e.value;for(let e of n(`multiply`))r*=e.value;for(let e of n(`set`))r=e.value;return r}var NB=class e{constructor(e){this.modifiers=[],this.cache=null,this.baseValues={...e.base},this.derived=e.derived??[]}base(e){return this.baseValues[e]??0}setBase(e,t){this.baseValues[e]=t,this.cache=null}addModifier(e){this.modifiers.push(e),this.cache=null}removeModifier(e){let t=this.modifiers.indexOf(e);t!==-1&&this.modifiers.splice(t,1),this.cache=null}removeModifiersFrom(e){this.modifiers=this.modifiers.filter(t=>t.source!==e),this.cache=null}get(e){return this.resolveAll()[e]??0}resolveAll(){if(this.cache)return this.cache;let e={...this.baseValues};for(let t of Object.keys(e))e[t]=MB(e[t],this.modifiersFor(t));for(let t of this.derived)e[t.name]=MB(t.from(e),this.modifiersFor(t.name));return this.cache=e,e}modifiersFor(e){return this.modifiers.filter(t=>t.stat===e)}toJSON(){return{base:{...this.baseValues}}}static fromJSON(t,n){let r=new e(t);return r.baseValues={...t.base,...n.base},r.cache=null,r}};function PB(e,t,n){return{maxLevel:n,experienceFor:n=>n<=1?0:Math.round(e*(n-1)**t)}}var FB=class e{constructor(e,t={}){this.curve=e,this.level=t.level??1,this.experience=t.experience??this.curve.experienceFor(this.level)}get experienceToNext(){return this.level>=this.curve.maxLevel?null:this.curve.experienceFor(this.level+1)-this.experience}addExperience(e){this.experience+=e;let t=0;for(;this.level<this.curve.maxLevel&&this.experience>=this.curve.experienceFor(this.level+1);)this.level++,t++;return t}toJSON(){return{level:this.level,experience:this.experience}}static fromJSON(t,n){return new e(t,n)}};_e();function IB(e,t,n=()=>ne(1,20)){return e+n()>=t}var LB=class e{constructor(e,t={}){this.available=0,this.stats=e,this.capFor=t.cap??(()=>1/0),this.costFor=t.cost??(()=>1)}get points(){return this.available}grant(e){this.available+=e}canSpend(e){return this.nextRankCost(e)!==null}spend(e){let t=this.nextRankCost(e);if(t===null)return!1;let n=this.stats.base(e);return this.available-=t,this.stats.setBase(e,n+1),!0}nextRankCost(e){let t=this.stats.base(e);if(t>=this.capFor(e))return null;let n=this.costFor(e,t+1);return this.available>=n?n:null}toJSON(){return{points:this.available}}static fromJSON(t,n,r){let i=new e(t,n);return i.available=r.points,i}},RB=class e{constructor(e,t=null,n={}){this.worn=new Map,this.names=new Set(e),this.stats=t,this.isSlotLocked=n.locked??(()=>!1)}get(e){return this.worn.get(e)}isLocked(e){let t=this.worn.get(e);return t!==void 0&&this.isSlotLocked(e,t)}equip(e,t){if(this.assertSlot(e),this.isLocked(e))return;let n=this.unequip(e);return this.wear(e,t),n}wear(e,t){this.worn.set(e,t);for(let e of t.modifiers??[])this.stats?.addModifier({...e,source:t})}unequip(e){let t=this.worn.get(e);if(t&&!this.isSlotLocked(e,t))return this.worn.delete(e),this.stats?.removeModifiersFrom(t),t}get slots(){return[...this.names]}assertSlot(e){if(!this.names.has(e))throw Error(`no such equipment slot: "${e}"`)}toJSON(e){return{worn:[...this.worn].map(([t,n])=>[t,e(n)])}}static fromJSON(t,n){let r=new e(t.slots,t.stats??null,{locked:t.locked});for(let[e,i]of n.worn)r.assertSlot(e),r.wear(e,t.resolve(i));return r}},zB=class e{constructor(e={}){this.slots=[],this.capacity=e.capacity}get items(){return this.slots}get totalWeight(){return this.slots.reduce((e,t)=>e+this.weightOf(t),0)}weightOf(e){return(e.weight??0)*e.quantity+(e.contents?.totalWeight??0)}find(e,t){return this.slots.find(n=>n.id===e&&(t===void 0||n.instanceId===t))}add(e){if(!Number.isFinite(e.quantity)||e.quantity<=0||e.weight!==void 0&&(!Number.isFinite(e.weight)||e.weight<0)||this.capacity!==void 0&&this.totalWeight+this.weightOf(e)>this.capacity)return!1;if(e.stackable){let t=this.slots.find(t=>t.id===e.id&&t.stackable&&t.instanceId===e.instanceId);if(t)return t.quantity+=e.quantity,!0}return this.slots.push({...e}),!0}remove(e,t,n){if(t!==void 0&&(!Number.isFinite(t)||t<=0))return;let r=this.slots.findIndex(t=>t.id===e&&(n===void 0||t.instanceId===n));if(r===-1)return;let i=this.slots[r];i.quantity-=t??i.quantity,i.quantity<=0&&this.slots.splice(r,1)}take(e,t=1,n){if(!Number.isFinite(t)||t<=0)return;let r=this.slots.findIndex(t=>t.id===e&&(n===void 0||t.instanceId===n));if(r===-1)return;let i=this.slots[r],a=Math.min(Math.floor(t),i.quantity);if(a<=0)return;let o={...i,quantity:a};return i.quantity-=a,i.quantity<=0&&this.slots.splice(r,1),o}toJSON(){return{capacity:this.capacity,slots:this.slots.map(e=>({id:e.id,quantity:e.quantity,instanceId:e.instanceId,identified:e.identified,cursed:e.cursed,blessed:e.blessed,level:e.level,affix:e.affix,durability:e.durability,maxDurability:e.maxDurability,contents:e.contents?.toJSON()}))}}static fromJSON(t,n){let r=new e({capacity:n.capacity});return r.slots=n.slots.map(n=>{let r=t.get(n.id);if(!r)throw Error(`Inventory.fromJSON: no definition for item "${n.id}"`);let{contents:i,...a}=n,o={...r,...BB(a),id:n.id,quantity:n.quantity};return i&&(o.contents=e.fromJSON(t,i)),o}),r}};function BB(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function VB(e,t){return t.matches?t.matches(e):t.category===void 0?typeof t.id==`string`?e.id===t.id:(t.id??[]).includes(e.id):e.category===t.category}function HB(e){return e.matches!==void 0||e.category!==void 0||e.id!==void 0}function UB(e,t){let n=new Map;for(let t of e.items)n.set(t,t.quantity);let r=new Map;for(let i of t.ingredients){if(!HB(i))throw Error(`recipe ingredient must name an id, a category, or a matches predicate`);if(!Number.isFinite(i.quantity)||i.quantity<=0)throw Error(`recipe ingredient quantity must be a positive number`);let t=i.quantity;for(let a of e.items){if(t<=0)break;let e=n.get(a)??0;if(e<=0||!VB(a,i))continue;let o=Math.min(e,t);n.set(a,e-o),t-=o,r.set(a,(r.get(a)??0)+o)}if(t>0)return!1}for(let[t,n]of r)e.remove(t.id,n,t.instanceId);if(e.add(t.result))return!0;for(let[t,n]of r)e.add({...t,quantity:n});return!1}function WB(e,t){let n=e.add({duration:t.duration,tick:e=>t.tick?.(e),onExpire:t.onExpire});return{cancel:()=>{e.remove(n),t.onExpire()}}}function GB(e,t,n){let r=Symbol(`statusEffect`);for(let t of n.modifiers)e.addModifier({...t,source:r});return WB(t,{duration:n.duration,tick:n.tick,onExpire:()=>e.removeModifiersFrom(r)})}_e();function KB(e,t={}){let n=e.entries.filter(e=>e.weight>0&&(t.curse===void 0||!!e.curse===t.curse)&&(t.predicate?.(e)??!0));if(n.length===0)return null;let r=ie(n.map(e=>e.weight));return r===null?null:n[r]}function qB(e){return e.affix}function JB(e,t){let n=e.affix!==void 0;e.affix=t.id,t.curse?e.cursed=!0:n&&(e.cursed=!1)}function YB(e){e.affix!==void 0&&(e.cursed=!1),delete e.affix}function XB(e,t){if(e.affix===void 0){YB(t);return}t.affix=e.affix,t.cursed=e.cursed??!1}function ZB(e,t){return!(e.trigger!==t.trigger||e.kinds&&(t.kind===void 0||!e.kinds.includes(t.kind)))}function QB(e){e.identified=!0}function $B(e,t,n=`keep`){return Number.isFinite(t)?(e.level=(e.level??0)+t,n===`remove`&&YB(e),e.level):e.level??0}function eV(e,t){return e.maxDurability===void 0?!1:!Number.isFinite(t)||t<=0?(e.durability??e.maxDurability)<=0:(e.durability=Math.max(0,(e.durability??e.maxDurability)-t),e.durability<=0)}function tV(e,t){e.maxDurability!==void 0&&(!Number.isFinite(t)||t<=0||(e.durability=Math.min(e.maxDurability,(e.durability??e.maxDurability)+t)))}function nV(e,t,n){let r=new Map;for(let t of Object.keys(n.fields))r.set(t,e[t]),e[t]=n.fields[t];return WB(t,{duration:n.duration,tick:n.tick,onExpire:()=>{for(let[t,n]of r)e[t]=n}})}var rV=class e{constructor(e){this.progress=0,this.max=e.max,this.regenRate=e.regenRate,this.value=e.current??e.max}get current(){return this.value}canAfford(e){return this.value>=e}spend(e){return this.canAfford(e)?(this.value-=e,!0):!1}refund(e=1){let t=Math.min(e,this.max-this.value);return this.value+=t,t}advance(e=1){if(!(this.value>=this.max)){for(this.progress+=e;this.progress>=this.regenRate&&this.value<this.max;)this.progress-=this.regenRate,this.value++;this.value>=this.max&&(this.progress=0)}}toJSON(){return{current:this.value,progress:this.progress}}static fromJSON(t,n){let r=new e({...t,current:n.current});return r.progress=n.progress,r}};_e();function iV(e){if(e.entries.length===0||!A(e.chance??1))return null;let t=ie(e.entries.map(e=>e.weight));if(t===null)return null;let n=e.entries[t];return{id:n.id,quantity:n.quantity??1}}var aV=class e{constructor(e){this.grantedTiers=0,this.balance=0,this.choices=new Map,this.track=e}get points(){return this.balance}openTiers(e){let t=[];return this.track.tiers.forEach((n,r)=>{e>=n.threshold&&t.push(r)}),t}grant(e){let t=0;for(;this.grantedTiers<this.track.tiers.length&&e>=this.track.tiers[this.grantedTiers].threshold;){let e=this.track.tiers[this.grantedTiers];e.kind===`points`&&(this.balance+=e.points??0,t+=e.points??0),this.grantedTiers++}return t}spend(e){return this.balance<e?!1:(this.balance-=e,!0)}choose(e,t,n){let r=this.track.tiers[e];if(!r)throw Error(`no such advancement tier: ${e}`);if(r.kind===`points`)throw Error(`tier ${e} grants points, it has no choice`);if(n<r.threshold)throw Error(`tier ${e} has not opened yet`);if(this.choices.has(e))throw Error(`tier ${e} is already decided`);if(!(r.options??[]).some(e=>e.id===t))throw Error(`tier ${e} has no option "${t}"`);this.choices.set(e,t)}choice(e){return this.choices.get(e)??null}toJSON(){return{grantedTiers:this.grantedTiers,balance:this.balance,choices:[...this.choices]}}static fromJSON(t,n){let r=new e(t);r.grantedTiers=n.grantedTiers,r.balance=n.balance;for(let[e,t]of n.choices)r.choices.set(e,t);return r}};function oV(e,t){return t.map(t=>({stat:t.stat,op:t.op,value:t.base+t.perLevel*e}))}_e();function sV(e){if(e.labels.length<e.kinds.length)throw Error(`not enough appearances: ${e.kinds.length} kinds but only ${e.labels.length} labels`);let t=[...e.labels];for(let e=t.length-1;e>0;e--){let n=te(0,e+1);[t[e],t[n]]=[t[n],t[e]]}let n=new Map;return e.kinds.forEach((e,r)=>n.set(e,t[r])),n}var cV=class e{constructor(e){this.assigned=new Map,this.tables=e}appearanceOf(e,t){let n=this.assigned.get(e);if(!n){let t=this.tables[e];if(!t)throw Error(`no such appearance category: "${e}"`);n=sV(t),this.assigned.set(e,n)}let r=n.get(t);if(r===void 0)throw Error(`"${t}" is not in appearance category "${e}"`);return r}toJSON(){return{assigned:[...this.assigned].map(([e,t])=>[e,[...t]])}}static fromJSON(t,n){let r=new e(t);for(let[e,t]of n.assigned)r.assigned.set(e,new Map(t));return r}};function lV(e,t,n,r,i,a){let o=a.prices.get(r);if(!o)return!1;let s=t.find(r);if(!s||s.quantity<i)return!1;let c=o.buy*i;return e.base(a.currency)<c?!1:(t.remove(r,i),n.add({...s,quantity:i})?(e.setBase(a.currency,e.base(a.currency)-c),!0):(t.add({...s,quantity:i}),!1))}function uV(e,t,n,r,i,a){let o=a.prices.get(r);if(!o)return!1;let s=n.find(r);return!s||s.quantity<i?!1:(n.remove(r,i),t.add({...s,quantity:i})?(e.setBase(a.currency,e.base(a.currency)+o.sell*i),!0):(n.add({...s,quantity:i}),!1))}function dV(e){let t=Array.isArray(e)?e:[e];for(let e of t)if(!Number.isFinite(e.amount)||e.amount<0)throw Error(`a resource cost must be a non-negative number, "${e.stat}" costs ${e.amount}`);return t}function fV(e){let t=new Map;for(let n of e)t.set(n.stat,(t.get(n.stat)??0)+n.amount);return t}function pV(e,t){return[...fV(dV(t))].every(([t,n])=>e.base(t)>=n)}function mV(e,t){let n=fV(dV(t));if(![...n].every(([t,n])=>e.base(t)>=n))return!1;for(let[t,r]of n)e.setBase(t,e.base(t)-r);return!0}function hV(e,t,n=1){for(let[r,i]of fV(dV(t)))e.setBase(r,e.base(r)+i*n)}function gV(e,t,n,r){return mV(e,t)?n.refund(Math.floor(t.amount/r)):0}var _V=class e{constructor(){this.layers=[]}add(e,t=0){e<=0||this.layers.push({amount:e,decayPerTick:t})}get total(){return this.layers.reduce((e,t)=>e+t.amount,0)}get layerCount(){return this.layers.length}absorb(e){let t=e,n=0;for(;t>0&&this.layers.length>0;){let e=this.layers[this.layers.length-1],r=Math.min(e.amount,t);e.amount-=r,t-=r,n+=r,e.amount<=0&&this.layers.pop()}return n}advance(e=1){for(let t=this.layers.length-1;t>=0;t--){let n=this.layers[t];n.decayPerTick&&(n.amount-=n.decayPerTick*e,n.amount<=0&&this.layers.splice(t,1))}}clear(){this.layers=[]}toJSON(){return{layers:this.layers.map(e=>({...e}))}}static fromJSON(t){let n=new e;return n.layers=t.layers.map(e=>({...e})),n}};_e();function vV(e,t,n){return oe([...t]).slice(0,Math.min(n,t.length)).map(t=>{let n=Symbol(`trait:${t.name}`);for(let r of t.modifiers)e.addModifier({...r,source:n});return{trait:t,source:n}})}var yV=class{constructor(){this.affected=new Map}update(e,t){let n=new Set(e),r=e.filter(e=>!!e.aura),i=new Set(r);for(let i of r){let r=this.affected.get(i);r||(r=new Map,this.affected.set(i,r));for(let n of e){if(n===i)continue;let e=t(i,n),a=r.get(n);if(e&&!a){let e=Symbol(`aura:${i.aura.name}`);for(let t of i.aura.modifiers)n.stats.addModifier({...t,source:e});r.set(n,e)}else!e&&a&&(n.stats.removeModifiersFrom(a),r.delete(n))}for(let[e,t]of[...r])n.has(e)||(e.stats.removeModifiersFrom(t),r.delete(e))}for(let[e,t]of[...this.affected])if(!i.has(e)){for(let[e,n]of t)e.stats.removeModifiersFrom(n);this.affected.delete(e)}}},bV=class e{constructor(e){if(this.points=new Map,e.some(e=>!e.id||!Number.isFinite(e.threshold)||e.threshold<0))throw Error(`support levels need an id and a non-negative threshold`);this.levels=[...e].sort((e,t)=>e.threshold-t.threshold)}get(e,t){return this.points.get(xV(e,t))??0}level(e,t){let n=this.get(e,t),r=null;for(let e of this.levels){if(e.threshold>n)break;r=e}return r}add(e,t,n){if(!e||!t||e===t)throw Error(`support needs two different named units`);if(!Number.isFinite(n))throw Error(`support amount must be finite, got ${n}`);let r=this.level(e,t),i=xV(e,t),a=Math.max(0,(this.points.get(i)??0)+n);return this.points.set(i,a),{a:e,b:t,points:a,previousLevel:r,level:this.level(e,t)}}toJSON(){return{pairs:[...this.points].map(([e,t])=>{let[n,r]=e.split(`\0`);return[n,r,t]})}}static fromJSON(t,n){let r=new e(t);for(let[e,t,i]of n.pairs){if(!e||!t||e===t||!Number.isFinite(i)||i<0)throw Error(`invalid support save data`);let n=xV(e,t);if(r.points.has(n))throw Error(`invalid support save data: duplicate pair "${e}" / "${t}"`);r.points.set(n,i)}return r}};function xV(e,t){return[e,t].sort().join(`\0`)}var SV=new Set([`id`,`growth`,`level`,`startingAffix`,`startingItem`,`lowHpReaction`]);function CV(e,t={},n){let r=new NB({base:OV(e)}),i;e.growth!==void 0&&(i=new FB(DV(e,t),{level:e.level??1}));let a;if(e.startingItem!==void 0){let n=t.items?.[e.startingItem];if(!n)throw Error(`entity template "${e.id}": unknown starting item "${e.startingItem}"`);if(a=n(),e.startingAffix!==void 0){let n=t.affixes?.[e.startingAffix];if(!n)throw Error(`entity template "${e.id}": unknown affix "${e.startingAffix}"`);JB(a,n)}}else if(e.startingAffix!==void 0)throw Error(`entity template "${e.id}": a starting affix needs a starting item to carry it`);let o=new En,s={id:e.id,stats:r,progression:i,item:a,reactions:o};if(e.lowHpReaction!==void 0){if(!n)throw Error(`entity template "${e.id}": names a lowHpReaction threshold but no onLowHp callback was given`);let t=e.lowHpReaction;o.add({id:`low-hp`,when:e=>e.hp/e.maxHp<=t,action:()=>n(s)})}return s}function wV(e,t={},n){return e.map(e=>CV(e,t,n))}function TV(e){let t={stats:e.stats.toJSON()};return e.progression&&(t.progression=e.progression.toJSON()),e.item&&(t.item=e.item),t}function EV(e,t,n,r){let i=CV(e,t,r);if(i.stats=NB.fromJSON({base:OV(e)},n.stats),n.progression!==void 0){if(!i.progression)throw Error(`entity template "${e.id}": save data has progression but the row names no growth curve`);i.progression=FB.fromJSON(DV(e,t),n.progression)}return n.item!==void 0&&(i.item=n.item),i}function DV(e,t){let n=t.growthCurves?.[e.growth??``];if(!n)throw Error(`entity template "${e.id}": unknown growth curve "${e.growth}"`);return n}function OV(e){let t={};for(let[n,r]of Object.entries(e))if(!SV.has(n)){if(typeof r!=`number`)throw Error(`entity template "${e.id}": stat "${n}" must be a number, got ${typeof r}`);t[n]=r}return t}var kV=l({Advancement:()=>aV,Appearances:()=>cV,AuraField:()=>yV,Barrier:()=>_V,Charges:()=>rV,EquipmentSlots:()=>RB,Inventory:()=>zB,Progression:()=>FB,SkillPoints:()=>LB,StatBlock:()=>NB,SupportLedger:()=>bV,affixOf:()=>qB,applyAffix:()=>JB,applyItemStatusEffect:()=>nV,applyStatusEffect:()=>GB,assignAppearances:()=>sV,assignTraits:()=>vV,buildEntities:()=>wV,buildEntity:()=>CV,buy:()=>lV,canAfford:()=>pV,composeModifiers:()=>MB,convertToCharges:()=>gV,copyAffix:()=>XB,craft:()=>UB,damageItem:()=>eV,enchant:()=>$B,fromEntitySaveState:()=>EV,identify:()=>QB,matchesContext:()=>ZB,powerCurve:()=>PB,refund:()=>hV,removeAffix:()=>YB,repairItem:()=>tV,rollAffix:()=>KB,rollLoot:()=>iV,scaledModifiers:()=>oV,sell:()=>uV,skillCheck:()=>IB,spend:()=>mV,toEntitySaveState:()=>TV}),AV=class{constructor(){this.factories=new Map,this.loaded=new Map,this.currentId=null}define(e,t,n={}){this.factories.set(e,{create:t,persistent:n.persistent??!0})}enter(e,t){let n=this.factories.get(e);if(!n)throw Error(`no such map: "${e}"`);let r=this.loaded.get(e);return(!r||!n.persistent)&&(r=n.create(),this.loaded.set(e,r)),this.currentId=e,this.lastSpawn=t,r}get current(){return this.currentId?this.loaded.get(this.currentId)??null:null}get currentMapId(){return this.currentId}get spawn(){return this.lastSpawn}isLoaded(e){return this.loaded.has(e)}isPersistent(e){return this.factories.get(e)?.persistent??!0}unload(e){if(e===this.currentId)throw Error(`cannot unload the current map: "${e}"`);this.loaded.delete(e)}},jV=class{constructor(){this.locations=new Map}add(e){this.locations.set(e.id,e)}remove(e){this.locations.delete(e)}get(e){return this.locations.get(e)}at(e,t){for(let n of this.locations.values())if(n.x===e&&n.y===t)return n}get all(){return[...this.locations.values()]}},MV=class{constructor(){this.turn=0,this.effects=new Map}add(e){let t=Symbol();return this.effects.set(t,{...e}),t}remove(e){this.effects.delete(e)}has(e){return this.effects.has(e)}advance(e=1){this.turn+=e;for(let[t,n]of this.effects)n.tick(this.turn),n.duration!==void 0&&(n.duration-=e,n.duration<=0&&(this.effects.delete(t),n.onExpire?.()))}};_e();function NV(e){if(e.entries.length===0||!A(e.rate))return null;let t=ie(e.entries.map(e=>e.weight));return t===null?null:e.entries[t].value}var PV=class e{constructor(e={}){if(this.changed=new p,this.dayLength=e.dayLength??120,!(this.dayLength>0))throw Error(`an environment day must be longer than zero seconds`);if(this.boundaries=e.phaseBoundaries??[.2,.7,.8],this.boundaries[0]<=0||this.boundaries[0]>=this.boundaries[1]||this.boundaries[1]>=this.boundaries[2]||this.boundaries[2]>=1)throw Error(`environment phase boundaries must be ascending fractions strictly between 0 and 1`);if(this.seconds_=e.startSeconds??0,this.weather_=e.startWeather??`clear`,!Number.isFinite(this.seconds_))throw Error(`environment startSeconds must be finite`)}get day(){return Math.floor(this.seconds_/this.dayLength)}get seconds(){return this.seconds_}get weather(){return this.weather_}get phase(){let e=(this.seconds_%this.dayLength+this.dayLength)%this.dayLength/this.dayLength;return e<this.boundaries[0]?`dawn`:e<this.boundaries[1]?`day`:e<this.boundaries[2]?`dusk`:`night`}get night(){return this.phase===`night`}update(e){if(!Number.isFinite(e)||e<0)throw Error(`environment update must be non-negative, got ${e}`);this.seconds_+=e;let t=this.toJSON();return this.changed.dispatch(t),t}setWeather(e){if(!e)throw Error(`weather needs a non-empty id`);this.weather_=e;let t=this.toJSON();return this.changed.dispatch(t),t}toJSON(){return{day:this.day,seconds:this.seconds_,phase:this.phase,weather:this.weather_}}static fromJSON(t,n){return new e({...t,startSeconds:n.seconds,startWeather:n.weather})}},FV=class e{constructor(e){if(e.sides.length===0)throw Error(`SideTurns needs at least one side`);if(e.schedule.length===0)throw Error(`SideTurns needs a non-empty schedule`);let t=e.round??1,n=e.sideIndex??0,r=e.timeIndex??0;if(!Number.isInteger(t)||t<1)throw Error(`SideTurns round must be a positive integer`);if(n<0||n>=e.sides.length)throw Error(`SideTurns side index ${n} is outside ${e.sides.length} sides`);if(r<0||r>=e.schedule.length)throw Error(`SideTurns time index ${r} is outside ${e.schedule.length} times`);this.sides=[...e.sides],this.schedule=[...e.schedule],this.areas=e.areas??[],this.state={round:t,sideIndex:n,timeIndex:r}}get round(){return this.state.round}get side(){return this.sides[this.state.sideIndex]}get timeIndex(){return this.state.timeIndex}get timeOfDay(){return this.schedule[this.state.timeIndex]}get snapshot(){return{...this.state}}timeOfDayAt(e,t){for(let n of this.areas)if(n.contains(e,t))return n.times[this.state.timeIndex]??this.timeOfDay;return this.timeOfDay}lawfulBonusAt(e,t,n){return IV(e,this.timeOfDayAt(t,n).lawfulBonus)}advance(){let e=!1;return this.state.sideIndex++,this.state.sideIndex>=this.sides.length&&(this.state.sideIndex=0,this.state.round++,this.state.timeIndex=(this.state.timeIndex+1)%this.schedule.length,e=!0),{side:this.side,round:this.state.round,newRound:e}}toJSON(){return this.snapshot}static fromJSON(t,n){return new e({...t,round:n.round,sideIndex:n.sideIndex,timeIndex:n.timeIndex})}};function IV(e,t){switch(e){case`lawful`:return t;case`chaotic`:return-t;default:return 0}}var LV=l({EnvironmentClock:()=>PV,Overworld:()=>jV,SideTurns:()=>FV,TurnClock:()=>MV,World:()=>AV,alignmentBonus:()=>IV,rollEncounter:()=>NV});_e();function RV(e,t,n={}){let r=n.pick??te,i=0;return t.forEach((t,n)=>{zV(t,t.name??`#${n+1}`,e.shape);let a=BV(e,t);if(i+=a.length,a.length!==0)for(let[n,i]of a){let a=t.outputs[r(t.outputs.length)];for(let[r,o]of Object.entries(a))for(let a=0;a<t.height;a++)for(let s=0;s<t.width;s++){let c=o[a*t.width+s];c!==-1&&e.setTile(r,n+s,i+a,c)}}}),i}function zV(e,t,n){if(e.topology&&(n===`square`||n===`hex`)&&e.topology!==n)throw Error(`automap rule "${t}" targets ${e.topology} cells, but the map is ${n}`);if(!Number.isInteger(e.width)||e.width<=0||!Number.isInteger(e.height)||e.height<=0)throw Error(`automap rule "${t}" needs a positive width and height`);if(e.outputs.length===0)throw Error(`automap rule "${t}" has no outputs - a rule that matches and writes nothing is a mistake`);let r=e.width*e.height;for(let[n,i]of Object.entries(e.input))if(i.length!==r)throw Error(`automap rule "${t}" input "${n}" has ${i.length} cells, but the pattern is ${r}`);e.outputs.forEach((e,n)=>{for(let[i,a]of Object.entries(e))if(a.length!==r)throw Error(`automap rule "${t}" output ${n+1} "${i}" has ${a.length} cells, but the pattern is ${r}`)})}function BV(e,t){let n=[];for(let r=0;r+t.height<=e.heightInTiles;r++)for(let i=0;i+t.width<=e.widthInTiles;i++)VV(e,t,i,r)&&n.push([i,r]);return n}function VV(e,t,n,r){for(let[i,a]of Object.entries(t.input))for(let o=0;o<t.height;o++)for(let s=0;s<t.width;s++){let c=a[o*t.width+s];if(c!==-1&&e.getTile(i,n+s,r+o)!==c)return!1}return!0}var HV=class e{constructor(){this.switches=new Map,this.variables=new Map}switch(e){return this.switches.get(e)??!1}setSwitch(e,t){this.switches.set(e,t)}variable(e){return this.variables.get(e)??0}setVariable(e,t){this.variables.set(e,t)}toJSON(){return{switches:[...this.switches],variables:[...this.variables]}}static fromJSON(t){let n=new e;for(let[e,r]of t.switches)n.setSwitch(e,r);for(let[e,r]of t.variables)n.setVariable(e,r);return n}};function UV(e,t){return`switch`in e?t.switch(e.switch)===e.equals:t.variable(e.variable)>=e.atLeast}function WV(e,t){let n;for(let r of e.pages)(r.conditions??[]).every(e=>UV(e,t))&&(n=r);return n}var GV=class{constructor(e){this.cancelled=!1,this.options=e,this.state={game:e.game,answers:{}}}cancel(){this.cancelled=!0}async run(e){let t=await this.runList(e);if(t!==void 0){if(this.options.onUnknownCommand)return this.options.onUnknownCommand({goto:t}),this.state;throw Error(`a "goto ${t}" only runs inside runStory, not a straight run`)}return this.state}async runStory(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw Error(`this event story has no passage named "${t}"`);let n=e[t],r=0;for(;r<n.length&&!this.cancelled;){let t=await this.step(n[r]);if(r++,t!==void 0){if(!Object.prototype.hasOwnProperty.call(e,t))throw Error(`this event story has no passage named "${t}"`);n=e[t],r=0}}return this.state}async runList(e){for(let t of e){if(this.cancelled)break;let e=await this.step(t);if(e!==void 0)return e}}async step(e){if(`say`in e){await this.speak(e.say,e.speaker,e.portrait);return}if(`ask`in e){let t=await this.speak(e.ask,e.speaker,e.portrait,e.choices);return e.store&&(this.state.answers[e.store]=t),e.choices.find(e=>(e.value??e.text)===t)?.goto}if(`wait`in e){await new Promise(t=>setTimeout(t,e.wait*1e3));return}if(`setSwitch`in e){this.state.game.setSwitch(e.setSwitch,e.value);return}if(`setVariable`in e){this.state.game.setVariable(e.setVariable,e.value);return}if(`addVariable`in e){let t=this.state.game.variable(e.addVariable);this.state.game.setVariable(e.addVariable,t+e.amount);return}if(`if`in e){let t=UV(e.if,this.state.game);return this.runList(t?e.then:e.else??[])}if(`move`in e){await this.options.move?.(e.move.target,e.move.steps);return}if(`goto`in e)return e.goto;if(`call`in e){await e.call(this.state);return}this.options.onUnknownCommand?.(e)}speak(e,t,n,r){return this.options.present({text:e,speaker:t,portrait:n,choices:r})}};function KV(e,t){t&&e.has?.(t)&&e.play?.(t)}var qV=class{constructor(e,t,n,r){this.facing=`down`,this.target=null,this.progress=0,this.sprite=e,this.x=this.fromX=t,this.y=this.fromY=n,this.tileWidth=r.tileWidth,this.tileHeight=r.tileHeight,this.speed=r.speed??4,this.options=r,this.place(),this.playIdle()}get isMoving(){return this.target!==null}turnTo(e,t){this.target||(this.facing=JV(e,t),this.playIdle())}moveBy(e,t){return!this.target&&(this.facing=JV(e,t),this.fromX=this.x,this.fromY=this.y,this.target={x:this.x+e,y:this.y+t},this.progress=0,this.playWalk(),!0)}jumpBy(e,t){return!this.target&&(this.facing=JV(e,t),this.x+=e,this.y+=t,this.fromX=this.x,this.fromY=this.y,this.place(),this.playIdle(),!0)}update(e){this.sprite.update?.(e),this.target&&(this.progress=Math.min(1,this.progress+this.speed*e),this.sprite.x=YV(this.fromX,this.target.x,this.progress)*this.tileWidth,this.sprite.y=YV(this.fromY,this.target.y,this.progress)*this.tileHeight,this.progress>=1&&(this.x=this.target.x,this.y=this.target.y,this.target=null,this.playIdle()))}place(){this.sprite.x=this.x*this.tileWidth,this.sprite.y=this.y*this.tileHeight}playWalk(){KV(this.sprite,this.options.walkAnimation?.(this.facing))}playIdle(){KV(this.sprite,this.options.idleAnimation?.(this.facing))}};function JV(e,t){return e>0?`right`:e<0?`left`:t>0?`down`:`up`}function YV(e,t,n){return e+(t-e)*n}var XV=[`up`,`down`,`left`,`right`],ZV={up:{dx:0,dy:-1},down:{dx:0,dy:1},left:{dx:-1,dy:0},right:{dx:1,dy:0}},QV={up:{around:`down`,left90:`left`,right90:`right`},down:{around:`up`,left90:`right`,right90:`left`},left:{around:`right`,left90:`down`,right90:`up`},right:{around:`left`,left90:`up`,right90:`down`}},$V=class{constructor(e,t,n={}){this.index=0,this.waiting=0,this.mover=e,this.route=t,this.options=n}get done(){return!this.route.repeat&&this.index>=this.route.steps.length}update(e){if(this.mover.isMoving||this.done||this.waiting>0&&(this.waiting=Math.max(0,this.waiting-e),this.waiting>0))return;this.index>=this.route.steps.length&&(this.index=0);let t=this.route.steps[this.index];(this.runStep(t)||this.route.skippable)&&this.index++}runStep(e){if(`turn`in e){let{dx:t,dy:n}=this.resolveTurn(e);return this.mover.turnTo(t,n),!0}if(`wait`in e)return this.waiting=e.wait,!0;if(`jump`in e)return this.attempt(e.jump.dx,e.jump.dy,(e,t)=>this.mover.jumpBy(e,t));if(`step`in e)return this.attempt(e.step.dx,e.step.dy,(e,t)=>this.mover.moveBy(e,t));let{dx:t,dy:n}=this.resolveDirection(e);return this.attempt(t,n,(e,t)=>this.mover.moveBy(e,t))}resolveDirection(e){return e.dir===`random`?ZV[this.pickDirection()]:e.dir===`forward`?ZV[this.mover.facing]:e.dir===`backward`?ZV[QV[this.mover.facing].around]:e.dir===`toward`||e.dir===`away`?this.resolveAim(e.dir,e):ZV[e.dir]}resolveTurn(e){if(e.turn===`random`)return ZV[this.pickDirection()];if(e.turn===`around`||e.turn===`left90`||e.turn===`right90`)return ZV[QV[this.mover.facing][e.turn]];if(e.turn===`toward`||e.turn===`away`){let t=this.resolveAim(e.turn,e);return t.dx===0&&t.dy===0?ZV[this.mover.facing]:t}return ZV[e.turn]}resolveAim(e,t){let n=`target`in t?t.target():t,r=e===`toward`?1:-1,i=n.x-this.mover.x,a=n.y-this.mover.y;return Math.abs(i)>=Math.abs(a)?{dx:r*Math.sign(i)||0,dy:0}:{dx:0,dy:r*Math.sign(a)||0}}attempt(e,t,n){return e===0&&t===0?!0:this.options.canMove&&!this.options.canMove(e,t)?!1:n(e,t)}pickDirection(){let e=this.options.random??Math.random;return XV[Math.floor(e()*XV.length)]}},eH=class{constructor(e,t,n,r={}){this.facing=0,this.moving=!1,this.sprite=e,this.x=t,this.y=n,this.speed=r.speed??4,this.options=r,this.place(),this.playIdle()}get isMoving(){return this.moving}move(e,t,n){let r=Math.hypot(e,t);r>0?(this.facing=Math.atan2(t,e),this.x+=e/r*this.speed*n,this.y+=t/r*this.speed*n,this.moving||(this.moving=!0,this.playWalk())):this.moving&&(this.moving=!1,this.playIdle()),this.place(),this.sprite.update?.(n)}turnTo(e,t){this.moving||e===0&&t===0||(this.facing=Math.atan2(t,e),this.playIdle())}place(){this.sprite.x=this.x,this.sprite.y=this.y}playWalk(){KV(this.sprite,this.options.walkAnimation?.(this.facing))}playIdle(){KV(this.sprite,this.options.idleAnimation?.(this.facing))}};function tH(e,t){return e.x<t.x+t.width&&e.x+e.width>t.x&&e.y<t.y+t.height&&e.y+e.height>t.y}function nH(e,t){let n=e.x-t.x,r=e.y-t.y,i=e.radius+t.radius;return n*n+r*r<i*i}function rH(e,t){let n=On(e.x,t.x,t.x+t.width),r=On(e.y,t.y,t.y+t.height),i=e.x-n,a=e.y-r;return i*i+a*a<e.radius*e.radius}function iH(e,t,n,r){let{tileSize:i,isSolid:a}=r;if(!(i>0))throw Error(`collision tileSize must be positive`);let o=aH(e.x,e.y,e.width,e.height,t,i,a,!0);return{x:o,y:aH(o,e.y,e.width,e.height,n,i,a,!1)}}function aH(e,t,n,r,i,a,o,s){if(i===0)return s?e:t;let c=s?e:t,l=s?n:r,u=c+i,d=Math.floor((s?t:e)/a),f=Math.floor(((s?t+r:e+n)-1e-6)/a),p=(e,t)=>s?o(e,t):o(t,e);if(i>0){let e=Math.floor((c+l-1e-6)/a),t=Math.floor((u+l-1e-6)/a);for(let n=e+1;n<=t;n++)for(let e=d;e<=f;e++)if(p(n,e))return n*a-l}else{let e=Math.floor(c/a),t=Math.floor(u/a);for(let n=e-1;n>=t;n--)for(let e=d;e<=f;e++)if(p(n,e))return(n+1)*a}return u}var oH=class e{constructor(){this.definitions=new Map,this.stageIndex=new Map,this.tracked=null}define(e){this.definitions.set(e.id,e)}track(e){e!==null&&this.require(e),this.tracked=e}trackedQuest(){return this.tracked!==null&&this.status(this.tracked)===`active`?this.tracked:null}trackedLocation(){let e=this.trackedQuest();return e?this.currentStage(e)?.location??null:null}markerFor(e,t){return e.some(e=>this.status(e)===`active`&&this.stageSatisfied(e,t))?`turnIn`:e.some(e=>this.status(e)===`available`)?`offer`:`none`}canStart(e){return(this.require(e).requires??[]).every(e=>this.status(e)===`complete`)}start(e){if(!this.canStart(e))throw Error(`quest "${e}" cannot start yet - a prerequisite is incomplete`);this.stageIndex.set(e,0)}status(e){let t=this.require(e),n=this.stageIndex.get(e);return n===void 0?this.canStart(e)?`available`:`unavailable`:n>=t.stages.length?`complete`:`active`}currentStage(e){return this.status(e)===`active`?this.require(e).stages[this.stageIndex.get(e)]:null}progress(e,t){let n=this.currentStage(e);return n?.counter?Math.min(1,t.variable(n.counter.variable)/n.counter.target):null}advanceStage(e,t){return this.stageSatisfied(e,t)?(this.stageIndex.set(e,this.stageIndex.get(e)+1),!0):!1}stageSatisfied(e,t){let n=this.currentStage(e);return n?n.condition?UV(n.condition,t):!n.counter||t.variable(n.counter.variable)>=n.counter.target:!1}require(e){let t=this.definitions.get(e);if(!t)throw Error(`no such quest: "${e}"`);return t}toJSON(){return{stageIndex:[...this.stageIndex],tracked:this.tracked}}static fromJSON(t,n){let r=new e;for(let e of t)r.define(e);for(let[e,t]of n.stageIndex)r.stageIndex.set(e,t);return n.tracked&&(r.tracked=n.tracked),r}};function sH(e){let t=[],n=new Map;for(let r of e){let e=n.get(r.questId);e||(e={id:r.questId,stages:[]},r.requires!==void 0&&(e.requires=r.requires),n.set(r.questId,e),t.push(r.questId)),e.stages.push(cH(e.id,r))}return t.map(e=>n.get(e))}function cH(e,t){if(t.conditionSwitch!==void 0&&t.conditionVariable!==void 0)throw Error(`quest "${e}": a stage row cannot name both a condition switch and a condition variable`);let n={};if(t.conditionSwitch!==void 0){if(t.conditionEquals===void 0)throw Error(`quest "${e}": conditionSwitch needs a conditionEquals`);n.condition={switch:t.conditionSwitch,equals:t.conditionEquals}}else if(t.conditionVariable!==void 0){if(t.conditionAtLeast===void 0)throw Error(`quest "${e}": conditionVariable needs a conditionAtLeast`);n.condition={variable:t.conditionVariable,atLeast:t.conditionAtLeast}}if(t.counterVariable!==void 0){if(t.counterTarget===void 0)throw Error(`quest "${e}": counterVariable needs a counterTarget`);n.counter={variable:t.counterVariable,target:t.counterTarget}}if(t.description!==void 0&&(n.description=t.description),t.locationMap!==void 0||t.locationX!==void 0||t.locationY!==void 0){if(t.locationX===void 0||t.locationY===void 0)throw Error(`quest "${e}": a stage location needs both locationX and locationY`);n.location={x:t.locationX,y:t.locationY},t.locationMap!==void 0&&(n.location.map=t.locationMap)}return n}var lH=class{constructor(e){this.name=e}},uH=4,dH=8,fH=new WeakMap;function pH(e){return fH.get(e)}function mH(e,t){return fH.set(e,t),e}var hH=1e3,gH=class{constructor(e){this.pos=0,this.depth=0,this.symbols=[],this.objects=[],this.bytes=e}byte(){if(this.pos>=this.bytes.length)throw Error(`Marshal: unexpected end of input`);return this.bytes[this.pos++]}take(e){if(e<0)throw Error(`Marshal: negative length`);let t=this.bytes.subarray(this.pos,this.pos+e);if(t.length<e)throw Error(`Marshal: unexpected end of input`);return this.pos+=e,t}readFixnum(){let e=this.byte()<<24>>24;if(e===0)return 0;if(e>=5&&e<=127)return e-5;if(e<=-5&&e>=-128)return e+5;if(e>0){let t=0;for(let n=0;n<e;n++)t|=this.byte()<<8*n;return t>>>0}let t=-e,n=0;for(let e=0;e<t;e++)n|=this.byte()<<8*e;return(n>>>0)-2**(8*t)}readBytes(){return this.take(this.readFixnum())}readSymbol(){let e=new TextDecoder().decode(this.readBytes());return this.symbols.push(e),e}readSymbolLink(){let e=this.readFixnum(),t=this.symbols[e];if(t===void 0)throw Error(`Marshal: symbol link ${e} out of range`);return t}readSymbolValue(){let e=String.fromCharCode(this.byte());if(e===`:`)return this.readSymbol();if(e===`;`)return this.readSymbolLink();throw Error(`Marshal: expected a symbol, got tag "${e}"`)}link(e){return this.objects.push(e),e}readBignum(){let e=String.fromCharCode(this.byte())===`-`?-1:1,t=this.readFixnum(),n=0,r=1;for(let e=0;e<t;e++)n+=(this.byte()|this.byte()<<8)*r,r*=65536;return e*n}readFloat(){let e=new TextDecoder().decode(this.readBytes());return e===`inf`?1/0:e===`-inf`?-1/0:e===`nan`?NaN:Number(e)}readArray(){let e=[];this.link(e);let t=this.readFixnum();for(let n=0;n<t;n++)e.push(this.readValue());return e}readHash(e){let t=new Map;this.link(t);let n=this.readFixnum();for(let e=0;e<n;e++)t.set(this.readValue(),this.readValue());return e&&fH.set(t,this.readValue()),t}readIvars(e){let t={};for(let n=0;n<e;n++)t[this.readSymbolValue()]=this.readValue();return t}readObject(){let e={class:``,ivars:{}};return this.link(e),e.class=this.readSymbolValue(),e.ivars=this.readIvars(this.readFixnum()),e}readIvarWrapped(){let e=this.readValue();return this.readIvars(this.readFixnum()),e}readUserDefined(){let e={class:``,raw:new Uint8Array};return this.link(e),e.class=this.readSymbolValue(),e.raw=this.readBytes().slice(),e}readUserMarshal(){let e={class:``,value:null};return this.link(e),e.class=this.readSymbolValue(),e.value=this.readValue(),e}readValue(){if(++this.depth>hH)throw Error(`Marshal: values nested more than ${hH} deep`);try{return this.readTagged()}finally{this.depth--}}readTagged(){let e=String.fromCharCode(this.byte());switch(e){case`0`:return null;case`T`:return!0;case`F`:return!1;case`i`:return this.readFixnum();case`l`:return this.link(this.readBignum());case`f`:return this.link(this.readFloat());case`:`:return this.readSymbol();case`;`:return this.readSymbolLink();case`"`:return this.link(new TextDecoder().decode(this.readBytes()));case`[`:return this.readArray();case`{`:return this.readHash(!1);case`}`:return this.readHash(!0);case`o`:return this.readObject();case`I`:return this.readIvarWrapped();case`u`:return this.readUserDefined();case`U`:return this.readUserMarshal();case`@`:{let e=this.readFixnum(),t=this.objects[e];if(t===void 0)throw Error(`Marshal: object link ${e} out of range`);return t}default:throw Error(`Marshal: unsupported tag "${e}" (0x${e.charCodeAt(0).toString(16)})`)}}readDocument(){let e=this.byte(),t=this.byte();if(e!==uH||t>dH)throw Error(`Marshal: unsupported version ${e}.${t} (expected ${uH}.${dH} or lower)`);return this.readValue()}};function _H(e){return new gH(e).readDocument()}function vH(e){return typeof e==`object`&&!!e&&`class`in e&&`ivars`in e}function yH(e){let t=[uH,dH];return bH(t,e),new Uint8Array(t)}function bH(e,t){if(t==null)e.push(xH(`0`));else if(t===!0)e.push(xH(`T`));else if(t===!1)e.push(xH(`F`));else if(t instanceof lH)e.push(xH(`:`)),SH(e,t.name);else if(typeof t==`number`)Number.isInteger(t)&&Math.abs(t)<2**30?(e.push(xH(`i`)),CH(e,t)):(e.push(xH(`f`)),SH(e,Number.isFinite(t)?String(t):t>0?`inf`:t<0?`-inf`:`nan`));else if(typeof t==`string`)e.push(xH(`"`)),SH(e,t);else if(Array.isArray(t)){e.push(xH(`[`)),CH(e,t.length);for(let n of t)bH(e,n)}else if(t instanceof Map){let n=fH.has(t);e.push(xH(n?`}`:`{`)),CH(e,t.size);for(let[n,r]of t)bH(e,n),bH(e,r);n&&bH(e,fH.get(t))}else if(vH(t)){e.push(xH(`o`)),e.push(xH(`:`)),SH(e,t.class);let n=Object.entries(t.ivars);CH(e,n.length);for(let[t,r]of n)e.push(xH(`:`)),SH(e,t),bH(e,r)}else throw Error(`Marshal: cannot encode a value of type ${typeof t}`)}function xH(e){return e.charCodeAt(0)}function SH(e,t){let n=new TextEncoder().encode(t);CH(e,n.length);for(let t of n)e.push(t)}function CH(e,t){if(t===0){e.push(0);return}if(t>0&&t<=122){e.push(t+5);return}if(t<0&&t>=-123){e.push(t-5&255);return}if(t>0){for(let n=1;n<=4;n++)if(t<2**(8*n)){e.push(n);for(let r=0;r<n;r++)e.push(t>>>8*r&255);return}}else for(let n=1;n<=4;n++)if(t>=-(2**(8*n))){e.push(-n&255);let r=t+2**(8*n);for(let t=0;t<n;t++)e.push(r>>>8*t&255);return}throw Error(`Marshal: integer ${t} is out of range for a Fixnum`)}function wH(e){return Hr(e).map(e=>e.speaker===void 0?{say:e.text}:{say:e.text,speaker:e.speaker})}function TH(e,t={}){let n={};for(let t of e)`say`in t?n[t.say]=t.say:`ask`in t&&(n[t.ask]=t.ask);return{locale:t.locale??`en`,direction:t.direction??`ltr`,messages:n}}function EH(e){let{story:t,start:n,title:r}=Ur(e);return r===void 0?{story:t,start:n}:{story:t,start:n,title:r}}var DH=l({AUTOMAP_EMPTY:()=>-1,EventRunner:()=>GV,FreeMover:()=>eH,GameState:()=>HV,GridMover:()=>qV,MoveRouteRunner:()=>$V,QuestLog:()=>oH,RubySymbol:()=>lH,aabbOverlap:()=>tH,activePage:()=>WV,automap:()=>RV,circleAabbOverlap:()=>rH,circleOverlap:()=>nH,conditionHolds:()=>UV,decodeMarshal:()=>_H,encodeMarshal:()=>yH,extractDialogueCatalog:()=>TH,hashDefaultOf:()=>pH,importTwee:()=>EH,parseDialogueText:()=>wH,questsFromRows:()=>sH,resolveAabbAgainstTiles:()=>iH,withHashDefault:()=>mH}),OH=PB(20,2,100),kH=class{constructor(e){this.species=e.species,this.deriveStats=e.deriveStats,this.progression=new FB(e.species.growth??OH,{level:e.level??1}),this.stats=new NB({base:this.computeBase()})}refreshStats(){let e=this.computeBase();for(let[t,n]of Object.entries(e))this.stats.setBase(t,n)}computeBase(){let e=this.progression.level;return this.deriveStats?this.deriveStats(this.species.baseStats,e):{...this.species.baseStats}}},AH=class{constructor(){this.multipliers=new Map}key(e,t){return`${e}:${t}`}set(e,t,n){this.multipliers.set(this.key(e,t),n)}get(e,t){return this.multipliers.get(this.key(e,t))??1}multiplierFor(e,t){return t.reduce((t,n)=>t*this.get(e,n),1)}},jH=class{constructor(e){this.storage=[],this.active=Array(e).fill(null)}get members(){return this.active}get boxed(){return this.storage}add(e){let t=this.active.indexOf(null);t===-1?this.storage.push(e):this.active[t]=e}store(e){let t=this.active[e];t&&(this.active[e]=null,this.storage.push(t))}withdraw(e,t){if(t<0||t>=this.active.length)return;let n=this.storage[e];if(!n)return;this.storage.splice(e,1);let r=this.active[t];this.active[t]=n,r&&this.storage.push(r)}get activeMembers(){return this.active.filter(e=>e!==null)}};function MH(e){return[...e].sort((e,t)=>(t.priority??0)-(e.priority??0)||t.speed-e.speed)}function NH(e,t){let n=null;for(let r of e)r.at(t)&&(n=r.into);return n}var PH=class{constructor(e,t){this.stages=new Map,this.modifiers=new Map,this.stats=e,this.max=t.max,this.multiplierFor=t.multiplier}get(e){return this.stages.get(e)??0}change(e,t){let n=this.get(e),r=Math.max(-this.max,Math.min(this.max,n+t)),i=r-n;return i===0?0:(this.stages.set(e,r),this.applyModifier(e,r),i)}applyModifier(e,t){let n=this.modifiers.get(e);if(n&&this.stats.removeModifier(n),t===0){this.modifiers.delete(e);return}let r={stat:e,op:`multiply`,value:this.multiplierFor(t)};this.stats.addModifier(r),this.modifiers.set(e,r)}resetAll(){for(let e of this.modifiers.values())this.stats.removeModifier(e);this.modifiers.clear(),this.stages.clear()}};function FH(e,t,n,r=(e,n)=>t.multiplierFor(e.type,n)){if(e.length===0)return null;let i=e[0],a=r(i,n);for(let t of e.slice(1)){let e=r(t,n);e>a&&(a=e,i=t)}return i}function IH(e,t,n,r){let i=null,a=LH(e,n,r);return t.forEach((e,t)=>{let o=LH(e.types,n,r);o<a&&(a=o,i=t)}),i}function LH(e,t,n){return Math.max(...n.map(n=>t.multiplierFor(n,e)))}var RH=class extends S{},zH=class{constructor(){this.conditions=new Map}set(e){this.conditions.set(e.id,{...e})}has(e){return this.conditions.has(e)}get(e){return this.conditions.get(e)}clear(e){this.conditions.delete(e)}get active(){return[...this.conditions.values()]}advance(e=1){for(let[t,n]of this.conditions)n.duration!==void 0&&(n.duration-=e,n.duration<=0&&this.conditions.delete(t))}},BH=class{constructor(e){this.chanceToHit=VH(e.chanceToHit??1),this.strikeDuration=Math.max(0,e.strikeDuration??0),this.totalDamage=Math.max(0,e.damage)*Math.max(0,e.strikes),this.expectedDamage=this.totalDamage*this.chanceToHit,this.defenderHp0=e.defender.hp;let t=[],n=e.defender.hp;for(let r=0;r<=e.strikes;r++)r>0&&(e.hits?.[r-1]??!0)&&(n-=Math.max(0,e.damage)),t.push({strike:r,time:r*this.strikeDuration,attackerHp:e.attacker.hp,defenderHp:Math.max(0,n),defenderDamage:this.defenderHp0-Math.max(0,n)});this.frames=t}get duration(){return this.strikeDuration*(this.frames.length-1)}get defenderKilled(){return this.frames[this.frames.length-1].defenderHp===0}sampleAt(e){let t=this.frames.length-1;if(this.strikeDuration<=0)return this.frames[t];let n=0;for(let r=0;r<=t&&this.frames[r].time<=e+1e-9;r++)n=r;return this.frames[n]}};function VH(e){return Math.max(0,Math.min(1,e))}var HH=class{constructor(e){this.onChange=new p,this.stage_=`attacker`,this.charge=null,this.victim=null,this.highlight_=0,this.units=e.units,this.side=e.side,this.disabledOf=e.disabled??(e=>e.disabled??!1),this.canTarget=e.canTarget??(()=>!0)}get stage(){return this.stage_}get attacker(){return this.charge}get target(){return this.victim}get done(){return this.charge!==null&&this.victim!==null}get candidates(){return this.units.filter(e=>(this.side===void 0||e.side===this.side)&&!this.disabledOf(e))}get targets(){let e=this.charge;return e?this.units.filter(t=>t.id!==e.id&&!this.disabledOf(t)&&(e.side===void 0||t.side!==e.side)&&this.canTarget(e,t)):[]}get highlight(){return this.highlight_}get highlighted(){return this.active()[this.highlight_]??null}move(e){let t=this.active();t.length!==0&&(this.highlight_=((this.highlight_+e)%t.length+t.length)%t.length,this.onChange.dispatch())}select(){let e=this.highlighted;return e?(this.stage_===`attacker`?(this.charge=e,this.stage_=`target`,this.highlight_=0):this.victim=e,this.onChange.dispatch(),!0):!1}back(){if(this.stage_===`attacker`)return;let e=this.charge;this.charge=null,this.victim=null,this.stage_=`attacker`;let t=e?this.candidates.findIndex(t=>t.id===e.id):-1;this.highlight_=t>=0?t:0,this.onChange.dispatch()}reset(){this.charge=null,this.victim=null,this.stage_=`attacker`,this.highlight_=0,this.onChange.dispatch()}active(){return this.stage_===`attacker`?this.candidates:this.targets}},UH=class{constructor(e){this.onChange=new p,this.built=null,this.elapsed_=0,this.handleSelectorChange=()=>{if(this.selector.done&&this.attacker&&this.target){let e=this.damageFor(this.attacker,this.target);this.built=new BH({attacker:{hp:this.attacker.hp??0,name:this.attacker.id},defender:{hp:this.target.hp??0,name:this.target.id},damage:e.damage,strikes:e.strikes,...e.chanceToHit===void 0?{}:{chanceToHit:e.chanceToHit},...e.hits===void 0?{}:{hits:e.hits},strikeDuration:this.strikeDuration}),this.elapsed_=0}else this.built=null;this.onChange.dispatch()},this.damageFor=e.damageFor,this.strikeDuration=e.strikeDuration??0,this.selector=new HH({units:e.units,...e.side===void 0?{}:{side:e.side},...e.disabled===void 0?{}:{disabled:e.disabled},...e.canTarget===void 0?{}:{canTarget:e.canTarget}}),this.selector.onChange.add(this.handleSelectorChange)}get stage(){return this.selector.stage}get attacker(){return this.selector.attacker}get target(){return this.selector.target}get preview(){return this.built}get elapsed(){return this.elapsed_}get finished(){return this.built!==null&&this.elapsed_>=this.built.duration}get frame(){return this.built?this.built.sampleAt(this.elapsed_):null}move(e){this.selector.move(e)}select(){return this.selector.select()}back(){this.selector.back()}update(e){return this.built?(this.elapsed_=Math.min(this.built.duration,this.elapsed_+Math.max(0,e)),this.frame):null}finish(){this.built&&(this.elapsed_=this.built.duration)}reset(){this.selector.reset(),this.built=null,this.elapsed_=0}},WH=class{constructor(){this.onChange=new p,this.planned=[],this.undone=[]}get plans(){return this.planned}get isEmpty(){return this.planned.length===0}get canUndo(){return this.planned.length>0}get canRedo(){return this.undone.length>0}plannedFor(e){return this.planned.find(t=>t.unit===e)}plan(e){let t=this.planned.findIndex(t=>t.unit===e.unit);t>=0?this.planned[t]=e:this.planned.push(e),this.undone=[],this.onChange.dispatch()}undo(){let e=this.planned.pop();return e?(this.undone.push(e),this.onChange.dispatch(),e):null}redo(){let e=this.undone.pop();return e?(this.planned=this.planned.filter(t=>t.unit!==e.unit),this.planned.push(e),this.onChange.dispatch(),e):null}clear(){(this.planned.length!==0||this.undone.length!==0)&&(this.planned=[],this.undone=[],this.onChange.dispatch())}commit(){let e=this.planned;return this.planned=[],this.undone=[],e.length>0&&this.onChange.dispatch(),e}},GH=class e{constructor(){this.counts=new Map}record(e,t,n=1){let r=this.counts.get(e)??new Map;r.set(t,(r.get(t)??0)+n),this.counts.set(e,r)}forType(e,t){return this.counts.get(e)?.get(t)??0}total(e){let t=this.counts.get(e);if(!t)return 0;let n=0;for(let e of t.values())n+=e;return n}breakdown(e){let t=this.counts.get(e);return t?[...t.entries()].map(([e,t])=>({unitType:e,count:t})):[]}toJSON(){return{counts:[...this.counts].map(([e,t])=>[e,[...t]])}}static fromJSON(t){let n=new e;for(let[e,r]of t.counts)n.counts.set(e,new Map(r));return n}},KH=l({AttackDialog:()=>UH,AttackPreview:()=>BH,BattleHooks:()=>RH,BattleStats:()=>GH,Creature:()=>kH,Field:()=>zH,Party:()=>jH,StatStages:()=>PH,TypeMatrix:()=>AH,UnitSelector:()=>HH,Whiteboard:()=>WH,battleOrder:()=>MH,checkEvolution:()=>NH,chooseMove:()=>FH,chooseSwitch:()=>IH});function qH(e){let t=e.charCodeAt(0)-97,n=e.charCodeAt(1)-49;if(t<0||t>7||n<0||n>7||e.length!==2)throw Error(`not a square: "${e}"`);return n*8+t}function JH(e){return String.fromCharCode(97+(e&7))+String.fromCharCode(49+(e>>3))}function YH(e){let t=[];for(let n=7;n>=0;n--){let r=``,i=0;for(let t=0;t<8;t++){let a=e.board[n*8+t];if(!a){i++;continue}i>0&&(r+=String(i),i=0);let o={pawn:`p`,knight:`n`,bishop:`b`,rook:`r`,queen:`q`,king:`k`}[a.kind];r+=a.side===`white`?o.toUpperCase():o}i>0&&(r+=String(i)),t.push(r)}let n=(e.castling.whiteKingside?`K`:``)+(e.castling.whiteQueenside?`Q`:``)+(e.castling.blackKingside?`k`:``)+(e.castling.blackQueenside?`q`:``);return`${t.join(`/`)} ${e.turn===`white`?`w`:`b`} ${n||`-`} ${e.enPassant===null?`-`:JH(e.enPassant)}`}function XH(e){let t=e.trim().split(/\s+/);if(t.length<4)throw Error(`not a FEN string: "${e}"`);let n=Array(64).fill(null),r=t[0].split(`/`);if(r.length!==8)throw Error(`a FEN placement needs 8 ranks: "${e}"`);if(r.forEach((t,r)=>{let i=7-r,a=0;for(let r of t)if(r>=`1`&&r<=`8`)a+=r.charCodeAt(0)-48;else{let o=r===r.toUpperCase()?`white`:`black`,s={p:`pawn`,n:`knight`,b:`bishop`,r:`rook`,q:`queen`,k:`king`}[r.toLowerCase()];if(!s||a>7)throw Error(`bad FEN rank "${t}" in "${e}"`);n[i*8+a]={side:o,kind:s},a++}if(a!==8)throw Error(`bad FEN rank "${t}" in "${e}"`)}),t[1]!==`w`&&t[1]!==`b`)throw Error(`a FEN side is "w" or "b": "${e}"`);let i={whiteKingside:!1,whiteQueenside:!1,blackKingside:!1,blackQueenside:!1};if(t[2]!==`-`)for(let n of t[2])if(n===`K`)i.whiteKingside=!0;else if(n===`Q`)i.whiteQueenside=!0;else if(n===`k`)i.blackKingside=!0;else if(n===`q`)i.blackQueenside=!0;else throw Error(`bad FEN castling "${t[2]}" in "${e}"`);let a=t[3]===`-`?null:qH(t[3]);if(a!==null){let n=t[1]===`w`?5:2;if($H(a)!==n)throw Error(`bad FEN en passant square "${t[3]}" in "${e}"`)}let o={board:n,turn:t[1]===`w`?`white`:`black`,castling:i,enPassant:a};return cU(n,`white`),cU(n,`black`),o}function ZH(e){return e===`white`?`black`:`white`}function QH(e){return e&7}function $H(e){return e>>3}function eU(e,t){return e>=0&&e<8&&t>=0&&t<8}function tU(){let e=[`rook`,`knight`,`bishop`,`queen`,`king`,`bishop`,`knight`,`rook`],t=Array(64).fill(null);for(let n=0;n<8;n++)t[n]={side:`white`,kind:e[n]},t[8+n]={side:`white`,kind:`pawn`},t[48+n]={side:`black`,kind:`pawn`},t[56+n]={side:`black`,kind:e[n]};return{board:t,turn:`white`,castling:{whiteKingside:!0,whiteQueenside:!0,blackKingside:!0,blackQueenside:!0},enPassant:null}}function nU(e){return{board:e.board.map(e=>e?{side:e.side,kind:e.kind}:null),turn:e.turn,castling:{...e.castling},enPassant:e.enPassant}}var rU=[[1,2],[2,1],[2,-1],[1,-2],[-1,-2],[-2,-1],[-2,1],[-1,2]],iU=[[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1],[0,-1],[1,-1]],aU=[[1,1],[-1,1],[-1,-1],[1,-1]],oU=[[1,0],[0,1],[-1,0],[0,-1]];function sU(e,t,n){let r=QH(t),i=$H(t),a=n===`white`?i-1:i+1;for(let t of[-1,1]){if(!eU(r+t,a))continue;let i=e[a*8+r+t];if(i&&i.side===n&&i.kind===`pawn`)return!0}for(let[t,a]of rU){if(!eU(r+t,i+a))continue;let o=e[(i+a)*8+r+t];if(o&&o.side===n&&o.kind===`knight`)return!0}for(let[t,a]of iU){if(!eU(r+t,i+a))continue;let o=e[(i+a)*8+r+t];if(o&&o.side===n&&o.kind===`king`)return!0}let o=[{steps:aU,kinds:[`bishop`,`queen`]},{steps:oU,kinds:[`rook`,`queen`]}];for(let{steps:t,kinds:a}of o)for(let[o,s]of t){let t=r+o,c=i+s;for(;eU(t,c);){let r=e[c*8+t];if(r){if(r.side===n&&a.includes(r.kind))return!0;break}t+=o,c+=s}}return!1}function cU(e,t){let n=e.findIndex(e=>e!==null&&e.side===t&&e.kind===`king`);if(n===-1)throw Error(`a position without a ${t} king cannot be judged`);return n}function lU(e,t){return sU(e.board,cU(e.board,t),ZH(t))}function uU(e,t){let n=e.board[t];if(!n||n.side!==e.turn)return[];let r=[],i=QH(t),a=$H(t),o=o=>{for(let[s,c]of o){let o=i+s,l=a+c;for(;eU(o,l);){let i=l*8+o,a=e.board[i];if(!a)r.push({from:t,to:i});else{a.side!==n.side&&r.push({from:t,to:i});break}o+=s,l+=c}}};switch(n.kind){case`pawn`:{let o=n.side===`white`?1:-1,s=n.side===`white`?1:6,c=n.side===`white`?7:0;if(eU(i,a+o)&&!e.board[(a+o)*8+i]){let n=(a+o)*8+i;if(a+o===c)for(let e of[`knight`,`bishop`,`rook`,`queen`])r.push({from:t,to:n,promotion:e});else r.push({from:t,to:n}),a===s&&!e.board[(a+2*o)*8+i]&&r.push({from:t,to:(a+2*o)*8+i})}for(let s of[-1,1]){if(!eU(i+s,a+o))continue;let l=(a+o)*8+i+s,u=e.board[l];if(u&&u.side!==n.side){if(a+o===c)for(let e of[`knight`,`bishop`,`rook`,`queen`])r.push({from:t,to:l,promotion:e});else r.push({from:t,to:l})}else!u&&l===e.enPassant&&r.push({from:t,to:l,enPassantTake:a*8+i+s})}break}case`knight`:for(let[o,s]of rU){if(!eU(i+o,a+s))continue;let c=(a+s)*8+i+o,l=e.board[c];(!l||l.side!==n.side)&&r.push({from:t,to:c})}break;case`bishop`:o(aU);break;case`rook`:o(oU);break;case`queen`:o(aU),o(oU);break;case`king`:{for(let[o,s]of iU){if(!eU(i+o,a+s))continue;let c=(a+s)*8+i+o,l=e.board[c];l&&l.side===n.side||l&&l.kind===`king`||r.push({from:t,to:c})}let o=n.side===`white`?0:56,s=n.side===`white`?{king:e.castling.whiteKingside,queen:e.castling.whiteQueenside}:{king:e.castling.blackKingside,queen:e.castling.blackQueenside};t===o+4&&!lU(e,n.side)&&(s.king&&!e.board[o+5]&&!e.board[o+6]&&!sU(e.board,o+5,ZH(n.side))&&!sU(e.board,o+6,ZH(n.side))&&r.push({from:t,to:o+6,castle:`kingside`}),s.queen&&!e.board[o+3]&&!e.board[o+2]&&!e.board[o+1]&&!sU(e.board,o+3,ZH(n.side))&&!sU(e.board,o+2,ZH(n.side))&&r.push({from:t,to:o+2,castle:`queenside`}));break}}return r}function dU(e,t){let n=e.board[t.from];if(!n)throw Error(`no piece on ${JH(t.from)} to move`);let r=(e,t)=>{let n=e===`white`?0:56;return t===n||t===n+7};n.kind===`king`&&(n.side===`white`?e.castling.whiteKingside=e.castling.whiteQueenside=!1:e.castling.blackKingside=e.castling.blackQueenside=!1),n.kind===`rook`&&r(n.side,t.from)&&(e.castling[fU(n.side,t.from)]=!1);let i=e.board[t.to];if(i&&i.kind===`rook`&&r(i.side,t.to)&&(e.castling[fU(i.side,t.to)]=!1),e.board[t.to]=t.promotion?{side:n.side,kind:t.promotion}:n,e.board[t.from]=null,t.enPassantTake!==void 0&&(e.board[t.enPassantTake]=null),t.castle){let r=n.side===`white`?0:56;t.castle===`kingside`?(e.board[r+5]=e.board[r+7],e.board[r+7]=null):(e.board[r+3]=e.board[r],e.board[r]=null)}e.enPassant=n.kind===`pawn`&&Math.abs(t.to-t.from)===16?(t.from+t.to)/2:null,e.turn=ZH(n.side)}function fU(e,t){let n=QH(t)===7;return e===`white`?n?`whiteKingside`:`whiteQueenside`:n?`blackKingside`:`blackQueenside`}function pU(e){let t=[];for(let n=0;n<64;n++)if(e.board[n]&&e.board[n]?.side===e.turn)for(let r of uU(e,n)){let n=nU(e);dU(n,r),!lU(n,e.turn)&&t.push({from:r.from,to:r.to,...r.promotion?{promotion:r.promotion}:{}})}return t}function mU(e,t){let n=e.board[t.from];if(!n||n.side!==e.turn)throw Error(`no ${e.turn} piece on ${JH(t.from)} to move`);let r=uU(e,t.from).find(e=>e.to===t.to&&(e.promotion??null)===(t.promotion??null));if(!r)throw Error(`${JH(t.from)}-${JH(t.to)} is not a legal move here`);let i=nU(e);if(dU(i,r),lU(i,e.turn))throw Error(`${JH(t.from)}-${JH(t.to)} leaves the king in check`);dU(e,r)}function hU(e){return pU(e).length>0?`ongoing`:lU(e,e.turn)?e.turn===`white`?`black-wins`:`white-wins`:`stalemate`}var gU=1e5;function _U(e,t,n){if(!Number.isInteger(n.depth)||n.depth<1)throw RangeError(`depth must be a positive integer`);let r=n.maxNodes??gU;if(!Number.isInteger(r)||r<1)throw RangeError(`maxNodes must be a positive integer`);let i=e.currentPlayer(t),a=0,o=0,s,c=(t,l,u,d)=>{if(n.signal?.aborted)return s=`cancelled`,0;if(++a>r)return s=`budget-exceeded`,0;let f=e.currentPlayer(t)===i;if(n.onNode?.(l,f),l===0||e.isTerminal(t))return e.evaluate(t,i);let p=e.moves(t);if(!p.length)return e.evaluate(t,i);let m=f?-1/0:1/0;for(let n of p){let r=c(e.apply(t,n),l-1,u,d);if(s)return r;if(f?(m=Math.max(m,r),u=Math.max(u,m)):(m=Math.min(m,r),d=Math.min(d,m)),d<=u){o++;break}}return m},l=e.moves(t),u=null,d=e.evaluate(t,i);if(!e.isTerminal(t)&&l.length){let r=e.currentPlayer(t)===i,a=r?-1/0:1/0,o=-1/0,f=1/0;for(let i of l){let l=c(e.apply(t,i),n.depth-1,o,f);if(s)break;(u===null||(r?l>a:l<a))&&(u=i,a=l),r?o=Math.max(o,a):f=Math.min(f,a)}u!==null&&(d=a)}return{move:s?null:u,score:d,depth:n.depth,nodes:a,cutoffs:o,status:s??`complete`,state:t}}function vU(e,t){return e.moves(t).map(n=>({move:n,child:e.apply(t,n)}))}function yU(e,t){let n=null,r=t?-1/0:1/0;for(let{move:i,score:a}of e)(n===null||(t?a>r:a<r))&&(n=i,r=a);return n}function bU(){return globalThis.process?.getBuiltinModule?.(`node:worker_threads`)}function xU(){let e=globalThis.process?.getBuiltinModule?.(`node:worker_threads`)?.parentPort??null,t=globalThis,n=e=>{let t=[],n=new Set,r=e=>{if(typeof e!=`object`||!e||n.has(e))return;if(n.add(e),ArrayBuffer.isView(e)){let n=e.buffer;n instanceof ArrayBuffer&&!t.includes(n)&&t.push(n);return}if(e instanceof ArrayBuffer){t.includes(e)||t.push(e);return}if(Array.isArray(e)){for(let t of e)r(t);return}let i=Object.getPrototypeOf(e);if(i===Object.prototype||i===null)for(let t of Object.values(e))r(t)};return r(e),t},r=(n,r=[])=>{e?e.postMessage(n,r):t.postMessage(n,r)},i=async e=>{try{let t=await Function(`return (${e.code});`)()(...e.args);r({ok:!0,value:t},n(t))}catch(e){let t=e;r({ok:!1,message:String(t?.message??e),stack:typeof t?.stack==`string`?t.stack:void 0})}};e?e.on(`message`,e=>void i(e)):t.onmessage=e=>void i(e.data)}var SU=e=>{if(typeof Worker>`u`||typeof Blob>`u`||typeof URL>`u`||typeof URL.createObjectURL!=`function`)return null;let t=URL.createObjectURL(new Blob([`(${xU.toString()})()`],{type:`text/javascript`})),n;try{n=new Worker(t)}catch(e){throw URL.revokeObjectURL(t),e}return n.onmessage=t=>e.reply(t.data),n.onerror=t=>e.fail(Error(t.message||`the worker failed to run`)),n.onmessageerror=()=>e.fail(Error(`the worker sent a reply that could not be deserialized`)),{post:(e,t)=>n.postMessage(e,t),terminate:()=>{n.terminate(),URL.revokeObjectURL(t)}}},CU=e=>{let t=bU();if(!t)return null;let n=new t.Worker(`(${xU.toString()})()`,{eval:!0});return n.on(`message`,t=>e.reply(t)),n.on(`error`,t=>e.fail(t instanceof Error?t:Error(String(t)))),n.on(`messageerror`,()=>e.fail(Error(`the worker sent a reply that could not be deserialized`))),n.on(`exit`,t=>e.fail(Error(`the worker exited with code ${t} before answering`))),{post:(e,t)=>n.postMessage(e,t),terminate:()=>void n.terminate()}};function wU(e){let t=Error(e.message);return e.stack&&(t.stack=e.stack),t}function TU(e,t,n={}){return new Promise((r,i)=>{if(n.signal?.aborted){i(n.signal.reason);return}let a=!1,o,s,c=e=>{a||(a=!0,o!==void 0&&clearTimeout(o),n.signal?.removeEventListener(`abort`,l),s?.terminate(),e())};function l(){c(()=>i(n.signal.reason))}let u={reply:e=>c(()=>{e.ok?r(e.value):i(wU(e))}),fail:e=>c(()=>i(e))};try{s=SU(u)??CU(u)}catch(e){i(e);return}if(!s){i(Error(`spawn() needs Web Workers or node:worker_threads, and this environment offers neither`));return}n.timeout!==void 0&&n.timeout>0&&(o=setTimeout(()=>c(()=>i(Error(`the task did not answer within ${n.timeout} ms`))),n.timeout)),n.signal?.addEventListener(`abort`,l,{once:!0});try{s.post({code:e.toString(),args:t??[]},n.transfer??[])}catch(e){c(()=>i(e))}})}var EU=1e5,DU={pawn:100,knight:320,bishop:330,rook:500,queen:900,king:0};function OU(e,t={}){return kU(e,t).move}function kU(e,t={}){let n=_U(NU,e,{depth:Math.max(1,Math.floor(t.depth??3)),maxNodes:t.maxNodes===void 0?1e5:Math.max(1,Math.floor(t.maxNodes))});return{move:n.move,score:n.score,nodes:n.nodes}}async function AU(e,t={}){let n=Math.max(1,Math.floor(t.depth??3)),r=t.maxNodes===void 0?1e5:Math.max(1,Math.floor(t.maxNodes)),i=t.jobs??jU();if(!Number.isInteger(i)||i<1)throw RangeError(`jobs must be a positive integer`);if(t.signal?.aborted)throw t.signal.reason;let a=NU.currentPlayer(e),o=vU(NU,e);if(NU.isTerminal(e)||!o.length)return{move:null,score:NU.evaluate(e,a),nodes:0};let s=Math.max(1,Math.min(i,o.length)),c=Array(o.length),l=0,u=!1,d=0,f=t.signal?{signal:t.signal}:{};if(await Promise.all(Array.from({length:s},async()=>{for(;;){let e=d++;if(e>=o.length)return;let t=await TU(MU,[o[e].child,a,n-1,r],f);l+=t.nodes,t.budgetExceeded?u=!0:c[e]={move:o[e].move,score:t.score}}})),u)return{move:null,score:NU.evaluate(e,a),nodes:l};let p=c.filter(e=>e!==void 0),m=yU(p,!0);return{move:m,score:p.find(e=>e.move===m)?.score??NU.evaluate(e,a),nodes:l}}function jU(){let e=globalThis,t=e.navigator?.hardwareConcurrency;if(typeof t==`number`&&Number.isInteger(t)&&t>0)return Math.min(t,8);try{let t=e.process?.getBuiltinModule?.(`node:os`)?.availableParallelism?.();if(typeof t==`number`&&Number.isInteger(t)&&t>0)return Math.min(t,8)}catch{}return 4}function MU(e,t,n,r){let i={pawn:100,knight:320,bishop:330,rook:500,queen:900,king:0},a=e=>e===`white`?`black`:`white`,o=e=>e&7,s=e=>e>>3,c=(e,t)=>e>=0&&e<8&&t>=0&&t<8,l=[[1,2],[2,1],[2,-1],[1,-2],[-1,-2],[-2,-1],[-2,1],[-1,2]],u=[[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1],[0,-1],[1,-1]],d=[[1,1],[-1,1],[-1,-1],[1,-1]],f=[[1,0],[0,1],[-1,0],[0,-1]],p=(e,t,n)=>{let r=o(t),i=s(t),a=n===`white`?i-1:i+1;for(let t of[-1,1]){if(!c(r+t,a))continue;let i=e[a*8+r+t];if(i&&i.side===n&&i.kind===`pawn`)return!0}for(let[t,a]of l){if(!c(r+t,i+a))continue;let o=e[(i+a)*8+r+t];if(o&&o.side===n&&o.kind===`knight`)return!0}for(let[t,a]of u){if(!c(r+t,i+a))continue;let o=e[(i+a)*8+r+t];if(o&&o.side===n&&o.kind===`king`)return!0}let p=[{steps:d,kinds:[`bishop`,`queen`]},{steps:f,kinds:[`rook`,`queen`]}];for(let{steps:t,kinds:a}of p)for(let[o,s]of t){let t=r+o,l=i+s;for(;c(t,l);){let r=e[l*8+t];if(r){if(r.side===n&&a.includes(r.kind))return!0;break}t+=o,l+=s}}return!1},m=(e,t)=>{let n=e.findIndex(e=>e!==null&&e.side===t&&e.kind===`king`);if(n===-1)throw Error(`a position without a ${t} king cannot be judged`);return n},h=(e,t)=>p(e.board,m(e.board,t),a(t)),g=(e,t)=>{let n=e.board[t];if(!n||n.side!==e.turn)return[];let r=[],i=o(t),m=s(t),g=a=>{for(let[o,s]of a){let a=i+o,l=m+s;for(;c(a,l);){let i=l*8+a,c=e.board[i];if(!c)r.push({from:t,to:i});else{c.side!==n.side&&r.push({from:t,to:i});break}a+=o,l+=s}}};switch(n.kind){case`pawn`:{let a=n.side===`white`?1:-1,o=n.side===`white`?1:6,s=n.side===`white`?7:0;if(c(i,m+a)&&!e.board[(m+a)*8+i]){let n=(m+a)*8+i;if(m+a===s)for(let e of[`knight`,`bishop`,`rook`,`queen`])r.push({from:t,to:n,promotion:e});else r.push({from:t,to:n}),m===o&&!e.board[(m+2*a)*8+i]&&r.push({from:t,to:(m+2*a)*8+i})}for(let o of[-1,1]){if(!c(i+o,m+a))continue;let l=(m+a)*8+i+o,u=e.board[l];if(u&&u.side!==n.side){if(m+a===s)for(let e of[`knight`,`bishop`,`rook`,`queen`])r.push({from:t,to:l,promotion:e});else r.push({from:t,to:l})}else!u&&l===e.enPassant&&r.push({from:t,to:l,enPassantTake:m*8+i+o})}break}case`knight`:for(let[a,o]of l){if(!c(i+a,m+o))continue;let s=(m+o)*8+i+a,l=e.board[s];(!l||l.side!==n.side)&&r.push({from:t,to:s})}break;case`bishop`:g(d);break;case`rook`:g(f);break;case`queen`:g(d),g(f);break;case`king`:{for(let[a,o]of u){if(!c(i+a,m+o))continue;let s=(m+o)*8+i+a,l=e.board[s];l&&l.side===n.side||l&&l.kind===`king`||r.push({from:t,to:s})}let o=n.side===`white`?0:56,s=n.side===`white`?{king:e.castling.whiteKingside,queen:e.castling.whiteQueenside}:{king:e.castling.blackKingside,queen:e.castling.blackQueenside};t===o+4&&!h(e,n.side)&&(s.king&&!e.board[o+5]&&!e.board[o+6]&&!p(e.board,o+5,a(n.side))&&!p(e.board,o+6,a(n.side))&&r.push({from:t,to:o+6,castle:`kingside`}),s.queen&&!e.board[o+3]&&!e.board[o+2]&&!e.board[o+1]&&!p(e.board,o+3,a(n.side))&&!p(e.board,o+2,a(n.side))&&r.push({from:t,to:o+2,castle:`queenside`}));break}}return r},_=(e,t)=>{let n=e.board[t.from];if(!n)throw Error(`no piece on ${t.from} to move`);let r=(e,t)=>{let n=e===`white`?0:56;return t===n||t===n+7},i=(e,t)=>{let n=o(t)===7;return e===`white`?n?`whiteKingside`:`whiteQueenside`:n?`blackKingside`:`blackQueenside`};n.kind===`king`&&(n.side===`white`?e.castling.whiteKingside=e.castling.whiteQueenside=!1:e.castling.blackKingside=e.castling.blackQueenside=!1),n.kind===`rook`&&r(n.side,t.from)&&(e.castling[i(n.side,t.from)]=!1);let s=e.board[t.to];if(s&&s.kind===`rook`&&r(s.side,t.to)&&(e.castling[i(s.side,t.to)]=!1),e.board[t.to]=t.promotion?{side:n.side,kind:t.promotion}:n,e.board[t.from]=null,t.enPassantTake!==void 0&&(e.board[t.enPassantTake]=null),t.castle){let r=n.side===`white`?0:56;t.castle===`kingside`?(e.board[r+5]=e.board[r+7],e.board[r+7]=null):(e.board[r+3]=e.board[r],e.board[r]=null)}e.enPassant=n.kind===`pawn`&&Math.abs(t.to-t.from)===16?(t.from+t.to)/2:null,e.turn=a(n.side)},v=e=>({board:e.board.map(e=>e?{side:e.side,kind:e.kind}:null),turn:e.turn,castling:{...e.castling},enPassant:e.enPassant}),y=e=>{let t=[];for(let n=0;n<64;n++)if(e.board[n]&&e.board[n]?.side===e.turn)for(let r of g(e,n)){let n=v(e);_(n,r),!h(n,e.turn)&&t.push({from:r.from,to:r.to,...r.promotion?{promotion:r.promotion}:{}})}return t},b=e=>y(e).length>0?`ongoing`:h(e,e.turn)?e.turn===`white`?`black-wins`:`white-wins`:`stalemate`,x=(e,t)=>{let n=e.board[t.to];return(t.promotion?i[t.promotion]:0)*10+(n?i[n.kind]:0)},S=(e,t)=>t.slice().sort((t,n)=>x(e,n)-x(e,t)),C=(e,t)=>{let n=0;for(let t of e.board)t&&(n+=(t.side===`white`?1:-1)*i[t.kind]);return t===1?n:-n},ee=(e,t)=>{let n=b(e);return n===`stalemate`||!h(e,e.turn)?0:(n===`white-wins`?1:-1)===t?1e5:-1e5},w=e=>b(e)===`ongoing`?C(e,t):ee(e,t),T=0,E=!1,D=(e,n,i,a)=>{if(++T>r)return E=!0,0;let o=(e.turn===`white`?1:-1)===t;if(n===0||b(e)!==`ongoing`)return w(e);let s=S(e,y(e));if(!s.length)return w(e);let c=o?-1/0:1/0;for(let t of s){let r=v(e),s=g(r,t.from).find(e=>e.to===t.to&&(e.promotion??null)===(t.promotion??null));if(!s)throw Error(`a legal move stopped being legal: ${t.from}-${t.to}`);_(r,s);let l=D(r,n-1,i,a);if(E)return l;if(o?(c=Math.max(c,l),i=Math.max(i,c)):(c=Math.min(c,l),a=Math.min(a,c)),a<=i)break}return c};return{score:D(e,n,-1/0,1/0),nodes:T,budgetExceeded:E}}var NU={currentPlayer:e=>e.turn===`white`?1:-1,moves:e=>IU(e,pU(e)),apply:(e,t)=>{let n=nU(e);return mU(n,t),n},isTerminal:e=>hU(e)!==`ongoing`,evaluate:(e,t)=>hU(e)===`ongoing`?PU(e,t):FU(e,t)};function PU(e,t){let n=0;for(let t of e.board)t&&(n+=(t.side===`white`?1:-1)*DU[t.kind]);return t===1?n:-n}function FU(e,t){let n=hU(e);return n===`stalemate`||!lU(e,e.turn)?0:(n===`white-wins`?1:-1)===t?EU:-1e5}function IU(e,t){return t.slice().sort((t,n)=>LU(e,n)-LU(e,t))}function LU(e,t){let n=e.board[t.to];return(t.promotion?DU[t.promotion]:0)*10+(n?DU[n.kind]:0)}function RU(e,t){return e.positions[YH(t)]??null}var zU={q:`queen`,r:`rook`,b:`bishop`,n:`knight`};function BU(e){let t=/^([a-h][1-8])([a-h][1-8])([qrbn])?$/.exec(e);if(!t)throw Error(`not a UCI move: "${e}"`);let n=t[3]?zU[t[3]]:void 0;return n?{from:qH(t[1]),to:qH(t[2]),promotion:n}:{from:qH(t[1]),to:qH(t[2])}}var VU={pawn:0,knight:1,bishop:2,rook:3,queen:4,king:5},HU=[`queen`,`rook`,`bishop`,`knight`],UU=[[1,2],[2,1],[2,-1],[1,-2],[-1,-2],[-2,-1],[-2,1],[-1,2]],WU=[[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1],[0,-1],[1,-1]],GU=[[1,1],[-1,1],[-1,-1],[1,-1]],KU=[[1,0],[0,1],[-1,0],[0,-1]];function qU(e){return 1n<<BigInt(e)}function JU(e){return Math.log2(Number(e))}function YU(e){return Array.from({length:64},(t,n)=>{let r=n&7,i=n>>3,a=0n;for(let[t,n]of e){let e=r+t,o=i+n;e>=0&&e<8&&o>=0&&o<8&&(a|=qU(o*8+e))}return a})}var XU=YU(UU),ZU=YU(WU);function QU(e,t){return e.pieces[t]|e.pieces[t+1]|e.pieces[t+2]|e.pieces[t+3]|e.pieces[t+4]|e.pieces[t+5]}function $U(e,t){let n=qU(t);for(let t=0;t<12;t++)if(e.pieces[t]&n)return t;return-1}function eW(e,t,n){let r=n?0:6,i=t&7,a=t>>3,o=n?a-1:a+1;for(let t of[-1,1]){let n=i+t;if(o>=0&&o<8&&n>=0&&n<8&&e.pieces[r]&qU(o*8+n))return!0}if(XU[t]&e.pieces[r+1]||ZU[t]&e.pieces[r+5])return!0;let s=[{steps:GU,kinds:[2,4]},{steps:KU,kinds:[3,4]}];for(let{steps:t,kinds:n}of s)for(let[o,s]of t){let t=i+o,c=a+s;for(;t>=0&&t<8&&c>=0&&c<8;){let i=$U(e,c*8+t);if(i!==-1){if(i>=r&&i<r+6&&n.includes(i-r))return!0;break}t+=o,c+=s}}return!1}function tW(e,t){return e===`white`?t?1:2:t?4:8}function nW(e){let t=Array(12).fill(0n),n=[-1,-1];if(e.board.forEach((e,r)=>{if(!e)return;let i=(e.side===`white`?0:6)+VU[e.kind];t[i]|=qU(r),e.kind===`king`&&(n[e.side===`white`?0:1]=r)}),n[0]===-1||n[1]===-1)throw Error(`a position without both kings cannot go on bitboards`);return{pieces:t,turn:e.turn,castling:+!!e.castling.whiteKingside|(e.castling.whiteQueenside?2:0)|(e.castling.blackKingside?4:0)|(e.castling.blackQueenside?8:0),enPassant:e.enPassant,halfmove:0,kings:n}}function rW(){return nW(tU())}function iW(e){let t=e.turn===`white`,n=t?0:6,r=QU(e,n),i=QU(e,n===0?6:0),a=r|i,o=[],s=[];for(let c=0;c<64;c++){if(!(r&qU(c)))continue;let l=-1;for(let t=0;t<6;t++)if(e.pieces[n+t]&qU(c)){l=t;break}s.length=0,aW(e,c,l,a,i,s);for(let n of s){let r=oW(e,n);eW(e,e.kings[+!t],!t)||o.push({...n}),sW(e,n,r)}}return o}function aW(e,t,n,r,i,a){let o=e.turn===`white`,s=t&7,c=t>>3,l=(e,n)=>{a.push(n?{from:t,to:e,promotion:n}:{from:t,to:e})},u=e=>{for(let[t,n]of e){let e=s+t,a=c+n;for(;e>=0&&e<8&&a>=0&&a<8;){let o=a*8+e,s=qU(o);if(!(r&s))l(o);else{i&s&&l(o);break}e+=t,a+=n}}};switch(n){case 0:{let n=o?8:-8,a=o?1:6,u=o?7:0,d=t+n;if(d>=0&&d<64&&!(r&qU(d))){if(d>>3===u)for(let e of HU)l(d,e);else{l(d);let e=t+2*n;c===a&&!(r&qU(e))&&l(e)}}for(let r of[-1,1]){let a=s+r;if(a<0||a>7)continue;let o=t+n+r;if(!(o<0||o>=64)){if(i&qU(o)){if(o>>3===u)for(let e of HU)l(o,e);else l(o)}else o===e.enPassant&&l(o)}}break}case 1:{let n=XU[t]&~QU(e,o?0:6);for(;n;){let e=n&-n;l(JU(e)),n^=e}break}case 2:u(GU);break;case 3:u(KU);break;case 4:u(GU),u(KU);break;case 5:{let n=ZU[t]&~QU(e,o?0:6);for(n&=~e.pieces[o?11:5];n;){let e=n&-n;l(JU(e)),n^=e}let i=o?0:56,a=e.castling,s=o?a&1:a&4,c=o?a&2:a&8;t===i+4&&!eW(e,t,!o)&&(s&&!(r&qU(i+5))&&!(r&qU(i+6))&&!eW(e,i+5,!o)&&!eW(e,i+6,!o)&&l(i+6),c&&!(r&qU(i+3))&&!(r&qU(i+2))&&!(r&qU(i+1))&&!eW(e,i+3,!o)&&!eW(e,i+2,!o)&&l(i+2));break}}}function oW(e,t){let n=e.turn===`white`,r=+!n,i=r*6,a=qU(t.from),o=qU(t.to),s=-1;for(let t=0;t<6;t++)if(e.pieces[i+t]&a){s=t;break}if(s===-1)throw Error(`no piece on ${t.from} to move`);let c={captured:null,castling:e.castling,enPassant:e.enPassant,halfmove:e.halfmove,kingSquare:e.kings[r]},l=(1-r)*6,u=n?8:-8,d=t.to;s===0&&t.to===e.enPassant&&(d=t.to-u);let f=qU(d);for(let t=0;t<6;t++)if(e.pieces[l+t]&f){c.captured={color:1-r,kind:t},e.pieces[l+t]^=f;break}let p=n?0:56,m=n?56:0;if(s===5&&(e.castling&=~(tW(e.turn,!0)|tW(e.turn,!1))),s===3&&(t.from===p||t.from===p+7)&&(e.castling&=~tW(e.turn,t.from===p+7)),c.captured?.kind===3&&(d===m||d===m+7)&&(e.castling&=~tW(n?`black`:`white`,d===m+7)),e.pieces[i+s]^=a,t.promotion?e.pieces[i+VU[t.promotion]]|=o:e.pieces[i+s]|=o,s===5&&Math.abs(t.to-t.from)===2){let n=i+3;t.to>t.from?e.pieces[n]^=qU(p+7)|qU(p+5):e.pieces[n]^=qU(p)|qU(p+3)}return e.enPassant=s===0&&Math.abs(t.to-t.from)===16?(t.from+t.to)/2:null,e.halfmove=s===0||c.captured?0:e.halfmove+1,s===5&&(e.kings[r]=t.to),e.turn=n?`black`:`white`,c}function sW(e,t,n){e.turn=e.turn===`white`?`black`:`white`;let r=e.turn===`white`,i=+!r,a=i*6,o=qU(t.to),s=t.promotion?0:(()=>{for(let t=0;t<6;t++)if(e.pieces[a+t]&o)return t;throw Error(`nothing on ${t.to} to take back`)})();if(t.promotion?e.pieces[a+VU[t.promotion]]^=o:e.pieces[a+s]^=o,e.pieces[a+s]|=qU(t.from),s===5&&Math.abs(t.to-t.from)===2){let n=r?0:56,i=a+3;t.to>t.from?e.pieces[i]^=qU(n+7)|qU(n+5):e.pieces[i]^=qU(n)|qU(n+3)}if(n.captured){let a=r?8:-8,o=s===0&&t.to===n.enPassant?t.to-a:t.to;e.pieces[(1-i)*6+n.captured.kind]|=qU(o)}e.castling=n.castling,e.enPassant=n.enPassant,e.halfmove=n.halfmove,e.kings[i]=n.kingSquare}function cW(e,t){if(!Number.isInteger(t)||t<0)throw RangeError(`perft depth must be a non-negative integer`);if(t===0)return 1;let n=0;for(let r of iW(e)){let i=oW(e,r);n+=cW(e,t-1),sW(e,r,i)}return n}function lW(e,t={}){let n=1e6,r=[100,320,330,500,900,0],i=Math.max(1,Math.floor(t.depth??3)),a=t.maxNodes===void 0?5e5:Math.max(1,Math.floor(t.maxNodes)),o=t.timeMs===void 0?-1:Date.now()+Math.max(1,t.timeMs),s={pieces:e.pieces.slice(),turn:e.turn,castling:e.castling,enPassant:e.enPassant,halfmove:e.halfmove,kings:[e.kings[0],e.kings[1]]};function c(e){return 1n<<BigInt(e)}function l(e){return Math.log2(Number(e))}let u=[[1,2],[2,1],[2,-1],[1,-2],[-1,-2],[-2,-1],[-2,1],[-1,2]],d=[[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1],[0,-1],[1,-1]],f=[[1,1],[-1,1],[-1,-1],[1,-1]],p=[[1,0],[0,1],[-1,0],[0,-1]];function m(e){return Array.from({length:64},(t,n)=>{let r=n&7,i=n>>3,a=0n;for(let[t,n]of e){let e=r+t,o=i+n;e>=0&&e<8&&o>=0&&o<8&&(a|=c(o*8+e))}return a})}let h=m(u),g=m(d);function _(e){return s.pieces[e]|s.pieces[e+1]|s.pieces[e+2]|s.pieces[e+3]|s.pieces[e+4]|s.pieces[e+5]}function v(e){let t=c(e);for(let e=0;e<12;e++)if(s.pieces[e]&t)return e%6;return-1}function y(e,t){let n=t?0:6,r=e&7,i=e>>3,a=t?i-1:i+1;for(let e of[-1,1]){let t=r+e;if(a>=0&&a<8&&t>=0&&t<8&&s.pieces[n]&c(a*8+t))return!0}if(h[e]&s.pieces[n+1]||g[e]&s.pieces[n+5])return!0;let o=[{steps:f,kinds:[2,4]},{steps:p,kinds:[3,4]}];for(let{steps:e,kinds:n}of o)for(let[a,o]of e){let e=r+a,l=i+o;for(;e>=0&&e<8&&l>=0&&l<8;){let r=v(l*8+e);if(r!==-1){if((()=>{let t=c(l*8+e);for(let e=0;e<12;e++)if(s.pieces[e]&t)return e<6?0:1;return-1})()===+!t&&n.includes(r))return!0;break}e+=a,l+=o}}return!1}let b=0n,x=11400714819323198485n;function S(){x=x+11400714819323198485n&18446744073709551615n;let e=x;return e=(e^e>>30n)*13787848793156543929n&18446744073709551615n,e=(e^e>>27n)*10723151780598845931n&18446744073709551615n,e^e>>31n}let C=Array.from({length:12},()=>Array.from({length:64},()=>S())),ee=S(),w=Array.from({length:16},()=>S()),T=Array.from({length:8},()=>S());function E(){let e=0n;for(let t=0;t<12;t++){let n=s.pieces[t];for(;n;){let r=n&-n;e^=C[t][l(r)],n^=r}}return s.turn===`black`&&(e^=ee),e^=w[s.castling],s.enPassant!==null&&(e^=T[s.enPassant&7]),e}b=E();function D(e,t){return e===`white`?t?1:2:t?4:8}function O(e){let t=s.turn===`white`,n=+!t,r=n*6,i=c(e.from),a=c(e.to),o=-1;for(let e=0;e<6;e++)if(s.pieces[r+e]&i){o=e;break}let l={captured:null,castling:s.castling,enPassant:s.enPassant,halfmove:s.halfmove,kingSquare:s.kings[n],key:b,nullMove:!1},u=(1-n)*6,d=t?8:-8,f=e.to;o===0&&e.to===s.enPassant&&(f=e.to-d);let p=c(f);for(let e=0;e<6;e++)if(s.pieces[u+e]&p){l.captured={color:1-n,kind:e},s.pieces[u+e]^=p;break}let m=t?0:56,h=t?56:0;o===5&&(s.castling&=~(D(s.turn,!0)|D(s.turn,!1))),o===3&&(e.from===m||e.from===m+7)&&(s.castling&=~D(s.turn,e.from===m+7)),l.captured&&l.captured.kind===3&&(f===h||f===h+7)&&(s.castling&=~D(t?`black`:`white`,f===h+7));let g={queen:4,rook:3,bishop:2,knight:1};if(s.pieces[r+o]^=i,e.promotion?s.pieces[r+g[e.promotion]]|=a:s.pieces[r+o]|=a,o===5&&Math.abs(e.to-e.from)===2){let t=r+3;e.to>e.from?s.pieces[t]^=c(m+7)|c(m+5):s.pieces[t]^=c(m)|c(m+3)}return s.enPassant=o===0&&Math.abs(e.to-e.from)===16?(e.from+e.to)/2:null,s.halfmove=o===0||l.captured?0:s.halfmove+1,o===5&&(s.kings[n]=e.to),s.turn=t?`black`:`white`,b=E(),l}function te(e,t){s.turn=s.turn===`white`?`black`:`white`;let n=s.turn===`white`,r=+!n,i=r*6,a=c(e.to),o=e.promotion?0:(()=>{for(let e=0;e<6;e++)if(s.pieces[i+e]&a)return e;return-1})(),l={queen:4,rook:3,bishop:2,knight:1};if(e.promotion?s.pieces[i+l[e.promotion]]^=a:s.pieces[i+o]^=a,s.pieces[i+o]|=c(e.from),o===5&&Math.abs(e.to-e.from)===2){let t=n?0:56,r=i+3;e.to>e.from?s.pieces[r]^=c(t+7)|c(t+5):s.pieces[r]^=c(t)|c(t+3)}if(t.captured){let i=n?8:-8,a=o===0&&e.to===t.enPassant?e.to-i:e.to;s.pieces[(1-r)*6+t.captured.kind]|=c(a)}s.castling=t.castling,s.enPassant=t.enPassant,s.halfmove=t.halfmove,s.kings[r]=t.kingSquare,b=t.key}function ne(){let e={captured:null,castling:s.castling,enPassant:s.enPassant,halfmove:s.halfmove,kingSquare:-1,key:b,nullMove:!0};return s.enPassant=null,s.halfmove+=1,s.turn=s.turn===`white`?`black`:`white`,b=E(),e}function k(e){s.turn=s.turn===`white`?`black`:`white`,s.enPassant=e.enPassant,s.halfmove=e.halfmove,b=e.key}function A(e,t,n,r,i){let a=s.turn===`white`,o=e&7,u=e>>3,d=(t,n)=>{i.push(n?{from:e,to:t,promotion:n}:{from:e,to:t})},m=e=>{for(let[t,i]of e){let e=o+t,a=u+i;for(;e>=0&&e<8&&a>=0&&a<8;){let o=a*8+e,s=c(o);if(!(n&s))d(o);else{r&s&&d(o);break}e+=t,a+=i}}},v=[`queen`,`rook`,`bishop`,`knight`];if(t===0){let t=a?8:-8,i=a?1:6,l=a?7:0,f=e+t;if(f>=0&&f<64&&!(n&c(f))){if(f>>3===l)for(let e of v)d(f,e);else{d(f);let r=e+2*t;u===i&&!(n&c(r))&&d(r)}}for(let n of[-1,1]){let i=o+n;if(i<0||i>7)continue;let a=e+t+n;if(!(a<0||a>=64)){if(r&c(a)){if(a>>3===l)for(let e of v)d(a,e);else d(a)}else a===s.enPassant&&d(a)}}}else if(t===1){let t=h[e]&~_(a?0:6);for(;t;){let e=t&-t;d(l(e)),t^=e}}else if(t===2)m(f);else if(t===3)m(p);else if(t===4)m(f),m(p);else{let t=g[e]&~_(a?0:6);for(t&=~s.pieces[a?11:5];t;){let e=t&-t;d(l(e)),t^=e}let r=a?0:56,i=s.castling,o=a?i&1:i&4,u=a?i&2:i&8;e===r+4&&!y(e,!a)&&(o&&!(n&c(r+5))&&!(n&c(r+6))&&!y(r+5,!a)&&!y(r+6,!a)&&d(r+6),u&&!(n&c(r+3))&&!(n&c(r+2))&&!(n&c(r+1))&&!y(r+3,!a)&&!y(r+2,!a)&&d(r+2))}}function re(){let e=s.turn===`white`,t=e?0:6,n=_(t),r=_(t===0?6:0),i=n|r,a=[],o=[];for(let l=0;l<64;l++){if(!(n&c(l)))continue;let u=-1;for(let e=0;e<6;e++)if(s.pieces[t+e]&c(l)){u=e;break}o.length=0,A(l,u,i,r,o);for(let t of o){let n=O(t);y(s.kings[+!e],!e)||a.push({...t}),te(t,n)}}return a}function ie(e){let t=e?0:6;return s.pieces[t+1]!==0n||s.pieces[t+2]!==0n||s.pieces[t+3]!==0n||s.pieces[t+4]!==0n}function ae(){let e=0,t=0;for(let n=0;n<12;n++){if(n%6==5)continue;let r=s.pieces[n];for(;r;)r&=r-1n,e++,(n%6==1||n%6==2)&&t++}return e===0||e===1&&t===1}function oe(){let e=0,t=0;for(let n=0;n<12;n++){let r=s.pieces[n];for(;r;)r&=r-1n,n%6==4?e++:n%6!=5&&n%6!=0&&t++}return e===0||e===2&&t<=2}function se(e,t,n,r){let i=t&7,a=n?t>>3:7-(t>>3),o=3.5-Math.abs(i-3.5),s=3.5-Math.abs(a-3.5);return e===0?(a-1)*12+Math.max(0,o)*4:e===1?(o+s)*6-12:e===2?(o+s)*4:e===3?(o+s)*2+(a===6?12:0):e===4?(o+s)*2:r?(o+s)*10:-a*10+o*2}function j(){let e=oe(),t=0;for(let n=0;n<12;n++){let i=n<6,a=n%6,o=s.pieces[n];for(;o;){let n=o&-o,s=l(n),c=r[a]+se(a,s,i,e);t+=i?c:-c,o^=n}}return s.turn===`white`?t:-t}let ce=65536,le=Array(ce).fill(-1n),ue=Array(ce).fill(-1),de=Array(ce).fill(0),fe=Array(ce).fill(0),pe=Array(ce).fill(0);function me(e){let t=e.promotion===`queen`?1:e.promotion===`rook`?2:e.promotion===`bishop`?3:e.promotion===`knight`?4:0;return e.from|e.to<<6|t<<12}function he(e,t,n,r){let i=Number(b&BigInt(65535));if(le[i]!==b)return{score:null,move:0};let a=pe[i];if(ue[i]<e)return{score:null,move:a};let o=de[i];o>99e3?o-=r:o<-99e3&&(o+=r);let s=fe[i];return s===0||s===1&&o>=n||s===2&&o<=t?{score:o,move:a}:{score:null,move:a}}function ge(e,t,n,r,i){let a=Number(b&BigInt(65535));if(le[a]===b&&ue[a]>e)return;let o=t;t>99e3?o+=i:t<-99e3&&(o-=i),le[a]=b,ue[a]=e,de[a]=o,fe[a]=n,pe[a]=r}let _e=Array.from({length:64},()=>[0,0]),ve=Array.from({length:2},()=>Array.from({length:64},()=>Array(64).fill(0)));function M(e){let t=s.turn===`white`?6:0,n=c(e);for(let e=4;e>=0;e--)if(s.pieces[t+e]&n)return e;return-1}function N(e,t,n){let i=s.turn===`white`?0:1,a=e.map(e=>{let a=me(e);if(a===t)return 3e6;let o=M(e.to),c=v(e.from),l=e.to===s.enPassant&&c===0;if(o!==-1||l){let t=2e6+(l?r[0]:r[o])*8-c;return e.promotion&&(t+=900),t}return e.promotion?15e5:n<64?_e[n][0]===a?1e6:_e[n][1]===a?9e5:ve[i][e.from][e.to]:0}),o=e.map((e,t)=>t);for(let e=0;e<o.length;e++){let t=e;for(let n=e+1;n<o.length;n++)a[o[n]]>a[o[t]]&&(t=n);[o[e],o[t]]=[o[t],o[e]]}return o}let ye=0,be=!1,P=[];function xe(){return be?!0:ye>a||t.signal?.aborted||o!==-1&&!(ye&2047)&&Date.now()>=o?(be=!0,!0):!1}function Se(e,t,n){if(ye++,xe())return 0;let i=s.turn===`white`;if(s.halfmove>=100||ae())return 0;if(y(s.kings[+!i],!i))return F(1,e,t,n,!1);let a=j();if(a>=t)return t;a>e&&(e=a);let o=re().filter(e=>{if(e.promotion||e.to===s.enPassant&&v(e.from)===0)return!0;let t=i?6:0,n=c(e.to);for(let e=0;e<5;e++)if(s.pieces[t+e]&n)return!0;return!1}),l=N(o,0,Math.min(n,63));for(let i of l){let s=o[i],c=M(s.to);if(a+(c===-1?900:r[c])+200<e)continue;let l=O(s);P.push(b);let u=-Se(-t,-e,n+1);if(P.pop(),te(s,l),be)return 0;if(u>=t)return t;u>e&&(e=u)}return e}function F(e,t,n,r,i){if(ye++,xe())return 0;let a=s.turn===`white`;if(s.halfmove>=100||ae())return 0;let o=0;for(let e of P)if(e===b&&++o>=2)return 0;if(r>=64)return j();if(e<=0)return Se(t,n,r);let c=y(s.kings[+!a],!a),l=he(e,t,n,r);if(l.score!==null)return l.score;if(c)i=!1;else if(i&&e>=3&&ie(a)&&n<99e3){let t=e>4?3:2,i=ne();P.push(b);let a=-F(e-1-t,-n,-n+1,r+1,!1);if(P.pop(),k(i),be)return 0;if(a>=n)return n}let u=re();if(u.length===0)return c?-(1e5-r):0;let d=N(u,l.move,Math.min(r,63)),f=+!a,p=-1e6,m=0,h=2;for(let i=0;i<d.length;i++){let a=u[d[i]],o=me(a),l=M(a.to)!==-1||a.to===s.enPassant&&v(a.from)===0,g=O(a);P.push(b);let _;if(i===0)_=-F(e-1,-n,-t,r+1,!0);else{let o=0;e>=3&&i>=4&&!l&&!a.promotion&&!c&&(o=1),o>0?(_=-F(e-1-o,-t-1,-t,r+1,!0),!be&&_>t&&(_=-F(e-1,-n,-t,r+1,!0))):(_=-F(e-1,-t-1,-t,r+1,!0),!be&&_>t&&_<n&&(_=-F(e-1,-n,-t,r+1,!0)))}if(P.pop(),te(a,g),be)return 0;if(_>p&&(p=_,m=o),_>t&&(t=_,h=+(_>=n),!l&&!a.promotion&&r<64&&(ve[f][a.from][a.to]+=e*e,_e[r][0]!==o&&(_e[r][1]=_e[r][0],_e[r][0]=o))),t>=n)break}return ge(e,p,h,m,r),p}let Ce=re();if(Ce.length===0){let e=s.turn===`white`;return{move:null,score:y(s.kings[+!e],!e)?-1e5:0,nodes:ye,depth:0}}P.push(b);let we={from:Ce[0].from,to:Ce[0].to,...Ce[0].promotion?{promotion:Ce[0].promotion}:{}},Te=-1e6,Ee=0,De=Ce.map(e=>({...e}));for(let e=1;e<=i;e++){let t=-1e6,r=n,i=!1,a=we,o=Te;e>=4&&Ee>0&&(i=!0,t=Te-24,r=Te+24);for(let s=0;s<3;s++){let s=t,c=r,l=a,u=-1e6,d=N(De,me({from:a.from,to:a.to,promotion:a.promotion}),0),f=[];for(let n=0;n<d.length;n++){let i=De[d[n]],a=O(i);P.push(b);let o;if(n===0?o=-F(e-1,-r,-t,1,!0):(o=-F(e-1,-t-1,-t,1,!0),!be&&o>t&&o<r&&(o=-F(e-1,-r,-t,1,!0))),P.pop(),te(i,a),be)break;f.push(i),o>u&&(u=o,l=i),o>t&&(t=o)}if(be)break;for(let e of De)f.includes(e)||f.push(e);if(De=f,a=l,o=u,!i)break;if(u<=s||u>=c){t=-1e6,r=n,i=!1;continue}break}if(be||(we=a,Te=o,De=[we,...De.filter(e=>e!==we)],Ee=e,Te>99e3||Te<-99e3)||xe())break}return P.pop(),Ee===0?{move:null,score:j(),nodes:ye,depth:0}:{move:we,score:Te,nodes:ye,depth:Ee}}function uW(e){let t=`pieces`in e?e:nW(e);return{pieces:t.pieces.slice(),turn:t.turn,castling:t.castling,enPassant:t.enPassant,halfmove:t.halfmove,kings:[t.kings[0],t.kings[1]]}}function dW(e,t={}){return lW(uW(e),{depth:t.depth,maxNodes:t.maxNodes,timeMs:t.timeMs,signal:t.signal})}function fW(){let e=globalThis,t=e.navigator?.hardwareConcurrency;if(typeof t==`number`&&Number.isInteger(t)&&t>0)return Math.min(t,8);try{let t=e.process?.getBuiltinModule?.(`node:os`)?.availableParallelism?.();if(typeof t==`number`&&Number.isInteger(t)&&t>0)return Math.min(t,8)}catch{}return 4}async function pW(e,t={}){let n=Math.max(1,Math.floor(t.depth??3)),r=t.maxNodes===void 0?5e5:Math.max(1,Math.floor(t.maxNodes)),i=t.jobs??fW();if(!Number.isInteger(i)||i<1)throw RangeError(`jobs must be a positive integer`);if(t.signal?.aborted)throw t.signal.reason;let a=uW(e),o=iW(a);if(!o.length)return{...lW(a,{depth:n,maxNodes:r}),rootScores:[]};let s=Math.max(1,Math.min(i,o.length)),c=o.map(e=>{let t=uW(a);return oW(t,e),t}),l=Array(o.length),u=0,d=0,f=t.signal?{signal:t.signal}:{};await Promise.all(Array.from({length:s},async()=>{for(;;){let e=d++;if(e>=o.length)return;let i=await TU(lW,[c[e],{depth:Math.max(1,n-1),maxNodes:r,timeMs:t.timeMs}],f);u+=i.nodes,l[e]=-i.score}}));let p=0;for(let e=1;e<o.length;e++)(l[e]??-1/0)>(l[p]??-1/0)&&(p=e);let m=o[p];return{move:{from:m.from,to:m.to,...m.promotion?{promotion:m.promotion}:{}},score:l[p]??0,nodes:u,depth:n,rootScores:o.map((e,t)=>({move:{from:e.from,to:e.to,...e.promotion?{promotion:e.promotion}:{}},score:l[t]??0}))}}var mW={queen:`Q`,rook:`R`,bishop:`B`,knight:`N`},hW={Q:`queen`,R:`rook`,B:`bishop`,N:`knight`},gW={pawn:0,knight:1,bishop:2,rook:3,queen:4,king:5};function _W(e){let t={queen:0,rook:1,bishop:2,knight:3};return`K${e.slice().sort((e,n)=>t[e]-t[n]).map(e=>mW[e]).join(``)}K`}var vW=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`;function yW(e){let t=``;for(let n=0;n<e.length;n+=3){let r=e[n],i=n+1<e.length?e[n+1]:0,a=n+2<e.length?e[n+2]:0;t+=vW[r>>2]+vW[(r&3)<<4|i>>4],t+=n+1<e.length?vW[(i&15)<<2|a>>6]:`=`,t+=n+2<e.length?vW[a&63]:`=`}return t}function bW(e){if(e.length%4!=0)throw Error(`tablebase data is not base64: length is not a multiple of 4`);let t=Array(e.length);for(let n=0;n<e.length;n++){if(e[n]===`=`){t[n]=-1;continue}let r=vW.indexOf(e[n]);if(r===-1)throw Error(`tablebase data is not base64: ${e[n]}`);t[n]=r}let n=[];for(let e=0;e<t.length;e+=4){let[r,i,a,o]=[t[e],t[e+1],t[e+2],t[e+3]];if(r===-1||i===-1)throw Error(`tablebase data is not base64: padding inside a quantum`);n.push(r<<2|i>>4),a!==-1&&n.push((i&15)<<4|a>>2),o!==-1&&n.push((a&3)<<6|o)}return new Uint8Array(n)}function xW(e){let t=Array(256).fill(0);for(let n of e)t[n]++;let n=t.map((e,t)=>({count:e,symbol:t})).filter(e=>e.count>0),r=[1,n.length];if(n.length===0)return yW(new Uint8Array([1,0,0,0,0,0]));if(n.length===1){r.push(n[0].symbol,0);let t=new Uint8Array(r.length+4);return t.set(r,0),t[r.length]=e.length&255,t[r.length+1]=e.length>>8&255,t[r.length+2]=e.length>>16&255,t[r.length+3]=e.length>>24&255,yW(t)}let i=SW(n.map(e=>e.count)),a=n.map((e,t)=>({symbol:e.symbol,length:i[t]})).sort((e,t)=>e.symbol-t.symbol);for(let e of a)r.push(e.symbol);for(let e of a)r.push(e.length);let o=CW(a),s=new Map;for(let e=0;e<a.length;e++)s.set(a[e].symbol,o[e]);let c=0;for(let e of n)c+=e.count*s.get(e.symbol).length;let l=new Uint8Array(r.length+4+Math.ceil(c/8));l.set(r,0),l[r.length]=e.length&255,l[r.length+1]=e.length>>8&255,l[r.length+2]=e.length>>16&255,l[r.length+3]=e.length>>24&255;let u=0,d=r.length+4;for(let t of e){let e=s.get(t);for(let t=e.length-1;t>=0;t--)e.code>>t&1&&(l[d+(u>>3)]|=1<<7-(u&7)),u++}return yW(l)}function SW(e){let t=e.length;if(t===0)return[];let n=e.slice(),r=Array(t).fill(0),i=e.map((e,t)=>t),a=[];for(;i.length>1;){i.sort((e,t)=>n[e]-n[t]);let e=i.shift(),t=i.shift();a.push([e,t]),n[e]+=n[t],n[t]=-1,i.push(e)}for(let e=a.length-1;e>=0;e--){let[t,n]=a[e];r[n]=r[t]+1,r[t]++}if(r.some(e=>e>32))throw Error(`tablebase Huffman code too deep`);return r}function CW(e){let t=e.slice().sort((e,t)=>e.length-t.length||e.symbol-t.symbol),n=0,r=t[0].length,i=new Map;for(let e of t)n<<=e.length-r,i.set(e.symbol,{code:n,length:e.length}),n++,r=e.length;return e.map(e=>i.get(e.symbol))}function wW(e){let t=bW(e);if(t.length<2)throw Error(`tablebase data holds no header`);if(t[0]!==1)throw Error(`tablebase data version ${t[0]} is not 1`);let n=t[1];if(2+2*n>t.length)throw Error(`tablebase data ends inside its header`);let r=[],i=[];for(let e=0;e<n;e++)r.push(t[2+e]);for(let e=0;e<n;e++)i.push(t[2+n+e]);let a=2+2*n;if(n===0){if(a+4!==t.length)throw Error(`tablebase data trails its empty header`);return new Uint8Array}if(n===1){if(a+4!==t.length)throw Error(`tablebase data trails its single-symbol header`);let e=t[a]|t[a+1]<<8|t[a+2]<<16|t[a+3]<<24;return new Uint8Array(e).fill(r[0])}if(a+4>t.length)throw Error(`tablebase data ends before its count`);let o=t[a]|t[a+1]<<8|t[a+2]<<16|t[a+3]<<24,s=r.map((e,t)=>({symbol:e,length:i[t]})),c=CW(s),l={};for(let e=0;e<s.length;e++){let t=l;for(let n=c[e].length-1;n>=0;n--){let r=c[e].code>>n&1;n===0?r?t.one={symbol:s[e].symbol}:t.zero={symbol:s[e].symbol}:(r?t.one=t.one??{}:t.zero=t.zero??{},t=r?t.one:t.zero)}}let u=new Uint8Array(o),d=0,f=0,p=a+4,m=(t.length-p)*8;for(;d<o;){if(f>=m)throw Error(`tablebase data ends before its count`);let e=l;for(;;){let n=t[p+(f>>3)]>>7-(f&7)&1;if(f++,e=n?e.one:e.zero,!e)throw Error(`tablebase data walks off its Huffman tree`);if(e.symbol!==void 0)break}u[d++]=e.symbol}for(;f<m;f++)if(t[p+(f>>3)]>>7-(f&7)&1)throw Error(`tablebase data does not end in zero padding`);return u}function TW(e){let t=wW(e);if(t.length%2!=0)throw Error(`tablebase distances are not byte pairs`);let n=new Uint16Array(t.length/2);for(let e=0;e<n.length;e++)n[e]=t[2*e]|t[2*e+1]<<8;return n}function EW(e){if(e.version!==1)throw Error(`${e.id}: unknown tablebase version ${String(e.version)}`);if(e.id!==_W(e.white))throw Error(`${e.id}: id does not match its extras`);for(let t of e.white)if(!hW[mW[t]])throw Error(`${e.id}: not a tablebase piece: ${String(t)}`);let t=2+e.white.length,n=1;for(let e=0;e<t;e++)n*=64;if(n*=2,e.positions!==n)throw Error(`${e.id}: claims ${e.positions} positions, holds ${n}`);let r=wW(e.wdl);if(r.length!==n)throw Error(`${e.id}: WDL decodes to ${r.length} positions, needs ${n}`);let i=TW(e.dtm);if(i.length!==n)throw Error(`${e.id}: distances decode to ${i.length} positions, need ${n}`);let a={queen:0,rook:1,bishop:2,knight:3};return{id:e.id,extras:e.white.slice().sort((e,t)=>a[e]-a[t]).map(e=>gW[e]),positions:n,wdl:r,dtm:i}}function DW(e){if(`pieces`in e){let t=[];for(let n=0;n<12;n++){let r=e.pieces[n];for(;r;){let e=r&-r;t.push({kind:n%6,side:n<6?`white`:`black`,square:Math.log2(Number(e))}),r^=e}}return t}let t=[];return e.board.forEach((e,n)=>{e&&t.push({kind:gW[e.kind],side:e.side,square:n})}),t}function OW(e){if(`pieces`in e)return e.castling!==0;let t=e.castling;return t.whiteKingside||t.whiteQueenside||t.blackKingside||t.blackQueenside}function kW(e,t,n=0){if(!Number.isInteger(n)||n<0)throw RangeError(`halfmove must be a non-negative integer`);let r=DW(t),i=r.filter(e=>e.kind===5&&e.side===`white`),a=r.filter(e=>e.kind===5&&e.side===`black`);if(i.length!==1||a.length!==1||r.some(e=>e.kind===0)||r.some(e=>e.kind!==5&&e.side===`black`)||OW(t))return null;let o=r.filter(e=>e.kind!==5).sort((e,t)=>t.kind-e.kind).map(e=>e.kind);if(!o.length)return null;let s={4:`Q`,3:`R`,2:`B`,1:`N`},c=e[`K${o.map(e=>s[e]).join(``)}K`];if(!c)return null;let l=r.find(e=>e.kind===5&&e.side===`white`).square,u=r.find(e=>e.kind===5&&e.side===`black`).square,d=o.map((e,t)=>r.filter(t=>t.kind===e&&t.side===`white`).map(e=>e.square).sort((e,t)=>e-t)[AW(o,e,t)]),f=l;for(let e of d)f=f*64+e;f=f*64+u,f=f*2+ +(t.turn===`black`);let p=c.wdl[f];if(p===0)return null;let m=c.dtm[f],h=p===3?`win`:p===1?`loss`:`draw`;return h!==`draw`&&m>100-n&&(h=`draw`),{outcome:h,dtm:m}}function AW(e,t,n){let r=0;for(let i=0;i<n;i++)e[i]===t&&r++;return r}_e();var jW=class{constructor(e,t,n){if(this.width=e,this.height=t,e<1||t<1)throw Error(`a board needs positive dimensions`);if(n&&n.length!==e*t)throw Error(`board cell count does not match dimensions`);this.cells=n?[...n]:Array(e*t).fill(null)}index(e,t){if(!this.inside(e,t))throw Error(`cell (${e},${t}) is outside the board`);return tr(this.width,e,t)}inside(e,t){return er(this.width,this.height,e,t)}get(e,t){return this.cells[this.index(e,t)]}set(e,t,n){this.cells[this.index(e,t)]=n}move(e,t){let n=this.get(e.x,e.y);if(n===null)throw Error(`cannot move an empty cell`);return this.set(e.x,e.y,null),this.set(t.x,t.y,n),n}};function MW(){let e=Array(64).fill(null);for(let t=0;t<3;t++)for(let n=0;n<8;n++)(n+t)%2&&(e[t*8+n]={side:`black`,king:!1});for(let t=5;t<8;t++)for(let n=0;n<8;n++)(n+t)%2&&(e[t*8+n]={side:`red`,king:!1});return{board:e,turn:`red`,forcedFrom:null}}function NW(e){let t=e.forcedFrom===null?e.board.map((t,n)=>t?.side===e.turn?n:-1).filter(e=>e>=0):[e.forcedFrom],n=t.flatMap(t=>FW(e,t,!0));return n.length>0?n:e.forcedFrom===null?t.flatMap(t=>FW(e,t,!1)):[]}function PW(e,t){if(!NW(e).some(e=>e.from===t.from&&e.to===t.to&&e.captures.length===t.captures.length))throw Error(`illegal checkers move`);let n=e.board[t.from];if(!n)throw Error(`no checkers piece on the source cell`);e.board[t.from]=null;for(let n of t.captures)e.board[n]=null;let r=!n.king&&(n.side===`red`&&Math.floor(t.to/8)===0||n.side===`black`&&Math.floor(t.to/8)===7);e.board[t.to]={...n,king:n.king||r};let i={board:e.board,turn:e.turn,forcedFrom:t.captures.length>0?t.to:null};t.captures.length===0||FW(i,t.to,!0).length===0?(e.turn=e.turn===`red`?`black`:`red`,e.forcedFrom=null):e.forcedFrom=t.to}function FW(e,t,n){let r=e.board[t];if(!r)return[];let i=t%8,a=Math.floor(t/8),o=r.king?[-1,1]:r.side===`red`?[-1]:[1],s=[];for(let c of o)for(let o of[-1,1]){let l=i+o,u=a+c,d=i+o*2,f=a+c*2;if(n){if(d<0||f<0||d>=8||f>=8)continue;let n=u*8+l,i=f*8+d;e.board[n]?.side!==r.side&&e.board[n]&&!e.board[i]&&s.push({from:t,to:i,captures:[n]})}else l>=0&&u>=0&&l<8&&u<8&&!e.board[u*8+l]&&s.push({from:t,to:u*8+l,captures:[]})}return s}function IW(e=9){if(e<2||e>25)throw Error(`Go size must be between 2 and 25`);return{size:e,board:Array(e*e).fill(null),turn:`black`,ko:null,passes:0}}function LW(e,t,n){let r=VW(e,t,n);if(e.board[r]||e.ko===r)throw Error(`Go cell is occupied or forbidden by ko`);let i=[...e.board];i[r]=e.turn;let a=e.turn===`black`?`white`:`black`,o=0,s=null;for(let t of HW(e.size,r)){if(i[t]!==a||WW(i,e.size,t)!==0)continue;let n=UW(i,e.size,t);n.length===1&&(s=n[0]);for(let e of n)i[e]=null;o+=n.length}if(WW(i,e.size,r)===0)throw Error(`suicide is not a legal Go move`);e.ko=o===1&&WW(i,e.size,r)===1?s:null,e.board=i,e.turn=a,e.passes=0}function RW(e){e.turn=e.turn===`black`?`white`:`black`,e.ko=null,e.passes++}function zW(e){return e.passes>=2?`finished`:`ongoing`}function BW(e){let t={black:0,white:0},n=new Set;for(let r=0;r<e.board.length;r++){let i=e.board[r];if(i)t[i]++;else if(!n.has(r)){let i=UW(e.board,e.size,r),a=new Set;for(let t of i)for(let n of HW(e.size,t))e.board[n]&&a.add(e.board[n]);for(let e of i)n.add(e);a.size===1&&(t[[...a][0]]+=i.length)}}return t}function VW(e,t,n){if(t<0||n<0||t>=e.size||n>=e.size)throw Error(`Go cell is outside the board`);return n*e.size+t}function HW(e,t){let n=t%e,r=Math.floor(t/e),i=[];return n>0&&i.push(t-1),n<e-1&&i.push(t+1),r>0&&i.push(t-e),r<e-1&&i.push(t+e),i}function UW(e,t,n){let r=e[n],i=[],a=[n],o=new Set;for(;a.length;){let n=a.pop();if(!(o.has(n)||e[n]!==r)){o.add(n),i.push(n);for(let e of HW(t,n))a.push(e)}}return i}function WW(e,t,n){let r=UW(e,t,n),i=new Set;for(let n of r)for(let r of HW(t,n))e[r]===null&&i.add(r);return i.size}function GW(){let e=Array(24).fill(0);return e[0]=2,e[11]=5,e[16]=3,e[18]=5,e[23]=-2,e[12]=-5,e[7]=-3,e[5]=-5,{points:e,bar:{white:0,black:0},off:{white:0,black:0},turn:`white`}}function KW(){let e=oG(2,6);return e[0]===e[1]?[...e,...e]:e}function qW(e,t){let n=e.turn===`white`?1:-1,r=n===1?[18,23]:[0,5],i=e=>n===1?24-e:e+1,a=!0,o=1/0;for(let t=0;t<24;t++)e.points[t]*n<=0||((t<r[0]||t>r[1])&&(a=!1),o=Math.min(o,i(t)));let s=(e,t)=>{if(!a)return!1;let n=i(e);return t===n||t>n&&n===o},c=[];for(let r of t){if(e.bar[e.turn]>0){let t=e.turn===`white`?r-1:24-r;YW(e,t,n)&&c.push({from:`bar`,to:t,die:r});continue}for(let t=0;t<24;t++)if(e.points[t]*n>0){let i=t+r*n;i<0||i>=24?s(t,r)&&c.push({from:t,to:`off`,die:r}):YW(e,i,n)&&c.push({from:t,to:i,die:r})}}return c}function JW(e,t){if(!qW(e,[t.die]).some(e=>e.from===t.from&&e.to===t.to))throw Error(`illegal backgammon move`);let n=e.turn===`white`?1:-1;if(t.from===`bar`?e.bar[e.turn]--:e.points[t.from]-=n,t.to===`off`)e.off[e.turn]++;else{if(e.points[t.to]*n<0){let n=e.turn===`white`?`black`:`white`;e.points[t.to]=0,e.bar[n]++}e.points[t.to]+=n}}function YW(e,t,n){return e.points[t]*n>=-1}function XW(e=0){let t=[`clubs`,`diamonds`,`hearts`,`spades`],n=[];for(let e of t)for(let t=1;t<=13;t++)n.push({suit:e,rank:t});return n.concat(Array(e).fill(null).map(()=>({suit:`spades`,rank:1})))}function ZW(e){return oe(e)}function QW(e,t,n){if(t<0||n<0||e.length<t*n)throw Error(`not enough cards to deal`);return Array.from({length:t},()=>e.splice(0,n))}function $W(e,t){if(e.length===0)throw Error(`a trick needs at least one play`);let n=e[0].card.suit,r=e=>e.rank===1?14:e.rank;return(t&&e.some(e=>e.card.suit===t)?e.filter(e=>e.card.suit===t):e.filter(e=>e.card.suit===n)).reduce((e,t)=>r(t.card)>r(e.card)?t:e).owner}function eG(e){let t=XW();return e===void 0?ZW(t):E(e,()=>ZW(t)),{stock:t,waste:[],tableau:Array.from({length:7},(e,n)=>({down:t.splice(0,6-n),up:t.splice(0,1)})),foundations:[[],[],[],[]]}}function tG(e){e.stock.length===0&&(e.stock=e.waste.reverse(),e.waste=[]);let t=e.stock.pop()??null;return t&&e.waste.push(t),t}function nG(e,t,n,r=1){let i=e.tableau[t],a=e.tableau[n],o=i?.up.slice(-r);if(!i||!a||!o?.length||(a.up.length===0?o[0].rank!==13:!aG(o[0],a.up.at(-1))))throw Error(`illegal solitaire tableau move`);i.up.splice(-r,r),a.up.push(...o),i.down.length&&i.up.length===0&&i.up.push(i.down.pop())}function rG(e,t){let n=t===`waste`?e.waste.at(-1):e.tableau[t].up.at(-1);if(!n)throw Error(`no solitaire card to move`);let r=e.foundations.find(e=>e[0]?.suit===n.suit||e.length===0);if(!r||n.rank!==r.length+1)throw Error(`card cannot move to its foundation`);if(t===`waste`)e.waste.pop();else{let n=e.tableau[t];n.up.pop(),n.down.length&&n.up.length===0&&n.up.push(n.down.pop())}r.push(n)}function iG(e){return e.foundations.every(e=>e.length===13)}function aG(e,t){let n=e.suit===`diamonds`||e.suit===`hearts`,r=t.suit===`diamonds`||t.suit===`hearts`;return e.rank===t.rank-1&&n!==r}function oG(e,t){if(!Number.isInteger(e)||e<0||!Number.isInteger(t)||t<1)throw Error(`dice need a non-negative count and positive sides`);return Array.from({length:e},()=>ne(1,t))}function sG(e){let t=/^(\d+)d(\d+)([+-]\d+)?$/i.exec(e.trim());if(!t)throw Error(`bad dice expression: "${e}"`);return oG(Number(t[1]),Number(t[2])).reduce((e,t)=>e+t,Number(t[3]??0))}var cG=class{constructor(e,t){this.kept=new Set,this.count=e,this.sides=t,this.values=oG(e,t)}reRoll(){for(let e=0;e<this.values.length;e++)this.kept.has(e)||(this.values[e]=ne(1,this.sides))}keep(e){if(e<0||e>=this.count)throw Error(`die index is outside the cup`);this.kept.add(e)}clearKept(){this.kept.clear()}};function lG(e,t){if(e.length!==5||e.some(e=>e<1||e>6))throw Error(`a score sheet needs five d6 values`);let n=new Map;for(let t of e)n.set(t,(n.get(t)??0)+1);let r=e.reduce((e,t)=>e+t,0);if(t===`chance`)return r;if(t===`yahtzee`)return n.size===1?50:0;if(t===`fullHouse`)return[...n.values()].sort().join(`,`)===`2,3`?25:0;if(t===`threeKind`)return[...n.values()].some(e=>e>=3)?r:0;if(t===`fourKind`)return[...n.values()].some(e=>e>=4)?r:0;if(t===`smallStraight`||t===`largeStraight`){let e=[`1234`,`2345`,`3456`],r=[`12345`,`23456`],i=[...n.keys()].sort().join(``);return(t===`smallStraight`?e:r).some(e=>i.includes(e))?t===`smallStraight`?30:40:0}let i=[`ones`,`twos`,`threes`,`fours`,`fives`,`sixes`].indexOf(t)+1;return i>0?(n.get(i)??0)*i:0}function uG(e,t,n=`hex`){if(e<1||t<1)throw Error(`a tactical map needs positive dimensions`);return{width:e,height:t,shape:n,cells:Array.from({length:e*t},()=>({passable:!0,cover:0})),units:[],turn:``,round:1}}function dG(e,t,n){return xG(e,t,n)&&!bG(e,t,n)}function fG(e,t){if(!dG(e,t.x,t.y))throw Error(`tactical unit cannot be placed there`);e.units.push({...t,maxActions:t.maxActions??t.actions}),e.turn||=t.owner}function pG(e,t){let n=yG(e,t);if(n.owner!==e.turn||n.actions<=0)return[];let r=TG(e,n,wG(e,n)),i=[];for(let a=0;a<e.height;a++)for(let o=0;o<e.width;o++){if(o===n.x&&a===n.y||!e.cells[a*e.width+o].passable||bG(e,o,a))continue;let s=EG(e,n,o,a,n.actions,r);s!==null&&i.push({unit:t,x:o,y:a,cost:s})}return i}function mG(e,t){let n=pG(e,t.unit).find(e=>e.x===t.x&&e.y===t.y);if(!n)throw Error(`illegal tactical move`);let r=yG(e,t.unit);r.x=t.x,r.y=t.y,r.actions-=n.cost}function hG(e,t){let n=yG(e,t);if(n.owner!==e.turn||n.actions<=0)throw Error(`only an active unit can enter overwatch`);n.actions=0,n.overwatch=!0}function gG(e,t,n){let r=yG(e,t),i=[];for(let t of[...e.units]){if(!t.overwatch||t.owner===r.owner||CG(e,t,r)>3)continue;let a=e.cells[r.y*e.width+r.x].cover??0,o=Math.max(0,n-a);if(r.hp=Math.max(0,r.hp-o),t.overwatch=!1,i.push({attacker:t.id,defender:r.id,damage:o,cover:a,killed:r.hp===0}),r.hp===0){e.units=e.units.filter(e=>e!==r);break}}return i}function _G(e,t,n,r){let i=yG(e,t),a=yG(e,n);if(i.owner!==e.turn||i.owner===a.owner)throw Error(`invalid tactical attack`);if(CG(e,i,a)>3)throw Error(`tactical target is out of range`);let o=e.cells[a.y*e.width+a.x].cover??0,s=Math.max(0,r-o);a.hp=Math.max(0,a.hp-s);let c=a.hp===0;return c&&(e.units=e.units.filter(e=>e!==a)),{attacker:t,defender:n,damage:s,cover:o,killed:c}}function vG(e){let t=[...new Set(e.units.map(e=>e.owner))];if(t.length===0)return;let n=t.indexOf(e.turn)+1;n>=t.length&&e.round++,e.turn=t[n%t.length];for(let t of e.units)t.owner===e.turn&&(t.actions=t.maxActions??t.actions,t.overwatch=!1)}function yG(e,t){let n=e.units.find(e=>e.id===t);if(!n)throw Error(`unknown tactical unit "${t}"`);return n}function bG(e,t,n){return e.units.some(e=>e.x===t&&e.y===n)}function xG(e,t,n){return t>=0&&n>=0&&t<e.width&&n<e.height}function SG(e,t,n){return e.shape===`hex`?qn(t,n):[{x:t-1,y:n},{x:t+1,y:n},{x:t,y:n-1},{x:t,y:n+1}]}function CG(e,t,n){return e.shape===`hex`?Jn(t,n):Math.abs(t.x-n.x)+Math.abs(t.y-n.y)}function wG(e,t){return new Set(e.units.filter(n=>n.owner!==t.owner&&SG(e,t.x,t.y).some(e=>e.x===n.x&&e.y===n.y)).map(e=>e.id))}function TG(e,t,n){let r=new Set;for(let i of e.units)if(!(i.owner===t.owner||n.has(i.id)))for(let t of SG(e,i.x,i.y))r.add(`${t.x},${t.y}`);return r}function EG(e,t,n,r,i,a){let o=[{x:t.x,y:t.y,distance:0}],s=0,c=new Set([`${t.x},${t.y}`]);for(;s<o.length;){let t=o[s++];if(t.x===n&&t.y===r)return t.distance;if(!(t.distance>=i||t.distance>0&&a.has(`${t.x},${t.y}`)))for(let i of SG(e,t.x,t.y)){let a=`${i.x},${i.y}`;xG(e,i.x,i.y)&&!c.has(a)&&e.cells[i.y*e.width+i.x].passable&&(!bG(e,i.x,i.y)||i.x===n&&i.y===r)&&(c.add(a),o.push({x:i.x,y:i.y,distance:t.distance+1}))}}return null}var DG=class{constructor(e,t){if(this.visible=new Map,this.explored=new Map,this.shared=new Map,e<1||t<1)throw Error(`fog needs positive dimensions`);this.width=e,this.height=t}share(e){let t=[...new Set(e)].filter(e=>!!e);if(t.length===0)return;let n=new Set(t);for(let e of t)for(let t of this.shared.get(e)??[])n.add(t);for(let e of n)this.shared.set(e,n)}sync(e,t,n){if(!e)throw Error(`fog needs a faction id`);let r=new Set;for(let e of t)for(let t of n(e))this.inside(t.x,t.y)&&r.add(this.index(t.x,t.y));this.visible.set(e,r);let i=this.explored.get(e)??new Set;for(let e of r)i.add(e);this.explored.set(e,i)}reveal(e,t){if(!e)throw Error(`fog needs a faction id`);let n=this.explored.get(e)??new Set;for(let e of t)this.inside(e.x,e.y)&&n.add(this.index(e.x,e.y));this.explored.set(e,n)}isVisible(e,t,n){return this.seenBy(this.visible,e,this.index(t,n))}sees(e){return(t,n)=>this.isVisible(e,t,n)}isExplored(e,t,n){return this.seenBy(this.explored,e,this.index(t,n))}visibleCells(e){return this.cellsSeenBy(this.visible,e)}exploredCells(e){return this.cellsSeenBy(this.explored,e)}seenBy(e,t,n){let r=this.shared.get(t);if(!r)return e.get(t)?.has(n)??!1;for(let t of r)if(e.get(t)?.has(n))return!0;return!1}cellsSeenBy(e,t){let n=this.shared.get(t);if(!n)return[...e.get(t)??[]];let r=new Set;for(let t of n)for(let n of e.get(t)??[])r.add(n);return[...r].sort((e,t)=>e-t)}inside(e,t){return er(this.width,this.height,e,t)}index(e,t){return this.inside(e,t)?tr(this.width,e,t):-1}};function OG(e){return{currency:e,pool:[]}}function kG(e,t,n,r){return e.currency<r||!dG(t,n.x,n.y)?!1:(fG(t,n),e.currency-=r,!0)}function AG(e,t,n,r,i){let a=e.pool.findIndex(e=>e.id===n);return a===-1||!dG(t,r,i)?!1:(fG(t,{...e.pool[a],x:r,y:i}),e.pool.splice(a,1),!0)}function jG(e,t,n){let r=t.units.findIndex(e=>e.id===n);if(r===-1)return!1;let{x:i,y:a,...o}=t.units[r];return e.pool.push(o),t.units.splice(r,1),!0}function MG(e,t,n){return e.units.filter(e=>e.owner===t).length*(n.incomePerUnit-n.upkeepPerUnit)}function NG(e,t,n,r){return e.currency+=MG(t,n,r),e.currency}_e();function PG(e,t,n,r){if(e<1||t<1)throw Error(`a skirmish map needs positive dimensions`);let i=r??Object.keys(n)[0];if(!i||!n[i])throw Error(`a skirmish map needs at least one terrain kind`);return{width:e,height:t,terrainTable:n,cells:Array.from({length:e*t},()=>({terrain:i})),units:[],turn:``,round:1}}function FG(e,t,n,r,i=!1){if(!GG(e,t,n))throw Error(`cell is outside the skirmish map`);if(!e.terrainTable[r])throw Error(`unknown skirmish terrain "${r}"`);e.cells[n*e.width+t]=i?{terrain:r,village:!0}:{terrain:r}}function IG(e,t,n){return GG(e,t,n)&&JG(e,t,n)<1/0&&!KG(e,t,n)}function LG(e,t){if(!IG(e,t.x,t.y))throw Error(`skirmish unit cannot be placed there`);e.units.push({...t,remainingMoves:t.moves}),e.turn||=t.owner}function RG(e,t){let n=WG(e,t),r=n.remainingMoves??n.moves;if(n.owner!==e.turn||r<=0)return[];let i=new Set(e.units.filter(e=>e.id!==n.id).map(e=>`${e.x},${e.y}`)),a=YG(e,n,r,i),o=[];for(let s=0;s<e.height;s++)for(let c=0;c<e.width;c++){if(c===n.x&&s===n.y||JG(e,c,s)===1/0||i.has(`${c},${s}`))continue;let l=a.get(`${c},${s}`);l!==void 0&&l<=r&&o.push({unit:t,x:c,y:s,cost:l})}return o}function zG(e,t){let n=RG(e,t.unit).find(e=>e.x===t.x&&e.y===t.y);if(!n)throw Error(`illegal skirmish move`);let r=WG(e,t.unit);r.x=t.x,r.y=t.y,r.remainingMoves=(r.remainingMoves??r.moves)-n.cost;let i=e.cells[t.y*e.width+t.x];i.village&&(i.owner=r.owner)}function BG(e,t,n){let r=WG(e,t),i=WG(e,n);if(r.owner!==e.turn||r.owner===i.owner)throw Error(`invalid skirmish attack`);if(Jn(r,i)!==1)throw Error(`skirmish combat is adjacency-only`);let a=[VG(e,r,i)];return i.hp>0&&a.push(VG(e,i,r)),e.units=e.units.filter(e=>e.hp>0),{strikes:a}}function VG(e,t,n){let r=qG(e,n.x,n.y).defense,i=A(Math.max(0,Math.min(1,t.hitChance*(1-r)))),a=i?Math.min(t.attack,n.hp):0;return n.hp-=a,{attacker:t.id,defender:n.id,hit:i,damage:a,killed:n.hp<=0}}function HG(e,t,n,r){return n+e.cells.filter(e=>e.village&&e.owner===t).length*r}function UG(e,t=0){let n=[...new Set(e.units.map(e=>e.owner))];if(n.length===0)return;let r=n.indexOf(e.turn)+1;r>=n.length&&e.round++,e.turn=n[r%n.length];for(let n of e.units){if(n.owner!==e.turn)continue;n.remainingMoves=n.moves;let r=e.cells[n.y*e.width+n.x];r.village&&r.owner===n.owner&&t>0&&(n.hp=Math.min(n.maxHp,n.hp+t))}}function WG(e,t){let n=e.units.find(e=>e.id===t);if(!n)throw Error(`unknown skirmish unit "${t}"`);return n}function GG(e,t,n){return er(e.width,e.height,t,n)}function KG(e,t,n){return e.units.some(e=>e.x===t&&e.y===n)}function qG(e,t,n){return e.terrainTable[e.cells[n*e.width+t].terrain]}function JG(e,t,n){return qG(e,t,n).moveCost}function YG(e,t,n,r){let i=[],a=(e,t)=>{[i[e],i[t]]=[i[t],i[e]]},o=e=>{i.push(e);let t=i.length-1;for(;t>0;){let e=t-1>>1;if(i[e].cost<=i[t].cost)break;a(t,e),t=e}},s=()=>{if(i.length===0)return;let e=i[0],t=i.pop();if(i.length>0){i[0]=t;let e=0;for(;;){let t=e*2+1,n=t+1,r=e;if(t<i.length&&i[t].cost<i[r].cost&&(r=t),n<i.length&&i[n].cost<i[r].cost&&(r=n),r===e)break;a(e,r),e=r}}return e},c=new Map([[`${t.x},${t.y}`,0]]);for(o({x:t.x,y:t.y,cost:0});;){let t=s();if(t===void 0)break;let i=`${t.x},${t.y}`;if(!(t.cost>(c.get(i)??1/0)))for(let i of qn(t.x,t.y)){if(!GG(e,i.x,i.y))continue;let a=JG(e,i.x,i.y);if(a===1/0||r.has(`${i.x},${i.y}`))continue;let s=t.cost+a;if(s>n)continue;let l=`${i.x},${i.y}`;s<(c.get(l)??1/0)&&(c.set(l,s),o({x:i.x,y:i.y,cost:s}))}}return c}var XG=l({BoardGrid:()=>jW,DiceCup:()=>cG,FactionFog:()=>DG,addSkirmishUnit:()=>LG,addTacticalUnit:()=>fG,applyBackgammonMove:()=>JW,applyCheckersMove:()=>PW,applyMove:()=>mU,applyUpkeep:()=>NG,armyIncome:()=>MG,backgammonMoves:()=>qW,bankUnit:()=>jG,bitboardFromChess:()=>nW,bitboardMoves:()=>iW,canPlaceSkirmishUnit:()=>IG,canPlaceTacticalUnit:()=>dG,checkersMoves:()=>NW,chessGame:()=>NU,chooseMove:()=>OU,cloneChess:()=>nU,createDeck:()=>XW,deal:()=>QW,dealSolitaire:()=>eG,drawSolitaire:()=>tG,endSkirmishTurn:()=>UG,endTacticalTurn:()=>vG,gameResult:()=>hU,goResult:()=>zW,goScore:()=>BW,huffDecode:()=>wW,huffEncode:()=>xW,inCheck:()=>lU,legalMoves:()=>pU,loadTablebaseEnding:()=>EW,makeMove:()=>oW,moveSkirmishUnit:()=>zG,moveSolitaireTableau:()=>nG,moveSolitaireToFoundation:()=>rG,moveTacticalUnit:()=>mG,parseFen:()=>XH,parseUciMove:()=>BU,passGo:()=>RW,perft:()=>cW,playGo:()=>LW,positionKey:()=>YH,probeBook:()=>RU,probeTablebase:()=>kW,recall:()=>AG,recruit:()=>kG,rollBackgammonDice:()=>KW,rollDice:()=>oG,rollExpression:()=>sG,scoreDice:()=>lG,search:()=>kU,searchAsync:()=>AU,searchTourney:()=>dW,searchTourneyAsync:()=>pW,setSkirmishTerrain:()=>FG,setTacticalOverwatch:()=>hG,shuffleDeck:()=>ZW,skirmishAttack:()=>BG,skirmishIncome:()=>HG,skirmishMoves:()=>RG,solitaireWon:()=>iG,sq:()=>qH,squareName:()=>JH,startingArmy:()=>OG,startingBackgammon:()=>GW,startingBitboard:()=>rW,startingCheckers:()=>MW,startingChess:()=>tU,startingGo:()=>IW,startingSkirmish:()=>PG,startingTactics:()=>uG,tablebaseId:()=>_W,tacticalAttack:()=>_G,tacticalMoves:()=>pG,tourneyThink:()=>lW,trickWinner:()=>$W,triggerTacticalOverwatch:()=>gG,unmakeMove:()=>sW});function ZG(e){return new Audio(HM(e))}var QG=new p,$G=class{constructor(e,t={}){this.next=0,this.suspended_=!1;let n=Math.max(1,t.poolSize??4),r=t.create??ZG;this.volume=t.volume??1,this.caption=t.caption,this.pool=Array.from({length:n},()=>r(e))}play(e=1,t=1){if(this.suspended_)return;let n=this.pool[this.next];this.next=(this.next+1)%this.pool.length,n.volume=this.volume*e,n.playbackRate=t,n.currentTime=0,Promise.resolve(n.play()).catch(()=>{}),this.caption&&QG.dispatch({text:this.caption})}stopAll(){for(let e of this.pool)e.pause(),e.currentTime=0}suspend(){this.suspended_=!0,this.stopAll()}resume(){this.suspended_=!1}get isSuspended(){return this.suspended_}},eK=class{constructor(e={}){this.current=null,this.fades=[],this.trackQueue=null,this.playlistFade=1,this.suspended_=!1,this.duckLevel_=1,this.volume=e.volume??1,this.create=e.create??ZG}play(e,t=1){this.trackQueue=null,this.start(e,t,!0)}playTracks(e,t=1){if(e.length===0){this.stop(t);return}this.trackQueue=[...e],this.playlistFade=t,this.startNextTrack()}startNextTrack(){if(!this.trackQueue?.length)return;let e=this.trackQueue.shift();this.trackQueue.push(e),this.start(e,this.playlistFade,!1)}start(e,t,n){let r=this.create(e);r.loop=n,!n&&r.onended!==void 0&&(r.onended=()=>{this.current===r&&this.startNextTrack()});let i=this.current;if(this.current=r,t<=0){r.volume=this.volume*this.duckLevel_,Promise.resolve(r.play()).catch(()=>{}),i?.pause();return}r.volume=0,Promise.resolve(r.play()).catch(()=>{}),this.fades.push({audio:r,elapsed:0,duration:t,from:0,to:this.volume*this.duckLevel_,stopAtEnd:!1}),i&&this.fades.push({audio:i,elapsed:0,duration:t,from:i.volume,to:0,stopAtEnd:!0})}stop(e=1){this.trackQueue=null;let t=this.current;if(t){if(this.current=null,e<=0){t.pause();return}this.fades.push({audio:t,elapsed:0,duration:e,from:t.volume,to:0,stopAtEnd:!0})}}suspend(){this.suspended_=!0,this.current?.pause();for(let e of this.fades)e.audio.pause()}resume(){this.suspended_&&(this.suspended_=!1,this.current&&Promise.resolve(this.current.play()).catch(()=>{}))}duck(e=.5,t=.5){let n=Number.isFinite(e)?Math.max(0,Math.min(1,e)):1,r=this.duckLevel_;this.duckLevel_=n;for(let e of this.fades)e.to=r>0?e.to/r*n:this.volume*n;if(this.current){let e=this.volume*n;t<=0?this.current.volume=e:this.fades.push({audio:this.current,elapsed:0,duration:t,from:this.current.volume,to:e,stopAtEnd:!1})}}unduck(e=.5){this.duck(1,e)}get duckLevel(){return this.duckLevel_}get isSuspended(){return this.suspended_}update(e){if(!this.suspended_)for(let t of[...this.fades]){t.elapsed+=e;let n=Math.min(1,t.elapsed/t.duration);t.audio.volume=t.from+(t.to-t.from)*n,n>=1&&(this.fades.splice(this.fades.indexOf(t),1),t.stopAtEnd&&(t.audio.pause(),t.audio.currentTime=0))}}},tK=class{constructor(e){this.states=new Map,this.cues=new Map,this.currentTrack=null,this.music=e}define(e,t){this.states.set(e,t)}enter(e){let t=this.states.get(e);if(!t)throw Error(`Orchestrator: no state defined for "${e}"`);t.track!==this.currentTrack&&(this.music.play(t.track,t.fadeDuration),this.currentTrack=t.track)}on(e,t){this.cues.set(e,t)}trigger(e){this.cues.get(e)?.play()}suspend(){this.music.suspend();for(let e of this.cues.values())e.suspend()}resume(){this.music.resume();for(let e of this.cues.values())e.resume()}};function nK(e={}){let t=e.waveform??`square`,n=e.frequency??440,r=e.duration??.15,i=e.volume??.3,a=e.decay??8,o=e.sampleRate??22050,s=e.seed??1;if(!(r>0))throw Error(`tone duration must be positive`);if(t!==`noise`&&!(n>0))throw Error(`tone frequency must be positive`);if(!(o>0))throw Error(`tone sample rate must be positive`);let c=Math.max(1,Math.round(r*o)),l=new Float32Array(c);for(let e=0;e<c;e++){let r=e/o,u=a>0?Math.exp(-a*e/c):1,d=2*Math.PI*n*r;l[e]=i*u*iK(t,d,s,e)}return oK(l,o)}function rK(e={},t=e=>new Audio(e)){let n=t(nK(e));return Promise.resolve(n.play()).catch(()=>{}),n}function iK(e,t,n,r){switch(e){case`sine`:return Math.sin(t);case`square`:return Math.sin(t)>=0?1:-1;case`triangle`:{let e=t/(2*Math.PI),n=e-Math.floor(e);return 4*Math.abs(n-.5)-1}case`noise`:return aK(n,r)}}function aK(e,t){let n=Math.imul(e^t,2654435761)>>>0;return n=Math.imul(n^n>>>15,2246822519)>>>0,n=Math.imul(n^n>>>13,3266489917)>>>0,n^=n>>>16,(n>>>0)/4294967295*2-1}function oK(e,t){let n=e.length*2,r=new ArrayBuffer(44+n),i=new DataView(r);sK(i,0,`RIFF`),i.setUint32(4,36+n,!0),sK(i,8,`WAVE`),sK(i,12,`fmt `),i.setUint32(16,16,!0),i.setUint16(20,1,!0),i.setUint16(22,1,!0),i.setUint32(24,t,!0),i.setUint32(28,t*2,!0),i.setUint16(32,2,!0),i.setUint16(34,16,!0),sK(i,36,`data`),i.setUint32(40,n,!0);let a=44;for(let t of e){let e=Math.max(-1,Math.min(1,t));i.setInt16(a,Math.round(e*(e<0?32768:32767)),!0),a+=2}let o=``,s=new Uint8Array(r);for(let e of s)o+=String.fromCharCode(e);return`data:audio/wav;base64,${btoa(o)}`}function sK(e,t,n){for(let r=0;r<n.length;r++)e.setUint8(t+r,n.charCodeAt(r))}function cK(e,t){let[n,r]=e,i=n*4*dK[t]/r;if(!Number.isInteger(i)||i<1)throw Error(`a ${t} grid does not cut a ${n}/${r} bar into whole slots (it needs ${i})`);return i}function lK(e,t){return e/dK[t]}function uK(e){if(typeof e!=`object`||!e)throw Error(`a groove template must be an object`);let{name:t,timeSignature:n,ppq:r,tempoBpm:i,subdivision:a,offsets:o}=e;if(typeof t!=`string`||t.length===0)throw Error(`a groove template needs a non-empty name`);if(!Array.isArray(n)||n.length!==2)throw Error(`groove template "${t}": timeSignature must be [beats, beatValue]`);let[s,c]=n;if(!Number.isInteger(s)||s<1)throw Error(`groove template "${t}": time signature numerator must be a positive integer, got ${String(s)}`);if(!Number.isInteger(c)||c<1||c&c-1)throw Error(`groove template "${t}": time signature denominator must be a power of two, got ${String(c)}`);if(!Number.isInteger(r)||r<1)throw Error(`groove template "${t}": ppq must be a positive integer, got ${String(r)}`);if(!Number.isFinite(i)||i<=0)throw Error(`groove template "${t}": tempoBpm must be greater than 0, got ${String(i)}`);if(a!==`8n`&&a!==`16n`&&a!==`32n`)throw Error(`groove template "${t}": subdivision must be 8n, 16n or 32n, got ${String(a)}`);let l=lK(r,a);if(!Number.isInteger(l)||l<1)throw Error(`groove template "${t}": ${r} ppq does not cut into whole ${a} ticks (it needs ${String(l)})`);let u=cK(n,a);if(!Array.isArray(o)||o.length!==u)throw Error(`groove template "${t}": a ${a} grid in ${s}/${c} has ${u} slots, this carries ${Array.isArray(o)?o.length:String(o)}`);o.forEach((e,n)=>{if(typeof e!=`object`||!e)throw Error(`groove template "${t}": slot ${n} must be an object`);if(e.subdivisionIndex!==n)throw Error(`groove template "${t}": slots must run in order, slot ${n} carries ${String(e.subdivisionIndex)}`);if(!Number.isInteger(e.timeOffsetTicks))throw Error(`groove template "${t}": slot ${n} has a fractional timeOffsetTicks (${String(e.timeOffsetTicks)}); ticks are whole numbers`);if(!Number.isFinite(e.velocityFactor)||e.velocityFactor<0)throw Error(`groove template "${t}": slot ${n} has velocityFactor ${String(e.velocityFactor)}, which must be a finite number of at least 0`)})}var dK,fK=s((()=>{dK={"8n":2,"16n":4,"32n":8}}));function pK(e){let t=e.intensity;if(!Number.isFinite(t)||t<0||t>1)throw Error(`humanization intensity must be between 0 and 1, got ${String(e.intensity)}`);let n=e.timingVarianceMs??MK;if(!Number.isFinite(n)||n<0)throw Error(`timingVarianceMs must be a finite number of at least 0, got ${String(e.timingVarianceMs)}`);let r=e.velocityVariance??NK;if(!Number.isFinite(r)||r<0)throw Error(`velocityVariance must be a finite number of at least 0, got ${String(e.velocityVariance)}`);let i=e.style?PK[e.style]:FK,a=e.grooveTemplate??null;return a&&uK(a),{intensity:t,timingMs:n,velocityVariance:r,timingScale:i.timing,velocityScale:i.velocity,template:a,warn:e.onWarn??(e=>console.warn(e))}}function mK(e){let t=[];for(let n of e)n.type===`tempo`&&t.push({tick:n.tick,microsecondsPerQuarter:n.microsecondsPerQuarter});t.sort((e,t)=>e.tick-t.tick);let n=[{tick:0,microsecondsPerQuarter:5e5}];for(let e of t)e.tick===n[n.length-1].tick?n[n.length-1]=e:n.push(e);return n}function hK(e,t){let n=0,r=e.length-1,i=0;for(;n<=r;){let a=n+r>>1;e[a].tick<=t?(i=a,n=a+1):r=a-1}return 6e7/e[i].microsecondsPerQuarter}function gK(e,t,n){return e*t*n/6e4}function _K(e,t,n){return e*6e4/(t*n)}function vK(e){let t=null;return()=>{if(t!==null){let e=t;return t=null,e}let n=Math.sqrt(-2*Math.log(1-e.float())),r=2*Math.PI*e.float();return t=n*Math.sin(r),n*Math.cos(r)}}function yK(e){let t=new Uint8Array(256);for(let e=0;e<256;e++)t[e]=e;for(let n=255;n>0;n--){let r=e.int(n+1),i=t[n];t[n]=t[r],t[r]=i}let n=(e,t)=>e&1?t:-t;return e=>{let r=Math.floor(e),i=e-r,a=i*i*i*(i*(i*6-15)+10),o=n(t[r&255],i);return o+a*(n(t[r+1&255],i-1)-o)}}function bK(e){let t=new Map;for(let n of e.offsets)t.set(n.subdivisionIndex,{ms:_K(n.timeOffsetTicks,e.ppq,e.tempoBpm),factor:n.velocityFactor});return t}function xK(e){let t=new Uint8Array(e.length),n=new Map;for(let t=0;t<e.length;t++){let r=e[t];if(r.type!==`noteOn`||r.channel===kK)continue;let i=n.get(r.channel);i?i.push({index:t,note:r.note}):n.set(r.channel,[{index:t,note:r.note}])}for(let e of n.values())for(let n=1;n<e.length-1;n++)e[n].note>e[n-1].note&&e[n].note>e[n+1].note&&(t[e[n].index]=1);return t}function SK(e){return e.channel===kK?AK.includes(e.note):e.note<jK}function CK(e,t,n){let r=pK(t),i=new j(t.seed),a=vK(i),o=yK(i),s=e.ticksPerQuarter,c=mK(e.events),l=r.template?bK(r.template):null,u=r.template?lK(s,r.template.subdivision):0,d=r.template?cK(r.template.timeSignature,r.template.subdivision):0,f=n===`groove`?xK(e.events):null,p=[],m=new Map,h=!1;for(let t=0;t<e.events.length;t++){let i=e.events[t];if(i.type===`noteOff`){let e=m.get(IK(i)),t=e&&e.length>0?e.shift():0;p.push(t===0?{...i}:{...i,tick:i.tick+t});continue}if(i.type!==`noteOn`){p.push({...i});continue}let g=hK(c,i.tick);r.template&&!h&&Math.abs(g-r.template.tempoBpm)>DK&&(h=!0,r.warn(`groove template "${r.template.name}" is written at ${r.template.tempoBpm} BPM but this file is at ${g.toFixed(1)} BPM by tick ${i.tick}: its offsets are rescaled to keep the same timing in milliseconds`));let _=gK(r.timingMs*r.timingScale,s,g),v=a()*_+o(i.tick/s*wK)*_*TK;if(n===`groove`&&SK(i)){let e=gK(OK,s,g);v=Math.min(e,Math.max(-e,v))}let y;l&&(y=l.get(Math.floor(i.tick/u)%d));let b=Math.round(r.intensity*((y?gK(y.ms,s,g):0)+v));i.tick+b<0&&(b=-i.tick);let x=Math.round(i.velocity*(1+r.intensity*((y?y.factor:1)-1))+r.intensity*a()*r.velocityVariance*r.velocityScale);f&&f[t]===1&&(x=Math.round(x*(1+r.intensity*EK))),x=Math.min(127,Math.max(1,x));let S=IK(i),C=m.get(S);C?C.push(b):m.set(S,[b]),p.push({...i,tick:i.tick+b,velocity:x})}return p.sort((e,t)=>e.tick-t.tick),{ticksPerQuarter:s,events:p,loopStartTick:e.loopStartTick}}var wK,TK,EK,DK,OK,kK,AK,jK,MK,NK,PK,FK,IK,LK=s((()=>{_e(),fK(),wK=.25,TK=.5,EK=.15,DK=1,OK=5,kK=9,AK=[35,36],jK=48,MK=8,NK=10,PK={jazz:{timing:1.3,velocity:1.1},rock:{timing:.8,velocity:1.2},classical:{timing:.6,velocity:1.4},funk:{timing:1,velocity:1.3}},FK={timing:1,velocity:1},IK=e=>`${e.channel}:${e.note}`})),RK=l({LiteHumanizer:()=>zK}),zK,BK=s((()=>{LK(),zK=class{constructor(){this.tierName=`lite`,this.approximateSizeMb=.05}async initialize(){}async process(e,t){if(t.grooveTemplate)throw Error(`the lite tier applies no groove grid: ask HumanizerFactory for "groove" when a template is in play`);return CK(e,t,`lite`)}}})),VK=l({GrooveHumanizer:()=>HK}),HK,UK=s((()=>{LK(),HK=class{constructor(){this.tierName=`groove`,this.approximateSizeMb=.5}async initialize(){}async process(e,t){return CK(e,t,`groove`)}}})),WK=class e{static async create(t){let n=await e.load(t);return await n.initialize(),n}static async load(e){switch(e){case`lite`:return new(await(Promise.resolve().then(()=>(BK(),RK)))).LiteHumanizer;case`groove`:return new(await(Promise.resolve().then(()=>(UK(),VK)))).GrooveHumanizer;case`magenta`:throw Error(`the 'magenta' tier is not shipped: it needs @magenta/music and a PerformanceRNN checkpoint, and neither can be fetched from a file:// build`);default:throw Error(`unknown humanizer tier: ${String(e)}`)}}};async function GK(e,t){let{tier:n,...r}=t,i=n??(r.grooveTemplate?`groove`:`lite`);return(await WK.create(i)).process(e,r)}var KK=5e5,qK=111;function JK(e){let t=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength),n=new DataView(t.buffer,t.byteOffset,t.byteLength),r=0,i=e=>{let n=``;for(let i=0;i<e;i++)n+=String.fromCharCode(t[r+i]);return r+=e,n},a=()=>{let e=n.getUint32(r,!1);return r+=4,e},o=()=>{let e=n.getUint16(r,!1);return r+=2,e},s=()=>{let e=0;for(;;){let n=t[r++];if(e=e<<7|n&127,!(n&128))return e}};if(i(4)!==`MThd`||a()!==6)throw Error(`invalid MIDI header chunk`);let c=o(),l=o(),u=o();if(c!==0&&c!==1)throw Error(`unsupported MIDI format ${c}`);if(u&32768)throw Error(`SMPTE-based MIDI timing is not supported`);let d=u,f=[],p=null;for(let e=0;e<l;e++){let e=i(4),n=a();if(e!==`MTrk`){r+=n;continue}let o=r+n,c=0,l=0;for(;r<o;){c+=s();let e=t[r];if(e<128?e=l:(r++,e<240&&(l=e)),e===255){let e=t[r++],n=s();if(e===81&&n===3){let e=t[r]<<16|t[r+1]<<8|t[r+2];f.push({tick:c,type:`tempo`,microsecondsPerQuarter:e})}r+=n}else if(e===240||e===247)r+=s();else{let n=e&240,i=e&15;if(n===128||n===144){let e=t[r++],a=t[r++],o=n===144&&a>0;f.push({tick:c,type:o?`noteOn`:`noteOff`,note:e,velocity:a,channel:i})}else if(n===176){let e=t[r++],n=t[r++];f.push({tick:c,type:`control`,channel:i,controller:e,value:n}),e===qK&&p===null&&(p=c)}else if(n===192){let e=t[r++];f.push({tick:c,type:`program`,channel:i,program:e})}else if(n===224){let e=t[r++],n=t[r++];f.push({tick:c,type:`pitchBend`,channel:i,value:(n<<7|e)-8192})}else if(n===160||n===208)r+=n===160?2:1;else throw Error(`unsupported MIDI status byte 0x${e.toString(16)}`)}}}return f.sort((e,t)=>e.tick-t.tick),{ticksPerQuarter:d,events:f,loopStartTick:p}}var YK=2;function XK(e){let t=[{tick:0,time:0,microsecondsPerQuarter:KK}];for(let n of e.events){if(n.type!==`tempo`)continue;let r=t[t.length-1];t.push({tick:n.tick,time:r.time+(n.tick-r.tick)*r.microsecondsPerQuarter/e.ticksPerQuarter/1e6,microsecondsPerQuarter:n.microsecondsPerQuarter})}return t}function ZK(e,t,n){let r=e[0];for(let t of e)if(t.tick<=n)r=t;else break;return r.time+(n-r.tick)*r.microsecondsPerQuarter/t/1e6}function QK(e){return e.loopStartTick===null?null:ZK(XK(e),e.ticksPerQuarter,e.loopStartTick)}function $K(e){let t=XK(e),n=Array.from({length:16},()=>({program:0,bank:0,volume:100,expression:127,pan:64,bend:0})),r=e=>{let t=n[e]??n[0];return{program:t.program,bank:t.bank,gain:t.volume/127*(t.expression/127),pan:(t.pan-64)/64,...t.bend?{bend:t.bend}:{}}},i=[],a=new Map;for(let o of e.events){if(o.type===`tempo`)continue;if(o.type===`pitchBend`){(n[o.channel]??n[0]).bend=o.value/8192*YK;continue}if(o.type===`program`){(n[o.channel]??n[0]).program=o.program;continue}if(o.type===`control`){let e=n[o.channel]??n[0];o.controller===0?e.bank=o.value:o.controller===7?e.volume=o.value:o.controller===10?e.pan=o.value:o.controller===11&&(e.expression=o.value);continue}let s=ZK(t,e.ticksPerQuarter,o.tick),c=`${o.channel}:${o.note}`;if(o.type===`noteOn`)a.set(c,{time:s,velocity:o.velocity,voice:r(o.channel)});else{let e=a.get(c);e&&(i.push({time:e.time,duration:Math.max(.01,s-e.time),note:o.note,velocity:e.velocity,channel:o.channel,...e.voice}),a.delete(c))}}for(let[e,t]of a){let[n,r]=e.split(`:`).map(Number);i.push({time:t.time,duration:.3,note:r,velocity:t.velocity,channel:n,...t.voice})}return i.sort((e,t)=>e.time-t.time)}function eq(e){return 440*2**((e-69)/12)}var tq=class e{constructor(e,t={}){this.elapsed=0,this.index=0,this.playing=!1,this.notes=$K(e),this.playFn=t.play??rK,this.waveform=t.waveform??`square`,this.volume=t.volume??.2}static async create(t,n={}){return new e(n.humanize?await GK(t,n.humanize):t,n)}play(){this.playing=this.index<this.notes.length}pause(){this.playing=!1}stop(){this.playing=!1,this.elapsed=0,this.index=0}update(e){if(this.playing){for(this.elapsed+=e;this.index<this.notes.length&&this.notes[this.index].time<=this.elapsed;){let e=this.notes[this.index];this.playFn({waveform:this.waveform,frequency:eq(e.note),duration:e.duration,volume:this.volume*(e.velocity/127)}),this.index++}this.index>=this.notes.length&&(this.playing=!1)}}get isPlaying(){return this.playing}get duration(){let e=this.notes.at(-1);return e?e.time+e.duration:0}},nq={keyRange:43,velRange:44,instrument:41,sampleId:53,rootKey:58,coarseTune:51,fineTune:52,sampleModes:54,attenuation:48,pan:17,attack:34,hold:35,decay:36,sustain:37,release:38};function rq(e){return 2**(e/1200)}function iq(e){return e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function aq(e,t){let n=``;for(let r=0;r<20;r++){let i=e[t+r];if(i===0)break;n+=String.fromCharCode(i)}return n}function oq(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=t=>String.fromCharCode(e[t],e[t+1],e[t+2],e[t+3]);if(n(0)!==`RIFF`||n(8)!==`sfbk`)throw Error(`not a SoundFont 2 file`);let r=new Map,i=new Map,a=(e,o)=>{let s=e;for(;s+8<=o;){let e=n(s),o=t.getUint32(s+4,!0);e===`LIST`?(i.set(n(s+8),{at:s,size:o}),a(s+12,s+8+o)):r.set(e,{at:s+8,size:o}),s+=8+o+(o&1)}};a(12,e.length);for(let e of[`phdr`,`pbag`,`pgen`,`inst`,`ibag`,`igen`,`shdr`,`smpl`])if(!r.has(e))throw Error(`SoundFont is missing "${e}"`);let o=(e,t,n)=>{let i=r.get(e),a=[];for(let e=i.at;e+t<=i.at+i.size;e+=t)a.push(n(e));return a},s=n=>o(n,4,n=>({oper:t.getUint16(n,!0),lo:e[n+2],hi:e[n+3],amount:t.getInt16(n+2,!0)})),c=e=>o(e,4,e=>t.getUint16(e,!0)),l=o(`phdr`,38,n=>({name:aq(e,n),preset:t.getUint16(n+20,!0),bank:t.getUint16(n+22,!0),bag:t.getUint16(n+24,!0)})),u=o(`inst`,22,n=>({name:aq(e,n),bag:t.getUint16(n+20,!0)})),d=o(`shdr`,46,n=>({name:aq(e,n),start:t.getUint32(n+20,!0),end:t.getUint32(n+24,!0),loopStart:t.getUint32(n+28,!0),loopEnd:t.getUint32(n+32,!0),rate:t.getUint32(n+36,!0),rootKey:e[n+40],correction:t.getInt8(n+41),link:t.getUint16(n+42,!0),type:t.getUint16(n+44,!0)})),f=r.get(`smpl`),p=new Int16Array(e.buffer.slice(e.byteOffset+f.at,e.byteOffset+f.at+f.size-(f.size&1))),m=i.get(`INFO`)??null;return{bytes:e,presets:l,presetBags:c(`pbag`),presetGens:s(`pgen`),instruments:u,instBags:c(`ibag`),instGens:s(`igen`),samples:d,smpl:p,info:m?e.slice(m.at,m.at+8+m.size+(m.size&1)):null}}function sq(e,t,n){return t.slice(e[n],e[n+1]??t.length)}function cq(e,t,n,r,i){let a=e[r].bag,o=e[r+1]?.bag??t.length-1,s=[],c=null;for(let e=a;e<o;e++){let r=sq(t,n,e),o=new Map;for(let e of r)o.set(e.oper,e);if(!o.has(i)){e===a&&(c=o);continue}s.push({gens:o,global:c})}return s}function lq(e,t){return e.gens.get(t)??e.global?.get(t)??null}function uq(e,t,n){return e.get(`${t}:${n}`)??e.get(`0:${n}`)??(t===128?e.get(`128:0`):void 0)??e.get(`0:0`)}function dq(e){let t=oq(iq(e)),n=new Map,r=new Map,i=e=>{if(n.has(e))return n.get(e);let i=t.samples[e];if(!i||i.end<=i.start||i.type&32768)return n.set(e,null),null;let a=new Float32Array(i.end-i.start);for(let e=0;e<a.length;e++)a[e]=t.smpl[i.start+e]/32768;let o={data:a,rate:i.rate||22050,loopStart:i.loopStart-i.start,loopEnd:i.loopEnd-i.start};return n.set(e,o),r.set(e,{rootKey:i.rootKey===255?60:i.rootKey,correction:i.correction}),o},a=new Map;for(let e=0;e<t.presets.length-1;e++)a.set(`${t.presets[e].bank}:${t.presets[e].preset}`,e);function o(e,n,o,s){let c=uq(a,e,n);if(c===void 0)return[];let l=[],u=(e,t,n)=>{let r=lq(e,t);return!r||n>=r.lo&&n<=r.hi};for(let e of cq(t.presets,t.presetBags,t.presetGens,c,nq.instrument)){if(!u(e,nq.keyRange,o)||!u(e,nq.velRange,s))continue;let n=lq(e,nq.instrument).amount;if(t.instruments[n+1])for(let a of cq(t.instruments,t.instBags,t.instGens,n,nq.sampleId)){if(!u(a,nq.keyRange,o)||!u(a,nq.velRange,s))continue;let t=lq(a,nq.sampleId).amount,n=i(t);if(!n)continue;let c=(t,n=0)=>(lq(a,t)?.amount??n)+(lq(e,t)?.amount??0),d=lq(a,nq.rootKey)?.amount,f=lq(a,nq.sampleModes)?.amount??0,p=r.get(t);l.push({sample:n,rootKey:d!==void 0&&d>=0?d:p.rootKey,cents:c(nq.coarseTune)*100+c(nq.fineTune)+p.correction,loop:(f&3)==1||(f&3)==3,gain:10**(-Math.max(0,c(nq.attenuation))/200),pan:Math.max(-1,Math.min(1,c(nq.pan)/500)),attack:rq(c(nq.attack,-12e3)),hold:rq(c(nq.hold,-12e3)),decay:rq(c(nq.decay,-12e3)),sustain:10**(-Math.max(0,c(nq.sustain))/200),release:rq(c(nq.release,-12e3))})}}return l}return{voices:o,hasPreset:(e,t)=>a.has(`${e}:${t}`)||a.has(`0:${t}`),presetCount:a.size}}function fq(e){let t=new Set,n=[];for(let r of e)for(let e of $K(r)){let r=e.channel===9?128:e.bank,i=`${r}:${e.program}`;t.has(i)||(t.add(i),n.push({bank:r,program:e.program}))}return n}function pq(e){return[e&255,e>>8&255]}function mq(e){return[e&255,e>>8&255,e>>16&255,e>>24&255]}function hq(e){let t=[...e].map(e=>e.charCodeAt(0)&255).slice(0,20);return[...t,...Array(20-t.length).fill(0)]}function gq(e){return[...e].map(e=>e.charCodeAt(0))}function _q(e,t){let n=new Uint8Array(8+t.length+(t.length&1));return n.set(gq(e),0),new DataView(n.buffer).setUint32(4,t.length,!0),n.set(t,8),n}function vq(e){let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function yq(e,t){let n=vq([new Uint8Array(gq(e)),...t]);return vq([new Uint8Array(gq(`LIST`)),new Uint8Array(mq(n.length)),n])}function bq(e,t){let n=oq(iq(e)),r=new Map;for(let e=0;e<n.presets.length-1;e++)r.set(`${n.presets[e].bank}:${n.presets[e].preset}`,e);let i=new Set,a=[];for(let{bank:e,program:n}of t){let t=uq(r,e,n);t!==void 0&&!i.has(t)&&(i.add(t),a.push(t))}a.sort((e,t)=>e-t);let o=e=>{let t=n.samples[e];return!!t&&t.end>t.start&&!(t.type&32768)},s=(e,t,n)=>e.map(e=>e.oper===t?{oper:t,lo:n.get(e.amount)&255,hi:n.get(e.amount)>>8&255,amount:n.get(e.amount)}:e),c=[],l=new Map;{let e=new Set;for(let t of a){let r=n.presets[t].bag,i=n.presets[t+1]?.bag??n.presetBags.length-1;for(let t=r;t<i;t++){let r=sq(n.presetBags,n.presetGens,t);if(!r.some(e=>e.oper===nq.instrument))continue;let i=r.find(e=>e.oper===nq.instrument).amount;n.instruments[i+1]&&(e.has(i)||(e.add(i),c.push(i)))}}}let u=new Map(c.map((e,t)=>[e,t]));for(let e of c){let t=n.instruments[e].bag,r=n.instruments[e+1]?.bag??n.instBags.length-1,i=[];for(let e=t;e<r;e++){let t=sq(n.instBags,n.instGens,e);if(!t.some(e=>e.oper===nq.sampleId))continue;let r=t.find(e=>e.oper===nq.sampleId).amount;o(r)&&i.push(t)}l.set(e,i)}let d=[];{let e=new Set,t=r=>{if(e.has(r)||!o(r))return;e.add(r),d.push(r);let i=n.samples[r].link;i!==r&&t(i)};for(let e of c)for(let n of l.get(e))t(n.find(e=>e.oper===nq.sampleId).amount)}let f=new Map(d.map((e,t)=>[e,t])),p=e=>[...pq(e.oper),e.lo,e.hi],m=e=>[...pq(e),...pq(0)],h=[],g=[],_=[];for(let e of a){let t=n.presets[e],r=h.length,i=t.bag,a=n.presets[e+1]?.bag??n.presetBags.length-1;for(let e=i;e<a;e++){let t=sq(n.presetBags,n.presetGens,e);(e===i&&!t.some(e=>e.oper===nq.instrument)||t.some(e=>e.oper===nq.instrument))&&(h.push(g.length),g.push(...s(t,nq.instrument,u)))}_.push({name:t.name,preset:t.preset,bank:t.bank,bag:r})}h.push(g.length);let v=[],y=[],b=[];for(let e of c){let t=v.length,r=l.get(e),i=n.instruments[e].bag,a=n.instruments[e+1]?.bag??n.instBags.length-1;for(let e=i;e<a;e++){let t=sq(n.instBags,n.instGens,e);e===i&&!t.some(e=>e.oper===nq.sampleId)&&(v.push(y.length),y.push(...t))}for(let e of r)v.push(y.length),y.push(...s(e,nq.sampleId,f));b.push({name:n.instruments[e].name,bag:t})}v.push(y.length);let x=[],S=[];for(let e of d){let t=n.samples[e],r=S.length/2;for(let e=t.start;e<t.end;e++){let t=n.smpl[e];S.push(t&255,t>>8&255)}let i=f.get(e);x.push({...t,start:r,end:r+(t.end-t.start),loopStart:r+(t.loopStart-t.start),loopEnd:r+(t.loopEnd-t.start),link:f.get(t.link)??i})}let C=e=>[...hq(e.name),...pq(e.preset),...pq(e.bank),...pq(e.bag),...Array(12).fill(0)],ee=n.presets[n.presets.length-1],w=_q(`phdr`,[..._.flatMap(C),...C({name:ee?.name??`EOS`,preset:0,bank:0,bag:h.length-1})]),T=_q(`pbag`,h.flatMap(m)),E=_q(`pgen`,g.flatMap(p)),D=_q(`pmod`,Array(10).fill(0)),O=e=>[...hq(e.name),...pq(e.bag)],te=n.instruments[n.instruments.length-1],ne=_q(`inst`,[...b.flatMap(O),...O({name:te?.name??`EOS`,bag:v.length-1})]),k=_q(`ibag`,v.flatMap(m)),A=_q(`igen`,y.flatMap(p)),re=_q(`imod`,Array(10).fill(0)),ie=e=>[...hq(e.name),...mq(e.start),...mq(e.end),...mq(e.loopStart),...mq(e.loopEnd),...mq(e.rate),e.rootKey,e.correction&255,...pq(e.link),...pq(e.type)],ae={name:``,start:0,end:0,loopStart:0,loopEnd:0,rate:0,rootKey:0,correction:0,link:0,type:0},oe=_q(`shdr`,[...x.flatMap(ie),...ie(ae)]),se=yq(`sdta`,[_q(`smpl`,S)]),j=yq(`pdta`,[w,T,D,E,ne,k,re,A,oe]),ce=vq([new Uint8Array(gq(`sfbk`)),...n.info?[n.info]:[],se,j]);return vq([new Uint8Array(gq(`RIFF`)),new Uint8Array(mq(ce.length)),ce]).buffer}var xq=22050,Sq=.35,Cq=480;function wq(e,t={}){return Oq(Eq(e,t))}async function Tq(e,t={}){return TU(Oq,[Eq(JK(e),{soundfont:t.soundFontBytes?dq(t.soundFontBytes):null,sampleRate:t.sampleRate,gain:t.gain,maxDuration:t.maxDuration})])}function Eq(e,t){let n=t.sampleRate??xq,r=t.gain??Sq,i=t.maxDuration??Cq;if(!(n>0))throw Error(`render sample rate must be positive`);if(!(r>=0))throw Error(`render gain must not be negative`);if(!(i>0))throw Error(`render max duration must be positive`);let a=$K(e).filter(e=>e.time<i);if(a.length===0)throw Error(`MIDI file has no notes`);let o=t.soundfont??null,s=new Map;return{notes:a.map(e=>({...e,frequency:eq(e.note),voices:o?Dq(o,s,e):void 0})),loopStart:QK(e),sampleRate:n,gain:r,maxDuration:i}}function Dq(e,t,n){let r=n.channel===9?128:n.bank,i=`${r}:${n.program}:${n.note}:${n.velocity>>3}`,a=t.get(i);return a||(a=e.voices(r,n.program,n.note,n.velocity),t.set(i,a)),a}function Oq(e){let{sampleRate:t,gain:n,maxDuration:r}=e,i=e.notes,a=i.reduce((e,t)=>Math.max(e,t.time+t.duration),0),o=Math.min(r,a+1.5),s=Math.max(1,Math.ceil(o*t)),c=new Float32Array(s),l=new Float32Array(s),u=Math.min(e.loopStart??0,Math.max(0,o-.1));function d(e){let t=(Math.max(-1,Math.min(1,e))+1)*Math.PI/4;return[Math.cos(t),Math.sin(t)]}function f(e,t,n,r,i,a,o,s){let c=i.sample.data;if(c.length===0)return;let l=2**(((r.note-i.rootKey)*100+i.cents+(r.bend??0)*100)/1200)*i.sample.rate/n;if(!(l>0))return;let u=r.time+r.duration,f=Math.max(.002,i.attack),p=f+i.hold+Math.min(i.decay,30),m=Math.max(.03,Math.min(i.release,4)),h=c.length/i.sample.rate,g=r.channel===9?Math.max(u,r.time+Math.min(2,h)):Math.max(u,r.time+f),_=g-r.time,v=a*i.gain,y=v*i.sustain,[b,x]=d(r.pan+i.pan),S=i.loop&&i.sample.loopEnd>i.sample.loopStart,C=i.sample.loopEnd-i.sample.loopStart,ee=Math.min(s,o+Math.ceil((g+m+.02-r.time)*n)),w=0;for(let a=o;a<ee;a++){let o=a/n-r.time,s;s=o<f?o/f*v:o<f+i.hold?v:o<p?v+(y-v)*((o-f-i.hold)/Math.max(1e-6,p-f-i.hold)):o<_?y:o<_+m?y*(1-(o-_)/m):0,S&&w>=i.sample.loopEnd&&(w=i.sample.loopStart+(w-i.sample.loopStart)%C);let u=Math.floor(w),d=Math.min(1,Math.max(0,w-u)),h;if(!S&&w>=c.length||u<0)h=0;else{let e=c[Math.min(u,c.length-1)];h=e+(c[Math.min(u+1,c.length-1)]-e)*d}e[a]+=h*s*b,t[a]+=h*s*x,w+=l}}function p(e){return e<8?{wave:`triangle`,attack:.005,decay:1.2,sustain:.25,release:.2,detune:0}:e<16?{wave:`sine`,attack:.003,decay:.8,sustain:.1,release:.5,detune:0}:e<24?{wave:`square`,attack:.01,decay:.1,sustain:.7,release:.08,detune:0,cutoff:2500}:e<32?{wave:`sawtooth`,attack:.004,decay:.6,sustain:.15,release:.15,detune:0,cutoff:3e3}:e<40?{wave:`triangle`,attack:.005,decay:.4,sustain:.5,release:.1,detune:0}:e<56?{wave:`sawtooth`,attack:.12,decay:.2,sustain:.8,release:.3,detune:6,cutoff:3500}:e<80?{wave:`sawtooth`,attack:.04,decay:.15,sustain:.75,release:.12,detune:0,cutoff:4500}:e<88?{wave:`square`,attack:.01,decay:.1,sustain:.8,release:.1,detune:0,cutoff:3800}:e<104?{wave:`sawtooth`,attack:.25,decay:.3,sustain:.7,release:.5,detune:8,cutoff:2200}:{wave:`triangle`,attack:.005,decay:.5,sustain:.2,release:.2,detune:0}}function m(e,t){switch(e){case`sine`:return Math.sin(t);case`square`:return Math.sin(t)>=0?1:-1;case`sawtooth`:{let e=t/(2*Math.PI);return 2*(e-Math.floor(e))-1}case`triangle`:{let e=t/(2*Math.PI);return 4*Math.abs(e-Math.floor(e)-.5)-1}}}function h(e,t,n,r,i,a){return e<t?e/t:e<t+n?1-(1-r)*((e-t)/Math.max(1e-6,n)):e<i?r:e<i+a?r*(1-(e-i)/a):0}function g(e,t){let n=Math.imul(e^t,2654435761)>>>0;return n=Math.imul(n^n>>>15,2246822519)>>>0,n=Math.imul(n^n>>>13,3266489917)>>>0,n^=n>>>16,(n>>>0)/4294967295*2-1}function _(e,t,n,r,i,a,o){if(r.channel===9){v(e,t,n,r,i,a,o);return}let s=p(r.program),c=r.frequency*2**((s.detune+(r.bend??0)*100)/1200),l=Math.max(r.duration,s.attack+.01),u=Math.max(.02,s.release),f=Math.min(o,a+Math.ceil((l+u+.02)*n)),[g,_]=d(r.pan),y=s.cutoff!==void 0,b=y?1-Math.exp(-2*Math.PI*Math.min(s.cutoff,c*8+800)/n):0,x=0,S=0,C=2*Math.PI*c/n;for(let o=a;o<f;o++){let a=o/n-r.time,c=m(s.wave,S);S+=C,x=y?x+b*(c-x):c;let d=i*h(a,s.attack,s.decay,s.sustain,l,u);e[o]+=x*d*g,t[o]+=x*d*_}}function v(e,t,n,r,i,a,o){let[s,c]=d(r.pan),l=r.note*7919+a;if(r.note===35||r.note===36||r.note<45){let l=i*1.4,u=Math.min(o,a+Math.ceil(.27*n)),d=0;for(let i=a;i<u;i++){let a=i/n-r.time,o=a<.12?150*(45/150)**(a/.12):45;d+=2*Math.PI*o/n;let u=l*(.001/l)**Math.min(1,a/.22);e[i]+=Math.sin(d)*u*s,t[i]+=Math.sin(d)*u*c}return}let u=r.note===38||r.note===40,f=u?.16:r.note>=49?.5:.06,p=i*(u?.9:.5),m=Math.min(o,a+Math.ceil((f+.02)*n));for(let i=a;i<m;i++){let o=i/n-r.time,u=p*(.001/p)**Math.min(1,o/f),d=g(l,i-a)*u;e[i]+=d*s,t[i]+=d*c}}for(let e of i){let r=Math.floor(e.time*t);if(r>=s)continue;let i=n*Math.max(.02,e.velocity/127*e.gain),a=e.voices??[];if(a.length>0)for(let n of a)f(c,l,t,e,n,i,r,s);else _(c,l,t,e,i,r,s)}return{sampleRate:t,left:c,right:l,loopStart:u,loopEnd:o,duration:o}}function kq(e,t,n,r,i,a){let o=e.createBufferSource();o.buffer=n,o.playbackRate.value=i;let s=e.createGain();s.gain.value=r;let c=null;return typeof e.createStereoPanner==`function`?(c=e.createStereoPanner(),c.pan.value=a,o.connect(s),s.connect(c),c.connect(t)):(o.connect(s),s.connect(t)),{source:o,gain:s,panner:c}}var Aq=class{constructor(e,t){this.source=null,this.gainNode=null,this.pannerNode=null,this.buffer=null,this.params={volume:1,pitch:1,pan:0},this.loopRegion=null,this.repeat=!0,this.startedAt=0,this.offset=0,this.context=e,this.destination=t??e.destination}get isPlaying(){return this.source!==null}get duration(){return this.buffer?.duration??0}play(e,t={}){this.stop();let n=t.volume??1,r=t.pitch??1,i=t.pan??0,{source:a,gain:o,panner:s}=kq(this.context,this.destination,e,n,r,i),c=t.loop??null,l=t.repeat??!0;if(a.loop=l,c&&(a.loopStart=c.start,a.loopEnd=c.end),!l){let e=a;a.onended=()=>{this.source===e&&this.clearNodes()}}this.source=a,this.gainNode=o,this.pannerNode=s,this.buffer=e,this.params={volume:n,pitch:r,pan:i},this.loopRegion=c,this.repeat=l,this.offset=Math.min(Math.max(0,t.pos??0),Math.max(0,e.duration-.001)),this.startedAt=this.context.currentTime,a.start(0,this.offset)}update(e){if(e.volume!==void 0&&(this.params.volume=e.volume),e.pitch!==void 0&&(this.params.pitch=e.pitch),e.pan!==void 0&&(this.params.pan=e.pan),!this.source||!this.gainNode)return;let t=this.context.currentTime;this.gainNode.gain.setTargetAtTime(this.params.volume,t,.02),this.source.playbackRate.value=this.params.pitch,this.pannerNode&&(this.pannerNode.pan.value=this.params.pan)}stop(e=0){let t=this.position(),n=this.source,r=this.gainNode;if(this.clearNodes(),this.offset=t,n)try{if(e>0&&r){let t=this.context.currentTime;r.gain.cancelScheduledValues(t),r.gain.setValueAtTime(r.gain.value,t),r.gain.linearRampToValueAtTime(0,t+e),n.stop(t+e+.02)}else n.stop()}catch{}}position(){if(!this.source||!this.buffer)return this.offset;let e=Math.max(0,this.context.currentTime-this.startedAt)*this.params.pitch,t=this.offset+e;if(this.repeat&&this.duration>0){let e=this.loopRegion?.start??0,n=this.loopRegion?.end??this.buffer.duration;n>e&&t>=n&&(t=e+(t-e)%(n-e))}return t}seek(e){this.restore({...this.state(),pos:e})}state(){return{...this.params,pos:this.position()}}restore(e){let t=this.buffer;this.update({volume:e.volume,pitch:e.pitch,pan:e.pan}),t&&this.source?this.play(t,{volume:e.volume,pitch:e.pitch,pan:e.pan,pos:e.pos,loop:this.loopRegion,repeat:this.repeat}):this.offset=Math.max(0,e.pos)}clearNodes(){this.source&&(this.source.onended=null),this.source=null,this.gainNode=null,this.pannerNode=null}};function jq(e,t,n,r){let i=Number(e);return Math.min(n,Math.max(t,Number.isFinite(i)?i:r))}var Mq=class e{constructor(e,t={}){this.tracks={bgm:null,bgs:null},this.saved={bgm:null,bgs:null},this.requests={bgm:0,bgs:0},this.me=null,this.meToken=0,this.suspendedBgm=null,this.seNodes=new Set,this.mixerLevels={bgm:{volume:1,muted:!1},bgs:{volume:1,muted:!1},me:{volume:1,muted:!1},se:{volume:1,muted:!1}},this.context=e,this.destination=t.destination??e.destination,this.load=t.load??(async()=>null);let n=()=>{let t=e.createGain();return t.connect(this.destination),t};this.kindGains={bgm:n(),bgs:n(),me:n(),se:n()},this.bgmChannel=new Aq(e,this.kindGains.bgm),this.bgsChannel=new Aq(e,this.kindGains.bgs)}setMixer(e,t){let n=this.mixerLevels[e];t.volume!==void 0&&(n.volume=jq(t.volume,0,1,1)),t.muted!==void 0&&(n.muted=t.muted),this.kindGains[e].gain.value=n.muted?0:n.volume}mixer(e){return{...this.mixerLevels[e]}}playBgm(e){return this.playLoop(`bgm`,e)}playBgs(e){return this.playLoop(`bgs`,e)}stopBgm(){this.requests.bgm++,this.tracks.bgm=null,this.suspendedBgm=null,this.bgmChannel.stop()}stopBgs(){this.requests.bgs++,this.tracks.bgs=null,this.bgsChannel.stop()}fadeOutBgm(e=1){this.requests.bgm++,this.tracks.bgm=null,this.suspendedBgm=null,this.bgmChannel.stop(Math.max(0,e))}fadeOutBgs(e=1){this.requests.bgs++,this.tracks.bgs=null,this.bgsChannel.stop(Math.max(0,e))}currentTrack(e){let t=this.tracks[e];if(t){let n=e===`bgm`?this.bgmChannel:this.bgsChannel;return{...t,pos:n.isPlaying?n.position():t.pos}}return e===`bgm`?this.suspendedBgm:null}saveBgm(){return this.saved.bgm=this.currentTrack(`bgm`),this.saved.bgm}saveBgs(){return this.saved.bgs=this.currentTrack(`bgs`),this.saved.bgs}replayBgm(){return this.saved.bgm?this.playBgm(this.saved.bgm):Promise.resolve()}replayBgs(){return this.saved.bgs?this.playBgs(this.saved.bgs):Promise.resolve()}async playMe(t){let n=e.normalize(t),r=++this.meToken;if(this.stopMeNodes(),!n.name)return;let i=await this.load(`me`,n.name);if(r!==this.meToken||!i)return;let a=this.currentTrack(`bgm`);a&&(this.suspendedBgm=a,this.requests.bgm++,this.bgmChannel.stop(),this.tracks.bgm=null);let{source:o}=kq(this.context,this.kindGains.me,i.buffer,n.volume/100,n.pitch/100,n.pan/100);this.me={source:o,token:r},o.onended=()=>{this.me?.token===r&&this.finishMe()},o.start(0)}stopMe(e=!0){this.stopMeNodes(),e&&this.finishMe()}async playSe(t){let n=e.normalize(t);if(!n.name)return;let r=await this.load(`se`,n.name);if(!r)return;let{source:i}=kq(this.context,this.kindGains.se,r.buffer,n.volume/100,n.pitch/100,n.pan/100),a={source:i};this.seNodes.add(a),i.onended=()=>{this.seNodes.delete(a)},i.start(0)}stopSe(){for(let e of this.seNodes){e.source.onended=null;try{e.source.stop()}catch{}}this.seNodes.clear()}stopAll(){this.requests.bgm++,this.requests.bgs++,this.tracks.bgm=null,this.tracks.bgs=null,this.suspendedBgm=null,this.bgmChannel.stop(),this.bgsChannel.stop(),this.stopMeNodes(),this.stopSe()}snapshot(){return{bgm:this.currentTrack(`bgm`),bgs:this.currentTrack(`bgs`),savedBgm:this.saved.bgm,savedBgs:this.saved.bgs}}restore(e){e&&typeof e==`object`&&(this.saved.bgm=e.savedBgm??null,this.saved.bgs=e.savedBgs??null,e.bgm&&this.playBgm(e.bgm),e.bgs&&this.playBgs(e.bgs))}static normalize(e){return{name:String(e?.name||``),volume:jq(e?.volume,0,100,90),pitch:jq(e?.pitch,10,400,100),pan:jq(e?.pan,-100,100,0),pos:Math.max(0,Number(e?.pos)||0)}}async playLoop(t,n){let r=t===`bgm`?this.bgmChannel:this.bgsChannel,i=e.normalize(n);if(!i.name){this.requests[t]++,this.tracks[t]=null,t===`bgm`&&(this.suspendedBgm=null),r.stop();return}let a=this.tracks[t];if(a&&a.name===i.name&&!(i.pos>0)){this.tracks[t]={...i,pos:0},r.update({volume:i.volume/100,pitch:i.pitch/100,pan:i.pan/100});return}if(t===`bgm`&&this.me){this.requests.bgm++,this.suspendedBgm=i,this.tracks.bgm=null,r.stop();return}let o=++this.requests[t];r.stop(),this.tracks[t]={...i,pos:0};let s=await this.load(t,i.name);if(o===this.requests[t]){if(!s){this.tracks[t]=null;return}r.play(s.buffer,{volume:i.volume/100,pitch:i.pitch/100,pan:i.pan/100,pos:i.pos,loop:s.loop??null})}}stopMeNodes(){let e=this.me;if(this.me=null,e){e.source.onended=null;try{e.source.stop()}catch{}}}finishMe(){this.me=null;let e=this.suspendedBgm;this.suspendedBgm=null,e&&!this.tracks.bgm&&this.playBgm(e)}},Nq=65536;function Pq(e){let t=Iq(e.subarray(0,Nq));if(!t)return null;let n=new DataView(t.buffer,t.byteOffset,t.byteLength),r=new TextDecoder(`utf-8`),i=7,a=()=>{if(i+4>t.length)return null;let e=n.getUint32(i,!0);return i+=4,i+e<=t.length?e:null},o=a();if(o===null||(i+=o,i+4>t.length))return null;let s=n.getUint32(i,!0);i+=4;let c=null,l=null;for(let e=0;e<s;e++){let e=a();if(e===null)break;let n=r.decode(t.subarray(i,i+e));i+=e;let o=n.indexOf(`=`);if(o<0)continue;let s=n.slice(0,o).toUpperCase(),u=/^\d+$/.test(n.slice(o+1))?Number(n.slice(o+1)):null;u!==null&&(s===`LOOPSTART`?c=u:s===`LOOPLENGTH`&&(l=u))}return c===null?null:{loopStart:c,loopLength:l}}function Fq(e,t,n){if(!e||!(t>0))return null;let r=e.loopStart/t,i=e.loopLength?(e.loopStart+e.loopLength)/t:n;return r>=0&&i>r&&r<n?{start:r,end:Math.min(i,n)}:null}function Iq(e){let t=[3,118,111,114,98,105,115],n=[],r=0;for(;r+27<=e.length;){if(e[r]!==79||e[r+1]!==103||e[r+2]!==103||e[r+3]!==83)return null;let i=e[r+26],a=r+27+i;if(a>e.length)return null;let o=a;for(let a=0;a<i;a++){let i=e[r+27+a];if(o+i>e.length)return null;for(let t=0;t<i;t++)n.push(e[o+t]);if(o+=i,i<255){if(t.every((e,t)=>n[t]===e))return Uint8Array.from(n);n=[]}}r=o}return null}function Lq(e,t={}){let n=t.refDistance??1,r=t.maxDistance??1/0,i=t.rolloff??1;if(!(e>n))return 1;if(!(e<r))return 0;let a=(n/e)**+i;return Math.max(0,Math.min(1,a))}function Rq(e,t){let n=t.x-e.x,r=t.y-e.y,i=Math.hypot(n,r);if(i===0)return 0;let a=Math.sin(e.facing),o=Math.cos(e.facing),s=(n*a+r*o)/i;return Math.max(-1,Math.min(1,s))}var zq=class{constructor(e={}){this.x=e.x??0,this.y=e.y??0,this.facing=e.facing??0}moveTo(e,t){this.x=e,this.y=t}face(e){this.facing=e}},Bq=class{constructor(e,t={}){this.sound=e,this.x=t.x??0,this.y=t.y??0,this.falloff={refDistance:t.refDistance,maxDistance:t.maxDistance,rolloff:t.rolloff}}moveTo(e,t){this.x=e,this.y=t}gainTo(e){return Lq(Math.hypot(this.x-e.x,this.y-e.y),this.falloff)}panTo(e){return Rq(e,this)}playFor(e){let t=this.gainTo(e);return t<=0?0:(this.sound.play(t),t)}};BK(),UK();var Vq=256,Hq=64,Uq=10,Wq=2,Gq=.05,Kq=4,qq=96;function Jq(e,t){let n=e.length,r=0;for(let i=1;i<n;i++){let a=n>>1;for(;r&a;)r^=a,a>>=1;if(r^=a,i<r){let n=e[i];e[i]=e[r],e[r]=n,n=t[i],t[i]=t[r],t[r]=n}}for(let r=2;r<=n;r<<=1){let i=-2*Math.PI/r,a=Math.cos(i),o=Math.sin(i),s=r>>1;for(let i=0;i<n;i+=r){let n=1,r=0;for(let c=0;c<s;c++){let l=i+c,u=l+s,d=e[u]*n-t[u]*r,f=e[u]*r+t[u]*n;e[u]=e[l]-d,t[u]=t[l]-f,e[l]+=d,t[l]+=f;let p=n*a-r*o;r=n*o+r*a,n=p}}}}function Yq(e,t){if(e.length===0||t<=0)return[];let n=Vq/2,r=new Float32Array(e.length+256);r.set(e,n);let i=new Float64Array(Vq);for(let e=0;e<Vq;e++)i[e]=.5-.5*Math.cos(2*Math.PI*e/255);let a=new Float64Array(Vq),o=new Float64Array(Vq),s=new Float64Array(Vq/2),c=[],l=[],u=0;for(let e=0;e+Vq<=r.length;e+=Hq){let t=0;for(let n=0;n<Vq;n++)a[n]=r[e+n]*i[n],o[n]=0,t+=a[n]*a[n];l.push(u===0?t===0?0:1/0:t/u-1),u=t,Jq(a,o);let n=0;for(let e=0;e<Vq/2;e++){let t=Math.hypot(a[e],o[e]),r=t-s[e];r>0&&(n+=r),s[e]=t}c.push(n)}let d=[],f=-1/0;for(let e=0;e<c.length;e++){let r=Math.max(0,e-Uq),i=Math.min(c.length-1,e+Uq),a=i-r+1,o=0;for(let e=r;e<=i;e++)o+=c[e];o/=a;let s=0;for(let e=r;e<=i;e++)s+=(c[e]-o)**2;let u=o+Wq*Math.sqrt(s/a);if(c[e]<=0||c[e]<u||l[e]<Gq&&(e===0||l[e-1]<Gq)||e>0&&c[e-1]>c[e]||e+1<c.length&&c[e+1]>=c[e]||e-f<Kq)continue;let p=(e*Hq+n-qq)/t;d.push(Math.max(0,p)),f=e}return d}fK();var Xq=`extracted`,Zq=[4,4],Qq=120,$q=120,eJ=480;function tJ(e){let t=[...e].sort((e,t)=>e-t),n=t.length>>1;return t.length%2==1?t[n]:(t[n-1]+t[n])/2}function nJ(e){return Math.round(tJ(e))}function rJ(e){for(let t of e.events)if(t.type===`tempo`)return Math.round(6e7/t.microsecondsPerQuarter*100)/100;return Qq}function iJ(e){return e.events.filter(e=>e.type===`noteOn`)}function aJ(e){return iJ(e).map(e=>e.velocity)}function oJ(e,t,n,r,i){let a=e.map((e,t)=>({subdivisionIndex:t,timeOffsetTicks:e.time.length>0?nJ(e.time):0,velocityFactor:e.velocity.length>0?i(e):1}));return{name:Xq,timeSignature:[...Zq],ppq:n,tempoBpm:r,subdivision:t,offsets:a}}var sJ=class{async extractFromMidiPair(e,t,n=`16n`){let r=t.ticksPerQuarter,i=lK(r,n),a=cK(Zq,n),o=r/e.ticksPerQuarter,s=iJ(e).map(e=>({channel:e.channel,note:e.note,tick:e.tick*o,velocity:e.velocity})),c=new Set,l=[];for(let e of iJ(t)){let t=-1,n=1/0;for(let r=0;r<s.length;r++){let i=s[r];if(c.has(r)||i.channel!==e.channel||i.note!==e.note)continue;let a=Math.abs(i.tick-e.tick);a<n&&(n=a,t=r)}t<0||n>i/2||(c.add(t),l.push({slotTick:s[t].tick,delta:e.tick-s[t].tick,factor:s[t].velocity>0?e.velocity/s[t].velocity:null}))}let u=Array.from({length:a},()=>({time:[],velocity:[]}));for(let e of l){let t=(Math.round(e.slotTick/i)%a+a)%a;u[t].time.push(e.delta),e.factor!==null&&u[t].velocity.push(e.factor)}return oJ(u,n,r,rJ(t),e=>tJ(e.velocity))}async extractFromSingleMidi(e,t=`16n`){let n=e.ticksPerQuarter,r=lK(n,t),i=cK(Zq,t),a=Array.from({length:i},()=>({time:[],velocity:[]}));for(let t of iJ(e)){let e=Math.round(t.tick/r)*r,n=(Math.round(e/r)%i+i)%i;a[n].time.push(t.tick-e),a[n].velocity.push(t.velocity)}let o=tJ(aJ(e));return oJ(a,t,n,rJ(e),e=>o<=0?1:tJ(e.velocity)/o)}async extractFromAudioBuffer(e,t=`16n`,n=$q){if(!Number.isFinite(n)||n<=0)throw Error(`tempoBpm must be greater than 0, got ${String(n)}`);let r=[];for(let t=0;t<e.numberOfChannels;t++)r.push(e.getChannelData(t));let i=new Float32Array(e.length);for(let e of r)for(let t=0;t<e.length;t++)i[t]+=e[t]/r.length;let a=Yq(i,e.sampleRate);if(a.length===0)throw Error(`no onsets detected in the buffer - a groove needs audible attacks, and this audio has none`);let o=eJ,s=lK(o,t),c=cK(Zq,t),l=n*o/60,u=Array.from({length:c},()=>({time:[],velocity:[]}));for(let e of a){let t=e*l,n=Math.round(t/s)*s;u[(Math.round(n/s)%c+c)%c].time.push(t-n)}return oJ(u,t,o,n,()=>1)}};fK();var cJ=`mwg-groove:`,lJ=36,uJ=64,dJ=[`8n`,`16n`,`32n`],fJ=new TextEncoder;function pJ(e){throw Error(`the ${e} format is not shipped: it is an undocumented proprietary container, and a guessed reader could load a different groove than the file holds`)}function mJ(e){return[...e].map(e=>e.charCodeAt(0)&127)}function hJ(e){let t=[e&127],n=e>>>7;for(;n>0;)t.unshift(n&127|128),n>>>=7;return t}function gJ(e,t){return[255,e,...hJ(t.length),...t]}function _J(e){uK(e);let{name:t,timeSignature:n,ppq:r,subdivision:i,offsets:a}=e,o=cK(n,i),s=lK(r,i);if(r>32767)throw Error(`groove template "${t}": ppq ${r} does not fit MIDI's 15-bit division`);if(lJ+o-1>127)throw Error(`groove template "${t}": ${o} slots need pitches up to ${lJ+o-1}, past MIDI's top note of 127`);let c=Math.round(6e7/e.tempoBpm);if(c<1||c>16777215)throw Error(`groove template "${t}": tempoBpm ${e.tempoBpm} does not fit MIDI's three-byte tempo (${c} microseconds)`);a.forEach((e,n)=>{if(Math.abs(e.timeOffsetTicks)>=s)throw Error(`groove template "${t}": slot ${n} is offset by ${e.timeOffsetTicks} ticks, outside the +/-${s} the MIDI encoding's one-slot anchor can tell from a slot shift`);let r=Math.round(uJ*e.velocityFactor);if(r<1||r>127)throw Error(`groove template "${t}": slot ${n} has velocityFactor ${e.velocityFactor}, outside the ${1/uJ} to ${127/uJ} the MIDI encoding can store at ${1/uJ} per velocity unit`)});let l=[{tick:0,bytes:gJ(81,[c>>16&255,c>>8&255,c&255])},{tick:0,bytes:gJ(88,[n[0],Math.log2(n[1]),24,8])},{tick:0,bytes:gJ(1,[...fJ.encode(cJ+t)])}];a.forEach((e,t)=>{let n=s*(t+1)+e.timeOffsetTicks,r=n+Math.max(1,Math.floor(s/4));l.push({tick:n,bytes:[144,lJ+t,Math.round(uJ*e.velocityFactor)]}),l.push({tick:r,bytes:[128,lJ+t,0]})}),l.sort((e,t)=>e.tick-t.tick);let u=[],d=0;for(let e of l)u.push(...hJ(e.tick-d),...e.bytes),d=e.tick;return u.push(0,255,47,0),new Uint8Array([...mJ(`MThd`),0,0,0,6,0,0,0,1,r>>8&255,r&255,...mJ(`MTrk`),u.length>>>24&255,u.length>>>16&255,u.length>>>8&255,u.length&255,...u])}function vJ(e,t){for(let n of dJ)try{if(cK(e,n)===t)return n}catch{}throw Error(`a ${t}-slot groove in ${e[0]}/${e[1]} is not one of the 8n, 16n or 32n grids`)}function yJ(e){let t=typeof e==`string`?fJ.encode(e):e,n=new DataView(t.buffer,t.byteOffset,t.byteLength),r=0,i=(e,n)=>{if(r+e>t.length)throw Error(`truncated MIDI file while reading ${n}`)},a=(e,n)=>{i(e,n);let a=``;for(let n=0;n<e;n++)a+=String.fromCharCode(t[r+n]);return r+=e,a},o=e=>(i(1,e),t[r++]),s=e=>{i(2,e);let t=n.getUint16(r);return r+=2,t},c=e=>{i(4,e);let t=n.getUint32(r);return r+=4,t},l=e=>{let t=0;for(let n=0;n<4;n++){let n=o(e);if(t=t<<7|n&127,!(n&128))return t}throw Error(`a variable-length quantity in ${e} runs past four bytes`)};if(a(4,`the file header`)!==`MThd`)throw Error(`not a Standard MIDI File: the MThd header is missing`);let u=c(`the header length`);if(u<6)throw Error(`MThd is ${u} bytes, expected at least 6`);let d=s(`the format`),f=s(`the track count`),p=s(`the division`);if(r+=u-6,d>1)throw Error(`MIDI format ${d} is not a file this reader understands`);if(p&32768)throw Error(`SMPTE time in the division carries no tick grid to read a groove from`);if(f!==1)throw Error(`an mwg groove file holds one track, this one has ${f}`);if(a(4,`the track header`)!==`MTrk`)throw Error(`the MTrk track header is missing`);let m=c(`the track length`),h=r+m;if(h>t.length)throw Error(`truncated MIDI file: the track runs past the end of the data`);let g=0,_=0,v=null,y=null,b=null,x=!1,S=new Map;for(;r<h;){g+=l(`a delta time`);let e=t[r];if(e<128){if(_===0)throw Error(`data at tick ${g} follows a delta time with no running status to read it under`);e=_}else r++,e<240&&(_=e);if(e===255){let e=o(`a meta type`),n=l(`a meta length`);i(n,`a meta event`);let a=r;if(e===81&&n===3)v=t[a]<<16|t[a+1]<<8|t[a+2];else if(e===88&&n>=2)y=[t[a],2**t[a+1]];else if((e===1||e===3)&&n>0){let e=``;for(let r=0;r<n;r++)e+=String.fromCharCode(t[a+r]);e.startsWith(cJ)&&(b=e.slice(11))}r+=n,e===47&&(x=!0),_=0;continue}if(e===240||e===247){r+=l(`a sysex length`),_=0;continue}let n=e&240;if(n===144||n===128){let e=o(`a note number`),t=o(`a note velocity`);if(n===144&&t>0){if(S.has(e))throw Error(`pitch ${e} carries more than one note-on, which no groove encodes`);S.set(e,{tick:g,velocity:t})}}else if(n===176||n===224)i(2,`a controller or bend event`),r+=2;else if(n===192||n===208)i(1,`a program or channel-aftertouch event`),r+=1;else throw Error(`unexpected status byte 0x${e.toString(16)} at tick ${g}`)}if(!x)throw Error(`the track has no end-of-track meta, so the file is incomplete`);if(b===null)throw Error(`no ${cJ} text meta: this file was not written as a groove`);if(y===null)throw Error(`no time-signature meta: an mwg groove file always carries one`);let C=p,ee=S.size,w=vJ(y,ee),T=lK(C,w),E=[];for(let e=0;e<ee;e++){let t=S.get(lJ+e);if(!t)throw Error(`slot ${e} is missing: expected a note on pitch ${lJ+e}`);E.push({subdivisionIndex:e,timeOffsetTicks:t.tick-T*(e+1),velocityFactor:t.velocity/uJ})}let D={name:b,timeSignature:y,ppq:C,tempoBpm:v===null?120:Math.round(6e7/v*100)/100,subdivision:w,offsets:E};return uK(D),D}function bJ(e){let t=typeof e==`string`?e:new TextDecoder().decode(e),n;try{n=JSON.parse(t)}catch(e){throw Error(`not valid JSON: ${e instanceof Error?e.message:String(e)}`)}if(typeof n!=`object`||!n||Array.isArray(n))throw Error(`a groove JSON export must be an object`);return uK(n),n}var xJ=class{async exportFormat(e,t){switch(t){case`json`:return uK(e),JSON.stringify(e,null,2);case`midi`:return _J(e);case`ableton-agr`:case`reaper-groove`:return pJ(t);default:throw Error(`unknown groove format: ${String(t)}`)}}async importFormat(e,t){switch(t){case`json`:return bJ(e);case`midi`:return yJ(e);case`ableton-agr`:case`reaper-groove`:return pJ(t);default:throw Error(`unknown groove format: ${String(t)}`)}}},SJ=l({AudioBus:()=>Mq,AudioListener:()=>zq,Channel:()=>Aq,GrooveConverter:()=>xJ,GrooveExtractor:()=>sJ,GrooveHumanizer:()=>HK,HumanizerFactory:()=>WK,LiteHumanizer:()=>zK,MidiPlayer:()=>tq,Music:()=>eK,Orchestrator:()=>tK,Sound:()=>$G,SoundSource:()=>Bq,assertGrooveTemplate:()=>uK,audioGain:()=>Lq,audioPan:()=>Rq,collectSoundFontUsage:()=>fq,createAudio:()=>ZG,humanizeMidi:()=>GK,loopRegionFromTags:()=>Fq,midiLoopStart:()=>QK,noteToFrequency:()=>eq,onCaption:()=>QG,parseMidi:()=>JK,parseSoundFont:()=>dq,parseVorbisLoopTags:()=>Pq,playTone:()=>rK,renderMidiToBuffer:()=>wq,renderMidiToBufferAsync:()=>Tq,scheduleMidi:()=>$K,subdivisionCount:()=>cK,subsetSoundFont:()=>bq,synthesizeTone:()=>nK});fK();function CJ(e,t){if(!Number.isSafeInteger(t)||t<0)throw RangeError(`Turn budget must be a non-negative safe integer`);let n=0;for(;n<t;){if(e.finished())return{status:`finished`,steps:n};let t=e.scheduler.peek();if(t===null)return{status:`empty`,steps:n};if(e.needsInput(t))return{status:`input`,actor:t,steps:n};let r=e.act(t);if(r!==null){if(!Number.isFinite(r)||r<0)throw RangeError(`Action cost must be finite and non-negative, or null`);e.scheduler.spend(r)}n++}return{status:`limit`,steps:n}}function wJ(e){if(e?.version!==1||typeof e.observationVersion!=`string`||!e.observationVersion.length)throw TypeError(`unsupported neural model or observation version`);if(!Array.isArray(e.layers)||!e.layers.length||e.layers.length>32)throw RangeError(`a neural model needs 1..32 layers`);let t=0;for(let n=0;n<e.layers.length;n++){let r=e.layers[n];if(!r||!Number.isInteger(r.inputSize)||!Number.isInteger(r.outputSize)||r.inputSize<1||r.outputSize<1||r.inputSize>4096||r.outputSize>4096)throw RangeError(`neural layer dimensions must be integers in 1..4096`);if(t+=r.inputSize*r.outputSize+r.outputSize,t>1e6)throw RangeError(`neural model exceeds one million parameters`);if(n&&e.layers[n-1].outputSize!==r.inputSize)throw RangeError(`neural layer dimensions do not connect`);if(!Array.isArray(r.weights)||!Array.isArray(r.biases)||r.weights.length!==r.inputSize*r.outputSize||r.biases.length!==r.outputSize||!Array.from(r.weights).every(Number.isFinite)||!Array.from(r.biases).every(Number.isFinite))throw TypeError(`neural weights and biases must be finite and match layer dimensions`)}let n=e.layers.map(e=>({...e,weights:Float64Array.from(e.weights),biases:Float64Array.from(e.biases),buffer:new Float64Array(e.outputSize)})),r=(e,t)=>{if(e.length!==n[0].inputSize)throw TypeError(`neural input must be finite and match the model`);for(let t=0;t<e.length;t++)if(!Number.isFinite(e[t]))throw TypeError(`neural input must be finite`);let r=n[n.length-1];if(t&&t.length!==r.outputSize)throw RangeError(`neural output buffer has the wrong size`);let i=e;for(let e=0;e<n.length;e++){let t=n[e];for(let r=0;r<t.outputSize;r++){let a=t.biases[r];for(let e=0;e<t.inputSize;e++)a+=t.weights[r*t.inputSize+e]*i[e];if(!Number.isFinite(a))throw RangeError(`neural activation overflow`);t.buffer[r]=e===n.length-1?a:Math.max(0,a)}i=t.buffer}let a=t??new Float64Array(r.outputSize);return a.set(r.buffer),a},i=new Float64Array(n[n.length-1].outputSize);return{predict:r,select(e,t){let n=e.mask;if(n&&(n.length!==i.length||!Array.from(n).every(e=>typeof e==`boolean`)))throw TypeError(`neural action mask must contain one boolean per output`);r(e.input,i);let a=null;for(let e=0;e<i.length;e++)(!n||n[e])&&(a===null||i[e]>i[a])&&(a=e);if(a===null||!t)return a;let o=t();if(!Number.isFinite(o)||o<0||o>=1)throw RangeError(`sampling random must return a value in [0, 1)`);let s=0;for(let e=0;e<i.length;e++)(!n||n[e])&&(s+=Math.exp(i[e]-i[a]));let c=o*s;for(let e=0;e<i.length;e++)if((!n||n[e])&&(c-=Math.exp(i[e]-i[a]),c<0))return e;return a}}}function TJ(e,t,n){let r=Function(`return (${e});`)()(t);return n.map(e=>r.predict(e))}var EJ=class{constructor(e){this.evaluator=wJ(e),this.model=structuredClone(e)}predict(e,t){return this.evaluator.predict(e,t)}selectAction(e,t){return this.evaluator.select(e,t)}exportModel(){return structuredClone(this.model)}behavior(e,t,n,r=!1){if(t.length!==this.model.layers[this.model.layers.length-1].outputSize)throw RangeError(`neural action mapping must match output size`);let i=structuredClone(t);return{id:e,decide:e=>{e.checkpoint();let t=this.selectAction(n(e.perception),r?e.random:void 0);return t===null?null:structuredClone(i[t])}}}predictBatchAsync(e,t={}){let n=this.model.layers[0].inputSize,r=this.model.layers[this.model.layers.length-1].outputSize;if(e.length>65536||e.length*Math.max(n,r)>1e6)return Promise.reject(RangeError(`neural batch exceeds its observation or value limit`));for(let t of e)if(!t||t.length!==n)return Promise.reject(TypeError(`neural batch inputs must match the model`));return TU(TJ,[wJ.toString(),this.model,e],t)}};_e();var DJ=class{get truncated(){return!this.terminated&&this.steps>=this.maxSteps}constructor(e,t,n=j){if(this.steps=0,this.terminated=!1,this.ready=!1,this.agentCount=0,this.rules=e,this.Random=n,this.random=new this.Random(0),!Number.isInteger(t.maxSteps)||t.maxSteps<1||t.maxSteps>1e6)throw RangeError(`training maxSteps must be in 1..1000000`);if(typeof e.observationVersion!=`string`||!e.observationVersion.length)throw TypeError(`training requires an observation version`);this.maxSteps=t.maxSteps,this.observationVersion=e.observationVersion}reset(e){if(!Number.isInteger(e)||e<0||e>4294967295)throw RangeError(`training seed must be uint32`);this.random=new this.Random(e),this.state=this.rules.initial(this.random),this.steps=0,this.terminated=this.rules.finished?.(this.state)??!1,this.ready=!0;let t=this.observations();return this.agentCount=t.length,{observations:t,rewards:t.map(()=>0),terminated:this.terminated,truncated:!1}}step(e){if(!this.ready||this.terminated||this.truncated)throw Error(`training episode needs reset before step`);let t=this.observations();if(e.length!==this.agentCount)throw RangeError(`training action count must match the agent roster`);for(let n=0;n<e.length;n++){let r=e[n],i=t[n].mask;if(r===null?!i||i.some(Boolean):!Number.isInteger(r)||r<0||i&&(r>=i.length||!i[r]))throw RangeError(`training action is not legal`)}let n=structuredClone(this.state),r=this.rules.command(this.state,e),i=this.rules.rule(this.state,r,this.random),a=Array.from(this.rules.rewards(n,r,i));if(a.length!==this.agentCount||!a.every(Number.isFinite))throw TypeError(`training rewards must be finite and match the agent roster`);this.state=i.state,this.steps++,this.terminated=i.status===`finished`;let o=this.observations();if(o.length!==this.agentCount)throw RangeError(`training agent roster changed during an episode`);return{observations:o,rewards:a,terminated:this.terminated,truncated:this.truncated}}snapshot(){if(!this.ready)throw Error(`training environment needs reset before snapshot`);return structuredClone({version:1,observationVersion:this.observationVersion,state:this.state,seed:this.random.seed,random:this.random.getState().map(e=>e>>>0),steps:this.steps,maxSteps:this.maxSteps,terminated:this.terminated,truncated:this.truncated})}restore(e){if(e.version!==1||e.observationVersion!==this.observationVersion||e.maxSteps!==this.maxSteps)throw TypeError(`training snapshot version, schema or step limit does not match`);if(!Number.isInteger(e.steps)||e.steps<0||e.steps>this.maxSteps||!Number.isInteger(e.seed)||e.seed<0||e.seed>4294967295||!Array.isArray(e.random)||e.random.length!==4||!e.random.every(e=>Number.isInteger(e)&&e>=0&&e<=4294967295)||!e.random.some(e=>e!==0)||typeof e.terminated!=`boolean`||typeof e.truncated!=`boolean`||e.terminated&&e.truncated||e.truncated!==(!e.terminated&&e.steps===this.maxSteps))throw TypeError(`invalid training snapshot`);this.state=structuredClone(e.state),this.random=new this.Random(e.seed),this.random.setState(e.random),this.steps=e.steps,this.terminated=e.terminated,this.ready=!0;let t=this.observations();return this.agentCount=t.length,{observations:t,rewards:t.map(()=>0),terminated:this.terminated,truncated:this.truncated}}observations(){let e=structuredClone(Array.from(this.rules.observe(this.state)));if(!e.length||e.length>4096)throw RangeError(`training requires 1..4096 agents`);for(let t of e)if(!t.input.length||t.input.length>4096||!Array.from(t.input).every(Number.isFinite)||t.mask&&(!t.mask.length||t.mask.length>4096||!Array.from(t.mask).every(e=>typeof e==`boolean`)))throw TypeError(`invalid training observation`);return e}};function OJ(e,t,n){return kJ(n),AJ(e,t,n,{Generator:j,createNeuralEvaluator:wJ})}function kJ(e){let t=e.trajectoryLimit??0;if(!e.seeds.length||e.seeds.length>1e4||!Array.from(e.seeds).every(e=>Number.isInteger(e)&&e>=0&&e<=4294967295)||!Number.isInteger(t)||t<0||t*e.seeds.length>1e4)throw RangeError(`rollouts require 1..10000 uint32 seeds and at most 10000 stored transitions`)}function AJ(e,t,n,r){if(t.observationVersion!==e.observationVersion)throw TypeError(`model observation schema does not match environment`);let i=n.trajectoryLimit??0,a=r.createNeuralEvaluator(t);return Array.from(n.seeds,t=>{if(n.signal?.aborted)throw n.signal.reason;let o=new r.Generator((t^2654435769)>>>0),s=e.reset(t),c=s.rewards.map(()=>0),l=[],u=0;for(;!s.terminated&&!s.truncated;){if(n.signal?.aborted)throw n.signal.reason;let t=s.observations.map(e=>a.select(e,n.sample?()=>o.float():void 0)),r=e.step(t);for(let e=0;e<c.length;e++)if(c[e]+=r.rewards[e],!Number.isFinite(c[e]))throw RangeError(`training cumulative reward overflow`);l.length<i&&l.push({before:s,actions:t,after:r}),s=r,u++}return{seed:t,steps:u,rewards:c,terminated:s.terminated,truncated:s.truncated,trajectory:l}})}function jJ(e,t,n,r){let i=Function(`return (${e[0]});`)(),a=Function(`return (${e[1]});`)(),o=Function(`return (${e[2]});`)(),s=class extends o{constructor(e,t){super(e,t,i)}};return Function(`return (${e[3]});`)()(Function(`return (${e[4]});`)()({TrainingEnvironment:s},t),n,r,{Generator:i,createNeuralEvaluator:a})}async function MJ(e,t,n,r){let i=r.jobs??4;if(!Number.isInteger(i)||i<1||i>64)throw RangeError(`rollout jobs must be in 1..64`);if(r.signal?.aborted)throw r.signal.reason;let a=r.trajectoryLimit??0;kJ(r),wJ(n);let o=new AbortController,s=()=>o.abort(r.signal?.reason);r.signal?.addEventListener(`abort`,s,{once:!0});let c=[j.toString(),wJ.toString(),DJ.toString(),AJ.toString(),e.toString()],l=Math.min(i,r.seeds.length);try{return(await Promise.all(Array.from({length:l},(e,i)=>{let s=Math.floor(i*r.seeds.length/l),u=Math.floor((i+1)*r.seeds.length/l),d=r.seeds.slice(s,u);return TU(jJ,[c,t,n,{seeds:d,sample:r.sample,trajectoryLimit:a}],{signal:o.signal,timeout:r.timeout})}))).flat()}finally{o.abort(),r.signal?.removeEventListener(`abort`,s)}}function NJ(e,t){let n=[...t.actions];if(!n.length||n.some(e=>typeof e!=`string`))throw TypeError(`imitation needs the recorded action names in policy order`);let r=fn(t.events),i=e.reset(t.seed);if(i.observations.length!==1)throw Error(`imitation trains the recorded player alone: the environment must expose one agent`);let a=[],o=i,s=0;for(let t of r){if(o.terminated||o.truncated)break;let r=n.indexOf(t.action);if(r<0)throw Error(`a recorded action ${JSON.stringify(t.action)} is not in the action list`);a.push({observation:o.observations[0],action:r,frame:t.frame}),o=e.step([r]),s++}return{samples:a,steps:s,terminated:o.terminated,truncated:o.truncated}}function PJ(e,t,n){let r=e.reset(n.seed),i=r.rewards.map(()=>0),a=[],o=0;for(;!r.terminated&&!r.truncated;){let n=t(r.observations);if(!Array.isArray(n)||n.length!==r.observations.length)throw RangeError(`the seeded-run chooser must return one action per agent`);a.push([...n]);let s=e.step(n);for(let e=0;e<i.length;e++)if(i[e]+=s.rewards[e],!Number.isFinite(i[e]))throw RangeError(`seeded-run cumulative reward overflow`);r=s,o++}return{seed:n.seed,steps:o,actions:a,rewards:i,terminated:r.terminated,truncated:r.truncated}}function FJ(e){let t=e.state,n=e.status??`ready`,r=[],i=0;for(let a of e.commands){if(n===`finished`)break;let o=e.step(t,a,e.random);t=o.state,n=o.status;for(let e of o.events)r.push(e);i++}return{state:t,events:r,status:n,processedCommands:i}}var IJ=class e{constructor(e){if(this._reminders=[],this._results={},this.levels=new Map(e.levels.map(e=>[e.id,e])),this.levels.size!==e.levels.length)throw Error(`campaign level ids must be unique`);if(!this.levels.has(e.start))throw Error(`unknown campaign start level: ${e.start}`);this._currentLevel=e.start,this._state=Ht(e.state,`campaign state`)}get currentLevel(){return this._currentLevel}get state(){return structuredClone(this._state)}get reminders(){return[...this._reminders]}get results(){return structuredClone(this._results)}playCurrent(){if(!this._currentLevel)throw Error(`campaign has no current level`);let e=this.levels.get(this._currentLevel);return this.completeCurrent(e.run(this.state,{levelId:e.id}))}completeCurrent(e){if(!this._currentLevel)throw Error(`campaign has no current level`);let t=this._currentLevel,n=Ht(e.state,`level result state`),r=e.result===void 0?void 0:Ht(e.result,`level result`);if(this._state=n,r!==void 0&&(this._results[t]=r),this._reminders=[...e.reminders??[]],e.outcome!==`completed`)this._currentLevel=null;else if(e.next===void 0)throw Error(`campaign level ${t} did not choose a next level`);else{if(e.next!==null&&!this.levels.has(e.next))throw Error(`unknown campaign transition: ${t} -> ${e.next}`);this._currentLevel=e.next}return{...e,state:this.state}}snapshot(){return{currentLevel:this._currentLevel,state:this.state,reminders:this.reminders,results:this.results}}static restore(t,n){let r=t.currentLevel??n.levels[0]?.id;if(!r)throw Error(`campaign restore requires at least one level`);let i=new e({levels:n.levels,start:r,state:t.state});return i._currentLevel=t.currentLevel,i._reminders=[...t.reminders],i._results=Ht(t.results,`snapshot.results`),i}};_e();function LJ(e){let t=new j(e.seed);return{...FJ({state:Ht(e.initialState,`initialState`),commands:e.commands,status:e.status,random:t,step:e.step}),seed:e.seed,random:t.getState()}}_e();function RJ(e,t,n){let r=zJ.restore({...e,journal:[]},n),i=e=>({valid:!1,checked:e.index,state:r.state,journal:r.journal.toJSON(),mismatch:e});for(let e=0;e<t.length;e++){let n=t[e];if(n.sequence!==e)return i({index:e,action:n.action,expectedEvents:n.events,actualEvents:[],reason:`sequence`});let a;try{a=r.dispatch(n.action)}catch(t){return i({index:e,action:n.action,expectedEvents:n.events,actualEvents:[],reason:`execution`,error:t instanceof Error?t.message:String(t)})}if(Ir(a.events)!==Ir(n.events))return i({index:e,action:n.action,expectedEvents:n.events,actualEvents:a.events,reason:`events`})}return n.expectedFinalState!==void 0&&Ir(r.state)!==Ir(n.expectedFinalState)?i({index:t.length,action:t.at(-1)?.action,expectedEvents:[],actualEvents:[],reason:`final-state`}):{valid:!0,checked:t.length,state:r.state,journal:r.journal.toJSON()}}var zJ=class e{constructor(e){this._state=e.state,this._scheduler=e.scheduler,this.random=e.random,this.rule=e.rule,this.actorId=e.actorId,this.recordJournal=e.journal!==null,this.journal=e.journal??new Cn,this.actorOf=e.history?.actorOf??null,this.history=e.history?new Er(e.history):null,this.history&&this.history.push(this.historySnapshot())}get scheduler(){return this._scheduler}get state(){return this._state}dispatch(e){let t=this.random.getState(),n=this.rule(this._state,e,{random:this.random,scheduler:this._scheduler}),r;try{r=this.history?Ht(n.state,`state`):null,this.recordJournal&&this.journal.append(e,n.events)}catch(e){throw this.random.setState(t),e}return this._state=n.state,n.cost!=null&&this._scheduler.spend(n.cost),this.history&&this.history.push(this.historySnapshot(r)),n}get canUndo(){return this.history?.canUndo??!1}get canRedo(){return this.history?.canRedo??!1}undo(){if(!this.history||!this.actorOf)return null;let e=this.history.undo();return e?(this.restoreCheckpoint(e),this.snapshot()):null}redo(){if(!this.history||!this.actorOf)return null;let e=this.history.redo();return e?(this.restoreCheckpoint(e),this.snapshot()):null}snapshot(e=1){return{version:e,state:this._state,scheduler:this.scheduler.toJSON(this.actorId),random:this.random.getState(),journal:this.journal.toJSON()}}static restore(t,n){let r=n.random??new j;r.setState(t.random);let i=fB.restore(t.scheduler,n.actorOf);return new e({state:t.state,scheduler:i,random:r,journal:Cn.fromJSON(t.journal??[]),rule:n.rule,actorId:n.actorId})}historySnapshot(e=Ht(this._state,`state`)){return{...this.snapshot(),state:e}}restoreCheckpoint(e){if(!this.actorOf)throw Error(`simulation history needs actorOf to restore a checkpoint`);this._state=structuredClone(e.state),this._scheduler=fB.restore(e.scheduler,this.actorOf),this.random.setState(e.random),this.journal.replace(e.journal??[])}},BJ=class e{constructor(e){this.followUps=[],this.runtime=e.runtime,this.queue=new Mr({play:e.play}),this.followUpOf=e.followUp}get locked(){return this.queue.isBusy}submit(e){return this.locked?null:this.commit(e)}update(e){this.queue.update(e),this.drainFollowUps()}cancel(){this.queue.clear(),this.followUps=[]}snapshot(e=1){return this.runtime.snapshot(e)}static restore(t,n){let r=zJ.restore(t,{rule:n.rule,actorOf:n.actorOf,actorId:n.actorId});return new e({runtime:r,play:n.play,followUp:n.followUp})}commit(e){let t=this.runtime.dispatch(e);return this.queue.enqueue(t.events),this.followUpOf&&this.followUps.push(...this.followUpOf(t)),this.drainFollowUps(),t}drainFollowUps(){for(;!this.queue.isBusy&&this.followUps.length>0;){let e=this.followUps.shift();this.commit(e)}}},VJ=class{constructor(e){this.saves=new Rt(e)}save(e,t,n){this.saves.save(e,{campaign:t.campaign.snapshot(),world:t.world,simulation:t.simulation?t.simulation.snapshot():null},n)}load(e){return this.saves.load(e)?.state??null}list(){return this.saves.list()}delete(e){this.saves.delete(e)}},HJ=l({Campaign:()=>IJ,CampaignSave:()=>VJ,EventPresentation:()=>BJ,Scheduler:()=>fB,SimulationRuntime:()=>zJ,TrainingEnvironment:()=>DJ,advanceToInput:()=>CJ,imitationFromReplay:()=>NJ,runHeadlessScenario:()=>LJ,runRollouts:()=>OJ,runRolloutsAsync:()=>MJ,runScenario:()=>FJ,runSeededEpisode:()=>PJ,validateSimulationReplay:()=>RJ}),UJ=d(c(((e,t)=>{(function(n,r){typeof e==`object`&&t!==void 0?t.exports=r():typeof define==`function`&&define.amd?define(r):n.JSON5=r()})(e,(function(){"use strict";function e(e,t){return t={exports:{}},e(t,t.exports),t.exports}var t=e(function(e){var t=e.exports=typeof window<`u`&&window.Math==Math?window:typeof self<`u`&&self.Math==Math?self:Function(`return this`)();typeof __g==`number`&&(__g=t)}),n=e(function(e){var t=e.exports={version:`2.6.5`};typeof __e==`number`&&(__e=t)});n.version;var r=function(e){return typeof e==`object`?e!==null:typeof e==`function`},i=function(e){if(!r(e))throw TypeError(e+` is not an object!`);return e},a=function(e){try{return!!e()}catch{return!0}},o=!a(function(){return Object.defineProperty({},"a",{get:function(){return 7}}).a!=7}),s=t.document,c=r(s)&&r(s.createElement),l=function(e){return c?s.createElement(e):{}},u=!o&&!a(function(){return Object.defineProperty(l(`div`),"a",{get:function(){return 7}}).a!=7}),d=function(e,t){if(!r(e))return e;var n,i;if(t&&typeof(n=e.toString)==`function`&&!r(i=n.call(e))||typeof(n=e.valueOf)==`function`&&!r(i=n.call(e))||!t&&typeof(n=e.toString)==`function`&&!r(i=n.call(e)))return i;throw TypeError(`Can't convert object to primitive value`)},f=Object.defineProperty,p={f:o?Object.defineProperty:function(e,t,n){if(i(e),t=d(t,!0),i(n),u)try{return f(e,t,n)}catch{}if(`get`in n||`set`in n)throw TypeError(`Accessors not supported!`);return`value`in n&&(e[t]=n.value),e}},m=function(e,t){return{enumerable:!(e&1),configurable:!(e&2),writable:!(e&4),value:t}},h=o?function(e,t,n){return p.f(e,t,m(1,n))}:function(e,t,n){return e[t]=n,e},g={}.hasOwnProperty,_=function(e,t){return g.call(e,t)},v=0,y=Math.random(),b=function(e){return`Symbol(${e===void 0?``:e})_${(++v+y).toString(36)}`},x=e(function(e){var r=`__core-js_shared__`,i=t[r]||(t[r]={});(e.exports=function(e,t){return i[e]||(i[e]=t===void 0?{}:t)})(`versions`,[]).push({version:n.version,mode:`global`,copyright:`© 2019 Denis Pushkarev (zloirock.ru)`})})(`native-function-to-string`,Function.toString),S=e(function(e){var r=b(`src`),i=`toString`,a=(``+x).split(i);n.inspectSource=function(e){return x.call(e)},(e.exports=function(e,n,i,o){var s=typeof i==`function`;s&&(_(i,`name`)||h(i,`name`,n)),e[n]!==i&&(s&&(_(i,r)||h(i,r,e[n]?``+e[n]:a.join(String(n)))),e===t?e[n]=i:o?e[n]?e[n]=i:h(e,n,i):(delete e[n],h(e,n,i)))})(Function.prototype,i,function(){return typeof this==`function`&&this[r]||x.call(this)})}),C=function(e){if(typeof e!=`function`)throw TypeError(e+` is not a function!`);return e},ee=function(e,t,n){if(C(e),t===void 0)return e;switch(n){case 1:return function(n){return e.call(t,n)};case 2:return function(n,r){return e.call(t,n,r)};case 3:return function(n,r,i){return e.call(t,n,r,i)}}return function(){return e.apply(t,arguments)}},w=`prototype`,T=function(e,r,i){var a=e&T.F,o=e&T.G,s=e&T.S,c=e&T.P,l=e&T.B,u=o?t:s?t[r]||(t[r]={}):(t[r]||{})[w],d=o?n:n[r]||(n[r]={}),f=d[w]||(d[w]={}),p,m,g,_;for(p in o&&(i=r),i)m=!a&&u&&u[p]!==void 0,g=(m?u:i)[p],_=l&&m?ee(g,t):c&&typeof g==`function`?ee(Function.call,g):g,u&&S(u,p,g,e&T.U),d[p]!=g&&h(d,p,_),c&&f[p]!=g&&(f[p]=g)};t.core=n,T.F=1,T.G=2,T.S=4,T.P=8,T.B=16,T.W=32,T.U=64,T.R=128;var E=T,D=Math.ceil,O=Math.floor,te=function(e){return isNaN(e=+e)?0:(e>0?O:D)(e)},ne=function(e){if(e==null)throw TypeError(`Can't call method on `+e);return e},k=function(e){return function(t,n){var r=String(ne(t)),i=te(n),a=r.length,o,s;return i<0||i>=a?e?``:void 0:(o=r.charCodeAt(i),o<55296||o>56319||i+1===a||(s=r.charCodeAt(i+1))<56320||s>57343?e?r.charAt(i):o:e?r.slice(i,i+2):(o-55296<<10)+(s-56320)+65536)}}(!1);E(E.P,`String`,{codePointAt:function(e){return k(this,e)}}),n.String.codePointAt;var A=Math.max,re=Math.min,ie=function(e,t){return e=te(e),e<0?A(e+t,0):re(e,t)},ae=String.fromCharCode,oe=String.fromCodePoint;E(E.S+E.F*(!!oe&&oe.length!=1),`String`,{fromCodePoint:function(e){for(var t=arguments,n=[],r=arguments.length,i=0,a;r>i;){if(a=+t[i++],ie(a,1114111)!==a)throw RangeError(a+` is not a valid code point`);n.push(a<65536?ae(a):ae(((a-=65536)>>10)+55296,a%1024+56320))}return n.join(``)}}),n.String.fromCodePoint;var se={Space_Separator:/[\u1680\u2000-\u200A\u202F\u205F\u3000]/,ID_Start:/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/,ID_Continue:/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/},j={isSpaceSeparator:function(e){return typeof e==`string`&&se.Space_Separator.test(e)},isIdStartChar:function(e){return typeof e==`string`&&(e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`||e===`$`||e===`_`||se.ID_Start.test(e))},isIdContinueChar:function(e){return typeof e==`string`&&(e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`||e>=`0`&&e<=`9`||e===`$`||e===`_`||e===`‌`||e===`‍`||se.ID_Continue.test(e))},isDigit:function(e){return typeof e==`string`&&/[0-9]/.test(e)},isHexDigit:function(e){return typeof e==`string`&&/[0-9A-Fa-f]/.test(e)}},ce,le,ue,de,fe,pe,me,he,ge,_e=function(e,t){ce=String(e),le=`start`,ue=[],de=0,fe=1,pe=0,me=void 0,he=void 0,ge=void 0;do me=xe(),ke[le]();while(me.type!==`eof`);return typeof t==`function`?ve({"":ge},``,t):ge};function ve(e,t,n){var r=e[t];if(typeof r==`object`&&r){if(Array.isArray(r))for(var i=0;i<r.length;i++){var a=String(i),o=ve(r,a,n);o===void 0?delete r[a]:Object.defineProperty(r,a,{value:o,writable:!0,enumerable:!0,configurable:!0})}else for(var s in r){var c=ve(r,s,n);c===void 0?delete r[s]:Object.defineProperty(r,s,{value:c,writable:!0,enumerable:!0,configurable:!0})}}return n.call(e,t,r)}var M,N,ye,be,P;function xe(){for(M=`default`,N=``,ye=!1,be=1;;){P=Se();var e=Ce[M]();if(e)return e}}function Se(){if(ce[de])return String.fromCodePoint(ce.codePointAt(de))}function F(){var e=Se();return e===`
1384
+ `,n);return[n,r===-1?this.text.length:r]}moveCaretLine(e,t=!1){let[n]=this.lineRange(this.caretLine),r=this.goalColumn??this.caretIndex-n,[i,a]=this.lineRange(this.caretLine+e);this.setCaret(i+Math.min(r,a-i),t),this.goalColumn=r}limit(e){return this.maxLength!==void 0&&e.length>this.maxLength?e.slice(0,this.maxLength):e}},KL=class e extends Y{constructor(t){super(),this.onClick=new p,this.onPress=new p,this.onRelease=new p,this.state=`idle`,this.themeListener=()=>this.draw(),this.width_=t.width,this.height_=t.height,this.disabled_=t.disabled??!1,this.skin=t.skin,this.labelOptions=t.label??{};let n=Q();this.background=e.createBackground(this.skin,n),this.addChild(this.background),this.icon=t.icon??null,this.icon&&this.addChild(this.icon),this.labelText=t.text===void 0?null:new sF({align:`center`,...this.labelOptions,text:t.text}),this.labelText&&this.addChild(this.labelText),t.onClick&&this.onClick.add(t.onClick),t.onPress&&this.onPress.add(t.onPress),t.onRelease&&this.onRelease.add(t.onRelease),this.eventMode=`static`,this.on(`pointerover`,()=>this.setState(`hover`)),this.on(`pointerout`,()=>this.setState(`idle`)),this.on(`pointerdown`,()=>{this.setState(`pressed`),this.onPress.dispatch()}),this.on(`pointerup`,()=>{let e=this.state===`pressed`;this.setState(`hover`),e&&(this.onRelease.dispatch(),this.onClick.dispatch())}),this.on(`pointerupoutside`,()=>{let e=this.state===`pressed`;this.setState(`idle`),e&&this.onRelease.dispatch()}),this.setState(this.disabled_?`disabled`:`idle`),$.add(this.themeListener)}static createBackground(e,t){return e?new eI(e.texture,{border:e.border}):t.panel?new eI(t.panel,{border:t.panelBorder}):new bE}resize(e,t){this.width_=e,this.height_=t,this.draw()}setText(e){e===void 0?(this.labelText?.destroy(),this.labelText=null):this.labelText?this.labelText.setText(e):(this.labelText=new sF({align:`center`,...this.labelOptions,text:e}),this.addChild(this.labelText)),this.layoutContent()}get disabled(){return this.disabled_}setDisabled(e){this.disabled_=e,this.setState(e?`disabled`:`idle`)}setState(e){this.disabled_&&e!==`disabled`||(this.state=e,this.cursor=this.disabled_?`default`:`pointer`,this.eventMode=this.disabled_?`none`:`static`,this.draw())}layoutContent(){let e=Q().direction===`rtl`;if(this.icon&&!this.labelText){this.icon.x=Math.round((this.width_-this.icon.width)/2),this.icon.y=Math.round((this.height_-this.icon.height)/2);return}if(this.icon&&this.labelText){let t=Q().spacing,n=this.icon.width+t+this.labelText.width,r=Math.round((this.width_-n)/2);this.icon.x=e?r+this.labelText.width+t:r,this.icon.y=Math.round((this.height_-this.icon.height)/2),this.labelText.x=e?r:r+this.icon.width+t,this.labelText.y=Math.round((this.height_-this.labelText.height)/2);return}this.labelText&&(this.labelText.x=Math.round((this.width_-this.labelText.width)/2),this.labelText.y=Math.round((this.height_-this.labelText.height)/2))}draw(){let e=Q(),t=this.state===`pressed`?10066329:this.state===`hover`?14540253:this.state===`disabled`?7829367:16777215;if(this.background instanceof eI)this.background.resize(this.width_,this.height_),this.background.tint=this.skin?.tints?.[this.state]??t;else{let t=this.state===`pressed`?e.color.selection:e.color.panelFill;this.background.clear().roundRect(0,0,this.width_,this.height_,4).fill({color:t,alpha:this.state===`disabled`?.5:1}).stroke({color:e.color.panelBorder,width:1})}this.labelText?.setColor(this.disabled_?e.color.textDim:this.labelOptions.color??e.color.text),this.icon&&(this.icon.alpha=this.disabled_?.4:1),this.layoutContent()}destroy(e){$.remove(this.themeListener),super.destroy(e)}},qL=e=>e.split(``).map(e=>({label:e})),JL={rows:[qL(`QWERTYUIOP`),qL(`ASDFGHJKL`),qL(`ZXCVBNM`),qL(`1234567890`),[{label:`Bksp`,action:`backspace`},{label:`Left`,action:`left`},{label:`Right`,action:`right`},{label:`Space`,text:` `,span:3},{label:`OK`,action:`confirm`},{label:`Esc`,action:`cancel`}]]};function YL(e){e.action===void 0?we(e.text??e.label):Te(e.action)}function XL(e,t){let n=[],r=0;for(let i of e.rows){let e=i.reduce((e,t)=>e+(t.span??1),0),a=(t.width-t.gap*(e-1))/e,o=0;for(let e of i){let i=e.span??1,s=a*i+t.gap*(i-1);n.push({key:e,x:o,y:r,width:s,height:t.keyHeight}),o+=s+t.gap}r+=t.keyHeight+t.gap}return n}var ZL=class extends Y{constructor(e,t){super();let n=Q().spacing,r=Math.max(Q().font.size*2,18),i=0;for(let a of XL(e,{width:t.width,keyHeight:r,gap:n})){let e=new KL({width:a.width,height:a.height,text:a.key.label,onClick:()=>YL(a.key)});e.position.set(a.x,a.y),this.addChild(e),i=Math.max(i,a.y+a.height)}this.laidOutHeight=i}get contentHeight(){return this.laidOutHeight}},QL=.5,$L=class extends iI{constructor(e){super({width:e.width,height:e.height,title:e.title,modal:!0,closable:!1,dims:e.dims,blocker:e.blocker??!0,anchor:e.anchor??`center`}),this.preview=``,this.promptError=null,this.keyboard=null,this.messageLabel=null,this.caretBar=new bE,this.measurer=new sF,this.canMeasureCaret=typeof document<`u`,this.blinkOn=!0,this.blinkElapsed=0,this.promptThemeListener=()=>this.restylePrompt(),this.textListener=e=>!this.closed&&(this.edit(()=>this.model.insert(e)),!0),this.compositionListener=e=>!this.closed&&(e.phase===`end`?this.edit(()=>{this.preview=``,this.model.insert(e.text)}):(this.preview=e.phase===`start`?``:e.text,this.render()),!0),this.model=new GL({value:e.initialValue??``,maxLength:e.maxLength}),this.validate=e.validate,this.onConfirm=e.onConfirm,this.onCancel=e.onCancel,this.announce=e.announce??!0,this.announcer=e.announcer??rI;let t=Q();this.lineHeight=t.font.size*t.font.lineHeight;let n=t.spacing;e.message!==void 0&&(this.messageLabel=new sF({text:e.message}),this.content.addChild(this.messageLabel)),this.valueY=this.messageLabel?this.lineHeight+n:0,this.valueLabel=new sF,this.valueLabel.y=this.valueY,this.content.addChild(this.valueLabel),this.previewLabel=new sF({color:t.color.textDim}),this.previewLabel.y=this.valueY+this.lineHeight+n,this.content.addChild(this.previewLabel),this.errorLabel=new sF({color:t.color.textHighlight}),this.errorLabel.y=this.previewLabel.y+this.lineHeight+n,this.content.addChild(this.errorLabel),this.content.addChild(this.caretBar),e.keyboard&&(this.keyboard=new ZL(e.keyboard,{width:this.contentWidth}),this.keyboard.y=this.errorLabel.y+this.lineHeight+n,this.content.addChild(this.keyboard),this.resize(e.width,e.height+this.keyboard.contentHeight+n)),Se.add(this.textListener),F.add(this.compositionListener),$.add(this.promptThemeListener),this.render(),this.announce&&e.message!==void 0&&this.announcer.announce(e.message)}get value(){return this.model.value}get caretIndex(){return this.model.caret}get error(){return this.promptError}handleAction(e){if(this.delegate)return super.handleAction(e);if(this.closed)return!1;switch(e){case`left`:return this.model.moveCaret(-1),this.render(),!0;case`right`:return this.model.moveCaret(1),this.render(),!0;case`backspace`:return this.edit(()=>this.model.backspace()),!0;case`delete`:return this.edit(()=>this.model.deleteForward()),!0;case`confirm`:return this.confirm(),!0;case`cancel`:return this.onCancel?.(),this.close(),!0;default:return!1}}update(e){this.blinkElapsed+=e,!(this.blinkElapsed<QL)&&(this.blinkElapsed=0,this.blinkOn=!this.blinkOn,this.caretBar.visible=this.blinkOn&&this.canMeasureCaret)}destroy(e){Se.remove(this.textListener),F.remove(this.compositionListener),$.remove(this.promptThemeListener),this.measurer.destroy(),super.destroy(e)}edit(e){let t=this.model.value;e(),this.model.value!==t&&(this.promptError=null),this.render()}confirm(){let e=this.validate?.(this.model.value)??null;if(e){this.promptError=e,this.render(),this.announce&&this.announcer.announce(e,{assertive:!0});return}this.onConfirm(this.model.value),this.close()}restylePrompt(){let e=Q();this.previewLabel.setColor(e.color.textDim),this.errorLabel.setColor(e.color.textHighlight),this.render()}render(){this.valueLabel.setText(this.model.value),this.measurer.setText(this.model.value.slice(0,this.model.caret));let e=0;if(this.canMeasureCaret)try{e=this.measurer.width}catch{this.canMeasureCaret=!1}this.caretBar.clear().rect(this.valueLabel.x+e,this.valueY,2,this.lineHeight).fill({color:Q().color.text}),this.caretBar.visible=this.blinkOn&&this.canMeasureCaret,this.previewLabel.setText(this.preview),this.previewLabel.visible=this.preview.length>0,this.errorLabel.setText(this.promptError??``),this.errorLabel.visible=this.promptError!==null}},eR=/[A-Za-z0-9]/;function tR(e,t){let{lineHeight:n,columnHeight:r}=t,i=t.rotate??eR,a=[],o=0,s=0;for(let t of e){if(t===`
1385
+ `){o++,s=0;continue}s*n>=r&&(o++,s=0);let e=i.test(t),c=o===0?0:-o*n;a.push({char:t,x:e?c-n/2:c,y:e?s*n+n/2:s*n,rotate:e}),s++}return a}var nR=class extends Y{constructor(e){super(),this.themeListener=e=>this.build(e),this.opts=e,this.build(Q()),$.add(this.themeListener)}build(e){this.removeChildren().forEach(e=>e.destroy());let t=this.opts.size??e.font.size,n=Math.ceil(t*e.font.lineHeight),r=tR(this.opts.text,{lineHeight:n,columnHeight:this.opts.columnHeight,rotate:this.opts.rotate});for(let n of r){let r=new wA({text:n.char,style:{fontFamily:e.font.family,fontSize:t,fill:this.opts.color??e.color.text}});n.rotate&&(r.anchor.set(.5),r.rotation=Math.PI/2),r.x=n.x,r.y=n.y,this.addChild(r)}}destroy(e){$.remove(this.themeListener),super.destroy(e)}};function rR(e,t=0,n=1){return n>t?Math.max(0,Math.min(1,(e-t)/(n-t))):0}function iR(e,t=0,n=1,r=0){let i=t+Math.max(0,Math.min(1,e))*(n-t);if(!(r>0))return i;let a=(String(r).split(`.`)[1]??``).length,o=t+Math.round((i-t)/r)*r;return Number(Math.max(t,Math.min(n,o)).toFixed(a))}var aR=class extends Y{constructor(e){super(),this.onChange=new p,this.track=new bE,this.fill=new bE,this.knob=new bE,this.dragging=!1,this.themeListener=()=>this.draw(),this.handleDown=e=>{this.disabled_||(this.dragging=!0,this.setFraction(this.fractionAt(this.toLocal(e.global).x)))},this.handleMove=e=>{this.dragging&&!this.disabled_&&this.setFraction(this.fractionAt(this.toLocal(e.global).x))},this.handleUp=()=>{this.dragging=!1},this.width_=e.width,this.height_=e.height??6,this.knobSize=e.knobSize??Math.max(12,this.height_*2),this.min=e.min??0,this.max=e.max??1,this.step=e.step??0,this.value_=this.snap(e.value??this.min),this.disabled_=e.disabled??!1,this.addChild(this.track),this.addChild(this.fill),this.addChild(this.knob),this.draw(),this.eventMode=`static`,this.cursor=`pointer`,this.on(`pointerdown`,this.handleDown),this.on(`pointermove`,this.handleMove),this.on(`pointerup`,this.handleUp),this.on(`pointerupoutside`,this.handleUp),$.add(this.themeListener)}get value(){return this.value_}get fraction(){return rR(this.value_,this.min,this.max)}get disabled(){return this.disabled_}setDisabled(e){this.disabled_=e,this.cursor=e?`default`:`pointer`,this.draw()}setValue(e){let t=this.snap(e);if(t===this.value_){this.draw();return}this.value_=t,this.draw(),this.onChange.dispatch(t)}setFraction(e){this.setValue(iR(e,this.min,this.max,this.step))}resize(e,t){this.width_=e,this.height_=t,this.draw()}get trackLength(){return Math.max(0,this.width_-this.knobSize)}snap(e){return iR(rR(e,this.min,this.max),this.min,this.max,this.step)}fractionAt(e){return this.trackLength>0?Math.max(0,Math.min(1,(e-this.knobSize/2)/this.trackLength)):0}draw(){let e=Q(),t=this.disabled_?e.color.textDim:e.color.textHighlight,n=e.color.panelFill,r=(this.knobSize-this.height_)/2;this.track.clear().roundRect(0,r,this.width_,this.height_,this.height_/2).fill({color:n});let i=this.knobSize/2+this.fraction*this.trackLength;this.fill.clear(),i>this.knobSize/2&&this.fill.roundRect(this.knobSize/2,r,i-this.knobSize/2,this.height_,this.height_/2).fill({color:t}),this.knob.clear().circle(i,this.knobSize/2,this.knobSize/2).fill({color:t})}destroy(e){$.remove(this.themeListener),super.destroy(e)}},oR=class extends Y{constructor(e={}){super(),this.onChange=new p,this.box=new bE,this.themeListener=()=>this.draw(),this.handleTap=()=>{this.disabled_||this.toggle()},this.size_=e.size??20,this.checked_=e.checked??!1,this.disabled_=e.disabled??!1,this.addChild(this.box),this.draw(),this.eventMode=`static`,this.cursor=`pointer`,this.on(`pointertap`,this.handleTap),$.add(this.themeListener)}get checked(){return this.checked_}get disabled(){return this.disabled_}setDisabled(e){this.disabled_=e,this.cursor=e?`default`:`pointer`,this.draw()}setChecked(e){if(e===this.checked_){this.draw();return}this.checked_=e,this.draw(),this.onChange.dispatch(e)}toggle(){this.setChecked(!this.checked_)}resize(e){this.size_=e,this.draw()}draw(){let e=Q(),t=this.disabled_?e.color.textDim:e.color.textHighlight;if(this.box.clear().roundRect(0,0,this.size_,this.size_,4).fill({color:e.color.panelFill}).stroke({color:this.disabled_?e.color.textDim:e.color.panelBorder,width:2}),this.checked_){let e=this.size_*.25;this.box.moveTo(e,this.size_*.55).lineTo(this.size_*.45,this.size_-e).lineTo(this.size_-e,e).stroke({color:t,width:Math.max(2,this.size_*.12),cap:`round`,join:`round`})}}destroy(e){$.remove(this.themeListener),super.destroy(e)}},sR=class extends Y{constructor(e={}){super(),this.onChange=new p,this.options_=[],this.rows=[],this.circles=[],this.selected_=-1,this.themeListener=()=>this.draw(),this.size_=e.size??20,this.gap_=e.gap??8,this.buildRows(e.options??[]),this.selected_=this.defaultSelection(e.selected),this.draw(),$.add(this.themeListener)}get selected(){return this.selected_}get selectedOption(){return this.options_[this.selected_]??null}get length(){return this.options_.length}get rowHeight(){return this.size_+this.gap_}setOptions(e,t){this.buildRows(e),this.selected_=this.defaultSelection(t),this.draw()}select(e){let t=this.options_[e];if(t&&!t.disabled){if(e===this.selected_){this.draw();return}this.selected_=e,this.draw(),this.onChange.dispatch(e)}}move(e){let t=this.options_.length;if(t===0)return!1;let n=this.selected_;for(let r=0;r<t;r++){n=(n+e+t)%t;let r=this.options_[n];if(r&&!r.disabled)return this.select(n),!0}return!1}handleAction(e){switch(e){case`up`:case`left`:return this.move(-1);case`down`:case`right`:return this.move(1);default:return!1}}tapRow(e){this.select(e)}defaultSelection(e){if(e!==void 0){let t=this.options_[e];if(t&&!t.disabled)return e}let t=this.options_.findIndex(e=>!e.disabled);return t===-1?-1:t}buildRows(e){for(let e of this.rows)e.destroy({children:!0});this.rows=[],this.circles=[],this.options_=[...e],this.removeChildren(),e.forEach((e,t)=>{let n=new Y;n.y=t*this.rowHeight,n.eventMode=`static`,n.cursor=e.disabled?`default`:`pointer`,n.on(`pointertap`,()=>this.tapRow(t));let r=new bE;n.addChild(r),this.circles.push(r);let i=new sF({text:e.text});n.addChild(i),this.rows.push(n),this.addChild(n)})}draw(){let e=Q(),t=e.direction===`rtl`;this.rows.forEach((n,r)=>{let i=this.options_[r].disabled,a=this.circles[r];a.clear().circle(this.size_/2,this.size_/2,this.size_/2-1).fill({color:e.color.panelFill}).stroke({color:i?e.color.textDim:e.color.panelBorder,width:2}),r===this.selected_&&a.circle(this.size_/2,this.size_/2,Math.max(2,this.size_*.28)).fill({color:i?e.color.textDim:e.color.textHighlight});let o=this.size_+e.spacing,s=n.children.find(e=>e instanceof sF),c=s?.width??0;s&&(s.setColor(i?e.color.textDim:e.color.text),s.y=Math.round((this.size_-s.height)/2)),t?(s&&(s.x=0),a.x=c+e.spacing):(a.x=0,s&&(s.x=o))})}destroy(e){$.remove(this.themeListener),super.destroy(e)}};function cR(e,t,n,r,i=1,a=!1){if(!(r>n))return n;let o=i>0?i:1,s=(String(o).split(`.`)[1]??``).length,c=Math.round((e-n)/o)+Math.round(t),l=Math.round((r-n)/o)+1,u=c;return u=a?(u%l+l)%l:Math.max(0,Math.min(l-1,u)),Number((n+u*o).toFixed(s))}var lR=class extends Y{constructor(e={}){super(),this.onChange=new p,this.face=new bE,this.themeListener=()=>this.draw(),this.handleTap=e=>{this.disabled_||(this.toLocal(e.global).y<this.height_/2?this.increment():this.decrement())},this.width_=e.width??24,this.height_=e.height??32,this.min=e.min??0,this.max=e.max??9,this.step=e.step??1,this.wrap=e.wrap??!1,this.disabled_=e.disabled??!1,this.value_=cR(e.value??this.min,0,this.min,this.max,this.step,!1),this.addChild(this.face),this.draw(),this.eventMode=`static`,this.cursor=`pointer`,this.on(`pointertap`,this.handleTap),$.add(this.themeListener)}get value(){return this.value_}get disabled(){return this.disabled_}setDisabled(e){this.disabled_=e,this.cursor=e?`default`:`pointer`,this.draw()}setValue(e){this.commit(cR(e,0,this.min,this.max,this.step,this.wrap))}increment(){this.commit(cR(this.value_,1,this.min,this.max,this.step,this.wrap))}decrement(){this.commit(cR(this.value_,-1,this.min,this.max,this.step,this.wrap))}resize(e,t){this.width_=e,this.height_=t,this.draw()}commit(e){if(e===this.value_){this.draw();return}this.value_=e,this.draw(),this.onChange.dispatch(e)}draw(){let e=Q(),t=this.disabled_?e.color.textDim:e.color.textHighlight;this.face.clear().roundRect(0,0,this.width_,this.height_,4).fill({color:e.color.panelFill}).stroke({color:e.color.panelBorder,width:1});let n=this.width_/2,r=Math.min(this.width_/4,this.height_/5);this.face.moveTo(n-r,r*1.6).lineTo(n,r*.6).lineTo(n+r,r*1.6).closePath().fill({color:t}),this.face.moveTo(n-r,this.height_-r*1.6).lineTo(n,this.height_-r*.6).lineTo(n+r,this.height_-r*1.6).closePath().fill({color:t})}destroy(e){$.remove(this.themeListener),super.destroy(e)}},uR=class{constructor(e){this.onChange=new p,this.open_=!1,this.options_=[...e.options],this.disabled_=e.disabled??!1;let t=e.selectedIndex??this.firstEnabled();this.current=this.options_[t]?.disabled?this.firstEnabled():t,this.highlight_=this.current}get options(){return this.options_}get selectedIndex(){return this.current}get selected(){return this.options_[this.current]??null}get isOpen(){return this.open_}get disabled(){return this.disabled_}get highlight(){return this.highlight_}setDisabled(e){this.disabled_=e,e&&(this.open_=!1)}setOptions(e){this.options_=[...e],this.current=this.firstEnabled(),this.highlight_=this.current,this.open_=!1}open(){this.disabled_||this.open_||(this.open_=!0,this.highlight_=this.current)}close(){this.open_=!1}toggleOpen(){this.open_?this.close():this.open()}move(e){if(!this.open_||this.options_.length===0)return;let t=this.options_.length,n=this.highlight_;for(let r=0;r<t;r++)if(n=((n+e)%t+t)%t,!this.options_[n].disabled){this.highlight_=n;return}}setHighlight(e){e<0||e>=this.options_.length||this.options_[e].disabled||(this.highlight_=e)}confirm(){if(!this.open_)return!1;let e=this.options_[this.highlight_];return!e||e.disabled?!1:(this.open_=!1,this.highlight_!==this.current&&(this.current=this.highlight_,this.onChange.dispatch({option:e,index:this.current})),!0)}cancel(){this.open_=!1,this.highlight_=this.current}firstEnabled(){let e=this.options_.findIndex(e=>!e.disabled);return e===-1?0:e}},dR=class{constructor(e){this.onChange=new p,this.current=0,this.sortKey_=null,this.ascending=!0,this.columns_=[...e.columns],this.rows_=[...e.rows??[]],this.pageSize_=e.pageSize??0,this.disabledOf=e.disabled??(()=>!1),this.current=this.firstEnabled()}get columns(){return this.columns_}get rows(){return this.rows_}get pageSize(){return this.pageSize_}get sortKey(){return this.sortKey_}get sortAscending(){return this.ascending}get selectedIndex(){return this.current}get selected(){return this.rows_[this.current]??null}get page(){return this.pageSize_>0?Math.floor(this.current/this.pageSize_):0}get pageCount(){return this.pageSize_>0?Math.max(1,Math.ceil(this.rows_.length/this.pageSize_)):1}get pageRows(){if(this.pageSize_<=0)return this.rows_;let e=this.page*this.pageSize_;return this.rows_.slice(e,e+this.pageSize_)}setRows(e){this.rows_=[...e],this.current=this.firstEnabled(),this.onChange.dispatch()}setColumns(e){this.columns_=[...e],this.sortKey_&&!this.columns_.some(e=>e.key===this.sortKey_)&&(this.sortKey_=null),this.onChange.dispatch()}setPageSize(e){this.pageSize_=Math.max(0,e),this.onChange.dispatch()}sortBy(e){let t=this.columns_.find(t=>t.key===e);if(!t)return;this.sortKey_===e?this.ascending=!this.ascending:(this.sortKey_=e,this.ascending=!0);let n=t.compare??((t,n)=>pR(fR(t,e),fR(n,e)));this.rows_.sort((e,t)=>(this.ascending?1:-1)*n(e,t)),this.current=this.firstEnabled(),this.onChange.dispatch()}select(e){e<0||e>=this.rows_.length||this.disabledOf(this.rows_[e])||(this.current=e,this.onChange.dispatch())}move(e){let t=this.rows_.length;if(t===0)return;let n=this.current;for(let r=0;r<t;r++){if(n+=e,n<0||n>=t)return;if(!this.disabledOf(this.rows_[n])){this.current=n,this.onChange.dispatch();return}}}setPage(e){if(this.pageSize_<=0)return;let t=Math.max(0,Math.min(this.pageCount-1,e))*this.pageSize_,n=Math.min(t+this.pageSize_,this.rows_.length);for(let e=t;e<n;e++)if(!this.disabledOf(this.rows_[e])){this.current=e,this.onChange.dispatch();return}}nextPage(e=1){this.setPage(this.page+e)}firstEnabled(){let e=this.rows_.findIndex(e=>!this.disabledOf(e));return e===-1?0:e}};function fR(e,t){return e&&typeof e==`object`?e[t]:void 0}function pR(e,t){return e===t?0:e===void 0?-1:t===void 0?1:typeof e==`number`&&typeof t==`number`?e-t:String(e).localeCompare(String(t))}var mR=class{constructor(e){this.onChange=new p,this.expanded=new Set,this.current=0,this.roots_=e.roots;for(let t of e.expanded??[])this.expanded.add(t);this.disabledOf=e.disabled??(()=>!1),this.current=this.firstEnabled()}get roots(){return this.roots_}get rows(){let e=[],t=(n,r)=>{for(let i of n){let n=(i.children?.length??0)>0,a=n&&this.expanded.has(i.id);e.push({node:i,depth:r,expanded:a,hasChildren:n}),a&&t(i.children,r+1)}};return t(this.roots_,0),e}get selectedIndex(){return this.current}get selected(){return this.rows[this.current]?.node??null}isExpanded(e){return this.expanded.has(e)}expand(e){this.expanded.has(e)||(this.expanded.add(e),this.onChange.dispatch())}collapse(e){if(!this.expanded.has(e))return;let t=this.rows[this.current]?.node.id;if(this.expanded.delete(e),t!==void 0&&!this.rows.some(e=>e.node.id===t)){let t=this.rows.findIndex(t=>t.node.id===e);t>=0&&(this.current=t)}this.onChange.dispatch()}toggle(e){this.expanded.has(e)?this.collapse(e):this.expand(e)}expandAll(){let e=t=>{for(let n of t)n.children?.length&&(this.expanded.add(n.id),e(n.children))};e(this.roots_),this.onChange.dispatch()}collapseAll(){this.expanded.clear(),this.select(0),this.onChange.dispatch()}select(e){let t=this.rows[e];t&&!this.disabledOf(t.node)&&(this.current=e,this.onChange.dispatch())}move(e){let t=this.rows.length;if(t===0)return;let n=this.current;for(let r=0;r<t;r++){if(n+=e,n<0||n>=t)return;if(!this.disabledOf(this.rows[n].node)){this.current=n,this.onChange.dispatch();return}}}firstEnabled(){let e=this.rows.findIndex(e=>!this.disabledOf(e.node));return e===-1?0:e}};function hR(e,t,n){return Math.max(0,Math.min(Math.max(0,t-n),e))}var gR=class extends Y{constructor(e){super(),this.onChange=new p,this.content=new Y,this.maskShape=new bE,this.track=new bE,this.thumb=new bE,this.themeListener=()=>this.draw(),this.handleWheel=e=>{this.scrollBy(e.deltaY)},this.width_=e.width,this.height_=e.height,this.contentHeight_=Math.max(0,e.contentHeight??0),this.offset_=hR(e.offset??0,this.contentHeight_,this.height_),this.addChild(this.content),this.addChild(this.maskShape),this.addChild(this.track),this.addChild(this.thumb),this.content.mask=this.maskShape,this.eventMode=`static`,this.on(`wheel`,this.handleWheel),this.draw(),$.add(this.themeListener)}get offset(){return this.offset_}get contentHeight(){return this.contentHeight_}get viewportHeight(){return this.height_}get maxOffset(){return Math.max(0,this.contentHeight_-this.height_)}get scrollable(){return this.maxOffset>0}setContentHeight(e){this.contentHeight_=Math.max(0,e),this.setOffset(hR(this.offset_,this.contentHeight_,this.height_))}resize(e,t){this.width_=e,this.height_=t,this.setOffset(hR(this.offset_,this.contentHeight_,this.height_))}scrollBy(e){this.setOffset(hR(this.offset_+e,this.contentHeight_,this.height_))}scrollTo(e){this.setOffset(hR(e,this.contentHeight_,this.height_))}scrollIntoView(e,t){e<this.offset_?this.scrollTo(e):e+t>this.offset_+this.height_&&this.scrollTo(e+t-this.height_)}setOffset(e){if(e===this.offset_){this.draw();return}this.offset_=e,this.draw(),this.onChange.dispatch(e)}draw(){let e=Q();if(this.content.y=-this.offset_,this.maskShape.clear().rect(0,0,this.width_,this.height_).fill({color:16777215}),this.track.clear(),this.thumb.clear(),!this.scrollable)return;let t=this.width_-6;this.track.roundRect(t,0,6,this.height_,3).fill({color:e.color.panelFill});let n=Math.max(6,this.height_/this.contentHeight_*this.height_),r=this.offset_/this.maxOffset*(this.height_-n);this.thumb.roundRect(t,r,6,n,3).fill({color:e.color.textHighlight})}destroy(e){$.remove(this.themeListener),super.destroy(e)}};function _R(e){switch(e){case`top`:case`bottom`:return{x:.5,y:e===`top`?0:1};case`left`:case`right`:return{x:e===`left`?0:1,y:.5};case`top-left`:return{x:0,y:0};case`top-right`:return{x:1,y:0};case`bottom-left`:return{x:0,y:1};case`bottom-right`:return{x:1,y:1};default:return{x:.5,y:.5}}}function vR(e,t,n={width:0,height:0}){let r=e.margin??0,i=t.x+r,a=t.y+r,o=Math.max(0,t.width-r*2),s=Math.max(0,t.height-r*2);if(e.anchor===`fill`){let t=i+(e.offsetX??0),n=a+(e.offsetY??0);return{x:t,y:n,width:e.width??Math.max(0,i+o-t),height:e.height??Math.max(0,a+s-n)}}let c=_R(e.anchor??`center`),l=e.alignX??c.x,u=e.alignY??c.y,d=e.width??n.width,f=e.height??n.height;return{x:i+l*Math.max(0,o-d)+(e.offsetX??0),y:a+u*Math.max(0,s-f)+(e.offsetY??0),width:d,height:f}}var yR=class{constructor(e){this.spec=e}get columns(){return this.spec.columns}get rows(){return this.spec.rows}columnSizes(e){return bR(this.spec.columns,e,this.gap)}rowSizes(e){return bR(this.spec.rows,e,this.gap)}rect(e,t,n,r={}){let i=this.columnSizes(n.width),a=this.rowSizes(n.height),o=r.columnSpan??1,s=r.rowSpan??1;return{x:n.x+SR(i,t,this.gap),y:n.y+SR(a,e,this.gap),width:CR(i,t,o,this.gap),height:CR(a,e,s,this.gap)}}get gap(){return this.spec.gap??0}};function bR(e,t,n){let r=n*Math.max(0,e.length-1),i=Math.max(0,t-r),a=e.reduce((e,t)=>e+(t.size??0),0),o=e.reduce((e,t)=>e+(t.grow??0),0),s=Math.max(0,i-a),c=0;return e.map((t,n)=>{if(t.size!==void 0)return t.size;if(!t.grow||o===0)return 0;let r=n===xR(e)?s-c:Math.floor(s*t.grow/o);return c+=r,r})}function xR(e){for(let t=e.length-1;t>=0;t--)if(e[t].grow)return t;return-1}function SR(e,t,n){let r=0;for(let i=0;i<t&&i<e.length;i++)r+=e[i]+n;return r}function CR(e,t,n,r){let i=0;for(let a=t;a<t+n&&a<e.length;a++)i+=e[a],a>t&&(i+=r);return Math.max(0,i)}var wR=[`idle`,`hover`,`pressed`,`disabled`,`selected`,`focused`],TR=class e{constructor(){this.map=new Map}static{this.ANY=`*`}define(e,t,n){let r=this.map.get(e)??{};r[t]={...r[t],...n},this.map.set(e,r)}has(e){return this.map.has(e)}widgets(){return[...this.map.keys()]}resolve(t,n=`idle`){return this.map.get(t)?.[n]??this.map.get(t)?.idle??this.map.get(e.ANY)?.[n]??this.map.get(e.ANY)?.idle??{}}statesOf(e){let t=this.map.get(e);return t?wR.filter(e=>t[e]!==void 0):[]}static from(t){let n=new e;for(let[e,r]of Object.entries(t))if(ER(r))for(let t of wR){let i=r[t];i&&n.define(e,t,i)}else n.define(e,`idle`,r);return n}};function ER(e){return wR.some(t=>e[t]!==void 0)}var DR=class extends Y{constructor(e){super(),this.capturing=null,this.onKeyCaptured=e=>this.capturing?(e.preventDefault(),e.code===`Escape`?this.cancelCapture():this.finishCapture(this.capturing,e.code),!0):!1,this.actions=[...e.actions],this.labelFor=e.label??(e=>e),this.onConflict=e.onConflict??(()=>!0),this.list=new sI({width:e.width,height:e.height,rowHeight:e.rowHeight,items:this.rows()}),this.addChild(this.list)}rows(){return this.actions.map(e=>({text:this.rowText(e),value:e,disabled:this.capturing!==null&&this.capturing!==e}))}rowText(e){if(this.capturing===e)return`${this.labelFor(e)}: press a key...`;let t=Ie(e);return`${this.labelFor(e)}: ${t.length?t.join(`, `):`(unbound)`}`}refresh(){let e=this.list.selectedIndex;this.list.setItems(this.rows()),this.list.select(e)}startCapture(e){this.capturing=e,this.refresh(),queueMicrotask(()=>{this.capturing===e&&xe.add(this.onKeyCaptured)})}cancelCapture(){xe.remove(this.onKeyCaptured),this.capturing=null,this.refresh()}finishCapture(e,t){xe.remove(this.onKeyCaptured),this.capturing=null;let n=Pe(t).filter(t=>t!==e);if(n.length>0&&!this.onConflict(t,e,n)){this.refresh();return}for(let e of n)Me(e,Ie(e).filter(e=>e!==t));Me(e,[t]),this.refresh()}get isCapturing(){return this.capturing!==null}handleAction(e){if(this.capturing)return!0;if(e===`confirm`){let e=this.list.selected?.value;return e&&this.startCapture(e),!0}return this.list.handleAction(e)}destroy(e){xe.remove(this.onKeyCaptured),super.destroy(e)}},OR=class extends Y{constructor(e){super(),this.highlight=new bE,this.main=new Y,this.rebindLayer=new Y,this.rows=[],this.selected=0,this.rebind=null,this.themeListener=()=>this.drawHighlight(),this.settings=e.settings,this.width_=e.width??320,this.rowHeight=e.rowHeight??36,this.labels={music:`Music`,sfx:`Sound effects`,muted:`Mute`,zoom:`Zoom`,controls:`Controls...`,reset:`Reset to defaults`,rebindHint:`Keys (cancel: back)`,...e.labels},this.zoomMin=e.zoomMin??.5,this.zoomMax=e.zoomMax??4,this.zoomStep=e.zoomStep??.25,this.customRows=e.custom??[],this.actionsOption=e.actions,this.onConflict=e.onConflict,this.addChild(this.highlight),this.addChild(this.main),this.addChild(this.rebindLayer),this.rebindLayer.visible=!1,this.buildMain(),this.refresh(),this.drawHighlight(),$.add(this.themeListener)}get selectedRow(){return this.rows[this.selected]?.id??``}get isRebinding(){return this.rebind!==null}handleAction(e){if(this.rebind)return e===`cancel`&&!this.rebind.isCapturing?(this.closeRebind(),!0):this.rebind.handleAction(e);let t=this.rows[this.selected];if(!t)return!1;switch(e){case`up`:return this.select((this.selected+this.rows.length-1)%this.rows.length),!0;case`down`:return this.select((this.selected+1)%this.rows.length),!0;case`left`:return t.adjust(-1),!0;case`right`:return t.adjust(1),!0;case`confirm`:return t.activate(),!0;default:return!1}}refresh(){for(let e of this.rows)e.refresh()}select(e){this.selected=e,this.drawHighlight()}drawHighlight(){if(this.rows.length===0){this.highlight.clear();return}this.highlight.clear().rect(0,this.selected*this.rowHeight,this.width_,this.rowHeight).fill({color:Q().color.selection})}buildMain(){let e=this.settings.current;this.addSliderRow(`music`,this.labels.music,0,100,1,10,Math.round(e.musicVolume*100),e=>this.settings.setMusicVolume(e/100)),this.addSliderRow(`sfx`,this.labels.sfx,0,100,1,10,Math.round(e.sfxVolume*100),e=>this.settings.setSfxVolume(e/100)),this.addToggleRow(`muted`,this.labels.muted,e.muted,e=>this.settings.setMuted(e)),this.addSliderRow(`zoom`,this.labels.zoom,this.zoomMin,this.zoomMax,this.zoomStep,this.zoomStep,e.zoom,e=>this.settings.setZoom(e));for(let e of this.customRows)this.addCustomRow(e);this.addActionRow(`controls`,this.labels.controls,()=>this.openRebind()),this.addActionRow(`reset`,this.labels.reset,()=>{this.settings.reset(),this.refresh()}),this.main.children.forEach((e,t)=>{e.y=t*this.rowHeight})}addSliderRow(e,t,n,r,i,a,o,s){let c=new Y,l=new sF({text:t});l.y=10;let u=new aR({width:140,min:n,max:r,step:i,value:o});u.x=this.width_-148,u.y=10,c.addChild(l,u),this.main.addChild(c);let d=()=>{l.setText(`${t}: ${u.value}`)};d(),u.onChange.add(e=>{s(e),d()}),this.rows.push({id:e,root:c,adjust:e=>u.setValue(u.value+e*a),activate:()=>{},refresh:()=>{u.setValue(this.readSlider(e)),d()}})}readSlider(e){let t=this.settings.current;switch(e){case`music`:return Math.round(t.musicVolume*100);case`sfx`:return Math.round(t.sfxVolume*100);case`zoom`:return t.zoom;default:return 0}}addToggleRow(e,t,n,r){let i=new Y,a=new sF({text:t});a.y=10;let o=new oR({checked:n});o.x=this.width_-28,o.y=8,i.addChild(a,o),this.main.addChild(i),o.onChange.add(r),this.rows.push({id:e,root:i,adjust:()=>o.toggle(),activate:()=>o.toggle(),refresh:()=>o.setChecked(this.readToggle(e))})}readToggle(e){return e===`muted`?this.settings.current.muted:this.settings.getCustom(e.slice(7),!1)===!0}addCustomRow(e){let t=`custom:${e.key}`;if(e.kind===`boolean`){let n=this.settings.getCustom(e.key,!1);this.addToggleRow(t,e.label,n===!0,t=>this.settings.setCustom(e.key,t))}else if(e.kind===`number`){let n=this.settings.getCustom(e.key,e.min),r=typeof n==`number`?n:e.min,i=e.step??0,a=i>0?i:(e.max-e.min)/20,o=new Y,s=new sF({text:e.label});s.y=10;let c=new aR({width:140,min:e.min,max:e.max,step:e.step??0,value:r});c.x=this.width_-148,c.y=10,o.addChild(s,c),this.main.addChild(o);let l=()=>{s.setText(`${e.label}: ${c.value}`)};l(),c.onChange.add(t=>{this.settings.setCustom(e.key,t),l()}),this.rows.push({id:t,root:o,adjust:e=>c.setValue(c.value+e*a),activate:()=>{},refresh:()=>{let t=this.settings.getCustom(e.key,e.min);c.setValue(typeof t==`number`?t:e.min),l()}})}else{let n=e.options,r=new Y,i=new sF({text:e.label});i.y=10;let a=new lR({min:0,max:n.length-1,step:1,value:0,wrap:!0});a.x=this.width_-32,a.y=2,r.addChild(i,a),this.main.addChild(r);let o=e=>{let t=typeof e==`string`?n.indexOf(e):-1;return t>=0?t:0},s=()=>{i.setText(`${e.label}: ${n[a.value]}`)};a.setValue(o(this.settings.getCustom(e.key,n[0]))),s(),a.onChange.add(t=>{this.settings.setCustom(e.key,n[t]),s()}),this.rows.push({id:t,root:r,adjust:e=>e>0?a.increment():a.decrement(),activate:()=>a.increment(),refresh:()=>{a.setValue(o(this.settings.getCustom(e.key,n[0]))),s()}})}}addActionRow(e,t,n){let r=new Y,i=new KL({width:this.width_-16,height:28,text:t,onClick:n});i.x=8,i.y=4,r.addChild(i),this.main.addChild(r),this.rows.push({id:e,root:r,adjust:()=>{},activate:n,refresh:()=>{}})}openRebind(){let e=this.actionsOption??Object.keys(this.settings.current.bindings),t=new sF({text:this.labels.rebindHint}),n=new DR({width:this.width_,height:Math.max(1,e.length)*this.rowHeight,actions:e,onConflict:this.onConflict});t.y=0,n.y=this.rowHeight,this.rebindLayer.addChild(t,n),this.rebindLayer.visible=!0,this.main.visible=!1,this.highlight.visible=!1,this.rebind=n}closeRebind(){this.settings.setBindings(Le()),this.rebindLayer.removeChildren(),this.rebind?.destroy(),this.rebind=null,this.rebindLayer.visible=!1,this.main.visible=!0,this.highlight.visible=!0}destroy(e){$.remove(this.themeListener),this.rebind?.destroy(),this.rebind=null,super.destroy(e)}},kR=class extends Y{constructor(e){if(super(),this.emptyLayer=new Y,this.filledLayer=new Y,this.maskShape=new bE,this.themeListener=()=>this.draw(),e.filledTexture===void 0!=(e.emptyTexture===void 0))throw Error(`a Meter takes filledTexture and emptyTexture together, or neither`);this.count_=jR(e.count),this.size_=e.size??16,this.gap_=e.gap??4,this.value_=AR(e.value??this.count_,this.count_),this.explicitColor=e.color!==void 0,this.fillColor=e.color??Q().color.textHighlight,this.emptyColor_=e.emptyColor,this.filledTexture=e.filledTexture,this.emptyTexture=e.emptyTexture,this.addChild(this.emptyLayer),this.addChild(this.filledLayer),this.addChild(this.maskShape),this.filledLayer.mask=this.maskShape,this.draw(),$.add(this.themeListener)}get value(){return this.value_}get count(){return this.count_}get color(){return this.fillColor}setValue(e,t=this.count_){this.count_=jR(t),this.value_=AR(e,this.count_),this.draw()}setColor(e){this.explicitColor=!0,this.fillColor=e,this.draw()}resize(e,t=this.gap_){this.size_=e,this.gap_=t,this.draw()}get totalWidth(){return this.count_*this.size_+(this.count_-1)*this.gap_}iconX(e){let t=e*(this.size_+this.gap_);return Q().direction===`rtl`?this.totalWidth-t-this.size_:t}draw(){let e=Q();this.explicitColor||(this.fillColor=e.color.textHighlight);let t=this.emptyColor_??e.color.panelFill;this.emptyLayer.removeChildren(),this.filledLayer.removeChildren();for(let e=0;e<this.count_;e++){let n=this.iconX(e);this.emptyLayer.addChild(this.icon(n,t,this.emptyTexture,!1)),this.filledLayer.addChild(this.icon(n,this.fillColor,this.filledTexture,!0))}let n=this.totalWidth*(this.count_>0?this.value_/this.count_:0),r=e.direction===`rtl`?this.totalWidth-n:0;this.maskShape.clear().rect(r,0,n,this.size_).fill({color:16777215})}icon(e,t,n,r){if(n){let i=new xl(n);return i.x=e,i.width=this.size_,i.height=this.size_,r&&this.explicitColor&&(i.tint=t),i}let i=new bE,a=this.size_/2;return i.circle(e+a,a,a).fill({color:t}),i}destroy(e){$.remove(this.themeListener),super.destroy(e)}};function AR(e,t){return Number.isFinite(e)?Math.max(0,Math.min(t,e)):t}function jR(e){return Number.isFinite(e)?Math.max(1,Math.floor(e)):1}var MR=class extends Y{constructor(e){super(),this.track=new bE,this.fill=new bE,this.themeListener=()=>this.draw(),this.width_=e.width,this.height_=e.height,this.explicitColor=e.color!==void 0,this.fillColor=e.color??Q().color.textHighlight,this.fraction=NR((e.value??1)/(e.max??1)),this.fillTexture=e.fillTexture,this.backgroundTexture=e.backgroundTexture,this.background_=e.background,this.roundUpToPixel=e.roundUpToPixel??!1,this.addChild(this.track),this.addChild(this.fill),this.draw(),$.add(this.themeListener)}get value(){return this.fraction}setValue(e,t=1){this.fraction=NR(t>0?e/t:0),this.draw()}get color(){return this.fillColor}setColor(e){this.explicitColor=!0,this.fillColor=e,this.draw()}get background(){return this.background_??Q().color.panelFill}resize(e,t){this.width_=e,this.height_=t,this.draw()}draw(){let e=Q();if(this.explicitColor||(this.fillColor=e.color.textHighlight),this.track.clear().rect(0,0,this.width_,this.height_),this.track.fill(this.backgroundTexture?{texture:this.backgroundTexture}:{color:this.background}),this.fill.clear(),this.fraction>0){let t=this.width_*this.fraction,n=this.roundUpToPixel?Math.ceil(t):t,r=e.direction===`rtl`?this.width_-n:0;this.fill.rect(r,0,n,this.height_),this.fill.fill(this.fillTexture?this.explicitColor?{texture:this.fillTexture,color:this.fillColor}:{texture:this.fillTexture}:{color:this.fillColor})}}destroy(e){$.remove(this.themeListener),super.destroy(e)}};function NR(e){return Math.max(0,Math.min(1,e))}function PR(e,t){return t<=0?1-e:t>=1||e<=t?1:1-(e-t)/(1-t)}function FR(e,t,n=!1){return n||e<=0?0:-t*e}function IR(e,t,n){return n<=0?e:Math.max(e,Math.min(n,t))}var LR=class extends Y{constructor(e){super(),this.rising=new Y,this.elapsed=0,this.done=!1,this.duration=e.duration??.8,this.rise=e.rise??24,this.hold=Math.min(1,Math.max(0,e.hold??0));let t=new sF({text:e.text,color:e.color,size:e.size});t.anchor.set(.5),this.rising.addChild(t),this.addChild(this.rising)}get finished(){return this.done}get riseOffset(){return this.rising.y}ageAtLeast(e){this.elapsed=IR(this.elapsed,this.duration,e)}update(e){if(this.done)return;this.elapsed=Math.min(this.duration,this.elapsed+e);let t=this.duration>0?this.elapsed/this.duration:1;this.rising.y=FR(t,this.rise,yr()),this.alpha=PR(t,this.hold),t>=1&&(this.done=!0,this.parent?.removeChild(this),this.destroy({children:!0}))}},RR=4;function zR(e){return Math.max(0,e)/5}function BR(e,t,n=4){let r=t.y-t.height/2;return e.y+e.height/2+n<=r?e.y:r-e.height/2-n}function VR(e,t,n=4){let r=[];if(t.key===void 0)return r;let i=t;for(let a=e.length-1;a>=0;a--){let o=e[a];if(o.key!==t.key)continue;let s=BR(o,i,n);if(s===o.y)break;r.push({index:a,y:s,ageAtLeast:zR(r.length+1)}),i={...o,y:s}}return r}var HR=class extends Y{constructor(...e){super(...e),this.live=[]}push(e){let t=new LR({text:e.text,color:e.color,size:e.size,duration:e.duration,rise:e.rise,hold:e.hold});e.scale!==void 0&&t.scale.set(e.scale);let n={key:e.key,x:e.x,y:e.y,height:t.height};for(let e of VR(this.live.map(e=>e.entry),n)){let t=this.live[e.index];t.entry.y=e.y,t.popup.y=e.y,t.popup.ageAtLeast(e.ageAtLeast)}return t.position.set(e.x,e.y),this.addChild(t),this.live.push({popup:t,entry:n}),t}update(e){for(let{popup:t}of this.live)t.update(e);for(let e=this.live.length-1;e>=0;e--)this.live[e].popup.finished&&this.live.splice(e,1)}get count(){return this.live.length}clear(){for(let{popup:e}of this.live)this.removeChild(e),e.destroy({children:!0});this.live.length=0}},UR=class extends Y{constructor(e={}){super(),this.queue=[],this.current=null,this.phase=`fadeIn`,this.elapsed=0,this.fadeIn=e.fadeIn??.25,this.hold=e.hold??1,this.fadeOut=e.fadeOut??1.75,this.scaleFrom=e.scaleFrom??2}show(e){this.queue.push(e),this.current||this.start(this.queue.shift())}get isBusy(){return this.current!==null||this.queue.length>0}start(e){this.current=e,this.phase=`fadeIn`,this.elapsed=0,this.addChild(e),e.alpha=this.fadeIn>0?0:1,e.scale.set(this.fadeIn>0?this.scaleFrom:1)}update(e){let t=this.current;if(!t)return;if(this.elapsed+=e,this.phase===`fadeIn`){let e=this.fadeIn,n=e>0?Math.min(1,this.elapsed/e):1,r=wr.easeOutCubic(n);t.alpha=r,t.scale.set(this.scaleFrom+(1-this.scaleFrom)*r),n>=1&&this.advance();return}if(this.phase===`hold`){this.elapsed>=this.hold&&this.advance();return}let n=this.fadeOut,r=n>0?Math.min(1,this.elapsed/n):1;t.alpha=1-r,r>=1&&this.finish()}advance(){this.phase=this.phase===`fadeIn`?`hold`:`fadeOut`,this.elapsed=0}finish(){let e=this.current;if(!e)return;this.removeChild(e),e.destroy({children:!0}),this.current=null;let t=this.queue.shift();t&&this.start(t)}},WR=class extends Y{constructor(e={}){super(),this.viewWidth=0,this.viewHeight=0,this.panelWidth=0,this.panelHeight=0,this.pending=null,this.waited=0,this.delay=e.delay??.4,this.maxWidth=e.maxWidth??200,this.offsetX=e.offset?.x??12,this.offsetY=e.offset?.y??16,this.margin=e.margin??4,this.panel=new iI({width:0,height:0,modal:!1,closable:!1,dims:!1}),this.body=new sF({text:``,wrapWidth:this.maxWidth}),this.panel.content.addChild(this.body),this.addChild(this.panel),this.visible=!1}setViewport(e,t){this.viewWidth=e,this.viewHeight=t,this.visible&&this.place()}hover(e,t,n){if(this.pending&&this.pending.text===e){this.pending.x=t,this.pending.y=n,this.visible&&this.place();return}this.pending={text:e,x:t,y:n},this.waited=0,this.visible=!1}leave(){this.pending=null,this.waited=0,this.visible=!1}get isShowing(){return this.visible}get text(){return this.pending?.text??null}get panelPosition(){return{x:this.panel.x,y:this.panel.y}}get size(){return{width:this.panelWidth,height:this.panelHeight}}update(e){if(!this.pending||this.visible||(this.waited+=e,this.waited<this.delay))return!1;this.body.setText(this.pending.text);let t=Q(),n=(t.panel?t.panelBorder:2)+t.padding,r=this.measureBody();return this.panelWidth=Math.ceil(r.width)+n*2,this.panelHeight=Math.ceil(r.height)+n*2,this.panel.resize(this.panelWidth,this.panelHeight),this.visible=!0,this.place(),!0}measureBody(){return{width:this.body.width,height:this.body.height}}place(){let e=this.pending;if(!e)return;let t=this.panelWidth,n=this.panelHeight,r=e.x+this.offsetX,i=e.y+this.offsetY;this.viewWidth>0&&(r+t+this.margin>this.viewWidth&&(r=e.x-this.offsetX-t),r=Math.max(this.margin,Math.min(r,Math.max(this.margin,this.viewWidth-t-this.margin)))),this.viewHeight>0&&(i+n+this.margin>this.viewHeight&&(i=e.y-this.offsetY-n),i=Math.max(this.margin,Math.min(i,Math.max(this.margin,this.viewHeight-n-this.margin)))),this.panel.x=r,this.panel.y=i}},GR=class extends Y{constructor(e){super(),this.topics=e.topics;let t=e.listWidth??Math.floor(e.width/3),n=e.width-t-Q().spacing,r=Q().direction===`rtl`;this.list=new sI({width:t,height:e.height,items:this.topics.map(e=>({text:e.title})),onHighlight:(e,t)=>this.showBody(t),onSelect:(e,t)=>this.showBody(t)}),this.list.x=r?e.width-t:0,this.addChild(this.list),this.body=new sF({wrapWidth:n}),this.body.x=r?0:t+Q().spacing,this.addChild(this.body),this.topics.length>0&&this.showBody(this.list.selectedIndex)}showBody(e){this.body.setText(this.topics[e]?.body??``)}handleAction(e){return this.list.handleAction(e)}},KR=class e extends Y{constructor(t){super(),this.text=new sF({text:e.format(t.stats),wrapWidth:t.width}),this.addChild(this.text)}setStats(t,n){this.text.setText(e.format(t)),n!==void 0&&(this.text.style.wordWrapWidth=n)}static format(e){return e.map(e=>`${e.label}: ${e.value}`).join(`
1386
+ `)}},qR=class extends Y{constructor(e){super(),this.backdrop=new bE,this.progress=new MR({width:240,height:10,value:0}),this.width_=e.width,this.height_=e.height,this.onRetry=e.onRetry,this.onCancel=e.onCancel,this.title=new sF({text:e.title??`Loading`,size:18,bold:!0,align:`center`}),this.status=new sF({text:`Preparing...`,align:`center`}),this.addChild(this.backdrop,this.title,this.status,this.progress),this.layout()}setSnapshot(e){let t=e.total>0?e.completed/e.total:0;this.progress.setValue(t),e.status===`failed`?this.status.setText(`Loading failed. Retry or cancel.`):e.status===`cancelled`?this.status.setText(`Loading cancelled.`):e.status===`ready`?this.status.setText(`Ready`):this.status.setText(e.current?`Loading ${e.current}...`:`Preparing...`)}bind(e){this.setSnapshot(e.snapshot);let t=e=>this.setSnapshot(e);return e.changed.add(t),()=>e.changed.remove(t)}retry(){this.onRetry?.()}cancel(){this.onCancel?.()}resize(e,t){this.width_=e,this.height_=t,this.layout()}layout(){let e=Q().color;this.backdrop.clear().rect(0,0,this.width_,this.height_).fill({color:e.overlay,alpha:.92});let t=this.width_/2,n=this.height_/2;this.title.anchor.set(.5),this.status.anchor.set(.5),this.title.position.set(t,n-36),this.status.position.set(t,n-8),this.progress.position.set(t-120,n+16)}};function JR(e,t={}){return n=>new Promise(r=>{e.push(new WL({width:t.width??480,height:t.height??120,speed:t.speed??45,pages:[{text:n.text,speaker:n.speaker,portrait:n.portrait}],choices:n.choices,anchor:t.anchor??`bottom`,onDone:e=>r(e)}))})}function YR(e){let t=e/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4}function XR(e){return .2126*YR(e>>16&255)+.7152*YR(e>>8&255)+.0722*YR(e&255)}function ZR(e,t){let[n,r]=[XR(e),XR(t)].sort((e,t)=>t-e);return(n+.05)/(r+.05)}function QR(e,t,n=`AA`,r=!1){let i=n===`AAA`?r?4.5:7:r?3:4.5;return ZR(e,t)>=i}var $R={farLeft:.12,left:.28,center:.5,right:.72,farRight:.88},ez=class extends Y{constructor(e,t){super(),this.backdropLayer=new Y,this.actorLayer=new Y,this.backdrop=null,this.outgoingBackdrop=null,this.actors=new Map,this.definitions=new Map,this.focused=null,this.tweener=new Tr,this.dimAmount=.45,this.stageWidth=e,this.stageHeight=t,this.addChild(this.backdropLayer),this.addChild(this.actorLayer)}defineCharacter(e,t){this.definitions.set(e,t)}resize(e,t){this.stageWidth=e,this.stageHeight=t;for(let e of[this.backdrop,this.outgoingBackdrop])e&&this.fitBackdrop(e);for(let e of this.actors.values())this.placeActor(e)}setBackdrop(e,t=.4){this.outgoingBackdrop?.destroy();let n=this.backdrop;this.outgoingBackdrop=n;let r=new xl(e);this.fitBackdrop(r),this.backdrop=r,this.backdropLayer.addChild(r);let i=()=>{this.outgoingBackdrop===n&&(n?.destroy(),this.outgoingBackdrop=null)};return t<=0?(i(),Promise.resolve()):(r.alpha=0,this.tweener.tween(t,e=>{r.alpha=e}).then(i))}fitBackdrop(e){let t=e.texture,n=Math.max(this.stageWidth/t.width,this.stageHeight/t.height);e.scale.set(n),e.x=Math.round((this.stageWidth-t.width*n)/2),e.y=Math.round((this.stageHeight-t.height*n)/2)}show(e,t={}){let n=this.definitions.get(e);if(!n)throw Error(`no character defined as "${e}"`);let r=t.expression??Object.keys(n.expressions)[0],i=this.actors.get(e);if(i)return t.at!==void 0&&(i.slot=this.slotOf(t.at)),this.setExpression(e,r),this.placeActor(i),Promise.resolve();let a=new Zj(n.sheet.get(n.expressions[r])),o={id:e,sprite:a,definition:n,slot:this.slotOf(t.at??`center`),expression:r};this.actors.set(e,o),this.actorLayer.addChild(a),this.placeActor(o),this.applyFocus();let s=t.fade??.25;return s<=0?Promise.resolve():(a.alpha=0,this.tweener.tween(s,e=>{a.alpha=e}))}hide(e,t=.25){let n=this.actors.get(e);return n?(this.actors.delete(e),this.focused===e&&(this.focused=null),this.applyFocus(),t<=0?(n.sprite.destroy(),Promise.resolve()):this.tweener.tween(t,e=>{n.sprite.alpha=1-e}).then(()=>n.sprite.destroy())):Promise.resolve()}hideAll(e=.25){return Promise.all([...this.actors.keys()].map(t=>this.hide(t,e))).then(()=>void 0)}setExpression(e,t){let n=this.actors.get(e);if(!n)return;let r=n.definition.expressions[t];if(r===void 0)throw Error(`character "${e}" has no expression "${t}"`);n.expression=t,n.sprite.texture=n.definition.sheet.get(r)}focus(e){this.focused=e,this.applyFocus()}applyFocus(){let e=Math.round(255*(1-this.dimAmount)),t=e<<16|e<<8|e;for(let e of this.actors.values()){let n=this.focused!==null&&e.id!==this.focused;e.sprite.tint=n?t:16777215}}slotOf(e){return typeof e==`number`?e:$R[e]}placeActor(e){let t=e.definition,n=(t.height??.7)*this.stageHeight,r=n/t.sheet.frameHeight;e.sprite.scale.set(r),e.sprite.x=Math.round(e.slot*this.stageWidth-t.sheet.frameWidth*r/2),e.sprite.y=Math.round((t.baseline??.92)*this.stageHeight-n)}update(e){this.tweener.update(e)}get isBusy(){return this.tweener.isBusy}},tz=class{constructor(e){this.state={answers:{}},this.cancelled=!1,this.historyLog=[],this.seenLines=new Set,this.skipSeen=!1,this.options=e}cancel(){this.cancelled=!0}get history(){return this.historyLog}async showLast(){let e=this.historyLog.at(-1);if(!e)return!1;let{windows:t}=this.options;return await new Promise(n=>{t.push(new WL({width:this.options.boxWidth??480,height:this.options.boxHeight??120,speed:0,pages:[{text:e.text,speaker:e.speaker}],dims:!1,anchor:`bottom`,onDone:()=>n()}))}),!0}async run(e){for(let t of e){if(this.cancelled)break;let e=await this.step(t);if(e!==void 0)throw Error(`a "goto ${e}" only runs inside runStory, not a straight run`)}return this.state}async runStory(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw Error(`this story has no passage named "${t}"`);let n=e[t],r=0;for(;r<n.length&&!this.cancelled;){let t=await this.step(n[r]);if(r++,t!==void 0){if(!Object.prototype.hasOwnProperty.call(e,t))throw Error(`this story has no passage named "${t}"`);n=e[t],r=0}}return this.state}async step(e){let{stage:t}=this.options;if(`backdrop`in e){await t.setBackdrop(this.options.backdrop(e.backdrop),e.fade);return}if(`show`in e){await t.show(e.show,{at:e.at,expression:e.expression,fade:e.fade});return}if(`hide`in e){await t.hide(e.hide,e.fade);return}if(`hideAll`in e){await t.hideAll(e.fade);return}if(`expression`in e){t.setExpression(e.of,e.expression);return}if(`say`in e){await this.speak(e.say,e.as,e.speaker),this.recordHistory(e.say,e.as,e.speaker);return}if(`ask`in e){let t=await this.speak(e.ask,e.as,e.speaker,e.choices);return this.recordHistory(e.ask,e.as,e.speaker,t),e.store&&(this.state.answers[e.store]=t),e.choices.find(e=>(e.value??e.text)===t)?.goto}if(`goto`in e)return e.goto;if(`wait`in e){await new Promise(t=>setTimeout(t,e.wait*1e3));return}`call`in e&&await e.call(this.state)}recordHistory(e,t,n,r){let i=n??(t?this.options.displayName?.(t)??t:void 0);this.seenLines.add(nz(t,e)),this.historyLog.push({text:e,speaker:i,chosen:r})}speak(e,t,n,r){let{stage:i,windows:a}=this.options;i.focus(t??null);let o=n??(t?this.options.displayName?.(t)??t:void 0),s=this.skipSeen&&!r&&this.seenLines.has(nz(t,e));return new Promise(t=>{a.push(new WL({width:this.options.boxWidth??480,height:this.options.boxHeight??120,speed:s?0:this.options.speed??45,autoAdvance:s?0:void 0,mode:this.options.mode,pages:[{text:e,speaker:o}],choices:r,dims:!1,anchor:`bottom`,onDone:e=>t(e)}))})}};function nz(e,t){return`${e??``}\u0000${t}`}function rz(e){let{story:t,start:n,title:r}=Ur(e);return r===void 0?{story:t,start:n}:{story:t,start:n,title:r}}function iz(e){return Hr(e).map(e=>e.speaker===void 0?{say:e.text}:{say:e.text,as:e.speaker})}function az(e,t={}){let n={},r=e=>{for(let t of e)`say`in t?n[t.say]=t.say:`ask`in t&&(n[t.ask]=t.ask)};if(Array.isArray(e))r(e);else for(let t of Object.values(e))r(t);return{locale:t.locale??`en`,direction:t.direction??`ltr`,messages:n}}var oz=class{constructor(e){this.onChange=new p,this.onMusic=new p,this.index=0,this.beats=e}get length(){return this.beats.length}get position(){return this.index}get current(){return this.beats[this.index]??null}get done(){return this.beats.length===0||this.index>=this.beats.length-1}get music(){return this.current?.music??null}goTo(e){let t=Math.max(0,Math.min(this.beats.length-1,e));this.index=t,this.report()}advance(){return!this.done&&(this.goTo(this.index+1),!0)}back(){return this.index!==0&&(this.goTo(this.index-1),!0)}skip(){this.goTo(this.beats.length-1)}restart(){this.goTo(0)}report(){let e=this.current;e&&this.onChange.dispatch(e),this.onMusic.dispatch(this.music)}},sz=class extends Y{constructor(e){super(),this.backdrop=new xl(J.EMPTY),this.handleAdvance=()=>{this.advance()},this.handleBeat=e=>{this.applyBeat(e)},this.sequence=e.sequence,this.textureFor=e.textureFor??(()=>null),this.playMusic=e.playMusic??(()=>{}),this.width_=e.width,this.height_=e.height,this.titleLabel=new sF({text:``,color:Q().color.textHighlight}),this.textLabel=new sF({text:``,wrapWidth:this.width_*.8}),this.addChild(this.backdrop),this.addChild(this.titleLabel),this.addChild(this.textLabel),this.eventMode=`static`,this.on(`pointertap`,this.handleAdvance),this.sequence.onChange.add(this.handleBeat),this.sequence.onMusic.add(this.playMusic),this.applyBeat(this.sequence.current)}get current(){return this.sequence.current}advance(){return this.sequence.advance()}skip(){this.sequence.skip()}resize(e,t){this.width_=e,this.height_=t,this.applyBeat(this.current)}applyBeat(e){if(!e){this.backdrop.visible=!1;return}let t=e.image?this.textureFor(e.image):null;if(this.backdrop.visible=t!==null,t){this.backdrop.texture=t;let e=Math.max(this.width_/t.width,this.height_/t.height);this.backdrop.scale.set(e),this.backdrop.x=(this.width_-t.width*e)/2,this.backdrop.y=(this.height_-t.height*e)/2}this.titleLabel.setText(e.title??``),this.titleLabel.x=this.width_*.1,this.titleLabel.y=this.height_*.12,this.textLabel.setText(e.text),this.textLabel.x=this.width_*.1,this.textLabel.y=this.height_*.24,this.textLabel.style.wordWrapWidth=this.width_*.8}destroy(e){this.sequence.onChange.remove(this.handleBeat),this.sequence.onMusic.remove(this.playMusic),super.destroy(e)}},cz=[[1,0],[1,-1],[0,-1],[-1,-1],[-1,0],[0,1]],lz=[[1,1],[1,0],[0,-1],[-1,0],[-1,1],[0,1]];function uz(e){return e===4?or:cr}var dz={passable:!1,transparent:!1},fz={passable:!0,transparent:!0},pz=class e{constructor(e,t,n,r=0,i=`square`,a){if(this.rooms=[],this.width=e,this.shape=i,this.height=t,a!==void 0&&(!Number.isFinite(a)||a<0))throw Error(`viewDistance must be a finite non-negative number`);this.viewDistance=a,this.kinds=n,this.terrain=new Uint8Array(e*t).fill(r)}get cellCount(){return this.width*this.height}index(e,t){return tr(this.width,e,t)}xOf(e){return nr(this.width,e)}yOf(e){return rr(this.width,e)}inside(e,t){return er(this.width,this.height,e,t)}neighbors(e,t,n=8){return this.shape===`hex`?qn(e,t):uz(n).map(([n,r])=>({x:e+n,y:t+r}))}forEachNeighbor(e,t,n,r){let i=this.shape===`hex`?e&1?lz:cz:uz(n);for(let[n,a]of i)r(e+n,t+a)}insideWithBorder(e,t){return e>0&&t>0&&e<this.width-1&&t<this.height-1}get(e,t){return this.inside(e,t)?this.terrain[this.index(e,t)]:0}set(e,t,n){this.inside(e,t)&&(this.terrain[this.index(e,t)]=n)}kindAt(e,t){return this.kinds[this.get(e,t)]??dz}passable(e,t){return this.inside(e,t)&&this.kindAt(e,t).passable}transparent(e,t){return this.inside(e,t)&&this.kindAt(e,t).transparent}fillRect(e,t){for(let n=e.top;n<=e.bottom;n++)for(let r=e.left;r<=e.right;r++)this.set(r,n,t)}passableCells(){let e=[];for(let t=0;t<this.terrain.length;t++)this.kinds[this.terrain[t]]?.passable&&e.push(t);return e}toJSON(){return{width:this.width,height:this.height,shape:this.shape,terrain:[...this.terrain],rooms:this.rooms.map(e=>({...e})),...this.viewDistance===void 0?{}:{viewDistance:this.viewDistance}}}static fromJSON(t,n){let r=new e(n.width,n.height,t,0,n.shape,n.viewDistance);return r.terrain.set(n.terrain.slice(0,r.terrain.length)),r.rooms=n.rooms.map(e=>({...e})),r}};function mz(e){return{x:Math.floor((e.left+e.right)/2),y:Math.floor((e.top+e.bottom)/2)}}function hz(e,t,n=0){return!(e.right+n<t.left||t.right+n<e.left||e.bottom+n<t.top||t.bottom+n<e.top)}_e();var gz={id:`hall`,paint:(e,t,n)=>e.fillRect(t,n)};function _z(e){return Math.min(e.right-e.left+1,e.bottom-e.top+1)}function vz(e){return Math.max(e.right-e.left+1,e.bottom-e.top+1)}function yz(e,t){let n=_z(t),r=vz(t);return e.filter(e=>n>=(e.minSize??0)&&r<=(e.maxSize??1/0))}function bz(e,t){let n=yz(e,t);if(n.length===0)return null;let r=ie(n.map(e=>e.weight??1));return r===null?null:n[r]}_e();var xz=[{passable:!1,transparent:!1},{passable:!0,transparent:!0}];function Sz(e){let{width:t,height:n,rooms:r=14,minRoomSize:i=4,maxRoomSize:a=10,extraCorridors:o=3,wall:s=0,floor:c=1,kinds:l=[],hooks:u,builders:d}=e,f=new pz(t,n,[...xz,...l],s),p=[],m=[],h=[],g=0;for(let e=0;e<r*6&&p.length<r;e++){let e=ne(i,a),r=ne(i,a),o=te(1,Math.max(2,t-e-1)),s=te(1,Math.max(2,n-r-1)),l={left:o,top:s,right:o+e-1,bottom:s+r-1};if(l.right>=t-1||l.bottom>=n-1){g++;continue}if(p.some(e=>hz(l,e,2))){g++;continue}p.push(l);let m=(d?.length?bz(d,l):null)??gz;m.paint(f,l,c),h.push(m.id),u?.onRoomPlaced?.(l,p.length-1)}for(let e=1;e<p.length;e++){wz(f,mz(p[e-1]),mz(p[e]),c);let t={a:e-1,b:e,extra:!1};m.push(t),u?.onCorridorCarved?.(t,p[e-1],p[e])}for(let e=0;e<o&&p.length>2;e++){let e=te(p.length),t=te(p.length);if(e!==t){wz(f,mz(p[e]),mz(p[t]),c);let n={a:e,b:t,extra:!0};m.push(n),u?.onCorridorCarved?.(n,p[e],p[t])}}return f.rooms=p,{level:f,graph:m,retries:g,roomBuilders:h}}function Cz(e){return Sz(e).level}function wz(e,t,n,r){A(.5)?(Tz(e,t.x,n.x,t.y,!0,r),Tz(e,t.y,n.y,n.x,!1,r)):(Tz(e,t.y,n.y,t.x,!1,r),Tz(e,t.x,n.x,n.y,!0,r))}function Tz(e,t,n,r,i,a){let o=t<=n?1:-1;for(let s=t;s!==n+o;s+=o){let t=i?s:r,n=i?r:s;e.insideWithBorder(t,n)&&e.set(t,n,a)}}function Ez(e,t=new Set){let n=e.passableCells().filter(e=>!t.has(e));return n.length>0?n[te(n.length)]:null}function Dz(e,t){let n=null,r=-1;for(let i of e.rooms){let e=mz(i),a=(e.x-t.x)**2+(e.y-t.y)**2;a>r&&(r=a,n=i)}return n}var Oz=class e{constructor(){this.defs=new Map,this.placed=new Map}define(e,t){this.defs.set(e,t)}place(e,t){if(!this.defs.has(t))throw Error(`FeatureLayer.place: no definition for kind "${t}"`);this.placed.set(e,t)}has(e){return this.placed.has(e)}kindAt(e){return this.placed.get(e)}remove(e){this.placed.delete(e)}inspect(e,t){this.defAt(e)?.inspect?.(e,t)}interact(e,t){let n=this.defAt(e);n&&(n.interact&&n.interact(e,t)===!1||(n.consequence?.(e,t),n.persistent===!1&&this.remove(e)))}defAt(e){let t=this.placed.get(e);return t===void 0?void 0:this.defs.get(t)}toJSON(){return{cells:[...this.placed.entries()]}}static fromJSON(t,n){let r=new e;for(let[e,n]of t)r.define(e,n);for(let[e,t]of n.cells)r.place(e,t);return r}};_e();function kz(e,t=[],n=!0){let r=[],i=e.map(e=>e.value);t.forEach((e,t)=>{if(e.enabled===!1){r.push({step:`rare`,index:t,outcome:`deferred`});return}let n=A(e.chance);r.push({step:`rare`,index:t,outcome:n?`added`:`skipped`}),n&&i.push(e.value)});for(let t=0;t<e.length;t++){let n=e[t].alternative;if(!n)continue;let a=A(n.chance);r.push({step:`alternative`,index:t,outcome:a?`swapped`:`kept`}),a&&(i[t]=n.value)}return n&&(oe(i),r.push({step:`shuffle`,index:-1,outcome:`shuffled`})),{roster:i,trace:r}}function Az(e,t){return e.length===t.length&&e.every((e,n)=>e.a===t[n].a&&e.b===t[n].b&&e.extra===t[n].extra)}function jz(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function Mz(e,t){if(e.length!==t.length)return!1;let n=[...e].sort((e,t)=>e[0]-t[0]),r=[...t].sort((e,t)=>e[0]-t[0]);return n.every(([e,t],n)=>e===r[n][0]&&t===r[n][1])}function Nz(e,t){let n=[];return e.retries!==t.retries&&n.push({stage:`graph`,field:`retries`,expected:e.retries,actual:t.retries}),Az(e.graph,t.graph)||n.push({stage:`graph`,field:`graph`,expected:e.graph,actual:t.graph}),(e.width!==t.width||e.height!==t.height||!jz(e.terrain,t.terrain))&&n.push({stage:`paint`,field:`terrain`,expected:e.terrain,actual:t.terrain}),(e.roomBuilders.length!==t.roomBuilders.length||e.roomBuilders.some((e,n)=>e!==t.roomBuilders[n]))&&n.push({stage:`paint`,field:`roomBuilders`,expected:e.roomBuilders,actual:t.roomBuilders}),Mz(e.features,t.features)||n.push({stage:`paint`,field:`features`,expected:e.features,actual:t.features}),JSON.stringify(e.content)!==JSON.stringify(t.content)&&n.push({stage:`paint`,field:`content`,expected:e.content,actual:t.content}),e.rngDraws!==t.rngDraws&&n.push({stage:`paint`,field:`rngDraws`,expected:e.rngDraws,actual:t.rngDraws}),n}function Pz(e,t=2){let n=e(),r=[];for(let i=1;i<t;i++)r.push(...Nz(n,e()));return r}var Fz=23283064365386963e-26;new class e{constructor(){this._seed=0,this._s0=0,this._s1=0,this._s2=0,this._c=0}getSeed(){return this._seed}setSeed(e){return e=e<1?1/e:e,this._seed=e,this._s0=(e>>>0)*Fz,e=e*69069+1>>>0,this._s1=e*Fz,e=e*69069+1>>>0,this._s2=e*Fz,this._c=1,this}getUniform(){let e=2091639*this._s0+this._c*Fz;return this._s0=this._s1,this._s1=this._s2,this._c=e|0,this._s2=e-this._c,this._s2}getUniformInt(e,t){let n=Math.max(e,t),r=Math.min(e,t);return Math.floor(this.getUniform()*(n-r+1))+r}getNormal(e=0,t=1){let n,r,i;do n=2*this.getUniform()-1,r=2*this.getUniform()-1,i=n*n+r*r;while(i>1||i==0);return e+n*Math.sqrt(-2*Math.log(i)/i)*t}getPercentage(){return 1+Math.floor(this.getUniform()*100)}getItem(e){return e.length?e[Math.floor(this.getUniform()*e.length)]:null}shuffle(e){let t=[],n=e.slice();for(;n.length;){let e=n.indexOf(this.getItem(n));t.push(n.splice(e,1)[0])}return t}getWeightedValue(e){let t=0;for(let n in e)t+=e[n];let n=this.getUniform()*t,r,i=0;for(r in e)if(i+=e[r],n<i)return r;return r}getState(){return[this._s0,this._s1,this._s2,this._c]}setState(e){return this._s0=e[0],this._s1=e[1],this._s2=e[2],this._c=e[3],this}clone(){return new e().setState(this.getState())}}().setSeed(Date.now());var Iz=class{getContainer(){return null}setOptions(e){this._options=e}},Lz=class extends Iz{constructor(){super(),this._ctx=document.createElement(`canvas`).getContext(`2d`)}schedule(e){requestAnimationFrame(e)}getContainer(){return this._ctx.canvas}setOptions(e){super.setOptions(e);let t=`${e.fontStyle?`${e.fontStyle} `:``} ${e.fontSize}px ${e.fontFamily}`;this._ctx.font=t,this._updateSize(),this._ctx.font=t,this._ctx.textAlign=`center`,this._ctx.textBaseline=`middle`}clear(){let e=this._ctx.globalCompositeOperation;this._ctx.globalCompositeOperation=`copy`,this._ctx.fillStyle=this._options.bg,this._ctx.fillRect(0,0,this._ctx.canvas.width,this._ctx.canvas.height),this._ctx.globalCompositeOperation=e}eventToPosition(e,t){let n=this._ctx.canvas,r=n.getBoundingClientRect();return e-=r.left,t-=r.top,e*=n.width/r.width,t*=n.height/r.height,e<0||t<0||e>=n.width||t>=n.height?[-1,-1]:this._normalizedEventToPosition(e,t)}};function Rz(e){return e.charAt(0).toUpperCase()+e.substring(1)}function zz(e,...t){let n=zz.map;return e.replace(/%(?:([a-z]+)|(?:{([^}]+)}))/gi,function(r,i,a,o){if(e.charAt(o-1)==`%`)return r.substring(1);if(!t.length)return r;let s=t[0],c=(i||a).split(`,`),l=c.shift()||``,u=n[l.toLowerCase()];if(!u)return r;s=t.shift();let d=s[u].apply(s,c),f=l.charAt(0);return f!=f.toLowerCase()&&(d=Rz(d)),d})}zz.map={s:`toString`};var Bz=class e extends Lz{constructor(){super(),this._spacingX=0,this._spacingY=0,this._canvasCache={}}setOptions(e){super.setOptions(e),this._canvasCache={}}draw(t,n){e.cache?this._drawWithCache(t):this._drawNoCache(t,n)}_drawWithCache(e){let[t,n,r,i,a]=e,o=``+r+i+a,s;if(o in this._canvasCache)s=this._canvasCache[o];else{let e=this._options.border;s=document.createElement(`canvas`);let t=s.getContext(`2d`);if(s.width=this._spacingX,s.height=this._spacingY,t.fillStyle=a,t.fillRect(e,e,s.width-e,s.height-e),r){t.fillStyle=i,t.font=this._ctx.font,t.textAlign=`center`,t.textBaseline=`middle`;let e=[].concat(r);for(let n=0;n<e.length;n++)t.fillText(e[n],this._spacingX/2,Math.ceil(this._spacingY/2))}this._canvasCache[o]=s}this._ctx.drawImage(s,t*this._spacingX,n*this._spacingY)}_drawNoCache(e,t){let[n,r,i,a,o]=e;if(t){let e=this._options.border;this._ctx.fillStyle=o,this._ctx.fillRect(n*this._spacingX+e,r*this._spacingY+e,this._spacingX-e,this._spacingY-e)}if(!i)return;this._ctx.fillStyle=a;let s=[].concat(i);for(let e=0;e<s.length;e++)this._ctx.fillText(s[e],(n+.5)*this._spacingX,Math.ceil((r+.5)*this._spacingY))}computeSize(e,t){return[Math.floor(e/this._spacingX),Math.floor(t/this._spacingY)]}computeFontSize(e,t){let n=Math.floor(e/this._options.width),r=Math.floor(t/this._options.height),i=this._ctx.font;this._ctx.font=`100px `+this._options.fontFamily;let a=Math.ceil(this._ctx.measureText(`W`).width);this._ctx.font=i;let o=a/100*r/n;return o>1&&(r=Math.floor(r/o)),Math.floor(r/this._options.spacing)}_normalizedEventToPosition(e,t){return[Math.floor(e/this._spacingX),Math.floor(t/this._spacingY)]}_updateSize(){let e=this._options,t=Math.ceil(this._ctx.measureText(`W`).width);this._spacingX=Math.ceil(e.spacing*t),this._spacingY=Math.ceil(e.spacing*e.fontSize),e.forceSquareRatio&&(this._spacingX=this._spacingY=Math.max(this._spacingX,this._spacingY)),this._ctx.canvas.width=e.width*this._spacingX,this._ctx.canvas.height=e.height*this._spacingY}};Bz.cache=!1;var Vz={4:[[0,-1],[1,0],[0,1],[-1,0]],8:[[0,-1],[1,-1],[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1]],6:[[-1,-1],[1,-1],[2,0],[1,1],[-1,1],[-2,0]]},Hz=class{constructor(e,t={}){this._lightPasses=e,this._options=Object.assign({topology:8},t)}_getCircle(e,t,n){let r=[],i,a,o;switch(this._options.topology){case 4:a=1,o=[0,1],i=[Vz[8][7],Vz[8][1],Vz[8][3],Vz[8][5]];break;case 6:i=Vz[6],a=1,o=[-1,1];break;case 8:i=Vz[4],a=2,o=[-1,1];break;default:throw Error(`Incorrect topology for FOV computation`)}let s=e+o[0]*n,c=t+o[1]*n;for(let e=0;e<i.length;e++)for(let t=0;t<n*a;t++)r.push([s,c]),s+=i[e][0],c+=i[e][1];return r}},Uz=class extends Hz{compute(e,t,n,r){if(r(e,t,0,1),!this._lightPasses(e,t))return;let i=[],a,o,s,c,l;for(let u=1;u<=n;u++){let n=this._getCircle(e,t,u),d=360/n.length;for(let e=0;e<n.length;e++)if(s=n[e][0],c=n[e][1],a=d*(e-.5),o=a+d,l=!this._lightPasses(s,c),this._visibleCoords(Math.floor(a),Math.ceil(o),l,i)&&r(s,c,u,1),i.length==2&&i[0]==0&&i[1]==360)return}}_visibleCoords(e,t,n,r){if(e<0){let i=this._visibleCoords(0,t,n,r),a=this._visibleCoords(360+e,360,n,r);return i||a}let i=0;for(;i<r.length&&r[i]<e;)i++;if(i==r.length)return n&&r.push(e,t),!0;let a=0;if(i%2){for(;i<r.length&&r[i]<t;)i++,a++;return a!=0&&(n&&(a%2?r.splice(i-a,a,t):r.splice(i-a,a)),!0)}for(;i<r.length&&r[i]<t;)i++,a++;return e==r[i-a]&&a==1?!1:(n&&(a%2?r.splice(i-a,a,e):r.splice(i-a,a,e,t)),!0)}},Wz=class extends Hz{compute(e,t,n,r){if(r(e,t,0,1),!this._lightPasses(e,t))return;let i=[],a,o,s,c,l,u;for(let d=1;d<=n;d++){let n=this._getCircle(e,t,d),f=n.length;for(let e=0;e<f;e++)if(a=n[e][0],o=n[e][1],c=[e?2*e-1:2*f-1,2*f],l=[2*e+1,2*f],s=!this._lightPasses(a,o),u=this._checkVisibility(c,l,s,i),u&&r(a,o,d,u),i.length==2&&i[0][0]==0&&i[1][0]==i[1][1])return}}_checkVisibility(e,t,n,r){if(e[0]>t[0])return(this._checkVisibility(e,[e[1],e[1]],n,r)+this._checkVisibility([0,1],t,n,r))/2;let i=0,a=!1;for(;i<r.length;){let t=r[i],n=t[0]*e[1]-e[0]*t[1];if(n>=0){n==0&&!(i%2)&&(a=!0);break}i++}let o=r.length,s=!1;for(;o--;){let e=r[o],n=t[0]*e[1]-e[0]*t[1];if(n>=0){n==0&&o%2&&(s=!0);break}}let c=!0;if((i==o&&(a||s)||a&&s&&i+1==o&&o%2||i>o&&i%2)&&(c=!1),!c)return 0;let l,u=o-i+1;if(u%2){if(i%2){let e=r[i];l=(t[0]*e[1]-e[0]*t[1])/(e[1]*t[1]),n&&r.splice(i,u,t)}else{let t=r[o];l=(t[0]*e[1]-e[0]*t[1])/(e[1]*t[1]),n&&r.splice(i,u,e)}}else if(i%2){let e=r[i],t=r[o];l=(t[0]*e[1]-e[0]*t[1])/(e[1]*t[1]),n&&r.splice(i,u)}else return n&&r.splice(i,u,e,t),1;let d=(t[0]*e[1]-e[0]*t[1])/(e[1]*t[1]);return l/d}},Gz=[[-1,0,0,1],[0,-1,1,0],[0,-1,-1,0],[-1,0,0,-1],[1,0,0,-1],[0,1,-1,0],[0,1,1,0],[1,0,0,1]],Kz={DiscreteShadowcasting:Uz,PreciseShadowcasting:Wz,RecursiveShadowcasting:class extends Hz{compute(e,t,n,r){r(e,t,0,1);for(let i=0;i<Gz.length;i++)this._renderOctant(e,t,Gz[i],n,r)}compute180(e,t,n,r,i){i(e,t,0,1);let a=(r-1+8)%8,o=(r-2+8)%8,s=(r+1+8)%8;this._renderOctant(e,t,Gz[o],n,i),this._renderOctant(e,t,Gz[a],n,i),this._renderOctant(e,t,Gz[r],n,i),this._renderOctant(e,t,Gz[s],n,i)}compute90(e,t,n,r,i){i(e,t,0,1);let a=(r-1+8)%8;this._renderOctant(e,t,Gz[r],n,i),this._renderOctant(e,t,Gz[a],n,i)}_renderOctant(e,t,n,r,i){this._castVisibility(e,t,1,1,0,r+1,n[0],n[1],n[2],n[3],i)}_castVisibility(e,t,n,r,i,a,o,s,c,l,u){if(!(r<i))for(let d=n;d<=a;d++){let n=-d-1,f=-d,p=!1,m=0;for(;n<=0;){n+=1;let h=e+n*o+f*s,g=t+n*c+f*l,_=(n-.5)/(f+.5),v=(n+.5)/(f-.5);if(!(v>r)){if(_<i)break;if(n*n+f*f<a*a&&u(h,g,d,1),!p)!this._lightPasses(h,g)&&d<a&&(p=!0,this._castVisibility(e,t,d+1,r,_,a,o,s,c,l,u),m=v);else{if(!this._lightPasses(h,g)){m=v;continue}p=!1,r=m}}}if(p)break}}}};.5*(Math.sqrt(3)-1),(3-Math.sqrt(3))/6;var qz=class{constructor(e,t,n,r={}){this._toX=e,this._toY=t,this._passableCallback=n,this._options=Object.assign({topology:8},r),this._dirs=Vz[this._options.topology],this._options.topology==8&&(this._dirs=[this._dirs[0],this._dirs[2],this._dirs[4],this._dirs[6],this._dirs[1],this._dirs[3],this._dirs[5],this._dirs[7]])}_getNeighbors(e,t){let n=[];for(let r=0;r<this._dirs.length;r++){let i=this._dirs[r],a=e+i[0],o=t+i[1];this._passableCallback(a,o)&&n.push([a,o])}return n}},Jz={Dijkstra:class extends qz{constructor(e,t,n,r){super(e,t,n,r),this._computed={},this._todo=[],this._add(e,t,null)}compute(e,t,n){let r=e+`,`+t;if(r in this._computed||this._compute(e,t),!(r in this._computed))return;let i=this._computed[r];for(;i;)n(i.x,i.y),i=i.prev}_compute(e,t){for(;this._todo.length;){let n=this._todo.shift();if(n.x==e&&n.y==t)return;let r=this._getNeighbors(n.x,n.y);for(let e=0;e<r.length;e++){let t=r[e],i=t[0],a=t[1];i+`,`+a in this._computed||this._add(i,a,n)}}}_add(e,t,n){let r={x:e,y:t,prev:n};this._computed[e+`,`+t]=r,this._todo.push(r)}},AStar:class extends qz{constructor(e,t,n,r={}){super(e,t,n,r),this._todo=[],this._done={}}compute(e,t,n){for(this._todo=[],this._done={},this._fromX=e,this._fromY=t,this._add(this._toX,this._toY,null);this._todo.length;){let n=this._todo.shift(),r=n.x+`,`+n.y;if(r in this._done)continue;if(this._done[r]=n,n.x==e&&n.y==t)break;let i=this._getNeighbors(n.x,n.y);for(let e=0;e<i.length;e++){let t=i[e],r=t[0],a=t[1];r+`,`+a in this._done||this._add(r,a,n)}}let r=this._done[e+`,`+t];if(r)for(;r;)n(r.x,r.y),r=r.prev}_add(e,t,n){let r=this._distance(e,t),i={x:e,y:t,prev:n,g:n?n.g+1:0,h:r},a=i.g+i.h;for(let e=0;e<this._todo.length;e++){let t=this._todo[e],n=t.g+t.h;if(a<n||a==n&&r<t.h){this._todo.splice(e,0,i);return}}this._todo.push(i)}_distance(e,t){switch(this._options.topology){case 4:return Math.abs(e-this._fromX)+Math.abs(t-this._fromY);case 6:let n=Math.abs(e-this._fromX),r=Math.abs(t-this._fromY);return r+Math.max(0,(n-r)/2);case 8:return Math.max(Math.abs(e-this._fromX),Math.abs(t-this._fromY))}}}};function Yz(e,t){return ur(e,t)}function Xz(e,t){let n=[],r=e.x,i=e.y,a=Math.abs(t.x-e.x),o=-Math.abs(t.y-e.y),s=e.x<t.x?1:-1,c=e.y<t.y?1:-1,l=a+o;for(;n.push({x:r,y:i}),r!==t.x||i!==t.y;){let e=l*2;e>=o&&(l+=o,r+=s),e<=a&&(l+=a,i+=c)}return n}function Zz(e,t,n,r={}){let i=e.shape===`hex`?Xn(t,n):Xz(t,n),a=r.stop??`opaque`,o=[],s=null;for(let t of i)if(o.push(t),o.length!==1&&a!==`none`&&(a===`outside`&&!e.inside(t.x,t.y)||a===`opaque`&&e.inside(t.x,t.y)&&!e.transparent(t.x,t.y)||a===`impassable`&&e.inside(t.x,t.y)&&!e.passable(t.x,t.y))){s=t;break}return{cells:o,stop:s}}function Qz(e,t,n){let r=e.shape===`hex`?Xn(t,n):Xz(t,n);for(let t=1;t<r.length-1;t++)if(!e.transparent(r[t].x,r[t].y))return!1;return!0}function $z(e,t,n,r){return!((e.shape===`hex`?Jn(t,n):Yz(t,n))>r.range||(r.requireLineOfSight??!0)&&!Qz(e,t,n))}function eB(e,t,n){switch(n.kind){case`single`:return[t];case`line`:return Xz(e,t);case`cone`:return rB(e,t,n.width);case`burst`:{let e=[],r=n.radius;for(let n=-r;n<=r;n++)for(let i=-r;i<=r;i++)i*i+n*n>r*r||e.push({x:t.x+i,y:t.y+n});return e}}}function tB(e,t,n,r){return e.shape===`hex`?r.kind===`single`?[{...n}]:r.kind===`line`?Xn(t,n):r.kind===`burst`?Zn(n,r.radius):nB(t,n,r.width):eB(t,n,r)}function nB(e,t,n){let r=Jn(e,t);if(r===0)return[{...e}];let i=Xn(e,t),a=[];for(let t=1;t<=r;t++){let o=i[t],s=Math.round(t/r*n);for(let n of Zn(o,s))Jn(e,n)===t&&a.push(n)}return a}function rB(e,t,n){let r=t.x-e.x,i=t.y-e.y,a=Math.max(Math.abs(r),Math.abs(i));if(a===0)return[{...e}];let o=Math.sign(r),s=Math.sign(i),c=r!==0&&i!==0?o:s,l=r!==0&&i!==0?-s:o,u=[];for(let t=1;t<=a;t++){let r=e.x+o*t,i=e.y+s*t,d=Math.round(t/a*n);for(let e=-d;e<=d;e++)u.push({x:r+c*e,y:i+l*e})}return u}var iB=.5;function aB(e){return e<0?-Math.round(-e):Math.round(e)}function oB(e,t,n,r){if(!Number.isFinite(r.degrees)||r.degrees<0)throw Error(`a cone sector needs a finite non-negative angle in degrees`);if(!Number.isFinite(r.range)||r.range<0)throw Error(`a cone sector needs a finite non-negative range`);let i=n.x-t.x,a=n.y-t.y;if(i===0&&a===0)return[{...t}];let o=Math.atan2(a,i),s=r.degrees*Math.PI/360,c=Math.max(1,Math.round(r.degrees/iB)),l=r.stop??`opaque`,u=new Set,d=[];for(let n=0;n<=c;n++){let i=o-s+2*s*n/c,a={x:t.x+aB(Math.cos(i)*r.range),y:t.y+aB(Math.sin(i)*r.range)};for(let n of Zz(e,t,a,{stop:l}).cells){if(n.x===t.x&&n.y===t.y||!e.inside(n.x,n.y))continue;let r=e.index(n.x,n.y);u.has(r)||(u.add(r),d.push({x:n.x,y:n.y}))}}return d}function sB(e,t,n,r){let i=new Set,a=[],o=t;for(let t=0;t<n;t++){let t=-1,n=r+1;for(let a=0;a<e.length;a++){if(i.has(a))continue;let s=Yz(o,e[a]);s<=r&&s<n&&(n=s,t=a)}if(t===-1)break;i.add(t),a.push(e[t]),o=e[t]}return a}function cB(e,t,n=1){for(let n of t)if(e<=n.max)return n.multiplier;return n}function lB(e,t){return t.length===0?1:t[Math.min(e,t.length-1)]}function uB(e,t,n,r){let i=[];for(let a=1;a<=r;a++){let r={x:t.x+n.x*a,y:t.y+n.y*a};if(!e.passable(r.x,r.y))break;i.push(r)}return i}var dB=class{constructor(e,t){if(this.onMove=new p,this.onConfirm=new p,this.onCancel=new p,!Number.isFinite(t.range)||t.range<0)throw Error(`targeting range must be a finite non-negative number`);this.level=e,this.origin={...t.origin},this.range=t.range,this.requireLineOfSight=t.requireLineOfSight??!0,this.validate=t.validate,this.shape=t.shape??{kind:`single`},this.cursor={...t.cursor??t.origin}}get target(){return{...this.cursor}}get distance(){return this.level.shape===`hex`?Jn(this.origin,this.cursor):Yz(this.origin,this.cursor)}get inRange(){return this.distance<=this.range}get inSight(){return Qz(this.level,this.origin,this.cursor)}get valid(){return!this.inRange||this.requireLineOfSight&&!this.inSight?!1:!this.validate||this.validate(this.cursor)}move(e,t){if(this.level.shape===`hex`){let n=this.level.neighbors(this.cursor.x,this.cursor.y).find(n=>n.x-this.cursor.x===e&&n.y-this.cursor.y===t);n&&this.moveTo(n);return}this.moveTo({x:this.cursor.x+e,y:this.cursor.y+t})}moveTo(e){this.level.inside(e.x,e.y)&&(this.cursor={x:e.x,y:e.y},this.onMove.dispatch({...this.cursor}))}setShape(e){this.shape=e}preview(){return this.valid?tB(this.level,this.origin,this.cursor,this.shape):[]}confirm(){if(!this.valid)return null;let e={origin:{...this.origin},target:{...this.cursor},shape:this.shape,cells:this.preview()};return this.onConfirm.dispatch(e),e}cancel(){this.onCancel.dispatch()}},fB=class{constructor(e){this.visible=new Set,this.explored=new Set,this.light=new Map,this.level=e,this.fov=e.shape===`hex`?null:new Kz.PreciseShadowcasting((t,n)=>e.transparent(t,n))}update(e,t,n=this.level.viewDistance??Math.max(this.level.width,this.level.height),r){if(this.visible.clear(),this.light.clear(),r){this.updateFromHeight(e,t,n,r);return}if(this.fov){this.fov.compute(e,t,n,(e,t,n,r)=>{if(!this.level.inside(e,t))return;let i=this.level.index(e,t);this.visible.add(i),this.explored.add(i),this.light.set(i,r)});return}let i={x:e,y:t};for(let e of Zn(i,n)){if(!this.level.inside(e.x,e.y))continue;let t=Xn(i,e);t.slice(1,-1).some(e=>!this.level.inside(e.x,e.y)||!this.level.transparent(e.x,e.y))||this.lightCell(e.x,e.y,t.length-1,n)}}lightCell(e,t,n,r){let i=this.level.index(e,t);this.visible.add(i),this.explored.add(i),this.light.set(i,r===0?1:Math.max(0,1-n/(r+1)))}updateFromHeight(e,t,n,r){let i=r.height??r.heights.heightAt(e,t),a={x:e,y:t};if(this.level.shape===`hex`){for(let e of Zn(a,n)){if(!this.level.inside(e.x,e.y))continue;let t=Xn(a,e);this.heightBlocked(t,r.heights,i,r.heights.heightAt(e.x,e.y))||this.lightCell(e.x,e.y,t.length-1,n)}return}for(let o=t-n;o<=t+n;o++)for(let t=e-n;t<=e+n;t++){if(!this.level.inside(t,o)||Yz(a,{x:t,y:o})>n)continue;let e=Xz(a,{x:t,y:o});this.heightBlocked(e,r.heights,i,r.heights.heightAt(t,o))||this.lightCell(t,o,e.length-1,n)}}heightBlocked(e,t,n,r){let i=Math.max(n,r);for(let n=1;n<e.length-1;n++){let r=e[n];if(!this.level.inside(r.x,r.y)||!this.level.transparent(r.x,r.y)||t.heightAt(r.x,r.y)>i)return!0}return!1}isVisible(e,t){return this.visible.has(this.level.index(e,t))}isExplored(e,t){return this.explored.has(this.level.index(e,t))}lightAt(e,t){return this.light.get(this.level.index(e,t))??0}reset(){this.visible.clear(),this.explored.clear(),this.light.clear()}revealAll(){for(let e=0;e<this.level.cellCount;e++)this.explored.add(e)}},pB=class{constructor(e){this.level=e,this.heights=new Int32Array(e.cellCount)}heightAt(e,t){return this.level.inside(e,t)?this.heights[this.level.index(e,t)]:0}set(e,t,n){if(!Number.isInteger(n))throw Error(`a cell's height must be a whole number, got ${n}`);this.level.inside(e,t)&&(this.heights[this.level.index(e,t)]=n)}},mB=class{constructor(e){this.level=e}passable(e){let t=e.blocked;return(e,n)=>this.level.passable(e,n)?!t?.has(this.level.index(e,n)):!1}stepper(e){let t=this.passable(e),n=e.heights;if(!n)return(e,n,r,i)=>this.level.inside(e,n)&&this.level.inside(r,i)&&t(r,i);let r=e.climb??1;if(!Number.isInteger(r)||r<0)throw Error(`a climb limit must be a non-negative whole number, got ${e.climb}`);return(e,i,a,o)=>this.level.inside(e,i)&&this.level.inside(a,o)&&t(a,o)&&n.heightAt(a,o)-n.heightAt(e,i)<=r}find(e,t,n={}){if(this.level.shape===`hex`||n.heights){let r=this.distanceMap(t,n),i=[],a=e;for(let e=0;e<this.level.cellCount;e++){let e=this.descend(a,r,n);if(!e||(i.push(e),e.x===t.x&&e.y===t.y))break;a=e}return i}let r=new Jz.AStar(t.x,t.y,this.passable(n),{topology:n.topology??8}),i=[];return r.compute(e.x,e.y,(e,t)=>i.push({x:e,y:t})),i.slice(1)}step(e,t,n={}){return this.find(e,t,n)[0]??null}distanceMap(e,t={}){let n=new Int32Array(this.level.cellCount).fill(-1),r=this.passable(t),i=this.stepper(t);if(!r(e.x,e.y))return n;let a=[this.level.index(e.x,e.y)];n[a[0]]=0;for(let e=0;e<a.length;e++){let r=a[e],o=this.level.xOf(r),s=this.level.yOf(r),c=n[r]+1;this.level.forEachNeighbor(o,s,t.topology??8,(e,t)=>{if(!i(e,t,o,s))return;let r=this.level.index(e,t);n[r]===-1&&(n[r]=c,a.push(r))})}return n}descend(e,t,n={}){let r=this.stepper(n),i=t[this.level.index(e.x,e.y)];if(i<=0)return null;let a=null,o=i;return this.level.forEachNeighbor(e.x,e.y,n.topology??8,(n,i)=>{if(!r(e.x,e.y,n,i))return;let s=t[this.level.index(n,i)];s!==-1&&s<o&&(o=s,a={x:n,y:i})}),a}autoExplore(e,t,n={}){let r=this.passable(n),i=this.stepper(n);if(!r(e.x,e.y))return[];let a=new Map,o=new Set([this.level.index(e.x,e.y)]),s=[e];for(let e=0;e<s.length;e++){let r=s[e];if(e>0&&!t.isExplored(r.x,r.y))return this.reconstruct(a,r);this.level.forEachNeighbor(r.x,r.y,n.topology??8,(e,t)=>{if(!i(r.x,r.y,e,t))return;let n=this.level.index(e,t);o.has(n)||(o.add(n),a.set(n,r),s.push({x:e,y:t}))})}return[]}reconstruct(e,t){let n=[t],r=e.get(this.level.index(t.x,t.y));for(;r;)n.push(r),r=e.get(this.level.index(r.x,r.y));return n.reverse()}},hB=class e{constructor(){this.entries=[],this.sequence=0,this.now=0}get size(){return this.entries.length}get actors(){return this.entries.map(e=>e.actor)}has(e){return this.entries.some(t=>t.actor===e)}add(e,t=0,n=e.priority??0){if(!Number.isFinite(t)||t<0)throw Error(`scheduler delay must be finite and non-negative`);if(!Number.isFinite(n))throw Error(`scheduler priority must be finite`);this.entries.push({actor:e,time:this.now+t,sequence:this.sequence++,priority:n}),this.sort()}remove(e){let t=this.entries.findIndex(t=>t.actor===e);t!==-1&&this.entries.splice(t,1)}clear(){this.entries.length=0,this.now=0,this.sequence=0}peek(){let e=this.entries[0];return e?(this.now=Math.max(this.now,e.time),e.actor):null}spend(e){let t=this.entries[0];if(!t)return;let n=t.actor.speed??1;t.time=this.now+e/(n>0?n:1),t.sequence=this.sequence++,this.sort()}postpone(e,t){let n=this.entries.find(t=>t.actor===e);n&&(n.time+=t,n.sequence=this.sequence++,this.sort())}timeOf(e){return this.entries.find(t=>t.actor===e)?.time??null}toJSON(e){return{now:this.now,sequence:this.sequence,entries:this.entries.map(t=>({id:e(t.actor),time:t.time,sequence:t.sequence,...t.priority===0?{}:{priority:t.priority}}))}}static restore(t,n){let r=new e;return r.now=t.now,r.sequence=t.sequence,r.entries=t.entries.map(e=>({actor:n(e.id),time:e.time,sequence:e.sequence,priority:e.priority??0})),r.sort(),r}sort(){this.entries.sort((e,t)=>e.time-t.time||t.priority-e.priority||e.sequence-t.sequence)}};_e();function gB(e,t,n,r,i,a={}){let o=a.sightRadius??6,s=a.fleeBelow??0;if((a.disposition??`hostile`)!==`hostile`&&a.provoked!==!0)return{state:`wander`,step:_B(e,n,a)};let c=new fB(e);return c.update(n.x,n.y,o),c.isVisible(i.x,i.y)?r<=s?{state:`flee`,step:vB(e,n,i,a)}:{state:`hunt`,step:t.step(n,i,a)}:{state:`wander`,step:_B(e,n,a)}}function _B(e,t,n){return re(yB(e,t,n))}function vB(e,t,n,r){let i=yB(e,t,r),a=null,o=bB(t,n);for(let e of i){let t=bB(e,n);t>o&&(o=t,a=e)}return a}function yB(e,t,n){let r=n.blocked,i=[];for(let[a,o]of uz(n.topology??8)){let n={x:t.x+a,y:t.y+o};e.passable(n.x,n.y)&&(r?.has(e.index(n.x,n.y))||i.push(n))}return i}function bB(e,t){return(e.x-t.x)**2+(e.y-t.y)**2}var xB=class e{constructor(e){this.revealedKind=new Map,this.discovered=new Set,this.level=e}conceal(e,t,n,r){let i=this.level.index(e,t);this.revealedKind.set(i,r),this.discovered.delete(i),this.level.set(e,t,n)}isSecret(e,t){let n=this.level.index(e,t);return this.revealedKind.has(n)&&!this.discovered.has(n)}isDiscovered(e,t){return this.discovered.has(this.level.index(e,t))}discover(e,t){if(!this.isSecret(e,t))return!1;let n=this.level.index(e,t);return this.discovered.add(n),this.level.set(e,t,this.revealedKind.get(n)),!0}toJSON(){return{revealed:[...this.revealedKind],discovered:[...this.discovered]}}static fromJSON(t,n){let r=new e(t);for(let[e,t]of n.revealed)r.revealedKind.set(e,t);for(let e of n.discovered)r.discovered.add(e);return r}},SB=class e{constructor(e){this.openKind=new Map,this.closedKind=new Map,this.lockedBy=new Map,this.open_=new Map,this.level=e}place(e,t,n){let r=this.level.index(e,t);this.openKind.set(r,n.open),this.closedKind.set(r,n.closed),this.open_.set(r,n.startOpen??!1),n.locked===void 0?this.lockedBy.delete(r):this.lockedBy.set(r,n.locked),this.level.set(e,t,this.open_.get(r)?n.open:n.closed)}isDoor(e,t){return this.open_.has(this.level.index(e,t))}isOpen(e,t){return this.open_.get(this.level.index(e,t))===!0}isLocked(e,t){return this.lockedBy.has(this.level.index(e,t))}requiredKey(e,t){return this.lockedBy.get(this.level.index(e,t))}open(e,t){let n=this.level.index(e,t);return!this.open_.has(n)||this.open_.get(n)||this.lockedBy.has(n)?!1:(this.open_.set(n,!0),this.level.set(e,t,this.openKind.get(n)),!0)}close(e,t){let n=this.level.index(e,t);return!this.open_.has(n)||!this.open_.get(n)?!1:(this.open_.set(n,!1),this.level.set(e,t,this.closedKind.get(n)),!0)}unlock(e,t){let n=this.level.index(e,t);return this.lockedBy.has(n)?(this.lockedBy.delete(n),!0):!1}toJSON(){let e=[];for(let[t,n]of this.openKind)e.push({cell:t,open:n,closed:this.closedKind.get(t),locked:this.lockedBy.get(t),isOpen:this.open_.get(t)===!0});return{doors:e}}static fromJSON(t,n){let r=new e(t);for(let e of n.doors){let n=t.xOf(e.cell),i=t.yOf(e.cell);r.place(n,i,{open:e.open,closed:e.closed,locked:e.locked,startOpen:e.isOpen})}return r}},CB=class e{constructor(e=[]){this.current=0;for(let t=1;t<e.length;t++)if(e[t]>=e[t-1])throw Error(`boss phase thresholds must descend`);this.thresholds=e}get phase(){return this.current}check(e){let t=0;for(;t<this.thresholds.length&&e<=this.thresholds[t];)t++;let n=[];for(;this.current<t;)this.current++,n.push(this.current);return n}reset(){this.current=0}toJSON(){return{phase:this.current}}static fromJSON(t,n){let r=new e(t);return r.current=n.phase,r}},wB=class e{constructor(e){this.remaining=new Map,this.cooldowns=new Map(Object.entries(e))}advance(e=1){for(let[t,n]of this.remaining)n<=e?this.remaining.delete(t):this.remaining.set(t,n-e)}ready(){let e=[];for(let t of this.cooldowns.keys())this.remaining.has(t)||e.push(t);return e}use(e){let t=this.cooldowns.get(e);return t===void 0||this.remaining.has(e)?!1:(t>0&&this.remaining.set(e,t),!0)}toJSON(){return{remaining:[...this.remaining]}}static fromJSON(t,n){let r=new e(t);for(let[e,t]of n.remaining)r.remaining.set(e,t);return r}},TB=class extends S{modifyDamage(e,t,n){let r={attacker:e,defender:t,amount:n,prevented:!1};return this.emit(`beforeDamage`,r),r.amount=Math.max(0,r.amount),r.amount===0&&(r.prevented=!0),r}},EB=class{constructor(e){this.detected=!1,this.radius=e.radius}get isDetected(){return this.detected}checkDetection(e,t){if(this.detected)return!1;let n=t.some(t=>Yz(e,t)<=this.radius);return n&&(this.detected=!0),n}reset(){this.detected=!1}},DB=class e{constructor(e){this.streak=0,this.lastTurn=-1/0,this.window=e}get count(){return this.streak}trigger(e){return this.streak=e-this.lastTurn<=this.window?this.streak+1:1,this.lastTurn=e,this.streak}isActive(e){return e-this.lastTurn<=this.window}reset(){this.streak=0,this.lastTurn=-1/0}toJSON(){return{streak:this.streak,lastTurn:this.lastTurn}}static fromJSON(t,n){let r=new e(t);return r.streak=n.streak,r.lastTurn=n.lastTurn,r}},OB=class e{constructor(e){if(this.index=-1,this.remaining=0,e.length===0)throw Error(`a multi-stage ability needs at least one stage`);this.stages=e}get active(){return this.index>=0}get stage(){return this.index>=0?this.stages[this.index]:null}start(){return!this.active&&(this.index=0,this.remaining=this.stages[0].duration,!0)}advance(){return!this.active||(this.remaining--,this.remaining>0)?null:(this.index++,this.index>=this.stages.length?(this.index=-1,`done`):(this.remaining=this.stages[this.index].duration,this.stages[this.index].name))}cancel(){this.index=-1,this.remaining=0}toJSON(){return{index:this.index,remaining:this.remaining}}static fromJSON(t,n){let r=new e(t);return r.index=n.index,r.remaining=n.remaining,r}},kB=class e{constructor(e){if(this.index=0,this.state=`idle`,typeof e.damage!=`function`&&!Number.isFinite(e.damage))throw Error(`beam damage must be a finite number or a function`);if(typeof e.damage==`number`&&e.damage<0)throw Error(`beam damage must be non-negative`);if(this.options=e,this.shape=e.shape??(e.fronts?`fronts`:`line`),e.fronts){let t=e.fronts([{...e.from}],0);this.fronts=t.length?[t.map(e=>({...e}))]:[]}else this.fronts=tB(e.level,e.from,e.target,{kind:`line`}).slice(1).map(e=>[{...e}])}get active(){return this.state===`active`}get done(){return this.state===`done`||this.state===`blocked`||this.state===`cancelled`}get beamShape(){return this.shape}get currentPath(){return this.fronts.flat().map(e=>({...e}))}start(){return this.state===`idle`&&(this.state=this.fronts.length===0?`done`:`active`,!0)}advance(){if(this.state!==`active`)return this.inactiveStep();let e=this.fronts[this.index]??[],t=Math.max(0,this.fronts.length-this.index-1),n=[],r=[],i=0;for(let a of e){let e={cell:{...a},step:this.index,remaining:t};if(!this.blocked(a,e)){n.push({...a}),this.options.onCell?.({...a},e);for(let t of this.options.targetsAt?.(a)??[]){let n=typeof this.options.damage==`function`?this.options.damage(t,e):this.options.damage;if(!Number.isFinite(n)||n<0)throw Error(`beam damage callback must return a non-negative finite number`);i+=n,r.push(t),this.options.applyDamage?.(t,n,e)}}}let a=this.index;if(this.index++,this.options.fronts&&n.length>0){let e=this.options.fronts(n.map(e=>({...e})),this.index);e.length&&this.fronts.push(e.map(e=>({...e})))}return n.length===0?this.state=`blocked`:this.index>=this.fronts.length&&(this.state=`done`),{status:n.length===0?`blocked`:this.state,cell:n[0]?{...n[0]}:null,cells:n.map(e=>({...e})),step:a,remaining:t,targets:[...r],damage:i}}cancel(){(this.state===`active`||this.state===`idle`)&&(this.state=`cancelled`)}toJSON(){return{state:this.state,fronts:this.fronts.map(e=>e.map(e=>({...e}))),index:this.index,shape:this.shape}}static fromJSON(t,n){let r=n.shape??(t.fronts?`fronts`:`line`);if(t.shape!==void 0&&t.shape!==r)throw Error(`beam save is shape "${r}", not "${t.shape}"`);let i=Object.create(e.prototype);return i.options=t,i.shape=r,i.fronts=n.fronts?n.fronts.map(e=>e.map(e=>({...e}))):(n.path??[]).map(e=>[{...e}]),i.index=n.index,i.state=n.state,i}blocked(e,t){let n=this.options.blocker??(this.options.stopAtOpaque===!1?`none`:`terrain`),r=!1;return n===`terrain`?r=!this.options.level.inside(e.x,e.y)||!this.options.level.transparent(e.x,e.y):n!==`none`&&(r=n({...e},t)===!0),r||this.options.isBlocked?.({...e},t)===!0}inactiveStep(){return{status:this.state,cell:null,cells:[],step:this.index,remaining:Math.max(0,this.fronts.length-this.index),targets:[],damage:0}}};_e();function AB(e,t={}){return(t.within?[...t.within]:NB(e.cellCount)).filter(n=>!(t.occupied?.has(n)||t.terrain&&!t.terrain.has(e.terrain[n])))}function jB(e,t,n){let r=new Set([t]),i=[t];for(let t=0;t<Math.max(0,n);t++){let t=[];for(let n of i)e.forEachNeighbor(e.xOf(n),e.yOf(n),8,(n,i)=>{if(!e.inside(n,i))return;let a=e.index(n,i);r.has(a)||(r.add(a),t.push(a))});i=t}return r.delete(t),[...r]}function MB(e,t){let n=[...new Set(e)];oe(n);let r=n.slice(0,Math.max(0,t));return{cells:r,trace:{requested:t,available:n.length,selected:r}}}function NB(e){let t=Array(e);for(let n=0;n<e;n++)t[n]=n;return t}var PB=l({AbilityCycle:()=>wB,BossPhases:()=>CB,CombatHooks:()=>TB,DUNGEON_KINDS:()=>xz,Doors:()=>SB,Elevation:()=>pB,FLOOR:()=>fz,FeatureLayer:()=>Oz,FieldOfView:()=>fB,Level:()=>pz,MultiStageAbility:()=>OB,MultiTurnBeam:()=>kB,Pathfinder:()=>mB,Scheduler:()=>hB,Secrets:()=>xB,Stealth:()=>EB,TargetingController:()=>dB,TriggerTracker:()=>DB,WALL:()=>dz,areaFalloffMultiplier:()=>lB,ballistica:()=>Zz,canTarget:()=>$z,candidateCells:()=>AB,cellsNear:()=>jB,chainTargets:()=>sB,chebyshevDistance:()=>Yz,checkDeterminism:()=>Pz,compareDungeonArtifacts:()=>Nz,coneCells:()=>rB,coneSector:()=>oB,decideMonsterAI:()=>gB,eligibleBuilders:()=>yz,findFreeCell:()=>Ez,furthestRoom:()=>Dz,generateDungeon:()=>Cz,generateDungeonGraph:()=>Sz,hallBuilder:()=>gz,hasLineOfSight:()=>Qz,hexConeCells:()=>nB,knockbackPath:()=>uB,neighbourOffsets:()=>uz,pickBuilder:()=>bz,rangeMultiplier:()=>cB,rectCenter:()=>mz,rectsOverlap:()=>hz,resolveArea:()=>eB,resolveAreaOnLevel:()=>tB,rollRoster:()=>kz,selectDistinctCells:()=>MB,traceLine:()=>Xz});function FB(e,t){let n=e=>t.filter(t=>t.op===e).sort((e,t)=>(e.order??0)-(t.order??0)),r=e;for(let e of n(`add`))r+=e.value;for(let e of n(`multiply`))r*=e.value;for(let e of n(`set`))r=e.value;return r}var IB=class e{constructor(e){this.modifiers=[],this.cache=null,this.baseValues={...e.base},this.derived=e.derived??[]}base(e){return this.baseValues[e]??0}setBase(e,t){this.baseValues[e]=t,this.cache=null}addModifier(e){this.modifiers.push(e),this.cache=null}removeModifier(e){let t=this.modifiers.indexOf(e);t!==-1&&this.modifiers.splice(t,1),this.cache=null}removeModifiersFrom(e){this.modifiers=this.modifiers.filter(t=>t.source!==e),this.cache=null}get(e){return this.resolveAll()[e]??0}resolveAll(){if(this.cache)return this.cache;let e={...this.baseValues};for(let t of Object.keys(e))e[t]=FB(e[t],this.modifiersFor(t));for(let t of this.derived)e[t.name]=FB(t.from(e),this.modifiersFor(t.name));return this.cache=e,e}modifiersFor(e){return this.modifiers.filter(t=>t.stat===e)}toJSON(){return{base:{...this.baseValues}}}static fromJSON(t,n){let r=new e(t);return r.baseValues={...t.base,...n.base},r.cache=null,r}};function LB(e,t,n){return{maxLevel:n,experienceFor:n=>n<=1?0:Math.round(e*(n-1)**t)}}var RB=class e{constructor(e,t={}){this.curve=e,this.level=t.level??1,this.experience=t.experience??this.curve.experienceFor(this.level)}get experienceToNext(){return this.level>=this.curve.maxLevel?null:this.curve.experienceFor(this.level+1)-this.experience}addExperience(e){this.experience+=e;let t=0;for(;this.level<this.curve.maxLevel&&this.experience>=this.curve.experienceFor(this.level+1);)this.level++,t++;return t}toJSON(){return{level:this.level,experience:this.experience}}static fromJSON(t,n){return new e(t,n)}};_e();function zB(e,t,n=()=>ne(1,20)){return e+n()>=t}var BB=class e{constructor(e,t={}){this.available=0,this.stats=e,this.capFor=t.cap??(()=>1/0),this.costFor=t.cost??(()=>1)}get points(){return this.available}grant(e){this.available+=e}canSpend(e){return this.nextRankCost(e)!==null}spend(e){let t=this.nextRankCost(e);if(t===null)return!1;let n=this.stats.base(e);return this.available-=t,this.stats.setBase(e,n+1),!0}nextRankCost(e){let t=this.stats.base(e);if(t>=this.capFor(e))return null;let n=this.costFor(e,t+1);return this.available>=n?n:null}toJSON(){return{points:this.available}}static fromJSON(t,n,r){let i=new e(t,n);return i.available=r.points,i}},VB=class e{constructor(e,t=null,n={}){this.worn=new Map,this.names=new Set(e),this.stats=t,this.isSlotLocked=n.locked??(()=>!1)}get(e){return this.worn.get(e)}isLocked(e){let t=this.worn.get(e);return t!==void 0&&this.isSlotLocked(e,t)}equip(e,t){if(this.assertSlot(e),this.isLocked(e))return;let n=this.unequip(e);return this.wear(e,t),n}wear(e,t){this.worn.set(e,t);for(let e of t.modifiers??[])this.stats?.addModifier({...e,source:t})}unequip(e){let t=this.worn.get(e);if(t&&!this.isSlotLocked(e,t))return this.worn.delete(e),this.stats?.removeModifiersFrom(t),t}get slots(){return[...this.names]}assertSlot(e){if(!this.names.has(e))throw Error(`no such equipment slot: "${e}"`)}toJSON(e){return{worn:[...this.worn].map(([t,n])=>[t,e(n)])}}static fromJSON(t,n){let r=new e(t.slots,t.stats??null,{locked:t.locked});for(let[e,i]of n.worn)r.assertSlot(e),r.wear(e,t.resolve(i));return r}},HB=class e{constructor(e={}){this.slots=[],this.capacity=e.capacity}get items(){return this.slots}get totalWeight(){return this.slots.reduce((e,t)=>e+this.weightOf(t),0)}weightOf(e){return(e.weight??0)*e.quantity+(e.contents?.totalWeight??0)}find(e,t){return this.slots.find(n=>n.id===e&&(t===void 0||n.instanceId===t))}add(e){if(!Number.isFinite(e.quantity)||e.quantity<=0||e.weight!==void 0&&(!Number.isFinite(e.weight)||e.weight<0)||this.capacity!==void 0&&this.totalWeight+this.weightOf(e)>this.capacity)return!1;if(e.stackable){let t=this.slots.find(t=>t.id===e.id&&t.stackable&&t.instanceId===e.instanceId);if(t)return t.quantity+=e.quantity,!0}return this.slots.push({...e}),!0}remove(e,t,n){if(t!==void 0&&(!Number.isFinite(t)||t<=0))return;let r=this.slots.findIndex(t=>t.id===e&&(n===void 0||t.instanceId===n));if(r===-1)return;let i=this.slots[r];i.quantity-=t??i.quantity,i.quantity<=0&&this.slots.splice(r,1)}take(e,t=1,n){if(!Number.isFinite(t)||t<=0)return;let r=this.slots.findIndex(t=>t.id===e&&(n===void 0||t.instanceId===n));if(r===-1)return;let i=this.slots[r],a=Math.min(Math.floor(t),i.quantity);if(a<=0)return;let o={...i,quantity:a};return i.quantity-=a,i.quantity<=0&&this.slots.splice(r,1),o}toJSON(){return{capacity:this.capacity,slots:this.slots.map(e=>({id:e.id,quantity:e.quantity,instanceId:e.instanceId,identified:e.identified,cursed:e.cursed,blessed:e.blessed,level:e.level,affix:e.affix,durability:e.durability,maxDurability:e.maxDurability,contents:e.contents?.toJSON()}))}}static fromJSON(t,n){let r=new e({capacity:n.capacity});return r.slots=n.slots.map(n=>{let r=t.get(n.id);if(!r)throw Error(`Inventory.fromJSON: no definition for item "${n.id}"`);let{contents:i,...a}=n,o={...r,...UB(a),id:n.id,quantity:n.quantity};return i&&(o.contents=e.fromJSON(t,i)),o}),r}};function UB(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function WB(e,t){return t.matches?t.matches(e):t.category===void 0?typeof t.id==`string`?e.id===t.id:(t.id??[]).includes(e.id):e.category===t.category}function GB(e){return e.matches!==void 0||e.category!==void 0||e.id!==void 0}function KB(e,t){let n=new Map;for(let t of e.items)n.set(t,t.quantity);let r=new Map;for(let i of t.ingredients){if(!GB(i))throw Error(`recipe ingredient must name an id, a category, or a matches predicate`);if(!Number.isFinite(i.quantity)||i.quantity<=0)throw Error(`recipe ingredient quantity must be a positive number`);let t=i.quantity;for(let a of e.items){if(t<=0)break;let e=n.get(a)??0;if(e<=0||!WB(a,i))continue;let o=Math.min(e,t);n.set(a,e-o),t-=o,r.set(a,(r.get(a)??0)+o)}if(t>0)return!1}for(let[t,n]of r)e.remove(t.id,n,t.instanceId);if(e.add(t.result))return!0;for(let[t,n]of r)e.add({...t,quantity:n});return!1}function qB(e,t){let n=e.add({duration:t.duration,tick:e=>t.tick?.(e),onExpire:t.onExpire});return{cancel:()=>{e.remove(n),t.onExpire()}}}function JB(e,t,n){let r=Symbol(`statusEffect`);for(let t of n.modifiers)e.addModifier({...t,source:r});return qB(t,{duration:n.duration,tick:n.tick,onExpire:()=>e.removeModifiersFrom(r)})}_e();function YB(e,t={}){let n=e.entries.filter(e=>e.weight>0&&(t.curse===void 0||!!e.curse===t.curse)&&(t.predicate?.(e)??!0));if(n.length===0)return null;let r=ie(n.map(e=>e.weight));return r===null?null:n[r]}function XB(e){return e.affix}function ZB(e,t){let n=e.affix!==void 0;e.affix=t.id,t.curse?e.cursed=!0:n&&(e.cursed=!1)}function QB(e){e.affix!==void 0&&(e.cursed=!1),delete e.affix}function $B(e,t){if(e.affix===void 0){QB(t);return}t.affix=e.affix,t.cursed=e.cursed??!1}function eV(e,t){return!(e.trigger!==t.trigger||e.kinds&&(t.kind===void 0||!e.kinds.includes(t.kind)))}function tV(e){e.identified=!0}function nV(e,t,n=`keep`){return Number.isFinite(t)?(e.level=(e.level??0)+t,n===`remove`&&QB(e),e.level):e.level??0}function rV(e,t){return e.maxDurability===void 0?!1:!Number.isFinite(t)||t<=0?(e.durability??e.maxDurability)<=0:(e.durability=Math.max(0,(e.durability??e.maxDurability)-t),e.durability<=0)}function iV(e,t){e.maxDurability!==void 0&&(!Number.isFinite(t)||t<=0||(e.durability=Math.min(e.maxDurability,(e.durability??e.maxDurability)+t)))}function aV(e,t,n){let r=new Map;for(let t of Object.keys(n.fields))r.set(t,e[t]),e[t]=n.fields[t];return qB(t,{duration:n.duration,tick:n.tick,onExpire:()=>{for(let[t,n]of r)e[t]=n}})}var oV=class e{constructor(e){this.progress=0,this.max=e.max,this.regenRate=e.regenRate,this.value=e.current??e.max}get current(){return this.value}canAfford(e){return this.value>=e}spend(e){return this.canAfford(e)?(this.value-=e,!0):!1}refund(e=1){let t=Math.min(e,this.max-this.value);return this.value+=t,t}advance(e=1){if(!(this.value>=this.max)){for(this.progress+=e;this.progress>=this.regenRate&&this.value<this.max;)this.progress-=this.regenRate,this.value++;this.value>=this.max&&(this.progress=0)}}toJSON(){return{current:this.value,progress:this.progress}}static fromJSON(t,n){let r=new e({...t,current:n.current});return r.progress=n.progress,r}};_e();function sV(e){if(e.entries.length===0||!A(e.chance??1))return null;let t=ie(e.entries.map(e=>e.weight));if(t===null)return null;let n=e.entries[t];return{id:n.id,quantity:n.quantity??1}}var cV=class e{constructor(e){this.grantedTiers=0,this.balance=0,this.choices=new Map,this.track=e}get points(){return this.balance}openTiers(e){let t=[];return this.track.tiers.forEach((n,r)=>{e>=n.threshold&&t.push(r)}),t}grant(e){let t=0;for(;this.grantedTiers<this.track.tiers.length&&e>=this.track.tiers[this.grantedTiers].threshold;){let e=this.track.tiers[this.grantedTiers];e.kind===`points`&&(this.balance+=e.points??0,t+=e.points??0),this.grantedTiers++}return t}spend(e){return this.balance<e?!1:(this.balance-=e,!0)}choose(e,t,n){let r=this.track.tiers[e];if(!r)throw Error(`no such advancement tier: ${e}`);if(r.kind===`points`)throw Error(`tier ${e} grants points, it has no choice`);if(n<r.threshold)throw Error(`tier ${e} has not opened yet`);if(this.choices.has(e))throw Error(`tier ${e} is already decided`);if(!(r.options??[]).some(e=>e.id===t))throw Error(`tier ${e} has no option "${t}"`);this.choices.set(e,t)}choice(e){return this.choices.get(e)??null}toJSON(){return{grantedTiers:this.grantedTiers,balance:this.balance,choices:[...this.choices]}}static fromJSON(t,n){let r=new e(t);r.grantedTiers=n.grantedTiers,r.balance=n.balance;for(let[e,t]of n.choices)r.choices.set(e,t);return r}};function lV(e,t){return t.map(t=>({stat:t.stat,op:t.op,value:t.base+t.perLevel*e}))}_e();function uV(e){if(e.labels.length<e.kinds.length)throw Error(`not enough appearances: ${e.kinds.length} kinds but only ${e.labels.length} labels`);let t=[...e.labels];for(let e=t.length-1;e>0;e--){let n=te(0,e+1);[t[e],t[n]]=[t[n],t[e]]}let n=new Map;return e.kinds.forEach((e,r)=>n.set(e,t[r])),n}var dV=class e{constructor(e){this.assigned=new Map,this.tables=e}appearanceOf(e,t){let n=this.assigned.get(e);if(!n){let t=this.tables[e];if(!t)throw Error(`no such appearance category: "${e}"`);n=uV(t),this.assigned.set(e,n)}let r=n.get(t);if(r===void 0)throw Error(`"${t}" is not in appearance category "${e}"`);return r}toJSON(){return{assigned:[...this.assigned].map(([e,t])=>[e,[...t]])}}static fromJSON(t,n){let r=new e(t);for(let[e,t]of n.assigned)r.assigned.set(e,new Map(t));return r}};function fV(e,t,n,r,i,a){let o=a.prices.get(r);if(!o)return!1;let s=t.find(r);if(!s||s.quantity<i)return!1;let c=o.buy*i;return e.base(a.currency)<c?!1:(t.remove(r,i),n.add({...s,quantity:i})?(e.setBase(a.currency,e.base(a.currency)-c),!0):(t.add({...s,quantity:i}),!1))}function pV(e,t,n,r,i,a){let o=a.prices.get(r);if(!o)return!1;let s=n.find(r);return!s||s.quantity<i?!1:(n.remove(r,i),t.add({...s,quantity:i})?(e.setBase(a.currency,e.base(a.currency)+o.sell*i),!0):(n.add({...s,quantity:i}),!1))}function mV(e){let t=Array.isArray(e)?e:[e];for(let e of t)if(!Number.isFinite(e.amount)||e.amount<0)throw Error(`a resource cost must be a non-negative number, "${e.stat}" costs ${e.amount}`);return t}function hV(e){let t=new Map;for(let n of e)t.set(n.stat,(t.get(n.stat)??0)+n.amount);return t}function gV(e,t){return[...hV(mV(t))].every(([t,n])=>e.base(t)>=n)}function _V(e,t){let n=hV(mV(t));if(![...n].every(([t,n])=>e.base(t)>=n))return!1;for(let[t,r]of n)e.setBase(t,e.base(t)-r);return!0}function vV(e,t,n=1){for(let[r,i]of hV(mV(t)))e.setBase(r,e.base(r)+i*n)}function yV(e,t,n,r){return _V(e,t)?n.refund(Math.floor(t.amount/r)):0}var bV=class e{constructor(){this.layers=[]}add(e,t=0){e<=0||this.layers.push({amount:e,decayPerTick:t})}get total(){return this.layers.reduce((e,t)=>e+t.amount,0)}get layerCount(){return this.layers.length}absorb(e){let t=e,n=0;for(;t>0&&this.layers.length>0;){let e=this.layers[this.layers.length-1],r=Math.min(e.amount,t);e.amount-=r,t-=r,n+=r,e.amount<=0&&this.layers.pop()}return n}advance(e=1){for(let t=this.layers.length-1;t>=0;t--){let n=this.layers[t];n.decayPerTick&&(n.amount-=n.decayPerTick*e,n.amount<=0&&this.layers.splice(t,1))}}clear(){this.layers=[]}toJSON(){return{layers:this.layers.map(e=>({...e}))}}static fromJSON(t){let n=new e;return n.layers=t.layers.map(e=>({...e})),n}};_e();function xV(e,t,n){return oe([...t]).slice(0,Math.min(n,t.length)).map(t=>{let n=Symbol(`trait:${t.name}`);for(let r of t.modifiers)e.addModifier({...r,source:n});return{trait:t,source:n}})}var SV=class{constructor(){this.affected=new Map}update(e,t){let n=new Set(e),r=e.filter(e=>!!e.aura),i=new Set(r);for(let i of r){let r=this.affected.get(i);r||(r=new Map,this.affected.set(i,r));for(let n of e){if(n===i)continue;let e=t(i,n),a=r.get(n);if(e&&!a){let e=Symbol(`aura:${i.aura.name}`);for(let t of i.aura.modifiers)n.stats.addModifier({...t,source:e});r.set(n,e)}else!e&&a&&(n.stats.removeModifiersFrom(a),r.delete(n))}for(let[e,t]of[...r])n.has(e)||(e.stats.removeModifiersFrom(t),r.delete(e))}for(let[e,t]of[...this.affected])if(!i.has(e)){for(let[e,n]of t)e.stats.removeModifiersFrom(n);this.affected.delete(e)}}},CV=class e{constructor(e){if(this.points=new Map,e.some(e=>!e.id||!Number.isFinite(e.threshold)||e.threshold<0))throw Error(`support levels need an id and a non-negative threshold`);this.levels=[...e].sort((e,t)=>e.threshold-t.threshold)}get(e,t){return this.points.get(wV(e,t))??0}level(e,t){let n=this.get(e,t),r=null;for(let e of this.levels){if(e.threshold>n)break;r=e}return r}add(e,t,n){if(!e||!t||e===t)throw Error(`support needs two different named units`);if(!Number.isFinite(n))throw Error(`support amount must be finite, got ${n}`);let r=this.level(e,t),i=wV(e,t),a=Math.max(0,(this.points.get(i)??0)+n);return this.points.set(i,a),{a:e,b:t,points:a,previousLevel:r,level:this.level(e,t)}}toJSON(){return{pairs:[...this.points].map(([e,t])=>{let[n,r]=e.split(`\0`);return[n,r,t]})}}static fromJSON(t,n){let r=new e(t);for(let[e,t,i]of n.pairs){if(!e||!t||e===t||!Number.isFinite(i)||i<0)throw Error(`invalid support save data`);let n=wV(e,t);if(r.points.has(n))throw Error(`invalid support save data: duplicate pair "${e}" / "${t}"`);r.points.set(n,i)}return r}};function wV(e,t){return[e,t].sort().join(`\0`)}var TV=new Set([`id`,`growth`,`level`,`startingAffix`,`startingItem`,`lowHpReaction`]);function EV(e,t={},n){let r=new IB({base:jV(e)}),i;e.growth!==void 0&&(i=new RB(AV(e,t),{level:e.level??1}));let a;if(e.startingItem!==void 0){let n=t.items?.[e.startingItem];if(!n)throw Error(`entity template "${e.id}": unknown starting item "${e.startingItem}"`);if(a=n(),e.startingAffix!==void 0){let n=t.affixes?.[e.startingAffix];if(!n)throw Error(`entity template "${e.id}": unknown affix "${e.startingAffix}"`);ZB(a,n)}}else if(e.startingAffix!==void 0)throw Error(`entity template "${e.id}": a starting affix needs a starting item to carry it`);let o=new En,s={id:e.id,stats:r,progression:i,item:a,reactions:o};if(e.lowHpReaction!==void 0){if(!n)throw Error(`entity template "${e.id}": names a lowHpReaction threshold but no onLowHp callback was given`);let t=e.lowHpReaction;o.add({id:`low-hp`,when:e=>e.hp/e.maxHp<=t,action:()=>n(s)})}return s}function DV(e,t={},n){return e.map(e=>EV(e,t,n))}function OV(e){let t={stats:e.stats.toJSON()};return e.progression&&(t.progression=e.progression.toJSON()),e.item&&(t.item=e.item),t}function kV(e,t,n,r){let i=EV(e,t,r);if(i.stats=IB.fromJSON({base:jV(e)},n.stats),n.progression!==void 0){if(!i.progression)throw Error(`entity template "${e.id}": save data has progression but the row names no growth curve`);i.progression=RB.fromJSON(AV(e,t),n.progression)}return n.item!==void 0&&(i.item=n.item),i}function AV(e,t){let n=t.growthCurves?.[e.growth??``];if(!n)throw Error(`entity template "${e.id}": unknown growth curve "${e.growth}"`);return n}function jV(e){let t={};for(let[n,r]of Object.entries(e))if(!TV.has(n)){if(typeof r!=`number`)throw Error(`entity template "${e.id}": stat "${n}" must be a number, got ${typeof r}`);t[n]=r}return t}var MV=l({Advancement:()=>cV,Appearances:()=>dV,AuraField:()=>SV,Barrier:()=>bV,Charges:()=>oV,EquipmentSlots:()=>VB,Inventory:()=>HB,Progression:()=>RB,SkillPoints:()=>BB,StatBlock:()=>IB,SupportLedger:()=>CV,affixOf:()=>XB,applyAffix:()=>ZB,applyItemStatusEffect:()=>aV,applyStatusEffect:()=>JB,assignAppearances:()=>uV,assignTraits:()=>xV,buildEntities:()=>DV,buildEntity:()=>EV,buy:()=>fV,canAfford:()=>gV,composeModifiers:()=>FB,convertToCharges:()=>yV,copyAffix:()=>$B,craft:()=>KB,damageItem:()=>rV,enchant:()=>nV,fromEntitySaveState:()=>kV,identify:()=>tV,matchesContext:()=>eV,powerCurve:()=>LB,refund:()=>vV,removeAffix:()=>QB,repairItem:()=>iV,rollAffix:()=>YB,rollLoot:()=>sV,scaledModifiers:()=>lV,sell:()=>pV,skillCheck:()=>zB,spend:()=>_V,toEntitySaveState:()=>OV}),NV=class{constructor(){this.factories=new Map,this.loaded=new Map,this.currentId=null}define(e,t,n={}){this.factories.set(e,{create:t,persistent:n.persistent??!0})}enter(e,t){let n=this.factories.get(e);if(!n)throw Error(`no such map: "${e}"`);let r=this.loaded.get(e);return(!r||!n.persistent)&&(r=n.create(),this.loaded.set(e,r)),this.currentId=e,this.lastSpawn=t,r}get current(){return this.currentId?this.loaded.get(this.currentId)??null:null}get currentMapId(){return this.currentId}get spawn(){return this.lastSpawn}isLoaded(e){return this.loaded.has(e)}isPersistent(e){return this.factories.get(e)?.persistent??!0}unload(e){if(e===this.currentId)throw Error(`cannot unload the current map: "${e}"`);this.loaded.delete(e)}},PV=class{constructor(){this.locations=new Map}add(e){this.locations.set(e.id,e)}remove(e){this.locations.delete(e)}get(e){return this.locations.get(e)}at(e,t){for(let n of this.locations.values())if(n.x===e&&n.y===t)return n}get all(){return[...this.locations.values()]}},FV=class{constructor(){this.turn=0,this.effects=new Map}add(e){let t=Symbol();return this.effects.set(t,{...e}),t}remove(e){this.effects.delete(e)}has(e){return this.effects.has(e)}advance(e=1){this.turn+=e;for(let[t,n]of this.effects)n.tick(this.turn),n.duration!==void 0&&(n.duration-=e,n.duration<=0&&(this.effects.delete(t),n.onExpire?.()))}};_e();function IV(e){if(e.entries.length===0||!A(e.rate))return null;let t=ie(e.entries.map(e=>e.weight));return t===null?null:e.entries[t].value}var LV=class e{constructor(e={}){if(this.changed=new p,this.dayLength=e.dayLength??120,!(this.dayLength>0))throw Error(`an environment day must be longer than zero seconds`);if(this.boundaries=e.phaseBoundaries??[.2,.7,.8],this.boundaries[0]<=0||this.boundaries[0]>=this.boundaries[1]||this.boundaries[1]>=this.boundaries[2]||this.boundaries[2]>=1)throw Error(`environment phase boundaries must be ascending fractions strictly between 0 and 1`);if(this.seconds_=e.startSeconds??0,this.weather_=e.startWeather??`clear`,!Number.isFinite(this.seconds_))throw Error(`environment startSeconds must be finite`)}get day(){return Math.floor(this.seconds_/this.dayLength)}get seconds(){return this.seconds_}get weather(){return this.weather_}get phase(){let e=(this.seconds_%this.dayLength+this.dayLength)%this.dayLength/this.dayLength;return e<this.boundaries[0]?`dawn`:e<this.boundaries[1]?`day`:e<this.boundaries[2]?`dusk`:`night`}get night(){return this.phase===`night`}update(e){if(!Number.isFinite(e)||e<0)throw Error(`environment update must be non-negative, got ${e}`);this.seconds_+=e;let t=this.toJSON();return this.changed.dispatch(t),t}setWeather(e){if(!e)throw Error(`weather needs a non-empty id`);this.weather_=e;let t=this.toJSON();return this.changed.dispatch(t),t}toJSON(){return{day:this.day,seconds:this.seconds_,phase:this.phase,weather:this.weather_}}static fromJSON(t,n){return new e({...t,startSeconds:n.seconds,startWeather:n.weather})}},RV=class e{constructor(e){if(e.sides.length===0)throw Error(`SideTurns needs at least one side`);if(e.schedule.length===0)throw Error(`SideTurns needs a non-empty schedule`);let t=e.round??1,n=e.sideIndex??0,r=e.timeIndex??0;if(!Number.isInteger(t)||t<1)throw Error(`SideTurns round must be a positive integer`);if(n<0||n>=e.sides.length)throw Error(`SideTurns side index ${n} is outside ${e.sides.length} sides`);if(r<0||r>=e.schedule.length)throw Error(`SideTurns time index ${r} is outside ${e.schedule.length} times`);this.sides=[...e.sides],this.schedule=[...e.schedule],this.areas=e.areas??[],this.state={round:t,sideIndex:n,timeIndex:r}}get round(){return this.state.round}get side(){return this.sides[this.state.sideIndex]}get timeIndex(){return this.state.timeIndex}get timeOfDay(){return this.schedule[this.state.timeIndex]}get snapshot(){return{...this.state}}timeOfDayAt(e,t){for(let n of this.areas)if(n.contains(e,t))return n.times[this.state.timeIndex]??this.timeOfDay;return this.timeOfDay}lawfulBonusAt(e,t,n){return zV(e,this.timeOfDayAt(t,n).lawfulBonus)}advance(){let e=!1;return this.state.sideIndex++,this.state.sideIndex>=this.sides.length&&(this.state.sideIndex=0,this.state.round++,this.state.timeIndex=(this.state.timeIndex+1)%this.schedule.length,e=!0),{side:this.side,round:this.state.round,newRound:e}}toJSON(){return this.snapshot}static fromJSON(t,n){return new e({...t,round:n.round,sideIndex:n.sideIndex,timeIndex:n.timeIndex})}};function zV(e,t){switch(e){case`lawful`:return t;case`chaotic`:return-t;default:return 0}}var BV=l({EnvironmentClock:()=>LV,Overworld:()=>PV,SideTurns:()=>RV,TurnClock:()=>FV,World:()=>NV,alignmentBonus:()=>zV,rollEncounter:()=>IV});_e();function VV(e,t,n={}){let r=n.pick??te,i=0;return t.forEach((t,n)=>{HV(t,t.name??`#${n+1}`,e.shape);let a=UV(e,t);if(i+=a.length,a.length!==0)for(let[n,i]of a){let a=t.outputs[r(t.outputs.length)];for(let[r,o]of Object.entries(a))for(let a=0;a<t.height;a++)for(let s=0;s<t.width;s++){let c=o[a*t.width+s];c!==-1&&e.setTile(r,n+s,i+a,c)}}}),i}function HV(e,t,n){if(e.topology&&(n===`square`||n===`hex`)&&e.topology!==n)throw Error(`automap rule "${t}" targets ${e.topology} cells, but the map is ${n}`);if(!Number.isInteger(e.width)||e.width<=0||!Number.isInteger(e.height)||e.height<=0)throw Error(`automap rule "${t}" needs a positive width and height`);if(e.outputs.length===0)throw Error(`automap rule "${t}" has no outputs - a rule that matches and writes nothing is a mistake`);let r=e.width*e.height;for(let[n,i]of Object.entries(e.input))if(i.length!==r)throw Error(`automap rule "${t}" input "${n}" has ${i.length} cells, but the pattern is ${r}`);e.outputs.forEach((e,n)=>{for(let[i,a]of Object.entries(e))if(a.length!==r)throw Error(`automap rule "${t}" output ${n+1} "${i}" has ${a.length} cells, but the pattern is ${r}`)})}function UV(e,t){let n=[];for(let r=0;r+t.height<=e.heightInTiles;r++)for(let i=0;i+t.width<=e.widthInTiles;i++)WV(e,t,i,r)&&n.push([i,r]);return n}function WV(e,t,n,r){for(let[i,a]of Object.entries(t.input))for(let o=0;o<t.height;o++)for(let s=0;s<t.width;s++){let c=a[o*t.width+s];if(c!==-1&&e.getTile(i,n+s,r+o)!==c)return!1}return!0}var GV=class e{constructor(){this.switches=new Map,this.variables=new Map}switch(e){return this.switches.get(e)??!1}setSwitch(e,t){this.switches.set(e,t)}variable(e){return this.variables.get(e)??0}setVariable(e,t){this.variables.set(e,t)}toJSON(){return{switches:[...this.switches],variables:[...this.variables]}}static fromJSON(t){let n=new e;for(let[e,r]of t.switches)n.setSwitch(e,r);for(let[e,r]of t.variables)n.setVariable(e,r);return n}};function KV(e,t){return`switch`in e?t.switch(e.switch)===e.equals:t.variable(e.variable)>=e.atLeast}function qV(e,t){let n;for(let r of e.pages)(r.conditions??[]).every(e=>KV(e,t))&&(n=r);return n}var JV=class{constructor(e){this.cancelled=!1,this.options=e,this.state={game:e.game,answers:{}}}cancel(){this.cancelled=!0}async run(e){let t=await this.runList(e);if(t!==void 0){if(this.options.onUnknownCommand)return this.options.onUnknownCommand({goto:t}),this.state;throw Error(`a "goto ${t}" only runs inside runStory, not a straight run`)}return this.state}async runStory(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw Error(`this event story has no passage named "${t}"`);let n=e[t],r=0;for(;r<n.length&&!this.cancelled;){let t=await this.step(n[r]);if(r++,t!==void 0){if(!Object.prototype.hasOwnProperty.call(e,t))throw Error(`this event story has no passage named "${t}"`);n=e[t],r=0}}return this.state}async runList(e){for(let t of e){if(this.cancelled)break;let e=await this.step(t);if(e!==void 0)return e}}async step(e){if(`say`in e){await this.speak(e.say,e.speaker,e.portrait);return}if(`ask`in e){let t=await this.speak(e.ask,e.speaker,e.portrait,e.choices);return e.store&&(this.state.answers[e.store]=t),e.choices.find(e=>(e.value??e.text)===t)?.goto}if(`wait`in e){await new Promise(t=>setTimeout(t,e.wait*1e3));return}if(`setSwitch`in e){this.state.game.setSwitch(e.setSwitch,e.value);return}if(`setVariable`in e){this.state.game.setVariable(e.setVariable,e.value);return}if(`addVariable`in e){let t=this.state.game.variable(e.addVariable);this.state.game.setVariable(e.addVariable,t+e.amount);return}if(`if`in e){let t=KV(e.if,this.state.game);return this.runList(t?e.then:e.else??[])}if(`move`in e){await this.options.move?.(e.move.target,e.move.steps);return}if(`goto`in e)return e.goto;if(`call`in e){await e.call(this.state);return}this.options.onUnknownCommand?.(e)}speak(e,t,n,r){return this.options.present({text:e,speaker:t,portrait:n,choices:r})}};function YV(e,t){t&&e.has?.(t)&&e.play?.(t)}var XV=class{constructor(e,t,n,r){this.facing=`down`,this.target=null,this.progress=0,this.sprite=e,this.x=this.fromX=t,this.y=this.fromY=n,this.tileWidth=r.tileWidth,this.tileHeight=r.tileHeight,this.speed=r.speed??4,this.options=r,this.place(),this.playIdle()}get isMoving(){return this.target!==null}turnTo(e,t){this.target||(this.facing=ZV(e,t),this.playIdle())}moveBy(e,t){return!this.target&&(this.facing=ZV(e,t),this.fromX=this.x,this.fromY=this.y,this.target={x:this.x+e,y:this.y+t},this.progress=0,this.playWalk(),!0)}jumpBy(e,t){return!this.target&&(this.facing=ZV(e,t),this.x+=e,this.y+=t,this.fromX=this.x,this.fromY=this.y,this.place(),this.playIdle(),!0)}update(e){this.sprite.update?.(e),this.target&&(this.progress=Math.min(1,this.progress+this.speed*e),this.sprite.x=QV(this.fromX,this.target.x,this.progress)*this.tileWidth,this.sprite.y=QV(this.fromY,this.target.y,this.progress)*this.tileHeight,this.progress>=1&&(this.x=this.target.x,this.y=this.target.y,this.target=null,this.playIdle()))}place(){this.sprite.x=this.x*this.tileWidth,this.sprite.y=this.y*this.tileHeight}playWalk(){YV(this.sprite,this.options.walkAnimation?.(this.facing))}playIdle(){YV(this.sprite,this.options.idleAnimation?.(this.facing))}};function ZV(e,t){return e>0?`right`:e<0?`left`:t>0?`down`:`up`}function QV(e,t,n){return e+(t-e)*n}var $V=[`up`,`down`,`left`,`right`],eH={up:{dx:0,dy:-1},down:{dx:0,dy:1},left:{dx:-1,dy:0},right:{dx:1,dy:0}},tH={up:{around:`down`,left90:`left`,right90:`right`},down:{around:`up`,left90:`right`,right90:`left`},left:{around:`right`,left90:`down`,right90:`up`},right:{around:`left`,left90:`up`,right90:`down`}},nH=class{constructor(e,t,n={}){this.index=0,this.waiting=0,this.mover=e,this.route=t,this.options=n}get done(){return!this.route.repeat&&this.index>=this.route.steps.length}update(e){if(this.mover.isMoving||this.done||this.waiting>0&&(this.waiting=Math.max(0,this.waiting-e),this.waiting>0))return;this.index>=this.route.steps.length&&(this.index=0);let t=this.route.steps[this.index];(this.runStep(t)||this.route.skippable)&&this.index++}runStep(e){if(`turn`in e){let{dx:t,dy:n}=this.resolveTurn(e);return this.mover.turnTo(t,n),!0}if(`wait`in e)return this.waiting=e.wait,!0;if(`jump`in e)return this.attempt(e.jump.dx,e.jump.dy,(e,t)=>this.mover.jumpBy(e,t));if(`step`in e)return this.attempt(e.step.dx,e.step.dy,(e,t)=>this.mover.moveBy(e,t));let{dx:t,dy:n}=this.resolveDirection(e);return this.attempt(t,n,(e,t)=>this.mover.moveBy(e,t))}resolveDirection(e){return e.dir===`random`?eH[this.pickDirection()]:e.dir===`forward`?eH[this.mover.facing]:e.dir===`backward`?eH[tH[this.mover.facing].around]:e.dir===`toward`||e.dir===`away`?this.resolveAim(e.dir,e):eH[e.dir]}resolveTurn(e){if(e.turn===`random`)return eH[this.pickDirection()];if(e.turn===`around`||e.turn===`left90`||e.turn===`right90`)return eH[tH[this.mover.facing][e.turn]];if(e.turn===`toward`||e.turn===`away`){let t=this.resolveAim(e.turn,e);return t.dx===0&&t.dy===0?eH[this.mover.facing]:t}return eH[e.turn]}resolveAim(e,t){let n=`target`in t?t.target():t,r=e===`toward`?1:-1,i=n.x-this.mover.x,a=n.y-this.mover.y;return Math.abs(i)>=Math.abs(a)?{dx:r*Math.sign(i)||0,dy:0}:{dx:0,dy:r*Math.sign(a)||0}}attempt(e,t,n){return e===0&&t===0?!0:this.options.canMove&&!this.options.canMove(e,t)?!1:n(e,t)}pickDirection(){let e=this.options.random??Math.random;return $V[Math.floor(e()*$V.length)]}},rH=class{constructor(e,t,n,r={}){this.facing=0,this.moving=!1,this.sprite=e,this.x=t,this.y=n,this.speed=r.speed??4,this.options=r,this.place(),this.playIdle()}get isMoving(){return this.moving}move(e,t,n){let r=Math.hypot(e,t);r>0?(this.facing=Math.atan2(t,e),this.x+=e/r*this.speed*n,this.y+=t/r*this.speed*n,this.moving||(this.moving=!0,this.playWalk())):this.moving&&(this.moving=!1,this.playIdle()),this.place(),this.sprite.update?.(n)}turnTo(e,t){this.moving||e===0&&t===0||(this.facing=Math.atan2(t,e),this.playIdle())}place(){this.sprite.x=this.x,this.sprite.y=this.y}playWalk(){YV(this.sprite,this.options.walkAnimation?.(this.facing))}playIdle(){YV(this.sprite,this.options.idleAnimation?.(this.facing))}};function iH(e,t){return e.x<t.x+t.width&&e.x+e.width>t.x&&e.y<t.y+t.height&&e.y+e.height>t.y}function aH(e,t){let n=e.x-t.x,r=e.y-t.y,i=e.radius+t.radius;return n*n+r*r<i*i}function oH(e,t){let n=On(e.x,t.x,t.x+t.width),r=On(e.y,t.y,t.y+t.height),i=e.x-n,a=e.y-r;return i*i+a*a<e.radius*e.radius}function sH(e,t,n,r){let{tileSize:i,isSolid:a}=r;if(!(i>0))throw Error(`collision tileSize must be positive`);let o=cH(e.x,e.y,e.width,e.height,t,i,a,!0);return{x:o,y:cH(o,e.y,e.width,e.height,n,i,a,!1)}}function cH(e,t,n,r,i,a,o,s){if(i===0)return s?e:t;let c=s?e:t,l=s?n:r,u=c+i,d=Math.floor((s?t:e)/a),f=Math.floor(((s?t+r:e+n)-1e-6)/a),p=(e,t)=>s?o(e,t):o(t,e);if(i>0){let e=Math.floor((c+l-1e-6)/a),t=Math.floor((u+l-1e-6)/a);for(let n=e+1;n<=t;n++)for(let e=d;e<=f;e++)if(p(n,e))return n*a-l}else{let e=Math.floor(c/a),t=Math.floor(u/a);for(let n=e-1;n>=t;n--)for(let e=d;e<=f;e++)if(p(n,e))return(n+1)*a}return u}var lH=class e{constructor(){this.definitions=new Map,this.stageIndex=new Map,this.tracked=null}define(e){this.definitions.set(e.id,e)}track(e){e!==null&&this.require(e),this.tracked=e}trackedQuest(){return this.tracked!==null&&this.status(this.tracked)===`active`?this.tracked:null}trackedLocation(){let e=this.trackedQuest();return e?this.currentStage(e)?.location??null:null}markerFor(e,t){return e.some(e=>this.status(e)===`active`&&this.stageSatisfied(e,t))?`turnIn`:e.some(e=>this.status(e)===`available`)?`offer`:`none`}canStart(e){return(this.require(e).requires??[]).every(e=>this.status(e)===`complete`)}start(e){if(!this.canStart(e))throw Error(`quest "${e}" cannot start yet - a prerequisite is incomplete`);this.stageIndex.set(e,0)}status(e){let t=this.require(e),n=this.stageIndex.get(e);return n===void 0?this.canStart(e)?`available`:`unavailable`:n>=t.stages.length?`complete`:`active`}currentStage(e){return this.status(e)===`active`?this.require(e).stages[this.stageIndex.get(e)]:null}progress(e,t){let n=this.currentStage(e);return n?.counter?Math.min(1,t.variable(n.counter.variable)/n.counter.target):null}advanceStage(e,t){return this.stageSatisfied(e,t)?(this.stageIndex.set(e,this.stageIndex.get(e)+1),!0):!1}stageSatisfied(e,t){let n=this.currentStage(e);return n?n.condition?KV(n.condition,t):!n.counter||t.variable(n.counter.variable)>=n.counter.target:!1}require(e){let t=this.definitions.get(e);if(!t)throw Error(`no such quest: "${e}"`);return t}toJSON(){return{stageIndex:[...this.stageIndex],tracked:this.tracked}}static fromJSON(t,n){let r=new e;for(let e of t)r.define(e);for(let[e,t]of n.stageIndex)r.stageIndex.set(e,t);return n.tracked&&(r.tracked=n.tracked),r}};function uH(e){let t=[],n=new Map;for(let r of e){let e=n.get(r.questId);e||(e={id:r.questId,stages:[]},r.requires!==void 0&&(e.requires=r.requires),n.set(r.questId,e),t.push(r.questId)),e.stages.push(dH(e.id,r))}return t.map(e=>n.get(e))}function dH(e,t){if(t.conditionSwitch!==void 0&&t.conditionVariable!==void 0)throw Error(`quest "${e}": a stage row cannot name both a condition switch and a condition variable`);let n={};if(t.conditionSwitch!==void 0){if(t.conditionEquals===void 0)throw Error(`quest "${e}": conditionSwitch needs a conditionEquals`);n.condition={switch:t.conditionSwitch,equals:t.conditionEquals}}else if(t.conditionVariable!==void 0){if(t.conditionAtLeast===void 0)throw Error(`quest "${e}": conditionVariable needs a conditionAtLeast`);n.condition={variable:t.conditionVariable,atLeast:t.conditionAtLeast}}if(t.counterVariable!==void 0){if(t.counterTarget===void 0)throw Error(`quest "${e}": counterVariable needs a counterTarget`);n.counter={variable:t.counterVariable,target:t.counterTarget}}if(t.description!==void 0&&(n.description=t.description),t.locationMap!==void 0||t.locationX!==void 0||t.locationY!==void 0){if(t.locationX===void 0||t.locationY===void 0)throw Error(`quest "${e}": a stage location needs both locationX and locationY`);n.location={x:t.locationX,y:t.locationY},t.locationMap!==void 0&&(n.location.map=t.locationMap)}return n}var fH=class{constructor(e){this.name=e}},pH=4,mH=8,hH=new WeakMap;function gH(e){return hH.get(e)}function _H(e,t){return hH.set(e,t),e}var vH=1e3,yH=class{constructor(e){this.pos=0,this.depth=0,this.symbols=[],this.objects=[],this.bytes=e}byte(){if(this.pos>=this.bytes.length)throw Error(`Marshal: unexpected end of input`);return this.bytes[this.pos++]}take(e){if(e<0)throw Error(`Marshal: negative length`);let t=this.bytes.subarray(this.pos,this.pos+e);if(t.length<e)throw Error(`Marshal: unexpected end of input`);return this.pos+=e,t}readFixnum(){let e=this.byte()<<24>>24;if(e===0)return 0;if(e>=5&&e<=127)return e-5;if(e<=-5&&e>=-128)return e+5;if(e>0){let t=0;for(let n=0;n<e;n++)t|=this.byte()<<8*n;return t>>>0}let t=-e,n=0;for(let e=0;e<t;e++)n|=this.byte()<<8*e;return(n>>>0)-2**(8*t)}readBytes(){return this.take(this.readFixnum())}readSymbol(){let e=new TextDecoder().decode(this.readBytes());return this.symbols.push(e),e}readSymbolLink(){let e=this.readFixnum(),t=this.symbols[e];if(t===void 0)throw Error(`Marshal: symbol link ${e} out of range`);return t}readSymbolValue(){let e=String.fromCharCode(this.byte());if(e===`:`)return this.readSymbol();if(e===`;`)return this.readSymbolLink();throw Error(`Marshal: expected a symbol, got tag "${e}"`)}link(e){return this.objects.push(e),e}readBignum(){let e=String.fromCharCode(this.byte())===`-`?-1:1,t=this.readFixnum(),n=0,r=1;for(let e=0;e<t;e++)n+=(this.byte()|this.byte()<<8)*r,r*=65536;return e*n}readFloat(){let e=new TextDecoder().decode(this.readBytes());return e===`inf`?1/0:e===`-inf`?-1/0:e===`nan`?NaN:Number(e)}readArray(){let e=[];this.link(e);let t=this.readFixnum();for(let n=0;n<t;n++)e.push(this.readValue());return e}readHash(e){let t=new Map;this.link(t);let n=this.readFixnum();for(let e=0;e<n;e++)t.set(this.readValue(),this.readValue());return e&&hH.set(t,this.readValue()),t}readIvars(e){let t={};for(let n=0;n<e;n++)t[this.readSymbolValue()]=this.readValue();return t}readObject(){let e={class:``,ivars:{}};return this.link(e),e.class=this.readSymbolValue(),e.ivars=this.readIvars(this.readFixnum()),e}readIvarWrapped(){let e=this.readValue();return this.readIvars(this.readFixnum()),e}readUserDefined(){let e={class:``,raw:new Uint8Array};return this.link(e),e.class=this.readSymbolValue(),e.raw=this.readBytes().slice(),e}readUserMarshal(){let e={class:``,value:null};return this.link(e),e.class=this.readSymbolValue(),e.value=this.readValue(),e}readValue(){if(++this.depth>vH)throw Error(`Marshal: values nested more than ${vH} deep`);try{return this.readTagged()}finally{this.depth--}}readTagged(){let e=String.fromCharCode(this.byte());switch(e){case`0`:return null;case`T`:return!0;case`F`:return!1;case`i`:return this.readFixnum();case`l`:return this.link(this.readBignum());case`f`:return this.link(this.readFloat());case`:`:return this.readSymbol();case`;`:return this.readSymbolLink();case`"`:return this.link(new TextDecoder().decode(this.readBytes()));case`[`:return this.readArray();case`{`:return this.readHash(!1);case`}`:return this.readHash(!0);case`o`:return this.readObject();case`I`:return this.readIvarWrapped();case`u`:return this.readUserDefined();case`U`:return this.readUserMarshal();case`@`:{let e=this.readFixnum(),t=this.objects[e];if(t===void 0)throw Error(`Marshal: object link ${e} out of range`);return t}default:throw Error(`Marshal: unsupported tag "${e}" (0x${e.charCodeAt(0).toString(16)})`)}}readDocument(){let e=this.byte(),t=this.byte();if(e!==pH||t>mH)throw Error(`Marshal: unsupported version ${e}.${t} (expected ${pH}.${mH} or lower)`);return this.readValue()}};function bH(e){return new yH(e).readDocument()}function xH(e){return typeof e==`object`&&!!e&&`class`in e&&`ivars`in e}function SH(e){let t=[pH,mH];return CH(t,e),new Uint8Array(t)}function CH(e,t){if(t==null)e.push(wH(`0`));else if(t===!0)e.push(wH(`T`));else if(t===!1)e.push(wH(`F`));else if(t instanceof fH)e.push(wH(`:`)),TH(e,t.name);else if(typeof t==`number`)Number.isInteger(t)&&Math.abs(t)<2**30?(e.push(wH(`i`)),EH(e,t)):(e.push(wH(`f`)),TH(e,Number.isFinite(t)?String(t):t>0?`inf`:t<0?`-inf`:`nan`));else if(typeof t==`string`)e.push(wH(`"`)),TH(e,t);else if(Array.isArray(t)){e.push(wH(`[`)),EH(e,t.length);for(let n of t)CH(e,n)}else if(t instanceof Map){let n=hH.has(t);e.push(wH(n?`}`:`{`)),EH(e,t.size);for(let[n,r]of t)CH(e,n),CH(e,r);n&&CH(e,hH.get(t))}else if(xH(t)){e.push(wH(`o`)),e.push(wH(`:`)),TH(e,t.class);let n=Object.entries(t.ivars);EH(e,n.length);for(let[t,r]of n)e.push(wH(`:`)),TH(e,t),CH(e,r)}else throw Error(`Marshal: cannot encode a value of type ${typeof t}`)}function wH(e){return e.charCodeAt(0)}function TH(e,t){let n=new TextEncoder().encode(t);EH(e,n.length);for(let t of n)e.push(t)}function EH(e,t){if(t===0){e.push(0);return}if(t>0&&t<=122){e.push(t+5);return}if(t<0&&t>=-123){e.push(t-5&255);return}if(t>0){for(let n=1;n<=4;n++)if(t<2**(8*n)){e.push(n);for(let r=0;r<n;r++)e.push(t>>>8*r&255);return}}else for(let n=1;n<=4;n++)if(t>=-(2**(8*n))){e.push(-n&255);let r=t+2**(8*n);for(let t=0;t<n;t++)e.push(r>>>8*t&255);return}throw Error(`Marshal: integer ${t} is out of range for a Fixnum`)}function DH(e){return Hr(e).map(e=>e.speaker===void 0?{say:e.text}:{say:e.text,speaker:e.speaker})}function OH(e,t={}){let n={};for(let t of e)`say`in t?n[t.say]=t.say:`ask`in t&&(n[t.ask]=t.ask);return{locale:t.locale??`en`,direction:t.direction??`ltr`,messages:n}}function kH(e){let{story:t,start:n,title:r}=Ur(e);return r===void 0?{story:t,start:n}:{story:t,start:n,title:r}}var AH=l({AUTOMAP_EMPTY:()=>-1,EventRunner:()=>JV,FreeMover:()=>rH,GameState:()=>GV,GridMover:()=>XV,MoveRouteRunner:()=>nH,QuestLog:()=>lH,RubySymbol:()=>fH,aabbOverlap:()=>iH,activePage:()=>qV,automap:()=>VV,circleAabbOverlap:()=>oH,circleOverlap:()=>aH,conditionHolds:()=>KV,decodeMarshal:()=>bH,encodeMarshal:()=>SH,extractDialogueCatalog:()=>OH,hashDefaultOf:()=>gH,importTwee:()=>kH,parseDialogueText:()=>DH,questsFromRows:()=>uH,resolveAabbAgainstTiles:()=>sH,withHashDefault:()=>_H}),jH=LB(20,2,100),MH=class{constructor(e){this.species=e.species,this.deriveStats=e.deriveStats,this.progression=new RB(e.species.growth??jH,{level:e.level??1}),this.stats=new IB({base:this.computeBase()})}refreshStats(){let e=this.computeBase();for(let[t,n]of Object.entries(e))this.stats.setBase(t,n)}computeBase(){let e=this.progression.level;return this.deriveStats?this.deriveStats(this.species.baseStats,e):{...this.species.baseStats}}},NH=class{constructor(){this.multipliers=new Map}key(e,t){return`${e}:${t}`}set(e,t,n){this.multipliers.set(this.key(e,t),n)}get(e,t){return this.multipliers.get(this.key(e,t))??1}multiplierFor(e,t){return t.reduce((t,n)=>t*this.get(e,n),1)}},PH=class{constructor(e){this.storage=[],this.active=Array(e).fill(null)}get members(){return this.active}get boxed(){return this.storage}add(e){let t=this.active.indexOf(null);t===-1?this.storage.push(e):this.active[t]=e}store(e){let t=this.active[e];t&&(this.active[e]=null,this.storage.push(t))}withdraw(e,t){if(t<0||t>=this.active.length)return;let n=this.storage[e];if(!n)return;this.storage.splice(e,1);let r=this.active[t];this.active[t]=n,r&&this.storage.push(r)}get activeMembers(){return this.active.filter(e=>e!==null)}};function FH(e){return[...e].sort((e,t)=>(t.priority??0)-(e.priority??0)||t.speed-e.speed)}function IH(e,t){let n=null;for(let r of e)r.at(t)&&(n=r.into);return n}var LH=class{constructor(e,t){this.stages=new Map,this.modifiers=new Map,this.stats=e,this.max=t.max,this.multiplierFor=t.multiplier}get(e){return this.stages.get(e)??0}change(e,t){let n=this.get(e),r=Math.max(-this.max,Math.min(this.max,n+t)),i=r-n;return i===0?0:(this.stages.set(e,r),this.applyModifier(e,r),i)}applyModifier(e,t){let n=this.modifiers.get(e);if(n&&this.stats.removeModifier(n),t===0){this.modifiers.delete(e);return}let r={stat:e,op:`multiply`,value:this.multiplierFor(t)};this.stats.addModifier(r),this.modifiers.set(e,r)}resetAll(){for(let e of this.modifiers.values())this.stats.removeModifier(e);this.modifiers.clear(),this.stages.clear()}};function RH(e,t,n,r=(e,n)=>t.multiplierFor(e.type,n)){if(e.length===0)return null;let i=e[0],a=r(i,n);for(let t of e.slice(1)){let e=r(t,n);e>a&&(a=e,i=t)}return i}function zH(e,t,n,r){let i=null,a=BH(e,n,r);return t.forEach((e,t)=>{let o=BH(e.types,n,r);o<a&&(a=o,i=t)}),i}function BH(e,t,n){return Math.max(...n.map(n=>t.multiplierFor(n,e)))}var VH=class extends S{},HH=class{constructor(){this.conditions=new Map}set(e){this.conditions.set(e.id,{...e})}has(e){return this.conditions.has(e)}get(e){return this.conditions.get(e)}clear(e){this.conditions.delete(e)}get active(){return[...this.conditions.values()]}advance(e=1){for(let[t,n]of this.conditions)n.duration!==void 0&&(n.duration-=e,n.duration<=0&&this.conditions.delete(t))}},UH=class{constructor(e){this.chanceToHit=WH(e.chanceToHit??1),this.strikeDuration=Math.max(0,e.strikeDuration??0),this.totalDamage=Math.max(0,e.damage)*Math.max(0,e.strikes),this.expectedDamage=this.totalDamage*this.chanceToHit,this.defenderHp0=e.defender.hp;let t=[],n=e.defender.hp;for(let r=0;r<=e.strikes;r++)r>0&&(e.hits?.[r-1]??!0)&&(n-=Math.max(0,e.damage)),t.push({strike:r,time:r*this.strikeDuration,attackerHp:e.attacker.hp,defenderHp:Math.max(0,n),defenderDamage:this.defenderHp0-Math.max(0,n)});this.frames=t}get duration(){return this.strikeDuration*(this.frames.length-1)}get defenderKilled(){return this.frames[this.frames.length-1].defenderHp===0}sampleAt(e){let t=this.frames.length-1;if(this.strikeDuration<=0)return this.frames[t];let n=0;for(let r=0;r<=t&&this.frames[r].time<=e+1e-9;r++)n=r;return this.frames[n]}};function WH(e){return Math.max(0,Math.min(1,e))}var GH=class{constructor(e){this.onChange=new p,this.stage_=`attacker`,this.charge=null,this.victim=null,this.highlight_=0,this.units=e.units,this.side=e.side,this.disabledOf=e.disabled??(e=>e.disabled??!1),this.canTarget=e.canTarget??(()=>!0)}get stage(){return this.stage_}get attacker(){return this.charge}get target(){return this.victim}get done(){return this.charge!==null&&this.victim!==null}get candidates(){return this.units.filter(e=>(this.side===void 0||e.side===this.side)&&!this.disabledOf(e))}get targets(){let e=this.charge;return e?this.units.filter(t=>t.id!==e.id&&!this.disabledOf(t)&&(e.side===void 0||t.side!==e.side)&&this.canTarget(e,t)):[]}get highlight(){return this.highlight_}get highlighted(){return this.active()[this.highlight_]??null}move(e){let t=this.active();t.length!==0&&(this.highlight_=((this.highlight_+e)%t.length+t.length)%t.length,this.onChange.dispatch())}select(){let e=this.highlighted;return e?(this.stage_===`attacker`?(this.charge=e,this.stage_=`target`,this.highlight_=0):this.victim=e,this.onChange.dispatch(),!0):!1}back(){if(this.stage_===`attacker`)return;let e=this.charge;this.charge=null,this.victim=null,this.stage_=`attacker`;let t=e?this.candidates.findIndex(t=>t.id===e.id):-1;this.highlight_=t>=0?t:0,this.onChange.dispatch()}reset(){this.charge=null,this.victim=null,this.stage_=`attacker`,this.highlight_=0,this.onChange.dispatch()}active(){return this.stage_===`attacker`?this.candidates:this.targets}},KH=class{constructor(e){this.onChange=new p,this.built=null,this.elapsed_=0,this.handleSelectorChange=()=>{if(this.selector.done&&this.attacker&&this.target){let e=this.damageFor(this.attacker,this.target);this.built=new UH({attacker:{hp:this.attacker.hp??0,name:this.attacker.id},defender:{hp:this.target.hp??0,name:this.target.id},damage:e.damage,strikes:e.strikes,...e.chanceToHit===void 0?{}:{chanceToHit:e.chanceToHit},...e.hits===void 0?{}:{hits:e.hits},strikeDuration:this.strikeDuration}),this.elapsed_=0}else this.built=null;this.onChange.dispatch()},this.damageFor=e.damageFor,this.strikeDuration=e.strikeDuration??0,this.selector=new GH({units:e.units,...e.side===void 0?{}:{side:e.side},...e.disabled===void 0?{}:{disabled:e.disabled},...e.canTarget===void 0?{}:{canTarget:e.canTarget}}),this.selector.onChange.add(this.handleSelectorChange)}get stage(){return this.selector.stage}get attacker(){return this.selector.attacker}get target(){return this.selector.target}get preview(){return this.built}get elapsed(){return this.elapsed_}get finished(){return this.built!==null&&this.elapsed_>=this.built.duration}get frame(){return this.built?this.built.sampleAt(this.elapsed_):null}move(e){this.selector.move(e)}select(){return this.selector.select()}back(){this.selector.back()}update(e){return this.built?(this.elapsed_=Math.min(this.built.duration,this.elapsed_+Math.max(0,e)),this.frame):null}finish(){this.built&&(this.elapsed_=this.built.duration)}reset(){this.selector.reset(),this.built=null,this.elapsed_=0}},qH=class{constructor(){this.onChange=new p,this.planned=[],this.undone=[]}get plans(){return this.planned}get isEmpty(){return this.planned.length===0}get canUndo(){return this.planned.length>0}get canRedo(){return this.undone.length>0}plannedFor(e){return this.planned.find(t=>t.unit===e)}plan(e){let t=this.planned.findIndex(t=>t.unit===e.unit);t>=0?this.planned[t]=e:this.planned.push(e),this.undone=[],this.onChange.dispatch()}undo(){let e=this.planned.pop();return e?(this.undone.push(e),this.onChange.dispatch(),e):null}redo(){let e=this.undone.pop();return e?(this.planned=this.planned.filter(t=>t.unit!==e.unit),this.planned.push(e),this.onChange.dispatch(),e):null}clear(){(this.planned.length!==0||this.undone.length!==0)&&(this.planned=[],this.undone=[],this.onChange.dispatch())}commit(){let e=this.planned;return this.planned=[],this.undone=[],e.length>0&&this.onChange.dispatch(),e}},JH=class e{constructor(){this.counts=new Map}record(e,t,n=1){let r=this.counts.get(e)??new Map;r.set(t,(r.get(t)??0)+n),this.counts.set(e,r)}forType(e,t){return this.counts.get(e)?.get(t)??0}total(e){let t=this.counts.get(e);if(!t)return 0;let n=0;for(let e of t.values())n+=e;return n}breakdown(e){let t=this.counts.get(e);return t?[...t.entries()].map(([e,t])=>({unitType:e,count:t})):[]}toJSON(){return{counts:[...this.counts].map(([e,t])=>[e,[...t]])}}static fromJSON(t){let n=new e;for(let[e,r]of t.counts)n.counts.set(e,new Map(r));return n}},YH=l({AttackDialog:()=>KH,AttackPreview:()=>UH,BattleHooks:()=>VH,BattleStats:()=>JH,Creature:()=>MH,Field:()=>HH,Party:()=>PH,StatStages:()=>LH,TypeMatrix:()=>NH,UnitSelector:()=>GH,Whiteboard:()=>qH,battleOrder:()=>FH,checkEvolution:()=>IH,chooseMove:()=>RH,chooseSwitch:()=>zH});function XH(e){let t=e.charCodeAt(0)-97,n=e.charCodeAt(1)-49;if(t<0||t>7||n<0||n>7||e.length!==2)throw Error(`not a square: "${e}"`);return n*8+t}function ZH(e){return String.fromCharCode(97+(e&7))+String.fromCharCode(49+(e>>3))}function QH(e){let t=[];for(let n=7;n>=0;n--){let r=``,i=0;for(let t=0;t<8;t++){let a=e.board[n*8+t];if(!a){i++;continue}i>0&&(r+=String(i),i=0);let o={pawn:`p`,knight:`n`,bishop:`b`,rook:`r`,queen:`q`,king:`k`}[a.kind];r+=a.side===`white`?o.toUpperCase():o}i>0&&(r+=String(i)),t.push(r)}let n=(e.castling.whiteKingside?`K`:``)+(e.castling.whiteQueenside?`Q`:``)+(e.castling.blackKingside?`k`:``)+(e.castling.blackQueenside?`q`:``);return`${t.join(`/`)} ${e.turn===`white`?`w`:`b`} ${n||`-`} ${e.enPassant===null?`-`:ZH(e.enPassant)}`}function $H(e){let t=e.trim().split(/\s+/);if(t.length<4)throw Error(`not a FEN string: "${e}"`);let n=Array(64).fill(null),r=t[0].split(`/`);if(r.length!==8)throw Error(`a FEN placement needs 8 ranks: "${e}"`);if(r.forEach((t,r)=>{let i=7-r,a=0;for(let r of t)if(r>=`1`&&r<=`8`)a+=r.charCodeAt(0)-48;else{let o=r===r.toUpperCase()?`white`:`black`,s={p:`pawn`,n:`knight`,b:`bishop`,r:`rook`,q:`queen`,k:`king`}[r.toLowerCase()];if(!s||a>7)throw Error(`bad FEN rank "${t}" in "${e}"`);n[i*8+a]={side:o,kind:s},a++}if(a!==8)throw Error(`bad FEN rank "${t}" in "${e}"`)}),t[1]!==`w`&&t[1]!==`b`)throw Error(`a FEN side is "w" or "b": "${e}"`);let i={whiteKingside:!1,whiteQueenside:!1,blackKingside:!1,blackQueenside:!1};if(t[2]!==`-`)for(let n of t[2])if(n===`K`)i.whiteKingside=!0;else if(n===`Q`)i.whiteQueenside=!0;else if(n===`k`)i.blackKingside=!0;else if(n===`q`)i.blackQueenside=!0;else throw Error(`bad FEN castling "${t[2]}" in "${e}"`);let a=t[3]===`-`?null:XH(t[3]);if(a!==null){let n=t[1]===`w`?5:2;if(nU(a)!==n)throw Error(`bad FEN en passant square "${t[3]}" in "${e}"`)}let o={board:n,turn:t[1]===`w`?`white`:`black`,castling:i,enPassant:a};return dU(n,`white`),dU(n,`black`),o}function eU(e){return e===`white`?`black`:`white`}function tU(e){return e&7}function nU(e){return e>>3}function rU(e,t){return e>=0&&e<8&&t>=0&&t<8}function iU(){let e=[`rook`,`knight`,`bishop`,`queen`,`king`,`bishop`,`knight`,`rook`],t=Array(64).fill(null);for(let n=0;n<8;n++)t[n]={side:`white`,kind:e[n]},t[8+n]={side:`white`,kind:`pawn`},t[48+n]={side:`black`,kind:`pawn`},t[56+n]={side:`black`,kind:e[n]};return{board:t,turn:`white`,castling:{whiteKingside:!0,whiteQueenside:!0,blackKingside:!0,blackQueenside:!0},enPassant:null}}function aU(e){return{board:e.board.map(e=>e?{side:e.side,kind:e.kind}:null),turn:e.turn,castling:{...e.castling},enPassant:e.enPassant}}var oU=[[1,2],[2,1],[2,-1],[1,-2],[-1,-2],[-2,-1],[-2,1],[-1,2]],sU=[[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1],[0,-1],[1,-1]],cU=[[1,1],[-1,1],[-1,-1],[1,-1]],lU=[[1,0],[0,1],[-1,0],[0,-1]];function uU(e,t,n){let r=tU(t),i=nU(t),a=n===`white`?i-1:i+1;for(let t of[-1,1]){if(!rU(r+t,a))continue;let i=e[a*8+r+t];if(i&&i.side===n&&i.kind===`pawn`)return!0}for(let[t,a]of oU){if(!rU(r+t,i+a))continue;let o=e[(i+a)*8+r+t];if(o&&o.side===n&&o.kind===`knight`)return!0}for(let[t,a]of sU){if(!rU(r+t,i+a))continue;let o=e[(i+a)*8+r+t];if(o&&o.side===n&&o.kind===`king`)return!0}let o=[{steps:cU,kinds:[`bishop`,`queen`]},{steps:lU,kinds:[`rook`,`queen`]}];for(let{steps:t,kinds:a}of o)for(let[o,s]of t){let t=r+o,c=i+s;for(;rU(t,c);){let r=e[c*8+t];if(r){if(r.side===n&&a.includes(r.kind))return!0;break}t+=o,c+=s}}return!1}function dU(e,t){let n=e.findIndex(e=>e!==null&&e.side===t&&e.kind===`king`);if(n===-1)throw Error(`a position without a ${t} king cannot be judged`);return n}function fU(e,t){return uU(e.board,dU(e.board,t),eU(t))}function pU(e,t){let n=e.board[t];if(!n||n.side!==e.turn)return[];let r=[],i=tU(t),a=nU(t),o=o=>{for(let[s,c]of o){let o=i+s,l=a+c;for(;rU(o,l);){let i=l*8+o,a=e.board[i];if(!a)r.push({from:t,to:i});else{a.side!==n.side&&r.push({from:t,to:i});break}o+=s,l+=c}}};switch(n.kind){case`pawn`:{let o=n.side===`white`?1:-1,s=n.side===`white`?1:6,c=n.side===`white`?7:0;if(rU(i,a+o)&&!e.board[(a+o)*8+i]){let n=(a+o)*8+i;if(a+o===c)for(let e of[`knight`,`bishop`,`rook`,`queen`])r.push({from:t,to:n,promotion:e});else r.push({from:t,to:n}),a===s&&!e.board[(a+2*o)*8+i]&&r.push({from:t,to:(a+2*o)*8+i})}for(let s of[-1,1]){if(!rU(i+s,a+o))continue;let l=(a+o)*8+i+s,u=e.board[l];if(u&&u.side!==n.side){if(a+o===c)for(let e of[`knight`,`bishop`,`rook`,`queen`])r.push({from:t,to:l,promotion:e});else r.push({from:t,to:l})}else!u&&l===e.enPassant&&r.push({from:t,to:l,enPassantTake:a*8+i+s})}break}case`knight`:for(let[o,s]of oU){if(!rU(i+o,a+s))continue;let c=(a+s)*8+i+o,l=e.board[c];(!l||l.side!==n.side)&&r.push({from:t,to:c})}break;case`bishop`:o(cU);break;case`rook`:o(lU);break;case`queen`:o(cU),o(lU);break;case`king`:{for(let[o,s]of sU){if(!rU(i+o,a+s))continue;let c=(a+s)*8+i+o,l=e.board[c];l&&l.side===n.side||l&&l.kind===`king`||r.push({from:t,to:c})}let o=n.side===`white`?0:56,s=n.side===`white`?{king:e.castling.whiteKingside,queen:e.castling.whiteQueenside}:{king:e.castling.blackKingside,queen:e.castling.blackQueenside};t===o+4&&!fU(e,n.side)&&(s.king&&!e.board[o+5]&&!e.board[o+6]&&!uU(e.board,o+5,eU(n.side))&&!uU(e.board,o+6,eU(n.side))&&r.push({from:t,to:o+6,castle:`kingside`}),s.queen&&!e.board[o+3]&&!e.board[o+2]&&!e.board[o+1]&&!uU(e.board,o+3,eU(n.side))&&!uU(e.board,o+2,eU(n.side))&&r.push({from:t,to:o+2,castle:`queenside`}));break}}return r}function mU(e,t){let n=e.board[t.from];if(!n)throw Error(`no piece on ${ZH(t.from)} to move`);let r=(e,t)=>{let n=e===`white`?0:56;return t===n||t===n+7};n.kind===`king`&&(n.side===`white`?e.castling.whiteKingside=e.castling.whiteQueenside=!1:e.castling.blackKingside=e.castling.blackQueenside=!1),n.kind===`rook`&&r(n.side,t.from)&&(e.castling[hU(n.side,t.from)]=!1);let i=e.board[t.to];if(i&&i.kind===`rook`&&r(i.side,t.to)&&(e.castling[hU(i.side,t.to)]=!1),e.board[t.to]=t.promotion?{side:n.side,kind:t.promotion}:n,e.board[t.from]=null,t.enPassantTake!==void 0&&(e.board[t.enPassantTake]=null),t.castle){let r=n.side===`white`?0:56;t.castle===`kingside`?(e.board[r+5]=e.board[r+7],e.board[r+7]=null):(e.board[r+3]=e.board[r],e.board[r]=null)}e.enPassant=n.kind===`pawn`&&Math.abs(t.to-t.from)===16?(t.from+t.to)/2:null,e.turn=eU(n.side)}function hU(e,t){let n=tU(t)===7;return e===`white`?n?`whiteKingside`:`whiteQueenside`:n?`blackKingside`:`blackQueenside`}function gU(e){let t=[];for(let n=0;n<64;n++)if(e.board[n]&&e.board[n]?.side===e.turn)for(let r of pU(e,n)){let n=aU(e);mU(n,r),!fU(n,e.turn)&&t.push({from:r.from,to:r.to,...r.promotion?{promotion:r.promotion}:{}})}return t}function _U(e,t){let n=e.board[t.from];if(!n||n.side!==e.turn)throw Error(`no ${e.turn} piece on ${ZH(t.from)} to move`);let r=pU(e,t.from).find(e=>e.to===t.to&&(e.promotion??null)===(t.promotion??null));if(!r)throw Error(`${ZH(t.from)}-${ZH(t.to)} is not a legal move here`);let i=aU(e);if(mU(i,r),fU(i,e.turn))throw Error(`${ZH(t.from)}-${ZH(t.to)} leaves the king in check`);mU(e,r)}function vU(e){return gU(e).length>0?`ongoing`:fU(e,e.turn)?e.turn===`white`?`black-wins`:`white-wins`:`stalemate`}var yU=1e5;function bU(e,t,n){if(!Number.isInteger(n.depth)||n.depth<1)throw RangeError(`depth must be a positive integer`);let r=n.maxNodes??yU;if(!Number.isInteger(r)||r<1)throw RangeError(`maxNodes must be a positive integer`);let i=e.currentPlayer(t),a=0,o=0,s,c=(t,l,u,d)=>{if(n.signal?.aborted)return s=`cancelled`,0;if(++a>r)return s=`budget-exceeded`,0;let f=e.currentPlayer(t)===i;if(n.onNode?.(l,f),l===0||e.isTerminal(t))return e.evaluate(t,i);let p=e.moves(t);if(!p.length)return e.evaluate(t,i);let m=f?-1/0:1/0;for(let n of p){let r=c(e.apply(t,n),l-1,u,d);if(s)return r;if(f?(m=Math.max(m,r),u=Math.max(u,m)):(m=Math.min(m,r),d=Math.min(d,m)),d<=u){o++;break}}return m},l=e.moves(t),u=null,d=e.evaluate(t,i);if(!e.isTerminal(t)&&l.length){let r=e.currentPlayer(t)===i,a=r?-1/0:1/0,o=-1/0,f=1/0;for(let i of l){let l=c(e.apply(t,i),n.depth-1,o,f);if(s)break;(u===null||(r?l>a:l<a))&&(u=i,a=l),r?o=Math.max(o,a):f=Math.min(f,a)}u!==null&&(d=a)}return{move:s?null:u,score:d,depth:n.depth,nodes:a,cutoffs:o,status:s??`complete`,state:t}}function xU(e,t){return e.moves(t).map(n=>({move:n,child:e.apply(t,n)}))}function SU(e,t){let n=null,r=t?-1/0:1/0;for(let{move:i,score:a}of e)(n===null||(t?a>r:a<r))&&(n=i,r=a);return n}function CU(){return globalThis.process?.getBuiltinModule?.(`node:worker_threads`)}function wU(){let e=globalThis.process?.getBuiltinModule?.(`node:worker_threads`)?.parentPort??null,t=globalThis,n=e=>{let t=[],n=new Set,r=e=>{if(typeof e!=`object`||!e||n.has(e))return;if(n.add(e),ArrayBuffer.isView(e)){let n=e.buffer;n instanceof ArrayBuffer&&!t.includes(n)&&t.push(n);return}if(e instanceof ArrayBuffer){t.includes(e)||t.push(e);return}if(Array.isArray(e)){for(let t of e)r(t);return}let i=Object.getPrototypeOf(e);if(i===Object.prototype||i===null)for(let t of Object.values(e))r(t)};return r(e),t},r=(n,r=[])=>{e?e.postMessage(n,r):t.postMessage(n,r)},i=async e=>{try{let t=await Function(`return (${e.code});`)()(...e.args);r({ok:!0,value:t},n(t))}catch(e){let t=e;r({ok:!1,message:String(t?.message??e),stack:typeof t?.stack==`string`?t.stack:void 0})}};e?e.on(`message`,e=>void i(e)):t.onmessage=e=>void i(e.data)}var TU=e=>{if(typeof Worker>`u`||typeof Blob>`u`||typeof URL>`u`||typeof URL.createObjectURL!=`function`)return null;let t=URL.createObjectURL(new Blob([`(${wU.toString()})()`],{type:`text/javascript`})),n;try{n=new Worker(t)}catch(e){throw URL.revokeObjectURL(t),e}return n.onmessage=t=>e.reply(t.data),n.onerror=t=>e.fail(Error(t.message||`the worker failed to run`)),n.onmessageerror=()=>e.fail(Error(`the worker sent a reply that could not be deserialized`)),{post:(e,t)=>n.postMessage(e,t),terminate:()=>{n.terminate(),URL.revokeObjectURL(t)}}},EU=e=>{let t=CU();if(!t)return null;let n=new t.Worker(`(${wU.toString()})()`,{eval:!0});return n.on(`message`,t=>e.reply(t)),n.on(`error`,t=>e.fail(t instanceof Error?t:Error(String(t)))),n.on(`messageerror`,()=>e.fail(Error(`the worker sent a reply that could not be deserialized`))),n.on(`exit`,t=>e.fail(Error(`the worker exited with code ${t} before answering`))),{post:(e,t)=>n.postMessage(e,t),terminate:()=>void n.terminate()}};function DU(e){let t=Error(e.message);return e.stack&&(t.stack=e.stack),t}function OU(e,t,n={}){return new Promise((r,i)=>{if(n.signal?.aborted){i(n.signal.reason);return}let a=!1,o,s,c=e=>{a||(a=!0,o!==void 0&&clearTimeout(o),n.signal?.removeEventListener(`abort`,l),s?.terminate(),e())};function l(){c(()=>i(n.signal.reason))}let u={reply:e=>c(()=>{e.ok?r(e.value):i(DU(e))}),fail:e=>c(()=>i(e))};try{s=TU(u)??EU(u)}catch(e){i(e);return}if(!s){i(Error(`spawn() needs Web Workers or node:worker_threads, and this environment offers neither`));return}n.timeout!==void 0&&n.timeout>0&&(o=setTimeout(()=>c(()=>i(Error(`the task did not answer within ${n.timeout} ms`))),n.timeout)),n.signal?.addEventListener(`abort`,l,{once:!0});try{s.post({code:e.toString(),args:t??[]},n.transfer??[])}catch(e){c(()=>i(e))}})}var kU=1e5,AU={pawn:100,knight:320,bishop:330,rook:500,queen:900,king:0};function jU(e,t={}){return MU(e,t).move}function MU(e,t={}){let n=bU(IU,e,{depth:Math.max(1,Math.floor(t.depth??3)),maxNodes:t.maxNodes===void 0?1e5:Math.max(1,Math.floor(t.maxNodes))});return{move:n.move,score:n.score,nodes:n.nodes}}async function NU(e,t={}){let n=Math.max(1,Math.floor(t.depth??3)),r=t.maxNodes===void 0?1e5:Math.max(1,Math.floor(t.maxNodes)),i=t.jobs??PU();if(!Number.isInteger(i)||i<1)throw RangeError(`jobs must be a positive integer`);if(t.signal?.aborted)throw t.signal.reason;let a=IU.currentPlayer(e),o=xU(IU,e);if(IU.isTerminal(e)||!o.length)return{move:null,score:IU.evaluate(e,a),nodes:0};let s=Math.max(1,Math.min(i,o.length)),c=Array(o.length),l=0,u=!1,d=0,f=t.signal?{signal:t.signal}:{};if(await Promise.all(Array.from({length:s},async()=>{for(;;){let e=d++;if(e>=o.length)return;let t=await OU(FU,[o[e].child,a,n-1,r],f);l+=t.nodes,t.budgetExceeded?u=!0:c[e]={move:o[e].move,score:t.score}}})),u)return{move:null,score:IU.evaluate(e,a),nodes:l};let p=c.filter(e=>e!==void 0),m=SU(p,!0);return{move:m,score:p.find(e=>e.move===m)?.score??IU.evaluate(e,a),nodes:l}}function PU(){let e=globalThis,t=e.navigator?.hardwareConcurrency;if(typeof t==`number`&&Number.isInteger(t)&&t>0)return Math.min(t,8);try{let t=e.process?.getBuiltinModule?.(`node:os`)?.availableParallelism?.();if(typeof t==`number`&&Number.isInteger(t)&&t>0)return Math.min(t,8)}catch{}return 4}function FU(e,t,n,r){let i={pawn:100,knight:320,bishop:330,rook:500,queen:900,king:0},a=e=>e===`white`?`black`:`white`,o=e=>e&7,s=e=>e>>3,c=(e,t)=>e>=0&&e<8&&t>=0&&t<8,l=[[1,2],[2,1],[2,-1],[1,-2],[-1,-2],[-2,-1],[-2,1],[-1,2]],u=[[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1],[0,-1],[1,-1]],d=[[1,1],[-1,1],[-1,-1],[1,-1]],f=[[1,0],[0,1],[-1,0],[0,-1]],p=(e,t,n)=>{let r=o(t),i=s(t),a=n===`white`?i-1:i+1;for(let t of[-1,1]){if(!c(r+t,a))continue;let i=e[a*8+r+t];if(i&&i.side===n&&i.kind===`pawn`)return!0}for(let[t,a]of l){if(!c(r+t,i+a))continue;let o=e[(i+a)*8+r+t];if(o&&o.side===n&&o.kind===`knight`)return!0}for(let[t,a]of u){if(!c(r+t,i+a))continue;let o=e[(i+a)*8+r+t];if(o&&o.side===n&&o.kind===`king`)return!0}let p=[{steps:d,kinds:[`bishop`,`queen`]},{steps:f,kinds:[`rook`,`queen`]}];for(let{steps:t,kinds:a}of p)for(let[o,s]of t){let t=r+o,l=i+s;for(;c(t,l);){let r=e[l*8+t];if(r){if(r.side===n&&a.includes(r.kind))return!0;break}t+=o,l+=s}}return!1},m=(e,t)=>{let n=e.findIndex(e=>e!==null&&e.side===t&&e.kind===`king`);if(n===-1)throw Error(`a position without a ${t} king cannot be judged`);return n},h=(e,t)=>p(e.board,m(e.board,t),a(t)),g=(e,t)=>{let n=e.board[t];if(!n||n.side!==e.turn)return[];let r=[],i=o(t),m=s(t),g=a=>{for(let[o,s]of a){let a=i+o,l=m+s;for(;c(a,l);){let i=l*8+a,c=e.board[i];if(!c)r.push({from:t,to:i});else{c.side!==n.side&&r.push({from:t,to:i});break}a+=o,l+=s}}};switch(n.kind){case`pawn`:{let a=n.side===`white`?1:-1,o=n.side===`white`?1:6,s=n.side===`white`?7:0;if(c(i,m+a)&&!e.board[(m+a)*8+i]){let n=(m+a)*8+i;if(m+a===s)for(let e of[`knight`,`bishop`,`rook`,`queen`])r.push({from:t,to:n,promotion:e});else r.push({from:t,to:n}),m===o&&!e.board[(m+2*a)*8+i]&&r.push({from:t,to:(m+2*a)*8+i})}for(let o of[-1,1]){if(!c(i+o,m+a))continue;let l=(m+a)*8+i+o,u=e.board[l];if(u&&u.side!==n.side){if(m+a===s)for(let e of[`knight`,`bishop`,`rook`,`queen`])r.push({from:t,to:l,promotion:e});else r.push({from:t,to:l})}else!u&&l===e.enPassant&&r.push({from:t,to:l,enPassantTake:m*8+i+o})}break}case`knight`:for(let[a,o]of l){if(!c(i+a,m+o))continue;let s=(m+o)*8+i+a,l=e.board[s];(!l||l.side!==n.side)&&r.push({from:t,to:s})}break;case`bishop`:g(d);break;case`rook`:g(f);break;case`queen`:g(d),g(f);break;case`king`:{for(let[a,o]of u){if(!c(i+a,m+o))continue;let s=(m+o)*8+i+a,l=e.board[s];l&&l.side===n.side||l&&l.kind===`king`||r.push({from:t,to:s})}let o=n.side===`white`?0:56,s=n.side===`white`?{king:e.castling.whiteKingside,queen:e.castling.whiteQueenside}:{king:e.castling.blackKingside,queen:e.castling.blackQueenside};t===o+4&&!h(e,n.side)&&(s.king&&!e.board[o+5]&&!e.board[o+6]&&!p(e.board,o+5,a(n.side))&&!p(e.board,o+6,a(n.side))&&r.push({from:t,to:o+6,castle:`kingside`}),s.queen&&!e.board[o+3]&&!e.board[o+2]&&!e.board[o+1]&&!p(e.board,o+3,a(n.side))&&!p(e.board,o+2,a(n.side))&&r.push({from:t,to:o+2,castle:`queenside`}));break}}return r},_=(e,t)=>{let n=e.board[t.from];if(!n)throw Error(`no piece on ${t.from} to move`);let r=(e,t)=>{let n=e===`white`?0:56;return t===n||t===n+7},i=(e,t)=>{let n=o(t)===7;return e===`white`?n?`whiteKingside`:`whiteQueenside`:n?`blackKingside`:`blackQueenside`};n.kind===`king`&&(n.side===`white`?e.castling.whiteKingside=e.castling.whiteQueenside=!1:e.castling.blackKingside=e.castling.blackQueenside=!1),n.kind===`rook`&&r(n.side,t.from)&&(e.castling[i(n.side,t.from)]=!1);let s=e.board[t.to];if(s&&s.kind===`rook`&&r(s.side,t.to)&&(e.castling[i(s.side,t.to)]=!1),e.board[t.to]=t.promotion?{side:n.side,kind:t.promotion}:n,e.board[t.from]=null,t.enPassantTake!==void 0&&(e.board[t.enPassantTake]=null),t.castle){let r=n.side===`white`?0:56;t.castle===`kingside`?(e.board[r+5]=e.board[r+7],e.board[r+7]=null):(e.board[r+3]=e.board[r],e.board[r]=null)}e.enPassant=n.kind===`pawn`&&Math.abs(t.to-t.from)===16?(t.from+t.to)/2:null,e.turn=a(n.side)},v=e=>({board:e.board.map(e=>e?{side:e.side,kind:e.kind}:null),turn:e.turn,castling:{...e.castling},enPassant:e.enPassant}),y=e=>{let t=[];for(let n=0;n<64;n++)if(e.board[n]&&e.board[n]?.side===e.turn)for(let r of g(e,n)){let n=v(e);_(n,r),!h(n,e.turn)&&t.push({from:r.from,to:r.to,...r.promotion?{promotion:r.promotion}:{}})}return t},b=e=>y(e).length>0?`ongoing`:h(e,e.turn)?e.turn===`white`?`black-wins`:`white-wins`:`stalemate`,x=(e,t)=>{let n=e.board[t.to];return(t.promotion?i[t.promotion]:0)*10+(n?i[n.kind]:0)},S=(e,t)=>t.slice().sort((t,n)=>x(e,n)-x(e,t)),C=(e,t)=>{let n=0;for(let t of e.board)t&&(n+=(t.side===`white`?1:-1)*i[t.kind]);return t===1?n:-n},ee=(e,t)=>{let n=b(e);return n===`stalemate`||!h(e,e.turn)?0:(n===`white-wins`?1:-1)===t?1e5:-1e5},w=e=>b(e)===`ongoing`?C(e,t):ee(e,t),T=0,E=!1,D=(e,n,i,a)=>{if(++T>r)return E=!0,0;let o=(e.turn===`white`?1:-1)===t;if(n===0||b(e)!==`ongoing`)return w(e);let s=S(e,y(e));if(!s.length)return w(e);let c=o?-1/0:1/0;for(let t of s){let r=v(e),s=g(r,t.from).find(e=>e.to===t.to&&(e.promotion??null)===(t.promotion??null));if(!s)throw Error(`a legal move stopped being legal: ${t.from}-${t.to}`);_(r,s);let l=D(r,n-1,i,a);if(E)return l;if(o?(c=Math.max(c,l),i=Math.max(i,c)):(c=Math.min(c,l),a=Math.min(a,c)),a<=i)break}return c};return{score:D(e,n,-1/0,1/0),nodes:T,budgetExceeded:E}}var IU={currentPlayer:e=>e.turn===`white`?1:-1,moves:e=>zU(e,gU(e)),apply:(e,t)=>{let n=aU(e);return _U(n,t),n},isTerminal:e=>vU(e)!==`ongoing`,evaluate:(e,t)=>vU(e)===`ongoing`?LU(e,t):RU(e,t)};function LU(e,t){let n=0;for(let t of e.board)t&&(n+=(t.side===`white`?1:-1)*AU[t.kind]);return t===1?n:-n}function RU(e,t){let n=vU(e);return n===`stalemate`||!fU(e,e.turn)?0:(n===`white-wins`?1:-1)===t?kU:-1e5}function zU(e,t){return t.slice().sort((t,n)=>BU(e,n)-BU(e,t))}function BU(e,t){let n=e.board[t.to];return(t.promotion?AU[t.promotion]:0)*10+(n?AU[n.kind]:0)}function VU(e,t){return e.positions[QH(t)]??null}var HU={q:`queen`,r:`rook`,b:`bishop`,n:`knight`};function UU(e){let t=/^([a-h][1-8])([a-h][1-8])([qrbn])?$/.exec(e);if(!t)throw Error(`not a UCI move: "${e}"`);let n=t[3]?HU[t[3]]:void 0;return n?{from:XH(t[1]),to:XH(t[2]),promotion:n}:{from:XH(t[1]),to:XH(t[2])}}var WU={pawn:0,knight:1,bishop:2,rook:3,queen:4,king:5},GU=[`queen`,`rook`,`bishop`,`knight`],KU=[[1,2],[2,1],[2,-1],[1,-2],[-1,-2],[-2,-1],[-2,1],[-1,2]],qU=[[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1],[0,-1],[1,-1]],JU=[[1,1],[-1,1],[-1,-1],[1,-1]],YU=[[1,0],[0,1],[-1,0],[0,-1]];function XU(e){return 1n<<BigInt(e)}function ZU(e){return Math.log2(Number(e))}function QU(e){return Array.from({length:64},(t,n)=>{let r=n&7,i=n>>3,a=0n;for(let[t,n]of e){let e=r+t,o=i+n;e>=0&&e<8&&o>=0&&o<8&&(a|=XU(o*8+e))}return a})}var $U=QU(KU),eW=QU(qU);function tW(e,t){return e.pieces[t]|e.pieces[t+1]|e.pieces[t+2]|e.pieces[t+3]|e.pieces[t+4]|e.pieces[t+5]}function nW(e,t){let n=XU(t);for(let t=0;t<12;t++)if(e.pieces[t]&n)return t;return-1}function rW(e,t,n){let r=n?0:6,i=t&7,a=t>>3,o=n?a-1:a+1;for(let t of[-1,1]){let n=i+t;if(o>=0&&o<8&&n>=0&&n<8&&e.pieces[r]&XU(o*8+n))return!0}if($U[t]&e.pieces[r+1]||eW[t]&e.pieces[r+5])return!0;let s=[{steps:JU,kinds:[2,4]},{steps:YU,kinds:[3,4]}];for(let{steps:t,kinds:n}of s)for(let[o,s]of t){let t=i+o,c=a+s;for(;t>=0&&t<8&&c>=0&&c<8;){let i=nW(e,c*8+t);if(i!==-1){if(i>=r&&i<r+6&&n.includes(i-r))return!0;break}t+=o,c+=s}}return!1}function iW(e,t){return e===`white`?t?1:2:t?4:8}function aW(e){let t=Array(12).fill(0n),n=[-1,-1];if(e.board.forEach((e,r)=>{if(!e)return;let i=(e.side===`white`?0:6)+WU[e.kind];t[i]|=XU(r),e.kind===`king`&&(n[e.side===`white`?0:1]=r)}),n[0]===-1||n[1]===-1)throw Error(`a position without both kings cannot go on bitboards`);return{pieces:t,turn:e.turn,castling:+!!e.castling.whiteKingside|(e.castling.whiteQueenside?2:0)|(e.castling.blackKingside?4:0)|(e.castling.blackQueenside?8:0),enPassant:e.enPassant,halfmove:0,kings:n}}function oW(){return aW(iU())}function sW(e){let t=e.turn===`white`,n=t?0:6,r=tW(e,n),i=tW(e,n===0?6:0),a=r|i,o=[],s=[];for(let c=0;c<64;c++){if(!(r&XU(c)))continue;let l=-1;for(let t=0;t<6;t++)if(e.pieces[n+t]&XU(c)){l=t;break}s.length=0,cW(e,c,l,a,i,s);for(let n of s){let r=lW(e,n);rW(e,e.kings[+!t],!t)||o.push({...n}),uW(e,n,r)}}return o}function cW(e,t,n,r,i,a){let o=e.turn===`white`,s=t&7,c=t>>3,l=(e,n)=>{a.push(n?{from:t,to:e,promotion:n}:{from:t,to:e})},u=e=>{for(let[t,n]of e){let e=s+t,a=c+n;for(;e>=0&&e<8&&a>=0&&a<8;){let o=a*8+e,s=XU(o);if(!(r&s))l(o);else{i&s&&l(o);break}e+=t,a+=n}}};switch(n){case 0:{let n=o?8:-8,a=o?1:6,u=o?7:0,d=t+n;if(d>=0&&d<64&&!(r&XU(d))){if(d>>3===u)for(let e of GU)l(d,e);else{l(d);let e=t+2*n;c===a&&!(r&XU(e))&&l(e)}}for(let r of[-1,1]){let a=s+r;if(a<0||a>7)continue;let o=t+n+r;if(!(o<0||o>=64)){if(i&XU(o)){if(o>>3===u)for(let e of GU)l(o,e);else l(o)}else o===e.enPassant&&l(o)}}break}case 1:{let n=$U[t]&~tW(e,o?0:6);for(;n;){let e=n&-n;l(ZU(e)),n^=e}break}case 2:u(JU);break;case 3:u(YU);break;case 4:u(JU),u(YU);break;case 5:{let n=eW[t]&~tW(e,o?0:6);for(n&=~e.pieces[o?11:5];n;){let e=n&-n;l(ZU(e)),n^=e}let i=o?0:56,a=e.castling,s=o?a&1:a&4,c=o?a&2:a&8;t===i+4&&!rW(e,t,!o)&&(s&&!(r&XU(i+5))&&!(r&XU(i+6))&&!rW(e,i+5,!o)&&!rW(e,i+6,!o)&&l(i+6),c&&!(r&XU(i+3))&&!(r&XU(i+2))&&!(r&XU(i+1))&&!rW(e,i+3,!o)&&!rW(e,i+2,!o)&&l(i+2));break}}}function lW(e,t){let n=e.turn===`white`,r=+!n,i=r*6,a=XU(t.from),o=XU(t.to),s=-1;for(let t=0;t<6;t++)if(e.pieces[i+t]&a){s=t;break}if(s===-1)throw Error(`no piece on ${t.from} to move`);let c={captured:null,castling:e.castling,enPassant:e.enPassant,halfmove:e.halfmove,kingSquare:e.kings[r]},l=(1-r)*6,u=n?8:-8,d=t.to;s===0&&t.to===e.enPassant&&(d=t.to-u);let f=XU(d);for(let t=0;t<6;t++)if(e.pieces[l+t]&f){c.captured={color:1-r,kind:t},e.pieces[l+t]^=f;break}let p=n?0:56,m=n?56:0;if(s===5&&(e.castling&=~(iW(e.turn,!0)|iW(e.turn,!1))),s===3&&(t.from===p||t.from===p+7)&&(e.castling&=~iW(e.turn,t.from===p+7)),c.captured?.kind===3&&(d===m||d===m+7)&&(e.castling&=~iW(n?`black`:`white`,d===m+7)),e.pieces[i+s]^=a,t.promotion?e.pieces[i+WU[t.promotion]]|=o:e.pieces[i+s]|=o,s===5&&Math.abs(t.to-t.from)===2){let n=i+3;t.to>t.from?e.pieces[n]^=XU(p+7)|XU(p+5):e.pieces[n]^=XU(p)|XU(p+3)}return e.enPassant=s===0&&Math.abs(t.to-t.from)===16?(t.from+t.to)/2:null,e.halfmove=s===0||c.captured?0:e.halfmove+1,s===5&&(e.kings[r]=t.to),e.turn=n?`black`:`white`,c}function uW(e,t,n){e.turn=e.turn===`white`?`black`:`white`;let r=e.turn===`white`,i=+!r,a=i*6,o=XU(t.to),s=t.promotion?0:(()=>{for(let t=0;t<6;t++)if(e.pieces[a+t]&o)return t;throw Error(`nothing on ${t.to} to take back`)})();if(t.promotion?e.pieces[a+WU[t.promotion]]^=o:e.pieces[a+s]^=o,e.pieces[a+s]|=XU(t.from),s===5&&Math.abs(t.to-t.from)===2){let n=r?0:56,i=a+3;t.to>t.from?e.pieces[i]^=XU(n+7)|XU(n+5):e.pieces[i]^=XU(n)|XU(n+3)}if(n.captured){let a=r?8:-8,o=s===0&&t.to===n.enPassant?t.to-a:t.to;e.pieces[(1-i)*6+n.captured.kind]|=XU(o)}e.castling=n.castling,e.enPassant=n.enPassant,e.halfmove=n.halfmove,e.kings[i]=n.kingSquare}function dW(e,t){if(!Number.isInteger(t)||t<0)throw RangeError(`perft depth must be a non-negative integer`);if(t===0)return 1;let n=0;for(let r of sW(e)){let i=lW(e,r);n+=dW(e,t-1),uW(e,r,i)}return n}function fW(e,t={}){let n=1e6,r=[100,320,330,500,900,0],i=Math.max(1,Math.floor(t.depth??3)),a=t.maxNodes===void 0?5e5:Math.max(1,Math.floor(t.maxNodes)),o=t.timeMs===void 0?-1:Date.now()+Math.max(1,t.timeMs),s={pieces:e.pieces.slice(),turn:e.turn,castling:e.castling,enPassant:e.enPassant,halfmove:e.halfmove,kings:[e.kings[0],e.kings[1]]};function c(e){return 1n<<BigInt(e)}function l(e){return Math.log2(Number(e))}let u=[[1,2],[2,1],[2,-1],[1,-2],[-1,-2],[-2,-1],[-2,1],[-1,2]],d=[[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1],[0,-1],[1,-1]],f=[[1,1],[-1,1],[-1,-1],[1,-1]],p=[[1,0],[0,1],[-1,0],[0,-1]];function m(e){return Array.from({length:64},(t,n)=>{let r=n&7,i=n>>3,a=0n;for(let[t,n]of e){let e=r+t,o=i+n;e>=0&&e<8&&o>=0&&o<8&&(a|=c(o*8+e))}return a})}let h=m(u),g=m(d);function _(e){return s.pieces[e]|s.pieces[e+1]|s.pieces[e+2]|s.pieces[e+3]|s.pieces[e+4]|s.pieces[e+5]}function v(e){let t=c(e);for(let e=0;e<12;e++)if(s.pieces[e]&t)return e%6;return-1}function y(e,t){let n=t?0:6,r=e&7,i=e>>3,a=t?i-1:i+1;for(let e of[-1,1]){let t=r+e;if(a>=0&&a<8&&t>=0&&t<8&&s.pieces[n]&c(a*8+t))return!0}if(h[e]&s.pieces[n+1]||g[e]&s.pieces[n+5])return!0;let o=[{steps:f,kinds:[2,4]},{steps:p,kinds:[3,4]}];for(let{steps:e,kinds:n}of o)for(let[a,o]of e){let e=r+a,l=i+o;for(;e>=0&&e<8&&l>=0&&l<8;){let r=v(l*8+e);if(r!==-1){if((()=>{let t=c(l*8+e);for(let e=0;e<12;e++)if(s.pieces[e]&t)return e<6?0:1;return-1})()===+!t&&n.includes(r))return!0;break}e+=a,l+=o}}return!1}let b=0n,x=11400714819323198485n;function S(){x=x+11400714819323198485n&18446744073709551615n;let e=x;return e=(e^e>>30n)*13787848793156543929n&18446744073709551615n,e=(e^e>>27n)*10723151780598845931n&18446744073709551615n,e^e>>31n}let C=Array.from({length:12},()=>Array.from({length:64},()=>S())),ee=S(),w=Array.from({length:16},()=>S()),T=Array.from({length:8},()=>S());function E(){let e=0n;for(let t=0;t<12;t++){let n=s.pieces[t];for(;n;){let r=n&-n;e^=C[t][l(r)],n^=r}}return s.turn===`black`&&(e^=ee),e^=w[s.castling],s.enPassant!==null&&(e^=T[s.enPassant&7]),e}b=E();function D(e,t){return e===`white`?t?1:2:t?4:8}function O(e){let t=s.turn===`white`,n=+!t,r=n*6,i=c(e.from),a=c(e.to),o=-1;for(let e=0;e<6;e++)if(s.pieces[r+e]&i){o=e;break}let l={captured:null,castling:s.castling,enPassant:s.enPassant,halfmove:s.halfmove,kingSquare:s.kings[n],key:b,nullMove:!1},u=(1-n)*6,d=t?8:-8,f=e.to;o===0&&e.to===s.enPassant&&(f=e.to-d);let p=c(f);for(let e=0;e<6;e++)if(s.pieces[u+e]&p){l.captured={color:1-n,kind:e},s.pieces[u+e]^=p;break}let m=t?0:56,h=t?56:0;o===5&&(s.castling&=~(D(s.turn,!0)|D(s.turn,!1))),o===3&&(e.from===m||e.from===m+7)&&(s.castling&=~D(s.turn,e.from===m+7)),l.captured&&l.captured.kind===3&&(f===h||f===h+7)&&(s.castling&=~D(t?`black`:`white`,f===h+7));let g={queen:4,rook:3,bishop:2,knight:1};if(s.pieces[r+o]^=i,e.promotion?s.pieces[r+g[e.promotion]]|=a:s.pieces[r+o]|=a,o===5&&Math.abs(e.to-e.from)===2){let t=r+3;e.to>e.from?s.pieces[t]^=c(m+7)|c(m+5):s.pieces[t]^=c(m)|c(m+3)}return s.enPassant=o===0&&Math.abs(e.to-e.from)===16?(e.from+e.to)/2:null,s.halfmove=o===0||l.captured?0:s.halfmove+1,o===5&&(s.kings[n]=e.to),s.turn=t?`black`:`white`,b=E(),l}function te(e,t){s.turn=s.turn===`white`?`black`:`white`;let n=s.turn===`white`,r=+!n,i=r*6,a=c(e.to),o=e.promotion?0:(()=>{for(let e=0;e<6;e++)if(s.pieces[i+e]&a)return e;return-1})(),l={queen:4,rook:3,bishop:2,knight:1};if(e.promotion?s.pieces[i+l[e.promotion]]^=a:s.pieces[i+o]^=a,s.pieces[i+o]|=c(e.from),o===5&&Math.abs(e.to-e.from)===2){let t=n?0:56,r=i+3;e.to>e.from?s.pieces[r]^=c(t+7)|c(t+5):s.pieces[r]^=c(t)|c(t+3)}if(t.captured){let i=n?8:-8,a=o===0&&e.to===t.enPassant?e.to-i:e.to;s.pieces[(1-r)*6+t.captured.kind]|=c(a)}s.castling=t.castling,s.enPassant=t.enPassant,s.halfmove=t.halfmove,s.kings[r]=t.kingSquare,b=t.key}function ne(){let e={captured:null,castling:s.castling,enPassant:s.enPassant,halfmove:s.halfmove,kingSquare:-1,key:b,nullMove:!0};return s.enPassant=null,s.halfmove+=1,s.turn=s.turn===`white`?`black`:`white`,b=E(),e}function k(e){s.turn=s.turn===`white`?`black`:`white`,s.enPassant=e.enPassant,s.halfmove=e.halfmove,b=e.key}function A(e,t,n,r,i){let a=s.turn===`white`,o=e&7,u=e>>3,d=(t,n)=>{i.push(n?{from:e,to:t,promotion:n}:{from:e,to:t})},m=e=>{for(let[t,i]of e){let e=o+t,a=u+i;for(;e>=0&&e<8&&a>=0&&a<8;){let o=a*8+e,s=c(o);if(!(n&s))d(o);else{r&s&&d(o);break}e+=t,a+=i}}},v=[`queen`,`rook`,`bishop`,`knight`];if(t===0){let t=a?8:-8,i=a?1:6,l=a?7:0,f=e+t;if(f>=0&&f<64&&!(n&c(f))){if(f>>3===l)for(let e of v)d(f,e);else{d(f);let r=e+2*t;u===i&&!(n&c(r))&&d(r)}}for(let n of[-1,1]){let i=o+n;if(i<0||i>7)continue;let a=e+t+n;if(!(a<0||a>=64)){if(r&c(a)){if(a>>3===l)for(let e of v)d(a,e);else d(a)}else a===s.enPassant&&d(a)}}}else if(t===1){let t=h[e]&~_(a?0:6);for(;t;){let e=t&-t;d(l(e)),t^=e}}else if(t===2)m(f);else if(t===3)m(p);else if(t===4)m(f),m(p);else{let t=g[e]&~_(a?0:6);for(t&=~s.pieces[a?11:5];t;){let e=t&-t;d(l(e)),t^=e}let r=a?0:56,i=s.castling,o=a?i&1:i&4,u=a?i&2:i&8;e===r+4&&!y(e,!a)&&(o&&!(n&c(r+5))&&!(n&c(r+6))&&!y(r+5,!a)&&!y(r+6,!a)&&d(r+6),u&&!(n&c(r+3))&&!(n&c(r+2))&&!(n&c(r+1))&&!y(r+3,!a)&&!y(r+2,!a)&&d(r+2))}}function re(){let e=s.turn===`white`,t=e?0:6,n=_(t),r=_(t===0?6:0),i=n|r,a=[],o=[];for(let l=0;l<64;l++){if(!(n&c(l)))continue;let u=-1;for(let e=0;e<6;e++)if(s.pieces[t+e]&c(l)){u=e;break}o.length=0,A(l,u,i,r,o);for(let t of o){let n=O(t);y(s.kings[+!e],!e)||a.push({...t}),te(t,n)}}return a}function ie(e){let t=e?0:6;return s.pieces[t+1]!==0n||s.pieces[t+2]!==0n||s.pieces[t+3]!==0n||s.pieces[t+4]!==0n}function ae(){let e=0,t=0;for(let n=0;n<12;n++){if(n%6==5)continue;let r=s.pieces[n];for(;r;)r&=r-1n,e++,(n%6==1||n%6==2)&&t++}return e===0||e===1&&t===1}function oe(){let e=0,t=0;for(let n=0;n<12;n++){let r=s.pieces[n];for(;r;)r&=r-1n,n%6==4?e++:n%6!=5&&n%6!=0&&t++}return e===0||e===2&&t<=2}function se(e,t,n,r){let i=t&7,a=n?t>>3:7-(t>>3),o=3.5-Math.abs(i-3.5),s=3.5-Math.abs(a-3.5);return e===0?(a-1)*12+Math.max(0,o)*4:e===1?(o+s)*6-12:e===2?(o+s)*4:e===3?(o+s)*2+(a===6?12:0):e===4?(o+s)*2:r?(o+s)*10:-a*10+o*2}function j(){let e=oe(),t=0;for(let n=0;n<12;n++){let i=n<6,a=n%6,o=s.pieces[n];for(;o;){let n=o&-o,s=l(n),c=r[a]+se(a,s,i,e);t+=i?c:-c,o^=n}}return s.turn===`white`?t:-t}let ce=65536,le=Array(ce).fill(-1n),ue=Array(ce).fill(-1),de=Array(ce).fill(0),fe=Array(ce).fill(0),pe=Array(ce).fill(0);function me(e){let t=e.promotion===`queen`?1:e.promotion===`rook`?2:e.promotion===`bishop`?3:e.promotion===`knight`?4:0;return e.from|e.to<<6|t<<12}function he(e,t,n,r){let i=Number(b&BigInt(65535));if(le[i]!==b)return{score:null,move:0};let a=pe[i];if(ue[i]<e)return{score:null,move:a};let o=de[i];o>99e3?o-=r:o<-99e3&&(o+=r);let s=fe[i];return s===0||s===1&&o>=n||s===2&&o<=t?{score:o,move:a}:{score:null,move:a}}function ge(e,t,n,r,i){let a=Number(b&BigInt(65535));if(le[a]===b&&ue[a]>e)return;let o=t;t>99e3?o+=i:t<-99e3&&(o-=i),le[a]=b,ue[a]=e,de[a]=o,fe[a]=n,pe[a]=r}let _e=Array.from({length:64},()=>[0,0]),ve=Array.from({length:2},()=>Array.from({length:64},()=>Array(64).fill(0)));function M(e){let t=s.turn===`white`?6:0,n=c(e);for(let e=4;e>=0;e--)if(s.pieces[t+e]&n)return e;return-1}function N(e,t,n){let i=s.turn===`white`?0:1,a=e.map(e=>{let a=me(e);if(a===t)return 3e6;let o=M(e.to),c=v(e.from),l=e.to===s.enPassant&&c===0;if(o!==-1||l){let t=2e6+(l?r[0]:r[o])*8-c;return e.promotion&&(t+=900),t}return e.promotion?15e5:n<64?_e[n][0]===a?1e6:_e[n][1]===a?9e5:ve[i][e.from][e.to]:0}),o=e.map((e,t)=>t);for(let e=0;e<o.length;e++){let t=e;for(let n=e+1;n<o.length;n++)a[o[n]]>a[o[t]]&&(t=n);[o[e],o[t]]=[o[t],o[e]]}return o}let ye=0,be=!1,P=[];function xe(){return be?!0:ye>a||t.signal?.aborted||o!==-1&&!(ye&2047)&&Date.now()>=o?(be=!0,!0):!1}function Se(e,t,n){if(ye++,xe())return 0;let i=s.turn===`white`;if(s.halfmove>=100||ae())return 0;if(y(s.kings[+!i],!i))return F(1,e,t,n,!1);let a=j();if(a>=t)return t;a>e&&(e=a);let o=re().filter(e=>{if(e.promotion||e.to===s.enPassant&&v(e.from)===0)return!0;let t=i?6:0,n=c(e.to);for(let e=0;e<5;e++)if(s.pieces[t+e]&n)return!0;return!1}),l=N(o,0,Math.min(n,63));for(let i of l){let s=o[i],c=M(s.to);if(a+(c===-1?900:r[c])+200<e)continue;let l=O(s);P.push(b);let u=-Se(-t,-e,n+1);if(P.pop(),te(s,l),be)return 0;if(u>=t)return t;u>e&&(e=u)}return e}function F(e,t,n,r,i){if(ye++,xe())return 0;let a=s.turn===`white`;if(s.halfmove>=100||ae())return 0;let o=0;for(let e of P)if(e===b&&++o>=2)return 0;if(r>=64)return j();if(e<=0)return Se(t,n,r);let c=y(s.kings[+!a],!a),l=he(e,t,n,r);if(l.score!==null)return l.score;if(c)i=!1;else if(i&&e>=3&&ie(a)&&n<99e3){let t=e>4?3:2,i=ne();P.push(b);let a=-F(e-1-t,-n,-n+1,r+1,!1);if(P.pop(),k(i),be)return 0;if(a>=n)return n}let u=re();if(u.length===0)return c?-(1e5-r):0;let d=N(u,l.move,Math.min(r,63)),f=+!a,p=-1e6,m=0,h=2;for(let i=0;i<d.length;i++){let a=u[d[i]],o=me(a),l=M(a.to)!==-1||a.to===s.enPassant&&v(a.from)===0,g=O(a);P.push(b);let _;if(i===0)_=-F(e-1,-n,-t,r+1,!0);else{let o=0;e>=3&&i>=4&&!l&&!a.promotion&&!c&&(o=1),o>0?(_=-F(e-1-o,-t-1,-t,r+1,!0),!be&&_>t&&(_=-F(e-1,-n,-t,r+1,!0))):(_=-F(e-1,-t-1,-t,r+1,!0),!be&&_>t&&_<n&&(_=-F(e-1,-n,-t,r+1,!0)))}if(P.pop(),te(a,g),be)return 0;if(_>p&&(p=_,m=o),_>t&&(t=_,h=+(_>=n),!l&&!a.promotion&&r<64&&(ve[f][a.from][a.to]+=e*e,_e[r][0]!==o&&(_e[r][1]=_e[r][0],_e[r][0]=o))),t>=n)break}return ge(e,p,h,m,r),p}let Ce=re();if(Ce.length===0){let e=s.turn===`white`;return{move:null,score:y(s.kings[+!e],!e)?-1e5:0,nodes:ye,depth:0}}P.push(b);let we={from:Ce[0].from,to:Ce[0].to,...Ce[0].promotion?{promotion:Ce[0].promotion}:{}},Te=-1e6,Ee=0,De=Ce.map(e=>({...e}));for(let e=1;e<=i;e++){let t=-1e6,r=n,i=!1,a=we,o=Te;e>=4&&Ee>0&&(i=!0,t=Te-24,r=Te+24);for(let s=0;s<3;s++){let s=t,c=r,l=a,u=-1e6,d=N(De,me({from:a.from,to:a.to,promotion:a.promotion}),0),f=[];for(let n=0;n<d.length;n++){let i=De[d[n]],a=O(i);P.push(b);let o;if(n===0?o=-F(e-1,-r,-t,1,!0):(o=-F(e-1,-t-1,-t,1,!0),!be&&o>t&&o<r&&(o=-F(e-1,-r,-t,1,!0))),P.pop(),te(i,a),be)break;f.push(i),o>u&&(u=o,l=i),o>t&&(t=o)}if(be)break;for(let e of De)f.includes(e)||f.push(e);if(De=f,a=l,o=u,!i)break;if(u<=s||u>=c){t=-1e6,r=n,i=!1;continue}break}if(be||(we=a,Te=o,De=[we,...De.filter(e=>e!==we)],Ee=e,Te>99e3||Te<-99e3)||xe())break}return P.pop(),Ee===0?{move:null,score:j(),nodes:ye,depth:0}:{move:we,score:Te,nodes:ye,depth:Ee}}function pW(e){let t=`pieces`in e?e:aW(e);return{pieces:t.pieces.slice(),turn:t.turn,castling:t.castling,enPassant:t.enPassant,halfmove:t.halfmove,kings:[t.kings[0],t.kings[1]]}}function mW(e,t={}){return fW(pW(e),{depth:t.depth,maxNodes:t.maxNodes,timeMs:t.timeMs,signal:t.signal})}function hW(){let e=globalThis,t=e.navigator?.hardwareConcurrency;if(typeof t==`number`&&Number.isInteger(t)&&t>0)return Math.min(t,8);try{let t=e.process?.getBuiltinModule?.(`node:os`)?.availableParallelism?.();if(typeof t==`number`&&Number.isInteger(t)&&t>0)return Math.min(t,8)}catch{}return 4}async function gW(e,t={}){let n=Math.max(1,Math.floor(t.depth??3)),r=t.maxNodes===void 0?5e5:Math.max(1,Math.floor(t.maxNodes)),i=t.jobs??hW();if(!Number.isInteger(i)||i<1)throw RangeError(`jobs must be a positive integer`);if(t.signal?.aborted)throw t.signal.reason;let a=pW(e),o=sW(a);if(!o.length)return{...fW(a,{depth:n,maxNodes:r}),rootScores:[]};let s=Math.max(1,Math.min(i,o.length)),c=o.map(e=>{let t=pW(a);return lW(t,e),t}),l=Array(o.length),u=0,d=0,f=t.signal?{signal:t.signal}:{};await Promise.all(Array.from({length:s},async()=>{for(;;){let e=d++;if(e>=o.length)return;let i=await OU(fW,[c[e],{depth:Math.max(1,n-1),maxNodes:r,timeMs:t.timeMs}],f);u+=i.nodes,l[e]=-i.score}}));let p=0;for(let e=1;e<o.length;e++)(l[e]??-1/0)>(l[p]??-1/0)&&(p=e);let m=o[p];return{move:{from:m.from,to:m.to,...m.promotion?{promotion:m.promotion}:{}},score:l[p]??0,nodes:u,depth:n,rootScores:o.map((e,t)=>({move:{from:e.from,to:e.to,...e.promotion?{promotion:e.promotion}:{}},score:l[t]??0}))}}var _W={queen:`Q`,rook:`R`,bishop:`B`,knight:`N`},vW={Q:`queen`,R:`rook`,B:`bishop`,N:`knight`},yW={pawn:0,knight:1,bishop:2,rook:3,queen:4,king:5};function bW(e){let t={queen:0,rook:1,bishop:2,knight:3};return`K${e.slice().sort((e,n)=>t[e]-t[n]).map(e=>_W[e]).join(``)}K`}var xW=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`;function SW(e){let t=``;for(let n=0;n<e.length;n+=3){let r=e[n],i=n+1<e.length?e[n+1]:0,a=n+2<e.length?e[n+2]:0;t+=xW[r>>2]+xW[(r&3)<<4|i>>4],t+=n+1<e.length?xW[(i&15)<<2|a>>6]:`=`,t+=n+2<e.length?xW[a&63]:`=`}return t}function CW(e){if(e.length%4!=0)throw Error(`tablebase data is not base64: length is not a multiple of 4`);let t=Array(e.length);for(let n=0;n<e.length;n++){if(e[n]===`=`){t[n]=-1;continue}let r=xW.indexOf(e[n]);if(r===-1)throw Error(`tablebase data is not base64: ${e[n]}`);t[n]=r}let n=[];for(let e=0;e<t.length;e+=4){let[r,i,a,o]=[t[e],t[e+1],t[e+2],t[e+3]];if(r===-1||i===-1)throw Error(`tablebase data is not base64: padding inside a quantum`);n.push(r<<2|i>>4),a!==-1&&n.push((i&15)<<4|a>>2),o!==-1&&n.push((a&3)<<6|o)}return new Uint8Array(n)}function wW(e){let t=Array(256).fill(0);for(let n of e)t[n]++;let n=t.map((e,t)=>({count:e,symbol:t})).filter(e=>e.count>0),r=[1,n.length];if(n.length===0)return SW(new Uint8Array([1,0,0,0,0,0]));if(n.length===1){r.push(n[0].symbol,0);let t=new Uint8Array(r.length+4);return t.set(r,0),t[r.length]=e.length&255,t[r.length+1]=e.length>>8&255,t[r.length+2]=e.length>>16&255,t[r.length+3]=e.length>>24&255,SW(t)}let i=TW(n.map(e=>e.count)),a=n.map((e,t)=>({symbol:e.symbol,length:i[t]})).sort((e,t)=>e.symbol-t.symbol);for(let e of a)r.push(e.symbol);for(let e of a)r.push(e.length);let o=EW(a),s=new Map;for(let e=0;e<a.length;e++)s.set(a[e].symbol,o[e]);let c=0;for(let e of n)c+=e.count*s.get(e.symbol).length;let l=new Uint8Array(r.length+4+Math.ceil(c/8));l.set(r,0),l[r.length]=e.length&255,l[r.length+1]=e.length>>8&255,l[r.length+2]=e.length>>16&255,l[r.length+3]=e.length>>24&255;let u=0,d=r.length+4;for(let t of e){let e=s.get(t);for(let t=e.length-1;t>=0;t--)e.code>>t&1&&(l[d+(u>>3)]|=1<<7-(u&7)),u++}return SW(l)}function TW(e){let t=e.length;if(t===0)return[];let n=e.slice(),r=Array(t).fill(0),i=e.map((e,t)=>t),a=[];for(;i.length>1;){i.sort((e,t)=>n[e]-n[t]);let e=i.shift(),t=i.shift();a.push([e,t]),n[e]+=n[t],n[t]=-1,i.push(e)}for(let e=a.length-1;e>=0;e--){let[t,n]=a[e];r[n]=r[t]+1,r[t]++}if(r.some(e=>e>32))throw Error(`tablebase Huffman code too deep`);return r}function EW(e){let t=e.slice().sort((e,t)=>e.length-t.length||e.symbol-t.symbol),n=0,r=t[0].length,i=new Map;for(let e of t)n<<=e.length-r,i.set(e.symbol,{code:n,length:e.length}),n++,r=e.length;return e.map(e=>i.get(e.symbol))}function DW(e){let t=CW(e);if(t.length<2)throw Error(`tablebase data holds no header`);if(t[0]!==1)throw Error(`tablebase data version ${t[0]} is not 1`);let n=t[1];if(2+2*n>t.length)throw Error(`tablebase data ends inside its header`);let r=[],i=[];for(let e=0;e<n;e++)r.push(t[2+e]);for(let e=0;e<n;e++)i.push(t[2+n+e]);let a=2+2*n;if(n===0){if(a+4!==t.length)throw Error(`tablebase data trails its empty header`);return new Uint8Array}if(n===1){if(a+4!==t.length)throw Error(`tablebase data trails its single-symbol header`);let e=t[a]|t[a+1]<<8|t[a+2]<<16|t[a+3]<<24;return new Uint8Array(e).fill(r[0])}if(a+4>t.length)throw Error(`tablebase data ends before its count`);let o=t[a]|t[a+1]<<8|t[a+2]<<16|t[a+3]<<24,s=r.map((e,t)=>({symbol:e,length:i[t]})),c=EW(s),l={};for(let e=0;e<s.length;e++){let t=l;for(let n=c[e].length-1;n>=0;n--){let r=c[e].code>>n&1;n===0?r?t.one={symbol:s[e].symbol}:t.zero={symbol:s[e].symbol}:(r?t.one=t.one??{}:t.zero=t.zero??{},t=r?t.one:t.zero)}}let u=new Uint8Array(o),d=0,f=0,p=a+4,m=(t.length-p)*8;for(;d<o;){if(f>=m)throw Error(`tablebase data ends before its count`);let e=l;for(;;){let n=t[p+(f>>3)]>>7-(f&7)&1;if(f++,e=n?e.one:e.zero,!e)throw Error(`tablebase data walks off its Huffman tree`);if(e.symbol!==void 0)break}u[d++]=e.symbol}for(;f<m;f++)if(t[p+(f>>3)]>>7-(f&7)&1)throw Error(`tablebase data does not end in zero padding`);return u}function OW(e){let t=DW(e);if(t.length%2!=0)throw Error(`tablebase distances are not byte pairs`);let n=new Uint16Array(t.length/2);for(let e=0;e<n.length;e++)n[e]=t[2*e]|t[2*e+1]<<8;return n}function kW(e){if(e.version!==1)throw Error(`${e.id}: unknown tablebase version ${String(e.version)}`);if(e.id!==bW(e.white))throw Error(`${e.id}: id does not match its extras`);for(let t of e.white)if(!vW[_W[t]])throw Error(`${e.id}: not a tablebase piece: ${String(t)}`);let t=2+e.white.length,n=1;for(let e=0;e<t;e++)n*=64;if(n*=2,e.positions!==n)throw Error(`${e.id}: claims ${e.positions} positions, holds ${n}`);let r=DW(e.wdl);if(r.length!==n)throw Error(`${e.id}: WDL decodes to ${r.length} positions, needs ${n}`);let i=OW(e.dtm);if(i.length!==n)throw Error(`${e.id}: distances decode to ${i.length} positions, need ${n}`);let a={queen:0,rook:1,bishop:2,knight:3};return{id:e.id,extras:e.white.slice().sort((e,t)=>a[e]-a[t]).map(e=>yW[e]),positions:n,wdl:r,dtm:i}}function AW(e){if(`pieces`in e){let t=[];for(let n=0;n<12;n++){let r=e.pieces[n];for(;r;){let e=r&-r;t.push({kind:n%6,side:n<6?`white`:`black`,square:Math.log2(Number(e))}),r^=e}}return t}let t=[];return e.board.forEach((e,n)=>{e&&t.push({kind:yW[e.kind],side:e.side,square:n})}),t}function jW(e){if(`pieces`in e)return e.castling!==0;let t=e.castling;return t.whiteKingside||t.whiteQueenside||t.blackKingside||t.blackQueenside}function MW(e,t,n=0){if(!Number.isInteger(n)||n<0)throw RangeError(`halfmove must be a non-negative integer`);let r=AW(t),i=r.filter(e=>e.kind===5&&e.side===`white`),a=r.filter(e=>e.kind===5&&e.side===`black`);if(i.length!==1||a.length!==1||r.some(e=>e.kind===0)||r.some(e=>e.kind!==5&&e.side===`black`)||jW(t))return null;let o=r.filter(e=>e.kind!==5).sort((e,t)=>t.kind-e.kind).map(e=>e.kind);if(!o.length)return null;let s={4:`Q`,3:`R`,2:`B`,1:`N`},c=e[`K${o.map(e=>s[e]).join(``)}K`];if(!c)return null;let l=r.find(e=>e.kind===5&&e.side===`white`).square,u=r.find(e=>e.kind===5&&e.side===`black`).square,d=o.map((e,t)=>r.filter(t=>t.kind===e&&t.side===`white`).map(e=>e.square).sort((e,t)=>e-t)[NW(o,e,t)]),f=l;for(let e of d)f=f*64+e;f=f*64+u,f=f*2+ +(t.turn===`black`);let p=c.wdl[f];if(p===0)return null;let m=c.dtm[f],h=p===3?`win`:p===1?`loss`:`draw`;return h!==`draw`&&m>100-n&&(h=`draw`),{outcome:h,dtm:m}}function NW(e,t,n){let r=0;for(let i=0;i<n;i++)e[i]===t&&r++;return r}_e();var PW=class{constructor(e,t,n){if(this.width=e,this.height=t,e<1||t<1)throw Error(`a board needs positive dimensions`);if(n&&n.length!==e*t)throw Error(`board cell count does not match dimensions`);this.cells=n?[...n]:Array(e*t).fill(null)}index(e,t){if(!this.inside(e,t))throw Error(`cell (${e},${t}) is outside the board`);return tr(this.width,e,t)}inside(e,t){return er(this.width,this.height,e,t)}get(e,t){return this.cells[this.index(e,t)]}set(e,t,n){this.cells[this.index(e,t)]=n}move(e,t){let n=this.get(e.x,e.y);if(n===null)throw Error(`cannot move an empty cell`);return this.set(e.x,e.y,null),this.set(t.x,t.y,n),n}};function FW(){let e=Array(64).fill(null);for(let t=0;t<3;t++)for(let n=0;n<8;n++)(n+t)%2&&(e[t*8+n]={side:`black`,king:!1});for(let t=5;t<8;t++)for(let n=0;n<8;n++)(n+t)%2&&(e[t*8+n]={side:`red`,king:!1});return{board:e,turn:`red`,forcedFrom:null}}function IW(e){let t=e.forcedFrom===null?e.board.map((t,n)=>t?.side===e.turn?n:-1).filter(e=>e>=0):[e.forcedFrom],n=t.flatMap(t=>RW(e,t,!0));return n.length>0?n:e.forcedFrom===null?t.flatMap(t=>RW(e,t,!1)):[]}function LW(e,t){if(!IW(e).some(e=>e.from===t.from&&e.to===t.to&&e.captures.length===t.captures.length))throw Error(`illegal checkers move`);let n=e.board[t.from];if(!n)throw Error(`no checkers piece on the source cell`);e.board[t.from]=null;for(let n of t.captures)e.board[n]=null;let r=!n.king&&(n.side===`red`&&Math.floor(t.to/8)===0||n.side===`black`&&Math.floor(t.to/8)===7);e.board[t.to]={...n,king:n.king||r};let i={board:e.board,turn:e.turn,forcedFrom:t.captures.length>0?t.to:null};t.captures.length===0||RW(i,t.to,!0).length===0?(e.turn=e.turn===`red`?`black`:`red`,e.forcedFrom=null):e.forcedFrom=t.to}function RW(e,t,n){let r=e.board[t];if(!r)return[];let i=t%8,a=Math.floor(t/8),o=r.king?[-1,1]:r.side===`red`?[-1]:[1],s=[];for(let c of o)for(let o of[-1,1]){let l=i+o,u=a+c,d=i+o*2,f=a+c*2;if(n){if(d<0||f<0||d>=8||f>=8)continue;let n=u*8+l,i=f*8+d;e.board[n]?.side!==r.side&&e.board[n]&&!e.board[i]&&s.push({from:t,to:i,captures:[n]})}else l>=0&&u>=0&&l<8&&u<8&&!e.board[u*8+l]&&s.push({from:t,to:u*8+l,captures:[]})}return s}function zW(e=9){if(e<2||e>25)throw Error(`Go size must be between 2 and 25`);return{size:e,board:Array(e*e).fill(null),turn:`black`,ko:null,passes:0}}function BW(e,t,n){let r=WW(e,t,n);if(e.board[r]||e.ko===r)throw Error(`Go cell is occupied or forbidden by ko`);let i=[...e.board];i[r]=e.turn;let a=e.turn===`black`?`white`:`black`,o=0,s=null;for(let t of GW(e.size,r)){if(i[t]!==a||qW(i,e.size,t)!==0)continue;let n=KW(i,e.size,t);n.length===1&&(s=n[0]);for(let e of n)i[e]=null;o+=n.length}if(qW(i,e.size,r)===0)throw Error(`suicide is not a legal Go move`);e.ko=o===1&&qW(i,e.size,r)===1?s:null,e.board=i,e.turn=a,e.passes=0}function VW(e){e.turn=e.turn===`black`?`white`:`black`,e.ko=null,e.passes++}function HW(e){return e.passes>=2?`finished`:`ongoing`}function UW(e){let t={black:0,white:0},n=new Set;for(let r=0;r<e.board.length;r++){let i=e.board[r];if(i)t[i]++;else if(!n.has(r)){let i=KW(e.board,e.size,r),a=new Set;for(let t of i)for(let n of GW(e.size,t))e.board[n]&&a.add(e.board[n]);for(let e of i)n.add(e);a.size===1&&(t[[...a][0]]+=i.length)}}return t}function WW(e,t,n){if(t<0||n<0||t>=e.size||n>=e.size)throw Error(`Go cell is outside the board`);return n*e.size+t}function GW(e,t){let n=t%e,r=Math.floor(t/e),i=[];return n>0&&i.push(t-1),n<e-1&&i.push(t+1),r>0&&i.push(t-e),r<e-1&&i.push(t+e),i}function KW(e,t,n){let r=e[n],i=[],a=[n],o=new Set;for(;a.length;){let n=a.pop();if(!(o.has(n)||e[n]!==r)){o.add(n),i.push(n);for(let e of GW(t,n))a.push(e)}}return i}function qW(e,t,n){let r=KW(e,t,n),i=new Set;for(let n of r)for(let r of GW(t,n))e[r]===null&&i.add(r);return i.size}function JW(){let e=Array(24).fill(0);return e[0]=2,e[11]=5,e[16]=3,e[18]=5,e[23]=-2,e[12]=-5,e[7]=-3,e[5]=-5,{points:e,bar:{white:0,black:0},off:{white:0,black:0},turn:`white`}}function YW(){let e=lG(2,6);return e[0]===e[1]?[...e,...e]:e}function XW(e,t){let n=e.turn===`white`?1:-1,r=n===1?[18,23]:[0,5],i=e=>n===1?24-e:e+1,a=!0,o=1/0;for(let t=0;t<24;t++)e.points[t]*n<=0||((t<r[0]||t>r[1])&&(a=!1),o=Math.min(o,i(t)));let s=(e,t)=>{if(!a)return!1;let n=i(e);return t===n||t>n&&n===o},c=[];for(let r of t){if(e.bar[e.turn]>0){let t=e.turn===`white`?r-1:24-r;QW(e,t,n)&&c.push({from:`bar`,to:t,die:r});continue}for(let t=0;t<24;t++)if(e.points[t]*n>0){let i=t+r*n;i<0||i>=24?s(t,r)&&c.push({from:t,to:`off`,die:r}):QW(e,i,n)&&c.push({from:t,to:i,die:r})}}return c}function ZW(e,t){if(!XW(e,[t.die]).some(e=>e.from===t.from&&e.to===t.to))throw Error(`illegal backgammon move`);let n=e.turn===`white`?1:-1;if(t.from===`bar`?e.bar[e.turn]--:e.points[t.from]-=n,t.to===`off`)e.off[e.turn]++;else{if(e.points[t.to]*n<0){let n=e.turn===`white`?`black`:`white`;e.points[t.to]=0,e.bar[n]++}e.points[t.to]+=n}}function QW(e,t,n){return e.points[t]*n>=-1}function $W(e=0){let t=[`clubs`,`diamonds`,`hearts`,`spades`],n=[];for(let e of t)for(let t=1;t<=13;t++)n.push({suit:e,rank:t});return n.concat(Array(e).fill(null).map(()=>({suit:`spades`,rank:1})))}function eG(e){return oe(e)}function tG(e,t,n){if(t<0||n<0||e.length<t*n)throw Error(`not enough cards to deal`);return Array.from({length:t},()=>e.splice(0,n))}function nG(e,t){if(e.length===0)throw Error(`a trick needs at least one play`);let n=e[0].card.suit,r=e=>e.rank===1?14:e.rank;return(t&&e.some(e=>e.card.suit===t)?e.filter(e=>e.card.suit===t):e.filter(e=>e.card.suit===n)).reduce((e,t)=>r(t.card)>r(e.card)?t:e).owner}function rG(e){let t=$W();return e===void 0?eG(t):E(e,()=>eG(t)),{stock:t,waste:[],tableau:Array.from({length:7},(e,n)=>({down:t.splice(0,6-n),up:t.splice(0,1)})),foundations:[[],[],[],[]]}}function iG(e){e.stock.length===0&&(e.stock=e.waste.reverse(),e.waste=[]);let t=e.stock.pop()??null;return t&&e.waste.push(t),t}function aG(e,t,n,r=1){let i=e.tableau[t],a=e.tableau[n],o=i?.up.slice(-r);if(!i||!a||!o?.length||(a.up.length===0?o[0].rank!==13:!cG(o[0],a.up.at(-1))))throw Error(`illegal solitaire tableau move`);i.up.splice(-r,r),a.up.push(...o),i.down.length&&i.up.length===0&&i.up.push(i.down.pop())}function oG(e,t){let n=t===`waste`?e.waste.at(-1):e.tableau[t].up.at(-1);if(!n)throw Error(`no solitaire card to move`);let r=e.foundations.find(e=>e[0]?.suit===n.suit||e.length===0);if(!r||n.rank!==r.length+1)throw Error(`card cannot move to its foundation`);if(t===`waste`)e.waste.pop();else{let n=e.tableau[t];n.up.pop(),n.down.length&&n.up.length===0&&n.up.push(n.down.pop())}r.push(n)}function sG(e){return e.foundations.every(e=>e.length===13)}function cG(e,t){let n=e.suit===`diamonds`||e.suit===`hearts`,r=t.suit===`diamonds`||t.suit===`hearts`;return e.rank===t.rank-1&&n!==r}function lG(e,t){if(!Number.isInteger(e)||e<0||!Number.isInteger(t)||t<1)throw Error(`dice need a non-negative count and positive sides`);return Array.from({length:e},()=>ne(1,t))}function uG(e){let t=/^(\d+)d(\d+)([+-]\d+)?$/i.exec(e.trim());if(!t)throw Error(`bad dice expression: "${e}"`);return lG(Number(t[1]),Number(t[2])).reduce((e,t)=>e+t,Number(t[3]??0))}var dG=class{constructor(e,t){this.kept=new Set,this.count=e,this.sides=t,this.values=lG(e,t)}reRoll(){for(let e=0;e<this.values.length;e++)this.kept.has(e)||(this.values[e]=ne(1,this.sides))}keep(e){if(e<0||e>=this.count)throw Error(`die index is outside the cup`);this.kept.add(e)}clearKept(){this.kept.clear()}};function fG(e,t){if(e.length!==5||e.some(e=>e<1||e>6))throw Error(`a score sheet needs five d6 values`);let n=new Map;for(let t of e)n.set(t,(n.get(t)??0)+1);let r=e.reduce((e,t)=>e+t,0);if(t===`chance`)return r;if(t===`yahtzee`)return n.size===1?50:0;if(t===`fullHouse`)return[...n.values()].sort().join(`,`)===`2,3`?25:0;if(t===`threeKind`)return[...n.values()].some(e=>e>=3)?r:0;if(t===`fourKind`)return[...n.values()].some(e=>e>=4)?r:0;if(t===`smallStraight`||t===`largeStraight`){let e=[`1234`,`2345`,`3456`],r=[`12345`,`23456`],i=[...n.keys()].sort().join(``);return(t===`smallStraight`?e:r).some(e=>i.includes(e))?t===`smallStraight`?30:40:0}let i=[`ones`,`twos`,`threes`,`fours`,`fives`,`sixes`].indexOf(t)+1;return i>0?(n.get(i)??0)*i:0}function pG(e,t,n=`hex`){if(e<1||t<1)throw Error(`a tactical map needs positive dimensions`);return{width:e,height:t,shape:n,cells:Array.from({length:e*t},()=>({passable:!0,cover:0})),units:[],turn:``,round:1}}function mG(e,t,n){return wG(e,t,n)&&!CG(e,t,n)}function hG(e,t){if(!mG(e,t.x,t.y))throw Error(`tactical unit cannot be placed there`);e.units.push({...t,maxActions:t.maxActions??t.actions}),e.turn||=t.owner}function gG(e,t){let n=SG(e,t);if(n.owner!==e.turn||n.actions<=0)return[];let r=OG(e,n,DG(e,n)),i=[];for(let a=0;a<e.height;a++)for(let o=0;o<e.width;o++){if(o===n.x&&a===n.y||!e.cells[a*e.width+o].passable||CG(e,o,a))continue;let s=kG(e,n,o,a,n.actions,r);s!==null&&i.push({unit:t,x:o,y:a,cost:s})}return i}function _G(e,t){let n=gG(e,t.unit).find(e=>e.x===t.x&&e.y===t.y);if(!n)throw Error(`illegal tactical move`);let r=SG(e,t.unit);r.x=t.x,r.y=t.y,r.actions-=n.cost}function vG(e,t){let n=SG(e,t);if(n.owner!==e.turn||n.actions<=0)throw Error(`only an active unit can enter overwatch`);n.actions=0,n.overwatch=!0}function yG(e,t,n){let r=SG(e,t),i=[];for(let t of[...e.units]){if(!t.overwatch||t.owner===r.owner||EG(e,t,r)>3)continue;let a=e.cells[r.y*e.width+r.x].cover??0,o=Math.max(0,n-a);if(r.hp=Math.max(0,r.hp-o),t.overwatch=!1,i.push({attacker:t.id,defender:r.id,damage:o,cover:a,killed:r.hp===0}),r.hp===0){e.units=e.units.filter(e=>e!==r);break}}return i}function bG(e,t,n,r){let i=SG(e,t),a=SG(e,n);if(i.owner!==e.turn||i.owner===a.owner)throw Error(`invalid tactical attack`);if(EG(e,i,a)>3)throw Error(`tactical target is out of range`);let o=e.cells[a.y*e.width+a.x].cover??0,s=Math.max(0,r-o);a.hp=Math.max(0,a.hp-s);let c=a.hp===0;return c&&(e.units=e.units.filter(e=>e!==a)),{attacker:t,defender:n,damage:s,cover:o,killed:c}}function xG(e){let t=[...new Set(e.units.map(e=>e.owner))];if(t.length===0)return;let n=t.indexOf(e.turn)+1;n>=t.length&&e.round++,e.turn=t[n%t.length];for(let t of e.units)t.owner===e.turn&&(t.actions=t.maxActions??t.actions,t.overwatch=!1)}function SG(e,t){let n=e.units.find(e=>e.id===t);if(!n)throw Error(`unknown tactical unit "${t}"`);return n}function CG(e,t,n){return e.units.some(e=>e.x===t&&e.y===n)}function wG(e,t,n){return t>=0&&n>=0&&t<e.width&&n<e.height}function TG(e,t,n){return e.shape===`hex`?qn(t,n):[{x:t-1,y:n},{x:t+1,y:n},{x:t,y:n-1},{x:t,y:n+1}]}function EG(e,t,n){return e.shape===`hex`?Jn(t,n):Math.abs(t.x-n.x)+Math.abs(t.y-n.y)}function DG(e,t){return new Set(e.units.filter(n=>n.owner!==t.owner&&TG(e,t.x,t.y).some(e=>e.x===n.x&&e.y===n.y)).map(e=>e.id))}function OG(e,t,n){let r=new Set;for(let i of e.units)if(!(i.owner===t.owner||n.has(i.id)))for(let t of TG(e,i.x,i.y))r.add(`${t.x},${t.y}`);return r}function kG(e,t,n,r,i,a){let o=[{x:t.x,y:t.y,distance:0}],s=0,c=new Set([`${t.x},${t.y}`]);for(;s<o.length;){let t=o[s++];if(t.x===n&&t.y===r)return t.distance;if(!(t.distance>=i||t.distance>0&&a.has(`${t.x},${t.y}`)))for(let i of TG(e,t.x,t.y)){let a=`${i.x},${i.y}`;wG(e,i.x,i.y)&&!c.has(a)&&e.cells[i.y*e.width+i.x].passable&&(!CG(e,i.x,i.y)||i.x===n&&i.y===r)&&(c.add(a),o.push({x:i.x,y:i.y,distance:t.distance+1}))}}return null}var AG=class{constructor(e,t){if(this.visible=new Map,this.explored=new Map,this.shared=new Map,e<1||t<1)throw Error(`fog needs positive dimensions`);this.width=e,this.height=t}share(e){let t=[...new Set(e)].filter(e=>!!e);if(t.length===0)return;let n=new Set(t);for(let e of t)for(let t of this.shared.get(e)??[])n.add(t);for(let e of n)this.shared.set(e,n)}sync(e,t,n){if(!e)throw Error(`fog needs a faction id`);let r=new Set;for(let e of t)for(let t of n(e))this.inside(t.x,t.y)&&r.add(this.index(t.x,t.y));this.visible.set(e,r);let i=this.explored.get(e)??new Set;for(let e of r)i.add(e);this.explored.set(e,i)}reveal(e,t){if(!e)throw Error(`fog needs a faction id`);let n=this.explored.get(e)??new Set;for(let e of t)this.inside(e.x,e.y)&&n.add(this.index(e.x,e.y));this.explored.set(e,n)}isVisible(e,t,n){return this.seenBy(this.visible,e,this.index(t,n))}sees(e){return(t,n)=>this.isVisible(e,t,n)}isExplored(e,t,n){return this.seenBy(this.explored,e,this.index(t,n))}visibleCells(e){return this.cellsSeenBy(this.visible,e)}exploredCells(e){return this.cellsSeenBy(this.explored,e)}seenBy(e,t,n){let r=this.shared.get(t);if(!r)return e.get(t)?.has(n)??!1;for(let t of r)if(e.get(t)?.has(n))return!0;return!1}cellsSeenBy(e,t){let n=this.shared.get(t);if(!n)return[...e.get(t)??[]];let r=new Set;for(let t of n)for(let n of e.get(t)??[])r.add(n);return[...r].sort((e,t)=>e-t)}inside(e,t){return er(this.width,this.height,e,t)}index(e,t){return this.inside(e,t)?tr(this.width,e,t):-1}};function jG(e){return{currency:e,pool:[]}}function MG(e,t,n,r){return e.currency<r||!mG(t,n.x,n.y)?!1:(hG(t,n),e.currency-=r,!0)}function NG(e,t,n,r,i){let a=e.pool.findIndex(e=>e.id===n);return a===-1||!mG(t,r,i)?!1:(hG(t,{...e.pool[a],x:r,y:i}),e.pool.splice(a,1),!0)}function PG(e,t,n){let r=t.units.findIndex(e=>e.id===n);if(r===-1)return!1;let{x:i,y:a,...o}=t.units[r];return e.pool.push(o),t.units.splice(r,1),!0}function FG(e,t,n){return e.units.filter(e=>e.owner===t).length*(n.incomePerUnit-n.upkeepPerUnit)}function IG(e,t,n,r){return e.currency+=FG(t,n,r),e.currency}_e();function LG(e,t,n,r){if(e<1||t<1)throw Error(`a skirmish map needs positive dimensions`);let i=r??Object.keys(n)[0];if(!i||!n[i])throw Error(`a skirmish map needs at least one terrain kind`);return{width:e,height:t,terrainTable:n,cells:Array.from({length:e*t},()=>({terrain:i})),units:[],turn:``,round:1}}function RG(e,t,n,r,i=!1){if(!JG(e,t,n))throw Error(`cell is outside the skirmish map`);if(!e.terrainTable[r])throw Error(`unknown skirmish terrain "${r}"`);e.cells[n*e.width+t]=i?{terrain:r,village:!0}:{terrain:r}}function zG(e,t,n){return JG(e,t,n)&&ZG(e,t,n)<1/0&&!YG(e,t,n)}function BG(e,t){if(!zG(e,t.x,t.y))throw Error(`skirmish unit cannot be placed there`);e.units.push({...t,remainingMoves:t.moves}),e.turn||=t.owner}function VG(e,t){let n=qG(e,t),r=n.remainingMoves??n.moves;if(n.owner!==e.turn||r<=0)return[];let i=new Set(e.units.filter(e=>e.id!==n.id).map(e=>`${e.x},${e.y}`)),a=QG(e,n,r,i),o=[];for(let s=0;s<e.height;s++)for(let c=0;c<e.width;c++){if(c===n.x&&s===n.y||ZG(e,c,s)===1/0||i.has(`${c},${s}`))continue;let l=a.get(`${c},${s}`);l!==void 0&&l<=r&&o.push({unit:t,x:c,y:s,cost:l})}return o}function HG(e,t){let n=VG(e,t.unit).find(e=>e.x===t.x&&e.y===t.y);if(!n)throw Error(`illegal skirmish move`);let r=qG(e,t.unit);r.x=t.x,r.y=t.y,r.remainingMoves=(r.remainingMoves??r.moves)-n.cost;let i=e.cells[t.y*e.width+t.x];i.village&&(i.owner=r.owner)}function UG(e,t,n){let r=qG(e,t),i=qG(e,n);if(r.owner!==e.turn||r.owner===i.owner)throw Error(`invalid skirmish attack`);if(Jn(r,i)!==1)throw Error(`skirmish combat is adjacency-only`);let a=[WG(e,r,i)];return i.hp>0&&a.push(WG(e,i,r)),e.units=e.units.filter(e=>e.hp>0),{strikes:a}}function WG(e,t,n){let r=XG(e,n.x,n.y).defense,i=A(Math.max(0,Math.min(1,t.hitChance*(1-r)))),a=i?Math.min(t.attack,n.hp):0;return n.hp-=a,{attacker:t.id,defender:n.id,hit:i,damage:a,killed:n.hp<=0}}function GG(e,t,n,r){return n+e.cells.filter(e=>e.village&&e.owner===t).length*r}function KG(e,t=0){let n=[...new Set(e.units.map(e=>e.owner))];if(n.length===0)return;let r=n.indexOf(e.turn)+1;r>=n.length&&e.round++,e.turn=n[r%n.length];for(let n of e.units){if(n.owner!==e.turn)continue;n.remainingMoves=n.moves;let r=e.cells[n.y*e.width+n.x];r.village&&r.owner===n.owner&&t>0&&(n.hp=Math.min(n.maxHp,n.hp+t))}}function qG(e,t){let n=e.units.find(e=>e.id===t);if(!n)throw Error(`unknown skirmish unit "${t}"`);return n}function JG(e,t,n){return er(e.width,e.height,t,n)}function YG(e,t,n){return e.units.some(e=>e.x===t&&e.y===n)}function XG(e,t,n){return e.terrainTable[e.cells[n*e.width+t].terrain]}function ZG(e,t,n){return XG(e,t,n).moveCost}function QG(e,t,n,r){let i=[],a=(e,t)=>{[i[e],i[t]]=[i[t],i[e]]},o=e=>{i.push(e);let t=i.length-1;for(;t>0;){let e=t-1>>1;if(i[e].cost<=i[t].cost)break;a(t,e),t=e}},s=()=>{if(i.length===0)return;let e=i[0],t=i.pop();if(i.length>0){i[0]=t;let e=0;for(;;){let t=e*2+1,n=t+1,r=e;if(t<i.length&&i[t].cost<i[r].cost&&(r=t),n<i.length&&i[n].cost<i[r].cost&&(r=n),r===e)break;a(e,r),e=r}}return e},c=new Map([[`${t.x},${t.y}`,0]]);for(o({x:t.x,y:t.y,cost:0});;){let t=s();if(t===void 0)break;let i=`${t.x},${t.y}`;if(!(t.cost>(c.get(i)??1/0)))for(let i of qn(t.x,t.y)){if(!JG(e,i.x,i.y))continue;let a=ZG(e,i.x,i.y);if(a===1/0||r.has(`${i.x},${i.y}`))continue;let s=t.cost+a;if(s>n)continue;let l=`${i.x},${i.y}`;s<(c.get(l)??1/0)&&(c.set(l,s),o({x:i.x,y:i.y,cost:s}))}}return c}var $G=l({BoardGrid:()=>PW,DiceCup:()=>dG,FactionFog:()=>AG,addSkirmishUnit:()=>BG,addTacticalUnit:()=>hG,applyBackgammonMove:()=>ZW,applyCheckersMove:()=>LW,applyMove:()=>_U,applyUpkeep:()=>IG,armyIncome:()=>FG,backgammonMoves:()=>XW,bankUnit:()=>PG,bitboardFromChess:()=>aW,bitboardMoves:()=>sW,canPlaceSkirmishUnit:()=>zG,canPlaceTacticalUnit:()=>mG,checkersMoves:()=>IW,chessGame:()=>IU,chooseMove:()=>jU,cloneChess:()=>aU,createDeck:()=>$W,deal:()=>tG,dealSolitaire:()=>rG,drawSolitaire:()=>iG,endSkirmishTurn:()=>KG,endTacticalTurn:()=>xG,gameResult:()=>vU,goResult:()=>HW,goScore:()=>UW,huffDecode:()=>DW,huffEncode:()=>wW,inCheck:()=>fU,legalMoves:()=>gU,loadTablebaseEnding:()=>kW,makeMove:()=>lW,moveSkirmishUnit:()=>HG,moveSolitaireTableau:()=>aG,moveSolitaireToFoundation:()=>oG,moveTacticalUnit:()=>_G,parseFen:()=>$H,parseUciMove:()=>UU,passGo:()=>VW,perft:()=>dW,playGo:()=>BW,positionKey:()=>QH,probeBook:()=>VU,probeTablebase:()=>MW,recall:()=>NG,recruit:()=>MG,rollBackgammonDice:()=>YW,rollDice:()=>lG,rollExpression:()=>uG,scoreDice:()=>fG,search:()=>MU,searchAsync:()=>NU,searchTourney:()=>mW,searchTourneyAsync:()=>gW,setSkirmishTerrain:()=>RG,setTacticalOverwatch:()=>vG,shuffleDeck:()=>eG,skirmishAttack:()=>UG,skirmishIncome:()=>GG,skirmishMoves:()=>VG,solitaireWon:()=>sG,sq:()=>XH,squareName:()=>ZH,startingArmy:()=>jG,startingBackgammon:()=>JW,startingBitboard:()=>oW,startingCheckers:()=>FW,startingChess:()=>iU,startingGo:()=>zW,startingSkirmish:()=>LG,startingTactics:()=>pG,tablebaseId:()=>bW,tacticalAttack:()=>bG,tacticalMoves:()=>gG,tourneyThink:()=>fW,trickWinner:()=>nG,triggerTacticalOverwatch:()=>yG,unmakeMove:()=>uW});function eK(e){return new Audio(HM(e))}var tK=new p,nK=class{constructor(e,t={}){this.next=0,this.suspended_=!1;let n=Math.max(1,t.poolSize??4),r=t.create??eK;this.volume=t.volume??1,this.caption=t.caption,this.pool=Array.from({length:n},()=>r(e))}play(e=1,t=1){if(this.suspended_)return;let n=this.pool[this.next];this.next=(this.next+1)%this.pool.length,n.volume=this.volume*e,n.playbackRate=t,n.currentTime=0,Promise.resolve(n.play()).catch(()=>{}),this.caption&&tK.dispatch({text:this.caption})}stopAll(){for(let e of this.pool)e.pause(),e.currentTime=0}suspend(){this.suspended_=!0,this.stopAll()}resume(){this.suspended_=!1}get isSuspended(){return this.suspended_}},rK=class{constructor(e={}){this.current=null,this.fades=[],this.trackQueue=null,this.playlistFade=1,this.suspended_=!1,this.duckLevel_=1,this.volume=e.volume??1,this.create=e.create??eK}play(e,t=1){this.trackQueue=null,this.start(e,t,!0)}playTracks(e,t=1){if(e.length===0){this.stop(t);return}this.trackQueue=[...e],this.playlistFade=t,this.startNextTrack()}startNextTrack(){if(!this.trackQueue?.length)return;let e=this.trackQueue.shift();this.trackQueue.push(e),this.start(e,this.playlistFade,!1)}start(e,t,n){let r=this.create(e);r.loop=n,!n&&r.onended!==void 0&&(r.onended=()=>{this.current===r&&this.startNextTrack()});let i=this.current;if(this.current=r,t<=0){r.volume=this.volume*this.duckLevel_,Promise.resolve(r.play()).catch(()=>{}),i?.pause();return}r.volume=0,Promise.resolve(r.play()).catch(()=>{}),this.fades.push({audio:r,elapsed:0,duration:t,from:0,to:this.volume*this.duckLevel_,stopAtEnd:!1}),i&&this.fades.push({audio:i,elapsed:0,duration:t,from:i.volume,to:0,stopAtEnd:!0})}stop(e=1){this.trackQueue=null;let t=this.current;if(t){if(this.current=null,e<=0){t.pause();return}this.fades.push({audio:t,elapsed:0,duration:e,from:t.volume,to:0,stopAtEnd:!0})}}suspend(){this.suspended_=!0,this.current?.pause();for(let e of this.fades)e.audio.pause()}resume(){this.suspended_&&(this.suspended_=!1,this.current&&Promise.resolve(this.current.play()).catch(()=>{}))}duck(e=.5,t=.5){let n=Number.isFinite(e)?Math.max(0,Math.min(1,e)):1,r=this.duckLevel_;this.duckLevel_=n;for(let e of this.fades)e.to=r>0?e.to/r*n:this.volume*n;if(this.current){let e=this.volume*n;t<=0?this.current.volume=e:this.fades.push({audio:this.current,elapsed:0,duration:t,from:this.current.volume,to:e,stopAtEnd:!1})}}unduck(e=.5){this.duck(1,e)}get duckLevel(){return this.duckLevel_}get isSuspended(){return this.suspended_}update(e){if(!this.suspended_)for(let t of[...this.fades]){t.elapsed+=e;let n=Math.min(1,t.elapsed/t.duration);t.audio.volume=t.from+(t.to-t.from)*n,n>=1&&(this.fades.splice(this.fades.indexOf(t),1),t.stopAtEnd&&(t.audio.pause(),t.audio.currentTime=0))}}},iK=class{constructor(e){this.states=new Map,this.cues=new Map,this.currentTrack=null,this.music=e}define(e,t){this.states.set(e,t)}enter(e){let t=this.states.get(e);if(!t)throw Error(`Orchestrator: no state defined for "${e}"`);t.track!==this.currentTrack&&(this.music.play(t.track,t.fadeDuration),this.currentTrack=t.track)}on(e,t){this.cues.set(e,t)}trigger(e){this.cues.get(e)?.play()}suspend(){this.music.suspend();for(let e of this.cues.values())e.suspend()}resume(){this.music.resume();for(let e of this.cues.values())e.resume()}};function aK(e={}){let t=e.waveform??`square`,n=e.frequency??440,r=e.duration??.15,i=e.volume??.3,a=e.decay??8,o=e.sampleRate??22050,s=e.seed??1;if(!(r>0))throw Error(`tone duration must be positive`);if(t!==`noise`&&!(n>0))throw Error(`tone frequency must be positive`);if(!(o>0))throw Error(`tone sample rate must be positive`);let c=Math.max(1,Math.round(r*o)),l=new Float32Array(c);for(let e=0;e<c;e++){let r=e/o,u=a>0?Math.exp(-a*e/c):1,d=2*Math.PI*n*r;l[e]=i*u*sK(t,d,s,e)}return lK(l,o)}function oK(e={},t=e=>new Audio(e)){let n=t(aK(e));return Promise.resolve(n.play()).catch(()=>{}),n}function sK(e,t,n,r){switch(e){case`sine`:return Math.sin(t);case`square`:return Math.sin(t)>=0?1:-1;case`triangle`:{let e=t/(2*Math.PI),n=e-Math.floor(e);return 4*Math.abs(n-.5)-1}case`noise`:return cK(n,r)}}function cK(e,t){let n=Math.imul(e^t,2654435761)>>>0;return n=Math.imul(n^n>>>15,2246822519)>>>0,n=Math.imul(n^n>>>13,3266489917)>>>0,n^=n>>>16,(n>>>0)/4294967295*2-1}function lK(e,t){let n=e.length*2,r=new ArrayBuffer(44+n),i=new DataView(r);uK(i,0,`RIFF`),i.setUint32(4,36+n,!0),uK(i,8,`WAVE`),uK(i,12,`fmt `),i.setUint32(16,16,!0),i.setUint16(20,1,!0),i.setUint16(22,1,!0),i.setUint32(24,t,!0),i.setUint32(28,t*2,!0),i.setUint16(32,2,!0),i.setUint16(34,16,!0),uK(i,36,`data`),i.setUint32(40,n,!0);let a=44;for(let t of e){let e=Math.max(-1,Math.min(1,t));i.setInt16(a,Math.round(e*(e<0?32768:32767)),!0),a+=2}let o=``,s=new Uint8Array(r);for(let e of s)o+=String.fromCharCode(e);return`data:audio/wav;base64,${btoa(o)}`}function uK(e,t,n){for(let r=0;r<n.length;r++)e.setUint8(t+r,n.charCodeAt(r))}function dK(e,t){let[n,r]=e,i=n*4*mK[t]/r;if(!Number.isInteger(i)||i<1)throw Error(`a ${t} grid does not cut a ${n}/${r} bar into whole slots (it needs ${i})`);return i}function fK(e,t){return e/mK[t]}function pK(e){if(typeof e!=`object`||!e)throw Error(`a groove template must be an object`);let{name:t,timeSignature:n,ppq:r,tempoBpm:i,subdivision:a,offsets:o}=e;if(typeof t!=`string`||t.length===0)throw Error(`a groove template needs a non-empty name`);if(!Array.isArray(n)||n.length!==2)throw Error(`groove template "${t}": timeSignature must be [beats, beatValue]`);let[s,c]=n;if(!Number.isInteger(s)||s<1)throw Error(`groove template "${t}": time signature numerator must be a positive integer, got ${String(s)}`);if(!Number.isInteger(c)||c<1||c&c-1)throw Error(`groove template "${t}": time signature denominator must be a power of two, got ${String(c)}`);if(!Number.isInteger(r)||r<1)throw Error(`groove template "${t}": ppq must be a positive integer, got ${String(r)}`);if(!Number.isFinite(i)||i<=0)throw Error(`groove template "${t}": tempoBpm must be greater than 0, got ${String(i)}`);if(a!==`8n`&&a!==`16n`&&a!==`32n`)throw Error(`groove template "${t}": subdivision must be 8n, 16n or 32n, got ${String(a)}`);let l=fK(r,a);if(!Number.isInteger(l)||l<1)throw Error(`groove template "${t}": ${r} ppq does not cut into whole ${a} ticks (it needs ${String(l)})`);let u=dK(n,a);if(!Array.isArray(o)||o.length!==u)throw Error(`groove template "${t}": a ${a} grid in ${s}/${c} has ${u} slots, this carries ${Array.isArray(o)?o.length:String(o)}`);o.forEach((e,n)=>{if(typeof e!=`object`||!e)throw Error(`groove template "${t}": slot ${n} must be an object`);if(e.subdivisionIndex!==n)throw Error(`groove template "${t}": slots must run in order, slot ${n} carries ${String(e.subdivisionIndex)}`);if(!Number.isInteger(e.timeOffsetTicks))throw Error(`groove template "${t}": slot ${n} has a fractional timeOffsetTicks (${String(e.timeOffsetTicks)}); ticks are whole numbers`);if(!Number.isFinite(e.velocityFactor)||e.velocityFactor<0)throw Error(`groove template "${t}": slot ${n} has velocityFactor ${String(e.velocityFactor)}, which must be a finite number of at least 0`)})}var mK,hK=s((()=>{mK={"8n":2,"16n":4,"32n":8}}));function gK(e){let t=e.intensity;if(!Number.isFinite(t)||t<0||t>1)throw Error(`humanization intensity must be between 0 and 1, got ${String(e.intensity)}`);let n=e.timingVarianceMs??FK;if(!Number.isFinite(n)||n<0)throw Error(`timingVarianceMs must be a finite number of at least 0, got ${String(e.timingVarianceMs)}`);let r=e.velocityVariance??IK;if(!Number.isFinite(r)||r<0)throw Error(`velocityVariance must be a finite number of at least 0, got ${String(e.velocityVariance)}`);let i=e.style?LK[e.style]:RK,a=e.grooveTemplate??null;return a&&pK(a),{intensity:t,timingMs:n,velocityVariance:r,timingScale:i.timing,velocityScale:i.velocity,template:a,warn:e.onWarn??(e=>console.warn(e))}}function _K(e){let t=[];for(let n of e)n.type===`tempo`&&t.push({tick:n.tick,microsecondsPerQuarter:n.microsecondsPerQuarter});t.sort((e,t)=>e.tick-t.tick);let n=[{tick:0,microsecondsPerQuarter:5e5}];for(let e of t)e.tick===n[n.length-1].tick?n[n.length-1]=e:n.push(e);return n}function vK(e,t){let n=0,r=e.length-1,i=0;for(;n<=r;){let a=n+r>>1;e[a].tick<=t?(i=a,n=a+1):r=a-1}return 6e7/e[i].microsecondsPerQuarter}function yK(e,t,n){return e*t*n/6e4}function bK(e,t,n){return e*6e4/(t*n)}function xK(e){let t=null;return()=>{if(t!==null){let e=t;return t=null,e}let n=Math.sqrt(-2*Math.log(1-e.float())),r=2*Math.PI*e.float();return t=n*Math.sin(r),n*Math.cos(r)}}function SK(e){let t=new Uint8Array(256);for(let e=0;e<256;e++)t[e]=e;for(let n=255;n>0;n--){let r=e.int(n+1),i=t[n];t[n]=t[r],t[r]=i}let n=(e,t)=>e&1?t:-t;return e=>{let r=Math.floor(e),i=e-r,a=i*i*i*(i*(i*6-15)+10),o=n(t[r&255],i);return o+a*(n(t[r+1&255],i-1)-o)}}function CK(e){let t=new Map;for(let n of e.offsets)t.set(n.subdivisionIndex,{ms:bK(n.timeOffsetTicks,e.ppq,e.tempoBpm),factor:n.velocityFactor});return t}function wK(e){let t=new Uint8Array(e.length),n=new Map;for(let t=0;t<e.length;t++){let r=e[t];if(r.type!==`noteOn`||r.channel===MK)continue;let i=n.get(r.channel);i?i.push({index:t,note:r.note}):n.set(r.channel,[{index:t,note:r.note}])}for(let e of n.values())for(let n=1;n<e.length-1;n++)e[n].note>e[n-1].note&&e[n].note>e[n+1].note&&(t[e[n].index]=1);return t}function TK(e){return e.channel===MK?NK.includes(e.note):e.note<PK}function EK(e,t,n){let r=gK(t),i=new j(t.seed),a=xK(i),o=SK(i),s=e.ticksPerQuarter,c=_K(e.events),l=r.template?CK(r.template):null,u=r.template?fK(s,r.template.subdivision):0,d=r.template?dK(r.template.timeSignature,r.template.subdivision):0,f=n===`groove`?wK(e.events):null,p=[],m=new Map,h=!1;for(let t=0;t<e.events.length;t++){let i=e.events[t];if(i.type===`noteOff`){let e=m.get(zK(i)),t=e&&e.length>0?e.shift():0;p.push(t===0?{...i}:{...i,tick:i.tick+t});continue}if(i.type!==`noteOn`){p.push({...i});continue}let g=vK(c,i.tick);r.template&&!h&&Math.abs(g-r.template.tempoBpm)>AK&&(h=!0,r.warn(`groove template "${r.template.name}" is written at ${r.template.tempoBpm} BPM but this file is at ${g.toFixed(1)} BPM by tick ${i.tick}: its offsets are rescaled to keep the same timing in milliseconds`));let _=yK(r.timingMs*r.timingScale,s,g),v=a()*_+o(i.tick/s*DK)*_*OK;if(n===`groove`&&TK(i)){let e=yK(jK,s,g);v=Math.min(e,Math.max(-e,v))}let y;l&&(y=l.get(Math.floor(i.tick/u)%d));let b=Math.round(r.intensity*((y?yK(y.ms,s,g):0)+v));i.tick+b<0&&(b=-i.tick);let x=Math.round(i.velocity*(1+r.intensity*((y?y.factor:1)-1))+r.intensity*a()*r.velocityVariance*r.velocityScale);f&&f[t]===1&&(x=Math.round(x*(1+r.intensity*kK))),x=Math.min(127,Math.max(1,x));let S=zK(i),C=m.get(S);C?C.push(b):m.set(S,[b]),p.push({...i,tick:i.tick+b,velocity:x})}return p.sort((e,t)=>e.tick-t.tick),{ticksPerQuarter:s,events:p,loopStartTick:e.loopStartTick}}var DK,OK,kK,AK,jK,MK,NK,PK,FK,IK,LK,RK,zK,BK=s((()=>{_e(),hK(),DK=.25,OK=.5,kK=.15,AK=1,jK=5,MK=9,NK=[35,36],PK=48,FK=8,IK=10,LK={jazz:{timing:1.3,velocity:1.1},rock:{timing:.8,velocity:1.2},classical:{timing:.6,velocity:1.4},funk:{timing:1,velocity:1.3}},RK={timing:1,velocity:1},zK=e=>`${e.channel}:${e.note}`})),VK=l({LiteHumanizer:()=>HK}),HK,UK=s((()=>{BK(),HK=class{constructor(){this.tierName=`lite`,this.approximateSizeMb=.05}async initialize(){}async process(e,t){if(t.grooveTemplate)throw Error(`the lite tier applies no groove grid: ask HumanizerFactory for "groove" when a template is in play`);return EK(e,t,`lite`)}}})),WK=l({GrooveHumanizer:()=>GK}),GK,KK=s((()=>{BK(),GK=class{constructor(){this.tierName=`groove`,this.approximateSizeMb=.5}async initialize(){}async process(e,t){return EK(e,t,`groove`)}}})),qK=class e{static async create(t){let n=await e.load(t);return await n.initialize(),n}static async load(e){switch(e){case`lite`:return new(await(Promise.resolve().then(()=>(UK(),VK)))).LiteHumanizer;case`groove`:return new(await(Promise.resolve().then(()=>(KK(),WK)))).GrooveHumanizer;case`magenta`:throw Error(`the 'magenta' tier is not shipped: it needs @magenta/music and a PerformanceRNN checkpoint, and neither can be fetched from a file:// build`);default:throw Error(`unknown humanizer tier: ${String(e)}`)}}};async function JK(e,t){let{tier:n,...r}=t,i=n??(r.grooveTemplate?`groove`:`lite`);return(await qK.create(i)).process(e,r)}var YK=5e5,XK=111;function ZK(e){let t=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength),n=new DataView(t.buffer,t.byteOffset,t.byteLength),r=0,i=e=>{let n=``;for(let i=0;i<e;i++)n+=String.fromCharCode(t[r+i]);return r+=e,n},a=()=>{let e=n.getUint32(r,!1);return r+=4,e},o=()=>{let e=n.getUint16(r,!1);return r+=2,e},s=()=>{let e=0;for(;;){let n=t[r++];if(e=e<<7|n&127,!(n&128))return e}};if(i(4)!==`MThd`||a()!==6)throw Error(`invalid MIDI header chunk`);let c=o(),l=o(),u=o();if(c!==0&&c!==1)throw Error(`unsupported MIDI format ${c}`);if(u&32768)throw Error(`SMPTE-based MIDI timing is not supported`);let d=u,f=[],p=null;for(let e=0;e<l;e++){let e=i(4),n=a();if(e!==`MTrk`){r+=n;continue}let o=r+n,c=0,l=0;for(;r<o;){c+=s();let e=t[r];if(e<128?e=l:(r++,e<240&&(l=e)),e===255){let e=t[r++],n=s();if(e===81&&n===3){let e=t[r]<<16|t[r+1]<<8|t[r+2];f.push({tick:c,type:`tempo`,microsecondsPerQuarter:e})}r+=n}else if(e===240||e===247)r+=s();else{let n=e&240,i=e&15;if(n===128||n===144){let e=t[r++],a=t[r++],o=n===144&&a>0;f.push({tick:c,type:o?`noteOn`:`noteOff`,note:e,velocity:a,channel:i})}else if(n===176){let e=t[r++],n=t[r++];f.push({tick:c,type:`control`,channel:i,controller:e,value:n}),e===XK&&p===null&&(p=c)}else if(n===192){let e=t[r++];f.push({tick:c,type:`program`,channel:i,program:e})}else if(n===224){let e=t[r++],n=t[r++];f.push({tick:c,type:`pitchBend`,channel:i,value:(n<<7|e)-8192})}else if(n===160||n===208)r+=n===160?2:1;else throw Error(`unsupported MIDI status byte 0x${e.toString(16)}`)}}}return f.sort((e,t)=>e.tick-t.tick),{ticksPerQuarter:d,events:f,loopStartTick:p}}var QK=2;function $K(e){let t=[{tick:0,time:0,microsecondsPerQuarter:YK}];for(let n of e.events){if(n.type!==`tempo`)continue;let r=t[t.length-1];t.push({tick:n.tick,time:r.time+(n.tick-r.tick)*r.microsecondsPerQuarter/e.ticksPerQuarter/1e6,microsecondsPerQuarter:n.microsecondsPerQuarter})}return t}function eq(e,t,n){let r=e[0];for(let t of e)if(t.tick<=n)r=t;else break;return r.time+(n-r.tick)*r.microsecondsPerQuarter/t/1e6}function tq(e){return e.loopStartTick===null?null:eq($K(e),e.ticksPerQuarter,e.loopStartTick)}function nq(e){let t=$K(e),n=Array.from({length:16},()=>({program:0,bank:0,volume:100,expression:127,pan:64,bend:0})),r=e=>{let t=n[e]??n[0];return{program:t.program,bank:t.bank,gain:t.volume/127*(t.expression/127),pan:(t.pan-64)/64,...t.bend?{bend:t.bend}:{}}},i=[],a=new Map;for(let o of e.events){if(o.type===`tempo`)continue;if(o.type===`pitchBend`){(n[o.channel]??n[0]).bend=o.value/8192*QK;continue}if(o.type===`program`){(n[o.channel]??n[0]).program=o.program;continue}if(o.type===`control`){let e=n[o.channel]??n[0];o.controller===0?e.bank=o.value:o.controller===7?e.volume=o.value:o.controller===10?e.pan=o.value:o.controller===11&&(e.expression=o.value);continue}let s=eq(t,e.ticksPerQuarter,o.tick),c=`${o.channel}:${o.note}`;if(o.type===`noteOn`)a.set(c,{time:s,velocity:o.velocity,voice:r(o.channel)});else{let e=a.get(c);e&&(i.push({time:e.time,duration:Math.max(.01,s-e.time),note:o.note,velocity:e.velocity,channel:o.channel,...e.voice}),a.delete(c))}}for(let[e,t]of a){let[n,r]=e.split(`:`).map(Number);i.push({time:t.time,duration:.3,note:r,velocity:t.velocity,channel:n,...t.voice})}return i.sort((e,t)=>e.time-t.time)}function rq(e){return 440*2**((e-69)/12)}var iq=class e{constructor(e,t={}){this.elapsed=0,this.index=0,this.playing=!1,this.notes=nq(e),this.playFn=t.play??oK,this.waveform=t.waveform??`square`,this.volume=t.volume??.2}static async create(t,n={}){return new e(n.humanize?await JK(t,n.humanize):t,n)}play(){this.playing=this.index<this.notes.length}pause(){this.playing=!1}stop(){this.playing=!1,this.elapsed=0,this.index=0}update(e){if(this.playing){for(this.elapsed+=e;this.index<this.notes.length&&this.notes[this.index].time<=this.elapsed;){let e=this.notes[this.index];this.playFn({waveform:this.waveform,frequency:rq(e.note),duration:e.duration,volume:this.volume*(e.velocity/127)}),this.index++}this.index>=this.notes.length&&(this.playing=!1)}}get isPlaying(){return this.playing}get duration(){let e=this.notes.at(-1);return e?e.time+e.duration:0}},aq={keyRange:43,velRange:44,instrument:41,sampleId:53,rootKey:58,coarseTune:51,fineTune:52,sampleModes:54,attenuation:48,pan:17,attack:34,hold:35,decay:36,sustain:37,release:38};function oq(e){return 2**(e/1200)}function sq(e){return e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function cq(e,t){let n=``;for(let r=0;r<20;r++){let i=e[t+r];if(i===0)break;n+=String.fromCharCode(i)}return n}function lq(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=t=>String.fromCharCode(e[t],e[t+1],e[t+2],e[t+3]);if(n(0)!==`RIFF`||n(8)!==`sfbk`)throw Error(`not a SoundFont 2 file`);let r=new Map,i=new Map,a=(e,o)=>{let s=e;for(;s+8<=o;){let e=n(s),o=t.getUint32(s+4,!0);e===`LIST`?(i.set(n(s+8),{at:s,size:o}),a(s+12,s+8+o)):r.set(e,{at:s+8,size:o}),s+=8+o+(o&1)}};a(12,e.length);for(let e of[`phdr`,`pbag`,`pgen`,`inst`,`ibag`,`igen`,`shdr`,`smpl`])if(!r.has(e))throw Error(`SoundFont is missing "${e}"`);let o=(e,t,n)=>{let i=r.get(e),a=[];for(let e=i.at;e+t<=i.at+i.size;e+=t)a.push(n(e));return a},s=n=>o(n,4,n=>({oper:t.getUint16(n,!0),lo:e[n+2],hi:e[n+3],amount:t.getInt16(n+2,!0)})),c=e=>o(e,4,e=>t.getUint16(e,!0)),l=o(`phdr`,38,n=>({name:cq(e,n),preset:t.getUint16(n+20,!0),bank:t.getUint16(n+22,!0),bag:t.getUint16(n+24,!0)})),u=o(`inst`,22,n=>({name:cq(e,n),bag:t.getUint16(n+20,!0)})),d=o(`shdr`,46,n=>({name:cq(e,n),start:t.getUint32(n+20,!0),end:t.getUint32(n+24,!0),loopStart:t.getUint32(n+28,!0),loopEnd:t.getUint32(n+32,!0),rate:t.getUint32(n+36,!0),rootKey:e[n+40],correction:t.getInt8(n+41),link:t.getUint16(n+42,!0),type:t.getUint16(n+44,!0)})),f=r.get(`smpl`),p=new Int16Array(e.buffer.slice(e.byteOffset+f.at,e.byteOffset+f.at+f.size-(f.size&1))),m=i.get(`INFO`)??null;return{bytes:e,presets:l,presetBags:c(`pbag`),presetGens:s(`pgen`),instruments:u,instBags:c(`ibag`),instGens:s(`igen`),samples:d,smpl:p,info:m?e.slice(m.at,m.at+8+m.size+(m.size&1)):null}}function uq(e,t,n){return t.slice(e[n],e[n+1]??t.length)}function dq(e,t,n,r,i){let a=e[r].bag,o=e[r+1]?.bag??t.length-1,s=[],c=null;for(let e=a;e<o;e++){let r=uq(t,n,e),o=new Map;for(let e of r)o.set(e.oper,e);if(!o.has(i)){e===a&&(c=o);continue}s.push({gens:o,global:c})}return s}function fq(e,t){return e.gens.get(t)??e.global?.get(t)??null}function pq(e,t,n){return e.get(`${t}:${n}`)??e.get(`0:${n}`)??(t===128?e.get(`128:0`):void 0)??e.get(`0:0`)}function mq(e){let t=lq(sq(e)),n=new Map,r=new Map,i=e=>{if(n.has(e))return n.get(e);let i=t.samples[e];if(!i||i.end<=i.start||i.type&32768)return n.set(e,null),null;let a=new Float32Array(i.end-i.start);for(let e=0;e<a.length;e++)a[e]=t.smpl[i.start+e]/32768;let o={data:a,rate:i.rate||22050,loopStart:i.loopStart-i.start,loopEnd:i.loopEnd-i.start};return n.set(e,o),r.set(e,{rootKey:i.rootKey===255?60:i.rootKey,correction:i.correction}),o},a=new Map;for(let e=0;e<t.presets.length-1;e++)a.set(`${t.presets[e].bank}:${t.presets[e].preset}`,e);function o(e,n,o,s){let c=pq(a,e,n);if(c===void 0)return[];let l=[],u=(e,t,n)=>{let r=fq(e,t);return!r||n>=r.lo&&n<=r.hi};for(let e of dq(t.presets,t.presetBags,t.presetGens,c,aq.instrument)){if(!u(e,aq.keyRange,o)||!u(e,aq.velRange,s))continue;let n=fq(e,aq.instrument).amount;if(t.instruments[n+1])for(let a of dq(t.instruments,t.instBags,t.instGens,n,aq.sampleId)){if(!u(a,aq.keyRange,o)||!u(a,aq.velRange,s))continue;let t=fq(a,aq.sampleId).amount,n=i(t);if(!n)continue;let c=(t,n=0)=>(fq(a,t)?.amount??n)+(fq(e,t)?.amount??0),d=fq(a,aq.rootKey)?.amount,f=fq(a,aq.sampleModes)?.amount??0,p=r.get(t);l.push({sample:n,rootKey:d!==void 0&&d>=0?d:p.rootKey,cents:c(aq.coarseTune)*100+c(aq.fineTune)+p.correction,loop:(f&3)==1||(f&3)==3,gain:10**(-Math.max(0,c(aq.attenuation))/200),pan:Math.max(-1,Math.min(1,c(aq.pan)/500)),attack:oq(c(aq.attack,-12e3)),hold:oq(c(aq.hold,-12e3)),decay:oq(c(aq.decay,-12e3)),sustain:10**(-Math.max(0,c(aq.sustain))/200),release:oq(c(aq.release,-12e3))})}}return l}return{voices:o,hasPreset:(e,t)=>a.has(`${e}:${t}`)||a.has(`0:${t}`),presetCount:a.size}}function hq(e){let t=new Set,n=[];for(let r of e)for(let e of nq(r)){let r=e.channel===9?128:e.bank,i=`${r}:${e.program}`;t.has(i)||(t.add(i),n.push({bank:r,program:e.program}))}return n}function gq(e){return[e&255,e>>8&255]}function _q(e){return[e&255,e>>8&255,e>>16&255,e>>24&255]}function vq(e){let t=[...e].map(e=>e.charCodeAt(0)&255).slice(0,20);return[...t,...Array(20-t.length).fill(0)]}function yq(e){return[...e].map(e=>e.charCodeAt(0))}function bq(e,t){let n=new Uint8Array(8+t.length+(t.length&1));return n.set(yq(e),0),new DataView(n.buffer).setUint32(4,t.length,!0),n.set(t,8),n}function xq(e){let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function Sq(e,t){let n=xq([new Uint8Array(yq(e)),...t]);return xq([new Uint8Array(yq(`LIST`)),new Uint8Array(_q(n.length)),n])}function Cq(e,t){let n=lq(sq(e)),r=new Map;for(let e=0;e<n.presets.length-1;e++)r.set(`${n.presets[e].bank}:${n.presets[e].preset}`,e);let i=new Set,a=[];for(let{bank:e,program:n}of t){let t=pq(r,e,n);t!==void 0&&!i.has(t)&&(i.add(t),a.push(t))}a.sort((e,t)=>e-t);let o=e=>{let t=n.samples[e];return!!t&&t.end>t.start&&!(t.type&32768)},s=(e,t,n)=>e.map(e=>e.oper===t?{oper:t,lo:n.get(e.amount)&255,hi:n.get(e.amount)>>8&255,amount:n.get(e.amount)}:e),c=[],l=new Map;{let e=new Set;for(let t of a){let r=n.presets[t].bag,i=n.presets[t+1]?.bag??n.presetBags.length-1;for(let t=r;t<i;t++){let r=uq(n.presetBags,n.presetGens,t);if(!r.some(e=>e.oper===aq.instrument))continue;let i=r.find(e=>e.oper===aq.instrument).amount;n.instruments[i+1]&&(e.has(i)||(e.add(i),c.push(i)))}}}let u=new Map(c.map((e,t)=>[e,t]));for(let e of c){let t=n.instruments[e].bag,r=n.instruments[e+1]?.bag??n.instBags.length-1,i=[];for(let e=t;e<r;e++){let t=uq(n.instBags,n.instGens,e);if(!t.some(e=>e.oper===aq.sampleId))continue;let r=t.find(e=>e.oper===aq.sampleId).amount;o(r)&&i.push(t)}l.set(e,i)}let d=[];{let e=new Set,t=r=>{if(e.has(r)||!o(r))return;e.add(r),d.push(r);let i=n.samples[r].link;i!==r&&t(i)};for(let e of c)for(let n of l.get(e))t(n.find(e=>e.oper===aq.sampleId).amount)}let f=new Map(d.map((e,t)=>[e,t])),p=e=>[...gq(e.oper),e.lo,e.hi],m=e=>[...gq(e),...gq(0)],h=[],g=[],_=[];for(let e of a){let t=n.presets[e],r=h.length,i=t.bag,a=n.presets[e+1]?.bag??n.presetBags.length-1;for(let e=i;e<a;e++){let t=uq(n.presetBags,n.presetGens,e);(e===i&&!t.some(e=>e.oper===aq.instrument)||t.some(e=>e.oper===aq.instrument))&&(h.push(g.length),g.push(...s(t,aq.instrument,u)))}_.push({name:t.name,preset:t.preset,bank:t.bank,bag:r})}h.push(g.length);let v=[],y=[],b=[];for(let e of c){let t=v.length,r=l.get(e),i=n.instruments[e].bag,a=n.instruments[e+1]?.bag??n.instBags.length-1;for(let e=i;e<a;e++){let t=uq(n.instBags,n.instGens,e);e===i&&!t.some(e=>e.oper===aq.sampleId)&&(v.push(y.length),y.push(...t))}for(let e of r)v.push(y.length),y.push(...s(e,aq.sampleId,f));b.push({name:n.instruments[e].name,bag:t})}v.push(y.length);let x=[],S=[];for(let e of d){let t=n.samples[e],r=S.length/2;for(let e=t.start;e<t.end;e++){let t=n.smpl[e];S.push(t&255,t>>8&255)}let i=f.get(e);x.push({...t,start:r,end:r+(t.end-t.start),loopStart:r+(t.loopStart-t.start),loopEnd:r+(t.loopEnd-t.start),link:f.get(t.link)??i})}let C=e=>[...vq(e.name),...gq(e.preset),...gq(e.bank),...gq(e.bag),...Array(12).fill(0)],ee=n.presets[n.presets.length-1],w=bq(`phdr`,[..._.flatMap(C),...C({name:ee?.name??`EOS`,preset:0,bank:0,bag:h.length-1})]),T=bq(`pbag`,h.flatMap(m)),E=bq(`pgen`,g.flatMap(p)),D=bq(`pmod`,Array(10).fill(0)),O=e=>[...vq(e.name),...gq(e.bag)],te=n.instruments[n.instruments.length-1],ne=bq(`inst`,[...b.flatMap(O),...O({name:te?.name??`EOS`,bag:v.length-1})]),k=bq(`ibag`,v.flatMap(m)),A=bq(`igen`,y.flatMap(p)),re=bq(`imod`,Array(10).fill(0)),ie=e=>[...vq(e.name),..._q(e.start),..._q(e.end),..._q(e.loopStart),..._q(e.loopEnd),..._q(e.rate),e.rootKey,e.correction&255,...gq(e.link),...gq(e.type)],ae={name:``,start:0,end:0,loopStart:0,loopEnd:0,rate:0,rootKey:0,correction:0,link:0,type:0},oe=bq(`shdr`,[...x.flatMap(ie),...ie(ae)]),se=Sq(`sdta`,[bq(`smpl`,S)]),j=Sq(`pdta`,[w,T,D,E,ne,k,re,A,oe]),ce=xq([new Uint8Array(yq(`sfbk`)),...n.info?[n.info]:[],se,j]);return xq([new Uint8Array(yq(`RIFF`)),new Uint8Array(_q(ce.length)),ce]).buffer}var wq=22050,Tq=.35,Eq=480;function Dq(e,t={}){return jq(kq(e,t))}async function Oq(e,t={}){return OU(jq,[kq(ZK(e),{soundfont:t.soundFontBytes?mq(t.soundFontBytes):null,sampleRate:t.sampleRate,gain:t.gain,maxDuration:t.maxDuration})])}function kq(e,t){let n=t.sampleRate??wq,r=t.gain??Tq,i=t.maxDuration??Eq;if(!(n>0))throw Error(`render sample rate must be positive`);if(!(r>=0))throw Error(`render gain must not be negative`);if(!(i>0))throw Error(`render max duration must be positive`);let a=nq(e).filter(e=>e.time<i);if(a.length===0)throw Error(`MIDI file has no notes`);let o=t.soundfont??null,s=new Map;return{notes:a.map(e=>({...e,frequency:rq(e.note),voices:o?Aq(o,s,e):void 0})),loopStart:tq(e),sampleRate:n,gain:r,maxDuration:i}}function Aq(e,t,n){let r=n.channel===9?128:n.bank,i=`${r}:${n.program}:${n.note}:${n.velocity>>3}`,a=t.get(i);return a||(a=e.voices(r,n.program,n.note,n.velocity),t.set(i,a)),a}function jq(e){let{sampleRate:t,gain:n,maxDuration:r}=e,i=e.notes,a=i.reduce((e,t)=>Math.max(e,t.time+t.duration),0),o=Math.min(r,a+1.5),s=Math.max(1,Math.ceil(o*t)),c=new Float32Array(s),l=new Float32Array(s),u=Math.min(e.loopStart??0,Math.max(0,o-.1));function d(e){let t=(Math.max(-1,Math.min(1,e))+1)*Math.PI/4;return[Math.cos(t),Math.sin(t)]}function f(e,t,n,r,i,a,o,s){let c=i.sample.data;if(c.length===0)return;let l=2**(((r.note-i.rootKey)*100+i.cents+(r.bend??0)*100)/1200)*i.sample.rate/n;if(!(l>0))return;let u=r.time+r.duration,f=Math.max(.002,i.attack),p=f+i.hold+Math.min(i.decay,30),m=Math.max(.03,Math.min(i.release,4)),h=c.length/i.sample.rate,g=r.channel===9?Math.max(u,r.time+Math.min(2,h)):Math.max(u,r.time+f),_=g-r.time,v=a*i.gain,y=v*i.sustain,[b,x]=d(r.pan+i.pan),S=i.loop&&i.sample.loopEnd>i.sample.loopStart,C=i.sample.loopEnd-i.sample.loopStart,ee=Math.min(s,o+Math.ceil((g+m+.02-r.time)*n)),w=0;for(let a=o;a<ee;a++){let o=a/n-r.time,s;s=o<f?o/f*v:o<f+i.hold?v:o<p?v+(y-v)*((o-f-i.hold)/Math.max(1e-6,p-f-i.hold)):o<_?y:o<_+m?y*(1-(o-_)/m):0,S&&w>=i.sample.loopEnd&&(w=i.sample.loopStart+(w-i.sample.loopStart)%C);let u=Math.floor(w),d=Math.min(1,Math.max(0,w-u)),h;if(!S&&w>=c.length||u<0)h=0;else{let e=c[Math.min(u,c.length-1)];h=e+(c[Math.min(u+1,c.length-1)]-e)*d}e[a]+=h*s*b,t[a]+=h*s*x,w+=l}}function p(e){return e<8?{wave:`triangle`,attack:.005,decay:1.2,sustain:.25,release:.2,detune:0}:e<16?{wave:`sine`,attack:.003,decay:.8,sustain:.1,release:.5,detune:0}:e<24?{wave:`square`,attack:.01,decay:.1,sustain:.7,release:.08,detune:0,cutoff:2500}:e<32?{wave:`sawtooth`,attack:.004,decay:.6,sustain:.15,release:.15,detune:0,cutoff:3e3}:e<40?{wave:`triangle`,attack:.005,decay:.4,sustain:.5,release:.1,detune:0}:e<56?{wave:`sawtooth`,attack:.12,decay:.2,sustain:.8,release:.3,detune:6,cutoff:3500}:e<80?{wave:`sawtooth`,attack:.04,decay:.15,sustain:.75,release:.12,detune:0,cutoff:4500}:e<88?{wave:`square`,attack:.01,decay:.1,sustain:.8,release:.1,detune:0,cutoff:3800}:e<104?{wave:`sawtooth`,attack:.25,decay:.3,sustain:.7,release:.5,detune:8,cutoff:2200}:{wave:`triangle`,attack:.005,decay:.5,sustain:.2,release:.2,detune:0}}function m(e,t){switch(e){case`sine`:return Math.sin(t);case`square`:return Math.sin(t)>=0?1:-1;case`sawtooth`:{let e=t/(2*Math.PI);return 2*(e-Math.floor(e))-1}case`triangle`:{let e=t/(2*Math.PI);return 4*Math.abs(e-Math.floor(e)-.5)-1}}}function h(e,t,n,r,i,a){return e<t?e/t:e<t+n?1-(1-r)*((e-t)/Math.max(1e-6,n)):e<i?r:e<i+a?r*(1-(e-i)/a):0}function g(e,t){let n=Math.imul(e^t,2654435761)>>>0;return n=Math.imul(n^n>>>15,2246822519)>>>0,n=Math.imul(n^n>>>13,3266489917)>>>0,n^=n>>>16,(n>>>0)/4294967295*2-1}function _(e,t,n,r,i,a,o){if(r.channel===9){v(e,t,n,r,i,a,o);return}let s=p(r.program),c=r.frequency*2**((s.detune+(r.bend??0)*100)/1200),l=Math.max(r.duration,s.attack+.01),u=Math.max(.02,s.release),f=Math.min(o,a+Math.ceil((l+u+.02)*n)),[g,_]=d(r.pan),y=s.cutoff!==void 0,b=y?1-Math.exp(-2*Math.PI*Math.min(s.cutoff,c*8+800)/n):0,x=0,S=0,C=2*Math.PI*c/n;for(let o=a;o<f;o++){let a=o/n-r.time,c=m(s.wave,S);S+=C,x=y?x+b*(c-x):c;let d=i*h(a,s.attack,s.decay,s.sustain,l,u);e[o]+=x*d*g,t[o]+=x*d*_}}function v(e,t,n,r,i,a,o){let[s,c]=d(r.pan),l=r.note*7919+a;if(r.note===35||r.note===36||r.note<45){let l=i*1.4,u=Math.min(o,a+Math.ceil(.27*n)),d=0;for(let i=a;i<u;i++){let a=i/n-r.time,o=a<.12?150*(45/150)**(a/.12):45;d+=2*Math.PI*o/n;let u=l*(.001/l)**Math.min(1,a/.22);e[i]+=Math.sin(d)*u*s,t[i]+=Math.sin(d)*u*c}return}let u=r.note===38||r.note===40,f=u?.16:r.note>=49?.5:.06,p=i*(u?.9:.5),m=Math.min(o,a+Math.ceil((f+.02)*n));for(let i=a;i<m;i++){let o=i/n-r.time,u=p*(.001/p)**Math.min(1,o/f),d=g(l,i-a)*u;e[i]+=d*s,t[i]+=d*c}}for(let e of i){let r=Math.floor(e.time*t);if(r>=s)continue;let i=n*Math.max(.02,e.velocity/127*e.gain),a=e.voices??[];if(a.length>0)for(let n of a)f(c,l,t,e,n,i,r,s);else _(c,l,t,e,i,r,s)}return{sampleRate:t,left:c,right:l,loopStart:u,loopEnd:o,duration:o}}function Mq(e,t,n,r,i,a){let o=e.createBufferSource();o.buffer=n,o.playbackRate.value=i;let s=e.createGain();s.gain.value=r;let c=null;return typeof e.createStereoPanner==`function`?(c=e.createStereoPanner(),c.pan.value=a,o.connect(s),s.connect(c),c.connect(t)):(o.connect(s),s.connect(t)),{source:o,gain:s,panner:c}}var Nq=class{constructor(e,t){this.source=null,this.gainNode=null,this.pannerNode=null,this.buffer=null,this.params={volume:1,pitch:1,pan:0},this.loopRegion=null,this.repeat=!0,this.startedAt=0,this.offset=0,this.context=e,this.destination=t??e.destination}get isPlaying(){return this.source!==null}get duration(){return this.buffer?.duration??0}play(e,t={}){this.stop();let n=t.volume??1,r=t.pitch??1,i=t.pan??0,{source:a,gain:o,panner:s}=Mq(this.context,this.destination,e,n,r,i),c=t.loop??null,l=t.repeat??!0;if(a.loop=l,c&&(a.loopStart=c.start,a.loopEnd=c.end),!l){let e=a;a.onended=()=>{this.source===e&&this.clearNodes()}}this.source=a,this.gainNode=o,this.pannerNode=s,this.buffer=e,this.params={volume:n,pitch:r,pan:i},this.loopRegion=c,this.repeat=l,this.offset=Math.min(Math.max(0,t.pos??0),Math.max(0,e.duration-.001)),this.startedAt=this.context.currentTime,a.start(0,this.offset)}update(e){if(e.volume!==void 0&&(this.params.volume=e.volume),e.pitch!==void 0&&(this.params.pitch=e.pitch),e.pan!==void 0&&(this.params.pan=e.pan),!this.source||!this.gainNode)return;let t=this.context.currentTime;this.gainNode.gain.setTargetAtTime(this.params.volume,t,.02),this.source.playbackRate.value=this.params.pitch,this.pannerNode&&(this.pannerNode.pan.value=this.params.pan)}stop(e=0){let t=this.position(),n=this.source,r=this.gainNode;if(this.clearNodes(),this.offset=t,n)try{if(e>0&&r){let t=this.context.currentTime;r.gain.cancelScheduledValues(t),r.gain.setValueAtTime(r.gain.value,t),r.gain.linearRampToValueAtTime(0,t+e),n.stop(t+e+.02)}else n.stop()}catch{}}position(){if(!this.source||!this.buffer)return this.offset;let e=Math.max(0,this.context.currentTime-this.startedAt)*this.params.pitch,t=this.offset+e;if(this.repeat&&this.duration>0){let e=this.loopRegion?.start??0,n=this.loopRegion?.end??this.buffer.duration;n>e&&t>=n&&(t=e+(t-e)%(n-e))}return t}seek(e){this.restore({...this.state(),pos:e})}state(){return{...this.params,pos:this.position()}}restore(e){let t=this.buffer;this.update({volume:e.volume,pitch:e.pitch,pan:e.pan}),t&&this.source?this.play(t,{volume:e.volume,pitch:e.pitch,pan:e.pan,pos:e.pos,loop:this.loopRegion,repeat:this.repeat}):this.offset=Math.max(0,e.pos)}clearNodes(){this.source&&(this.source.onended=null),this.source=null,this.gainNode=null,this.pannerNode=null}};function Pq(e,t,n,r){let i=Number(e);return Math.min(n,Math.max(t,Number.isFinite(i)?i:r))}var Fq=class e{constructor(e,t={}){this.tracks={bgm:null,bgs:null},this.saved={bgm:null,bgs:null},this.requests={bgm:0,bgs:0},this.me=null,this.meToken=0,this.suspendedBgm=null,this.seNodes=new Set,this.mixerLevels={bgm:{volume:1,muted:!1},bgs:{volume:1,muted:!1},me:{volume:1,muted:!1},se:{volume:1,muted:!1}},this.context=e,this.destination=t.destination??e.destination,this.load=t.load??(async()=>null);let n=()=>{let t=e.createGain();return t.connect(this.destination),t};this.kindGains={bgm:n(),bgs:n(),me:n(),se:n()},this.bgmChannel=new Nq(e,this.kindGains.bgm),this.bgsChannel=new Nq(e,this.kindGains.bgs)}setMixer(e,t){let n=this.mixerLevels[e];t.volume!==void 0&&(n.volume=Pq(t.volume,0,1,1)),t.muted!==void 0&&(n.muted=t.muted),this.kindGains[e].gain.value=n.muted?0:n.volume}mixer(e){return{...this.mixerLevels[e]}}playBgm(e){return this.playLoop(`bgm`,e)}playBgs(e){return this.playLoop(`bgs`,e)}stopBgm(){this.requests.bgm++,this.tracks.bgm=null,this.suspendedBgm=null,this.bgmChannel.stop()}stopBgs(){this.requests.bgs++,this.tracks.bgs=null,this.bgsChannel.stop()}fadeOutBgm(e=1){this.requests.bgm++,this.tracks.bgm=null,this.suspendedBgm=null,this.bgmChannel.stop(Math.max(0,e))}fadeOutBgs(e=1){this.requests.bgs++,this.tracks.bgs=null,this.bgsChannel.stop(Math.max(0,e))}currentTrack(e){let t=this.tracks[e];if(t){let n=e===`bgm`?this.bgmChannel:this.bgsChannel;return{...t,pos:n.isPlaying?n.position():t.pos}}return e===`bgm`?this.suspendedBgm:null}saveBgm(){return this.saved.bgm=this.currentTrack(`bgm`),this.saved.bgm}saveBgs(){return this.saved.bgs=this.currentTrack(`bgs`),this.saved.bgs}replayBgm(){return this.saved.bgm?this.playBgm(this.saved.bgm):Promise.resolve()}replayBgs(){return this.saved.bgs?this.playBgs(this.saved.bgs):Promise.resolve()}async playMe(t){let n=e.normalize(t),r=++this.meToken;if(this.stopMeNodes(),!n.name)return;let i=await this.load(`me`,n.name);if(r!==this.meToken||!i)return;let a=this.currentTrack(`bgm`);a&&(this.suspendedBgm=a,this.requests.bgm++,this.bgmChannel.stop(),this.tracks.bgm=null);let{source:o}=Mq(this.context,this.kindGains.me,i.buffer,n.volume/100,n.pitch/100,n.pan/100);this.me={source:o,token:r},o.onended=()=>{this.me?.token===r&&this.finishMe()},o.start(0)}stopMe(e=!0){this.stopMeNodes(),e&&this.finishMe()}async playSe(t){let n=e.normalize(t);if(!n.name)return;let r=await this.load(`se`,n.name);if(!r)return;let{source:i}=Mq(this.context,this.kindGains.se,r.buffer,n.volume/100,n.pitch/100,n.pan/100),a={source:i};this.seNodes.add(a),i.onended=()=>{this.seNodes.delete(a)},i.start(0)}stopSe(){for(let e of this.seNodes){e.source.onended=null;try{e.source.stop()}catch{}}this.seNodes.clear()}stopAll(){this.requests.bgm++,this.requests.bgs++,this.tracks.bgm=null,this.tracks.bgs=null,this.suspendedBgm=null,this.bgmChannel.stop(),this.bgsChannel.stop(),this.stopMeNodes(),this.stopSe()}snapshot(){return{bgm:this.currentTrack(`bgm`),bgs:this.currentTrack(`bgs`),savedBgm:this.saved.bgm,savedBgs:this.saved.bgs}}restore(e){e&&typeof e==`object`&&(this.saved.bgm=e.savedBgm??null,this.saved.bgs=e.savedBgs??null,e.bgm&&this.playBgm(e.bgm),e.bgs&&this.playBgs(e.bgs))}static normalize(e){return{name:String(e?.name||``),volume:Pq(e?.volume,0,100,90),pitch:Pq(e?.pitch,10,400,100),pan:Pq(e?.pan,-100,100,0),pos:Math.max(0,Number(e?.pos)||0)}}async playLoop(t,n){let r=t===`bgm`?this.bgmChannel:this.bgsChannel,i=e.normalize(n);if(!i.name){this.requests[t]++,this.tracks[t]=null,t===`bgm`&&(this.suspendedBgm=null),r.stop();return}let a=this.tracks[t];if(a&&a.name===i.name&&!(i.pos>0)){this.tracks[t]={...i,pos:0},r.update({volume:i.volume/100,pitch:i.pitch/100,pan:i.pan/100});return}if(t===`bgm`&&this.me){this.requests.bgm++,this.suspendedBgm=i,this.tracks.bgm=null,r.stop();return}let o=++this.requests[t];r.stop(),this.tracks[t]={...i,pos:0};let s=await this.load(t,i.name);if(o===this.requests[t]){if(!s){this.tracks[t]=null;return}r.play(s.buffer,{volume:i.volume/100,pitch:i.pitch/100,pan:i.pan/100,pos:i.pos,loop:s.loop??null})}}stopMeNodes(){let e=this.me;if(this.me=null,e){e.source.onended=null;try{e.source.stop()}catch{}}}finishMe(){this.me=null;let e=this.suspendedBgm;this.suspendedBgm=null,e&&!this.tracks.bgm&&this.playBgm(e)}},Iq=65536;function Lq(e){let t=zq(e.subarray(0,Iq));if(!t)return null;let n=new DataView(t.buffer,t.byteOffset,t.byteLength),r=new TextDecoder(`utf-8`),i=7,a=()=>{if(i+4>t.length)return null;let e=n.getUint32(i,!0);return i+=4,i+e<=t.length?e:null},o=a();if(o===null||(i+=o,i+4>t.length))return null;let s=n.getUint32(i,!0);i+=4;let c=null,l=null;for(let e=0;e<s;e++){let e=a();if(e===null)break;let n=r.decode(t.subarray(i,i+e));i+=e;let o=n.indexOf(`=`);if(o<0)continue;let s=n.slice(0,o).toUpperCase(),u=/^\d+$/.test(n.slice(o+1))?Number(n.slice(o+1)):null;u!==null&&(s===`LOOPSTART`?c=u:s===`LOOPLENGTH`&&(l=u))}return c===null?null:{loopStart:c,loopLength:l}}function Rq(e,t,n){if(!e||!(t>0))return null;let r=e.loopStart/t,i=e.loopLength?(e.loopStart+e.loopLength)/t:n;return r>=0&&i>r&&r<n?{start:r,end:Math.min(i,n)}:null}function zq(e){let t=[3,118,111,114,98,105,115],n=[],r=0;for(;r+27<=e.length;){if(e[r]!==79||e[r+1]!==103||e[r+2]!==103||e[r+3]!==83)return null;let i=e[r+26],a=r+27+i;if(a>e.length)return null;let o=a;for(let a=0;a<i;a++){let i=e[r+27+a];if(o+i>e.length)return null;for(let t=0;t<i;t++)n.push(e[o+t]);if(o+=i,i<255){if(t.every((e,t)=>n[t]===e))return Uint8Array.from(n);n=[]}}r=o}return null}function Bq(e,t={}){let n=t.refDistance??1,r=t.maxDistance??1/0,i=t.rolloff??1;if(!(e>n))return 1;if(!(e<r))return 0;let a=(n/e)**+i;return Math.max(0,Math.min(1,a))}function Vq(e,t){let n=t.x-e.x,r=t.y-e.y,i=Math.hypot(n,r);if(i===0)return 0;let a=Math.sin(e.facing),o=Math.cos(e.facing),s=(n*a+r*o)/i;return Math.max(-1,Math.min(1,s))}var Hq=class{constructor(e={}){this.x=e.x??0,this.y=e.y??0,this.facing=e.facing??0}moveTo(e,t){this.x=e,this.y=t}face(e){this.facing=e}},Uq=class{constructor(e,t={}){this.sound=e,this.x=t.x??0,this.y=t.y??0,this.falloff={refDistance:t.refDistance,maxDistance:t.maxDistance,rolloff:t.rolloff}}moveTo(e,t){this.x=e,this.y=t}gainTo(e){return Bq(Math.hypot(this.x-e.x,this.y-e.y),this.falloff)}panTo(e){return Vq(e,this)}playFor(e){let t=this.gainTo(e);return t<=0?0:(this.sound.play(t),t)}};UK(),KK();var Wq=256,Gq=64,Kq=10,qq=2,Jq=.05,Yq=4,Xq=96;function Zq(e,t){let n=e.length,r=0;for(let i=1;i<n;i++){let a=n>>1;for(;r&a;)r^=a,a>>=1;if(r^=a,i<r){let n=e[i];e[i]=e[r],e[r]=n,n=t[i],t[i]=t[r],t[r]=n}}for(let r=2;r<=n;r<<=1){let i=-2*Math.PI/r,a=Math.cos(i),o=Math.sin(i),s=r>>1;for(let i=0;i<n;i+=r){let n=1,r=0;for(let c=0;c<s;c++){let l=i+c,u=l+s,d=e[u]*n-t[u]*r,f=e[u]*r+t[u]*n;e[u]=e[l]-d,t[u]=t[l]-f,e[l]+=d,t[l]+=f;let p=n*a-r*o;r=n*o+r*a,n=p}}}}function Qq(e,t){if(e.length===0||t<=0)return[];let n=Wq/2,r=new Float32Array(e.length+256);r.set(e,n);let i=new Float64Array(Wq);for(let e=0;e<Wq;e++)i[e]=.5-.5*Math.cos(2*Math.PI*e/255);let a=new Float64Array(Wq),o=new Float64Array(Wq),s=new Float64Array(Wq/2),c=[],l=[],u=0;for(let e=0;e+Wq<=r.length;e+=Gq){let t=0;for(let n=0;n<Wq;n++)a[n]=r[e+n]*i[n],o[n]=0,t+=a[n]*a[n];l.push(u===0?t===0?0:1/0:t/u-1),u=t,Zq(a,o);let n=0;for(let e=0;e<Wq/2;e++){let t=Math.hypot(a[e],o[e]),r=t-s[e];r>0&&(n+=r),s[e]=t}c.push(n)}let d=[],f=-1/0;for(let e=0;e<c.length;e++){let r=Math.max(0,e-Kq),i=Math.min(c.length-1,e+Kq),a=i-r+1,o=0;for(let e=r;e<=i;e++)o+=c[e];o/=a;let s=0;for(let e=r;e<=i;e++)s+=(c[e]-o)**2;let u=o+qq*Math.sqrt(s/a);if(c[e]<=0||c[e]<u||l[e]<Jq&&(e===0||l[e-1]<Jq)||e>0&&c[e-1]>c[e]||e+1<c.length&&c[e+1]>=c[e]||e-f<Yq)continue;let p=(e*Gq+n-Xq)/t;d.push(Math.max(0,p)),f=e}return d}hK();var $q=`extracted`,eJ=[4,4],tJ=120,nJ=120,rJ=480;function iJ(e){let t=[...e].sort((e,t)=>e-t),n=t.length>>1;return t.length%2==1?t[n]:(t[n-1]+t[n])/2}function aJ(e){return Math.round(iJ(e))}function oJ(e){for(let t of e.events)if(t.type===`tempo`)return Math.round(6e7/t.microsecondsPerQuarter*100)/100;return tJ}function sJ(e){return e.events.filter(e=>e.type===`noteOn`)}function cJ(e){return sJ(e).map(e=>e.velocity)}function lJ(e,t,n,r,i){let a=e.map((e,t)=>({subdivisionIndex:t,timeOffsetTicks:e.time.length>0?aJ(e.time):0,velocityFactor:e.velocity.length>0?i(e):1}));return{name:$q,timeSignature:[...eJ],ppq:n,tempoBpm:r,subdivision:t,offsets:a}}var uJ=class{async extractFromMidiPair(e,t,n=`16n`){let r=t.ticksPerQuarter,i=fK(r,n),a=dK(eJ,n),o=r/e.ticksPerQuarter,s=sJ(e).map(e=>({channel:e.channel,note:e.note,tick:e.tick*o,velocity:e.velocity})),c=new Set,l=[];for(let e of sJ(t)){let t=-1,n=1/0;for(let r=0;r<s.length;r++){let i=s[r];if(c.has(r)||i.channel!==e.channel||i.note!==e.note)continue;let a=Math.abs(i.tick-e.tick);a<n&&(n=a,t=r)}t<0||n>i/2||(c.add(t),l.push({slotTick:s[t].tick,delta:e.tick-s[t].tick,factor:s[t].velocity>0?e.velocity/s[t].velocity:null}))}let u=Array.from({length:a},()=>({time:[],velocity:[]}));for(let e of l){let t=(Math.round(e.slotTick/i)%a+a)%a;u[t].time.push(e.delta),e.factor!==null&&u[t].velocity.push(e.factor)}return lJ(u,n,r,oJ(t),e=>iJ(e.velocity))}async extractFromSingleMidi(e,t=`16n`){let n=e.ticksPerQuarter,r=fK(n,t),i=dK(eJ,t),a=Array.from({length:i},()=>({time:[],velocity:[]}));for(let t of sJ(e)){let e=Math.round(t.tick/r)*r,n=(Math.round(e/r)%i+i)%i;a[n].time.push(t.tick-e),a[n].velocity.push(t.velocity)}let o=iJ(cJ(e));return lJ(a,t,n,oJ(e),e=>o<=0?1:iJ(e.velocity)/o)}async extractFromAudioBuffer(e,t=`16n`,n=nJ){if(!Number.isFinite(n)||n<=0)throw Error(`tempoBpm must be greater than 0, got ${String(n)}`);let r=[];for(let t=0;t<e.numberOfChannels;t++)r.push(e.getChannelData(t));let i=new Float32Array(e.length);for(let e of r)for(let t=0;t<e.length;t++)i[t]+=e[t]/r.length;let a=Qq(i,e.sampleRate);if(a.length===0)throw Error(`no onsets detected in the buffer - a groove needs audible attacks, and this audio has none`);let o=rJ,s=fK(o,t),c=dK(eJ,t),l=n*o/60,u=Array.from({length:c},()=>({time:[],velocity:[]}));for(let e of a){let t=e*l,n=Math.round(t/s)*s;u[(Math.round(n/s)%c+c)%c].time.push(t-n)}return lJ(u,t,o,n,()=>1)}};hK();var dJ=`mwg-groove:`,fJ=36,pJ=64,mJ=[`8n`,`16n`,`32n`],hJ=new TextEncoder;function gJ(e){throw Error(`the ${e} format is not shipped: it is an undocumented proprietary container, and a guessed reader could load a different groove than the file holds`)}function _J(e){return[...e].map(e=>e.charCodeAt(0)&127)}function vJ(e){let t=[e&127],n=e>>>7;for(;n>0;)t.unshift(n&127|128),n>>>=7;return t}function yJ(e,t){return[255,e,...vJ(t.length),...t]}function bJ(e){pK(e);let{name:t,timeSignature:n,ppq:r,subdivision:i,offsets:a}=e,o=dK(n,i),s=fK(r,i);if(r>32767)throw Error(`groove template "${t}": ppq ${r} does not fit MIDI's 15-bit division`);if(fJ+o-1>127)throw Error(`groove template "${t}": ${o} slots need pitches up to ${fJ+o-1}, past MIDI's top note of 127`);let c=Math.round(6e7/e.tempoBpm);if(c<1||c>16777215)throw Error(`groove template "${t}": tempoBpm ${e.tempoBpm} does not fit MIDI's three-byte tempo (${c} microseconds)`);a.forEach((e,n)=>{if(Math.abs(e.timeOffsetTicks)>=s)throw Error(`groove template "${t}": slot ${n} is offset by ${e.timeOffsetTicks} ticks, outside the +/-${s} the MIDI encoding's one-slot anchor can tell from a slot shift`);let r=Math.round(pJ*e.velocityFactor);if(r<1||r>127)throw Error(`groove template "${t}": slot ${n} has velocityFactor ${e.velocityFactor}, outside the ${1/pJ} to ${127/pJ} the MIDI encoding can store at ${1/pJ} per velocity unit`)});let l=[{tick:0,bytes:yJ(81,[c>>16&255,c>>8&255,c&255])},{tick:0,bytes:yJ(88,[n[0],Math.log2(n[1]),24,8])},{tick:0,bytes:yJ(1,[...hJ.encode(dJ+t)])}];a.forEach((e,t)=>{let n=s*(t+1)+e.timeOffsetTicks,r=n+Math.max(1,Math.floor(s/4));l.push({tick:n,bytes:[144,fJ+t,Math.round(pJ*e.velocityFactor)]}),l.push({tick:r,bytes:[128,fJ+t,0]})}),l.sort((e,t)=>e.tick-t.tick);let u=[],d=0;for(let e of l)u.push(...vJ(e.tick-d),...e.bytes),d=e.tick;return u.push(0,255,47,0),new Uint8Array([..._J(`MThd`),0,0,0,6,0,0,0,1,r>>8&255,r&255,..._J(`MTrk`),u.length>>>24&255,u.length>>>16&255,u.length>>>8&255,u.length&255,...u])}function xJ(e,t){for(let n of mJ)try{if(dK(e,n)===t)return n}catch{}throw Error(`a ${t}-slot groove in ${e[0]}/${e[1]} is not one of the 8n, 16n or 32n grids`)}function SJ(e){let t=typeof e==`string`?hJ.encode(e):e,n=new DataView(t.buffer,t.byteOffset,t.byteLength),r=0,i=(e,n)=>{if(r+e>t.length)throw Error(`truncated MIDI file while reading ${n}`)},a=(e,n)=>{i(e,n);let a=``;for(let n=0;n<e;n++)a+=String.fromCharCode(t[r+n]);return r+=e,a},o=e=>(i(1,e),t[r++]),s=e=>{i(2,e);let t=n.getUint16(r);return r+=2,t},c=e=>{i(4,e);let t=n.getUint32(r);return r+=4,t},l=e=>{let t=0;for(let n=0;n<4;n++){let n=o(e);if(t=t<<7|n&127,!(n&128))return t}throw Error(`a variable-length quantity in ${e} runs past four bytes`)};if(a(4,`the file header`)!==`MThd`)throw Error(`not a Standard MIDI File: the MThd header is missing`);let u=c(`the header length`);if(u<6)throw Error(`MThd is ${u} bytes, expected at least 6`);let d=s(`the format`),f=s(`the track count`),p=s(`the division`);if(r+=u-6,d>1)throw Error(`MIDI format ${d} is not a file this reader understands`);if(p&32768)throw Error(`SMPTE time in the division carries no tick grid to read a groove from`);if(f!==1)throw Error(`an mwg groove file holds one track, this one has ${f}`);if(a(4,`the track header`)!==`MTrk`)throw Error(`the MTrk track header is missing`);let m=c(`the track length`),h=r+m;if(h>t.length)throw Error(`truncated MIDI file: the track runs past the end of the data`);let g=0,_=0,v=null,y=null,b=null,x=!1,S=new Map;for(;r<h;){g+=l(`a delta time`);let e=t[r];if(e<128){if(_===0)throw Error(`data at tick ${g} follows a delta time with no running status to read it under`);e=_}else r++,e<240&&(_=e);if(e===255){let e=o(`a meta type`),n=l(`a meta length`);i(n,`a meta event`);let a=r;if(e===81&&n===3)v=t[a]<<16|t[a+1]<<8|t[a+2];else if(e===88&&n>=2)y=[t[a],2**t[a+1]];else if((e===1||e===3)&&n>0){let e=``;for(let r=0;r<n;r++)e+=String.fromCharCode(t[a+r]);e.startsWith(dJ)&&(b=e.slice(11))}r+=n,e===47&&(x=!0),_=0;continue}if(e===240||e===247){r+=l(`a sysex length`),_=0;continue}let n=e&240;if(n===144||n===128){let e=o(`a note number`),t=o(`a note velocity`);if(n===144&&t>0){if(S.has(e))throw Error(`pitch ${e} carries more than one note-on, which no groove encodes`);S.set(e,{tick:g,velocity:t})}}else if(n===176||n===224)i(2,`a controller or bend event`),r+=2;else if(n===192||n===208)i(1,`a program or channel-aftertouch event`),r+=1;else throw Error(`unexpected status byte 0x${e.toString(16)} at tick ${g}`)}if(!x)throw Error(`the track has no end-of-track meta, so the file is incomplete`);if(b===null)throw Error(`no ${dJ} text meta: this file was not written as a groove`);if(y===null)throw Error(`no time-signature meta: an mwg groove file always carries one`);let C=p,ee=S.size,w=xJ(y,ee),T=fK(C,w),E=[];for(let e=0;e<ee;e++){let t=S.get(fJ+e);if(!t)throw Error(`slot ${e} is missing: expected a note on pitch ${fJ+e}`);E.push({subdivisionIndex:e,timeOffsetTicks:t.tick-T*(e+1),velocityFactor:t.velocity/pJ})}let D={name:b,timeSignature:y,ppq:C,tempoBpm:v===null?120:Math.round(6e7/v*100)/100,subdivision:w,offsets:E};return pK(D),D}function CJ(e){let t=typeof e==`string`?e:new TextDecoder().decode(e),n;try{n=JSON.parse(t)}catch(e){throw Error(`not valid JSON: ${e instanceof Error?e.message:String(e)}`)}if(typeof n!=`object`||!n||Array.isArray(n))throw Error(`a groove JSON export must be an object`);return pK(n),n}var wJ=class{async exportFormat(e,t){switch(t){case`json`:return pK(e),JSON.stringify(e,null,2);case`midi`:return bJ(e);case`ableton-agr`:case`reaper-groove`:return gJ(t);default:throw Error(`unknown groove format: ${String(t)}`)}}async importFormat(e,t){switch(t){case`json`:return CJ(e);case`midi`:return SJ(e);case`ableton-agr`:case`reaper-groove`:return gJ(t);default:throw Error(`unknown groove format: ${String(t)}`)}}},TJ=l({AudioBus:()=>Fq,AudioListener:()=>Hq,Channel:()=>Nq,GrooveConverter:()=>wJ,GrooveExtractor:()=>uJ,GrooveHumanizer:()=>GK,HumanizerFactory:()=>qK,LiteHumanizer:()=>HK,MidiPlayer:()=>iq,Music:()=>rK,Orchestrator:()=>iK,Sound:()=>nK,SoundSource:()=>Uq,assertGrooveTemplate:()=>pK,audioGain:()=>Bq,audioPan:()=>Vq,collectSoundFontUsage:()=>hq,createAudio:()=>eK,humanizeMidi:()=>JK,loopRegionFromTags:()=>Rq,midiLoopStart:()=>tq,noteToFrequency:()=>rq,onCaption:()=>tK,parseMidi:()=>ZK,parseSoundFont:()=>mq,parseVorbisLoopTags:()=>Lq,playTone:()=>oK,renderMidiToBuffer:()=>Dq,renderMidiToBufferAsync:()=>Oq,scheduleMidi:()=>nq,subdivisionCount:()=>dK,subsetSoundFont:()=>Cq,synthesizeTone:()=>aK});hK();function EJ(e,t){if(!Number.isSafeInteger(t)||t<0)throw RangeError(`Turn budget must be a non-negative safe integer`);let n=0;for(;n<t;){if(e.finished())return{status:`finished`,steps:n};let t=e.scheduler.peek();if(t===null)return{status:`empty`,steps:n};if(e.needsInput(t))return{status:`input`,actor:t,steps:n};let r=e.act(t);if(r!==null){if(!Number.isFinite(r)||r<0)throw RangeError(`Action cost must be finite and non-negative, or null`);e.scheduler.spend(r)}n++}return{status:`limit`,steps:n}}function DJ(e){if(e?.version!==1||typeof e.observationVersion!=`string`||!e.observationVersion.length)throw TypeError(`unsupported neural model or observation version`);if(!Array.isArray(e.layers)||!e.layers.length||e.layers.length>32)throw RangeError(`a neural model needs 1..32 layers`);let t=0;for(let n=0;n<e.layers.length;n++){let r=e.layers[n];if(!r||!Number.isInteger(r.inputSize)||!Number.isInteger(r.outputSize)||r.inputSize<1||r.outputSize<1||r.inputSize>4096||r.outputSize>4096)throw RangeError(`neural layer dimensions must be integers in 1..4096`);if(t+=r.inputSize*r.outputSize+r.outputSize,t>1e6)throw RangeError(`neural model exceeds one million parameters`);if(n&&e.layers[n-1].outputSize!==r.inputSize)throw RangeError(`neural layer dimensions do not connect`);if(!Array.isArray(r.weights)||!Array.isArray(r.biases)||r.weights.length!==r.inputSize*r.outputSize||r.biases.length!==r.outputSize||!Array.from(r.weights).every(Number.isFinite)||!Array.from(r.biases).every(Number.isFinite))throw TypeError(`neural weights and biases must be finite and match layer dimensions`)}let n=e.layers.map(e=>({...e,weights:Float64Array.from(e.weights),biases:Float64Array.from(e.biases),buffer:new Float64Array(e.outputSize)})),r=(e,t)=>{if(e.length!==n[0].inputSize)throw TypeError(`neural input must be finite and match the model`);for(let t=0;t<e.length;t++)if(!Number.isFinite(e[t]))throw TypeError(`neural input must be finite`);let r=n[n.length-1];if(t&&t.length!==r.outputSize)throw RangeError(`neural output buffer has the wrong size`);let i=e;for(let e=0;e<n.length;e++){let t=n[e];for(let r=0;r<t.outputSize;r++){let a=t.biases[r];for(let e=0;e<t.inputSize;e++)a+=t.weights[r*t.inputSize+e]*i[e];if(!Number.isFinite(a))throw RangeError(`neural activation overflow`);t.buffer[r]=e===n.length-1?a:Math.max(0,a)}i=t.buffer}let a=t??new Float64Array(r.outputSize);return a.set(r.buffer),a},i=new Float64Array(n[n.length-1].outputSize);return{predict:r,select(e,t){let n=e.mask;if(n&&(n.length!==i.length||!Array.from(n).every(e=>typeof e==`boolean`)))throw TypeError(`neural action mask must contain one boolean per output`);r(e.input,i);let a=null;for(let e=0;e<i.length;e++)(!n||n[e])&&(a===null||i[e]>i[a])&&(a=e);if(a===null||!t)return a;let o=t();if(!Number.isFinite(o)||o<0||o>=1)throw RangeError(`sampling random must return a value in [0, 1)`);let s=0;for(let e=0;e<i.length;e++)(!n||n[e])&&(s+=Math.exp(i[e]-i[a]));let c=o*s;for(let e=0;e<i.length;e++)if((!n||n[e])&&(c-=Math.exp(i[e]-i[a]),c<0))return e;return a}}}function OJ(e,t,n){let r=Function(`return (${e});`)()(t);return n.map(e=>r.predict(e))}var kJ=class{constructor(e){this.evaluator=DJ(e),this.model=structuredClone(e)}predict(e,t){return this.evaluator.predict(e,t)}selectAction(e,t){return this.evaluator.select(e,t)}exportModel(){return structuredClone(this.model)}behavior(e,t,n,r=!1){if(t.length!==this.model.layers[this.model.layers.length-1].outputSize)throw RangeError(`neural action mapping must match output size`);let i=structuredClone(t);return{id:e,decide:e=>{e.checkpoint();let t=this.selectAction(n(e.perception),r?e.random:void 0);return t===null?null:structuredClone(i[t])}}}predictBatchAsync(e,t={}){let n=this.model.layers[0].inputSize,r=this.model.layers[this.model.layers.length-1].outputSize;if(e.length>65536||e.length*Math.max(n,r)>1e6)return Promise.reject(RangeError(`neural batch exceeds its observation or value limit`));for(let t of e)if(!t||t.length!==n)return Promise.reject(TypeError(`neural batch inputs must match the model`));return OU(OJ,[DJ.toString(),this.model,e],t)}};_e();var AJ=class{get truncated(){return!this.terminated&&this.steps>=this.maxSteps}constructor(e,t,n=j){if(this.steps=0,this.terminated=!1,this.ready=!1,this.agentCount=0,this.rules=e,this.Random=n,this.random=new this.Random(0),!Number.isInteger(t.maxSteps)||t.maxSteps<1||t.maxSteps>1e6)throw RangeError(`training maxSteps must be in 1..1000000`);if(typeof e.observationVersion!=`string`||!e.observationVersion.length)throw TypeError(`training requires an observation version`);this.maxSteps=t.maxSteps,this.observationVersion=e.observationVersion}reset(e){if(!Number.isInteger(e)||e<0||e>4294967295)throw RangeError(`training seed must be uint32`);this.random=new this.Random(e),this.state=this.rules.initial(this.random),this.steps=0,this.terminated=this.rules.finished?.(this.state)??!1,this.ready=!0;let t=this.observations();return this.agentCount=t.length,{observations:t,rewards:t.map(()=>0),terminated:this.terminated,truncated:!1}}step(e){if(!this.ready||this.terminated||this.truncated)throw Error(`training episode needs reset before step`);let t=this.observations();if(e.length!==this.agentCount)throw RangeError(`training action count must match the agent roster`);for(let n=0;n<e.length;n++){let r=e[n],i=t[n].mask;if(r===null?!i||i.some(Boolean):!Number.isInteger(r)||r<0||i&&(r>=i.length||!i[r]))throw RangeError(`training action is not legal`)}let n=structuredClone(this.state),r=this.rules.command(this.state,e),i=this.rules.rule(this.state,r,this.random),a=Array.from(this.rules.rewards(n,r,i));if(a.length!==this.agentCount||!a.every(Number.isFinite))throw TypeError(`training rewards must be finite and match the agent roster`);this.state=i.state,this.steps++,this.terminated=i.status===`finished`;let o=this.observations();if(o.length!==this.agentCount)throw RangeError(`training agent roster changed during an episode`);return{observations:o,rewards:a,terminated:this.terminated,truncated:this.truncated}}snapshot(){if(!this.ready)throw Error(`training environment needs reset before snapshot`);return structuredClone({version:1,observationVersion:this.observationVersion,state:this.state,seed:this.random.seed,random:this.random.getState().map(e=>e>>>0),steps:this.steps,maxSteps:this.maxSteps,terminated:this.terminated,truncated:this.truncated})}restore(e){if(e.version!==1||e.observationVersion!==this.observationVersion||e.maxSteps!==this.maxSteps)throw TypeError(`training snapshot version, schema or step limit does not match`);if(!Number.isInteger(e.steps)||e.steps<0||e.steps>this.maxSteps||!Number.isInteger(e.seed)||e.seed<0||e.seed>4294967295||!Array.isArray(e.random)||e.random.length!==4||!e.random.every(e=>Number.isInteger(e)&&e>=0&&e<=4294967295)||!e.random.some(e=>e!==0)||typeof e.terminated!=`boolean`||typeof e.truncated!=`boolean`||e.terminated&&e.truncated||e.truncated!==(!e.terminated&&e.steps===this.maxSteps))throw TypeError(`invalid training snapshot`);this.state=structuredClone(e.state),this.random=new this.Random(e.seed),this.random.setState(e.random),this.steps=e.steps,this.terminated=e.terminated,this.ready=!0;let t=this.observations();return this.agentCount=t.length,{observations:t,rewards:t.map(()=>0),terminated:this.terminated,truncated:this.truncated}}observations(){let e=structuredClone(Array.from(this.rules.observe(this.state)));if(!e.length||e.length>4096)throw RangeError(`training requires 1..4096 agents`);for(let t of e)if(!t.input.length||t.input.length>4096||!Array.from(t.input).every(Number.isFinite)||t.mask&&(!t.mask.length||t.mask.length>4096||!Array.from(t.mask).every(e=>typeof e==`boolean`)))throw TypeError(`invalid training observation`);return e}};function jJ(e,t,n){return MJ(n),NJ(e,t,n,{Generator:j,createNeuralEvaluator:DJ})}function MJ(e){let t=e.trajectoryLimit??0;if(!e.seeds.length||e.seeds.length>1e4||!Array.from(e.seeds).every(e=>Number.isInteger(e)&&e>=0&&e<=4294967295)||!Number.isInteger(t)||t<0||t*e.seeds.length>1e4)throw RangeError(`rollouts require 1..10000 uint32 seeds and at most 10000 stored transitions`)}function NJ(e,t,n,r){if(t.observationVersion!==e.observationVersion)throw TypeError(`model observation schema does not match environment`);let i=n.trajectoryLimit??0,a=r.createNeuralEvaluator(t);return Array.from(n.seeds,t=>{if(n.signal?.aborted)throw n.signal.reason;let o=new r.Generator((t^2654435769)>>>0),s=e.reset(t),c=s.rewards.map(()=>0),l=[],u=0;for(;!s.terminated&&!s.truncated;){if(n.signal?.aborted)throw n.signal.reason;let t=s.observations.map(e=>a.select(e,n.sample?()=>o.float():void 0)),r=e.step(t);for(let e=0;e<c.length;e++)if(c[e]+=r.rewards[e],!Number.isFinite(c[e]))throw RangeError(`training cumulative reward overflow`);l.length<i&&l.push({before:s,actions:t,after:r}),s=r,u++}return{seed:t,steps:u,rewards:c,terminated:s.terminated,truncated:s.truncated,trajectory:l}})}function PJ(e,t,n,r){let i=Function(`return (${e[0]});`)(),a=Function(`return (${e[1]});`)(),o=Function(`return (${e[2]});`)(),s=class extends o{constructor(e,t){super(e,t,i)}};return Function(`return (${e[3]});`)()(Function(`return (${e[4]});`)()({TrainingEnvironment:s},t),n,r,{Generator:i,createNeuralEvaluator:a})}async function FJ(e,t,n,r){let i=r.jobs??4;if(!Number.isInteger(i)||i<1||i>64)throw RangeError(`rollout jobs must be in 1..64`);if(r.signal?.aborted)throw r.signal.reason;let a=r.trajectoryLimit??0;MJ(r),DJ(n);let o=new AbortController,s=()=>o.abort(r.signal?.reason);r.signal?.addEventListener(`abort`,s,{once:!0});let c=[j.toString(),DJ.toString(),AJ.toString(),NJ.toString(),e.toString()],l=Math.min(i,r.seeds.length);try{return(await Promise.all(Array.from({length:l},(e,i)=>{let s=Math.floor(i*r.seeds.length/l),u=Math.floor((i+1)*r.seeds.length/l),d=r.seeds.slice(s,u);return OU(PJ,[c,t,n,{seeds:d,sample:r.sample,trajectoryLimit:a}],{signal:o.signal,timeout:r.timeout})}))).flat()}finally{o.abort(),r.signal?.removeEventListener(`abort`,s)}}function IJ(e,t){let n=[...t.actions];if(!n.length||n.some(e=>typeof e!=`string`))throw TypeError(`imitation needs the recorded action names in policy order`);let r=fn(t.events),i=e.reset(t.seed);if(i.observations.length!==1)throw Error(`imitation trains the recorded player alone: the environment must expose one agent`);let a=[],o=i,s=0;for(let t of r){if(o.terminated||o.truncated)break;let r=n.indexOf(t.action);if(r<0)throw Error(`a recorded action ${JSON.stringify(t.action)} is not in the action list`);a.push({observation:o.observations[0],action:r,frame:t.frame}),o=e.step([r]),s++}return{samples:a,steps:s,terminated:o.terminated,truncated:o.truncated}}function LJ(e,t,n){let r=e.reset(n.seed),i=r.rewards.map(()=>0),a=[],o=0;for(;!r.terminated&&!r.truncated;){let n=t(r.observations);if(!Array.isArray(n)||n.length!==r.observations.length)throw RangeError(`the seeded-run chooser must return one action per agent`);a.push([...n]);let s=e.step(n);for(let e=0;e<i.length;e++)if(i[e]+=s.rewards[e],!Number.isFinite(i[e]))throw RangeError(`seeded-run cumulative reward overflow`);r=s,o++}return{seed:n.seed,steps:o,actions:a,rewards:i,terminated:r.terminated,truncated:r.truncated}}function RJ(e){let t=e.state,n=e.status??`ready`,r=[],i=0;for(let a of e.commands){if(n===`finished`)break;let o=e.step(t,a,e.random);t=o.state,n=o.status;for(let e of o.events)r.push(e);i++}return{state:t,events:r,status:n,processedCommands:i}}var zJ=class e{constructor(e){if(this._reminders=[],this._results={},this.levels=new Map(e.levels.map(e=>[e.id,e])),this.levels.size!==e.levels.length)throw Error(`campaign level ids must be unique`);if(!this.levels.has(e.start))throw Error(`unknown campaign start level: ${e.start}`);this._currentLevel=e.start,this._state=Ht(e.state,`campaign state`)}get currentLevel(){return this._currentLevel}get state(){return structuredClone(this._state)}get reminders(){return[...this._reminders]}get results(){return structuredClone(this._results)}playCurrent(){if(!this._currentLevel)throw Error(`campaign has no current level`);let e=this.levels.get(this._currentLevel);return this.completeCurrent(e.run(this.state,{levelId:e.id}))}completeCurrent(e){if(!this._currentLevel)throw Error(`campaign has no current level`);let t=this._currentLevel,n=Ht(e.state,`level result state`),r=e.result===void 0?void 0:Ht(e.result,`level result`);if(this._state=n,r!==void 0&&(this._results[t]=r),this._reminders=[...e.reminders??[]],e.outcome!==`completed`)this._currentLevel=null;else if(e.next===void 0)throw Error(`campaign level ${t} did not choose a next level`);else{if(e.next!==null&&!this.levels.has(e.next))throw Error(`unknown campaign transition: ${t} -> ${e.next}`);this._currentLevel=e.next}return{...e,state:this.state}}snapshot(){return{currentLevel:this._currentLevel,state:this.state,reminders:this.reminders,results:this.results}}static restore(t,n){let r=t.currentLevel??n.levels[0]?.id;if(!r)throw Error(`campaign restore requires at least one level`);let i=new e({levels:n.levels,start:r,state:t.state});return i._currentLevel=t.currentLevel,i._reminders=[...t.reminders],i._results=Ht(t.results,`snapshot.results`),i}};_e();function BJ(e){let t=new j(e.seed);return{...RJ({state:Ht(e.initialState,`initialState`),commands:e.commands,status:e.status,random:t,step:e.step}),seed:e.seed,random:t.getState()}}_e();function VJ(e,t,n){let r=HJ.restore({...e,journal:[]},n),i=e=>({valid:!1,checked:e.index,state:r.state,journal:r.journal.toJSON(),mismatch:e});for(let e=0;e<t.length;e++){let n=t[e];if(n.sequence!==e)return i({index:e,action:n.action,expectedEvents:n.events,actualEvents:[],reason:`sequence`});let a;try{a=r.dispatch(n.action)}catch(t){return i({index:e,action:n.action,expectedEvents:n.events,actualEvents:[],reason:`execution`,error:t instanceof Error?t.message:String(t)})}if(Ir(a.events)!==Ir(n.events))return i({index:e,action:n.action,expectedEvents:n.events,actualEvents:a.events,reason:`events`})}return n.expectedFinalState!==void 0&&Ir(r.state)!==Ir(n.expectedFinalState)?i({index:t.length,action:t.at(-1)?.action,expectedEvents:[],actualEvents:[],reason:`final-state`}):{valid:!0,checked:t.length,state:r.state,journal:r.journal.toJSON()}}var HJ=class e{constructor(e){this._state=e.state,this._scheduler=e.scheduler,this.random=e.random,this.rule=e.rule,this.actorId=e.actorId,this.recordJournal=e.journal!==null,this.journal=e.journal??new Cn,this.actorOf=e.history?.actorOf??null,this.history=e.history?new Er(e.history):null,this.history&&this.history.push(this.historySnapshot())}get scheduler(){return this._scheduler}get state(){return this._state}dispatch(e){let t=this.random.getState(),n=this.rule(this._state,e,{random:this.random,scheduler:this._scheduler}),r;try{r=this.history?Ht(n.state,`state`):null,this.recordJournal&&this.journal.append(e,n.events)}catch(e){throw this.random.setState(t),e}return this._state=n.state,n.cost!=null&&this._scheduler.spend(n.cost),this.history&&this.history.push(this.historySnapshot(r)),n}get canUndo(){return this.history?.canUndo??!1}get canRedo(){return this.history?.canRedo??!1}undo(){if(!this.history||!this.actorOf)return null;let e=this.history.undo();return e?(this.restoreCheckpoint(e),this.snapshot()):null}redo(){if(!this.history||!this.actorOf)return null;let e=this.history.redo();return e?(this.restoreCheckpoint(e),this.snapshot()):null}snapshot(e=1){return{version:e,state:this._state,scheduler:this.scheduler.toJSON(this.actorId),random:this.random.getState(),journal:this.journal.toJSON()}}static restore(t,n){let r=n.random??new j;r.setState(t.random);let i=hB.restore(t.scheduler,n.actorOf);return new e({state:t.state,scheduler:i,random:r,journal:Cn.fromJSON(t.journal??[]),rule:n.rule,actorId:n.actorId})}historySnapshot(e=Ht(this._state,`state`)){return{...this.snapshot(),state:e}}restoreCheckpoint(e){if(!this.actorOf)throw Error(`simulation history needs actorOf to restore a checkpoint`);this._state=structuredClone(e.state),this._scheduler=hB.restore(e.scheduler,this.actorOf),this.random.setState(e.random),this.journal.replace(e.journal??[])}},UJ=class e{constructor(e){this.followUps=[],this.runtime=e.runtime,this.queue=new Mr({play:e.play}),this.followUpOf=e.followUp}get locked(){return this.queue.isBusy}submit(e){return this.locked?null:this.commit(e)}update(e){this.queue.update(e),this.drainFollowUps()}cancel(){this.queue.clear(),this.followUps=[]}snapshot(e=1){return this.runtime.snapshot(e)}static restore(t,n){let r=HJ.restore(t,{rule:n.rule,actorOf:n.actorOf,actorId:n.actorId});return new e({runtime:r,play:n.play,followUp:n.followUp})}commit(e){let t=this.runtime.dispatch(e);return this.queue.enqueue(t.events),this.followUpOf&&this.followUps.push(...this.followUpOf(t)),this.drainFollowUps(),t}drainFollowUps(){for(;!this.queue.isBusy&&this.followUps.length>0;){let e=this.followUps.shift();this.commit(e)}}},WJ=class{constructor(e){this.saves=new Rt(e)}save(e,t,n){this.saves.save(e,{campaign:t.campaign.snapshot(),world:t.world,simulation:t.simulation?t.simulation.snapshot():null},n)}load(e){return this.saves.load(e)?.state??null}list(){return this.saves.list()}delete(e){this.saves.delete(e)}},GJ=l({Campaign:()=>zJ,CampaignSave:()=>WJ,EventPresentation:()=>UJ,Scheduler:()=>hB,SimulationRuntime:()=>HJ,TrainingEnvironment:()=>AJ,advanceToInput:()=>EJ,imitationFromReplay:()=>IJ,runHeadlessScenario:()=>BJ,runRollouts:()=>jJ,runRolloutsAsync:()=>FJ,runScenario:()=>RJ,runSeededEpisode:()=>LJ,validateSimulationReplay:()=>VJ}),KJ=d(c(((e,t)=>{(function(n,r){typeof e==`object`&&t!==void 0?t.exports=r():typeof define==`function`&&define.amd?define(r):n.JSON5=r()})(e,(function(){"use strict";function e(e,t){return t={exports:{}},e(t,t.exports),t.exports}var t=e(function(e){var t=e.exports=typeof window<`u`&&window.Math==Math?window:typeof self<`u`&&self.Math==Math?self:Function(`return this`)();typeof __g==`number`&&(__g=t)}),n=e(function(e){var t=e.exports={version:`2.6.5`};typeof __e==`number`&&(__e=t)});n.version;var r=function(e){return typeof e==`object`?e!==null:typeof e==`function`},i=function(e){if(!r(e))throw TypeError(e+` is not an object!`);return e},a=function(e){try{return!!e()}catch{return!0}},o=!a(function(){return Object.defineProperty({},"a",{get:function(){return 7}}).a!=7}),s=t.document,c=r(s)&&r(s.createElement),l=function(e){return c?s.createElement(e):{}},u=!o&&!a(function(){return Object.defineProperty(l(`div`),"a",{get:function(){return 7}}).a!=7}),d=function(e,t){if(!r(e))return e;var n,i;if(t&&typeof(n=e.toString)==`function`&&!r(i=n.call(e))||typeof(n=e.valueOf)==`function`&&!r(i=n.call(e))||!t&&typeof(n=e.toString)==`function`&&!r(i=n.call(e)))return i;throw TypeError(`Can't convert object to primitive value`)},f=Object.defineProperty,p={f:o?Object.defineProperty:function(e,t,n){if(i(e),t=d(t,!0),i(n),u)try{return f(e,t,n)}catch{}if(`get`in n||`set`in n)throw TypeError(`Accessors not supported!`);return`value`in n&&(e[t]=n.value),e}},m=function(e,t){return{enumerable:!(e&1),configurable:!(e&2),writable:!(e&4),value:t}},h=o?function(e,t,n){return p.f(e,t,m(1,n))}:function(e,t,n){return e[t]=n,e},g={}.hasOwnProperty,_=function(e,t){return g.call(e,t)},v=0,y=Math.random(),b=function(e){return`Symbol(${e===void 0?``:e})_${(++v+y).toString(36)}`},x=e(function(e){var r=`__core-js_shared__`,i=t[r]||(t[r]={});(e.exports=function(e,t){return i[e]||(i[e]=t===void 0?{}:t)})(`versions`,[]).push({version:n.version,mode:`global`,copyright:`© 2019 Denis Pushkarev (zloirock.ru)`})})(`native-function-to-string`,Function.toString),S=e(function(e){var r=b(`src`),i=`toString`,a=(``+x).split(i);n.inspectSource=function(e){return x.call(e)},(e.exports=function(e,n,i,o){var s=typeof i==`function`;s&&(_(i,`name`)||h(i,`name`,n)),e[n]!==i&&(s&&(_(i,r)||h(i,r,e[n]?``+e[n]:a.join(String(n)))),e===t?e[n]=i:o?e[n]?e[n]=i:h(e,n,i):(delete e[n],h(e,n,i)))})(Function.prototype,i,function(){return typeof this==`function`&&this[r]||x.call(this)})}),C=function(e){if(typeof e!=`function`)throw TypeError(e+` is not a function!`);return e},ee=function(e,t,n){if(C(e),t===void 0)return e;switch(n){case 1:return function(n){return e.call(t,n)};case 2:return function(n,r){return e.call(t,n,r)};case 3:return function(n,r,i){return e.call(t,n,r,i)}}return function(){return e.apply(t,arguments)}},w=`prototype`,T=function(e,r,i){var a=e&T.F,o=e&T.G,s=e&T.S,c=e&T.P,l=e&T.B,u=o?t:s?t[r]||(t[r]={}):(t[r]||{})[w],d=o?n:n[r]||(n[r]={}),f=d[w]||(d[w]={}),p,m,g,_;for(p in o&&(i=r),i)m=!a&&u&&u[p]!==void 0,g=(m?u:i)[p],_=l&&m?ee(g,t):c&&typeof g==`function`?ee(Function.call,g):g,u&&S(u,p,g,e&T.U),d[p]!=g&&h(d,p,_),c&&f[p]!=g&&(f[p]=g)};t.core=n,T.F=1,T.G=2,T.S=4,T.P=8,T.B=16,T.W=32,T.U=64,T.R=128;var E=T,D=Math.ceil,O=Math.floor,te=function(e){return isNaN(e=+e)?0:(e>0?O:D)(e)},ne=function(e){if(e==null)throw TypeError(`Can't call method on `+e);return e},k=function(e){return function(t,n){var r=String(ne(t)),i=te(n),a=r.length,o,s;return i<0||i>=a?e?``:void 0:(o=r.charCodeAt(i),o<55296||o>56319||i+1===a||(s=r.charCodeAt(i+1))<56320||s>57343?e?r.charAt(i):o:e?r.slice(i,i+2):(o-55296<<10)+(s-56320)+65536)}}(!1);E(E.P,`String`,{codePointAt:function(e){return k(this,e)}}),n.String.codePointAt;var A=Math.max,re=Math.min,ie=function(e,t){return e=te(e),e<0?A(e+t,0):re(e,t)},ae=String.fromCharCode,oe=String.fromCodePoint;E(E.S+E.F*(!!oe&&oe.length!=1),`String`,{fromCodePoint:function(e){for(var t=arguments,n=[],r=arguments.length,i=0,a;r>i;){if(a=+t[i++],ie(a,1114111)!==a)throw RangeError(a+` is not a valid code point`);n.push(a<65536?ae(a):ae(((a-=65536)>>10)+55296,a%1024+56320))}return n.join(``)}}),n.String.fromCodePoint;var se={Space_Separator:/[\u1680\u2000-\u200A\u202F\u205F\u3000]/,ID_Start:/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/,ID_Continue:/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/},j={isSpaceSeparator:function(e){return typeof e==`string`&&se.Space_Separator.test(e)},isIdStartChar:function(e){return typeof e==`string`&&(e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`||e===`$`||e===`_`||se.ID_Start.test(e))},isIdContinueChar:function(e){return typeof e==`string`&&(e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`||e>=`0`&&e<=`9`||e===`$`||e===`_`||e===`‌`||e===`‍`||se.ID_Continue.test(e))},isDigit:function(e){return typeof e==`string`&&/[0-9]/.test(e)},isHexDigit:function(e){return typeof e==`string`&&/[0-9A-Fa-f]/.test(e)}},ce,le,ue,de,fe,pe,me,he,ge,_e=function(e,t){ce=String(e),le=`start`,ue=[],de=0,fe=1,pe=0,me=void 0,he=void 0,ge=void 0;do me=xe(),ke[le]();while(me.type!==`eof`);return typeof t==`function`?ve({"":ge},``,t):ge};function ve(e,t,n){var r=e[t];if(typeof r==`object`&&r){if(Array.isArray(r))for(var i=0;i<r.length;i++){var a=String(i),o=ve(r,a,n);o===void 0?delete r[a]:Object.defineProperty(r,a,{value:o,writable:!0,enumerable:!0,configurable:!0})}else for(var s in r){var c=ve(r,s,n);c===void 0?delete r[s]:Object.defineProperty(r,s,{value:c,writable:!0,enumerable:!0,configurable:!0})}}return n.call(e,t,r)}var M,N,ye,be,P;function xe(){for(M=`default`,N=``,ye=!1,be=1;;){P=Se();var e=Ce[M]();if(e)return e}}function Se(){if(ce[de])return String.fromCodePoint(ce.codePointAt(de))}function F(){var e=Se();return e===`
1387
1387
  `?(fe++,pe=0):e?pe+=e.length:pe++,e&&(de+=e.length),e}var Ce={default:function(){switch(P){case` `:case`\v`:case`\f`:case` `:case`\xA0`:case``:case`
1388
1388
  `:case`\r`:case`\u2028`:case`\u2029`:F();return;case`/`:F(),M=`comment`;return;case void 0:return F(),we(`eof`)}if(j.isSpaceSeparator(P)){F();return}return Ce[le]()},comment:function(){switch(P){case`*`:F(),M=`multiLineComment`;return;case`/`:F(),M=`singleLineComment`;return}throw Me(F())},multiLineComment:function(){switch(P){case`*`:F(),M=`multiLineCommentAsterisk`;return;case void 0:throw Me(F())}F()},multiLineCommentAsterisk:function(){switch(P){case`*`:F();return;case`/`:F(),M=`default`;return;case void 0:throw Me(F())}F(),M=`multiLineComment`},singleLineComment:function(){switch(P){case`
1389
1389
  `:case`\r`:case`\u2028`:case`\u2029`:F(),M=`default`;return;case void 0:return F(),we(`eof`)}F()},value:function(){switch(P){case`{`:case`[`:return we(`punctuator`,F());case`n`:return F(),Te(`ull`),we(`null`,null);case`t`:return F(),Te(`rue`),we(`boolean`,!0);case`f`:return F(),Te(`alse`),we(`boolean`,!1);case`-`:case`+`:F()===`-`&&(be=-1),M=`sign`;return;case`.`:N=F(),M=`decimalPointLeading`;return;case`0`:N=F(),M=`zero`;return;case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:N=F(),M=`decimalInteger`;return;case`I`:return F(),Te(`nfinity`),we(`numeric`,1/0);case`N`:return F(),Te(`aN`),we(`numeric`,NaN);case`"`:case`'`:ye=F()===`"`,N=``,M=`string`;return}throw Me(F())},identifierNameStartEscape:function(){if(P!==`u`)throw Me(F());F();var e=Oe();switch(e){case`$`:case`_`:break;default:if(!j.isIdStartChar(e))throw Pe()}N+=e,M=`identifierName`},identifierName:function(){switch(P){case`$`:case`_`:case`‌`:case`‍`:N+=F();return;case`\\`:F(),M=`identifierNameEscape`;return}if(j.isIdContinueChar(P)){N+=F();return}return we(`identifier`,N)},identifierNameEscape:function(){if(P!==`u`)throw Me(F());F();var e=Oe();switch(e){case`$`:case`_`:case`‌`:case`‍`:break;default:if(!j.isIdContinueChar(e))throw Pe()}N+=e,M=`identifierName`},sign:function(){switch(P){case`.`:N=F(),M=`decimalPointLeading`;return;case`0`:N=F(),M=`zero`;return;case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:N=F(),M=`decimalInteger`;return;case`I`:return F(),Te(`nfinity`),we(`numeric`,be*(1/0));case`N`:return F(),Te(`aN`),we(`numeric`,NaN)}throw Me(F())},zero:function(){switch(P){case`.`:N+=F(),M=`decimalPoint`;return;case`e`:case`E`:N+=F(),M=`decimalExponent`;return;case`x`:case`X`:N+=F(),M=`hexadecimal`;return}return we(`numeric`,be*0)},decimalInteger:function(){switch(P){case`.`:N+=F(),M=`decimalPoint`;return;case`e`:case`E`:N+=F(),M=`decimalExponent`;return}if(j.isDigit(P)){N+=F();return}return we(`numeric`,be*Number(N))},decimalPointLeading:function(){if(j.isDigit(P)){N+=F(),M=`decimalFraction`;return}throw Me(F())},decimalPoint:function(){switch(P){case`e`:case`E`:N+=F(),M=`decimalExponent`;return}if(j.isDigit(P)){N+=F(),M=`decimalFraction`;return}return we(`numeric`,be*Number(N))},decimalFraction:function(){switch(P){case`e`:case`E`:N+=F(),M=`decimalExponent`;return}if(j.isDigit(P)){N+=F();return}return we(`numeric`,be*Number(N))},decimalExponent:function(){switch(P){case`+`:case`-`:N+=F(),M=`decimalExponentSign`;return}if(j.isDigit(P)){N+=F(),M=`decimalExponentInteger`;return}throw Me(F())},decimalExponentSign:function(){if(j.isDigit(P)){N+=F(),M=`decimalExponentInteger`;return}throw Me(F())},decimalExponentInteger:function(){if(j.isDigit(P)){N+=F();return}return we(`numeric`,be*Number(N))},hexadecimal:function(){if(j.isHexDigit(P)){N+=F(),M=`hexadecimalInteger`;return}throw Me(F())},hexadecimalInteger:function(){if(j.isHexDigit(P)){N+=F();return}return we(`numeric`,be*Number(N))},string:function(){switch(P){case`\\`:F(),N+=Ee();return;case`"`:if(ye)return F(),we(`string`,N);N+=F();return;case`'`:if(!ye)return F(),we(`string`,N);N+=F();return;case`
@@ -1396,12 +1396,12 @@ fn mainFragment(
1396
1396
  `+t+`}`}}return r.pop(),i=t,m}function g(e){if(e.length===0)return m(e,!0);var t=String.fromCodePoint(e.codePointAt(0));if(!j.isIdStartChar(t))return m(e,!0);for(var n=t.length;n<e.length;n++)if(!j.isIdContinueChar(String.fromCodePoint(e.codePointAt(n))))return m(e,!0);return e}function _(e){if(r.indexOf(e)>=0)throw TypeError(`Converting circular structure to JSON5`);r.push(e);var t=i;i+=s;for(var n=[],a=0;a<e.length;a++){var o=p(String(a),e);n.push(o===void 0?`null`:o)}var c;if(n.length===0)c=`[]`;else if(s===``)c=`[`+n.join(`,`)+`]`;else{var l=`,
1397
1397
  `+i,u=n.join(l);c=`[
1398
1398
  `+i+u+`,
1399
- `+t+`]`}return r.pop(),i=t,c}}}}))}))(),1),WJ=class extends Error{constructor(e){super(`${e.location.file}:${e.location.line}:${e.location.column}: ${e.message}`),this.name=`MwlSyntaxError`,this.diagnostic=e}},GJ=new Set([`define`,`enddef`,`arg`,`ifdef`,`ifndef`,`else`,`endif`,`include`]);function KJ(e,t={}){let n=new Map,r=new Set(t.defines??[]),i=e.split(/\r?\n/),a=[],o=[!0],s=null;for(let e=0;e<i.length;e++){let c=i[e],l=/^\s*#([A-Za-z_][\w-]*)(?:\s+(.*))?$/.exec(c);if(l&&GJ.has(l[1])){let i=l[1],u=l[2]?.trim()??``;if(i===`define`){if(!o.at(-1)||s)continue;let n=fY(u);if(n.length===0)throw mY(`MWL_DEFINE`,`macro name is required`,t.file,e,c);s={name:n[0],parameters:n.slice(1),body:[]},r.add(n[0]);continue}if(i===`arg`){s&&u&&s.parameters.push(u.split(/\s+/)[0]);continue}if(i===`enddef`){if(!s)throw mY(`MWL_ENDDEF`,`unexpected #enddef`,t.file,e,c);n.set(s.name,{name:s.name,parameters:s.parameters,body:s.body.join(`
1400
- `)}),s=null;continue}if(i===`ifdef`||i===`ifndef`){let e=r.has(u);o.push(o.at(-1)===!0&&(i===`ifdef`?e:!e));continue}if(i===`else`){if(o.length<2)throw mY(`MWL_ELSE`,`unexpected #else`,t.file,e,c);o[o.length-1]=o[o.length-2]&&!o.at(-1);continue}if(i===`endif`){if(o.length<2)throw mY(`MWL_ENDIF`,`unexpected #endif`,t.file,e,c);o.pop();continue}if(i===`include`){if(o.at(-1)){let n=t.includes?.[pY(u)];if(n===void 0)throw mY(`MWL_INCLUDE`,`include not supplied: ${u}`,t.file,e,c);a.push(KJ(n,t))}continue}}if(s){o.at(-1)&&s.body.push(c);continue}o.at(-1)&&!/^\s*#/.test(c)&&a.push(c)}if(s)throw mY(`MWL_ENDDEF`,`macro ${s.name} is missing #enddef`,t.file,i.length-1,i.at(-1)??``);if(o.length!==1)throw mY(`MWL_ENDIF`,`conditional is missing #endif`,t.file,i.length-1,i.at(-1)??``);return YJ(qJ(a.join(`
1401
- `),n,t))}function qJ(e,t,n){let r=``,i=0;for(;i<e.length;){let a=ZJ(e,i);if(a!==i){r+=e.slice(i,a),i=a;continue}let o=e[i];if(o!==`{`){r+=o,i++;continue}let s=e.indexOf(`}`,i+1);if(s<0){r+=o,i++;continue}let c=e.slice(i,s+1),l=fY(e.slice(i+1,s)),u=t.get(l[0]);if(u){let e=u.body;for(let t=0;t<u.parameters.length;t++){let n=u.parameters[t],r=l.find(e=>e.startsWith(`${n}=`)),i=r?r.slice(n.length+1):l[t+1]??``;e=e.replaceAll(`{${n}}`,i)}r+=qJ(e,t,n)}else if(n.macroPolicy!==`ignore`&&JJ(l[0]))throw hY(`MWL_MACRO`,`unknown macro "${l[0]}"`,e,n.file,i);else r+=c;i=s+1}return r}function JJ(e){return e!==void 0&&aY.test(e)}function YJ(e){let t=/^_\(\s*("(?:[^"\\]|\\[\s\S])*"|'(?:[^'\\]|\\[\s\S])*')\s*\)/,n=``,r=0;for(;r<e.length;){let i=ZJ(e,r);if(i!==r){n+=e.slice(r,i),r=i;continue}let a=e[r];if(a===`_`){let i=t.exec(e.slice(r));if(i){n+=`{"$gettext": ${i[1]}}`,r+=i[0].length;continue}}n+=a,r++}return n}function XJ(e,t){let n=e[t],r=t+1;for(;r<e.length;){let t=e[r];if(t===`\\`){r+=2;continue}if(t===n)return r+1;if(t===`
1402
- `)return r;r++}return r}function ZJ(e,t){let n=e[t];if(n===`"`||n===`'`)return XJ(e,t);let r=e[t+1];if(n===`/`&&(r===`/`||r===`*`)){let n=r===`/`?e.indexOf(`
1403
- `,t):e.indexOf(`*/`,t+2);return n<0?e.length:r===`/`?n:n+2}return t}function QJ(e,t=`<mwl>`){let n=YJ(e);if(n.trim()===``)return[];let r;try{r=UJ.default.parse(n)}catch(e){throw lY(e,n,t)}if(r===void 0)return[];if(!Array.isArray(r))throw new WJ({code:`MWL_DOCUMENT`,message:`MWL document must be a top-level array of nodes`,location:{file:t,line:1,column:1},lineText:n.split(/\r?\n/)[0]??``});let i={file:t,sites:oY(n,t),cursor:{index:0},parent:void 0};return $J(r).map(e=>rY(e,i))}function $J(e){let t=[];for(let n of e){let e=eY(n);Array.isArray(e)?t.push(...e):t.push(e)}return t}function eY(e){if(Array.isArray(e))return e.flatMap(e=>eY(e));if(typeof e!=`object`||!e)return e;let t=e;if(typeof t.tag!=`string`){let n=Object.keys(t);if(n.length!==1||!aY.test(n[0]))return e;let r=n[0],i=t[r];return Array.isArray(i)?i.map(e=>tY(r,e)):tY(r,i)}let n={...t},r=[];Array.isArray(t.children)&&r.push(...t.children.flatMap(e=>eY(e)));for(let[e,i]of Object.entries(t)){if(e===`tag`||e===`children`||!aY.test(e)||!nY(i))continue;let t=Array.isArray(i)?i:[i];r.push(...t.map(t=>tY(e,t))),delete n[e]}return r.length&&(n.children=r),n}function tY(e,t){return typeof t!=`object`||!t||Array.isArray(t)?{tag:e,value:t}:eY({tag:e,...t})}function nY(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(`$gettext`in e)||Array.isArray(e)&&e.every(e=>typeof e==`object`&&!!e&&!Array.isArray(e))}function rY(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw new WJ({code:`MWL_TAG`,message:`MWL node must be an object with a tag`,location:t.parent??{file:t.file,line:1,column:1}});let n=e;if(typeof n.tag!=`string`||!aY.test(n.tag))throw new WJ({code:`MWL_TAG`,message:`MWL node needs a tag name`,location:t.parent??{file:t.file,line:1,column:1}});let r=n.tag,i=sY(t,r),a=i.location,o=n.children??[];if(!Array.isArray(o))throw new WJ({code:`MWL_TAG`,message:`children of [${r}] must be an array`,location:a});let s={},c={},l={},u=[];for(let[e,t]of Object.entries(n)){if(e===`tag`||e===`children`)continue;s[e]=iY(r,e,t,a,u);let n=i.properties?.get(e);n&&(c[e]=n.location,l[e]=n.valueLocation)}let d={...t,parent:a},f={tag:r,attributes:s,children:o.map(e=>rY(e,d)),location:a,gettext:u};return Object.defineProperties(f,{attributeLocations:{value:c,enumerable:!1},valueLocations:{value:l,enumerable:!1}}),f}function iY(e,t,n,r,i){if(!aY.test(t)||t.startsWith(`$`)||t.startsWith(`_`))throw new WJ({code:`MWL_ATTRIBUTE`,message:`unknown attribute "${t}" on [${e}]`,location:r});if(typeof n==`string`)return n;if(typeof n==`number`&&Number.isFinite(n))return String(n);if(typeof n==`boolean`)return n?`true`:`false`;if(typeof n==`object`&&n&&!Array.isArray(n)){let e=Object.keys(n),r=n.$gettext;if(e.length===1&&e[0]===`$gettext`&&typeof r==`string`)return i.push(t),r}throw new WJ({code:`MWL_ATTRIBUTE`,message:`attribute "${t}" on [${e}] must be a string, number, boolean, or _("...")`,location:r})}var aY=/^[A-Za-z_][\w-]*$/;function oY(e,t){let n=[],r=[];for(let i=0;i<e.length;){let a=ZJ(e,i);if(a!==i){i=a;continue}let o=e[i];if(o===`{`){let e={start:i,properties:new Map};r.push(e),i++;continue}if(o===`}`){r.pop(),i++;continue}let s=/[A-Za-z_$][\w$-]*/y;s.lastIndex=i;let c=s.exec(e);if(!c){i++;continue}let l=c.index+c[0].length;for(;/\s/.test(e[l]??``);)l++;if(e[l]!==`:`){i=c.index+c[0].length;continue}let u=l+1;for(;/\s/.test(e[u]??``);)u++;let d=r.at(-1);if(d&&(d.properties.set(c[0],{location:cY(e,t,c.index),valueLocation:cY(e,t,u)}),c[0]===`tag`&&(e[u]===`"`||e[u]===`'`))){let r=XJ(e,u),i=e.slice(u,r),a;try{a=UJ.default.parse(i)}catch{a=void 0}typeof a==`string`&&n.push({tag:a,location:cY(e,t,c.index),properties:d.properties})}i=c.index+c[0].length}return n}function sY(e,t){for(let n=e.cursor.index;n<e.sites.length;n++)if(e.sites[n].tag===t)return e.cursor.index=n+1,e.sites[n];return{tag:t,location:e.parent??{file:e.file,line:1,column:1}}}function cY(e,t,n){let r=1,i=1;for(let t=0;t<n;t++)e[t]===`
1404
- `?(r++,i=1):i++;return{file:t,line:r,column:i}}function lY(e,t,n){let r=t.split(/\r?\n/),i=e,a=typeof i?.lineNumber==`number`?i.lineNumber:1,o=typeof i?.columnNumber==`number`?i.columnNumber:1,s=e instanceof Error?e.message:String(e);return s.includes(`'_'`)&&(s+=` (write translatable text as _("..."))`),new WJ({code:`MWL_SYNTAX`,message:s,location:{file:n,line:Math.max(1,a),column:Math.max(1,o)},lineText:r[Math.max(1,a)-1]})}function uY(e,t,n=e){let r=e.trim(),i=/^_\(\s*([\s\S]*?)\s*\)$/.exec(r),a=i?i[1]:r;if(a.startsWith(`"`)||a.startsWith(`'`)){try{let e=UJ.default.parse(a);if(typeof e==`string`)return e}catch{}throw new WJ({code:`MWL_STRING`,message:`unterminated string value`,location:t,lineText:n})}if(i)throw new WJ({code:`MWL_STRING`,message:`_("...") needs a quoted string`,location:t,lineText:n});return r}function dY(e){return/^_\(\s*["']/.test(e.trim())}function fY(e){let t=[],n=``,r=!1;for(let i=0;i<e.length;i++){let a=e[i];a===`"`&&(r=!r),/\s/.test(a)&&!r?(n&&t.push(n),n=``):n+=a}return n&&t.push(n),t}function pY(e){return e.startsWith(`"`)&&e.endsWith(`"`)?e.slice(1,-1):e}function mY(e,t,n,r,i){return new WJ({code:e,message:t,location:{file:n??`<mwl>`,line:r+1,column:1},lineText:i})}function hY(e,t,n,r,i){let a=cY(n,r??`<mwl>`,i);return new WJ({code:e,message:t,location:a,lineText:n.split(/\r?\n/)[a.line-1]})}function gY(e,t,n,r){if(!Number.isInteger(t.version)||t.version<1)throw Error(`MWL save version must be a positive integer`);let i={format:`mwl-save`,version:t.version,world:e,...n===void 0?{}:{hookState:xY(n)},...r===void 0?{}:{journal:SY(r)}};return JSON.stringify(i)}function _Y(e,t){return vY(e,t).world}function vY(e,t){let n=JSON.parse(e),r=bY(n)?n:{format:`mwl-save`,version:1,world:n};if(r.version>t.version)throw Error(`MWL save version ${r.version} is newer than supported version ${t.version}`);let i=yY(r.world);for(let e=r.version;e<t.version;e++){let n=t.migrations?.[e+1];if(!n)throw Error(`missing MWL save migration to version ${e+1}`);i=yY(n(i))}return{format:`mwl-save`,version:t.version,world:i,...r.hookState===void 0?{}:{hookState:xY(r.hookState)},...r.journal===void 0?{}:{journal:SY(r.journal)}}}function yY(e){if(!e||typeof e!=`object`)throw Error(`invalid MWL saved world`);jt(e);let t=e;if(!Number.isInteger(t.turn)||!t.variables||typeof t.variables!=`object`||!t.units||typeof t.units!=`object`)throw Error(`invalid MWL saved world: turn, variables, and units are required`);if(t.status!==void 0&&![`playing`,`won`,`lost`].includes(t.status))throw Error(`invalid MWL saved world status`);return Ht(t,`saved world`)}function bY(e){return!!e&&typeof e==`object`&&e.format===`mwl-save`&&typeof e.version==`number`&&`world`in e}function xY(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`invalid MWL hook state`);jt(e);let t;try{t=JSON.stringify(e)}catch{throw Error(`MWL hook state must be JSON-serialisable`)}let n=JSON.parse(t);if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`invalid MWL hook state`);return n}function SY(e){try{let t=JSON.stringify(e),n=JSON.parse(t);if(!Array.isArray(n))throw Error();return jt(n),n}catch{throw Error(`MWL journal must be JSON-serialisable`)}}function CY(e,t,n={}){let r=e.search(/\s+where\s+/),i=r<0?e:e.slice(0,r),a={...t};if(r>=0)for(let t of e.slice(r).replace(/^\s+where\s+/,``).split(`,`)){let e=/^\s*([A-Za-z_][A-Za-z0-9_.-]*)\s*=\s*(.+)\s*$/.exec(t);if(!e)throw Error(`invalid MWL where binding: ${t}`);let r=new wY(e[2],a,n.helpers??{});if(a[e[1]]=r.parseOr(),!r.atEnd())throw Error(`invalid MWL where binding: ${t}`)}let o=new wY(i,a,n.helpers??{}),s=o.parseOr();if(!o.atEnd())throw Error(`unexpected token in MWL condition: ${o.peek()}`);return EY(s)}var wY=class{constructor(e,t,n){this.index=0,this.tokens=TY(e),this.context=t,this.helpers=n}parseOr(){let e=this.parseAnd();for(;this.take(`or`);)e=EY(e)||EY(this.parseAnd());return e}parseAnd(){let e=this.parseNot();for(;this.take(`and`);)e=EY(e)&&EY(this.parseNot());return e}parseNot(){return this.take(`not`)?!EY(this.parseNot()):this.parseComparison()}parseComparison(){let e=this.parseAdditive(),t=this.peek();if(![`==`,`~=`,`<`,`<=`,`>`,`>=`].includes(t))return e;this.index++;let n=this.parseAdditive();if(t===`==`)return e===n;if(t===`~=`)return e!==n;if(typeof e!=`number`||typeof n!=`number`)throw Error(`${t} requires numeric operands`);return t===`<`?e<n:t===`<=`?e<=n:t===`>`?e>n:e>=n}parseAdditive(){let e=this.parseMultiplicative();for(;this.peek()===`+`||this.peek()===`-`;){let t=this.tokens[this.index++],n=this.parseMultiplicative();if(typeof e!=`number`||typeof n!=`number`)throw Error(`${t} requires numeric operands`);e=t===`+`?e+n:e-n}return e}parseMultiplicative(){let e=this.parsePrimary();for(;this.peek()===`*`||this.peek()===`/`;){let t=this.tokens[this.index++],n=this.parsePrimary();if(typeof e!=`number`||typeof n!=`number`)throw Error(`${t} requires numeric operands`);if(t===`/`&&n===0)throw Error(`division by zero in MWL condition`);e=t===`*`?e*n:e/n}return e}parsePrimary(){if(this.take(`(`)){let e=this.parseOr();return this.expect(`)`),e}let e=this.tokens[this.index++];if(e===void 0)throw Error(`incomplete MWL condition`);if(/^-?(?:\d+(?:\.\d*)?|\.\d+)$/.test(e))return Number(e);if(e===`true`||e===`yes`)return!0;if(e===`false`||e===`no`)return!1;if(e.startsWith(`"`)||e.startsWith(`'`))return e.slice(1,-1);let t=this.helpers[e];if(t&&this.take(`(`)){let e=[];if(!this.take(`)`)){do e.push(this.parseOr());while(this.take(`,`));this.expect(`)`)}return t(...e)}let n=this.context[e];if(n===void 0)throw Error(`missing MWL condition variable "${e}"`);return n}take(e){return this.peek()===e&&(this.index++,!0)}expect(e){if(!this.take(e))throw Error(`expected "${e}" in MWL condition`)}peek(){return this.tokens[this.index]??`<end>`}atEnd(){return this.index>=this.tokens.length}};function TY(e){let t=[],n=/\s*(?:("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')|([A-Za-z_][A-Za-z0-9_.-]*)|(-?(?:\d+(?:\.\d*)?|\.\d+))|(==|~=|<=|>=|[()+*/,<>-]))/y,r=0;for(;r<e.length;){n.lastIndex=r;let i=n.exec(e);if(!i)throw Error(`invalid MWL condition near "${e.slice(r)}"`);t.push(i[1]??i[2]??i[3]??i[4]),r=n.lastIndex}return t}function EY(e){return e!==!1&&e!==0&&e!==``}function DY(e){let t=new NY(e),n=t.expression();if(t.skip(),!t.atEnd())throw Error(`invalid MWL expression near "${t.rest()}"`);return n}function OY(e,t){let n=typeof e==`string`?DY(e):e;if(n.kind===`number`)return n.value;if(n.kind===`variable`){let e=t[n.name];if(e===void 0||!Number.isFinite(e))throw Error(`missing MWL expression variable "${n.name}"`);return e}let r=OY(n.left,t),i=OY(n.right,t);if(n.op===`+`)return r+i;if(n.op===`-`)return r-i;if(n.op===`*`)return r*i;if(n.op===`/`){if(i===0)throw Error(`division by zero in MWL expression`);return r/i}return r**i}var kY=256,AY=4096,jY=/(?:\d+(?:\.\d*)?|\.\d+)/y,MY=/[A-Za-z_][A-Za-z0-9_.-]*/y,NY=class{constructor(e){this.index=0,this.depth=0,this.operators=0,this.source=e}expression(){return this.additive()}additive(){let e=this.multiplicative();for(;;){this.skip();let t=this.peek(`+`)?`+`:this.peek(`-`)?`-`:null;if(!t)return e;this.index++,this.operator(),e={kind:`binary`,op:t,left:e,right:this.multiplicative()}}}multiplicative(){let e=this.power();for(;;){this.skip();let t=this.peek(`*`)?`*`:this.peek(`/`)?`/`:null;if(!t)return e;this.index++,this.operator(),e={kind:`binary`,op:t,left:e,right:this.power()}}}power(){let e=this.primary();return this.skip(),this.peek(`^`)&&(this.index++,this.operator(),e={kind:`binary`,op:`^`,left:e,right:this.nested(()=>this.power())}),e}primary(){if(this.skip(),this.peek(`(`)){this.index++;let e=this.nested(()=>this.expression());if(this.skip(),!this.peek(`)`))throw Error(`missing closing parenthesis in MWL expression`);return this.index++,e}let e=this.match(jY);if(e)return this.index+=e[0].length,{kind:`number`,value:Number(e[0])};let t=this.match(MY);if(t)return this.index+=t[0].length,{kind:`variable`,name:t[0]};throw Error(`expected number, variable, or parenthesis near "${this.rest()}"`)}match(e){return e.lastIndex=this.index,e.exec(this.source)}nested(e){if(++this.depth>kY)throw Error(`MWL expression is nested more than ${kY} deep`);try{return e()}finally{this.depth--}}operator(){if(++this.operators>AY)throw Error(`MWL expression has more than ${AY} operators`)}peek(e){return this.source[this.index]===e}skip(){for(;/\s/.test(this.source[this.index]??``);)this.index++}atEnd(){return this.index>=this.source.length}rest(){let e=this.source.slice(this.index,this.index+40);return this.index+40<this.source.length?`${e}...`:e}};function PY(e){let t=[],n=e=>{t.push(e),e.children.forEach(n)};return e.forEach(n),t}function FY(e,t){let n=e.attributes[t];if(!n)throw Error(`MWL ${e.tag} is missing ${t}`);return n}function IY(e,t){let n=e.attributes[t];if(n===void 0)return;let r=Number(n);return Number.isFinite(r)?r:void 0}function LY(e,t,n){let r=e.attributes[t];if(r===void 0)return n;let i=Number.parseInt(r,10);return Number.isFinite(i)?i:n}function RY(e,t){return zY(e.attributes[t])}function zY(e){return e===void 0?void 0:e===`true`||e===`yes`}function BY(e,t){return e!==void 0&&t.includes(e)?e:void 0}function VY(e,t,n){let r=n.carryoverPercentage??80,i=t?e.gold[t.id]??e.sides[t.id]?.gold??0:0;return{result:n.result,gold:Math.floor(i*r/100)+(n.bonus??0),add:n.carryoverAdd??!1,recall:t?Object.entries(e.units).filter(([,e])=>e.alive&&e.side===t.id).map(([e])=>e).sort():[],nextScenario:n.nextScenario??null}}function HY(e,t){return e.add?t+e.gold:Math.max(t,e.gold)}_e();var UY=FY,WY=(e,t,n)=>LY(e,t,n)??n;function GY(){return{variables:{},units:{},sides:{},maps:{},gold:{},turn:1,status:`playing`,sideStatus:{},map:null,timeOfDay:``,scheduleIndex:0}}var KY=1048576;function qY(e){let t=e.split(/\r?\n/).filter(e=>e.trim()!==``).map(e=>e.split(`,`).map(e=>e.trim())),n=t.length,r=t.reduce((e,t)=>Math.max(e,t.length),0);if(r*n>KY)throw Error(`MWL terrain is ${r}x${n}, more than ${KY} cells`);let i=[],a={};for(let e=0;e<n;e++)for(let n=0;n<r;n++){let r=t[e]?.[n]??`_off^_usr`,o=/^([A-Za-z0-9_][\w.-]*)\s+(\S.*)$/.exec(r);o?(i.push(o[2]),(a[o[1]]??=[]).push({x:n,y:e})):i.push(r)}return{width:r,height:n,codes:i,starts:a}}var JY=/\$\(([^)]*)\)/g,YY=/\$([A-Za-z_][A-Za-z0-9_.]*)/g,XY=class e{constructor(e,t={}){this.journal=new Cn,this.unitTypes=new Map,this.schedule=[],this.pendingDialogue=null,this.dialogueCounter=0,this.traceBatch=null,this.game=e,this.world=t.world??GY(),this.onMessage=t.onMessage,this.resolveMap=t.resolveMap,this.hooks=t.hooks,this.onTrace=t.onTrace,this.persistence=t.persistence??{version:1},this.random=t.random??new j,!t.random&&this.world.random&&this.random.setState(this.world.random),this.loadUnitTypes(),this.loadSchedule(),this.loadInitialContent(),this.loadInitialUnits(),this.loadLeaders(),this.loadScenarioExtras()}run(e){this.recordAction({type:`run`,trigger:e},()=>this.runInternal(e))}runInternal(e){for(let t of this.nodes(`event`))(t.attributes.on??t.attributes.trigger)===e&&this.eventFiltersMatch(t)&&this.claimEvent(t)&&this.executeTracedEvent(t,e);this.checkObjectives()}fireEvent(e){return this.recordAction({type:`fire_event`,id:e},()=>this.fireEventInternal(e))}fireEventInternal(e){let t=this.nodes(`event`).find(t=>t.attributes.id===e);return!t||!this.eventFiltersMatch(t)||!this.claimEvent(t)?!1:(this.executeTracedEvent(t,`fireEvent`),this.checkObjectives(),!0)}fireMoveto(e){this.recordAction({type:`fire_moveto`,unit:e},()=>this.fireMovetoInternal(e))}fireMovetoInternal(e){let t=this.world.units[e];if(t&&t.alive){for(let n of this.nodes(`event`))(n.attributes.on??n.attributes.trigger)===`moveto`&&(n.attributes.x===void 0||_X(n.attributes.x,t.x))&&(n.attributes.y===void 0||_X(n.attributes.y,t.y))&&(n.attributes.unit===void 0||n.attributes.unit===e)&&(n.attributes.side===void 0||n.attributes.side===t.side)&&this.eventFiltersMatch(n)&&this.claimEvent(n)&&this.executeTracedEvent(n,`moveto`);this.checkObjectives()}}claimEvent(e){if(!(e.attributes.once===void 0?e.attributes.on===`moveto`:e.attributes.once!==`false`))return!0;let t=e.attributes.id??`${e.attributes.on??e.attributes.trigger??`event`}@${e.location?.line??0}`,n=this.world.firedEvents??=[];return!n.includes(t)&&(n.push(t),!0)}eventFiltersMatch(e){if(!this.conditionMatches(e)||!this.filterConditionMatches(e))return!1;let t=e.children.find(e=>e.tag===`filter`);return!t||this.filterMatches(t)}executeEvent(e){this.runBlock(this.commandChildren(e))}runBlock(e){for(let t=0;t<e.length;t++){let n=e[t];if(!this.isConsumedElse(e,t)){if(n.tag===`say`){this.showSay(n);continue}if(n.tag===`dialogue`){this.showDialogue(n);continue}this.executeNode(n)}}}isConsumedElse(e,t){let n=e[t-1];return e[t]?.tag===`else`&&n?.tag===`if`&&this.nodeConditionMatches(n)}executeTracedEvent(e,t){let n=e.attributes.id??`${e.attributes.on??e.attributes.trigger??`event`}@${e.location?.line??0}`;this.trace({type:`event`,phase:`claimed`,id:n,trigger:t});try{this.executeEvent(e),this.trace({type:`event`,phase:`completed`,id:n,trigger:t})}catch(e){throw this.trace({type:`error`,message:String(e),event:n}),e}}showDialogue(e){let t=null;for(let n of e.children)n.tag===`message`?(this.showMessage(n.attributes),t={text:n.attributes.text??n.attributes.value??``,...n.attributes.speaker===void 0?{}:{speaker:n.attributes.speaker},...n.attributes.portrait===void 0?{}:{portrait:n.attributes.portrait},...n.attributes.side===void 0||n.attributes.side===``?{}:{side:n.attributes.side}}):n.tag===`say`&&(this.showSay(n),t={text:n.attributes.text??``,speaker:n.attributes.speaker});let n=[];for(let t of e.children){if(t.tag!==`choice`||!t.attributes.text||t.attributes.variable!==void 0&&!lX(this.variableAt(t.attributes.variable),t.attributes.equals))continue;let e=t.children.filter(e=>e.tag===`branch`);if(e.length)for(let r of e)n.push({text:r.attributes.text??t.attributes.text,branch:r.children});else t.attributes.event&&n.push({text:t.attributes.text,event:t.attributes.event})}if(n.length===0)return;this.dialogueCounter+=1;let r=`dialogue-${this.dialogueCounter}`;this.pendingDialogue={id:r,choices:n},this.world.pendingDialogue={id:r,choices:n},this.onMessage?.({text:t?.text??``,...t?.speaker===void 0?{}:{speaker:t.speaker},choices:n,dialogueId:r})}showSay(e){this.onMessage&&this.onMessage({text:e.attributes.text??``,...e.attributes.speaker===void 0?{}:{speaker:e.attributes.speaker}})}answerDialogue(e,t){return this.recordAction({type:`answer_dialogue`,dialogueId:e,choiceIndex:t},()=>this.answerDialogueInternal(e,t))}answerDialogueInternal(e,t){let n=this.pendingDialogue;if(!n||n.id!==e)return!1;let r=n.choices[t];if(!r)return!1;if(this.pendingDialogue=null,delete this.world.pendingDialogue,r.event){let e=this.nodes(`event`).find(e=>e.attributes.id===r.event);if(!e)throw Error(`MWL dialogue choice points at unknown event: ${r.event}`);if(!this.claimEvent(e))return!0;this.executeEvent(e)}else this.runBlock(r.branch??[]);return this.checkObjectives(),!0}evaluate(){return this.checkObjectives(),this.world.status}save(){let e=this.hooks?.saveable,t=e?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.save()])):void 0;return gY(this.world,this.persistence,t,this.journal.toJSON())}snapshot(){return JSON.stringify(this.world)}restore(e){let t=vY(e,this.persistence),n=t.world;Object.assign(this.world.variables,n.variables),Object.assign(this.world.units,n.units),Object.assign(this.world.sides,n.sides??{}),Object.assign(this.world.maps,n.maps??{}),Object.assign(this.world.gold,n.gold??{}),this.world.turn=n.turn,this.world.status=n.status,this.world.sideStatus={...n.sideStatus??{}},this.world.map=n.map??null,this.world.timeOfDay=n.timeOfDay??this.schedule[0]??``,this.world.scheduleIndex=n.scheduleIndex??0,this.world.random=n.random,this.random.setState(n.random??new j().getState()),this.world.firedEvents=[...n.firedEvents??[]],this.world.villages=n.villages?structuredClone(n.villages):void 0,this.world.clearedShroud=n.clearedShroud?structuredClone(n.clearedShroud):void 0,this.world.roles=n.roles?structuredClone(n.roles):void 0,this.world.objects=n.objects?structuredClone(n.objects):void 0,this.world.story=n.story?structuredClone(n.story):void 0,this.world.pendingDialogue=n.pendingDialogue,this.pendingDialogue=n.pendingDialogue?{id:n.pendingDialogue.id,choices:[...n.pendingDialogue.choices]}:null;let r=n.pendingDialogue?.id.match(/^dialogue-(\d+)$/);r&&(this.dialogueCounter=Math.max(this.dialogueCounter,Number(r[1])));for(let[e,n]of Object.entries(t.hookState??{}))this.hooks?.saveable?.[e]?.restore(n);this.journal.replace(t.journal??[])}recordAction(e,t){let n=this.traceBatch===null;n&&(this.traceBatch=[]);try{let r=t();return n&&this.journal.append(e,this.traceBatch??[]),r}finally{n&&(this.traceBatch=null)}}trace(e){this.traceBatch?.push(e),this.onTrace?.(e)}loadUnitTypes(){for(let e of this.nodes(`unit_type`)){let t=e.attributes.id;t&&this.unitTypes.set(t,{hitpoints:WY(e,`hitpoints`,1),movement:WY(e,`movement`,0)})}}loadSchedule(){this.schedule=this.nodes(`schedule`).flatMap(e=>e.children.filter(e=>e.tag===`time`).map(e=>e.attributes.id).filter(e=>!!e)),this.world.scheduleIndex=0,this.world.timeOfDay=this.schedule[0]??``}loadInitialContent(){for(let e of this.nodes(`side`)){let t={gold:WY(e,`gold`,0),income:WY(e,`income`,0)};e.attributes.leader!==void 0&&(t.leader=e.attributes.leader),e.attributes.controller!==void 0&&(t.controller=e.attributes.controller),e.attributes.recruit!==void 0&&(t.recruit=e.attributes.recruit),e.attributes.team_name!==void 0&&(t.teamName=e.attributes.team_name),e.attributes.user_team_name!==void 0&&(t.userTeamName=e.attributes.user_team_name),e.attributes.share_vision!==void 0&&(t.shareVision=e.attributes.share_vision),e.attributes.flag!==void 0&&(t.flag=e.attributes.flag),e.attributes.village_gold!==void 0&&(t.villageGold=WY(e,`village_gold`,0));for(let n of[`heal`,`fog`,`shroud`,`hidden`]){let r=e.attributes[n];r!==void 0&&(t[n]=r===`yes`||r===`true`)}this.world.sides[UY(e,`id`)]=t}for(let e of this.nodes(`map`)){let t=e.attributes.id??e.attributes.name??`map`;this.world.maps[t]={terrain:e.attributes.terrain??``,file:e.attributes.file},this.world.map||(this.world.map=this.buildMap(t,e))}}topLevelNodes(e){return(this.game.roots.find(e=>e.tag===`game`)?.children??this.game.roots).filter(t=>t.tag===e)}loadScenarioExtras(){for(let e of this.topLevelNodes(`object`)){let t={x:WY(e,`x`,0),y:WY(e,`y`,0)};e.attributes.id!==void 0&&(t.id=e.attributes.id),e.attributes.name!==void 0&&(t.name=e.attributes.name),e.attributes.image!==void 0&&(t.image=e.attributes.image),e.attributes.side!==void 0&&(t.side=e.attributes.side),(this.world.objects??=[]).push(t)}for(let e of this.topLevelNodes(`story`)){let t=e.attributes.text??e.attributes.value;if(t===void 0)continue;let n={text:t};e.attributes.title!==void 0&&(n.title=e.attributes.title),e.attributes.image!==void 0&&(n.image=e.attributes.image),e.attributes.music!==void 0&&(n.music=e.attributes.music),(this.world.story??=[]).push(n)}for(let e of this.topLevelNodes(`role`)){let t=e.attributes.role??e.attributes.name;if(t===void 0)continue;let n=cX(e.attributes,`role`,`name`),r=Object.entries(this.world.units).filter(([e,t])=>t.alive&&sX(t,e,n));for(let[,e]of r)e.role=t;(this.world.roles??={})[t]=r.map(([e])=>e)}}buildMap(e,t){let n=t.attributes.terrain;if(!n&&t.attributes.file&&this.resolveMap&&(n=this.resolveMap(t.attributes.file)),!n)return null;let r=qY(n);for(let e of t.children){if(e.tag!==`start`)continue;let t=e.attributes.side,n=aX(e,`x`),i=aX(e,`y`);t!==void 0&&n!==void 0&&i!==void 0&&(r.starts[t]??=[]).push({x:n,y:i})}return{id:e,...r}}loadInitialUnits(){for(let e of this.nodes(`unit`)){let t=UY(e,`id`),n={hp:WY(e,`hp`,1),x:WY(e,`x`,0),y:WY(e,`y`,0),alive:!0};if(e.attributes.type!==void 0){n.type=e.attributes.type;let t=this.unitTypes.get(e.attributes.type);t&&(n.moves=t.movement)}e.attributes.side!==void 0&&(n.side=e.attributes.side),e.attributes.name!==void 0&&(n.name=e.attributes.name),e.attributes.role!==void 0&&(n.role=e.attributes.role);let r=RY(e,`can_recruit`);r!==void 0&&(n.can_recruit=r),this.world.units[t]=n}}loadLeaders(){for(let e of this.nodes(`side`)){let t=e.attributes.leader;if(!t)continue;let n=e.attributes.id;if(!n)continue;let r=this.world.map?.starts[n];if(!r?.length)continue;let i=this.unitTypes.get(t);for(let e of r){if(this.unitAt(e.x,e.y))continue;let r=`${t} ${n} (${e.x},${e.y})`;this.world.units[r]={hp:i?.hitpoints??1,x:e.x,y:e.y,alive:!0,type:t,side:n,moves:i?.movement??0,can_recruit:!0,leader:!0}}}}unitAt(e,t){return Object.values(this.world.units).find(n=>n.alive&&n.x===e&&n.y===t)}static{this.commandHandlers={message:(e,t)=>e.showMessage(t.attributes),spawn:(e,t)=>e.cmdSpawn(t),move:(e,t)=>e.cmdMove(t),kill:(e,t)=>e.cmdKill(t),fire_event:(e,t)=>e.cmdFireEvent(t),store_unit:(e,t)=>e.cmdStoreUnit(t),unstore_unit:(e,t)=>e.cmdUnstoreUnit(t),recall:(e,t)=>e.cmdRecall(t),modify_unit:(e,t)=>e.cmdModifyUnit(t),heal_unit:(e,t)=>e.cmdHealUnit(t),set_terrain:(e,t)=>e.setTerrain(WY(t,`x`,0),WY(t,`y`,0),UY(t,`terrain`)),capture_village:(e,t)=>e.cmdCaptureVillage(t),clear_shroud:(e,t)=>e.cmdClearShroud(t),role:(e,t)=>e.cmdRole(t),attack:(e,t)=>e.attack(t.attributes.defender??t.attributes.target??UY(t,`target`),WY(t,`amount`,0)),modify_gold:(e,t)=>e.addGold(t.attributes.side??UY(t,`target`),WY(t,`delta`,WY(t,`amount`,0))),gold:(e,t)=>e.addGold(UY(t,`side`),WY(t,`delta`,WY(t,`amount`,0))),set_variable:(e,t)=>e.cmdSetVariable(t),while:(e,t)=>e.cmdWhile(t),foreach:(e,t)=>e.cmdForeach(t),switch:(e,t)=>e.cmdSwitch(t),end_turn:e=>e.endTurn(),win:(e,t)=>e.cmdWin(t),lose:(e,t)=>e.cmdLose(t),endlevel:(e,t)=>e.cmdEndlevel(t),if:(e,t)=>e.cmdIf(t),else:(e,t)=>e.runBlock(e.commandChildren(t)),hook:(e,t)=>e.runHook(t)}}executeNode(t){let n=t.tag===`command`?t.attributes.name:t.tag;if(!n)throw Error(`MWL command is missing name`);let r=e.commandHandlers[n];if(!r)throw Error(`unknown MWL command: ${n}`);r(this,t)}cmdSpawn(e){this.spawnUnit(e.attributes.type??``,e.attributes.side,WY(e,`x`,0),WY(e,`y`,0),e.attributes.id??e.attributes.target,e.attributes.hp===void 0?void 0:WY(e,`hp`,1))}cmdMove(e){this.applyMove(e.attributes.unit??UY(e,`target`),WY(e,`x`,0),WY(e,`y`,0))}cmdKill(e){let t=e.attributes.unit??e.attributes.target;t===void 0?tX(this.world,e.attributes):this.killUnit(t)}cmdFireEvent(e){let t=e.attributes.id??e.attributes.name;if(!t)throw Error(`[fire_event] requires id`);this.fireEvent(t)}cmdStoreUnit(e){let t=e.attributes.variable??e.attributes.name??UY(e,`variable`);this.setVariableAt(t,this.matchingUnits(e,[`variable`,`name`]).map(([e,t])=>({id:e,...nX(t)})))}cmdUnstoreUnit(e){let t=UY(e,`variable`);for(let e of this.storedUnits(t))this.restoreUnit(e,{})}cmdRecall(e){let t=this.storedUnits(UY(e,`variable`)),n=e.attributes.id??e.attributes.unit,r=n===void 0?t[0]:t.find(e=>e.id===n);if(!r)throw Error(`[recall] found no stored unit${n===void 0?``:` named ${n}`}`);let i={};e.attributes.x!==void 0&&(i.x=WY(e,`x`,0)),e.attributes.y!==void 0&&(i.y=WY(e,`y`,0)),e.attributes.side!==void 0&&(i.side=e.attributes.side),this.restoreUnit(r,i)}cmdModifyUnit(e){let t=e.children.find(e=>e.tag===`set`)?.attributes??e.attributes;for(let[,n]of this.matchingUnits(e))rX(n,t)}cmdHealUnit(e){let t=aX(e,`amount`),n=aX(e,`hp`);if(t===void 0&&n===void 0)throw Error(`[heal_unit] requires amount or hp`);for(let[,r]of this.matchingUnits(e))r.hp=n??r.hp+(t??0)}cmdCaptureVillage(e){let t=WY(e,`x`,0),n=WY(e,`y`,0),r={x:t,y:n,side:UY(e,`side`)};e.attributes.name!==void 0&&(r.name=e.attributes.name),(this.world.villages??={})[`${t},${n}`]=r}cmdClearShroud(e){let t=UY(e,`side`),n=WY(e,`x`,0),r=WY(e,`y`,0),i=WY(e,`radius`,1),a=new Set(this.world.clearedShroud?.[t]??[]);for(let e=-i;e<=i;e++)for(let t=-i;t<=i;t++)a.add(`${n+t},${r+e}`);(this.world.clearedShroud??={})[t]=[...a]}cmdRole(e){let t=e.attributes.role??e.attributes.name;if(!t)throw Error(`[role] requires role`);let n=this.matchingUnits(e,[`role`,`name`]);for(let[,e]of n)e.role=t;(this.world.roles??={})[t]=n.map(([e])=>e)}cmdSetVariable(e){let t=e.attributes.path;this.setVariable(t===void 0?e.tag===`command`?UY(e,`target`):UY(e,`name`):this.expandPath(t),e.attributes.value??``,e.attributes.mode)}cmdWhile(e){let t=WY(e,`max_iterations`,1e3);if(t<1||t>1e5)throw Error(`MWL while max_iterations must be between 1 and 100000`);for(let n=0;n<t&&this.nodeConditionMatches(e);n++)this.runBlock(this.commandChildren(e))}cmdForeach(e){let t=this.variableAt(UY(e,`variable`)),n=Array.isArray(t)?t.map((e,t)=>[String(t),e]):typeof t==`string`?t.split(`,`).map((e,t)=>[String(t),e.trim()]).filter(([,e])=>e!==``):t&&typeof t==`object`?Object.entries(t):[],r=e.attributes.item??`item`,i=e.attributes.index??`index`;for(let t=0;t<n.length;t++)this.setVariableAt(r,n[t][1]),this.setVariableAt(i,t),this.runBlock(this.commandChildren(e))}cmdSwitch(e){let t=this.variableAt(UY(e,`variable`)),n=e.children.find(e=>e.tag===`case`&&e.attributes.equals!==void 0&&lX(t,e.attributes.equals)),r=e.children.find(e=>e.tag==="default");this.runBlock((n??r)?.children??[])}cmdWin(e){this.markSideResult(e.attributes.side,`won`),this.world.status=`won`}cmdLose(e){this.markSideResult(e.attributes.side,`lost`),this.world.status=`lost`}cmdEndlevel(e){let t=e.attributes.result===`defeat`?`defeat`:`victory`;this.world.status=t===`defeat`?`lost`:`won`,this.world.carryover=VY(this.world,QY(this.world,e.attributes.side),{result:t,bonus:LY(e,`bonus`),carryoverPercentage:IY(e,`carryover_percentage`),carryoverAdd:RY(e,`carryover_add`),nextScenario:e.attributes.next_scenario??null})}cmdIf(e){let t=e.children.find(e=>e.tag===`else`),n=this.nodeConditionMatches(e)?e:t;this.runBlock(n?this.commandChildren(n):[])}commandChildren(e){return e.children.filter(e=>e.tag!==`condition`&&e.tag!==`filter`&&e.tag!==`filter_condition`)}runHook(e){let t=e.attributes.name??``,n=this.hooks?.command?.[t];if(!n)throw Error(`MWL hook ${t} is not implemented`);let{name:r,...i}=e.attributes;n(this.worldView(),this.emit(),i)}applyMove(e,t,n){let r=this.world.units[e];if(!r||!r.alive)throw Error(`MWL unit is not alive: ${e}`);let i=this.world.map??null;if(i){if(t<0||n<0||t>=i.width||n>=i.height)throw Error(`MWL move out of bounds: ${t},${n}`);let e=this.unitAt(t,n);if(e&&e!==r)throw Error(`MWL move onto an occupied cell: ${t},${n}`)}if(typeof r.moves==`number`){if(r.moves<=0)throw Error(`MWL unit has no moves left: ${e}`);--r.moves}r.x=t,r.y=n,this.fireMoveto(e)}showMessage(e){if(!this.onMessage)return;let t={text:this.interpolate(e.text??e.value??``),...e.speaker===void 0?{}:{speaker:e.speaker},...e.portrait===void 0?{}:{portrait:e.portrait},...e.side===void 0||e.side===``?{}:{side:e.side}};this.onMessage(t)}interpolate(e){let t=this.numericVariables();return e.replace(JY,(e,n)=>{try{return String(OY(n,t))}catch{return``}}).replace(YY,(e,t)=>{let n=this.variableAt(t);return n===void 0||typeof n==`boolean`?``:String(n)})}expandPath(e){return e.replace(JY,(e,t)=>String(OY(t,this.numericVariables()))).replace(YY,(e,t)=>{let n=this.variableAt(t);if(n===void 0)throw Error(`MWL variable path reference "$${t}" names no variable`);if(typeof n==`boolean`||typeof n==`object`)throw Error(`MWL variable path reference "$${t}" is not a name or number`);return String(n)})}setVariable(e,t,n){if(n===`literal`){this.setVariableAt(e,t);return}if(n===`number`){let n=Number(t);if(t.trim()===``||!Number.isFinite(n))throw Error(`MWL set_variable mode="number" needs a number, got "${t}"`);this.setVariableAt(e,n);return}if(n===`expression`){this.setVariableAt(e,OY(t,this.numericVariables()));return}if(n!==void 0)throw Error(`unknown MWL set_variable mode "${n}"`);let r=Number(t);if(t.trim()!==``&&Number.isFinite(r)){this.setVariableAt(e,r);return}let i=/^\$([A-Za-z_][A-Za-z0-9_.]*)$/.exec(t.trim());if(i){let t=this.variableAt(i[1]);this.setVariableAt(e,t===void 0?``:t);return}let a=this.numericVariables();if(/[+*/^()]|\s-\s/.test(t)||Object.prototype.hasOwnProperty.call(a,t.trim())){this.setVariableAt(e,OY(t,a));return}this.setVariableAt(e,t)}numericVariables(){return Object.fromEntries(Object.entries(this.world.variables).filter(e=>typeof e[1]==`number`))}variableAt(e){return hX(this.world.variables,e)}setVariableAt(e,t){let n=this.variableAt(e);mX(this.world.variables,e,t),this.trace({type:`variable`,name:e,...n===void 0?{}:{previous:n},value:t})}spawnUnit(e,t,n,r,i,a){let o=e?this.unitTypes.get(e):void 0,s=i??`${e||`unit`}#${t??``}@${n},${r}`;this.world.units[s]={hp:a??o?.hitpoints??1,x:n,y:r,alive:!0,...e?{type:e}:{},...t===void 0?{}:{side:t},...o?{moves:o.movement}:{}}}killUnit(e){let t=this.world.units[e];if(!t||!t.alive)throw Error(`MWL unit is not alive: ${e}`);t.alive=!1}matchingUnits(e,t=[]){let n=e.children.find(e=>e.tag===`filter`),r=n?n.attributes:cX(e.attributes,...t);return Object.entries(this.world.units).filter(([e,t])=>t.alive&&sX(t,e,r))}storedUnits(e){let t=this.variableAt(e);if(!Array.isArray(t))throw Error(`MWL variable ${e} is not a stored unit list; store one first`);return t.filter(e=>!!e&&typeof e==`object`&&!Array.isArray(e))}restoreUnit(e,t){let n=typeof e.id==`string`?e.id:void 0;if(!n)throw Error(`a stored unit snapshot is missing its id`);let r={hp:typeof e.hp==`number`?e.hp:1,x:t.x??(typeof e.x==`number`?e.x:0),y:t.y??(typeof e.y==`number`?e.y:0),alive:e.alive!==!1};typeof e.type==`string`&&(r.type=e.type);let i=t.side??(typeof e.side==`string`?e.side:void 0);i!==void 0&&(r.side=i),typeof e.moves==`number`&&(r.moves=e.moves),typeof e.name==`string`&&(r.name=e.name),typeof e.role==`string`&&(r.role=e.role),typeof e.can_recruit==`boolean`&&(r.can_recruit=e.can_recruit),typeof e.leader==`boolean`&&(r.leader=e.leader),this.world.units[n]=r}setTerrain(e,t,n){let r=this.world.map;if(!r)throw Error(`[set_terrain] needs a loaded map`);if(e<0||t<0||e>=r.width||t>=r.height)throw Error(`[set_terrain] is outside the map: ${e},${t}`);let i=[...r.codes];i[t*r.width+e]=n,this.world.map={...r,codes:i}}addGold(e,t){this.world.gold[e]=(this.world.gold[e]??0)+t}endTurn(){this.world.turn+=1,this.advanceSchedule(),this.resetMoves(),this.run(`turn`),this.checkTimeOver()}checkTimeOver(){let e=LY(this.game.roots[0],`turn_limit`);e===void 0||this.world.turn<=e||this.world.variables.time_over===`yes`||(this.world.variables.time_over=`yes`,this.run(`time_over`))}advanceSchedule(){if(!this.schedule.length)return;let e=((this.world.scheduleIndex??0)+1)%this.schedule.length;this.world.scheduleIndex=e,this.world.timeOfDay=this.schedule[e]}resetMoves(){for(let e of Object.values(this.world.units)){if(!e.alive)continue;let t=e.type?this.unitTypes.get(e.type):void 0;t&&(e.moves=t.movement)}}filterMatches(e){return Object.entries(this.world.units).some(([t,n])=>n.alive&&sX(n,t,e.attributes))}conditionMatches(e){return e.children.filter(e=>e.tag===`condition`).every(e=>{if(e.attributes.condition===`hook`){let t=e.attributes.hook,n=t?.startsWith(`predicate:`)?t.slice(10):void 0,r=n?this.hooks?.predicate?.[n]:void 0;if(!r)throw Error(`MWL predicate ${n??`<missing>`} is not implemented`);let{condition:i,hook:a,...o}=e.attributes;return!!r(this.worldView(),o)}return oX(this.variableAt(e.attributes.variable),e.attributes,gX(this.world.variables))})}nodeConditionMatches(e){return e.attributes.test===void 0?this.conditionMatches(e):CY(e.attributes.test,uX(this.world.variables))}filterConditionMatches(e){let t=e.children.find(e=>e.tag===`filter_condition`);return!t||t.children.every(e=>{if(e.tag===`variable`){let t=e.attributes.name;return t!==void 0&&oX(this.variableAt(t),e.attributes,gX(this.world.variables))}if(e.tag===`predicate`){let t=e.attributes.name,n=t?this.hooks?.predicate?.[t]:void 0;if(!n)throw Error(`MWL predicate ${t??`<missing>`} is not implemented`);let{name:r,...i}=e.attributes;return!!n(this.worldView(),i)}return e.tag!==`have_unit`||Object.entries(this.world.units).some(([t,n])=>n.alive&&(e.attributes.id===void 0||t===e.attributes.id)&&sX(n,t,e.attributes))})}conditionMet(e,t){let n=e.attributes.condition??``,r=e.attributes.side??t;switch(n){case`units_dead`:{let t=e.attributes.side_filter??r;return t!==void 0&&!Object.values(this.world.units).some(e=>e.alive&&e.side===t)}case`turns_elapsed`:{let t=aX(e,`turns`);return t!==void 0&&this.world.turn>=t}case`gold_at_least`:{let n=aX(e,`gold`),r=e.attributes.side??t;return n!==void 0&&r!==void 0&&(this.world.gold[r]??0)>=n}case`unit_at`:{let t=aX(e,`x`),n=aX(e,`y`),i=e.attributes.side_filter??r;return Object.values(this.world.units).some(r=>r.alive&&(i===void 0||r.side===i)&&(e.attributes.type===void 0||r.type===e.attributes.type)&&r.x===t&&r.y===n)}case`hook`:{let t=e.attributes.hook??``,n=this.hooks?.predicate?.[t];if(!n)throw Error(`MWL hook ${t} is not implemented`);let{hook:r,condition:i,...a}=e.attributes;return!!n(this.worldView(),a)}default:return!1}}checkObjectives(){if(this.world.status!==`playing`)return;let e=new Set,t=this.nodes(`side`);for(let n of t)for(let t of n.children)(t.tag===`victory`||t.tag===`defeat`)&&e.add(t);if(this.nodes(`victory`).some(t=>!e.has(t)&&this.conditionMet(t))){this.world.status=`won`;return}if(this.nodes(`defeat`).some(t=>!e.has(t)&&this.conditionMet(t))){this.world.status=`lost`;return}let n=!1,r=!1;for(let e of t){let t=e.attributes.id;t&&(this.world.sideStatus?.[t]??`playing`)===`playing`&&(e.children.some(e=>e.tag===`victory`&&this.conditionMet(e,t))?(this.markSideResult(t,`won`),n=!0):e.children.some(e=>e.tag===`defeat`&&this.conditionMet(e,t))&&(this.markSideResult(t,`lost`),r=!0))}n?this.world.status=`won`:r&&(this.world.status=`lost`)}markSideResult(e,t){e!==void 0&&e!==``&&((this.world.sideStatus??={})[e]=t)}worldView(){return{variables:this.world.variables,variableAt:e=>this.variableAt(e),units:this.world.units,sides:this.world.sides,turn:this.world.turn,random:{float:()=>this.drawRandom(e=>e.float()),int:e=>this.drawRandom(t=>t.int(e))}}}drawRandom(e){let t=e(this.random);return this.world.random=this.random.getState(),t}emit(){return{move:(e,t,n)=>this.applyMove(e,t,n),attack:(e,t,n)=>{throw Error(`MWL hook attack is not available in the framework runtime; the engine adapter owns combat`)},spawn:(e,t,n,r)=>this.spawnUnit(e,t,n,r),kill:e=>this.killUnit(e),gold:(e,t)=>this.addGold(e,t),setVariable:(e,t)=>{mX(this.world.variables,e,t)},message:(e,t)=>this.onMessage?.({text:t,...e?{speaker:e}:{}}),endTurn:()=>this.endTurn(),win:e=>{this.markSideResult(e,`won`),this.world.status=`won`},lose:e=>{this.markSideResult(e,`lost`),this.world.status=`lost`}}}attack(e,t){let n=this.world.units[e];if(!n||!n.alive)throw Error(`MWL unit is not alive: ${e}`);n.hp=Math.max(0,n.hp-t),n.hp===0&&(n.alive=!1)}nodes(e){let t=[],n=r=>{r.tag===e&&t.push(r),r.children.forEach(n)};return this.game.roots.forEach(n),t}};function ZY(e,t){if(e.status===`playing`||t.name===`win`||t.name===`lose`)switch(t.name){case`set_variable`:mX(e.variables,t.target,t.value);break;case`modify_gold`:e.gold[t.target]=(e.gold[t.target]??0)+t.amount;break;case`move`:{let n=eX(e,t.target);n.x=t.x,n.y=t.y;break}case`spawn`:e.units[t.target]={hp:t.hp,x:t.x,y:t.y,alive:!0};break;case`kill`:t.target===void 0?tX(e,t.filter??{}):eX(e,t.target).alive=!1;break;case`end_turn`:e.turn++;break;case`win`:t.side!==void 0&&t.side!==``&&((e.sideStatus??={})[t.side]=`won`),e.status=`won`;break;case`lose`:t.side!==void 0&&t.side!==``&&((e.sideStatus??={})[t.side]=`lost`),e.status=`lost`;break;case`endlevel`:e.status=t.result===`defeat`?`lost`:`won`,e.carryover=VY(e,t.side??null,t)}}function QY(e,t){let n=t??Object.entries(e.sides).find(([,e])=>e.controller===`human`)?.[0];return!n||!(n in e.sides)?null:{id:n}}function $Y(e){let t=new Map;for(let[n,r]of Object.entries(e.sides)){if(!r.teamName||r.shareVision===`none`)continue;let e=t.get(r.teamName);e?e.push(n):t.set(r.teamName,[n])}return[...t.values()].filter(e=>e.length>1)}function eX(e,t){let n=e.units[t];if(!n||!n.alive)throw Error(`MWL unit is not alive: ${t}`);return n}function tX(e,t){let n=0;for(let[r,i]of Object.entries(e.units))i.alive&&sX(i,r,t)&&(i.alive=!1,n++);return n}function nX(e){let t={hp:e.hp,x:e.x,y:e.y,alive:e.alive};return e.type!==void 0&&(t.type=e.type),e.side!==void 0&&(t.side=e.side),e.moves!==void 0&&(t.moves=e.moves),e.name!==void 0&&(t.name=e.name),e.role!==void 0&&(t.role=e.role),e.can_recruit!==void 0&&(t.can_recruit=e.can_recruit),e.leader!==void 0&&(t.leader=e.leader),t}function rX(e,t){let n=iX(t.hp);n!==void 0&&(e.hp=n);let r=iX(t.moves);r!==void 0&&(e.moves=r),t.type!==void 0&&(e.type=t.type),t.side!==void 0&&(e.side=t.side);let i=zY(t.alive);i!==void 0&&(e.alive=i),t.name!==void 0&&(e.name=t.name),t.role!==void 0&&(e.role=t.role);let a=zY(t.can_recruit);a!==void 0&&(e.can_recruit=a)}function iX(e){if(e===void 0||e===``)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function aX(e,t){let n=e.attributes[t];if(n===void 0||n===``)return;let r=Number.parseInt(n,10);return Number.isFinite(r)?r:void 0}function oX(e,t,n){let r=e=>{if(!e.startsWith(`$`))return e;let t=n(e.slice(1));return typeof t==`string`||typeof t==`number`||typeof t==`boolean`?t:void 0};if(t.equals!==void 0)return lX(e,r(t.equals));if(t.not_equals!==void 0)return!lX(e,r(t.not_equals));if(t.in!==void 0)return t.in.split(`,`).map(e=>e.trim()).some(t=>lX(e,t));if(t.not_in!==void 0)return!t.not_in.split(`,`).map(e=>e.trim()).some(t=>lX(e,t));let i=typeof e==`number`?e:Number(e),a=e=>Number(t[e]);return t.less_than!==void 0||t.greater_than!==void 0||t.less_than_or_equal_to!==void 0||t.greater_than_or_equal_to!==void 0?!(typeof e==`boolean`||!Number.isFinite(i)||t.less_than!==void 0&&!(i<a(`less_than`))||t.greater_than!==void 0&&!(i>a(`greater_than`))||t.less_than_or_equal_to!==void 0&&!(i<=a(`less_than_or_equal_to`))||t.greater_than_or_equal_to!==void 0&&!(i>=a(`greater_than_or_equal_to`))):e!==void 0}function sX(e,t,n){let r=(n.not_type??``).split(`,`).map(e=>e.trim()).filter(Boolean),i=zY(n.can_recruit),a=zY(n.leader),o=n.unit??n.id;return(o===void 0||t===o)&&(n.side===void 0||e.side===n.side)&&(n.type===void 0||e.type===n.type)&&(r.length===0||!r.includes(e.type??``))&&(n.name===void 0||e.name===n.name)&&(n.role===void 0||e.role===n.role)&&(i===void 0||(e.can_recruit??!1)===i)&&(a===void 0||(e.leader??!1)===a)&&(n.x===void 0||_X(n.x,e.x))&&(n.y===void 0||_X(n.y,e.y))}function cX(e,...t){if(t.length===0)return{...e};let n={...e};for(let e of t)delete n[e];return n}function lX(e,t){if(e===void 0||t===void 0||typeof t!=`string`)return e===t;let n=Number(t);return typeof e==`number`&&t.trim()!==``&&Number.isFinite(n)?e===n:e===t}function uX(e){return Object.fromEntries(Object.entries(e).filter(e=>typeof e[1]==`string`||typeof e[1]==`number`||typeof e[1]==`boolean`))}function dX(e){return e.split(`.`).flatMap(e=>{let t=/^([^[\]]*)((?:\[[^\]]*\])*)$/.exec(e);if(!t)return[e];let n=t[1]===``?[]:[t[1]];for(let e of t[2].matchAll(/\[([^\]]*)\]/g)){let t=Number(e[1]);n.push({index:/^\d+$/.test(e[1].trim())?t:void 0})}return n}).filter(e=>typeof e!=`string`||e!==``)}function fX(e){let t=dX(e);if(t.some(e=>typeof e!=`string`&&e.index===void 0))throw Error(`invalid variable path: ${e}`);return t}function pX(e){return typeof e!=`string`}function mX(e,t,n){let r=fX(t),i=e=>typeof e==`string`?e:e.index,a=e;for(let e=0;e<r.length-1;e++){let t=i(r[e]),n=a[t];(!n||typeof n!=`object`)&&(a[t]=pX(r[e+1])?[]:{}),a=a[t]}a[i(r[r.length-1])]=n}function hX(e,t){let n=e;for(let e of dX(t))if(typeof e==`string`){if(!n||typeof n!=`object`||Array.isArray(n))return;n=n[e]}else{if(!Array.isArray(n)||e.index===void 0)return;n=n[e.index]}return n}function gX(e){return t=>hX(e,t)}function _X(e,t){return e.split(`,`).some(e=>{let n=e.trim(),r=n.match(/^(-?\d+)\s*-\s*(-?\d+)$/);if(r){let e=Number(r[1]),n=Number(r[2]);return t>=Math.min(e,n)&&t<=Math.max(e,n)}return/^-?\d+$/.test(n)&&Number(n)===t})}var vX=/^\s*([A-Za-z_][\w]*)\s*=\s*(.*?)\s*$/;function yX(e){let t=e.split(/\r?\n/),n={},r=0;for(;r<t.length;r++){let e=t[r];if(e.trim()===``)continue;let i=vX.exec(e);if(!i)break;n[i[1]]=i[2]}return{header:n,...qY(t.slice(r).map(bX).join(`
1405
- `))}}function bX(e){let t=e.length;for(;t>0&&(e[t-1]===`,`||/\s/.test(e[t-1]));)t--;return e.slice(0,t)}function xX(e){let t=[];for(let n of e.split(`|`)){let e=n.indexOf(`:`);if(e<=0||e===n.length-1)throw Error(`invalid table column "${n}"`);let r=n.slice(0,e).trim(),i=n.slice(e+1).trim();if(!/^[A-Za-z_][\w.-]*$/.test(r))throw Error(`invalid table column name "${r}"`);if(![`string`,`number`,`boolean`,`list`,`map`].includes(i))throw Error(`invalid table column type "${i}"`);if(t.some(e=>e.name===r))throw Error(`duplicate table column "${r}"`);t.push({name:r,type:i})}if(t.length===0)throw Error(`table must declare at least one column`);return t}var SX={game:{attributes:{schema:`string`,title:`string`,data_root:`string`,start_scene:`id`,default_schedule:`id`,save_slot:`string`,turn_limit:`integer`},children:`campaign.terrain_type.movetype.unit_type.unit.side.map.schedule.event.objectives.trait.weapon_special.dialogue.save.item.inventory.monster.status.loot.turn_clock.battle_move.type_matchup.evolution.table.object.story.role`.split(`.`)},campaign:{attributes:{id:`id`,name:`string`,title:`string`,description:`string`,start_scene:`id`,first_scenario:`id`},openChildren:!0},table:{attributes:{id:`id`,columns:`string`,list_delimiter:`string`,map_delimiter:`string`},children:[`row`]},row:{openAttributes:`string`},terrain_type:{attributes:{id:`id`,string:`string`,aliasof:`string`,mvt_alias:`string`,default_base:`string`,heals:`integer`,gives_income:`boolean`,map_code:`string`,base_tile:`string`,overlay_tile:`string`,defense:`number`,healing:`number`}},movetype:{attributes:{id:`id`,name:`string`},children:[`movement_costs`,`defense`,`resistance`]},movement_costs:{openAttributes:`number`},defense:{openAttributes:`number`},resistance:{openAttributes:`number`},unit_type:{attributes:{id:`string`,name:`string`,description:`string`,image:`string`,image_icon:`string`,profile:`string`,sound:`string`,hitpoints:`integer`,movement:`integer`,movement_type:`id`,movetype:`id`,experience:`integer`,level:`integer`,alignment:`id`,cost:`integer`,advances_to:`string`,race:`id`,usage:`id`},children:[`attack`,`trait`,`ability`]},unit:{attributes:{id:`id`,type:`string`,side:`string`,name:`string`,role:`string`,can_recruit:`boolean`,hp:`integer`,x:`integer`,y:`integer`}},attack:{attributes:{id:`id`,attacker:`string`,defender:`string`,target:`string`,amount:`integer`,weapon:`id`,name:`string`,sound:`string`,description:`string`,type:`id`,range:`id`,damage:`integer`,number:`integer`,strikes:`integer`,icon:`string`,specials:`string`}},side:{attributes:{id:`string`,controller:`id`,gold:`integer`,income:`integer`,income_base:`integer`,income_per_village:`integer`,leader:`id`,team:`integer`,recruit:`string`,color:`string`,team_name:`string`,user_team_name:`string`,share_vision:`string`,village_gold:`integer`,heal:`boolean`,fog:`boolean`,shroud:`boolean`,hidden:`boolean`,flag:`string`}},map:{attributes:{id:`id`,name:`string`,file:`string`,terrain:`string`},children:[`start`]},start:{attributes:{side:`string`,x:`integer`,y:`integer`}},schedule:{attributes:{id:`id`},children:[`time`]},time:{attributes:{id:`id`,name:`string`,lawful_bonus:`number`}},event:{attributes:{id:`id`,on:`id`,trigger:`id`,x:`coordinate`,y:`coordinate`,side:`string`,unit:`string`,once:`boolean`},children:`condition.filter.filter_condition.while.foreach.switch.command.say.dialogue.move.attack.spawn.kill.gold.endlevel.set_variable.if.else.message.teleport.end_turn.win.lose.hook.fire_event.store_unit.unstore_unit.recall.modify_unit.heal_unit.set_terrain.capture_village.clear_shroud.role`.split(`.`)},objectives:{attributes:{side:`string`,victory:`string`,defeat:`string`},children:[`victory`,`defeat`]},victory:{attributes:{side:`string`,condition:`id`,type:`string`,x:`integer`,y:`integer`,side_filter:`string`,turns:`integer`,gold:`integer`,hook:`string`,value:`integer`}},defeat:{attributes:{side:`string`,condition:`id`,type:`string`,x:`integer`,y:`integer`,side_filter:`string`,turns:`integer`,gold:`integer`,hook:`string`,value:`integer`}},condition:{attributes:{condition:`id`,hook:`string`,variable:`string`,equals:`string`,not_equals:`string`,in:`string`,not_in:`string`,less_than:`string`,greater_than:`string`,less_than_or_equal_to:`string`,greater_than_or_equal_to:`string`}},filter:{attributes:{side:`string`,type:`string`,not_type:`string`,unit:`string`,name:`string`,role:`string`,x:`coordinate`,y:`coordinate`,level:`integer`,alignment:`id`,can_recruit:`boolean`,leader:`boolean`}},filter_condition:{children:[`variable`,`have_unit`,`predicate`]},variable:{attributes:{name:`id`,equals:`string`,not_equals:`string`,in:`string`,not_in:`string`,less_than:`string`,greater_than:`string`,less_than_or_equal_to:`string`,greater_than_or_equal_to:`string`}},have_unit:{attributes:{id:`string`,type:`string`,side:`string`,name:`string`,role:`string`,can_recruit:`boolean`,x:`coordinate`,y:`coordinate`}},predicate:{attributes:{name:`id`},openAttributes:`string`},command:{attributes:{name:`id`,target:`string`,path:`string`,value:`string`,mode:[`literal`,`number`,`expression`],amount:`integer`,x:`integer`,y:`integer`,hp:`integer`}},move:{attributes:{unit:`string`,target:`string`,x:`integer`,y:`integer`}},spawn:{attributes:{id:`string`,type:`string`,side:`string`,x:`integer`,y:`integer`,hp:`integer`}},kill:{attributes:{unit:`string`,target:`string`},openAttributes:`string`},gold:{attributes:{side:`string`,delta:`integer`,amount:`integer`}},endlevel:{attributes:{result:`id`,side:`string`,bonus:`integer`,carryover_percentage:`integer`,carryover_add:`boolean`,next_scenario:`id`}},set_variable:{attributes:{name:`id`,target:`id`,path:`string`,value:`string`,mode:[`literal`,`number`,`expression`]}},if:{attributes:{test:`string`},children:[`condition`,`while`,`foreach`,`switch`,`if`,`else`,`command`,`message`,`move`,`attack`,`spawn`,`kill`,`gold`,`set_variable`,`win`,`lose`,`hook`]},else:{children:[`condition`,`while`,`foreach`,`switch`,`if`,`else`,`command`,`message`,`move`,`attack`,`spawn`,`kill`,`gold`,`set_variable`,`win`,`lose`,`hook`]},while:{attributes:{test:`string`,max_iterations:`integer`},children:[`condition`,`while`,`foreach`,`switch`,`if`,`else`,`message`,`move`,`attack`,`spawn`,`kill`,`gold`,`set_variable`,`win`,`lose`,`hook`]},foreach:{attributes:{variable:`id`,item:`id`,index:`id`},children:[`while`,`foreach`,`switch`,`if`,`else`,`message`,`move`,`attack`,`spawn`,`kill`,`gold`,`set_variable`,`win`,`lose`,`hook`]},switch:{attributes:{variable:`id`},children:[`case`,`default`]},case:{attributes:{equals:`string`},children:[`while`,`foreach`,`switch`,`if`,`else`,`message`,`move`,`attack`,`spawn`,`kill`,`gold`,`set_variable`,`win`,`lose`,`hook`,`dialogue`]},default:{children:[`while`,`foreach`,`switch`,`if`,`else`,`message`,`move`,`attack`,`spawn`,`kill`,`gold`,`set_variable`,`win`,`lose`,`hook`,`dialogue`]},message:{attributes:{speaker:`string`,text:`string`,value:`string`,portrait:`string`,side:`string`}},teleport:{attributes:{unit:`string`,target:`string`,x:`integer`,y:`integer`}},end_turn:{attributes:{}},win:{attributes:{side:`string`}},lose:{attributes:{side:`string`}},say:{attributes:{speaker:`id`,text:`string`}},dialogue:{attributes:{id:`id`,ref:`id`},children:[`say`,`choice`,`branch`,`message`]},choice:{attributes:{text:`string`,event:`id`,variable:`id`,equals:`string`},children:[`branch`]},branch:{attributes:{text:`string`},children:[`message`,`say`,`command`,`set_variable`,`move`,`attack`,`spawn`,`kill`,`gold`,`hook`]},trait:{attributes:{id:`id`,name:`string`},children:[`effect`]},ability:{attributes:{id:`id`,name:`string`},children:[`effect`]},weapon_special:{attributes:{id:`id`,name:`string`}},hook:{attributes:{name:`string`},openAttributes:`string`},fire_event:{attributes:{id:`id`,name:`string`}},store_unit:{attributes:{variable:`string`,name:`string`},children:[`filter`]},unstore_unit:{attributes:{variable:`string`,name:`string`}},recall:{attributes:{variable:`string`,id:`string`,unit:`string`,side:`string`,x:`integer`,y:`integer`}},modify_unit:{attributes:{hp:`integer`,moves:`integer`,type:`string`,side:`string`,alive:`boolean`},children:[`filter`,`set`]},set:{openAttributes:`string`},heal_unit:{attributes:{amount:`integer`,hp:`integer`,side:`string`,type:`string`,x:`integer`,y:`integer`},children:[`filter`]},set_terrain:{attributes:{terrain:`string`,x:`integer`,y:`integer`}},capture_village:{attributes:{side:`string`,x:`integer`,y:`integer`,name:`string`}},clear_shroud:{attributes:{side:`string`,x:`integer`,y:`integer`,radius:`integer`}},role:{attributes:{role:`string`,name:`string`,type:`string`,not_type:`string`,unit:`string`,side:`string`,can_recruit:`boolean`,x:`integer`,y:`integer`},children:[`filter`]},object:{attributes:{id:`id`,name:`string`,image:`string`,side:`string`,x:`integer`,y:`integer`},children:[`filter`]},story:{attributes:{text:`string`,value:`string`,title:`string`,image:`string`,music:`string`}},item:{attributes:{id:`id`,name:`string`,slot:`id`,stackable:`boolean`,weight:`number`,image:`string`,icon:`string`},children:[`effect`]},inventory:{attributes:{unit:`string`,side:`string`,items:`string`}},monster:{attributes:{id:`string`,name:`string`,hp:`integer`,types:`string`,attack:`number`,defense:`number`,speed:`number`,accuracy:`number`,evasion:`number`,damage_min:`integer`,damage_max:`integer`,armor_min:`integer`,armor_max:`integer`,experience:`integer`,max_level:`integer`,image:`string`},children:[`ability`,`loot`]},status:{attributes:{id:`id`,name:`string`,duration:`integer`,tick:`string`,modifiers:`string`}},loot:{attributes:{item:`id`,chance:`number`,quantity:`integer`,weight:`number`}},turn_clock:{attributes:{id:`id`,tick:`number`,hunger:`number`}},ai:{attributes:{id:`id`,strategy:`id`,target:`id`,difficulty:`number`,scope:`id`,provider:`id`,algorithm:`id`,depth:`integer`,max_nodes:`integer`,player:`string`,moves:`string`,apply:`string`,terminal:`string`,evaluate:`string`},children:[`behavior`]},behavior:{attributes:{id:`id`,when:`string`,action:`string`,hook:`string`}},battle_move:{attributes:{id:`id`,type:`id`,target:`id`,power:`number`,cost:`number`}},type_matchup:{attributes:{attacker:`id`,defender:`id`,multiplier:`number`}},evolution:{attributes:{from:`id`,into:`id`,level:`integer`}},effect:{attributes:{apply_to:`id`,range:`id`,increase:`string`,increase_total:`string`,increase_damage:`string`,add:`string`,sub:`string`,multiply:`string`,divide:`string`,set:`string`}},save:{attributes:{version:`integer`,fields:`string`,migration:`string`}}},CX={...SX,game:{...SX.game,required:[`schema`]},table:{...SX.table,required:[`id`,`columns`],cardinality:{row:{min:1}}},terrain_type:{...SX.terrain_type,required:[`id`]},movetype:{...SX.movetype,required:[`id`]},unit_type:{...SX.unit_type,required:[`id`]},unit:{...SX.unit,required:[`id`,`type`,`side`]}};function wX(e,t=SX){let n=[],r=new Map,i=e=>{let t=e.attributes.id;t&&r.set(t,[...r.get(t)??[],e]),e.children.forEach(i)};e.forEach(i);let a=[],o=(e,i=!1)=>{let s=t[e.tag];if(!s){if(i){e.children.forEach(e=>o(e,!0));return}n.push({code:`MWL_UNKNOWN_TAG`,message:`unknown tag ${e.tag}`,location:e.location});return}for(let t of Object.keys(e.attributes))s.openAttributes||(!s.attributes||!(t in s.attributes))&&n.push({code:`MWL_UNKNOWN_ATTRIBUTE`,message:`unknown attribute ${t} on ${e.tag}`,location:e.attributeLocations?.[t]??e.location});for(let t of s.required??[])e.attributes[t]===void 0&&n.push({code:`MWL_REQUIRED_ATTRIBUTE`,message:`${t} is required on ${e.tag}`,location:e.location});for(let[t,i]of Object.entries(s.attributes??{})){let o=e.attributes[t];if(o!==void 0&&!OX(o,i)&&n.push({code:`MWL_VALUE`,message:`${t} must be ${kX(i)}`,location:e.valueLocations?.[t]??e.attributeLocations?.[t]??e.location}),o!==void 0&&i===`ref`){let i=(r.get(o)??[]).filter(e=>{let n=s.refTargets?.[t];return!n||n===`*`||e.tag===n});i.length===0?n.push({code:`MWL_REF_MISSING`,message:`${t} references missing target ${o}`,location:e.location}):i.length>1?n.push({code:`MWL_REF_DUPLICATE`,message:`${t} references ambiguous target ${o}`,location:e.location}):s.acyclicRefs?.includes(t)&&a.push({from:e,to:i[0],name:t})}}if(s.openAttributes)for(let[t,r]of Object.entries(e.attributes))OX(r,s.openAttributes)||n.push({code:`MWL_VALUE`,message:`${t} must be ${s.openAttributes}`,location:e.valueLocations?.[t]??e.attributeLocations?.[t]??e.location});for(let t of e.children)!s.openChildren&&s.children&&!s.children.includes(t.tag)&&n.push({code:`MWL_CHILD`,message:`${t.tag} is not allowed inside ${e.tag}`,location:t.location}),o(t,s.openChildren===!0);for(let[t,r]of Object.entries(s.cardinality??{})){let i=e.children.filter(e=>e.tag===t).length;r.min!==void 0&&i<r.min&&n.push({code:`MWL_CARDINALITY`,message:`${e.tag} needs at least ${r.min} ${t} child${r.min===1?``:`ren`}`,location:e.location}),r.max!==void 0&&i>r.max&&n.push({code:`MWL_CARDINALITY`,message:`${e.tag} allows at most ${r.max} ${t} child${r.max===1?``:`ren`}`,location:e.location})}};e.forEach(e=>o(e)),TX(e,n);let s=new Set,c=new Set,l=(e,t)=>{if(s.has(e)){let r=t.indexOf(e);n.push({code:`MWL_REF_CYCLE`,message:`reference cycle through ${t.slice(r).map(e=>e.attributes.id??e.tag).join(` -> `)}`,location:e.location});return}if(!c.has(e)){s.add(e);for(let n of a.filter(t=>t.from===e))l(n.to,[...t,e]);s.delete(e),c.add(e)}};for(let e of a)l(e.from,[]);return n.sort((e,t)=>e.location.line-t.location.line||e.location.column-t.location.column)}function TX(e,t){let n=e=>{if(e.tag===`table`){let n;try{n=xX(e.attributes.columns??``)}catch(r){t.push({code:`MWL_TABLE`,message:String(r).replace(/^Error: /,``),location:e.location}),n=[]}let r=new Map(n.map(e=>[e.name,e]));for(let i of e.children.filter(e=>e.tag===`row`)){for(let e of Object.keys(i.attributes))r.has(e)||t.push({code:`MWL_TABLE`,message:`unknown table column ${e}`,location:i.location});for(let r of n){let n=i.attributes[r.name];if(n===void 0){t.push({code:`MWL_TABLE`,message:`missing table column ${r.name}`,location:i.location});continue}try{EX(n,r.type,r.name,e.attributes.list_delimiter,e.attributes.map_delimiter)}catch(e){t.push({code:`MWL_TABLE`,message:String(e).replace(/^Error: /,``),location:i.location})}}}}e.children.forEach(n)};e.forEach(n)}function EX(e,t,n,r=`;`,i=`=`){return Br(e,t,{column:n,listDelimiter:r,mapDelimiter:i,acceptYesNo:!0})}function DX(e){return/^[A-Za-z_][\w.[\]-]*$/.test(e)}function OX(e,t){return AX(t)?t.includes(e):t===`number`?Number.isFinite(Number(e)):t===`integer`?/^-?\d+$/.test(e):t===`boolean`?e===`true`||e===`false`||e===`yes`||e===`no`:t===`ref`?/^[A-Za-z_][\w.-]*$/.test(e):t===`coordinate`?/^-?\d+(?:\s*,\s*-?\d+|\s*-\s*-?\d+)*$/.test(e):t!==`id`||DX(e)}function kX(e){return AX(e)?`one of ${e.join(`, `)}`:e}function AX(e){return Array.isArray(e)}function jX(e,t={}){return NX(QJ(KJ(e,t),t.file),t)}function MX(e,t={}){let n=[];for(let r of[...e].sort((e,t)=>e.file<t.file?-1:+(e.file>t.file))){let e=KJ(r.source,{...t,file:r.file});n.push(...QJ(e,r.file))}return NX(n,t)}function NX(e,t={}){let n=e.find(e=>e.tag===`game`)?.attributes.schema,r=wX(e,t.schemas??(n===`1.0`?CX:void 0));if(r.length){let e=r[0];throw Error(`${e.location.file}:${e.location.line}:${e.location.column}: ${e.message}`)}let i=new Set,a=new Set,o=e=>{for(let[t,n]of Object.entries(e.attributes))if(PX(t))for(let e of IX(n).map(e=>e.trim()).filter(FX))i.add(LX(e));let t=e.gettext??[`name`,`text`,`title`];for(let n of t){let t=e.attributes[n];t!==void 0&&a.add(t)}let n={tag:e.tag,attributes:{...e.attributes},children:e.children.map(o),location:e.location};return Object.defineProperties(n,{attributeLocations:{value:e.attributeLocations,enumerable:!1},valueLocations:{value:e.valueLocations,enumerable:!1}}),e.gettext&&Object.assign(n,{gettext:[...e.gettext]}),n};return{schema:e.find(e=>e.tag===`game`)?.attributes.schema??`0.1`,roots:e.map(o),assets:[...i].sort(),messages:[...a].sort()}}function PX(e){return e===`file`||e===`image`||e===`image_icon`||e===`icon`||e===`profile`||e===`sound`||e.endsWith(`_sound`)||e.endsWith(`_image`)}function FX(e){return e.includes(`/`)||/\.(?:png|jpg|jpeg|gif|svg|webp|wav|ogg|mp3|flac|glb|gltf|vox|map|cfg)$/i.test(e)||e.startsWith(`data:`)}function IX(e){let t=[],n=0,r=0,i=0;for(let a=0;a<e.length;a+=1)e[a]===`(`?r+=1:e[a]===`)`&&r>0?--r:e[a]===`[`?i+=1:e[a]===`]`&&i>0?--i:e[a]===`,`&&r===0&&i===0&&(t.push(e.slice(n,a)),n=a+1);return t.push(e.slice(n)),t}function LX(e){let t=e.match(/~[A-Za-z][A-Za-z0-9_-]*(?:\(|$)/);return t?e.slice(0,t.index).trim():e}function RX(e,t={}){let n={};for(let t of e.messages)n[t]=t;return{locale:t.locale??`en`,direction:t.direction??`ltr`,messages:n}}function zX(e,t=`gameData`){return`export const ${t} = ${JSON.stringify(e,null,` `)} as const;\n`}function BX(e,t={}){let n=[{name:`game-data.ts`,content:zX(e,t.variable??`gameData`)},{name:`i18n.json`,content:`${JSON.stringify(RX(e),null,` `)}\n`},{name:`assets.json`,content:`${JSON.stringify({assets:e.assets},null,` `)}\n`},...Object.entries(t.artifacts??{}).sort(([e],[t])=>e<t?-1:+(e>t)).map(([e,t])=>({name:e,content:t}))];for(let e of n)t.onEmit?.(e);return n}function VX(e,t={},n={}){let r=BX(MX(e,t),n),i=BX(MX(e,t),n);if(r.length!==i.length||r.some((e,t)=>e.name!==i[t]?.name||e.content!==i[t]?.content))throw Error(`MWL generated artifacts are not deterministic`);return r}var HX=/^[A-Za-z_][\w-]*$/,UX=[`predicate`,`modifier`,`generator`,`command`,`ai`,`migration`];function WX(e){let t=e.indexOf(`:`);if(t<=0)return null;let n=e.slice(0,t),r=e.slice(t+1).trim();return!HX.test(n)||!HX.test(r)?null:{type:n,name:r}}function GX(e,t=[`hook`,`migration`]){let n=new Map,r=new Set(t),i=e=>{for(let[t,n]of Object.entries(e.attributes))r.has(t)&&a(n,e.location),e.tag===`hook`&&t===`name`&&a(n,e.location);e.children.forEach(i)},a=(e,t)=>{let r=WX(e);if(!r)return;let i=`${r.type}:${r.name}`;n.has(i)||n.set(i,{...r,location:t})};return e.roots.forEach(i),[...n.values()].sort((e,t)=>e.type.localeCompare(t.type)||e.name.localeCompare(t.name))}function KX(e,t){if(t.attributes===void 0&&t.openAttributes===void 0)return[];let n=e.location??{file:`<hook>`,line:0,column:0},r=[];for(let[i,a]of Object.entries(e.attributes)){if(i===`name`)continue;let e=t.attributes?.[i]??t.openAttributes;if(e===void 0){r.push({code:`MWL_UNKNOWN_ATTRIBUTE`,message:`unknown attribute ${i} on hook ${t.id}`,location:n});continue}OX(a,e)||r.push({code:`MWL_VALUE`,message:`${i} must be ${kX(e)} on hook ${t.id}`,location:n})}return r}function qX(e,t){let n=new Set(t),r=[];for(let t of e){let e=`${t.type}:${t.name}`;n.has(e)||r.push({code:`MWL_HOOK`,message:`hook ${e} is not implemented`,location:t.location??{file:`<hook>`,line:0,column:0}})}return r}function JX(e){let t=[];t.push(`// Generated by mwl - do not edit.`),t.push(`import type { AiHook, CommandHook, GeneratorHook, MigrationHook, ModifierHook, PredicateHook } from '@datamoc/mw_games/mwl';`),t.push(``),t.push(`export interface MwlHooks {`);for(let n of e){let e=UX.includes(n.type)?`${n.type[0].toUpperCase()}${n.type.slice(1)}Hook`:`MwlDomainHook`;t.push(`\t'${n.type}:${n.name}': ${e};`)}return t.push(`}`),t.push(``),t.join(`
1406
- `)}function YX(e,t){let n=e.scenarios;if(n.length===0)throw Error(`campaign ${e.id} declares no scenarios`);let r=new Set(n.map(e=>e.id));if(r.size!==n.length)throw Error(`campaign ${e.id} declares a scenario twice`);let i=e.firstScenario||n[0].id;if(!r.has(i))throw Error(`campaign ${e.id} starts on an unknown scenario: ${i}`);return{start:i,levels:n.map(e=>({id:e.id,run:(n,r)=>{let i=t.run(e,n,r);return i.next===void 0?{...i,next:e.nextScenario??null}:i}}))}}var XX=FY,ZX=IY,QX=LY,$X=RY,eZ=BY;function tZ(e){let t=PY(e.roots);return{campaigns:t.filter(e=>e.tag===`campaign`).map(e=>({id:XX(e,`id`),name:e.attributes.name,title:e.attributes.title,description:e.attributes.description,startScene:e.attributes.start_scene,firstScenario:e.attributes.first_scenario,scenarios:e.children.filter(e=>e.tag===`scenario`).map(e=>({id:XX(e,`id`),nextScenario:e.attributes.next_scenario||void 0}))})),items:t.filter(e=>e.tag===`item`).map(e=>({id:XX(e,`id`),name:XX(e,`name`),slot:e.attributes.slot,stackable:$X(e,`stackable`),weight:ZX(e,`weight`),image:e.attributes.image,icon:e.attributes.icon,effects:e.children.filter(e=>e.tag===`effect`).map(rZ)})),monsters:t.filter(e=>e.tag===`monster`).map(e=>({id:XX(e,`id`),name:e.attributes.name,hp:QX(e,`hp`,1),accuracy:ZX(e,`accuracy`),evasion:ZX(e,`evasion`),damage:iZ(e,`damage_min`,`damage_max`),armor:iZ(e,`armor_min`,`armor_max`),experience:QX(e,`experience`),maxLevel:QX(e,`max_level`),image:e.attributes.image,types:e.attributes.types?.split(`,`).map(e=>e.trim()).filter(Boolean),baseStats:[`attack`,`defense`,`speed`,`hp`].reduce((t,n)=>{let r=ZX(e,n);return r!==void 0&&(t[n===`hp`?`maxHp`:n]=r),t},{})})),statuses:t.filter(e=>e.tag===`status`).map(e=>({id:XX(e,`id`),name:e.attributes.name,duration:QX(e,`duration`),tick:e.attributes.tick,modifiers:e.attributes.modifiers})),loot:t.filter(e=>e.tag===`loot`).map(e=>({item:XX(e,`item`),chance:ZX(e,`chance`),quantity:QX(e,`quantity`),weight:ZX(e,`weight`)})),turnClocks:t.filter(e=>e.tag===`turn_clock`).map(e=>({id:XX(e,`id`),tick:ZX(e,`tick`),hunger:ZX(e,`hunger`)})),ai:t.filter(e=>e.tag===`ai`).map(e=>({id:XX(e,`id`),strategy:e.attributes.strategy,target:e.attributes.target,difficulty:ZX(e,`difficulty`),scope:eZ(e.attributes.scope,[`actor`,`controller`]),provider:eZ(e.attributes.provider,[`javascript`,`lua`]),algorithm:eZ(e.attributes.algorithm,[`rules`,`alpha_beta`]),depth:QX(e,`depth`),maxNodes:QX(e,`max_nodes`),player:e.attributes.player,moves:e.attributes.moves,apply:e.attributes.apply,terminal:e.attributes.terminal,evaluate:e.attributes.evaluate,behaviors:e.children.filter(e=>e.tag===`behavior`).map(e=>({id:XX(e,`id`),when:e.attributes.when,action:e.attributes.action,hook:e.attributes.hook}))})),moves:t.filter(e=>e.tag===`battle_move`).map(e=>({id:XX(e,`id`),type:XX(e,`type`),target:XX(e,`target`),power:ZX(e,`power`),cost:ZX(e,`cost`)})),typeMatchups:t.filter(e=>e.tag===`type_matchup`).map(e=>({attacker:XX(e,`attacker`),defender:XX(e,`defender`),multiplier:ZX(e,`multiplier`)??1})),evolutions:t.filter(e=>e.tag===`evolution`).map(e=>({from:XX(e,`from`),into:XX(e,`into`),level:QX(e,`level`,1)})),tables:t.filter(e=>e.tag===`table`).map(nZ)}}function nZ(e){let t=xX(XX(e,`columns`));return{id:XX(e,`id`),columns:t,rows:e.children.filter(e=>e.tag===`row`).map(n=>{let r={};for(let i of t){let t=n.attributes[i.name];t!==void 0&&(r[i.name]=EX(t,i.type,i.name,e.attributes.list_delimiter,e.attributes.map_delimiter))}return r})}}function rZ(e){let t=[`add`,`sub`,`multiply`,`divide`,`set`,`increase`,`increase_total`,`increase_damage`].find(t=>e.attributes[t]!==void 0);return{applyTo:XX(e,`apply_to`),operation:t,value:t?e.attributes[t]:void 0,range:e.attributes.range}}function iZ(e,t,n){let r=ZX(e,t),i=ZX(e,n);return r===void 0||i===void 0?void 0:[r,i]}function aZ(e){return e.rows}function oZ(e,t={}){let n=[`// ${t.header??`Generated from MWL tables - do not edit by hand.`}`];e.length>0&&n.push(`import { typedRows } from '@datamoc/mw_games/mwl';`,`import type { MwlContentCatalog } from '@datamoc/mw_games/mwl';`);let r=new Set;for(let t of e){let e=sZ(t.id,r);n.push(``,`const ${e}Columns = [${t.columns.map(e=>`{ name: ${JSON.stringify(e.name)}, type: ${JSON.stringify(e.type)} }`).join(`, `)}] as const;`),n.push(`export interface ${e}Row {`);for(let e of t.columns)n.push(`\t${cZ(e.name)}?: ${lZ(e.type)};`);n.push(`}`,``,`/** Typed rows of the \`${t.id}\` table. */`);let i=`${e[0].toLowerCase()}${e.slice(1)}Rows`;n.push(`export function ${i}(catalog: Pick<MwlContentCatalog, 'tables'>): ${e}Row[] {`,`\tconst table = catalog.tables.find((entry) => entry.id === ${JSON.stringify(t.id)});`,`\treturn typedRows({ columns: ${e}Columns, rows: table?.rows ?? [] });`,`}`)}return`${n.join(`
1407
- `)}\n`}function sZ(e,t){let n=e.split(/[^A-Za-z0-9]+/).filter(e=>e.length>0).map(e=>e[0].toUpperCase()+e.slice(1)).join(``)||`Table`,r=/^[A-Za-z_$]/.test(n)?n:`_${n}`,i=r;for(let e=2;t.has(i);e++)i=`${r}${e}`;return t.add(i),i}function cZ(e){return/^[A-Za-z_$][\w$]*$/.test(e)?e:JSON.stringify(e)}function lZ(e){switch(e){case`number`:return`number`;case`boolean`:return`boolean`;case`list`:return`string[]`;case`map`:return`Record<string, string>`;default:return`string`}}function uZ(e,t={}){return{id:e.id,stackable:e.stackable,weight:e.weight,slot:e.slot,modifiers:e.effects.map(e=>pZ(e,t))}}function dZ(e,t=1){return{id:e.id,quantity:t,stackable:e.stackable,weight:e.weight}}function fZ(e,t,n={}){return MB(e,t.map(e=>pZ(e,n)))}function pZ(e,t={}){let n=e.operation;if(n!==`add`&&n!==`sub`&&n!==`multiply`&&n!==`divide`&&n!==`set`)throw Error(`MWL effect operation "${n??``}" is not a StatBlock modifier`);let r=e.value;if(r===void 0)throw Error(`MWL effect has no value`);let i=OY(r,t);return{stat:e.applyTo,op:n===`sub`?`add`:n===`divide`?`multiply`:n,value:n===`sub`?-i:n===`divide`?1/i:i}}function mZ(e,t={}){let n=[],r=new Map,i=PY(e.roots);for(let e of i){let i=e.attributes.id;if(i){let a=`${t.rowIdScope===`file`?e.location?.file??`<mwl>`:``}\0${e.tag}:${i}`,o=r.get(a);o?n.push(vZ(`MWL_DUPLICATE_ID`,`duplicate ${e.tag} id "${i}"`,e.location??o.location)):r.set(a,e)}if(e.tag===`item`&&t.slots&&e.attributes.slot&&!t.slots.includes(e.attributes.slot)&&n.push(vZ(`MWL_UNKNOWN_SLOT`,`unknown equipment slot "${e.attributes.slot}"`,e.location)),e.tag===`effect`){let t=[`add`,`sub`,`multiply`,`divide`,`set`,`increase`,`increase_total`,`increase_damage`].filter(t=>e.attributes[t]!==void 0);(!e.attributes.apply_to||t.length!==1)&&n.push(vZ(`MWL_INCOMPLETE_EFFECT`,`an effect needs apply_to and exactly one operation`,e.location))}bZ(e,t.mapBounds,n)}hZ(i,n),gZ(i,t.tableReferences,n);let a=GX(e,[`hook`,`migration`,...t.hookAttributes??[]]),o=new Map;for(let e of t.hooks??[])o.set(typeof e==`string`?e:e.id,typeof e==`string`?{id:e}:e);for(let e of i){let t=e.attributes.hook??(e.tag===`hook`?e.attributes.name:void 0);t!==void 0&&!WX(t)&&n.push(vZ(`MWL_INVALID_HOOK`,`invalid hook reference "${t}"`,e.location));let r=e.tag===`hook`&&e.attributes.name?o.get(e.attributes.name):void 0;r&&n.push(...KX(e,r))}if(t.hooks)for(let e of a)o.has(`${e.type}:${e.name}`)||n.push(vZ(`MWL_UNKNOWN_HOOK`,`hook ${e.type}:${e.name} is not declared by the game`,e.location));return n}function hZ(e,t){let n=new Map;for(let t of e){let e=t.attributes.id;e&&n.set(`${t.tag}\0${e}`,t)}let r=new Set,i=new Set,a=new Set,o=(e,s)=>{if(r.has(e)){let n=s.indexOf(e),r=s.slice(n).map(e=>`${e.tag}:${e.attributes.id??`<anonymous>`}`).sort().join(`|`);if(a.has(r))return;a.add(r),t.push({code:`MWL_ALIAS_CYCLE`,message:`alias cycle through ${s.slice(n).map(e=>e.attributes.id??e.tag).join(` -> `)}`,location:e.valueLocations?.aliasof??e.attributeLocations?.aliasof??e.location??yZ()});return}if(!i.has(e)){r.add(e);for(let t of(e.attributes.aliasof??``).split(`,`).map(e=>e.trim()).filter(Boolean)){let r=n.get(`${e.tag}\0${t}`);r&&o(r,[...s,e])}r.delete(e),i.add(e)}};for(let t of e)t.attributes.aliasof!==void 0&&o(t,[])}function gZ(e,t,n){if(!t)return;let r=new Map;for(let t of e){let e=t.tag===`table`?t.attributes.id:void 0;e&&!r.has(e)&&r.set(e,t)}let i=e=>{try{return xX(e.attributes.columns??``)}catch{return}},a=e=>e.children.filter(e=>e.tag===`row`);for(let o of t){let t=r.get(o.table);if(!t){n.push(vZ(`MWL_TABLE_REFERENCE`,`unknown table "${o.table}" in tableReferences`,yZ()));continue}let s=i(t)?.find(e=>e.name===o.column);if(!s){n.push(vZ(`MWL_TABLE_REFERENCE`,`unknown column "${o.column}" in table "${o.table}"`,t.location));continue}let c,l;if(`oneOf`in o)c=new Set(o.oneOf),l=`one of the declared values`;else if(`node`in o.references){let t=new Set;for(let n of e)n.tag===o.references.node&&n.attributes.id&&t.add(n.attributes.id);c=t,l=`node "${o.references.node}"`}else{let e=o.references,s=r.get(e.table),u=s?i(s)?.find(t=>t.name===e.column):void 0;if(!s||!u){n.push(vZ(`MWL_TABLE_REFERENCE`,`unknown reference target "${e.table}.${e.column}" for table "${o.table}" column "${o.column}"`,t.location));continue}let d=new Set;for(let e of a(s))for(let t of _Z(e,u,s.attributes.list_delimiter))d.add(t);c=d,l=`${e.table}.${e.column}`}let u=t.attributes.list_delimiter;a(t).forEach((e,t)=>{for(let r of _Z(e,s,u))c.has(r)||n.push({code:`MWL_TABLE_REFERENCE`,message:`table "${o.table}" row ${t+1} column "${o.column}": unknown value "${r}" (expected ${l})`,location:e.valueLocations?.[o.column]??e.attributeLocations?.[o.column]??e.location??yZ()})})}}function _Z(e,t,n){let r=e.attributes[t.name];return r===void 0||r===``?[]:t.type===`list`?r.split(n??`;`).map(e=>e.trim()).filter(e=>e.length>0):[r]}function vZ(e,t,n){return{code:e,message:t,location:n??yZ()}}function yZ(){return{file:`<mwl>`,line:1,column:1}}function bZ(e,t,n){if(t)for(let r of[`x`,`y`]){let i=e.attributes[r];if(i===void 0)continue;let a=r===`x`?t.width:t.height;if(!Number.isInteger(a)||a<=0)continue;let o=i.split(`,`).flatMap(e=>{let t=e.trim(),n=/^(-?\d+)\s*-\s*(-?\d+)$/.exec(t);return n?[Number(n[1]),Number(n[2])]:/^-?\d+$/.test(t)?[Number(t)]:[]});o.length>0&&o.some(e=>e<0||e>=a)&&n.push({code:`MWL_COORDINATE`,message:`${r} coordinate is outside the ${a}-cell map bound`,location:e.valueLocations?.[r]??e.attributeLocations?.[r]??e.location??{file:`<mwl>`,line:1,column:1}})}}function xZ(e,t={}){return mZ({schema:`0.1`,roots:e,assets:[],messages:[]},t)}function SZ(e,t={}){try{let n=MX(e,t),r=CZ(n),i=[];for(let e of r.opaqueTags)i.push({severity:`warning`,code:`opaque-tag`,message:`ignored opaque tag: ${e}`});for(let e of r.danglingReferences)i.push({severity:`error`,code:`dangling-reference`,message:`dangling content reference: ${e}`});return{game:n,resources:[...n.assets],dependencies:[...r.references],ignored:[...r.opaqueTags],diagnostics:i}}catch(e){return{resources:[],dependencies:[],ignored:[],diagnostics:[{severity:`error`,code:`compile`,message:String(e)}]}}}function CZ(e){let t=PY(e.roots),n={},r=new Set;for(let e of t)n[e.tag]=(n[e.tag]??0)+1,e.attributes.id&&r.add(e.attributes.id);let i=new Set(Object.keys(SX)),a=t.filter(e=>!i.has(e.tag)).map(e=>e.tag).filter((e,t,n)=>n.indexOf(e)===t).sort(),o=new Set;for(let e of t)for(let[t,n]of Object.entries(e.attributes))if(/^(?:ability|item|terrain|unit|unit_type|weapon)(?:_id)?$/.test(t))for(let e of n.split(`,`).map(e=>e.trim()).filter(Boolean))o.add(e);return{tags:Object.fromEntries(Object.entries(n).sort(([e],[t])=>e.localeCompare(t))),opaqueTags:a,references:[...o].sort(),danglingReferences:[...o].filter(e=>!r.has(e)).sort()}}function wZ(e,t){let n={},r=[];for(let[i,a]of Object.entries(t)){let t=a.source??i,o=e.attributes[t];if(o===void 0){a.required?r.push(PZ(`MWL_REQUIRED_FIELD`,`missing required attribute "${t}"`,e)):a.default!==void 0&&(n[i]=a.default);continue}let s=NZ(o,a.type);s===void 0?r.push(PZ(`MWL_FIELD_TYPE`,`invalid ${a.type} attribute "${t}": "${o}"`,e)):n[i]=s}return{value:n,diagnostics:r}}function TZ(e,t,n){let r=[],i=[];for(let a of e.children){if(a.tag!==t)continue;let e=n(a);r.push(e.value),i.push(...e.diagnostics)}return{value:r,diagnostics:i}}function EZ(e,t){let n=new Map;for(let r of e){let e=OZ(...kZ(r,t.key));if(n.has(e)&&t.duplicate!==`last`)throw Error(`duplicate table key: ${e}`);n.set(e,t.value?t.value(r):r)}return n}function DZ(e,t){let n=new Map;for(let r of e){let e=OZ(...kZ(r,t.key)),i=n.get(e);i?i.push(r):n.set(e,[r])}return n}function OZ(...e){return JSON.stringify(e)}function kZ(e,t){if(typeof t==`function`){let n=t(e);return AZ(n)?[...n]:[n]}return jZ(t)?t.map(t=>MZ(e[t],String(t))):[MZ(e[t],String(t))]}function AZ(e){return Array.isArray(e)}function jZ(e){return Array.isArray(e)}function MZ(e,t){if(e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`)return e;throw TypeError(`table key column "${t}" must be a string, number, boolean, or null`)}function NZ(e,t){if(t===`string`)return e;if(t===`id`)return DX(e)?e:void 0;if(t===`number`)return Number.isFinite(Number(e))?Number(e):void 0;if(t===`integer`)return/^-?\d+$/.test(e)?Number(e):void 0;if(t===`boolean`)return e===`true`||e===`yes`?!0:e===`false`||e===`no`?!1:void 0;let n=e.split(`,`).map(e=>e.trim()).filter(Boolean);return t===`id-list`?n.every(e=>DX(e))?n:void 0:n.every(e=>Number.isFinite(Number(e)))?n.map(Number):void 0}function PZ(e,t,n){return{code:e,message:t,location:n.location??{file:`<mwl>`,line:1,column:1}}}function FZ(){return{evaluate(e,t={}){let n={};for(let[e,r]of Object.entries(t)){if(typeof r!=`number`)throw Error(`MWL expression context value must be numeric: ${e}`);n[e]=r}return OY(e,n)},execute(){throw Error(`the expression ScriptHost cannot execute statements`)},call(){throw Error(`the expression ScriptHost cannot call functions`)},dispose(){}}}var IZ=l({MWL_DEFAULT_CARRYOVER_PERCENTAGE:()=>80,MWL_SCHEMA_01:()=>`0.1`,MWL_SCHEMA_10:()=>`1.0`,MwlRuntime:()=>XY,MwlSyntaxError:()=>WJ,attributeTypeDescription:()=>kX,campaignChain:()=>YX,carryoverIntoScenario:()=>HY,coerceTableValue:()=>EX,collectHookReferences:()=>GX,compile:()=>jX,compileAndEmitSources:()=>VX,compileNodes:()=>NX,compileSources:()=>MX,composeEffects:()=>fZ,contentCatalog:()=>tZ,contentReport:()=>CZ,createExpressionScriptHost:()=>FZ,createWorld:()=>GY,decodeSave:()=>_Y,decodeSaveEnvelope:()=>vY,effectToModifier:()=>pZ,emitArtifacts:()=>BX,emitHooksDeclaration:()=>JX,emitModule:()=>zX,emitTableTypes:()=>oZ,encodeSave:()=>gY,endLevelCarryover:()=>VY,evaluateCondition:()=>CY,evaluateExpression:()=>OY,execute:()=>ZY,extractCatalog:()=>RX,hookTypes:()=>UX,inventoryItem:()=>dZ,isGettext:()=>dY,isMwlId:()=>DX,itemDefinition:()=>uZ,loadContent:()=>SZ,parse:()=>QJ,parseExpression:()=>DY,parseHookReference:()=>WX,parseMapFile:()=>yX,parseTableColumns:()=>xX,parseTerrain:()=>qY,parseValue:()=>uY,preprocess:()=>KJ,readAttributes:()=>wZ,readChildren:()=>TZ,readTableIndex:()=>DZ,readTableMap:()=>EZ,schema01:()=>SX,schema10:()=>CX,sideVisionGroups:()=>$Y,tableKey:()=>OZ,typedRows:()=>aZ,validAttributeValue:()=>OX,validate:()=>wX,validateCatalog:()=>mZ,validateCatalogNodes:()=>xZ,validateHookAttributes:()=>KX,validateHookReferences:()=>qX,validateWorld:()=>yY}),LZ=class{constructor(e,t={}){if(this.latestDecision=null,this.decide=e,this.every=t.every??1,!Number.isInteger(this.every)||this.every<1||this.every>1e6)throw RangeError(`a suggestion budget must be a frame count in 1..1000000`);this.since=this.every-1}update(e){return this.since++,this.since<this.every?null:(this.since=0,this.latestDecision=this.decide(e),this.latestDecision)}get latest(){return this.latestDecision}clear(){this.latestDecision=null}};function RZ(e,t){return e.filter(e=>(t.side===void 0||e.side===t.side)&&(t.type===void 0||e.type===t.type)&&(t.role===void 0||e.role===t.role)&&(t.can_recruit===void 0||(e.can_recruit??!1)===t.can_recruit)&&(t.name===void 0||e.name===t.name))}function zZ(e,t,n,r){let i=0,a=0,o=1;for(let s of t)s.id!==e.id&&r(s.x,s.y)&&(o++,s.side===e.side?i+=n(s.id):a+=n(s.id));return{own:n(e.id),allies:i,enemies:a,seen:o}}function BZ(e,t,n,r){let i=0,a=0,o=0;for(let s of t)r(s.x,s.y)&&(o++,s.side===e?i+=n(s.id):a+=n(s.id));return{own:0,allies:i,enemies:a,seen:o}}function VZ(e,t){return e.own*t.own+e.allies*t.allies+e.enemies*t.enemies}var HZ=class e{constructor(e={}){this.values={};for(let[t,n]of Object.entries(e))n!==void 0&&(this.values[t]=n)}has(e){return this.values[e]!==void 0}get(e){return this.values[e]}set(e,t){this.values[e]=t}number(e,t=0){let n=this.values[e];return typeof n==`number`&&Number.isFinite(n)?n:typeof n==`boolean`?+!!n:t}flag(e,t=!1){let n=this.values[e];return typeof n==`boolean`?n:t}list(e){let t=this.values[e];return Array.isArray(t)?t:typeof t==`string`?[t]:[]}names(){return Object.keys(this.values)}with(t){let n=new e(this.values);for(let[e,r]of Object.entries(t))r!==void 0&&n.set(e,r);return n}toJSON(){return{...this.values}}static fromJSON(t){return new e(t)}},UZ=class{constructor(e=[],t={}){this.levels=new Map,this.base=new HZ(t);for(let t of e){if(this.levels.has(t.id))throw Error(`duplicate difficulty level: ${t.id}`);this.levels.set(t.id,t)}}get ids(){return[...this.levels.keys()]}get(e){return this.levels.get(e)}aspectsFor(e){let t=this.levels.get(e);if(!t)throw Error(`unknown difficulty level: ${e}`);return this.base.with(t.aspects??{})}},WZ=class{constructor(){this.byUnit=new Map}set(e){this.byUnit.set(e.unit,{...e})}clear(e){this.byUnit.delete(e)}get(e){return this.byUnit.get(e)}all(){return[...this.byUnit.values()]}get isEmpty(){return this.byUnit.size===0}},GZ=class{constructor(e,t=null){this.order=e,this.fallback=t}get length(){return this.order.length}at(e){if(this.order.length===0)return this.fallback;let t=(e%this.order.length+this.order.length)%this.order.length;return this.order[t]}next(e){if(this.order.length===0)return this.fallback;if(e===null)return this.order[0];let t=this.order.indexOf(e);return this.at(t<0?0:t+1)}},KZ=class{constructor(e){this.stages=e.stages}decide(e,t){if(e.length===0)return null;for(let n of this.stages){if(n.when&&!n.when(t))continue;let r=n.weigh??qZ,i=null;for(let a of e){let e=r(a,t);(!i||e>i.score)&&(i={candidate:a,stage:n.id,score:e})}return i}return null}};function qZ(e,t){let n=0;for(let[r,i]of Object.entries(e.factors??{}))r!==`distance`&&(n+=i*t.aspects.number(r,1));let r=e.factors?.distance;return r!==void 0&&(n+=JZ(r,t.aspects.number(`keep_away`,0))),n}function JZ(e,t){return!(t>0)||e>=t?0:-(t-e)}function YZ(e){return e?Math.max(0,e.priority??1):0}var XZ=l({AIBudgetExceededError:()=>tQ,AICancelledError:()=>eQ,Aspects:()=>HZ,Difficulty:()=>UZ,Goals:()=>WZ,HeuristicAI:()=>KZ,JavaScriptAI:()=>$Z,NeuralPolicy:()=>EJ,RecruitmentPattern:()=>GZ,Suggester:()=>LZ,alphaBetaSearch:()=>_U,defaultWeigh:()=>qZ,firstWins:()=>yU,goalScore:()=>YZ,keepAwayScore:()=>JZ,personalScoreView:()=>zZ,rootSplits:()=>vU,scoreWith:()=>VZ,sideScoreView:()=>BZ,subjectsWhere:()=>RZ}),ZZ=1e4,QZ=16,$Z=class{constructor(e={}){this.agents=new Map,this.states=new Map,this.options=e,oQ(e.maxSteps??ZZ,`maxSteps`),sQ(e.maxMilliseconds??QZ,`maxMilliseconds`)}register(e){if(!/^[A-Za-z_][A-Za-z0-9_.-]*$/.test(e.id))throw Error(`invalid AI agent id: ${e.id}`);if(this.agents.has(e.id))throw Error(`AI agent already registered: ${e.id}`);if(!e.behaviors.length)throw Error(`AI agent has no behaviours: ${e.id}`);let t=new Set;for(let n of e.behaviors){if(!n.id||t.has(n.id))throw Error(`duplicate AI behaviour: ${n.id}`);t.add(n.id)}this.agents.set(e.id,e),this.states.set(e.id,{})}decide(e,t){let n=this.agents.get(e);if(!n)throw Error(`unknown AI agent: ${e}`);let r=rQ(t.state??this.states.get(e)??{}),i=t.maxSteps??this.options.maxSteps??ZZ,a=t.maxMilliseconds??this.options.maxMilliseconds??QZ;oQ(i,`maxSteps`),sQ(a,`maxMilliseconds`);let o=0,s=cQ(),c=[],l=aQ(t.seed??this.options.seed??7173991),u=()=>{if(o++,t.signal?.aborted)throw new eQ;if(o>i||cQ()-s>a)throw new tQ},d={perception:iQ(t.perception),state:r,random:()=>(u(),l()),checkpoint:u,emit(e,t){if(!e)throw Error(`AI event name must not be empty`);u(),c.push(t===void 0?{name:e}:{name:e,payload:iQ(t)})}},f=null,p,m=`idle`;try{for(let e of n.behaviors)if(u(),!e.when||e.when(d)){p=e.id,f=nQ(e.decide(d)),m=f?`action`:`idle`;break}}catch(e){if(e instanceof eQ)m=`cancelled`;else if(e instanceof tQ)m=`budget-exceeded`;else throw e}let h={agent:e,action:f,state:rQ(r),behavior:p,status:m,steps:o,events:c};return this.states.set(e,rQ(r)),this.options.onDecision?.(h),h}search(e,t,n){return _U(e,t,n)}exportState(){return{version:1,agents:Object.fromEntries([...this.states].map(([e,t])=>[e,rQ(t)]))}}importState(e){if(e.version!==1)throw Error(`unsupported AI state version: ${e.version}`);for(let[t,n]of Object.entries(e.agents)){if(!this.agents.has(t))throw Error(`AI state names unknown agent: ${t}`);this.states.set(t,rQ(n))}}dispose(){this.agents.clear(),this.states.clear()}},eQ=class extends Error{constructor(){super(`AI decision cancelled`),this.name=`AICancelledError`}},tQ=class extends Error{constructor(){super(`AI decision budget exceeded`),this.name=`AIBudgetExceededError`}};function nQ(e){if(e===null)return null;if(!e||typeof e!=`object`||Array.isArray(e)||typeof e.type!=`string`||!e.type)throw Error(`AI action must be an object with a non-empty string type`);return iQ(e)}function rQ(e){return iQ(e)}function iQ(e){return typeof e!=`object`||!e?e:Array.isArray(e)?e.map(iQ):Object.fromEntries(Object.entries(e).map(([e,t])=>[e,iQ(t)]))}function aQ(e){if(!Number.isInteger(e))throw TypeError(`AI seed must be an integer`);let t=e>>>0;return()=>(t=Math.imul(t,1664525)+1013904223>>>0,t/4294967296)}function oQ(e,t){if(!Number.isInteger(e)||e<1)throw RangeError(`${t} must be a positive integer`)}function sQ(e,t){if(!Number.isFinite(e)||e<0)throw RangeError(`${t} must be a non-negative number`)}function cQ(){return typeof performance>`u`?Date.now():performance.now()}return _e(),ja(),Xo(),vs(),Object.defineProperty(e,"AI",{enumerable:!0,get:function(){return XZ}}),e.Achievements=Tn,e.ActionJournal=Cn,e.ActorAnimator=vP,Object.defineProperty(e,"Actors",{enumerable:!0,get:function(){return kV}}),e.AnimatedSprite=AM,e.Animation=OM,Object.defineProperty(e,"Audio",{enumerable:!0,get:function(){return SJ}}),e.BLOB_SHAPES=bP,e.Bar=kR,Object.defineProperty(e,"Battle",{enumerable:!0,get:function(){return KH}}),e.Beam=iP,e.Beams=aP,e.BitmapLabel=YF,e.Blob=Cr,Object.defineProperty(e,"Board",{enumerable:!0,get:function(){return XG}}),e.Button=UL,e.CIRCLE8=cr,e.COLOR_BLINDNESS_MATRICES=dN,e.Camera=aN,e.CanonicalState=Ut,e.Checkbox=rR,e.Collection=sn,e.ColorTransformBatcher=Bj,e.Container2D=Y,e.DataTable=cR,e.DialogueStage=ZR,e.Dropdown=sR,e.EMPTY=qN,e.Easing=wr,e.EntityRegistry=jr,e.FLOATING_TEXT_STACK_GAP=FR,e.FeedbackClient=Hn,e.Flights=rP,e.FloatingText=PR,e.FloatingTextStack=zR,e.FogLayer=uP,e.Game=Aj,e.Generator=j,e.Gradient=RP,e.Grid=gR,e.HALO_ANIMATION=dP,e.Halo=fP,e.HelpScreen=HR,e.HookRegistry=S,e.HttpTransport=qt,Object.defineProperty(e,"I18n",{enumerable:!0,get:function(){return dL}}),e.IconGrid=aI,Object.defineProperty(e,"Input",{enumerable:!0,get:function(){return ve}}),e.JavaRandom=xt,e.Label=iF,e.LastRun=_n,e.LayeredSprite=eP,e.LightningArc=oP,e.LiquidLayer=cP,e.ListView=iI,e.LoadQueue=Ar,e.LoadingScreen=WR,e.LockstepClient=Xt,e.Logger=b,e.MarkupText=UF,e.MersenneTwister=he,e.MessageBox=VL,e.MessageLog=cF,e.Meter=ER,e.Minimap=hN,Object.defineProperty(e,"Mwl",{enumerable:!0,get:function(){return IZ}}),e.NEIGHBOURS4=or,e.NEIGHBOURS8=sr,e.NO_COLOR_ADD=Xj,e.NewsClient=rn,e.NewsSeenTracker=on,e.NinePatch=ZF,e.Node2D=MP,e.OnScreenKeyboard=JL,e.ParticleEmitter=gP,e.Player=ln,e.PlayerInput=_t,e.PlayerStats=tn,e.PresentationQueue=Mr,e.Projectile=tP,e.QualityScaler=Cj,e.RENDERING_DECISIONS=BP,e.RPGM_AUTOTILE_SLOT_BASES=TN,e.RPGM_AUTOTILE_SLOT_COUNTS=EN,e.RPGM_FLOOR_AUTOTILE_TABLE=ON,e.RPGM_WALL_AUTOTILE_TABLE=kN,e.RadioGroup=iR,Object.defineProperty(e,"Random",{enumerable:!0,get:function(){return C}}),e.RandomStreams=ge,e.ReactionTable=En,e.RebindScreen=wR,e.Recorder=cn,e.Rectangle2D=K,e.Registry=g,Object.defineProperty(e,"Resources",{enumerable:!0,get:function(){return nN}}),e.RichLabel=wF,Object.defineProperty(e,"Roguelike",{enumerable:!0,get:function(){return jB}}),Object.defineProperty(e,"Rpg",{enumerable:!0,get:function(){return DH}}),e.RpgmAutotileAtlas=wN,e.RunHistory=en,e.SaveSyncClient=Jt,e.SaveSystem=Rt,e.Scene=m,e.Scene2D=jj,e.SceneComponentHost=v,e.SceneStack=h,e.ScreenEffects=_P,e.ScreenReader=$F,e.ScrollBox=pR,e.Session=Dn,e.Settings=Mn,e.SettingsScreen=TR,e.Shape2D=PP,e.Signal=p,Object.defineProperty(e,"Simulation",{enumerable:!0,get:function(){return HJ}}),e.Skins=SR,e.Slider=nR,e.Spawner=Un,e.Spinner=oR,e.Sprite2D=IP,e.SpriteAttachment=sP,e.SpriteGroup=NM,e.SpriteSheet=iN,e.StageScript=QR,e.StateRegistry=Wt,e.StatsScreen=UR,e.StatusVisuals=yP,e.StoryScreen=iz,e.StorySequence=rz,e.SyncGuard=Lr,e.TabbedList=oI,e.TelemetryClient=nn,e.TerrainGraphicsLayer=zP,e.Text2D=FP,e.TextModel=HL,e.TextPrompt=XL,e.Texture2D=J,e.TileMap=$N,e.TiledSprite=LP,e.TintedSprite=Zj,e.Toast=BR,e.Tooltip=VR,e.TreeView=dR,e.Tweener=Tr,e.UPPERCASE_KEYBOARD=GL,e.UndoHistory=Er,e.VerticalLabel=$L,e.Viewport=lN,e.Window=tI,e.WindowStack=nI,Object.defineProperty(e,"World",{enumerable:!0,get:function(){return LV}}),e.XP_AUTOTILE_PATTERNS=AN,e.XP_NEIGHBORS_TO_PATTERN=jN,e.advanceReveal=tF,e.anchorAlign=mR,e.applyAllImageModifiers=_M,e.applyImageModifiers=gM,e.applyTextureModifiers=SM,e.assertAutotileLayout=FN,e.autotileCellParts=VN,e.autotileFrames=TP,e.bitmapLabelStyle=XF,e.blendMatrix=dM,e.blendPixels=TM,e.blobIndex=wP,e.cellFromKey=ar,e.cellIndex=tr,e.cellInside=er,e.cellKey=ir,e.cellX=nr,e.cellY=rr,e.channelScaleMatrix=uM,e.channelSwapMatrix=fM,e.chebyshev=ur,e.checkNoControlCharacters=Ot,e.checkSize=Dt,e.clamp=On,e.cloneData=Ht,e.colorShiftMatrix=lM,e.completeReveal=nF,e.contrastRatio=JR,e.createCamera=cN,e.createColorBlindnessFilter=fN,e.createHandles=_,e.createLayers=NP,e.croppedTexture=vM,e.defaultSettings=kn,e.defaultTheme=JP,e.deserializeReplay=dn,e.detectWebGpu=HP,e.distance=fr,e.downloadReplayFile=bn,e.effectiveMusicVolume=An,e.effectiveSfxVolume=jn,e.escapeHtml=IF,e.euclidean=lr,e.exportReplayFile=hn,e.extractDialogueCatalog=nz,e.fitWindowZoom=lF,e.floatingTextAgeAtLeast=NR,e.floatingTextAlpha=jR,e.floatingTextRise=MR,e.floatingTextStackLifePenalty=IR,e.floatingTextStackLift=LR,e.floatingTextStackMoves=RR,e.hexDistance=Jn,e.hexLine=Xn,e.hexNeighbors=qn,e.hexRange=Zn,e.hexRotate=DP,e.hexToPixel=Qn,e.highContrastTheme=YP,e.imageModifier=sM,e.importReplayFile=gn,e.importTwee=ez,e.inspectGraphicsCapabilities=VP,e.isOnScreen=MM,e.layoutMarkupLines=NF,e.layoutVertical=QL,e.linesToDrop=sF,e.loadTiledMap=qP,e.manhattan=dr,e.markupAccessibilityText=MF,e.markupToHtml=jF,e.maskPixels=wM,e.matchTerrainRule=kP,e.meetsContrast=YR,e.messageBoxPresenter=GR,e.minimapCellCenter=mN,e.motionDuration=Sr,e.newlyRevealed=pN,e.packColorAdd=qj,e.packTintAdd=Jj,e.paintFogPixels=lP,e.paletteRangeMapping=nM,e.parseCSV=Rr,e.parseColorPairs=bM,e.parseDialogueLines=Hr,e.parseDialogueText=tz,e.parseImagePath=oM,e.parseInbound=Nt,e.parseMarkdown=xF,e.parseMarkup=kF,e.parsePaletteLists=xM,e.parseReplayEvents=fn,e.parseRotateMode=cM,e.parseTwee=Ur,e.pickReplayFile=Sn,e.pixelToHex=$n,e.positionMarkupLines=FF,e.prefersReducedMotion=vr,e.readReplayFile=xn,e.recolorTexture=aM,e.rectOf=rN,e.reducedMotion=yr,e.registerColorTransform=Kj,e.relativeLuminance=qR,e.remapPixels=rM,e.resolveAnchor=hR,e.resolveTerrainGraphics=AP,e.resumeRunPlayer=yn,e.revealComplete=rF,e.rotatePixels=EM,e.rpgmAutotileFrame=CN,e.rpgmAutotileSlot=DN,e.rpgmTableEdgeCells=KN,e.runCheckpoint=vn,e.sanitizeInboundText=kt,e.scramble=St,e.screenReader=eI,e.scrollOffset=fR,e.serializeReplay=un,e.setReducedMotion=br,e.setTheme=ZP,e.sharpenText=dF,e.sliceSpans=CF,e.sliderFraction=eR,e.sliderValueAt=tR,e.snapZoom=sN,e.spinValue=aR,e.splitScreenHalves=uN,e.spriteColorMatrix=pM,e.squareRotate=EP,e.startReveal=eF,e.stateChecksum=Ir,e.stripMarkdown=SF,e.stripMarkup=AF,e.takeLastEntries=oF,e.theme=Q,e.themeChanged=$,e.tileFrame=XN,e.tileFrameIndex=QN,e.tileFrameSheet=ZN,e.uncloneablePath=zt,e.unscramble=Ct,e.validateSchema=Mt,e.version=f,e.watchReducedMotion=xr,e.weightedFlood=Dr,e.withTextureCanvas=iM,e.xpAutotilePattern=NN,e.xpAutotileRef=MN,e})({});
1399
+ `+t+`]`}return r.pop(),i=t,c}}}}))}))(),1),qJ=class extends Error{constructor(e){super(`${e.location.file}:${e.location.line}:${e.location.column}: ${e.message}`),this.name=`MwlSyntaxError`,this.diagnostic=e}},JJ=new Set([`define`,`enddef`,`arg`,`ifdef`,`ifndef`,`else`,`endif`,`include`]);function YJ(e,t={}){let n=new Map,r=new Set(t.defines??[]),i=e.split(/\r?\n/),a=[],o=[!0],s=null;for(let e=0;e<i.length;e++){let c=i[e],l=/^\s*#([A-Za-z_][\w-]*)(?:\s+(.*))?$/.exec(c);if(l&&JJ.has(l[1])){let i=l[1],u=l[2]?.trim()??``;if(i===`define`){if(!o.at(-1)||s)continue;let n=hY(u);if(n.length===0)throw _Y(`MWL_DEFINE`,`macro name is required`,t.file,e,c);s={name:n[0],parameters:n.slice(1),body:[]},r.add(n[0]);continue}if(i===`arg`){s&&u&&s.parameters.push(u.split(/\s+/)[0]);continue}if(i===`enddef`){if(!s)throw _Y(`MWL_ENDDEF`,`unexpected #enddef`,t.file,e,c);n.set(s.name,{name:s.name,parameters:s.parameters,body:s.body.join(`
1400
+ `)}),s=null;continue}if(i===`ifdef`||i===`ifndef`){let e=r.has(u);o.push(o.at(-1)===!0&&(i===`ifdef`?e:!e));continue}if(i===`else`){if(o.length<2)throw _Y(`MWL_ELSE`,`unexpected #else`,t.file,e,c);o[o.length-1]=o[o.length-2]&&!o.at(-1);continue}if(i===`endif`){if(o.length<2)throw _Y(`MWL_ENDIF`,`unexpected #endif`,t.file,e,c);o.pop();continue}if(i===`include`){if(o.at(-1)){let n=t.includes?.[gY(u)];if(n===void 0)throw _Y(`MWL_INCLUDE`,`include not supplied: ${u}`,t.file,e,c);a.push(YJ(n,t))}continue}}if(s){o.at(-1)&&s.body.push(c);continue}o.at(-1)&&!/^\s*#/.test(c)&&a.push(c)}if(s)throw _Y(`MWL_ENDDEF`,`macro ${s.name} is missing #enddef`,t.file,i.length-1,i.at(-1)??``);if(o.length!==1)throw _Y(`MWL_ENDIF`,`conditional is missing #endif`,t.file,i.length-1,i.at(-1)??``);return QJ(XJ(a.join(`
1401
+ `),n,t))}function XJ(e,t,n){let r=``,i=0;for(;i<e.length;){let a=eY(e,i);if(a!==i){r+=e.slice(i,a),i=a;continue}let o=e[i];if(o!==`{`){r+=o,i++;continue}let s=e.indexOf(`}`,i+1);if(s<0){r+=o,i++;continue}let c=e.slice(i,s+1),l=hY(e.slice(i+1,s)),u=t.get(l[0]);if(u){let e=u.body;for(let t=0;t<u.parameters.length;t++){let n=u.parameters[t],r=l.find(e=>e.startsWith(`${n}=`)),i=r?r.slice(n.length+1):l[t+1]??``;e=e.replaceAll(`{${n}}`,i)}r+=XJ(e,t,n)}else if(n.macroPolicy!==`ignore`&&ZJ(l[0]))throw vY(`MWL_MACRO`,`unknown macro "${l[0]}"`,e,n.file,i);else r+=c;i=s+1}return r}function ZJ(e){return e!==void 0&&cY.test(e)}function QJ(e){let t=/^_\(\s*("(?:[^"\\]|\\[\s\S])*"|'(?:[^'\\]|\\[\s\S])*')\s*\)/,n=``,r=0;for(;r<e.length;){let i=eY(e,r);if(i!==r){n+=e.slice(r,i),r=i;continue}let a=e[r];if(a===`_`){let i=t.exec(e.slice(r));if(i){n+=`{"$gettext": ${i[1]}}`,r+=i[0].length;continue}}n+=a,r++}return n}function $J(e,t){let n=e[t],r=t+1;for(;r<e.length;){let t=e[r];if(t===`\\`){r+=2;continue}if(t===n)return r+1;if(t===`
1402
+ `)return r;r++}return r}function eY(e,t){let n=e[t];if(n===`"`||n===`'`)return $J(e,t);let r=e[t+1];if(n===`/`&&(r===`/`||r===`*`)){let n=r===`/`?e.indexOf(`
1403
+ `,t):e.indexOf(`*/`,t+2);return n<0?e.length:r===`/`?n:n+2}return t}function tY(e,t=`<mwl>`){let n=QJ(e);if(n.trim()===``)return[];let r;try{r=KJ.default.parse(n)}catch(e){throw fY(e,n,t)}if(r===void 0)return[];if(!Array.isArray(r))throw new qJ({code:`MWL_DOCUMENT`,message:`MWL document must be a top-level array of nodes`,location:{file:t,line:1,column:1},lineText:n.split(/\r?\n/)[0]??``});let i={file:t,sites:lY(n,t),cursor:{index:0},parent:void 0};return nY(r).map(e=>oY(e,i))}function nY(e){let t=[];for(let n of e){let e=rY(n);Array.isArray(e)?t.push(...e):t.push(e)}return t}function rY(e){if(Array.isArray(e))return e.flatMap(e=>rY(e));if(typeof e!=`object`||!e)return e;let t=e;if(typeof t.tag!=`string`){let n=Object.keys(t);if(n.length!==1||!cY.test(n[0]))return e;let r=n[0],i=t[r];return Array.isArray(i)?i.map(e=>iY(r,e)):iY(r,i)}let n={...t},r=[];Array.isArray(t.children)&&r.push(...t.children.flatMap(e=>rY(e)));for(let[e,i]of Object.entries(t)){if(e===`tag`||e===`children`||!cY.test(e)||!aY(i))continue;let t=Array.isArray(i)?i:[i];r.push(...t.map(t=>iY(e,t))),delete n[e]}return r.length&&(n.children=r),n}function iY(e,t){return typeof t!=`object`||!t||Array.isArray(t)?{tag:e,value:t}:rY({tag:e,...t})}function aY(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(`$gettext`in e)||Array.isArray(e)&&e.every(e=>typeof e==`object`&&!!e&&!Array.isArray(e))}function oY(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw new qJ({code:`MWL_TAG`,message:`MWL node must be an object with a tag`,location:t.parent??{file:t.file,line:1,column:1}});let n=e;if(typeof n.tag!=`string`||!cY.test(n.tag))throw new qJ({code:`MWL_TAG`,message:`MWL node needs a tag name`,location:t.parent??{file:t.file,line:1,column:1}});let r=n.tag,i=uY(t,r),a=i.location,o=n.children??[];if(!Array.isArray(o))throw new qJ({code:`MWL_TAG`,message:`children of [${r}] must be an array`,location:a});let s={},c={},l={},u=[];for(let[e,t]of Object.entries(n)){if(e===`tag`||e===`children`)continue;s[e]=sY(r,e,t,a,u);let n=i.properties?.get(e);n&&(c[e]=n.location,l[e]=n.valueLocation)}let d={...t,parent:a},f={tag:r,attributes:s,children:o.map(e=>oY(e,d)),location:a,gettext:u};return Object.defineProperties(f,{attributeLocations:{value:c,enumerable:!1},valueLocations:{value:l,enumerable:!1}}),f}function sY(e,t,n,r,i){if(!cY.test(t)||t.startsWith(`$`)||t.startsWith(`_`))throw new qJ({code:`MWL_ATTRIBUTE`,message:`unknown attribute "${t}" on [${e}]`,location:r});if(typeof n==`string`)return n;if(typeof n==`number`&&Number.isFinite(n))return String(n);if(typeof n==`boolean`)return n?`true`:`false`;if(typeof n==`object`&&n&&!Array.isArray(n)){let e=Object.keys(n),r=n.$gettext;if(e.length===1&&e[0]===`$gettext`&&typeof r==`string`)return i.push(t),r}throw new qJ({code:`MWL_ATTRIBUTE`,message:`attribute "${t}" on [${e}] must be a string, number, boolean, or _("...")`,location:r})}var cY=/^[A-Za-z_][\w-]*$/;function lY(e,t){let n=[],r=[];for(let i=0;i<e.length;){let a=eY(e,i);if(a!==i){i=a;continue}let o=e[i];if(o===`{`){let e={start:i,properties:new Map};r.push(e),i++;continue}if(o===`}`){r.pop(),i++;continue}let s=/[A-Za-z_$][\w$-]*/y;s.lastIndex=i;let c=s.exec(e);if(!c){i++;continue}let l=c.index+c[0].length;for(;/\s/.test(e[l]??``);)l++;if(e[l]!==`:`){i=c.index+c[0].length;continue}let u=l+1;for(;/\s/.test(e[u]??``);)u++;let d=r.at(-1);if(d&&(d.properties.set(c[0],{location:dY(e,t,c.index),valueLocation:dY(e,t,u)}),c[0]===`tag`&&(e[u]===`"`||e[u]===`'`))){let r=$J(e,u),i=e.slice(u,r),a;try{a=KJ.default.parse(i)}catch{a=void 0}typeof a==`string`&&n.push({tag:a,location:dY(e,t,c.index),properties:d.properties})}i=c.index+c[0].length}return n}function uY(e,t){for(let n=e.cursor.index;n<e.sites.length;n++)if(e.sites[n].tag===t)return e.cursor.index=n+1,e.sites[n];return{tag:t,location:e.parent??{file:e.file,line:1,column:1}}}function dY(e,t,n){let r=1,i=1;for(let t=0;t<n;t++)e[t]===`
1404
+ `?(r++,i=1):i++;return{file:t,line:r,column:i}}function fY(e,t,n){let r=t.split(/\r?\n/),i=e,a=typeof i?.lineNumber==`number`?i.lineNumber:1,o=typeof i?.columnNumber==`number`?i.columnNumber:1,s=e instanceof Error?e.message:String(e);return s.includes(`'_'`)&&(s+=` (write translatable text as _("..."))`),new qJ({code:`MWL_SYNTAX`,message:s,location:{file:n,line:Math.max(1,a),column:Math.max(1,o)},lineText:r[Math.max(1,a)-1]})}function pY(e,t,n=e){let r=e.trim(),i=/^_\(\s*([\s\S]*?)\s*\)$/.exec(r),a=i?i[1]:r;if(a.startsWith(`"`)||a.startsWith(`'`)){try{let e=KJ.default.parse(a);if(typeof e==`string`)return e}catch{}throw new qJ({code:`MWL_STRING`,message:`unterminated string value`,location:t,lineText:n})}if(i)throw new qJ({code:`MWL_STRING`,message:`_("...") needs a quoted string`,location:t,lineText:n});return r}function mY(e){return/^_\(\s*["']/.test(e.trim())}function hY(e){let t=[],n=``,r=!1;for(let i=0;i<e.length;i++){let a=e[i];a===`"`&&(r=!r),/\s/.test(a)&&!r?(n&&t.push(n),n=``):n+=a}return n&&t.push(n),t}function gY(e){return e.startsWith(`"`)&&e.endsWith(`"`)?e.slice(1,-1):e}function _Y(e,t,n,r,i){return new qJ({code:e,message:t,location:{file:n??`<mwl>`,line:r+1,column:1},lineText:i})}function vY(e,t,n,r,i){let a=dY(n,r??`<mwl>`,i);return new qJ({code:e,message:t,location:a,lineText:n.split(/\r?\n/)[a.line-1]})}function yY(e,t,n,r){if(!Number.isInteger(t.version)||t.version<1)throw Error(`MWL save version must be a positive integer`);let i={format:`mwl-save`,version:t.version,world:e,...n===void 0?{}:{hookState:wY(n)},...r===void 0?{}:{journal:TY(r)}};return JSON.stringify(i)}function bY(e,t){return xY(e,t).world}function xY(e,t){let n=JSON.parse(e),r=CY(n)?n:{format:`mwl-save`,version:1,world:n};if(r.version>t.version)throw Error(`MWL save version ${r.version} is newer than supported version ${t.version}`);let i=SY(r.world);for(let e=r.version;e<t.version;e++){let n=t.migrations?.[e+1];if(!n)throw Error(`missing MWL save migration to version ${e+1}`);i=SY(n(i))}return{format:`mwl-save`,version:t.version,world:i,...r.hookState===void 0?{}:{hookState:wY(r.hookState)},...r.journal===void 0?{}:{journal:TY(r.journal)}}}function SY(e){if(!e||typeof e!=`object`)throw Error(`invalid MWL saved world`);jt(e);let t=e;if(!Number.isInteger(t.turn)||!t.variables||typeof t.variables!=`object`||!t.units||typeof t.units!=`object`)throw Error(`invalid MWL saved world: turn, variables, and units are required`);if(t.status!==void 0&&![`playing`,`won`,`lost`].includes(t.status))throw Error(`invalid MWL saved world status`);return Ht(t,`saved world`)}function CY(e){return!!e&&typeof e==`object`&&e.format===`mwl-save`&&typeof e.version==`number`&&`world`in e}function wY(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`invalid MWL hook state`);jt(e);let t;try{t=JSON.stringify(e)}catch{throw Error(`MWL hook state must be JSON-serialisable`)}let n=JSON.parse(t);if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`invalid MWL hook state`);return n}function TY(e){try{let t=JSON.stringify(e),n=JSON.parse(t);if(!Array.isArray(n))throw Error();return jt(n),n}catch{throw Error(`MWL journal must be JSON-serialisable`)}}function EY(e,t,n={}){let r=e.search(/\s+where\s+/),i=r<0?e:e.slice(0,r),a={...t};if(r>=0)for(let t of e.slice(r).replace(/^\s+where\s+/,``).split(`,`)){let e=/^\s*([A-Za-z_][A-Za-z0-9_.-]*)\s*=\s*(.+)\s*$/.exec(t);if(!e)throw Error(`invalid MWL where binding: ${t}`);let r=new DY(e[2],a,n.helpers??{});if(a[e[1]]=r.parseOr(),!r.atEnd())throw Error(`invalid MWL where binding: ${t}`)}let o=new DY(i,a,n.helpers??{}),s=o.parseOr();if(!o.atEnd())throw Error(`unexpected token in MWL condition: ${o.peek()}`);return kY(s)}var DY=class{constructor(e,t,n){this.index=0,this.tokens=OY(e),this.context=t,this.helpers=n}parseOr(){let e=this.parseAnd();for(;this.take(`or`);)e=kY(e)||kY(this.parseAnd());return e}parseAnd(){let e=this.parseNot();for(;this.take(`and`);)e=kY(e)&&kY(this.parseNot());return e}parseNot(){return this.take(`not`)?!kY(this.parseNot()):this.parseComparison()}parseComparison(){let e=this.parseAdditive(),t=this.peek();if(![`==`,`~=`,`<`,`<=`,`>`,`>=`].includes(t))return e;this.index++;let n=this.parseAdditive();if(t===`==`)return e===n;if(t===`~=`)return e!==n;if(typeof e!=`number`||typeof n!=`number`)throw Error(`${t} requires numeric operands`);return t===`<`?e<n:t===`<=`?e<=n:t===`>`?e>n:e>=n}parseAdditive(){let e=this.parseMultiplicative();for(;this.peek()===`+`||this.peek()===`-`;){let t=this.tokens[this.index++],n=this.parseMultiplicative();if(typeof e!=`number`||typeof n!=`number`)throw Error(`${t} requires numeric operands`);e=t===`+`?e+n:e-n}return e}parseMultiplicative(){let e=this.parsePrimary();for(;this.peek()===`*`||this.peek()===`/`;){let t=this.tokens[this.index++],n=this.parsePrimary();if(typeof e!=`number`||typeof n!=`number`)throw Error(`${t} requires numeric operands`);if(t===`/`&&n===0)throw Error(`division by zero in MWL condition`);e=t===`*`?e*n:e/n}return e}parsePrimary(){if(this.take(`(`)){let e=this.parseOr();return this.expect(`)`),e}let e=this.tokens[this.index++];if(e===void 0)throw Error(`incomplete MWL condition`);if(/^-?(?:\d+(?:\.\d*)?|\.\d+)$/.test(e))return Number(e);if(e===`true`||e===`yes`)return!0;if(e===`false`||e===`no`)return!1;if(e.startsWith(`"`)||e.startsWith(`'`))return e.slice(1,-1);let t=this.helpers[e];if(t&&this.take(`(`)){let e=[];if(!this.take(`)`)){do e.push(this.parseOr());while(this.take(`,`));this.expect(`)`)}return t(...e)}let n=this.context[e];if(n===void 0)throw Error(`missing MWL condition variable "${e}"`);return n}take(e){return this.peek()===e&&(this.index++,!0)}expect(e){if(!this.take(e))throw Error(`expected "${e}" in MWL condition`)}peek(){return this.tokens[this.index]??`<end>`}atEnd(){return this.index>=this.tokens.length}};function OY(e){let t=[],n=/\s*(?:("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')|([A-Za-z_][A-Za-z0-9_.-]*)|(-?(?:\d+(?:\.\d*)?|\.\d+))|(==|~=|<=|>=|[()+*/,<>-]))/y,r=0;for(;r<e.length;){n.lastIndex=r;let i=n.exec(e);if(!i)throw Error(`invalid MWL condition near "${e.slice(r)}"`);t.push(i[1]??i[2]??i[3]??i[4]),r=n.lastIndex}return t}function kY(e){return e!==!1&&e!==0&&e!==``}function AY(e){let t=new IY(e),n=t.expression();if(t.skip(),!t.atEnd())throw Error(`invalid MWL expression near "${t.rest()}"`);return n}function jY(e,t){let n=typeof e==`string`?AY(e):e;if(n.kind===`number`)return n.value;if(n.kind===`variable`){let e=t[n.name];if(e===void 0||!Number.isFinite(e))throw Error(`missing MWL expression variable "${n.name}"`);return e}let r=jY(n.left,t),i=jY(n.right,t);if(n.op===`+`)return r+i;if(n.op===`-`)return r-i;if(n.op===`*`)return r*i;if(n.op===`/`){if(i===0)throw Error(`division by zero in MWL expression`);return r/i}return r**i}var MY=256,NY=4096,PY=/(?:\d+(?:\.\d*)?|\.\d+)/y,FY=/[A-Za-z_][A-Za-z0-9_.-]*/y,IY=class{constructor(e){this.index=0,this.depth=0,this.operators=0,this.source=e}expression(){return this.additive()}additive(){let e=this.multiplicative();for(;;){this.skip();let t=this.peek(`+`)?`+`:this.peek(`-`)?`-`:null;if(!t)return e;this.index++,this.operator(),e={kind:`binary`,op:t,left:e,right:this.multiplicative()}}}multiplicative(){let e=this.power();for(;;){this.skip();let t=this.peek(`*`)?`*`:this.peek(`/`)?`/`:null;if(!t)return e;this.index++,this.operator(),e={kind:`binary`,op:t,left:e,right:this.power()}}}power(){let e=this.primary();return this.skip(),this.peek(`^`)&&(this.index++,this.operator(),e={kind:`binary`,op:`^`,left:e,right:this.nested(()=>this.power())}),e}primary(){if(this.skip(),this.peek(`(`)){this.index++;let e=this.nested(()=>this.expression());if(this.skip(),!this.peek(`)`))throw Error(`missing closing parenthesis in MWL expression`);return this.index++,e}let e=this.match(PY);if(e)return this.index+=e[0].length,{kind:`number`,value:Number(e[0])};let t=this.match(FY);if(t)return this.index+=t[0].length,{kind:`variable`,name:t[0]};throw Error(`expected number, variable, or parenthesis near "${this.rest()}"`)}match(e){return e.lastIndex=this.index,e.exec(this.source)}nested(e){if(++this.depth>MY)throw Error(`MWL expression is nested more than ${MY} deep`);try{return e()}finally{this.depth--}}operator(){if(++this.operators>NY)throw Error(`MWL expression has more than ${NY} operators`)}peek(e){return this.source[this.index]===e}skip(){for(;/\s/.test(this.source[this.index]??``);)this.index++}atEnd(){return this.index>=this.source.length}rest(){let e=this.source.slice(this.index,this.index+40);return this.index+40<this.source.length?`${e}...`:e}};function LY(e){let t=[],n=e=>{t.push(e),e.children.forEach(n)};return e.forEach(n),t}function RY(e,t){let n=e.attributes[t];if(!n)throw Error(`MWL ${e.tag} is missing ${t}`);return n}function zY(e,t){let n=e.attributes[t];if(n===void 0)return;let r=Number(n);return Number.isFinite(r)?r:void 0}function BY(e,t,n){let r=e.attributes[t];if(r===void 0)return n;let i=Number.parseInt(r,10);return Number.isFinite(i)?i:n}function VY(e,t){return HY(e.attributes[t])}function HY(e){return e===void 0?void 0:e===`true`||e===`yes`}function UY(e,t){return e!==void 0&&t.includes(e)?e:void 0}function WY(e,t,n){let r=n.carryoverPercentage??80,i=t?e.gold[t.id]??e.sides[t.id]?.gold??0:0;return{result:n.result,gold:Math.floor(i*r/100)+(n.bonus??0),add:n.carryoverAdd??!1,recall:t?Object.entries(e.units).filter(([,e])=>e.alive&&e.side===t.id).map(([e])=>e).sort():[],nextScenario:n.nextScenario??null}}function GY(e,t){return e.add?t+e.gold:Math.max(t,e.gold)}_e();var KY=RY,qY=(e,t,n)=>BY(e,t,n)??n;function JY(){return{variables:{},units:{},sides:{},maps:{},gold:{},turn:1,status:`playing`,sideStatus:{},map:null,timeOfDay:``,scheduleIndex:0}}var YY=1048576;function XY(e){let t=e.split(/\r?\n/).filter(e=>e.trim()!==``).map(e=>e.split(`,`).map(e=>e.trim())),n=t.length,r=t.reduce((e,t)=>Math.max(e,t.length),0);if(r*n>YY)throw Error(`MWL terrain is ${r}x${n}, more than ${YY} cells`);let i=[],a={};for(let e=0;e<n;e++)for(let n=0;n<r;n++){let r=t[e]?.[n]??`_off^_usr`,o=/^([A-Za-z0-9_][\w.-]*)\s+(\S.*)$/.exec(r);o?(i.push(o[2]),(a[o[1]]??=[]).push({x:n,y:e})):i.push(r)}return{width:r,height:n,codes:i,starts:a}}var ZY=/\$\(([^)]*)\)/g,QY=/\$([A-Za-z_][A-Za-z0-9_.]*)/g,$Y=class e{constructor(e,t={}){this.journal=new Cn,this.unitTypes=new Map,this.schedule=[],this.pendingDialogue=null,this.dialogueCounter=0,this.traceBatch=null,this.game=e,this.world=t.world??JY(),this.onMessage=t.onMessage,this.resolveMap=t.resolveMap,this.hooks=t.hooks,this.onTrace=t.onTrace,this.persistence=t.persistence??{version:1},this.random=t.random??new j,!t.random&&this.world.random&&this.random.setState(this.world.random),this.loadUnitTypes(),this.loadSchedule(),this.loadInitialContent(),this.loadInitialUnits(),this.loadLeaders(),this.loadScenarioExtras()}run(e){this.recordAction({type:`run`,trigger:e},()=>this.runInternal(e))}runInternal(e){for(let t of this.nodes(`event`))(t.attributes.on??t.attributes.trigger)===e&&this.eventFiltersMatch(t)&&this.claimEvent(t)&&this.executeTracedEvent(t,e);this.checkObjectives()}fireEvent(e){return this.recordAction({type:`fire_event`,id:e},()=>this.fireEventInternal(e))}fireEventInternal(e){let t=this.nodes(`event`).find(t=>t.attributes.id===e);return!t||!this.eventFiltersMatch(t)||!this.claimEvent(t)?!1:(this.executeTracedEvent(t,`fireEvent`),this.checkObjectives(),!0)}fireMoveto(e){this.recordAction({type:`fire_moveto`,unit:e},()=>this.fireMovetoInternal(e))}fireMovetoInternal(e){let t=this.world.units[e];if(t&&t.alive){for(let n of this.nodes(`event`))(n.attributes.on??n.attributes.trigger)===`moveto`&&(n.attributes.x===void 0||bX(n.attributes.x,t.x))&&(n.attributes.y===void 0||bX(n.attributes.y,t.y))&&(n.attributes.unit===void 0||n.attributes.unit===e)&&(n.attributes.side===void 0||n.attributes.side===t.side)&&this.eventFiltersMatch(n)&&this.claimEvent(n)&&this.executeTracedEvent(n,`moveto`);this.checkObjectives()}}claimEvent(e){if(!(e.attributes.once===void 0?e.attributes.on===`moveto`:e.attributes.once!==`false`))return!0;let t=e.attributes.id??`${e.attributes.on??e.attributes.trigger??`event`}@${e.location?.line??0}`,n=this.world.firedEvents??=[];return!n.includes(t)&&(n.push(t),!0)}eventFiltersMatch(e){if(!this.conditionMatches(e)||!this.filterConditionMatches(e))return!1;let t=e.children.find(e=>e.tag===`filter`);return!t||this.filterMatches(t)}executeEvent(e){this.runBlock(this.commandChildren(e))}runBlock(e){for(let t=0;t<e.length;t++){let n=e[t];if(!this.isConsumedElse(e,t)){if(n.tag===`say`){this.showSay(n);continue}if(n.tag===`dialogue`){this.showDialogue(n);continue}this.executeNode(n)}}}isConsumedElse(e,t){let n=e[t-1];return e[t]?.tag===`else`&&n?.tag===`if`&&this.nodeConditionMatches(n)}executeTracedEvent(e,t){let n=e.attributes.id??`${e.attributes.on??e.attributes.trigger??`event`}@${e.location?.line??0}`;this.trace({type:`event`,phase:`claimed`,id:n,trigger:t});try{this.executeEvent(e),this.trace({type:`event`,phase:`completed`,id:n,trigger:t})}catch(e){throw this.trace({type:`error`,message:String(e),event:n}),e}}showDialogue(e){let t=null;for(let n of e.children)n.tag===`message`?(this.showMessage(n.attributes),t={text:n.attributes.text??n.attributes.value??``,...n.attributes.speaker===void 0?{}:{speaker:n.attributes.speaker},...n.attributes.portrait===void 0?{}:{portrait:n.attributes.portrait},...n.attributes.side===void 0||n.attributes.side===``?{}:{side:n.attributes.side}}):n.tag===`say`&&(this.showSay(n),t={text:n.attributes.text??``,speaker:n.attributes.speaker});let n=[];for(let t of e.children){if(t.tag!==`choice`||!t.attributes.text||t.attributes.variable!==void 0&&!fX(this.variableAt(t.attributes.variable),t.attributes.equals))continue;let e=t.children.filter(e=>e.tag===`branch`);if(e.length)for(let r of e)n.push({text:r.attributes.text??t.attributes.text,branch:r.children});else t.attributes.event&&n.push({text:t.attributes.text,event:t.attributes.event})}if(n.length===0)return;this.dialogueCounter+=1;let r=`dialogue-${this.dialogueCounter}`;this.pendingDialogue={id:r,choices:n},this.world.pendingDialogue={id:r,choices:n},this.onMessage?.({text:t?.text??``,...t?.speaker===void 0?{}:{speaker:t.speaker},choices:n,dialogueId:r})}showSay(e){this.onMessage&&this.onMessage({text:e.attributes.text??``,...e.attributes.speaker===void 0?{}:{speaker:e.attributes.speaker}})}answerDialogue(e,t){return this.recordAction({type:`answer_dialogue`,dialogueId:e,choiceIndex:t},()=>this.answerDialogueInternal(e,t))}answerDialogueInternal(e,t){let n=this.pendingDialogue;if(!n||n.id!==e)return!1;let r=n.choices[t];if(!r)return!1;if(this.pendingDialogue=null,delete this.world.pendingDialogue,r.event){let e=this.nodes(`event`).find(e=>e.attributes.id===r.event);if(!e)throw Error(`MWL dialogue choice points at unknown event: ${r.event}`);if(!this.claimEvent(e))return!0;this.executeEvent(e)}else this.runBlock(r.branch??[]);return this.checkObjectives(),!0}evaluate(){return this.checkObjectives(),this.world.status}save(){let e=this.hooks?.saveable,t=e?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.save()])):void 0;return yY(this.world,this.persistence,t,this.journal.toJSON())}snapshot(){return JSON.stringify(this.world)}restore(e){let t=xY(e,this.persistence),n=t.world;Object.assign(this.world.variables,n.variables),Object.assign(this.world.units,n.units),Object.assign(this.world.sides,n.sides??{}),Object.assign(this.world.maps,n.maps??{}),Object.assign(this.world.gold,n.gold??{}),this.world.turn=n.turn,this.world.status=n.status,this.world.sideStatus={...n.sideStatus??{}},this.world.map=n.map??null,this.world.timeOfDay=n.timeOfDay??this.schedule[0]??``,this.world.scheduleIndex=n.scheduleIndex??0,this.world.random=n.random,this.random.setState(n.random??new j().getState()),this.world.firedEvents=[...n.firedEvents??[]],this.world.villages=n.villages?structuredClone(n.villages):void 0,this.world.clearedShroud=n.clearedShroud?structuredClone(n.clearedShroud):void 0,this.world.roles=n.roles?structuredClone(n.roles):void 0,this.world.objects=n.objects?structuredClone(n.objects):void 0,this.world.story=n.story?structuredClone(n.story):void 0,this.world.pendingDialogue=n.pendingDialogue,this.pendingDialogue=n.pendingDialogue?{id:n.pendingDialogue.id,choices:[...n.pendingDialogue.choices]}:null;let r=n.pendingDialogue?.id.match(/^dialogue-(\d+)$/);r&&(this.dialogueCounter=Math.max(this.dialogueCounter,Number(r[1])));for(let[e,n]of Object.entries(t.hookState??{}))this.hooks?.saveable?.[e]?.restore(n);this.journal.replace(t.journal??[])}recordAction(e,t){let n=this.traceBatch===null;n&&(this.traceBatch=[]);try{let r=t();return n&&this.journal.append(e,this.traceBatch??[]),r}finally{n&&(this.traceBatch=null)}}trace(e){this.traceBatch?.push(e),this.onTrace?.(e)}loadUnitTypes(){for(let e of this.nodes(`unit_type`)){let t=e.attributes.id;t&&this.unitTypes.set(t,{hitpoints:qY(e,`hitpoints`,1),movement:qY(e,`movement`,0)})}}loadSchedule(){this.schedule=this.nodes(`schedule`).flatMap(e=>e.children.filter(e=>e.tag===`time`).map(e=>e.attributes.id).filter(e=>!!e)),this.world.scheduleIndex=0,this.world.timeOfDay=this.schedule[0]??``}loadInitialContent(){for(let e of this.nodes(`side`)){let t={gold:qY(e,`gold`,0),income:qY(e,`income`,0)};e.attributes.leader!==void 0&&(t.leader=e.attributes.leader),e.attributes.controller!==void 0&&(t.controller=e.attributes.controller),e.attributes.recruit!==void 0&&(t.recruit=e.attributes.recruit),e.attributes.team_name!==void 0&&(t.teamName=e.attributes.team_name),e.attributes.user_team_name!==void 0&&(t.userTeamName=e.attributes.user_team_name),e.attributes.share_vision!==void 0&&(t.shareVision=e.attributes.share_vision),e.attributes.flag!==void 0&&(t.flag=e.attributes.flag),e.attributes.village_gold!==void 0&&(t.villageGold=qY(e,`village_gold`,0));for(let n of[`heal`,`fog`,`shroud`,`hidden`]){let r=e.attributes[n];r!==void 0&&(t[n]=r===`yes`||r===`true`)}this.world.sides[KY(e,`id`)]=t}for(let e of this.nodes(`map`)){let t=e.attributes.id??e.attributes.name??`map`;this.world.maps[t]={terrain:e.attributes.terrain??``,file:e.attributes.file},this.world.map||(this.world.map=this.buildMap(t,e))}}topLevelNodes(e){return(this.game.roots.find(e=>e.tag===`game`)?.children??this.game.roots).filter(t=>t.tag===e)}loadScenarioExtras(){for(let e of this.topLevelNodes(`object`)){let t={x:qY(e,`x`,0),y:qY(e,`y`,0)};e.attributes.id!==void 0&&(t.id=e.attributes.id),e.attributes.name!==void 0&&(t.name=e.attributes.name),e.attributes.image!==void 0&&(t.image=e.attributes.image),e.attributes.side!==void 0&&(t.side=e.attributes.side),(this.world.objects??=[]).push(t)}for(let e of this.topLevelNodes(`story`)){let t=e.attributes.text??e.attributes.value;if(t===void 0)continue;let n={text:t};e.attributes.title!==void 0&&(n.title=e.attributes.title),e.attributes.image!==void 0&&(n.image=e.attributes.image),e.attributes.music!==void 0&&(n.music=e.attributes.music),(this.world.story??=[]).push(n)}for(let e of this.topLevelNodes(`role`)){let t=e.attributes.role??e.attributes.name;if(t===void 0)continue;let n=dX(e.attributes,`role`,`name`),r=Object.entries(this.world.units).filter(([e,t])=>t.alive&&uX(t,e,n));for(let[,e]of r)e.role=t;(this.world.roles??={})[t]=r.map(([e])=>e)}}buildMap(e,t){let n=t.attributes.terrain;if(!n&&t.attributes.file&&this.resolveMap&&(n=this.resolveMap(t.attributes.file)),!n)return null;let r=XY(n);for(let e of t.children){if(e.tag!==`start`)continue;let t=e.attributes.side,n=cX(e,`x`),i=cX(e,`y`);t!==void 0&&n!==void 0&&i!==void 0&&(r.starts[t]??=[]).push({x:n,y:i})}return{id:e,...r}}loadInitialUnits(){for(let e of this.nodes(`unit`)){let t=KY(e,`id`),n={hp:qY(e,`hp`,1),x:qY(e,`x`,0),y:qY(e,`y`,0),alive:!0};if(e.attributes.type!==void 0){n.type=e.attributes.type;let t=this.unitTypes.get(e.attributes.type);t&&(n.moves=t.movement)}e.attributes.side!==void 0&&(n.side=e.attributes.side),e.attributes.name!==void 0&&(n.name=e.attributes.name),e.attributes.role!==void 0&&(n.role=e.attributes.role);let r=VY(e,`can_recruit`);r!==void 0&&(n.can_recruit=r),this.world.units[t]=n}}loadLeaders(){for(let e of this.nodes(`side`)){let t=e.attributes.leader;if(!t)continue;let n=e.attributes.id;if(!n)continue;let r=this.world.map?.starts[n];if(!r?.length)continue;let i=this.unitTypes.get(t);for(let e of r){if(this.unitAt(e.x,e.y))continue;let r=`${t} ${n} (${e.x},${e.y})`;this.world.units[r]={hp:i?.hitpoints??1,x:e.x,y:e.y,alive:!0,type:t,side:n,moves:i?.movement??0,can_recruit:!0,leader:!0}}}}unitAt(e,t){return Object.values(this.world.units).find(n=>n.alive&&n.x===e&&n.y===t)}static{this.commandHandlers={message:(e,t)=>e.showMessage(t.attributes),spawn:(e,t)=>e.cmdSpawn(t),move:(e,t)=>e.cmdMove(t),kill:(e,t)=>e.cmdKill(t),fire_event:(e,t)=>e.cmdFireEvent(t),store_unit:(e,t)=>e.cmdStoreUnit(t),unstore_unit:(e,t)=>e.cmdUnstoreUnit(t),recall:(e,t)=>e.cmdRecall(t),modify_unit:(e,t)=>e.cmdModifyUnit(t),heal_unit:(e,t)=>e.cmdHealUnit(t),set_terrain:(e,t)=>e.setTerrain(qY(t,`x`,0),qY(t,`y`,0),KY(t,`terrain`)),capture_village:(e,t)=>e.cmdCaptureVillage(t),clear_shroud:(e,t)=>e.cmdClearShroud(t),role:(e,t)=>e.cmdRole(t),attack:(e,t)=>e.attack(t.attributes.defender??t.attributes.target??KY(t,`target`),qY(t,`amount`,0)),modify_gold:(e,t)=>e.addGold(t.attributes.side??KY(t,`target`),qY(t,`delta`,qY(t,`amount`,0))),gold:(e,t)=>e.addGold(KY(t,`side`),qY(t,`delta`,qY(t,`amount`,0))),set_variable:(e,t)=>e.cmdSetVariable(t),while:(e,t)=>e.cmdWhile(t),foreach:(e,t)=>e.cmdForeach(t),switch:(e,t)=>e.cmdSwitch(t),end_turn:e=>e.endTurn(),win:(e,t)=>e.cmdWin(t),lose:(e,t)=>e.cmdLose(t),endlevel:(e,t)=>e.cmdEndlevel(t),if:(e,t)=>e.cmdIf(t),else:(e,t)=>e.runBlock(e.commandChildren(t)),hook:(e,t)=>e.runHook(t)}}executeNode(t){let n=t.tag===`command`?t.attributes.name:t.tag;if(!n)throw Error(`MWL command is missing name`);let r=e.commandHandlers[n];if(!r)throw Error(`unknown MWL command: ${n}`);r(this,t)}cmdSpawn(e){this.spawnUnit(e.attributes.type??``,e.attributes.side,qY(e,`x`,0),qY(e,`y`,0),e.attributes.id??e.attributes.target,e.attributes.hp===void 0?void 0:qY(e,`hp`,1))}cmdMove(e){this.applyMove(e.attributes.unit??KY(e,`target`),qY(e,`x`,0),qY(e,`y`,0))}cmdKill(e){let t=e.attributes.unit??e.attributes.target;t===void 0?iX(this.world,e.attributes):this.killUnit(t)}cmdFireEvent(e){let t=e.attributes.id??e.attributes.name;if(!t)throw Error(`[fire_event] requires id`);this.fireEvent(t)}cmdStoreUnit(e){let t=e.attributes.variable??e.attributes.name??KY(e,`variable`);this.setVariableAt(t,this.matchingUnits(e,[`variable`,`name`]).map(([e,t])=>({id:e,...aX(t)})))}cmdUnstoreUnit(e){let t=KY(e,`variable`);for(let e of this.storedUnits(t))this.restoreUnit(e,{})}cmdRecall(e){let t=this.storedUnits(KY(e,`variable`)),n=e.attributes.id??e.attributes.unit,r=n===void 0?t[0]:t.find(e=>e.id===n);if(!r)throw Error(`[recall] found no stored unit${n===void 0?``:` named ${n}`}`);let i={};e.attributes.x!==void 0&&(i.x=qY(e,`x`,0)),e.attributes.y!==void 0&&(i.y=qY(e,`y`,0)),e.attributes.side!==void 0&&(i.side=e.attributes.side),this.restoreUnit(r,i)}cmdModifyUnit(e){let t=e.children.find(e=>e.tag===`set`)?.attributes??e.attributes;for(let[,n]of this.matchingUnits(e))oX(n,t)}cmdHealUnit(e){let t=cX(e,`amount`),n=cX(e,`hp`);if(t===void 0&&n===void 0)throw Error(`[heal_unit] requires amount or hp`);for(let[,r]of this.matchingUnits(e))r.hp=n??r.hp+(t??0)}cmdCaptureVillage(e){let t=qY(e,`x`,0),n=qY(e,`y`,0),r={x:t,y:n,side:KY(e,`side`)};e.attributes.name!==void 0&&(r.name=e.attributes.name),(this.world.villages??={})[`${t},${n}`]=r}cmdClearShroud(e){let t=KY(e,`side`),n=qY(e,`x`,0),r=qY(e,`y`,0),i=qY(e,`radius`,1),a=new Set(this.world.clearedShroud?.[t]??[]);for(let e=-i;e<=i;e++)for(let t=-i;t<=i;t++)a.add(`${n+t},${r+e}`);(this.world.clearedShroud??={})[t]=[...a]}cmdRole(e){let t=e.attributes.role??e.attributes.name;if(!t)throw Error(`[role] requires role`);let n=this.matchingUnits(e,[`role`,`name`]);for(let[,e]of n)e.role=t;(this.world.roles??={})[t]=n.map(([e])=>e)}cmdSetVariable(e){let t=e.attributes.path;this.setVariable(t===void 0?e.tag===`command`?KY(e,`target`):KY(e,`name`):this.expandPath(t),e.attributes.value??``,e.attributes.mode)}cmdWhile(e){let t=qY(e,`max_iterations`,1e3);if(t<1||t>1e5)throw Error(`MWL while max_iterations must be between 1 and 100000`);for(let n=0;n<t&&this.nodeConditionMatches(e);n++)this.runBlock(this.commandChildren(e))}cmdForeach(e){let t=this.variableAt(KY(e,`variable`)),n=Array.isArray(t)?t.map((e,t)=>[String(t),e]):typeof t==`string`?t.split(`,`).map((e,t)=>[String(t),e.trim()]).filter(([,e])=>e!==``):t&&typeof t==`object`?Object.entries(t):[],r=e.attributes.item??`item`,i=e.attributes.index??`index`;for(let t=0;t<n.length;t++)this.setVariableAt(r,n[t][1]),this.setVariableAt(i,t),this.runBlock(this.commandChildren(e))}cmdSwitch(e){let t=this.variableAt(KY(e,`variable`)),n=e.children.find(e=>e.tag===`case`&&e.attributes.equals!==void 0&&fX(t,e.attributes.equals)),r=e.children.find(e=>e.tag==="default");this.runBlock((n??r)?.children??[])}cmdWin(e){this.markSideResult(e.attributes.side,`won`),this.world.status=`won`}cmdLose(e){this.markSideResult(e.attributes.side,`lost`),this.world.status=`lost`}cmdEndlevel(e){let t=e.attributes.result===`defeat`?`defeat`:`victory`;this.world.status=t===`defeat`?`lost`:`won`,this.world.carryover=WY(this.world,tX(this.world,e.attributes.side),{result:t,bonus:BY(e,`bonus`),carryoverPercentage:zY(e,`carryover_percentage`),carryoverAdd:VY(e,`carryover_add`),nextScenario:e.attributes.next_scenario??null})}cmdIf(e){let t=e.children.find(e=>e.tag===`else`),n=this.nodeConditionMatches(e)?e:t;this.runBlock(n?this.commandChildren(n):[])}commandChildren(e){return e.children.filter(e=>e.tag!==`condition`&&e.tag!==`filter`&&e.tag!==`filter_condition`)}runHook(e){let t=e.attributes.name??``,n=this.hooks?.command?.[t];if(!n)throw Error(`MWL hook ${t} is not implemented`);let{name:r,...i}=e.attributes;n(this.worldView(),this.emit(),i)}applyMove(e,t,n){let r=this.world.units[e];if(!r||!r.alive)throw Error(`MWL unit is not alive: ${e}`);let i=this.world.map??null;if(i){if(t<0||n<0||t>=i.width||n>=i.height)throw Error(`MWL move out of bounds: ${t},${n}`);let e=this.unitAt(t,n);if(e&&e!==r)throw Error(`MWL move onto an occupied cell: ${t},${n}`)}if(typeof r.moves==`number`){if(r.moves<=0)throw Error(`MWL unit has no moves left: ${e}`);--r.moves}r.x=t,r.y=n,this.fireMoveto(e)}showMessage(e){if(!this.onMessage)return;let t={text:this.interpolate(e.text??e.value??``),...e.speaker===void 0?{}:{speaker:e.speaker},...e.portrait===void 0?{}:{portrait:e.portrait},...e.side===void 0||e.side===``?{}:{side:e.side}};this.onMessage(t)}interpolate(e){let t=this.numericVariables();return e.replace(ZY,(e,n)=>{try{return String(jY(n,t))}catch{return``}}).replace(QY,(e,t)=>{let n=this.variableAt(t);return n===void 0||typeof n==`boolean`?``:String(n)})}expandPath(e){return e.replace(ZY,(e,t)=>String(jY(t,this.numericVariables()))).replace(QY,(e,t)=>{let n=this.variableAt(t);if(n===void 0)throw Error(`MWL variable path reference "$${t}" names no variable`);if(typeof n==`boolean`||typeof n==`object`)throw Error(`MWL variable path reference "$${t}" is not a name or number`);return String(n)})}setVariable(e,t,n){if(n===`literal`){this.setVariableAt(e,t);return}if(n===`number`){let n=Number(t);if(t.trim()===``||!Number.isFinite(n))throw Error(`MWL set_variable mode="number" needs a number, got "${t}"`);this.setVariableAt(e,n);return}if(n===`expression`){this.setVariableAt(e,jY(t,this.numericVariables()));return}if(n!==void 0)throw Error(`unknown MWL set_variable mode "${n}"`);let r=Number(t);if(t.trim()!==``&&Number.isFinite(r)){this.setVariableAt(e,r);return}let i=/^\$([A-Za-z_][A-Za-z0-9_.]*)$/.exec(t.trim());if(i){let t=this.variableAt(i[1]);this.setVariableAt(e,t===void 0?``:t);return}let a=this.numericVariables();if(/[+*/^()]|\s-\s/.test(t)||Object.prototype.hasOwnProperty.call(a,t.trim())){this.setVariableAt(e,jY(t,a));return}this.setVariableAt(e,t)}numericVariables(){return Object.fromEntries(Object.entries(this.world.variables).filter(e=>typeof e[1]==`number`))}variableAt(e){return vX(this.world.variables,e)}setVariableAt(e,t){let n=this.variableAt(e);_X(this.world.variables,e,t),this.trace({type:`variable`,name:e,...n===void 0?{}:{previous:n},value:t})}spawnUnit(e,t,n,r,i,a){let o=e?this.unitTypes.get(e):void 0,s=i??`${e||`unit`}#${t??``}@${n},${r}`;this.world.units[s]={hp:a??o?.hitpoints??1,x:n,y:r,alive:!0,...e?{type:e}:{},...t===void 0?{}:{side:t},...o?{moves:o.movement}:{}}}killUnit(e){let t=this.world.units[e];if(!t||!t.alive)throw Error(`MWL unit is not alive: ${e}`);t.alive=!1}matchingUnits(e,t=[]){let n=e.children.find(e=>e.tag===`filter`),r=n?n.attributes:dX(e.attributes,...t);return Object.entries(this.world.units).filter(([e,t])=>t.alive&&uX(t,e,r))}storedUnits(e){let t=this.variableAt(e);if(!Array.isArray(t))throw Error(`MWL variable ${e} is not a stored unit list; store one first`);return t.filter(e=>!!e&&typeof e==`object`&&!Array.isArray(e))}restoreUnit(e,t){let n=typeof e.id==`string`?e.id:void 0;if(!n)throw Error(`a stored unit snapshot is missing its id`);let r={hp:typeof e.hp==`number`?e.hp:1,x:t.x??(typeof e.x==`number`?e.x:0),y:t.y??(typeof e.y==`number`?e.y:0),alive:e.alive!==!1};typeof e.type==`string`&&(r.type=e.type);let i=t.side??(typeof e.side==`string`?e.side:void 0);i!==void 0&&(r.side=i),typeof e.moves==`number`&&(r.moves=e.moves),typeof e.name==`string`&&(r.name=e.name),typeof e.role==`string`&&(r.role=e.role),typeof e.can_recruit==`boolean`&&(r.can_recruit=e.can_recruit),typeof e.leader==`boolean`&&(r.leader=e.leader),this.world.units[n]=r}setTerrain(e,t,n){let r=this.world.map;if(!r)throw Error(`[set_terrain] needs a loaded map`);if(e<0||t<0||e>=r.width||t>=r.height)throw Error(`[set_terrain] is outside the map: ${e},${t}`);let i=[...r.codes];i[t*r.width+e]=n,this.world.map={...r,codes:i}}addGold(e,t){this.world.gold[e]=(this.world.gold[e]??0)+t}endTurn(){this.world.turn+=1,this.advanceSchedule(),this.resetMoves(),this.run(`turn`),this.checkTimeOver()}checkTimeOver(){let e=BY(this.game.roots[0],`turn_limit`);e===void 0||this.world.turn<=e||this.world.variables.time_over===`yes`||(this.world.variables.time_over=`yes`,this.run(`time_over`))}advanceSchedule(){if(!this.schedule.length)return;let e=((this.world.scheduleIndex??0)+1)%this.schedule.length;this.world.scheduleIndex=e,this.world.timeOfDay=this.schedule[e]}resetMoves(){for(let e of Object.values(this.world.units)){if(!e.alive)continue;let t=e.type?this.unitTypes.get(e.type):void 0;t&&(e.moves=t.movement)}}filterMatches(e){return Object.entries(this.world.units).some(([t,n])=>n.alive&&uX(n,t,e.attributes))}conditionMatches(e){return e.children.filter(e=>e.tag===`condition`).every(e=>{if(e.attributes.condition===`hook`){let t=e.attributes.hook,n=t?.startsWith(`predicate:`)?t.slice(10):void 0,r=n?this.hooks?.predicate?.[n]:void 0;if(!r)throw Error(`MWL predicate ${n??`<missing>`} is not implemented`);let{condition:i,hook:a,...o}=e.attributes;return!!r(this.worldView(),o)}return lX(this.variableAt(e.attributes.variable),e.attributes,yX(this.world.variables))})}nodeConditionMatches(e){return e.attributes.test===void 0?this.conditionMatches(e):EY(e.attributes.test,pX(this.world.variables))}filterConditionMatches(e){let t=e.children.find(e=>e.tag===`filter_condition`);return!t||t.children.every(e=>{if(e.tag===`variable`){let t=e.attributes.name;return t!==void 0&&lX(this.variableAt(t),e.attributes,yX(this.world.variables))}if(e.tag===`predicate`){let t=e.attributes.name,n=t?this.hooks?.predicate?.[t]:void 0;if(!n)throw Error(`MWL predicate ${t??`<missing>`} is not implemented`);let{name:r,...i}=e.attributes;return!!n(this.worldView(),i)}return e.tag!==`have_unit`||Object.entries(this.world.units).some(([t,n])=>n.alive&&(e.attributes.id===void 0||t===e.attributes.id)&&uX(n,t,e.attributes))})}conditionMet(e,t){let n=e.attributes.condition??``,r=e.attributes.side??t;switch(n){case`units_dead`:{let t=e.attributes.side_filter??r;return t!==void 0&&!Object.values(this.world.units).some(e=>e.alive&&e.side===t)}case`turns_elapsed`:{let t=cX(e,`turns`);return t!==void 0&&this.world.turn>=t}case`gold_at_least`:{let n=cX(e,`gold`),r=e.attributes.side??t;return n!==void 0&&r!==void 0&&(this.world.gold[r]??0)>=n}case`unit_at`:{let t=cX(e,`x`),n=cX(e,`y`),i=e.attributes.side_filter??r;return Object.values(this.world.units).some(r=>r.alive&&(i===void 0||r.side===i)&&(e.attributes.type===void 0||r.type===e.attributes.type)&&r.x===t&&r.y===n)}case`hook`:{let t=e.attributes.hook??``,n=this.hooks?.predicate?.[t];if(!n)throw Error(`MWL hook ${t} is not implemented`);let{hook:r,condition:i,...a}=e.attributes;return!!n(this.worldView(),a)}default:return!1}}checkObjectives(){if(this.world.status!==`playing`)return;let e=new Set,t=this.nodes(`side`);for(let n of t)for(let t of n.children)(t.tag===`victory`||t.tag===`defeat`)&&e.add(t);if(this.nodes(`victory`).some(t=>!e.has(t)&&this.conditionMet(t))){this.world.status=`won`;return}if(this.nodes(`defeat`).some(t=>!e.has(t)&&this.conditionMet(t))){this.world.status=`lost`;return}let n=!1,r=!1;for(let e of t){let t=e.attributes.id;t&&(this.world.sideStatus?.[t]??`playing`)===`playing`&&(e.children.some(e=>e.tag===`victory`&&this.conditionMet(e,t))?(this.markSideResult(t,`won`),n=!0):e.children.some(e=>e.tag===`defeat`&&this.conditionMet(e,t))&&(this.markSideResult(t,`lost`),r=!0))}n?this.world.status=`won`:r&&(this.world.status=`lost`)}markSideResult(e,t){e!==void 0&&e!==``&&((this.world.sideStatus??={})[e]=t)}worldView(){return{variables:this.world.variables,variableAt:e=>this.variableAt(e),units:this.world.units,sides:this.world.sides,turn:this.world.turn,random:{float:()=>this.drawRandom(e=>e.float()),int:e=>this.drawRandom(t=>t.int(e))}}}drawRandom(e){let t=e(this.random);return this.world.random=this.random.getState(),t}emit(){return{move:(e,t,n)=>this.applyMove(e,t,n),attack:(e,t,n)=>{throw Error(`MWL hook attack is not available in the framework runtime; the engine adapter owns combat`)},spawn:(e,t,n,r)=>this.spawnUnit(e,t,n,r),kill:e=>this.killUnit(e),gold:(e,t)=>this.addGold(e,t),setVariable:(e,t)=>{_X(this.world.variables,e,t)},message:(e,t)=>this.onMessage?.({text:t,...e?{speaker:e}:{}}),endTurn:()=>this.endTurn(),win:e=>{this.markSideResult(e,`won`),this.world.status=`won`},lose:e=>{this.markSideResult(e,`lost`),this.world.status=`lost`}}}attack(e,t){let n=this.world.units[e];if(!n||!n.alive)throw Error(`MWL unit is not alive: ${e}`);n.hp=Math.max(0,n.hp-t),n.hp===0&&(n.alive=!1)}nodes(e){let t=[],n=r=>{r.tag===e&&t.push(r),r.children.forEach(n)};return this.game.roots.forEach(n),t}};function eX(e,t){if(e.status===`playing`||t.name===`win`||t.name===`lose`)switch(t.name){case`set_variable`:_X(e.variables,t.target,t.value);break;case`modify_gold`:e.gold[t.target]=(e.gold[t.target]??0)+t.amount;break;case`move`:{let n=rX(e,t.target);n.x=t.x,n.y=t.y;break}case`spawn`:e.units[t.target]={hp:t.hp,x:t.x,y:t.y,alive:!0};break;case`kill`:t.target===void 0?iX(e,t.filter??{}):rX(e,t.target).alive=!1;break;case`end_turn`:e.turn++;break;case`win`:t.side!==void 0&&t.side!==``&&((e.sideStatus??={})[t.side]=`won`),e.status=`won`;break;case`lose`:t.side!==void 0&&t.side!==``&&((e.sideStatus??={})[t.side]=`lost`),e.status=`lost`;break;case`endlevel`:e.status=t.result===`defeat`?`lost`:`won`,e.carryover=WY(e,t.side??null,t)}}function tX(e,t){let n=t??Object.entries(e.sides).find(([,e])=>e.controller===`human`)?.[0];return!n||!(n in e.sides)?null:{id:n}}function nX(e){let t=new Map;for(let[n,r]of Object.entries(e.sides)){if(!r.teamName||r.shareVision===`none`)continue;let e=t.get(r.teamName);e?e.push(n):t.set(r.teamName,[n])}return[...t.values()].filter(e=>e.length>1)}function rX(e,t){let n=e.units[t];if(!n||!n.alive)throw Error(`MWL unit is not alive: ${t}`);return n}function iX(e,t){let n=0;for(let[r,i]of Object.entries(e.units))i.alive&&uX(i,r,t)&&(i.alive=!1,n++);return n}function aX(e){let t={hp:e.hp,x:e.x,y:e.y,alive:e.alive};return e.type!==void 0&&(t.type=e.type),e.side!==void 0&&(t.side=e.side),e.moves!==void 0&&(t.moves=e.moves),e.name!==void 0&&(t.name=e.name),e.role!==void 0&&(t.role=e.role),e.can_recruit!==void 0&&(t.can_recruit=e.can_recruit),e.leader!==void 0&&(t.leader=e.leader),t}function oX(e,t){let n=sX(t.hp);n!==void 0&&(e.hp=n);let r=sX(t.moves);r!==void 0&&(e.moves=r),t.type!==void 0&&(e.type=t.type),t.side!==void 0&&(e.side=t.side);let i=HY(t.alive);i!==void 0&&(e.alive=i),t.name!==void 0&&(e.name=t.name),t.role!==void 0&&(e.role=t.role);let a=HY(t.can_recruit);a!==void 0&&(e.can_recruit=a)}function sX(e){if(e===void 0||e===``)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function cX(e,t){let n=e.attributes[t];if(n===void 0||n===``)return;let r=Number.parseInt(n,10);return Number.isFinite(r)?r:void 0}function lX(e,t,n){let r=e=>{if(!e.startsWith(`$`))return e;let t=n(e.slice(1));return typeof t==`string`||typeof t==`number`||typeof t==`boolean`?t:void 0};if(t.equals!==void 0)return fX(e,r(t.equals));if(t.not_equals!==void 0)return!fX(e,r(t.not_equals));if(t.in!==void 0)return t.in.split(`,`).map(e=>e.trim()).some(t=>fX(e,t));if(t.not_in!==void 0)return!t.not_in.split(`,`).map(e=>e.trim()).some(t=>fX(e,t));let i=typeof e==`number`?e:Number(e),a=e=>Number(t[e]);return t.less_than!==void 0||t.greater_than!==void 0||t.less_than_or_equal_to!==void 0||t.greater_than_or_equal_to!==void 0?!(typeof e==`boolean`||!Number.isFinite(i)||t.less_than!==void 0&&!(i<a(`less_than`))||t.greater_than!==void 0&&!(i>a(`greater_than`))||t.less_than_or_equal_to!==void 0&&!(i<=a(`less_than_or_equal_to`))||t.greater_than_or_equal_to!==void 0&&!(i>=a(`greater_than_or_equal_to`))):e!==void 0}function uX(e,t,n){let r=(n.not_type??``).split(`,`).map(e=>e.trim()).filter(Boolean),i=HY(n.can_recruit),a=HY(n.leader),o=n.unit??n.id;return(o===void 0||t===o)&&(n.side===void 0||e.side===n.side)&&(n.type===void 0||e.type===n.type)&&(r.length===0||!r.includes(e.type??``))&&(n.name===void 0||e.name===n.name)&&(n.role===void 0||e.role===n.role)&&(i===void 0||(e.can_recruit??!1)===i)&&(a===void 0||(e.leader??!1)===a)&&(n.x===void 0||bX(n.x,e.x))&&(n.y===void 0||bX(n.y,e.y))}function dX(e,...t){if(t.length===0)return{...e};let n={...e};for(let e of t)delete n[e];return n}function fX(e,t){if(e===void 0||t===void 0||typeof t!=`string`)return e===t;let n=Number(t);return typeof e==`number`&&t.trim()!==``&&Number.isFinite(n)?e===n:e===t}function pX(e){return Object.fromEntries(Object.entries(e).filter(e=>typeof e[1]==`string`||typeof e[1]==`number`||typeof e[1]==`boolean`))}function mX(e){return e.split(`.`).flatMap(e=>{let t=/^([^[\]]*)((?:\[[^\]]*\])*)$/.exec(e);if(!t)return[e];let n=t[1]===``?[]:[t[1]];for(let e of t[2].matchAll(/\[([^\]]*)\]/g)){let t=Number(e[1]);n.push({index:/^\d+$/.test(e[1].trim())?t:void 0})}return n}).filter(e=>typeof e!=`string`||e!==``)}function hX(e){let t=mX(e);if(t.some(e=>typeof e!=`string`&&e.index===void 0))throw Error(`invalid variable path: ${e}`);return t}function gX(e){return typeof e!=`string`}function _X(e,t,n){let r=hX(t),i=e=>typeof e==`string`?e:e.index,a=e;for(let e=0;e<r.length-1;e++){let t=i(r[e]),n=a[t];(!n||typeof n!=`object`)&&(a[t]=gX(r[e+1])?[]:{}),a=a[t]}a[i(r[r.length-1])]=n}function vX(e,t){let n=e;for(let e of mX(t))if(typeof e==`string`){if(!n||typeof n!=`object`||Array.isArray(n))return;n=n[e]}else{if(!Array.isArray(n)||e.index===void 0)return;n=n[e.index]}return n}function yX(e){return t=>vX(e,t)}function bX(e,t){return e.split(`,`).some(e=>{let n=e.trim(),r=n.match(/^(-?\d+)\s*-\s*(-?\d+)$/);if(r){let e=Number(r[1]),n=Number(r[2]);return t>=Math.min(e,n)&&t<=Math.max(e,n)}return/^-?\d+$/.test(n)&&Number(n)===t})}var xX=/^\s*([A-Za-z_][\w]*)\s*=\s*(.*?)\s*$/;function SX(e){let t=e.split(/\r?\n/),n={},r=0;for(;r<t.length;r++){let e=t[r];if(e.trim()===``)continue;let i=xX.exec(e);if(!i)break;n[i[1]]=i[2]}return{header:n,...XY(t.slice(r).map(CX).join(`
1405
+ `))}}function CX(e){let t=e.length;for(;t>0&&(e[t-1]===`,`||/\s/.test(e[t-1]));)t--;return e.slice(0,t)}function wX(e){let t=[];for(let n of e.split(`|`)){let e=n.indexOf(`:`);if(e<=0||e===n.length-1)throw Error(`invalid table column "${n}"`);let r=n.slice(0,e).trim(),i=n.slice(e+1).trim();if(!/^[A-Za-z_][\w.-]*$/.test(r))throw Error(`invalid table column name "${r}"`);if(![`string`,`number`,`boolean`,`list`,`map`].includes(i))throw Error(`invalid table column type "${i}"`);if(t.some(e=>e.name===r))throw Error(`duplicate table column "${r}"`);t.push({name:r,type:i})}if(t.length===0)throw Error(`table must declare at least one column`);return t}var TX={game:{attributes:{schema:`string`,title:`string`,data_root:`string`,start_scene:`id`,default_schedule:`id`,save_slot:`string`,turn_limit:`integer`},children:`campaign.terrain_type.movetype.unit_type.unit.side.map.schedule.event.objectives.trait.weapon_special.dialogue.save.item.inventory.monster.status.loot.turn_clock.battle_move.type_matchup.evolution.table.object.story.role`.split(`.`)},campaign:{attributes:{id:`id`,name:`string`,title:`string`,description:`string`,start_scene:`id`,first_scenario:`id`},openChildren:!0},table:{attributes:{id:`id`,columns:`string`,list_delimiter:`string`,map_delimiter:`string`},children:[`row`]},row:{openAttributes:`string`},terrain_type:{attributes:{id:`id`,string:`string`,aliasof:`string`,mvt_alias:`string`,default_base:`string`,heals:`integer`,gives_income:`boolean`,map_code:`string`,base_tile:`string`,overlay_tile:`string`,defense:`number`,healing:`number`}},movetype:{attributes:{id:`id`,name:`string`},children:[`movement_costs`,`defense`,`resistance`]},movement_costs:{openAttributes:`number`},defense:{openAttributes:`number`},resistance:{openAttributes:`number`},unit_type:{attributes:{id:`string`,name:`string`,description:`string`,image:`string`,image_icon:`string`,profile:`string`,sound:`string`,hitpoints:`integer`,movement:`integer`,movement_type:`id`,movetype:`id`,experience:`integer`,level:`integer`,alignment:`id`,cost:`integer`,advances_to:`string`,race:`id`,usage:`id`},children:[`attack`,`trait`,`ability`]},unit:{attributes:{id:`id`,type:`string`,side:`string`,name:`string`,role:`string`,can_recruit:`boolean`,hp:`integer`,x:`integer`,y:`integer`}},attack:{attributes:{id:`id`,attacker:`string`,defender:`string`,target:`string`,amount:`integer`,weapon:`id`,name:`string`,sound:`string`,description:`string`,type:`id`,range:`id`,damage:`integer`,number:`integer`,strikes:`integer`,icon:`string`,specials:`string`}},side:{attributes:{id:`string`,controller:`id`,gold:`integer`,income:`integer`,income_base:`integer`,income_per_village:`integer`,leader:`id`,team:`integer`,recruit:`string`,color:`string`,team_name:`string`,user_team_name:`string`,share_vision:`string`,village_gold:`integer`,heal:`boolean`,fog:`boolean`,shroud:`boolean`,hidden:`boolean`,flag:`string`}},map:{attributes:{id:`id`,name:`string`,file:`string`,terrain:`string`},children:[`start`]},start:{attributes:{side:`string`,x:`integer`,y:`integer`}},schedule:{attributes:{id:`id`},children:[`time`]},time:{attributes:{id:`id`,name:`string`,lawful_bonus:`number`}},event:{attributes:{id:`id`,on:`id`,trigger:`id`,x:`coordinate`,y:`coordinate`,side:`string`,unit:`string`,once:`boolean`},children:`condition.filter.filter_condition.while.foreach.switch.command.say.dialogue.move.attack.spawn.kill.gold.endlevel.set_variable.if.else.message.teleport.end_turn.win.lose.hook.fire_event.store_unit.unstore_unit.recall.modify_unit.heal_unit.set_terrain.capture_village.clear_shroud.role`.split(`.`)},objectives:{attributes:{side:`string`,victory:`string`,defeat:`string`},children:[`victory`,`defeat`]},victory:{attributes:{side:`string`,condition:`id`,type:`string`,x:`integer`,y:`integer`,side_filter:`string`,turns:`integer`,gold:`integer`,hook:`string`,value:`integer`}},defeat:{attributes:{side:`string`,condition:`id`,type:`string`,x:`integer`,y:`integer`,side_filter:`string`,turns:`integer`,gold:`integer`,hook:`string`,value:`integer`}},condition:{attributes:{condition:`id`,hook:`string`,variable:`string`,equals:`string`,not_equals:`string`,in:`string`,not_in:`string`,less_than:`string`,greater_than:`string`,less_than_or_equal_to:`string`,greater_than_or_equal_to:`string`}},filter:{attributes:{side:`string`,type:`string`,not_type:`string`,unit:`string`,name:`string`,role:`string`,x:`coordinate`,y:`coordinate`,level:`integer`,alignment:`id`,can_recruit:`boolean`,leader:`boolean`}},filter_condition:{children:[`variable`,`have_unit`,`predicate`]},variable:{attributes:{name:`id`,equals:`string`,not_equals:`string`,in:`string`,not_in:`string`,less_than:`string`,greater_than:`string`,less_than_or_equal_to:`string`,greater_than_or_equal_to:`string`}},have_unit:{attributes:{id:`string`,type:`string`,side:`string`,name:`string`,role:`string`,can_recruit:`boolean`,x:`coordinate`,y:`coordinate`}},predicate:{attributes:{name:`id`},openAttributes:`string`},command:{attributes:{name:`id`,target:`string`,path:`string`,value:`string`,mode:[`literal`,`number`,`expression`],amount:`integer`,x:`integer`,y:`integer`,hp:`integer`}},move:{attributes:{unit:`string`,target:`string`,x:`integer`,y:`integer`}},spawn:{attributes:{id:`string`,type:`string`,side:`string`,x:`integer`,y:`integer`,hp:`integer`}},kill:{attributes:{unit:`string`,target:`string`},openAttributes:`string`},gold:{attributes:{side:`string`,delta:`integer`,amount:`integer`}},endlevel:{attributes:{result:`id`,side:`string`,bonus:`integer`,carryover_percentage:`integer`,carryover_add:`boolean`,next_scenario:`id`}},set_variable:{attributes:{name:`id`,target:`id`,path:`string`,value:`string`,mode:[`literal`,`number`,`expression`]}},if:{attributes:{test:`string`},children:[`condition`,`while`,`foreach`,`switch`,`if`,`else`,`command`,`message`,`move`,`attack`,`spawn`,`kill`,`gold`,`set_variable`,`win`,`lose`,`hook`]},else:{children:[`condition`,`while`,`foreach`,`switch`,`if`,`else`,`command`,`message`,`move`,`attack`,`spawn`,`kill`,`gold`,`set_variable`,`win`,`lose`,`hook`]},while:{attributes:{test:`string`,max_iterations:`integer`},children:[`condition`,`while`,`foreach`,`switch`,`if`,`else`,`message`,`move`,`attack`,`spawn`,`kill`,`gold`,`set_variable`,`win`,`lose`,`hook`]},foreach:{attributes:{variable:`id`,item:`id`,index:`id`},children:[`while`,`foreach`,`switch`,`if`,`else`,`message`,`move`,`attack`,`spawn`,`kill`,`gold`,`set_variable`,`win`,`lose`,`hook`]},switch:{attributes:{variable:`id`},children:[`case`,`default`]},case:{attributes:{equals:`string`},children:[`while`,`foreach`,`switch`,`if`,`else`,`message`,`move`,`attack`,`spawn`,`kill`,`gold`,`set_variable`,`win`,`lose`,`hook`,`dialogue`]},default:{children:[`while`,`foreach`,`switch`,`if`,`else`,`message`,`move`,`attack`,`spawn`,`kill`,`gold`,`set_variable`,`win`,`lose`,`hook`,`dialogue`]},message:{attributes:{speaker:`string`,text:`string`,value:`string`,portrait:`string`,side:`string`}},teleport:{attributes:{unit:`string`,target:`string`,x:`integer`,y:`integer`}},end_turn:{attributes:{}},win:{attributes:{side:`string`}},lose:{attributes:{side:`string`}},say:{attributes:{speaker:`id`,text:`string`}},dialogue:{attributes:{id:`id`,ref:`id`},children:[`say`,`choice`,`branch`,`message`]},choice:{attributes:{text:`string`,event:`id`,variable:`id`,equals:`string`},children:[`branch`]},branch:{attributes:{text:`string`},children:[`message`,`say`,`command`,`set_variable`,`move`,`attack`,`spawn`,`kill`,`gold`,`hook`]},trait:{attributes:{id:`id`,name:`string`},children:[`effect`]},ability:{attributes:{id:`id`,name:`string`},children:[`effect`]},weapon_special:{attributes:{id:`id`,name:`string`}},hook:{attributes:{name:`string`},openAttributes:`string`},fire_event:{attributes:{id:`id`,name:`string`}},store_unit:{attributes:{variable:`string`,name:`string`},children:[`filter`]},unstore_unit:{attributes:{variable:`string`,name:`string`}},recall:{attributes:{variable:`string`,id:`string`,unit:`string`,side:`string`,x:`integer`,y:`integer`}},modify_unit:{attributes:{hp:`integer`,moves:`integer`,type:`string`,side:`string`,alive:`boolean`},children:[`filter`,`set`]},set:{openAttributes:`string`},heal_unit:{attributes:{amount:`integer`,hp:`integer`,side:`string`,type:`string`,x:`integer`,y:`integer`},children:[`filter`]},set_terrain:{attributes:{terrain:`string`,x:`integer`,y:`integer`}},capture_village:{attributes:{side:`string`,x:`integer`,y:`integer`,name:`string`}},clear_shroud:{attributes:{side:`string`,x:`integer`,y:`integer`,radius:`integer`}},role:{attributes:{role:`string`,name:`string`,type:`string`,not_type:`string`,unit:`string`,side:`string`,can_recruit:`boolean`,x:`integer`,y:`integer`},children:[`filter`]},object:{attributes:{id:`id`,name:`string`,image:`string`,side:`string`,x:`integer`,y:`integer`},children:[`filter`]},story:{attributes:{text:`string`,value:`string`,title:`string`,image:`string`,music:`string`}},item:{attributes:{id:`id`,name:`string`,slot:`id`,stackable:`boolean`,weight:`number`,image:`string`,icon:`string`},children:[`effect`]},inventory:{attributes:{unit:`string`,side:`string`,items:`string`}},monster:{attributes:{id:`string`,name:`string`,hp:`integer`,types:`string`,attack:`number`,defense:`number`,speed:`number`,accuracy:`number`,evasion:`number`,damage_min:`integer`,damage_max:`integer`,armor_min:`integer`,armor_max:`integer`,experience:`integer`,max_level:`integer`,image:`string`},children:[`ability`,`loot`]},status:{attributes:{id:`id`,name:`string`,duration:`integer`,tick:`string`,modifiers:`string`}},loot:{attributes:{item:`id`,chance:`number`,quantity:`integer`,weight:`number`}},turn_clock:{attributes:{id:`id`,tick:`number`,hunger:`number`}},ai:{attributes:{id:`id`,strategy:`id`,target:`id`,difficulty:`number`,scope:`id`,provider:`id`,algorithm:`id`,depth:`integer`,max_nodes:`integer`,player:`string`,moves:`string`,apply:`string`,terminal:`string`,evaluate:`string`},children:[`behavior`]},behavior:{attributes:{id:`id`,when:`string`,action:`string`,hook:`string`}},battle_move:{attributes:{id:`id`,type:`id`,target:`id`,power:`number`,cost:`number`}},type_matchup:{attributes:{attacker:`id`,defender:`id`,multiplier:`number`}},evolution:{attributes:{from:`id`,into:`id`,level:`integer`}},effect:{attributes:{apply_to:`id`,range:`id`,increase:`string`,increase_total:`string`,increase_damage:`string`,add:`string`,sub:`string`,multiply:`string`,divide:`string`,set:`string`}},save:{attributes:{version:`integer`,fields:`string`,migration:`string`}}},EX={...TX,game:{...TX.game,required:[`schema`]},table:{...TX.table,required:[`id`,`columns`],cardinality:{row:{min:1}}},terrain_type:{...TX.terrain_type,required:[`id`]},movetype:{...TX.movetype,required:[`id`]},unit_type:{...TX.unit_type,required:[`id`]},unit:{...TX.unit,required:[`id`,`type`,`side`]}};function DX(e,t=TX){let n=[],r=new Map,i=e=>{let t=e.attributes.id;t&&r.set(t,[...r.get(t)??[],e]),e.children.forEach(i)};e.forEach(i);let a=[],o=(e,i=!1)=>{let s=t[e.tag];if(!s){if(i){e.children.forEach(e=>o(e,!0));return}n.push({code:`MWL_UNKNOWN_TAG`,message:`unknown tag ${e.tag}`,location:e.location});return}for(let t of Object.keys(e.attributes))s.openAttributes||(!s.attributes||!(t in s.attributes))&&n.push({code:`MWL_UNKNOWN_ATTRIBUTE`,message:`unknown attribute ${t} on ${e.tag}`,location:e.attributeLocations?.[t]??e.location});for(let t of s.required??[])e.attributes[t]===void 0&&n.push({code:`MWL_REQUIRED_ATTRIBUTE`,message:`${t} is required on ${e.tag}`,location:e.location});for(let[t,i]of Object.entries(s.attributes??{})){let o=e.attributes[t];if(o!==void 0&&!jX(o,i)&&n.push({code:`MWL_VALUE`,message:`${t} must be ${MX(i)}`,location:e.valueLocations?.[t]??e.attributeLocations?.[t]??e.location}),o!==void 0&&i===`ref`){let i=(r.get(o)??[]).filter(e=>{let n=s.refTargets?.[t];return!n||n===`*`||e.tag===n});i.length===0?n.push({code:`MWL_REF_MISSING`,message:`${t} references missing target ${o}`,location:e.location}):i.length>1?n.push({code:`MWL_REF_DUPLICATE`,message:`${t} references ambiguous target ${o}`,location:e.location}):s.acyclicRefs?.includes(t)&&a.push({from:e,to:i[0],name:t})}}if(s.openAttributes)for(let[t,r]of Object.entries(e.attributes))jX(r,s.openAttributes)||n.push({code:`MWL_VALUE`,message:`${t} must be ${s.openAttributes}`,location:e.valueLocations?.[t]??e.attributeLocations?.[t]??e.location});for(let t of e.children)!s.openChildren&&s.children&&!s.children.includes(t.tag)&&n.push({code:`MWL_CHILD`,message:`${t.tag} is not allowed inside ${e.tag}`,location:t.location}),o(t,s.openChildren===!0);for(let[t,r]of Object.entries(s.cardinality??{})){let i=e.children.filter(e=>e.tag===t).length;r.min!==void 0&&i<r.min&&n.push({code:`MWL_CARDINALITY`,message:`${e.tag} needs at least ${r.min} ${t} child${r.min===1?``:`ren`}`,location:e.location}),r.max!==void 0&&i>r.max&&n.push({code:`MWL_CARDINALITY`,message:`${e.tag} allows at most ${r.max} ${t} child${r.max===1?``:`ren`}`,location:e.location})}};e.forEach(e=>o(e)),OX(e,n);let s=new Set,c=new Set,l=(e,t)=>{if(s.has(e)){let r=t.indexOf(e);n.push({code:`MWL_REF_CYCLE`,message:`reference cycle through ${t.slice(r).map(e=>e.attributes.id??e.tag).join(` -> `)}`,location:e.location});return}if(!c.has(e)){s.add(e);for(let n of a.filter(t=>t.from===e))l(n.to,[...t,e]);s.delete(e),c.add(e)}};for(let e of a)l(e.from,[]);return n.sort((e,t)=>e.location.line-t.location.line||e.location.column-t.location.column)}function OX(e,t){let n=e=>{if(e.tag===`table`){let n;try{n=wX(e.attributes.columns??``)}catch(r){t.push({code:`MWL_TABLE`,message:String(r).replace(/^Error: /,``),location:e.location}),n=[]}let r=new Map(n.map(e=>[e.name,e]));for(let i of e.children.filter(e=>e.tag===`row`)){for(let e of Object.keys(i.attributes))r.has(e)||t.push({code:`MWL_TABLE`,message:`unknown table column ${e}`,location:i.location});for(let r of n){let n=i.attributes[r.name];if(n===void 0){t.push({code:`MWL_TABLE`,message:`missing table column ${r.name}`,location:i.location});continue}try{kX(n,r.type,r.name,e.attributes.list_delimiter,e.attributes.map_delimiter)}catch(e){t.push({code:`MWL_TABLE`,message:String(e).replace(/^Error: /,``),location:i.location})}}}}e.children.forEach(n)};e.forEach(n)}function kX(e,t,n,r=`;`,i=`=`){return Br(e,t,{column:n,listDelimiter:r,mapDelimiter:i,acceptYesNo:!0})}function AX(e){return/^[A-Za-z_][\w.[\]-]*$/.test(e)}function jX(e,t){return NX(t)?t.includes(e):t===`number`?Number.isFinite(Number(e)):t===`integer`?/^-?\d+$/.test(e):t===`boolean`?e===`true`||e===`false`||e===`yes`||e===`no`:t===`ref`?/^[A-Za-z_][\w.-]*$/.test(e):t===`coordinate`?/^-?\d+(?:\s*,\s*-?\d+|\s*-\s*-?\d+)*$/.test(e):t!==`id`||AX(e)}function MX(e){return NX(e)?`one of ${e.join(`, `)}`:e}function NX(e){return Array.isArray(e)}function PX(e,t={}){return IX(tY(YJ(e,t),t.file),t)}function FX(e,t={}){let n=[];for(let r of[...e].sort((e,t)=>e.file<t.file?-1:+(e.file>t.file))){let e=YJ(r.source,{...t,file:r.file});n.push(...tY(e,r.file))}return IX(n,t)}function IX(e,t={}){let n=e.find(e=>e.tag===`game`)?.attributes.schema,r=DX(e,t.schemas??(n===`1.0`?EX:void 0));if(r.length){let e=r[0];throw Error(`${e.location.file}:${e.location.line}:${e.location.column}: ${e.message}`)}let i=new Set,a=new Set,o=e=>{for(let[t,n]of Object.entries(e.attributes))if(LX(t))for(let e of zX(n).map(e=>e.trim()).filter(RX))i.add(BX(e));let t=e.gettext??[`name`,`text`,`title`];for(let n of t){let t=e.attributes[n];t!==void 0&&a.add(t)}let n={tag:e.tag,attributes:{...e.attributes},children:e.children.map(o),location:e.location};return Object.defineProperties(n,{attributeLocations:{value:e.attributeLocations,enumerable:!1},valueLocations:{value:e.valueLocations,enumerable:!1}}),e.gettext&&Object.assign(n,{gettext:[...e.gettext]}),n};return{schema:e.find(e=>e.tag===`game`)?.attributes.schema??`0.1`,roots:e.map(o),assets:[...i].sort(),messages:[...a].sort()}}function LX(e){return e===`file`||e===`image`||e===`image_icon`||e===`icon`||e===`profile`||e===`sound`||e.endsWith(`_sound`)||e.endsWith(`_image`)}function RX(e){return e.includes(`/`)||/\.(?:png|jpg|jpeg|gif|svg|webp|wav|ogg|mp3|flac|glb|gltf|vox|map|cfg)$/i.test(e)||e.startsWith(`data:`)}function zX(e){let t=[],n=0,r=0,i=0;for(let a=0;a<e.length;a+=1)e[a]===`(`?r+=1:e[a]===`)`&&r>0?--r:e[a]===`[`?i+=1:e[a]===`]`&&i>0?--i:e[a]===`,`&&r===0&&i===0&&(t.push(e.slice(n,a)),n=a+1);return t.push(e.slice(n)),t}function BX(e){let t=e.match(/~[A-Za-z][A-Za-z0-9_-]*(?:\(|$)/);return t?e.slice(0,t.index).trim():e}function VX(e,t={}){let n={};for(let t of e.messages)n[t]=t;return{locale:t.locale??`en`,direction:t.direction??`ltr`,messages:n}}function HX(e,t=`gameData`){return`export const ${t} = ${JSON.stringify(e,null,` `)} as const;\n`}function UX(e,t={}){let n=[{name:`game-data.ts`,content:HX(e,t.variable??`gameData`)},{name:`i18n.json`,content:`${JSON.stringify(VX(e),null,` `)}\n`},{name:`assets.json`,content:`${JSON.stringify({assets:e.assets},null,` `)}\n`},...Object.entries(t.artifacts??{}).sort(([e],[t])=>e<t?-1:+(e>t)).map(([e,t])=>({name:e,content:t}))];for(let e of n)t.onEmit?.(e);return n}function WX(e,t={},n={}){let r=UX(FX(e,t),n),i=UX(FX(e,t),n);if(r.length!==i.length||r.some((e,t)=>e.name!==i[t]?.name||e.content!==i[t]?.content))throw Error(`MWL generated artifacts are not deterministic`);return r}var GX=/^[A-Za-z_][\w-]*$/,KX=[`predicate`,`modifier`,`generator`,`command`,`ai`,`migration`];function qX(e){let t=e.indexOf(`:`);if(t<=0)return null;let n=e.slice(0,t),r=e.slice(t+1).trim();return!GX.test(n)||!GX.test(r)?null:{type:n,name:r}}function JX(e,t=[`hook`,`migration`]){let n=new Map,r=new Set(t),i=e=>{for(let[t,n]of Object.entries(e.attributes))r.has(t)&&a(n,e.location),e.tag===`hook`&&t===`name`&&a(n,e.location);e.children.forEach(i)},a=(e,t)=>{let r=qX(e);if(!r)return;let i=`${r.type}:${r.name}`;n.has(i)||n.set(i,{...r,location:t})};return e.roots.forEach(i),[...n.values()].sort((e,t)=>e.type.localeCompare(t.type)||e.name.localeCompare(t.name))}function YX(e,t){if(t.attributes===void 0&&t.openAttributes===void 0)return[];let n=e.location??{file:`<hook>`,line:0,column:0},r=[];for(let[i,a]of Object.entries(e.attributes)){if(i===`name`)continue;let e=t.attributes?.[i]??t.openAttributes;if(e===void 0){r.push({code:`MWL_UNKNOWN_ATTRIBUTE`,message:`unknown attribute ${i} on hook ${t.id}`,location:n});continue}jX(a,e)||r.push({code:`MWL_VALUE`,message:`${i} must be ${MX(e)} on hook ${t.id}`,location:n})}return r}function XX(e,t){let n=new Set(t),r=[];for(let t of e){let e=`${t.type}:${t.name}`;n.has(e)||r.push({code:`MWL_HOOK`,message:`hook ${e} is not implemented`,location:t.location??{file:`<hook>`,line:0,column:0}})}return r}function ZX(e){let t=[];t.push(`// Generated by mwl - do not edit.`),t.push(`import type { AiHook, CommandHook, GeneratorHook, MigrationHook, ModifierHook, PredicateHook } from '@datamoc/mw_games/mwl';`),t.push(``),t.push(`export interface MwlHooks {`);for(let n of e){let e=KX.includes(n.type)?`${n.type[0].toUpperCase()}${n.type.slice(1)}Hook`:`MwlDomainHook`;t.push(`\t'${n.type}:${n.name}': ${e};`)}return t.push(`}`),t.push(``),t.join(`
1406
+ `)}function QX(e,t){let n=e.scenarios;if(n.length===0)throw Error(`campaign ${e.id} declares no scenarios`);let r=new Set(n.map(e=>e.id));if(r.size!==n.length)throw Error(`campaign ${e.id} declares a scenario twice`);let i=e.firstScenario||n[0].id;if(!r.has(i))throw Error(`campaign ${e.id} starts on an unknown scenario: ${i}`);return{start:i,levels:n.map(e=>({id:e.id,run:(n,r)=>{let i=t.run(e,n,r);return i.next===void 0?{...i,next:e.nextScenario??null}:i}}))}}var $X=RY,eZ=zY,tZ=BY,nZ=VY,rZ=UY;function iZ(e){let t=LY(e.roots);return{campaigns:t.filter(e=>e.tag===`campaign`).map(e=>({id:$X(e,`id`),name:e.attributes.name,title:e.attributes.title,description:e.attributes.description,startScene:e.attributes.start_scene,firstScenario:e.attributes.first_scenario,scenarios:e.children.filter(e=>e.tag===`scenario`).map(e=>({id:$X(e,`id`),nextScenario:e.attributes.next_scenario||void 0}))})),items:t.filter(e=>e.tag===`item`).map(e=>({id:$X(e,`id`),name:$X(e,`name`),slot:e.attributes.slot,stackable:nZ(e,`stackable`),weight:eZ(e,`weight`),image:e.attributes.image,icon:e.attributes.icon,effects:e.children.filter(e=>e.tag===`effect`).map(oZ)})),monsters:t.filter(e=>e.tag===`monster`).map(e=>({id:$X(e,`id`),name:e.attributes.name,hp:tZ(e,`hp`,1),accuracy:eZ(e,`accuracy`),evasion:eZ(e,`evasion`),damage:sZ(e,`damage_min`,`damage_max`),armor:sZ(e,`armor_min`,`armor_max`),experience:tZ(e,`experience`),maxLevel:tZ(e,`max_level`),image:e.attributes.image,types:e.attributes.types?.split(`,`).map(e=>e.trim()).filter(Boolean),baseStats:[`attack`,`defense`,`speed`,`hp`].reduce((t,n)=>{let r=eZ(e,n);return r!==void 0&&(t[n===`hp`?`maxHp`:n]=r),t},{})})),statuses:t.filter(e=>e.tag===`status`).map(e=>({id:$X(e,`id`),name:e.attributes.name,duration:tZ(e,`duration`),tick:e.attributes.tick,modifiers:e.attributes.modifiers})),loot:t.filter(e=>e.tag===`loot`).map(e=>({item:$X(e,`item`),chance:eZ(e,`chance`),quantity:tZ(e,`quantity`),weight:eZ(e,`weight`)})),turnClocks:t.filter(e=>e.tag===`turn_clock`).map(e=>({id:$X(e,`id`),tick:eZ(e,`tick`),hunger:eZ(e,`hunger`)})),ai:t.filter(e=>e.tag===`ai`).map(e=>({id:$X(e,`id`),strategy:e.attributes.strategy,target:e.attributes.target,difficulty:eZ(e,`difficulty`),scope:rZ(e.attributes.scope,[`actor`,`controller`]),provider:rZ(e.attributes.provider,[`javascript`,`lua`]),algorithm:rZ(e.attributes.algorithm,[`rules`,`alpha_beta`]),depth:tZ(e,`depth`),maxNodes:tZ(e,`max_nodes`),player:e.attributes.player,moves:e.attributes.moves,apply:e.attributes.apply,terminal:e.attributes.terminal,evaluate:e.attributes.evaluate,behaviors:e.children.filter(e=>e.tag===`behavior`).map(e=>({id:$X(e,`id`),when:e.attributes.when,action:e.attributes.action,hook:e.attributes.hook}))})),moves:t.filter(e=>e.tag===`battle_move`).map(e=>({id:$X(e,`id`),type:$X(e,`type`),target:$X(e,`target`),power:eZ(e,`power`),cost:eZ(e,`cost`)})),typeMatchups:t.filter(e=>e.tag===`type_matchup`).map(e=>({attacker:$X(e,`attacker`),defender:$X(e,`defender`),multiplier:eZ(e,`multiplier`)??1})),evolutions:t.filter(e=>e.tag===`evolution`).map(e=>({from:$X(e,`from`),into:$X(e,`into`),level:tZ(e,`level`,1)})),tables:t.filter(e=>e.tag===`table`).map(aZ)}}function aZ(e){let t=wX($X(e,`columns`));return{id:$X(e,`id`),columns:t,rows:e.children.filter(e=>e.tag===`row`).map(n=>{let r={};for(let i of t){let t=n.attributes[i.name];t!==void 0&&(r[i.name]=kX(t,i.type,i.name,e.attributes.list_delimiter,e.attributes.map_delimiter))}return r})}}function oZ(e){let t=[`add`,`sub`,`multiply`,`divide`,`set`,`increase`,`increase_total`,`increase_damage`].find(t=>e.attributes[t]!==void 0);return{applyTo:$X(e,`apply_to`),operation:t,value:t?e.attributes[t]:void 0,range:e.attributes.range}}function sZ(e,t,n){let r=eZ(e,t),i=eZ(e,n);return r===void 0||i===void 0?void 0:[r,i]}function cZ(e){return e.rows}function lZ(e,t={}){let n=[`// ${t.header??`Generated from MWL tables - do not edit by hand.`}`];e.length>0&&n.push(`import { typedRows } from '@datamoc/mw_games/mwl';`,`import type { MwlContentCatalog } from '@datamoc/mw_games/mwl';`);let r=new Set;for(let t of e){let e=uZ(t.id,r);n.push(``,`const ${e}Columns = [${t.columns.map(e=>`{ name: ${JSON.stringify(e.name)}, type: ${JSON.stringify(e.type)} }`).join(`, `)}] as const;`),n.push(`export interface ${e}Row {`);for(let e of t.columns)n.push(`\t${dZ(e.name)}?: ${fZ(e.type)};`);n.push(`}`,``,`/** Typed rows of the \`${t.id}\` table. */`);let i=`${e[0].toLowerCase()}${e.slice(1)}Rows`;n.push(`export function ${i}(catalog: Pick<MwlContentCatalog, 'tables'>): ${e}Row[] {`,`\tconst table = catalog.tables.find((entry) => entry.id === ${JSON.stringify(t.id)});`,`\treturn typedRows({ columns: ${e}Columns, rows: table?.rows ?? [] });`,`}`)}return`${n.join(`
1407
+ `)}\n`}function uZ(e,t){let n=e.split(/[^A-Za-z0-9]+/).filter(e=>e.length>0).map(e=>e[0].toUpperCase()+e.slice(1)).join(``)||`Table`,r=/^[A-Za-z_$]/.test(n)?n:`_${n}`,i=r;for(let e=2;t.has(i);e++)i=`${r}${e}`;return t.add(i),i}function dZ(e){return/^[A-Za-z_$][\w$]*$/.test(e)?e:JSON.stringify(e)}function fZ(e){switch(e){case`number`:return`number`;case`boolean`:return`boolean`;case`list`:return`string[]`;case`map`:return`Record<string, string>`;default:return`string`}}function pZ(e,t={}){return{id:e.id,stackable:e.stackable,weight:e.weight,slot:e.slot,modifiers:e.effects.map(e=>gZ(e,t))}}function mZ(e,t=1){return{id:e.id,quantity:t,stackable:e.stackable,weight:e.weight}}function hZ(e,t,n={}){return FB(e,t.map(e=>gZ(e,n)))}function gZ(e,t={}){let n=e.operation;if(n!==`add`&&n!==`sub`&&n!==`multiply`&&n!==`divide`&&n!==`set`)throw Error(`MWL effect operation "${n??``}" is not a StatBlock modifier`);let r=e.value;if(r===void 0)throw Error(`MWL effect has no value`);let i=jY(r,t);return{stat:e.applyTo,op:n===`sub`?`add`:n===`divide`?`multiply`:n,value:n===`sub`?-i:n===`divide`?1/i:i}}function _Z(e,t={}){let n=[],r=new Map,i=LY(e.roots);for(let e of i){let i=e.attributes.id;if(i){let a=`${t.rowIdScope===`file`?e.location?.file??`<mwl>`:``}\0${e.tag}:${i}`,o=r.get(a);o?n.push(xZ(`MWL_DUPLICATE_ID`,`duplicate ${e.tag} id "${i}"`,e.location??o.location)):r.set(a,e)}if(e.tag===`item`&&t.slots&&e.attributes.slot&&!t.slots.includes(e.attributes.slot)&&n.push(xZ(`MWL_UNKNOWN_SLOT`,`unknown equipment slot "${e.attributes.slot}"`,e.location)),e.tag===`effect`){let t=[`add`,`sub`,`multiply`,`divide`,`set`,`increase`,`increase_total`,`increase_damage`].filter(t=>e.attributes[t]!==void 0);(!e.attributes.apply_to||t.length!==1)&&n.push(xZ(`MWL_INCOMPLETE_EFFECT`,`an effect needs apply_to and exactly one operation`,e.location))}CZ(e,t.mapBounds,n)}vZ(i,n),yZ(i,t.tableReferences,n);let a=JX(e,[`hook`,`migration`,...t.hookAttributes??[]]),o=new Map;for(let e of t.hooks??[])o.set(typeof e==`string`?e:e.id,typeof e==`string`?{id:e}:e);for(let e of i){let t=e.attributes.hook??(e.tag===`hook`?e.attributes.name:void 0);t!==void 0&&!qX(t)&&n.push(xZ(`MWL_INVALID_HOOK`,`invalid hook reference "${t}"`,e.location));let r=e.tag===`hook`&&e.attributes.name?o.get(e.attributes.name):void 0;r&&n.push(...YX(e,r))}if(t.hooks)for(let e of a)o.has(`${e.type}:${e.name}`)||n.push(xZ(`MWL_UNKNOWN_HOOK`,`hook ${e.type}:${e.name} is not declared by the game`,e.location));return n}function vZ(e,t){let n=new Map;for(let t of e){let e=t.attributes.id;e&&n.set(`${t.tag}\0${e}`,t)}let r=new Set,i=new Set,a=new Set,o=(e,s)=>{if(r.has(e)){let n=s.indexOf(e),r=s.slice(n).map(e=>`${e.tag}:${e.attributes.id??`<anonymous>`}`).sort().join(`|`);if(a.has(r))return;a.add(r),t.push({code:`MWL_ALIAS_CYCLE`,message:`alias cycle through ${s.slice(n).map(e=>e.attributes.id??e.tag).join(` -> `)}`,location:e.valueLocations?.aliasof??e.attributeLocations?.aliasof??e.location??SZ()});return}if(!i.has(e)){r.add(e);for(let t of(e.attributes.aliasof??``).split(`,`).map(e=>e.trim()).filter(Boolean)){let r=n.get(`${e.tag}\0${t}`);r&&o(r,[...s,e])}r.delete(e),i.add(e)}};for(let t of e)t.attributes.aliasof!==void 0&&o(t,[])}function yZ(e,t,n){if(!t)return;let r=new Map;for(let t of e){let e=t.tag===`table`?t.attributes.id:void 0;e&&!r.has(e)&&r.set(e,t)}let i=e=>{try{return wX(e.attributes.columns??``)}catch{return}},a=e=>e.children.filter(e=>e.tag===`row`);for(let o of t){let t=r.get(o.table);if(!t){n.push(xZ(`MWL_TABLE_REFERENCE`,`unknown table "${o.table}" in tableReferences`,SZ()));continue}let s=i(t)?.find(e=>e.name===o.column);if(!s){n.push(xZ(`MWL_TABLE_REFERENCE`,`unknown column "${o.column}" in table "${o.table}"`,t.location));continue}let c,l;if(`oneOf`in o)c=new Set(o.oneOf),l=`one of the declared values`;else if(`node`in o.references){let t=new Set;for(let n of e)n.tag===o.references.node&&n.attributes.id&&t.add(n.attributes.id);c=t,l=`node "${o.references.node}"`}else{let e=o.references,s=r.get(e.table),u=s?i(s)?.find(t=>t.name===e.column):void 0;if(!s||!u){n.push(xZ(`MWL_TABLE_REFERENCE`,`unknown reference target "${e.table}.${e.column}" for table "${o.table}" column "${o.column}"`,t.location));continue}let d=new Set;for(let e of a(s))for(let t of bZ(e,u,s.attributes.list_delimiter))d.add(t);c=d,l=`${e.table}.${e.column}`}let u=t.attributes.list_delimiter;a(t).forEach((e,t)=>{for(let r of bZ(e,s,u))c.has(r)||n.push({code:`MWL_TABLE_REFERENCE`,message:`table "${o.table}" row ${t+1} column "${o.column}": unknown value "${r}" (expected ${l})`,location:e.valueLocations?.[o.column]??e.attributeLocations?.[o.column]??e.location??SZ()})})}}function bZ(e,t,n){let r=e.attributes[t.name];return r===void 0||r===``?[]:t.type===`list`?r.split(n??`;`).map(e=>e.trim()).filter(e=>e.length>0):[r]}function xZ(e,t,n){return{code:e,message:t,location:n??SZ()}}function SZ(){return{file:`<mwl>`,line:1,column:1}}function CZ(e,t,n){if(t)for(let r of[`x`,`y`]){let i=e.attributes[r];if(i===void 0)continue;let a=r===`x`?t.width:t.height;if(!Number.isInteger(a)||a<=0)continue;let o=i.split(`,`).flatMap(e=>{let t=e.trim(),n=/^(-?\d+)\s*-\s*(-?\d+)$/.exec(t);return n?[Number(n[1]),Number(n[2])]:/^-?\d+$/.test(t)?[Number(t)]:[]});o.length>0&&o.some(e=>e<0||e>=a)&&n.push({code:`MWL_COORDINATE`,message:`${r} coordinate is outside the ${a}-cell map bound`,location:e.valueLocations?.[r]??e.attributeLocations?.[r]??e.location??{file:`<mwl>`,line:1,column:1}})}}function wZ(e,t={}){return _Z({schema:`0.1`,roots:e,assets:[],messages:[]},t)}function TZ(e,t={}){try{let n=FX(e,t),r=EZ(n),i=[];for(let e of r.opaqueTags)i.push({severity:`warning`,code:`opaque-tag`,message:`ignored opaque tag: ${e}`});for(let e of r.danglingReferences)i.push({severity:`error`,code:`dangling-reference`,message:`dangling content reference: ${e}`});return{game:n,resources:[...n.assets],dependencies:[...r.references],ignored:[...r.opaqueTags],diagnostics:i}}catch(e){return{resources:[],dependencies:[],ignored:[],diagnostics:[{severity:`error`,code:`compile`,message:String(e)}]}}}function EZ(e){let t=LY(e.roots),n={},r=new Set;for(let e of t)n[e.tag]=(n[e.tag]??0)+1,e.attributes.id&&r.add(e.attributes.id);let i=new Set(Object.keys(TX)),a=t.filter(e=>!i.has(e.tag)).map(e=>e.tag).filter((e,t,n)=>n.indexOf(e)===t).sort(),o=new Set;for(let e of t)for(let[t,n]of Object.entries(e.attributes))if(/^(?:ability|item|terrain|unit|unit_type|weapon)(?:_id)?$/.test(t))for(let e of n.split(`,`).map(e=>e.trim()).filter(Boolean))o.add(e);return{tags:Object.fromEntries(Object.entries(n).sort(([e],[t])=>e.localeCompare(t))),opaqueTags:a,references:[...o].sort(),danglingReferences:[...o].filter(e=>!r.has(e)).sort()}}function DZ(e,t){let n={},r=[];for(let[i,a]of Object.entries(t)){let t=a.source??i,o=e.attributes[t];if(o===void 0){a.required?r.push(LZ(`MWL_REQUIRED_FIELD`,`missing required attribute "${t}"`,e)):a.default!==void 0&&(n[i]=a.default);continue}let s=IZ(o,a.type);s===void 0?r.push(LZ(`MWL_FIELD_TYPE`,`invalid ${a.type} attribute "${t}": "${o}"`,e)):n[i]=s}return{value:n,diagnostics:r}}function OZ(e,t,n){let r=[],i=[];for(let a of e.children){if(a.tag!==t)continue;let e=n(a);r.push(e.value),i.push(...e.diagnostics)}return{value:r,diagnostics:i}}function kZ(e,t){let n=new Map;for(let r of e){let e=jZ(...MZ(r,t.key));if(n.has(e)&&t.duplicate!==`last`)throw Error(`duplicate table key: ${e}`);n.set(e,t.value?t.value(r):r)}return n}function AZ(e,t){let n=new Map;for(let r of e){let e=jZ(...MZ(r,t.key)),i=n.get(e);i?i.push(r):n.set(e,[r])}return n}function jZ(...e){return JSON.stringify(e)}function MZ(e,t){if(typeof t==`function`){let n=t(e);return NZ(n)?[...n]:[n]}return PZ(t)?t.map(t=>FZ(e[t],String(t))):[FZ(e[t],String(t))]}function NZ(e){return Array.isArray(e)}function PZ(e){return Array.isArray(e)}function FZ(e,t){if(e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`)return e;throw TypeError(`table key column "${t}" must be a string, number, boolean, or null`)}function IZ(e,t){if(t===`string`)return e;if(t===`id`)return AX(e)?e:void 0;if(t===`number`)return Number.isFinite(Number(e))?Number(e):void 0;if(t===`integer`)return/^-?\d+$/.test(e)?Number(e):void 0;if(t===`boolean`)return e===`true`||e===`yes`?!0:e===`false`||e===`no`?!1:void 0;let n=e.split(`,`).map(e=>e.trim()).filter(Boolean);return t===`id-list`?n.every(e=>AX(e))?n:void 0:n.every(e=>Number.isFinite(Number(e)))?n.map(Number):void 0}function LZ(e,t,n){return{code:e,message:t,location:n.location??{file:`<mwl>`,line:1,column:1}}}function RZ(){return{evaluate(e,t={}){let n={};for(let[e,r]of Object.entries(t)){if(typeof r!=`number`)throw Error(`MWL expression context value must be numeric: ${e}`);n[e]=r}return jY(e,n)},execute(){throw Error(`the expression ScriptHost cannot execute statements`)},call(){throw Error(`the expression ScriptHost cannot call functions`)},dispose(){}}}var zZ=l({MWL_DEFAULT_CARRYOVER_PERCENTAGE:()=>80,MWL_SCHEMA_01:()=>`0.1`,MWL_SCHEMA_10:()=>`1.0`,MwlRuntime:()=>$Y,MwlSyntaxError:()=>qJ,attributeTypeDescription:()=>MX,campaignChain:()=>QX,carryoverIntoScenario:()=>GY,coerceTableValue:()=>kX,collectHookReferences:()=>JX,compile:()=>PX,compileAndEmitSources:()=>WX,compileNodes:()=>IX,compileSources:()=>FX,composeEffects:()=>hZ,contentCatalog:()=>iZ,contentReport:()=>EZ,createExpressionScriptHost:()=>RZ,createWorld:()=>JY,decodeSave:()=>bY,decodeSaveEnvelope:()=>xY,effectToModifier:()=>gZ,emitArtifacts:()=>UX,emitHooksDeclaration:()=>ZX,emitModule:()=>HX,emitTableTypes:()=>lZ,encodeSave:()=>yY,endLevelCarryover:()=>WY,evaluateCondition:()=>EY,evaluateExpression:()=>jY,execute:()=>eX,extractCatalog:()=>VX,hookTypes:()=>KX,inventoryItem:()=>mZ,isGettext:()=>mY,isMwlId:()=>AX,itemDefinition:()=>pZ,loadContent:()=>TZ,parse:()=>tY,parseExpression:()=>AY,parseHookReference:()=>qX,parseMapFile:()=>SX,parseTableColumns:()=>wX,parseTerrain:()=>XY,parseValue:()=>pY,preprocess:()=>YJ,readAttributes:()=>DZ,readChildren:()=>OZ,readTableIndex:()=>AZ,readTableMap:()=>kZ,schema01:()=>TX,schema10:()=>EX,sideVisionGroups:()=>nX,tableKey:()=>jZ,typedRows:()=>cZ,validAttributeValue:()=>jX,validate:()=>DX,validateCatalog:()=>_Z,validateCatalogNodes:()=>wZ,validateHookAttributes:()=>YX,validateHookReferences:()=>XX,validateWorld:()=>SY}),BZ=class{constructor(e,t={}){if(this.latestDecision=null,this.decide=e,this.every=t.every??1,!Number.isInteger(this.every)||this.every<1||this.every>1e6)throw RangeError(`a suggestion budget must be a frame count in 1..1000000`);this.since=this.every-1}update(e){return this.since++,this.since<this.every?null:(this.since=0,this.latestDecision=this.decide(e),this.latestDecision)}get latest(){return this.latestDecision}clear(){this.latestDecision=null}};function VZ(e,t){return e.filter(e=>(t.side===void 0||e.side===t.side)&&(t.type===void 0||e.type===t.type)&&(t.role===void 0||e.role===t.role)&&(t.can_recruit===void 0||(e.can_recruit??!1)===t.can_recruit)&&(t.name===void 0||e.name===t.name))}function HZ(e,t,n,r){let i=0,a=0,o=1;for(let s of t)s.id!==e.id&&r(s.x,s.y)&&(o++,s.side===e.side?i+=n(s.id):a+=n(s.id));return{own:n(e.id),allies:i,enemies:a,seen:o}}function UZ(e,t,n,r){let i=0,a=0,o=0;for(let s of t)r(s.x,s.y)&&(o++,s.side===e?i+=n(s.id):a+=n(s.id));return{own:0,allies:i,enemies:a,seen:o}}function WZ(e,t){return e.own*t.own+e.allies*t.allies+e.enemies*t.enemies}var GZ=class e{constructor(e={}){this.values={};for(let[t,n]of Object.entries(e))n!==void 0&&(this.values[t]=n)}has(e){return this.values[e]!==void 0}get(e){return this.values[e]}set(e,t){this.values[e]=t}number(e,t=0){let n=this.values[e];return typeof n==`number`&&Number.isFinite(n)?n:typeof n==`boolean`?+!!n:t}flag(e,t=!1){let n=this.values[e];return typeof n==`boolean`?n:t}list(e){let t=this.values[e];return Array.isArray(t)?t:typeof t==`string`?[t]:[]}names(){return Object.keys(this.values)}with(t){let n=new e(this.values);for(let[e,r]of Object.entries(t))r!==void 0&&n.set(e,r);return n}toJSON(){return{...this.values}}static fromJSON(t){return new e(t)}},KZ=class{constructor(e=[],t={}){this.levels=new Map,this.base=new GZ(t);for(let t of e){if(this.levels.has(t.id))throw Error(`duplicate difficulty level: ${t.id}`);this.levels.set(t.id,t)}}get ids(){return[...this.levels.keys()]}get(e){return this.levels.get(e)}aspectsFor(e){let t=this.levels.get(e);if(!t)throw Error(`unknown difficulty level: ${e}`);return this.base.with(t.aspects??{})}},qZ=class{constructor(){this.byUnit=new Map}set(e){this.byUnit.set(e.unit,{...e})}clear(e){this.byUnit.delete(e)}get(e){return this.byUnit.get(e)}all(){return[...this.byUnit.values()]}get isEmpty(){return this.byUnit.size===0}},JZ=class{constructor(e,t=null){this.order=e,this.fallback=t}get length(){return this.order.length}at(e){if(this.order.length===0)return this.fallback;let t=(e%this.order.length+this.order.length)%this.order.length;return this.order[t]}next(e){if(this.order.length===0)return this.fallback;if(e===null)return this.order[0];let t=this.order.indexOf(e);return this.at(t<0?0:t+1)}},YZ=class{constructor(e){this.stages=e.stages}decide(e,t){if(e.length===0)return null;for(let n of this.stages){if(n.when&&!n.when(t))continue;let r=n.weigh??XZ,i=null;for(let a of e){let e=r(a,t);(!i||e>i.score)&&(i={candidate:a,stage:n.id,score:e})}return i}return null}};function XZ(e,t){let n=0;for(let[r,i]of Object.entries(e.factors??{}))r!==`distance`&&(n+=i*t.aspects.number(r,1));let r=e.factors?.distance;return r!==void 0&&(n+=ZZ(r,t.aspects.number(`keep_away`,0))),n}function ZZ(e,t){return!(t>0)||e>=t?0:-(t-e)}function QZ(e){return e?Math.max(0,e.priority??1):0}var $Z=l({AIBudgetExceededError:()=>iQ,AICancelledError:()=>rQ,Aspects:()=>GZ,Difficulty:()=>KZ,Goals:()=>qZ,HeuristicAI:()=>YZ,JavaScriptAI:()=>nQ,NeuralPolicy:()=>kJ,RecruitmentPattern:()=>JZ,Suggester:()=>BZ,alphaBetaSearch:()=>bU,defaultWeigh:()=>XZ,firstWins:()=>SU,goalScore:()=>QZ,keepAwayScore:()=>ZZ,personalScoreView:()=>HZ,rootSplits:()=>xU,scoreWith:()=>WZ,sideScoreView:()=>UZ,subjectsWhere:()=>VZ}),eQ=1e4,tQ=16,nQ=class{constructor(e={}){this.agents=new Map,this.states=new Map,this.options=e,lQ(e.maxSteps??eQ,`maxSteps`),uQ(e.maxMilliseconds??tQ,`maxMilliseconds`)}register(e){if(!/^[A-Za-z_][A-Za-z0-9_.-]*$/.test(e.id))throw Error(`invalid AI agent id: ${e.id}`);if(this.agents.has(e.id))throw Error(`AI agent already registered: ${e.id}`);if(!e.behaviors.length)throw Error(`AI agent has no behaviours: ${e.id}`);let t=new Set;for(let n of e.behaviors){if(!n.id||t.has(n.id))throw Error(`duplicate AI behaviour: ${n.id}`);t.add(n.id)}this.agents.set(e.id,e),this.states.set(e.id,{})}decide(e,t){let n=this.agents.get(e);if(!n)throw Error(`unknown AI agent: ${e}`);let r=oQ(t.state??this.states.get(e)??{}),i=t.maxSteps??this.options.maxSteps??eQ,a=t.maxMilliseconds??this.options.maxMilliseconds??tQ;lQ(i,`maxSteps`),uQ(a,`maxMilliseconds`);let o=0,s=dQ(),c=[],l=cQ(t.seed??this.options.seed??7173991),u=()=>{if(o++,t.signal?.aborted)throw new rQ;if(o>i||dQ()-s>a)throw new iQ},d={perception:sQ(t.perception),state:r,random:()=>(u(),l()),checkpoint:u,emit(e,t){if(!e)throw Error(`AI event name must not be empty`);u(),c.push(t===void 0?{name:e}:{name:e,payload:sQ(t)})}},f=null,p,m=`idle`;try{for(let e of n.behaviors)if(u(),!e.when||e.when(d)){p=e.id,f=aQ(e.decide(d)),m=f?`action`:`idle`;break}}catch(e){if(e instanceof rQ)m=`cancelled`;else if(e instanceof iQ)m=`budget-exceeded`;else throw e}let h={agent:e,action:f,state:oQ(r),behavior:p,status:m,steps:o,events:c};return this.states.set(e,oQ(r)),this.options.onDecision?.(h),h}search(e,t,n){return bU(e,t,n)}exportState(){return{version:1,agents:Object.fromEntries([...this.states].map(([e,t])=>[e,oQ(t)]))}}importState(e){if(e.version!==1)throw Error(`unsupported AI state version: ${e.version}`);for(let[t,n]of Object.entries(e.agents)){if(!this.agents.has(t))throw Error(`AI state names unknown agent: ${t}`);this.states.set(t,oQ(n))}}dispose(){this.agents.clear(),this.states.clear()}},rQ=class extends Error{constructor(){super(`AI decision cancelled`),this.name=`AICancelledError`}},iQ=class extends Error{constructor(){super(`AI decision budget exceeded`),this.name=`AIBudgetExceededError`}};function aQ(e){if(e===null)return null;if(!e||typeof e!=`object`||Array.isArray(e)||typeof e.type!=`string`||!e.type)throw Error(`AI action must be an object with a non-empty string type`);return sQ(e)}function oQ(e){return sQ(e)}function sQ(e){return typeof e!=`object`||!e?e:Array.isArray(e)?e.map(sQ):Object.fromEntries(Object.entries(e).map(([e,t])=>[e,sQ(t)]))}function cQ(e){if(!Number.isInteger(e))throw TypeError(`AI seed must be an integer`);let t=e>>>0;return()=>(t=Math.imul(t,1664525)+1013904223>>>0,t/4294967296)}function lQ(e,t){if(!Number.isInteger(e)||e<1)throw RangeError(`${t} must be a positive integer`)}function uQ(e,t){if(!Number.isFinite(e)||e<0)throw RangeError(`${t} must be a non-negative number`)}function dQ(){return typeof performance>`u`?Date.now():performance.now()}return _e(),ja(),Xo(),vs(),Object.defineProperty(e,"AI",{enumerable:!0,get:function(){return $Z}}),e.Achievements=Tn,e.ActionJournal=Cn,e.ActorAnimator=vP,Object.defineProperty(e,"Actors",{enumerable:!0,get:function(){return MV}}),e.AnimatedSprite=AM,e.Animation=OM,Object.defineProperty(e,"Audio",{enumerable:!0,get:function(){return TJ}}),e.BLOB_SHAPES=CP,e.Bar=MR,Object.defineProperty(e,"Battle",{enumerable:!0,get:function(){return YH}}),e.Beam=iP,e.Beams=aP,e.BitmapLabel=QF,e.Blob=Cr,Object.defineProperty(e,"Board",{enumerable:!0,get:function(){return $G}}),e.Button=KL,e.CIRCLE8=cr,e.COLOR_BLINDNESS_MATRICES=dN,e.Camera=aN,e.CanonicalState=Ut,e.Checkbox=oR,e.Collection=sn,e.ColorTransformBatcher=Bj,e.Container2D=Y,e.DataTable=dR,e.DialogueStage=ez,e.Dropdown=uR,e.EMPTY=qN,e.Easing=wr,e.EntityRegistry=jr,e.FLOATING_TEXT_STACK_GAP=RR,e.FeedbackClient=Hn,e.Flights=rP,e.FloatingText=LR,e.FloatingTextStack=HR,e.FogLayer=uP,e.Game=Aj,e.Generator=j,e.Gradient=VP,e.Grid=yR,e.HALO_ANIMATION=dP,e.Halo=fP,e.HelpScreen=GR,e.HookRegistry=S,e.HttpTransport=qt,Object.defineProperty(e,"I18n",{enumerable:!0,get:function(){return mL}}),e.IconGrid=cI,Object.defineProperty(e,"Input",{enumerable:!0,get:function(){return ve}}),e.JavaRandom=xt,e.Label=sF,e.LastRun=_n,e.LayeredSprite=eP,e.LightningArc=oP,e.LiquidLayer=cP,e.ListView=sI,e.LoadQueue=Ar,e.LoadingScreen=qR,e.LockstepClient=Xt,e.Logger=b,e.MarkupText=KF,e.MersenneTwister=he,e.MessageBox=WL,e.MessageLog=dF,e.Meter=kR,e.Minimap=hN,Object.defineProperty(e,"Mwl",{enumerable:!0,get:function(){return zZ}}),e.NEIGHBOURS4=or,e.NEIGHBOURS8=sr,e.NO_COLOR_ADD=Xj,e.NewsClient=rn,e.NewsSeenTracker=on,e.NinePatch=eI,e.Node2D=FP,e.OnScreenKeyboard=ZL,e.ParticleEmitter=gP,e.Player=ln,e.PlayerInput=_t,e.PlayerStats=tn,e.PresentationQueue=Mr,e.Projectile=tP,e.QualityScaler=Cj,e.RENDERING_DECISIONS=UP,e.RPGM_AUTOTILE_SLOT_BASES=TN,e.RPGM_AUTOTILE_SLOT_COUNTS=EN,e.RPGM_FLOOR_AUTOTILE_TABLE=ON,e.RPGM_WALL_AUTOTILE_TABLE=kN,e.RadioGroup=sR,Object.defineProperty(e,"Random",{enumerable:!0,get:function(){return C}}),e.RandomStreams=ge,e.ReactionTable=En,e.RebindScreen=DR,e.Recorder=cn,e.Rectangle2D=K,e.Registry=g,Object.defineProperty(e,"Resources",{enumerable:!0,get:function(){return nN}}),e.RichLabel=DF,Object.defineProperty(e,"Roguelike",{enumerable:!0,get:function(){return PB}}),Object.defineProperty(e,"Rpg",{enumerable:!0,get:function(){return AH}}),e.RpgmAutotileAtlas=wN,e.RunHistory=en,e.SaveSyncClient=Jt,e.SaveSystem=Rt,e.Scene=m,e.Scene2D=jj,e.SceneComponentHost=v,e.SceneStack=h,e.ScreenEffects=_P,e.ScreenReader=nI,e.ScrollBox=gR,e.Session=Dn,e.Settings=Mn,e.SettingsScreen=OR,e.Shape2D=LP,e.Signal=p,Object.defineProperty(e,"Simulation",{enumerable:!0,get:function(){return GJ}}),e.Skins=TR,e.Slider=aR,e.Spawner=Un,e.Spinner=lR,e.Sprite2D=zP,e.SpriteAttachment=sP,e.SpriteGroup=NM,e.SpriteMotion=SP,e.SpriteSheet=iN,e.StageScript=tz,e.StateRegistry=Wt,e.StatsScreen=KR,e.StatusVisuals=yP,e.StoryScreen=sz,e.StorySequence=oz,e.SyncGuard=Lr,e.TabbedList=lI,e.TelemetryClient=nn,e.TerrainGraphicsLayer=HP,e.Text2D=RP,e.TextModel=GL,e.TextPrompt=$L,e.Texture2D=J,e.TileMap=$N,e.TiledSprite=BP,e.TintedSprite=Zj,e.Toast=UR,e.Tooltip=WR,e.TreeView=mR,e.Tweener=Tr,e.UPPERCASE_KEYBOARD=JL,e.UndoHistory=Er,e.VerticalLabel=nR,e.Viewport=lN,e.Window=iI,e.WindowStack=aI,Object.defineProperty(e,"World",{enumerable:!0,get:function(){return BV}}),e.XP_AUTOTILE_PATTERNS=AN,e.XP_NEIGHBORS_TO_PATTERN=jN,e.advanceReveal=iF,e.anchorAlign=_R,e.applyAllImageModifiers=_M,e.applyImageModifiers=gM,e.applyTextureModifiers=SM,e.assertAutotileLayout=FN,e.autotileCellParts=VN,e.autotileFrames=OP,e.bitmapLabelStyle=$F,e.blendMatrix=dM,e.blendPixels=TM,e.blobIndex=DP,e.cellFromKey=ar,e.cellIndex=tr,e.cellInside=er,e.cellKey=ir,e.cellX=nr,e.cellY=rr,e.channelScaleMatrix=uM,e.channelSwapMatrix=fM,e.chebyshev=ur,e.checkNoControlCharacters=Ot,e.checkSize=Dt,e.clamp=On,e.cloneData=Ht,e.colorShiftMatrix=lM,e.completeReveal=aF,e.contrastRatio=ZR,e.createCamera=cN,e.createColorBlindnessFilter=fN,e.createHandles=_,e.createLayers=IP,e.croppedTexture=vM,e.defaultSettings=kn,e.defaultTheme=ZP,e.deserializeReplay=dn,e.detectWebGpu=GP,e.distance=fr,e.downloadReplayFile=bn,e.effectiveMusicVolume=An,e.effectiveSfxVolume=jn,e.escapeHtml=zF,e.euclidean=lr,e.exportReplayFile=hn,e.extractDialogueCatalog=az,e.fitWindowZoom=fF,e.floatingTextAgeAtLeast=IR,e.floatingTextAlpha=PR,e.floatingTextRise=FR,e.floatingTextStackLifePenalty=zR,e.floatingTextStackLift=BR,e.floatingTextStackMoves=VR,e.hexDistance=Jn,e.hexLine=Xn,e.hexNeighbors=qn,e.hexRange=Zn,e.hexRotate=AP,e.hexToPixel=Qn,e.highContrastTheme=QP,e.imageModifier=sM,e.importReplayFile=gn,e.importTwee=rz,e.inspectGraphicsCapabilities=WP,e.isOnScreen=MM,e.layoutMarkupLines=IF,e.layoutVertical=tR,e.linesToDrop=uF,e.loadTiledMap=XP,e.manhattan=dr,e.markupAccessibilityText=FF,e.markupToHtml=PF,e.maskPixels=wM,e.matchTerrainRule=MP,e.meetsContrast=QR,e.messageBoxPresenter=JR,e.minimapCellCenter=mN,e.motionDuration=Sr,e.newlyRevealed=pN,e.packColorAdd=qj,e.packTintAdd=Jj,e.paintFogPixels=lP,e.paletteRangeMapping=nM,e.parseCSV=Rr,e.parseColorPairs=bM,e.parseDialogueLines=Hr,e.parseDialogueText=iz,e.parseImagePath=oM,e.parseInbound=Nt,e.parseMarkdown=wF,e.parseMarkup=MF,e.parsePaletteLists=xM,e.parseReplayEvents=fn,e.parseRotateMode=cM,e.parseTwee=Ur,e.pickReplayFile=Sn,e.pixelToHex=$n,e.positionMarkupLines=RF,e.prefersReducedMotion=vr,e.readReplayFile=xn,e.recolorTexture=aM,e.rectOf=rN,e.reducedMotion=yr,e.registerColorTransform=Kj,e.relativeLuminance=XR,e.remapPixels=rM,e.resolveAnchor=vR,e.resolveTerrainGraphics=NP,e.resumeRunPlayer=yn,e.revealComplete=oF,e.rotatePixels=EM,e.rpgmAutotileFrame=CN,e.rpgmAutotileSlot=DN,e.rpgmTableEdgeCells=KN,e.runCheckpoint=vn,e.sanitizeInboundText=kt,e.scramble=St,e.screenReader=rI,e.scrollOffset=hR,e.serializeReplay=un,e.setReducedMotion=br,e.setTheme=eF,e.sharpenText=mF,e.sliceSpans=EF,e.sliderFraction=rR,e.sliderValueAt=iR,e.snapZoom=sN,e.spinValue=cR,e.splitScreenHalves=uN,e.spriteColorMatrix=pM,e.squareRotate=kP,e.startReveal=rF,e.stateChecksum=Ir,e.stripMarkdown=TF,e.stripMarkup=NF,e.takeLastEntries=lF,e.theme=Q,e.themeChanged=$,e.tileFrame=XN,e.tileFrameIndex=QN,e.tileFrameSheet=ZN,e.uncloneablePath=zt,e.unscramble=Ct,e.validateSchema=Mt,e.version=f,e.watchReducedMotion=xr,e.weightedFlood=Dr,e.withTextureCanvas=iM,e.xpAutotilePattern=NN,e.xpAutotileRef=MN,e})({});