@utsp/core 0.17.0-nightly.20260128135217.8ab29d7 → 0.17.0-nightly.20260128152056.03a8669

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -10,6 +10,6 @@ Orders breakdown: ${this.getOrdersBreakdown()}`),this.orders=this.orders.slice(0
10
10
  `,this.buttons.forEach(t=>{e+=` [${t.bindingId}] ${t.name}: `,e+=`(default: ${t.defaultValue})
11
11
  `}),e+=`Touch Zones (${this.touchZones.size}):
12
12
  `,this.touchZones.forEach(t=>{e+=` [${t.zoneId}] ${t.name}: `,e+=`(${t.x}, ${t.y}) ${t.width}x${t.height}
13
- `}),e}};b(yr,"InputBindingRegistry");var ie=yr;function Xe(x=0n){return{tick:x,axes:new Map,buttons:new Map,displayId:0,mouseX:0,mouseY:0,mouseOverDisplay:!1,textInputs:[],macroEvents:[],displayViewports:[],touchPositions:[]}}b(Xe,"createEmptyCompressedInputPacket");function Ge(x){let e=Math.max(-1,Math.min(1,x));return Math.round(e*127)}b(Ge,"encodeAxisToInt8");function $e(x){return x/127}b($e,"decodeInt8ToAxis");function W(x){return x===0?0:Math.ceil(x/8)}b(W,"getButtonByteCount");function Ze(x,e){let r=x,n=W(e);return 8+r+n+4}b(Ze,"getCompressedPacketSize");var Cr=class Cr{decode(e,t=0){let r=e.readUInt8(t);switch(r){case 1:return this.decodeClick(e,t);case 2:return this.decodeChange(e,t);case 3:return this.decodeSubmit(e,t);case 4:return this.decodeSelect(e,t);default:throw new Error(`Unknown macro event type: 0x${r.toString(16)}`)}}decodeAll(e,t,r){let n=[],o=0;for(let i=0;i<r;i++){let{event:s,bytesRead:a}=this.decode(e,t+o);n.push(s),o+=a}return{events:n,bytesRead:o}}decodeClick(e,t){let r=e.readUInt8(t),n=e.readUInt8(t+1);return{event:{type:r,instanceId:n},bytesRead:2}}decodeChange(e,t){let r=e.readUInt8(t),n=e.readUInt8(t+1),o=e.readUInt8(t+2),i,s;return o===1?(i=e.readUInt8(t+3)===1,s=4):(i=e.readFloatBE(t+3),s=7),{event:{type:r,instanceId:n,value:i},bytesRead:s}}decodeSubmit(e,t){let r=t,n=e.readUInt8(t++),o=e.readUInt8(t++),i=e.readUInt16BE(t);t+=2;let s=e.toUint8Array().subarray(t,t+i);t+=i;let a=new TextDecoder().decode(s);return{event:{type:n,instanceId:o,text:a},bytesRead:t-r}}decodeSelect(e,t){let r=e.readUInt8(t),n=e.readUInt8(t+1),o=e.readUInt16BE(t+2);return{event:{type:r,instanceId:n,index:o},bytesRead:4}}};b(Cr,"MacroEventDecoder");var We=Cr;V();function je(x,e){let t=e.getAllAxes().length,r=e.getAllButtons().length,n=W(r),o=8+t+n+4;if(x.length<o)throw new Error(`Invalid compressed input packet: expected at least ${o} bytes (${t} axes + ${r} buttons), got ${x.length}`);let i=new DataView(x.buffer,x.byteOffset,x.byteLength),s=0,a=Xe();a.tick=i.getBigUint64(s,!0),s+=8;for(let l=0;l<t;l++){let c=x[s],u=c>127?c-256:c,p=$e(u);a.axes.set(l,p),s+=1}for(let l=0;l<n;l++){let c=x[s];for(let u=0;u<8;u++){let p=l*8+u;if(p<r){let m=(c&1<<u)!==0;a.buttons.set(p,m)}}s+=1}a.displayId=x[s],s+=1,a.mouseX=x[s],s+=1,a.mouseY=x[s],s+=1;let d=x[s];if(a.mouseOverDisplay=(d&1)!==0,s+=1,s<x.length){let l=x[s];s+=1;let c=new TextDecoder;a.textInputs=[];for(let u=0;u<l&&s<x.length;u++){let p=x[s];if(s+=1,s+p<=x.length){let m=x.slice(s,s+p),g=c.decode(m);a.textInputs.push(g),s+=p}}}if(s<x.length){let l=x[s];s+=1;let c=new We,u=[],p=C.from(x);for(let m=0;m<l&&s<x.length;m++){let g=c.decode(p,s);u.push(g.event),s+=g.bytesRead}a.macroEvents=u}if(s<x.length){let l=x[s];s+=1;for(let c=0;c<l&&s+5<=x.length;c++){let u=x[s];s+=1;let p=i.getUint16(s,!1);s+=2;let m=i.getUint16(s,!1);s+=2,a.displayViewports.push({displayId:u,pixelWidth:p,pixelHeight:m})}}if(s<x.length){let l=Math.min(x[s],10);s+=1;for(let c=0;c<l&&s+4<=x.length;c++){let u=x[s]&15;s+=1;let p=x[s];s+=1;let m=x[s];s+=1;let y=(x[s]&1)!==0;s+=1,a.touchPositions.push({id:u,x:p,y:m,over:y})}}return a}b(je,"decodeCompressedInput");var T=require("@utsp/types");var fr=class fr{constructor(e,t){h(this,"enabled",!1);h(this,"currentStats",null);h(this,"_userId");h(this,"_userName");this._userId=e,this._userName=t}setEnabled(e){this.enabled=e,e||(this.currentStats=null)}isEnabled(){return this.enabled}get userId(){return this.currentStats?.userId??this._userId}get userName(){return this.currentStats?.userName??this._userName}get tick(){return this.currentStats?.tick??0}get timestamp(){return this.currentStats?.timestamp??0}get displayCount(){return this.currentStats?.displayCount??0}get totalDisplayArea(){return this.currentStats?.totalDisplayArea??0}get totalLayers(){return this.currentStats?.totalLayers??0}get visibleLayers(){return this.currentStats?.visibleLayers??0}get staticLayers(){return this.currentStats?.staticLayers??0}get dynamicLayers(){return this.currentStats?.dynamicLayers??0}get totalOrders(){return this.currentStats?.totalOrders??0}get ordersByLayer(){return this.currentStats?.ordersByLayer??new Map}get staticPacketSize(){return this.currentStats?.staticPacketSize??0}get dynamicPacketSize(){return this.currentStats?.dynamicPacketSize??0}get totalPacketSize(){return this.currentStats?.totalPacketSize??0}get compressedPacketSize(){return Math.round(this.totalPacketSize*.25)}get hasInput(){return this.currentStats?.hasInput??!1}get axisCount(){return this.currentStats?.axisCount??0}get buttonCount(){return this.currentStats?.buttonCount??0}startTick(e){this.enabled&&(this.currentStats={userId:this._userId,userName:this._userName,tick:e,timestamp:Date.now(),displayCount:0,totalDisplayArea:0,totalLayers:0,visibleLayers:0,staticLayers:0,dynamicLayers:0,totalOrders:0,ordersByLayer:new Map,staticPacketSize:0,dynamicPacketSize:0,totalPacketSize:0,hasInput:!1,axisCount:0,buttonCount:0})}recordDisplays(e,t){!this.enabled||!this.currentStats||(this.currentStats.displayCount=e,this.currentStats.totalDisplayArea=t)}recordLayers(e,t,r,n){!this.enabled||!this.currentStats||(this.currentStats.totalLayers=e,this.currentStats.visibleLayers=t,this.currentStats.staticLayers=r,this.currentStats.dynamicLayers=n)}recordLayerOrders(e,t){!this.enabled||!this.currentStats||(this.currentStats.totalOrders+=t,this.currentStats.ordersByLayer.set(e,t))}recordPacketSizes(e,t){!this.enabled||!this.currentStats||(this.currentStats.staticPacketSize=e,this.currentStats.dynamicPacketSize=t,this.currentStats.totalPacketSize=e+t)}recordInput(e,t,r){!this.enabled||!this.currentStats||(this.currentStats.hasInput=e,this.currentStats.axisCount=t,this.currentStats.buttonCount=r)}endTick(){}reset(){this.currentStats=null}};b(fr,"UserStats");var se=fr;var Mr=class Mr{constructor(e,t,r){this.id=e;this.name=t;h(this,"displays",[]);h(this,"layers",[]);h(this,"spriteRegistry");h(this,"mode");h(this,"axes",new Map);h(this,"buttons",new Map);h(this,"textInputs",[]);h(this,"mouseX",0);h(this,"mouseY",0);h(this,"mouseOver",!1);h(this,"mouseDisplayId",0);h(this,"touchPositions",new Map);h(this,"activeTouchId",null);h(this,"inputBindings",new ie);h(this,"stats");h(this,"soundCommands",[]);h(this,"nextSoundInstanceId",1);h(this,"audioConfigCommands",[]);h(this,"lastListenerX",-1);h(this,"lastListenerY",-1);h(this,"pendingSendSounds",!1);h(this,"audioProcessor");h(this,"loadedSounds",new Map);h(this,"soundLoadErrors",new Map);h(this,"playingSounds",new Map);h(this,"mobileVibrationCommands",[]);h(this,"mobileVibrationProcessor");h(this,"gamepadVibrationCommands",[]);h(this,"gamepadVibrationProcessor");h(this,"macroRegistry",new re);h(this,"macroEngine",new oe);h(this,"macroEventHandlers",new Map);h(this,"postProcessCommands",[]);h(this,"currentPostProcessConfig",null);h(this,"bridgeMessages",[]);h(this,"totalBytesSent",0);h(this,"totalBytesReceived",0);h(this,"bytesSentPerTick",[]);h(this,"bytesReceivedPerTick",[]);h(this,"bytesTickIndex",0);h(this,"bytesTickRate",20);h(this,"currentTickBytesSent",0);h(this,"currentTickBytesReceived",0);h(this,"availableViewports",new Map);h(this,"displayCommandSink",{setPostProcess:(e,t)=>this.setPostProcess(e,t),setScanlinesEnabled:(e,t)=>this.setScanlinesEnabled(e,t),setScanlinesOpacity:(e,t)=>this.setScanlinesOpacity(e,t),setScanlinesPattern:(e,t)=>this.setScanlinesPattern(e,t),setAmbientEffect:(e,t)=>this.setAmbientEffect(e,t),setAmbientEffectEnabled:(e,t)=>this.setAmbientEffectEnabled(e,t),setAmbientEffectBlur:(e,t)=>this.setAmbientEffectBlur(e,t),setAmbientEffectScale:(e,t)=>this.setAmbientEffectScale(e,t),isAmbientEffectEnabled:()=>this.isAmbientEffectEnabled(),getAmbientEffectConfig:()=>this.getAmbientEffectConfig(),getPostProcessConfig:()=>this.getPostProcessConfig(),setScalingMode:(e,t)=>this.setScalingMode(e,t),getScalingMode:e=>this.getScalingMode(e),setCellSize:(e,t,r)=>this.setCellSize(e,t,r),getCellSize:e=>this.getCellSize(e),setGrid:(e,t)=>this.setGrid(e,t),setGridEnabled:(e,t)=>this.setGridEnabled(e,t),isGridEnabled:e=>this.isGridEnabled(e),getGridConfig:e=>this.getGridConfig(e),switchPalette:(e,t)=>this.switchPalette(e,t),getCurrentPaletteSlotId:e=>this.getCurrentPaletteSlotId(e)});h(this,"data");h(this,"currentScalingModes",new Map);h(this,"currentCellSizes",new Map);h(this,"currentGridConfigs",new Map);h(this,"currentPaletteSlotIds",new Map);this.mode=r,this.stats=new se(e,t),this.data={}}setSpriteRegistry(e){this.spriteRegistry=e;for(let t of this.layers)t.setSpriteRegistry(e);this.macroEngine.setSpriteRegistry(e)}getDisplays(){return this.displays}addDisplay(e){e.setCommandSink(this.displayCommandSink),this.displays.push(e)}removeDisplay(e){let t=this.displays.indexOf(e);return t!==-1?(this.displays.splice(t,1),!0):!1}clearDisplays(){this.displays=[]}setDisplayViewport(e,t,r){this.availableViewports.set(e,{pixelWidth:t,pixelHeight:r})}getDisplayViewport(e){return this.availableViewports.get(e)??null}getAllDisplayViewports(){return this.availableViewports}calculateMaxCells(e,t,r){let n=this.availableViewports.get(e);return n?{cols:Math.floor(n.pixelWidth/t),rows:Math.floor(n.pixelHeight/r)}:null}getLayers(){return this.layers}getLayerById(e){return this.layers.find(t=>t.getId()===e)}addLayer(e,t){e.setMode(this.mode);let r=this.layers.length+1;te(e,r),this.layers.push(e),this.spriteRegistry&&e.setSpriteRegistry(this.spriteRegistry),t&&this.macroRegistry.setLayerMapping(t,e.getId())}removeLayer(e){let t=this.layers.indexOf(e);return t!==-1?(this.layers.splice(t,1),!0):!1}clearLayers(){this.layers=[]}setMousePosition(e,t,r=!0){this.mouseX=Math.max(0,Math.min(255,e)),this.mouseY=Math.max(0,Math.min(255,t)),this.mouseOver=r}setTouchPosition(e,t,r,n=!0,o=0){if(e<0||e>9){console.warn(`Invalid touchId ${e}, must be 0-9`);return}n?(this.touchPositions.set(e,{x:Math.max(0,Math.min(255,t)),y:Math.max(0,Math.min(255,r)),over:!0,displayId:o}),this.activeTouchId=e):(this.touchPositions.delete(e),this.activeTouchId===e&&(this.activeTouchId=null))}setAxis(e,t){let r=Math.max(-1,Math.min(1,t));this.axes.set(e,r)}getAxis(e){return this.axes.get(e)??0}setButton(e,t){this.buttons.set(e,t)}getButton(e){return this.buttons.get(e)??!1}getButtonJustPressed(e){let t=`${e}_justPressed`;return this.buttons.get(t)??!1}getButtonJustReleased(e){let t=`${e}_justReleased`;return this.buttons.get(t)??!1}setTextInputs(e){this.textInputs=e}getTextInputs(){return this.textInputs}clearTextInputs(){this.textInputs=[]}getAxisNames(){return Array.from(this.axes.keys())}getButtonNames(){return Array.from(this.buttons.keys())}clearAxes(){this.axes.clear()}clearButtons(){this.buttons.clear()}getMouseDisplayInfo(){if(!this.mouseOver||this.displays.length===0)return null;let e=this.displays[0],t=0,r=this.mouseX,n=this.mouseY,o=e.getOrigin(),i=o.x+r,s=o.y+n;return{displayId:t,localX:r,localY:n,worldX:i,worldY:s}}getTouchDisplayInfo(e=0){if(e<0||e>9)return console.warn(`Invalid touchId ${e}, must be 0-9`),null;let t=this.touchPositions.get(e);if(!t||!t.over||this.displays.length===0)return null;let r=this.displays[0],n=t.displayId,o=t.x,i=t.y,s=r.getOrigin(),a=s.x+o,d=s.y+i;return{displayId:n,localX:o,localY:i,worldX:a,worldY:d}}getIsMouseOnADisplay(){return this.mouseOver}getMouseDisplayHover(){let e=this.getMouseDisplayInfo();return e?e.displayId:null}findLayerById(e){return this.layers.find(t=>t.getId()===e)??null}applyUpdate(e){if(this.updateDisplaysFromPacket(e.displays),this.updateLayersFromPacket(e.layers),e.macroOrders&&e.macroOrders.length>0)for(let t of e.macroOrders)this.macroEngine.applyOrder(t)}updateDisplaysFromPacket(e){for(let t of e){let r=this.displays[t.id];if(!r){for(r=new Q(t.id,t.sizeX,t.sizeY);this.displays.length<=t.id;)this.displays.push(null);this.displays[t.id]=r}r.setCommandSink(this.displayCommandSink),r.setOrigin(new T.Vector2(t.originX,t.originY)),r.setSize(new T.Vector2(t.sizeX,t.sizeY)),r.setRenderPasses(t.renderPasses)}}updateLayersFromPacket(e){for(let t of e){let r=this.findLayerById(t.id);r||(r=new ee(new T.Vector2(t.originX,t.originY),t.zIndex,t.width,t.height,{mustBeReliable:!1,isMacroLayer:t.isMacroLayer,charCodeMode:t.is16bit?"16bit":"8bit"}),te(r,t.id),r.setMode(this.mode),this.spriteRegistry&&r.setSpriteRegistry(this.spriteRegistry),this.addLayer(r)),t.updateFlags&1&&r.setOrigin(new T.Vector2(t.originX,t.originY)),t.updateFlags&2&&r.setZOrder(t.zIndex),t.updateFlags&4&&r.setOrders(t.orders)}}defineAxisBinding(e,t,r=[],n=-1,o=1,i=0){this.inputBindings.defineAxis(e,t,r,n,o,i)}defineButtonBinding(e,t,r=[],n=!1){this.inputBindings.defineButton(e,t,r,n)}defineAxisBindings(e){e.forEach(({bindingId:t,name:r,sources:n,min:o,max:i,defaultValue:s})=>{this.defineAxisBinding(t,r,n??[],o,i,s)})}defineButtonBindings(e){e.forEach(({bindingId:t,name:r,sources:n,defaultValue:o})=>{this.defineButtonBinding(t,r,n??[],o)})}getInputBindingsLoadPacket(){return this.inputBindings.toLoadPacket()}applyInputBindingsLoadPacket(e){try{let t=JSON.parse(e);if(t.type!=="input-binding")throw new Error(`Invalid packet type: ${t.type}`);this.inputBindings.clear();for(let r of t.axes)this.defineAxisBinding(r.bindingId,r.name,r.sources||[],r.min,r.max,r.defaultValue);for(let r of t.buttons)this.defineButtonBinding(r.bindingId,r.name,r.sources||[],r.defaultValue)}catch(t){throw console.error("[User] Failed to apply input bindings:",t),t}}getInputBindingRegistry(){return this.inputBindings}getStats(){return this.stats}getTotalBytesSent(){return this.totalBytesSent}getTotalBytesReceived(){return this.totalBytesReceived}recordBytesSent(e){this.totalBytesSent+=e,this.currentTickBytesSent+=e}recordBytesReceived(e){this.totalBytesReceived+=e,this.currentTickBytesReceived+=e}resetByteCounters(){this.totalBytesSent=0,this.totalBytesReceived=0}setBytesTickRate(e){e<=0||(this.bytesTickRate=e,this.bytesSentPerTick=new Array(e).fill(0),this.bytesReceivedPerTick=new Array(e).fill(0),this.bytesTickIndex=0)}endTickBytes(){this.bytesSentPerTick.length!==this.bytesTickRate&&(this.bytesSentPerTick=new Array(this.bytesTickRate).fill(0),this.bytesReceivedPerTick=new Array(this.bytesTickRate).fill(0)),this.bytesSentPerTick[this.bytesTickIndex]=this.currentTickBytesSent,this.bytesReceivedPerTick[this.bytesTickIndex]=this.currentTickBytesReceived,this.bytesTickIndex=(this.bytesTickIndex+1)%this.bytesTickRate,this.currentTickBytesSent=0,this.currentTickBytesReceived=0}getBytesSentPerSecond(){return this.bytesSentPerTick.reduce((e,t)=>e+t,0)}getBytesReceivedPerSecond(){return this.bytesReceivedPerTick.reduce((e,t)=>e+t,0)}getAxisBindingId(e){return this.inputBindings.getAxisBindingId(e)}getButtonBindingId(e){return this.inputBindings.getButtonBindingId(e)}decodeAndApplyCompressedInput(e){let t=je(e,this.inputBindings),r=this.inputBindings.getAllAxes(),n=this.inputBindings.getAllButtons(),o=r.sort((s,a)=>s.bindingId-a.bindingId),i=n.sort((s,a)=>s.bindingId-a.bindingId);for(let[s,a]of t.axes)if(s<o.length){let d=o[s];this.setAxis(d.name,a)}for(let[s,a]of t.buttons)if(s<i.length){let d=i[s];this.setButton(d.name,a)}this.mouseX=t.mouseX,this.mouseY=t.mouseY,this.mouseOver=t.mouseOverDisplay,this.mouseDisplayId=t.displayId;for(let s of t.touchPositions)this.setTouchPosition(s.id,s.x,s.y,s.over);for(let s of t.displayViewports)this.setDisplayViewport(s.displayId,s.pixelWidth,s.pixelHeight)}playSound(e,t){let r=this.nextSoundInstanceId++,n={sound:e,instanceId:r,volume:t?.volume,pitch:t?.pitch,loop:t?.loop,fadeIn:t?.fadeIn,x:t?.x,y:t?.y,lowpass:t?.lowpass,highpass:t?.highpass,reverb:t?.reverb};return this.soundCommands.push(n),r}stopSound(e){let t={sound:e};this.soundCommands.push(t)}fadeOutSound(e,t){let r={fadeOut:!0,sound:e,duration:t};this.soundCommands.push(r)}fadeOutAllSounds(e){let t={fadeOut:!0,sound:"all",duration:e};this.soundCommands.push(t)}stopAllSounds(){let e={sound:"all"};this.soundCommands.push(e)}pauseSound(e){let t={pause:!0,sound:e};this.soundCommands.push(t)}pauseAllSounds(){let e={pause:!0,sound:"all"};this.soundCommands.push(e)}resumeSound(e){let t={resume:!0,sound:e};this.soundCommands.push(t)}resumeAllSounds(){let e={resume:!0,sound:"all"};this.soundCommands.push(e)}setSoundEffects(e,t){let r={setEffects:!0,instanceId:e,lowpass:t.lowpass,highpass:t.highpass,reverb:t.reverb};this.soundCommands.push(r)}setListenerPosition(e,t){e===this.lastListenerX&&t===this.lastListenerY||(this.lastListenerX=e,this.lastListenerY=t,this.audioConfigCommands.push({type:"set-listener-position",x:e,y:t}))}configureSpatialAudio(e){this.audioConfigCommands.push({type:"configure-spatial",...e})}flushAudioConfigCommands(){let e=this.audioConfigCommands;return this.audioConfigCommands=[],e}hasAudioConfigCommands(){return this.audioConfigCommands.length>0}flushSoundCommands(){let e=this.soundCommands;return this.soundCommands=[],e}hasSoundCommands(){return this.soundCommands.length>0}sendSounds(){this.pendingSendSounds=!0}needsSendSounds(){return this.pendingSendSounds}clearSendSounds(){this.pendingSendSounds=!1}setAudioProcessor(e){this.audioProcessor=e,this.macroEngine.setAudioCallback(t=>{e.play(t)})}getAudioProcessor(){return this.audioProcessor}applyAudioCommands(e){if(this.audioProcessor&&this.mode!=="server")for(let t of e){if("setEffects"in t&&t.setEffects===!0){let n=t;this.audioProcessor.setEffects(n.instanceId,n.lowpass,n.highpass,n.reverb);continue}if("fadeOut"in t&&t.fadeOut===!0){let n=t;this.audioProcessor.fadeOut(n.sound,n.duration);continue}if("pause"in t&&t.pause===!0){let n=t;this.audioProcessor.pause(n.sound);continue}if("resume"in t&&t.resume===!0){let n=t;this.audioProcessor.resume(n.sound);continue}if("instanceId"in t||"volume"in t||"pitch"in t||"loop"in t||"fadeIn"in t||"x"in t||"y"in t||"lowpass"in t||"highpass"in t||"reverb"in t){let n=t,o=n.x!==void 0&&n.y!==void 0?{x:n.x,y:n.y}:void 0;this.audioProcessor.play(n.sound,{volume:n.volume,pitch:n.pitch,loop:n.loop,fadeIn:n.fadeIn,position:o,instanceId:n.instanceId,lowpass:n.lowpass,highpass:n.highpass,reverb:n.reverb})}else{let n=t;n.sound==="all"?this.audioProcessor.stopAll():this.audioProcessor.stop(n.sound)}}}applyAudioConfigCommands(e){if(this.audioProcessor&&this.mode!=="server")for(let t of e)t.type==="set-listener-position"?this.audioProcessor.setListenerPosition(t.x,t.y):t.type==="configure-spatial"&&this.audioProcessor.configureSpatial({maxDistance:t.maxDistance,referenceDistance:t.referenceDistance,rolloffFactor:t.rolloffFactor,panSpread:t.panSpread})}vibrate(e){let t={pattern:e};this.mobileVibrationCommands.push(t)}cancelVibration(){let e={cancel:!0};this.mobileVibrationCommands.push(e)}vibrateTap(){this.vibrate(10)}vibrateMediumTap(){this.vibrate(25)}vibrateHeavyTap(){this.vibrate(50)}vibrateSuccess(){this.vibrate([30,50,30])}vibrateError(){this.vibrate([50,30,50,30,50])}vibrateWarning(){this.vibrate([100])}vibrateSelection(){this.vibrate(5)}vibrateImpact(e="medium"){let t={light:15,medium:30,heavy:50};this.vibrate(t[e])}vibrateNotification(){this.vibrate([100,100,100,100,100])}vibrateGamepad(e,t){let r={gamepadIndex:e,options:t};this.gamepadVibrationCommands.push(r)}stopGamepadVibration(e="all"){let t={gamepadIndex:e,cancel:!0};this.gamepadVibrationCommands.push(t)}gamepadTap(e=0){this.vibrateGamepad(e,{duration:50,strongMagnitude:.3,weakMagnitude:.5})}gamepadImpact(e=0){this.vibrateGamepad(e,{duration:100,strongMagnitude:.7,weakMagnitude:.3})}gamepadHeavy(e=0){this.vibrateGamepad(e,{duration:200,strongMagnitude:1,weakMagnitude:.2})}gamepadExplosion(e=0){this.vibrateGamepad(e,{duration:400,strongMagnitude:1,weakMagnitude:.8})}gamepadSuccess(e=0){this.vibrateGamepad(e,{duration:150,strongMagnitude:.4,weakMagnitude:.6})}gamepadError(e=0){this.vibrateGamepad(e,{duration:300,strongMagnitude:.8,weakMagnitude:.4})}hasGamepadVibrationCommands(){return this.gamepadVibrationCommands.length>0}flushGamepadVibrationCommands(){let e=this.gamepadVibrationCommands;return this.gamepadVibrationCommands=[],e}setGamepadVibrationProcessor(e){this.gamepadVibrationProcessor=e}applyGamepadVibrationCommands(e){if(this.gamepadVibrationProcessor&&this.mode!=="server"){for(let t of e)if("cancel"in t&&t.cancel===!0)t.gamepadIndex==="all"?this.gamepadVibrationProcessor.stopAllVibrations():this.gamepadVibrationProcessor.stopVibration(t.gamepadIndex);else if("options"in t){let r=t;if(r.gamepadIndex==="all")for(let n=0;n<4;n++)this.gamepadVibrationProcessor.vibrate(n,r.options);else this.gamepadVibrationProcessor.vibrate(r.gamepadIndex,r.options)}}}hasMobileVibrationCommands(){return this.mobileVibrationCommands.length>0}flushMobileVibrationCommands(){let e=this.mobileVibrationCommands;return this.mobileVibrationCommands=[],e}setMobileVibrationProcessor(e){this.mobileVibrationProcessor=e}getMobileVibrationProcessor(){return this.mobileVibrationProcessor}applyMobileVibrationCommands(e){if(this.mobileVibrationProcessor&&this.mode!=="server")for(let t of e)"cancel"in t&&t.cancel===!0?this.mobileVibrationProcessor.cancel():"pattern"in t&&this.mobileVibrationProcessor.vibrate(t.pattern)}applyVibrationOrders(e){if(this.mode==="server")return;let{VibrationOrderType:t}=(Sr(),K(An)),{MobileVibrateFlags:r,GamepadVibrateFlags:n}=(Ir(),K(En));for(let o of e)switch(o.type){case t.MobileVibrate:{if(!this.mobileVibrationProcessor)break;let i=o,s=i.pattern;i.flags&r.HasIntensity&&i.intensity!==void 0&&(s=s.map(a=>Math.round(a*i.intensity))),this.mobileVibrationProcessor.vibrate(s);break}case t.MobileCancel:{if(!this.mobileVibrationProcessor)break;this.mobileVibrationProcessor.cancel();break}case t.GamepadVibrate:{if(!this.gamepadVibrationProcessor)break;let i=o,s={duration:i.duration,strongMagnitude:i.strongMagnitude/255,weakMagnitude:i.weakMagnitude/255,startDelay:i.startDelay};if(i.flags&n.AllGamepads)for(let a=0;a<4;a++)this.gamepadVibrationProcessor.vibrate(a,s);else this.gamepadVibrationProcessor.vibrate(i.gamepadIndex,s);break}case t.GamepadCancel:{if(!this.gamepadVibrationProcessor)break;let i=o;i.flags&n.AllGamepads?this.gamepadVibrationProcessor.stopAllVibrations():this.gamepadVibrationProcessor.stopVibration(i.gamepadIndex);break}}}applyAudioOrders(e){if(!this.audioProcessor||this.mode==="server")return;let{AudioOrderType:t,AudioTargetType:r}=(Ur(),K(Pn)),{PlaySoundFlags:n}=(vr(),K(Rn));for(let o of e)switch(o.type){case t.PlaySound:case t.PlayGlobalSound:{let i=o,s=i.volume!==void 0?i.volume/255:void 0,a=i.pitch!==void 0?.25*Math.pow(2,i.pitch/64):void 0,d=i.fadeIn!==void 0?i.fadeIn/10:void 0,l=(i.flags&n.Loop)!==0,c=i.posX!==void 0&&i.posY!==void 0?{x:i.posX,y:i.posY}:void 0;this.audioProcessor.play(i.soundId,{volume:s,pitch:a,loop:l,fadeIn:d,position:c,instanceId:i.instanceId,lowpass:i.lowpass,highpass:i.highpass,reverb:i.reverb});break}case t.StopSound:{let i=o;i.targetType===r.All?this.audioProcessor.stopAll():i.targetType===r.InstanceId?this.audioProcessor.stop(i.target):this.audioProcessor.stop(i.target);break}case t.FadeOutSound:{let i=o,s=i.duration/10;i.targetType===r.All?this.audioProcessor.fadeOut("all",s):this.audioProcessor.fadeOut(i.target,s);break}case t.PauseSound:{let i=o;i.targetType===r.All?this.audioProcessor.pause("all"):this.audioProcessor.pause(i.target);break}case t.ResumeSound:{let i=o;i.targetType===r.All?this.audioProcessor.resume("all"):this.audioProcessor.resume(i.target);break}case t.SetListenerPosition:{let i=o;this.audioProcessor.setListenerPosition(i.x,i.y);break}case t.ConfigureSpatial:{let i=o;this.audioProcessor.configureSpatial({maxDistance:i.maxDistance*100,referenceDistance:i.referenceDistance*100,rolloffFactor:i.rolloffFactor/100,panSpread:i.panSpread/255});break}case t.SetSoundEffects:{let i=o;this.audioProcessor.setEffects(i.instanceId,i.lowpass,i.highpass,i.reverb);break}}}handleAudioAck(e){switch(e.type){case"sound-loaded":this.loadedSounds.set(e.soundId,{name:e.name,loadedAt:Date.now()}),this.soundLoadErrors.delete(e.soundId);break;case"sound-error":this.soundLoadErrors.set(e.soundId,{name:e.name,error:e.error,at:Date.now()});break;case"playback-started":this.playingSounds.set(e.instanceId,{soundId:e.soundId,startedAt:Date.now()});break;case"playback-ended":this.playingSounds.delete(e.instanceId);break;case"playback-error":e.instanceId!==void 0&&this.playingSounds.delete(e.instanceId);break}}isSoundLoaded(e){return this.loadedSounds.has(e)}getSoundLoadError(e){return this.soundLoadErrors.get(e)?.error}getLoadedSounds(){return this.loadedSounds}getSoundLoadErrors(){return this.soundLoadErrors}isSoundPlaying(e){return this.playingSounds.has(e)}getPlayingSounds(){return this.playingSounds}getPlayingSoundCount(){return this.playingSounds.size}getAudioLoadingState(e){let t=this.loadedSounds.size,r=this.soundLoadErrors.size,n=e>0&&t>=e,o=Array.from(this.soundLoadErrors.values()).map(i=>i.name);return{loadedCount:t,totalExpected:e,errorCount:r,isComplete:n,errors:o}}loadMacro(e,t){let r={...t,id:e},n=this.macroRegistry.registerMacro(r);return this.mode==="client"&&this.macroEngine.loadTemplate(n,r),n}createInstance(e){return this.updateLayerMappings(),this.macroRegistry.createInstance(e)}updateInstance(e,t){return this.macroRegistry.updateInstance(e,t)}removeInstance(e){return this.macroEventHandlers.delete(e),this.macroRegistry.removeInstance(e)}onMacroEvent(e,t,r){this.macroEventHandlers.has(e)||this.macroEventHandlers.set(e,new Map),this.macroEventHandlers.get(e).set(t,r)}offMacroEvent(e,t){t?this.macroEventHandlers.get(e)?.delete(t):this.macroEventHandlers.delete(e)}handleMacroEvent(e){let t=this.macroRegistry.getInstanceName(e.instanceId);if(!t){console.warn(`MacroEvent: Unknown instance ID ${e.instanceId}`);return}let r=this.macroEventHandlers.get(t);if(!r)return;let n,o;switch(e.type){case 1:n="click",o=void 0;break;case 2:n="change",o=e.value;break;case 3:n="submit",o=e.text;break;case 4:n="select",o=e.index;break;default:return}let i=r.get(n);i&&i(o)}flushMacroOrders(){return this.macroRegistry.flushPendingOrders()}hasPendingMacroOrders(){return this.macroRegistry.hasPendingOrders()}applyMacroOrders(e){for(let t of e)this.macroEngine.applyOrder(t)}getMacroRegistry(){return this.macroRegistry}getMacroLoads(){return this.macroRegistry.toAllMacroLoads()}updateLayerMappings(){for(let e of this.layers){let t=e.getName();t&&this.macroRegistry.setLayerMapping(t,e.getId())}}registerLayerName(e,t){this.macroRegistry.setLayerMapping(e,t.getId())}loadMacroTemplate(e,t){this.macroEngine.loadTemplate(e,t)}updateMacros(){return this.macroEngine.update()}processMacroEvents(e){for(let t of e.events){let r=this.macroRegistry.getInstanceName(t.instanceId);if(!r)continue;let n=this.macroEventHandlers.get(r);if(!n)continue;let o=n.get(t.event);o&&o(t.data)}}updateMacroMouse(e,t,r){let n=this.displays.find(o=>o.getId()===this.mouseDisplayId);if(!n&&this.displays.length>0&&(n=this.displays[0]),n){let o=n.getOrigin(),i=e+o.x,s=t+o.y;this.macroEngine.updateMouse(i,s,r)}else this.macroEngine.updateMouse(e,t,r)}getMacroRenderOrders(){let e=this.macroEngine.getOrdersByLayer(),t=this.displays[0];if(!t)return e;let r=t.getOrigin();if(r.x===0&&r.y===0)return e;let n=new Map;for(let[o,i]of e){let s=i.map(a=>{let d={...a};return"posX"in d&&typeof d.posX=="number"&&(d.posX=d.posX-r.x),"posY"in d&&typeof d.posY=="number"&&(d.posY=d.posY-r.y),d});n.set(o,s)}return n}getMacroEffectOffset(){return this.macroEngine.getEffectOffset()}getMacroEngine(){return this.macroEngine}macroFocusNext(){this.macroEngine.focusNext()}macroFocusPrevious(){this.macroEngine.focusPrevious()}macroActivateFocused(){this.macroEngine.activateFocused()}setPostProcess(e,t){let r=JSON.stringify(t),n=JSON.stringify(this.currentPostProcessConfig);r!==n&&(this.currentPostProcessConfig=t,this.postProcessCommands.push({type:"set-config",displayId:e,config:t??void 0}))}setScanlinesEnabled(e,t){if(t){let r=this.currentPostProcessConfig?.scanlines;this.setPostProcess(e,{scanlines:{enabled:!0,opacity:r?.opacity??T.POST_PROCESS_DEFAULTS.scanlines.opacity,pattern:r?.pattern??T.POST_PROCESS_DEFAULTS.scanlines.pattern,color:r?.color??T.POST_PROCESS_DEFAULTS.scanlines.color}})}else this.setPostProcess(e,{scanlines:{enabled:!1}})}setScanlinesOpacity(e,t){let r=Math.max(0,Math.min(1,t)),n=this.currentPostProcessConfig?.scanlines;this.setPostProcess(e,{scanlines:{enabled:!0,opacity:r,pattern:n?.pattern??"horizontal",color:n?.color??{r:0,g:0,b:0}}})}setScanlinesPattern(e,t){let r=this.currentPostProcessConfig?.scanlines;this.setPostProcess(e,{scanlines:{enabled:r?.enabled??!0,opacity:r?.opacity??T.POST_PROCESS_DEFAULTS.scanlines.opacity,pattern:t,color:r?.color??{r:0,g:0,b:0}}})}setAmbientEffect(e,t){let r=this.currentPostProcessConfig?.ambientEffect;typeof t=="boolean"?this.setPostProcess(e,{...this.currentPostProcessConfig,ambientEffect:{enabled:t,blur:r?.blur??T.POST_PROCESS_DEFAULTS.ambientEffect.blur,scale:r?.scale??T.POST_PROCESS_DEFAULTS.ambientEffect.scale}}):this.setPostProcess(e,{...this.currentPostProcessConfig,ambientEffect:{enabled:!0,blur:t.blur??r?.blur??T.POST_PROCESS_DEFAULTS.ambientEffect.blur,scale:t.scale??r?.scale??T.POST_PROCESS_DEFAULTS.ambientEffect.scale}})}setAmbientEffectEnabled(e,t){this.setAmbientEffect(e,t)}setAmbientEffectBlur(e,t){let r=this.currentPostProcessConfig?.ambientEffect;this.setPostProcess(e,{...this.currentPostProcessConfig,ambientEffect:{enabled:r?.enabled??!0,blur:Math.max(0,t),scale:r?.scale??T.POST_PROCESS_DEFAULTS.ambientEffect.scale}})}setAmbientEffectScale(e,t){let r=this.currentPostProcessConfig?.ambientEffect;this.setPostProcess(e,{...this.currentPostProcessConfig,ambientEffect:{enabled:r?.enabled??!0,blur:r?.blur??T.POST_PROCESS_DEFAULTS.ambientEffect.blur,scale:Math.max(1,t)}})}isAmbientEffectEnabled(){return this.currentPostProcessConfig?.ambientEffect?.enabled??!1}getAmbientEffectConfig(){let e=this.currentPostProcessConfig?.ambientEffect;return e?{enabled:e.enabled,blur:e.blur??T.POST_PROCESS_DEFAULTS.ambientEffect.blur,scale:e.scale??T.POST_PROCESS_DEFAULTS.ambientEffect.scale}:null}getPostProcessConfig(){return this.currentPostProcessConfig}hasPostProcessCommands(){return this.postProcessCommands.length>0}flushPostProcessCommands(){let e=this.postProcessCommands;return this.postProcessCommands=[],e}setScalingMode(e,t){this.currentScalingModes.get(e)!==t&&(this.currentScalingModes.set(e,t),this.postProcessCommands.push({type:"set-scaling-mode",displayId:e,scalingMode:t}))}getScalingMode(e){return this.currentScalingModes.get(e)??null}setCellSize(e,t,r){let n=Math.max(1,Math.min(255,Math.round(t))),o=Math.max(1,Math.min(255,Math.round(r))),i=this.currentCellSizes.get(e);i&&i.width===n&&i.height===o||(this.currentCellSizes.set(e,{width:n,height:o}),this.postProcessCommands.push({type:"set-cell-size",displayId:e,cellWidth:n,cellHeight:o}))}getCellSize(e){let t=this.currentCellSizes.get(e);return{cellWidth:t?.width??8,cellHeight:t?.height??8}}setGrid(e,t){let r;typeof t=="boolean"?r={enabled:t,color:T.GRID_DEFAULTS.color,lineWidth:T.GRID_DEFAULTS.lineWidth}:r={enabled:t.enabled,color:t.color??T.GRID_DEFAULTS.color,lineWidth:t.lineWidth??T.GRID_DEFAULTS.lineWidth},this.currentGridConfigs.set(e,r),this.postProcessCommands.push({type:"set-grid",displayId:e,gridConfig:r})}setGridEnabled(e,t){this.setGrid(e,t)}isGridEnabled(e){return this.currentGridConfigs.get(e)?.enabled??!1}getGridConfig(e){return this.currentGridConfigs.get(e)??null}switchPalette(e,t){if(t<0||t>255)throw new Error(`Palette slot ID must be between 0 and 255, got ${t}`);this.currentPaletteSlotIds.get(e)!==t&&(this.currentPaletteSlotIds.set(e,t),this.postProcessCommands.push({type:"switch-palette",displayId:e,paletteSlotId:t}))}getCurrentPaletteSlotId(e){return this.currentPaletteSlotIds.get(e)??null}sendBridge(e,t){this.bridgeMessages.push({channel:e,data:t})}getBridgeMessages(){let e=this.bridgeMessages;return this.bridgeMessages=[],e}hasBridgeMessages(){return this.bridgeMessages.length>0}getDebugInfo(){let e=Array.from(this.availableViewports.entries()).map(([t,r])=>({displayId:t,pixelWidth:r.pixelWidth,pixelHeight:r.pixelHeight}));return{id:this.id,name:this.name,bytesSentTotal:this.totalBytesSent,bytesSentTick:this.currentTickBytesSent,availableViewports:e,layers:this.layers.map(t=>t.getDebugInfo()),displays:this.displays.map(t=>t.getDebugInfo())}}};b(Mr,"User");var ae=Mr;$();$();V();var Ar=class Ar{constructor(){h(this,"charCodeSize",we)}encode(e,t=!1){switch(e.type){case 1:return this.encodeCharOrder(e,t);case 2:return this.encodeTextOrder(e);case 23:return this.encodeTextMultilineOrder(e);case 3:return this.encodeSubFrameOrder(e,t);case 4:return this.encodeSubFrameMultiColorOrder(e,t);case 5:return this.encodeFullFrameOrder(e,t);case 6:return this.encodeFullFrameMultiColorOrder(e,t);case 7:return this.encodeSpriteOrder(e);case 8:return this.encodeSpriteMultiColorOrder(e);case 9:return this.encodeColorMapOrder(e);case 10:return this.encodeShapeOrder(e,t);case 11:return this.encodeDotCloudOrder(e,t);case 12:return this.encodeDotCloudMultiColorOrder(e,t);case 17:return this.encodeBitmaskOrder(e,t);case 18:return this.encodeBitmask4Order(e,t);case 24:return this.encodeBitmask16Order(e,t);case 25:return this.encodePolylineOrder(e,t);case 13:return this.encodeSpriteCloudOrder(e);case 14:return this.encodeSpriteCloudMultiColorOrder(e);case 15:return this.encodeSpriteCloudVariedOrder(e);case 16:return this.encodeSpriteCloudVariedMultiColorOrder(e);case 19:return this.encodeFillOrder(e,t);case 20:return this.encodeFillCharOrder(e,t);case 21:return this.encodeFillSpriteOrder(e);case 22:return this.encodeFillSpriteMultiColorOrder(e);default:throw new Error(`Unknown order type: ${e.type}`)}}writeCharCode(e,t,r,n){return n?(e.writeUInt16LE(t,r),r+2):(e.writeUInt8(t,r),r+1)}encodeCharOrder(e,t){let r=C.allocUnsafe(Ot+(t?1:0)),n=0;return r.writeUInt8(e.type,n++),r.writeUInt8(e.posX,n++),r.writeUInt8(e.posY,n++),n=this.writeCharCode(r,e.charCode,n,t),r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++),r.toUint8Array()}encodeTextOrder(e){let t=new TextEncoder().encode(e.text),r=C.allocUnsafe(wt+t.length),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.posX,n++),r.writeUInt8(e.posY,n++),r.writeUInt8(t.length,n++);for(let o=0;o<t.length;o++)r.writeUInt8(t[o],n++);return r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++),r.toUint8Array()}encodeTextMultilineOrder(e){let t=new TextEncoder().encode(e.text),r=C.allocUnsafe(Ut+t.length),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.posX,n++),r.writeUInt8(e.posY,n++),r.writeUInt8(t.length,n++);for(let o=0;o<t.length;o++)r.writeUInt8(t[o],n++);return r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++),r.toUint8Array()}encodeSubFrameOrder(e,t){let r=e.sizeX*e.sizeY,n=this.charCodeSize(t),o=C.allocUnsafe(vt+r*n),i=0;o.writeUInt8(e.type,i++),o.writeUInt8(e.posX,i++),o.writeUInt8(e.posY,i++),o.writeUInt8(e.sizeX-1,i++),o.writeUInt8(e.sizeY-1,i++),o.writeUInt8(e.bgColorCode,i++),o.writeUInt8(e.fgColorCode,i++);for(let s of e.frame)i=this.writeCharCode(o,s,i,t);return o.toUint8Array()}encodeSubFrameMultiColorOrder(e,t){let r=e.sizeX*e.sizeY,n=this.charCodeSize(t),o=C.allocUnsafe(Mt+r*(n+2)),i=0;o.writeUInt8(e.type,i++),o.writeUInt8(e.posX,i++),o.writeUInt8(e.posY,i++),o.writeUInt8(e.sizeX-1,i++),o.writeUInt8(e.sizeY-1,i++);for(let s of e.frame)i=this.writeCharCode(o,s.charCode,i,t),o.writeUInt8(s.bgColorCode,i++),o.writeUInt8(s.fgColorCode,i++);return o.toUint8Array()}encodeFullFrameOrder(e,t){let r=e.frame.length,n=this.charCodeSize(t),o=C.allocUnsafe(At+r*n),i=0;o.writeUInt8(e.type,i++),o.writeUInt8(e.bgColorCode,i++),o.writeUInt8(e.fgColorCode,i++);for(let s of e.frame)i=this.writeCharCode(o,s,i,t);return o.toUint8Array()}encodeFullFrameMultiColorOrder(e,t){let r=e.frame.length,n=this.charCodeSize(t),o=C.allocUnsafe(Et+r*(n+2)),i=0;o.writeUInt8(e.type,i++);for(let s of e.frame)i=this.writeCharCode(o,s.charCode,i,t),o.writeUInt8(s.bgColorCode,i++),o.writeUInt8(s.fgColorCode,i++);return o.toUint8Array()}encodeSpriteOrder(e){let t=C.allocUnsafe(Pt),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.posX,r++),t.writeUInt8(e.posY,r++),t.writeUInt8(e.spriteIndex,r++),t.writeUInt8(e.bgColorCode,r++),t.writeUInt8(e.fgColorCode,r++),t.toUint8Array()}encodeSpriteMultiColorOrder(e){let t=C.allocUnsafe(kt),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.posX,r++),t.writeUInt8(e.posY,r++),t.writeUInt8(e.spriteIndex,r++),t.toUint8Array()}encodeColorMapOrder(e){let t=e.sizeX*e.sizeY,r=C.allocUnsafe(Rt+t*2),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.posX,n++),r.writeUInt8(e.posY,n++),r.writeUInt8(e.sizeX-1,n++),r.writeUInt8(e.sizeY-1,n++);for(let o of e.colorData)r.writeUInt8(o.bgColorCode,n++),r.writeUInt8(o.fgColorCode,n++);return r.toUint8Array()}encodeShapeOrder(e,t){let r=this.encodeShapeData(e.shapeType,e.shapeData,t),n=C.allocUnsafe(Bt+r.length),o=0;n.writeUInt8(e.type,o++),n.writeUInt8(e.shapeType,o++);for(let i=0;i<r.length;i++)n.writeUInt8(r[i],o++);return n.toUint8Array()}encodeShapeData(e,t,r){let n=this.charCodeSize(r);switch(e){case 1:{let o=C.allocUnsafe(zt+(r?1:0)),i=0;return o.writeUInt8(t.posX,i++),o.writeUInt8(t.posY,i++),o.writeUInt8(t.width-1,i++),o.writeUInt8(t.height-1,i++),o.writeUInt8(t.filled?1:0,i++),i=this.writeCharCode(o,t.charCode,i,r),o.writeUInt8(t.bgColorCode,i++),o.writeUInt8(t.fgColorCode,i++),o.toUint8Array()}case 2:{let o=C.allocUnsafe(Tt+(r?1:0)),i=0;return o.writeUInt8(t.centerX,i++),o.writeUInt8(t.centerY,i++),o.writeUInt8(t.radius-1,i++),o.writeUInt8(t.filled?1:0,i++),i=this.writeCharCode(o,t.charCode,i,r),o.writeUInt8(t.bgColorCode,i++),o.writeUInt8(t.fgColorCode,i++),o.toUint8Array()}case 3:{let o=C.allocUnsafe(Lt+(r?1:0)),i=0;return o.writeUInt8(t.x1,i++),o.writeUInt8(t.y1,i++),o.writeUInt8(t.x2,i++),o.writeUInt8(t.y2,i++),i=this.writeCharCode(o,t.charCode,i,r),o.writeUInt8(t.bgColorCode,i++),o.writeUInt8(t.fgColorCode,i++),o.toUint8Array()}case 4:{let o=C.allocUnsafe(Ft+(r?1:0)),i=0;return o.writeUInt8(t.centerX,i++),o.writeUInt8(t.centerY,i++),o.writeUInt8(t.radiusX-1,i++),o.writeUInt8(t.radiusY-1,i++),o.writeUInt8(t.filled?1:0,i++),i=this.writeCharCode(o,t.charCode,i,r),o.writeUInt8(t.bgColorCode,i++),o.writeUInt8(t.fgColorCode,i++),o.toUint8Array()}case 5:{let o=C.allocUnsafe(Dt+(r?1:0)),i=0;return o.writeUInt8(t.x1,i++),o.writeUInt8(t.y1,i++),o.writeUInt8(t.x2,i++),o.writeUInt8(t.y2,i++),o.writeUInt8(t.x3,i++),o.writeUInt8(t.y3,i++),o.writeUInt8(t.filled?1:0,i++),i=this.writeCharCode(o,t.charCode,i,r),o.writeUInt8(t.bgColorCode,i++),o.writeUInt8(t.fgColorCode,i++),o.toUint8Array()}default:throw new Error(`Unknown shape type: ${e}`)}}encodeDotCloudOrder(e,t){let r=e.positions.length,n=this.charCodeSize(t),o=C.allocUnsafe(Vt+(t?1:0)+r*2),i=0;o.writeUInt8(e.type,i++),i=this.writeCharCode(o,e.charCode,i,t),o.writeUInt8(e.bgColorCode,i++),o.writeUInt8(e.fgColorCode,i++),o.writeUInt16BE(r,i),i+=2;for(let s of e.positions)o.writeUInt8(s.posX,i++),o.writeUInt8(s.posY,i++);return o.toUint8Array()}encodeDotCloudMultiColorOrder(e,t){let r=e.dots.length,n=this.charCodeSize(t),o=C.allocUnsafe(_t+r*(n+4)),i=0;o.writeUInt8(e.type,i++),o.writeUInt16BE(r,i),i+=2;for(let s of e.dots)i=this.writeCharCode(o,s.charCode,i,t),o.writeUInt8(s.bgColorCode,i++),o.writeUInt8(s.fgColorCode,i++),o.writeUInt8(s.posX,i++),o.writeUInt8(s.posY,i++);return o.toUint8Array()}encodeBitmaskOrder(e,t){let r=e.mask.length,n=C.allocUnsafe(Nt+(t?1:0)+r),o=0;n.writeUInt8(e.type,o++),n.writeUInt8(e.posX,o++),n.writeUInt8(e.posY,o++),n.writeUInt8(e.sizeX-1,o++),n.writeUInt8(e.sizeY-1,o++),o=this.writeCharCode(n,e.charCode,o,t),n.writeUInt8(e.bgColorCode,o++),n.writeUInt8(e.fgColorCode,o++),n.writeUInt8(e.override?1:0,o++);for(let i=0;i<r;i++)n.writeUInt8(e.mask[i],o++);return n.toUint8Array()}encodeBitmask4Order(e,t){let r=e.mask.length,n=this.charCodeSize(t),o=C.allocUnsafe(Yt+3*(t?1:0)+r),i=0;o.writeUInt8(e.type,i++),o.writeUInt8(e.posX,i++),o.writeUInt8(e.posY,i++),o.writeUInt8(e.sizeX-1,i++),o.writeUInt8(e.sizeY-1,i++),o.writeUInt8(e.override?1:0,i++);for(let s of e.variants)i=this.writeCharCode(o,s.charCode,i,t),o.writeUInt8(s.bgColorCode,i++),o.writeUInt8(s.fgColorCode,i++);for(let s=0;s<r;s++)o.writeUInt8(e.mask[s],i++);return o.toUint8Array()}encodeBitmask16Order(e,t){let r=e.mask.length,n=this.charCodeSize(t),o=C.allocUnsafe(Ht+15*(t?1:0)+r),i=0;o.writeUInt8(e.type,i++),o.writeUInt8(e.posX,i++),o.writeUInt8(e.posY,i++),o.writeUInt8(e.sizeX-1,i++),o.writeUInt8(e.sizeY-1,i++),o.writeUInt8(e.override?1:0,i++);for(let s of e.variants)i=this.writeCharCode(o,s.charCode,i,t),o.writeUInt8(s.bgColorCode,i++),o.writeUInt8(s.fgColorCode,i++);for(let s=0;s<r;s++)o.writeUInt8(e.mask[s],i++);return o.toUint8Array()}encodePolylineOrder(e,t){let r=e.points.length,n=C.allocUnsafe(Xt+(t?1:0)+r*2),o=0;n.writeUInt8(e.type,o++),o=this.writeCharCode(n,e.charCode,o,t),n.writeUInt8(e.fgColorCode,o++),n.writeUInt8(e.bgColorCode,o++),n.writeUInt8(r,o++);for(let i of e.points)n.writeUInt8(i.x,o++),n.writeUInt8(i.y,o++);return n.toUint8Array()}encodeSpriteCloudOrder(e){let t=e.positions.length,r=C.allocUnsafe(Gt+t*2),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.spriteIndex,n++),r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++),r.writeUInt16BE(t,n),n+=2;for(let o of e.positions)r.writeUInt8(o.posX,n++),r.writeUInt8(o.posY,n++);return r.toUint8Array()}encodeSpriteCloudMultiColorOrder(e){let t=e.positions.length,r=C.allocUnsafe($t+t*2),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.spriteIndex,n++),r.writeUInt16BE(t,n),n+=2;for(let o of e.positions)r.writeUInt8(o.posX,n++),r.writeUInt8(o.posY,n++);return r.toUint8Array()}encodeSpriteCloudVariedOrder(e){let t=e.sprites.length,r=C.allocUnsafe(Zt+t*5),n=0;r.writeUInt8(e.type,n++),r.writeUInt16BE(t,n),n+=2;for(let o of e.sprites)r.writeUInt8(o.spriteIndex,n++),r.writeUInt8(o.bgColorCode,n++),r.writeUInt8(o.fgColorCode,n++),r.writeUInt8(o.posX,n++),r.writeUInt8(o.posY,n++);return r.toUint8Array()}encodeSpriteCloudVariedMultiColorOrder(e){let t=e.sprites.length,r=C.allocUnsafe(Wt+t*3),n=0;r.writeUInt8(e.type,n++),r.writeUInt16BE(t,n),n+=2;for(let o of e.sprites)r.writeUInt8(o.spriteIndex,n++),r.writeUInt8(o.posX,n++),r.writeUInt8(o.posY,n++);return r.toUint8Array()}encodeFillOrder(e,t){let r=C.allocUnsafe(jt+(t?1:0)),n=0;return r.writeUInt8(e.type,n++),n=this.writeCharCode(r,e.charCode,n,t),r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++),r.toUint8Array()}encodeFillCharOrder(e,t){let r=e.patternWidth*e.patternHeight,n=this.charCodeSize(t),o=C.allocUnsafe(Jt+r*n),i=0;o.writeUInt8(e.type,i++),o.writeUInt8(e.patternWidth-1,i++),o.writeUInt8(e.patternHeight-1,i++),o.writeUInt8(e.bgColorCode,i++),o.writeUInt8(e.fgColorCode,i++);for(let s of e.pattern)i=this.writeCharCode(o,s,i,t);return o.toUint8Array()}encodeFillSpriteOrder(e){let t=C.allocUnsafe(qt),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.spriteIndex,r++),t.writeUInt8(e.bgColorCode,r++),t.writeUInt8(e.fgColorCode,r++),t.toUint8Array()}encodeFillSpriteMultiColorOrder(e){let t=C.allocUnsafe(Kt),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.spriteIndex,r++),t.toUint8Array()}};b(Ar,"OrderEncoder");var rt=Ar;V();var Bn=255,zn=32,Tn=64,Er=class Er{constructor(){h(this,"orderEncoder");this.orderEncoder=new rt}encode(e){let t=e.is16bit;if(e.orders.length>Bn)throw new Error(`[UTSP] LayerEncoder: Layer ${e.id} has ${e.orders.length} orders, max is ${Bn}. This would cause packet corruption! Split into multiple layers.`);let r=e.orders.map(l=>this.orderEncoder.encode(l,t)),n=13,o=r.reduce((l,c)=>l+c.length,0),i=n+o,s=C.allocUnsafe(i),a=0;s.writeUInt16BE(e.id,a),a+=2;let d=e.updateFlags;e.isMacroLayer?d|=zn:d&=~zn,t?d|=Tn:d&=~Tn,s.writeUInt8(d,a++),s.writeUInt8(e.zIndex,a++),s.writeUInt16BE(e.originX,a),a+=2,s.writeUInt16BE(e.originY,a),a+=2,s.writeUInt16BE(e.width,a),a+=2,s.writeUInt16BE(e.height,a),a+=2,s.writeUInt8(e.orders.length,a++);for(let l of r)C.from(l).copy(s,a),a+=l.length;return s.toUint8Array()}calculateSize(e){let r=e.is16bit;return 13+e.orders.reduce((o,i)=>o+this.orderEncoder.encode(i,r).length,0)}};b(Er,"LayerEncoder");var nt=Er;V();$();var Pr=class Pr{encode(e){switch(e.type){case 1:return this.encodePlaySoundOrder(e);case 2:return this.encodePlayGlobalSoundOrder(e);case 3:return this.encodeStopSoundOrder(e);case 4:return this.encodeFadeOutSoundOrder(e);case 5:return this.encodePauseSoundOrder(e);case 6:return this.encodeResumeSoundOrder(e);case 7:return this.encodeSetListenerPositionOrder(e);case 8:return this.encodeConfigureSpatialOrder(e);case 9:return this.encodeSetSoundEffectsOrder(e);default:throw new Error(`Unknown audio order type: ${e.type}`)}}calculateSize(e){switch(e.type){case 1:return this.calculatePlaySoundSize(e);case 2:return this.calculatePlayGlobalSoundSize(e);case 3:case 5:case 6:return this.calculateTargetOrderSize(e);case 4:return this.calculateFadeOutSize(e);case 7:return ke;case 8:return Re;case 9:return this.calculateSetSoundEffectsSize(e);default:throw new Error(`Unknown audio order type: ${e.type}`)}}encodePlaySoundOrder(e){let t=this.calculatePlaySoundSize(e),r=C.allocUnsafe(t),n=0;return r.writeUInt8(e.type,n++),r.writeUInt8(e.soundId,n++),r.writeUInt16BE(e.instanceId,n),n+=2,r.writeUInt8(e.flags,n++),e.flags&2&&r.writeUInt8(e.volume??255,n++),e.flags&4&&r.writeUInt8(e.pitch??128,n++),e.flags&8&&r.writeUInt8(e.fadeIn??0,n++),e.flags&16&&(r.writeUInt16BE(e.posX??0,n),n+=2,r.writeUInt16BE(e.posY??0,n),n+=2),e.flags&32&&r.writeUInt8(e.lowpass??0,n++),e.flags&64&&r.writeUInt8(e.highpass??0,n++),e.flags&128&&r.writeUInt8(e.reverb??0,n++),r.toUint8Array()}encodePlayGlobalSoundOrder(e){let t=this.calculatePlayGlobalSoundSize(e),r=C.allocUnsafe(t),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.soundId,n++),r.writeUInt16BE(e.instanceId,n),n+=2;let o=e.flags&-17;return r.writeUInt8(o,n++),o&2&&r.writeUInt8(e.volume??255,n++),o&4&&r.writeUInt8(e.pitch??128,n++),o&8&&r.writeUInt8(e.fadeIn??0,n++),o&32&&r.writeUInt8(e.lowpass??0,n++),o&64&&r.writeUInt8(e.highpass??0,n++),o&128&&r.writeUInt8(e.reverb??0,n++),r.toUint8Array()}calculatePlaySoundSize(e){let t=Qt;return e.flags&2&&(t+=1),e.flags&4&&(t+=1),e.flags&8&&(t+=1),e.flags&16&&(t+=4),e.flags&32&&(t+=1),e.flags&64&&(t+=1),e.flags&128&&(t+=1),t}calculatePlayGlobalSoundSize(e){let t=er,r=e.flags&-17;return r&2&&(t+=1),r&4&&(t+=1),r&8&&(t+=1),r&32&&(t+=1),r&64&&(t+=1),r&128&&(t+=1),t}encodeStopSoundOrder(e){return this.encodeTargetOrder(e.type,e.targetType,e.target)}encodePauseSoundOrder(e){return this.encodeTargetOrder(e.type,e.targetType,e.target)}encodeResumeSoundOrder(e){return this.encodeTargetOrder(e.type,e.targetType,e.target)}encodeFadeOutSoundOrder(e){let t=this.calculateFadeOutSize(e),r=C.allocUnsafe(t),n=0;return r.writeUInt8(e.type,n++),r.writeUInt8(e.targetType,n++),r.writeUInt8(e.duration,n++),e.targetType===0?r.writeUInt16BE(e.target??0,n):e.targetType===1&&r.writeUInt8(e.target??0,n),r.toUint8Array()}encodeTargetOrder(e,t,r){let n=2;t===0?n+=2:t===1&&(n+=1);let o=C.allocUnsafe(n),i=0;return o.writeUInt8(e,i++),o.writeUInt8(t,i++),t===0?o.writeUInt16BE(r??0,i):t===1&&o.writeUInt8(r??0,i),o.toUint8Array()}calculateTargetOrderSize(e){let t=2;return e.targetType===0?t+=2:e.targetType===1&&(t+=1),t}calculateFadeOutSize(e){let t=3;return e.targetType===0?t+=2:e.targetType===1&&(t+=1),t}encodeSetListenerPositionOrder(e){let t=C.allocUnsafe(ke),r=0;return t.writeUInt8(e.type,r++),t.writeUInt16BE(e.x,r),r+=2,t.writeUInt16BE(e.y,r),t.toUint8Array()}encodeConfigureSpatialOrder(e){let t=C.allocUnsafe(Re),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.maxDistance,r++),t.writeUInt8(e.referenceDistance,r++),t.writeUInt8(e.rolloffFactor,r++),t.writeUInt8(e.panSpread,r++),t.toUint8Array()}encodeSetSoundEffectsOrder(e){let t=this.calculateSetSoundEffectsSize(e),r=C.allocUnsafe(t),n=0;return r.writeUInt8(e.type,n++),r.writeUInt16BE(e.instanceId,n),n+=2,r.writeUInt8(e.flags,n++),e.flags&1&&r.writeUInt8(e.lowpass??0,n++),e.flags&2&&r.writeUInt8(e.highpass??0,n++),e.flags&4&&r.writeUInt8(e.reverb??0,n++),r.toUint8Array()}calculateSetSoundEffectsSize(e){let t=4;return e.flags&1&&(t+=1),e.flags&2&&(t+=1),e.flags&4&&(t+=1),t}};b(Pr,"AudioOrderEncoder");var ot=Pr;V();var kr=class kr{encode(e){switch(e.type){case 1:return this.encodeMobileVibrateOrder(e);case 2:return this.encodeMobileCancelOrder(e);case 16:return this.encodeGamepadVibrateOrder(e);case 17:return this.encodeGamepadCancelOrder(e);default:throw new Error(`Unknown vibration order type: ${e.type}`)}}calculateSize(e){switch(e.type){case 1:return this.calculateMobileVibrateSize(e);case 2:return 1;case 16:return this.calculateGamepadVibrateSize(e);case 17:return 3;default:throw new Error(`Unknown vibration order type: ${e.type}`)}}calculateMobileVibrateSize(e){let t=3+e.pattern.length*2;return e.intensity!==void 0&&(t+=1),t}encodeMobileVibrateOrder(e){let t=this.calculateMobileVibrateSize(e),r=C.allocUnsafe(t),n=0,o=0;e.intensity!==void 0&&(o|=1),r.writeUInt8(e.type,n++),r.writeUInt8(o,n++),r.writeUInt8(e.pattern.length,n++);for(let i of e.pattern){let s=Math.min(65535,Math.max(0,Math.round(i)));r.writeUInt16BE(s,n),n+=2}if(e.intensity!==void 0){let i=Math.round(Math.min(1,Math.max(0,e.intensity))*255);r.writeUInt8(i,n++)}return r.toUint8Array()}encodeMobileCancelOrder(e){let t=C.allocUnsafe(1);return t.writeUInt8(2,0),t.toUint8Array()}calculateGamepadVibrateSize(e){let t=7;return e.startDelay!==void 0&&e.startDelay>0&&(t+=2),t}encodeGamepadVibrateOrder(e){let t=this.calculateGamepadVibrateSize(e),r=C.allocUnsafe(t),n=0,o=0;e.startDelay!==void 0&&e.startDelay>0&&(o|=1),e.gamepadIndex===255&&(o|=2),r.writeUInt8(e.type,n++),r.writeUInt8(o,n++),r.writeUInt8(e.gamepadIndex,n++);let i=Math.min(65535,Math.max(0,Math.round(e.duration)));if(r.writeUInt16BE(i,n),n+=2,r.writeUInt8(e.strongMagnitude,n++),r.writeUInt8(e.weakMagnitude,n++),e.startDelay!==void 0&&e.startDelay>0){let s=Math.min(65535,Math.max(0,Math.round(e.startDelay)));r.writeUInt16BE(s,n),n+=2}return r.toUint8Array()}encodeGamepadCancelOrder(e){let t=C.allocUnsafe(3),r=0,n=0;return e.gamepadIndex===255&&(n|=2),t.writeUInt8(e.type,r++),t.writeUInt8(n,r++),t.writeUInt8(e.gamepadIndex,r++),t.toUint8Array()}};b(kr,"VibrationOrderEncoder");var de=kr;V();var Rr=class Rr{encode(e){switch(e.type){case 1:return this.encodeCreateInstance(e);case 2:return this.encodeUpdateInstance(e);case 3:return this.encodeRemoveInstance(e);default:throw new Error(`Unknown macro order type: ${e.type}`)}}calculateSize(e){switch(e.type){case 1:return this.calculateCreateInstanceSize(e);case 2:return this.calculateUpdateInstanceSize(e);case 3:return 2;default:throw new Error(`Unknown macro order type: ${e.type}`)}}encodeCreateInstance(e){let t=JSON.stringify(e.params),r=new TextEncoder().encode(t);if(r.length>65535)throw new Error(`Params JSON too large: ${r.length} bytes (max 65535)`);let n=11+r.length,o=C.allocUnsafe(n),i=0;return o.writeUInt8(e.type,i++),o.writeUInt8(e.instanceId,i++),o.writeUInt8(e.macroId,i++),o.writeUInt8(e.layerId,i++),o.writeInt16BE(e.x,i),i+=2,o.writeInt16BE(e.y,i),i+=2,o.writeUInt8(e.tabIndex,i++),o.writeUInt16BE(r.length,i),i+=2,o.toUint8Array().set(r,i),o.toUint8Array()}calculateCreateInstanceSize(e){let t=JSON.stringify(e.params);return 11+new TextEncoder().encode(t).length}encodeUpdateInstance(e){let t=JSON.stringify(e.params),r=new TextEncoder().encode(t);if(r.length>65535)throw new Error(`Params JSON too large: ${r.length} bytes (max 65535)`);let n=4+r.length,o=C.allocUnsafe(n),i=0;return o.writeUInt8(e.type,i++),o.writeUInt8(e.instanceId,i++),o.writeUInt16BE(r.length,i),i+=2,o.toUint8Array().set(r,i),o.toUint8Array()}calculateUpdateInstanceSize(e){let t=JSON.stringify(e.params);return 4+new TextEncoder().encode(t).length}encodeRemoveInstance(e){let t=C.allocUnsafe(2);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.toUint8Array()}};b(Rr,"MacroOrderEncoder");var it=Rr;V();$();var Tr=class Tr{encode(e){switch(e.type){case 1:return this.encodeSetConfigOrder(e);case 2:return this.encodeSetScanlinesOrder(e);case 3:return this.encodeSetAmbientEffectOrder(e);case 4:return this.encodeSetScalingModeOrder(e);case 5:return this.encodeSetGridOrder(e);case 6:return this.encodeSwitchPaletteOrder(e);case 7:return this.encodeSetCellSizeOrder(e);default:throw new Error(`Unknown post-process order type: ${e.type}`)}}calculateSize(e){switch(e.type){case 1:return this.calculateSetConfigSize(e);case 2:return Be;case 3:return ze;case 4:return Te;case 5:return Le;case 6:return Fe;case 7:return De;default:throw new Error(`Unknown post-process order type: ${e.type}`)}}encodeSetConfigOrder(e){let t=this.calculateSetConfigSize(e),r=C.allocUnsafe(t),n=0;return r.writeUInt8(e.type,n++),r.writeUInt8(e.displayId,n++),r.writeUInt8(e.flags,n++),e.flags&1&&e.scanlines&&(r.writeUInt8(e.scanlines.enabled?1:0,n++),r.writeUInt8(Math.round(e.scanlines.opacity*255),n++),r.writeUInt8(e.scanlines.pattern,n++),r.writeUInt8(e.scanlines.colorR,n++),r.writeUInt8(e.scanlines.colorG,n++),r.writeUInt8(e.scanlines.colorB,n++)),e.flags&2&&e.ambientEffect&&(r.writeUInt8(e.ambientEffect.enabled?1:0,n++),r.writeUInt8(Math.min(255,Math.round(e.ambientEffect.blur)),n++),r.writeUInt8(Math.min(255,Math.max(100,Math.round(e.ambientEffect.scale*100))),n++),r.writeUInt8(Math.round(e.ambientEffect.opacity*255),n++)),r.toUint8Array()}calculateSetConfigSize(e){let t=tr;return e.flags&1&&(t+=6),e.flags&2&&(t+=4),t}encodeSetScanlinesOrder(e){let t=C.allocUnsafe(Be),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.displayId,r++),t.writeUInt8(e.enabled?1:0,r++),t.writeUInt8(Math.round(e.opacity*255),r++),t.writeUInt8(e.pattern,r++),t.writeUInt8(e.colorR,r++),t.writeUInt8(e.colorG,r++),t.writeUInt8(e.colorB,r++),t.toUint8Array()}encodeSetAmbientEffectOrder(e){let t=C.allocUnsafe(ze),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.displayId,r++),t.writeUInt8(e.enabled?1:0,r++),t.writeUInt8(Math.min(255,Math.round(e.blur)),r++),t.writeUInt8(Math.min(255,Math.max(100,Math.round(e.scale*100))),r++),t.writeUInt8(Math.round(e.opacity*255),r++),t.toUint8Array()}encodeSetScalingModeOrder(e){let t=C.allocUnsafe(Te),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.displayId,r++),t.writeUInt8(e.mode,r++),t.toUint8Array()}encodeSetGridOrder(e){let t=C.allocUnsafe(Le),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.displayId,r++),t.writeUInt8(e.enabled?1:0,r++),t.writeUInt8(e.colorR,r++),t.writeUInt8(e.colorG,r++),t.writeUInt8(e.colorB,r++),t.writeUInt8(e.colorA,r++),t.writeUInt8(Math.min(10,Math.max(1,e.lineWidth)),r++),t.toUint8Array()}encodeSwitchPaletteOrder(e){let t=C.allocUnsafe(Fe),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.displayId,r++),t.writeUInt8(e.slotId,r++),t.toUint8Array()}encodeSetCellSizeOrder(e){let t=C.allocUnsafe(De),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.displayId,r++),t.writeUInt8(e.cellWidth,r++),t.writeUInt8(e.cellHeight,r++),t.toUint8Array()}};b(Tr,"PostProcessOrderEncoder");var st=Tr;V();var Dn=4,Lr=4,Vn=8,Fr=class Fr{encode(e){let t=e.renderPasses?.length??0;if(t>Lr)throw new Error(`renderPasses supports up to ${Lr} entries, got ${t}`);let r=Vn+t*Dn,n=C.allocUnsafe(r),o=0;if(n.writeUInt8(e.id,o++),n.writeUInt16BE(e.originX,o),o+=2,n.writeUInt16BE(e.originY,o),o+=2,n.writeUInt8(e.sizeX-1,o++),n.writeUInt8(e.sizeY-1,o++),n.writeUInt8(t,o++),t>0&&e.renderPasses)for(let i of e.renderPasses){let s=Math.max(0,Math.min(255,i.id)),a=Math.max(0,Math.min(255,i.zMin)),d=Math.max(0,Math.min(255,i.zMax)),l=i.enabled===!1?0:1;n.writeUInt8(s,o++),n.writeUInt8(a,o++),n.writeUInt8(d,o++),n.writeUInt8(l,o++)}return n.toUint8Array()}calculateSize(e){let t=Math.min(e.renderPasses?.length??0,Lr);return Vn+t*Dn}};b(Fr,"DisplayEncoder");var at=Fr;V();var Dr=class Dr{constructor(){h(this,"layerEncoder");h(this,"audioOrderEncoder");h(this,"vibrationOrderEncoder");h(this,"macroOrderEncoder");h(this,"postProcessOrderEncoder");h(this,"displayEncoder");this.layerEncoder=new nt,this.audioOrderEncoder=new ot,this.vibrationOrderEncoder=new de,this.macroOrderEncoder=new it,this.postProcessOrderEncoder=new st,this.displayEncoder=new at}encode(e){let t=e.layers.map(O=>this.layerEncoder.encode(O)),r=e.audioOrders||[],n=r.map(O=>this.audioOrderEncoder.encode(O)),o=e.vibrationOrders||[],i=o.map(O=>this.vibrationOrderEncoder.encode(O)),s=e.macroOrders||[],a=s.map(O=>this.macroOrderEncoder.encode(O)),d=e.postProcessOrders||[],l=d.map(O=>this.postProcessOrderEncoder.encode(O)),c=9,u=e.displays.reduce((O,z)=>O+this.displayEncoder.calculateSize(z),0),p=2,m=t.reduce((O,z)=>O+z.length,0),g=1,y=n.reduce((O,z)=>O+z.length,0),S=1,w=i.reduce((O,z)=>O+z.length,0),I=1,U=a.reduce((O,z)=>O+z.length,0),M=1,P=l.reduce((O,z)=>O+z.length,0),E=c+u+p+m+g+y+S+w+I+U+M+P,v=C.allocUnsafe(E),f=0,L=typeof e.tick=="bigint"?e.tick:BigInt(e.tick);v.writeBigUInt64BE(L,f),f+=8,v.writeUInt8(e.displays.length,f),f+=1;for(let O of e.displays){let z=this.displayEncoder.encode(O);C.from(z).copy(v,f),f+=z.length}v.writeUInt16BE(e.layers.length,f),f+=2;for(let O of t)C.from(O).copy(v,f),f+=O.length;v.writeUInt8(r.length,f),f+=1;for(let O of n)C.from(O).copy(v,f),f+=O.length;v.writeUInt8(o.length,f),f+=1;for(let O of i)C.from(O).copy(v,f),f+=O.length;v.writeUInt8(s.length,f),f+=1;for(let O of a)C.from(O).copy(v,f),f+=O.length;v.writeUInt8(d.length,f),f+=1;for(let O of l)C.from(O).copy(v,f),f+=O.length;return v.toUint8Array()}calculateSize(e){let r=e.displays.reduce((w,I)=>w+this.displayEncoder.calculateSize(I),0),n=2,o=e.layers.reduce((w,I)=>w+this.layerEncoder.calculateSize(I),0),i=1,a=(e.audioOrders||[]).reduce((w,I)=>w+this.audioOrderEncoder.calculateSize(I),0),d=1,c=(e.vibrationOrders||[]).reduce((w,I)=>w+this.vibrationOrderEncoder.calculateSize(I),0),u=1,m=(e.macroOrders||[]).reduce((w,I)=>w+this.macroOrderEncoder.calculateSize(I),0),g=1,S=(e.postProcessOrders||[]).reduce((w,I)=>w+this.postProcessOrderEncoder.calculateSize(I),0);return 9+r+n+o+i+a+d+c+u+m+g+S}static createEmptyPacket(e){return{tick:typeof e=="bigint"?Number(e):e,displayCount:0,displays:[],layerCount:0,layers:[],audioOrderCount:0,audioOrders:[],vibrationOrderCount:0,vibrationOrders:[],macroOrderCount:0,macroOrders:[],postProcessOrderCount:0,postProcessOrders:[]}}encodeEmpty(e){let t=C.allocUnsafe(15),r=typeof e=="bigint"?e:BigInt(e);return t.writeBigUInt64BE(r,0),t.writeUInt8(0,8),t.writeUInt16BE(0,9),t.writeUInt8(0,11),t.writeUInt8(0,12),t.writeUInt8(0,13),t.writeUInt8(0,14),t.toUint8Array()}};b(Dr,"UpdatePacketEncoder");var dt=Dr;var Vr=(s=>(s[s.ColorPalette=1]="ColorPalette",s[s.Sprite=2]="Sprite",s[s.MulticolorSprite=3]="MulticolorSprite",s[s.Sound=5]="Sound",s[s.Macro=7]="Macro",s[s.ImageFont=8]="ImageFont",s[s.ImageFontBlock=9]="ImageFontBlock",s))(Vr||{});V();var _r=class _r{encode(e){let t=JSON.stringify(e.template),r=new TextEncoder().encode(t);if(r.length>65535)throw new Error(`Macro template JSON too large: ${r.length} bytes (max 65535)`);let n=4+r.length,o=C.allocUnsafe(n),i=0;return o.writeUInt8(7,i++),o.writeUInt8(e.macroId,i++),o.writeUInt16BE(r.length,i),i+=2,o.toUint8Array().set(r,i),o.toUint8Array()}calculateSize(e){let t=JSON.stringify(e.template);return 4+new TextEncoder().encode(t).length}};b(_r,"MacroLoadEncoder");var lt=_r;V();var Nr=class Nr{encode(e){switch(e.loadType){case 1:return this.encodeColorPalette(e);case 2:return this.encodeSprite(e);case 3:return this.encodeMulticolorSprite(e);case 5:return this.encodeSound(e);case 8:return this.encodeImageFont(e);case 9:return this.encodeImageFontBlock(e);default:throw new Error(`Unknown load type: ${e.loadType}`)}}encodeColorPalette(e){let t=e.colors.length;if(t>255)throw new Error(`Palette size ${t} exceeds maximum of 255`);let r=e.slotId!==void 0,n=r?4:3,o=C.allocUnsafe(n+t*6),i=0;o.writeUInt8(1,i++),o.writeUInt8(r?255:0,i++),r&&o.writeUInt8(e.slotId,i++),o.writeUInt8(t,i++);for(let s of e.colors)o.writeUInt8(s.colorId,i++),o.writeUInt8(s.r,i++),o.writeUInt8(s.g,i++),o.writeUInt8(s.b,i++),o.writeUInt8(s.a,i++),o.writeUInt8(s.e??0,i++);return o.toUint8Array()}encodeSprite(e){let t=e.sprites.length;if(t>255)throw new Error(`Sprite count ${t} exceeds maximum of 255`);let r=2;for(let i of e.sprites)r+=3,r+=i.data.length;let n=C.allocUnsafe(r),o=0;n.writeUInt8(2,o++),n.writeUInt8(t,o++);for(let i of e.sprites){if(i.data.length!==i.sizeX*i.sizeY)throw new Error(`Sprite ${i.spriteId}: data length ${i.data.length} does not match size ${i.sizeX}x${i.sizeY}`);n.writeUInt8(i.spriteId,o++),n.writeUInt8(i.sizeX,o++),n.writeUInt8(i.sizeY,o++);for(let s of i.data)n.writeUInt8(s,o++)}return n.toUint8Array()}encodeMulticolorSprite(e){let t=e.sprites.length;if(t>255)throw new Error(`Sprite count ${t} exceeds maximum of 255`);let r=2;for(let i of e.sprites)r+=3,r+=i.data.length*3;let n=C.allocUnsafe(r),o=0;n.writeUInt8(3,o++),n.writeUInt8(t,o++);for(let i of e.sprites){if(i.data.length!==i.sizeX*i.sizeY)throw new Error(`Sprite ${i.spriteId}: data length ${i.data.length} does not match size ${i.sizeX}x${i.sizeY}`);n.writeUInt8(i.spriteId,o++),n.writeUInt8(i.sizeX,o++),n.writeUInt8(i.sizeY,o++);for(let s of i.data)n.writeUInt8(s.charCode,o++),n.writeUInt8(s.fgColorId,o++),n.writeUInt8(s.bgColorId,o++)}return n.toUint8Array()}encodeSound(e){let t=e.sounds.length;if(t>255)throw new Error(`Sound count ${t} exceeds maximum of 255`);let r=2;for(let i of e.sounds){if(i.midiData.length>65535)throw new Error(`Sound ${i.soundId}: MIDI data size ${i.midiData.length} exceeds maximum of 65535 bytes`);r+=3,r+=i.midiData.length}let n=C.allocUnsafe(r),o=0;n.writeUInt8(5,o++),n.writeUInt8(t,o++);for(let i of e.sounds){n.writeUInt8(i.soundId,o++),n.writeUInt16BE(i.midiData.length,o),o+=2;for(let s=0;s<i.midiData.length;s++)n.writeUInt8(i.midiData[s],o++)}return n.toUint8Array()}encodeImageFont(e){if(![1,4,16].includes(e.atlasBlocks))throw new Error(`Invalid atlasBlocks value: ${e.atlasBlocks}. Must be 1, 4, or 16.`);let r=C.allocUnsafe(6),n=0;return r.writeUInt8(8,n++),r.writeUInt8(e.glyphWidth,n++),r.writeUInt8(e.glyphHeight,n++),r.writeUInt8(e.cellWidth,n++),r.writeUInt8(e.cellHeight,n++),r.writeUInt8(e.atlasBlocks,n++),r.toUint8Array()}encodeImageFontBlock(e){let t=6+e.imageData.length,r=C.allocUnsafe(t),n=0;r.writeUInt8(9,n++),r.writeUInt8(e.blockIndex,n++),r.writeUInt32LE(e.imageData.length,n),n+=4;for(let o=0;o<e.imageData.length;o++)r.writeUInt8(e.imageData[o],n++);return r.toUint8Array()}};b(Nr,"LoadEncoder");var le=Nr;V();var Yr=class Yr{decode(e,t=0){let r=t,n=e.readUInt8(t++);if(n!==7)throw new Error(`Expected LoadType.Macro (0x07), got 0x${n.toString(16)}`);let o=e.readUInt8(t++),i=e.readUInt16BE(t);t+=2;let s=e.toUint8Array().subarray(t,t+i);t+=i;let a=new TextDecoder().decode(s),d=JSON.parse(a);return{load:{loadType:7,macroId:o,template:d},bytesRead:t-r}}};b(Yr,"MacroLoadDecoder");var ct=Yr;var Hr=class Hr{decode(e,t=0){let r=C.from(e);if(t>=r.length)throw new Error("Buffer too short to decode load type");let n=r.readUInt8(t);switch(n){case 1:return this.decodeColorPalette(r,t);case 2:return this.decodeSprite(r,t);case 3:return this.decodeMulticolorSprite(r,t);case 5:return this.decodeSound(r,t);case 7:return this.decodeMacro(r,t);case 8:return this.decodeImageFont(r,t);case 9:return this.decodeImageFontBlock(r,t);default:throw new Error(`Unknown load type: 0x${n.toString(16)}`)}}decodeColorPalette(e,t){let r=t;this.checkSize(e,t,3,"ColorPalette header");let n=e.readUInt8(t++),i=e.readUInt8(t++)===255,s;i&&(this.checkSize(e,t,1,"ColorPalette slotId"),s=e.readUInt8(t++));let a=e.readUInt8(t++);this.checkSize(e,t,a*6,`ColorPalette ${a} colors`);let d=[];for(let c=0;c<a;c++)d.push({colorId:e.readUInt8(t++),r:e.readUInt8(t++),g:e.readUInt8(t++),b:e.readUInt8(t++),a:e.readUInt8(t++),e:e.readUInt8(t++)});return{load:{loadType:1,...s!==void 0&&{slotId:s},colors:d},bytesRead:t-r}}decodeSprite(e,t){let r=t;this.checkSize(e,t,2,"Sprite header");let n=e.readUInt8(t++),o=e.readUInt8(t++),i=[];for(let a=0;a<o;a++){this.checkSize(e,t,3,`Sprite ${a} header`);let d=e.readUInt8(t++),l=e.readUInt8(t++),c=e.readUInt8(t++),u=l*c;this.checkSize(e,t,u,`Sprite ${a} data`);let p=[];for(let m=0;m<u;m++)p.push(e.readUInt8(t++));i.push({spriteId:d,sizeX:l,sizeY:c,data:p})}return{load:{loadType:2,sprites:i},bytesRead:t-r}}decodeMulticolorSprite(e,t){let r=t;this.checkSize(e,t,2,"MulticolorSprite header");let n=e.readUInt8(t++),o=e.readUInt8(t++),i=[];for(let a=0;a<o;a++){this.checkSize(e,t,3,`MulticolorSprite ${a} header`);let d=e.readUInt8(t++),l=e.readUInt8(t++),c=e.readUInt8(t++),u=l*c;this.checkSize(e,t,u*3,`MulticolorSprite ${a} data`);let p=[];for(let m=0;m<u;m++)p.push({charCode:e.readUInt8(t++),fgColorId:e.readUInt8(t++),bgColorId:e.readUInt8(t++)});i.push({spriteId:d,sizeX:l,sizeY:c,data:p})}return{load:{loadType:3,sprites:i},bytesRead:t-r}}decodeSound(e,t){let r=t;this.checkSize(e,t,2,"Sound header");let n=e.readUInt8(t++),o=e.readUInt8(t++),i=[];for(let a=0;a<o;a++){this.checkSize(e,t,3,`Sound ${a} header`);let d=e.readUInt8(t++),l=e.readUInt16BE(t);t+=2,this.checkSize(e,t,l,`Sound ${a} MIDI data`);let c=new Uint8Array(l);for(let u=0;u<l;u++)c[u]=e.readUInt8(t++);i.push({soundId:d,midiData:c})}return{load:{loadType:5,sounds:i},bytesRead:t-r}}checkSize(e,t,r,n){if(t+r>e.length)throw new Error(`Buffer too short for ${n}: need ${r} bytes at offset ${t}, but only ${e.length-t} bytes remaining`)}decodeMacro(e,t){return new ct().decode(e,t)}decodeImageFont(e,t){let r=t;this.checkSize(e,t,6,"ImageFont header");let n=e.readUInt8(t++),o=e.readUInt8(t++),i=e.readUInt8(t++),s=e.readUInt8(t++),a=e.readUInt8(t++),d=e.readUInt8(t++);if(![1,4,16].includes(d))throw new Error(`Invalid atlasBlocks value: ${d}. Must be 1, 4, or 16.`);let l=d;return{load:{loadType:8,glyphWidth:o,glyphHeight:i,cellWidth:s,cellHeight:a,atlasBlocks:l},bytesRead:t-r}}decodeImageFontBlock(e,t){let r=t;this.checkSize(e,t,2,"ImageFontBlock header");let n=e.readUInt8(t++),o=e.readUInt8(t++);this.checkSize(e,t,4,"ImageFontBlock data size");let i=e.readUInt32LE(t);t+=4,this.checkSize(e,t,i,"ImageFontBlock data");let s=new Uint8Array(i);for(let d=0;d<i;d++)s[d]=e.readUInt8(t++);return{load:{loadType:9,blockIndex:o,imageData:s},bytesRead:t-r}}};b(Hr,"LoadDecoder");var ut=Hr;var X=class X{constructor(e){this.engine=e;h(this,"colorCache",new Array(256));h(this,"cellsBuffer",[]);h(this,"opacityBuffer",new Uint8Array(0));h(this,"visibleLayersBuffer",[]);h(this,"visibleLayerIdsBuffer",[]);h(this,"passCellsBuffers",[]);h(this,"passOpacityBuffers",[]);this.rebuildColorCache()}static getChar(e){let t=X.charCache.get(e);return t===void 0&&(t=String.fromCharCode(e),X.charCache.set(e,t)),t}getLastVisibleLayerIds(){return this.visibleLayerIdsBuffer}rebuildColorCache(){for(let e=0;e<256;e++){let t=this.engine.getColor(e);t?this.colorCache[e]={r:t.r,g:t.g,b:t.b,a:t.a}:this.colorCache[e]={r:0,g:0,b:0,a:0}}}getColorRGB(e){return this.colorCache[e]??this.colorCache[255]}getColorEmission(e){let t=this.engine.getColor(e);return t?t.e:0}isLayerVisible(e,t){let r=e.x,n=e.x+e.width,o=e.y,i=e.y+e.height,s=t.x,a=t.x+256,d=t.y,l=t.y+256;return!(n<=s||r>=a||i<=d||o>=l)}rasterize(e,t,r){let n=this.normalizePasses(r);return this.rasterizeMultiPass(e,t,n)}rasterizeSinglePass(e,t){let r=e.width*e.height,n=this.cellsBuffer;n.length=r;for(let d=0;d<r;d++)n[d]?(n[d].char=" ",n[d].fgColorIndex=255,n[d].bgColorIndex=255,n[d].fgEmission=0,n[d].bgEmission=0):n[d]={char:" ",fgColorIndex:255,bgColorIndex:255,fgEmission:0,bgEmission:0};this.opacityBuffer.length<r?this.opacityBuffer=new Uint8Array(r):this.opacityBuffer.fill(0,0,r);let o=this.opacityBuffer,i=this.visibleLayersBuffer;i.length=0;for(let d=0;d<t.length;d++){let l=t[d];l.isEnabled()&&this.isLayerVisible(e,l.getOrigin())&&i.push(l)}i.sort((d,l)=>l.getZOrder()-d.getZOrder());let s=this.visibleLayerIdsBuffer;s.length=i.length;for(let d=0;d<i.length;d++)s[d]=i[d].getId();for(let d=0;d<e.height;d++)for(let l=0;l<e.width;l++){let c=d*e.width+l;if(o[c])continue;let u=e.x+l,p=e.y+d;for(let m=0;m<i.length;m++){let g=i[m],y=u-g.getOrigin().x,S=p-g.getOrigin().y,w=g.getWidth(),I=g.getHeight();if(y<0||y>=w||S<0||S>=I)continue;let U=S*w+y,M=g.getData(),P=M.getCharCode(U),E=M.getFgColorCode(U),v=M.getBgColorCode(U),f=n[c];if(P!==0&&f.char===" "&&(f.char=X.getChar(P)),E!==255&&f.fgColorIndex===255&&(f.fgColorIndex=E,f.fgEmission=this.getColorEmission(E)),v!==255){f.bgColorIndex===255&&(f.bgColorIndex=v,f.bgEmission=this.getColorEmission(v)),o[c]=1;break}}}let a=new Array(r);for(let d=0;d<r;d++)a[d]={char:n[d].char,fgColorIndex:n[d].fgColorIndex,bgColorIndex:n[d].bgColorIndex,fgEmission:n[d].fgEmission,bgEmission:n[d].bgEmission};return{id:e.id,width:e.width,height:e.height,cells:a,palette:this.colorCache}}rasterizeMultiPass(e,t,r){let n=e.width*e.height;this.ensurePassBuffers(r.length,n),this.visibleLayerIdsBuffer.length=0;let o=this.visibleLayersBuffer;o.length=0;for(let l=0;l<t.length;l++){let c=t[l];c.isEnabled()&&this.isLayerVisible(e,c.getOrigin())&&o.push(c)}o.sort((l,c)=>c.getZOrder()-l.getZOrder());for(let l=0;l<r.length;l++){let c=r[l],u=this.passCellsBuffers[l],p=this.preparePassBuffers(u,this.passOpacityBuffers[l],n);this.passOpacityBuffers[l]=p;let m=[];for(let y=0;y<o.length;y++){let S=o[y],w=S.getZOrder();w<c.zMin||w>c.zMax||m.push(S)}let g=this.visibleLayerIdsBuffer.length;for(let y=0;y<m.length;y++)this.visibleLayerIdsBuffer[g+y]=m[y].getId();this.composePass(e,m,u,p)}let i=this.cellsBuffer,s=this.preparePassBuffers(i,this.opacityBuffer,n);this.opacityBuffer=s;let a=new Array(n),d=[];for(let l=0;l<r.length;l++){let c=this.passCellsBuffers[l],u=new Array(n);for(let p=0;p<n;p++){let m=c[p];u[p]={char:m.char,fgColorIndex:m.fgColorIndex,bgColorIndex:m.bgColorIndex,fgEmission:m.fgEmission,bgEmission:m.bgEmission}}d.push({id:r[l].id,zMin:r[l].zMin,zMax:r[l].zMax,cells:u})}for(let l=0;l<n;l++){let c=i[l];for(let u=r.length-1;u>=0;u--){let p=this.passCellsBuffers[u][l];if(c.char===" "&&p.char!==" "&&(c.char=p.char),c.fgColorIndex===255&&p.fgColorIndex!==255&&(c.fgColorIndex=p.fgColorIndex,c.fgEmission=p.fgEmission),p.bgColorIndex!==255){c.bgColorIndex===255&&(c.bgColorIndex=p.bgColorIndex,c.bgEmission=p.bgEmission);break}}a[l]={char:c.char,fgColorIndex:c.fgColorIndex,bgColorIndex:c.bgColorIndex,fgEmission:c.fgEmission,bgEmission:c.bgEmission}}return{id:e.id,width:e.width,height:e.height,cells:a,palette:this.colorCache,passes:d}}composePass(e,t,r,n){let o=e.width,i=e.height;for(let s=0;s<i;s++)for(let a=0;a<o;a++){let d=s*o+a;if(n[d])continue;let l=e.x+a,c=e.y+s;for(let u=0;u<t.length;u++){let p=t[u],m=l-p.getOrigin().x,g=c-p.getOrigin().y,y=p.getWidth(),S=p.getHeight();if(m<0||m>=y||g<0||g>=S)continue;let w=g*y+m,I=p.getData(),U=I.getCharCode(w),M=I.getFgColorCode(w),P=I.getBgColorCode(w),E=r[d];if(U!==0&&E.char===" "&&(E.char=X.getChar(U)),M!==255&&E.fgColorIndex===255&&(E.fgColorIndex=M,E.fgEmission=this.getColorEmission(M)),P!==255){E.bgColorIndex===255&&(E.bgColorIndex=P,E.bgEmission=this.getColorEmission(P)),n[d]=1;break}}}}preparePassBuffers(e,t,r){e.length=r;for(let n=0;n<r;n++)e[n]?(e[n].char=" ",e[n].fgColorIndex=255,e[n].bgColorIndex=255,e[n].fgEmission=0,e[n].bgEmission=0):e[n]={char:" ",fgColorIndex:255,bgColorIndex:255,fgEmission:0,bgEmission:0};return t.length<r?t=new Uint8Array(r):t.fill(0,0,r),t}ensurePassBuffers(e,t){for(;this.passCellsBuffers.length<e;)this.passCellsBuffers.push([]);for(;this.passOpacityBuffers.length<e;)this.passOpacityBuffers.push(new Uint8Array(t));this.passCellsBuffers.length>e&&(this.passCellsBuffers.length=e),this.passOpacityBuffers.length>e&&(this.passOpacityBuffers.length=e);for(let r=0;r<e;r++)this.passOpacityBuffers[r].length<t?this.passOpacityBuffers[r]=new Uint8Array(t):this.passOpacityBuffers[r].fill(0,0,t)}normalizePasses(e){let t={id:0,zMin:0,zMax:255,enabled:!0};if(!e||e.length===0)return[t];let r=e.filter(n=>n.enabled!==!1);return r.length===0?[t]:r.slice(0,4)}rasterizeWithSortedLayers(e,t){let r=e.width*e.height,n=this.cellsBuffer;n.length=r;for(let a=0;a<r;a++)n[a]?(n[a].char=" ",n[a].fgColorIndex=255,n[a].bgColorIndex=255,n[a].fgEmission=0,n[a].bgEmission=0):n[a]={char:" ",fgColorIndex:255,bgColorIndex:255,fgEmission:0,bgEmission:0};this.opacityBuffer.length<r?this.opacityBuffer=new Uint8Array(r):this.opacityBuffer.fill(0,0,r);let o=this.opacityBuffer,i=this.visibleLayersBuffer;i.length=0;for(let a=0;a<t.length;a++){let d=t[a];this.isLayerVisible(e,d.getOrigin())&&i.push(d)}for(let a=0;a<e.height;a++)for(let d=0;d<e.width;d++){let l=a*e.width+d;if(o[l])continue;let c=e.x+d,u=e.y+a;for(let p=0;p<i.length;p++){let m=i[p],g=c-m.getOrigin().x,y=u-m.getOrigin().y,S=m.getWidth(),w=m.getHeight();if(g<0||g>=S||y<0||y>=w)continue;let I=y*S+g,U=m.getData(),M=U.getCharCode(I),P=U.getFgColorCode(I),E=U.getBgColorCode(I),v=n[l];if(M!==0&&v.char===" "&&(v.char=X.getChar(M)),P!==255&&v.fgColorIndex===255&&(v.fgColorIndex=P,v.fgEmission=this.getColorEmission(P)),E!==255){v.bgColorIndex===255&&(v.bgColorIndex=E,v.bgEmission=this.getColorEmission(E)),o[l]=1;break}}}let s=new Array(r);for(let a=0;a<r;a++)s[a]={char:n[a].char,fgColorIndex:n[a].fgColorIndex,bgColorIndex:n[a].bgColorIndex,fgEmission:n[a].fgEmission,bgEmission:n[a].bgEmission};return{id:e.id,width:e.width,height:e.height,cells:s,palette:this.colorCache}}calculateIntersection(e,t){let r=e.x,n=e.x+e.width,o=e.y,i=e.y+e.height,s=t.x,a=t.x+256,d=t.y,l=t.y+256,c=Math.max(r,s),u=Math.min(n,a),p=Math.max(o,d),m=Math.min(i,l);return{visible:c<u&&p<m,originStart:{x:c-e.x,y:p-e.y},originEnd:{x:u-e.x,y:m-e.y},layerStart:{x:c-t.x,y:p-t.y},layerEnd:{x:u-t.x,y:m-t.y}}}};b(X,"DisplayRasterizer"),h(X,"charCache",(()=>{let e=new Map;for(let t=0;t<256;t++)e.set(t,String.fromCharCode(t));return e})());var pt=X;var Xr=class Xr{constructor(){h(this,"enabled",!1);h(this,"currentStats",null)}setEnabled(e){this.enabled=e,e||(this.currentStats=null)}isEnabled(){return this.enabled}get tick(){return this.currentStats?.tick??0}get timestamp(){return this.currentStats?.timestamp??0}get totalOrders(){return this.currentStats?.totalOrders??0}get ordersByLayer(){return this.currentStats?.ordersByLayer??new Map}get ordersByType(){return this.currentStats?.ordersByType??new Map}get totalLayers(){return this.currentStats?.totalLayers??0}get visibleLayers(){return this.currentStats?.visibleLayers??0}get layersPerDisplay(){return this.currentStats?.layersPerDisplay??new Map}get displayCompositeLayerIds(){return this.currentStats?.displayCompositeLayerIds??new Map}get updatePacketSize(){return this.currentStats?.updatePacketSize??0}get displayHeaderSize(){return this.currentStats?.displayHeaderSize??0}get layerHeaderSize(){return this.currentStats?.layerHeaderSize??0}get orderDataSize(){return this.currentStats?.orderDataSize??0}get compressionRatio(){return this.currentStats?.compressionRatio??0}get compressedPacketSize(){return Math.round(this.updatePacketSize*this.compressionRatio)}get totalCells(){return this.currentStats?.totalCells??0}get nonEmptyCells(){return this.currentStats?.nonEmptyCells??0}get cellsWithBackground(){return this.currentStats?.cellsWithBackground??0}get rasterizationTimeMs(){return this.currentStats?.rasterizationTimeMs??0}get encodingTimeMs(){return this.currentStats?.encodingTimeMs??0}get packetSplit(){return this.currentStats?.packetSplit}get layerDetails(){return this.currentStats?.layerDetails}startTick(e){this.enabled&&(this.currentStats={tick:e,timestamp:Date.now(),totalOrders:0,ordersByLayer:new Map,ordersByType:new Map,totalLayers:0,visibleLayers:0,layersPerDisplay:new Map,updatePacketSize:0,displayHeaderSize:0,layerHeaderSize:0,orderDataSize:0,compressionRatio:0,totalCells:0,nonEmptyCells:0,cellsWithBackground:0,rasterizationTimeMs:0,encodingTimeMs:0,displayCompositeLayerIds:new Map})}recordDisplayComposite(e,t){!this.enabled||!this.currentStats||(this.currentStats.displayCompositeLayerIds||(this.currentStats.displayCompositeLayerIds=new Map),this.currentStats.displayCompositeLayerIds.set(e,[...t]))}recordLayerOrders(e,t){if(!(!this.enabled||!this.currentStats)){this.currentStats.totalOrders+=t.length,this.currentStats.ordersByLayer.set(e,t.length);for(let r of t){let n=this.currentStats.ordersByType.get(r.type)||0;this.currentStats.ordersByType.set(r.type,n+1)}}}recordLayers(e,t){!this.enabled||!this.currentStats||(this.currentStats.totalLayers=e,this.currentStats.visibleLayers=t)}recordDisplayLayers(e,t){!this.enabled||!this.currentStats||this.currentStats.layersPerDisplay.set(e,t)}recordUpdatePacketSize(e,t,r,n){!this.enabled||!this.currentStats||(this.currentStats.updatePacketSize=e,this.currentStats.displayHeaderSize=t,this.currentStats.layerHeaderSize=r,this.currentStats.orderDataSize=n,this.currentStats.compressionRatio=.25)}recordPacketSplit(e,t,r,n){!this.enabled||!this.currentStats||(this.currentStats.packetSplit={userId:e,displayCount:t,staticLayerCount:r,dynamicLayerCount:n})}recordLayerInfo(e,t,r,n){!this.enabled||!this.currentStats||(this.currentStats.layerDetails||(this.currentStats.layerDetails=[]),this.currentStats.layerDetails.push({layerId:e,mustBeReliable:t,orderCount:r,updateFlags:n}))}recordRenderStats(e,t,r){!this.enabled||!this.currentStats||(this.currentStats.totalCells=e,this.currentStats.nonEmptyCells=t,this.currentStats.cellsWithBackground=r)}recordRasterizationTime(e){!this.enabled||!this.currentStats||(this.currentStats.rasterizationTimeMs=e)}recordEncodingTime(e){!this.enabled||!this.currentStats||(this.currentStats.encodingTimeMs=e)}endTick(){}reset(){this.currentStats=null}};b(Xr,"CoreStats");var ce=Xr;var _n=[[0,0],[9786,1],[9787,2],[9829,3],[9830,4],[9827,5],[9824,6],[8226,7],[9688,8],[9675,9],[9689,10],[9794,11],[9792,12],[9834,13],[9835,14],[9788,15],[9658,16],[9668,17],[8597,18],[8252,19],[182,20],[167,21],[9644,22],[8616,23],[8593,24],[8595,25],[8594,26],[8592,27],[8735,28],[8596,29],[9650,30],[9660,31],[8962,127],[199,128],[252,129],[233,130],[226,131],[228,132],[224,133],[229,134],[231,135],[234,136],[235,137],[232,138],[239,139],[238,140],[236,141],[196,142],[197,143],[201,144],[230,145],[198,146],[244,147],[246,148],[242,149],[251,150],[249,151],[255,152],[214,153],[220,154],[162,155],[163,156],[165,157],[8359,158],[402,159],[225,160],[237,161],[243,162],[250,163],[241,164],[209,165],[170,166],[186,167],[191,168],[8976,169],[172,170],[189,171],[188,172],[161,173],[171,174],[187,175],[9617,176],[9618,177],[9619,178],[9474,179],[9508,180],[9569,181],[9570,182],[9558,183],[9557,184],[9571,185],[9553,186],[9559,187],[9565,188],[9564,189],[9563,190],[9488,191],[9492,192],[9524,193],[9516,194],[9500,195],[9472,196],[9532,197],[9566,198],[9567,199],[9562,200],[9556,201],[9577,202],[9574,203],[9568,204],[9552,205],[9580,206],[9575,207],[9576,208],[9572,209],[9573,210],[9561,211],[9560,212],[9554,213],[9555,214],[9579,215],[9578,216],[9496,217],[9484,218],[9608,219],[9604,220],[9612,221],[9616,222],[9600,223],[945,224],[223,225],[915,226],[960,227],[931,228],[963,229],[181,230],[964,231],[934,232],[920,233],[937,234],[948,235],[8734,236],[966,237],[949,238],[8745,239],[8801,240],[177,241],[8805,242],[8804,243],[8992,244],[8993,245],[247,246],[8776,247],[176,248],[8729,249],[183,250],[8730,251],[8319,252],[178,253],[9632,254],[160,255]],Uo=new Map(_n),Xs=new Map(_n.map(([x,e])=>[e,x]));function j(x){if(x<128)return x;let e=Uo.get(x);return e!==void 0?e:x&255}b(j,"unicodeToCp437");var Gr=class Gr{constructor(){h(this,"unicolorSprites",new Map);h(this,"multicolorSprites",new Map)}loadUnicolorSprites(e){if("loadType"in e){this.loadUnicolorSpritesFromPacket(e);return}for(let t of e){let{spriteId:r,sizeX:n,sizeY:o,data:i}=t,s=new Z(n*o);if(typeof i=="string"){let d=i.replace(/\n/g,"");for(let l=0;l<Math.min(d.length,n*o);l++)s.set(l,j(d.charCodeAt(l)))}else if(Array.isArray(i)&&i.length>0&&typeof i[0]=="string"){let d=i;for(let l=0;l<Math.min(d.length,o);l++){let c=d[l];if(c)for(let u=0;u<Math.min(c.length,n);u++)s.set(l*n+u,j(c.charCodeAt(u)))}}else{let d=i;for(let l=0;l<Math.min(d.length,n*o);l++)s.set(l,d[l])}let a={id:r,sizeX:n,sizeY:o,data:s};this.unicolorSprites.set(a.id,a)}}loadUnicolorSpritesFromPacket(e){for(let t of e.sprites){let r=new Z(t.sizeX*t.sizeY);for(let o=0;o<t.data.length;o++)r.set(o,t.data[o]);let n={id:t.spriteId,sizeX:t.sizeX,sizeY:t.sizeY,data:r};this.unicolorSprites.set(n.id,n)}}loadMulticolorSprites(e){if("loadType"in e){this.loadMulticolorSpritesFromPacket(e);return}for(let t of e){let{spriteId:r,sizeX:n,sizeY:o,data:i}=t,s=new Y(n*o);for(let d=0;d<Math.min(i.length,n*o);d++){let l=i[d],c=typeof l.charCode=="string"?j(l.charCode.charCodeAt(0)):l.charCode;s.set(d,c,l.fgColorId,l.bgColorId)}let a={id:r,sizeX:n,sizeY:o,data:s};this.multicolorSprites.set(a.id,a)}}loadMulticolorSpritesFromPacket(e){for(let t of e.sprites){let r=new Y(t.sizeX*t.sizeY);for(let o=0;o<t.data.length;o++){let i=t.data[o];r.set(o,i.charCode,i.fgColorId,i.bgColorId)}let n={id:t.spriteId,sizeX:t.sizeX,sizeY:t.sizeY,data:r};this.multicolorSprites.set(n.id,n)}}getUnicolorSprite(e){return this.unicolorSprites.get(e)}getMulticolorSprite(e){return this.multicolorSprites.get(e)}hasUnicolorSprite(e){return this.unicolorSprites.has(e)}hasMulticolorSprite(e){return this.multicolorSprites.has(e)}unloadUnicolorSprite(e){return this.unicolorSprites.delete(e)}unloadMulticolorSprite(e){return this.multicolorSprites.delete(e)}clearUnicolorSprites(){this.unicolorSprites.clear()}clearMulticolorSprites(){this.multicolorSprites.clear()}clearAll(){this.unicolorSprites.clear(),this.multicolorSprites.clear()}getUnicolorSpriteCount(){return this.unicolorSprites.size}getMulticolorSpriteCount(){return this.multicolorSprites.size}getTotalSpriteCount(){return this.unicolorSprites.size+this.multicolorSprites.size}};b(Gr,"SpriteRegistry");var ue=Gr;var $r=(t=>(t.Bitmap="bitmap",t.Image="image",t))($r||{});function mt(x){return Math.sqrt(x)*16}b(mt,"getAtlasColumns");function Zr(x){return x*256-1}b(Zr,"getMaxCharCode");function Nn(x,e){let r=mt(x)*e;return{width:r,height:r}}b(Nn,"getAtlasDimensions");var Wr=class Wr{constructor(e,t){this.fontId=e;this.config=t;h(this,"atlasColumns");h(this,"maxCharCode");h(this,"blocks",new Map);this.atlasColumns=mt(t.atlasBlocks),this.maxCharCode=Zr(t.atlasBlocks)}addBlock(e,t){if(e<0||e>=this.config.atlasBlocks)throw new Error(`Invalid block index ${e} for font with ${this.config.atlasBlocks} blocks`);this.blocks.set(e,t)}getBlock(e){return this.blocks.get(e)}getFontId(){return this.fontId}getConfig(){return{glyphWidth:this.config.glyphWidth,glyphHeight:this.config.glyphHeight,cellWidth:this.config.cellWidth,cellHeight:this.config.cellHeight,atlasBlocks:this.config.atlasBlocks}}getGlyphWidth(){return this.config.glyphWidth}getGlyphHeight(){return this.config.glyphHeight}getCellWidth(){return this.config.cellWidth??this.config.glyphWidth}getCellHeight(){return this.config.cellHeight??this.config.glyphHeight}getAtlasBlocks(){return this.config.atlasBlocks}getAtlasColumns(){return this.atlasColumns}getMaxCharCode(){return this.maxCharCode}getAtlasDimensions(){return{width:this.atlasColumns*this.config.glyphWidth,height:this.atlasColumns*this.config.glyphHeight}}getCharUV(e){if(e<0||e>this.maxCharCode)return null;let t=e%this.atlasColumns,r=Math.floor(e/this.atlasColumns),n=t/this.atlasColumns,o=r/this.atlasColumns,i=(t+1)/this.atlasColumns,s=(r+1)/this.atlasColumns;return{u1:n,v1:o,u2:i,v2:s}}isValidCharCode(e){return e>=0&&e<=this.maxCharCode}};b(Wr,"ImageFont");var J=Wr;var jr=class jr{constructor(){h(this,"fonts",new Map);h(this,"nameToId",new Map);h(this,"nextId",0)}allocateId(e){if(this.nextId>255)throw new Error(`Cannot register font "${e}": maximum 256 fonts reached`);return this.nextId++}registerFont(e,t){if(this.nameToId.has(e))throw new Error(`ImageFont with name "${e}" already exists`);let r=this.allocateId(e),n={glyphWidth:t.glyphWidth,glyphHeight:t.glyphHeight,cellWidth:t.cellWidth,cellHeight:t.cellHeight,atlasBlocks:t.atlasBlocks??1},o=new J(r,n);return this.fonts.set(r,o),this.nameToId.set(e,r),r}addBlock(e,t,r){let n=this.fonts.get(e);if(!n)throw new Error(`ImageFont with ID ${e} not found`);n.addBlock(t,r)}loadFont(e,t){if(this.fonts.has(e))throw new Error(`ImageFont with ID ${e} already exists`);let r=new J(e,t);this.fonts.set(e,r),e>=this.nextId&&(this.nextId=e+1)}getFont(e){return this.fonts.get(e)}getFontByName(e){let t=this.nameToId.get(e);if(t!==void 0)return this.fonts.get(t)}getFontId(e){return this.nameToId.get(e)}getFontName(e){for(let[t,r]of this.nameToId.entries())if(r===e)return t}hasFont(e){return this.fonts.has(e)}hasFontByName(e){return this.nameToId.has(e)}unloadFont(e){if(!this.fonts.get(e))return!1;for(let[r,n]of this.nameToId.entries())if(n===e){this.nameToId.delete(r);break}return this.fonts.delete(e)}unloadFontByName(e){let t=this.nameToId.get(e);return t===void 0?!1:(this.nameToId.delete(e),this.fonts.delete(t))}clearFonts(){this.fonts.clear(),this.nameToId.clear(),this.nextId=0}getFontIds(){return Array.from(this.fonts.keys()).sort((e,t)=>e-t)}getFontNames(){return Array.from(this.nameToId.keys())}getAllFonts(){return Array.from(this.fonts.entries()).sort((e,t)=>e[0]-t[0]).map(e=>e[1])}getFontCount(){return this.fonts.size}};b(jr,"ImageFontRegistry");var pe=jr;var Jr=class Jr{constructor(){h(this,"sounds",new Map);h(this,"nameToId",new Map);h(this,"nextId",0)}registerFile(e,t,r){let n=this.allocateId(e),o={soundId:n,name:e,loadType:"file",format:t,data:r};return this.sounds.set(n,o),this.nameToId.set(e,n),n}registerFileWithId(e,t,r,n){this.validateId(e),this.checkIdAvailable(e,t);let o={soundId:e,name:t,loadType:"file",format:r,data:n};this.sounds.set(e,o),this.nameToId.set(t,e)}registerExternal(e,t,r,n,o){let i=this.allocateId(e),s={soundId:i,name:e,loadType:"external",format:t,url:r,size:n,checksum:o};return this.sounds.set(i,s),this.nameToId.set(e,i),i}registerExternalWithId(e,t,r,n,o,i){this.validateId(e),this.checkIdAvailable(e,t);let s={soundId:e,name:t,loadType:"external",format:r,url:n,size:o,checksum:i};this.sounds.set(e,s),this.nameToId.set(t,e)}get(e){if(typeof e=="number")return this.sounds.get(e);let t=this.nameToId.get(e);return t!==void 0?this.sounds.get(t):void 0}has(e){return this.get(e)!==void 0}getAll(){return Array.from(this.sounds.values())}getFileSounds(){return this.getAll().filter(e=>e.loadType==="file")}getExternalSounds(){return this.getAll().filter(e=>e.loadType==="external")}getNames(){return Array.from(this.nameToId.keys())}getId(e){return this.nameToId.get(e)}toLoadPackets(){let e=[],t=this.sounds.size,r=this.getFileSounds();if(r.length>0){let o=r.map(i=>({soundId:i.soundId,name:i.name,format:i.format,data:i.data}));e.push({type:"sound",mode:"file",sounds:o,totalSounds:t})}let n=this.getExternalSounds();if(n.length>0){let o=n.map(i=>({soundId:i.soundId,name:i.name,format:i.format,url:i.url,size:i.size,checksum:i.checksum}));e.push({type:"sound",mode:"external",sounds:o,totalSounds:t})}return e}toLoadPacket(e){let t=this.get(e);return t?t.loadType==="file"?{type:"sound",mode:"file",sounds:[{soundId:t.soundId,name:t.name,format:t.format,data:t.data}]}:{type:"sound",mode:"external",sounds:[{soundId:t.soundId,name:t.name,format:t.format,url:t.url,size:t.size,checksum:t.checksum}]}:null}unregister(e){let t=this.get(e);return t?(this.sounds.delete(t.soundId),this.nameToId.delete(t.name),!0):!1}clear(){this.sounds.clear(),this.nameToId.clear(),this.nextId=0}get size(){return this.sounds.size}getStats(){let e=this.getAll(),t=e.filter(n=>n.loadType==="file"),r=t.reduce((n,o)=>n+(o.data?.length??0),0);return{total:e.length,file:t.length,external:e.length-t.length,totalFileSize:r}}allocateId(e){if(this.nameToId.has(e))throw new Error(`Sound with name "${e}" already exists`);for(;this.sounds.has(this.nextId);)if(this.nextId++,this.nextId>255)throw new Error("Maximum number of sounds (256) reached");return this.nextId++}validateId(e){if(!Number.isInteger(e)||e<0||e>255)throw new Error(`Invalid sound ID: ${e}. Must be an integer between 0 and 255.`)}checkIdAvailable(e,t){if(this.sounds.has(e)){let r=this.sounds.get(e);throw new Error(`Sound ID ${e} is already used by "${r.name}". Cannot register "${t}".`)}if(this.nameToId.has(t))throw new Error(`Sound with name "${t}" already exists`)}};b(Jr,"SoundRegistry");var me=Jr;var qr=class qr{constructor(e){this.soundRegistry=e}collectFromUser(e){let t=[],r=e.flushSoundCommands();for(let o of r){let i=this.convertSoundCommand(o);i&&t.push(i)}let n=e.flushAudioConfigCommands();for(let o of n){let i=this.convertConfigCommand(o);i&&t.push(i)}return t}convertSoundCommand(e){return"setEffects"in e&&e.setEffects===!0?this.convertSetEffectsCommand(e):"fadeOut"in e&&e.fadeOut===!0?this.convertFadeOutCommand(e):"pause"in e&&e.pause===!0?this.convertPauseCommand(e):"resume"in e&&e.resume===!0?this.convertResumeCommand(e):"instanceId"in e||"volume"in e||"pitch"in e||"loop"in e||"fadeIn"in e||"x"in e||"y"in e||"lowpass"in e||"highpass"in e||"reverb"in e?this.convertPlayCommand(e):this.convertStopCommand(e)}convertPlayCommand(e){let t=this.resolveSoundId(e.sound);if(t===null)return console.warn(`[AudioOrderCollector] Unknown sound: ${e.sound}`),null;let r=0;e.loop&&(r|=1),e.volume!==void 0&&(r|=2),e.pitch!==void 0&&(r|=4),e.fadeIn!==void 0&&(r|=8),e.lowpass!==void 0&&e.lowpass>0&&(r|=32),e.highpass!==void 0&&e.highpass>0&&(r|=64),e.reverb!==void 0&&e.reverb>0&&(r|=128);let n=e.x!==void 0&&e.y!==void 0;return n&&(r|=16),n?{type:1,soundId:t,instanceId:e.instanceId??0,flags:r,volume:e.volume!==void 0?this.encodeVolume(e.volume):void 0,pitch:e.pitch!==void 0?this.encodePitch(e.pitch):void 0,fadeIn:e.fadeIn!==void 0?this.encodeFadeTime(e.fadeIn):void 0,posX:this.encodePosition(e.x),posY:this.encodePosition(e.y),lowpass:e.lowpass!==void 0&&e.lowpass>0?this.encodeFilterFreq(e.lowpass):void 0,highpass:e.highpass!==void 0&&e.highpass>0?this.encodeFilterFreq(e.highpass):void 0,reverb:e.reverb!==void 0&&e.reverb>0?this.encodeReverb(e.reverb):void 0}:{type:2,soundId:t,instanceId:e.instanceId??0,flags:r&-17,volume:e.volume!==void 0?this.encodeVolume(e.volume):void 0,pitch:e.pitch!==void 0?this.encodePitch(e.pitch):void 0,fadeIn:e.fadeIn!==void 0?this.encodeFadeTime(e.fadeIn):void 0,lowpass:e.lowpass!==void 0&&e.lowpass>0?this.encodeFilterFreq(e.lowpass):void 0,highpass:e.highpass!==void 0&&e.highpass>0?this.encodeFilterFreq(e.highpass):void 0,reverb:e.reverb!==void 0&&e.reverb>0?this.encodeReverb(e.reverb):void 0}}convertStopCommand(e){let{targetType:t,target:r}=this.resolveTarget(e.sound);return{type:3,targetType:t,target:r}}convertFadeOutCommand(e){let{targetType:t,target:r}=this.resolveTarget(e.sound);return{type:4,targetType:t,duration:this.encodeFadeTime(e.duration),target:r}}convertPauseCommand(e){let{targetType:t,target:r}=this.resolveTarget(e.sound);return{type:5,targetType:t,target:r}}convertResumeCommand(e){let{targetType:t,target:r}=this.resolveTarget(e.sound);return{type:6,targetType:t,target:r}}convertSetEffectsCommand(e){let t=0;return e.lowpass!==void 0&&(t|=1),e.highpass!==void 0&&(t|=2),e.reverb!==void 0&&(t|=4),{type:9,instanceId:e.instanceId,flags:t,lowpass:e.lowpass!==void 0?this.encodeFilterFreq(e.lowpass):void 0,highpass:e.highpass!==void 0?this.encodeFilterFreq(e.highpass):void 0,reverb:e.reverb!==void 0?this.encodeReverb(e.reverb):void 0}}convertConfigCommand(e){return e.type==="set-listener-position"?{type:7,x:this.encodePosition(e.x),y:this.encodePosition(e.y)}:e.type==="configure-spatial"?{type:8,maxDistance:this.encodeDistance(e.maxDistance??1e3),referenceDistance:this.encodeDistance(e.referenceDistance??100),rolloffFactor:this.encodeRolloff(e.rolloffFactor??1),panSpread:this.encodePanSpread(e.panSpread??.5)}:null}resolveSoundId(e){if(typeof e=="number")return e>=0&&e<=255?e:null;let t=this.soundRegistry.getId(e);return t!==void 0?t:null}resolveTarget(e){if(e==="all")return{targetType:2,target:void 0};if(typeof e=="number")return{targetType:0,target:e};let t=this.soundRegistry.getId(e);return t!==void 0?{targetType:1,target:t}:(console.warn(`[AudioOrderCollector] Unknown sound name: ${e}, treating as 'all'`),{targetType:2,target:void 0})}encodeVolume(e){return Math.round(Math.max(0,Math.min(1,e))*255)}encodePitch(e){let t=Math.max(.25,Math.min(4,e)),r=64*Math.log2(t/.25);return Math.round(Math.max(0,Math.min(255,r)))}encodeFadeTime(e){return Math.round(Math.max(0,Math.min(25.5,e))*10)}encodeDistance(e){return Math.round(Math.max(0,Math.min(25500,e))/100)}encodeRolloff(e){return Math.round(Math.max(0,Math.min(2.55,e))*100)}encodePanSpread(e){return Math.round(Math.max(0,Math.min(1,e))*255)}encodePosition(e){return Math.round(Math.max(0,Math.min(65535,e)))}encodeFilterFreq(e){return e<=0?0:Math.round(Math.max(1,Math.min(255,e/100)))}encodeReverb(e){return Math.round(Math.max(0,Math.min(1,e))*255)}};b(qr,"AudioOrderCollector");var xe=qr;var Kr=class Kr{collectFromUser(e){let t=[];if(e.hasMobileVibrationCommands()){let r=e.flushMobileVibrationCommands();for(let n of r){let o=this.convertMobileCommand(n);o&&t.push(o)}}if(e.hasGamepadVibrationCommands()){let r=e.flushGamepadVibrationCommands();for(let n of r){let o=this.convertGamepadCommand(n);o&&t.push(o)}}return t}convertMobileCommand(e){return"cancel"in e&&e.cancel===!0?this.convertMobileCancelCommand():"pattern"in e?this.convertMobileVibrateCommand(e):null}convertMobileVibrateCommand(e){let t=0;e.intensity!==void 0&&e.intensity!==1&&(t|=1);let r=e.pattern,n=Array.isArray(r)?[...r]:[r],o={type:1,flags:t,pattern:n.map(i=>Math.round(i))};return t&1&&(o.intensity=Math.round(Math.min(1,Math.max(0,e.intensity))*255)/255),o}convertMobileCancelCommand(){return{type:2}}convertGamepadCommand(e){if("cancel"in e&&e.cancel===!0){let t=e.gamepadIndex??"all";return this.convertGamepadCancelCommand({gamepadIndex:t})}if("options"in e&&e.options){let t=e.gamepadIndex??0;return this.convertGamepadVibrateCommand({gamepadIndex:t,options:e.options})}return null}convertGamepadVibrateCommand(e){let{gamepadIndex:t,options:r}=e,n=0;r.startDelay!==void 0&&r.startDelay>0&&(n|=1);let o=t==="all"?255:t;t==="all"&&(n|=2);let i={type:16,flags:n,gamepadIndex:o,duration:Math.round(r.duration),strongMagnitude:Math.round(Math.min(1,Math.max(0,r.strongMagnitude??1))*255),weakMagnitude:Math.round(Math.min(1,Math.max(0,r.weakMagnitude??.5))*255)};return r.startDelay!==void 0&&r.startDelay>0&&(i.startDelay=Math.round(r.startDelay)),i}convertGamepadCancelCommand(e){let{gamepadIndex:t}=e,r=0,n=t==="all"?255:t;return t==="all"&&(r|=2),{type:17,flags:r,gamepadIndex:n}}};b(Kr,"VibrationOrderCollector");var he=Kr;var _=require("@utsp/types");var Qr=class Qr{collectFromUser(e){let t=e.flushPostProcessCommands();return this.convertCommands(t)}convertCommands(e){let t=[];for(let r of e){let n=this.convertCommand(r);n&&t.push(n)}return t}convertCommand(e){let t=e.displayId;switch(e.type){case"set-config":return this.convertSetConfig(e);case"set-scanlines-enabled":return this.createSetScanlinesOrder(t,e.enabled??!1,e.opacity);case"set-scanlines-opacity":return this.createSetScanlinesOrder(t,!0,e.opacity??_.POST_PROCESS_DEFAULTS.scanlines.opacity);case"set-ambient-effect-enabled":return this.createSetAmbientEffectOrder(t,e.enabled??!1);case"set-ambient-effect-blur":return this.createSetAmbientEffectOrder(t,!0,e.blur);case"set-ambient-effect-scale":return this.createSetAmbientEffectOrder(t,!0,void 0,e.scale);case"set-scaling-mode":return this.createSetScalingModeOrder(t,e.scalingMode);case"set-grid":return this.createSetGridOrder(t,e.gridConfig);case"switch-palette":return this.createSwitchPaletteOrder(t,e.paletteSlotId);case"set-cell-size":return this.createSetCellSizeOrder(t,e.cellWidth,e.cellHeight);default:return console.warn(`[PostProcessOrderCollector] Unknown command type: ${e.type}`),null}}convertSetConfig(e){let t=e.displayId;if(!e.config)return{type:1,displayId:t,flags:3,scanlines:{enabled:!1,opacity:0,pattern:0,colorR:0,colorG:0,colorB:0},ambientEffect:{enabled:!1,blur:0,scale:1,opacity:0}};let r=0,n={type:1,displayId:t,flags:0};if(e.config.scanlines){r|=1;let o=e.config.scanlines;n.scanlines={enabled:o.enabled,opacity:o.opacity??_.POST_PROCESS_DEFAULTS.scanlines.opacity,pattern:this.patternToType(o.pattern??"horizontal"),colorR:o.color?.r??0,colorG:o.color?.g??0,colorB:o.color?.b??0}}if(e.config.ambientEffect){r|=2;let o=e.config.ambientEffect;n.ambientEffect={enabled:o.enabled,blur:o.blur??_.POST_PROCESS_DEFAULTS.ambientEffect.blur,scale:o.scale??_.POST_PROCESS_DEFAULTS.ambientEffect.scale,opacity:o.opacity??_.POST_PROCESS_DEFAULTS.ambientEffect.opacity}}return n.flags=r,n}createSetScanlinesOrder(e,t,r){return{type:2,displayId:e,enabled:t,opacity:r??_.POST_PROCESS_DEFAULTS.scanlines.opacity,pattern:0,colorR:0,colorG:0,colorB:0}}createSetAmbientEffectOrder(e,t,r,n){return{type:3,displayId:e,enabled:t,blur:r??_.POST_PROCESS_DEFAULTS.ambientEffect.blur,scale:n??_.POST_PROCESS_DEFAULTS.ambientEffect.scale,opacity:_.POST_PROCESS_DEFAULTS.ambientEffect.opacity}}patternToType(e){switch(e){case"horizontal":return 0;case"vertical":return 1;case"grid":return 2;default:return 0}}createSetScalingModeOrder(e,t){return{type:4,displayId:e,mode:(0,_.scalingModeToValue)(t)}}createSetGridOrder(e,t){let{r,g:n,b:o,a:i}=this.parseColor(t.color??_.GRID_DEFAULTS.color);return{type:5,displayId:e,enabled:t.enabled,colorR:r,colorG:n,colorB:o,colorA:i,lineWidth:t.lineWidth??_.GRID_DEFAULTS.lineWidth}}createSwitchPaletteOrder(e,t){return{type:6,displayId:e,slotId:t}}createSetCellSizeOrder(e,t,r){return{type:7,displayId:e,cellWidth:t,cellHeight:r}}parseColor(e){let t=e.match(/rgba?\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*([\d.]+))?\s*\)/);if(t)return{r:parseInt(t[1],10),g:parseInt(t[2],10),b:parseInt(t[3],10),a:t[4]?Math.round(parseFloat(t[4])*255):255};let r=e.match(/^#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})$/);if(r){let n=r[1];return n.length===3?{r:parseInt(n[0]+n[0],16),g:parseInt(n[1]+n[1],16),b:parseInt(n[2]+n[2],16),a:255}:{r:parseInt(n.slice(0,2),16),g:parseInt(n.slice(2,4),16),b:parseInt(n.slice(4,6),16),a:255}}return{r:144,g:24,b:24,a:255}}};b(Qr,"PostProcessOrderCollector");var be=Qr;var fe=class fe{constructor(e={}){h(this,"mode");h(this,"maxUsers");h(this,"strictMode",!1);h(this,"currentTick",0);h(this,"stats",new ce);h(this,"spriteRegistry",new ue);h(this,"imageFontRegistry",new pe);h(this,"soundRegistry",new me);h(this,"audioOrderCollector",new xe(this.soundRegistry));h(this,"vibrationOrderCollector",new he);h(this,"postProcessOrderCollector",new be);h(this,"encoder",new dt);h(this,"users",new Map);h(this,"colorPalette",new Map);h(this,"paletteSlots",new Map);h(this,"displayRasterizer",new pt(this));h(this,"_renderCallCount",0);h(this,"onPaletteChangedCallback");h(this,"onFontAllocatedCallback");h(this,"onFontBlockAddedCallback");h(this,"onImageFontChangedCallback");this.mode=e.mode??"standalone",this.maxUsers=e.maxUsers??(this.mode==="client"?1:100),this.initializeDefaultPalette(),this.loadFont(8,8,1,8,8)}initializeDefaultPalette(){[{r:0,g:0,b:0},{r:170,g:0,b:0},{r:0,g:170,b:0},{r:170,g:85,b:0},{r:0,g:0,b:170},{r:170,g:0,b:170},{r:0,g:170,b:170},{r:170,g:170,b:170},{r:85,g:85,b:85},{r:255,g:85,b:85},{r:85,g:255,b:85},{r:255,g:255,b:85},{r:85,g:85,b:255},{r:255,g:85,b:255},{r:85,g:255,b:255},{r:255,g:255,b:255}].forEach((t,r)=>this.colorPalette.set(r,{...t,a:255,e:0})),fe.ANSI_VGA_COLORS.forEach(t=>this.colorPalette.set(t.colorId,t)),this.colorPalette.set(255,{r:0,g:0,b:0,a:0,e:0})}isServer(){return this.mode==="server"}isClient(){return this.mode==="client"}isStandalone(){return this.mode==="standalone"}createUser(e,t){if(this.users.has(e))throw new Error(`User with ID ${e} already exists`);if(this.mode==="server"&&this.users.size>=this.maxUsers)throw new Error(`Maximum number of users reached (${this.maxUsers}). Cannot create user ${e}`);if(this.mode==="client"&&this.users.size>=1)throw new Error(`Client mode only allows one user. Cannot create user ${e}`);let r=new ae(e,t,this.mode);return r.setSpriteRegistry(this.spriteRegistry),this.users.set(e,r),r}getUser(e){return this.users.get(e)??null}getUsers(){return Array.from(this.users.values())}hasUser(e){return this.users.has(e)}removeUser(e){return this.users.delete(e)}getUserCount(){return this.users.size}clearAllUsers(){this.users.clear()}setColor(e,t,r,n,o=255,i=0){if(e<0||e>255)throw new Error(`Color ID must be between 0 and 255, got ${e}`);if(e>=240)throw new Error("Color IDs 240-255 are reserved (240-254: UI palette, 255: skip color). Use IDs 0-239 for custom colors.");if(t<0||t>255||r<0||r>255||n<0||n>255||o<0||o>255||i<0||i>255)throw new Error("Color components must be between 0 and 255");this.colorPalette.set(e,{r:t,g:r,b:n,a:o,e:i}),this.onPaletteChangedCallback&&this.onPaletteChangedCallback(this.colorPalette)}onPaletteChanged(e){this.onPaletteChangedCallback=e}getColor(e){return this.colorPalette.get(e)??null}getPalette(){return new Map(this.colorPalette)}resetPalette(){this.colorPalette.clear(),this.initializeDefaultPalette(),this.onPaletteChangedCallback&&this.onPaletteChangedCallback(this.colorPalette)}loadPaletteToSlot(e,t){if(e<0||e>255)throw new Error(`Palette slot ID must be between 0 and 255, got ${e}`);let r=new Map;for(let n of t)n.colorId<0||n.colorId>255||r.set(n.colorId,{r:n.r,g:n.g,b:n.b,a:n.a,e:n.e??0});fe.ANSI_VGA_COLORS.forEach(n=>{r.set(n.colorId,{r:n.r,g:n.g,b:n.b,a:n.a,e:n.e})}),r.set(255,{r:0,g:0,b:0,a:0,e:0}),this.paletteSlots.set(e,r)}getPaletteFromSlot(e){return this.paletteSlots.get(e)??null}hasPaletteSlot(e){return this.paletteSlots.has(e)}clearPaletteSlot(e){this.paletteSlots.delete(e)}clearAllPaletteSlots(){this.paletteSlots.clear()}getColorCSS(e){let t=this.getColor(e);if(!t)return null;let r=t.a/255;return`rgba(${t.r}, ${t.g}, ${t.b}, ${r})`}getUserIds(){return Array.from(this.users.keys())}forEachUser(e){this.users.forEach(e)}filterUsers(e){return this.getUsers().filter(e)}findUser(e){return this.getUsers().find(e)}getCurrentTick(){return this.currentTick}getStats(){return this.stats}endTick(){this.stats.isEnabled()&&this.stats.startTick(this.currentTick);let e=new Map,t=0,r=0;return this.users.forEach((n,o)=>{let i=n.getLayers(),s=n.getDisplays();t+=i.length,n.getStats().isEnabled()&&n.getStats().startTick(this.currentTick);let a=s.map(S=>{let w=S.getOrigin(),I=S.getSize();return{id:S.getId(),originX:w.x,originY:w.y,sizeX:I.x,sizeY:I.y,renderPasses:S.getRenderPasses()}});s.forEach(S=>S.resetChangeTracking());let d=[],l=[];i.forEach((S,w)=>{if(!S.getNeedsCommit())return;let I=S.getOrigin(),U=S.getOrders(),M=S.getMustBeReliable(),P=S.calculateUpdateFlags();S.resetChangeTracking(),S.resetCommit(),S.getId()===0&&te(S,w);let E={id:S.getId(),updateFlags:P,zIndex:S.getZOrder(),originX:I.x,originY:I.y,width:S.getWidth(),height:S.getHeight(),isMacroLayer:S.getIsMacroLayer(),is16bit:S.getCharCodeMode()==="16bit",orderCount:U.length,orders:U};U.length>0&&this.stats.isEnabled()&&this.stats.recordLayerInfo(S.getId(),M,U.length,P),M?d.push(E):l.push(E)}),r+=d.length+l.length;let c=this.audioOrderCollector.collectFromUser(n),u=this.vibrationOrderCollector.collectFromUser(n),p=this.postProcessOrderCollector.collectFromUser(n),m=n.flushMacroOrders(),g=null,y=null;if(this.stats.isEnabled()&&this.stats.recordPacketSplit(o,a.length,d.length,l.length),(d.length>0||c.length>0||m.length>0)&&(g=this.encoder.encode({tick:this.currentTick,displayCount:a.length,displays:a,layerCount:d.length,layers:d,audioOrderCount:c.length,audioOrders:c,vibrationOrderCount:0,vibrationOrders:[],macroOrderCount:m.length,macroOrders:m,postProcessOrderCount:0,postProcessOrders:[]})),y=this.encoder.encode({tick:this.currentTick,displayCount:a.length,displays:a,layerCount:l.length,layers:l,audioOrderCount:0,audioOrders:[],vibrationOrderCount:u.length,vibrationOrders:u,macroOrderCount:0,macroOrders:[],postProcessOrderCount:p.length,postProcessOrders:p}),e.set(o,{static:g,dynamic:y}),n.getStats().isEnabled()){let S=s.reduce((M,P)=>{let E=P.getSize();return M+E.x*E.y},0);n.getStats().recordDisplays(s.length,S),n.getStats().recordLayers(i.length,d.length+l.length,d.length,l.length),[...d,...l].forEach(M=>{n.getStats().recordLayerOrders(M.id,M.orders.length)});let w=g?.length||0,I=y?.length||0;n.getStats().recordPacketSizes(w,I);let U=n.getInputBindingRegistry();n.getStats().recordInput(!1,U.getAxisCount(),U.getButtonCount()),n.getStats().endTick()}if(n.endTickBytes(),this.stats.isEnabled()){let S=[...d,...l];S.forEach((P,E)=>{this.stats.recordLayerOrders(E,P.orders)}),s.forEach((P,E)=>{this.stats.recordDisplayLayers(E,S.length)});let w=(g?.length||0)+(y?.length||0),I=a.reduce((P,E)=>{let v=Math.min(E.renderPasses?.length??0,4);return P+8+v*4},0),U=S.length*20,M=w-I-U;this.stats.recordUpdatePacketSize(w,I,U,M>0?M:0)}}),this.stats.isEnabled()&&(this.stats.recordLayers(t,r),this.stats.endTick()),this.currentTick++,e}getSnapshot(e){let t=this.getUser(e);if(!t)return null;let r=t.getDisplays(),n=t.getLayers(),o=r.map((s,a)=>{let d=s.getOrigin(),l=s.getSize();return{id:a,originX:d.x,originY:d.y,sizeX:l.x,sizeY:l.y,renderPasses:s.getRenderPasses()}}),i=n.map((s,a)=>{let d=s.getOrigin(),l=s.getOrders(),c=7;return s.getId()===0&&te(s,a),{id:s.getId(),updateFlags:c,zIndex:s.getZOrder(),originX:d.x,originY:d.y,width:s.getWidth(),height:s.getHeight(),isMacroLayer:s.getIsMacroLayer(),is16bit:s.getCharCodeMode()==="16bit",orderCount:l.length,orders:l}});return this.encoder.encode({tick:this.currentTick,displayCount:o.length,displays:o,layerCount:i.length,layers:i,audioOrderCount:0,audioOrders:[],vibrationOrderCount:0,vibrationOrders:[],macroOrderCount:0,macroOrders:[],postProcessOrderCount:0,postProcessOrders:[]})}resetTick(){this.currentTick=0}applyUpdatePacket(e,t){let r=this.getUser(e);if(!r){if(this.strictMode)throw new Error(`Cannot apply update packet: user ${e} does not exist`);return!1}return r.applyUpdate(t),t.audioOrders&&t.audioOrders.length>0&&r.applyAudioOrders(t.audioOrders),t.vibrationOrders&&t.vibrationOrders.length>0&&r.applyVibrationOrders(t.vibrationOrders),!0}applyUpdatePacketBuffer(e,t){let{UpdatePacketDecoder:r}=(pn(),K(Wn)),o=new r().decode(t);return this.applyUpdatePacket(e,o)?o:null}applyLoadPacket(e){try{let n=new ut().decode(e).load;switch(n.loadType){case 1:n.slotId!==void 0?this.loadPaletteToSlot(n.slotId,n.colors):(console.warn("[Core] ColorPalette load without slotId is deprecated. Loading into slot 0."),this.loadPaletteToSlot(0,n.colors));break;case 2:this.spriteRegistry.loadUnicolorSprites(n);break;case 3:this.spriteRegistry.loadMulticolorSprites(n);break;case 5:console.warn("[Core] Sound loading not yet implemented");break;case 8:this.loadFont(n.glyphWidth,n.glyphHeight,n.atlasBlocks,n.cellWidth,n.cellHeight);break;case 9:this.loadFontBlock(n.blockIndex,n.imageData);break;case 7:{for(let o of this.users.values())o.loadMacroTemplate(n.macroId,n.template);break}default:return console.error(`[Core] Unknown LoadType: ${n.loadType}`),!1}return!0}catch(t){return console.error("[Core] Failed to apply LoadPacket:",t),!1}}generatePaletteSlotLoadPacket(e){let t=this.getPaletteFromSlot(e);if(!t||t.size===0)return null;let r=new le,n=[];return t.forEach((o,i)=>{i!==255&&n.push({colorId:i,r:o.r,g:o.g,b:o.b,a:o.a,e:o.e})}),r.encode({loadType:1,slotId:e,colors:n})}generateAllPaletteSlotLoadPackets(){let e=[];return this.paletteSlots.forEach((t,r)=>{let n=this.generatePaletteSlotLoadPacket(r);n&&e.push(n)}),e}generateUnicolorSpritesLoadPacket(){let e=this.getSpriteRegistry(),t=[];for(let n=0;n<=255;n++){let o=e.getUnicolorSprite(n);if(o){let i=[];for(let s=0;s<o.sizeX*o.sizeY;s++)i.push(o.data.get(s));t.push({spriteId:o.id,sizeX:o.sizeX,sizeY:o.sizeY,data:i})}}return t.length===0?null:new le().encode({loadType:2,sprites:t})}generateMulticolorSpritesLoadPacket(){let e=this.getSpriteRegistry(),t=[];for(let n=0;n<=255;n++){let o=e.getMulticolorSprite(n);if(o){let i=[];for(let s=0;s<o.sizeX*o.sizeY;s++){let a=o.data.get(s);i.push({charCode:a.charCode,fgColorId:a.fgColorCode,bgColorId:a.bgColorCode})}t.push({spriteId:o.id,sizeX:o.sizeX,sizeY:o.sizeY,data:i})}}return t.length===0?null:new le().encode({loadType:3,sprites:t})}generateAllLoadPackets(){let e=[],t=this.generateAllPaletteSlotLoadPackets();e.push(...t);let r=this.generateUnicolorSpritesLoadPacket();r&&e.push(r);let n=this.generateMulticolorSpritesLoadPacket();return n&&e.push(n),e}generateMacroLoadPackets(e){let t=this.getUser(e);if(!t)return[];let r=t.getMacroLoads();if(r.length===0)return[];let n=new lt;return r.map(o=>n.encode(o))}generateInitialUpdatePacket(e){let t=this.getUser(e);if(!t||!t.hasPostProcessCommands())return null;let r=this.postProcessOrderCollector.collectFromUser(t);if(r.length===0)return null;let o=t.getDisplays().map(s=>{let a=s.getSize();return{id:s.getId(),originX:0,originY:0,sizeX:a.x,sizeY:a.y}});return this.encoder.encode({tick:0,displayCount:o.length,displays:o,layerCount:0,layers:[],audioOrderCount:0,audioOrders:[],vibrationOrderCount:0,vibrationOrders:[],macroOrderCount:0,macroOrders:[],postProcessOrderCount:r.length,postProcessOrders:r})}applyInputBindingsLoadPacket(e,t){let r=this.getUser(e);if(!r){if(this.strictMode)throw new Error(`Cannot apply input bindings: user ${e} does not exist`);return!1}try{return r.applyInputBindingsLoadPacket(t),!0}catch(n){return console.error(`[Core] Failed to apply input bindings for user ${e}:`,n),!1}}getRenderState(e,t){let r=this.getUser(e);if(!r)return null;let n=r.getDisplays(),o=t?r.getLayers().filter(t):r.getLayers(),i=performance.now(),s=[];for(let d of n){if(!d)continue;let l=d.getOrigin(),c=d.getSize();if(s.push(this.displayRasterizer.rasterize({id:d.getId(),x:l.x,y:l.y,width:c.x,height:c.y},o,d.getRenderPasses())),this.stats.isEnabled()){let u=d.getId();this.stats.recordDisplayComposite(u,this.displayRasterizer.getLastVisibleLayerIds())}}let a=performance.now()-i;return this._renderCallCount||(this._renderCallCount=0),this._renderCallCount++,{userId:r.id,userName:r.name,tick:this.currentTick,displays:s}}getAllRenderStates(){let e=new Map;return this.users.forEach((t,r)=>{let n=this.getRenderState(r);n&&e.set(r,n)}),e}enableStats(e){this.stats.setEnabled(e)}getStatsInstance(){return this.stats}resetStats(){this.stats.reset()}loadUnicolorSprites(e){this.spriteRegistry.loadUnicolorSprites(e)}loadMulticolorSprites(e){this.spriteRegistry.loadMulticolorSprites(e)}loadFont(e,t,r,n,o){let i={glyphWidth:e,glyphHeight:t,cellWidth:n,cellHeight:o,atlasBlocks:r};this.imageFontRegistry.hasFont(0)&&this.imageFontRegistry.unloadFont(0),this.imageFontRegistry.loadFont(0,i),this.onFontAllocatedCallback&&this.onFontAllocatedCallback()}loadFontBlock(e,t){if(typeof t=="string")return this.readResource(t).then(r=>{this.imageFontRegistry.addBlock(0,e,r),this.onFontBlockAddedCallback&&this.onFontBlockAddedCallback(e),e===0&&this.onImageFontChangedCallback&&this.onImageFontChangedCallback(0)});this.imageFontRegistry.addBlock(0,e,t),this.onFontBlockAddedCallback&&this.onFontBlockAddedCallback(e),e===0&&this.onImageFontChangedCallback&&this.onImageFontChangedCallback(0)}unloadUnicolorSprite(e){return this.spriteRegistry.unloadUnicolorSprite(e)}unloadMulticolorSprite(e){return this.spriteRegistry.unloadMulticolorSprite(e)}clearUnicolorSprites(){this.spriteRegistry.clearUnicolorSprites()}clearMulticolorSprites(){this.spriteRegistry.clearMulticolorSprites()}clearAllSprites(){this.spriteRegistry.clearAll()}getUnicolorSpriteCount(){return this.spriteRegistry.getUnicolorSpriteCount()}getMulticolorSpriteCount(){return this.spriteRegistry.getMulticolorSpriteCount()}getTotalSpriteCount(){return this.spriteRegistry.getTotalSpriteCount()}hasUnicolorSprite(e){return this.spriteRegistry.hasUnicolorSprite(e)}hasMulticolorSprite(e){return this.spriteRegistry.hasMulticolorSprite(e)}getSpriteRegistry(){return this.spriteRegistry}getSoundRegistry(){return this.soundRegistry}async loadSound(e,t){let r=this.detectSoundFormat(t),n=await this.readResource(t);return this.soundRegistry.registerFile(e,r,n)}async loadSounds(e){let t={},n=Object.entries(e).map(async([o,i])=>{let s=await this.loadSound(o,i);t[o]=s});return await Promise.all(n),t}detectSoundFormat(e){let t=e.split(".").pop()?.toLowerCase()??"",r={mp3:"mp3",wav:"wav",ogg:"ogg",webm:"webm",aac:"aac",m4a:"aac"},n=r[t];if(!n)throw new Error(`Unsupported audio format: .${t}. Supported: ${Object.keys(r).join(", ")}`);return n}async readResource(e){let t=globalThis,r=typeof t.window<"u"||typeof t.document<"u",n=typeof t.fetch=="function",o=/^https?:\/\//i.test(e),i=e.startsWith("file:");if(r)try{let p=await fetch(e);if(!p.ok)throw new Error(`HTTP ${p.status}: ${p.statusText}`);let m=await p.arrayBuffer();return new Uint8Array(m)}catch(p){let m=p instanceof Error?p.message:String(p);throw new Error(`Failed to load resource "${e}": ${m}`)}if((o||i)&&n)try{let p=await fetch(e);if(!p.ok)throw new Error(`HTTP ${p.status}: ${p.statusText}`);let m=await p.arrayBuffer();return new Uint8Array(m)}catch(p){let m=p instanceof Error?p.message:String(p);throw new Error(`Failed to load resource "${e}": ${m}`)}let s=typeof require<"u"?require:null;if(!s)throw new Error("Node.js require is not available");let a="fs",d=s("path"),l=s(a),c=d.resolve(e),u=l.readFileSync(c);return new Uint8Array(u)}registerSound(e,t,r){return this.soundRegistry.registerFile(e,t,r)}registerExternalSound(e,t,r,n){return this.soundRegistry.registerExternal(e,t,r,n)}hasSound(e){return this.soundRegistry.has(e)}generateSoundLoadPackets(){return this.soundRegistry.toLoadPackets()}async loadImageFont(e,t,r){let n=await this.loadImageData(t),o=this.imageFontRegistry.registerFont(e,r);return this.imageFontRegistry.addBlock(0,0,n),this.onFontAllocatedCallback&&this.onFontAllocatedCallback(),this.onFontBlockAddedCallback&&this.onFontBlockAddedCallback(0),this.onImageFontChangedCallback&&this.onImageFontChangedCallback(0),o}async loadImageFonts(e){let t={},n=Object.entries(e).map(async([o,{path:i,options:s}])=>{let a=await this.loadImageFont(o,i,s);t[o]=a});return await Promise.all(n),t}async loadImageData(e){let t=globalThis;if(typeof t.document<"u"||typeof t.window<"u"||typeof t.fetch=="function")try{let n=await fetch(e);if(!n.ok)throw new Error(`HTTP ${n.status}: ${n.statusText}`);let o=await n.arrayBuffer();return new Uint8Array(o)}catch(n){let o=n instanceof Error?n.message:String(n);throw new Error(`Failed to load image font "${e}": ${o}`)}else{let n=typeof require<"u"?require:null;if(!n)throw new Error("Node.js require is not available");let s=n("fs").readFileSync(e);return new Uint8Array(s)}}getImageFontId(e){return this.imageFontRegistry.getFontId(e)}getImageFontByName(e){return this.imageFontRegistry.getFontByName(e)??null}onFontAllocated(e){this.onFontAllocatedCallback=e}onFontBlockAdded(e){this.onFontBlockAddedCallback=e}onImageFontChanged(e){this.onImageFontChangedCallback=e}getImageFontRegistry(){return this.imageFontRegistry}loadImageFontById(e,t){this.imageFontRegistry.loadFont(e,t),this.onImageFontChangedCallback&&this.onImageFontChangedCallback(e)}getImageFont(e){return this.imageFontRegistry.getFont(e)??null}hasImageFont(e){return this.imageFontRegistry.hasFont(e)}hasImageFontByName(e){return this.imageFontRegistry.hasFontByName(e)}unloadImageFont(e){return this.imageFontRegistry.unloadFont(e)}unloadImageFontByName(e){return this.imageFontRegistry.unloadFontByName(e)}clearImageFonts(){this.imageFontRegistry.clearFonts()}getImageFontCount(){return this.imageFontRegistry.getFontCount()}getImageFontIds(){return this.imageFontRegistry.getFontIds()}getImageFontNames(){return this.imageFontRegistry.getFontNames()}};b(fe,"Core"),h(fe,"ANSI_VGA_COLORS",[{colorId:240,r:0,g:0,b:0,a:255,e:0},{colorId:241,r:170,g:0,b:0,a:255,e:0},{colorId:242,r:0,g:170,b:0,a:255,e:0},{colorId:243,r:170,g:85,b:0,a:255,e:0},{colorId:244,r:0,g:0,b:170,a:255,e:0},{colorId:245,r:170,g:0,b:170,a:255,e:0},{colorId:246,r:0,g:170,b:170,a:255,e:0},{colorId:247,r:170,g:170,b:170,a:255,e:0},{colorId:248,r:85,g:85,b:85,a:255,e:0},{colorId:249,r:255,g:85,b:85,a:255,e:0},{colorId:250,r:85,g:255,b:85,a:255,e:0},{colorId:251,r:255,g:255,b:85,a:255,e:0},{colorId:252,r:85,g:85,b:255,a:255,e:0},{colorId:253,r:255,g:85,b:255,a:255,e:0},{colorId:254,r:85,g:255,b:255,a:255,e:0}]);var yt=fe;var eo=require("@utsp/types");var Se=new Map([[0,new Uint8Array([0,0,0,0,0,0,0,0])],[1,new Uint8Array([0,60,102,102,102,60,0,0])],[2,new Uint8Array([0,60,126,126,126,60,0,0])],[3,new Uint8Array([0,108,254,254,124,56,16,0])],[4,new Uint8Array([0,16,56,124,56,16,0,0])],[5,new Uint8Array([0,56,124,56,108,16,56,0])],[6,new Uint8Array([0,16,56,124,124,16,56,0])],[7,new Uint8Array([0,0,24,60,60,24,0,0])],[8,new Uint8Array([255,255,231,195,195,231,255,255])],[9,new Uint8Array([0,60,66,66,66,60,0,0])],[10,new Uint8Array([255,195,189,189,189,195,255,255])],[11,new Uint8Array([0,30,14,26,120,204,120,0])],[12,new Uint8Array([0,60,102,102,60,24,126,24])],[13,new Uint8Array([0,6,14,14,14,124,120,0])],[14,new Uint8Array([0,102,118,126,126,60,24,0])],[15,new Uint8Array([0,153,90,60,60,90,153,0])],[16,new Uint8Array([0,16,48,112,48,16,0,0])],[17,new Uint8Array([0,8,12,14,12,8,0,0])],[18,new Uint8Array([0,24,60,126,24,126,60,24])],[19,new Uint8Array([0,102,102,102,102,0,102,0])],[20,new Uint8Array([0,127,219,219,123,27,27,0])],[21,new Uint8Array([62,99,56,108,108,56,204,120])],[22,new Uint8Array([0,0,0,0,126,126,126,0])],[23,new Uint8Array([0,24,60,126,24,126,60,24])],[24,new Uint8Array([0,24,60,126,255,255,0,0])],[25,new Uint8Array([0,0,255,255,126,60,24,0])],[26,new Uint8Array([0,48,120,252,252,120,48,0])],[27,new Uint8Array([0,12,30,63,63,30,12,0])],[28,new Uint8Array([0,0,24,24,24,126,0,0])],[29,new Uint8Array([0,16,48,127,48,16,0,0])],[30,new Uint8Array([0,0,24,60,126,24,24,0])],[31,new Uint8Array([0,0,24,24,126,60,24,0])],[32,new Uint8Array([0,0,0,0,0,0,0,0])],[33,new Uint8Array([24,24,24,24,24,0,24,0])],[34,new Uint8Array([108,108,108,0,0,0,0,0])],[35,new Uint8Array([54,54,127,54,127,54,54,0])],[36,new Uint8Array([12,63,104,62,11,126,24,0])],[37,new Uint8Array([96,102,12,24,48,102,6,0])],[38,new Uint8Array([56,108,108,56,109,102,59,0])],[39,new Uint8Array([24,24,24,0,0,0,0,0])],[40,new Uint8Array([12,24,48,48,48,24,12,0])],[41,new Uint8Array([48,24,12,12,12,24,48,0])],[42,new Uint8Array([0,102,60,255,60,102,0,0])],[43,new Uint8Array([0,24,24,126,24,24,0,0])],[44,new Uint8Array([0,0,0,0,0,24,24,48])],[45,new Uint8Array([0,0,0,126,0,0,0,0])],[46,new Uint8Array([0,0,0,0,0,24,24,0])],[47,new Uint8Array([0,6,12,24,48,96,0,0])],[48,new Uint8Array([60,102,110,126,118,102,60,0])],[49,new Uint8Array([24,56,24,24,24,24,126,0])],[50,new Uint8Array([60,102,6,12,24,48,126,0])],[51,new Uint8Array([60,102,6,28,6,102,60,0])],[52,new Uint8Array([12,28,60,108,126,12,12,0])],[53,new Uint8Array([126,96,124,6,6,102,60,0])],[54,new Uint8Array([28,48,96,124,102,102,60,0])],[55,new Uint8Array([126,6,12,24,48,48,48,0])],[56,new Uint8Array([60,102,102,60,102,102,60,0])],[57,new Uint8Array([60,102,102,62,6,12,56,0])],[58,new Uint8Array([0,0,24,24,0,24,24,0])],[59,new Uint8Array([0,0,24,24,0,24,24,48])],[60,new Uint8Array([12,24,48,96,48,24,12,0])],[61,new Uint8Array([0,0,126,0,126,0,0,0])],[62,new Uint8Array([48,24,12,6,12,24,48,0])],[63,new Uint8Array([60,102,12,24,24,0,24,0])],[64,new Uint8Array([60,102,110,106,110,96,60,0])],[65,new Uint8Array([60,102,102,126,102,102,102,0])],[66,new Uint8Array([124,102,102,124,102,102,124,0])],[67,new Uint8Array([60,102,96,96,96,102,60,0])],[68,new Uint8Array([120,108,102,102,102,108,120,0])],[69,new Uint8Array([126,96,96,124,96,96,126,0])],[70,new Uint8Array([126,96,96,124,96,96,96,0])],[71,new Uint8Array([60,102,96,110,102,102,60,0])],[72,new Uint8Array([102,102,102,126,102,102,102,0])],[73,new Uint8Array([126,24,24,24,24,24,126,0])],[74,new Uint8Array([62,12,12,12,12,108,56,0])],[75,new Uint8Array([102,108,120,112,120,108,102,0])],[76,new Uint8Array([96,96,96,96,96,96,126,0])],[77,new Uint8Array([99,119,127,107,99,99,99,0])],[78,new Uint8Array([102,102,118,126,110,102,102,0])],[79,new Uint8Array([60,102,102,102,102,102,60,0])],[80,new Uint8Array([124,102,102,124,96,96,96,0])],[81,new Uint8Array([60,102,102,102,106,108,54,0])],[82,new Uint8Array([124,102,102,124,108,102,102,0])],[83,new Uint8Array([60,102,96,60,6,102,60,0])],[84,new Uint8Array([126,24,24,24,24,24,24,0])],[85,new Uint8Array([102,102,102,102,102,102,60,0])],[86,new Uint8Array([102,102,102,102,102,60,24,0])],[87,new Uint8Array([99,99,99,107,127,119,99,0])],[88,new Uint8Array([102,102,60,24,60,102,102,0])],[89,new Uint8Array([102,102,102,60,24,24,24,0])],[90,new Uint8Array([126,6,12,24,48,96,126,0])],[91,new Uint8Array([60,48,48,48,48,48,60,0])],[92,new Uint8Array([0,96,48,24,12,6,0,0])],[93,new Uint8Array([60,12,12,12,12,12,60,0])],[94,new Uint8Array([24,60,102,0,0,0,0,0])],[95,new Uint8Array([0,0,0,0,0,0,255,0])],[96,new Uint8Array([48,24,12,0,0,0,0,0])],[97,new Uint8Array([0,0,60,6,62,102,62,0])],[98,new Uint8Array([96,96,124,102,102,102,124,0])],[99,new Uint8Array([0,0,60,102,96,102,60,0])],[100,new Uint8Array([6,6,62,102,102,102,62,0])],[101,new Uint8Array([0,0,60,102,126,96,60,0])],[102,new Uint8Array([28,54,48,124,48,48,48,0])],[103,new Uint8Array([0,0,62,102,102,62,6,60])],[104,new Uint8Array([96,96,124,102,102,102,102,0])],[105,new Uint8Array([24,0,56,24,24,24,60,0])],[106,new Uint8Array([12,0,28,12,12,12,108,56])],[107,new Uint8Array([96,96,102,108,120,108,102,0])],[108,new Uint8Array([56,24,24,24,24,24,60,0])],[109,new Uint8Array([0,0,102,127,107,107,99,0])],[110,new Uint8Array([0,0,124,102,102,102,102,0])],[111,new Uint8Array([0,0,60,102,102,102,60,0])],[112,new Uint8Array([0,0,124,102,102,124,96,96])],[113,new Uint8Array([0,0,62,102,102,62,6,6])],[114,new Uint8Array([0,0,108,118,96,96,96,0])],[115,new Uint8Array([0,0,62,96,60,6,124,0])],[116,new Uint8Array([48,48,124,48,48,54,28,0])],[117,new Uint8Array([0,0,102,102,102,102,62,0])],[118,new Uint8Array([0,0,102,102,102,60,24,0])],[119,new Uint8Array([0,0,99,107,107,127,54,0])],[120,new Uint8Array([0,0,102,60,24,60,102,0])],[121,new Uint8Array([0,0,102,102,102,62,6,60])],[122,new Uint8Array([0,0,126,12,24,48,126,0])],[123,new Uint8Array([14,24,24,112,24,24,14,0])],[124,new Uint8Array([24,24,24,24,24,24,24,0])],[125,new Uint8Array([112,24,24,14,24,24,112,0])],[126,new Uint8Array([49,107,70,0,0,0,0,0])],[127,new Uint8Array([0,24,60,126,126,24,60,0])],[128,new Uint8Array([60,102,96,96,102,60,24,48])],[129,new Uint8Array([102,0,102,102,102,102,62,0])],[130,new Uint8Array([12,24,60,102,126,96,60,0])],[131,new Uint8Array([24,102,60,6,62,102,62,0])],[132,new Uint8Array([102,0,60,6,62,102,62,0])],[133,new Uint8Array([48,24,60,6,62,102,62,0])],[134,new Uint8Array([24,36,60,6,62,102,62,0])],[135,new Uint8Array([0,0,60,96,96,60,24,48])],[136,new Uint8Array([24,102,60,102,126,96,60,0])],[137,new Uint8Array([102,0,60,102,126,96,60,0])],[138,new Uint8Array([48,24,60,102,126,96,60,0])],[139,new Uint8Array([102,0,24,24,24,24,24,0])],[140,new Uint8Array([24,102,0,24,24,24,24,0])],[141,new Uint8Array([48,24,0,24,24,24,24,0])],[142,new Uint8Array([102,0,60,102,126,102,102,0])],[143,new Uint8Array([24,36,60,102,126,102,102,0])],[144,new Uint8Array([12,24,126,96,124,96,126,0])],[145,new Uint8Array([0,0,110,27,127,216,119,0])],[146,new Uint8Array([63,108,108,127,108,108,111,0])],[147,new Uint8Array([24,102,60,102,102,102,60,0])],[148,new Uint8Array([102,0,60,102,102,102,60,0])],[149,new Uint8Array([48,24,60,102,102,102,60,0])],[150,new Uint8Array([24,102,0,102,102,102,62,0])],[151,new Uint8Array([48,24,0,102,102,102,62,0])],[152,new Uint8Array([102,0,102,102,62,6,60,0])],[153,new Uint8Array([102,0,60,102,102,102,60,0])],[154,new Uint8Array([102,0,102,102,102,102,60,0])],[155,new Uint8Array([0,24,62,96,96,62,24,0])],[156,new Uint8Array([28,54,48,124,48,48,126,0])],[157,new Uint8Array([102,102,60,126,24,126,24,0])],[158,new Uint8Array([124,102,124,98,102,111,102,3])],[159,new Uint8Array([14,27,24,60,24,24,216,112])],[160,new Uint8Array([12,24,60,6,62,102,62,0])],[161,new Uint8Array([12,24,0,24,24,24,24,0])],[162,new Uint8Array([12,24,60,102,102,102,60,0])],[163,new Uint8Array([12,24,0,102,102,102,62,0])],[164,new Uint8Array([54,108,0,124,102,102,102,0])],[165,new Uint8Array([54,108,102,118,126,110,102,0])],[166,new Uint8Array([28,6,30,54,30,0,62,0])],[167,new Uint8Array([28,54,54,54,28,0,62,0])],[168,new Uint8Array([24,0,24,48,96,102,60,0])],[169,new Uint8Array([0,0,0,254,192,192,0,0])],[170,new Uint8Array([0,0,0,254,6,6,0,0])],[171,new Uint8Array([96,224,98,102,108,24,48,110])],[172,new Uint8Array([96,224,98,102,108,24,62,6])],[173,new Uint8Array([24,0,24,24,60,60,24,0])],[174,new Uint8Array([0,0,54,108,216,108,54,0])],[175,new Uint8Array([0,0,216,108,54,108,216,0])],[176,new Uint8Array([34,136,34,136,34,136,34,136])],[177,new Uint8Array([136,34,136,34,136,34,136,34])],[178,new Uint8Array([170,85,170,85,170,85,170,85])],[179,new Uint8Array([24,24,24,24,24,24,24,24])],[180,new Uint8Array([24,24,24,248,24,24,24,24])],[181,new Uint8Array([24,24,24,252,28,24,24,24])],[182,new Uint8Array([54,54,54,246,54,54,54,54])],[183,new Uint8Array([0,0,0,254,54,54,54,54])],[184,new Uint8Array([0,0,0,252,28,24,24,24])],[185,new Uint8Array([54,54,54,252,54,54,54,54])],[186,new Uint8Array([54,54,54,54,54,54,54,54])],[187,new Uint8Array([0,0,0,252,54,54,54,54])],[188,new Uint8Array([54,54,54,252,0,0,0,0])],[189,new Uint8Array([54,54,54,247,0,0,0,0])],[190,new Uint8Array([24,24,24,252,0,0,0,0])],[191,new Uint8Array([0,0,0,248,24,24,24,24])],[192,new Uint8Array([24,24,24,31,0,0,0,0])],[193,new Uint8Array([24,24,24,255,0,0,0,0])],[194,new Uint8Array([0,0,0,255,24,24,24,24])],[195,new Uint8Array([24,24,24,31,24,24,24,24])],[196,new Uint8Array([0,0,0,255,0,0,0,0])],[197,new Uint8Array([24,24,24,255,24,24,24,24])],[198,new Uint8Array([24,24,31,31,24,24,24,24])],[199,new Uint8Array([54,54,55,55,54,54,54,54])],[200,new Uint8Array([54,54,54,63,0,0,0,0])],[201,new Uint8Array([0,0,0,63,54,54,54,54])],[202,new Uint8Array([54,54,54,255,0,0,0,0])],[203,new Uint8Array([0,0,0,255,54,54,54,54])],[204,new Uint8Array([54,54,54,63,54,54,54,54])],[205,new Uint8Array([0,0,0,255,0,255,0,0])],[206,new Uint8Array([54,54,54,255,54,54,54,54])],[207,new Uint8Array([24,24,24,255,0,255,0,0])],[208,new Uint8Array([54,54,54,255,0,0,0,0])],[209,new Uint8Array([0,0,0,255,0,255,24,24])],[210,new Uint8Array([0,0,0,255,54,54,54,54])],[211,new Uint8Array([24,24,24,31,0,31,0,0])],[212,new Uint8Array([54,54,54,62,0,0,0,0])],[213,new Uint8Array([0,0,0,31,0,31,24,24])],[214,new Uint8Array([0,0,0,62,54,54,54,54])],[215,new Uint8Array([24,24,24,255,24,255,24,24])],[216,new Uint8Array([54,54,54,255,54,54,54,54])],[217,new Uint8Array([24,24,24,248,0,0,0,0])],[218,new Uint8Array([0,0,0,31,24,24,24,24])],[219,new Uint8Array([255,255,255,255,255,255,255,255])],[220,new Uint8Array([0,0,0,0,255,255,255,255])],[221,new Uint8Array([240,240,240,240,240,240,240,240])],[222,new Uint8Array([15,15,15,15,15,15,15,15])],[223,new Uint8Array([255,255,255,255,0,0,0,0])],[224,new Uint8Array([0,0,123,207,207,123,0,0])],[225,new Uint8Array([124,102,102,124,102,102,108,96])],[226,new Uint8Array([126,102,96,96,96,96,96,0])],[227,new Uint8Array([0,0,127,54,54,54,54,0])],[228,new Uint8Array([126,96,48,24,48,96,126,0])],[229,new Uint8Array([0,0,63,102,102,102,60,0])],[230,new Uint8Array([0,0,102,102,102,124,96,96])],[231,new Uint8Array([0,0,126,24,24,24,24,0])],[232,new Uint8Array([24,126,219,219,219,126,24,0])],[233,new Uint8Array([60,102,102,126,102,102,60,0])],[234,new Uint8Array([60,102,102,102,60,102,102,0])],[235,new Uint8Array([28,48,24,60,102,102,60,0])],[236,new Uint8Array([0,0,110,219,219,118,0,0])],[237,new Uint8Array([6,12,126,219,219,126,96,192])],[238,new Uint8Array([30,48,96,126,96,48,30,0])],[239,new Uint8Array([60,102,102,102,102,102,0,0])],[240,new Uint8Array([0,126,0,126,0,126,0,0])],[241,new Uint8Array([24,24,126,24,24,0,126,0])],[242,new Uint8Array([48,24,12,24,48,0,126,0])],[243,new Uint8Array([12,24,48,24,12,0,126,0])],[244,new Uint8Array([14,27,27,24,24,24,24,24])],[245,new Uint8Array([24,24,24,24,24,216,216,112])],[246,new Uint8Array([0,24,0,126,0,24,0,0])],[247,new Uint8Array([0,118,220,0,118,220,0,0])],[248,new Uint8Array([56,108,108,56,0,0,0,0])],[249,new Uint8Array([0,0,0,24,24,0,0,0])],[250,new Uint8Array([0,0,0,0,24,0,0,0])],[251,new Uint8Array([15,12,12,12,236,108,60,28])],[252,new Uint8Array([108,54,54,54,54,0,0,0])],[253,new Uint8Array([120,12,24,48,124,0,0,0])],[254,new Uint8Array([0,0,60,60,60,60,0,0])],[255,new Uint8Array([0,0,0,0,0,0,0,0])]]);function jn(x){return Se.get(x)}b(jn,"getCharBitmap");function Jn(x){return Se.has(x)}b(Jn,"hasChar");function qn(){return Array.from(Se.keys()).sort((x,e)=>x-e)}b(qn,"getAllCharCodes");function Kn(){return{charWidth:8,charHeight:8,glyphs:new Map(Se)}}b(Kn,"getASCII8x8FontConfig");V();var mn=class mn{encode(e){switch(e.type){case 1:return this.encodeClick(e);case 2:return this.encodeChange(e);case 3:return this.encodeSubmit(e);case 4:return this.encodeSelect(e);default:throw new Error(`Unknown macro event type: ${e.type}`)}}calculateSize(e){switch(e.type){case 1:return 2;case 2:return this.calculateChangeSize(e);case 3:return this.calculateSubmitSize(e);case 4:return 4;default:throw new Error(`Unknown macro event type: ${e.type}`)}}encodeClick(e){let t=C.allocUnsafe(2);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.toUint8Array()}encodeChange(e){if(typeof e.value=="boolean"){let r=C.allocUnsafe(4);return r.writeUInt8(e.type,0),r.writeUInt8(e.instanceId,1),r.writeUInt8(1,2),r.writeUInt8(e.value?1:0,3),r.toUint8Array()}else{let r=C.allocUnsafe(7);return r.writeUInt8(e.type,0),r.writeUInt8(e.instanceId,1),r.writeUInt8(0,2),r.writeFloatBE(e.value,3),r.toUint8Array()}}calculateChangeSize(e){return typeof e.value=="boolean"?4:7}encodeSubmit(e){let t=new TextEncoder().encode(e.text);if(t.length>65535)throw new Error(`Submit text too large: ${t.length} bytes (max 65535)`);let r=4+t.length,n=C.allocUnsafe(r),o=0;return n.writeUInt8(e.type,o++),n.writeUInt8(e.instanceId,o++),n.writeUInt16BE(t.length,o),o+=2,n.toUint8Array().set(t,o),n.toUint8Array()}calculateSubmitSize(e){return 4+new TextEncoder().encode(e.text).length}encodeSelect(e){let t=C.allocUnsafe(4);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.writeUInt16BE(e.index,2),t.toUint8Array()}};b(mn,"MacroEventEncoder");var Ct=mn;function Qn(x,e,t,r,n,o,i,s=[],a=[],d=[],l=[]){let c=Array.from(e.entries()).sort((k,F)=>k[0]-F[0]),u=Array.from(t.entries()).sort((k,F)=>k[0]-F[0]),p=c.length,m=u.length,g=Ze(p,m),y=new TextEncoder,S=s.map(k=>y.encode(k)),w=1+S.reduce((k,F)=>k+1+F.length,0),I=new Ct,U=a.map(k=>I.encode(k)),M=1+U.reduce((k,F)=>k+F.length,0),P=Math.min(d.length,255),E=1+P*5,v=Math.min(l.length,10),f=1+v*4,L=g+w+M+E+f,O=new Uint8Array(L),z=new DataView(O.buffer),A=0;z.setBigUint64(A,x,!0),A+=8;for(let[,k]of c){let F=Ge(k);O[A]=F+256&255,A+=1}let to=W(m);for(let k=0;k<to;k++){let F=0;for(let Ee=0;Ee<8;Ee++){let bn=k*8+Ee;if(bn<m){let[,ro]=u[bn];ro&&(F|=1<<Ee)}}O[A]=F,A+=1}O[A]=r&255,A+=1,O[A]=n&255,A+=1,O[A]=o&255,A+=1;let hn=0;i&&(hn|=1),O[A]=hn,A+=1,O[A]=Math.min(s.length,255),A+=1;for(let k of S)O[A]=Math.min(k.length,255),A+=1,O.set(k.slice(0,255),A),A+=k.length;O[A]=Math.min(a.length,255),A+=1;for(let k of U)O.set(k,A),A+=k.length;O[A]=P,A+=1;for(let k=0;k<P;k++){let F=d[k];O[A]=F.displayId&255,A+=1,z.setUint16(A,Math.min(F.pixelWidth,65535),!1),A+=2,z.setUint16(A,Math.min(F.pixelHeight,65535),!1),A+=2}O[A]=v,A+=1;for(let k=0;k<v;k++){let F=l[k];O[A]=F.id&15,A+=1,O[A]=F.x&255,A+=1,O[A]=F.y&255,A+=1,O[A]=F.over?1:0,A+=1}return O}b(Qn,"encodeCompressedInput");var B=class B{static toCharCode(e){if(typeof e=="number")return e&65535;if(e.length===0)return 0;let t=e.charCodeAt(0);return j(t)}static dedent(e){let t=e.split(`
13
+ `}),e}};b(yr,"InputBindingRegistry");var ie=yr;function Xe(x=0n){return{tick:x,axes:new Map,buttons:new Map,displayId:0,mouseX:0,mouseY:0,mouseOverDisplay:!1,textInputs:[],macroEvents:[],displayViewports:[],touchPositions:[]}}b(Xe,"createEmptyCompressedInputPacket");function Ge(x){let e=Math.max(-1,Math.min(1,x));return Math.round(e*127)}b(Ge,"encodeAxisToInt8");function $e(x){return x/127}b($e,"decodeInt8ToAxis");function W(x){return x===0?0:Math.ceil(x/8)}b(W,"getButtonByteCount");function Ze(x,e){let r=x,n=W(e);return 8+r+n+4}b(Ze,"getCompressedPacketSize");var Cr=class Cr{decode(e,t=0){let r=e.readUInt8(t);switch(r){case 1:return this.decodeClick(e,t);case 2:return this.decodeChange(e,t);case 3:return this.decodeSubmit(e,t);case 4:return this.decodeSelect(e,t);default:throw new Error(`Unknown macro event type: 0x${r.toString(16)}`)}}decodeAll(e,t,r){let n=[],o=0;for(let i=0;i<r;i++){let{event:s,bytesRead:a}=this.decode(e,t+o);n.push(s),o+=a}return{events:n,bytesRead:o}}decodeClick(e,t){let r=e.readUInt8(t),n=e.readUInt8(t+1);return{event:{type:r,instanceId:n},bytesRead:2}}decodeChange(e,t){let r=e.readUInt8(t),n=e.readUInt8(t+1),o=e.readUInt8(t+2),i,s;return o===1?(i=e.readUInt8(t+3)===1,s=4):(i=e.readFloatBE(t+3),s=7),{event:{type:r,instanceId:n,value:i},bytesRead:s}}decodeSubmit(e,t){let r=t,n=e.readUInt8(t++),o=e.readUInt8(t++),i=e.readUInt16BE(t);t+=2;let s=e.toUint8Array().subarray(t,t+i);t+=i;let a=new TextDecoder().decode(s);return{event:{type:n,instanceId:o,text:a},bytesRead:t-r}}decodeSelect(e,t){let r=e.readUInt8(t),n=e.readUInt8(t+1),o=e.readUInt16BE(t+2);return{event:{type:r,instanceId:n,index:o},bytesRead:4}}};b(Cr,"MacroEventDecoder");var We=Cr;V();function je(x,e){let t=e.getAllAxes().length,r=e.getAllButtons().length,n=W(r),o=8+t+n+4;if(x.length<o)throw new Error(`Invalid compressed input packet: expected at least ${o} bytes (${t} axes + ${r} buttons), got ${x.length}`);let i=new DataView(x.buffer,x.byteOffset,x.byteLength),s=0,a=Xe();a.tick=i.getBigUint64(s,!0),s+=8;for(let l=0;l<t;l++){let c=x[s],u=c>127?c-256:c,p=$e(u);a.axes.set(l,p),s+=1}for(let l=0;l<n;l++){let c=x[s];for(let u=0;u<8;u++){let p=l*8+u;if(p<r){let m=(c&1<<u)!==0;a.buttons.set(p,m)}}s+=1}a.displayId=x[s],s+=1,a.mouseX=x[s],s+=1,a.mouseY=x[s],s+=1;let d=x[s];if(a.mouseOverDisplay=(d&1)!==0,s+=1,s<x.length){let l=x[s];s+=1;let c=new TextDecoder;a.textInputs=[];for(let u=0;u<l&&s<x.length;u++){let p=x[s];if(s+=1,s+p<=x.length){let m=x.slice(s,s+p),g=c.decode(m);a.textInputs.push(g),s+=p}}}if(s<x.length){let l=x[s];s+=1;let c=new We,u=[],p=C.from(x);for(let m=0;m<l&&s<x.length;m++){let g=c.decode(p,s);u.push(g.event),s+=g.bytesRead}a.macroEvents=u}if(s<x.length){let l=x[s];s+=1;for(let c=0;c<l&&s+5<=x.length;c++){let u=x[s];s+=1;let p=i.getUint16(s,!1);s+=2;let m=i.getUint16(s,!1);s+=2,a.displayViewports.push({displayId:u,pixelWidth:p,pixelHeight:m})}}if(s<x.length){let l=Math.min(x[s],10);s+=1;for(let c=0;c<l&&s+4<=x.length;c++){let u=x[s]&15;s+=1;let p=x[s];s+=1;let m=x[s];s+=1;let y=(x[s]&1)!==0;s+=1,a.touchPositions.push({id:u,x:p,y:m,over:y})}}return a}b(je,"decodeCompressedInput");var T=require("@utsp/types");var fr=class fr{constructor(e,t){h(this,"enabled",!1);h(this,"currentStats",null);h(this,"_userId");h(this,"_userName");this._userId=e,this._userName=t}setEnabled(e){this.enabled=e,e||(this.currentStats=null)}isEnabled(){return this.enabled}get userId(){return this.currentStats?.userId??this._userId}get userName(){return this.currentStats?.userName??this._userName}get tick(){return this.currentStats?.tick??0}get timestamp(){return this.currentStats?.timestamp??0}get displayCount(){return this.currentStats?.displayCount??0}get totalDisplayArea(){return this.currentStats?.totalDisplayArea??0}get totalLayers(){return this.currentStats?.totalLayers??0}get visibleLayers(){return this.currentStats?.visibleLayers??0}get staticLayers(){return this.currentStats?.staticLayers??0}get dynamicLayers(){return this.currentStats?.dynamicLayers??0}get totalOrders(){return this.currentStats?.totalOrders??0}get ordersByLayer(){return this.currentStats?.ordersByLayer??new Map}get staticPacketSize(){return this.currentStats?.staticPacketSize??0}get dynamicPacketSize(){return this.currentStats?.dynamicPacketSize??0}get totalPacketSize(){return this.currentStats?.totalPacketSize??0}get compressedPacketSize(){return Math.round(this.totalPacketSize*.25)}get hasInput(){return this.currentStats?.hasInput??!1}get axisCount(){return this.currentStats?.axisCount??0}get buttonCount(){return this.currentStats?.buttonCount??0}startTick(e){this.enabled&&(this.currentStats={userId:this._userId,userName:this._userName,tick:e,timestamp:Date.now(),displayCount:0,totalDisplayArea:0,totalLayers:0,visibleLayers:0,staticLayers:0,dynamicLayers:0,totalOrders:0,ordersByLayer:new Map,staticPacketSize:0,dynamicPacketSize:0,totalPacketSize:0,hasInput:!1,axisCount:0,buttonCount:0})}recordDisplays(e,t){!this.enabled||!this.currentStats||(this.currentStats.displayCount=e,this.currentStats.totalDisplayArea=t)}recordLayers(e,t,r,n){!this.enabled||!this.currentStats||(this.currentStats.totalLayers=e,this.currentStats.visibleLayers=t,this.currentStats.staticLayers=r,this.currentStats.dynamicLayers=n)}recordLayerOrders(e,t){!this.enabled||!this.currentStats||(this.currentStats.totalOrders+=t,this.currentStats.ordersByLayer.set(e,t))}recordPacketSizes(e,t){!this.enabled||!this.currentStats||(this.currentStats.staticPacketSize=e,this.currentStats.dynamicPacketSize=t,this.currentStats.totalPacketSize=e+t)}recordInput(e,t,r){!this.enabled||!this.currentStats||(this.currentStats.hasInput=e,this.currentStats.axisCount=t,this.currentStats.buttonCount=r)}endTick(){}reset(){this.currentStats=null}};b(fr,"UserStats");var se=fr;var Mr=class Mr{constructor(e,t,r){this.id=e;this.name=t;h(this,"displays",[]);h(this,"layers",[]);h(this,"spriteRegistry");h(this,"mode");h(this,"axes",new Map);h(this,"buttons",new Map);h(this,"textInputs",[]);h(this,"mouseX",0);h(this,"mouseY",0);h(this,"mouseOver",!1);h(this,"mouseDisplayId",0);h(this,"touchPositions",new Map);h(this,"activeTouchId",null);h(this,"inputBindings",new ie);h(this,"stats");h(this,"soundCommands",[]);h(this,"nextSoundInstanceId",1);h(this,"audioConfigCommands",[]);h(this,"lastListenerX",-1);h(this,"lastListenerY",-1);h(this,"pendingSendSounds",!1);h(this,"audioProcessor");h(this,"loadedSounds",new Map);h(this,"soundLoadErrors",new Map);h(this,"playingSounds",new Map);h(this,"mobileVibrationCommands",[]);h(this,"mobileVibrationProcessor");h(this,"gamepadVibrationCommands",[]);h(this,"gamepadVibrationProcessor");h(this,"macroRegistry",new re);h(this,"macroEngine",new oe);h(this,"macroEventHandlers",new Map);h(this,"postProcessCommands",[]);h(this,"currentPostProcessConfig",null);h(this,"bridgeMessages",[]);h(this,"totalBytesSent",0);h(this,"totalBytesReceived",0);h(this,"bytesSentPerTick",[]);h(this,"bytesReceivedPerTick",[]);h(this,"bytesTickIndex",0);h(this,"bytesTickRate",20);h(this,"currentTickBytesSent",0);h(this,"currentTickBytesReceived",0);h(this,"availableViewports",new Map);h(this,"displayCommandSink",{setPostProcess:(e,t)=>this.setPostProcess(e,t),setScanlinesEnabled:(e,t)=>this.setScanlinesEnabled(e,t),setScanlinesOpacity:(e,t)=>this.setScanlinesOpacity(e,t),setScanlinesPattern:(e,t)=>this.setScanlinesPattern(e,t),setAmbientEffect:(e,t)=>this.setAmbientEffect(e,t),setAmbientEffectEnabled:(e,t)=>this.setAmbientEffectEnabled(e,t),setAmbientEffectBlur:(e,t)=>this.setAmbientEffectBlur(e,t),setAmbientEffectScale:(e,t)=>this.setAmbientEffectScale(e,t),isAmbientEffectEnabled:()=>this.isAmbientEffectEnabled(),getAmbientEffectConfig:()=>this.getAmbientEffectConfig(),getPostProcessConfig:()=>this.getPostProcessConfig(),setScalingMode:(e,t)=>this.setScalingMode(e,t),getScalingMode:e=>this.getScalingMode(e),setCellSize:(e,t,r)=>this.setCellSize(e,t,r),getCellSize:e=>this.getCellSize(e),setGrid:(e,t)=>this.setGrid(e,t),setGridEnabled:(e,t)=>this.setGridEnabled(e,t),isGridEnabled:e=>this.isGridEnabled(e),getGridConfig:e=>this.getGridConfig(e),switchPalette:(e,t)=>this.switchPalette(e,t),getCurrentPaletteSlotId:e=>this.getCurrentPaletteSlotId(e)});h(this,"data");h(this,"currentScalingModes",new Map);h(this,"currentCellSizes",new Map);h(this,"currentGridConfigs",new Map);h(this,"currentPaletteSlotIds",new Map);this.mode=r,this.stats=new se(e,t),this.data={}}setSpriteRegistry(e){this.spriteRegistry=e;for(let t of this.layers)t.setSpriteRegistry(e);this.macroEngine.setSpriteRegistry(e)}getDisplays(){return this.displays}addDisplay(e){e.setCommandSink(this.displayCommandSink),this.displays.push(e)}removeDisplay(e){let t=this.displays.indexOf(e);return t!==-1?(this.displays.splice(t,1),!0):!1}clearDisplays(){this.displays=[]}setDisplayViewport(e,t,r){this.availableViewports.set(e,{pixelWidth:t,pixelHeight:r})}getDisplayViewport(e){return this.availableViewports.get(e)??null}getAllDisplayViewports(){return this.availableViewports}calculateMaxCells(e,t,r){let n=this.availableViewports.get(e);return n?{cols:Math.floor(n.pixelWidth/t),rows:Math.floor(n.pixelHeight/r)}:null}getLayers(){return this.layers}getLayerById(e){return this.layers.find(t=>t.getId()===e)}addLayer(e,t){e.setMode(this.mode);let r=this.layers.length+1;te(e,r),this.layers.push(e),this.spriteRegistry&&e.setSpriteRegistry(this.spriteRegistry),t&&this.macroRegistry.setLayerMapping(t,e.getId())}removeLayer(e){let t=this.layers.indexOf(e);return t!==-1?(this.layers.splice(t,1),!0):!1}clearLayers(){this.layers=[]}setMousePosition(e,t,r=!0){this.mouseX=Math.max(0,Math.min(255,e)),this.mouseY=Math.max(0,Math.min(255,t)),this.mouseOver=r}setTouchPosition(e,t,r,n=!0,o=0){if(e<0||e>9){console.warn(`Invalid touchId ${e}, must be 0-9`);return}n?(this.touchPositions.set(e,{x:Math.max(0,Math.min(255,t)),y:Math.max(0,Math.min(255,r)),over:!0,displayId:o}),this.activeTouchId=e):(this.touchPositions.delete(e),this.activeTouchId===e&&(this.activeTouchId=null))}setAxis(e,t){let r=Math.max(-1,Math.min(1,t));this.axes.set(e,r)}getAxis(e){return this.axes.get(e)??0}setButton(e,t){this.buttons.set(e,t)}getButton(e){return this.buttons.get(e)??!1}getButtonJustPressed(e){let t=`${e}_justPressed`;return this.buttons.get(t)??!1}getButtonJustReleased(e){let t=`${e}_justReleased`;return this.buttons.get(t)??!1}setTextInputs(e){this.textInputs=e}getTextInputs(){return this.textInputs}clearTextInputs(){this.textInputs=[]}getAxisNames(){return Array.from(this.axes.keys())}getButtonNames(){return Array.from(this.buttons.keys())}clearAxes(){this.axes.clear()}clearButtons(){this.buttons.clear()}getMouseDisplayInfo(){if(!this.mouseOver||this.displays.length===0)return null;let e=this.displays[0],t=0,r=this.mouseX,n=this.mouseY,o=e.getOrigin(),i=o.x+r,s=o.y+n;return{displayId:t,localX:r,localY:n,worldX:i,worldY:s}}getTouchDisplayInfo(e=0){if(e<0||e>9)return console.warn(`Invalid touchId ${e}, must be 0-9`),null;let t=this.touchPositions.get(e);if(!t||!t.over||this.displays.length===0)return null;let r=this.displays[0],n=t.displayId,o=t.x,i=t.y,s=r.getOrigin(),a=s.x+o,d=s.y+i;return{displayId:n,localX:o,localY:i,worldX:a,worldY:d}}getIsMouseOnADisplay(){return this.mouseOver}getMouseDisplayHover(){let e=this.getMouseDisplayInfo();return e?e.displayId:null}findLayerById(e){return this.layers.find(t=>t.getId()===e)??null}applyUpdate(e){if(this.updateDisplaysFromPacket(e.displays),this.updateLayersFromPacket(e.layers),e.macroOrders&&e.macroOrders.length>0)for(let t of e.macroOrders)this.macroEngine.applyOrder(t)}updateDisplaysFromPacket(e){for(let t of e){let r=this.displays[t.id];if(!r){for(r=new Q(t.id,t.sizeX,t.sizeY);this.displays.length<=t.id;)this.displays.push(null);this.displays[t.id]=r}r.setCommandSink(this.displayCommandSink),r.setOrigin(new T.Vector2(t.originX,t.originY)),r.setSize(new T.Vector2(t.sizeX,t.sizeY)),r.setRenderPasses(t.renderPasses)}}updateLayersFromPacket(e){for(let t of e){let r=this.findLayerById(t.id);r||(r=new ee(new T.Vector2(t.originX,t.originY),t.zIndex,t.width,t.height,{mustBeReliable:!1,isMacroLayer:t.isMacroLayer,charCodeMode:t.is16bit?"16bit":"8bit"}),te(r,t.id),r.setMode(this.mode),this.spriteRegistry&&r.setSpriteRegistry(this.spriteRegistry),this.addLayer(r)),t.updateFlags&1&&r.setOrigin(new T.Vector2(t.originX,t.originY)),t.updateFlags&2&&r.setZOrder(t.zIndex),t.updateFlags&4&&r.setOrders(t.orders)}}defineAxisBinding(e,t,r=[],n=-1,o=1,i=0){this.inputBindings.defineAxis(e,t,r,n,o,i)}defineButtonBinding(e,t,r=[],n=!1){this.inputBindings.defineButton(e,t,r,n)}defineAxisBindings(e){e.forEach(({bindingId:t,name:r,sources:n,min:o,max:i,defaultValue:s})=>{this.defineAxisBinding(t,r,n??[],o,i,s)})}defineButtonBindings(e){e.forEach(({bindingId:t,name:r,sources:n,defaultValue:o})=>{this.defineButtonBinding(t,r,n??[],o)})}getInputBindingsLoadPacket(){return this.inputBindings.toLoadPacket()}applyInputBindingsLoadPacket(e){try{let t=JSON.parse(e);if(t.type!=="input-binding")throw new Error(`Invalid packet type: ${t.type}`);this.inputBindings.clear();for(let r of t.axes)this.defineAxisBinding(r.bindingId,r.name,r.sources||[],r.min,r.max,r.defaultValue);for(let r of t.buttons)this.defineButtonBinding(r.bindingId,r.name,r.sources||[],r.defaultValue)}catch(t){throw console.error("[User] Failed to apply input bindings:",t),t}}getInputBindingRegistry(){return this.inputBindings}getStats(){return this.stats}getTotalBytesSent(){return this.totalBytesSent}getTotalBytesReceived(){return this.totalBytesReceived}recordBytesSent(e){this.totalBytesSent+=e,this.currentTickBytesSent+=e}recordBytesReceived(e){this.totalBytesReceived+=e,this.currentTickBytesReceived+=e}resetByteCounters(){this.totalBytesSent=0,this.totalBytesReceived=0}setBytesTickRate(e){e<=0||(this.bytesTickRate=e,this.bytesSentPerTick=new Array(e).fill(0),this.bytesReceivedPerTick=new Array(e).fill(0),this.bytesTickIndex=0)}endTickBytes(){this.bytesSentPerTick.length!==this.bytesTickRate&&(this.bytesSentPerTick=new Array(this.bytesTickRate).fill(0),this.bytesReceivedPerTick=new Array(this.bytesTickRate).fill(0)),this.bytesSentPerTick[this.bytesTickIndex]=this.currentTickBytesSent,this.bytesReceivedPerTick[this.bytesTickIndex]=this.currentTickBytesReceived,this.bytesTickIndex=(this.bytesTickIndex+1)%this.bytesTickRate,this.currentTickBytesSent=0,this.currentTickBytesReceived=0}getBytesSentPerSecond(){return this.bytesSentPerTick.reduce((e,t)=>e+t,0)}getBytesReceivedPerSecond(){return this.bytesReceivedPerTick.reduce((e,t)=>e+t,0)}getAxisBindingId(e){return this.inputBindings.getAxisBindingId(e)}getButtonBindingId(e){return this.inputBindings.getButtonBindingId(e)}decodeAndApplyCompressedInput(e){let t=je(e,this.inputBindings),r=this.inputBindings.getAllAxes(),n=this.inputBindings.getAllButtons(),o=r.sort((s,a)=>s.bindingId-a.bindingId),i=n.sort((s,a)=>s.bindingId-a.bindingId);for(let[s,a]of t.axes)if(s<o.length){let d=o[s];this.setAxis(d.name,a)}for(let[s,a]of t.buttons)if(s<i.length){let d=i[s],l=this.getButton(d.name);this.setButton(d.name,a);let c=a&&!l,u=!a&&l;this.setButton(`${d.name}_justPressed`,c),this.setButton(`${d.name}_justReleased`,u)}this.mouseX=t.mouseX,this.mouseY=t.mouseY,this.mouseOver=t.mouseOverDisplay,this.mouseDisplayId=t.displayId;for(let s of t.touchPositions)this.setTouchPosition(s.id,s.x,s.y,s.over);for(let s of t.displayViewports)this.setDisplayViewport(s.displayId,s.pixelWidth,s.pixelHeight)}playSound(e,t){let r=this.nextSoundInstanceId++,n={sound:e,instanceId:r,volume:t?.volume,pitch:t?.pitch,loop:t?.loop,fadeIn:t?.fadeIn,x:t?.x,y:t?.y,lowpass:t?.lowpass,highpass:t?.highpass,reverb:t?.reverb};return this.soundCommands.push(n),r}stopSound(e){let t={sound:e};this.soundCommands.push(t)}fadeOutSound(e,t){let r={fadeOut:!0,sound:e,duration:t};this.soundCommands.push(r)}fadeOutAllSounds(e){let t={fadeOut:!0,sound:"all",duration:e};this.soundCommands.push(t)}stopAllSounds(){let e={sound:"all"};this.soundCommands.push(e)}pauseSound(e){let t={pause:!0,sound:e};this.soundCommands.push(t)}pauseAllSounds(){let e={pause:!0,sound:"all"};this.soundCommands.push(e)}resumeSound(e){let t={resume:!0,sound:e};this.soundCommands.push(t)}resumeAllSounds(){let e={resume:!0,sound:"all"};this.soundCommands.push(e)}setSoundEffects(e,t){let r={setEffects:!0,instanceId:e,lowpass:t.lowpass,highpass:t.highpass,reverb:t.reverb};this.soundCommands.push(r)}setListenerPosition(e,t){e===this.lastListenerX&&t===this.lastListenerY||(this.lastListenerX=e,this.lastListenerY=t,this.audioConfigCommands.push({type:"set-listener-position",x:e,y:t}))}configureSpatialAudio(e){this.audioConfigCommands.push({type:"configure-spatial",...e})}flushAudioConfigCommands(){let e=this.audioConfigCommands;return this.audioConfigCommands=[],e}hasAudioConfigCommands(){return this.audioConfigCommands.length>0}flushSoundCommands(){let e=this.soundCommands;return this.soundCommands=[],e}hasSoundCommands(){return this.soundCommands.length>0}sendSounds(){this.pendingSendSounds=!0}needsSendSounds(){return this.pendingSendSounds}clearSendSounds(){this.pendingSendSounds=!1}setAudioProcessor(e){this.audioProcessor=e,this.macroEngine.setAudioCallback(t=>{e.play(t)})}getAudioProcessor(){return this.audioProcessor}applyAudioCommands(e){if(this.audioProcessor&&this.mode!=="server")for(let t of e){if("setEffects"in t&&t.setEffects===!0){let n=t;this.audioProcessor.setEffects(n.instanceId,n.lowpass,n.highpass,n.reverb);continue}if("fadeOut"in t&&t.fadeOut===!0){let n=t;this.audioProcessor.fadeOut(n.sound,n.duration);continue}if("pause"in t&&t.pause===!0){let n=t;this.audioProcessor.pause(n.sound);continue}if("resume"in t&&t.resume===!0){let n=t;this.audioProcessor.resume(n.sound);continue}if("instanceId"in t||"volume"in t||"pitch"in t||"loop"in t||"fadeIn"in t||"x"in t||"y"in t||"lowpass"in t||"highpass"in t||"reverb"in t){let n=t,o=n.x!==void 0&&n.y!==void 0?{x:n.x,y:n.y}:void 0;this.audioProcessor.play(n.sound,{volume:n.volume,pitch:n.pitch,loop:n.loop,fadeIn:n.fadeIn,position:o,instanceId:n.instanceId,lowpass:n.lowpass,highpass:n.highpass,reverb:n.reverb})}else{let n=t;n.sound==="all"?this.audioProcessor.stopAll():this.audioProcessor.stop(n.sound)}}}applyAudioConfigCommands(e){if(this.audioProcessor&&this.mode!=="server")for(let t of e)t.type==="set-listener-position"?this.audioProcessor.setListenerPosition(t.x,t.y):t.type==="configure-spatial"&&this.audioProcessor.configureSpatial({maxDistance:t.maxDistance,referenceDistance:t.referenceDistance,rolloffFactor:t.rolloffFactor,panSpread:t.panSpread})}vibrate(e){let t={pattern:e};this.mobileVibrationCommands.push(t)}cancelVibration(){let e={cancel:!0};this.mobileVibrationCommands.push(e)}vibrateTap(){this.vibrate(10)}vibrateMediumTap(){this.vibrate(25)}vibrateHeavyTap(){this.vibrate(50)}vibrateSuccess(){this.vibrate([30,50,30])}vibrateError(){this.vibrate([50,30,50,30,50])}vibrateWarning(){this.vibrate([100])}vibrateSelection(){this.vibrate(5)}vibrateImpact(e="medium"){let t={light:15,medium:30,heavy:50};this.vibrate(t[e])}vibrateNotification(){this.vibrate([100,100,100,100,100])}vibrateGamepad(e,t){let r={gamepadIndex:e,options:t};this.gamepadVibrationCommands.push(r)}stopGamepadVibration(e="all"){let t={gamepadIndex:e,cancel:!0};this.gamepadVibrationCommands.push(t)}gamepadTap(e=0){this.vibrateGamepad(e,{duration:50,strongMagnitude:.3,weakMagnitude:.5})}gamepadImpact(e=0){this.vibrateGamepad(e,{duration:100,strongMagnitude:.7,weakMagnitude:.3})}gamepadHeavy(e=0){this.vibrateGamepad(e,{duration:200,strongMagnitude:1,weakMagnitude:.2})}gamepadExplosion(e=0){this.vibrateGamepad(e,{duration:400,strongMagnitude:1,weakMagnitude:.8})}gamepadSuccess(e=0){this.vibrateGamepad(e,{duration:150,strongMagnitude:.4,weakMagnitude:.6})}gamepadError(e=0){this.vibrateGamepad(e,{duration:300,strongMagnitude:.8,weakMagnitude:.4})}hasGamepadVibrationCommands(){return this.gamepadVibrationCommands.length>0}flushGamepadVibrationCommands(){let e=this.gamepadVibrationCommands;return this.gamepadVibrationCommands=[],e}setGamepadVibrationProcessor(e){this.gamepadVibrationProcessor=e}applyGamepadVibrationCommands(e){if(this.gamepadVibrationProcessor&&this.mode!=="server"){for(let t of e)if("cancel"in t&&t.cancel===!0)t.gamepadIndex==="all"?this.gamepadVibrationProcessor.stopAllVibrations():this.gamepadVibrationProcessor.stopVibration(t.gamepadIndex);else if("options"in t){let r=t;if(r.gamepadIndex==="all")for(let n=0;n<4;n++)this.gamepadVibrationProcessor.vibrate(n,r.options);else this.gamepadVibrationProcessor.vibrate(r.gamepadIndex,r.options)}}}hasMobileVibrationCommands(){return this.mobileVibrationCommands.length>0}flushMobileVibrationCommands(){let e=this.mobileVibrationCommands;return this.mobileVibrationCommands=[],e}setMobileVibrationProcessor(e){this.mobileVibrationProcessor=e}getMobileVibrationProcessor(){return this.mobileVibrationProcessor}applyMobileVibrationCommands(e){if(this.mobileVibrationProcessor&&this.mode!=="server")for(let t of e)"cancel"in t&&t.cancel===!0?this.mobileVibrationProcessor.cancel():"pattern"in t&&this.mobileVibrationProcessor.vibrate(t.pattern)}applyVibrationOrders(e){if(this.mode==="server")return;let{VibrationOrderType:t}=(Sr(),K(An)),{MobileVibrateFlags:r,GamepadVibrateFlags:n}=(Ir(),K(En));for(let o of e)switch(o.type){case t.MobileVibrate:{if(!this.mobileVibrationProcessor)break;let i=o,s=i.pattern;i.flags&r.HasIntensity&&i.intensity!==void 0&&(s=s.map(a=>Math.round(a*i.intensity))),this.mobileVibrationProcessor.vibrate(s);break}case t.MobileCancel:{if(!this.mobileVibrationProcessor)break;this.mobileVibrationProcessor.cancel();break}case t.GamepadVibrate:{if(!this.gamepadVibrationProcessor)break;let i=o,s={duration:i.duration,strongMagnitude:i.strongMagnitude/255,weakMagnitude:i.weakMagnitude/255,startDelay:i.startDelay};if(i.flags&n.AllGamepads)for(let a=0;a<4;a++)this.gamepadVibrationProcessor.vibrate(a,s);else this.gamepadVibrationProcessor.vibrate(i.gamepadIndex,s);break}case t.GamepadCancel:{if(!this.gamepadVibrationProcessor)break;let i=o;i.flags&n.AllGamepads?this.gamepadVibrationProcessor.stopAllVibrations():this.gamepadVibrationProcessor.stopVibration(i.gamepadIndex);break}}}applyAudioOrders(e){if(!this.audioProcessor||this.mode==="server")return;let{AudioOrderType:t,AudioTargetType:r}=(Ur(),K(Pn)),{PlaySoundFlags:n}=(vr(),K(Rn));for(let o of e)switch(o.type){case t.PlaySound:case t.PlayGlobalSound:{let i=o,s=i.volume!==void 0?i.volume/255:void 0,a=i.pitch!==void 0?.25*Math.pow(2,i.pitch/64):void 0,d=i.fadeIn!==void 0?i.fadeIn/10:void 0,l=(i.flags&n.Loop)!==0,c=i.posX!==void 0&&i.posY!==void 0?{x:i.posX,y:i.posY}:void 0;this.audioProcessor.play(i.soundId,{volume:s,pitch:a,loop:l,fadeIn:d,position:c,instanceId:i.instanceId,lowpass:i.lowpass,highpass:i.highpass,reverb:i.reverb});break}case t.StopSound:{let i=o;i.targetType===r.All?this.audioProcessor.stopAll():i.targetType===r.InstanceId?this.audioProcessor.stop(i.target):this.audioProcessor.stop(i.target);break}case t.FadeOutSound:{let i=o,s=i.duration/10;i.targetType===r.All?this.audioProcessor.fadeOut("all",s):this.audioProcessor.fadeOut(i.target,s);break}case t.PauseSound:{let i=o;i.targetType===r.All?this.audioProcessor.pause("all"):this.audioProcessor.pause(i.target);break}case t.ResumeSound:{let i=o;i.targetType===r.All?this.audioProcessor.resume("all"):this.audioProcessor.resume(i.target);break}case t.SetListenerPosition:{let i=o;this.audioProcessor.setListenerPosition(i.x,i.y);break}case t.ConfigureSpatial:{let i=o;this.audioProcessor.configureSpatial({maxDistance:i.maxDistance*100,referenceDistance:i.referenceDistance*100,rolloffFactor:i.rolloffFactor/100,panSpread:i.panSpread/255});break}case t.SetSoundEffects:{let i=o;this.audioProcessor.setEffects(i.instanceId,i.lowpass,i.highpass,i.reverb);break}}}handleAudioAck(e){switch(e.type){case"sound-loaded":this.loadedSounds.set(e.soundId,{name:e.name,loadedAt:Date.now()}),this.soundLoadErrors.delete(e.soundId);break;case"sound-error":this.soundLoadErrors.set(e.soundId,{name:e.name,error:e.error,at:Date.now()});break;case"playback-started":this.playingSounds.set(e.instanceId,{soundId:e.soundId,startedAt:Date.now()});break;case"playback-ended":this.playingSounds.delete(e.instanceId);break;case"playback-error":e.instanceId!==void 0&&this.playingSounds.delete(e.instanceId);break}}isSoundLoaded(e){return this.loadedSounds.has(e)}getSoundLoadError(e){return this.soundLoadErrors.get(e)?.error}getLoadedSounds(){return this.loadedSounds}getSoundLoadErrors(){return this.soundLoadErrors}isSoundPlaying(e){return this.playingSounds.has(e)}getPlayingSounds(){return this.playingSounds}getPlayingSoundCount(){return this.playingSounds.size}getAudioLoadingState(e){let t=this.loadedSounds.size,r=this.soundLoadErrors.size,n=e>0&&t>=e,o=Array.from(this.soundLoadErrors.values()).map(i=>i.name);return{loadedCount:t,totalExpected:e,errorCount:r,isComplete:n,errors:o}}loadMacro(e,t){let r={...t,id:e},n=this.macroRegistry.registerMacro(r);return this.mode==="client"&&this.macroEngine.loadTemplate(n,r),n}createInstance(e){return this.updateLayerMappings(),this.macroRegistry.createInstance(e)}updateInstance(e,t){return this.macroRegistry.updateInstance(e,t)}removeInstance(e){return this.macroEventHandlers.delete(e),this.macroRegistry.removeInstance(e)}onMacroEvent(e,t,r){this.macroEventHandlers.has(e)||this.macroEventHandlers.set(e,new Map),this.macroEventHandlers.get(e).set(t,r)}offMacroEvent(e,t){t?this.macroEventHandlers.get(e)?.delete(t):this.macroEventHandlers.delete(e)}handleMacroEvent(e){let t=this.macroRegistry.getInstanceName(e.instanceId);if(!t){console.warn(`MacroEvent: Unknown instance ID ${e.instanceId}`);return}let r=this.macroEventHandlers.get(t);if(!r)return;let n,o;switch(e.type){case 1:n="click",o=void 0;break;case 2:n="change",o=e.value;break;case 3:n="submit",o=e.text;break;case 4:n="select",o=e.index;break;default:return}let i=r.get(n);i&&i(o)}flushMacroOrders(){return this.macroRegistry.flushPendingOrders()}hasPendingMacroOrders(){return this.macroRegistry.hasPendingOrders()}applyMacroOrders(e){for(let t of e)this.macroEngine.applyOrder(t)}getMacroRegistry(){return this.macroRegistry}getMacroLoads(){return this.macroRegistry.toAllMacroLoads()}updateLayerMappings(){for(let e of this.layers){let t=e.getName();t&&this.macroRegistry.setLayerMapping(t,e.getId())}}registerLayerName(e,t){this.macroRegistry.setLayerMapping(e,t.getId())}loadMacroTemplate(e,t){this.macroEngine.loadTemplate(e,t)}updateMacros(){return this.macroEngine.update()}processMacroEvents(e){for(let t of e.events){let r=this.macroRegistry.getInstanceName(t.instanceId);if(!r)continue;let n=this.macroEventHandlers.get(r);if(!n)continue;let o=n.get(t.event);o&&o(t.data)}}updateMacroMouse(e,t,r){let n=this.displays.find(o=>o.getId()===this.mouseDisplayId);if(!n&&this.displays.length>0&&(n=this.displays[0]),n){let o=n.getOrigin(),i=e+o.x,s=t+o.y;this.macroEngine.updateMouse(i,s,r)}else this.macroEngine.updateMouse(e,t,r)}getMacroRenderOrders(){let e=this.macroEngine.getOrdersByLayer(),t=this.displays[0];if(!t)return e;let r=t.getOrigin();if(r.x===0&&r.y===0)return e;let n=new Map;for(let[o,i]of e){let s=i.map(a=>{let d={...a};return"posX"in d&&typeof d.posX=="number"&&(d.posX=d.posX-r.x),"posY"in d&&typeof d.posY=="number"&&(d.posY=d.posY-r.y),d});n.set(o,s)}return n}getMacroEffectOffset(){return this.macroEngine.getEffectOffset()}getMacroEngine(){return this.macroEngine}macroFocusNext(){this.macroEngine.focusNext()}macroFocusPrevious(){this.macroEngine.focusPrevious()}macroActivateFocused(){this.macroEngine.activateFocused()}setPostProcess(e,t){let r=JSON.stringify(t),n=JSON.stringify(this.currentPostProcessConfig);r!==n&&(this.currentPostProcessConfig=t,this.postProcessCommands.push({type:"set-config",displayId:e,config:t??void 0}))}setScanlinesEnabled(e,t){if(t){let r=this.currentPostProcessConfig?.scanlines;this.setPostProcess(e,{scanlines:{enabled:!0,opacity:r?.opacity??T.POST_PROCESS_DEFAULTS.scanlines.opacity,pattern:r?.pattern??T.POST_PROCESS_DEFAULTS.scanlines.pattern,color:r?.color??T.POST_PROCESS_DEFAULTS.scanlines.color}})}else this.setPostProcess(e,{scanlines:{enabled:!1}})}setScanlinesOpacity(e,t){let r=Math.max(0,Math.min(1,t)),n=this.currentPostProcessConfig?.scanlines;this.setPostProcess(e,{scanlines:{enabled:!0,opacity:r,pattern:n?.pattern??"horizontal",color:n?.color??{r:0,g:0,b:0}}})}setScanlinesPattern(e,t){let r=this.currentPostProcessConfig?.scanlines;this.setPostProcess(e,{scanlines:{enabled:r?.enabled??!0,opacity:r?.opacity??T.POST_PROCESS_DEFAULTS.scanlines.opacity,pattern:t,color:r?.color??{r:0,g:0,b:0}}})}setAmbientEffect(e,t){let r=this.currentPostProcessConfig?.ambientEffect;typeof t=="boolean"?this.setPostProcess(e,{...this.currentPostProcessConfig,ambientEffect:{enabled:t,blur:r?.blur??T.POST_PROCESS_DEFAULTS.ambientEffect.blur,scale:r?.scale??T.POST_PROCESS_DEFAULTS.ambientEffect.scale}}):this.setPostProcess(e,{...this.currentPostProcessConfig,ambientEffect:{enabled:!0,blur:t.blur??r?.blur??T.POST_PROCESS_DEFAULTS.ambientEffect.blur,scale:t.scale??r?.scale??T.POST_PROCESS_DEFAULTS.ambientEffect.scale}})}setAmbientEffectEnabled(e,t){this.setAmbientEffect(e,t)}setAmbientEffectBlur(e,t){let r=this.currentPostProcessConfig?.ambientEffect;this.setPostProcess(e,{...this.currentPostProcessConfig,ambientEffect:{enabled:r?.enabled??!0,blur:Math.max(0,t),scale:r?.scale??T.POST_PROCESS_DEFAULTS.ambientEffect.scale}})}setAmbientEffectScale(e,t){let r=this.currentPostProcessConfig?.ambientEffect;this.setPostProcess(e,{...this.currentPostProcessConfig,ambientEffect:{enabled:r?.enabled??!0,blur:r?.blur??T.POST_PROCESS_DEFAULTS.ambientEffect.blur,scale:Math.max(1,t)}})}isAmbientEffectEnabled(){return this.currentPostProcessConfig?.ambientEffect?.enabled??!1}getAmbientEffectConfig(){let e=this.currentPostProcessConfig?.ambientEffect;return e?{enabled:e.enabled,blur:e.blur??T.POST_PROCESS_DEFAULTS.ambientEffect.blur,scale:e.scale??T.POST_PROCESS_DEFAULTS.ambientEffect.scale}:null}getPostProcessConfig(){return this.currentPostProcessConfig}hasPostProcessCommands(){return this.postProcessCommands.length>0}flushPostProcessCommands(){let e=this.postProcessCommands;return this.postProcessCommands=[],e}setScalingMode(e,t){this.currentScalingModes.get(e)!==t&&(this.currentScalingModes.set(e,t),this.postProcessCommands.push({type:"set-scaling-mode",displayId:e,scalingMode:t}))}getScalingMode(e){return this.currentScalingModes.get(e)??null}setCellSize(e,t,r){let n=Math.max(1,Math.min(255,Math.round(t))),o=Math.max(1,Math.min(255,Math.round(r))),i=this.currentCellSizes.get(e);i&&i.width===n&&i.height===o||(this.currentCellSizes.set(e,{width:n,height:o}),this.postProcessCommands.push({type:"set-cell-size",displayId:e,cellWidth:n,cellHeight:o}))}getCellSize(e){let t=this.currentCellSizes.get(e);return{cellWidth:t?.width??8,cellHeight:t?.height??8}}setGrid(e,t){let r;typeof t=="boolean"?r={enabled:t,color:T.GRID_DEFAULTS.color,lineWidth:T.GRID_DEFAULTS.lineWidth}:r={enabled:t.enabled,color:t.color??T.GRID_DEFAULTS.color,lineWidth:t.lineWidth??T.GRID_DEFAULTS.lineWidth},this.currentGridConfigs.set(e,r),this.postProcessCommands.push({type:"set-grid",displayId:e,gridConfig:r})}setGridEnabled(e,t){this.setGrid(e,t)}isGridEnabled(e){return this.currentGridConfigs.get(e)?.enabled??!1}getGridConfig(e){return this.currentGridConfigs.get(e)??null}switchPalette(e,t){if(t<0||t>255)throw new Error(`Palette slot ID must be between 0 and 255, got ${t}`);this.currentPaletteSlotIds.get(e)!==t&&(this.currentPaletteSlotIds.set(e,t),this.postProcessCommands.push({type:"switch-palette",displayId:e,paletteSlotId:t}))}getCurrentPaletteSlotId(e){return this.currentPaletteSlotIds.get(e)??null}sendBridge(e,t){this.bridgeMessages.push({channel:e,data:t})}getBridgeMessages(){let e=this.bridgeMessages;return this.bridgeMessages=[],e}hasBridgeMessages(){return this.bridgeMessages.length>0}getDebugInfo(){let e=Array.from(this.availableViewports.entries()).map(([t,r])=>({displayId:t,pixelWidth:r.pixelWidth,pixelHeight:r.pixelHeight}));return{id:this.id,name:this.name,bytesSentTotal:this.totalBytesSent,bytesSentTick:this.currentTickBytesSent,availableViewports:e,layers:this.layers.map(t=>t.getDebugInfo()),displays:this.displays.map(t=>t.getDebugInfo())}}};b(Mr,"User");var ae=Mr;$();$();V();var Ar=class Ar{constructor(){h(this,"charCodeSize",we)}encode(e,t=!1){switch(e.type){case 1:return this.encodeCharOrder(e,t);case 2:return this.encodeTextOrder(e);case 23:return this.encodeTextMultilineOrder(e);case 3:return this.encodeSubFrameOrder(e,t);case 4:return this.encodeSubFrameMultiColorOrder(e,t);case 5:return this.encodeFullFrameOrder(e,t);case 6:return this.encodeFullFrameMultiColorOrder(e,t);case 7:return this.encodeSpriteOrder(e);case 8:return this.encodeSpriteMultiColorOrder(e);case 9:return this.encodeColorMapOrder(e);case 10:return this.encodeShapeOrder(e,t);case 11:return this.encodeDotCloudOrder(e,t);case 12:return this.encodeDotCloudMultiColorOrder(e,t);case 17:return this.encodeBitmaskOrder(e,t);case 18:return this.encodeBitmask4Order(e,t);case 24:return this.encodeBitmask16Order(e,t);case 25:return this.encodePolylineOrder(e,t);case 13:return this.encodeSpriteCloudOrder(e);case 14:return this.encodeSpriteCloudMultiColorOrder(e);case 15:return this.encodeSpriteCloudVariedOrder(e);case 16:return this.encodeSpriteCloudVariedMultiColorOrder(e);case 19:return this.encodeFillOrder(e,t);case 20:return this.encodeFillCharOrder(e,t);case 21:return this.encodeFillSpriteOrder(e);case 22:return this.encodeFillSpriteMultiColorOrder(e);default:throw new Error(`Unknown order type: ${e.type}`)}}writeCharCode(e,t,r,n){return n?(e.writeUInt16LE(t,r),r+2):(e.writeUInt8(t,r),r+1)}encodeCharOrder(e,t){let r=C.allocUnsafe(Ot+(t?1:0)),n=0;return r.writeUInt8(e.type,n++),r.writeUInt8(e.posX,n++),r.writeUInt8(e.posY,n++),n=this.writeCharCode(r,e.charCode,n,t),r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++),r.toUint8Array()}encodeTextOrder(e){let t=new TextEncoder().encode(e.text),r=C.allocUnsafe(wt+t.length),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.posX,n++),r.writeUInt8(e.posY,n++),r.writeUInt8(t.length,n++);for(let o=0;o<t.length;o++)r.writeUInt8(t[o],n++);return r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++),r.toUint8Array()}encodeTextMultilineOrder(e){let t=new TextEncoder().encode(e.text),r=C.allocUnsafe(Ut+t.length),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.posX,n++),r.writeUInt8(e.posY,n++),r.writeUInt8(t.length,n++);for(let o=0;o<t.length;o++)r.writeUInt8(t[o],n++);return r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++),r.toUint8Array()}encodeSubFrameOrder(e,t){let r=e.sizeX*e.sizeY,n=this.charCodeSize(t),o=C.allocUnsafe(vt+r*n),i=0;o.writeUInt8(e.type,i++),o.writeUInt8(e.posX,i++),o.writeUInt8(e.posY,i++),o.writeUInt8(e.sizeX-1,i++),o.writeUInt8(e.sizeY-1,i++),o.writeUInt8(e.bgColorCode,i++),o.writeUInt8(e.fgColorCode,i++);for(let s of e.frame)i=this.writeCharCode(o,s,i,t);return o.toUint8Array()}encodeSubFrameMultiColorOrder(e,t){let r=e.sizeX*e.sizeY,n=this.charCodeSize(t),o=C.allocUnsafe(Mt+r*(n+2)),i=0;o.writeUInt8(e.type,i++),o.writeUInt8(e.posX,i++),o.writeUInt8(e.posY,i++),o.writeUInt8(e.sizeX-1,i++),o.writeUInt8(e.sizeY-1,i++);for(let s of e.frame)i=this.writeCharCode(o,s.charCode,i,t),o.writeUInt8(s.bgColorCode,i++),o.writeUInt8(s.fgColorCode,i++);return o.toUint8Array()}encodeFullFrameOrder(e,t){let r=e.frame.length,n=this.charCodeSize(t),o=C.allocUnsafe(At+r*n),i=0;o.writeUInt8(e.type,i++),o.writeUInt8(e.bgColorCode,i++),o.writeUInt8(e.fgColorCode,i++);for(let s of e.frame)i=this.writeCharCode(o,s,i,t);return o.toUint8Array()}encodeFullFrameMultiColorOrder(e,t){let r=e.frame.length,n=this.charCodeSize(t),o=C.allocUnsafe(Et+r*(n+2)),i=0;o.writeUInt8(e.type,i++);for(let s of e.frame)i=this.writeCharCode(o,s.charCode,i,t),o.writeUInt8(s.bgColorCode,i++),o.writeUInt8(s.fgColorCode,i++);return o.toUint8Array()}encodeSpriteOrder(e){let t=C.allocUnsafe(Pt),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.posX,r++),t.writeUInt8(e.posY,r++),t.writeUInt8(e.spriteIndex,r++),t.writeUInt8(e.bgColorCode,r++),t.writeUInt8(e.fgColorCode,r++),t.toUint8Array()}encodeSpriteMultiColorOrder(e){let t=C.allocUnsafe(kt),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.posX,r++),t.writeUInt8(e.posY,r++),t.writeUInt8(e.spriteIndex,r++),t.toUint8Array()}encodeColorMapOrder(e){let t=e.sizeX*e.sizeY,r=C.allocUnsafe(Rt+t*2),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.posX,n++),r.writeUInt8(e.posY,n++),r.writeUInt8(e.sizeX-1,n++),r.writeUInt8(e.sizeY-1,n++);for(let o of e.colorData)r.writeUInt8(o.bgColorCode,n++),r.writeUInt8(o.fgColorCode,n++);return r.toUint8Array()}encodeShapeOrder(e,t){let r=this.encodeShapeData(e.shapeType,e.shapeData,t),n=C.allocUnsafe(Bt+r.length),o=0;n.writeUInt8(e.type,o++),n.writeUInt8(e.shapeType,o++);for(let i=0;i<r.length;i++)n.writeUInt8(r[i],o++);return n.toUint8Array()}encodeShapeData(e,t,r){let n=this.charCodeSize(r);switch(e){case 1:{let o=C.allocUnsafe(zt+(r?1:0)),i=0;return o.writeUInt8(t.posX,i++),o.writeUInt8(t.posY,i++),o.writeUInt8(t.width-1,i++),o.writeUInt8(t.height-1,i++),o.writeUInt8(t.filled?1:0,i++),i=this.writeCharCode(o,t.charCode,i,r),o.writeUInt8(t.bgColorCode,i++),o.writeUInt8(t.fgColorCode,i++),o.toUint8Array()}case 2:{let o=C.allocUnsafe(Tt+(r?1:0)),i=0;return o.writeUInt8(t.centerX,i++),o.writeUInt8(t.centerY,i++),o.writeUInt8(t.radius-1,i++),o.writeUInt8(t.filled?1:0,i++),i=this.writeCharCode(o,t.charCode,i,r),o.writeUInt8(t.bgColorCode,i++),o.writeUInt8(t.fgColorCode,i++),o.toUint8Array()}case 3:{let o=C.allocUnsafe(Lt+(r?1:0)),i=0;return o.writeUInt8(t.x1,i++),o.writeUInt8(t.y1,i++),o.writeUInt8(t.x2,i++),o.writeUInt8(t.y2,i++),i=this.writeCharCode(o,t.charCode,i,r),o.writeUInt8(t.bgColorCode,i++),o.writeUInt8(t.fgColorCode,i++),o.toUint8Array()}case 4:{let o=C.allocUnsafe(Ft+(r?1:0)),i=0;return o.writeUInt8(t.centerX,i++),o.writeUInt8(t.centerY,i++),o.writeUInt8(t.radiusX-1,i++),o.writeUInt8(t.radiusY-1,i++),o.writeUInt8(t.filled?1:0,i++),i=this.writeCharCode(o,t.charCode,i,r),o.writeUInt8(t.bgColorCode,i++),o.writeUInt8(t.fgColorCode,i++),o.toUint8Array()}case 5:{let o=C.allocUnsafe(Dt+(r?1:0)),i=0;return o.writeUInt8(t.x1,i++),o.writeUInt8(t.y1,i++),o.writeUInt8(t.x2,i++),o.writeUInt8(t.y2,i++),o.writeUInt8(t.x3,i++),o.writeUInt8(t.y3,i++),o.writeUInt8(t.filled?1:0,i++),i=this.writeCharCode(o,t.charCode,i,r),o.writeUInt8(t.bgColorCode,i++),o.writeUInt8(t.fgColorCode,i++),o.toUint8Array()}default:throw new Error(`Unknown shape type: ${e}`)}}encodeDotCloudOrder(e,t){let r=e.positions.length,n=this.charCodeSize(t),o=C.allocUnsafe(Vt+(t?1:0)+r*2),i=0;o.writeUInt8(e.type,i++),i=this.writeCharCode(o,e.charCode,i,t),o.writeUInt8(e.bgColorCode,i++),o.writeUInt8(e.fgColorCode,i++),o.writeUInt16BE(r,i),i+=2;for(let s of e.positions)o.writeUInt8(s.posX,i++),o.writeUInt8(s.posY,i++);return o.toUint8Array()}encodeDotCloudMultiColorOrder(e,t){let r=e.dots.length,n=this.charCodeSize(t),o=C.allocUnsafe(_t+r*(n+4)),i=0;o.writeUInt8(e.type,i++),o.writeUInt16BE(r,i),i+=2;for(let s of e.dots)i=this.writeCharCode(o,s.charCode,i,t),o.writeUInt8(s.bgColorCode,i++),o.writeUInt8(s.fgColorCode,i++),o.writeUInt8(s.posX,i++),o.writeUInt8(s.posY,i++);return o.toUint8Array()}encodeBitmaskOrder(e,t){let r=e.mask.length,n=C.allocUnsafe(Nt+(t?1:0)+r),o=0;n.writeUInt8(e.type,o++),n.writeUInt8(e.posX,o++),n.writeUInt8(e.posY,o++),n.writeUInt8(e.sizeX-1,o++),n.writeUInt8(e.sizeY-1,o++),o=this.writeCharCode(n,e.charCode,o,t),n.writeUInt8(e.bgColorCode,o++),n.writeUInt8(e.fgColorCode,o++),n.writeUInt8(e.override?1:0,o++);for(let i=0;i<r;i++)n.writeUInt8(e.mask[i],o++);return n.toUint8Array()}encodeBitmask4Order(e,t){let r=e.mask.length,n=this.charCodeSize(t),o=C.allocUnsafe(Yt+3*(t?1:0)+r),i=0;o.writeUInt8(e.type,i++),o.writeUInt8(e.posX,i++),o.writeUInt8(e.posY,i++),o.writeUInt8(e.sizeX-1,i++),o.writeUInt8(e.sizeY-1,i++),o.writeUInt8(e.override?1:0,i++);for(let s of e.variants)i=this.writeCharCode(o,s.charCode,i,t),o.writeUInt8(s.bgColorCode,i++),o.writeUInt8(s.fgColorCode,i++);for(let s=0;s<r;s++)o.writeUInt8(e.mask[s],i++);return o.toUint8Array()}encodeBitmask16Order(e,t){let r=e.mask.length,n=this.charCodeSize(t),o=C.allocUnsafe(Ht+15*(t?1:0)+r),i=0;o.writeUInt8(e.type,i++),o.writeUInt8(e.posX,i++),o.writeUInt8(e.posY,i++),o.writeUInt8(e.sizeX-1,i++),o.writeUInt8(e.sizeY-1,i++),o.writeUInt8(e.override?1:0,i++);for(let s of e.variants)i=this.writeCharCode(o,s.charCode,i,t),o.writeUInt8(s.bgColorCode,i++),o.writeUInt8(s.fgColorCode,i++);for(let s=0;s<r;s++)o.writeUInt8(e.mask[s],i++);return o.toUint8Array()}encodePolylineOrder(e,t){let r=e.points.length,n=C.allocUnsafe(Xt+(t?1:0)+r*2),o=0;n.writeUInt8(e.type,o++),o=this.writeCharCode(n,e.charCode,o,t),n.writeUInt8(e.fgColorCode,o++),n.writeUInt8(e.bgColorCode,o++),n.writeUInt8(r,o++);for(let i of e.points)n.writeUInt8(i.x,o++),n.writeUInt8(i.y,o++);return n.toUint8Array()}encodeSpriteCloudOrder(e){let t=e.positions.length,r=C.allocUnsafe(Gt+t*2),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.spriteIndex,n++),r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++),r.writeUInt16BE(t,n),n+=2;for(let o of e.positions)r.writeUInt8(o.posX,n++),r.writeUInt8(o.posY,n++);return r.toUint8Array()}encodeSpriteCloudMultiColorOrder(e){let t=e.positions.length,r=C.allocUnsafe($t+t*2),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.spriteIndex,n++),r.writeUInt16BE(t,n),n+=2;for(let o of e.positions)r.writeUInt8(o.posX,n++),r.writeUInt8(o.posY,n++);return r.toUint8Array()}encodeSpriteCloudVariedOrder(e){let t=e.sprites.length,r=C.allocUnsafe(Zt+t*5),n=0;r.writeUInt8(e.type,n++),r.writeUInt16BE(t,n),n+=2;for(let o of e.sprites)r.writeUInt8(o.spriteIndex,n++),r.writeUInt8(o.bgColorCode,n++),r.writeUInt8(o.fgColorCode,n++),r.writeUInt8(o.posX,n++),r.writeUInt8(o.posY,n++);return r.toUint8Array()}encodeSpriteCloudVariedMultiColorOrder(e){let t=e.sprites.length,r=C.allocUnsafe(Wt+t*3),n=0;r.writeUInt8(e.type,n++),r.writeUInt16BE(t,n),n+=2;for(let o of e.sprites)r.writeUInt8(o.spriteIndex,n++),r.writeUInt8(o.posX,n++),r.writeUInt8(o.posY,n++);return r.toUint8Array()}encodeFillOrder(e,t){let r=C.allocUnsafe(jt+(t?1:0)),n=0;return r.writeUInt8(e.type,n++),n=this.writeCharCode(r,e.charCode,n,t),r.writeUInt8(e.bgColorCode,n++),r.writeUInt8(e.fgColorCode,n++),r.toUint8Array()}encodeFillCharOrder(e,t){let r=e.patternWidth*e.patternHeight,n=this.charCodeSize(t),o=C.allocUnsafe(Jt+r*n),i=0;o.writeUInt8(e.type,i++),o.writeUInt8(e.patternWidth-1,i++),o.writeUInt8(e.patternHeight-1,i++),o.writeUInt8(e.bgColorCode,i++),o.writeUInt8(e.fgColorCode,i++);for(let s of e.pattern)i=this.writeCharCode(o,s,i,t);return o.toUint8Array()}encodeFillSpriteOrder(e){let t=C.allocUnsafe(qt),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.spriteIndex,r++),t.writeUInt8(e.bgColorCode,r++),t.writeUInt8(e.fgColorCode,r++),t.toUint8Array()}encodeFillSpriteMultiColorOrder(e){let t=C.allocUnsafe(Kt),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.spriteIndex,r++),t.toUint8Array()}};b(Ar,"OrderEncoder");var rt=Ar;V();var Bn=255,zn=32,Tn=64,Er=class Er{constructor(){h(this,"orderEncoder");this.orderEncoder=new rt}encode(e){let t=e.is16bit;if(e.orders.length>Bn)throw new Error(`[UTSP] LayerEncoder: Layer ${e.id} has ${e.orders.length} orders, max is ${Bn}. This would cause packet corruption! Split into multiple layers.`);let r=e.orders.map(l=>this.orderEncoder.encode(l,t)),n=13,o=r.reduce((l,c)=>l+c.length,0),i=n+o,s=C.allocUnsafe(i),a=0;s.writeUInt16BE(e.id,a),a+=2;let d=e.updateFlags;e.isMacroLayer?d|=zn:d&=~zn,t?d|=Tn:d&=~Tn,s.writeUInt8(d,a++),s.writeUInt8(e.zIndex,a++),s.writeUInt16BE(e.originX,a),a+=2,s.writeUInt16BE(e.originY,a),a+=2,s.writeUInt16BE(e.width,a),a+=2,s.writeUInt16BE(e.height,a),a+=2,s.writeUInt8(e.orders.length,a++);for(let l of r)C.from(l).copy(s,a),a+=l.length;return s.toUint8Array()}calculateSize(e){let r=e.is16bit;return 13+e.orders.reduce((o,i)=>o+this.orderEncoder.encode(i,r).length,0)}};b(Er,"LayerEncoder");var nt=Er;V();$();var Pr=class Pr{encode(e){switch(e.type){case 1:return this.encodePlaySoundOrder(e);case 2:return this.encodePlayGlobalSoundOrder(e);case 3:return this.encodeStopSoundOrder(e);case 4:return this.encodeFadeOutSoundOrder(e);case 5:return this.encodePauseSoundOrder(e);case 6:return this.encodeResumeSoundOrder(e);case 7:return this.encodeSetListenerPositionOrder(e);case 8:return this.encodeConfigureSpatialOrder(e);case 9:return this.encodeSetSoundEffectsOrder(e);default:throw new Error(`Unknown audio order type: ${e.type}`)}}calculateSize(e){switch(e.type){case 1:return this.calculatePlaySoundSize(e);case 2:return this.calculatePlayGlobalSoundSize(e);case 3:case 5:case 6:return this.calculateTargetOrderSize(e);case 4:return this.calculateFadeOutSize(e);case 7:return ke;case 8:return Re;case 9:return this.calculateSetSoundEffectsSize(e);default:throw new Error(`Unknown audio order type: ${e.type}`)}}encodePlaySoundOrder(e){let t=this.calculatePlaySoundSize(e),r=C.allocUnsafe(t),n=0;return r.writeUInt8(e.type,n++),r.writeUInt8(e.soundId,n++),r.writeUInt16BE(e.instanceId,n),n+=2,r.writeUInt8(e.flags,n++),e.flags&2&&r.writeUInt8(e.volume??255,n++),e.flags&4&&r.writeUInt8(e.pitch??128,n++),e.flags&8&&r.writeUInt8(e.fadeIn??0,n++),e.flags&16&&(r.writeUInt16BE(e.posX??0,n),n+=2,r.writeUInt16BE(e.posY??0,n),n+=2),e.flags&32&&r.writeUInt8(e.lowpass??0,n++),e.flags&64&&r.writeUInt8(e.highpass??0,n++),e.flags&128&&r.writeUInt8(e.reverb??0,n++),r.toUint8Array()}encodePlayGlobalSoundOrder(e){let t=this.calculatePlayGlobalSoundSize(e),r=C.allocUnsafe(t),n=0;r.writeUInt8(e.type,n++),r.writeUInt8(e.soundId,n++),r.writeUInt16BE(e.instanceId,n),n+=2;let o=e.flags&-17;return r.writeUInt8(o,n++),o&2&&r.writeUInt8(e.volume??255,n++),o&4&&r.writeUInt8(e.pitch??128,n++),o&8&&r.writeUInt8(e.fadeIn??0,n++),o&32&&r.writeUInt8(e.lowpass??0,n++),o&64&&r.writeUInt8(e.highpass??0,n++),o&128&&r.writeUInt8(e.reverb??0,n++),r.toUint8Array()}calculatePlaySoundSize(e){let t=Qt;return e.flags&2&&(t+=1),e.flags&4&&(t+=1),e.flags&8&&(t+=1),e.flags&16&&(t+=4),e.flags&32&&(t+=1),e.flags&64&&(t+=1),e.flags&128&&(t+=1),t}calculatePlayGlobalSoundSize(e){let t=er,r=e.flags&-17;return r&2&&(t+=1),r&4&&(t+=1),r&8&&(t+=1),r&32&&(t+=1),r&64&&(t+=1),r&128&&(t+=1),t}encodeStopSoundOrder(e){return this.encodeTargetOrder(e.type,e.targetType,e.target)}encodePauseSoundOrder(e){return this.encodeTargetOrder(e.type,e.targetType,e.target)}encodeResumeSoundOrder(e){return this.encodeTargetOrder(e.type,e.targetType,e.target)}encodeFadeOutSoundOrder(e){let t=this.calculateFadeOutSize(e),r=C.allocUnsafe(t),n=0;return r.writeUInt8(e.type,n++),r.writeUInt8(e.targetType,n++),r.writeUInt8(e.duration,n++),e.targetType===0?r.writeUInt16BE(e.target??0,n):e.targetType===1&&r.writeUInt8(e.target??0,n),r.toUint8Array()}encodeTargetOrder(e,t,r){let n=2;t===0?n+=2:t===1&&(n+=1);let o=C.allocUnsafe(n),i=0;return o.writeUInt8(e,i++),o.writeUInt8(t,i++),t===0?o.writeUInt16BE(r??0,i):t===1&&o.writeUInt8(r??0,i),o.toUint8Array()}calculateTargetOrderSize(e){let t=2;return e.targetType===0?t+=2:e.targetType===1&&(t+=1),t}calculateFadeOutSize(e){let t=3;return e.targetType===0?t+=2:e.targetType===1&&(t+=1),t}encodeSetListenerPositionOrder(e){let t=C.allocUnsafe(ke),r=0;return t.writeUInt8(e.type,r++),t.writeUInt16BE(e.x,r),r+=2,t.writeUInt16BE(e.y,r),t.toUint8Array()}encodeConfigureSpatialOrder(e){let t=C.allocUnsafe(Re),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.maxDistance,r++),t.writeUInt8(e.referenceDistance,r++),t.writeUInt8(e.rolloffFactor,r++),t.writeUInt8(e.panSpread,r++),t.toUint8Array()}encodeSetSoundEffectsOrder(e){let t=this.calculateSetSoundEffectsSize(e),r=C.allocUnsafe(t),n=0;return r.writeUInt8(e.type,n++),r.writeUInt16BE(e.instanceId,n),n+=2,r.writeUInt8(e.flags,n++),e.flags&1&&r.writeUInt8(e.lowpass??0,n++),e.flags&2&&r.writeUInt8(e.highpass??0,n++),e.flags&4&&r.writeUInt8(e.reverb??0,n++),r.toUint8Array()}calculateSetSoundEffectsSize(e){let t=4;return e.flags&1&&(t+=1),e.flags&2&&(t+=1),e.flags&4&&(t+=1),t}};b(Pr,"AudioOrderEncoder");var ot=Pr;V();var kr=class kr{encode(e){switch(e.type){case 1:return this.encodeMobileVibrateOrder(e);case 2:return this.encodeMobileCancelOrder(e);case 16:return this.encodeGamepadVibrateOrder(e);case 17:return this.encodeGamepadCancelOrder(e);default:throw new Error(`Unknown vibration order type: ${e.type}`)}}calculateSize(e){switch(e.type){case 1:return this.calculateMobileVibrateSize(e);case 2:return 1;case 16:return this.calculateGamepadVibrateSize(e);case 17:return 3;default:throw new Error(`Unknown vibration order type: ${e.type}`)}}calculateMobileVibrateSize(e){let t=3+e.pattern.length*2;return e.intensity!==void 0&&(t+=1),t}encodeMobileVibrateOrder(e){let t=this.calculateMobileVibrateSize(e),r=C.allocUnsafe(t),n=0,o=0;e.intensity!==void 0&&(o|=1),r.writeUInt8(e.type,n++),r.writeUInt8(o,n++),r.writeUInt8(e.pattern.length,n++);for(let i of e.pattern){let s=Math.min(65535,Math.max(0,Math.round(i)));r.writeUInt16BE(s,n),n+=2}if(e.intensity!==void 0){let i=Math.round(Math.min(1,Math.max(0,e.intensity))*255);r.writeUInt8(i,n++)}return r.toUint8Array()}encodeMobileCancelOrder(e){let t=C.allocUnsafe(1);return t.writeUInt8(2,0),t.toUint8Array()}calculateGamepadVibrateSize(e){let t=7;return e.startDelay!==void 0&&e.startDelay>0&&(t+=2),t}encodeGamepadVibrateOrder(e){let t=this.calculateGamepadVibrateSize(e),r=C.allocUnsafe(t),n=0,o=0;e.startDelay!==void 0&&e.startDelay>0&&(o|=1),e.gamepadIndex===255&&(o|=2),r.writeUInt8(e.type,n++),r.writeUInt8(o,n++),r.writeUInt8(e.gamepadIndex,n++);let i=Math.min(65535,Math.max(0,Math.round(e.duration)));if(r.writeUInt16BE(i,n),n+=2,r.writeUInt8(e.strongMagnitude,n++),r.writeUInt8(e.weakMagnitude,n++),e.startDelay!==void 0&&e.startDelay>0){let s=Math.min(65535,Math.max(0,Math.round(e.startDelay)));r.writeUInt16BE(s,n),n+=2}return r.toUint8Array()}encodeGamepadCancelOrder(e){let t=C.allocUnsafe(3),r=0,n=0;return e.gamepadIndex===255&&(n|=2),t.writeUInt8(e.type,r++),t.writeUInt8(n,r++),t.writeUInt8(e.gamepadIndex,r++),t.toUint8Array()}};b(kr,"VibrationOrderEncoder");var de=kr;V();var Rr=class Rr{encode(e){switch(e.type){case 1:return this.encodeCreateInstance(e);case 2:return this.encodeUpdateInstance(e);case 3:return this.encodeRemoveInstance(e);default:throw new Error(`Unknown macro order type: ${e.type}`)}}calculateSize(e){switch(e.type){case 1:return this.calculateCreateInstanceSize(e);case 2:return this.calculateUpdateInstanceSize(e);case 3:return 2;default:throw new Error(`Unknown macro order type: ${e.type}`)}}encodeCreateInstance(e){let t=JSON.stringify(e.params),r=new TextEncoder().encode(t);if(r.length>65535)throw new Error(`Params JSON too large: ${r.length} bytes (max 65535)`);let n=11+r.length,o=C.allocUnsafe(n),i=0;return o.writeUInt8(e.type,i++),o.writeUInt8(e.instanceId,i++),o.writeUInt8(e.macroId,i++),o.writeUInt8(e.layerId,i++),o.writeInt16BE(e.x,i),i+=2,o.writeInt16BE(e.y,i),i+=2,o.writeUInt8(e.tabIndex,i++),o.writeUInt16BE(r.length,i),i+=2,o.toUint8Array().set(r,i),o.toUint8Array()}calculateCreateInstanceSize(e){let t=JSON.stringify(e.params);return 11+new TextEncoder().encode(t).length}encodeUpdateInstance(e){let t=JSON.stringify(e.params),r=new TextEncoder().encode(t);if(r.length>65535)throw new Error(`Params JSON too large: ${r.length} bytes (max 65535)`);let n=4+r.length,o=C.allocUnsafe(n),i=0;return o.writeUInt8(e.type,i++),o.writeUInt8(e.instanceId,i++),o.writeUInt16BE(r.length,i),i+=2,o.toUint8Array().set(r,i),o.toUint8Array()}calculateUpdateInstanceSize(e){let t=JSON.stringify(e.params);return 4+new TextEncoder().encode(t).length}encodeRemoveInstance(e){let t=C.allocUnsafe(2);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.toUint8Array()}};b(Rr,"MacroOrderEncoder");var it=Rr;V();$();var Tr=class Tr{encode(e){switch(e.type){case 1:return this.encodeSetConfigOrder(e);case 2:return this.encodeSetScanlinesOrder(e);case 3:return this.encodeSetAmbientEffectOrder(e);case 4:return this.encodeSetScalingModeOrder(e);case 5:return this.encodeSetGridOrder(e);case 6:return this.encodeSwitchPaletteOrder(e);case 7:return this.encodeSetCellSizeOrder(e);default:throw new Error(`Unknown post-process order type: ${e.type}`)}}calculateSize(e){switch(e.type){case 1:return this.calculateSetConfigSize(e);case 2:return Be;case 3:return ze;case 4:return Te;case 5:return Le;case 6:return Fe;case 7:return De;default:throw new Error(`Unknown post-process order type: ${e.type}`)}}encodeSetConfigOrder(e){let t=this.calculateSetConfigSize(e),r=C.allocUnsafe(t),n=0;return r.writeUInt8(e.type,n++),r.writeUInt8(e.displayId,n++),r.writeUInt8(e.flags,n++),e.flags&1&&e.scanlines&&(r.writeUInt8(e.scanlines.enabled?1:0,n++),r.writeUInt8(Math.round(e.scanlines.opacity*255),n++),r.writeUInt8(e.scanlines.pattern,n++),r.writeUInt8(e.scanlines.colorR,n++),r.writeUInt8(e.scanlines.colorG,n++),r.writeUInt8(e.scanlines.colorB,n++)),e.flags&2&&e.ambientEffect&&(r.writeUInt8(e.ambientEffect.enabled?1:0,n++),r.writeUInt8(Math.min(255,Math.round(e.ambientEffect.blur)),n++),r.writeUInt8(Math.min(255,Math.max(100,Math.round(e.ambientEffect.scale*100))),n++),r.writeUInt8(Math.round(e.ambientEffect.opacity*255),n++)),r.toUint8Array()}calculateSetConfigSize(e){let t=tr;return e.flags&1&&(t+=6),e.flags&2&&(t+=4),t}encodeSetScanlinesOrder(e){let t=C.allocUnsafe(Be),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.displayId,r++),t.writeUInt8(e.enabled?1:0,r++),t.writeUInt8(Math.round(e.opacity*255),r++),t.writeUInt8(e.pattern,r++),t.writeUInt8(e.colorR,r++),t.writeUInt8(e.colorG,r++),t.writeUInt8(e.colorB,r++),t.toUint8Array()}encodeSetAmbientEffectOrder(e){let t=C.allocUnsafe(ze),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.displayId,r++),t.writeUInt8(e.enabled?1:0,r++),t.writeUInt8(Math.min(255,Math.round(e.blur)),r++),t.writeUInt8(Math.min(255,Math.max(100,Math.round(e.scale*100))),r++),t.writeUInt8(Math.round(e.opacity*255),r++),t.toUint8Array()}encodeSetScalingModeOrder(e){let t=C.allocUnsafe(Te),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.displayId,r++),t.writeUInt8(e.mode,r++),t.toUint8Array()}encodeSetGridOrder(e){let t=C.allocUnsafe(Le),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.displayId,r++),t.writeUInt8(e.enabled?1:0,r++),t.writeUInt8(e.colorR,r++),t.writeUInt8(e.colorG,r++),t.writeUInt8(e.colorB,r++),t.writeUInt8(e.colorA,r++),t.writeUInt8(Math.min(10,Math.max(1,e.lineWidth)),r++),t.toUint8Array()}encodeSwitchPaletteOrder(e){let t=C.allocUnsafe(Fe),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.displayId,r++),t.writeUInt8(e.slotId,r++),t.toUint8Array()}encodeSetCellSizeOrder(e){let t=C.allocUnsafe(De),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.displayId,r++),t.writeUInt8(e.cellWidth,r++),t.writeUInt8(e.cellHeight,r++),t.toUint8Array()}};b(Tr,"PostProcessOrderEncoder");var st=Tr;V();var Dn=4,Lr=4,Vn=8,Fr=class Fr{encode(e){let t=e.renderPasses?.length??0;if(t>Lr)throw new Error(`renderPasses supports up to ${Lr} entries, got ${t}`);let r=Vn+t*Dn,n=C.allocUnsafe(r),o=0;if(n.writeUInt8(e.id,o++),n.writeUInt16BE(e.originX,o),o+=2,n.writeUInt16BE(e.originY,o),o+=2,n.writeUInt8(e.sizeX-1,o++),n.writeUInt8(e.sizeY-1,o++),n.writeUInt8(t,o++),t>0&&e.renderPasses)for(let i of e.renderPasses){let s=Math.max(0,Math.min(255,i.id)),a=Math.max(0,Math.min(255,i.zMin)),d=Math.max(0,Math.min(255,i.zMax)),l=i.enabled===!1?0:1;n.writeUInt8(s,o++),n.writeUInt8(a,o++),n.writeUInt8(d,o++),n.writeUInt8(l,o++)}return n.toUint8Array()}calculateSize(e){let t=Math.min(e.renderPasses?.length??0,Lr);return Vn+t*Dn}};b(Fr,"DisplayEncoder");var at=Fr;V();var Dr=class Dr{constructor(){h(this,"layerEncoder");h(this,"audioOrderEncoder");h(this,"vibrationOrderEncoder");h(this,"macroOrderEncoder");h(this,"postProcessOrderEncoder");h(this,"displayEncoder");this.layerEncoder=new nt,this.audioOrderEncoder=new ot,this.vibrationOrderEncoder=new de,this.macroOrderEncoder=new it,this.postProcessOrderEncoder=new st,this.displayEncoder=new at}encode(e){let t=e.layers.map(O=>this.layerEncoder.encode(O)),r=e.audioOrders||[],n=r.map(O=>this.audioOrderEncoder.encode(O)),o=e.vibrationOrders||[],i=o.map(O=>this.vibrationOrderEncoder.encode(O)),s=e.macroOrders||[],a=s.map(O=>this.macroOrderEncoder.encode(O)),d=e.postProcessOrders||[],l=d.map(O=>this.postProcessOrderEncoder.encode(O)),c=9,u=e.displays.reduce((O,z)=>O+this.displayEncoder.calculateSize(z),0),p=2,m=t.reduce((O,z)=>O+z.length,0),g=1,y=n.reduce((O,z)=>O+z.length,0),S=1,w=i.reduce((O,z)=>O+z.length,0),I=1,U=a.reduce((O,z)=>O+z.length,0),M=1,P=l.reduce((O,z)=>O+z.length,0),E=c+u+p+m+g+y+S+w+I+U+M+P,v=C.allocUnsafe(E),f=0,L=typeof e.tick=="bigint"?e.tick:BigInt(e.tick);v.writeBigUInt64BE(L,f),f+=8,v.writeUInt8(e.displays.length,f),f+=1;for(let O of e.displays){let z=this.displayEncoder.encode(O);C.from(z).copy(v,f),f+=z.length}v.writeUInt16BE(e.layers.length,f),f+=2;for(let O of t)C.from(O).copy(v,f),f+=O.length;v.writeUInt8(r.length,f),f+=1;for(let O of n)C.from(O).copy(v,f),f+=O.length;v.writeUInt8(o.length,f),f+=1;for(let O of i)C.from(O).copy(v,f),f+=O.length;v.writeUInt8(s.length,f),f+=1;for(let O of a)C.from(O).copy(v,f),f+=O.length;v.writeUInt8(d.length,f),f+=1;for(let O of l)C.from(O).copy(v,f),f+=O.length;return v.toUint8Array()}calculateSize(e){let r=e.displays.reduce((w,I)=>w+this.displayEncoder.calculateSize(I),0),n=2,o=e.layers.reduce((w,I)=>w+this.layerEncoder.calculateSize(I),0),i=1,a=(e.audioOrders||[]).reduce((w,I)=>w+this.audioOrderEncoder.calculateSize(I),0),d=1,c=(e.vibrationOrders||[]).reduce((w,I)=>w+this.vibrationOrderEncoder.calculateSize(I),0),u=1,m=(e.macroOrders||[]).reduce((w,I)=>w+this.macroOrderEncoder.calculateSize(I),0),g=1,S=(e.postProcessOrders||[]).reduce((w,I)=>w+this.postProcessOrderEncoder.calculateSize(I),0);return 9+r+n+o+i+a+d+c+u+m+g+S}static createEmptyPacket(e){return{tick:typeof e=="bigint"?Number(e):e,displayCount:0,displays:[],layerCount:0,layers:[],audioOrderCount:0,audioOrders:[],vibrationOrderCount:0,vibrationOrders:[],macroOrderCount:0,macroOrders:[],postProcessOrderCount:0,postProcessOrders:[]}}encodeEmpty(e){let t=C.allocUnsafe(15),r=typeof e=="bigint"?e:BigInt(e);return t.writeBigUInt64BE(r,0),t.writeUInt8(0,8),t.writeUInt16BE(0,9),t.writeUInt8(0,11),t.writeUInt8(0,12),t.writeUInt8(0,13),t.writeUInt8(0,14),t.toUint8Array()}};b(Dr,"UpdatePacketEncoder");var dt=Dr;var Vr=(s=>(s[s.ColorPalette=1]="ColorPalette",s[s.Sprite=2]="Sprite",s[s.MulticolorSprite=3]="MulticolorSprite",s[s.Sound=5]="Sound",s[s.Macro=7]="Macro",s[s.ImageFont=8]="ImageFont",s[s.ImageFontBlock=9]="ImageFontBlock",s))(Vr||{});V();var _r=class _r{encode(e){let t=JSON.stringify(e.template),r=new TextEncoder().encode(t);if(r.length>65535)throw new Error(`Macro template JSON too large: ${r.length} bytes (max 65535)`);let n=4+r.length,o=C.allocUnsafe(n),i=0;return o.writeUInt8(7,i++),o.writeUInt8(e.macroId,i++),o.writeUInt16BE(r.length,i),i+=2,o.toUint8Array().set(r,i),o.toUint8Array()}calculateSize(e){let t=JSON.stringify(e.template);return 4+new TextEncoder().encode(t).length}};b(_r,"MacroLoadEncoder");var lt=_r;V();var Nr=class Nr{encode(e){switch(e.loadType){case 1:return this.encodeColorPalette(e);case 2:return this.encodeSprite(e);case 3:return this.encodeMulticolorSprite(e);case 5:return this.encodeSound(e);case 8:return this.encodeImageFont(e);case 9:return this.encodeImageFontBlock(e);default:throw new Error(`Unknown load type: ${e.loadType}`)}}encodeColorPalette(e){let t=e.colors.length;if(t>255)throw new Error(`Palette size ${t} exceeds maximum of 255`);let r=e.slotId!==void 0,n=r?4:3,o=C.allocUnsafe(n+t*6),i=0;o.writeUInt8(1,i++),o.writeUInt8(r?255:0,i++),r&&o.writeUInt8(e.slotId,i++),o.writeUInt8(t,i++);for(let s of e.colors)o.writeUInt8(s.colorId,i++),o.writeUInt8(s.r,i++),o.writeUInt8(s.g,i++),o.writeUInt8(s.b,i++),o.writeUInt8(s.a,i++),o.writeUInt8(s.e??0,i++);return o.toUint8Array()}encodeSprite(e){let t=e.sprites.length;if(t>255)throw new Error(`Sprite count ${t} exceeds maximum of 255`);let r=2;for(let i of e.sprites)r+=3,r+=i.data.length;let n=C.allocUnsafe(r),o=0;n.writeUInt8(2,o++),n.writeUInt8(t,o++);for(let i of e.sprites){if(i.data.length!==i.sizeX*i.sizeY)throw new Error(`Sprite ${i.spriteId}: data length ${i.data.length} does not match size ${i.sizeX}x${i.sizeY}`);n.writeUInt8(i.spriteId,o++),n.writeUInt8(i.sizeX,o++),n.writeUInt8(i.sizeY,o++);for(let s of i.data)n.writeUInt8(s,o++)}return n.toUint8Array()}encodeMulticolorSprite(e){let t=e.sprites.length;if(t>255)throw new Error(`Sprite count ${t} exceeds maximum of 255`);let r=2;for(let i of e.sprites)r+=3,r+=i.data.length*3;let n=C.allocUnsafe(r),o=0;n.writeUInt8(3,o++),n.writeUInt8(t,o++);for(let i of e.sprites){if(i.data.length!==i.sizeX*i.sizeY)throw new Error(`Sprite ${i.spriteId}: data length ${i.data.length} does not match size ${i.sizeX}x${i.sizeY}`);n.writeUInt8(i.spriteId,o++),n.writeUInt8(i.sizeX,o++),n.writeUInt8(i.sizeY,o++);for(let s of i.data)n.writeUInt8(s.charCode,o++),n.writeUInt8(s.fgColorId,o++),n.writeUInt8(s.bgColorId,o++)}return n.toUint8Array()}encodeSound(e){let t=e.sounds.length;if(t>255)throw new Error(`Sound count ${t} exceeds maximum of 255`);let r=2;for(let i of e.sounds){if(i.midiData.length>65535)throw new Error(`Sound ${i.soundId}: MIDI data size ${i.midiData.length} exceeds maximum of 65535 bytes`);r+=3,r+=i.midiData.length}let n=C.allocUnsafe(r),o=0;n.writeUInt8(5,o++),n.writeUInt8(t,o++);for(let i of e.sounds){n.writeUInt8(i.soundId,o++),n.writeUInt16BE(i.midiData.length,o),o+=2;for(let s=0;s<i.midiData.length;s++)n.writeUInt8(i.midiData[s],o++)}return n.toUint8Array()}encodeImageFont(e){if(![1,4,16].includes(e.atlasBlocks))throw new Error(`Invalid atlasBlocks value: ${e.atlasBlocks}. Must be 1, 4, or 16.`);let r=C.allocUnsafe(6),n=0;return r.writeUInt8(8,n++),r.writeUInt8(e.glyphWidth,n++),r.writeUInt8(e.glyphHeight,n++),r.writeUInt8(e.cellWidth,n++),r.writeUInt8(e.cellHeight,n++),r.writeUInt8(e.atlasBlocks,n++),r.toUint8Array()}encodeImageFontBlock(e){let t=6+e.imageData.length,r=C.allocUnsafe(t),n=0;r.writeUInt8(9,n++),r.writeUInt8(e.blockIndex,n++),r.writeUInt32LE(e.imageData.length,n),n+=4;for(let o=0;o<e.imageData.length;o++)r.writeUInt8(e.imageData[o],n++);return r.toUint8Array()}};b(Nr,"LoadEncoder");var le=Nr;V();var Yr=class Yr{decode(e,t=0){let r=t,n=e.readUInt8(t++);if(n!==7)throw new Error(`Expected LoadType.Macro (0x07), got 0x${n.toString(16)}`);let o=e.readUInt8(t++),i=e.readUInt16BE(t);t+=2;let s=e.toUint8Array().subarray(t,t+i);t+=i;let a=new TextDecoder().decode(s),d=JSON.parse(a);return{load:{loadType:7,macroId:o,template:d},bytesRead:t-r}}};b(Yr,"MacroLoadDecoder");var ct=Yr;var Hr=class Hr{decode(e,t=0){let r=C.from(e);if(t>=r.length)throw new Error("Buffer too short to decode load type");let n=r.readUInt8(t);switch(n){case 1:return this.decodeColorPalette(r,t);case 2:return this.decodeSprite(r,t);case 3:return this.decodeMulticolorSprite(r,t);case 5:return this.decodeSound(r,t);case 7:return this.decodeMacro(r,t);case 8:return this.decodeImageFont(r,t);case 9:return this.decodeImageFontBlock(r,t);default:throw new Error(`Unknown load type: 0x${n.toString(16)}`)}}decodeColorPalette(e,t){let r=t;this.checkSize(e,t,3,"ColorPalette header");let n=e.readUInt8(t++),i=e.readUInt8(t++)===255,s;i&&(this.checkSize(e,t,1,"ColorPalette slotId"),s=e.readUInt8(t++));let a=e.readUInt8(t++);this.checkSize(e,t,a*6,`ColorPalette ${a} colors`);let d=[];for(let c=0;c<a;c++)d.push({colorId:e.readUInt8(t++),r:e.readUInt8(t++),g:e.readUInt8(t++),b:e.readUInt8(t++),a:e.readUInt8(t++),e:e.readUInt8(t++)});return{load:{loadType:1,...s!==void 0&&{slotId:s},colors:d},bytesRead:t-r}}decodeSprite(e,t){let r=t;this.checkSize(e,t,2,"Sprite header");let n=e.readUInt8(t++),o=e.readUInt8(t++),i=[];for(let a=0;a<o;a++){this.checkSize(e,t,3,`Sprite ${a} header`);let d=e.readUInt8(t++),l=e.readUInt8(t++),c=e.readUInt8(t++),u=l*c;this.checkSize(e,t,u,`Sprite ${a} data`);let p=[];for(let m=0;m<u;m++)p.push(e.readUInt8(t++));i.push({spriteId:d,sizeX:l,sizeY:c,data:p})}return{load:{loadType:2,sprites:i},bytesRead:t-r}}decodeMulticolorSprite(e,t){let r=t;this.checkSize(e,t,2,"MulticolorSprite header");let n=e.readUInt8(t++),o=e.readUInt8(t++),i=[];for(let a=0;a<o;a++){this.checkSize(e,t,3,`MulticolorSprite ${a} header`);let d=e.readUInt8(t++),l=e.readUInt8(t++),c=e.readUInt8(t++),u=l*c;this.checkSize(e,t,u*3,`MulticolorSprite ${a} data`);let p=[];for(let m=0;m<u;m++)p.push({charCode:e.readUInt8(t++),fgColorId:e.readUInt8(t++),bgColorId:e.readUInt8(t++)});i.push({spriteId:d,sizeX:l,sizeY:c,data:p})}return{load:{loadType:3,sprites:i},bytesRead:t-r}}decodeSound(e,t){let r=t;this.checkSize(e,t,2,"Sound header");let n=e.readUInt8(t++),o=e.readUInt8(t++),i=[];for(let a=0;a<o;a++){this.checkSize(e,t,3,`Sound ${a} header`);let d=e.readUInt8(t++),l=e.readUInt16BE(t);t+=2,this.checkSize(e,t,l,`Sound ${a} MIDI data`);let c=new Uint8Array(l);for(let u=0;u<l;u++)c[u]=e.readUInt8(t++);i.push({soundId:d,midiData:c})}return{load:{loadType:5,sounds:i},bytesRead:t-r}}checkSize(e,t,r,n){if(t+r>e.length)throw new Error(`Buffer too short for ${n}: need ${r} bytes at offset ${t}, but only ${e.length-t} bytes remaining`)}decodeMacro(e,t){return new ct().decode(e,t)}decodeImageFont(e,t){let r=t;this.checkSize(e,t,6,"ImageFont header");let n=e.readUInt8(t++),o=e.readUInt8(t++),i=e.readUInt8(t++),s=e.readUInt8(t++),a=e.readUInt8(t++),d=e.readUInt8(t++);if(![1,4,16].includes(d))throw new Error(`Invalid atlasBlocks value: ${d}. Must be 1, 4, or 16.`);let l=d;return{load:{loadType:8,glyphWidth:o,glyphHeight:i,cellWidth:s,cellHeight:a,atlasBlocks:l},bytesRead:t-r}}decodeImageFontBlock(e,t){let r=t;this.checkSize(e,t,2,"ImageFontBlock header");let n=e.readUInt8(t++),o=e.readUInt8(t++);this.checkSize(e,t,4,"ImageFontBlock data size");let i=e.readUInt32LE(t);t+=4,this.checkSize(e,t,i,"ImageFontBlock data");let s=new Uint8Array(i);for(let d=0;d<i;d++)s[d]=e.readUInt8(t++);return{load:{loadType:9,blockIndex:o,imageData:s},bytesRead:t-r}}};b(Hr,"LoadDecoder");var ut=Hr;var X=class X{constructor(e){this.engine=e;h(this,"colorCache",new Array(256));h(this,"cellsBuffer",[]);h(this,"opacityBuffer",new Uint8Array(0));h(this,"visibleLayersBuffer",[]);h(this,"visibleLayerIdsBuffer",[]);h(this,"passCellsBuffers",[]);h(this,"passOpacityBuffers",[]);this.rebuildColorCache()}static getChar(e){let t=X.charCache.get(e);return t===void 0&&(t=String.fromCharCode(e),X.charCache.set(e,t)),t}getLastVisibleLayerIds(){return this.visibleLayerIdsBuffer}rebuildColorCache(){for(let e=0;e<256;e++){let t=this.engine.getColor(e);t?this.colorCache[e]={r:t.r,g:t.g,b:t.b,a:t.a}:this.colorCache[e]={r:0,g:0,b:0,a:0}}}getColorRGB(e){return this.colorCache[e]??this.colorCache[255]}getColorEmission(e){let t=this.engine.getColor(e);return t?t.e:0}isLayerVisible(e,t){let r=e.x,n=e.x+e.width,o=e.y,i=e.y+e.height,s=t.x,a=t.x+256,d=t.y,l=t.y+256;return!(n<=s||r>=a||i<=d||o>=l)}rasterize(e,t,r){let n=this.normalizePasses(r);return this.rasterizeMultiPass(e,t,n)}rasterizeSinglePass(e,t){let r=e.width*e.height,n=this.cellsBuffer;n.length=r;for(let d=0;d<r;d++)n[d]?(n[d].char=" ",n[d].fgColorIndex=255,n[d].bgColorIndex=255,n[d].fgEmission=0,n[d].bgEmission=0):n[d]={char:" ",fgColorIndex:255,bgColorIndex:255,fgEmission:0,bgEmission:0};this.opacityBuffer.length<r?this.opacityBuffer=new Uint8Array(r):this.opacityBuffer.fill(0,0,r);let o=this.opacityBuffer,i=this.visibleLayersBuffer;i.length=0;for(let d=0;d<t.length;d++){let l=t[d];l.isEnabled()&&this.isLayerVisible(e,l.getOrigin())&&i.push(l)}i.sort((d,l)=>l.getZOrder()-d.getZOrder());let s=this.visibleLayerIdsBuffer;s.length=i.length;for(let d=0;d<i.length;d++)s[d]=i[d].getId();for(let d=0;d<e.height;d++)for(let l=0;l<e.width;l++){let c=d*e.width+l;if(o[c])continue;let u=e.x+l,p=e.y+d;for(let m=0;m<i.length;m++){let g=i[m],y=u-g.getOrigin().x,S=p-g.getOrigin().y,w=g.getWidth(),I=g.getHeight();if(y<0||y>=w||S<0||S>=I)continue;let U=S*w+y,M=g.getData(),P=M.getCharCode(U),E=M.getFgColorCode(U),v=M.getBgColorCode(U),f=n[c];if(P!==0&&f.char===" "&&(f.char=X.getChar(P)),E!==255&&f.fgColorIndex===255&&(f.fgColorIndex=E,f.fgEmission=this.getColorEmission(E)),v!==255){f.bgColorIndex===255&&(f.bgColorIndex=v,f.bgEmission=this.getColorEmission(v)),o[c]=1;break}}}let a=new Array(r);for(let d=0;d<r;d++)a[d]={char:n[d].char,fgColorIndex:n[d].fgColorIndex,bgColorIndex:n[d].bgColorIndex,fgEmission:n[d].fgEmission,bgEmission:n[d].bgEmission};return{id:e.id,width:e.width,height:e.height,cells:a,palette:this.colorCache}}rasterizeMultiPass(e,t,r){let n=e.width*e.height;this.ensurePassBuffers(r.length,n),this.visibleLayerIdsBuffer.length=0;let o=this.visibleLayersBuffer;o.length=0;for(let l=0;l<t.length;l++){let c=t[l];c.isEnabled()&&this.isLayerVisible(e,c.getOrigin())&&o.push(c)}o.sort((l,c)=>c.getZOrder()-l.getZOrder());for(let l=0;l<r.length;l++){let c=r[l],u=this.passCellsBuffers[l],p=this.preparePassBuffers(u,this.passOpacityBuffers[l],n);this.passOpacityBuffers[l]=p;let m=[];for(let y=0;y<o.length;y++){let S=o[y],w=S.getZOrder();w<c.zMin||w>c.zMax||m.push(S)}let g=this.visibleLayerIdsBuffer.length;for(let y=0;y<m.length;y++)this.visibleLayerIdsBuffer[g+y]=m[y].getId();this.composePass(e,m,u,p)}let i=this.cellsBuffer,s=this.preparePassBuffers(i,this.opacityBuffer,n);this.opacityBuffer=s;let a=new Array(n),d=[];for(let l=0;l<r.length;l++){let c=this.passCellsBuffers[l],u=new Array(n);for(let p=0;p<n;p++){let m=c[p];u[p]={char:m.char,fgColorIndex:m.fgColorIndex,bgColorIndex:m.bgColorIndex,fgEmission:m.fgEmission,bgEmission:m.bgEmission}}d.push({id:r[l].id,zMin:r[l].zMin,zMax:r[l].zMax,cells:u})}for(let l=0;l<n;l++){let c=i[l];for(let u=r.length-1;u>=0;u--){let p=this.passCellsBuffers[u][l];if(c.char===" "&&p.char!==" "&&(c.char=p.char),c.fgColorIndex===255&&p.fgColorIndex!==255&&(c.fgColorIndex=p.fgColorIndex,c.fgEmission=p.fgEmission),p.bgColorIndex!==255){c.bgColorIndex===255&&(c.bgColorIndex=p.bgColorIndex,c.bgEmission=p.bgEmission);break}}a[l]={char:c.char,fgColorIndex:c.fgColorIndex,bgColorIndex:c.bgColorIndex,fgEmission:c.fgEmission,bgEmission:c.bgEmission}}return{id:e.id,width:e.width,height:e.height,cells:a,palette:this.colorCache,passes:d}}composePass(e,t,r,n){let o=e.width,i=e.height;for(let s=0;s<i;s++)for(let a=0;a<o;a++){let d=s*o+a;if(n[d])continue;let l=e.x+a,c=e.y+s;for(let u=0;u<t.length;u++){let p=t[u],m=l-p.getOrigin().x,g=c-p.getOrigin().y,y=p.getWidth(),S=p.getHeight();if(m<0||m>=y||g<0||g>=S)continue;let w=g*y+m,I=p.getData(),U=I.getCharCode(w),M=I.getFgColorCode(w),P=I.getBgColorCode(w),E=r[d];if(U!==0&&E.char===" "&&(E.char=X.getChar(U)),M!==255&&E.fgColorIndex===255&&(E.fgColorIndex=M,E.fgEmission=this.getColorEmission(M)),P!==255){E.bgColorIndex===255&&(E.bgColorIndex=P,E.bgEmission=this.getColorEmission(P)),n[d]=1;break}}}}preparePassBuffers(e,t,r){e.length=r;for(let n=0;n<r;n++)e[n]?(e[n].char=" ",e[n].fgColorIndex=255,e[n].bgColorIndex=255,e[n].fgEmission=0,e[n].bgEmission=0):e[n]={char:" ",fgColorIndex:255,bgColorIndex:255,fgEmission:0,bgEmission:0};return t.length<r?t=new Uint8Array(r):t.fill(0,0,r),t}ensurePassBuffers(e,t){for(;this.passCellsBuffers.length<e;)this.passCellsBuffers.push([]);for(;this.passOpacityBuffers.length<e;)this.passOpacityBuffers.push(new Uint8Array(t));this.passCellsBuffers.length>e&&(this.passCellsBuffers.length=e),this.passOpacityBuffers.length>e&&(this.passOpacityBuffers.length=e);for(let r=0;r<e;r++)this.passOpacityBuffers[r].length<t?this.passOpacityBuffers[r]=new Uint8Array(t):this.passOpacityBuffers[r].fill(0,0,t)}normalizePasses(e){let t={id:0,zMin:0,zMax:255,enabled:!0};if(!e||e.length===0)return[t];let r=e.filter(n=>n.enabled!==!1);return r.length===0?[t]:r.slice(0,4)}rasterizeWithSortedLayers(e,t){let r=e.width*e.height,n=this.cellsBuffer;n.length=r;for(let a=0;a<r;a++)n[a]?(n[a].char=" ",n[a].fgColorIndex=255,n[a].bgColorIndex=255,n[a].fgEmission=0,n[a].bgEmission=0):n[a]={char:" ",fgColorIndex:255,bgColorIndex:255,fgEmission:0,bgEmission:0};this.opacityBuffer.length<r?this.opacityBuffer=new Uint8Array(r):this.opacityBuffer.fill(0,0,r);let o=this.opacityBuffer,i=this.visibleLayersBuffer;i.length=0;for(let a=0;a<t.length;a++){let d=t[a];this.isLayerVisible(e,d.getOrigin())&&i.push(d)}for(let a=0;a<e.height;a++)for(let d=0;d<e.width;d++){let l=a*e.width+d;if(o[l])continue;let c=e.x+d,u=e.y+a;for(let p=0;p<i.length;p++){let m=i[p],g=c-m.getOrigin().x,y=u-m.getOrigin().y,S=m.getWidth(),w=m.getHeight();if(g<0||g>=S||y<0||y>=w)continue;let I=y*S+g,U=m.getData(),M=U.getCharCode(I),P=U.getFgColorCode(I),E=U.getBgColorCode(I),v=n[l];if(M!==0&&v.char===" "&&(v.char=X.getChar(M)),P!==255&&v.fgColorIndex===255&&(v.fgColorIndex=P,v.fgEmission=this.getColorEmission(P)),E!==255){v.bgColorIndex===255&&(v.bgColorIndex=E,v.bgEmission=this.getColorEmission(E)),o[l]=1;break}}}let s=new Array(r);for(let a=0;a<r;a++)s[a]={char:n[a].char,fgColorIndex:n[a].fgColorIndex,bgColorIndex:n[a].bgColorIndex,fgEmission:n[a].fgEmission,bgEmission:n[a].bgEmission};return{id:e.id,width:e.width,height:e.height,cells:s,palette:this.colorCache}}calculateIntersection(e,t){let r=e.x,n=e.x+e.width,o=e.y,i=e.y+e.height,s=t.x,a=t.x+256,d=t.y,l=t.y+256,c=Math.max(r,s),u=Math.min(n,a),p=Math.max(o,d),m=Math.min(i,l);return{visible:c<u&&p<m,originStart:{x:c-e.x,y:p-e.y},originEnd:{x:u-e.x,y:m-e.y},layerStart:{x:c-t.x,y:p-t.y},layerEnd:{x:u-t.x,y:m-t.y}}}};b(X,"DisplayRasterizer"),h(X,"charCache",(()=>{let e=new Map;for(let t=0;t<256;t++)e.set(t,String.fromCharCode(t));return e})());var pt=X;var Xr=class Xr{constructor(){h(this,"enabled",!1);h(this,"currentStats",null)}setEnabled(e){this.enabled=e,e||(this.currentStats=null)}isEnabled(){return this.enabled}get tick(){return this.currentStats?.tick??0}get timestamp(){return this.currentStats?.timestamp??0}get totalOrders(){return this.currentStats?.totalOrders??0}get ordersByLayer(){return this.currentStats?.ordersByLayer??new Map}get ordersByType(){return this.currentStats?.ordersByType??new Map}get totalLayers(){return this.currentStats?.totalLayers??0}get visibleLayers(){return this.currentStats?.visibleLayers??0}get layersPerDisplay(){return this.currentStats?.layersPerDisplay??new Map}get displayCompositeLayerIds(){return this.currentStats?.displayCompositeLayerIds??new Map}get updatePacketSize(){return this.currentStats?.updatePacketSize??0}get displayHeaderSize(){return this.currentStats?.displayHeaderSize??0}get layerHeaderSize(){return this.currentStats?.layerHeaderSize??0}get orderDataSize(){return this.currentStats?.orderDataSize??0}get compressionRatio(){return this.currentStats?.compressionRatio??0}get compressedPacketSize(){return Math.round(this.updatePacketSize*this.compressionRatio)}get totalCells(){return this.currentStats?.totalCells??0}get nonEmptyCells(){return this.currentStats?.nonEmptyCells??0}get cellsWithBackground(){return this.currentStats?.cellsWithBackground??0}get rasterizationTimeMs(){return this.currentStats?.rasterizationTimeMs??0}get encodingTimeMs(){return this.currentStats?.encodingTimeMs??0}get packetSplit(){return this.currentStats?.packetSplit}get layerDetails(){return this.currentStats?.layerDetails}startTick(e){this.enabled&&(this.currentStats={tick:e,timestamp:Date.now(),totalOrders:0,ordersByLayer:new Map,ordersByType:new Map,totalLayers:0,visibleLayers:0,layersPerDisplay:new Map,updatePacketSize:0,displayHeaderSize:0,layerHeaderSize:0,orderDataSize:0,compressionRatio:0,totalCells:0,nonEmptyCells:0,cellsWithBackground:0,rasterizationTimeMs:0,encodingTimeMs:0,displayCompositeLayerIds:new Map})}recordDisplayComposite(e,t){!this.enabled||!this.currentStats||(this.currentStats.displayCompositeLayerIds||(this.currentStats.displayCompositeLayerIds=new Map),this.currentStats.displayCompositeLayerIds.set(e,[...t]))}recordLayerOrders(e,t){if(!(!this.enabled||!this.currentStats)){this.currentStats.totalOrders+=t.length,this.currentStats.ordersByLayer.set(e,t.length);for(let r of t){let n=this.currentStats.ordersByType.get(r.type)||0;this.currentStats.ordersByType.set(r.type,n+1)}}}recordLayers(e,t){!this.enabled||!this.currentStats||(this.currentStats.totalLayers=e,this.currentStats.visibleLayers=t)}recordDisplayLayers(e,t){!this.enabled||!this.currentStats||this.currentStats.layersPerDisplay.set(e,t)}recordUpdatePacketSize(e,t,r,n){!this.enabled||!this.currentStats||(this.currentStats.updatePacketSize=e,this.currentStats.displayHeaderSize=t,this.currentStats.layerHeaderSize=r,this.currentStats.orderDataSize=n,this.currentStats.compressionRatio=.25)}recordPacketSplit(e,t,r,n){!this.enabled||!this.currentStats||(this.currentStats.packetSplit={userId:e,displayCount:t,staticLayerCount:r,dynamicLayerCount:n})}recordLayerInfo(e,t,r,n){!this.enabled||!this.currentStats||(this.currentStats.layerDetails||(this.currentStats.layerDetails=[]),this.currentStats.layerDetails.push({layerId:e,mustBeReliable:t,orderCount:r,updateFlags:n}))}recordRenderStats(e,t,r){!this.enabled||!this.currentStats||(this.currentStats.totalCells=e,this.currentStats.nonEmptyCells=t,this.currentStats.cellsWithBackground=r)}recordRasterizationTime(e){!this.enabled||!this.currentStats||(this.currentStats.rasterizationTimeMs=e)}recordEncodingTime(e){!this.enabled||!this.currentStats||(this.currentStats.encodingTimeMs=e)}endTick(){}reset(){this.currentStats=null}};b(Xr,"CoreStats");var ce=Xr;var _n=[[0,0],[9786,1],[9787,2],[9829,3],[9830,4],[9827,5],[9824,6],[8226,7],[9688,8],[9675,9],[9689,10],[9794,11],[9792,12],[9834,13],[9835,14],[9788,15],[9658,16],[9668,17],[8597,18],[8252,19],[182,20],[167,21],[9644,22],[8616,23],[8593,24],[8595,25],[8594,26],[8592,27],[8735,28],[8596,29],[9650,30],[9660,31],[8962,127],[199,128],[252,129],[233,130],[226,131],[228,132],[224,133],[229,134],[231,135],[234,136],[235,137],[232,138],[239,139],[238,140],[236,141],[196,142],[197,143],[201,144],[230,145],[198,146],[244,147],[246,148],[242,149],[251,150],[249,151],[255,152],[214,153],[220,154],[162,155],[163,156],[165,157],[8359,158],[402,159],[225,160],[237,161],[243,162],[250,163],[241,164],[209,165],[170,166],[186,167],[191,168],[8976,169],[172,170],[189,171],[188,172],[161,173],[171,174],[187,175],[9617,176],[9618,177],[9619,178],[9474,179],[9508,180],[9569,181],[9570,182],[9558,183],[9557,184],[9571,185],[9553,186],[9559,187],[9565,188],[9564,189],[9563,190],[9488,191],[9492,192],[9524,193],[9516,194],[9500,195],[9472,196],[9532,197],[9566,198],[9567,199],[9562,200],[9556,201],[9577,202],[9574,203],[9568,204],[9552,205],[9580,206],[9575,207],[9576,208],[9572,209],[9573,210],[9561,211],[9560,212],[9554,213],[9555,214],[9579,215],[9578,216],[9496,217],[9484,218],[9608,219],[9604,220],[9612,221],[9616,222],[9600,223],[945,224],[223,225],[915,226],[960,227],[931,228],[963,229],[181,230],[964,231],[934,232],[920,233],[937,234],[948,235],[8734,236],[966,237],[949,238],[8745,239],[8801,240],[177,241],[8805,242],[8804,243],[8992,244],[8993,245],[247,246],[8776,247],[176,248],[8729,249],[183,250],[8730,251],[8319,252],[178,253],[9632,254],[160,255]],Uo=new Map(_n),Xs=new Map(_n.map(([x,e])=>[e,x]));function j(x){if(x<128)return x;let e=Uo.get(x);return e!==void 0?e:x&255}b(j,"unicodeToCp437");var Gr=class Gr{constructor(){h(this,"unicolorSprites",new Map);h(this,"multicolorSprites",new Map)}loadUnicolorSprites(e){if("loadType"in e){this.loadUnicolorSpritesFromPacket(e);return}for(let t of e){let{spriteId:r,sizeX:n,sizeY:o,data:i}=t,s=new Z(n*o);if(typeof i=="string"){let d=i.replace(/\n/g,"");for(let l=0;l<Math.min(d.length,n*o);l++)s.set(l,j(d.charCodeAt(l)))}else if(Array.isArray(i)&&i.length>0&&typeof i[0]=="string"){let d=i;for(let l=0;l<Math.min(d.length,o);l++){let c=d[l];if(c)for(let u=0;u<Math.min(c.length,n);u++)s.set(l*n+u,j(c.charCodeAt(u)))}}else{let d=i;for(let l=0;l<Math.min(d.length,n*o);l++)s.set(l,d[l])}let a={id:r,sizeX:n,sizeY:o,data:s};this.unicolorSprites.set(a.id,a)}}loadUnicolorSpritesFromPacket(e){for(let t of e.sprites){let r=new Z(t.sizeX*t.sizeY);for(let o=0;o<t.data.length;o++)r.set(o,t.data[o]);let n={id:t.spriteId,sizeX:t.sizeX,sizeY:t.sizeY,data:r};this.unicolorSprites.set(n.id,n)}}loadMulticolorSprites(e){if("loadType"in e){this.loadMulticolorSpritesFromPacket(e);return}for(let t of e){let{spriteId:r,sizeX:n,sizeY:o,data:i}=t,s=new Y(n*o);for(let d=0;d<Math.min(i.length,n*o);d++){let l=i[d],c=typeof l.charCode=="string"?j(l.charCode.charCodeAt(0)):l.charCode;s.set(d,c,l.fgColorId,l.bgColorId)}let a={id:r,sizeX:n,sizeY:o,data:s};this.multicolorSprites.set(a.id,a)}}loadMulticolorSpritesFromPacket(e){for(let t of e.sprites){let r=new Y(t.sizeX*t.sizeY);for(let o=0;o<t.data.length;o++){let i=t.data[o];r.set(o,i.charCode,i.fgColorId,i.bgColorId)}let n={id:t.spriteId,sizeX:t.sizeX,sizeY:t.sizeY,data:r};this.multicolorSprites.set(n.id,n)}}getUnicolorSprite(e){return this.unicolorSprites.get(e)}getMulticolorSprite(e){return this.multicolorSprites.get(e)}hasUnicolorSprite(e){return this.unicolorSprites.has(e)}hasMulticolorSprite(e){return this.multicolorSprites.has(e)}unloadUnicolorSprite(e){return this.unicolorSprites.delete(e)}unloadMulticolorSprite(e){return this.multicolorSprites.delete(e)}clearUnicolorSprites(){this.unicolorSprites.clear()}clearMulticolorSprites(){this.multicolorSprites.clear()}clearAll(){this.unicolorSprites.clear(),this.multicolorSprites.clear()}getUnicolorSpriteCount(){return this.unicolorSprites.size}getMulticolorSpriteCount(){return this.multicolorSprites.size}getTotalSpriteCount(){return this.unicolorSprites.size+this.multicolorSprites.size}};b(Gr,"SpriteRegistry");var ue=Gr;var $r=(t=>(t.Bitmap="bitmap",t.Image="image",t))($r||{});function mt(x){return Math.sqrt(x)*16}b(mt,"getAtlasColumns");function Zr(x){return x*256-1}b(Zr,"getMaxCharCode");function Nn(x,e){let r=mt(x)*e;return{width:r,height:r}}b(Nn,"getAtlasDimensions");var Wr=class Wr{constructor(e,t){this.fontId=e;this.config=t;h(this,"atlasColumns");h(this,"maxCharCode");h(this,"blocks",new Map);this.atlasColumns=mt(t.atlasBlocks),this.maxCharCode=Zr(t.atlasBlocks)}addBlock(e,t){if(e<0||e>=this.config.atlasBlocks)throw new Error(`Invalid block index ${e} for font with ${this.config.atlasBlocks} blocks`);this.blocks.set(e,t)}getBlock(e){return this.blocks.get(e)}getFontId(){return this.fontId}getConfig(){return{glyphWidth:this.config.glyphWidth,glyphHeight:this.config.glyphHeight,cellWidth:this.config.cellWidth,cellHeight:this.config.cellHeight,atlasBlocks:this.config.atlasBlocks}}getGlyphWidth(){return this.config.glyphWidth}getGlyphHeight(){return this.config.glyphHeight}getCellWidth(){return this.config.cellWidth??this.config.glyphWidth}getCellHeight(){return this.config.cellHeight??this.config.glyphHeight}getAtlasBlocks(){return this.config.atlasBlocks}getAtlasColumns(){return this.atlasColumns}getMaxCharCode(){return this.maxCharCode}getAtlasDimensions(){return{width:this.atlasColumns*this.config.glyphWidth,height:this.atlasColumns*this.config.glyphHeight}}getCharUV(e){if(e<0||e>this.maxCharCode)return null;let t=e%this.atlasColumns,r=Math.floor(e/this.atlasColumns),n=t/this.atlasColumns,o=r/this.atlasColumns,i=(t+1)/this.atlasColumns,s=(r+1)/this.atlasColumns;return{u1:n,v1:o,u2:i,v2:s}}isValidCharCode(e){return e>=0&&e<=this.maxCharCode}};b(Wr,"ImageFont");var J=Wr;var jr=class jr{constructor(){h(this,"fonts",new Map);h(this,"nameToId",new Map);h(this,"nextId",0)}allocateId(e){if(this.nextId>255)throw new Error(`Cannot register font "${e}": maximum 256 fonts reached`);return this.nextId++}registerFont(e,t){if(this.nameToId.has(e))throw new Error(`ImageFont with name "${e}" already exists`);let r=this.allocateId(e),n={glyphWidth:t.glyphWidth,glyphHeight:t.glyphHeight,cellWidth:t.cellWidth,cellHeight:t.cellHeight,atlasBlocks:t.atlasBlocks??1},o=new J(r,n);return this.fonts.set(r,o),this.nameToId.set(e,r),r}addBlock(e,t,r){let n=this.fonts.get(e);if(!n)throw new Error(`ImageFont with ID ${e} not found`);n.addBlock(t,r)}loadFont(e,t){if(this.fonts.has(e))throw new Error(`ImageFont with ID ${e} already exists`);let r=new J(e,t);this.fonts.set(e,r),e>=this.nextId&&(this.nextId=e+1)}getFont(e){return this.fonts.get(e)}getFontByName(e){let t=this.nameToId.get(e);if(t!==void 0)return this.fonts.get(t)}getFontId(e){return this.nameToId.get(e)}getFontName(e){for(let[t,r]of this.nameToId.entries())if(r===e)return t}hasFont(e){return this.fonts.has(e)}hasFontByName(e){return this.nameToId.has(e)}unloadFont(e){if(!this.fonts.get(e))return!1;for(let[r,n]of this.nameToId.entries())if(n===e){this.nameToId.delete(r);break}return this.fonts.delete(e)}unloadFontByName(e){let t=this.nameToId.get(e);return t===void 0?!1:(this.nameToId.delete(e),this.fonts.delete(t))}clearFonts(){this.fonts.clear(),this.nameToId.clear(),this.nextId=0}getFontIds(){return Array.from(this.fonts.keys()).sort((e,t)=>e-t)}getFontNames(){return Array.from(this.nameToId.keys())}getAllFonts(){return Array.from(this.fonts.entries()).sort((e,t)=>e[0]-t[0]).map(e=>e[1])}getFontCount(){return this.fonts.size}};b(jr,"ImageFontRegistry");var pe=jr;var Jr=class Jr{constructor(){h(this,"sounds",new Map);h(this,"nameToId",new Map);h(this,"nextId",0)}registerFile(e,t,r){let n=this.allocateId(e),o={soundId:n,name:e,loadType:"file",format:t,data:r};return this.sounds.set(n,o),this.nameToId.set(e,n),n}registerFileWithId(e,t,r,n){this.validateId(e),this.checkIdAvailable(e,t);let o={soundId:e,name:t,loadType:"file",format:r,data:n};this.sounds.set(e,o),this.nameToId.set(t,e)}registerExternal(e,t,r,n,o){let i=this.allocateId(e),s={soundId:i,name:e,loadType:"external",format:t,url:r,size:n,checksum:o};return this.sounds.set(i,s),this.nameToId.set(e,i),i}registerExternalWithId(e,t,r,n,o,i){this.validateId(e),this.checkIdAvailable(e,t);let s={soundId:e,name:t,loadType:"external",format:r,url:n,size:o,checksum:i};this.sounds.set(e,s),this.nameToId.set(t,e)}get(e){if(typeof e=="number")return this.sounds.get(e);let t=this.nameToId.get(e);return t!==void 0?this.sounds.get(t):void 0}has(e){return this.get(e)!==void 0}getAll(){return Array.from(this.sounds.values())}getFileSounds(){return this.getAll().filter(e=>e.loadType==="file")}getExternalSounds(){return this.getAll().filter(e=>e.loadType==="external")}getNames(){return Array.from(this.nameToId.keys())}getId(e){return this.nameToId.get(e)}toLoadPackets(){let e=[],t=this.sounds.size,r=this.getFileSounds();if(r.length>0){let o=r.map(i=>({soundId:i.soundId,name:i.name,format:i.format,data:i.data}));e.push({type:"sound",mode:"file",sounds:o,totalSounds:t})}let n=this.getExternalSounds();if(n.length>0){let o=n.map(i=>({soundId:i.soundId,name:i.name,format:i.format,url:i.url,size:i.size,checksum:i.checksum}));e.push({type:"sound",mode:"external",sounds:o,totalSounds:t})}return e}toLoadPacket(e){let t=this.get(e);return t?t.loadType==="file"?{type:"sound",mode:"file",sounds:[{soundId:t.soundId,name:t.name,format:t.format,data:t.data}]}:{type:"sound",mode:"external",sounds:[{soundId:t.soundId,name:t.name,format:t.format,url:t.url,size:t.size,checksum:t.checksum}]}:null}unregister(e){let t=this.get(e);return t?(this.sounds.delete(t.soundId),this.nameToId.delete(t.name),!0):!1}clear(){this.sounds.clear(),this.nameToId.clear(),this.nextId=0}get size(){return this.sounds.size}getStats(){let e=this.getAll(),t=e.filter(n=>n.loadType==="file"),r=t.reduce((n,o)=>n+(o.data?.length??0),0);return{total:e.length,file:t.length,external:e.length-t.length,totalFileSize:r}}allocateId(e){if(this.nameToId.has(e))throw new Error(`Sound with name "${e}" already exists`);for(;this.sounds.has(this.nextId);)if(this.nextId++,this.nextId>255)throw new Error("Maximum number of sounds (256) reached");return this.nextId++}validateId(e){if(!Number.isInteger(e)||e<0||e>255)throw new Error(`Invalid sound ID: ${e}. Must be an integer between 0 and 255.`)}checkIdAvailable(e,t){if(this.sounds.has(e)){let r=this.sounds.get(e);throw new Error(`Sound ID ${e} is already used by "${r.name}". Cannot register "${t}".`)}if(this.nameToId.has(t))throw new Error(`Sound with name "${t}" already exists`)}};b(Jr,"SoundRegistry");var me=Jr;var qr=class qr{constructor(e){this.soundRegistry=e}collectFromUser(e){let t=[],r=e.flushSoundCommands();for(let o of r){let i=this.convertSoundCommand(o);i&&t.push(i)}let n=e.flushAudioConfigCommands();for(let o of n){let i=this.convertConfigCommand(o);i&&t.push(i)}return t}convertSoundCommand(e){return"setEffects"in e&&e.setEffects===!0?this.convertSetEffectsCommand(e):"fadeOut"in e&&e.fadeOut===!0?this.convertFadeOutCommand(e):"pause"in e&&e.pause===!0?this.convertPauseCommand(e):"resume"in e&&e.resume===!0?this.convertResumeCommand(e):"instanceId"in e||"volume"in e||"pitch"in e||"loop"in e||"fadeIn"in e||"x"in e||"y"in e||"lowpass"in e||"highpass"in e||"reverb"in e?this.convertPlayCommand(e):this.convertStopCommand(e)}convertPlayCommand(e){let t=this.resolveSoundId(e.sound);if(t===null)return console.warn(`[AudioOrderCollector] Unknown sound: ${e.sound}`),null;let r=0;e.loop&&(r|=1),e.volume!==void 0&&(r|=2),e.pitch!==void 0&&(r|=4),e.fadeIn!==void 0&&(r|=8),e.lowpass!==void 0&&e.lowpass>0&&(r|=32),e.highpass!==void 0&&e.highpass>0&&(r|=64),e.reverb!==void 0&&e.reverb>0&&(r|=128);let n=e.x!==void 0&&e.y!==void 0;return n&&(r|=16),n?{type:1,soundId:t,instanceId:e.instanceId??0,flags:r,volume:e.volume!==void 0?this.encodeVolume(e.volume):void 0,pitch:e.pitch!==void 0?this.encodePitch(e.pitch):void 0,fadeIn:e.fadeIn!==void 0?this.encodeFadeTime(e.fadeIn):void 0,posX:this.encodePosition(e.x),posY:this.encodePosition(e.y),lowpass:e.lowpass!==void 0&&e.lowpass>0?this.encodeFilterFreq(e.lowpass):void 0,highpass:e.highpass!==void 0&&e.highpass>0?this.encodeFilterFreq(e.highpass):void 0,reverb:e.reverb!==void 0&&e.reverb>0?this.encodeReverb(e.reverb):void 0}:{type:2,soundId:t,instanceId:e.instanceId??0,flags:r&-17,volume:e.volume!==void 0?this.encodeVolume(e.volume):void 0,pitch:e.pitch!==void 0?this.encodePitch(e.pitch):void 0,fadeIn:e.fadeIn!==void 0?this.encodeFadeTime(e.fadeIn):void 0,lowpass:e.lowpass!==void 0&&e.lowpass>0?this.encodeFilterFreq(e.lowpass):void 0,highpass:e.highpass!==void 0&&e.highpass>0?this.encodeFilterFreq(e.highpass):void 0,reverb:e.reverb!==void 0&&e.reverb>0?this.encodeReverb(e.reverb):void 0}}convertStopCommand(e){let{targetType:t,target:r}=this.resolveTarget(e.sound);return{type:3,targetType:t,target:r}}convertFadeOutCommand(e){let{targetType:t,target:r}=this.resolveTarget(e.sound);return{type:4,targetType:t,duration:this.encodeFadeTime(e.duration),target:r}}convertPauseCommand(e){let{targetType:t,target:r}=this.resolveTarget(e.sound);return{type:5,targetType:t,target:r}}convertResumeCommand(e){let{targetType:t,target:r}=this.resolveTarget(e.sound);return{type:6,targetType:t,target:r}}convertSetEffectsCommand(e){let t=0;return e.lowpass!==void 0&&(t|=1),e.highpass!==void 0&&(t|=2),e.reverb!==void 0&&(t|=4),{type:9,instanceId:e.instanceId,flags:t,lowpass:e.lowpass!==void 0?this.encodeFilterFreq(e.lowpass):void 0,highpass:e.highpass!==void 0?this.encodeFilterFreq(e.highpass):void 0,reverb:e.reverb!==void 0?this.encodeReverb(e.reverb):void 0}}convertConfigCommand(e){return e.type==="set-listener-position"?{type:7,x:this.encodePosition(e.x),y:this.encodePosition(e.y)}:e.type==="configure-spatial"?{type:8,maxDistance:this.encodeDistance(e.maxDistance??1e3),referenceDistance:this.encodeDistance(e.referenceDistance??100),rolloffFactor:this.encodeRolloff(e.rolloffFactor??1),panSpread:this.encodePanSpread(e.panSpread??.5)}:null}resolveSoundId(e){if(typeof e=="number")return e>=0&&e<=255?e:null;let t=this.soundRegistry.getId(e);return t!==void 0?t:null}resolveTarget(e){if(e==="all")return{targetType:2,target:void 0};if(typeof e=="number")return{targetType:0,target:e};let t=this.soundRegistry.getId(e);return t!==void 0?{targetType:1,target:t}:(console.warn(`[AudioOrderCollector] Unknown sound name: ${e}, treating as 'all'`),{targetType:2,target:void 0})}encodeVolume(e){return Math.round(Math.max(0,Math.min(1,e))*255)}encodePitch(e){let t=Math.max(.25,Math.min(4,e)),r=64*Math.log2(t/.25);return Math.round(Math.max(0,Math.min(255,r)))}encodeFadeTime(e){return Math.round(Math.max(0,Math.min(25.5,e))*10)}encodeDistance(e){return Math.round(Math.max(0,Math.min(25500,e))/100)}encodeRolloff(e){return Math.round(Math.max(0,Math.min(2.55,e))*100)}encodePanSpread(e){return Math.round(Math.max(0,Math.min(1,e))*255)}encodePosition(e){return Math.round(Math.max(0,Math.min(65535,e)))}encodeFilterFreq(e){return e<=0?0:Math.round(Math.max(1,Math.min(255,e/100)))}encodeReverb(e){return Math.round(Math.max(0,Math.min(1,e))*255)}};b(qr,"AudioOrderCollector");var xe=qr;var Kr=class Kr{collectFromUser(e){let t=[];if(e.hasMobileVibrationCommands()){let r=e.flushMobileVibrationCommands();for(let n of r){let o=this.convertMobileCommand(n);o&&t.push(o)}}if(e.hasGamepadVibrationCommands()){let r=e.flushGamepadVibrationCommands();for(let n of r){let o=this.convertGamepadCommand(n);o&&t.push(o)}}return t}convertMobileCommand(e){return"cancel"in e&&e.cancel===!0?this.convertMobileCancelCommand():"pattern"in e?this.convertMobileVibrateCommand(e):null}convertMobileVibrateCommand(e){let t=0;e.intensity!==void 0&&e.intensity!==1&&(t|=1);let r=e.pattern,n=Array.isArray(r)?[...r]:[r],o={type:1,flags:t,pattern:n.map(i=>Math.round(i))};return t&1&&(o.intensity=Math.round(Math.min(1,Math.max(0,e.intensity))*255)/255),o}convertMobileCancelCommand(){return{type:2}}convertGamepadCommand(e){if("cancel"in e&&e.cancel===!0){let t=e.gamepadIndex??"all";return this.convertGamepadCancelCommand({gamepadIndex:t})}if("options"in e&&e.options){let t=e.gamepadIndex??0;return this.convertGamepadVibrateCommand({gamepadIndex:t,options:e.options})}return null}convertGamepadVibrateCommand(e){let{gamepadIndex:t,options:r}=e,n=0;r.startDelay!==void 0&&r.startDelay>0&&(n|=1);let o=t==="all"?255:t;t==="all"&&(n|=2);let i={type:16,flags:n,gamepadIndex:o,duration:Math.round(r.duration),strongMagnitude:Math.round(Math.min(1,Math.max(0,r.strongMagnitude??1))*255),weakMagnitude:Math.round(Math.min(1,Math.max(0,r.weakMagnitude??.5))*255)};return r.startDelay!==void 0&&r.startDelay>0&&(i.startDelay=Math.round(r.startDelay)),i}convertGamepadCancelCommand(e){let{gamepadIndex:t}=e,r=0,n=t==="all"?255:t;return t==="all"&&(r|=2),{type:17,flags:r,gamepadIndex:n}}};b(Kr,"VibrationOrderCollector");var he=Kr;var _=require("@utsp/types");var Qr=class Qr{collectFromUser(e){let t=e.flushPostProcessCommands();return this.convertCommands(t)}convertCommands(e){let t=[];for(let r of e){let n=this.convertCommand(r);n&&t.push(n)}return t}convertCommand(e){let t=e.displayId;switch(e.type){case"set-config":return this.convertSetConfig(e);case"set-scanlines-enabled":return this.createSetScanlinesOrder(t,e.enabled??!1,e.opacity);case"set-scanlines-opacity":return this.createSetScanlinesOrder(t,!0,e.opacity??_.POST_PROCESS_DEFAULTS.scanlines.opacity);case"set-ambient-effect-enabled":return this.createSetAmbientEffectOrder(t,e.enabled??!1);case"set-ambient-effect-blur":return this.createSetAmbientEffectOrder(t,!0,e.blur);case"set-ambient-effect-scale":return this.createSetAmbientEffectOrder(t,!0,void 0,e.scale);case"set-scaling-mode":return this.createSetScalingModeOrder(t,e.scalingMode);case"set-grid":return this.createSetGridOrder(t,e.gridConfig);case"switch-palette":return this.createSwitchPaletteOrder(t,e.paletteSlotId);case"set-cell-size":return this.createSetCellSizeOrder(t,e.cellWidth,e.cellHeight);default:return console.warn(`[PostProcessOrderCollector] Unknown command type: ${e.type}`),null}}convertSetConfig(e){let t=e.displayId;if(!e.config)return{type:1,displayId:t,flags:3,scanlines:{enabled:!1,opacity:0,pattern:0,colorR:0,colorG:0,colorB:0},ambientEffect:{enabled:!1,blur:0,scale:1,opacity:0}};let r=0,n={type:1,displayId:t,flags:0};if(e.config.scanlines){r|=1;let o=e.config.scanlines;n.scanlines={enabled:o.enabled,opacity:o.opacity??_.POST_PROCESS_DEFAULTS.scanlines.opacity,pattern:this.patternToType(o.pattern??"horizontal"),colorR:o.color?.r??0,colorG:o.color?.g??0,colorB:o.color?.b??0}}if(e.config.ambientEffect){r|=2;let o=e.config.ambientEffect;n.ambientEffect={enabled:o.enabled,blur:o.blur??_.POST_PROCESS_DEFAULTS.ambientEffect.blur,scale:o.scale??_.POST_PROCESS_DEFAULTS.ambientEffect.scale,opacity:o.opacity??_.POST_PROCESS_DEFAULTS.ambientEffect.opacity}}return n.flags=r,n}createSetScanlinesOrder(e,t,r){return{type:2,displayId:e,enabled:t,opacity:r??_.POST_PROCESS_DEFAULTS.scanlines.opacity,pattern:0,colorR:0,colorG:0,colorB:0}}createSetAmbientEffectOrder(e,t,r,n){return{type:3,displayId:e,enabled:t,blur:r??_.POST_PROCESS_DEFAULTS.ambientEffect.blur,scale:n??_.POST_PROCESS_DEFAULTS.ambientEffect.scale,opacity:_.POST_PROCESS_DEFAULTS.ambientEffect.opacity}}patternToType(e){switch(e){case"horizontal":return 0;case"vertical":return 1;case"grid":return 2;default:return 0}}createSetScalingModeOrder(e,t){return{type:4,displayId:e,mode:(0,_.scalingModeToValue)(t)}}createSetGridOrder(e,t){let{r,g:n,b:o,a:i}=this.parseColor(t.color??_.GRID_DEFAULTS.color);return{type:5,displayId:e,enabled:t.enabled,colorR:r,colorG:n,colorB:o,colorA:i,lineWidth:t.lineWidth??_.GRID_DEFAULTS.lineWidth}}createSwitchPaletteOrder(e,t){return{type:6,displayId:e,slotId:t}}createSetCellSizeOrder(e,t,r){return{type:7,displayId:e,cellWidth:t,cellHeight:r}}parseColor(e){let t=e.match(/rgba?\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*([\d.]+))?\s*\)/);if(t)return{r:parseInt(t[1],10),g:parseInt(t[2],10),b:parseInt(t[3],10),a:t[4]?Math.round(parseFloat(t[4])*255):255};let r=e.match(/^#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})$/);if(r){let n=r[1];return n.length===3?{r:parseInt(n[0]+n[0],16),g:parseInt(n[1]+n[1],16),b:parseInt(n[2]+n[2],16),a:255}:{r:parseInt(n.slice(0,2),16),g:parseInt(n.slice(2,4),16),b:parseInt(n.slice(4,6),16),a:255}}return{r:144,g:24,b:24,a:255}}};b(Qr,"PostProcessOrderCollector");var be=Qr;var fe=class fe{constructor(e={}){h(this,"mode");h(this,"maxUsers");h(this,"strictMode",!1);h(this,"currentTick",0);h(this,"stats",new ce);h(this,"spriteRegistry",new ue);h(this,"imageFontRegistry",new pe);h(this,"soundRegistry",new me);h(this,"audioOrderCollector",new xe(this.soundRegistry));h(this,"vibrationOrderCollector",new he);h(this,"postProcessOrderCollector",new be);h(this,"encoder",new dt);h(this,"users",new Map);h(this,"colorPalette",new Map);h(this,"paletteSlots",new Map);h(this,"displayRasterizer",new pt(this));h(this,"_renderCallCount",0);h(this,"onPaletteChangedCallback");h(this,"onFontAllocatedCallback");h(this,"onFontBlockAddedCallback");h(this,"onImageFontChangedCallback");this.mode=e.mode??"standalone",this.maxUsers=e.maxUsers??(this.mode==="client"?1:100),this.initializeDefaultPalette(),this.loadFont(8,8,1,8,8)}initializeDefaultPalette(){[{r:0,g:0,b:0},{r:170,g:0,b:0},{r:0,g:170,b:0},{r:170,g:85,b:0},{r:0,g:0,b:170},{r:170,g:0,b:170},{r:0,g:170,b:170},{r:170,g:170,b:170},{r:85,g:85,b:85},{r:255,g:85,b:85},{r:85,g:255,b:85},{r:255,g:255,b:85},{r:85,g:85,b:255},{r:255,g:85,b:255},{r:85,g:255,b:255},{r:255,g:255,b:255}].forEach((t,r)=>this.colorPalette.set(r,{...t,a:255,e:0})),fe.ANSI_VGA_COLORS.forEach(t=>this.colorPalette.set(t.colorId,t)),this.colorPalette.set(255,{r:0,g:0,b:0,a:0,e:0})}isServer(){return this.mode==="server"}isClient(){return this.mode==="client"}isStandalone(){return this.mode==="standalone"}createUser(e,t){if(this.users.has(e))throw new Error(`User with ID ${e} already exists`);if(this.mode==="server"&&this.users.size>=this.maxUsers)throw new Error(`Maximum number of users reached (${this.maxUsers}). Cannot create user ${e}`);if(this.mode==="client"&&this.users.size>=1)throw new Error(`Client mode only allows one user. Cannot create user ${e}`);let r=new ae(e,t,this.mode);return r.setSpriteRegistry(this.spriteRegistry),this.users.set(e,r),r}getUser(e){return this.users.get(e)??null}getUsers(){return Array.from(this.users.values())}hasUser(e){return this.users.has(e)}removeUser(e){return this.users.delete(e)}getUserCount(){return this.users.size}clearAllUsers(){this.users.clear()}setColor(e,t,r,n,o=255,i=0){if(e<0||e>255)throw new Error(`Color ID must be between 0 and 255, got ${e}`);if(e>=240)throw new Error("Color IDs 240-255 are reserved (240-254: UI palette, 255: skip color). Use IDs 0-239 for custom colors.");if(t<0||t>255||r<0||r>255||n<0||n>255||o<0||o>255||i<0||i>255)throw new Error("Color components must be between 0 and 255");this.colorPalette.set(e,{r:t,g:r,b:n,a:o,e:i}),this.onPaletteChangedCallback&&this.onPaletteChangedCallback(this.colorPalette)}onPaletteChanged(e){this.onPaletteChangedCallback=e}getColor(e){return this.colorPalette.get(e)??null}getPalette(){return new Map(this.colorPalette)}resetPalette(){this.colorPalette.clear(),this.initializeDefaultPalette(),this.onPaletteChangedCallback&&this.onPaletteChangedCallback(this.colorPalette)}loadPaletteToSlot(e,t){if(e<0||e>255)throw new Error(`Palette slot ID must be between 0 and 255, got ${e}`);let r=new Map;for(let n of t)n.colorId<0||n.colorId>255||r.set(n.colorId,{r:n.r,g:n.g,b:n.b,a:n.a,e:n.e??0});fe.ANSI_VGA_COLORS.forEach(n=>{r.set(n.colorId,{r:n.r,g:n.g,b:n.b,a:n.a,e:n.e})}),r.set(255,{r:0,g:0,b:0,a:0,e:0}),this.paletteSlots.set(e,r)}getPaletteFromSlot(e){return this.paletteSlots.get(e)??null}hasPaletteSlot(e){return this.paletteSlots.has(e)}clearPaletteSlot(e){this.paletteSlots.delete(e)}clearAllPaletteSlots(){this.paletteSlots.clear()}getColorCSS(e){let t=this.getColor(e);if(!t)return null;let r=t.a/255;return`rgba(${t.r}, ${t.g}, ${t.b}, ${r})`}getUserIds(){return Array.from(this.users.keys())}forEachUser(e){this.users.forEach(e)}filterUsers(e){return this.getUsers().filter(e)}findUser(e){return this.getUsers().find(e)}getCurrentTick(){return this.currentTick}getStats(){return this.stats}endTick(){this.stats.isEnabled()&&this.stats.startTick(this.currentTick);let e=new Map,t=0,r=0;return this.users.forEach((n,o)=>{let i=n.getLayers(),s=n.getDisplays();t+=i.length,n.getStats().isEnabled()&&n.getStats().startTick(this.currentTick);let a=s.map(S=>{let w=S.getOrigin(),I=S.getSize();return{id:S.getId(),originX:w.x,originY:w.y,sizeX:I.x,sizeY:I.y,renderPasses:S.getRenderPasses()}});s.forEach(S=>S.resetChangeTracking());let d=[],l=[];i.forEach((S,w)=>{if(!S.getNeedsCommit())return;let I=S.getOrigin(),U=S.getOrders(),M=S.getMustBeReliable(),P=S.calculateUpdateFlags();S.resetChangeTracking(),S.resetCommit(),S.getId()===0&&te(S,w);let E={id:S.getId(),updateFlags:P,zIndex:S.getZOrder(),originX:I.x,originY:I.y,width:S.getWidth(),height:S.getHeight(),isMacroLayer:S.getIsMacroLayer(),is16bit:S.getCharCodeMode()==="16bit",orderCount:U.length,orders:U};U.length>0&&this.stats.isEnabled()&&this.stats.recordLayerInfo(S.getId(),M,U.length,P),M?d.push(E):l.push(E)}),r+=d.length+l.length;let c=this.audioOrderCollector.collectFromUser(n),u=this.vibrationOrderCollector.collectFromUser(n),p=this.postProcessOrderCollector.collectFromUser(n),m=n.flushMacroOrders(),g=null,y=null;if(this.stats.isEnabled()&&this.stats.recordPacketSplit(o,a.length,d.length,l.length),(d.length>0||c.length>0||m.length>0)&&(g=this.encoder.encode({tick:this.currentTick,displayCount:a.length,displays:a,layerCount:d.length,layers:d,audioOrderCount:c.length,audioOrders:c,vibrationOrderCount:0,vibrationOrders:[],macroOrderCount:m.length,macroOrders:m,postProcessOrderCount:0,postProcessOrders:[]})),y=this.encoder.encode({tick:this.currentTick,displayCount:a.length,displays:a,layerCount:l.length,layers:l,audioOrderCount:0,audioOrders:[],vibrationOrderCount:u.length,vibrationOrders:u,macroOrderCount:0,macroOrders:[],postProcessOrderCount:p.length,postProcessOrders:p}),e.set(o,{static:g,dynamic:y}),n.getStats().isEnabled()){let S=s.reduce((M,P)=>{let E=P.getSize();return M+E.x*E.y},0);n.getStats().recordDisplays(s.length,S),n.getStats().recordLayers(i.length,d.length+l.length,d.length,l.length),[...d,...l].forEach(M=>{n.getStats().recordLayerOrders(M.id,M.orders.length)});let w=g?.length||0,I=y?.length||0;n.getStats().recordPacketSizes(w,I);let U=n.getInputBindingRegistry();n.getStats().recordInput(!1,U.getAxisCount(),U.getButtonCount()),n.getStats().endTick()}if(n.endTickBytes(),this.stats.isEnabled()){let S=[...d,...l];S.forEach((P,E)=>{this.stats.recordLayerOrders(E,P.orders)}),s.forEach((P,E)=>{this.stats.recordDisplayLayers(E,S.length)});let w=(g?.length||0)+(y?.length||0),I=a.reduce((P,E)=>{let v=Math.min(E.renderPasses?.length??0,4);return P+8+v*4},0),U=S.length*20,M=w-I-U;this.stats.recordUpdatePacketSize(w,I,U,M>0?M:0)}}),this.stats.isEnabled()&&(this.stats.recordLayers(t,r),this.stats.endTick()),this.currentTick++,e}getSnapshot(e){let t=this.getUser(e);if(!t)return null;let r=t.getDisplays(),n=t.getLayers(),o=r.map((s,a)=>{let d=s.getOrigin(),l=s.getSize();return{id:a,originX:d.x,originY:d.y,sizeX:l.x,sizeY:l.y,renderPasses:s.getRenderPasses()}}),i=n.map((s,a)=>{let d=s.getOrigin(),l=s.getOrders(),c=7;return s.getId()===0&&te(s,a),{id:s.getId(),updateFlags:c,zIndex:s.getZOrder(),originX:d.x,originY:d.y,width:s.getWidth(),height:s.getHeight(),isMacroLayer:s.getIsMacroLayer(),is16bit:s.getCharCodeMode()==="16bit",orderCount:l.length,orders:l}});return this.encoder.encode({tick:this.currentTick,displayCount:o.length,displays:o,layerCount:i.length,layers:i,audioOrderCount:0,audioOrders:[],vibrationOrderCount:0,vibrationOrders:[],macroOrderCount:0,macroOrders:[],postProcessOrderCount:0,postProcessOrders:[]})}resetTick(){this.currentTick=0}applyUpdatePacket(e,t){let r=this.getUser(e);if(!r){if(this.strictMode)throw new Error(`Cannot apply update packet: user ${e} does not exist`);return!1}return r.applyUpdate(t),t.audioOrders&&t.audioOrders.length>0&&r.applyAudioOrders(t.audioOrders),t.vibrationOrders&&t.vibrationOrders.length>0&&r.applyVibrationOrders(t.vibrationOrders),!0}applyUpdatePacketBuffer(e,t){let{UpdatePacketDecoder:r}=(pn(),K(Wn)),o=new r().decode(t);return this.applyUpdatePacket(e,o)?o:null}applyLoadPacket(e){try{let n=new ut().decode(e).load;switch(n.loadType){case 1:n.slotId!==void 0?this.loadPaletteToSlot(n.slotId,n.colors):(console.warn("[Core] ColorPalette load without slotId is deprecated. Loading into slot 0."),this.loadPaletteToSlot(0,n.colors));break;case 2:this.spriteRegistry.loadUnicolorSprites(n);break;case 3:this.spriteRegistry.loadMulticolorSprites(n);break;case 5:console.warn("[Core] Sound loading not yet implemented");break;case 8:this.loadFont(n.glyphWidth,n.glyphHeight,n.atlasBlocks,n.cellWidth,n.cellHeight);break;case 9:this.loadFontBlock(n.blockIndex,n.imageData);break;case 7:{for(let o of this.users.values())o.loadMacroTemplate(n.macroId,n.template);break}default:return console.error(`[Core] Unknown LoadType: ${n.loadType}`),!1}return!0}catch(t){return console.error("[Core] Failed to apply LoadPacket:",t),!1}}generatePaletteSlotLoadPacket(e){let t=this.getPaletteFromSlot(e);if(!t||t.size===0)return null;let r=new le,n=[];return t.forEach((o,i)=>{i!==255&&n.push({colorId:i,r:o.r,g:o.g,b:o.b,a:o.a,e:o.e})}),r.encode({loadType:1,slotId:e,colors:n})}generateAllPaletteSlotLoadPackets(){let e=[];return this.paletteSlots.forEach((t,r)=>{let n=this.generatePaletteSlotLoadPacket(r);n&&e.push(n)}),e}generateUnicolorSpritesLoadPacket(){let e=this.getSpriteRegistry(),t=[];for(let n=0;n<=255;n++){let o=e.getUnicolorSprite(n);if(o){let i=[];for(let s=0;s<o.sizeX*o.sizeY;s++)i.push(o.data.get(s));t.push({spriteId:o.id,sizeX:o.sizeX,sizeY:o.sizeY,data:i})}}return t.length===0?null:new le().encode({loadType:2,sprites:t})}generateMulticolorSpritesLoadPacket(){let e=this.getSpriteRegistry(),t=[];for(let n=0;n<=255;n++){let o=e.getMulticolorSprite(n);if(o){let i=[];for(let s=0;s<o.sizeX*o.sizeY;s++){let a=o.data.get(s);i.push({charCode:a.charCode,fgColorId:a.fgColorCode,bgColorId:a.bgColorCode})}t.push({spriteId:o.id,sizeX:o.sizeX,sizeY:o.sizeY,data:i})}}return t.length===0?null:new le().encode({loadType:3,sprites:t})}generateAllLoadPackets(){let e=[],t=this.generateAllPaletteSlotLoadPackets();e.push(...t);let r=this.generateUnicolorSpritesLoadPacket();r&&e.push(r);let n=this.generateMulticolorSpritesLoadPacket();return n&&e.push(n),e}generateMacroLoadPackets(e){let t=this.getUser(e);if(!t)return[];let r=t.getMacroLoads();if(r.length===0)return[];let n=new lt;return r.map(o=>n.encode(o))}generateInitialUpdatePacket(e){let t=this.getUser(e);if(!t||!t.hasPostProcessCommands())return null;let r=this.postProcessOrderCollector.collectFromUser(t);if(r.length===0)return null;let o=t.getDisplays().map(s=>{let a=s.getSize();return{id:s.getId(),originX:0,originY:0,sizeX:a.x,sizeY:a.y}});return this.encoder.encode({tick:0,displayCount:o.length,displays:o,layerCount:0,layers:[],audioOrderCount:0,audioOrders:[],vibrationOrderCount:0,vibrationOrders:[],macroOrderCount:0,macroOrders:[],postProcessOrderCount:r.length,postProcessOrders:r})}applyInputBindingsLoadPacket(e,t){let r=this.getUser(e);if(!r){if(this.strictMode)throw new Error(`Cannot apply input bindings: user ${e} does not exist`);return!1}try{return r.applyInputBindingsLoadPacket(t),!0}catch(n){return console.error(`[Core] Failed to apply input bindings for user ${e}:`,n),!1}}getRenderState(e,t){let r=this.getUser(e);if(!r)return null;let n=r.getDisplays(),o=t?r.getLayers().filter(t):r.getLayers(),i=performance.now(),s=[];for(let d of n){if(!d)continue;let l=d.getOrigin(),c=d.getSize();if(s.push(this.displayRasterizer.rasterize({id:d.getId(),x:l.x,y:l.y,width:c.x,height:c.y},o,d.getRenderPasses())),this.stats.isEnabled()){let u=d.getId();this.stats.recordDisplayComposite(u,this.displayRasterizer.getLastVisibleLayerIds())}}let a=performance.now()-i;return this._renderCallCount||(this._renderCallCount=0),this._renderCallCount++,{userId:r.id,userName:r.name,tick:this.currentTick,displays:s}}getAllRenderStates(){let e=new Map;return this.users.forEach((t,r)=>{let n=this.getRenderState(r);n&&e.set(r,n)}),e}enableStats(e){this.stats.setEnabled(e)}getStatsInstance(){return this.stats}resetStats(){this.stats.reset()}loadUnicolorSprites(e){this.spriteRegistry.loadUnicolorSprites(e)}loadMulticolorSprites(e){this.spriteRegistry.loadMulticolorSprites(e)}loadFont(e,t,r,n,o){let i={glyphWidth:e,glyphHeight:t,cellWidth:n,cellHeight:o,atlasBlocks:r};this.imageFontRegistry.hasFont(0)&&this.imageFontRegistry.unloadFont(0),this.imageFontRegistry.loadFont(0,i),this.onFontAllocatedCallback&&this.onFontAllocatedCallback()}loadFontBlock(e,t){if(typeof t=="string")return this.readResource(t).then(r=>{this.imageFontRegistry.addBlock(0,e,r),this.onFontBlockAddedCallback&&this.onFontBlockAddedCallback(e),e===0&&this.onImageFontChangedCallback&&this.onImageFontChangedCallback(0)});this.imageFontRegistry.addBlock(0,e,t),this.onFontBlockAddedCallback&&this.onFontBlockAddedCallback(e),e===0&&this.onImageFontChangedCallback&&this.onImageFontChangedCallback(0)}unloadUnicolorSprite(e){return this.spriteRegistry.unloadUnicolorSprite(e)}unloadMulticolorSprite(e){return this.spriteRegistry.unloadMulticolorSprite(e)}clearUnicolorSprites(){this.spriteRegistry.clearUnicolorSprites()}clearMulticolorSprites(){this.spriteRegistry.clearMulticolorSprites()}clearAllSprites(){this.spriteRegistry.clearAll()}getUnicolorSpriteCount(){return this.spriteRegistry.getUnicolorSpriteCount()}getMulticolorSpriteCount(){return this.spriteRegistry.getMulticolorSpriteCount()}getTotalSpriteCount(){return this.spriteRegistry.getTotalSpriteCount()}hasUnicolorSprite(e){return this.spriteRegistry.hasUnicolorSprite(e)}hasMulticolorSprite(e){return this.spriteRegistry.hasMulticolorSprite(e)}getSpriteRegistry(){return this.spriteRegistry}getSoundRegistry(){return this.soundRegistry}async loadSound(e,t){let r=this.detectSoundFormat(t),n=await this.readResource(t);return this.soundRegistry.registerFile(e,r,n)}async loadSounds(e){let t={},n=Object.entries(e).map(async([o,i])=>{let s=await this.loadSound(o,i);t[o]=s});return await Promise.all(n),t}detectSoundFormat(e){let t=e.split(".").pop()?.toLowerCase()??"",r={mp3:"mp3",wav:"wav",ogg:"ogg",webm:"webm",aac:"aac",m4a:"aac"},n=r[t];if(!n)throw new Error(`Unsupported audio format: .${t}. Supported: ${Object.keys(r).join(", ")}`);return n}async readResource(e){let t=globalThis,r=typeof t.window<"u"||typeof t.document<"u",n=typeof t.fetch=="function",o=/^https?:\/\//i.test(e),i=e.startsWith("file:");if(r)try{let p=await fetch(e);if(!p.ok)throw new Error(`HTTP ${p.status}: ${p.statusText}`);let m=await p.arrayBuffer();return new Uint8Array(m)}catch(p){let m=p instanceof Error?p.message:String(p);throw new Error(`Failed to load resource "${e}": ${m}`)}if((o||i)&&n)try{let p=await fetch(e);if(!p.ok)throw new Error(`HTTP ${p.status}: ${p.statusText}`);let m=await p.arrayBuffer();return new Uint8Array(m)}catch(p){let m=p instanceof Error?p.message:String(p);throw new Error(`Failed to load resource "${e}": ${m}`)}let s=typeof require<"u"?require:null;if(!s)throw new Error("Node.js require is not available");let a="fs",d=s("path"),l=s(a),c=d.resolve(e),u=l.readFileSync(c);return new Uint8Array(u)}registerSound(e,t,r){return this.soundRegistry.registerFile(e,t,r)}registerExternalSound(e,t,r,n){return this.soundRegistry.registerExternal(e,t,r,n)}hasSound(e){return this.soundRegistry.has(e)}generateSoundLoadPackets(){return this.soundRegistry.toLoadPackets()}async loadImageFont(e,t,r){let n=await this.loadImageData(t),o=this.imageFontRegistry.registerFont(e,r);return this.imageFontRegistry.addBlock(0,0,n),this.onFontAllocatedCallback&&this.onFontAllocatedCallback(),this.onFontBlockAddedCallback&&this.onFontBlockAddedCallback(0),this.onImageFontChangedCallback&&this.onImageFontChangedCallback(0),o}async loadImageFonts(e){let t={},n=Object.entries(e).map(async([o,{path:i,options:s}])=>{let a=await this.loadImageFont(o,i,s);t[o]=a});return await Promise.all(n),t}async loadImageData(e){let t=globalThis;if(typeof t.document<"u"||typeof t.window<"u"||typeof t.fetch=="function")try{let n=await fetch(e);if(!n.ok)throw new Error(`HTTP ${n.status}: ${n.statusText}`);let o=await n.arrayBuffer();return new Uint8Array(o)}catch(n){let o=n instanceof Error?n.message:String(n);throw new Error(`Failed to load image font "${e}": ${o}`)}else{let n=typeof require<"u"?require:null;if(!n)throw new Error("Node.js require is not available");let s=n("fs").readFileSync(e);return new Uint8Array(s)}}getImageFontId(e){return this.imageFontRegistry.getFontId(e)}getImageFontByName(e){return this.imageFontRegistry.getFontByName(e)??null}onFontAllocated(e){this.onFontAllocatedCallback=e}onFontBlockAdded(e){this.onFontBlockAddedCallback=e}onImageFontChanged(e){this.onImageFontChangedCallback=e}getImageFontRegistry(){return this.imageFontRegistry}loadImageFontById(e,t){this.imageFontRegistry.loadFont(e,t),this.onImageFontChangedCallback&&this.onImageFontChangedCallback(e)}getImageFont(e){return this.imageFontRegistry.getFont(e)??null}hasImageFont(e){return this.imageFontRegistry.hasFont(e)}hasImageFontByName(e){return this.imageFontRegistry.hasFontByName(e)}unloadImageFont(e){return this.imageFontRegistry.unloadFont(e)}unloadImageFontByName(e){return this.imageFontRegistry.unloadFontByName(e)}clearImageFonts(){this.imageFontRegistry.clearFonts()}getImageFontCount(){return this.imageFontRegistry.getFontCount()}getImageFontIds(){return this.imageFontRegistry.getFontIds()}getImageFontNames(){return this.imageFontRegistry.getFontNames()}};b(fe,"Core"),h(fe,"ANSI_VGA_COLORS",[{colorId:240,r:0,g:0,b:0,a:255,e:0},{colorId:241,r:170,g:0,b:0,a:255,e:0},{colorId:242,r:0,g:170,b:0,a:255,e:0},{colorId:243,r:170,g:85,b:0,a:255,e:0},{colorId:244,r:0,g:0,b:170,a:255,e:0},{colorId:245,r:170,g:0,b:170,a:255,e:0},{colorId:246,r:0,g:170,b:170,a:255,e:0},{colorId:247,r:170,g:170,b:170,a:255,e:0},{colorId:248,r:85,g:85,b:85,a:255,e:0},{colorId:249,r:255,g:85,b:85,a:255,e:0},{colorId:250,r:85,g:255,b:85,a:255,e:0},{colorId:251,r:255,g:255,b:85,a:255,e:0},{colorId:252,r:85,g:85,b:255,a:255,e:0},{colorId:253,r:255,g:85,b:255,a:255,e:0},{colorId:254,r:85,g:255,b:255,a:255,e:0}]);var yt=fe;var eo=require("@utsp/types");var Se=new Map([[0,new Uint8Array([0,0,0,0,0,0,0,0])],[1,new Uint8Array([0,60,102,102,102,60,0,0])],[2,new Uint8Array([0,60,126,126,126,60,0,0])],[3,new Uint8Array([0,108,254,254,124,56,16,0])],[4,new Uint8Array([0,16,56,124,56,16,0,0])],[5,new Uint8Array([0,56,124,56,108,16,56,0])],[6,new Uint8Array([0,16,56,124,124,16,56,0])],[7,new Uint8Array([0,0,24,60,60,24,0,0])],[8,new Uint8Array([255,255,231,195,195,231,255,255])],[9,new Uint8Array([0,60,66,66,66,60,0,0])],[10,new Uint8Array([255,195,189,189,189,195,255,255])],[11,new Uint8Array([0,30,14,26,120,204,120,0])],[12,new Uint8Array([0,60,102,102,60,24,126,24])],[13,new Uint8Array([0,6,14,14,14,124,120,0])],[14,new Uint8Array([0,102,118,126,126,60,24,0])],[15,new Uint8Array([0,153,90,60,60,90,153,0])],[16,new Uint8Array([0,16,48,112,48,16,0,0])],[17,new Uint8Array([0,8,12,14,12,8,0,0])],[18,new Uint8Array([0,24,60,126,24,126,60,24])],[19,new Uint8Array([0,102,102,102,102,0,102,0])],[20,new Uint8Array([0,127,219,219,123,27,27,0])],[21,new Uint8Array([62,99,56,108,108,56,204,120])],[22,new Uint8Array([0,0,0,0,126,126,126,0])],[23,new Uint8Array([0,24,60,126,24,126,60,24])],[24,new Uint8Array([0,24,60,126,255,255,0,0])],[25,new Uint8Array([0,0,255,255,126,60,24,0])],[26,new Uint8Array([0,48,120,252,252,120,48,0])],[27,new Uint8Array([0,12,30,63,63,30,12,0])],[28,new Uint8Array([0,0,24,24,24,126,0,0])],[29,new Uint8Array([0,16,48,127,48,16,0,0])],[30,new Uint8Array([0,0,24,60,126,24,24,0])],[31,new Uint8Array([0,0,24,24,126,60,24,0])],[32,new Uint8Array([0,0,0,0,0,0,0,0])],[33,new Uint8Array([24,24,24,24,24,0,24,0])],[34,new Uint8Array([108,108,108,0,0,0,0,0])],[35,new Uint8Array([54,54,127,54,127,54,54,0])],[36,new Uint8Array([12,63,104,62,11,126,24,0])],[37,new Uint8Array([96,102,12,24,48,102,6,0])],[38,new Uint8Array([56,108,108,56,109,102,59,0])],[39,new Uint8Array([24,24,24,0,0,0,0,0])],[40,new Uint8Array([12,24,48,48,48,24,12,0])],[41,new Uint8Array([48,24,12,12,12,24,48,0])],[42,new Uint8Array([0,102,60,255,60,102,0,0])],[43,new Uint8Array([0,24,24,126,24,24,0,0])],[44,new Uint8Array([0,0,0,0,0,24,24,48])],[45,new Uint8Array([0,0,0,126,0,0,0,0])],[46,new Uint8Array([0,0,0,0,0,24,24,0])],[47,new Uint8Array([0,6,12,24,48,96,0,0])],[48,new Uint8Array([60,102,110,126,118,102,60,0])],[49,new Uint8Array([24,56,24,24,24,24,126,0])],[50,new Uint8Array([60,102,6,12,24,48,126,0])],[51,new Uint8Array([60,102,6,28,6,102,60,0])],[52,new Uint8Array([12,28,60,108,126,12,12,0])],[53,new Uint8Array([126,96,124,6,6,102,60,0])],[54,new Uint8Array([28,48,96,124,102,102,60,0])],[55,new Uint8Array([126,6,12,24,48,48,48,0])],[56,new Uint8Array([60,102,102,60,102,102,60,0])],[57,new Uint8Array([60,102,102,62,6,12,56,0])],[58,new Uint8Array([0,0,24,24,0,24,24,0])],[59,new Uint8Array([0,0,24,24,0,24,24,48])],[60,new Uint8Array([12,24,48,96,48,24,12,0])],[61,new Uint8Array([0,0,126,0,126,0,0,0])],[62,new Uint8Array([48,24,12,6,12,24,48,0])],[63,new Uint8Array([60,102,12,24,24,0,24,0])],[64,new Uint8Array([60,102,110,106,110,96,60,0])],[65,new Uint8Array([60,102,102,126,102,102,102,0])],[66,new Uint8Array([124,102,102,124,102,102,124,0])],[67,new Uint8Array([60,102,96,96,96,102,60,0])],[68,new Uint8Array([120,108,102,102,102,108,120,0])],[69,new Uint8Array([126,96,96,124,96,96,126,0])],[70,new Uint8Array([126,96,96,124,96,96,96,0])],[71,new Uint8Array([60,102,96,110,102,102,60,0])],[72,new Uint8Array([102,102,102,126,102,102,102,0])],[73,new Uint8Array([126,24,24,24,24,24,126,0])],[74,new Uint8Array([62,12,12,12,12,108,56,0])],[75,new Uint8Array([102,108,120,112,120,108,102,0])],[76,new Uint8Array([96,96,96,96,96,96,126,0])],[77,new Uint8Array([99,119,127,107,99,99,99,0])],[78,new Uint8Array([102,102,118,126,110,102,102,0])],[79,new Uint8Array([60,102,102,102,102,102,60,0])],[80,new Uint8Array([124,102,102,124,96,96,96,0])],[81,new Uint8Array([60,102,102,102,106,108,54,0])],[82,new Uint8Array([124,102,102,124,108,102,102,0])],[83,new Uint8Array([60,102,96,60,6,102,60,0])],[84,new Uint8Array([126,24,24,24,24,24,24,0])],[85,new Uint8Array([102,102,102,102,102,102,60,0])],[86,new Uint8Array([102,102,102,102,102,60,24,0])],[87,new Uint8Array([99,99,99,107,127,119,99,0])],[88,new Uint8Array([102,102,60,24,60,102,102,0])],[89,new Uint8Array([102,102,102,60,24,24,24,0])],[90,new Uint8Array([126,6,12,24,48,96,126,0])],[91,new Uint8Array([60,48,48,48,48,48,60,0])],[92,new Uint8Array([0,96,48,24,12,6,0,0])],[93,new Uint8Array([60,12,12,12,12,12,60,0])],[94,new Uint8Array([24,60,102,0,0,0,0,0])],[95,new Uint8Array([0,0,0,0,0,0,255,0])],[96,new Uint8Array([48,24,12,0,0,0,0,0])],[97,new Uint8Array([0,0,60,6,62,102,62,0])],[98,new Uint8Array([96,96,124,102,102,102,124,0])],[99,new Uint8Array([0,0,60,102,96,102,60,0])],[100,new Uint8Array([6,6,62,102,102,102,62,0])],[101,new Uint8Array([0,0,60,102,126,96,60,0])],[102,new Uint8Array([28,54,48,124,48,48,48,0])],[103,new Uint8Array([0,0,62,102,102,62,6,60])],[104,new Uint8Array([96,96,124,102,102,102,102,0])],[105,new Uint8Array([24,0,56,24,24,24,60,0])],[106,new Uint8Array([12,0,28,12,12,12,108,56])],[107,new Uint8Array([96,96,102,108,120,108,102,0])],[108,new Uint8Array([56,24,24,24,24,24,60,0])],[109,new Uint8Array([0,0,102,127,107,107,99,0])],[110,new Uint8Array([0,0,124,102,102,102,102,0])],[111,new Uint8Array([0,0,60,102,102,102,60,0])],[112,new Uint8Array([0,0,124,102,102,124,96,96])],[113,new Uint8Array([0,0,62,102,102,62,6,6])],[114,new Uint8Array([0,0,108,118,96,96,96,0])],[115,new Uint8Array([0,0,62,96,60,6,124,0])],[116,new Uint8Array([48,48,124,48,48,54,28,0])],[117,new Uint8Array([0,0,102,102,102,102,62,0])],[118,new Uint8Array([0,0,102,102,102,60,24,0])],[119,new Uint8Array([0,0,99,107,107,127,54,0])],[120,new Uint8Array([0,0,102,60,24,60,102,0])],[121,new Uint8Array([0,0,102,102,102,62,6,60])],[122,new Uint8Array([0,0,126,12,24,48,126,0])],[123,new Uint8Array([14,24,24,112,24,24,14,0])],[124,new Uint8Array([24,24,24,24,24,24,24,0])],[125,new Uint8Array([112,24,24,14,24,24,112,0])],[126,new Uint8Array([49,107,70,0,0,0,0,0])],[127,new Uint8Array([0,24,60,126,126,24,60,0])],[128,new Uint8Array([60,102,96,96,102,60,24,48])],[129,new Uint8Array([102,0,102,102,102,102,62,0])],[130,new Uint8Array([12,24,60,102,126,96,60,0])],[131,new Uint8Array([24,102,60,6,62,102,62,0])],[132,new Uint8Array([102,0,60,6,62,102,62,0])],[133,new Uint8Array([48,24,60,6,62,102,62,0])],[134,new Uint8Array([24,36,60,6,62,102,62,0])],[135,new Uint8Array([0,0,60,96,96,60,24,48])],[136,new Uint8Array([24,102,60,102,126,96,60,0])],[137,new Uint8Array([102,0,60,102,126,96,60,0])],[138,new Uint8Array([48,24,60,102,126,96,60,0])],[139,new Uint8Array([102,0,24,24,24,24,24,0])],[140,new Uint8Array([24,102,0,24,24,24,24,0])],[141,new Uint8Array([48,24,0,24,24,24,24,0])],[142,new Uint8Array([102,0,60,102,126,102,102,0])],[143,new Uint8Array([24,36,60,102,126,102,102,0])],[144,new Uint8Array([12,24,126,96,124,96,126,0])],[145,new Uint8Array([0,0,110,27,127,216,119,0])],[146,new Uint8Array([63,108,108,127,108,108,111,0])],[147,new Uint8Array([24,102,60,102,102,102,60,0])],[148,new Uint8Array([102,0,60,102,102,102,60,0])],[149,new Uint8Array([48,24,60,102,102,102,60,0])],[150,new Uint8Array([24,102,0,102,102,102,62,0])],[151,new Uint8Array([48,24,0,102,102,102,62,0])],[152,new Uint8Array([102,0,102,102,62,6,60,0])],[153,new Uint8Array([102,0,60,102,102,102,60,0])],[154,new Uint8Array([102,0,102,102,102,102,60,0])],[155,new Uint8Array([0,24,62,96,96,62,24,0])],[156,new Uint8Array([28,54,48,124,48,48,126,0])],[157,new Uint8Array([102,102,60,126,24,126,24,0])],[158,new Uint8Array([124,102,124,98,102,111,102,3])],[159,new Uint8Array([14,27,24,60,24,24,216,112])],[160,new Uint8Array([12,24,60,6,62,102,62,0])],[161,new Uint8Array([12,24,0,24,24,24,24,0])],[162,new Uint8Array([12,24,60,102,102,102,60,0])],[163,new Uint8Array([12,24,0,102,102,102,62,0])],[164,new Uint8Array([54,108,0,124,102,102,102,0])],[165,new Uint8Array([54,108,102,118,126,110,102,0])],[166,new Uint8Array([28,6,30,54,30,0,62,0])],[167,new Uint8Array([28,54,54,54,28,0,62,0])],[168,new Uint8Array([24,0,24,48,96,102,60,0])],[169,new Uint8Array([0,0,0,254,192,192,0,0])],[170,new Uint8Array([0,0,0,254,6,6,0,0])],[171,new Uint8Array([96,224,98,102,108,24,48,110])],[172,new Uint8Array([96,224,98,102,108,24,62,6])],[173,new Uint8Array([24,0,24,24,60,60,24,0])],[174,new Uint8Array([0,0,54,108,216,108,54,0])],[175,new Uint8Array([0,0,216,108,54,108,216,0])],[176,new Uint8Array([34,136,34,136,34,136,34,136])],[177,new Uint8Array([136,34,136,34,136,34,136,34])],[178,new Uint8Array([170,85,170,85,170,85,170,85])],[179,new Uint8Array([24,24,24,24,24,24,24,24])],[180,new Uint8Array([24,24,24,248,24,24,24,24])],[181,new Uint8Array([24,24,24,252,28,24,24,24])],[182,new Uint8Array([54,54,54,246,54,54,54,54])],[183,new Uint8Array([0,0,0,254,54,54,54,54])],[184,new Uint8Array([0,0,0,252,28,24,24,24])],[185,new Uint8Array([54,54,54,252,54,54,54,54])],[186,new Uint8Array([54,54,54,54,54,54,54,54])],[187,new Uint8Array([0,0,0,252,54,54,54,54])],[188,new Uint8Array([54,54,54,252,0,0,0,0])],[189,new Uint8Array([54,54,54,247,0,0,0,0])],[190,new Uint8Array([24,24,24,252,0,0,0,0])],[191,new Uint8Array([0,0,0,248,24,24,24,24])],[192,new Uint8Array([24,24,24,31,0,0,0,0])],[193,new Uint8Array([24,24,24,255,0,0,0,0])],[194,new Uint8Array([0,0,0,255,24,24,24,24])],[195,new Uint8Array([24,24,24,31,24,24,24,24])],[196,new Uint8Array([0,0,0,255,0,0,0,0])],[197,new Uint8Array([24,24,24,255,24,24,24,24])],[198,new Uint8Array([24,24,31,31,24,24,24,24])],[199,new Uint8Array([54,54,55,55,54,54,54,54])],[200,new Uint8Array([54,54,54,63,0,0,0,0])],[201,new Uint8Array([0,0,0,63,54,54,54,54])],[202,new Uint8Array([54,54,54,255,0,0,0,0])],[203,new Uint8Array([0,0,0,255,54,54,54,54])],[204,new Uint8Array([54,54,54,63,54,54,54,54])],[205,new Uint8Array([0,0,0,255,0,255,0,0])],[206,new Uint8Array([54,54,54,255,54,54,54,54])],[207,new Uint8Array([24,24,24,255,0,255,0,0])],[208,new Uint8Array([54,54,54,255,0,0,0,0])],[209,new Uint8Array([0,0,0,255,0,255,24,24])],[210,new Uint8Array([0,0,0,255,54,54,54,54])],[211,new Uint8Array([24,24,24,31,0,31,0,0])],[212,new Uint8Array([54,54,54,62,0,0,0,0])],[213,new Uint8Array([0,0,0,31,0,31,24,24])],[214,new Uint8Array([0,0,0,62,54,54,54,54])],[215,new Uint8Array([24,24,24,255,24,255,24,24])],[216,new Uint8Array([54,54,54,255,54,54,54,54])],[217,new Uint8Array([24,24,24,248,0,0,0,0])],[218,new Uint8Array([0,0,0,31,24,24,24,24])],[219,new Uint8Array([255,255,255,255,255,255,255,255])],[220,new Uint8Array([0,0,0,0,255,255,255,255])],[221,new Uint8Array([240,240,240,240,240,240,240,240])],[222,new Uint8Array([15,15,15,15,15,15,15,15])],[223,new Uint8Array([255,255,255,255,0,0,0,0])],[224,new Uint8Array([0,0,123,207,207,123,0,0])],[225,new Uint8Array([124,102,102,124,102,102,108,96])],[226,new Uint8Array([126,102,96,96,96,96,96,0])],[227,new Uint8Array([0,0,127,54,54,54,54,0])],[228,new Uint8Array([126,96,48,24,48,96,126,0])],[229,new Uint8Array([0,0,63,102,102,102,60,0])],[230,new Uint8Array([0,0,102,102,102,124,96,96])],[231,new Uint8Array([0,0,126,24,24,24,24,0])],[232,new Uint8Array([24,126,219,219,219,126,24,0])],[233,new Uint8Array([60,102,102,126,102,102,60,0])],[234,new Uint8Array([60,102,102,102,60,102,102,0])],[235,new Uint8Array([28,48,24,60,102,102,60,0])],[236,new Uint8Array([0,0,110,219,219,118,0,0])],[237,new Uint8Array([6,12,126,219,219,126,96,192])],[238,new Uint8Array([30,48,96,126,96,48,30,0])],[239,new Uint8Array([60,102,102,102,102,102,0,0])],[240,new Uint8Array([0,126,0,126,0,126,0,0])],[241,new Uint8Array([24,24,126,24,24,0,126,0])],[242,new Uint8Array([48,24,12,24,48,0,126,0])],[243,new Uint8Array([12,24,48,24,12,0,126,0])],[244,new Uint8Array([14,27,27,24,24,24,24,24])],[245,new Uint8Array([24,24,24,24,24,216,216,112])],[246,new Uint8Array([0,24,0,126,0,24,0,0])],[247,new Uint8Array([0,118,220,0,118,220,0,0])],[248,new Uint8Array([56,108,108,56,0,0,0,0])],[249,new Uint8Array([0,0,0,24,24,0,0,0])],[250,new Uint8Array([0,0,0,0,24,0,0,0])],[251,new Uint8Array([15,12,12,12,236,108,60,28])],[252,new Uint8Array([108,54,54,54,54,0,0,0])],[253,new Uint8Array([120,12,24,48,124,0,0,0])],[254,new Uint8Array([0,0,60,60,60,60,0,0])],[255,new Uint8Array([0,0,0,0,0,0,0,0])]]);function jn(x){return Se.get(x)}b(jn,"getCharBitmap");function Jn(x){return Se.has(x)}b(Jn,"hasChar");function qn(){return Array.from(Se.keys()).sort((x,e)=>x-e)}b(qn,"getAllCharCodes");function Kn(){return{charWidth:8,charHeight:8,glyphs:new Map(Se)}}b(Kn,"getASCII8x8FontConfig");V();var mn=class mn{encode(e){switch(e.type){case 1:return this.encodeClick(e);case 2:return this.encodeChange(e);case 3:return this.encodeSubmit(e);case 4:return this.encodeSelect(e);default:throw new Error(`Unknown macro event type: ${e.type}`)}}calculateSize(e){switch(e.type){case 1:return 2;case 2:return this.calculateChangeSize(e);case 3:return this.calculateSubmitSize(e);case 4:return 4;default:throw new Error(`Unknown macro event type: ${e.type}`)}}encodeClick(e){let t=C.allocUnsafe(2);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.toUint8Array()}encodeChange(e){if(typeof e.value=="boolean"){let r=C.allocUnsafe(4);return r.writeUInt8(e.type,0),r.writeUInt8(e.instanceId,1),r.writeUInt8(1,2),r.writeUInt8(e.value?1:0,3),r.toUint8Array()}else{let r=C.allocUnsafe(7);return r.writeUInt8(e.type,0),r.writeUInt8(e.instanceId,1),r.writeUInt8(0,2),r.writeFloatBE(e.value,3),r.toUint8Array()}}calculateChangeSize(e){return typeof e.value=="boolean"?4:7}encodeSubmit(e){let t=new TextEncoder().encode(e.text);if(t.length>65535)throw new Error(`Submit text too large: ${t.length} bytes (max 65535)`);let r=4+t.length,n=C.allocUnsafe(r),o=0;return n.writeUInt8(e.type,o++),n.writeUInt8(e.instanceId,o++),n.writeUInt16BE(t.length,o),o+=2,n.toUint8Array().set(t,o),n.toUint8Array()}calculateSubmitSize(e){return 4+new TextEncoder().encode(e.text).length}encodeSelect(e){let t=C.allocUnsafe(4);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.writeUInt16BE(e.index,2),t.toUint8Array()}};b(mn,"MacroEventEncoder");var Ct=mn;function Qn(x,e,t,r,n,o,i,s=[],a=[],d=[],l=[]){let c=Array.from(e.entries()).sort((k,F)=>k[0]-F[0]),u=Array.from(t.entries()).sort((k,F)=>k[0]-F[0]),p=c.length,m=u.length,g=Ze(p,m),y=new TextEncoder,S=s.map(k=>y.encode(k)),w=1+S.reduce((k,F)=>k+1+F.length,0),I=new Ct,U=a.map(k=>I.encode(k)),M=1+U.reduce((k,F)=>k+F.length,0),P=Math.min(d.length,255),E=1+P*5,v=Math.min(l.length,10),f=1+v*4,L=g+w+M+E+f,O=new Uint8Array(L),z=new DataView(O.buffer),A=0;z.setBigUint64(A,x,!0),A+=8;for(let[,k]of c){let F=Ge(k);O[A]=F+256&255,A+=1}let to=W(m);for(let k=0;k<to;k++){let F=0;for(let Ee=0;Ee<8;Ee++){let bn=k*8+Ee;if(bn<m){let[,ro]=u[bn];ro&&(F|=1<<Ee)}}O[A]=F,A+=1}O[A]=r&255,A+=1,O[A]=n&255,A+=1,O[A]=o&255,A+=1;let hn=0;i&&(hn|=1),O[A]=hn,A+=1,O[A]=Math.min(s.length,255),A+=1;for(let k of S)O[A]=Math.min(k.length,255),A+=1,O.set(k.slice(0,255),A),A+=k.length;O[A]=Math.min(a.length,255),A+=1;for(let k of U)O.set(k,A),A+=k.length;O[A]=P,A+=1;for(let k=0;k<P;k++){let F=d[k];O[A]=F.displayId&255,A+=1,z.setUint16(A,Math.min(F.pixelWidth,65535),!1),A+=2,z.setUint16(A,Math.min(F.pixelHeight,65535),!1),A+=2}O[A]=v,A+=1;for(let k=0;k<v;k++){let F=l[k];O[A]=F.id&15,A+=1,O[A]=F.x&255,A+=1,O[A]=F.y&255,A+=1,O[A]=F.over?1:0,A+=1}return O}b(Qn,"encodeCompressedInput");var B=class B{static toCharCode(e){if(typeof e=="number")return e&65535;if(e.length===0)return 0;let t=e.charCodeAt(0);return j(t)}static dedent(e){let t=e.split(`
14
14
  `);if(t.length>0&&t[0].trim()===""&&t.shift(),t.length>0&&t[t.length-1].trim()===""&&t.pop(),t.length===0)return"";let r=t.filter(o=>o.trim().length>0);if(r.length===0)return"";let n=Math.min(...r.map(o=>{let i=o.match(/^(\s*)/);return i?i[1].length:0}));return t.map(o=>o.slice(n)).join(`
15
15
  `)}static encodeString(e){let t="";for(let r=0;r<e.length;r++){let n=e.charCodeAt(r),o=j(n);t+=String.fromCharCode(o)}return t}static char(e,t,r,n=15,o=0){return{type:1,posX:e,posY:t,charCode:B.toCharCode(r),bgColorCode:o,fgColorCode:n}}static text(e,t,r,n=15,o=0){return{type:2,posX:e,posY:t,text:B.encodeString(r),bgColorCode:o,fgColorCode:n}}static textMultiline(e,t,r,n=15,o=0){return{type:23,posX:e,posY:t,text:B.encodeString(B.dedent(r)),bgColorCode:o,fgColorCode:n}}static subFrame(e,t,r,n,o,i=15,s=0){return{type:3,posX:e,posY:t,sizeX:r,sizeY:n,frame:o.map(a=>B.toCharCode(a)),bgColorCode:s,fgColorCode:i}}static subFrameMultiColor(e,t,r,n,o){return{type:4,posX:e,posY:t,sizeX:r,sizeY:n,frame:o.map(i=>({charCode:B.toCharCode(i.charCode),bgColorCode:i.bgColorCode,fgColorCode:i.fgColorCode}))}}static fullFrame(e,t=15,r=0){return{type:5,frame:e.map(n=>B.toCharCode(n)),bgColorCode:r,fgColorCode:t}}static fullFrameMultiColor(e){return{type:6,frame:e.map(t=>({charCode:B.toCharCode(t.charCode),bgColorCode:t.bgColorCode,fgColorCode:t.fgColorCode}))}}static sprite(e,t,r,n=15,o=0){return{type:7,posX:e,posY:t,spriteIndex:r,bgColorCode:o,fgColorCode:n}}static spriteMultiColor(e,t,r){return{type:8,posX:e,posY:t,spriteIndex:r}}static colorMap(e,t,r,n,o){return{type:9,posX:e,posY:t,sizeX:r,sizeY:n,colorData:o}}static rectangle(e,t,r,n,o={}){return{type:10,shapeType:1,shapeData:{posX:e,posY:t,width:r,height:n,filled:o.filled??!0,charCode:B.toCharCode(o.charCode??219),bgColorCode:o.bgColor??0,fgColorCode:o.fgColor??15}}}static circle(e,t,r,n={}){return{type:10,shapeType:2,shapeData:{centerX:e,centerY:t,radius:r,filled:n.filled??!0,charCode:B.toCharCode(n.charCode??219),bgColorCode:n.bgColor??0,fgColorCode:n.fgColor??15}}}static line(e,t,r,n,o={}){return{type:10,shapeType:3,shapeData:{x1:e,y1:t,x2:r,y2:n,charCode:B.toCharCode(o.charCode??219),bgColorCode:o.bgColor??0,fgColorCode:o.fgColor??15}}}static ellipse(e,t,r,n,o={}){return{type:10,shapeType:4,shapeData:{centerX:e,centerY:t,radiusX:r,radiusY:n,filled:o.filled??!0,charCode:B.toCharCode(o.charCode??219),bgColorCode:o.bgColor??0,fgColorCode:o.fgColor??15}}}static triangle(e,t,r,n,o,i,s={}){return{type:10,shapeType:5,shapeData:{x1:e,y1:t,x2:r,y2:n,x3:o,y3:i,filled:s.filled??!0,charCode:B.toCharCode(s.charCode??219),bgColorCode:s.bgColor??0,fgColorCode:s.fgColor??15}}}static dotCloud(e,t,r=15,n=0){return{type:11,charCode:B.toCharCode(t),bgColorCode:n,fgColorCode:r,positions:e}}static dotCloudMultiColor(e){return{type:12,dots:e.map(t=>({...t,charCode:B.toCharCode(t.charCode)}))}}static bitmask(e,t,r,n,o,i,s=15,a=0,d=!1){let l=r*n,c=Math.ceil(l/8),u=new Uint8Array(c);for(let p=0;p<l;p++)if(o[p]){let m=Math.floor(p/8),g=p%8;u[m]|=1<<g}return{type:17,posX:e,posY:t,sizeX:r,sizeY:n,charCode:B.toCharCode(i),bgColorCode:a,fgColorCode:s,override:d,mask:u}}static bitmask4(e,t,r,n,o,i,s=!1){let a={char:"?",fgColor:15,bgColor:0},d=[i[0]??a,i[1]??a,i[2]??a],l=r*n,c=Math.ceil(l/4),u=new Uint8Array(c);for(let p=0;p<l;p++){let m=o[p]&3,g=Math.floor(p/4),y=p%4*2;u[g]|=m<<y}return{type:18,posX:e,posY:t,sizeX:r,sizeY:n,override:s,variants:[{charCode:B.toCharCode(d[0].char),fgColorCode:d[0].fgColor,bgColorCode:d[0].bgColor},{charCode:B.toCharCode(d[1].char),fgColorCode:d[1].fgColor,bgColorCode:d[1].bgColor},{charCode:B.toCharCode(d[2].char),fgColorCode:d[2].fgColor,bgColorCode:d[2].bgColor}],mask:u}}static bitmask16(e,t,r,n,o,i,s=!1){let a={char:"?",fgColor:15,bgColor:0},d=[];for(let p=0;p<15;p++)d.push(i[p]??a);let l=r*n,c=Math.ceil(l/2),u=new Uint8Array(c);for(let p=0;p<l;p++){let m=o[p]&15,g=Math.floor(p/2),y=p%2*4;u[g]|=m<<y}return{type:24,posX:e,posY:t,sizeX:r,sizeY:n,override:s,variants:d.map(p=>({charCode:B.toCharCode(p.char),fgColorCode:p.fgColor,bgColorCode:p.bgColor})),mask:u}}static spriteCloud(e,t,r=15,n=0){return{type:13,spriteIndex:e,bgColorCode:n,fgColorCode:r,positions:t}}static spriteCloudMultiColor(e,t){return{type:14,spriteIndex:e,positions:t}}static spriteCloudVaried(e){return{type:15,sprites:e}}static spriteCloudVariedMultiColor(e){return{type:16,sprites:e}}static fill(e=32,t=15,r=0){return{type:19,charCode:B.toCharCode(e),bgColorCode:r,fgColorCode:t}}static fillChar(e,t,r,n=15,o=0){return{type:20,patternWidth:e,patternHeight:t,pattern:r.map(i=>B.toCharCode(i)),bgColorCode:o,fgColorCode:n}}static fillSprite(e,t=15,r=0){return{type:21,spriteIndex:e,bgColorCode:r,fgColorCode:t}}static fillSpriteMultiColor(e){return{type:22,spriteIndex:e}}static boxWithBorder(e,t,r,n,o,i){return[this.rectangle(e+1,t+1,r-2,n-2,{charCode:i.charCode??219,bgColor:i.bgColor??0,fgColor:i.fgColor??8,filled:!0}),this.rectangle(e,t,r,n,{charCode:o.charCode??219,bgColor:o.bgColor??0,fgColor:o.fgColor??15,filled:!1})]}static grid(e,t,r,n,o,i,s={}){let a=[];for(let d=0;d<=o;d++)for(let l=0;l<=i;l++)a.push({posX:e+l*r,posY:t+d*n});return this.dotCloud(a,s.charCode??"+",s.fgColor??15,s.bgColor??0)}static polyline(e,t="*",r=15,n=0){return{type:25,charCode:B.toCharCode(t),fgColorCode:r,bgColorCode:n,points:e.map(o=>({x:o.x&255,y:o.y&255}))}}static polylineFromCoords(e,t="*",r=15,n=0){let o=[];for(let i=0;i<e.length-1;i+=2)o.push({x:e[i],y:e[i+1]});return this.polyline(o,t,r,n)}static polygon(e,t="*",r=15,n=0){if(e.length<2)return this.polyline(e,t,r,n);let o=[...e,e[0]];return this.polyline(o,t,r,n)}};b(B,"OrderBuilder");var ft=B;$();Ur();gn();var xn=(m=>(m[m.LayerEnabled=1]="LayerEnabled",m[m.SetMode=2]="SetMode",m[m.UpdatePosition=4]="UpdatePosition",m[m.UpdateZOrder=8]="UpdateZOrder",m[m.IsMacroLayer=32]="IsMacroLayer",m[m.CharCode16Bit=64]="CharCode16Bit",m[m.Disabled=0]="Disabled",m[m.EnabledAddMode=1]="EnabledAddMode",m[m.EnabledSetMode=3]="EnabledSetMode",m[m.EnabledAddMoveOnly=5]="EnabledAddMoveOnly",m[m.EnabledSetMoveOnly=7]="EnabledSetMoveOnly",m[m.EnabledAddReorderOnly=9]="EnabledAddReorderOnly",m[m.EnabledSetReorderOnly=11]="EnabledSetReorderOnly",m[m.FullUpdate=15]="FullUpdate",m))(xn||{}),St;(l=>{function x(c,u){return(c&u)!==0}l.hasFlag=x,b(x,"hasFlag");function e(c,u){return c|u}l.addFlag=e,b(e,"addFlag");function t(c,u){return c&~u}l.removeFlag=t,b(t,"removeFlag");function r(...c){return c.reduce((u,p)=>u|p,0)}l.combine=r,b(r,"combine");function n(c){return(c&144)===0}l.isValid=n,b(n,"isValid");function o(c){return x(c,1)}l.isEnabled=o,b(o,"isEnabled");function i(c){return x(c,2)}l.isSetMode=i,b(i,"isSetMode");function s(c){return x(c,4)}l.hasPositionChanged=s,b(s,"hasPositionChanged");function a(c){return x(c,8)}l.hasZOrderChanged=a,b(a,"hasZOrderChanged");function d(c){if(c===0)return"Disabled";let u=[];return x(c,1)?u.push("Enabled"):u.push("Disabled"),x(c,2)?u.push("SET"):u.push("ADD"),x(c,4)&&u.push("Position"),x(c,8)&&u.push("ZOrder"),x(c,32)&&u.push("Macro"),x(c,64)&&u.push("16bit"),u.join(" | ")}l.describe=d,b(d,"describe")})(St||(St={}));On();pn();vr();on();Sr();Ir();an();Fn();Ln();cn();