@utsp/core 0.17.3 → 0.17.4
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/README.md +26 -19
- package/dist/benchmark.cjs +1 -1
- package/dist/benchmark.d.ts +1 -1
- package/dist/benchmark.mjs +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +2 -2
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 ee=yr;function Ye(x=0n){return{tick:x,axes:new Map,buttons:new Map,displayId:0,mouseX:0,mouseY:0,mouseOverDisplay:!1,textInputs:[],macroEvents:[],displayViewports:[],touchPositions:[],isTabHidden:!1}}b(Ye,"createEmptyCompressedInputPacket");function Xe(x){let e=Math.max(-1,Math.min(1,x));return Math.round(e*127)}b(Xe,"encodeAxisToInt8");function Ge(x){return x/127}b(Ge,"decodeInt8ToAxis");function G(x){return x===0?0:Math.ceil(x/8)}b(G,"getButtonByteCount");function $e(x,e){let r=x,n=G(e);return 8+r+n+4}b($e,"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 Ze=Cr;var N=class N{constructor(e){h(this,"data");h(this,"view");this.data=new Uint8Array(e),this.view=new DataView(this.data.buffer)}static from(e){let t=new N(0);return t.data=e,t.view=new DataView(e.buffer,e.byteOffset,e.byteLength),t}static allocUnsafe(e){return new N(e)}get length(){return this.data.length}toUint8Array(){return this.data}readUInt8(e){return this.view.getUint8(e)}readInt8(e){return this.view.getInt8(e)}readUInt16BE(e){return this.view.getUint16(e,!1)}readInt16BE(e){return this.view.getInt16(e,!1)}readUInt16LE(e){return this.view.getUint16(e,!0)}readInt16LE(e){return this.view.getInt16(e,!0)}readUInt32BE(e){return this.view.getUint32(e,!1)}readInt32BE(e){return this.view.getInt32(e,!1)}readUInt32LE(e){return this.view.getUint32(e,!0)}readInt32LE(e){return this.view.getInt32(e,!0)}readBigUInt64BE(e){return this.view.getBigUint64(e,!1)}readBigInt64BE(e){return this.view.getBigInt64(e,!1)}readBigUInt64LE(e){return this.view.getBigUint64(e,!0)}readBigInt64LE(e){return this.view.getBigInt64(e,!0)}writeUInt8(e,t){this.view.setUint8(t,e)}writeInt8(e,t){this.view.setInt8(t,e)}writeUInt16BE(e,t){this.view.setUint16(t,e,!1)}writeInt16BE(e,t){this.view.setInt16(t,e,!1)}writeUInt16LE(e,t){this.view.setUint16(t,e,!0)}writeInt16LE(e,t){this.view.setInt16(t,e,!0)}writeUInt32BE(e,t){this.view.setUint32(t,e,!1)}writeInt32BE(e,t){this.view.setInt32(t,e,!1)}writeUInt32LE(e,t){this.view.setUint32(t,e,!0)}writeInt32LE(e,t){this.view.setInt32(t,e,!0)}writeBigUInt64BE(e,t){this.view.setBigUint64(t,e,!1)}writeBigInt64BE(e,t){this.view.setBigInt64(t,e,!1)}writeBigUInt64LE(e,t){this.view.setBigUint64(t,e,!0)}writeBigInt64LE(e,t){this.view.setBigInt64(t,e,!0)}readFloatBE(e){return this.view.getFloat32(e,!1)}readFloatLE(e){return this.view.getFloat32(e,!0)}writeFloatBE(e,t){this.view.setFloat32(t,e,!1)}writeFloatLE(e,t){this.view.setFloat32(t,e,!0)}copy(e,t=0,r=0,n=this.length){let o=this.data.subarray(r,n);return e.data.set(o,t),o.length}slice(e,t){let r=this.data.slice(e,t);return N.from(r)}subarray(e,t){let r=this.data.subarray(e,t);return N.from(r)}toBuffer(){return typeof Buffer<"u"&&Buffer.from?Buffer.from(this.data):this.data}static fromNodeBuffer(e){return e instanceof Uint8Array?N.from(e):N.from(new Uint8Array(e))}};b(N,"BufferCompat");var f=N;var uo=new TextDecoder,po=new Ze;function We(x,e){let t=e.getAllAxes().length,r=e.getAllButtons().length,n=G(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=Ye();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=Ge(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,a.isTabHidden=(d&2)!==0,s+=1,s<x.length){let l=x[s];s+=1,a.textInputs=[];for(let c=0;c<l&&s<x.length;c++){let u=x[s];if(s+=1,s+u<=x.length){let p=x.slice(s,s+u),m=uo.decode(p);a.textInputs.push(m),s+=u}}}if(s<x.length){let l=x[s];s+=1;let c=[],u=f.from(x);for(let p=0;p<l&&s<x.length;p++){let m=po.decode(u,s);c.push(m.event),s+=m.bytesRead}a.macroEvents=c}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(We,"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 te=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,"isTabHidden",!1);h(this,"touchPositions",new Map);h(this,"activeTouchId",null);h(this,"inputBindings",new ee);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 q);h(this,"macroEngine",new Q);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,"lastInputTick",-1n);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 te(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;J(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 W(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 j(new T.Vector2(t.originX,t.originY),t.zIndex,t.width,t.height,{mustBeReliable:!1,isMacroLayer:t.isMacroLayer,charCodeMode:t.is16bit?"16bit":"8bit"}),J(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=We(e,this.inputBindings);this.lastInputTick=t.tick;let 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,this.isTabHidden=t.isTabHidden;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(),fe(Sn)),{MobileVibrateFlags:r,GamepadVibrateFlags:n}=(Ir(),fe(In));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(),fe(On)),{PlaySoundFlags:n}=(vr(),fe(Un));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 re=Mr;var Ar=class Ar{constructor(){h(this,"charCodeSize",Ie)}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=f.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=f.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=f.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=f.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=f.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=f.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=f.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=f.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=f.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=f.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=f.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=f.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=f.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=f.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=f.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=f.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=f.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=f.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=f.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=f.allocUnsafe(Ht+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=f.allocUnsafe(Yt+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=f.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=f.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=f.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=f.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=f.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=f.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=f.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=f.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=f.allocUnsafe(Kt),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.spriteIndex,r++),t.toUint8Array()}};b(Ar,"OrderEncoder");var tt=Ar;var vn=255,Mn=32,An=64,Er=class Er{constructor(){h(this,"orderEncoder");this.orderEncoder=new tt}encode(e){let t=e.is16bit;if(e.orders.length>vn)throw new Error(`[UTSP] LayerEncoder: Layer ${e.id} has ${e.orders.length} orders, max is ${vn}. 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=f.allocUnsafe(i),a=0;s.writeUInt16BE(e.id,a),a+=2;let d=e.updateFlags;e.isMacroLayer?d|=Mn:d&=~Mn,t?d|=An:d&=~An,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)f.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 rt=Er;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 Pe;case 8:return ke;case 9:return this.calculateSetSoundEffectsSize(e);default:throw new Error(`Unknown audio order type: ${e.type}`)}}encodePlaySoundOrder(e){let t=this.calculatePlaySoundSize(e),r=f.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=f.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=f.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=f.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=f.allocUnsafe(Pe),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=f.allocUnsafe(ke),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=f.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 nt=Pr;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=f.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=f.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=f.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=f.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 ne=kr;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=f.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=f.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=f.allocUnsafe(2);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.toUint8Array()}};b(Rr,"MacroOrderEncoder");var ot=Rr;var Br=require("@utsp/types");var zr=(s=>(s[s.SetConfig=1]="SetConfig",s[s.SetScanlines=2]="SetScanlines",s[s.SetAmbientEffect=3]="SetAmbientEffect",s[s.SetScalingMode=4]="SetScalingMode",s[s.SetGrid=5]="SetGrid",s[s.SwitchPalette=6]="SwitchPalette",s[s.SetCellSize=7]="SetCellSize",s))(zr||{});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 Re;case 3:return Be;case 4:return ze;case 5:return Te;case 6:return Le;case 7:return Fe;default:throw new Error(`Unknown post-process order type: ${e.type}`)}}encodeSetConfigOrder(e){let t=this.calculateSetConfigSize(e),r=f.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=f.allocUnsafe(Re),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=f.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.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=f.allocUnsafe(ze),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.displayId,r++),t.writeUInt8(e.mode,r++),t.toUint8Array()}encodeSetGridOrder(e){let t=f.allocUnsafe(Te),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=f.allocUnsafe(Le),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.displayId,r++),t.writeUInt8(e.slotId,r++),t.toUint8Array()}encodeSetCellSizeOrder(e){let t=f.allocUnsafe(Fe),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 it=Tr;var En=4,Lr=4,Pn=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=Pn+t*En,n=f.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 Pn+t*En}};b(Fr,"DisplayEncoder");var st=Fr;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 rt,this.audioOrderEncoder=new nt,this.vibrationOrderEncoder=new ne,this.macroOrderEncoder=new ot,this.postProcessOrderEncoder=new it,this.displayEncoder=new st}encode(e){let t=e.layers.map(w=>this.layerEncoder.encode(w)),r=e.audioOrders||[],n=r.map(w=>this.audioOrderEncoder.encode(w)),o=e.vibrationOrders||[],i=o.map(w=>this.vibrationOrderEncoder.encode(w)),s=e.macroOrders||[],a=s.map(w=>this.macroOrderEncoder.encode(w)),d=e.postProcessOrders||[],l=d.map(w=>this.postProcessOrderEncoder.encode(w)),c=9,u=e.displays.reduce((w,P)=>w+this.displayEncoder.calculateSize(P),0),p=2,m=t.reduce((w,P)=>w+P.length,0),g=1,y=n.reduce((w,P)=>w+P.length,0),S=1,I=i.reduce((w,P)=>w+P.length,0),O=1,U=a.reduce((w,P)=>w+P.length,0),v=1,k=l.reduce((w,P)=>w+P.length,0),M=c+u+p+m+g+y+S+I+O+U+v+k,A=f.allocUnsafe(M),C=0,L=typeof e.tick=="bigint"?e.tick:BigInt(e.tick);A.writeBigUInt64BE(L,C),C+=8,A.writeUInt8(e.displays.length,C),C+=1;for(let w of e.displays){let P=this.displayEncoder.encode(w);f.from(P).copy(A,C),C+=P.length}A.writeUInt16BE(e.layers.length,C),C+=2;for(let w of t)f.from(w).copy(A,C),C+=w.length;A.writeUInt8(r.length,C),C+=1;for(let w of n)f.from(w).copy(A,C),C+=w.length;A.writeUInt8(o.length,C),C+=1;for(let w of i)f.from(w).copy(A,C),C+=w.length;A.writeUInt8(s.length,C),C+=1;for(let w of a)f.from(w).copy(A,C),C+=w.length;A.writeUInt8(d.length,C),C+=1;for(let w of l)f.from(w).copy(A,C),C+=w.length;return A.toUint8Array()}calculateSize(e){let r=e.displays.reduce((I,O)=>I+this.displayEncoder.calculateSize(O),0),n=2,o=e.layers.reduce((I,O)=>I+this.layerEncoder.calculateSize(O),0),i=1,a=(e.audioOrders||[]).reduce((I,O)=>I+this.audioOrderEncoder.calculateSize(O),0),d=1,c=(e.vibrationOrders||[]).reduce((I,O)=>I+this.vibrationOrderEncoder.calculateSize(O),0),u=1,m=(e.macroOrders||[]).reduce((I,O)=>I+this.macroOrderEncoder.calculateSize(O),0),g=1,S=(e.postProcessOrders||[]).reduce((I,O)=>I+this.postProcessOrderEncoder.calculateSize(O),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=f.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 at=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||{});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=f.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 dt=_r;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=f.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??255,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=f.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=f.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=f.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=f.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=f.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 oe=Nr;var Hr=class Hr{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(Hr,"MacroLoadDecoder");var lt=Hr;var Yr=class Yr{decode(e,t=0){let r=f.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 lt().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(Yr,"LoadDecoder");var ct=Yr;var mo=4,kn=4,Rn=8,Xr=class Xr{decode(e,t=0){this.checkSize(e,t,Rn);let r=t,n=e.readUInt8(r++),o=e.readUInt16BE(r);r+=2;let i=e.readUInt16BE(r);r+=2;let s=e.readUInt8(r++)+1,a=e.readUInt8(r++)+1,d=e.readUInt8(r++);if(d>kn)throw new Error(`Invalid renderPass count: ${d} (max ${kn})`);let l=d*mo;this.checkSize(e,r,l);let c=[];for(let p=0;p<d;p++){let m=e.readUInt8(r++),g=e.readUInt8(r++),y=e.readUInt8(r++),S=e.readUInt8(r++);c.push({id:m,zMin:g,zMax:y,enabled:(S&1)!==0})}return{display:{id:n,originX:o,originY:i,sizeX:s,sizeY:a,renderPasses:c.length>0?c:void 0},bytesRead:Rn+l}}checkSize(e,t,r){if(t+r>e.length)throw new Error(`Buffer too short for display: need ${r} bytes at offset ${t}, but only ${e.length-t} bytes available`)}};b(Xr,"DisplayDecoder");var ut=Xr;var Gr=class Gr{constructor(){h(this,"charCodeSize",Ie)}decode(e,t=0,r=!1){if(t>=e.length)throw new Error("Buffer too short to decode order type");let n=e.readUInt8(t);switch(n){case 1:return this.decodeCharOrder(e,t,r);case 2:return this.decodeTextOrder(e,t);case 23:return this.decodeTextMultilineOrder(e,t);case 3:return this.decodeSubFrameOrder(e,t,r);case 4:return this.decodeSubFrameMultiColorOrder(e,t,r);case 5:return this.decodeFullFrameOrder(e,t,r);case 6:return this.decodeFullFrameMultiColorOrder(e,t,r);case 7:return this.decodeSpriteOrder(e,t);case 8:return this.decodeSpriteMultiColorOrder(e,t);case 9:return this.decodeColorMapOrder(e,t);case 10:return this.decodeShapeOrder(e,t,r);case 11:return this.decodeDotCloudOrder(e,t,r);case 12:return this.decodeDotCloudMultiColorOrder(e,t,r);case 17:return this.decodeBitmaskOrder(e,t,r);case 18:return this.decodeBitmask4Order(e,t,r);case 24:return this.decodeBitmask16Order(e,t,r);case 25:return this.decodePolylineOrder(e,t,r);case 13:return this.decodeSpriteCloudOrder(e,t);case 14:return this.decodeSpriteCloudMultiColorOrder(e,t);case 15:return this.decodeSpriteCloudVariedOrder(e,t);case 16:return this.decodeSpriteCloudVariedMultiColorOrder(e,t);case 19:return this.decodeFillOrder(e,t,r);case 20:return this.decodeFillCharOrder(e,t,r);case 21:return this.decodeFillSpriteOrder(e,t);case 22:return this.decodeFillSpriteMultiColorOrder(e,t);default:throw new Error(`Unknown order type: 0x${n.toString(16)}`)}}readCharCode(e,t,r){return r?[e.readUInt16LE(t),t+2]:[e.readUInt8(t),t+1]}decodeCharOrder(e,t,r){let o=5+this.charCodeSize(r);this.checkSize(e,t,o);let i=t,s=e.readUInt8(i++),a=e.readUInt8(i++),d=e.readUInt8(i++),[l,c]=this.readCharCode(e,i,r);i=c;let u=e.readUInt8(i++),p=e.readUInt8(i++);return{order:{type:1,posX:a,posY:d,charCode:l,bgColorCode:u,fgColorCode:p},bytesRead:o}}decodeTextOrder(e,t){this.checkSize(e,t,5);let r=t,n=e.readUInt8(r+3);this.checkSize(e,t,5+n);let o=e.subarray(r+4,r+4+n),i=new TextDecoder().decode(o.toUint8Array());return{order:{type:2,posX:e.readUInt8(r+1),posY:e.readUInt8(r+2),text:i,bgColorCode:e.readUInt8(r+4+n),fgColorCode:e.readUInt8(r+5+n)},bytesRead:6+n}}decodeTextMultilineOrder(e,t){this.checkSize(e,t,5);let r=t,n=e.readUInt8(r+3);this.checkSize(e,t,5+n);let o=e.subarray(r+4,r+4+n),i=new TextDecoder().decode(o.toUint8Array());return{order:{type:23,posX:e.readUInt8(r+1),posY:e.readUInt8(r+2),text:i,bgColorCode:e.readUInt8(r+4+n),fgColorCode:e.readUInt8(r+5+n)},bytesRead:6+n}}decodeSubFrameOrder(e,t,r){this.checkSize(e,t,7);let n=t,o=this.charCodeSize(r),i=e.readUInt8(n+3)+1,s=e.readUInt8(n+4)+1,a=i*s;this.checkSize(e,t,7+a*o);let d=[],l=n+7;for(let u=0;u<a;u++){let[p,m]=this.readCharCode(e,l,r);d.push(p),l=m}return{order:{type:3,posX:e.readUInt8(n+1),posY:e.readUInt8(n+2),sizeX:i,sizeY:s,bgColorCode:e.readUInt8(n+5),fgColorCode:e.readUInt8(n+6),frame:d},bytesRead:7+a*o}}decodeSubFrameMultiColorOrder(e,t,r){this.checkSize(e,t,5);let n=t,o=this.charCodeSize(r),i=e.readUInt8(n+3)+1,s=e.readUInt8(n+4)+1,a=i*s,d=o+2;this.checkSize(e,t,5+a*d);let l=[],c=n+5;for(let p=0;p<a;p++){let[m,g]=this.readCharCode(e,c,r);c=g,l.push({charCode:m,bgColorCode:e.readUInt8(c++),fgColorCode:e.readUInt8(c++)})}return{order:{type:4,posX:e.readUInt8(n+1),posY:e.readUInt8(n+2),sizeX:i,sizeY:s,frame:l},bytesRead:5+a*d}}decodeFullFrameOrder(e,t,r,n){this.checkSize(e,t,3);let o=t,i=this.charCodeSize(r),s=n||Math.floor((e.length-t-3)/i);this.checkSize(e,t,3+s*i);let a=[],d=o+3;for(let c=0;c<s;c++){let[u,p]=this.readCharCode(e,d,r);a.push(u),d=p}return{order:{type:5,bgColorCode:e.readUInt8(o+1),fgColorCode:e.readUInt8(o+2),frame:a},bytesRead:3+s*i}}decodeFullFrameMultiColorOrder(e,t,r,n){this.checkSize(e,t,1);let o=t,s=this.charCodeSize(r)+2,a=n||Math.floor((e.length-t-1)/s);this.checkSize(e,t,1+a*s);let d=[],l=o+1;for(let u=0;u<a;u++){let[p,m]=this.readCharCode(e,l,r);l=m,d.push({charCode:p,bgColorCode:e.readUInt8(l++),fgColorCode:e.readUInt8(l++)})}return{order:{type:6,frame:d},bytesRead:1+a*s}}decodeSpriteOrder(e,t){this.checkSize(e,t,6);let r=t;return{order:{type:7,posX:e.readUInt8(r+1),posY:e.readUInt8(r+2),spriteIndex:e.readUInt8(r+3),bgColorCode:e.readUInt8(r+4),fgColorCode:e.readUInt8(r+5)},bytesRead:6}}decodeSpriteMultiColorOrder(e,t){this.checkSize(e,t,4);let r=t;return{order:{type:8,posX:e.readUInt8(r+1),posY:e.readUInt8(r+2),spriteIndex:e.readUInt8(r+3)},bytesRead:4}}decodeColorMapOrder(e,t){this.checkSize(e,t,5);let r=t,n=e.readUInt8(r+3)+1,o=e.readUInt8(r+4)+1,i=n*o;this.checkSize(e,t,5+i*2);let s=[];for(let d=0;d<i;d++){let l=r+5+d*2;s.push({bgColorCode:e.readUInt8(l),fgColorCode:e.readUInt8(l+1)})}return{order:{type:9,posX:e.readUInt8(r+1),posY:e.readUInt8(r+2),sizeX:n,sizeY:o,colorData:s},bytesRead:5+i*2}}decodeShapeOrder(e,t,r){this.checkSize(e,t,2);let n=t,o=e.readUInt8(n+1),{shapeData:i,bytesRead:s}=this.decodeShapeData(e,n+2,o,r);return{order:{type:10,shapeType:o,shapeData:i},bytesRead:2+s}}decodeShapeData(e,t,r,n){let o=t,i=this.charCodeSize(n);switch(r){case 1:{let s=7+i;this.checkSize(e,t,s);let a=e.readUInt8(o++),d=e.readUInt8(o++),l=e.readUInt8(o++)+1,c=e.readUInt8(o++)+1,u=e.readUInt8(o++)===1,[p,m]=this.readCharCode(e,o,n);o=m;let g=e.readUInt8(o++),y=e.readUInt8(o++);return{shapeData:{posX:a,posY:d,width:l,height:c,filled:u,charCode:p,bgColorCode:g,fgColorCode:y},bytesRead:s}}case 2:{let s=6+i;this.checkSize(e,t,s);let a=e.readUInt8(o++),d=e.readUInt8(o++),l=e.readUInt8(o++)+1,c=e.readUInt8(o++)===1,[u,p]=this.readCharCode(e,o,n);o=p;let m=e.readUInt8(o++),g=e.readUInt8(o++);return{shapeData:{centerX:a,centerY:d,radius:l,filled:c,charCode:u,bgColorCode:m,fgColorCode:g},bytesRead:s}}case 3:{let s=6+i;this.checkSize(e,t,s);let a=e.readUInt8(o++),d=e.readUInt8(o++),l=e.readUInt8(o++),c=e.readUInt8(o++),[u,p]=this.readCharCode(e,o,n);o=p;let m=e.readUInt8(o++),g=e.readUInt8(o++);return{shapeData:{x1:a,y1:d,x2:l,y2:c,charCode:u,bgColorCode:m,fgColorCode:g},bytesRead:s}}case 4:{let s=7+i;this.checkSize(e,t,s);let a=e.readUInt8(o++),d=e.readUInt8(o++),l=e.readUInt8(o++)+1,c=e.readUInt8(o++)+1,u=e.readUInt8(o++)===1,[p,m]=this.readCharCode(e,o,n);o=m;let g=e.readUInt8(o++),y=e.readUInt8(o++);return{shapeData:{centerX:a,centerY:d,radiusX:l,radiusY:c,filled:u,charCode:p,bgColorCode:g,fgColorCode:y},bytesRead:s}}case 5:{let s=9+i;this.checkSize(e,t,s);let a=e.readUInt8(o++),d=e.readUInt8(o++),l=e.readUInt8(o++),c=e.readUInt8(o++),u=e.readUInt8(o++),p=e.readUInt8(o++),m=e.readUInt8(o++)===1,[g,y]=this.readCharCode(e,o,n);o=y;let S=e.readUInt8(o++),I=e.readUInt8(o++);return{shapeData:{x1:a,y1:d,x2:l,y2:c,x3:u,y3:p,filled:m,charCode:g,bgColorCode:S,fgColorCode:I},bytesRead:s}}default:throw new Error(`Unknown shape type: ${r}`)}}decodeDotCloudOrder(e,t,r){let o=1+this.charCodeSize(r)+2+2;this.checkSize(e,t,o);let i=t,s=e.readUInt8(i++),[a,d]=this.readCharCode(e,i,r);i=d;let l=e.readUInt8(i++),c=e.readUInt8(i++),u=e.readUInt16BE(i);i+=2,this.checkSize(e,t,o+u*2);let p=[];for(let g=0;g<u;g++)p.push({posX:e.readUInt8(i++),posY:e.readUInt8(i++)});return{order:{type:11,charCode:a,bgColorCode:l,fgColorCode:c,positions:p},bytesRead:o+u*2}}decodeDotCloudMultiColorOrder(e,t,r){this.checkSize(e,t,3);let n=this.charCodeSize(r),o=t,i=e.readUInt16BE(o+1),s=n+4;this.checkSize(e,t,3+i*s);let a=[],d=o+3;for(let c=0;c<i;c++){let[u,p]=this.readCharCode(e,d,r);d=p,a.push({charCode:u,bgColorCode:e.readUInt8(d++),fgColorCode:e.readUInt8(d++),posX:e.readUInt8(d++),posY:e.readUInt8(d++)})}return{order:{type:12,dots:a},bytesRead:3+i*s}}decodeBitmaskOrder(e,t,r){let o=8+this.charCodeSize(r);this.checkSize(e,t,o);let i=t,s=e.readUInt8(i++),a=e.readUInt8(i++),d=e.readUInt8(i++),l=e.readUInt8(i++)+1,c=e.readUInt8(i++)+1,[u,p]=this.readCharCode(e,i,r);i=p;let m=e.readUInt8(i++),g=e.readUInt8(i++),y=e.readUInt8(i++)===1,S=Math.ceil(l*c/8);this.checkSize(e,t,o+S);let I=new Uint8Array(S);for(let U=0;U<S;U++)I[U]=e.readUInt8(i+U);return{order:{type:17,posX:a,posY:d,sizeX:l,sizeY:c,charCode:u,bgColorCode:m,fgColorCode:g,override:y,mask:I},bytesRead:o+S}}decodeBitmask4Order(e,t,r){let i=6+3*(this.charCodeSize(r)+2);this.checkSize(e,t,i);let s=t,a=e.readUInt8(s++),d=e.readUInt8(s++),l=e.readUInt8(s++),c=e.readUInt8(s++)+1,u=e.readUInt8(s++)+1,p=e.readUInt8(s++)===1,m=Math.ceil(c*u/4);this.checkSize(e,t,i+m);let g=[];for(let I=0;I<3;I++){let[O,U]=this.readCharCode(e,s,r);s=U,g.push({charCode:O,bgColorCode:e.readUInt8(s++),fgColorCode:e.readUInt8(s++)})}let y=new Uint8Array(m);for(let I=0;I<m;I++)y[I]=e.readUInt8(s+I);return{order:{type:18,posX:d,posY:l,sizeX:c,sizeY:u,override:p,variants:g,mask:y},bytesRead:i+m}}decodeBitmask16Order(e,t,r){let i=6+15*(this.charCodeSize(r)+2);this.checkSize(e,t,i);let s=t,a=e.readUInt8(s++),d=e.readUInt8(s++),l=e.readUInt8(s++),c=e.readUInt8(s++)+1,u=e.readUInt8(s++)+1,p=e.readUInt8(s++)===1,m=Math.ceil(c*u/2);this.checkSize(e,t,i+m);let g=[];for(let I=0;I<15;I++){let[O,U]=this.readCharCode(e,s,r);s=U,g.push({charCode:O,bgColorCode:e.readUInt8(s++),fgColorCode:e.readUInt8(s++)})}let y=new Uint8Array(m);for(let I=0;I<m;I++)y[I]=e.readUInt8(s+I);return{order:{type:24,posX:d,posY:l,sizeX:c,sizeY:u,override:p,variants:g,mask:y},bytesRead:i+m}}decodePolylineOrder(e,t,r){let o=4+this.charCodeSize(r);this.checkSize(e,t,o);let i=t,s=e.readUInt8(i++),[a,d]=this.readCharCode(e,i,r);i=d;let l=e.readUInt8(i++),c=e.readUInt8(i++),u=e.readUInt8(i++);this.checkSize(e,t,o+u*2);let p=[];for(let g=0;g<u;g++)p.push({x:e.readUInt8(i++),y:e.readUInt8(i++)});return{order:{type:25,charCode:a,fgColorCode:l,bgColorCode:c,points:p},bytesRead:o+u*2}}decodeSpriteCloudOrder(e,t){this.checkSize(e,t,6);let r=t,n=e.readUInt16BE(r+4);this.checkSize(e,t,6+n*2);let o=[];for(let s=0;s<n;s++){let a=r+6+s*2;o.push({posX:e.readUInt8(a),posY:e.readUInt8(a+1)})}return{order:{type:13,spriteIndex:e.readUInt8(r+1),bgColorCode:e.readUInt8(r+2),fgColorCode:e.readUInt8(r+3),positions:o},bytesRead:6+n*2}}decodeSpriteCloudMultiColorOrder(e,t){this.checkSize(e,t,4);let r=t,n=e.readUInt16BE(r+2);this.checkSize(e,t,4+n*2);let o=[];for(let s=0;s<n;s++){let a=r+4+s*2;o.push({posX:e.readUInt8(a),posY:e.readUInt8(a+1)})}return{order:{type:14,spriteIndex:e.readUInt8(r+1),positions:o},bytesRead:4+n*2}}decodeSpriteCloudVariedOrder(e,t){this.checkSize(e,t,3);let r=t,n=e.readUInt16BE(r+1);this.checkSize(e,t,3+n*5);let o=[];for(let s=0;s<n;s++){let a=r+3+s*5;o.push({spriteIndex:e.readUInt8(a),bgColorCode:e.readUInt8(a+1),fgColorCode:e.readUInt8(a+2),posX:e.readUInt8(a+3),posY:e.readUInt8(a+4)})}return{order:{type:15,sprites:o},bytesRead:3+n*5}}decodeSpriteCloudVariedMultiColorOrder(e,t){this.checkSize(e,t,3);let r=t,n=e.readUInt16BE(r+1);this.checkSize(e,t,3+n*3);let o=[];for(let s=0;s<n;s++){let a=r+3+s*3;o.push({spriteIndex:e.readUInt8(a),posX:e.readUInt8(a+1),posY:e.readUInt8(a+2)})}return{order:{type:16,sprites:o},bytesRead:3+n*3}}decodeFillOrder(e,t,r){let o=3+this.charCodeSize(r);this.checkSize(e,t,o);let i=t,s=e.readUInt8(i++),[a,d]=this.readCharCode(e,i,r);i=d;let l=e.readUInt8(i++),c=e.readUInt8(i++);return{order:{type:19,charCode:a,bgColorCode:l,fgColorCode:c},bytesRead:o}}decodeFillCharOrder(e,t,r){this.checkSize(e,t,5);let n=this.charCodeSize(r),o=t,i=e.readUInt8(o+1)+1,s=e.readUInt8(o+2)+1,a=i*s,d=5+a*n;this.checkSize(e,t,d);let l=[],c=o+5;for(let p=0;p<a;p++){let[m,g]=this.readCharCode(e,c,r);l.push(m),c=g}return{order:{type:20,patternWidth:i,patternHeight:s,bgColorCode:e.readUInt8(o+3),fgColorCode:e.readUInt8(o+4),pattern:l},bytesRead:d}}decodeFillSpriteOrder(e,t){this.checkSize(e,t,4);let r=t;return{order:{type:21,spriteIndex:e.readUInt8(r+1),bgColorCode:e.readUInt8(r+2),fgColorCode:e.readUInt8(r+3)},bytesRead:4}}decodeFillSpriteMultiColorOrder(e,t){this.checkSize(e,t,2);let r=t;return{order:{type:22,spriteIndex:e.readUInt8(r+1)},bytesRead:2}}checkSize(e,t,r){if(t+r>e.length)throw new Error(`Buffer too short: need ${r} bytes at offset ${t}, but only ${e.length-t} bytes available`)}};b(Gr,"OrderDecoder");var pt=Gr;var xo=32,ho=64,$r=class $r{constructor(){h(this,"orderDecoder");this.orderDecoder=new pt}decode(e,t=0){this.checkSize(e,t,13);let n=t,o=e.readUInt16BE(n);n+=2;let i=e.readUInt8(n++),s=e.readUInt8(n++),a=e.readUInt16BE(n);n+=2;let d=e.readUInt16BE(n);n+=2;let l=e.readUInt16BE(n);n+=2;let c=e.readUInt16BE(n);n+=2;let u=e.readUInt8(n++),p=(i&xo)!==0,m=(i&ho)!==0,g=[],y=n;for(let I=0;I<u;I++){let O=this.orderDecoder.decode(e,y,m);g.push(O.order),y+=O.bytesRead}return{layer:{id:o,updateFlags:i,zIndex:s,originX:a,originY:d,width:l,height:c,orderCount:u,orders:g,isMacroLayer:p,is16bit:m},bytesRead:y-t}}checkSize(e,t,r){if(t+r>e.length)throw new Error(`Buffer too short for layer: need ${r} bytes at offset ${t}, but only ${e.length-t} bytes available`)}};b($r,"LayerDecoder");var mt=$r;var Zr=class Zr{decode(e,t=0){if(t>=e.length)throw new Error("Buffer too short to decode audio order type");let r=e.readUInt8(t);switch(r){case 1:return this.decodePlaySoundOrder(e,t);case 2:return this.decodePlayGlobalSoundOrder(e,t);case 3:return this.decodeStopSoundOrder(e,t);case 4:return this.decodeFadeOutSoundOrder(e,t);case 5:return this.decodePauseSoundOrder(e,t);case 6:return this.decodeResumeSoundOrder(e,t);case 7:return this.decodeSetListenerPositionOrder(e,t);case 8:return this.decodeConfigureSpatialOrder(e,t);case 9:return this.decodeSetSoundEffectsOrder(e,t);default:throw new Error(`Unknown audio order type: 0x${r.toString(16)}`)}}decodePlaySoundOrder(e,t){this.checkSize(e,t,5);let r=t,n=e.readUInt8(r++),o=e.readUInt8(r++),i=e.readUInt16BE(r);r+=2;let s=e.readUInt8(r++),a={type:n,soundId:o,instanceId:i,flags:s};return s&2&&(this.checkSize(e,r,1),a.volume=e.readUInt8(r++)),s&4&&(this.checkSize(e,r,1),a.pitch=e.readUInt8(r++)),s&8&&(this.checkSize(e,r,1),a.fadeIn=e.readUInt8(r++)),s&16&&(this.checkSize(e,r,4),a.posX=e.readUInt16BE(r),r+=2,a.posY=e.readUInt16BE(r),r+=2),s&32&&(this.checkSize(e,r,1),a.lowpass=e.readUInt8(r++)),s&64&&(this.checkSize(e,r,1),a.highpass=e.readUInt8(r++)),s&128&&(this.checkSize(e,r,1),a.reverb=e.readUInt8(r++)),{order:a,bytesRead:r-t}}decodePlayGlobalSoundOrder(e,t){this.checkSize(e,t,5);let r=t,n=e.readUInt8(r++),o=e.readUInt8(r++),i=e.readUInt16BE(r);r+=2;let s=e.readUInt8(r++),a={type:n,soundId:o,instanceId:i,flags:s};return s&2&&(this.checkSize(e,r,1),a.volume=e.readUInt8(r++)),s&4&&(this.checkSize(e,r,1),a.pitch=e.readUInt8(r++)),s&8&&(this.checkSize(e,r,1),a.fadeIn=e.readUInt8(r++)),s&32&&(this.checkSize(e,r,1),a.lowpass=e.readUInt8(r++)),s&64&&(this.checkSize(e,r,1),a.highpass=e.readUInt8(r++)),s&128&&(this.checkSize(e,r,1),a.reverb=e.readUInt8(r++)),{order:a,bytesRead:r-t}}decodeStopSoundOrder(e,t){this.checkSize(e,t,2);let r=t,n=e.readUInt8(r++),o=e.readUInt8(r++),i={type:n,targetType:o};return o===0?(this.checkSize(e,r,2),i.target=e.readUInt16BE(r),r+=2):o===1&&(this.checkSize(e,r,1),i.target=e.readUInt8(r++)),{order:i,bytesRead:r-t}}decodeFadeOutSoundOrder(e,t){this.checkSize(e,t,3);let r=t,n=e.readUInt8(r++),o=e.readUInt8(r++),i=e.readUInt8(r++),s={type:n,targetType:o,duration:i};return o===0?(this.checkSize(e,r,2),s.target=e.readUInt16BE(r),r+=2):o===1&&(this.checkSize(e,r,1),s.target=e.readUInt8(r++)),{order:s,bytesRead:r-t}}decodePauseSoundOrder(e,t){this.checkSize(e,t,2);let r=t,n=e.readUInt8(r++),o=e.readUInt8(r++),i={type:n,targetType:o};return o===0?(this.checkSize(e,r,2),i.target=e.readUInt16BE(r),r+=2):o===1&&(this.checkSize(e,r,1),i.target=e.readUInt8(r++)),{order:i,bytesRead:r-t}}decodeResumeSoundOrder(e,t){this.checkSize(e,t,2);let r=t,n=e.readUInt8(r++),o=e.readUInt8(r++),i={type:n,targetType:o};return o===0?(this.checkSize(e,r,2),i.target=e.readUInt16BE(r),r+=2):o===1&&(this.checkSize(e,r,1),i.target=e.readUInt8(r++)),{order:i,bytesRead:r-t}}decodeSetListenerPositionOrder(e,t){this.checkSize(e,t,5);let r=t,n=e.readUInt8(r++),o=e.readUInt16BE(r);r+=2;let i=e.readUInt16BE(r);return r+=2,{order:{type:n,x:o,y:i},bytesRead:5}}decodeConfigureSpatialOrder(e,t){this.checkSize(e,t,5);let r=t;return{order:{type:e.readUInt8(r),maxDistance:e.readUInt8(r+1),referenceDistance:e.readUInt8(r+2),rolloffFactor:e.readUInt8(r+3),panSpread:e.readUInt8(r+4)},bytesRead:5}}decodeSetSoundEffectsOrder(e,t){this.checkSize(e,t,4);let r=t,n=e.readUInt8(r++),o=e.readUInt16BE(r);r+=2;let i=e.readUInt8(r++),s={type:n,instanceId:o,flags:i};return i&1&&(this.checkSize(e,r,1),s.lowpass=e.readUInt8(r++)),i&2&&(this.checkSize(e,r,1),s.highpass=e.readUInt8(r++)),i&4&&(this.checkSize(e,r,1),s.reverb=e.readUInt8(r++)),{order:s,bytesRead:r-t}}checkSize(e,t,r){if(t+r>e.length)throw new Error(`Buffer too short for audio order: need ${r} bytes at offset ${t}, but only ${e.length-t} bytes available`)}};b(Zr,"AudioOrderDecoder");var ie=Zr;var Wr=class Wr{decode(e,t=0){if(t>=e.length)throw new Error("Buffer too short to decode vibration order type");let r=e.readUInt8(t);switch(r){case 1:return this.decodeMobileVibrateOrder(e,t);case 2:return this.decodeMobileCancelOrder(e,t);case 16:return this.decodeGamepadVibrateOrder(e,t);case 17:return this.decodeGamepadCancelOrder(e,t);default:throw new Error(`Unknown vibration order type: 0x${r.toString(16)}`)}}decodeMobileVibrateOrder(e,t){let r=t,n=e.readUInt8(r++),o=e.readUInt8(r++),i=e.readUInt8(r++),s=[];for(let d=0;d<i;d++)s.push(e.readUInt16BE(r)),r+=2;let a={type:n,flags:o,pattern:s};return o&1&&(a.intensity=e.readUInt8(r++)/255),{order:a,bytesRead:r-t}}decodeMobileCancelOrder(e,t){return{order:{type:2},bytesRead:1}}decodeGamepadVibrateOrder(e,t){let r=t,n=e.readUInt8(r++),o=e.readUInt8(r++),i=e.readUInt8(r++),s=e.readUInt16BE(r);r+=2;let a=e.readUInt8(r++),d=e.readUInt8(r++),l={type:n,flags:o,gamepadIndex:i,duration:s,strongMagnitude:a,weakMagnitude:d};return o&1&&(l.startDelay=e.readUInt16BE(r),r+=2),{order:l,bytesRead:r-t}}decodeGamepadCancelOrder(e,t){let r=t,n=e.readUInt8(r++),o=e.readUInt8(r++),i=e.readUInt8(r++);return{order:{type:n,flags:o,gamepadIndex:i},bytesRead:r-t}}};b(Wr,"VibrationOrderDecoder");var se=Wr;var jr=class jr{decode(e,t=0){let r=e.readUInt8(t);switch(r){case 1:return this.decodeCreateInstance(e,t);case 2:return this.decodeUpdateInstance(e,t);case 3:return this.decodeRemoveInstance(e,t);default:throw new Error(`Unknown macro order type: 0x${r.toString(16)}`)}}decodeAll(e,t,r){let n=[],o=0;for(let i=0;i<r;i++){let{order:s,bytesRead:a}=this.decode(e,t+o);n.push(s),o+=a}return{orders:n,bytesRead:o}}decodeCreateInstance(e,t){let r=t,n=e.readUInt8(t++),o=e.readUInt8(t++),i=e.readUInt8(t++),s=e.readUInt8(t++),a=e.readInt16BE(t);t+=2;let d=e.readInt16BE(t);t+=2;let l=e.readUInt8(t++),c=e.readUInt16BE(t);t+=2;let u=e.toUint8Array().subarray(t,t+c);t+=c;let p=new TextDecoder().decode(u),m=JSON.parse(p);return{order:{type:n,instanceId:o,macroId:i,layerId:s,x:a,y:d,tabIndex:l,params:m},bytesRead:t-r}}decodeUpdateInstance(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),d=JSON.parse(a);return{order:{type:n,instanceId:o,params:d},bytesRead:t-r}}decodeRemoveInstance(e,t){let r=e.readUInt8(t),n=e.readUInt8(t+1);return{order:{type:r,instanceId:n},bytesRead:2}}};b(jr,"MacroOrderDecoder");var xt=jr;var Jr=class Jr{decode(e,t){let r=e[t];switch(r){case 1:return this.decodeSetConfigOrder(e,t);case 2:return this.decodeSetScanlinesOrder(e,t);case 3:return this.decodeSetAmbientEffectOrder(e,t);case 4:return this.decodeSetScalingModeOrder(e,t);case 5:return this.decodeSetGridOrder(e,t);case 6:return this.decodeSwitchPaletteOrder(e,t);case 7:return this.decodeSetCellSizeOrder(e,t);default:throw new Error(`Unknown post-process order type: ${r}`)}}decodeSetConfigOrder(e,t){let r=t,n=e[r++],o=e[r++],i=e[r++],s={type:n,displayId:o,flags:i};return i&1&&(s.scanlines={enabled:e[r++]===1,opacity:e[r++]/255,pattern:e[r++],colorR:e[r++],colorG:e[r++],colorB:e[r++]}),i&2&&(s.ambientEffect={enabled:e[r++]===1,blur:e[r++],scale:e[r++]/100,opacity:e[r++]/255}),{order:s,bytesRead:r-t}}decodeSetScanlinesOrder(e,t){let r=t;return{order:{type:e[r++],displayId:e[r++],enabled:e[r++]===1,opacity:e[r++]/255,pattern:e[r++],colorR:e[r++],colorG:e[r++],colorB:e[r++]},bytesRead:r-t}}decodeSetAmbientEffectOrder(e,t){let r=t;return{order:{type:e[r++],displayId:e[r++],enabled:e[r++]===1,blur:e[r++],scale:e[r++]/100,opacity:e[r++]/255},bytesRead:r-t}}decodeSetScalingModeOrder(e,t){let r=t;return{order:{type:e[r++],displayId:e[r++],mode:e[r++]},bytesRead:r-t}}decodeSetGridOrder(e,t){let r=t;return{order:{type:e[r++],displayId:e[r++],enabled:e[r++]===1,colorR:e[r++],colorG:e[r++],colorB:e[r++],colorA:e[r++],lineWidth:e[r++]},bytesRead:r-t}}decodeSwitchPaletteOrder(e,t){let r=t;return{order:{type:e[r++],displayId:e[r++],slotId:e[r++]},bytesRead:r-t}}decodeSetCellSizeOrder(e,t){let r=t;return{order:{type:e[r++],displayId:e[r++],cellWidth:e[r++],cellHeight:e[r++]},bytesRead:r-t}}};b(Jr,"PostProcessOrderDecoder");var ae=Jr;var qr=class qr{constructor(){h(this,"displayDecoder");h(this,"layerDecoder");h(this,"audioOrderDecoder");h(this,"vibrationOrderDecoder");h(this,"macroOrderDecoder");h(this,"postProcessOrderDecoder");this.displayDecoder=new ut,this.layerDecoder=new mt,this.audioOrderDecoder=new ie,this.vibrationOrderDecoder=new se,this.macroOrderDecoder=new xt,this.postProcessOrderDecoder=new ae}decode(e,t=0){let r=f.from(e);this.checkSize(r,t,15);let o=t,i=Number(r.readBigUInt64BE(o));o+=8;let s=r.readUInt8(o);o+=1;let a=[],d=0;for(let L=0;L<s;L++){let w=this.displayDecoder.decode(r,o);a.push(w.display),o+=w.bytesRead,d+=w.bytesRead}this.checkSize(r,o,2);let l=r.readUInt16BE(o);o+=2;let c=[],u=0;for(let L=0;L<l;L++){let w=this.layerDecoder.decode(r,o);c.push({...w.layer,byteSize:w.bytesRead}),o+=w.bytesRead,u+=w.bytesRead}this.checkSize(r,o,1);let p=r.readUInt8(o);o+=1;let m=[],g=0;for(let L=0;L<p;L++){let w=this.audioOrderDecoder.decode(r,o);m.push(w.order),o+=w.bytesRead,g+=w.bytesRead}this.checkSize(r,o,1);let y=r.readUInt8(o);o+=1;let S=[],I=0;for(let L=0;L<y;L++){let w=this.vibrationOrderDecoder.decode(r,o);S.push(w.order),o+=w.bytesRead,I+=w.bytesRead}this.checkSize(r,o,1);let O=r.readUInt8(o);o+=1;let U=[],v=0;for(let L=0;L<O;L++){let w=this.macroOrderDecoder.decode(r,o);U.push(w.order),o+=w.bytesRead,v+=w.bytesRead}this.checkSize(r,o,1);let k=r.readUInt8(o);o+=1;let M=[],A=0;for(let L=0;L<k;L++){let w=this.postProcessOrderDecoder.decode(r.toUint8Array(),o);M.push(w.order),o+=w.bytesRead,A+=w.bytesRead}return{tick:i,displayCount:s,displays:a,layerCount:l,layers:c,audioOrderCount:p,audioOrders:m,vibrationOrderCount:y,vibrationOrders:S,macroOrderCount:O,macroOrders:U,postProcessOrderCount:k,postProcessOrders:M,__byteSizes:{displays:d,layers:u,audioOrders:g,vibrationOrders:I,macroOrders:v,postProcessOrders:A}}}isValid(e,t=0){let r=f.from(e);try{return this.checkSize(r,t,15),!0}catch{return!1}}decodeHeader(e,t=0){let r=f.from(e);this.checkSize(r,t,13);let n=t,o=Number(r.readBigUInt64BE(n));n+=8;let i=r.readUInt8(n);n+=1;for(let a=0;a<i;a++){let d=this.displayDecoder.decode(r,n);n+=d.bytesRead}this.checkSize(r,n,2);let s=r.readUInt16BE(n);return{tick:o,displayCount:i,layerCount:s}}checkSize(e,t,r){if(t+r>e.length)throw new Error(`Buffer too short for update packet: need ${r} bytes at offset ${t}, but only ${e.length-t} bytes available`)}};b(qr,"UpdatePacketDecoder");var de=qr;var H=class H{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=H.charCache.get(e);return t===void 0&&(t=String.fromCharCode(e),H.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,I=g.getWidth(),O=g.getHeight();if(y<0||y>=I||S<0||S>=O)continue;let U=S*I+y,v=g.getData(),k=v.getCharCode(U),M=v.getFgColorCode(U),A=v.getBgColorCode(U),C=n[c];if(k!==0&&C.char===" "&&(C.char=H.getChar(k)),M!==255&&C.fgColorIndex===255&&(C.fgColorIndex=M,C.fgEmission=this.getColorEmission(M)),A!==255){C.bgColorIndex===255&&(C.bgColorIndex=A,C.bgEmission=this.getColorEmission(A)),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],I=S.getZOrder();I<c.zMin||I>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 I=g*y+m,O=p.getData(),U=O.getCharCode(I),v=O.getFgColorCode(I),k=O.getBgColorCode(I),M=r[d];if(U!==0&&M.char===" "&&(M.char=H.getChar(U)),v!==255&&M.fgColorIndex===255&&(M.fgColorIndex=v,M.fgEmission=this.getColorEmission(v)),k!==255){M.bgColorIndex===255&&(M.bgColorIndex=k,M.bgEmission=this.getColorEmission(k)),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(),I=m.getHeight();if(g<0||g>=S||y<0||y>=I)continue;let O=y*S+g,U=m.getData(),v=U.getCharCode(O),k=U.getFgColorCode(O),M=U.getBgColorCode(O),A=n[l];if(v!==0&&A.char===" "&&(A.char=H.getChar(v)),k!==255&&A.fgColorIndex===255&&(A.fgColorIndex=k,A.fgEmission=this.getColorEmission(k)),M!==255){A.bgColorIndex===255&&(A.bgColorIndex=M,A.bgEmission=this.getColorEmission(M)),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(H,"DisplayRasterizer"),h(H,"charCache",(()=>{let e=new Map;for(let t=0;t<256;t++)e.set(t,String.fromCharCode(t));return e})());var ht=H;var Kr=class Kr{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(Kr,"CoreStats");var le=Kr;var Bn=[[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]],bo=new Map(Bn),na=new Map(Bn.map(([x,e])=>[e,x]));function $(x){if(x<128)return x;let e=bo.get(x);return e!==void 0?e:x&255}b($,"unicodeToCp437");var Qr=class Qr{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 X(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,$(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,$(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 X(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 _(n*o);for(let d=0;d<Math.min(i.length,n*o);d++){let l=i[d],c=typeof l.charCode=="string"?$(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 _(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(Qr,"SpriteRegistry");var ce=Qr;var en=(t=>(t.Bitmap="bitmap",t.Image="image",t))(en||{});function bt(x){return Math.sqrt(x)*16}b(bt,"getAtlasColumns");function tn(x){return x*256-1}b(tn,"getMaxCharCode");function zn(x,e){let r=bt(x)*e;return{width:r,height:r}}b(zn,"getAtlasDimensions");var rn=class rn{constructor(e,t){this.fontId=e;this.config=t;h(this,"atlasColumns");h(this,"maxCharCode");h(this,"blocks",new Map);this.atlasColumns=bt(t.atlasBlocks),this.maxCharCode=tn(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(rn,"ImageFont");var Z=rn;var nn=class nn{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 Z(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 Z(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(nn,"ImageFontRegistry");var ue=nn;var on=class on{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(on,"SoundRegistry");var pe=on;var sn=class sn{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(sn,"AudioOrderCollector");var me=sn;var an=class an{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(an,"VibrationOrderCollector");var xe=an;var D=require("@utsp/types");var dn=class dn{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??D.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??D.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??D.POST_PROCESS_DEFAULTS.ambientEffect.blur,scale:o.scale??D.POST_PROCESS_DEFAULTS.ambientEffect.scale,opacity:o.opacity??D.POST_PROCESS_DEFAULTS.ambientEffect.opacity}}return n.flags=r,n}createSetScanlinesOrder(e,t,r){return{type:2,displayId:e,enabled:t,opacity:r??D.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??D.POST_PROCESS_DEFAULTS.ambientEffect.blur,scale:n??D.POST_PROCESS_DEFAULTS.ambientEffect.scale,opacity:D.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,D.scalingModeToValue)(t)}}createSetGridOrder(e,t){let{r,g:n,b:o,a:i}=this.parseColor(t.color??D.GRID_DEFAULTS.color);return{type:5,displayId:e,enabled:t.enabled,colorR:r,colorG:n,colorB:o,colorA:i,lineWidth:t.lineWidth??D.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(dn,"PostProcessOrderCollector");var he=dn;var be=class be{constructor(e={}){h(this,"mode");h(this,"maxUsers");h(this,"strictMode",!1);h(this,"currentTick",0);h(this,"stats",new le);h(this,"spriteRegistry",new ce);h(this,"imageFontRegistry",new ue);h(this,"soundRegistry",new pe);h(this,"audioOrderCollector",new me(this.soundRegistry));h(this,"vibrationOrderCollector",new xe);h(this,"postProcessOrderCollector",new he);h(this,"encoder",new at);h(this,"users",new Map);h(this,"colorPalette",new Map);h(this,"paletteSlots",new Map);h(this,"displayRasterizer",new ht(this));h(this,"updatePacketDecoder",new de);h(this,"loadDecoder",new ct);h(this,"cachedLoadPackets",null);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})),be.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 re(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.cachedLoadPackets=null,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??255,e:n.e??0});be.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 I=S.getOrigin(),O=S.getSize();return{id:S.getId(),originX:I.x,originY:I.y,sizeX:O.x,sizeY:O.y,renderPasses:S.getRenderPasses()}});s.forEach(S=>S.resetChangeTracking());let d=[],l=[];i.forEach((S,I)=>{if(!S.getNeedsCommit())return;let O=S.getOrigin(),U=S.getOrders(),v=S.getMustBeReliable(),k=S.calculateUpdateFlags();S.resetChangeTracking(),S.resetCommit(),S.getId()===0&&J(S,I);let M={id:S.getId(),updateFlags:k,zIndex:S.getZOrder(),originX:O.x,originY:O.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(),v,U.length,k),v?d.push(M):l.push(M)}),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((v,k)=>{let M=k.getSize();return v+M.x*M.y},0);n.getStats().recordDisplays(s.length,S),n.getStats().recordLayers(i.length,d.length+l.length,d.length,l.length),[...d,...l].forEach(v=>{n.getStats().recordLayerOrders(v.id,v.orders.length)});let I=g?.length||0,O=y?.length||0;n.getStats().recordPacketSizes(I,O);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((k,M)=>{this.stats.recordLayerOrders(M,k.orders)}),s.forEach((k,M)=>{this.stats.recordDisplayLayers(M,S.length)});let I=(g?.length||0)+(y?.length||0),O=a.reduce((k,M)=>{let A=Math.min(M.renderPasses?.length??0,4);return k+8+A*4},0),U=S.length*20,v=I-O-U;this.stats.recordUpdatePacketSize(I,O,U,v>0?v: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&&J(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 r=this.updatePacketDecoder.decode(t);return this.applyUpdatePacket(e,r)?r:null}applyLoadPacket(e){try{let r=this.loadDecoder.decode(e).load;switch(r.loadType){case 1:r.slotId!==void 0?this.loadPaletteToSlot(r.slotId,r.colors):(console.warn("[Core] ColorPalette load without slotId is deprecated. Loading into slot 0."),this.loadPaletteToSlot(0,r.colors));break;case 2:this.spriteRegistry.loadUnicolorSprites(r);break;case 3:this.spriteRegistry.loadMulticolorSprites(r);break;case 5:console.warn("[Core] Sound loading not yet implemented");break;case 8:this.loadFont(r.glyphWidth,r.glyphHeight,r.atlasBlocks,r.cellWidth,r.cellHeight);break;case 9:this.loadFontBlock(r.blockIndex,r.imageData);break;case 7:{for(let n of this.users.values())n.loadMacroTemplate(r.macroId,r.template);break}default:return console.error(`[Core] Unknown LoadType: ${r.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 oe,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(){if(this.spriteRegistry.getUnicolorSpriteCount()===0)return null;let e=[];for(let r=0;r<=255;r++){let n=this.spriteRegistry.getUnicolorSprite(r);if(n){let o=[];for(let i=0;i<n.sizeX*n.sizeY;i++)o.push(n.data.get(i));e.push({spriteId:n.id,sizeX:n.sizeX,sizeY:n.sizeY,data:o})}}return e.length===0?null:new oe().encode({loadType:2,sprites:e})}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 oe().encode({loadType:3,sprites:t})}generateAllLoadPackets(){if(this.cachedLoadPackets)return this.cachedLoadPackets;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),this.cachedLoadPackets=e,e}generateMacroLoadPackets(e){let t=this.getUser(e);if(!t)return[];let r=t.getMacroLoads();if(r.length===0)return[];let n=new dt;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(be,"Core"),h(be,"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 gt=be;var _n=require("@utsp/types");var ge=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 Tn(x){return ge.get(x)}b(Tn,"getCharBitmap");function Ln(x){return ge.has(x)}b(Ln,"hasChar");function Fn(){return Array.from(ge.keys()).sort((x,e)=>x-e)}b(Fn,"getAllCharCodes");function Dn(){return{charWidth:8,charHeight:8,glyphs:new Map(ge)}}b(Dn,"getASCII8x8FontConfig");var ln=class ln{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=f.allocUnsafe(2);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.toUint8Array()}encodeChange(e){if(typeof e.value=="boolean"){let r=f.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=f.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=f.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=f.allocUnsafe(4);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.writeUInt16BE(e.index,2),t.toUint8Array()}};b(ln,"MacroEventEncoder");var yt=ln;function Vn(x,e,t,r,n,o,i,s=[],a=[],d=[],l=[],c=!1){let u=Array.from(e.entries()).sort((R,F)=>R[0]-F[0]),p=Array.from(t.entries()).sort((R,F)=>R[0]-F[0]),m=u.length,g=p.length,y=$e(m,g),S=new TextEncoder,I=s.map(R=>S.encode(R)),O=1+I.reduce((R,F)=>R+1+F.length,0),U=new yt,v=a.map(R=>U.encode(R)),k=1+v.reduce((R,F)=>R+F.length,0),M=Math.min(d.length,255),A=1+M*5,C=Math.min(l.length,10),L=1+C*4,w=y+O+k+A+L,P=new Uint8Array(w),ve=new DataView(P.buffer),E=0;ve.setBigUint64(E,x,!0),E+=8;for(let[,R]of u){let F=Xe(R);P[E]=F+256&255,E+=1}let Nn=G(g);for(let R=0;R<Nn;R++){let F=0;for(let Me=0;Me<8;Me++){let un=R*8+Me;if(un<g){let[,Hn]=p[un];Hn&&(F|=1<<Me)}}P[E]=F,E+=1}P[E]=r&255,E+=1,P[E]=n&255,E+=1,P[E]=o&255,E+=1;let St=0;i&&(St|=1),c&&(St|=2),P[E]=St,E+=1,P[E]=Math.min(s.length,255),E+=1;for(let R of I)P[E]=Math.min(R.length,255),E+=1,P.set(R.slice(0,255),E),E+=R.length;P[E]=Math.min(a.length,255),E+=1;for(let R of v)P.set(R,E),E+=R.length;P[E]=M,E+=1;for(let R=0;R<M;R++){let F=d[R];P[E]=F.displayId&255,E+=1,ve.setUint16(E,Math.min(F.pixelWidth,65535),!1),E+=2,ve.setUint16(E,Math.min(F.pixelHeight,65535),!1),E+=2}P[E]=C,E+=1;for(let R=0;R<C;R++){let F=l[R];P[E]=F.id&15,E+=1,P[E]=F.x&255,E+=1,P[E]=F.y&255,E+=1,P[E]=F.over?1:0,E+=1}return P}b(Vn,"encodeCompressedInput");var z=class z{static toCharCode(e){if(typeof e=="number")return e&65535;if(e.length===0)return 0;let t=e.charCodeAt(0);return $(t)}static dedent(e){let t=e.split(`
|
|
13
|
+
`}),e}};b(yr,"InputBindingRegistry");var ee=yr;function Ye(x=0n){return{tick:x,axes:new Map,buttons:new Map,displayId:0,mouseX:0,mouseY:0,mouseOverDisplay:!1,textInputs:[],macroEvents:[],displayViewports:[],touchPositions:[],isTabHidden:!1}}b(Ye,"createEmptyCompressedInputPacket");function Xe(x){let e=Math.max(-1,Math.min(1,x));return Math.round(e*127)}b(Xe,"encodeAxisToInt8");function Ge(x){return x/127}b(Ge,"decodeInt8ToAxis");function G(x){return x===0?0:Math.ceil(x/8)}b(G,"getButtonByteCount");function $e(x,e){let r=x,n=G(e);return 8+r+n+4}b($e,"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 Ze=Cr;var N=class N{constructor(e){h(this,"data");h(this,"view");this.data=new Uint8Array(e),this.view=new DataView(this.data.buffer)}static from(e){let t=new N(0);return t.data=e,t.view=new DataView(e.buffer,e.byteOffset,e.byteLength),t}static allocUnsafe(e){return new N(e)}get length(){return this.data.length}toUint8Array(){return this.data}readUInt8(e){return this.view.getUint8(e)}readInt8(e){return this.view.getInt8(e)}readUInt16BE(e){return this.view.getUint16(e,!1)}readInt16BE(e){return this.view.getInt16(e,!1)}readUInt16LE(e){return this.view.getUint16(e,!0)}readInt16LE(e){return this.view.getInt16(e,!0)}readUInt32BE(e){return this.view.getUint32(e,!1)}readInt32BE(e){return this.view.getInt32(e,!1)}readUInt32LE(e){return this.view.getUint32(e,!0)}readInt32LE(e){return this.view.getInt32(e,!0)}readBigUInt64BE(e){return this.view.getBigUint64(e,!1)}readBigInt64BE(e){return this.view.getBigInt64(e,!1)}readBigUInt64LE(e){return this.view.getBigUint64(e,!0)}readBigInt64LE(e){return this.view.getBigInt64(e,!0)}writeUInt8(e,t){this.view.setUint8(t,e)}writeInt8(e,t){this.view.setInt8(t,e)}writeUInt16BE(e,t){this.view.setUint16(t,e,!1)}writeInt16BE(e,t){this.view.setInt16(t,e,!1)}writeUInt16LE(e,t){this.view.setUint16(t,e,!0)}writeInt16LE(e,t){this.view.setInt16(t,e,!0)}writeUInt32BE(e,t){this.view.setUint32(t,e,!1)}writeInt32BE(e,t){this.view.setInt32(t,e,!1)}writeUInt32LE(e,t){this.view.setUint32(t,e,!0)}writeInt32LE(e,t){this.view.setInt32(t,e,!0)}writeBigUInt64BE(e,t){this.view.setBigUint64(t,e,!1)}writeBigInt64BE(e,t){this.view.setBigInt64(t,e,!1)}writeBigUInt64LE(e,t){this.view.setBigUint64(t,e,!0)}writeBigInt64LE(e,t){this.view.setBigInt64(t,e,!0)}readFloatBE(e){return this.view.getFloat32(e,!1)}readFloatLE(e){return this.view.getFloat32(e,!0)}writeFloatBE(e,t){this.view.setFloat32(t,e,!1)}writeFloatLE(e,t){this.view.setFloat32(t,e,!0)}copy(e,t=0,r=0,n=this.length){let o=this.data.subarray(r,n);return e.data.set(o,t),o.length}slice(e,t){let r=this.data.slice(e,t);return N.from(r)}subarray(e,t){let r=this.data.subarray(e,t);return N.from(r)}toBuffer(){return typeof Buffer<"u"&&Buffer.from?Buffer.from(this.data):this.data}static fromNodeBuffer(e){return e instanceof Uint8Array?N.from(e):N.from(new Uint8Array(e))}};b(N,"BufferCompat");var f=N;var uo=new TextDecoder,po=new Ze;function We(x,e){let t=e.getAllAxes().length,r=e.getAllButtons().length,n=G(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=Ye();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=Ge(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,a.isTabHidden=(d&2)!==0,s+=1,s<x.length){let l=x[s];s+=1,a.textInputs=[];for(let c=0;c<l&&s<x.length;c++){let u=x[s];if(s+=1,s+u<=x.length){let p=x.slice(s,s+u),m=uo.decode(p);a.textInputs.push(m),s+=u}}}if(s<x.length){let l=x[s];s+=1;let c=[],u=f.from(x);for(let p=0;p<l&&s<x.length;p++){let m=po.decode(u,s);c.push(m.event),s+=m.bytesRead}a.macroEvents=c}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(We,"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 te=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,"isTabHidden",!1);h(this,"touchPositions",new Map);h(this,"activeTouchId",null);h(this,"inputBindings",new ee);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 q);h(this,"macroEngine",new Q);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,"lastInputTick",-1n);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 te(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;J(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 W(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 j(new T.Vector2(t.originX,t.originY),t.zIndex,t.width,t.height,{mustBeReliable:!1,isMacroLayer:t.isMacroLayer,charCodeMode:t.is16bit?"16bit":"8bit"}),J(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=We(e,this.inputBindings);this.lastInputTick=t.tick;let 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,this.isTabHidden=t.isTabHidden;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(),fe(Sn)),{MobileVibrateFlags:r,GamepadVibrateFlags:n}=(Ir(),fe(In));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(),fe(On)),{PlaySoundFlags:n}=(vr(),fe(Un));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 re=Mr;var Ar=class Ar{constructor(){h(this,"charCodeSize",Ie)}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=f.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=f.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=f.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=f.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=f.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=f.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=f.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=f.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=f.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=f.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=f.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=f.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=f.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=f.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=f.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=f.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=f.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=f.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=f.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=f.allocUnsafe(Ht+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=f.allocUnsafe(Yt+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=f.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=f.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=f.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=f.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=f.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=f.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=f.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=f.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=f.allocUnsafe(Kt),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.spriteIndex,r++),t.toUint8Array()}};b(Ar,"OrderEncoder");var tt=Ar;var vn=255,Mn=32,An=64,Er=class Er{constructor(){h(this,"orderEncoder");this.orderEncoder=new tt}encode(e){let t=e.is16bit;if(e.orders.length>vn)throw new Error(`[UTSP] LayerEncoder: Layer ${e.id} has ${e.orders.length} orders, max is ${vn}. 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=f.allocUnsafe(i),a=0;s.writeUInt16BE(e.id,a),a+=2;let d=e.updateFlags;e.isMacroLayer?d|=Mn:d&=~Mn,t?d|=An:d&=~An,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)f.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 rt=Er;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 Pe;case 8:return ke;case 9:return this.calculateSetSoundEffectsSize(e);default:throw new Error(`Unknown audio order type: ${e.type}`)}}encodePlaySoundOrder(e){let t=this.calculatePlaySoundSize(e),r=f.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=f.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=f.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=f.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=f.allocUnsafe(Pe),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=f.allocUnsafe(ke),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=f.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 nt=Pr;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=f.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=f.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=f.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=f.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 ne=kr;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=f.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=f.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=f.allocUnsafe(2);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.toUint8Array()}};b(Rr,"MacroOrderEncoder");var ot=Rr;var Br=require("@utsp/types");var zr=(s=>(s[s.SetConfig=1]="SetConfig",s[s.SetScanlines=2]="SetScanlines",s[s.SetAmbientEffect=3]="SetAmbientEffect",s[s.SetScalingMode=4]="SetScalingMode",s[s.SetGrid=5]="SetGrid",s[s.SwitchPalette=6]="SwitchPalette",s[s.SetCellSize=7]="SetCellSize",s))(zr||{});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 Re;case 3:return Be;case 4:return ze;case 5:return Te;case 6:return Le;case 7:return Fe;default:throw new Error(`Unknown post-process order type: ${e.type}`)}}encodeSetConfigOrder(e){let t=this.calculateSetConfigSize(e),r=f.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=f.allocUnsafe(Re),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=f.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.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=f.allocUnsafe(ze),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.displayId,r++),t.writeUInt8(e.mode,r++),t.toUint8Array()}encodeSetGridOrder(e){let t=f.allocUnsafe(Te),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=f.allocUnsafe(Le),r=0;return t.writeUInt8(e.type,r++),t.writeUInt8(e.displayId,r++),t.writeUInt8(e.slotId,r++),t.toUint8Array()}encodeSetCellSizeOrder(e){let t=f.allocUnsafe(Fe),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 it=Tr;var En=4,Lr=4,Pn=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=Pn+t*En,n=f.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 Pn+t*En}};b(Fr,"DisplayEncoder");var st=Fr;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 rt,this.audioOrderEncoder=new nt,this.vibrationOrderEncoder=new ne,this.macroOrderEncoder=new ot,this.postProcessOrderEncoder=new it,this.displayEncoder=new st}encode(e){let t=e.layers.map(w=>this.layerEncoder.encode(w)),r=e.audioOrders||[],n=r.map(w=>this.audioOrderEncoder.encode(w)),o=e.vibrationOrders||[],i=o.map(w=>this.vibrationOrderEncoder.encode(w)),s=e.macroOrders||[],a=s.map(w=>this.macroOrderEncoder.encode(w)),d=e.postProcessOrders||[],l=d.map(w=>this.postProcessOrderEncoder.encode(w)),c=9,u=e.displays.reduce((w,P)=>w+this.displayEncoder.calculateSize(P),0),p=2,m=t.reduce((w,P)=>w+P.length,0),g=1,y=n.reduce((w,P)=>w+P.length,0),S=1,I=i.reduce((w,P)=>w+P.length,0),O=1,U=a.reduce((w,P)=>w+P.length,0),v=1,k=l.reduce((w,P)=>w+P.length,0),M=c+u+p+m+g+y+S+I+O+U+v+k,A=f.allocUnsafe(M),C=0,L=typeof e.tick=="bigint"?e.tick:BigInt(e.tick);A.writeBigUInt64BE(L,C),C+=8,A.writeUInt8(e.displays.length,C),C+=1;for(let w of e.displays){let P=this.displayEncoder.encode(w);f.from(P).copy(A,C),C+=P.length}A.writeUInt16BE(e.layers.length,C),C+=2;for(let w of t)f.from(w).copy(A,C),C+=w.length;A.writeUInt8(r.length,C),C+=1;for(let w of n)f.from(w).copy(A,C),C+=w.length;A.writeUInt8(o.length,C),C+=1;for(let w of i)f.from(w).copy(A,C),C+=w.length;A.writeUInt8(s.length,C),C+=1;for(let w of a)f.from(w).copy(A,C),C+=w.length;A.writeUInt8(d.length,C),C+=1;for(let w of l)f.from(w).copy(A,C),C+=w.length;return A.toUint8Array()}calculateSize(e){let r=e.displays.reduce((I,O)=>I+this.displayEncoder.calculateSize(O),0),n=2,o=e.layers.reduce((I,O)=>I+this.layerEncoder.calculateSize(O),0),i=1,a=(e.audioOrders||[]).reduce((I,O)=>I+this.audioOrderEncoder.calculateSize(O),0),d=1,c=(e.vibrationOrders||[]).reduce((I,O)=>I+this.vibrationOrderEncoder.calculateSize(O),0),u=1,m=(e.macroOrders||[]).reduce((I,O)=>I+this.macroOrderEncoder.calculateSize(O),0),g=1,S=(e.postProcessOrders||[]).reduce((I,O)=>I+this.postProcessOrderEncoder.calculateSize(O),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=f.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 at=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||{});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=f.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 dt=_r;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=f.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??255,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=f.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=f.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=f.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=f.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=f.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 oe=Nr;var Hr=class Hr{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(Hr,"MacroLoadDecoder");var lt=Hr;var Yr=class Yr{decode(e,t=0){let r=f.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 lt().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(Yr,"LoadDecoder");var ct=Yr;var mo=4,kn=4,Rn=8,Xr=class Xr{decode(e,t=0){this.checkSize(e,t,Rn);let r=t,n=e.readUInt8(r++),o=e.readUInt16BE(r);r+=2;let i=e.readUInt16BE(r);r+=2;let s=e.readUInt8(r++)+1,a=e.readUInt8(r++)+1,d=e.readUInt8(r++);if(d>kn)throw new Error(`Invalid renderPass count: ${d} (max ${kn})`);let l=d*mo;this.checkSize(e,r,l);let c=[];for(let p=0;p<d;p++){let m=e.readUInt8(r++),g=e.readUInt8(r++),y=e.readUInt8(r++),S=e.readUInt8(r++);c.push({id:m,zMin:g,zMax:y,enabled:(S&1)!==0})}return{display:{id:n,originX:o,originY:i,sizeX:s,sizeY:a,renderPasses:c.length>0?c:void 0},bytesRead:Rn+l}}checkSize(e,t,r){if(t+r>e.length)throw new Error(`Buffer too short for display: need ${r} bytes at offset ${t}, but only ${e.length-t} bytes available`)}};b(Xr,"DisplayDecoder");var ut=Xr;var Gr=class Gr{constructor(){h(this,"charCodeSize",Ie)}decode(e,t=0,r=!1){if(t>=e.length)throw new Error("Buffer too short to decode order type");let n=e.readUInt8(t);switch(n){case 1:return this.decodeCharOrder(e,t,r);case 2:return this.decodeTextOrder(e,t);case 23:return this.decodeTextMultilineOrder(e,t);case 3:return this.decodeSubFrameOrder(e,t,r);case 4:return this.decodeSubFrameMultiColorOrder(e,t,r);case 5:return this.decodeFullFrameOrder(e,t,r);case 6:return this.decodeFullFrameMultiColorOrder(e,t,r);case 7:return this.decodeSpriteOrder(e,t);case 8:return this.decodeSpriteMultiColorOrder(e,t);case 9:return this.decodeColorMapOrder(e,t);case 10:return this.decodeShapeOrder(e,t,r);case 11:return this.decodeDotCloudOrder(e,t,r);case 12:return this.decodeDotCloudMultiColorOrder(e,t,r);case 17:return this.decodeBitmaskOrder(e,t,r);case 18:return this.decodeBitmask4Order(e,t,r);case 24:return this.decodeBitmask16Order(e,t,r);case 25:return this.decodePolylineOrder(e,t,r);case 13:return this.decodeSpriteCloudOrder(e,t);case 14:return this.decodeSpriteCloudMultiColorOrder(e,t);case 15:return this.decodeSpriteCloudVariedOrder(e,t);case 16:return this.decodeSpriteCloudVariedMultiColorOrder(e,t);case 19:return this.decodeFillOrder(e,t,r);case 20:return this.decodeFillCharOrder(e,t,r);case 21:return this.decodeFillSpriteOrder(e,t);case 22:return this.decodeFillSpriteMultiColorOrder(e,t);default:throw new Error(`Unknown order type: 0x${n.toString(16)}`)}}readCharCode(e,t,r){return r?[e.readUInt16LE(t),t+2]:[e.readUInt8(t),t+1]}decodeCharOrder(e,t,r){let o=5+this.charCodeSize(r);this.checkSize(e,t,o);let i=t,s=e.readUInt8(i++),a=e.readUInt8(i++),d=e.readUInt8(i++),[l,c]=this.readCharCode(e,i,r);i=c;let u=e.readUInt8(i++),p=e.readUInt8(i++);return{order:{type:1,posX:a,posY:d,charCode:l,bgColorCode:u,fgColorCode:p},bytesRead:o}}decodeTextOrder(e,t){this.checkSize(e,t,5);let r=t,n=e.readUInt8(r+3);this.checkSize(e,t,5+n);let o=e.subarray(r+4,r+4+n),i=new TextDecoder().decode(o.toUint8Array());return{order:{type:2,posX:e.readUInt8(r+1),posY:e.readUInt8(r+2),text:i,bgColorCode:e.readUInt8(r+4+n),fgColorCode:e.readUInt8(r+5+n)},bytesRead:6+n}}decodeTextMultilineOrder(e,t){this.checkSize(e,t,5);let r=t,n=e.readUInt8(r+3);this.checkSize(e,t,5+n);let o=e.subarray(r+4,r+4+n),i=new TextDecoder().decode(o.toUint8Array());return{order:{type:23,posX:e.readUInt8(r+1),posY:e.readUInt8(r+2),text:i,bgColorCode:e.readUInt8(r+4+n),fgColorCode:e.readUInt8(r+5+n)},bytesRead:6+n}}decodeSubFrameOrder(e,t,r){this.checkSize(e,t,7);let n=t,o=this.charCodeSize(r),i=e.readUInt8(n+3)+1,s=e.readUInt8(n+4)+1,a=i*s;this.checkSize(e,t,7+a*o);let d=[],l=n+7;for(let u=0;u<a;u++){let[p,m]=this.readCharCode(e,l,r);d.push(p),l=m}return{order:{type:3,posX:e.readUInt8(n+1),posY:e.readUInt8(n+2),sizeX:i,sizeY:s,bgColorCode:e.readUInt8(n+5),fgColorCode:e.readUInt8(n+6),frame:d},bytesRead:7+a*o}}decodeSubFrameMultiColorOrder(e,t,r){this.checkSize(e,t,5);let n=t,o=this.charCodeSize(r),i=e.readUInt8(n+3)+1,s=e.readUInt8(n+4)+1,a=i*s,d=o+2;this.checkSize(e,t,5+a*d);let l=[],c=n+5;for(let p=0;p<a;p++){let[m,g]=this.readCharCode(e,c,r);c=g,l.push({charCode:m,bgColorCode:e.readUInt8(c++),fgColorCode:e.readUInt8(c++)})}return{order:{type:4,posX:e.readUInt8(n+1),posY:e.readUInt8(n+2),sizeX:i,sizeY:s,frame:l},bytesRead:5+a*d}}decodeFullFrameOrder(e,t,r,n){this.checkSize(e,t,3);let o=t,i=this.charCodeSize(r),s=n||Math.floor((e.length-t-3)/i);this.checkSize(e,t,3+s*i);let a=[],d=o+3;for(let c=0;c<s;c++){let[u,p]=this.readCharCode(e,d,r);a.push(u),d=p}return{order:{type:5,bgColorCode:e.readUInt8(o+1),fgColorCode:e.readUInt8(o+2),frame:a},bytesRead:3+s*i}}decodeFullFrameMultiColorOrder(e,t,r,n){this.checkSize(e,t,1);let o=t,s=this.charCodeSize(r)+2,a=n||Math.floor((e.length-t-1)/s);this.checkSize(e,t,1+a*s);let d=[],l=o+1;for(let u=0;u<a;u++){let[p,m]=this.readCharCode(e,l,r);l=m,d.push({charCode:p,bgColorCode:e.readUInt8(l++),fgColorCode:e.readUInt8(l++)})}return{order:{type:6,frame:d},bytesRead:1+a*s}}decodeSpriteOrder(e,t){this.checkSize(e,t,6);let r=t;return{order:{type:7,posX:e.readUInt8(r+1),posY:e.readUInt8(r+2),spriteIndex:e.readUInt8(r+3),bgColorCode:e.readUInt8(r+4),fgColorCode:e.readUInt8(r+5)},bytesRead:6}}decodeSpriteMultiColorOrder(e,t){this.checkSize(e,t,4);let r=t;return{order:{type:8,posX:e.readUInt8(r+1),posY:e.readUInt8(r+2),spriteIndex:e.readUInt8(r+3)},bytesRead:4}}decodeColorMapOrder(e,t){this.checkSize(e,t,5);let r=t,n=e.readUInt8(r+3)+1,o=e.readUInt8(r+4)+1,i=n*o;this.checkSize(e,t,5+i*2);let s=[];for(let d=0;d<i;d++){let l=r+5+d*2;s.push({bgColorCode:e.readUInt8(l),fgColorCode:e.readUInt8(l+1)})}return{order:{type:9,posX:e.readUInt8(r+1),posY:e.readUInt8(r+2),sizeX:n,sizeY:o,colorData:s},bytesRead:5+i*2}}decodeShapeOrder(e,t,r){this.checkSize(e,t,2);let n=t,o=e.readUInt8(n+1),{shapeData:i,bytesRead:s}=this.decodeShapeData(e,n+2,o,r);return{order:{type:10,shapeType:o,shapeData:i},bytesRead:2+s}}decodeShapeData(e,t,r,n){let o=t,i=this.charCodeSize(n);switch(r){case 1:{let s=7+i;this.checkSize(e,t,s);let a=e.readUInt8(o++),d=e.readUInt8(o++),l=e.readUInt8(o++)+1,c=e.readUInt8(o++)+1,u=e.readUInt8(o++)===1,[p,m]=this.readCharCode(e,o,n);o=m;let g=e.readUInt8(o++),y=e.readUInt8(o++);return{shapeData:{posX:a,posY:d,width:l,height:c,filled:u,charCode:p,bgColorCode:g,fgColorCode:y},bytesRead:s}}case 2:{let s=6+i;this.checkSize(e,t,s);let a=e.readUInt8(o++),d=e.readUInt8(o++),l=e.readUInt8(o++)+1,c=e.readUInt8(o++)===1,[u,p]=this.readCharCode(e,o,n);o=p;let m=e.readUInt8(o++),g=e.readUInt8(o++);return{shapeData:{centerX:a,centerY:d,radius:l,filled:c,charCode:u,bgColorCode:m,fgColorCode:g},bytesRead:s}}case 3:{let s=6+i;this.checkSize(e,t,s);let a=e.readUInt8(o++),d=e.readUInt8(o++),l=e.readUInt8(o++),c=e.readUInt8(o++),[u,p]=this.readCharCode(e,o,n);o=p;let m=e.readUInt8(o++),g=e.readUInt8(o++);return{shapeData:{x1:a,y1:d,x2:l,y2:c,charCode:u,bgColorCode:m,fgColorCode:g},bytesRead:s}}case 4:{let s=7+i;this.checkSize(e,t,s);let a=e.readUInt8(o++),d=e.readUInt8(o++),l=e.readUInt8(o++)+1,c=e.readUInt8(o++)+1,u=e.readUInt8(o++)===1,[p,m]=this.readCharCode(e,o,n);o=m;let g=e.readUInt8(o++),y=e.readUInt8(o++);return{shapeData:{centerX:a,centerY:d,radiusX:l,radiusY:c,filled:u,charCode:p,bgColorCode:g,fgColorCode:y},bytesRead:s}}case 5:{let s=9+i;this.checkSize(e,t,s);let a=e.readUInt8(o++),d=e.readUInt8(o++),l=e.readUInt8(o++),c=e.readUInt8(o++),u=e.readUInt8(o++),p=e.readUInt8(o++),m=e.readUInt8(o++)===1,[g,y]=this.readCharCode(e,o,n);o=y;let S=e.readUInt8(o++),I=e.readUInt8(o++);return{shapeData:{x1:a,y1:d,x2:l,y2:c,x3:u,y3:p,filled:m,charCode:g,bgColorCode:S,fgColorCode:I},bytesRead:s}}default:throw new Error(`Unknown shape type: ${r}`)}}decodeDotCloudOrder(e,t,r){let o=1+this.charCodeSize(r)+2+2;this.checkSize(e,t,o);let i=t,s=e.readUInt8(i++),[a,d]=this.readCharCode(e,i,r);i=d;let l=e.readUInt8(i++),c=e.readUInt8(i++),u=e.readUInt16BE(i);i+=2,this.checkSize(e,t,o+u*2);let p=[];for(let g=0;g<u;g++)p.push({posX:e.readUInt8(i++),posY:e.readUInt8(i++)});return{order:{type:11,charCode:a,bgColorCode:l,fgColorCode:c,positions:p},bytesRead:o+u*2}}decodeDotCloudMultiColorOrder(e,t,r){this.checkSize(e,t,3);let n=this.charCodeSize(r),o=t,i=e.readUInt16BE(o+1),s=n+4;this.checkSize(e,t,3+i*s);let a=[],d=o+3;for(let c=0;c<i;c++){let[u,p]=this.readCharCode(e,d,r);d=p,a.push({charCode:u,bgColorCode:e.readUInt8(d++),fgColorCode:e.readUInt8(d++),posX:e.readUInt8(d++),posY:e.readUInt8(d++)})}return{order:{type:12,dots:a},bytesRead:3+i*s}}decodeBitmaskOrder(e,t,r){let o=8+this.charCodeSize(r);this.checkSize(e,t,o);let i=t,s=e.readUInt8(i++),a=e.readUInt8(i++),d=e.readUInt8(i++),l=e.readUInt8(i++)+1,c=e.readUInt8(i++)+1,[u,p]=this.readCharCode(e,i,r);i=p;let m=e.readUInt8(i++),g=e.readUInt8(i++),y=e.readUInt8(i++)===1,S=Math.ceil(l*c/8);this.checkSize(e,t,o+S);let I=new Uint8Array(S);for(let U=0;U<S;U++)I[U]=e.readUInt8(i+U);return{order:{type:17,posX:a,posY:d,sizeX:l,sizeY:c,charCode:u,bgColorCode:m,fgColorCode:g,override:y,mask:I},bytesRead:o+S}}decodeBitmask4Order(e,t,r){let i=6+3*(this.charCodeSize(r)+2);this.checkSize(e,t,i);let s=t,a=e.readUInt8(s++),d=e.readUInt8(s++),l=e.readUInt8(s++),c=e.readUInt8(s++)+1,u=e.readUInt8(s++)+1,p=e.readUInt8(s++)===1,m=Math.ceil(c*u/4);this.checkSize(e,t,i+m);let g=[];for(let I=0;I<3;I++){let[O,U]=this.readCharCode(e,s,r);s=U,g.push({charCode:O,bgColorCode:e.readUInt8(s++),fgColorCode:e.readUInt8(s++)})}let y=new Uint8Array(m);for(let I=0;I<m;I++)y[I]=e.readUInt8(s+I);return{order:{type:18,posX:d,posY:l,sizeX:c,sizeY:u,override:p,variants:g,mask:y},bytesRead:i+m}}decodeBitmask16Order(e,t,r){let i=6+15*(this.charCodeSize(r)+2);this.checkSize(e,t,i);let s=t,a=e.readUInt8(s++),d=e.readUInt8(s++),l=e.readUInt8(s++),c=e.readUInt8(s++)+1,u=e.readUInt8(s++)+1,p=e.readUInt8(s++)===1,m=Math.ceil(c*u/2);this.checkSize(e,t,i+m);let g=[];for(let I=0;I<15;I++){let[O,U]=this.readCharCode(e,s,r);s=U,g.push({charCode:O,bgColorCode:e.readUInt8(s++),fgColorCode:e.readUInt8(s++)})}let y=new Uint8Array(m);for(let I=0;I<m;I++)y[I]=e.readUInt8(s+I);return{order:{type:24,posX:d,posY:l,sizeX:c,sizeY:u,override:p,variants:g,mask:y},bytesRead:i+m}}decodePolylineOrder(e,t,r){let o=4+this.charCodeSize(r);this.checkSize(e,t,o);let i=t,s=e.readUInt8(i++),[a,d]=this.readCharCode(e,i,r);i=d;let l=e.readUInt8(i++),c=e.readUInt8(i++),u=e.readUInt8(i++);this.checkSize(e,t,o+u*2);let p=[];for(let g=0;g<u;g++)p.push({x:e.readUInt8(i++),y:e.readUInt8(i++)});return{order:{type:25,charCode:a,fgColorCode:l,bgColorCode:c,points:p},bytesRead:o+u*2}}decodeSpriteCloudOrder(e,t){this.checkSize(e,t,6);let r=t,n=e.readUInt16BE(r+4);this.checkSize(e,t,6+n*2);let o=[];for(let s=0;s<n;s++){let a=r+6+s*2;o.push({posX:e.readUInt8(a),posY:e.readUInt8(a+1)})}return{order:{type:13,spriteIndex:e.readUInt8(r+1),bgColorCode:e.readUInt8(r+2),fgColorCode:e.readUInt8(r+3),positions:o},bytesRead:6+n*2}}decodeSpriteCloudMultiColorOrder(e,t){this.checkSize(e,t,4);let r=t,n=e.readUInt16BE(r+2);this.checkSize(e,t,4+n*2);let o=[];for(let s=0;s<n;s++){let a=r+4+s*2;o.push({posX:e.readUInt8(a),posY:e.readUInt8(a+1)})}return{order:{type:14,spriteIndex:e.readUInt8(r+1),positions:o},bytesRead:4+n*2}}decodeSpriteCloudVariedOrder(e,t){this.checkSize(e,t,3);let r=t,n=e.readUInt16BE(r+1);this.checkSize(e,t,3+n*5);let o=[];for(let s=0;s<n;s++){let a=r+3+s*5;o.push({spriteIndex:e.readUInt8(a),bgColorCode:e.readUInt8(a+1),fgColorCode:e.readUInt8(a+2),posX:e.readUInt8(a+3),posY:e.readUInt8(a+4)})}return{order:{type:15,sprites:o},bytesRead:3+n*5}}decodeSpriteCloudVariedMultiColorOrder(e,t){this.checkSize(e,t,3);let r=t,n=e.readUInt16BE(r+1);this.checkSize(e,t,3+n*3);let o=[];for(let s=0;s<n;s++){let a=r+3+s*3;o.push({spriteIndex:e.readUInt8(a),posX:e.readUInt8(a+1),posY:e.readUInt8(a+2)})}return{order:{type:16,sprites:o},bytesRead:3+n*3}}decodeFillOrder(e,t,r){let o=3+this.charCodeSize(r);this.checkSize(e,t,o);let i=t,s=e.readUInt8(i++),[a,d]=this.readCharCode(e,i,r);i=d;let l=e.readUInt8(i++),c=e.readUInt8(i++);return{order:{type:19,charCode:a,bgColorCode:l,fgColorCode:c},bytesRead:o}}decodeFillCharOrder(e,t,r){this.checkSize(e,t,5);let n=this.charCodeSize(r),o=t,i=e.readUInt8(o+1)+1,s=e.readUInt8(o+2)+1,a=i*s,d=5+a*n;this.checkSize(e,t,d);let l=[],c=o+5;for(let p=0;p<a;p++){let[m,g]=this.readCharCode(e,c,r);l.push(m),c=g}return{order:{type:20,patternWidth:i,patternHeight:s,bgColorCode:e.readUInt8(o+3),fgColorCode:e.readUInt8(o+4),pattern:l},bytesRead:d}}decodeFillSpriteOrder(e,t){this.checkSize(e,t,4);let r=t;return{order:{type:21,spriteIndex:e.readUInt8(r+1),bgColorCode:e.readUInt8(r+2),fgColorCode:e.readUInt8(r+3)},bytesRead:4}}decodeFillSpriteMultiColorOrder(e,t){this.checkSize(e,t,2);let r=t;return{order:{type:22,spriteIndex:e.readUInt8(r+1)},bytesRead:2}}checkSize(e,t,r){if(t+r>e.length)throw new Error(`Buffer too short: need ${r} bytes at offset ${t}, but only ${e.length-t} bytes available`)}};b(Gr,"OrderDecoder");var pt=Gr;var xo=32,ho=64,$r=class $r{constructor(){h(this,"orderDecoder");this.orderDecoder=new pt}decode(e,t=0){this.checkSize(e,t,13);let n=t,o=e.readUInt16BE(n);n+=2;let i=e.readUInt8(n++),s=e.readUInt8(n++),a=e.readUInt16BE(n);n+=2;let d=e.readUInt16BE(n);n+=2;let l=e.readUInt16BE(n);n+=2;let c=e.readUInt16BE(n);n+=2;let u=e.readUInt8(n++),p=(i&xo)!==0,m=(i&ho)!==0,g=[],y=n;for(let I=0;I<u;I++){let O=this.orderDecoder.decode(e,y,m);g.push(O.order),y+=O.bytesRead}return{layer:{id:o,updateFlags:i,zIndex:s,originX:a,originY:d,width:l,height:c,orderCount:u,orders:g,isMacroLayer:p,is16bit:m},bytesRead:y-t}}checkSize(e,t,r){if(t+r>e.length)throw new Error(`Buffer too short for layer: need ${r} bytes at offset ${t}, but only ${e.length-t} bytes available`)}};b($r,"LayerDecoder");var mt=$r;var Zr=class Zr{decode(e,t=0){if(t>=e.length)throw new Error("Buffer too short to decode audio order type");let r=e.readUInt8(t);switch(r){case 1:return this.decodePlaySoundOrder(e,t);case 2:return this.decodePlayGlobalSoundOrder(e,t);case 3:return this.decodeStopSoundOrder(e,t);case 4:return this.decodeFadeOutSoundOrder(e,t);case 5:return this.decodePauseSoundOrder(e,t);case 6:return this.decodeResumeSoundOrder(e,t);case 7:return this.decodeSetListenerPositionOrder(e,t);case 8:return this.decodeConfigureSpatialOrder(e,t);case 9:return this.decodeSetSoundEffectsOrder(e,t);default:throw new Error(`Unknown audio order type: 0x${r.toString(16)}`)}}decodePlaySoundOrder(e,t){this.checkSize(e,t,5);let r=t,n=e.readUInt8(r++),o=e.readUInt8(r++),i=e.readUInt16BE(r);r+=2;let s=e.readUInt8(r++),a={type:n,soundId:o,instanceId:i,flags:s};return s&2&&(this.checkSize(e,r,1),a.volume=e.readUInt8(r++)),s&4&&(this.checkSize(e,r,1),a.pitch=e.readUInt8(r++)),s&8&&(this.checkSize(e,r,1),a.fadeIn=e.readUInt8(r++)),s&16&&(this.checkSize(e,r,4),a.posX=e.readUInt16BE(r),r+=2,a.posY=e.readUInt16BE(r),r+=2),s&32&&(this.checkSize(e,r,1),a.lowpass=e.readUInt8(r++)),s&64&&(this.checkSize(e,r,1),a.highpass=e.readUInt8(r++)),s&128&&(this.checkSize(e,r,1),a.reverb=e.readUInt8(r++)),{order:a,bytesRead:r-t}}decodePlayGlobalSoundOrder(e,t){this.checkSize(e,t,5);let r=t,n=e.readUInt8(r++),o=e.readUInt8(r++),i=e.readUInt16BE(r);r+=2;let s=e.readUInt8(r++),a={type:n,soundId:o,instanceId:i,flags:s};return s&2&&(this.checkSize(e,r,1),a.volume=e.readUInt8(r++)),s&4&&(this.checkSize(e,r,1),a.pitch=e.readUInt8(r++)),s&8&&(this.checkSize(e,r,1),a.fadeIn=e.readUInt8(r++)),s&32&&(this.checkSize(e,r,1),a.lowpass=e.readUInt8(r++)),s&64&&(this.checkSize(e,r,1),a.highpass=e.readUInt8(r++)),s&128&&(this.checkSize(e,r,1),a.reverb=e.readUInt8(r++)),{order:a,bytesRead:r-t}}decodeStopSoundOrder(e,t){this.checkSize(e,t,2);let r=t,n=e.readUInt8(r++),o=e.readUInt8(r++),i={type:n,targetType:o};return o===0?(this.checkSize(e,r,2),i.target=e.readUInt16BE(r),r+=2):o===1&&(this.checkSize(e,r,1),i.target=e.readUInt8(r++)),{order:i,bytesRead:r-t}}decodeFadeOutSoundOrder(e,t){this.checkSize(e,t,3);let r=t,n=e.readUInt8(r++),o=e.readUInt8(r++),i=e.readUInt8(r++),s={type:n,targetType:o,duration:i};return o===0?(this.checkSize(e,r,2),s.target=e.readUInt16BE(r),r+=2):o===1&&(this.checkSize(e,r,1),s.target=e.readUInt8(r++)),{order:s,bytesRead:r-t}}decodePauseSoundOrder(e,t){this.checkSize(e,t,2);let r=t,n=e.readUInt8(r++),o=e.readUInt8(r++),i={type:n,targetType:o};return o===0?(this.checkSize(e,r,2),i.target=e.readUInt16BE(r),r+=2):o===1&&(this.checkSize(e,r,1),i.target=e.readUInt8(r++)),{order:i,bytesRead:r-t}}decodeResumeSoundOrder(e,t){this.checkSize(e,t,2);let r=t,n=e.readUInt8(r++),o=e.readUInt8(r++),i={type:n,targetType:o};return o===0?(this.checkSize(e,r,2),i.target=e.readUInt16BE(r),r+=2):o===1&&(this.checkSize(e,r,1),i.target=e.readUInt8(r++)),{order:i,bytesRead:r-t}}decodeSetListenerPositionOrder(e,t){this.checkSize(e,t,5);let r=t,n=e.readUInt8(r++),o=e.readUInt16BE(r);r+=2;let i=e.readUInt16BE(r);return r+=2,{order:{type:n,x:o,y:i},bytesRead:5}}decodeConfigureSpatialOrder(e,t){this.checkSize(e,t,5);let r=t;return{order:{type:e.readUInt8(r),maxDistance:e.readUInt8(r+1),referenceDistance:e.readUInt8(r+2),rolloffFactor:e.readUInt8(r+3),panSpread:e.readUInt8(r+4)},bytesRead:5}}decodeSetSoundEffectsOrder(e,t){this.checkSize(e,t,4);let r=t,n=e.readUInt8(r++),o=e.readUInt16BE(r);r+=2;let i=e.readUInt8(r++),s={type:n,instanceId:o,flags:i};return i&1&&(this.checkSize(e,r,1),s.lowpass=e.readUInt8(r++)),i&2&&(this.checkSize(e,r,1),s.highpass=e.readUInt8(r++)),i&4&&(this.checkSize(e,r,1),s.reverb=e.readUInt8(r++)),{order:s,bytesRead:r-t}}checkSize(e,t,r){if(t+r>e.length)throw new Error(`Buffer too short for audio order: need ${r} bytes at offset ${t}, but only ${e.length-t} bytes available`)}};b(Zr,"AudioOrderDecoder");var ie=Zr;var Wr=class Wr{decode(e,t=0){if(t>=e.length)throw new Error("Buffer too short to decode vibration order type");let r=e.readUInt8(t);switch(r){case 1:return this.decodeMobileVibrateOrder(e,t);case 2:return this.decodeMobileCancelOrder(e,t);case 16:return this.decodeGamepadVibrateOrder(e,t);case 17:return this.decodeGamepadCancelOrder(e,t);default:throw new Error(`Unknown vibration order type: 0x${r.toString(16)}`)}}decodeMobileVibrateOrder(e,t){let r=t,n=e.readUInt8(r++),o=e.readUInt8(r++),i=e.readUInt8(r++),s=[];for(let d=0;d<i;d++)s.push(e.readUInt16BE(r)),r+=2;let a={type:n,flags:o,pattern:s};return o&1&&(a.intensity=e.readUInt8(r++)/255),{order:a,bytesRead:r-t}}decodeMobileCancelOrder(e,t){return{order:{type:2},bytesRead:1}}decodeGamepadVibrateOrder(e,t){let r=t,n=e.readUInt8(r++),o=e.readUInt8(r++),i=e.readUInt8(r++),s=e.readUInt16BE(r);r+=2;let a=e.readUInt8(r++),d=e.readUInt8(r++),l={type:n,flags:o,gamepadIndex:i,duration:s,strongMagnitude:a,weakMagnitude:d};return o&1&&(l.startDelay=e.readUInt16BE(r),r+=2),{order:l,bytesRead:r-t}}decodeGamepadCancelOrder(e,t){let r=t,n=e.readUInt8(r++),o=e.readUInt8(r++),i=e.readUInt8(r++);return{order:{type:n,flags:o,gamepadIndex:i},bytesRead:r-t}}};b(Wr,"VibrationOrderDecoder");var se=Wr;var jr=class jr{decode(e,t=0){let r=e.readUInt8(t);switch(r){case 1:return this.decodeCreateInstance(e,t);case 2:return this.decodeUpdateInstance(e,t);case 3:return this.decodeRemoveInstance(e,t);default:throw new Error(`Unknown macro order type: 0x${r.toString(16)}`)}}decodeAll(e,t,r){let n=[],o=0;for(let i=0;i<r;i++){let{order:s,bytesRead:a}=this.decode(e,t+o);n.push(s),o+=a}return{orders:n,bytesRead:o}}decodeCreateInstance(e,t){let r=t,n=e.readUInt8(t++),o=e.readUInt8(t++),i=e.readUInt8(t++),s=e.readUInt8(t++),a=e.readInt16BE(t);t+=2;let d=e.readInt16BE(t);t+=2;let l=e.readUInt8(t++),c=e.readUInt16BE(t);t+=2;let u=e.toUint8Array().subarray(t,t+c);t+=c;let p=new TextDecoder().decode(u),m=JSON.parse(p);return{order:{type:n,instanceId:o,macroId:i,layerId:s,x:a,y:d,tabIndex:l,params:m},bytesRead:t-r}}decodeUpdateInstance(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),d=JSON.parse(a);return{order:{type:n,instanceId:o,params:d},bytesRead:t-r}}decodeRemoveInstance(e,t){let r=e.readUInt8(t),n=e.readUInt8(t+1);return{order:{type:r,instanceId:n},bytesRead:2}}};b(jr,"MacroOrderDecoder");var xt=jr;var Jr=class Jr{decode(e,t){let r=e[t];switch(r){case 1:return this.decodeSetConfigOrder(e,t);case 2:return this.decodeSetScanlinesOrder(e,t);case 3:return this.decodeSetAmbientEffectOrder(e,t);case 4:return this.decodeSetScalingModeOrder(e,t);case 5:return this.decodeSetGridOrder(e,t);case 6:return this.decodeSwitchPaletteOrder(e,t);case 7:return this.decodeSetCellSizeOrder(e,t);default:throw new Error(`Unknown post-process order type: ${r}`)}}decodeSetConfigOrder(e,t){let r=t,n=e[r++],o=e[r++],i=e[r++],s={type:n,displayId:o,flags:i};return i&1&&(s.scanlines={enabled:e[r++]===1,opacity:e[r++]/255,pattern:e[r++],colorR:e[r++],colorG:e[r++],colorB:e[r++]}),i&2&&(s.ambientEffect={enabled:e[r++]===1,blur:e[r++],scale:e[r++]/100,opacity:e[r++]/255}),{order:s,bytesRead:r-t}}decodeSetScanlinesOrder(e,t){let r=t;return{order:{type:e[r++],displayId:e[r++],enabled:e[r++]===1,opacity:e[r++]/255,pattern:e[r++],colorR:e[r++],colorG:e[r++],colorB:e[r++]},bytesRead:r-t}}decodeSetAmbientEffectOrder(e,t){let r=t;return{order:{type:e[r++],displayId:e[r++],enabled:e[r++]===1,blur:e[r++],scale:e[r++]/100,opacity:e[r++]/255},bytesRead:r-t}}decodeSetScalingModeOrder(e,t){let r=t;return{order:{type:e[r++],displayId:e[r++],mode:e[r++]},bytesRead:r-t}}decodeSetGridOrder(e,t){let r=t;return{order:{type:e[r++],displayId:e[r++],enabled:e[r++]===1,colorR:e[r++],colorG:e[r++],colorB:e[r++],colorA:e[r++],lineWidth:e[r++]},bytesRead:r-t}}decodeSwitchPaletteOrder(e,t){let r=t;return{order:{type:e[r++],displayId:e[r++],slotId:e[r++]},bytesRead:r-t}}decodeSetCellSizeOrder(e,t){let r=t;return{order:{type:e[r++],displayId:e[r++],cellWidth:e[r++],cellHeight:e[r++]},bytesRead:r-t}}};b(Jr,"PostProcessOrderDecoder");var ae=Jr;var qr=class qr{constructor(){h(this,"displayDecoder");h(this,"layerDecoder");h(this,"audioOrderDecoder");h(this,"vibrationOrderDecoder");h(this,"macroOrderDecoder");h(this,"postProcessOrderDecoder");this.displayDecoder=new ut,this.layerDecoder=new mt,this.audioOrderDecoder=new ie,this.vibrationOrderDecoder=new se,this.macroOrderDecoder=new xt,this.postProcessOrderDecoder=new ae}decode(e,t=0){let r=f.from(e);this.checkSize(r,t,15);let o=t,i=Number(r.readBigUInt64BE(o));o+=8;let s=r.readUInt8(o);o+=1;let a=[],d=0;for(let L=0;L<s;L++){let w=this.displayDecoder.decode(r,o);a.push(w.display),o+=w.bytesRead,d+=w.bytesRead}this.checkSize(r,o,2);let l=r.readUInt16BE(o);o+=2;let c=[],u=0;for(let L=0;L<l;L++){let w=this.layerDecoder.decode(r,o);c.push({...w.layer,byteSize:w.bytesRead}),o+=w.bytesRead,u+=w.bytesRead}this.checkSize(r,o,1);let p=r.readUInt8(o);o+=1;let m=[],g=0;for(let L=0;L<p;L++){let w=this.audioOrderDecoder.decode(r,o);m.push(w.order),o+=w.bytesRead,g+=w.bytesRead}this.checkSize(r,o,1);let y=r.readUInt8(o);o+=1;let S=[],I=0;for(let L=0;L<y;L++){let w=this.vibrationOrderDecoder.decode(r,o);S.push(w.order),o+=w.bytesRead,I+=w.bytesRead}this.checkSize(r,o,1);let O=r.readUInt8(o);o+=1;let U=[],v=0;for(let L=0;L<O;L++){let w=this.macroOrderDecoder.decode(r,o);U.push(w.order),o+=w.bytesRead,v+=w.bytesRead}this.checkSize(r,o,1);let k=r.readUInt8(o);o+=1;let M=[],A=0;for(let L=0;L<k;L++){let w=this.postProcessOrderDecoder.decode(r.toUint8Array(),o);M.push(w.order),o+=w.bytesRead,A+=w.bytesRead}return{tick:i,displayCount:s,displays:a,layerCount:l,layers:c,audioOrderCount:p,audioOrders:m,vibrationOrderCount:y,vibrationOrders:S,macroOrderCount:O,macroOrders:U,postProcessOrderCount:k,postProcessOrders:M,__byteSizes:{displays:d,layers:u,audioOrders:g,vibrationOrders:I,macroOrders:v,postProcessOrders:A}}}isValid(e,t=0){let r=f.from(e);try{return this.checkSize(r,t,15),!0}catch{return!1}}decodeHeader(e,t=0){let r=f.from(e);this.checkSize(r,t,13);let n=t,o=Number(r.readBigUInt64BE(n));n+=8;let i=r.readUInt8(n);n+=1;for(let a=0;a<i;a++){let d=this.displayDecoder.decode(r,n);n+=d.bytesRead}this.checkSize(r,n,2);let s=r.readUInt16BE(n);return{tick:o,displayCount:i,layerCount:s}}checkSize(e,t,r){if(t+r>e.length)throw new Error(`Buffer too short for update packet: need ${r} bytes at offset ${t}, but only ${e.length-t} bytes available`)}};b(qr,"UpdatePacketDecoder");var de=qr;var H=class H{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=H.charCache.get(e);return t===void 0&&(t=String.fromCharCode(e),H.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,I=g.getWidth(),O=g.getHeight();if(y<0||y>=I||S<0||S>=O)continue;let U=S*I+y,v=g.getData(),k=v.getCharCode(U),M=v.getFgColorCode(U),A=v.getBgColorCode(U),C=n[c];if(k!==0&&C.char===" "&&(C.char=H.getChar(k)),M!==255&&C.fgColorIndex===255&&(C.fgColorIndex=M,C.fgEmission=this.getColorEmission(M)),A!==255){C.bgColorIndex===255&&(C.bgColorIndex=A,C.bgEmission=this.getColorEmission(A)),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],I=S.getZOrder();I<c.zMin||I>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 I=g*y+m,O=p.getData(),U=O.getCharCode(I),v=O.getFgColorCode(I),k=O.getBgColorCode(I),M=r[d];if(U!==0&&M.char===" "&&(M.char=H.getChar(U)),v!==255&&M.fgColorIndex===255&&(M.fgColorIndex=v,M.fgEmission=this.getColorEmission(v)),k!==255){M.bgColorIndex===255&&(M.bgColorIndex=k,M.bgEmission=this.getColorEmission(k)),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(),I=m.getHeight();if(g<0||g>=S||y<0||y>=I)continue;let O=y*S+g,U=m.getData(),v=U.getCharCode(O),k=U.getFgColorCode(O),M=U.getBgColorCode(O),A=n[l];if(v!==0&&A.char===" "&&(A.char=H.getChar(v)),k!==255&&A.fgColorIndex===255&&(A.fgColorIndex=k,A.fgEmission=this.getColorEmission(k)),M!==255){A.bgColorIndex===255&&(A.bgColorIndex=M,A.bgEmission=this.getColorEmission(M)),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(H,"DisplayRasterizer"),h(H,"charCache",(()=>{let e=new Map;for(let t=0;t<256;t++)e.set(t,String.fromCharCode(t));return e})());var ht=H;var Kr=class Kr{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(Kr,"CoreStats");var le=Kr;var Bn=[[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]],bo=new Map(Bn),na=new Map(Bn.map(([x,e])=>[e,x]));function $(x){if(x<128)return x;let e=bo.get(x);return e!==void 0?e:x&255}b($,"unicodeToCp437");var Qr=class Qr{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 X(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,$(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,$(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 X(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 _(n*o);for(let d=0;d<Math.min(i.length,n*o);d++){let l=i[d],c=typeof l.charCode=="string"?$(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 _(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(Qr,"SpriteRegistry");var ce=Qr;var en=(t=>(t.Bitmap="bitmap",t.Image="image",t))(en||{});function bt(x){return Math.sqrt(x)*16}b(bt,"getAtlasColumns");function tn(x){return x*256-1}b(tn,"getMaxCharCode");function zn(x,e){let r=bt(x)*e;return{width:r,height:r}}b(zn,"getAtlasDimensions");var rn=class rn{constructor(e,t){this.fontId=e;this.config=t;h(this,"atlasColumns");h(this,"maxCharCode");h(this,"blocks",new Map);this.atlasColumns=bt(t.atlasBlocks),this.maxCharCode=tn(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(rn,"ImageFont");var Z=rn;var nn=class nn{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 Z(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 Z(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(nn,"ImageFontRegistry");var ue=nn;var on=class on{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(on,"SoundRegistry");var pe=on;var sn=class sn{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(sn,"AudioOrderCollector");var me=sn;var an=class an{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(an,"VibrationOrderCollector");var xe=an;var D=require("@utsp/types");var dn=class dn{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??D.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??D.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??D.POST_PROCESS_DEFAULTS.ambientEffect.blur,scale:o.scale??D.POST_PROCESS_DEFAULTS.ambientEffect.scale,opacity:o.opacity??D.POST_PROCESS_DEFAULTS.ambientEffect.opacity}}return n.flags=r,n}createSetScanlinesOrder(e,t,r){return{type:2,displayId:e,enabled:t,opacity:r??D.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??D.POST_PROCESS_DEFAULTS.ambientEffect.blur,scale:n??D.POST_PROCESS_DEFAULTS.ambientEffect.scale,opacity:D.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,D.scalingModeToValue)(t)}}createSetGridOrder(e,t){let{r,g:n,b:o,a:i}=this.parseColor(t.color??D.GRID_DEFAULTS.color);return{type:5,displayId:e,enabled:t.enabled,colorR:r,colorG:n,colorB:o,colorA:i,lineWidth:t.lineWidth??D.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(dn,"PostProcessOrderCollector");var he=dn;var be=class be{constructor(e={}){h(this,"mode");h(this,"maxUsers");h(this,"strictMode",!1);h(this,"currentTick",0);h(this,"stats",new le);h(this,"spriteRegistry",new ce);h(this,"imageFontRegistry",new ue);h(this,"soundRegistry",new pe);h(this,"audioOrderCollector",new me(this.soundRegistry));h(this,"vibrationOrderCollector",new xe);h(this,"postProcessOrderCollector",new he);h(this,"encoder",new at);h(this,"users",new Map);h(this,"colorPalette",new Map);h(this,"paletteSlots",new Map);h(this,"displayRasterizer",new ht(this));h(this,"updatePacketDecoder",new de);h(this,"loadDecoder",new ct);h(this,"cachedLoadPackets",null);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})),be.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 re(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.cachedLoadPackets=null,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??255,e:n.e??0});be.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 I=S.getOrigin(),O=S.getSize();return{id:S.getId(),originX:I.x,originY:I.y,sizeX:O.x,sizeY:O.y,renderPasses:S.getRenderPasses()}});s.forEach(S=>S.resetChangeTracking());let d=[],l=[];i.forEach((S,I)=>{if(!S.getNeedsCommit())return;let O=S.getOrigin(),U=S.getOrders(),v=S.getMustBeReliable(),k=S.calculateUpdateFlags();S.resetChangeTracking(),S.resetCommit(),S.getId()===0&&J(S,I);let M={id:S.getId(),updateFlags:k,zIndex:S.getZOrder(),originX:O.x,originY:O.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(),v,U.length,k),v?d.push(M):l.push(M)}),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((v,k)=>{let M=k.getSize();return v+M.x*M.y},0);n.getStats().recordDisplays(s.length,S),n.getStats().recordLayers(i.length,d.length+l.length,d.length,l.length),[...d,...l].forEach(v=>{n.getStats().recordLayerOrders(v.id,v.orders.length)});let I=g?.length||0,O=y?.length||0;n.getStats().recordPacketSizes(I,O);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((k,M)=>{this.stats.recordLayerOrders(M,k.orders)}),s.forEach((k,M)=>{this.stats.recordDisplayLayers(M,S.length)});let I=(g?.length||0)+(y?.length||0),O=a.reduce((k,M)=>{let A=Math.min(M.renderPasses?.length??0,4);return k+8+A*4},0),U=S.length*20,v=I-O-U;this.stats.recordUpdatePacketSize(I,O,U,v>0?v: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&&J(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 r=this.updatePacketDecoder.decode(t);return this.applyUpdatePacket(e,r)?r:null}applyLoadPacket(e){try{let r=this.loadDecoder.decode(e).load;switch(r.loadType){case 1:r.slotId!==void 0?this.loadPaletteToSlot(r.slotId,r.colors):(console.warn("[Core] ColorPalette load without slotId is deprecated. Loading into slot 0."),this.loadPaletteToSlot(0,r.colors));break;case 2:this.spriteRegistry.loadUnicolorSprites(r);break;case 3:this.spriteRegistry.loadMulticolorSprites(r);break;case 5:console.warn("[Core] Sound loading not yet implemented");break;case 8:this.loadFont(r.glyphWidth,r.glyphHeight,r.atlasBlocks,r.cellWidth,r.cellHeight);break;case 9:this.loadFontBlock(r.blockIndex,r.imageData);break;case 7:{for(let n of this.users.values())n.loadMacroTemplate(r.macroId,r.template);break}default:return console.error(`[Core] Unknown LoadType: ${r.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 oe,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(){if(this.spriteRegistry.getUnicolorSpriteCount()===0)return null;let e=[];for(let r=0;r<=255;r++){let n=this.spriteRegistry.getUnicolorSprite(r);if(n){let o=[];for(let i=0;i<n.sizeX*n.sizeY;i++)o.push(n.data.get(i));e.push({spriteId:n.id,sizeX:n.sizeX,sizeY:n.sizeY,data:o})}}return e.length===0?null:new oe().encode({loadType:2,sprites:e})}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 oe().encode({loadType:3,sprites:t})}generateAllLoadPackets(){if(this.cachedLoadPackets)return this.cachedLoadPackets;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),this.cachedLoadPackets=e,e}generateMacroLoadPackets(e){let t=this.getUser(e);if(!t)return[];let r=t.getMacroLoads();if(r.length===0)return[];let n=new dt;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(be,"Core"),h(be,"ANSI_VGA_COLORS",[{colorId:240,r:0,g:0,b:0,a:255,e:0},{colorId:241,r:60,g:60,b:75,a:255,e:0},{colorId:242,r:160,g:160,b:180,a:255,e:0},{colorId:243,r:255,g:255,b:255,a:255,e:0},{colorId:244,r:230,g:50,b:80,a:255,e:0},{colorId:245,r:255,g:120,b:50,a:255,e:0},{colorId:246,r:255,g:210,b:60,a:255,e:0},{colorId:247,r:130,g:220,b:50,a:255,e:0},{colorId:248,r:35,g:100,b:55,a:255,e:0},{colorId:249,r:40,g:200,b:220,a:255,e:0},{colorId:250,r:60,g:120,b:240,a:255,e:0},{colorId:251,r:35,g:55,b:125,a:255,e:0},{colorId:252,r:150,g:70,b:210,a:255,e:0},{colorId:253,r:130,g:80,b:50,a:255,e:0},{colorId:254,r:240,g:210,b:170,a:255,e:0}]);var gt=be;var _n=require("@utsp/types");var ge=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 Tn(x){return ge.get(x)}b(Tn,"getCharBitmap");function Ln(x){return ge.has(x)}b(Ln,"hasChar");function Fn(){return Array.from(ge.keys()).sort((x,e)=>x-e)}b(Fn,"getAllCharCodes");function Dn(){return{charWidth:8,charHeight:8,glyphs:new Map(ge)}}b(Dn,"getASCII8x8FontConfig");var ln=class ln{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=f.allocUnsafe(2);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.toUint8Array()}encodeChange(e){if(typeof e.value=="boolean"){let r=f.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=f.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=f.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=f.allocUnsafe(4);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.writeUInt16BE(e.index,2),t.toUint8Array()}};b(ln,"MacroEventEncoder");var yt=ln;function Vn(x,e,t,r,n,o,i,s=[],a=[],d=[],l=[],c=!1){let u=Array.from(e.entries()).sort((R,F)=>R[0]-F[0]),p=Array.from(t.entries()).sort((R,F)=>R[0]-F[0]),m=u.length,g=p.length,y=$e(m,g),S=new TextEncoder,I=s.map(R=>S.encode(R)),O=1+I.reduce((R,F)=>R+1+F.length,0),U=new yt,v=a.map(R=>U.encode(R)),k=1+v.reduce((R,F)=>R+F.length,0),M=Math.min(d.length,255),A=1+M*5,C=Math.min(l.length,10),L=1+C*4,w=y+O+k+A+L,P=new Uint8Array(w),ve=new DataView(P.buffer),E=0;ve.setBigUint64(E,x,!0),E+=8;for(let[,R]of u){let F=Xe(R);P[E]=F+256&255,E+=1}let Nn=G(g);for(let R=0;R<Nn;R++){let F=0;for(let Me=0;Me<8;Me++){let un=R*8+Me;if(un<g){let[,Hn]=p[un];Hn&&(F|=1<<Me)}}P[E]=F,E+=1}P[E]=r&255,E+=1,P[E]=n&255,E+=1,P[E]=o&255,E+=1;let St=0;i&&(St|=1),c&&(St|=2),P[E]=St,E+=1,P[E]=Math.min(s.length,255),E+=1;for(let R of I)P[E]=Math.min(R.length,255),E+=1,P.set(R.slice(0,255),E),E+=R.length;P[E]=Math.min(a.length,255),E+=1;for(let R of v)P.set(R,E),E+=R.length;P[E]=M,E+=1;for(let R=0;R<M;R++){let F=d[R];P[E]=F.displayId&255,E+=1,ve.setUint16(E,Math.min(F.pixelWidth,65535),!1),E+=2,ve.setUint16(E,Math.min(F.pixelHeight,65535),!1),E+=2}P[E]=C,E+=1;for(let R=0;R<C;R++){let F=l[R];P[E]=F.id&15,E+=1,P[E]=F.x&255,E+=1,P[E]=F.y&255,E+=1,P[E]=F.over?1:0,E+=1}return P}b(Vn,"encodeCompressedInput");var z=class z{static toCharCode(e){if(typeof e=="number")return e&65535;if(e.length===0)return 0;let t=e.charCodeAt(0);return $(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=$(n);t+=String.fromCharCode(o)}return t}static char(e,t,r,n=15,o=0){return{type:1,posX:e,posY:t,charCode:z.toCharCode(r),bgColorCode:o,fgColorCode:n}}static text(e,t,r,n=15,o=0){return{type:2,posX:e,posY:t,text:z.encodeString(r),bgColorCode:o,fgColorCode:n}}static textMultiline(e,t,r,n=15,o=0){return{type:23,posX:e,posY:t,text:z.encodeString(z.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=>z.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:z.toCharCode(i.charCode),bgColorCode:i.bgColorCode,fgColorCode:i.fgColorCode}))}}static fullFrame(e,t=15,r=0){return{type:5,frame:e.map(n=>z.toCharCode(n)),bgColorCode:r,fgColorCode:t}}static fullFrameMultiColor(e){return{type:6,frame:e.map(t=>({charCode:z.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:z.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:z.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:z.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:z.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:z.toCharCode(s.charCode??219),bgColorCode:s.bgColor??0,fgColorCode:s.fgColor??15}}}static dotCloud(e,t,r=15,n=0){return{type:11,charCode:z.toCharCode(t),bgColorCode:n,fgColorCode:r,positions:e}}static dotCloudMultiColor(e){return{type:12,dots:e.map(t=>({...t,charCode:z.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:z.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:z.toCharCode(d[0].char),fgColorCode:d[0].fgColor,bgColorCode:d[0].bgColor},{charCode:z.toCharCode(d[1].char),fgColorCode:d[1].fgColor,bgColorCode:d[1].bgColor},{charCode:z.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:z.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:z.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=>z.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:z.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(z,"OrderBuilder");var Ct=z;Ur();var cn=(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))(cn||{}),ft;(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")})(ft||(ft={}));vr();Sr();Ir();
|