@utsp/runtime-server 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.
|
@@ -49,7 +49,7 @@ Orders breakdown: ${this.getOrdersBreakdown()}`),this.orders=this.orders.slice(0
|
|
|
49
49
|
`,this.buttons.forEach(t=>{e+=` [${t.bindingId}] ${t.name}: `,e+=`(default: ${t.defaultValue})
|
|
50
50
|
`}),e+=`Touch Zones (${this.touchZones.size}):
|
|
51
51
|
`,this.touchZones.forEach(t=>{e+=` [${t.zoneId}] ${t.name}: `,e+=`(${t.x}, ${t.y}) ${t.width}x${t.height}
|
|
52
|
-
`}),e}};J(tv,"InputBindingRegistry");var fI=tv;function rv(r=0n){return{tick:r,axes:new Map,buttons:new Map,displayId:0,mouseX:0,mouseY:0,mouseOverDisplay:!1,textInputs:[],macroEvents:[],displayViewports:[],touchPositions:[],isTabHidden:!1}}J(rv,"createEmptyCompressedInputPacket");function nv(r){let e=Math.max(-1,Math.min(1,r));return Math.round(e*127)}J(nv,"encodeAxisToInt8");function iv(r){return r/127}J(iv,"decodeInt8ToAxis");function Tu(r){return r===0?0:Math.ceil(r/8)}J(Tu,"getButtonByteCount");function sv(r,e){let t=r,n=Tu(e);return 8+t+n+4}J(sv,"getCompressedPacketSize");var ov=class{decode(e,t=0){let n=e.readUInt8(t);switch(n){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${n.toString(16)}`)}}decodeAll(e,t,n){let i=[],s=0;for(let o=0;o<n;o++){let{event:a,bytesRead:l}=this.decode(e,t+s);i.push(a),s+=l}return{events:i,bytesRead:s}}decodeClick(e,t){let n=e.readUInt8(t),i=e.readUInt8(t+1);return{event:{type:n,instanceId:i},bytesRead:2}}decodeChange(e,t){let n=e.readUInt8(t),i=e.readUInt8(t+1),s=e.readUInt8(t+2),o,a;return s===1?(o=e.readUInt8(t+3)===1,a=4):(o=e.readFloatBE(t+3),a=7),{event:{type:n,instanceId:i,value:o},bytesRead:a}}decodeSubmit(e,t){let n=t,i=e.readUInt8(t++),s=e.readUInt8(t++),o=e.readUInt16BE(t);t+=2;let a=e.toUint8Array().subarray(t,t+o);t+=o;let l=new TextDecoder().decode(a);return{event:{type:i,instanceId:s,text:l},bytesRead:t-n}}decodeSelect(e,t){let n=e.readUInt8(t),i=e.readUInt8(t+1),s=e.readUInt16BE(t+2);return{event:{type:n,instanceId:i,index:s},bytesRead:4}}};J(ov,"MacroEventDecoder");var pI=ov,av=class Zi{constructor(e){D(this,"data"),D(this,"view"),this.data=new Uint8Array(e),this.view=new DataView(this.data.buffer)}static from(e){let t=new Zi(0);return t.data=e,t.view=new DataView(e.buffer,e.byteOffset,e.byteLength),t}static allocUnsafe(e){return new Zi(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,n=0,i=this.length){let s=this.data.subarray(n,i);return e.data.set(s,t),s.length}slice(e,t){let n=this.data.slice(e,t);return Zi.from(n)}subarray(e,t){let n=this.data.subarray(e,t);return Zi.from(n)}toBuffer(){return typeof Buffer<"u"&&Buffer.from?Buffer.from(this.data):this.data}static fromNodeBuffer(e){return e instanceof Uint8Array?Zi.from(e):Zi.from(new Uint8Array(e))}};J(av,"BufferCompat");var ie=av,gI=new TextDecoder,mI=new pI;function lv(r,e){let t=e.getAllAxes().length,n=e.getAllButtons().length,i=Tu(n),s=8+t+i+4;if(r.length<s)throw new Error(`Invalid compressed input packet: expected at least ${s} bytes (${t} axes + ${n} buttons), got ${r.length}`);let o=new DataView(r.buffer,r.byteOffset,r.byteLength),a=0,l=rv();l.tick=o.getBigUint64(a,!0),a+=8;for(let c=0;c<t;c++){let d=r[a],h=d>127?d-256:d,f=iv(h);l.axes.set(c,f),a+=1}for(let c=0;c<i;c++){let d=r[a];for(let h=0;h<8;h++){let f=c*8+h;if(f<n){let p=(d&1<<h)!==0;l.buttons.set(f,p)}}a+=1}l.displayId=r[a],a+=1,l.mouseX=r[a],a+=1,l.mouseY=r[a],a+=1;let u=r[a];if(l.mouseOverDisplay=(u&1)!==0,l.isTabHidden=(u&2)!==0,a+=1,a<r.length){let c=r[a];a+=1,l.textInputs=[];for(let d=0;d<c&&a<r.length;d++){let h=r[a];if(a+=1,a+h<=r.length){let f=r.slice(a,a+h),p=gI.decode(f);l.textInputs.push(p),a+=h}}}if(a<r.length){let c=r[a];a+=1;let d=[],h=ie.from(r);for(let f=0;f<c&&a<r.length;f++){let p=mI.decode(h,a);d.push(p.event),a+=p.bytesRead}l.macroEvents=d}if(a<r.length){let c=r[a];a+=1;for(let d=0;d<c&&a+5<=r.length;d++){let h=r[a];a+=1;let f=o.getUint16(a,!1);a+=2;let p=o.getUint16(a,!1);a+=2,l.displayViewports.push({displayId:h,pixelWidth:f,pixelHeight:p})}}if(a<r.length){let c=Math.min(r[a],10);a+=1;for(let d=0;d<c&&a+4<=r.length;d++){let h=r[a]&15;a+=1;let f=r[a];a+=1;let p=r[a];a+=1;let m=(r[a]&1)!==0;a+=1,l.touchPositions.push({id:h,x:f,y:p,over:m})}}return l}J(lv,"decodeCompressedInput");var uv=class{constructor(e,t){D(this,"enabled",!1),D(this,"currentStats",null),D(this,"_userId"),D(this,"_userName"),this._userId=e,this._userName=t}setEnabled(e){this.enabled=e,e||(this.currentStats=null)}isEnabled(){return this.enabled}get userId(){var e;return((e=this.currentStats)==null?void 0:e.userId)??this._userId}get userName(){var e;return((e=this.currentStats)==null?void 0:e.userName)??this._userName}get tick(){var e;return((e=this.currentStats)==null?void 0:e.tick)??0}get timestamp(){var e;return((e=this.currentStats)==null?void 0:e.timestamp)??0}get displayCount(){var e;return((e=this.currentStats)==null?void 0:e.displayCount)??0}get totalDisplayArea(){var e;return((e=this.currentStats)==null?void 0:e.totalDisplayArea)??0}get totalLayers(){var e;return((e=this.currentStats)==null?void 0:e.totalLayers)??0}get visibleLayers(){var e;return((e=this.currentStats)==null?void 0:e.visibleLayers)??0}get staticLayers(){var e;return((e=this.currentStats)==null?void 0:e.staticLayers)??0}get dynamicLayers(){var e;return((e=this.currentStats)==null?void 0:e.dynamicLayers)??0}get totalOrders(){var e;return((e=this.currentStats)==null?void 0:e.totalOrders)??0}get ordersByLayer(){var e;return((e=this.currentStats)==null?void 0:e.ordersByLayer)??new Map}get staticPacketSize(){var e;return((e=this.currentStats)==null?void 0:e.staticPacketSize)??0}get dynamicPacketSize(){var e;return((e=this.currentStats)==null?void 0:e.dynamicPacketSize)??0}get totalPacketSize(){var e;return((e=this.currentStats)==null?void 0:e.totalPacketSize)??0}get compressedPacketSize(){return Math.round(this.totalPacketSize*.25)}get hasInput(){var e;return((e=this.currentStats)==null?void 0:e.hasInput)??!1}get axisCount(){var e;return((e=this.currentStats)==null?void 0:e.axisCount)??0}get buttonCount(){var e;return((e=this.currentStats)==null?void 0:e.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,n,i){!this.enabled||!this.currentStats||(this.currentStats.totalLayers=e,this.currentStats.visibleLayers=t,this.currentStats.staticLayers=n,this.currentStats.dynamicLayers=i)}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,n){!this.enabled||!this.currentStats||(this.currentStats.hasInput=e,this.currentStats.axisCount=t,this.currentStats.buttonCount=n)}endTick(){}reset(){this.currentStats=null}};J(uv,"UserStats");var yI=uv,cv=class{constructor(e,t,n){this.id=e,this.name=t,D(this,"displays",[]),D(this,"layers",[]),D(this,"spriteRegistry"),D(this,"mode"),D(this,"axes",new Map),D(this,"buttons",new Map),D(this,"textInputs",[]),D(this,"mouseX",0),D(this,"mouseY",0),D(this,"mouseOver",!1),D(this,"mouseDisplayId",0),D(this,"isTabHidden",!1),D(this,"touchPositions",new Map),D(this,"activeTouchId",null),D(this,"inputBindings",new fI),D(this,"stats"),D(this,"soundCommands",[]),D(this,"nextSoundInstanceId",1),D(this,"audioConfigCommands",[]),D(this,"lastListenerX",-1),D(this,"lastListenerY",-1),D(this,"pendingSendSounds",!1),D(this,"audioProcessor"),D(this,"loadedSounds",new Map),D(this,"soundLoadErrors",new Map),D(this,"playingSounds",new Map),D(this,"mobileVibrationCommands",[]),D(this,"mobileVibrationProcessor"),D(this,"gamepadVibrationCommands",[]),D(this,"gamepadVibrationProcessor"),D(this,"macroRegistry",new nI),D(this,"macroEngine",new hI),D(this,"macroEventHandlers",new Map),D(this,"postProcessCommands",[]),D(this,"currentPostProcessConfig",null),D(this,"bridgeMessages",[]),D(this,"totalBytesSent",0),D(this,"totalBytesReceived",0),D(this,"bytesSentPerTick",[]),D(this,"bytesReceivedPerTick",[]),D(this,"bytesTickIndex",0),D(this,"bytesTickRate",20),D(this,"currentTickBytesSent",0),D(this,"currentTickBytesReceived",0),D(this,"lastInputTick",-1n),D(this,"availableViewports",new Map),D(this,"displayCommandSink",{setPostProcess:(i,s)=>this.setPostProcess(i,s),setScanlinesEnabled:(i,s)=>this.setScanlinesEnabled(i,s),setScanlinesOpacity:(i,s)=>this.setScanlinesOpacity(i,s),setScanlinesPattern:(i,s)=>this.setScanlinesPattern(i,s),setAmbientEffect:(i,s)=>this.setAmbientEffect(i,s),setAmbientEffectEnabled:(i,s)=>this.setAmbientEffectEnabled(i,s),setAmbientEffectBlur:(i,s)=>this.setAmbientEffectBlur(i,s),setAmbientEffectScale:(i,s)=>this.setAmbientEffectScale(i,s),isAmbientEffectEnabled:()=>this.isAmbientEffectEnabled(),getAmbientEffectConfig:()=>this.getAmbientEffectConfig(),getPostProcessConfig:()=>this.getPostProcessConfig(),setScalingMode:(i,s)=>this.setScalingMode(i,s),getScalingMode:i=>this.getScalingMode(i),setCellSize:(i,s,o)=>this.setCellSize(i,s,o),getCellSize:i=>this.getCellSize(i),setGrid:(i,s)=>this.setGrid(i,s),setGridEnabled:(i,s)=>this.setGridEnabled(i,s),isGridEnabled:i=>this.isGridEnabled(i),getGridConfig:i=>this.getGridConfig(i),switchPalette:(i,s)=>this.switchPalette(i,s),getCurrentPaletteSlotId:i=>this.getCurrentPaletteSlotId(i)}),D(this,"data"),D(this,"currentScalingModes",new Map),D(this,"currentCellSizes",new Map),D(this,"currentGridConfigs",new Map),D(this,"currentPaletteSlotIds",new Map),this.mode=n,this.stats=new yI(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,n){this.availableViewports.set(e,{pixelWidth:t,pixelHeight:n})}getDisplayViewport(e){return this.availableViewports.get(e)??null}getAllDisplayViewports(){return this.availableViewports}calculateMaxCells(e,t,n){let i=this.availableViewports.get(e);return i?{cols:Math.floor(i.pixelWidth/t),rows:Math.floor(i.pixelHeight/n)}:null}getLayers(){return this.layers}getLayerById(e){return this.layers.find(t=>t.getId()===e)}addLayer(e,t){e.setMode(this.mode);let n=this.layers.length+1;Aa(e,n),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,n=!0){this.mouseX=Math.max(0,Math.min(255,e)),this.mouseY=Math.max(0,Math.min(255,t)),this.mouseOver=n}setTouchPosition(e,t,n,i=!0,s=0){if(e<0||e>9){console.warn(`Invalid touchId ${e}, must be 0-9`);return}i?(this.touchPositions.set(e,{x:Math.max(0,Math.min(255,t)),y:Math.max(0,Math.min(255,n)),over:!0,displayId:s}),this.activeTouchId=e):(this.touchPositions.delete(e),this.activeTouchId===e&&(this.activeTouchId=null))}setAxis(e,t){let n=Math.max(-1,Math.min(1,t));this.axes.set(e,n)}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,n=this.mouseX,i=this.mouseY,s=e.getOrigin(),o=s.x+n,a=s.y+i;return{displayId:t,localX:n,localY:i,worldX:o,worldY:a}}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 n=this.displays[0],i=t.displayId,s=t.x,o=t.y,a=n.getOrigin(),l=a.x+s,u=a.y+o;return{displayId:i,localX:s,localY:o,worldX:l,worldY:u}}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 n=this.displays[t.id];if(!n){for(n=new px(t.id,t.sizeX,t.sizeY);this.displays.length<=t.id;)this.displays.push(null);this.displays[t.id]=n}n.setCommandSink(this.displayCommandSink),n.setOrigin(new Yt(t.originX,t.originY)),n.setSize(new Yt(t.sizeX,t.sizeY)),n.setRenderPasses(t.renderPasses)}}updateLayersFromPacket(e){for(let t of e){let n=this.findLayerById(t.id);n||(n=new Zx(new Yt(t.originX,t.originY),t.zIndex,t.width,t.height,{mustBeReliable:!1,isMacroLayer:t.isMacroLayer,charCodeMode:t.is16bit?"16bit":"8bit"}),Aa(n,t.id),n.setMode(this.mode),this.spriteRegistry&&n.setSpriteRegistry(this.spriteRegistry),this.addLayer(n)),t.updateFlags&1&&n.setOrigin(new Yt(t.originX,t.originY)),t.updateFlags&2&&n.setZOrder(t.zIndex),t.updateFlags&4&&n.setOrders(t.orders)}}defineAxisBinding(e,t,n=[],i=-1,s=1,o=0){this.inputBindings.defineAxis(e,t,n,i,s,o)}defineButtonBinding(e,t,n=[],i=!1){this.inputBindings.defineButton(e,t,n,i)}defineAxisBindings(e){e.forEach(({bindingId:t,name:n,sources:i,min:s,max:o,defaultValue:a})=>{this.defineAxisBinding(t,n,i??[],s,o,a)})}defineButtonBindings(e){e.forEach(({bindingId:t,name:n,sources:i,defaultValue:s})=>{this.defineButtonBinding(t,n,i??[],s)})}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 n of t.axes)this.defineAxisBinding(n.bindingId,n.name,n.sources||[],n.min,n.max,n.defaultValue);for(let n of t.buttons)this.defineButtonBinding(n.bindingId,n.name,n.sources||[],n.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=lv(e,this.inputBindings);this.lastInputTick=t.tick;let n=this.inputBindings.getAllAxes(),i=this.inputBindings.getAllButtons(),s=n.sort((a,l)=>a.bindingId-l.bindingId),o=i.sort((a,l)=>a.bindingId-l.bindingId);for(let[a,l]of t.axes)if(a<s.length){let u=s[a];this.setAxis(u.name,l)}for(let[a,l]of t.buttons)if(a<o.length){let u=o[a],c=this.getButton(u.name);this.setButton(u.name,l);let d=l&&!c,h=!l&&c;this.setButton(`${u.name}_justPressed`,d),this.setButton(`${u.name}_justReleased`,h)}this.mouseX=t.mouseX,this.mouseY=t.mouseY,this.mouseOver=t.mouseOverDisplay,this.mouseDisplayId=t.displayId,this.isTabHidden=t.isTabHidden;for(let a of t.touchPositions)this.setTouchPosition(a.id,a.x,a.y,a.over);for(let a of t.displayViewports)this.setDisplayViewport(a.displayId,a.pixelWidth,a.pixelHeight)}playSound(e,t){let n=this.nextSoundInstanceId++,i={sound:e,instanceId:n,volume:t==null?void 0:t.volume,pitch:t==null?void 0:t.pitch,loop:t==null?void 0:t.loop,fadeIn:t==null?void 0:t.fadeIn,x:t==null?void 0:t.x,y:t==null?void 0:t.y,lowpass:t==null?void 0:t.lowpass,highpass:t==null?void 0:t.highpass,reverb:t==null?void 0:t.reverb};return this.soundCommands.push(i),n}stopSound(e){let t={sound:e};this.soundCommands.push(t)}fadeOutSound(e,t){let n={fadeOut:!0,sound:e,duration:t};this.soundCommands.push(n)}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 n={setEffects:!0,instanceId:e,lowpass:t.lowpass,highpass:t.highpass,reverb:t.reverb};this.soundCommands.push(n)}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,i=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:i,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 n={gamepadIndex:e,options:t};this.gamepadVibrationCommands.push(n)}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 n=t;if(n.gamepadIndex==="all")for(let i=0;i<4;i++)this.gamepadVibrationProcessor.vibrate(i,n.options);else this.gamepadVibrationProcessor.vibrate(n.gamepadIndex,n.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}=(A1(),ul(U1)),{MobileVibrateFlags:n,GamepadVibrateFlags:i}=(R1(),ul(T1));for(let s of e)switch(s.type){case t.MobileVibrate:{if(!this.mobileVibrationProcessor)break;let o=s,a=o.pattern;o.flags&n.HasIntensity&&o.intensity!==void 0&&(a=a.map(l=>Math.round(l*o.intensity))),this.mobileVibrationProcessor.vibrate(a);break}case t.MobileCancel:{if(!this.mobileVibrationProcessor)break;this.mobileVibrationProcessor.cancel();break}case t.GamepadVibrate:{if(!this.gamepadVibrationProcessor)break;let o=s,a={duration:o.duration,strongMagnitude:o.strongMagnitude/255,weakMagnitude:o.weakMagnitude/255,startDelay:o.startDelay};if(o.flags&i.AllGamepads)for(let l=0;l<4;l++)this.gamepadVibrationProcessor.vibrate(l,a);else this.gamepadVibrationProcessor.vibrate(o.gamepadIndex,a);break}case t.GamepadCancel:{if(!this.gamepadVibrationProcessor)break;let o=s;o.flags&i.AllGamepads?this.gamepadVibrationProcessor.stopAllVibrations():this.gamepadVibrationProcessor.stopVibration(o.gamepadIndex);break}}}applyAudioOrders(e){if(!this.audioProcessor||this.mode==="server")return;let{AudioOrderType:t,AudioTargetType:n}=(D1(),ul(P1)),{PlaySoundFlags:i}=(F1(),ul(O1));for(let s of e)switch(s.type){case t.PlaySound:case t.PlayGlobalSound:{let o=s,a=o.volume!==void 0?o.volume/255:void 0,l=o.pitch!==void 0?.25*Math.pow(2,o.pitch/64):void 0,u=o.fadeIn!==void 0?o.fadeIn/10:void 0,c=(o.flags&i.Loop)!==0,d=o.posX!==void 0&&o.posY!==void 0?{x:o.posX,y:o.posY}:void 0;this.audioProcessor.play(o.soundId,{volume:a,pitch:l,loop:c,fadeIn:u,position:d,instanceId:o.instanceId,lowpass:o.lowpass,highpass:o.highpass,reverb:o.reverb});break}case t.StopSound:{let o=s;o.targetType===n.All?this.audioProcessor.stopAll():o.targetType===n.InstanceId?this.audioProcessor.stop(o.target):this.audioProcessor.stop(o.target);break}case t.FadeOutSound:{let o=s,a=o.duration/10;o.targetType===n.All?this.audioProcessor.fadeOut("all",a):this.audioProcessor.fadeOut(o.target,a);break}case t.PauseSound:{let o=s;o.targetType===n.All?this.audioProcessor.pause("all"):this.audioProcessor.pause(o.target);break}case t.ResumeSound:{let o=s;o.targetType===n.All?this.audioProcessor.resume("all"):this.audioProcessor.resume(o.target);break}case t.SetListenerPosition:{let o=s;this.audioProcessor.setListenerPosition(o.x,o.y);break}case t.ConfigureSpatial:{let o=s;this.audioProcessor.configureSpatial({maxDistance:o.maxDistance*100,referenceDistance:o.referenceDistance*100,rolloffFactor:o.rolloffFactor/100,panSpread:o.panSpread/255});break}case t.SetSoundEffects:{let o=s;this.audioProcessor.setEffects(o.instanceId,o.lowpass,o.highpass,o.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){var t;return(t=this.soundLoadErrors.get(e))==null?void 0:t.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,n=this.soundLoadErrors.size,i=e>0&&t>=e,s=Array.from(this.soundLoadErrors.values()).map(o=>o.name);return{loadedCount:t,totalExpected:e,errorCount:n,isComplete:i,errors:s}}loadMacro(e,t){let n={...t,id:e},i=this.macroRegistry.registerMacro(n);return this.mode==="client"&&this.macroEngine.loadTemplate(i,n),i}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,n){this.macroEventHandlers.has(e)||this.macroEventHandlers.set(e,new Map),this.macroEventHandlers.get(e).set(t,n)}offMacroEvent(e,t){var n;t?(n=this.macroEventHandlers.get(e))==null||n.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 n=this.macroEventHandlers.get(t);if(!n)return;let i,s;switch(e.type){case 1:i="click",s=void 0;break;case 2:i="change",s=e.value;break;case 3:i="submit",s=e.text;break;case 4:i="select",s=e.index;break;default:return}let o=n.get(i);o&&o(s)}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 n=this.macroRegistry.getInstanceName(t.instanceId);if(!n)continue;let i=this.macroEventHandlers.get(n);if(!i)continue;let s=i.get(t.event);s&&s(t.data)}}updateMacroMouse(e,t,n){let i=this.displays.find(s=>s.getId()===this.mouseDisplayId);if(!i&&this.displays.length>0&&(i=this.displays[0]),i){let s=i.getOrigin(),o=e+s.x,a=t+s.y;this.macroEngine.updateMouse(o,a,n)}else this.macroEngine.updateMouse(e,t,n)}getMacroRenderOrders(){let e=this.macroEngine.getOrdersByLayer(),t=this.displays[0];if(!t)return e;let n=t.getOrigin();if(n.x===0&&n.y===0)return e;let i=new Map;for(let[s,o]of e){let a=o.map(l=>{let u={...l};return"posX"in u&&typeof u.posX=="number"&&(u.posX=u.posX-n.x),"posY"in u&&typeof u.posY=="number"&&(u.posY=u.posY-n.y),u});i.set(s,a)}return i}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 n=JSON.stringify(t),i=JSON.stringify(this.currentPostProcessConfig);n!==i&&(this.currentPostProcessConfig=t,this.postProcessCommands.push({type:"set-config",displayId:e,config:t??void 0}))}setScanlinesEnabled(e,t){var n;if(t){let i=(n=this.currentPostProcessConfig)==null?void 0:n.scanlines;this.setPostProcess(e,{scanlines:{enabled:!0,opacity:(i==null?void 0:i.opacity)??Ge.scanlines.opacity,pattern:(i==null?void 0:i.pattern)??Ge.scanlines.pattern,color:(i==null?void 0:i.color)??Ge.scanlines.color}})}else this.setPostProcess(e,{scanlines:{enabled:!1}})}setScanlinesOpacity(e,t){var s;let n=Math.max(0,Math.min(1,t)),i=(s=this.currentPostProcessConfig)==null?void 0:s.scanlines;this.setPostProcess(e,{scanlines:{enabled:!0,opacity:n,pattern:(i==null?void 0:i.pattern)??"horizontal",color:(i==null?void 0:i.color)??{r:0,g:0,b:0}}})}setScanlinesPattern(e,t){var i;let n=(i=this.currentPostProcessConfig)==null?void 0:i.scanlines;this.setPostProcess(e,{scanlines:{enabled:(n==null?void 0:n.enabled)??!0,opacity:(n==null?void 0:n.opacity)??Ge.scanlines.opacity,pattern:t,color:(n==null?void 0:n.color)??{r:0,g:0,b:0}}})}setAmbientEffect(e,t){var i;let n=(i=this.currentPostProcessConfig)==null?void 0:i.ambientEffect;typeof t=="boolean"?this.setPostProcess(e,{...this.currentPostProcessConfig,ambientEffect:{enabled:t,blur:(n==null?void 0:n.blur)??Ge.ambientEffect.blur,scale:(n==null?void 0:n.scale)??Ge.ambientEffect.scale}}):this.setPostProcess(e,{...this.currentPostProcessConfig,ambientEffect:{enabled:!0,blur:t.blur??(n==null?void 0:n.blur)??Ge.ambientEffect.blur,scale:t.scale??(n==null?void 0:n.scale)??Ge.ambientEffect.scale}})}setAmbientEffectEnabled(e,t){this.setAmbientEffect(e,t)}setAmbientEffectBlur(e,t){var i;let n=(i=this.currentPostProcessConfig)==null?void 0:i.ambientEffect;this.setPostProcess(e,{...this.currentPostProcessConfig,ambientEffect:{enabled:(n==null?void 0:n.enabled)??!0,blur:Math.max(0,t),scale:(n==null?void 0:n.scale)??Ge.ambientEffect.scale}})}setAmbientEffectScale(e,t){var i;let n=(i=this.currentPostProcessConfig)==null?void 0:i.ambientEffect;this.setPostProcess(e,{...this.currentPostProcessConfig,ambientEffect:{enabled:(n==null?void 0:n.enabled)??!0,blur:(n==null?void 0:n.blur)??Ge.ambientEffect.blur,scale:Math.max(1,t)}})}isAmbientEffectEnabled(){var e,t;return((t=(e=this.currentPostProcessConfig)==null?void 0:e.ambientEffect)==null?void 0:t.enabled)??!1}getAmbientEffectConfig(){var t;let e=(t=this.currentPostProcessConfig)==null?void 0:t.ambientEffect;return e?{enabled:e.enabled,blur:e.blur??Ge.ambientEffect.blur,scale:e.scale??Ge.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,n){let i=Math.max(1,Math.min(255,Math.round(t))),s=Math.max(1,Math.min(255,Math.round(n))),o=this.currentCellSizes.get(e);o&&o.width===i&&o.height===s||(this.currentCellSizes.set(e,{width:i,height:s}),this.postProcessCommands.push({type:"set-cell-size",displayId:e,cellWidth:i,cellHeight:s}))}getCellSize(e){let t=this.currentCellSizes.get(e);return{cellWidth:(t==null?void 0:t.width)??8,cellHeight:(t==null?void 0:t.height)??8}}setGrid(e,t){let n;typeof t=="boolean"?n={enabled:t,color:js.color,lineWidth:js.lineWidth}:n={enabled:t.enabled,color:t.color??js.color,lineWidth:t.lineWidth??js.lineWidth},this.currentGridConfigs.set(e,n),this.postProcessCommands.push({type:"set-grid",displayId:e,gridConfig:n})}setGridEnabled(e,t){this.setGrid(e,t)}isGridEnabled(e){var t;return((t=this.currentGridConfigs.get(e))==null?void 0:t.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,n])=>({displayId:t,pixelWidth:n.pixelWidth,pixelHeight:n.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())}}};J(cv,"User");var vI=cv,dv=class{constructor(){D(this,"charCodeSize",_1)}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,n,i){return i?(e.writeUInt16LE(t,n),n+2):(e.writeUInt8(t,n),n+1)}encodeCharOrder(e,t){let n=ie.allocUnsafe(gx+(t?1:0)),i=0;return n.writeUInt8(e.type,i++),n.writeUInt8(e.posX,i++),n.writeUInt8(e.posY,i++),i=this.writeCharCode(n,e.charCode,i,t),n.writeUInt8(e.bgColorCode,i++),n.writeUInt8(e.fgColorCode,i++),n.toUint8Array()}encodeTextOrder(e){let t=new TextEncoder().encode(e.text),n=ie.allocUnsafe(mx+t.length),i=0;n.writeUInt8(e.type,i++),n.writeUInt8(e.posX,i++),n.writeUInt8(e.posY,i++),n.writeUInt8(t.length,i++);for(let s=0;s<t.length;s++)n.writeUInt8(t[s],i++);return n.writeUInt8(e.bgColorCode,i++),n.writeUInt8(e.fgColorCode,i++),n.toUint8Array()}encodeTextMultilineOrder(e){let t=new TextEncoder().encode(e.text),n=ie.allocUnsafe(yx+t.length),i=0;n.writeUInt8(e.type,i++),n.writeUInt8(e.posX,i++),n.writeUInt8(e.posY,i++),n.writeUInt8(t.length,i++);for(let s=0;s<t.length;s++)n.writeUInt8(t[s],i++);return n.writeUInt8(e.bgColorCode,i++),n.writeUInt8(e.fgColorCode,i++),n.toUint8Array()}encodeSubFrameOrder(e,t){let n=e.sizeX*e.sizeY,i=this.charCodeSize(t),s=ie.allocUnsafe(vx+n*i),o=0;s.writeUInt8(e.type,o++),s.writeUInt8(e.posX,o++),s.writeUInt8(e.posY,o++),s.writeUInt8(e.sizeX-1,o++),s.writeUInt8(e.sizeY-1,o++),s.writeUInt8(e.bgColorCode,o++),s.writeUInt8(e.fgColorCode,o++);for(let a of e.frame)o=this.writeCharCode(s,a,o,t);return s.toUint8Array()}encodeSubFrameMultiColorOrder(e,t){let n=e.sizeX*e.sizeY,i=this.charCodeSize(t),s=ie.allocUnsafe(wx+n*(i+2)),o=0;s.writeUInt8(e.type,o++),s.writeUInt8(e.posX,o++),s.writeUInt8(e.posY,o++),s.writeUInt8(e.sizeX-1,o++),s.writeUInt8(e.sizeY-1,o++);for(let a of e.frame)o=this.writeCharCode(s,a.charCode,o,t),s.writeUInt8(a.bgColorCode,o++),s.writeUInt8(a.fgColorCode,o++);return s.toUint8Array()}encodeFullFrameOrder(e,t){let n=e.frame.length,i=this.charCodeSize(t),s=ie.allocUnsafe(Cx+n*i),o=0;s.writeUInt8(e.type,o++),s.writeUInt8(e.bgColorCode,o++),s.writeUInt8(e.fgColorCode,o++);for(let a of e.frame)o=this.writeCharCode(s,a,o,t);return s.toUint8Array()}encodeFullFrameMultiColorOrder(e,t){let n=e.frame.length,i=this.charCodeSize(t),s=ie.allocUnsafe(bx+n*(i+2)),o=0;s.writeUInt8(e.type,o++);for(let a of e.frame)o=this.writeCharCode(s,a.charCode,o,t),s.writeUInt8(a.bgColorCode,o++),s.writeUInt8(a.fgColorCode,o++);return s.toUint8Array()}encodeSpriteOrder(e){let t=ie.allocUnsafe(Sx),n=0;return t.writeUInt8(e.type,n++),t.writeUInt8(e.posX,n++),t.writeUInt8(e.posY,n++),t.writeUInt8(e.spriteIndex,n++),t.writeUInt8(e.bgColorCode,n++),t.writeUInt8(e.fgColorCode,n++),t.toUint8Array()}encodeSpriteMultiColorOrder(e){let t=ie.allocUnsafe(xx),n=0;return t.writeUInt8(e.type,n++),t.writeUInt8(e.posX,n++),t.writeUInt8(e.posY,n++),t.writeUInt8(e.spriteIndex,n++),t.toUint8Array()}encodeColorMapOrder(e){let t=e.sizeX*e.sizeY,n=ie.allocUnsafe(Ix+t*2),i=0;n.writeUInt8(e.type,i++),n.writeUInt8(e.posX,i++),n.writeUInt8(e.posY,i++),n.writeUInt8(e.sizeX-1,i++),n.writeUInt8(e.sizeY-1,i++);for(let s of e.colorData)n.writeUInt8(s.bgColorCode,i++),n.writeUInt8(s.fgColorCode,i++);return n.toUint8Array()}encodeShapeOrder(e,t){let n=this.encodeShapeData(e.shapeType,e.shapeData,t),i=ie.allocUnsafe(kx+n.length),s=0;i.writeUInt8(e.type,s++),i.writeUInt8(e.shapeType,s++);for(let o=0;o<n.length;o++)i.writeUInt8(n[o],s++);return i.toUint8Array()}encodeShapeData(e,t,n){switch(this.charCodeSize(n),e){case 1:{let i=ie.allocUnsafe(Ex+(n?1:0)),s=0;return i.writeUInt8(t.posX,s++),i.writeUInt8(t.posY,s++),i.writeUInt8(t.width-1,s++),i.writeUInt8(t.height-1,s++),i.writeUInt8(t.filled?1:0,s++),s=this.writeCharCode(i,t.charCode,s,n),i.writeUInt8(t.bgColorCode,s++),i.writeUInt8(t.fgColorCode,s++),i.toUint8Array()}case 2:{let i=ie.allocUnsafe(Mx+(n?1:0)),s=0;return i.writeUInt8(t.centerX,s++),i.writeUInt8(t.centerY,s++),i.writeUInt8(t.radius-1,s++),i.writeUInt8(t.filled?1:0,s++),s=this.writeCharCode(i,t.charCode,s,n),i.writeUInt8(t.bgColorCode,s++),i.writeUInt8(t.fgColorCode,s++),i.toUint8Array()}case 3:{let i=ie.allocUnsafe(Ux+(n?1:0)),s=0;return i.writeUInt8(t.x1,s++),i.writeUInt8(t.y1,s++),i.writeUInt8(t.x2,s++),i.writeUInt8(t.y2,s++),s=this.writeCharCode(i,t.charCode,s,n),i.writeUInt8(t.bgColorCode,s++),i.writeUInt8(t.fgColorCode,s++),i.toUint8Array()}case 4:{let i=ie.allocUnsafe(Ax+(n?1:0)),s=0;return i.writeUInt8(t.centerX,s++),i.writeUInt8(t.centerY,s++),i.writeUInt8(t.radiusX-1,s++),i.writeUInt8(t.radiusY-1,s++),i.writeUInt8(t.filled?1:0,s++),s=this.writeCharCode(i,t.charCode,s,n),i.writeUInt8(t.bgColorCode,s++),i.writeUInt8(t.fgColorCode,s++),i.toUint8Array()}case 5:{let i=ie.allocUnsafe(Tx+(n?1:0)),s=0;return i.writeUInt8(t.x1,s++),i.writeUInt8(t.y1,s++),i.writeUInt8(t.x2,s++),i.writeUInt8(t.y2,s++),i.writeUInt8(t.x3,s++),i.writeUInt8(t.y3,s++),i.writeUInt8(t.filled?1:0,s++),s=this.writeCharCode(i,t.charCode,s,n),i.writeUInt8(t.bgColorCode,s++),i.writeUInt8(t.fgColorCode,s++),i.toUint8Array()}default:throw new Error(`Unknown shape type: ${e}`)}}encodeDotCloudOrder(e,t){let n=e.positions.length;this.charCodeSize(t);let i=ie.allocUnsafe(Rx+(t?1:0)+n*2),s=0;i.writeUInt8(e.type,s++),s=this.writeCharCode(i,e.charCode,s,t),i.writeUInt8(e.bgColorCode,s++),i.writeUInt8(e.fgColorCode,s++),i.writeUInt16BE(n,s),s+=2;for(let o of e.positions)i.writeUInt8(o.posX,s++),i.writeUInt8(o.posY,s++);return i.toUint8Array()}encodeDotCloudMultiColorOrder(e,t){let n=e.dots.length,i=this.charCodeSize(t),s=ie.allocUnsafe(Px+n*(i+4)),o=0;s.writeUInt8(e.type,o++),s.writeUInt16BE(n,o),o+=2;for(let a of e.dots)o=this.writeCharCode(s,a.charCode,o,t),s.writeUInt8(a.bgColorCode,o++),s.writeUInt8(a.fgColorCode,o++),s.writeUInt8(a.posX,o++),s.writeUInt8(a.posY,o++);return s.toUint8Array()}encodeBitmaskOrder(e,t){let n=e.mask.length,i=ie.allocUnsafe(Bx+(t?1:0)+n),s=0;i.writeUInt8(e.type,s++),i.writeUInt8(e.posX,s++),i.writeUInt8(e.posY,s++),i.writeUInt8(e.sizeX-1,s++),i.writeUInt8(e.sizeY-1,s++),s=this.writeCharCode(i,e.charCode,s,t),i.writeUInt8(e.bgColorCode,s++),i.writeUInt8(e.fgColorCode,s++),i.writeUInt8(e.override?1:0,s++);for(let o=0;o<n;o++)i.writeUInt8(e.mask[o],s++);return i.toUint8Array()}encodeBitmask4Order(e,t){let n=e.mask.length;this.charCodeSize(t);let i=ie.allocUnsafe(zx+3*(t?1:0)+n),s=0;i.writeUInt8(e.type,s++),i.writeUInt8(e.posX,s++),i.writeUInt8(e.posY,s++),i.writeUInt8(e.sizeX-1,s++),i.writeUInt8(e.sizeY-1,s++),i.writeUInt8(e.override?1:0,s++);for(let o of e.variants)s=this.writeCharCode(i,o.charCode,s,t),i.writeUInt8(o.bgColorCode,s++),i.writeUInt8(o.fgColorCode,s++);for(let o=0;o<n;o++)i.writeUInt8(e.mask[o],s++);return i.toUint8Array()}encodeBitmask16Order(e,t){let n=e.mask.length;this.charCodeSize(t);let i=ie.allocUnsafe(Dx+15*(t?1:0)+n),s=0;i.writeUInt8(e.type,s++),i.writeUInt8(e.posX,s++),i.writeUInt8(e.posY,s++),i.writeUInt8(e.sizeX-1,s++),i.writeUInt8(e.sizeY-1,s++),i.writeUInt8(e.override?1:0,s++);for(let o of e.variants)s=this.writeCharCode(i,o.charCode,s,t),i.writeUInt8(o.bgColorCode,s++),i.writeUInt8(o.fgColorCode,s++);for(let o=0;o<n;o++)i.writeUInt8(e.mask[o],s++);return i.toUint8Array()}encodePolylineOrder(e,t){let n=e.points.length,i=ie.allocUnsafe(Ox+(t?1:0)+n*2),s=0;i.writeUInt8(e.type,s++),s=this.writeCharCode(i,e.charCode,s,t),i.writeUInt8(e.fgColorCode,s++),i.writeUInt8(e.bgColorCode,s++),i.writeUInt8(n,s++);for(let o of e.points)i.writeUInt8(o.x,s++),i.writeUInt8(o.y,s++);return i.toUint8Array()}encodeSpriteCloudOrder(e){let t=e.positions.length,n=ie.allocUnsafe(Fx+t*2),i=0;n.writeUInt8(e.type,i++),n.writeUInt8(e.spriteIndex,i++),n.writeUInt8(e.bgColorCode,i++),n.writeUInt8(e.fgColorCode,i++),n.writeUInt16BE(t,i),i+=2;for(let s of e.positions)n.writeUInt8(s.posX,i++),n.writeUInt8(s.posY,i++);return n.toUint8Array()}encodeSpriteCloudMultiColorOrder(e){let t=e.positions.length,n=ie.allocUnsafe(Lx+t*2),i=0;n.writeUInt8(e.type,i++),n.writeUInt8(e.spriteIndex,i++),n.writeUInt16BE(t,i),i+=2;for(let s of e.positions)n.writeUInt8(s.posX,i++),n.writeUInt8(s.posY,i++);return n.toUint8Array()}encodeSpriteCloudVariedOrder(e){let t=e.sprites.length,n=ie.allocUnsafe(_x+t*5),i=0;n.writeUInt8(e.type,i++),n.writeUInt16BE(t,i),i+=2;for(let s of e.sprites)n.writeUInt8(s.spriteIndex,i++),n.writeUInt8(s.bgColorCode,i++),n.writeUInt8(s.fgColorCode,i++),n.writeUInt8(s.posX,i++),n.writeUInt8(s.posY,i++);return n.toUint8Array()}encodeSpriteCloudVariedMultiColorOrder(e){let t=e.sprites.length,n=ie.allocUnsafe($x+t*3),i=0;n.writeUInt8(e.type,i++),n.writeUInt16BE(t,i),i+=2;for(let s of e.sprites)n.writeUInt8(s.spriteIndex,i++),n.writeUInt8(s.posX,i++),n.writeUInt8(s.posY,i++);return n.toUint8Array()}encodeFillOrder(e,t){let n=ie.allocUnsafe(Nx+(t?1:0)),i=0;return n.writeUInt8(e.type,i++),i=this.writeCharCode(n,e.charCode,i,t),n.writeUInt8(e.bgColorCode,i++),n.writeUInt8(e.fgColorCode,i++),n.toUint8Array()}encodeFillCharOrder(e,t){let n=e.patternWidth*e.patternHeight,i=this.charCodeSize(t),s=ie.allocUnsafe(Vx+n*i),o=0;s.writeUInt8(e.type,o++),s.writeUInt8(e.patternWidth-1,o++),s.writeUInt8(e.patternHeight-1,o++),s.writeUInt8(e.bgColorCode,o++),s.writeUInt8(e.fgColorCode,o++);for(let a of e.pattern)o=this.writeCharCode(s,a,o,t);return s.toUint8Array()}encodeFillSpriteOrder(e){let t=ie.allocUnsafe(Hx),n=0;return t.writeUInt8(e.type,n++),t.writeUInt8(e.spriteIndex,n++),t.writeUInt8(e.bgColorCode,n++),t.writeUInt8(e.fgColorCode,n++),t.toUint8Array()}encodeFillSpriteMultiColorOrder(e){let t=ie.allocUnsafe(jx),n=0;return t.writeUInt8(e.type,n++),t.writeUInt8(e.spriteIndex,n++),t.toUint8Array()}};J(dv,"OrderEncoder");var wI=dv,jg=255,Yg=32,Wg=64,hv=class{constructor(){D(this,"orderEncoder"),this.orderEncoder=new wI}encode(e){let t=e.is16bit;if(e.orders.length>jg)throw new Error(`[UTSP] LayerEncoder: Layer ${e.id} has ${e.orders.length} orders, max is ${jg}. This would cause packet corruption! Split into multiple layers.`);let n=e.orders.map(c=>this.orderEncoder.encode(c,t)),i=13,s=n.reduce((c,d)=>c+d.length,0),o=i+s,a=ie.allocUnsafe(o),l=0;a.writeUInt16BE(e.id,l),l+=2;let u=e.updateFlags;e.isMacroLayer?u|=Yg:u&=~Yg,t?u|=Wg:u&=~Wg,a.writeUInt8(u,l++),a.writeUInt8(e.zIndex,l++),a.writeUInt16BE(e.originX,l),l+=2,a.writeUInt16BE(e.originY,l),l+=2,a.writeUInt16BE(e.width,l),l+=2,a.writeUInt16BE(e.height,l),l+=2,a.writeUInt8(e.orders.length,l++);for(let c of n)ie.from(c).copy(a,l),l+=c.length;return a.toUint8Array()}calculateSize(e){let t=e.is16bit;return 13+e.orders.reduce((n,i)=>n+this.orderEncoder.encode(i,t).length,0)}};J(hv,"LayerEncoder");var CI=hv,fv=class{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 zg;case 8:return Dg;case 9:return this.calculateSetSoundEffectsSize(e);default:throw new Error(`Unknown audio order type: ${e.type}`)}}encodePlaySoundOrder(e){let t=this.calculatePlaySoundSize(e),n=ie.allocUnsafe(t),i=0;return n.writeUInt8(e.type,i++),n.writeUInt8(e.soundId,i++),n.writeUInt16BE(e.instanceId,i),i+=2,n.writeUInt8(e.flags,i++),e.flags&2&&n.writeUInt8(e.volume??255,i++),e.flags&4&&n.writeUInt8(e.pitch??128,i++),e.flags&8&&n.writeUInt8(e.fadeIn??0,i++),e.flags&16&&(n.writeUInt16BE(e.posX??0,i),i+=2,n.writeUInt16BE(e.posY??0,i),i+=2),e.flags&32&&n.writeUInt8(e.lowpass??0,i++),e.flags&64&&n.writeUInt8(e.highpass??0,i++),e.flags&128&&n.writeUInt8(e.reverb??0,i++),n.toUint8Array()}encodePlayGlobalSoundOrder(e){let t=this.calculatePlayGlobalSoundSize(e),n=ie.allocUnsafe(t),i=0;n.writeUInt8(e.type,i++),n.writeUInt8(e.soundId,i++),n.writeUInt16BE(e.instanceId,i),i+=2;let s=e.flags&-17;return n.writeUInt8(s,i++),s&2&&n.writeUInt8(e.volume??255,i++),s&4&&n.writeUInt8(e.pitch??128,i++),s&8&&n.writeUInt8(e.fadeIn??0,i++),s&32&&n.writeUInt8(e.lowpass??0,i++),s&64&&n.writeUInt8(e.highpass??0,i++),s&128&&n.writeUInt8(e.reverb??0,i++),n.toUint8Array()}calculatePlaySoundSize(e){let t=Yx;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=Wx,n=e.flags&-17;return n&2&&(t+=1),n&4&&(t+=1),n&8&&(t+=1),n&32&&(t+=1),n&64&&(t+=1),n&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),n=ie.allocUnsafe(t),i=0;return n.writeUInt8(e.type,i++),n.writeUInt8(e.targetType,i++),n.writeUInt8(e.duration,i++),e.targetType===0?n.writeUInt16BE(e.target??0,i):e.targetType===1&&n.writeUInt8(e.target??0,i),n.toUint8Array()}encodeTargetOrder(e,t,n){let i=2;t===0?i+=2:t===1&&(i+=1);let s=ie.allocUnsafe(i),o=0;return s.writeUInt8(e,o++),s.writeUInt8(t,o++),t===0?s.writeUInt16BE(n??0,o):t===1&&s.writeUInt8(n??0,o),s.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=ie.allocUnsafe(zg),n=0;return t.writeUInt8(e.type,n++),t.writeUInt16BE(e.x,n),n+=2,t.writeUInt16BE(e.y,n),t.toUint8Array()}encodeConfigureSpatialOrder(e){let t=ie.allocUnsafe(Dg),n=0;return t.writeUInt8(e.type,n++),t.writeUInt8(e.maxDistance,n++),t.writeUInt8(e.referenceDistance,n++),t.writeUInt8(e.rolloffFactor,n++),t.writeUInt8(e.panSpread,n++),t.toUint8Array()}encodeSetSoundEffectsOrder(e){let t=this.calculateSetSoundEffectsSize(e),n=ie.allocUnsafe(t),i=0;return n.writeUInt8(e.type,i++),n.writeUInt16BE(e.instanceId,i),i+=2,n.writeUInt8(e.flags,i++),e.flags&1&&n.writeUInt8(e.lowpass??0,i++),e.flags&2&&n.writeUInt8(e.highpass??0,i++),e.flags&4&&n.writeUInt8(e.reverb??0,i++),n.toUint8Array()}calculateSetSoundEffectsSize(e){let t=4;return e.flags&1&&(t+=1),e.flags&2&&(t+=1),e.flags&4&&(t+=1),t}};J(fv,"AudioOrderEncoder");var bI=fv,pv=class{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),n=ie.allocUnsafe(t),i=0,s=0;e.intensity!==void 0&&(s|=1),n.writeUInt8(e.type,i++),n.writeUInt8(s,i++),n.writeUInt8(e.pattern.length,i++);for(let o of e.pattern){let a=Math.min(65535,Math.max(0,Math.round(o)));n.writeUInt16BE(a,i),i+=2}if(e.intensity!==void 0){let o=Math.round(Math.min(1,Math.max(0,e.intensity))*255);n.writeUInt8(o,i++)}return n.toUint8Array()}encodeMobileCancelOrder(e){let t=ie.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),n=ie.allocUnsafe(t),i=0,s=0;e.startDelay!==void 0&&e.startDelay>0&&(s|=1),e.gamepadIndex===255&&(s|=2),n.writeUInt8(e.type,i++),n.writeUInt8(s,i++),n.writeUInt8(e.gamepadIndex,i++);let o=Math.min(65535,Math.max(0,Math.round(e.duration)));if(n.writeUInt16BE(o,i),i+=2,n.writeUInt8(e.strongMagnitude,i++),n.writeUInt8(e.weakMagnitude,i++),e.startDelay!==void 0&&e.startDelay>0){let a=Math.min(65535,Math.max(0,Math.round(e.startDelay)));n.writeUInt16BE(a,i),i+=2}return n.toUint8Array()}encodeGamepadCancelOrder(e){let t=ie.allocUnsafe(3),n=0,i=0;return e.gamepadIndex===255&&(i|=2),t.writeUInt8(e.type,n++),t.writeUInt8(i,n++),t.writeUInt8(e.gamepadIndex,n++),t.toUint8Array()}};J(pv,"VibrationOrderEncoder");var SI=pv,gv=class{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),n=new TextEncoder().encode(t);if(n.length>65535)throw new Error(`Params JSON too large: ${n.length} bytes (max 65535)`);let i=11+n.length,s=ie.allocUnsafe(i),o=0;return s.writeUInt8(e.type,o++),s.writeUInt8(e.instanceId,o++),s.writeUInt8(e.macroId,o++),s.writeUInt8(e.layerId,o++),s.writeInt16BE(e.x,o),o+=2,s.writeInt16BE(e.y,o),o+=2,s.writeUInt8(e.tabIndex,o++),s.writeUInt16BE(n.length,o),o+=2,s.toUint8Array().set(n,o),s.toUint8Array()}calculateCreateInstanceSize(e){let t=JSON.stringify(e.params);return 11+new TextEncoder().encode(t).length}encodeUpdateInstance(e){let t=JSON.stringify(e.params),n=new TextEncoder().encode(t);if(n.length>65535)throw new Error(`Params JSON too large: ${n.length} bytes (max 65535)`);let i=4+n.length,s=ie.allocUnsafe(i),o=0;return s.writeUInt8(e.type,o++),s.writeUInt8(e.instanceId,o++),s.writeUInt16BE(n.length,o),o+=2,s.toUint8Array().set(n,o),s.toUint8Array()}calculateUpdateInstanceSize(e){let t=JSON.stringify(e.params);return 4+new TextEncoder().encode(t).length}encodeRemoveInstance(e){let t=ie.allocUnsafe(2);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.toUint8Array()}};J(gv,"MacroOrderEncoder");var xI=gv,Xr=(r=>(r[r.SetConfig=1]="SetConfig",r[r.SetScanlines=2]="SetScanlines",r[r.SetAmbientEffect=3]="SetAmbientEffect",r[r.SetScalingMode=4]="SetScalingMode",r[r.SetGrid=5]="SetGrid",r[r.SwitchPalette=6]="SwitchPalette",r[r.SetCellSize=7]="SetCellSize",r))(Xr||{}),mv=class{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 Og;case 3:return Fg;case 4:return Lg;case 5:return _g;case 6:return $g;case 7:return Ng;default:throw new Error(`Unknown post-process order type: ${e.type}`)}}encodeSetConfigOrder(e){let t=this.calculateSetConfigSize(e),n=ie.allocUnsafe(t),i=0;return n.writeUInt8(e.type,i++),n.writeUInt8(e.displayId,i++),n.writeUInt8(e.flags,i++),e.flags&1&&e.scanlines&&(n.writeUInt8(e.scanlines.enabled?1:0,i++),n.writeUInt8(Math.round(e.scanlines.opacity*255),i++),n.writeUInt8(e.scanlines.pattern,i++),n.writeUInt8(e.scanlines.colorR,i++),n.writeUInt8(e.scanlines.colorG,i++),n.writeUInt8(e.scanlines.colorB,i++)),e.flags&2&&e.ambientEffect&&(n.writeUInt8(e.ambientEffect.enabled?1:0,i++),n.writeUInt8(Math.min(255,Math.round(e.ambientEffect.blur)),i++),n.writeUInt8(Math.min(255,Math.max(100,Math.round(e.ambientEffect.scale*100))),i++),n.writeUInt8(Math.round(e.ambientEffect.opacity*255),i++)),n.toUint8Array()}calculateSetConfigSize(e){let t=Gx;return e.flags&1&&(t+=6),e.flags&2&&(t+=4),t}encodeSetScanlinesOrder(e){let t=ie.allocUnsafe(Og),n=0;return t.writeUInt8(e.type,n++),t.writeUInt8(e.displayId,n++),t.writeUInt8(e.enabled?1:0,n++),t.writeUInt8(Math.round(e.opacity*255),n++),t.writeUInt8(e.pattern,n++),t.writeUInt8(e.colorR,n++),t.writeUInt8(e.colorG,n++),t.writeUInt8(e.colorB,n++),t.toUint8Array()}encodeSetAmbientEffectOrder(e){let t=ie.allocUnsafe(Fg),n=0;return t.writeUInt8(e.type,n++),t.writeUInt8(e.displayId,n++),t.writeUInt8(e.enabled?1:0,n++),t.writeUInt8(Math.min(255,Math.round(e.blur)),n++),t.writeUInt8(Math.min(255,Math.max(100,Math.round(e.scale*100))),n++),t.writeUInt8(Math.round(e.opacity*255),n++),t.toUint8Array()}encodeSetScalingModeOrder(e){let t=ie.allocUnsafe(Lg),n=0;return t.writeUInt8(e.type,n++),t.writeUInt8(e.displayId,n++),t.writeUInt8(e.mode,n++),t.toUint8Array()}encodeSetGridOrder(e){let t=ie.allocUnsafe(_g),n=0;return t.writeUInt8(e.type,n++),t.writeUInt8(e.displayId,n++),t.writeUInt8(e.enabled?1:0,n++),t.writeUInt8(e.colorR,n++),t.writeUInt8(e.colorG,n++),t.writeUInt8(e.colorB,n++),t.writeUInt8(e.colorA,n++),t.writeUInt8(Math.min(10,Math.max(1,e.lineWidth)),n++),t.toUint8Array()}encodeSwitchPaletteOrder(e){let t=ie.allocUnsafe($g),n=0;return t.writeUInt8(e.type,n++),t.writeUInt8(e.displayId,n++),t.writeUInt8(e.slotId,n++),t.toUint8Array()}encodeSetCellSizeOrder(e){let t=ie.allocUnsafe(Ng),n=0;return t.writeUInt8(e.type,n++),t.writeUInt8(e.displayId,n++),t.writeUInt8(e.cellWidth,n++),t.writeUInt8(e.cellHeight,n++),t.toUint8Array()}};J(mv,"PostProcessOrderEncoder");var II=mv,Gg=4,Fc=4,Xg=8,yv=class{encode(e){var o;let t=((o=e.renderPasses)==null?void 0:o.length)??0;if(t>Fc)throw new Error(`renderPasses supports up to ${Fc} entries, got ${t}`);let n=Xg+t*Gg,i=ie.allocUnsafe(n),s=0;if(i.writeUInt8(e.id,s++),i.writeUInt16BE(e.originX,s),s+=2,i.writeUInt16BE(e.originY,s),s+=2,i.writeUInt8(e.sizeX-1,s++),i.writeUInt8(e.sizeY-1,s++),i.writeUInt8(t,s++),t>0&&e.renderPasses)for(let a of e.renderPasses){let l=Math.max(0,Math.min(255,a.id)),u=Math.max(0,Math.min(255,a.zMin)),c=Math.max(0,Math.min(255,a.zMax)),d=a.enabled===!1?0:1;i.writeUInt8(l,s++),i.writeUInt8(u,s++),i.writeUInt8(c,s++),i.writeUInt8(d,s++)}return i.toUint8Array()}calculateSize(e){var n;let t=Math.min(((n=e.renderPasses)==null?void 0:n.length)??0,Fc);return Xg+t*Gg}};J(yv,"DisplayEncoder");var kI=yv,vv=class{constructor(){D(this,"layerEncoder"),D(this,"audioOrderEncoder"),D(this,"vibrationOrderEncoder"),D(this,"macroOrderEncoder"),D(this,"postProcessOrderEncoder"),D(this,"displayEncoder"),this.layerEncoder=new CI,this.audioOrderEncoder=new bI,this.vibrationOrderEncoder=new SI,this.macroOrderEncoder=new xI,this.postProcessOrderEncoder=new II,this.displayEncoder=new kI}encode(e){let t=e.layers.map(z=>this.layerEncoder.encode(z)),n=e.audioOrders||[],i=n.map(z=>this.audioOrderEncoder.encode(z)),s=e.vibrationOrders||[],o=s.map(z=>this.vibrationOrderEncoder.encode(z)),a=e.macroOrders||[],l=a.map(z=>this.macroOrderEncoder.encode(z)),u=e.postProcessOrders||[],c=u.map(z=>this.postProcessOrderEncoder.encode(z)),d=9,h=e.displays.reduce((z,P)=>z+this.displayEncoder.calculateSize(P),0),f=2,p=t.reduce((z,P)=>z+P.length,0),m=1,S=i.reduce((z,P)=>z+P.length,0),w=1,g=o.reduce((z,P)=>z+P.length,0),y=1,C=l.reduce((z,P)=>z+P.length,0),x=1,I=c.reduce((z,P)=>z+P.length,0),E=d+h+f+p+m+S+w+g+y+C+x+I,A=ie.allocUnsafe(E),R=0,F=typeof e.tick=="bigint"?e.tick:BigInt(e.tick);A.writeBigUInt64BE(F,R),R+=8,A.writeUInt8(e.displays.length,R),R+=1;for(let z of e.displays){let P=this.displayEncoder.encode(z);ie.from(P).copy(A,R),R+=P.length}A.writeUInt16BE(e.layers.length,R),R+=2;for(let z of t)ie.from(z).copy(A,R),R+=z.length;A.writeUInt8(n.length,R),R+=1;for(let z of i)ie.from(z).copy(A,R),R+=z.length;A.writeUInt8(s.length,R),R+=1;for(let z of o)ie.from(z).copy(A,R),R+=z.length;A.writeUInt8(a.length,R),R+=1;for(let z of l)ie.from(z).copy(A,R),R+=z.length;A.writeUInt8(u.length,R),R+=1;for(let z of c)ie.from(z).copy(A,R),R+=z.length;return A.toUint8Array()}calculateSize(e){let t=e.displays.reduce((f,p)=>f+this.displayEncoder.calculateSize(p),0),n=2,i=e.layers.reduce((f,p)=>f+this.layerEncoder.calculateSize(p),0),s=1,o=(e.audioOrders||[]).reduce((f,p)=>f+this.audioOrderEncoder.calculateSize(p),0),a=1,l=(e.vibrationOrders||[]).reduce((f,p)=>f+this.vibrationOrderEncoder.calculateSize(p),0),u=1,c=(e.macroOrders||[]).reduce((f,p)=>f+this.macroOrderEncoder.calculateSize(p),0),d=1,h=(e.postProcessOrders||[]).reduce((f,p)=>f+this.postProcessOrderEncoder.calculateSize(p),0);return 9+t+n+i+s+o+a+l+u+c+d+h}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=ie.allocUnsafe(15),n=typeof e=="bigint"?e:BigInt(e);return t.writeBigUInt64BE(n,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()}};J(vv,"UpdatePacketEncoder");var EI=vv,MI=(r=>(r[r.ColorPalette=1]="ColorPalette",r[r.Sprite=2]="Sprite",r[r.MulticolorSprite=3]="MulticolorSprite",r[r.Sound=5]="Sound",r[r.Macro=7]="Macro",r[r.ImageFont=8]="ImageFont",r[r.ImageFontBlock=9]="ImageFontBlock",r))(MI||{}),wv=class{encode(e){let t=JSON.stringify(e.template),n=new TextEncoder().encode(t);if(n.length>65535)throw new Error(`Macro template JSON too large: ${n.length} bytes (max 65535)`);let i=4+n.length,s=ie.allocUnsafe(i),o=0;return s.writeUInt8(7,o++),s.writeUInt8(e.macroId,o++),s.writeUInt16BE(n.length,o),o+=2,s.toUint8Array().set(n,o),s.toUint8Array()}calculateSize(e){let t=JSON.stringify(e.template);return 4+new TextEncoder().encode(t).length}};J(wv,"MacroLoadEncoder");var UI=wv,Cv=class{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 n=e.slotId!==void 0,i=n?4:3,s=ie.allocUnsafe(i+t*6),o=0;s.writeUInt8(1,o++),s.writeUInt8(n?255:0,o++),n&&s.writeUInt8(e.slotId,o++),s.writeUInt8(t,o++);for(let a of e.colors)s.writeUInt8(a.colorId,o++),s.writeUInt8(a.r,o++),s.writeUInt8(a.g,o++),s.writeUInt8(a.b,o++),s.writeUInt8(a.a??255,o++),s.writeUInt8(a.e??0,o++);return s.toUint8Array()}encodeSprite(e){let t=e.sprites.length;if(t>255)throw new Error(`Sprite count ${t} exceeds maximum of 255`);let n=2;for(let o of e.sprites)n+=3,n+=o.data.length;let i=ie.allocUnsafe(n),s=0;i.writeUInt8(2,s++),i.writeUInt8(t,s++);for(let o of e.sprites){if(o.data.length!==o.sizeX*o.sizeY)throw new Error(`Sprite ${o.spriteId}: data length ${o.data.length} does not match size ${o.sizeX}x${o.sizeY}`);i.writeUInt8(o.spriteId,s++),i.writeUInt8(o.sizeX,s++),i.writeUInt8(o.sizeY,s++);for(let a of o.data)i.writeUInt8(a,s++)}return i.toUint8Array()}encodeMulticolorSprite(e){let t=e.sprites.length;if(t>255)throw new Error(`Sprite count ${t} exceeds maximum of 255`);let n=2;for(let o of e.sprites)n+=3,n+=o.data.length*3;let i=ie.allocUnsafe(n),s=0;i.writeUInt8(3,s++),i.writeUInt8(t,s++);for(let o of e.sprites){if(o.data.length!==o.sizeX*o.sizeY)throw new Error(`Sprite ${o.spriteId}: data length ${o.data.length} does not match size ${o.sizeX}x${o.sizeY}`);i.writeUInt8(o.spriteId,s++),i.writeUInt8(o.sizeX,s++),i.writeUInt8(o.sizeY,s++);for(let a of o.data)i.writeUInt8(a.charCode,s++),i.writeUInt8(a.fgColorId,s++),i.writeUInt8(a.bgColorId,s++)}return i.toUint8Array()}encodeSound(e){let t=e.sounds.length;if(t>255)throw new Error(`Sound count ${t} exceeds maximum of 255`);let n=2;for(let o of e.sounds){if(o.midiData.length>65535)throw new Error(`Sound ${o.soundId}: MIDI data size ${o.midiData.length} exceeds maximum of 65535 bytes`);n+=3,n+=o.midiData.length}let i=ie.allocUnsafe(n),s=0;i.writeUInt8(5,s++),i.writeUInt8(t,s++);for(let o of e.sounds){i.writeUInt8(o.soundId,s++),i.writeUInt16BE(o.midiData.length,s),s+=2;for(let a=0;a<o.midiData.length;a++)i.writeUInt8(o.midiData[a],s++)}return i.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 t=ie.allocUnsafe(6),n=0;return t.writeUInt8(8,n++),t.writeUInt8(e.glyphWidth,n++),t.writeUInt8(e.glyphHeight,n++),t.writeUInt8(e.cellWidth,n++),t.writeUInt8(e.cellHeight,n++),t.writeUInt8(e.atlasBlocks,n++),t.toUint8Array()}encodeImageFontBlock(e){let t=6+e.imageData.length,n=ie.allocUnsafe(t),i=0;n.writeUInt8(9,i++),n.writeUInt8(e.blockIndex,i++),n.writeUInt32LE(e.imageData.length,i),i+=4;for(let s=0;s<e.imageData.length;s++)n.writeUInt8(e.imageData[s],i++);return n.toUint8Array()}};J(Cv,"LoadEncoder");var Lc=Cv,bv=class{decode(e,t=0){let n=t,i=e.readUInt8(t++);if(i!==7)throw new Error(`Expected LoadType.Macro (0x07), got 0x${i.toString(16)}`);let s=e.readUInt8(t++),o=e.readUInt16BE(t);t+=2;let a=e.toUint8Array().subarray(t,t+o);t+=o;let l=new TextDecoder().decode(a),u=JSON.parse(l);return{load:{loadType:7,macroId:s,template:u},bytesRead:t-n}}};J(bv,"MacroLoadDecoder");var AI=bv,Sv=class{decode(e,t=0){let n=ie.from(e);if(t>=n.length)throw new Error("Buffer too short to decode load type");let i=n.readUInt8(t);switch(i){case 1:return this.decodeColorPalette(n,t);case 2:return this.decodeSprite(n,t);case 3:return this.decodeMulticolorSprite(n,t);case 5:return this.decodeSound(n,t);case 7:return this.decodeMacro(n,t);case 8:return this.decodeImageFont(n,t);case 9:return this.decodeImageFontBlock(n,t);default:throw new Error(`Unknown load type: 0x${i.toString(16)}`)}}decodeColorPalette(e,t){let n=t;this.checkSize(e,t,3,"ColorPalette header"),e.readUInt8(t++);let i=e.readUInt8(t++)===255,s;i&&(this.checkSize(e,t,1,"ColorPalette slotId"),s=e.readUInt8(t++));let o=e.readUInt8(t++);this.checkSize(e,t,o*6,`ColorPalette ${o} colors`);let a=[];for(let l=0;l<o;l++)a.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:a},bytesRead:t-n}}decodeSprite(e,t){let n=t;this.checkSize(e,t,2,"Sprite header"),e.readUInt8(t++);let i=e.readUInt8(t++),s=[];for(let o=0;o<i;o++){this.checkSize(e,t,3,`Sprite ${o} header`);let a=e.readUInt8(t++),l=e.readUInt8(t++),u=e.readUInt8(t++),c=l*u;this.checkSize(e,t,c,`Sprite ${o} data`);let d=[];for(let h=0;h<c;h++)d.push(e.readUInt8(t++));s.push({spriteId:a,sizeX:l,sizeY:u,data:d})}return{load:{loadType:2,sprites:s},bytesRead:t-n}}decodeMulticolorSprite(e,t){let n=t;this.checkSize(e,t,2,"MulticolorSprite header"),e.readUInt8(t++);let i=e.readUInt8(t++),s=[];for(let o=0;o<i;o++){this.checkSize(e,t,3,`MulticolorSprite ${o} header`);let a=e.readUInt8(t++),l=e.readUInt8(t++),u=e.readUInt8(t++),c=l*u;this.checkSize(e,t,c*3,`MulticolorSprite ${o} data`);let d=[];for(let h=0;h<c;h++)d.push({charCode:e.readUInt8(t++),fgColorId:e.readUInt8(t++),bgColorId:e.readUInt8(t++)});s.push({spriteId:a,sizeX:l,sizeY:u,data:d})}return{load:{loadType:3,sprites:s},bytesRead:t-n}}decodeSound(e,t){let n=t;this.checkSize(e,t,2,"Sound header"),e.readUInt8(t++);let i=e.readUInt8(t++),s=[];for(let o=0;o<i;o++){this.checkSize(e,t,3,`Sound ${o} header`);let a=e.readUInt8(t++),l=e.readUInt16BE(t);t+=2,this.checkSize(e,t,l,`Sound ${o} MIDI data`);let u=new Uint8Array(l);for(let c=0;c<l;c++)u[c]=e.readUInt8(t++);s.push({soundId:a,midiData:u})}return{load:{loadType:5,sounds:s},bytesRead:t-n}}checkSize(e,t,n,i){if(t+n>e.length)throw new Error(`Buffer too short for ${i}: need ${n} bytes at offset ${t}, but only ${e.length-t} bytes remaining`)}decodeMacro(e,t){return new AI().decode(e,t)}decodeImageFont(e,t){let n=t;this.checkSize(e,t,6,"ImageFont header"),e.readUInt8(t++);let i=e.readUInt8(t++),s=e.readUInt8(t++),o=e.readUInt8(t++),a=e.readUInt8(t++),l=e.readUInt8(t++);if(![1,4,16].includes(l))throw new Error(`Invalid atlasBlocks value: ${l}. Must be 1, 4, or 16.`);return{load:{loadType:8,glyphWidth:i,glyphHeight:s,cellWidth:o,cellHeight:a,atlasBlocks:l},bytesRead:t-n}}decodeImageFontBlock(e,t){let n=t;this.checkSize(e,t,2,"ImageFontBlock header"),e.readUInt8(t++);let i=e.readUInt8(t++);this.checkSize(e,t,4,"ImageFontBlock data size");let s=e.readUInt32LE(t);t+=4,this.checkSize(e,t,s,"ImageFontBlock data");let o=new Uint8Array(s);for(let a=0;a<s;a++)o[a]=e.readUInt8(t++);return{load:{loadType:9,blockIndex:i,imageData:o},bytesRead:t-n}}};J(Sv,"LoadDecoder");var TI=Sv,RI=4,Kg=4,Zg=8,xv=class{decode(e,t=0){this.checkSize(e,t,Zg);let n=t,i=e.readUInt8(n++),s=e.readUInt16BE(n);n+=2;let o=e.readUInt16BE(n);n+=2;let a=e.readUInt8(n++)+1,l=e.readUInt8(n++)+1,u=e.readUInt8(n++);if(u>Kg)throw new Error(`Invalid renderPass count: ${u} (max ${Kg})`);let c=u*RI;this.checkSize(e,n,c);let d=[];for(let h=0;h<u;h++){let f=e.readUInt8(n++),p=e.readUInt8(n++),m=e.readUInt8(n++),S=e.readUInt8(n++);d.push({id:f,zMin:p,zMax:m,enabled:(S&1)!==0})}return{display:{id:i,originX:s,originY:o,sizeX:a,sizeY:l,renderPasses:d.length>0?d:void 0},bytesRead:Zg+c}}checkSize(e,t,n){if(t+n>e.length)throw new Error(`Buffer too short for display: need ${n} bytes at offset ${t}, but only ${e.length-t} bytes available`)}};J(xv,"DisplayDecoder");var PI=xv,Iv=class{constructor(){D(this,"charCodeSize",_1)}decode(e,t=0,n=!1){if(t>=e.length)throw new Error("Buffer too short to decode order type");let i=e.readUInt8(t);switch(i){case 1:return this.decodeCharOrder(e,t,n);case 2:return this.decodeTextOrder(e,t);case 23:return this.decodeTextMultilineOrder(e,t);case 3:return this.decodeSubFrameOrder(e,t,n);case 4:return this.decodeSubFrameMultiColorOrder(e,t,n);case 5:return this.decodeFullFrameOrder(e,t,n);case 6:return this.decodeFullFrameMultiColorOrder(e,t,n);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,n);case 11:return this.decodeDotCloudOrder(e,t,n);case 12:return this.decodeDotCloudMultiColorOrder(e,t,n);case 17:return this.decodeBitmaskOrder(e,t,n);case 18:return this.decodeBitmask4Order(e,t,n);case 24:return this.decodeBitmask16Order(e,t,n);case 25:return this.decodePolylineOrder(e,t,n);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,n);case 20:return this.decodeFillCharOrder(e,t,n);case 21:return this.decodeFillSpriteOrder(e,t);case 22:return this.decodeFillSpriteMultiColorOrder(e,t);default:throw new Error(`Unknown order type: 0x${i.toString(16)}`)}}readCharCode(e,t,n){return n?[e.readUInt16LE(t),t+2]:[e.readUInt8(t),t+1]}decodeCharOrder(e,t,n){let i=5+this.charCodeSize(n);this.checkSize(e,t,i);let s=t;e.readUInt8(s++);let o=e.readUInt8(s++),a=e.readUInt8(s++),[l,u]=this.readCharCode(e,s,n);s=u;let c=e.readUInt8(s++),d=e.readUInt8(s++);return{order:{type:1,posX:o,posY:a,charCode:l,bgColorCode:c,fgColorCode:d},bytesRead:i}}decodeTextOrder(e,t){this.checkSize(e,t,5);let n=t,i=e.readUInt8(n+3);this.checkSize(e,t,5+i);let s=e.subarray(n+4,n+4+i),o=new TextDecoder().decode(s.toUint8Array());return{order:{type:2,posX:e.readUInt8(n+1),posY:e.readUInt8(n+2),text:o,bgColorCode:e.readUInt8(n+4+i),fgColorCode:e.readUInt8(n+5+i)},bytesRead:6+i}}decodeTextMultilineOrder(e,t){this.checkSize(e,t,5);let n=t,i=e.readUInt8(n+3);this.checkSize(e,t,5+i);let s=e.subarray(n+4,n+4+i),o=new TextDecoder().decode(s.toUint8Array());return{order:{type:23,posX:e.readUInt8(n+1),posY:e.readUInt8(n+2),text:o,bgColorCode:e.readUInt8(n+4+i),fgColorCode:e.readUInt8(n+5+i)},bytesRead:6+i}}decodeSubFrameOrder(e,t,n){this.checkSize(e,t,7);let i=t,s=this.charCodeSize(n),o=e.readUInt8(i+3)+1,a=e.readUInt8(i+4)+1,l=o*a;this.checkSize(e,t,7+l*s);let u=[],c=i+7;for(let d=0;d<l;d++){let[h,f]=this.readCharCode(e,c,n);u.push(h),c=f}return{order:{type:3,posX:e.readUInt8(i+1),posY:e.readUInt8(i+2),sizeX:o,sizeY:a,bgColorCode:e.readUInt8(i+5),fgColorCode:e.readUInt8(i+6),frame:u},bytesRead:7+l*s}}decodeSubFrameMultiColorOrder(e,t,n){this.checkSize(e,t,5);let i=t,s=this.charCodeSize(n),o=e.readUInt8(i+3)+1,a=e.readUInt8(i+4)+1,l=o*a,u=s+2;this.checkSize(e,t,5+l*u);let c=[],d=i+5;for(let h=0;h<l;h++){let[f,p]=this.readCharCode(e,d,n);d=p,c.push({charCode:f,bgColorCode:e.readUInt8(d++),fgColorCode:e.readUInt8(d++)})}return{order:{type:4,posX:e.readUInt8(i+1),posY:e.readUInt8(i+2),sizeX:o,sizeY:a,frame:c},bytesRead:5+l*u}}decodeFullFrameOrder(e,t,n,i){this.checkSize(e,t,3);let s=t,o=this.charCodeSize(n),a=i||Math.floor((e.length-t-3)/o);this.checkSize(e,t,3+a*o);let l=[],u=s+3;for(let c=0;c<a;c++){let[d,h]=this.readCharCode(e,u,n);l.push(d),u=h}return{order:{type:5,bgColorCode:e.readUInt8(s+1),fgColorCode:e.readUInt8(s+2),frame:l},bytesRead:3+a*o}}decodeFullFrameMultiColorOrder(e,t,n,i){this.checkSize(e,t,1);let s=t,o=this.charCodeSize(n)+2,a=i||Math.floor((e.length-t-1)/o);this.checkSize(e,t,1+a*o);let l=[],u=s+1;for(let c=0;c<a;c++){let[d,h]=this.readCharCode(e,u,n);u=h,l.push({charCode:d,bgColorCode:e.readUInt8(u++),fgColorCode:e.readUInt8(u++)})}return{order:{type:6,frame:l},bytesRead:1+a*o}}decodeSpriteOrder(e,t){this.checkSize(e,t,6);let n=t;return{order:{type:7,posX:e.readUInt8(n+1),posY:e.readUInt8(n+2),spriteIndex:e.readUInt8(n+3),bgColorCode:e.readUInt8(n+4),fgColorCode:e.readUInt8(n+5)},bytesRead:6}}decodeSpriteMultiColorOrder(e,t){this.checkSize(e,t,4);let n=t;return{order:{type:8,posX:e.readUInt8(n+1),posY:e.readUInt8(n+2),spriteIndex:e.readUInt8(n+3)},bytesRead:4}}decodeColorMapOrder(e,t){this.checkSize(e,t,5);let n=t,i=e.readUInt8(n+3)+1,s=e.readUInt8(n+4)+1,o=i*s;this.checkSize(e,t,5+o*2);let a=[];for(let l=0;l<o;l++){let u=n+5+l*2;a.push({bgColorCode:e.readUInt8(u),fgColorCode:e.readUInt8(u+1)})}return{order:{type:9,posX:e.readUInt8(n+1),posY:e.readUInt8(n+2),sizeX:i,sizeY:s,colorData:a},bytesRead:5+o*2}}decodeShapeOrder(e,t,n){this.checkSize(e,t,2);let i=t,s=e.readUInt8(i+1),{shapeData:o,bytesRead:a}=this.decodeShapeData(e,i+2,s,n);return{order:{type:10,shapeType:s,shapeData:o},bytesRead:2+a}}decodeShapeData(e,t,n,i){let s=t,o=this.charCodeSize(i);switch(n){case 1:{let a=7+o;this.checkSize(e,t,a);let l=e.readUInt8(s++),u=e.readUInt8(s++),c=e.readUInt8(s++)+1,d=e.readUInt8(s++)+1,h=e.readUInt8(s++)===1,[f,p]=this.readCharCode(e,s,i);s=p;let m=e.readUInt8(s++),S=e.readUInt8(s++);return{shapeData:{posX:l,posY:u,width:c,height:d,filled:h,charCode:f,bgColorCode:m,fgColorCode:S},bytesRead:a}}case 2:{let a=6+o;this.checkSize(e,t,a);let l=e.readUInt8(s++),u=e.readUInt8(s++),c=e.readUInt8(s++)+1,d=e.readUInt8(s++)===1,[h,f]=this.readCharCode(e,s,i);s=f;let p=e.readUInt8(s++),m=e.readUInt8(s++);return{shapeData:{centerX:l,centerY:u,radius:c,filled:d,charCode:h,bgColorCode:p,fgColorCode:m},bytesRead:a}}case 3:{let a=6+o;this.checkSize(e,t,a);let l=e.readUInt8(s++),u=e.readUInt8(s++),c=e.readUInt8(s++),d=e.readUInt8(s++),[h,f]=this.readCharCode(e,s,i);s=f;let p=e.readUInt8(s++),m=e.readUInt8(s++);return{shapeData:{x1:l,y1:u,x2:c,y2:d,charCode:h,bgColorCode:p,fgColorCode:m},bytesRead:a}}case 4:{let a=7+o;this.checkSize(e,t,a);let l=e.readUInt8(s++),u=e.readUInt8(s++),c=e.readUInt8(s++)+1,d=e.readUInt8(s++)+1,h=e.readUInt8(s++)===1,[f,p]=this.readCharCode(e,s,i);s=p;let m=e.readUInt8(s++),S=e.readUInt8(s++);return{shapeData:{centerX:l,centerY:u,radiusX:c,radiusY:d,filled:h,charCode:f,bgColorCode:m,fgColorCode:S},bytesRead:a}}case 5:{let a=9+o;this.checkSize(e,t,a);let l=e.readUInt8(s++),u=e.readUInt8(s++),c=e.readUInt8(s++),d=e.readUInt8(s++),h=e.readUInt8(s++),f=e.readUInt8(s++),p=e.readUInt8(s++)===1,[m,S]=this.readCharCode(e,s,i);s=S;let w=e.readUInt8(s++),g=e.readUInt8(s++);return{shapeData:{x1:l,y1:u,x2:c,y2:d,x3:h,y3:f,filled:p,charCode:m,bgColorCode:w,fgColorCode:g},bytesRead:a}}default:throw new Error(`Unknown shape type: ${n}`)}}decodeDotCloudOrder(e,t,n){let i=1+this.charCodeSize(n)+2+2;this.checkSize(e,t,i);let s=t;e.readUInt8(s++);let[o,a]=this.readCharCode(e,s,n);s=a;let l=e.readUInt8(s++),u=e.readUInt8(s++),c=e.readUInt16BE(s);s+=2,this.checkSize(e,t,i+c*2);let d=[];for(let h=0;h<c;h++)d.push({posX:e.readUInt8(s++),posY:e.readUInt8(s++)});return{order:{type:11,charCode:o,bgColorCode:l,fgColorCode:u,positions:d},bytesRead:i+c*2}}decodeDotCloudMultiColorOrder(e,t,n){this.checkSize(e,t,3);let i=this.charCodeSize(n),s=t,o=e.readUInt16BE(s+1),a=i+4;this.checkSize(e,t,3+o*a);let l=[],u=s+3;for(let c=0;c<o;c++){let[d,h]=this.readCharCode(e,u,n);u=h,l.push({charCode:d,bgColorCode:e.readUInt8(u++),fgColorCode:e.readUInt8(u++),posX:e.readUInt8(u++),posY:e.readUInt8(u++)})}return{order:{type:12,dots:l},bytesRead:3+o*a}}decodeBitmaskOrder(e,t,n){let i=8+this.charCodeSize(n);this.checkSize(e,t,i);let s=t;e.readUInt8(s++);let o=e.readUInt8(s++),a=e.readUInt8(s++),l=e.readUInt8(s++)+1,u=e.readUInt8(s++)+1,[c,d]=this.readCharCode(e,s,n);s=d;let h=e.readUInt8(s++),f=e.readUInt8(s++),p=e.readUInt8(s++)===1,m=Math.ceil(l*u/8);this.checkSize(e,t,i+m);let S=new Uint8Array(m);for(let w=0;w<m;w++)S[w]=e.readUInt8(s+w);return{order:{type:17,posX:o,posY:a,sizeX:l,sizeY:u,charCode:c,bgColorCode:h,fgColorCode:f,override:p,mask:S},bytesRead:i+m}}decodeBitmask4Order(e,t,n){let i=6+3*(this.charCodeSize(n)+2);this.checkSize(e,t,i);let s=t;e.readUInt8(s++);let o=e.readUInt8(s++),a=e.readUInt8(s++),l=e.readUInt8(s++)+1,u=e.readUInt8(s++)+1,c=e.readUInt8(s++)===1,d=Math.ceil(l*u/4);this.checkSize(e,t,i+d);let h=[];for(let p=0;p<3;p++){let[m,S]=this.readCharCode(e,s,n);s=S,h.push({charCode:m,bgColorCode:e.readUInt8(s++),fgColorCode:e.readUInt8(s++)})}let f=new Uint8Array(d);for(let p=0;p<d;p++)f[p]=e.readUInt8(s+p);return{order:{type:18,posX:o,posY:a,sizeX:l,sizeY:u,override:c,variants:h,mask:f},bytesRead:i+d}}decodeBitmask16Order(e,t,n){let i=6+15*(this.charCodeSize(n)+2);this.checkSize(e,t,i);let s=t;e.readUInt8(s++);let o=e.readUInt8(s++),a=e.readUInt8(s++),l=e.readUInt8(s++)+1,u=e.readUInt8(s++)+1,c=e.readUInt8(s++)===1,d=Math.ceil(l*u/2);this.checkSize(e,t,i+d);let h=[];for(let p=0;p<15;p++){let[m,S]=this.readCharCode(e,s,n);s=S,h.push({charCode:m,bgColorCode:e.readUInt8(s++),fgColorCode:e.readUInt8(s++)})}let f=new Uint8Array(d);for(let p=0;p<d;p++)f[p]=e.readUInt8(s+p);return{order:{type:24,posX:o,posY:a,sizeX:l,sizeY:u,override:c,variants:h,mask:f},bytesRead:i+d}}decodePolylineOrder(e,t,n){let i=4+this.charCodeSize(n);this.checkSize(e,t,i);let s=t;e.readUInt8(s++);let[o,a]=this.readCharCode(e,s,n);s=a;let l=e.readUInt8(s++),u=e.readUInt8(s++),c=e.readUInt8(s++);this.checkSize(e,t,i+c*2);let d=[];for(let h=0;h<c;h++)d.push({x:e.readUInt8(s++),y:e.readUInt8(s++)});return{order:{type:25,charCode:o,fgColorCode:l,bgColorCode:u,points:d},bytesRead:i+c*2}}decodeSpriteCloudOrder(e,t){this.checkSize(e,t,6);let n=t,i=e.readUInt16BE(n+4);this.checkSize(e,t,6+i*2);let s=[];for(let o=0;o<i;o++){let a=n+6+o*2;s.push({posX:e.readUInt8(a),posY:e.readUInt8(a+1)})}return{order:{type:13,spriteIndex:e.readUInt8(n+1),bgColorCode:e.readUInt8(n+2),fgColorCode:e.readUInt8(n+3),positions:s},bytesRead:6+i*2}}decodeSpriteCloudMultiColorOrder(e,t){this.checkSize(e,t,4);let n=t,i=e.readUInt16BE(n+2);this.checkSize(e,t,4+i*2);let s=[];for(let o=0;o<i;o++){let a=n+4+o*2;s.push({posX:e.readUInt8(a),posY:e.readUInt8(a+1)})}return{order:{type:14,spriteIndex:e.readUInt8(n+1),positions:s},bytesRead:4+i*2}}decodeSpriteCloudVariedOrder(e,t){this.checkSize(e,t,3);let n=t,i=e.readUInt16BE(n+1);this.checkSize(e,t,3+i*5);let s=[];for(let o=0;o<i;o++){let a=n+3+o*5;s.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:s},bytesRead:3+i*5}}decodeSpriteCloudVariedMultiColorOrder(e,t){this.checkSize(e,t,3);let n=t,i=e.readUInt16BE(n+1);this.checkSize(e,t,3+i*3);let s=[];for(let o=0;o<i;o++){let a=n+3+o*3;s.push({spriteIndex:e.readUInt8(a),posX:e.readUInt8(a+1),posY:e.readUInt8(a+2)})}return{order:{type:16,sprites:s},bytesRead:3+i*3}}decodeFillOrder(e,t,n){let i=3+this.charCodeSize(n);this.checkSize(e,t,i);let s=t;e.readUInt8(s++);let[o,a]=this.readCharCode(e,s,n);s=a;let l=e.readUInt8(s++),u=e.readUInt8(s++);return{order:{type:19,charCode:o,bgColorCode:l,fgColorCode:u},bytesRead:i}}decodeFillCharOrder(e,t,n){this.checkSize(e,t,5);let i=this.charCodeSize(n),s=t,o=e.readUInt8(s+1)+1,a=e.readUInt8(s+2)+1,l=o*a,u=5+l*i;this.checkSize(e,t,u);let c=[],d=s+5;for(let h=0;h<l;h++){let[f,p]=this.readCharCode(e,d,n);c.push(f),d=p}return{order:{type:20,patternWidth:o,patternHeight:a,bgColorCode:e.readUInt8(s+3),fgColorCode:e.readUInt8(s+4),pattern:c},bytesRead:u}}decodeFillSpriteOrder(e,t){this.checkSize(e,t,4);let n=t;return{order:{type:21,spriteIndex:e.readUInt8(n+1),bgColorCode:e.readUInt8(n+2),fgColorCode:e.readUInt8(n+3)},bytesRead:4}}decodeFillSpriteMultiColorOrder(e,t){this.checkSize(e,t,2);let n=t;return{order:{type:22,spriteIndex:e.readUInt8(n+1)},bytesRead:2}}checkSize(e,t,n){if(t+n>e.length)throw new Error(`Buffer too short: need ${n} bytes at offset ${t}, but only ${e.length-t} bytes available`)}};J(Iv,"OrderDecoder");var BI=Iv,zI=32,DI=64,kv=class{constructor(){D(this,"orderDecoder"),this.orderDecoder=new BI}decode(e,t=0){this.checkSize(e,t,13);let n=t,i=e.readUInt16BE(n);n+=2;let s=e.readUInt8(n++),o=e.readUInt8(n++),a=e.readUInt16BE(n);n+=2;let l=e.readUInt16BE(n);n+=2;let u=e.readUInt16BE(n);n+=2;let c=e.readUInt16BE(n);n+=2;let d=e.readUInt8(n++),h=(s&zI)!==0,f=(s&DI)!==0,p=[],m=n;for(let S=0;S<d;S++){let w=this.orderDecoder.decode(e,m,f);p.push(w.order),m+=w.bytesRead}return{layer:{id:i,updateFlags:s,zIndex:o,originX:a,originY:l,width:u,height:c,orderCount:d,orders:p,isMacroLayer:h,is16bit:f},bytesRead:m-t}}checkSize(e,t,n){if(t+n>e.length)throw new Error(`Buffer too short for layer: need ${n} bytes at offset ${t}, but only ${e.length-t} bytes available`)}};J(kv,"LayerDecoder");var OI=kv,Ev=class{decode(e,t=0){if(t>=e.length)throw new Error("Buffer too short to decode audio order type");let n=e.readUInt8(t);switch(n){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${n.toString(16)}`)}}decodePlaySoundOrder(e,t){this.checkSize(e,t,5);let n=t,i=e.readUInt8(n++),s=e.readUInt8(n++),o=e.readUInt16BE(n);n+=2;let a=e.readUInt8(n++),l={type:i,soundId:s,instanceId:o,flags:a};return a&2&&(this.checkSize(e,n,1),l.volume=e.readUInt8(n++)),a&4&&(this.checkSize(e,n,1),l.pitch=e.readUInt8(n++)),a&8&&(this.checkSize(e,n,1),l.fadeIn=e.readUInt8(n++)),a&16&&(this.checkSize(e,n,4),l.posX=e.readUInt16BE(n),n+=2,l.posY=e.readUInt16BE(n),n+=2),a&32&&(this.checkSize(e,n,1),l.lowpass=e.readUInt8(n++)),a&64&&(this.checkSize(e,n,1),l.highpass=e.readUInt8(n++)),a&128&&(this.checkSize(e,n,1),l.reverb=e.readUInt8(n++)),{order:l,bytesRead:n-t}}decodePlayGlobalSoundOrder(e,t){this.checkSize(e,t,5);let n=t,i=e.readUInt8(n++),s=e.readUInt8(n++),o=e.readUInt16BE(n);n+=2;let a=e.readUInt8(n++),l={type:i,soundId:s,instanceId:o,flags:a};return a&2&&(this.checkSize(e,n,1),l.volume=e.readUInt8(n++)),a&4&&(this.checkSize(e,n,1),l.pitch=e.readUInt8(n++)),a&8&&(this.checkSize(e,n,1),l.fadeIn=e.readUInt8(n++)),a&32&&(this.checkSize(e,n,1),l.lowpass=e.readUInt8(n++)),a&64&&(this.checkSize(e,n,1),l.highpass=e.readUInt8(n++)),a&128&&(this.checkSize(e,n,1),l.reverb=e.readUInt8(n++)),{order:l,bytesRead:n-t}}decodeStopSoundOrder(e,t){this.checkSize(e,t,2);let n=t,i=e.readUInt8(n++),s=e.readUInt8(n++),o={type:i,targetType:s};return s===0?(this.checkSize(e,n,2),o.target=e.readUInt16BE(n),n+=2):s===1&&(this.checkSize(e,n,1),o.target=e.readUInt8(n++)),{order:o,bytesRead:n-t}}decodeFadeOutSoundOrder(e,t){this.checkSize(e,t,3);let n=t,i=e.readUInt8(n++),s=e.readUInt8(n++),o=e.readUInt8(n++),a={type:i,targetType:s,duration:o};return s===0?(this.checkSize(e,n,2),a.target=e.readUInt16BE(n),n+=2):s===1&&(this.checkSize(e,n,1),a.target=e.readUInt8(n++)),{order:a,bytesRead:n-t}}decodePauseSoundOrder(e,t){this.checkSize(e,t,2);let n=t,i=e.readUInt8(n++),s=e.readUInt8(n++),o={type:i,targetType:s};return s===0?(this.checkSize(e,n,2),o.target=e.readUInt16BE(n),n+=2):s===1&&(this.checkSize(e,n,1),o.target=e.readUInt8(n++)),{order:o,bytesRead:n-t}}decodeResumeSoundOrder(e,t){this.checkSize(e,t,2);let n=t,i=e.readUInt8(n++),s=e.readUInt8(n++),o={type:i,targetType:s};return s===0?(this.checkSize(e,n,2),o.target=e.readUInt16BE(n),n+=2):s===1&&(this.checkSize(e,n,1),o.target=e.readUInt8(n++)),{order:o,bytesRead:n-t}}decodeSetListenerPositionOrder(e,t){this.checkSize(e,t,5);let n=t,i=e.readUInt8(n++),s=e.readUInt16BE(n);n+=2;let o=e.readUInt16BE(n);return n+=2,{order:{type:i,x:s,y:o},bytesRead:5}}decodeConfigureSpatialOrder(e,t){this.checkSize(e,t,5);let n=t;return{order:{type:e.readUInt8(n),maxDistance:e.readUInt8(n+1),referenceDistance:e.readUInt8(n+2),rolloffFactor:e.readUInt8(n+3),panSpread:e.readUInt8(n+4)},bytesRead:5}}decodeSetSoundEffectsOrder(e,t){this.checkSize(e,t,4);let n=t,i=e.readUInt8(n++),s=e.readUInt16BE(n);n+=2;let o=e.readUInt8(n++),a={type:i,instanceId:s,flags:o};return o&1&&(this.checkSize(e,n,1),a.lowpass=e.readUInt8(n++)),o&2&&(this.checkSize(e,n,1),a.highpass=e.readUInt8(n++)),o&4&&(this.checkSize(e,n,1),a.reverb=e.readUInt8(n++)),{order:a,bytesRead:n-t}}checkSize(e,t,n){if(t+n>e.length)throw new Error(`Buffer too short for audio order: need ${n} bytes at offset ${t}, but only ${e.length-t} bytes available`)}};J(Ev,"AudioOrderDecoder");var FI=Ev,Mv=class{decode(e,t=0){if(t>=e.length)throw new Error("Buffer too short to decode vibration order type");let n=e.readUInt8(t);switch(n){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${n.toString(16)}`)}}decodeMobileVibrateOrder(e,t){let n=t,i=e.readUInt8(n++),s=e.readUInt8(n++),o=e.readUInt8(n++),a=[];for(let u=0;u<o;u++)a.push(e.readUInt16BE(n)),n+=2;let l={type:i,flags:s,pattern:a};return s&1&&(l.intensity=e.readUInt8(n++)/255),{order:l,bytesRead:n-t}}decodeMobileCancelOrder(e,t){return{order:{type:2},bytesRead:1}}decodeGamepadVibrateOrder(e,t){let n=t,i=e.readUInt8(n++),s=e.readUInt8(n++),o=e.readUInt8(n++),a=e.readUInt16BE(n);n+=2;let l=e.readUInt8(n++),u=e.readUInt8(n++),c={type:i,flags:s,gamepadIndex:o,duration:a,strongMagnitude:l,weakMagnitude:u};return s&1&&(c.startDelay=e.readUInt16BE(n),n+=2),{order:c,bytesRead:n-t}}decodeGamepadCancelOrder(e,t){let n=t,i=e.readUInt8(n++),s=e.readUInt8(n++),o=e.readUInt8(n++);return{order:{type:i,flags:s,gamepadIndex:o},bytesRead:n-t}}};J(Mv,"VibrationOrderDecoder");var LI=Mv,Uv=class{decode(e,t=0){let n=e.readUInt8(t);switch(n){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${n.toString(16)}`)}}decodeAll(e,t,n){let i=[],s=0;for(let o=0;o<n;o++){let{order:a,bytesRead:l}=this.decode(e,t+s);i.push(a),s+=l}return{orders:i,bytesRead:s}}decodeCreateInstance(e,t){let n=t,i=e.readUInt8(t++),s=e.readUInt8(t++),o=e.readUInt8(t++),a=e.readUInt8(t++),l=e.readInt16BE(t);t+=2;let u=e.readInt16BE(t);t+=2;let c=e.readUInt8(t++),d=e.readUInt16BE(t);t+=2;let h=e.toUint8Array().subarray(t,t+d);t+=d;let f=new TextDecoder().decode(h),p=JSON.parse(f);return{order:{type:i,instanceId:s,macroId:o,layerId:a,x:l,y:u,tabIndex:c,params:p},bytesRead:t-n}}decodeUpdateInstance(e,t){let n=t,i=e.readUInt8(t++),s=e.readUInt8(t++),o=e.readUInt16BE(t);t+=2;let a=e.toUint8Array().subarray(t,t+o);t+=o;let l=new TextDecoder().decode(a),u=JSON.parse(l);return{order:{type:i,instanceId:s,params:u},bytesRead:t-n}}decodeRemoveInstance(e,t){let n=e.readUInt8(t),i=e.readUInt8(t+1);return{order:{type:n,instanceId:i},bytesRead:2}}};J(Uv,"MacroOrderDecoder");var _I=Uv,Av=class{decode(e,t){let n=e[t];switch(n){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: ${n}`)}}decodeSetConfigOrder(e,t){let n=t,i=e[n++],s=e[n++],o=e[n++],a={type:i,displayId:s,flags:o};return o&1&&(a.scanlines={enabled:e[n++]===1,opacity:e[n++]/255,pattern:e[n++],colorR:e[n++],colorG:e[n++],colorB:e[n++]}),o&2&&(a.ambientEffect={enabled:e[n++]===1,blur:e[n++],scale:e[n++]/100,opacity:e[n++]/255}),{order:a,bytesRead:n-t}}decodeSetScanlinesOrder(e,t){let n=t;return{order:{type:e[n++],displayId:e[n++],enabled:e[n++]===1,opacity:e[n++]/255,pattern:e[n++],colorR:e[n++],colorG:e[n++],colorB:e[n++]},bytesRead:n-t}}decodeSetAmbientEffectOrder(e,t){let n=t;return{order:{type:e[n++],displayId:e[n++],enabled:e[n++]===1,blur:e[n++],scale:e[n++]/100,opacity:e[n++]/255},bytesRead:n-t}}decodeSetScalingModeOrder(e,t){let n=t;return{order:{type:e[n++],displayId:e[n++],mode:e[n++]},bytesRead:n-t}}decodeSetGridOrder(e,t){let n=t;return{order:{type:e[n++],displayId:e[n++],enabled:e[n++]===1,colorR:e[n++],colorG:e[n++],colorB:e[n++],colorA:e[n++],lineWidth:e[n++]},bytesRead:n-t}}decodeSwitchPaletteOrder(e,t){let n=t;return{order:{type:e[n++],displayId:e[n++],slotId:e[n++]},bytesRead:n-t}}decodeSetCellSizeOrder(e,t){let n=t;return{order:{type:e[n++],displayId:e[n++],cellWidth:e[n++],cellHeight:e[n++]},bytesRead:n-t}}};J(Av,"PostProcessOrderDecoder");var $I=Av,Tv=class{constructor(){D(this,"displayDecoder"),D(this,"layerDecoder"),D(this,"audioOrderDecoder"),D(this,"vibrationOrderDecoder"),D(this,"macroOrderDecoder"),D(this,"postProcessOrderDecoder"),this.displayDecoder=new PI,this.layerDecoder=new OI,this.audioOrderDecoder=new FI,this.vibrationOrderDecoder=new LI,this.macroOrderDecoder=new _I,this.postProcessOrderDecoder=new $I}decode(e,t=0){let n=ie.from(e);this.checkSize(n,t,15);let i=t,s=Number(n.readBigUInt64BE(i));i+=8;let o=n.readUInt8(i);i+=1;let a=[],l=0;for(let A=0;A<o;A++){let R=this.displayDecoder.decode(n,i);a.push(R.display),i+=R.bytesRead,l+=R.bytesRead}this.checkSize(n,i,2);let u=n.readUInt16BE(i);i+=2;let c=[],d=0;for(let A=0;A<u;A++){let R=this.layerDecoder.decode(n,i);c.push({...R.layer,byteSize:R.bytesRead}),i+=R.bytesRead,d+=R.bytesRead}this.checkSize(n,i,1);let h=n.readUInt8(i);i+=1;let f=[],p=0;for(let A=0;A<h;A++){let R=this.audioOrderDecoder.decode(n,i);f.push(R.order),i+=R.bytesRead,p+=R.bytesRead}this.checkSize(n,i,1);let m=n.readUInt8(i);i+=1;let S=[],w=0;for(let A=0;A<m;A++){let R=this.vibrationOrderDecoder.decode(n,i);S.push(R.order),i+=R.bytesRead,w+=R.bytesRead}this.checkSize(n,i,1);let g=n.readUInt8(i);i+=1;let y=[],C=0;for(let A=0;A<g;A++){let R=this.macroOrderDecoder.decode(n,i);y.push(R.order),i+=R.bytesRead,C+=R.bytesRead}this.checkSize(n,i,1);let x=n.readUInt8(i);i+=1;let I=[],E=0;for(let A=0;A<x;A++){let R=this.postProcessOrderDecoder.decode(n.toUint8Array(),i);I.push(R.order),i+=R.bytesRead,E+=R.bytesRead}return{tick:s,displayCount:o,displays:a,layerCount:u,layers:c,audioOrderCount:h,audioOrders:f,vibrationOrderCount:m,vibrationOrders:S,macroOrderCount:g,macroOrders:y,postProcessOrderCount:x,postProcessOrders:I,__byteSizes:{displays:l,layers:d,audioOrders:p,vibrationOrders:w,macroOrders:C,postProcessOrders:E}}}isValid(e,t=0){let n=ie.from(e);try{return this.checkSize(n,t,15),!0}catch{return!1}}decodeHeader(e,t=0){let n=ie.from(e);this.checkSize(n,t,13);let i=t,s=Number(n.readBigUInt64BE(i));i+=8;let o=n.readUInt8(i);i+=1;for(let l=0;l<o;l++){let u=this.displayDecoder.decode(n,i);i+=u.bytesRead}this.checkSize(n,i,2);let a=n.readUInt16BE(i);return{tick:s,displayCount:o,layerCount:a}}checkSize(e,t,n){if(t+n>e.length)throw new Error(`Buffer too short for update packet: need ${n} bytes at offset ${t}, but only ${e.length-t} bytes available`)}};J(Tv,"UpdatePacketDecoder");var NI=Tv,nh=class Ts{constructor(e){this.engine=e,D(this,"colorCache",new Array(256)),D(this,"cellsBuffer",[]),D(this,"opacityBuffer",new Uint8Array(0)),D(this,"visibleLayersBuffer",[]),D(this,"visibleLayerIdsBuffer",[]),D(this,"passCellsBuffers",[]),D(this,"passOpacityBuffers",[]),this.rebuildColorCache()}static getChar(e){let t=Ts.charCache.get(e);return t===void 0&&(t=String.fromCharCode(e),Ts.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 n=e.x,i=e.x+e.width,s=e.y,o=e.y+e.height,a=t.x,l=t.x+256,u=t.y,c=t.y+256;return!(i<=a||n>=l||o<=u||s>=c)}rasterize(e,t,n){let i=this.normalizePasses(n);return this.rasterizeMultiPass(e,t,i)}rasterizeSinglePass(e,t){let n=e.width*e.height,i=this.cellsBuffer;i.length=n;for(let u=0;u<n;u++)i[u]?(i[u].char=" ",i[u].fgColorIndex=255,i[u].bgColorIndex=255,i[u].fgEmission=0,i[u].bgEmission=0):i[u]={char:" ",fgColorIndex:255,bgColorIndex:255,fgEmission:0,bgEmission:0};this.opacityBuffer.length<n?this.opacityBuffer=new Uint8Array(n):this.opacityBuffer.fill(0,0,n);let s=this.opacityBuffer,o=this.visibleLayersBuffer;o.length=0;for(let u=0;u<t.length;u++){let c=t[u];c.isEnabled()&&this.isLayerVisible(e,c.getOrigin())&&o.push(c)}o.sort((u,c)=>c.getZOrder()-u.getZOrder());let a=this.visibleLayerIdsBuffer;a.length=o.length;for(let u=0;u<o.length;u++)a[u]=o[u].getId();for(let u=0;u<e.height;u++)for(let c=0;c<e.width;c++){let d=u*e.width+c;if(s[d])continue;let h=e.x+c,f=e.y+u;for(let p=0;p<o.length;p++){let m=o[p],S=h-m.getOrigin().x,w=f-m.getOrigin().y,g=m.getWidth(),y=m.getHeight();if(S<0||S>=g||w<0||w>=y)continue;let C=w*g+S,x=m.getData(),I=x.getCharCode(C),E=x.getFgColorCode(C),A=x.getBgColorCode(C),R=i[d];if(I!==0&&R.char===" "&&(R.char=Ts.getChar(I)),E!==255&&R.fgColorIndex===255&&(R.fgColorIndex=E,R.fgEmission=this.getColorEmission(E)),A!==255){R.bgColorIndex===255&&(R.bgColorIndex=A,R.bgEmission=this.getColorEmission(A)),s[d]=1;break}}}let l=new Array(n);for(let u=0;u<n;u++)l[u]={char:i[u].char,fgColorIndex:i[u].fgColorIndex,bgColorIndex:i[u].bgColorIndex,fgEmission:i[u].fgEmission,bgEmission:i[u].bgEmission};return{id:e.id,width:e.width,height:e.height,cells:l,palette:this.colorCache}}rasterizeMultiPass(e,t,n){let i=e.width*e.height;this.ensurePassBuffers(n.length,i),this.visibleLayerIdsBuffer.length=0;let s=this.visibleLayersBuffer;s.length=0;for(let c=0;c<t.length;c++){let d=t[c];d.isEnabled()&&this.isLayerVisible(e,d.getOrigin())&&s.push(d)}s.sort((c,d)=>d.getZOrder()-c.getZOrder());for(let c=0;c<n.length;c++){let d=n[c],h=this.passCellsBuffers[c],f=this.preparePassBuffers(h,this.passOpacityBuffers[c],i);this.passOpacityBuffers[c]=f;let p=[];for(let S=0;S<s.length;S++){let w=s[S],g=w.getZOrder();g<d.zMin||g>d.zMax||p.push(w)}let m=this.visibleLayerIdsBuffer.length;for(let S=0;S<p.length;S++)this.visibleLayerIdsBuffer[m+S]=p[S].getId();this.composePass(e,p,h,f)}let o=this.cellsBuffer,a=this.preparePassBuffers(o,this.opacityBuffer,i);this.opacityBuffer=a;let l=new Array(i),u=[];for(let c=0;c<n.length;c++){let d=this.passCellsBuffers[c],h=new Array(i);for(let f=0;f<i;f++){let p=d[f];h[f]={char:p.char,fgColorIndex:p.fgColorIndex,bgColorIndex:p.bgColorIndex,fgEmission:p.fgEmission,bgEmission:p.bgEmission}}u.push({id:n[c].id,zMin:n[c].zMin,zMax:n[c].zMax,cells:h})}for(let c=0;c<i;c++){let d=o[c];for(let h=n.length-1;h>=0;h--){let f=this.passCellsBuffers[h][c];if(d.char===" "&&f.char!==" "&&(d.char=f.char),d.fgColorIndex===255&&f.fgColorIndex!==255&&(d.fgColorIndex=f.fgColorIndex,d.fgEmission=f.fgEmission),f.bgColorIndex!==255){d.bgColorIndex===255&&(d.bgColorIndex=f.bgColorIndex,d.bgEmission=f.bgEmission);break}}l[c]={char:d.char,fgColorIndex:d.fgColorIndex,bgColorIndex:d.bgColorIndex,fgEmission:d.fgEmission,bgEmission:d.bgEmission}}return{id:e.id,width:e.width,height:e.height,cells:l,palette:this.colorCache,passes:u}}composePass(e,t,n,i){let s=e.width,o=e.height;for(let a=0;a<o;a++)for(let l=0;l<s;l++){let u=a*s+l;if(i[u])continue;let c=e.x+l,d=e.y+a;for(let h=0;h<t.length;h++){let f=t[h],p=c-f.getOrigin().x,m=d-f.getOrigin().y,S=f.getWidth(),w=f.getHeight();if(p<0||p>=S||m<0||m>=w)continue;let g=m*S+p,y=f.getData(),C=y.getCharCode(g),x=y.getFgColorCode(g),I=y.getBgColorCode(g),E=n[u];if(C!==0&&E.char===" "&&(E.char=Ts.getChar(C)),x!==255&&E.fgColorIndex===255&&(E.fgColorIndex=x,E.fgEmission=this.getColorEmission(x)),I!==255){E.bgColorIndex===255&&(E.bgColorIndex=I,E.bgEmission=this.getColorEmission(I)),i[u]=1;break}}}}preparePassBuffers(e,t,n){e.length=n;for(let i=0;i<n;i++)e[i]?(e[i].char=" ",e[i].fgColorIndex=255,e[i].bgColorIndex=255,e[i].fgEmission=0,e[i].bgEmission=0):e[i]={char:" ",fgColorIndex:255,bgColorIndex:255,fgEmission:0,bgEmission:0};return t.length<n?t=new Uint8Array(n):t.fill(0,0,n),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 n=0;n<e;n++)this.passOpacityBuffers[n].length<t?this.passOpacityBuffers[n]=new Uint8Array(t):this.passOpacityBuffers[n].fill(0,0,t)}normalizePasses(e){let t={id:0,zMin:0,zMax:255,enabled:!0};if(!e||e.length===0)return[t];let n=e.filter(i=>i.enabled!==!1);return n.length===0?[t]:n.slice(0,4)}rasterizeWithSortedLayers(e,t){let n=e.width*e.height,i=this.cellsBuffer;i.length=n;for(let l=0;l<n;l++)i[l]?(i[l].char=" ",i[l].fgColorIndex=255,i[l].bgColorIndex=255,i[l].fgEmission=0,i[l].bgEmission=0):i[l]={char:" ",fgColorIndex:255,bgColorIndex:255,fgEmission:0,bgEmission:0};this.opacityBuffer.length<n?this.opacityBuffer=new Uint8Array(n):this.opacityBuffer.fill(0,0,n);let s=this.opacityBuffer,o=this.visibleLayersBuffer;o.length=0;for(let l=0;l<t.length;l++){let u=t[l];this.isLayerVisible(e,u.getOrigin())&&o.push(u)}for(let l=0;l<e.height;l++)for(let u=0;u<e.width;u++){let c=l*e.width+u;if(s[c])continue;let d=e.x+u,h=e.y+l;for(let f=0;f<o.length;f++){let p=o[f],m=d-p.getOrigin().x,S=h-p.getOrigin().y,w=p.getWidth(),g=p.getHeight();if(m<0||m>=w||S<0||S>=g)continue;let y=S*w+m,C=p.getData(),x=C.getCharCode(y),I=C.getFgColorCode(y),E=C.getBgColorCode(y),A=i[c];if(x!==0&&A.char===" "&&(A.char=Ts.getChar(x)),I!==255&&A.fgColorIndex===255&&(A.fgColorIndex=I,A.fgEmission=this.getColorEmission(I)),E!==255){A.bgColorIndex===255&&(A.bgColorIndex=E,A.bgEmission=this.getColorEmission(E)),s[c]=1;break}}}let a=new Array(n);for(let l=0;l<n;l++)a[l]={char:i[l].char,fgColorIndex:i[l].fgColorIndex,bgColorIndex:i[l].bgColorIndex,fgEmission:i[l].fgEmission,bgEmission:i[l].bgEmission};return{id:e.id,width:e.width,height:e.height,cells:a,palette:this.colorCache}}calculateIntersection(e,t){let n=e.x,i=e.x+e.width,s=e.y,o=e.y+e.height,a=t.x,l=t.x+256,u=t.y,c=t.y+256,d=Math.max(n,a),h=Math.min(i,l),f=Math.max(s,u),p=Math.min(o,c);return{visible:d<h&&f<p,originStart:{x:d-e.x,y:f-e.y},originEnd:{x:h-e.x,y:p-e.y},layerStart:{x:d-t.x,y:f-t.y},layerEnd:{x:h-t.x,y:p-t.y}}}};J(nh,"DisplayRasterizer"),D(nh,"charCache",(()=>{let r=new Map;for(let e=0;e<256;e++)r.set(e,String.fromCharCode(e));return r})());var VI=nh,Rv=class{constructor(){D(this,"enabled",!1),D(this,"currentStats",null)}setEnabled(e){this.enabled=e,e||(this.currentStats=null)}isEnabled(){return this.enabled}get tick(){var e;return((e=this.currentStats)==null?void 0:e.tick)??0}get timestamp(){var e;return((e=this.currentStats)==null?void 0:e.timestamp)??0}get totalOrders(){var e;return((e=this.currentStats)==null?void 0:e.totalOrders)??0}get ordersByLayer(){var e;return((e=this.currentStats)==null?void 0:e.ordersByLayer)??new Map}get ordersByType(){var e;return((e=this.currentStats)==null?void 0:e.ordersByType)??new Map}get totalLayers(){var e;return((e=this.currentStats)==null?void 0:e.totalLayers)??0}get visibleLayers(){var e;return((e=this.currentStats)==null?void 0:e.visibleLayers)??0}get layersPerDisplay(){var e;return((e=this.currentStats)==null?void 0:e.layersPerDisplay)??new Map}get displayCompositeLayerIds(){var e;return((e=this.currentStats)==null?void 0:e.displayCompositeLayerIds)??new Map}get updatePacketSize(){var e;return((e=this.currentStats)==null?void 0:e.updatePacketSize)??0}get displayHeaderSize(){var e;return((e=this.currentStats)==null?void 0:e.displayHeaderSize)??0}get layerHeaderSize(){var e;return((e=this.currentStats)==null?void 0:e.layerHeaderSize)??0}get orderDataSize(){var e;return((e=this.currentStats)==null?void 0:e.orderDataSize)??0}get compressionRatio(){var e;return((e=this.currentStats)==null?void 0:e.compressionRatio)??0}get compressedPacketSize(){return Math.round(this.updatePacketSize*this.compressionRatio)}get totalCells(){var e;return((e=this.currentStats)==null?void 0:e.totalCells)??0}get nonEmptyCells(){var e;return((e=this.currentStats)==null?void 0:e.nonEmptyCells)??0}get cellsWithBackground(){var e;return((e=this.currentStats)==null?void 0:e.cellsWithBackground)??0}get rasterizationTimeMs(){var e;return((e=this.currentStats)==null?void 0:e.rasterizationTimeMs)??0}get encodingTimeMs(){var e;return((e=this.currentStats)==null?void 0:e.encodingTimeMs)??0}get packetSplit(){var e;return(e=this.currentStats)==null?void 0:e.packetSplit}get layerDetails(){var e;return(e=this.currentStats)==null?void 0:e.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 n of t){let i=this.currentStats.ordersByType.get(n.type)||0;this.currentStats.ordersByType.set(n.type,i+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,n,i){!this.enabled||!this.currentStats||(this.currentStats.updatePacketSize=e,this.currentStats.displayHeaderSize=t,this.currentStats.layerHeaderSize=n,this.currentStats.orderDataSize=i,this.currentStats.compressionRatio=.25)}recordPacketSplit(e,t,n,i){!this.enabled||!this.currentStats||(this.currentStats.packetSplit={userId:e,displayCount:t,staticLayerCount:n,dynamicLayerCount:i})}recordLayerInfo(e,t,n,i){!this.enabled||!this.currentStats||(this.currentStats.layerDetails||(this.currentStats.layerDetails=[]),this.currentStats.layerDetails.push({layerId:e,mustBeReliable:t,orderCount:n,updateFlags:i}))}recordRenderStats(e,t,n){!this.enabled||!this.currentStats||(this.currentStats.totalCells=e,this.currentStats.nonEmptyCells=t,this.currentStats.cellsWithBackground=n)}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}};J(Rv,"CoreStats");var HI=Rv,Pv=[[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]],jI=new Map(Pv);new Map(Pv.map(([r,e])=>[e,r]));function Qs(r){if(r<128)return r;let e=jI.get(r);return e!==void 0?e:r&255}J(Qs,"unicodeToCp437");var Bv=class{constructor(){D(this,"unicolorSprites",new Map),D(this,"multicolorSprites",new Map)}loadUnicolorSprites(e){if("loadType"in e){this.loadUnicolorSpritesFromPacket(e);return}for(let t of e){let{spriteId:n,sizeX:i,sizeY:s,data:o}=t,a=new Vg(i*s);if(typeof o=="string"){let u=o.replace(/\n/g,"");for(let c=0;c<Math.min(u.length,i*s);c++)a.set(c,Qs(u.charCodeAt(c)))}else if(Array.isArray(o)&&o.length>0&&typeof o[0]=="string"){let u=o;for(let c=0;c<Math.min(u.length,s);c++){let d=u[c];if(d)for(let h=0;h<Math.min(d.length,i);h++)a.set(c*i+h,Qs(d.charCodeAt(h)))}}else{let u=o;for(let c=0;c<Math.min(u.length,i*s);c++)a.set(c,u[c])}let l={id:n,sizeX:i,sizeY:s,data:a};this.unicolorSprites.set(l.id,l)}}loadUnicolorSpritesFromPacket(e){for(let t of e.sprites){let n=new Vg(t.sizeX*t.sizeY);for(let s=0;s<t.data.length;s++)n.set(s,t.data[s]);let i={id:t.spriteId,sizeX:t.sizeX,sizeY:t.sizeY,data:n};this.unicolorSprites.set(i.id,i)}}loadMulticolorSprites(e){if("loadType"in e){this.loadMulticolorSpritesFromPacket(e);return}for(let t of e){let{spriteId:n,sizeX:i,sizeY:s,data:o}=t,a=new th(i*s);for(let u=0;u<Math.min(o.length,i*s);u++){let c=o[u],d=typeof c.charCode=="string"?Qs(c.charCode.charCodeAt(0)):c.charCode;a.set(u,d,c.fgColorId,c.bgColorId)}let l={id:n,sizeX:i,sizeY:s,data:a};this.multicolorSprites.set(l.id,l)}}loadMulticolorSpritesFromPacket(e){for(let t of e.sprites){let n=new th(t.sizeX*t.sizeY);for(let s=0;s<t.data.length;s++){let o=t.data[s];n.set(s,o.charCode,o.fgColorId,o.bgColorId)}let i={id:t.spriteId,sizeX:t.sizeX,sizeY:t.sizeY,data:n};this.multicolorSprites.set(i.id,i)}}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}};J(Bv,"SpriteRegistry");var YI=Bv,WI=(r=>(r.Bitmap="bitmap",r.Image="image",r))(WI||{});function Ef(r){return Math.sqrt(r)*16}J(Ef,"getAtlasColumns");function zv(r){return r*256-1}J(zv,"getMaxCharCode");function GI(r,e){let t=Ef(r)*e;return{width:t,height:t}}J(GI,"getAtlasDimensions");var Dv=class{constructor(e,t){this.fontId=e,this.config=t,D(this,"atlasColumns"),D(this,"maxCharCode"),D(this,"blocks",new Map),this.atlasColumns=Ef(t.atlasBlocks),this.maxCharCode=zv(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,n=Math.floor(e/this.atlasColumns),i=t/this.atlasColumns,s=n/this.atlasColumns,o=(t+1)/this.atlasColumns,a=(n+1)/this.atlasColumns;return{u1:i,v1:s,u2:o,v2:a}}isValidCharCode(e){return e>=0&&e<=this.maxCharCode}};J(Dv,"ImageFont");var qg=Dv,Ov=class{constructor(){D(this,"fonts",new Map),D(this,"nameToId",new Map),D(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 n=this.allocateId(e),i={glyphWidth:t.glyphWidth,glyphHeight:t.glyphHeight,cellWidth:t.cellWidth,cellHeight:t.cellHeight,atlasBlocks:t.atlasBlocks??1},s=new qg(n,i);return this.fonts.set(n,s),this.nameToId.set(e,n),n}addBlock(e,t,n){let i=this.fonts.get(e);if(!i)throw new Error(`ImageFont with ID ${e} not found`);i.addBlock(t,n)}loadFont(e,t){if(this.fonts.has(e))throw new Error(`ImageFont with ID ${e} already exists`);let n=new qg(e,t);this.fonts.set(e,n),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,n]of this.nameToId.entries())if(n===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[t,n]of this.nameToId.entries())if(n===e){this.nameToId.delete(t);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}};J(Ov,"ImageFontRegistry");var XI=Ov,Fv=class{constructor(){D(this,"sounds",new Map),D(this,"nameToId",new Map),D(this,"nextId",0)}registerFile(e,t,n){let i=this.allocateId(e),s={soundId:i,name:e,loadType:"file",format:t,data:n};return this.sounds.set(i,s),this.nameToId.set(e,i),i}registerFileWithId(e,t,n,i){this.validateId(e),this.checkIdAvailable(e,t);let s={soundId:e,name:t,loadType:"file",format:n,data:i};this.sounds.set(e,s),this.nameToId.set(t,e)}registerExternal(e,t,n,i,s){let o=this.allocateId(e),a={soundId:o,name:e,loadType:"external",format:t,url:n,size:i,checksum:s};return this.sounds.set(o,a),this.nameToId.set(e,o),o}registerExternalWithId(e,t,n,i,s,o){this.validateId(e),this.checkIdAvailable(e,t);let a={soundId:e,name:t,loadType:"external",format:n,url:i,size:s,checksum:o};this.sounds.set(e,a),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,n=this.getFileSounds();if(n.length>0){let s=n.map(o=>({soundId:o.soundId,name:o.name,format:o.format,data:o.data}));e.push({type:"sound",mode:"file",sounds:s,totalSounds:t})}let i=this.getExternalSounds();if(i.length>0){let s=i.map(o=>({soundId:o.soundId,name:o.name,format:o.format,url:o.url,size:o.size,checksum:o.checksum}));e.push({type:"sound",mode:"external",sounds:s,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(i=>i.loadType==="file"),n=t.reduce((i,s)=>{var o;return i+(((o=s.data)==null?void 0:o.length)??0)},0);return{total:e.length,file:t.length,external:e.length-t.length,totalFileSize:n}}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 n=this.sounds.get(e);throw new Error(`Sound ID ${e} is already used by "${n.name}". Cannot register "${t}".`)}if(this.nameToId.has(t))throw new Error(`Sound with name "${t}" already exists`)}};J(Fv,"SoundRegistry");var KI=Fv,Lv=class{constructor(e){this.soundRegistry=e}collectFromUser(e){let t=[],n=e.flushSoundCommands();for(let s of n){let o=this.convertSoundCommand(s);o&&t.push(o)}let i=e.flushAudioConfigCommands();for(let s of i){let o=this.convertConfigCommand(s);o&&t.push(o)}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 n=0;e.loop&&(n|=1),e.volume!==void 0&&(n|=2),e.pitch!==void 0&&(n|=4),e.fadeIn!==void 0&&(n|=8),e.lowpass!==void 0&&e.lowpass>0&&(n|=32),e.highpass!==void 0&&e.highpass>0&&(n|=64),e.reverb!==void 0&&e.reverb>0&&(n|=128);let i=e.x!==void 0&&e.y!==void 0;return i&&(n|=16),i?{type:1,soundId:t,instanceId:e.instanceId??0,flags:n,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:n&-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:n}=this.resolveTarget(e.sound);return{type:3,targetType:t,target:n}}convertFadeOutCommand(e){let{targetType:t,target:n}=this.resolveTarget(e.sound);return{type:4,targetType:t,duration:this.encodeFadeTime(e.duration),target:n}}convertPauseCommand(e){let{targetType:t,target:n}=this.resolveTarget(e.sound);return{type:5,targetType:t,target:n}}convertResumeCommand(e){let{targetType:t,target:n}=this.resolveTarget(e.sound);return{type:6,targetType:t,target:n}}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)),n=64*Math.log2(t/.25);return Math.round(Math.max(0,Math.min(255,n)))}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)}};J(Lv,"AudioOrderCollector");var ZI=Lv,_v=class{collectFromUser(e){let t=[];if(e.hasMobileVibrationCommands()){let n=e.flushMobileVibrationCommands();for(let i of n){let s=this.convertMobileCommand(i);s&&t.push(s)}}if(e.hasGamepadVibrationCommands()){let n=e.flushGamepadVibrationCommands();for(let i of n){let s=this.convertGamepadCommand(i);s&&t.push(s)}}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 n=e.pattern,i=Array.isArray(n)?[...n]:[n],s={type:1,flags:t,pattern:i.map(o=>Math.round(o))};return t&1&&(s.intensity=Math.round(Math.min(1,Math.max(0,e.intensity))*255)/255),s}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:n}=e,i=0;n.startDelay!==void 0&&n.startDelay>0&&(i|=1);let s=t==="all"?255:t;t==="all"&&(i|=2);let o={type:16,flags:i,gamepadIndex:s,duration:Math.round(n.duration),strongMagnitude:Math.round(Math.min(1,Math.max(0,n.strongMagnitude??1))*255),weakMagnitude:Math.round(Math.min(1,Math.max(0,n.weakMagnitude??.5))*255)};return n.startDelay!==void 0&&n.startDelay>0&&(o.startDelay=Math.round(n.startDelay)),o}convertGamepadCancelCommand(e){let{gamepadIndex:t}=e,n=0,i=t==="all"?255:t;return t==="all"&&(n|=2),{type:17,flags:n,gamepadIndex:i}}};J(_v,"VibrationOrderCollector");var qI=_v,$v=class{collectFromUser(e){let t=e.flushPostProcessCommands();return this.convertCommands(t)}convertCommands(e){let t=[];for(let n of e){let i=this.convertCommand(n);i&&t.push(i)}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??Ge.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){var s,o,a;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 n=0,i={type:1,displayId:t,flags:0};if(e.config.scanlines){n|=1;let l=e.config.scanlines;i.scanlines={enabled:l.enabled,opacity:l.opacity??Ge.scanlines.opacity,pattern:this.patternToType(l.pattern??"horizontal"),colorR:((s=l.color)==null?void 0:s.r)??0,colorG:((o=l.color)==null?void 0:o.g)??0,colorB:((a=l.color)==null?void 0:a.b)??0}}if(e.config.ambientEffect){n|=2;let l=e.config.ambientEffect;i.ambientEffect={enabled:l.enabled,blur:l.blur??Ge.ambientEffect.blur,scale:l.scale??Ge.ambientEffect.scale,opacity:l.opacity??Ge.ambientEffect.opacity}}return i.flags=n,i}createSetScanlinesOrder(e,t,n){return{type:2,displayId:e,enabled:t,opacity:n??Ge.scanlines.opacity,pattern:0,colorR:0,colorG:0,colorB:0}}createSetAmbientEffectOrder(e,t,n,i){return{type:3,displayId:e,enabled:t,blur:n??Ge.ambientEffect.blur,scale:i??Ge.ambientEffect.scale,opacity:Ge.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:E1(t)}}createSetGridOrder(e,t){let{r:n,g:i,b:s,a:o}=this.parseColor(t.color??js.color);return{type:5,displayId:e,enabled:t.enabled,colorR:n,colorG:i,colorB:s,colorA:o,lineWidth:t.lineWidth??js.lineWidth}}createSwitchPaletteOrder(e,t){return{type:6,displayId:e,slotId:t}}createSetCellSizeOrder(e,t,n){return{type:7,displayId:e,cellWidth:t,cellHeight:n}}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 n=e.match(/^#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})$/);if(n){let i=n[1];return i.length===3?{r:parseInt(i[0]+i[0],16),g:parseInt(i[1]+i[1],16),b:parseInt(i[2]+i[2],16),a:255}:{r:parseInt(i.slice(0,2),16),g:parseInt(i.slice(2,4),16),b:parseInt(i.slice(4,6),16),a:255}}return{r:144,g:24,b:24,a:255}}};J($v,"PostProcessOrderCollector");var Mf=$v,ih=class sh{constructor(e={}){D(this,"mode"),D(this,"maxUsers"),D(this,"strictMode",!1),D(this,"currentTick",0),D(this,"stats",new HI),D(this,"spriteRegistry",new YI),D(this,"imageFontRegistry",new XI),D(this,"soundRegistry",new KI),D(this,"audioOrderCollector",new ZI(this.soundRegistry)),D(this,"vibrationOrderCollector",new qI),D(this,"postProcessOrderCollector",new Mf),D(this,"encoder",new EI),D(this,"users",new Map),D(this,"colorPalette",new Map),D(this,"paletteSlots",new Map),D(this,"displayRasterizer",new VI(this)),D(this,"updatePacketDecoder",new NI),D(this,"loadDecoder",new TI),D(this,"cachedLoadPackets",null),D(this,"_renderCallCount",0),D(this,"onPaletteChangedCallback"),D(this,"onFontAllocatedCallback"),D(this,"onFontBlockAddedCallback"),D(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((e,t)=>this.colorPalette.set(t,{...e,a:255,e:0})),sh.ANSI_VGA_COLORS.forEach(e=>this.colorPalette.set(e.colorId,e)),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 n=new vI(e,t,this.mode);return n.setSpriteRegistry(this.spriteRegistry),this.users.set(e,n),n}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,n,i,s=255,o=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||n<0||n>255||i<0||i>255||s<0||s>255||o<0||o>255)throw new Error("Color components must be between 0 and 255");this.colorPalette.set(e,{r:t,g:n,b:i,a:s,e:o}),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 n=new Map;for(let i of t)i.colorId<0||i.colorId>255||n.set(i.colorId,{r:i.r,g:i.g,b:i.b,a:i.a??255,e:i.e??0});sh.ANSI_VGA_COLORS.forEach(i=>{n.set(i.colorId,{r:i.r,g:i.g,b:i.b,a:i.a,e:i.e})}),n.set(255,{r:0,g:0,b:0,a:0,e:0}),this.paletteSlots.set(e,n)}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 n=t.a/255;return`rgba(${t.r}, ${t.g}, ${t.b}, ${n})`}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,n=0;return this.users.forEach((i,s)=>{let o=i.getLayers(),a=i.getDisplays();t+=o.length,i.getStats().isEnabled()&&i.getStats().startTick(this.currentTick);let l=a.map(w=>{let g=w.getOrigin(),y=w.getSize();return{id:w.getId(),originX:g.x,originY:g.y,sizeX:y.x,sizeY:y.y,renderPasses:w.getRenderPasses()}});a.forEach(w=>w.resetChangeTracking());let u=[],c=[];o.forEach((w,g)=>{if(!w.getNeedsCommit())return;let y=w.getOrigin(),C=w.getOrders(),x=w.getMustBeReliable(),I=w.calculateUpdateFlags();w.resetChangeTracking(),w.resetCommit(),w.getId()===0&&Aa(w,g);let E={id:w.getId(),updateFlags:I,zIndex:w.getZOrder(),originX:y.x,originY:y.y,width:w.getWidth(),height:w.getHeight(),isMacroLayer:w.getIsMacroLayer(),is16bit:w.getCharCodeMode()==="16bit",orderCount:C.length,orders:C};C.length>0&&this.stats.isEnabled()&&this.stats.recordLayerInfo(w.getId(),x,C.length,I),x?u.push(E):c.push(E)}),n+=u.length+c.length;let d=this.audioOrderCollector.collectFromUser(i),h=this.vibrationOrderCollector.collectFromUser(i),f=this.postProcessOrderCollector.collectFromUser(i),p=i.flushMacroOrders(),m=null,S=null;if(this.stats.isEnabled()&&this.stats.recordPacketSplit(s,l.length,u.length,c.length),(u.length>0||d.length>0||p.length>0)&&(m=this.encoder.encode({tick:this.currentTick,displayCount:l.length,displays:l,layerCount:u.length,layers:u,audioOrderCount:d.length,audioOrders:d,vibrationOrderCount:0,vibrationOrders:[],macroOrderCount:p.length,macroOrders:p,postProcessOrderCount:0,postProcessOrders:[]})),S=this.encoder.encode({tick:this.currentTick,displayCount:l.length,displays:l,layerCount:c.length,layers:c,audioOrderCount:0,audioOrders:[],vibrationOrderCount:h.length,vibrationOrders:h,macroOrderCount:0,macroOrders:[],postProcessOrderCount:f.length,postProcessOrders:f}),e.set(s,{static:m,dynamic:S}),i.getStats().isEnabled()){let w=a.reduce((x,I)=>{let E=I.getSize();return x+E.x*E.y},0);i.getStats().recordDisplays(a.length,w),i.getStats().recordLayers(o.length,u.length+c.length,u.length,c.length),[...u,...c].forEach(x=>{i.getStats().recordLayerOrders(x.id,x.orders.length)});let g=(m==null?void 0:m.length)||0,y=(S==null?void 0:S.length)||0;i.getStats().recordPacketSizes(g,y);let C=i.getInputBindingRegistry();i.getStats().recordInput(!1,C.getAxisCount(),C.getButtonCount()),i.getStats().endTick()}if(i.endTickBytes(),this.stats.isEnabled()){let w=[...u,...c];w.forEach((I,E)=>{this.stats.recordLayerOrders(E,I.orders)}),a.forEach((I,E)=>{this.stats.recordDisplayLayers(E,w.length)});let g=((m==null?void 0:m.length)||0)+((S==null?void 0:S.length)||0),y=l.reduce((I,E)=>{var R;let A=Math.min(((R=E.renderPasses)==null?void 0:R.length)??0,4);return I+8+A*4},0),C=w.length*20,x=g-y-C;this.stats.recordUpdatePacketSize(g,y,C,x>0?x:0)}}),this.stats.isEnabled()&&(this.stats.recordLayers(t,n),this.stats.endTick()),this.currentTick++,e}getSnapshot(e){let t=this.getUser(e);if(!t)return null;let n=t.getDisplays(),i=t.getLayers(),s=n.map((a,l)=>{let u=a.getOrigin(),c=a.getSize();return{id:l,originX:u.x,originY:u.y,sizeX:c.x,sizeY:c.y,renderPasses:a.getRenderPasses()}}),o=i.map((a,l)=>{let u=a.getOrigin(),c=a.getOrders();return a.getId()===0&&Aa(a,l),{id:a.getId(),updateFlags:7,zIndex:a.getZOrder(),originX:u.x,originY:u.y,width:a.getWidth(),height:a.getHeight(),isMacroLayer:a.getIsMacroLayer(),is16bit:a.getCharCodeMode()==="16bit",orderCount:c.length,orders:c}});return this.encoder.encode({tick:this.currentTick,displayCount:s.length,displays:s,layerCount:o.length,layers:o,audioOrderCount:0,audioOrders:[],vibrationOrderCount:0,vibrationOrders:[],macroOrderCount:0,macroOrders:[],postProcessOrderCount:0,postProcessOrders:[]})}resetTick(){this.currentTick=0}applyUpdatePacket(e,t){let n=this.getUser(e);if(!n){if(this.strictMode)throw new Error(`Cannot apply update packet: user ${e} does not exist`);return!1}return n.applyUpdate(t),t.audioOrders&&t.audioOrders.length>0&&n.applyAudioOrders(t.audioOrders),t.vibrationOrders&&t.vibrationOrders.length>0&&n.applyVibrationOrders(t.vibrationOrders),!0}applyUpdatePacketBuffer(e,t){let n=this.updatePacketDecoder.decode(t);return this.applyUpdatePacket(e,n)?n:null}applyLoadPacket(e){try{let t=this.loadDecoder.decode(e).load;switch(t.loadType){case 1:t.slotId!==void 0?this.loadPaletteToSlot(t.slotId,t.colors):(console.warn("[Core] ColorPalette load without slotId is deprecated. Loading into slot 0."),this.loadPaletteToSlot(0,t.colors));break;case 2:this.spriteRegistry.loadUnicolorSprites(t);break;case 3:this.spriteRegistry.loadMulticolorSprites(t);break;case 5:console.warn("[Core] Sound loading not yet implemented");break;case 8:this.loadFont(t.glyphWidth,t.glyphHeight,t.atlasBlocks,t.cellWidth,t.cellHeight);break;case 9:this.loadFontBlock(t.blockIndex,t.imageData);break;case 7:{for(let n of this.users.values())n.loadMacroTemplate(t.macroId,t.template);break}default:return console.error(`[Core] Unknown LoadType: ${t.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 n=new Lc,i=[];return t.forEach((s,o)=>{o!==255&&i.push({colorId:o,r:s.r,g:s.g,b:s.b,a:s.a,e:s.e})}),n.encode({loadType:1,slotId:e,colors:i})}generateAllPaletteSlotLoadPackets(){let e=[];return this.paletteSlots.forEach((t,n)=>{let i=this.generatePaletteSlotLoadPacket(n);i&&e.push(i)}),e}generateUnicolorSpritesLoadPacket(){if(this.spriteRegistry.getUnicolorSpriteCount()===0)return null;let e=[];for(let t=0;t<=255;t++){let n=this.spriteRegistry.getUnicolorSprite(t);if(n){let i=[];for(let s=0;s<n.sizeX*n.sizeY;s++)i.push(n.data.get(s));e.push({spriteId:n.id,sizeX:n.sizeX,sizeY:n.sizeY,data:i})}}return e.length===0?null:new Lc().encode({loadType:2,sprites:e})}generateMulticolorSpritesLoadPacket(){let e=this.getSpriteRegistry(),t=[];for(let n=0;n<=255;n++){let i=e.getMulticolorSprite(n);if(i){let s=[];for(let o=0;o<i.sizeX*i.sizeY;o++){let a=i.data.get(o);s.push({charCode:a.charCode,fgColorId:a.fgColorCode,bgColorId:a.bgColorCode})}t.push({spriteId:i.id,sizeX:i.sizeX,sizeY:i.sizeY,data:s})}}return t.length===0?null:new Lc().encode({loadType:3,sprites:t})}generateAllLoadPackets(){if(this.cachedLoadPackets)return this.cachedLoadPackets;let e=[],t=this.generateAllPaletteSlotLoadPackets();e.push(...t);let n=this.generateUnicolorSpritesLoadPacket();n&&e.push(n);let i=this.generateMulticolorSpritesLoadPacket();return i&&e.push(i),this.cachedLoadPackets=e,e}generateMacroLoadPackets(e){let t=this.getUser(e);if(!t)return[];let n=t.getMacroLoads();if(n.length===0)return[];let i=new UI;return n.map(s=>i.encode(s))}generateInitialUpdatePacket(e){let t=this.getUser(e);if(!t||!t.hasPostProcessCommands())return null;let n=this.postProcessOrderCollector.collectFromUser(t);if(n.length===0)return null;let i=t.getDisplays().map(s=>{let o=s.getSize();return{id:s.getId(),originX:0,originY:0,sizeX:o.x,sizeY:o.y}});return this.encoder.encode({tick:0,displayCount:i.length,displays:i,layerCount:0,layers:[],audioOrderCount:0,audioOrders:[],vibrationOrderCount:0,vibrationOrders:[],macroOrderCount:0,macroOrders:[],postProcessOrderCount:n.length,postProcessOrders:n})}applyInputBindingsLoadPacket(e,t){let n=this.getUser(e);if(!n){if(this.strictMode)throw new Error(`Cannot apply input bindings: user ${e} does not exist`);return!1}try{return n.applyInputBindingsLoadPacket(t),!0}catch(i){return console.error(`[Core] Failed to apply input bindings for user ${e}:`,i),!1}}getRenderState(e,t){let n=this.getUser(e);if(!n)return null;let i=n.getDisplays(),s=t?n.getLayers().filter(t):n.getLayers(),o=performance.now(),a=[];for(let l of i){if(!l)continue;let u=l.getOrigin(),c=l.getSize();if(a.push(this.displayRasterizer.rasterize({id:l.getId(),x:u.x,y:u.y,width:c.x,height:c.y},s,l.getRenderPasses())),this.stats.isEnabled()){let d=l.getId();this.stats.recordDisplayComposite(d,this.displayRasterizer.getLastVisibleLayerIds())}}return performance.now()-o,this._renderCallCount||(this._renderCallCount=0),this._renderCallCount++,{userId:n.id,userName:n.name,tick:this.currentTick,displays:a}}getAllRenderStates(){let e=new Map;return this.users.forEach((t,n)=>{let i=this.getRenderState(n);i&&e.set(n,i)}),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,n,i,s){let o={glyphWidth:e,glyphHeight:t,cellWidth:i,cellHeight:s,atlasBlocks:n};this.imageFontRegistry.hasFont(0)&&this.imageFontRegistry.unloadFont(0),this.imageFontRegistry.loadFont(0,o),this.onFontAllocatedCallback&&this.onFontAllocatedCallback()}loadFontBlock(e,t){if(typeof t=="string")return this.readResource(t).then(n=>{this.imageFontRegistry.addBlock(0,e,n),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 n=this.detectSoundFormat(t),i=await this.readResource(t);return this.soundRegistry.registerFile(e,n,i)}async loadSounds(e){let t={},n=Object.entries(e).map(async([i,s])=>{let o=await this.loadSound(i,s);t[i]=o});return await Promise.all(n),t}detectSoundFormat(e){var s;let t=((s=e.split(".").pop())==null?void 0:s.toLowerCase())??"",n={mp3:"mp3",wav:"wav",ogg:"ogg",webm:"webm",aac:"aac",m4a:"aac"},i=n[t];if(!i)throw new Error(`Unsupported audio format: .${t}. Supported: ${Object.keys(n).join(", ")}`);return i}async readResource(e){let t=globalThis,n=typeof t.window<"u"||typeof t.document<"u",i=typeof t.fetch=="function",s=/^https?:\/\//i.test(e),o=e.startsWith("file:");if(n)try{let f=await fetch(e);if(!f.ok)throw new Error(`HTTP ${f.status}: ${f.statusText}`);let p=await f.arrayBuffer();return new Uint8Array(p)}catch(f){let p=f instanceof Error?f.message:String(f);throw new Error(`Failed to load resource "${e}": ${p}`)}if((s||o)&&i)try{let f=await fetch(e);if(!f.ok)throw new Error(`HTTP ${f.status}: ${f.statusText}`);let p=await f.arrayBuffer();return new Uint8Array(p)}catch(f){let p=f instanceof Error?f.message:String(f);throw new Error(`Failed to load resource "${e}": ${p}`)}let a=typeof ll<"u"?ll:null;if(!a)throw new Error("Node.js require is not available");let l="fs",u=a("path"),c=a(l),d=u.resolve(e),h=c.readFileSync(d);return new Uint8Array(h)}registerSound(e,t,n){return this.soundRegistry.registerFile(e,t,n)}registerExternalSound(e,t,n,i){return this.soundRegistry.registerExternal(e,t,n,i)}hasSound(e){return this.soundRegistry.has(e)}generateSoundLoadPackets(){return this.soundRegistry.toLoadPackets()}async loadImageFont(e,t,n){let i=await this.loadImageData(t),s=this.imageFontRegistry.registerFont(e,n);return this.imageFontRegistry.addBlock(0,0,i),this.onFontAllocatedCallback&&this.onFontAllocatedCallback(),this.onFontBlockAddedCallback&&this.onFontBlockAddedCallback(0),this.onImageFontChangedCallback&&this.onImageFontChangedCallback(0),s}async loadImageFonts(e){let t={},n=Object.entries(e).map(async([i,{path:s,options:o}])=>{let a=await this.loadImageFont(i,s,o);t[i]=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 i=await n.arrayBuffer();return new Uint8Array(i)}catch(n){let i=n instanceof Error?n.message:String(n);throw new Error(`Failed to load image font "${e}": ${i}`)}else{let n=typeof ll<"u"?ll:null;if(!n)throw new Error("Node.js require is not available");let i=n("fs").readFileSync(e);return new Uint8Array(i)}}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()}};J(ih,"Core"),D(ih,"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 Nv=ih,Ru=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 QI(r){return Ru.get(r)}J(QI,"getCharBitmap");function JI(r){return Ru.has(r)}J(JI,"hasChar");function ek(){return Array.from(Ru.keys()).sort((r,e)=>r-e)}J(ek,"getAllCharCodes");function tk(){return{charWidth:8,charHeight:8,glyphs:new Map(Ru)}}J(tk,"getASCII8x8FontConfig");var Vv=class{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=ie.allocUnsafe(2);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.toUint8Array()}encodeChange(e){if(typeof e.value=="boolean"){let t=ie.allocUnsafe(4);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.writeUInt8(1,2),t.writeUInt8(e.value?1:0,3),t.toUint8Array()}else{let t=ie.allocUnsafe(7);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.writeUInt8(0,2),t.writeFloatBE(e.value,3),t.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 n=4+t.length,i=ie.allocUnsafe(n),s=0;return i.writeUInt8(e.type,s++),i.writeUInt8(e.instanceId,s++),i.writeUInt16BE(t.length,s),s+=2,i.toUint8Array().set(t,s),i.toUint8Array()}calculateSubmitSize(e){return 4+new TextEncoder().encode(e.text).length}encodeSelect(e){let t=ie.allocUnsafe(4);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.writeUInt16BE(e.index,2),t.toUint8Array()}};J(Vv,"MacroEventEncoder");var rk=Vv;function Hv(r,e,t,n,i,s,o,a=[],l=[],u=[],c=[],d=!1){let h=Array.from(e.entries()).sort((T,_)=>T[0]-_[0]),f=Array.from(t.entries()).sort((T,_)=>T[0]-_[0]),p=h.length,m=f.length,S=sv(p,m),w=new TextEncoder,g=a.map(T=>w.encode(T)),y=1+g.reduce((T,_)=>T+1+_.length,0),C=new rk,x=l.map(T=>C.encode(T)),I=1+x.reduce((T,_)=>T+_.length,0),E=Math.min(u.length,255),A=1+E*5,R=Math.min(c.length,10),F=1+R*4,z=S+y+I+A+F,P=new Uint8Array(z),O=new DataView(P.buffer),L=0;O.setBigUint64(L,r,!0),L+=8;for(let[,T]of h){let _=nv(T);P[L]=_+256&255,L+=1}let V=Tu(m);for(let T=0;T<V;T++){let _=0;for(let j=0;j<8;j++){let G=T*8+j;if(G<m){let[,ee]=f[G];ee&&(_|=1<<j)}}P[L]=_,L+=1}P[L]=n&255,L+=1,P[L]=i&255,L+=1,P[L]=s&255,L+=1;let X=0;o&&(X|=1),d&&(X|=2),P[L]=X,L+=1,P[L]=Math.min(a.length,255),L+=1;for(let T of g)P[L]=Math.min(T.length,255),L+=1,P.set(T.slice(0,255),L),L+=T.length;P[L]=Math.min(l.length,255),L+=1;for(let T of x)P.set(T,L),L+=T.length;P[L]=E,L+=1;for(let T=0;T<E;T++){let _=u[T];P[L]=_.displayId&255,L+=1,O.setUint16(L,Math.min(_.pixelWidth,65535),!1),L+=2,O.setUint16(L,Math.min(_.pixelHeight,65535),!1),L+=2}P[L]=R,L+=1;for(let T=0;T<R;T++){let _=c[T];P[L]=_.id&15,L+=1,P[L]=_.x&255,L+=1,P[L]=_.y&255,L+=1,P[L]=_.over?1:0,L+=1}return P}J(Hv,"encodeCompressedInput");var nk=class gt{static toCharCode(e){if(typeof e=="number")return e&65535;if(e.length===0)return 0;let t=e.charCodeAt(0);return Qs(t)}static dedent(e){let t=e.split(`
|
|
52
|
+
`}),e}};J(tv,"InputBindingRegistry");var fI=tv;function rv(r=0n){return{tick:r,axes:new Map,buttons:new Map,displayId:0,mouseX:0,mouseY:0,mouseOverDisplay:!1,textInputs:[],macroEvents:[],displayViewports:[],touchPositions:[],isTabHidden:!1}}J(rv,"createEmptyCompressedInputPacket");function nv(r){let e=Math.max(-1,Math.min(1,r));return Math.round(e*127)}J(nv,"encodeAxisToInt8");function iv(r){return r/127}J(iv,"decodeInt8ToAxis");function Tu(r){return r===0?0:Math.ceil(r/8)}J(Tu,"getButtonByteCount");function sv(r,e){let t=r,n=Tu(e);return 8+t+n+4}J(sv,"getCompressedPacketSize");var ov=class{decode(e,t=0){let n=e.readUInt8(t);switch(n){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${n.toString(16)}`)}}decodeAll(e,t,n){let i=[],s=0;for(let o=0;o<n;o++){let{event:a,bytesRead:l}=this.decode(e,t+s);i.push(a),s+=l}return{events:i,bytesRead:s}}decodeClick(e,t){let n=e.readUInt8(t),i=e.readUInt8(t+1);return{event:{type:n,instanceId:i},bytesRead:2}}decodeChange(e,t){let n=e.readUInt8(t),i=e.readUInt8(t+1),s=e.readUInt8(t+2),o,a;return s===1?(o=e.readUInt8(t+3)===1,a=4):(o=e.readFloatBE(t+3),a=7),{event:{type:n,instanceId:i,value:o},bytesRead:a}}decodeSubmit(e,t){let n=t,i=e.readUInt8(t++),s=e.readUInt8(t++),o=e.readUInt16BE(t);t+=2;let a=e.toUint8Array().subarray(t,t+o);t+=o;let l=new TextDecoder().decode(a);return{event:{type:i,instanceId:s,text:l},bytesRead:t-n}}decodeSelect(e,t){let n=e.readUInt8(t),i=e.readUInt8(t+1),s=e.readUInt16BE(t+2);return{event:{type:n,instanceId:i,index:s},bytesRead:4}}};J(ov,"MacroEventDecoder");var pI=ov,av=class Zi{constructor(e){D(this,"data"),D(this,"view"),this.data=new Uint8Array(e),this.view=new DataView(this.data.buffer)}static from(e){let t=new Zi(0);return t.data=e,t.view=new DataView(e.buffer,e.byteOffset,e.byteLength),t}static allocUnsafe(e){return new Zi(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,n=0,i=this.length){let s=this.data.subarray(n,i);return e.data.set(s,t),s.length}slice(e,t){let n=this.data.slice(e,t);return Zi.from(n)}subarray(e,t){let n=this.data.subarray(e,t);return Zi.from(n)}toBuffer(){return typeof Buffer<"u"&&Buffer.from?Buffer.from(this.data):this.data}static fromNodeBuffer(e){return e instanceof Uint8Array?Zi.from(e):Zi.from(new Uint8Array(e))}};J(av,"BufferCompat");var ie=av,gI=new TextDecoder,mI=new pI;function lv(r,e){let t=e.getAllAxes().length,n=e.getAllButtons().length,i=Tu(n),s=8+t+i+4;if(r.length<s)throw new Error(`Invalid compressed input packet: expected at least ${s} bytes (${t} axes + ${n} buttons), got ${r.length}`);let o=new DataView(r.buffer,r.byteOffset,r.byteLength),a=0,l=rv();l.tick=o.getBigUint64(a,!0),a+=8;for(let c=0;c<t;c++){let d=r[a],h=d>127?d-256:d,f=iv(h);l.axes.set(c,f),a+=1}for(let c=0;c<i;c++){let d=r[a];for(let h=0;h<8;h++){let f=c*8+h;if(f<n){let p=(d&1<<h)!==0;l.buttons.set(f,p)}}a+=1}l.displayId=r[a],a+=1,l.mouseX=r[a],a+=1,l.mouseY=r[a],a+=1;let u=r[a];if(l.mouseOverDisplay=(u&1)!==0,l.isTabHidden=(u&2)!==0,a+=1,a<r.length){let c=r[a];a+=1,l.textInputs=[];for(let d=0;d<c&&a<r.length;d++){let h=r[a];if(a+=1,a+h<=r.length){let f=r.slice(a,a+h),p=gI.decode(f);l.textInputs.push(p),a+=h}}}if(a<r.length){let c=r[a];a+=1;let d=[],h=ie.from(r);for(let f=0;f<c&&a<r.length;f++){let p=mI.decode(h,a);d.push(p.event),a+=p.bytesRead}l.macroEvents=d}if(a<r.length){let c=r[a];a+=1;for(let d=0;d<c&&a+5<=r.length;d++){let h=r[a];a+=1;let f=o.getUint16(a,!1);a+=2;let p=o.getUint16(a,!1);a+=2,l.displayViewports.push({displayId:h,pixelWidth:f,pixelHeight:p})}}if(a<r.length){let c=Math.min(r[a],10);a+=1;for(let d=0;d<c&&a+4<=r.length;d++){let h=r[a]&15;a+=1;let f=r[a];a+=1;let p=r[a];a+=1;let m=(r[a]&1)!==0;a+=1,l.touchPositions.push({id:h,x:f,y:p,over:m})}}return l}J(lv,"decodeCompressedInput");var uv=class{constructor(e,t){D(this,"enabled",!1),D(this,"currentStats",null),D(this,"_userId"),D(this,"_userName"),this._userId=e,this._userName=t}setEnabled(e){this.enabled=e,e||(this.currentStats=null)}isEnabled(){return this.enabled}get userId(){var e;return((e=this.currentStats)==null?void 0:e.userId)??this._userId}get userName(){var e;return((e=this.currentStats)==null?void 0:e.userName)??this._userName}get tick(){var e;return((e=this.currentStats)==null?void 0:e.tick)??0}get timestamp(){var e;return((e=this.currentStats)==null?void 0:e.timestamp)??0}get displayCount(){var e;return((e=this.currentStats)==null?void 0:e.displayCount)??0}get totalDisplayArea(){var e;return((e=this.currentStats)==null?void 0:e.totalDisplayArea)??0}get totalLayers(){var e;return((e=this.currentStats)==null?void 0:e.totalLayers)??0}get visibleLayers(){var e;return((e=this.currentStats)==null?void 0:e.visibleLayers)??0}get staticLayers(){var e;return((e=this.currentStats)==null?void 0:e.staticLayers)??0}get dynamicLayers(){var e;return((e=this.currentStats)==null?void 0:e.dynamicLayers)??0}get totalOrders(){var e;return((e=this.currentStats)==null?void 0:e.totalOrders)??0}get ordersByLayer(){var e;return((e=this.currentStats)==null?void 0:e.ordersByLayer)??new Map}get staticPacketSize(){var e;return((e=this.currentStats)==null?void 0:e.staticPacketSize)??0}get dynamicPacketSize(){var e;return((e=this.currentStats)==null?void 0:e.dynamicPacketSize)??0}get totalPacketSize(){var e;return((e=this.currentStats)==null?void 0:e.totalPacketSize)??0}get compressedPacketSize(){return Math.round(this.totalPacketSize*.25)}get hasInput(){var e;return((e=this.currentStats)==null?void 0:e.hasInput)??!1}get axisCount(){var e;return((e=this.currentStats)==null?void 0:e.axisCount)??0}get buttonCount(){var e;return((e=this.currentStats)==null?void 0:e.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,n,i){!this.enabled||!this.currentStats||(this.currentStats.totalLayers=e,this.currentStats.visibleLayers=t,this.currentStats.staticLayers=n,this.currentStats.dynamicLayers=i)}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,n){!this.enabled||!this.currentStats||(this.currentStats.hasInput=e,this.currentStats.axisCount=t,this.currentStats.buttonCount=n)}endTick(){}reset(){this.currentStats=null}};J(uv,"UserStats");var yI=uv,cv=class{constructor(e,t,n){this.id=e,this.name=t,D(this,"displays",[]),D(this,"layers",[]),D(this,"spriteRegistry"),D(this,"mode"),D(this,"axes",new Map),D(this,"buttons",new Map),D(this,"textInputs",[]),D(this,"mouseX",0),D(this,"mouseY",0),D(this,"mouseOver",!1),D(this,"mouseDisplayId",0),D(this,"isTabHidden",!1),D(this,"touchPositions",new Map),D(this,"activeTouchId",null),D(this,"inputBindings",new fI),D(this,"stats"),D(this,"soundCommands",[]),D(this,"nextSoundInstanceId",1),D(this,"audioConfigCommands",[]),D(this,"lastListenerX",-1),D(this,"lastListenerY",-1),D(this,"pendingSendSounds",!1),D(this,"audioProcessor"),D(this,"loadedSounds",new Map),D(this,"soundLoadErrors",new Map),D(this,"playingSounds",new Map),D(this,"mobileVibrationCommands",[]),D(this,"mobileVibrationProcessor"),D(this,"gamepadVibrationCommands",[]),D(this,"gamepadVibrationProcessor"),D(this,"macroRegistry",new nI),D(this,"macroEngine",new hI),D(this,"macroEventHandlers",new Map),D(this,"postProcessCommands",[]),D(this,"currentPostProcessConfig",null),D(this,"bridgeMessages",[]),D(this,"totalBytesSent",0),D(this,"totalBytesReceived",0),D(this,"bytesSentPerTick",[]),D(this,"bytesReceivedPerTick",[]),D(this,"bytesTickIndex",0),D(this,"bytesTickRate",20),D(this,"currentTickBytesSent",0),D(this,"currentTickBytesReceived",0),D(this,"lastInputTick",-1n),D(this,"availableViewports",new Map),D(this,"displayCommandSink",{setPostProcess:(i,s)=>this.setPostProcess(i,s),setScanlinesEnabled:(i,s)=>this.setScanlinesEnabled(i,s),setScanlinesOpacity:(i,s)=>this.setScanlinesOpacity(i,s),setScanlinesPattern:(i,s)=>this.setScanlinesPattern(i,s),setAmbientEffect:(i,s)=>this.setAmbientEffect(i,s),setAmbientEffectEnabled:(i,s)=>this.setAmbientEffectEnabled(i,s),setAmbientEffectBlur:(i,s)=>this.setAmbientEffectBlur(i,s),setAmbientEffectScale:(i,s)=>this.setAmbientEffectScale(i,s),isAmbientEffectEnabled:()=>this.isAmbientEffectEnabled(),getAmbientEffectConfig:()=>this.getAmbientEffectConfig(),getPostProcessConfig:()=>this.getPostProcessConfig(),setScalingMode:(i,s)=>this.setScalingMode(i,s),getScalingMode:i=>this.getScalingMode(i),setCellSize:(i,s,o)=>this.setCellSize(i,s,o),getCellSize:i=>this.getCellSize(i),setGrid:(i,s)=>this.setGrid(i,s),setGridEnabled:(i,s)=>this.setGridEnabled(i,s),isGridEnabled:i=>this.isGridEnabled(i),getGridConfig:i=>this.getGridConfig(i),switchPalette:(i,s)=>this.switchPalette(i,s),getCurrentPaletteSlotId:i=>this.getCurrentPaletteSlotId(i)}),D(this,"data"),D(this,"currentScalingModes",new Map),D(this,"currentCellSizes",new Map),D(this,"currentGridConfigs",new Map),D(this,"currentPaletteSlotIds",new Map),this.mode=n,this.stats=new yI(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,n){this.availableViewports.set(e,{pixelWidth:t,pixelHeight:n})}getDisplayViewport(e){return this.availableViewports.get(e)??null}getAllDisplayViewports(){return this.availableViewports}calculateMaxCells(e,t,n){let i=this.availableViewports.get(e);return i?{cols:Math.floor(i.pixelWidth/t),rows:Math.floor(i.pixelHeight/n)}:null}getLayers(){return this.layers}getLayerById(e){return this.layers.find(t=>t.getId()===e)}addLayer(e,t){e.setMode(this.mode);let n=this.layers.length+1;Aa(e,n),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,n=!0){this.mouseX=Math.max(0,Math.min(255,e)),this.mouseY=Math.max(0,Math.min(255,t)),this.mouseOver=n}setTouchPosition(e,t,n,i=!0,s=0){if(e<0||e>9){console.warn(`Invalid touchId ${e}, must be 0-9`);return}i?(this.touchPositions.set(e,{x:Math.max(0,Math.min(255,t)),y:Math.max(0,Math.min(255,n)),over:!0,displayId:s}),this.activeTouchId=e):(this.touchPositions.delete(e),this.activeTouchId===e&&(this.activeTouchId=null))}setAxis(e,t){let n=Math.max(-1,Math.min(1,t));this.axes.set(e,n)}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,n=this.mouseX,i=this.mouseY,s=e.getOrigin(),o=s.x+n,a=s.y+i;return{displayId:t,localX:n,localY:i,worldX:o,worldY:a}}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 n=this.displays[0],i=t.displayId,s=t.x,o=t.y,a=n.getOrigin(),l=a.x+s,u=a.y+o;return{displayId:i,localX:s,localY:o,worldX:l,worldY:u}}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 n=this.displays[t.id];if(!n){for(n=new px(t.id,t.sizeX,t.sizeY);this.displays.length<=t.id;)this.displays.push(null);this.displays[t.id]=n}n.setCommandSink(this.displayCommandSink),n.setOrigin(new Yt(t.originX,t.originY)),n.setSize(new Yt(t.sizeX,t.sizeY)),n.setRenderPasses(t.renderPasses)}}updateLayersFromPacket(e){for(let t of e){let n=this.findLayerById(t.id);n||(n=new Zx(new Yt(t.originX,t.originY),t.zIndex,t.width,t.height,{mustBeReliable:!1,isMacroLayer:t.isMacroLayer,charCodeMode:t.is16bit?"16bit":"8bit"}),Aa(n,t.id),n.setMode(this.mode),this.spriteRegistry&&n.setSpriteRegistry(this.spriteRegistry),this.addLayer(n)),t.updateFlags&1&&n.setOrigin(new Yt(t.originX,t.originY)),t.updateFlags&2&&n.setZOrder(t.zIndex),t.updateFlags&4&&n.setOrders(t.orders)}}defineAxisBinding(e,t,n=[],i=-1,s=1,o=0){this.inputBindings.defineAxis(e,t,n,i,s,o)}defineButtonBinding(e,t,n=[],i=!1){this.inputBindings.defineButton(e,t,n,i)}defineAxisBindings(e){e.forEach(({bindingId:t,name:n,sources:i,min:s,max:o,defaultValue:a})=>{this.defineAxisBinding(t,n,i??[],s,o,a)})}defineButtonBindings(e){e.forEach(({bindingId:t,name:n,sources:i,defaultValue:s})=>{this.defineButtonBinding(t,n,i??[],s)})}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 n of t.axes)this.defineAxisBinding(n.bindingId,n.name,n.sources||[],n.min,n.max,n.defaultValue);for(let n of t.buttons)this.defineButtonBinding(n.bindingId,n.name,n.sources||[],n.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=lv(e,this.inputBindings);this.lastInputTick=t.tick;let n=this.inputBindings.getAllAxes(),i=this.inputBindings.getAllButtons(),s=n.sort((a,l)=>a.bindingId-l.bindingId),o=i.sort((a,l)=>a.bindingId-l.bindingId);for(let[a,l]of t.axes)if(a<s.length){let u=s[a];this.setAxis(u.name,l)}for(let[a,l]of t.buttons)if(a<o.length){let u=o[a],c=this.getButton(u.name);this.setButton(u.name,l);let d=l&&!c,h=!l&&c;this.setButton(`${u.name}_justPressed`,d),this.setButton(`${u.name}_justReleased`,h)}this.mouseX=t.mouseX,this.mouseY=t.mouseY,this.mouseOver=t.mouseOverDisplay,this.mouseDisplayId=t.displayId,this.isTabHidden=t.isTabHidden;for(let a of t.touchPositions)this.setTouchPosition(a.id,a.x,a.y,a.over);for(let a of t.displayViewports)this.setDisplayViewport(a.displayId,a.pixelWidth,a.pixelHeight)}playSound(e,t){let n=this.nextSoundInstanceId++,i={sound:e,instanceId:n,volume:t==null?void 0:t.volume,pitch:t==null?void 0:t.pitch,loop:t==null?void 0:t.loop,fadeIn:t==null?void 0:t.fadeIn,x:t==null?void 0:t.x,y:t==null?void 0:t.y,lowpass:t==null?void 0:t.lowpass,highpass:t==null?void 0:t.highpass,reverb:t==null?void 0:t.reverb};return this.soundCommands.push(i),n}stopSound(e){let t={sound:e};this.soundCommands.push(t)}fadeOutSound(e,t){let n={fadeOut:!0,sound:e,duration:t};this.soundCommands.push(n)}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 n={setEffects:!0,instanceId:e,lowpass:t.lowpass,highpass:t.highpass,reverb:t.reverb};this.soundCommands.push(n)}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,i=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:i,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 n={gamepadIndex:e,options:t};this.gamepadVibrationCommands.push(n)}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 n=t;if(n.gamepadIndex==="all")for(let i=0;i<4;i++)this.gamepadVibrationProcessor.vibrate(i,n.options);else this.gamepadVibrationProcessor.vibrate(n.gamepadIndex,n.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}=(A1(),ul(U1)),{MobileVibrateFlags:n,GamepadVibrateFlags:i}=(R1(),ul(T1));for(let s of e)switch(s.type){case t.MobileVibrate:{if(!this.mobileVibrationProcessor)break;let o=s,a=o.pattern;o.flags&n.HasIntensity&&o.intensity!==void 0&&(a=a.map(l=>Math.round(l*o.intensity))),this.mobileVibrationProcessor.vibrate(a);break}case t.MobileCancel:{if(!this.mobileVibrationProcessor)break;this.mobileVibrationProcessor.cancel();break}case t.GamepadVibrate:{if(!this.gamepadVibrationProcessor)break;let o=s,a={duration:o.duration,strongMagnitude:o.strongMagnitude/255,weakMagnitude:o.weakMagnitude/255,startDelay:o.startDelay};if(o.flags&i.AllGamepads)for(let l=0;l<4;l++)this.gamepadVibrationProcessor.vibrate(l,a);else this.gamepadVibrationProcessor.vibrate(o.gamepadIndex,a);break}case t.GamepadCancel:{if(!this.gamepadVibrationProcessor)break;let o=s;o.flags&i.AllGamepads?this.gamepadVibrationProcessor.stopAllVibrations():this.gamepadVibrationProcessor.stopVibration(o.gamepadIndex);break}}}applyAudioOrders(e){if(!this.audioProcessor||this.mode==="server")return;let{AudioOrderType:t,AudioTargetType:n}=(D1(),ul(P1)),{PlaySoundFlags:i}=(F1(),ul(O1));for(let s of e)switch(s.type){case t.PlaySound:case t.PlayGlobalSound:{let o=s,a=o.volume!==void 0?o.volume/255:void 0,l=o.pitch!==void 0?.25*Math.pow(2,o.pitch/64):void 0,u=o.fadeIn!==void 0?o.fadeIn/10:void 0,c=(o.flags&i.Loop)!==0,d=o.posX!==void 0&&o.posY!==void 0?{x:o.posX,y:o.posY}:void 0;this.audioProcessor.play(o.soundId,{volume:a,pitch:l,loop:c,fadeIn:u,position:d,instanceId:o.instanceId,lowpass:o.lowpass,highpass:o.highpass,reverb:o.reverb});break}case t.StopSound:{let o=s;o.targetType===n.All?this.audioProcessor.stopAll():o.targetType===n.InstanceId?this.audioProcessor.stop(o.target):this.audioProcessor.stop(o.target);break}case t.FadeOutSound:{let o=s,a=o.duration/10;o.targetType===n.All?this.audioProcessor.fadeOut("all",a):this.audioProcessor.fadeOut(o.target,a);break}case t.PauseSound:{let o=s;o.targetType===n.All?this.audioProcessor.pause("all"):this.audioProcessor.pause(o.target);break}case t.ResumeSound:{let o=s;o.targetType===n.All?this.audioProcessor.resume("all"):this.audioProcessor.resume(o.target);break}case t.SetListenerPosition:{let o=s;this.audioProcessor.setListenerPosition(o.x,o.y);break}case t.ConfigureSpatial:{let o=s;this.audioProcessor.configureSpatial({maxDistance:o.maxDistance*100,referenceDistance:o.referenceDistance*100,rolloffFactor:o.rolloffFactor/100,panSpread:o.panSpread/255});break}case t.SetSoundEffects:{let o=s;this.audioProcessor.setEffects(o.instanceId,o.lowpass,o.highpass,o.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){var t;return(t=this.soundLoadErrors.get(e))==null?void 0:t.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,n=this.soundLoadErrors.size,i=e>0&&t>=e,s=Array.from(this.soundLoadErrors.values()).map(o=>o.name);return{loadedCount:t,totalExpected:e,errorCount:n,isComplete:i,errors:s}}loadMacro(e,t){let n={...t,id:e},i=this.macroRegistry.registerMacro(n);return this.mode==="client"&&this.macroEngine.loadTemplate(i,n),i}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,n){this.macroEventHandlers.has(e)||this.macroEventHandlers.set(e,new Map),this.macroEventHandlers.get(e).set(t,n)}offMacroEvent(e,t){var n;t?(n=this.macroEventHandlers.get(e))==null||n.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 n=this.macroEventHandlers.get(t);if(!n)return;let i,s;switch(e.type){case 1:i="click",s=void 0;break;case 2:i="change",s=e.value;break;case 3:i="submit",s=e.text;break;case 4:i="select",s=e.index;break;default:return}let o=n.get(i);o&&o(s)}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 n=this.macroRegistry.getInstanceName(t.instanceId);if(!n)continue;let i=this.macroEventHandlers.get(n);if(!i)continue;let s=i.get(t.event);s&&s(t.data)}}updateMacroMouse(e,t,n){let i=this.displays.find(s=>s.getId()===this.mouseDisplayId);if(!i&&this.displays.length>0&&(i=this.displays[0]),i){let s=i.getOrigin(),o=e+s.x,a=t+s.y;this.macroEngine.updateMouse(o,a,n)}else this.macroEngine.updateMouse(e,t,n)}getMacroRenderOrders(){let e=this.macroEngine.getOrdersByLayer(),t=this.displays[0];if(!t)return e;let n=t.getOrigin();if(n.x===0&&n.y===0)return e;let i=new Map;for(let[s,o]of e){let a=o.map(l=>{let u={...l};return"posX"in u&&typeof u.posX=="number"&&(u.posX=u.posX-n.x),"posY"in u&&typeof u.posY=="number"&&(u.posY=u.posY-n.y),u});i.set(s,a)}return i}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 n=JSON.stringify(t),i=JSON.stringify(this.currentPostProcessConfig);n!==i&&(this.currentPostProcessConfig=t,this.postProcessCommands.push({type:"set-config",displayId:e,config:t??void 0}))}setScanlinesEnabled(e,t){var n;if(t){let i=(n=this.currentPostProcessConfig)==null?void 0:n.scanlines;this.setPostProcess(e,{scanlines:{enabled:!0,opacity:(i==null?void 0:i.opacity)??Ge.scanlines.opacity,pattern:(i==null?void 0:i.pattern)??Ge.scanlines.pattern,color:(i==null?void 0:i.color)??Ge.scanlines.color}})}else this.setPostProcess(e,{scanlines:{enabled:!1}})}setScanlinesOpacity(e,t){var s;let n=Math.max(0,Math.min(1,t)),i=(s=this.currentPostProcessConfig)==null?void 0:s.scanlines;this.setPostProcess(e,{scanlines:{enabled:!0,opacity:n,pattern:(i==null?void 0:i.pattern)??"horizontal",color:(i==null?void 0:i.color)??{r:0,g:0,b:0}}})}setScanlinesPattern(e,t){var i;let n=(i=this.currentPostProcessConfig)==null?void 0:i.scanlines;this.setPostProcess(e,{scanlines:{enabled:(n==null?void 0:n.enabled)??!0,opacity:(n==null?void 0:n.opacity)??Ge.scanlines.opacity,pattern:t,color:(n==null?void 0:n.color)??{r:0,g:0,b:0}}})}setAmbientEffect(e,t){var i;let n=(i=this.currentPostProcessConfig)==null?void 0:i.ambientEffect;typeof t=="boolean"?this.setPostProcess(e,{...this.currentPostProcessConfig,ambientEffect:{enabled:t,blur:(n==null?void 0:n.blur)??Ge.ambientEffect.blur,scale:(n==null?void 0:n.scale)??Ge.ambientEffect.scale}}):this.setPostProcess(e,{...this.currentPostProcessConfig,ambientEffect:{enabled:!0,blur:t.blur??(n==null?void 0:n.blur)??Ge.ambientEffect.blur,scale:t.scale??(n==null?void 0:n.scale)??Ge.ambientEffect.scale}})}setAmbientEffectEnabled(e,t){this.setAmbientEffect(e,t)}setAmbientEffectBlur(e,t){var i;let n=(i=this.currentPostProcessConfig)==null?void 0:i.ambientEffect;this.setPostProcess(e,{...this.currentPostProcessConfig,ambientEffect:{enabled:(n==null?void 0:n.enabled)??!0,blur:Math.max(0,t),scale:(n==null?void 0:n.scale)??Ge.ambientEffect.scale}})}setAmbientEffectScale(e,t){var i;let n=(i=this.currentPostProcessConfig)==null?void 0:i.ambientEffect;this.setPostProcess(e,{...this.currentPostProcessConfig,ambientEffect:{enabled:(n==null?void 0:n.enabled)??!0,blur:(n==null?void 0:n.blur)??Ge.ambientEffect.blur,scale:Math.max(1,t)}})}isAmbientEffectEnabled(){var e,t;return((t=(e=this.currentPostProcessConfig)==null?void 0:e.ambientEffect)==null?void 0:t.enabled)??!1}getAmbientEffectConfig(){var t;let e=(t=this.currentPostProcessConfig)==null?void 0:t.ambientEffect;return e?{enabled:e.enabled,blur:e.blur??Ge.ambientEffect.blur,scale:e.scale??Ge.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,n){let i=Math.max(1,Math.min(255,Math.round(t))),s=Math.max(1,Math.min(255,Math.round(n))),o=this.currentCellSizes.get(e);o&&o.width===i&&o.height===s||(this.currentCellSizes.set(e,{width:i,height:s}),this.postProcessCommands.push({type:"set-cell-size",displayId:e,cellWidth:i,cellHeight:s}))}getCellSize(e){let t=this.currentCellSizes.get(e);return{cellWidth:(t==null?void 0:t.width)??8,cellHeight:(t==null?void 0:t.height)??8}}setGrid(e,t){let n;typeof t=="boolean"?n={enabled:t,color:js.color,lineWidth:js.lineWidth}:n={enabled:t.enabled,color:t.color??js.color,lineWidth:t.lineWidth??js.lineWidth},this.currentGridConfigs.set(e,n),this.postProcessCommands.push({type:"set-grid",displayId:e,gridConfig:n})}setGridEnabled(e,t){this.setGrid(e,t)}isGridEnabled(e){var t;return((t=this.currentGridConfigs.get(e))==null?void 0:t.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,n])=>({displayId:t,pixelWidth:n.pixelWidth,pixelHeight:n.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())}}};J(cv,"User");var vI=cv,dv=class{constructor(){D(this,"charCodeSize",_1)}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,n,i){return i?(e.writeUInt16LE(t,n),n+2):(e.writeUInt8(t,n),n+1)}encodeCharOrder(e,t){let n=ie.allocUnsafe(gx+(t?1:0)),i=0;return n.writeUInt8(e.type,i++),n.writeUInt8(e.posX,i++),n.writeUInt8(e.posY,i++),i=this.writeCharCode(n,e.charCode,i,t),n.writeUInt8(e.bgColorCode,i++),n.writeUInt8(e.fgColorCode,i++),n.toUint8Array()}encodeTextOrder(e){let t=new TextEncoder().encode(e.text),n=ie.allocUnsafe(mx+t.length),i=0;n.writeUInt8(e.type,i++),n.writeUInt8(e.posX,i++),n.writeUInt8(e.posY,i++),n.writeUInt8(t.length,i++);for(let s=0;s<t.length;s++)n.writeUInt8(t[s],i++);return n.writeUInt8(e.bgColorCode,i++),n.writeUInt8(e.fgColorCode,i++),n.toUint8Array()}encodeTextMultilineOrder(e){let t=new TextEncoder().encode(e.text),n=ie.allocUnsafe(yx+t.length),i=0;n.writeUInt8(e.type,i++),n.writeUInt8(e.posX,i++),n.writeUInt8(e.posY,i++),n.writeUInt8(t.length,i++);for(let s=0;s<t.length;s++)n.writeUInt8(t[s],i++);return n.writeUInt8(e.bgColorCode,i++),n.writeUInt8(e.fgColorCode,i++),n.toUint8Array()}encodeSubFrameOrder(e,t){let n=e.sizeX*e.sizeY,i=this.charCodeSize(t),s=ie.allocUnsafe(vx+n*i),o=0;s.writeUInt8(e.type,o++),s.writeUInt8(e.posX,o++),s.writeUInt8(e.posY,o++),s.writeUInt8(e.sizeX-1,o++),s.writeUInt8(e.sizeY-1,o++),s.writeUInt8(e.bgColorCode,o++),s.writeUInt8(e.fgColorCode,o++);for(let a of e.frame)o=this.writeCharCode(s,a,o,t);return s.toUint8Array()}encodeSubFrameMultiColorOrder(e,t){let n=e.sizeX*e.sizeY,i=this.charCodeSize(t),s=ie.allocUnsafe(wx+n*(i+2)),o=0;s.writeUInt8(e.type,o++),s.writeUInt8(e.posX,o++),s.writeUInt8(e.posY,o++),s.writeUInt8(e.sizeX-1,o++),s.writeUInt8(e.sizeY-1,o++);for(let a of e.frame)o=this.writeCharCode(s,a.charCode,o,t),s.writeUInt8(a.bgColorCode,o++),s.writeUInt8(a.fgColorCode,o++);return s.toUint8Array()}encodeFullFrameOrder(e,t){let n=e.frame.length,i=this.charCodeSize(t),s=ie.allocUnsafe(Cx+n*i),o=0;s.writeUInt8(e.type,o++),s.writeUInt8(e.bgColorCode,o++),s.writeUInt8(e.fgColorCode,o++);for(let a of e.frame)o=this.writeCharCode(s,a,o,t);return s.toUint8Array()}encodeFullFrameMultiColorOrder(e,t){let n=e.frame.length,i=this.charCodeSize(t),s=ie.allocUnsafe(bx+n*(i+2)),o=0;s.writeUInt8(e.type,o++);for(let a of e.frame)o=this.writeCharCode(s,a.charCode,o,t),s.writeUInt8(a.bgColorCode,o++),s.writeUInt8(a.fgColorCode,o++);return s.toUint8Array()}encodeSpriteOrder(e){let t=ie.allocUnsafe(Sx),n=0;return t.writeUInt8(e.type,n++),t.writeUInt8(e.posX,n++),t.writeUInt8(e.posY,n++),t.writeUInt8(e.spriteIndex,n++),t.writeUInt8(e.bgColorCode,n++),t.writeUInt8(e.fgColorCode,n++),t.toUint8Array()}encodeSpriteMultiColorOrder(e){let t=ie.allocUnsafe(xx),n=0;return t.writeUInt8(e.type,n++),t.writeUInt8(e.posX,n++),t.writeUInt8(e.posY,n++),t.writeUInt8(e.spriteIndex,n++),t.toUint8Array()}encodeColorMapOrder(e){let t=e.sizeX*e.sizeY,n=ie.allocUnsafe(Ix+t*2),i=0;n.writeUInt8(e.type,i++),n.writeUInt8(e.posX,i++),n.writeUInt8(e.posY,i++),n.writeUInt8(e.sizeX-1,i++),n.writeUInt8(e.sizeY-1,i++);for(let s of e.colorData)n.writeUInt8(s.bgColorCode,i++),n.writeUInt8(s.fgColorCode,i++);return n.toUint8Array()}encodeShapeOrder(e,t){let n=this.encodeShapeData(e.shapeType,e.shapeData,t),i=ie.allocUnsafe(kx+n.length),s=0;i.writeUInt8(e.type,s++),i.writeUInt8(e.shapeType,s++);for(let o=0;o<n.length;o++)i.writeUInt8(n[o],s++);return i.toUint8Array()}encodeShapeData(e,t,n){switch(this.charCodeSize(n),e){case 1:{let i=ie.allocUnsafe(Ex+(n?1:0)),s=0;return i.writeUInt8(t.posX,s++),i.writeUInt8(t.posY,s++),i.writeUInt8(t.width-1,s++),i.writeUInt8(t.height-1,s++),i.writeUInt8(t.filled?1:0,s++),s=this.writeCharCode(i,t.charCode,s,n),i.writeUInt8(t.bgColorCode,s++),i.writeUInt8(t.fgColorCode,s++),i.toUint8Array()}case 2:{let i=ie.allocUnsafe(Mx+(n?1:0)),s=0;return i.writeUInt8(t.centerX,s++),i.writeUInt8(t.centerY,s++),i.writeUInt8(t.radius-1,s++),i.writeUInt8(t.filled?1:0,s++),s=this.writeCharCode(i,t.charCode,s,n),i.writeUInt8(t.bgColorCode,s++),i.writeUInt8(t.fgColorCode,s++),i.toUint8Array()}case 3:{let i=ie.allocUnsafe(Ux+(n?1:0)),s=0;return i.writeUInt8(t.x1,s++),i.writeUInt8(t.y1,s++),i.writeUInt8(t.x2,s++),i.writeUInt8(t.y2,s++),s=this.writeCharCode(i,t.charCode,s,n),i.writeUInt8(t.bgColorCode,s++),i.writeUInt8(t.fgColorCode,s++),i.toUint8Array()}case 4:{let i=ie.allocUnsafe(Ax+(n?1:0)),s=0;return i.writeUInt8(t.centerX,s++),i.writeUInt8(t.centerY,s++),i.writeUInt8(t.radiusX-1,s++),i.writeUInt8(t.radiusY-1,s++),i.writeUInt8(t.filled?1:0,s++),s=this.writeCharCode(i,t.charCode,s,n),i.writeUInt8(t.bgColorCode,s++),i.writeUInt8(t.fgColorCode,s++),i.toUint8Array()}case 5:{let i=ie.allocUnsafe(Tx+(n?1:0)),s=0;return i.writeUInt8(t.x1,s++),i.writeUInt8(t.y1,s++),i.writeUInt8(t.x2,s++),i.writeUInt8(t.y2,s++),i.writeUInt8(t.x3,s++),i.writeUInt8(t.y3,s++),i.writeUInt8(t.filled?1:0,s++),s=this.writeCharCode(i,t.charCode,s,n),i.writeUInt8(t.bgColorCode,s++),i.writeUInt8(t.fgColorCode,s++),i.toUint8Array()}default:throw new Error(`Unknown shape type: ${e}`)}}encodeDotCloudOrder(e,t){let n=e.positions.length;this.charCodeSize(t);let i=ie.allocUnsafe(Rx+(t?1:0)+n*2),s=0;i.writeUInt8(e.type,s++),s=this.writeCharCode(i,e.charCode,s,t),i.writeUInt8(e.bgColorCode,s++),i.writeUInt8(e.fgColorCode,s++),i.writeUInt16BE(n,s),s+=2;for(let o of e.positions)i.writeUInt8(o.posX,s++),i.writeUInt8(o.posY,s++);return i.toUint8Array()}encodeDotCloudMultiColorOrder(e,t){let n=e.dots.length,i=this.charCodeSize(t),s=ie.allocUnsafe(Px+n*(i+4)),o=0;s.writeUInt8(e.type,o++),s.writeUInt16BE(n,o),o+=2;for(let a of e.dots)o=this.writeCharCode(s,a.charCode,o,t),s.writeUInt8(a.bgColorCode,o++),s.writeUInt8(a.fgColorCode,o++),s.writeUInt8(a.posX,o++),s.writeUInt8(a.posY,o++);return s.toUint8Array()}encodeBitmaskOrder(e,t){let n=e.mask.length,i=ie.allocUnsafe(Bx+(t?1:0)+n),s=0;i.writeUInt8(e.type,s++),i.writeUInt8(e.posX,s++),i.writeUInt8(e.posY,s++),i.writeUInt8(e.sizeX-1,s++),i.writeUInt8(e.sizeY-1,s++),s=this.writeCharCode(i,e.charCode,s,t),i.writeUInt8(e.bgColorCode,s++),i.writeUInt8(e.fgColorCode,s++),i.writeUInt8(e.override?1:0,s++);for(let o=0;o<n;o++)i.writeUInt8(e.mask[o],s++);return i.toUint8Array()}encodeBitmask4Order(e,t){let n=e.mask.length;this.charCodeSize(t);let i=ie.allocUnsafe(zx+3*(t?1:0)+n),s=0;i.writeUInt8(e.type,s++),i.writeUInt8(e.posX,s++),i.writeUInt8(e.posY,s++),i.writeUInt8(e.sizeX-1,s++),i.writeUInt8(e.sizeY-1,s++),i.writeUInt8(e.override?1:0,s++);for(let o of e.variants)s=this.writeCharCode(i,o.charCode,s,t),i.writeUInt8(o.bgColorCode,s++),i.writeUInt8(o.fgColorCode,s++);for(let o=0;o<n;o++)i.writeUInt8(e.mask[o],s++);return i.toUint8Array()}encodeBitmask16Order(e,t){let n=e.mask.length;this.charCodeSize(t);let i=ie.allocUnsafe(Dx+15*(t?1:0)+n),s=0;i.writeUInt8(e.type,s++),i.writeUInt8(e.posX,s++),i.writeUInt8(e.posY,s++),i.writeUInt8(e.sizeX-1,s++),i.writeUInt8(e.sizeY-1,s++),i.writeUInt8(e.override?1:0,s++);for(let o of e.variants)s=this.writeCharCode(i,o.charCode,s,t),i.writeUInt8(o.bgColorCode,s++),i.writeUInt8(o.fgColorCode,s++);for(let o=0;o<n;o++)i.writeUInt8(e.mask[o],s++);return i.toUint8Array()}encodePolylineOrder(e,t){let n=e.points.length,i=ie.allocUnsafe(Ox+(t?1:0)+n*2),s=0;i.writeUInt8(e.type,s++),s=this.writeCharCode(i,e.charCode,s,t),i.writeUInt8(e.fgColorCode,s++),i.writeUInt8(e.bgColorCode,s++),i.writeUInt8(n,s++);for(let o of e.points)i.writeUInt8(o.x,s++),i.writeUInt8(o.y,s++);return i.toUint8Array()}encodeSpriteCloudOrder(e){let t=e.positions.length,n=ie.allocUnsafe(Fx+t*2),i=0;n.writeUInt8(e.type,i++),n.writeUInt8(e.spriteIndex,i++),n.writeUInt8(e.bgColorCode,i++),n.writeUInt8(e.fgColorCode,i++),n.writeUInt16BE(t,i),i+=2;for(let s of e.positions)n.writeUInt8(s.posX,i++),n.writeUInt8(s.posY,i++);return n.toUint8Array()}encodeSpriteCloudMultiColorOrder(e){let t=e.positions.length,n=ie.allocUnsafe(Lx+t*2),i=0;n.writeUInt8(e.type,i++),n.writeUInt8(e.spriteIndex,i++),n.writeUInt16BE(t,i),i+=2;for(let s of e.positions)n.writeUInt8(s.posX,i++),n.writeUInt8(s.posY,i++);return n.toUint8Array()}encodeSpriteCloudVariedOrder(e){let t=e.sprites.length,n=ie.allocUnsafe(_x+t*5),i=0;n.writeUInt8(e.type,i++),n.writeUInt16BE(t,i),i+=2;for(let s of e.sprites)n.writeUInt8(s.spriteIndex,i++),n.writeUInt8(s.bgColorCode,i++),n.writeUInt8(s.fgColorCode,i++),n.writeUInt8(s.posX,i++),n.writeUInt8(s.posY,i++);return n.toUint8Array()}encodeSpriteCloudVariedMultiColorOrder(e){let t=e.sprites.length,n=ie.allocUnsafe($x+t*3),i=0;n.writeUInt8(e.type,i++),n.writeUInt16BE(t,i),i+=2;for(let s of e.sprites)n.writeUInt8(s.spriteIndex,i++),n.writeUInt8(s.posX,i++),n.writeUInt8(s.posY,i++);return n.toUint8Array()}encodeFillOrder(e,t){let n=ie.allocUnsafe(Nx+(t?1:0)),i=0;return n.writeUInt8(e.type,i++),i=this.writeCharCode(n,e.charCode,i,t),n.writeUInt8(e.bgColorCode,i++),n.writeUInt8(e.fgColorCode,i++),n.toUint8Array()}encodeFillCharOrder(e,t){let n=e.patternWidth*e.patternHeight,i=this.charCodeSize(t),s=ie.allocUnsafe(Vx+n*i),o=0;s.writeUInt8(e.type,o++),s.writeUInt8(e.patternWidth-1,o++),s.writeUInt8(e.patternHeight-1,o++),s.writeUInt8(e.bgColorCode,o++),s.writeUInt8(e.fgColorCode,o++);for(let a of e.pattern)o=this.writeCharCode(s,a,o,t);return s.toUint8Array()}encodeFillSpriteOrder(e){let t=ie.allocUnsafe(Hx),n=0;return t.writeUInt8(e.type,n++),t.writeUInt8(e.spriteIndex,n++),t.writeUInt8(e.bgColorCode,n++),t.writeUInt8(e.fgColorCode,n++),t.toUint8Array()}encodeFillSpriteMultiColorOrder(e){let t=ie.allocUnsafe(jx),n=0;return t.writeUInt8(e.type,n++),t.writeUInt8(e.spriteIndex,n++),t.toUint8Array()}};J(dv,"OrderEncoder");var wI=dv,jg=255,Yg=32,Wg=64,hv=class{constructor(){D(this,"orderEncoder"),this.orderEncoder=new wI}encode(e){let t=e.is16bit;if(e.orders.length>jg)throw new Error(`[UTSP] LayerEncoder: Layer ${e.id} has ${e.orders.length} orders, max is ${jg}. This would cause packet corruption! Split into multiple layers.`);let n=e.orders.map(c=>this.orderEncoder.encode(c,t)),i=13,s=n.reduce((c,d)=>c+d.length,0),o=i+s,a=ie.allocUnsafe(o),l=0;a.writeUInt16BE(e.id,l),l+=2;let u=e.updateFlags;e.isMacroLayer?u|=Yg:u&=~Yg,t?u|=Wg:u&=~Wg,a.writeUInt8(u,l++),a.writeUInt8(e.zIndex,l++),a.writeUInt16BE(e.originX,l),l+=2,a.writeUInt16BE(e.originY,l),l+=2,a.writeUInt16BE(e.width,l),l+=2,a.writeUInt16BE(e.height,l),l+=2,a.writeUInt8(e.orders.length,l++);for(let c of n)ie.from(c).copy(a,l),l+=c.length;return a.toUint8Array()}calculateSize(e){let t=e.is16bit;return 13+e.orders.reduce((n,i)=>n+this.orderEncoder.encode(i,t).length,0)}};J(hv,"LayerEncoder");var CI=hv,fv=class{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 zg;case 8:return Dg;case 9:return this.calculateSetSoundEffectsSize(e);default:throw new Error(`Unknown audio order type: ${e.type}`)}}encodePlaySoundOrder(e){let t=this.calculatePlaySoundSize(e),n=ie.allocUnsafe(t),i=0;return n.writeUInt8(e.type,i++),n.writeUInt8(e.soundId,i++),n.writeUInt16BE(e.instanceId,i),i+=2,n.writeUInt8(e.flags,i++),e.flags&2&&n.writeUInt8(e.volume??255,i++),e.flags&4&&n.writeUInt8(e.pitch??128,i++),e.flags&8&&n.writeUInt8(e.fadeIn??0,i++),e.flags&16&&(n.writeUInt16BE(e.posX??0,i),i+=2,n.writeUInt16BE(e.posY??0,i),i+=2),e.flags&32&&n.writeUInt8(e.lowpass??0,i++),e.flags&64&&n.writeUInt8(e.highpass??0,i++),e.flags&128&&n.writeUInt8(e.reverb??0,i++),n.toUint8Array()}encodePlayGlobalSoundOrder(e){let t=this.calculatePlayGlobalSoundSize(e),n=ie.allocUnsafe(t),i=0;n.writeUInt8(e.type,i++),n.writeUInt8(e.soundId,i++),n.writeUInt16BE(e.instanceId,i),i+=2;let s=e.flags&-17;return n.writeUInt8(s,i++),s&2&&n.writeUInt8(e.volume??255,i++),s&4&&n.writeUInt8(e.pitch??128,i++),s&8&&n.writeUInt8(e.fadeIn??0,i++),s&32&&n.writeUInt8(e.lowpass??0,i++),s&64&&n.writeUInt8(e.highpass??0,i++),s&128&&n.writeUInt8(e.reverb??0,i++),n.toUint8Array()}calculatePlaySoundSize(e){let t=Yx;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=Wx,n=e.flags&-17;return n&2&&(t+=1),n&4&&(t+=1),n&8&&(t+=1),n&32&&(t+=1),n&64&&(t+=1),n&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),n=ie.allocUnsafe(t),i=0;return n.writeUInt8(e.type,i++),n.writeUInt8(e.targetType,i++),n.writeUInt8(e.duration,i++),e.targetType===0?n.writeUInt16BE(e.target??0,i):e.targetType===1&&n.writeUInt8(e.target??0,i),n.toUint8Array()}encodeTargetOrder(e,t,n){let i=2;t===0?i+=2:t===1&&(i+=1);let s=ie.allocUnsafe(i),o=0;return s.writeUInt8(e,o++),s.writeUInt8(t,o++),t===0?s.writeUInt16BE(n??0,o):t===1&&s.writeUInt8(n??0,o),s.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=ie.allocUnsafe(zg),n=0;return t.writeUInt8(e.type,n++),t.writeUInt16BE(e.x,n),n+=2,t.writeUInt16BE(e.y,n),t.toUint8Array()}encodeConfigureSpatialOrder(e){let t=ie.allocUnsafe(Dg),n=0;return t.writeUInt8(e.type,n++),t.writeUInt8(e.maxDistance,n++),t.writeUInt8(e.referenceDistance,n++),t.writeUInt8(e.rolloffFactor,n++),t.writeUInt8(e.panSpread,n++),t.toUint8Array()}encodeSetSoundEffectsOrder(e){let t=this.calculateSetSoundEffectsSize(e),n=ie.allocUnsafe(t),i=0;return n.writeUInt8(e.type,i++),n.writeUInt16BE(e.instanceId,i),i+=2,n.writeUInt8(e.flags,i++),e.flags&1&&n.writeUInt8(e.lowpass??0,i++),e.flags&2&&n.writeUInt8(e.highpass??0,i++),e.flags&4&&n.writeUInt8(e.reverb??0,i++),n.toUint8Array()}calculateSetSoundEffectsSize(e){let t=4;return e.flags&1&&(t+=1),e.flags&2&&(t+=1),e.flags&4&&(t+=1),t}};J(fv,"AudioOrderEncoder");var bI=fv,pv=class{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),n=ie.allocUnsafe(t),i=0,s=0;e.intensity!==void 0&&(s|=1),n.writeUInt8(e.type,i++),n.writeUInt8(s,i++),n.writeUInt8(e.pattern.length,i++);for(let o of e.pattern){let a=Math.min(65535,Math.max(0,Math.round(o)));n.writeUInt16BE(a,i),i+=2}if(e.intensity!==void 0){let o=Math.round(Math.min(1,Math.max(0,e.intensity))*255);n.writeUInt8(o,i++)}return n.toUint8Array()}encodeMobileCancelOrder(e){let t=ie.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),n=ie.allocUnsafe(t),i=0,s=0;e.startDelay!==void 0&&e.startDelay>0&&(s|=1),e.gamepadIndex===255&&(s|=2),n.writeUInt8(e.type,i++),n.writeUInt8(s,i++),n.writeUInt8(e.gamepadIndex,i++);let o=Math.min(65535,Math.max(0,Math.round(e.duration)));if(n.writeUInt16BE(o,i),i+=2,n.writeUInt8(e.strongMagnitude,i++),n.writeUInt8(e.weakMagnitude,i++),e.startDelay!==void 0&&e.startDelay>0){let a=Math.min(65535,Math.max(0,Math.round(e.startDelay)));n.writeUInt16BE(a,i),i+=2}return n.toUint8Array()}encodeGamepadCancelOrder(e){let t=ie.allocUnsafe(3),n=0,i=0;return e.gamepadIndex===255&&(i|=2),t.writeUInt8(e.type,n++),t.writeUInt8(i,n++),t.writeUInt8(e.gamepadIndex,n++),t.toUint8Array()}};J(pv,"VibrationOrderEncoder");var SI=pv,gv=class{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),n=new TextEncoder().encode(t);if(n.length>65535)throw new Error(`Params JSON too large: ${n.length} bytes (max 65535)`);let i=11+n.length,s=ie.allocUnsafe(i),o=0;return s.writeUInt8(e.type,o++),s.writeUInt8(e.instanceId,o++),s.writeUInt8(e.macroId,o++),s.writeUInt8(e.layerId,o++),s.writeInt16BE(e.x,o),o+=2,s.writeInt16BE(e.y,o),o+=2,s.writeUInt8(e.tabIndex,o++),s.writeUInt16BE(n.length,o),o+=2,s.toUint8Array().set(n,o),s.toUint8Array()}calculateCreateInstanceSize(e){let t=JSON.stringify(e.params);return 11+new TextEncoder().encode(t).length}encodeUpdateInstance(e){let t=JSON.stringify(e.params),n=new TextEncoder().encode(t);if(n.length>65535)throw new Error(`Params JSON too large: ${n.length} bytes (max 65535)`);let i=4+n.length,s=ie.allocUnsafe(i),o=0;return s.writeUInt8(e.type,o++),s.writeUInt8(e.instanceId,o++),s.writeUInt16BE(n.length,o),o+=2,s.toUint8Array().set(n,o),s.toUint8Array()}calculateUpdateInstanceSize(e){let t=JSON.stringify(e.params);return 4+new TextEncoder().encode(t).length}encodeRemoveInstance(e){let t=ie.allocUnsafe(2);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.toUint8Array()}};J(gv,"MacroOrderEncoder");var xI=gv,Xr=(r=>(r[r.SetConfig=1]="SetConfig",r[r.SetScanlines=2]="SetScanlines",r[r.SetAmbientEffect=3]="SetAmbientEffect",r[r.SetScalingMode=4]="SetScalingMode",r[r.SetGrid=5]="SetGrid",r[r.SwitchPalette=6]="SwitchPalette",r[r.SetCellSize=7]="SetCellSize",r))(Xr||{}),mv=class{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 Og;case 3:return Fg;case 4:return Lg;case 5:return _g;case 6:return $g;case 7:return Ng;default:throw new Error(`Unknown post-process order type: ${e.type}`)}}encodeSetConfigOrder(e){let t=this.calculateSetConfigSize(e),n=ie.allocUnsafe(t),i=0;return n.writeUInt8(e.type,i++),n.writeUInt8(e.displayId,i++),n.writeUInt8(e.flags,i++),e.flags&1&&e.scanlines&&(n.writeUInt8(e.scanlines.enabled?1:0,i++),n.writeUInt8(Math.round(e.scanlines.opacity*255),i++),n.writeUInt8(e.scanlines.pattern,i++),n.writeUInt8(e.scanlines.colorR,i++),n.writeUInt8(e.scanlines.colorG,i++),n.writeUInt8(e.scanlines.colorB,i++)),e.flags&2&&e.ambientEffect&&(n.writeUInt8(e.ambientEffect.enabled?1:0,i++),n.writeUInt8(Math.min(255,Math.round(e.ambientEffect.blur)),i++),n.writeUInt8(Math.min(255,Math.max(100,Math.round(e.ambientEffect.scale*100))),i++),n.writeUInt8(Math.round(e.ambientEffect.opacity*255),i++)),n.toUint8Array()}calculateSetConfigSize(e){let t=Gx;return e.flags&1&&(t+=6),e.flags&2&&(t+=4),t}encodeSetScanlinesOrder(e){let t=ie.allocUnsafe(Og),n=0;return t.writeUInt8(e.type,n++),t.writeUInt8(e.displayId,n++),t.writeUInt8(e.enabled?1:0,n++),t.writeUInt8(Math.round(e.opacity*255),n++),t.writeUInt8(e.pattern,n++),t.writeUInt8(e.colorR,n++),t.writeUInt8(e.colorG,n++),t.writeUInt8(e.colorB,n++),t.toUint8Array()}encodeSetAmbientEffectOrder(e){let t=ie.allocUnsafe(Fg),n=0;return t.writeUInt8(e.type,n++),t.writeUInt8(e.displayId,n++),t.writeUInt8(e.enabled?1:0,n++),t.writeUInt8(Math.min(255,Math.round(e.blur)),n++),t.writeUInt8(Math.min(255,Math.max(100,Math.round(e.scale*100))),n++),t.writeUInt8(Math.round(e.opacity*255),n++),t.toUint8Array()}encodeSetScalingModeOrder(e){let t=ie.allocUnsafe(Lg),n=0;return t.writeUInt8(e.type,n++),t.writeUInt8(e.displayId,n++),t.writeUInt8(e.mode,n++),t.toUint8Array()}encodeSetGridOrder(e){let t=ie.allocUnsafe(_g),n=0;return t.writeUInt8(e.type,n++),t.writeUInt8(e.displayId,n++),t.writeUInt8(e.enabled?1:0,n++),t.writeUInt8(e.colorR,n++),t.writeUInt8(e.colorG,n++),t.writeUInt8(e.colorB,n++),t.writeUInt8(e.colorA,n++),t.writeUInt8(Math.min(10,Math.max(1,e.lineWidth)),n++),t.toUint8Array()}encodeSwitchPaletteOrder(e){let t=ie.allocUnsafe($g),n=0;return t.writeUInt8(e.type,n++),t.writeUInt8(e.displayId,n++),t.writeUInt8(e.slotId,n++),t.toUint8Array()}encodeSetCellSizeOrder(e){let t=ie.allocUnsafe(Ng),n=0;return t.writeUInt8(e.type,n++),t.writeUInt8(e.displayId,n++),t.writeUInt8(e.cellWidth,n++),t.writeUInt8(e.cellHeight,n++),t.toUint8Array()}};J(mv,"PostProcessOrderEncoder");var II=mv,Gg=4,Fc=4,Xg=8,yv=class{encode(e){var o;let t=((o=e.renderPasses)==null?void 0:o.length)??0;if(t>Fc)throw new Error(`renderPasses supports up to ${Fc} entries, got ${t}`);let n=Xg+t*Gg,i=ie.allocUnsafe(n),s=0;if(i.writeUInt8(e.id,s++),i.writeUInt16BE(e.originX,s),s+=2,i.writeUInt16BE(e.originY,s),s+=2,i.writeUInt8(e.sizeX-1,s++),i.writeUInt8(e.sizeY-1,s++),i.writeUInt8(t,s++),t>0&&e.renderPasses)for(let a of e.renderPasses){let l=Math.max(0,Math.min(255,a.id)),u=Math.max(0,Math.min(255,a.zMin)),c=Math.max(0,Math.min(255,a.zMax)),d=a.enabled===!1?0:1;i.writeUInt8(l,s++),i.writeUInt8(u,s++),i.writeUInt8(c,s++),i.writeUInt8(d,s++)}return i.toUint8Array()}calculateSize(e){var n;let t=Math.min(((n=e.renderPasses)==null?void 0:n.length)??0,Fc);return Xg+t*Gg}};J(yv,"DisplayEncoder");var kI=yv,vv=class{constructor(){D(this,"layerEncoder"),D(this,"audioOrderEncoder"),D(this,"vibrationOrderEncoder"),D(this,"macroOrderEncoder"),D(this,"postProcessOrderEncoder"),D(this,"displayEncoder"),this.layerEncoder=new CI,this.audioOrderEncoder=new bI,this.vibrationOrderEncoder=new SI,this.macroOrderEncoder=new xI,this.postProcessOrderEncoder=new II,this.displayEncoder=new kI}encode(e){let t=e.layers.map(z=>this.layerEncoder.encode(z)),n=e.audioOrders||[],i=n.map(z=>this.audioOrderEncoder.encode(z)),s=e.vibrationOrders||[],o=s.map(z=>this.vibrationOrderEncoder.encode(z)),a=e.macroOrders||[],l=a.map(z=>this.macroOrderEncoder.encode(z)),u=e.postProcessOrders||[],c=u.map(z=>this.postProcessOrderEncoder.encode(z)),d=9,h=e.displays.reduce((z,P)=>z+this.displayEncoder.calculateSize(P),0),f=2,p=t.reduce((z,P)=>z+P.length,0),m=1,S=i.reduce((z,P)=>z+P.length,0),w=1,g=o.reduce((z,P)=>z+P.length,0),y=1,C=l.reduce((z,P)=>z+P.length,0),x=1,I=c.reduce((z,P)=>z+P.length,0),E=d+h+f+p+m+S+w+g+y+C+x+I,A=ie.allocUnsafe(E),R=0,F=typeof e.tick=="bigint"?e.tick:BigInt(e.tick);A.writeBigUInt64BE(F,R),R+=8,A.writeUInt8(e.displays.length,R),R+=1;for(let z of e.displays){let P=this.displayEncoder.encode(z);ie.from(P).copy(A,R),R+=P.length}A.writeUInt16BE(e.layers.length,R),R+=2;for(let z of t)ie.from(z).copy(A,R),R+=z.length;A.writeUInt8(n.length,R),R+=1;for(let z of i)ie.from(z).copy(A,R),R+=z.length;A.writeUInt8(s.length,R),R+=1;for(let z of o)ie.from(z).copy(A,R),R+=z.length;A.writeUInt8(a.length,R),R+=1;for(let z of l)ie.from(z).copy(A,R),R+=z.length;A.writeUInt8(u.length,R),R+=1;for(let z of c)ie.from(z).copy(A,R),R+=z.length;return A.toUint8Array()}calculateSize(e){let t=e.displays.reduce((f,p)=>f+this.displayEncoder.calculateSize(p),0),n=2,i=e.layers.reduce((f,p)=>f+this.layerEncoder.calculateSize(p),0),s=1,o=(e.audioOrders||[]).reduce((f,p)=>f+this.audioOrderEncoder.calculateSize(p),0),a=1,l=(e.vibrationOrders||[]).reduce((f,p)=>f+this.vibrationOrderEncoder.calculateSize(p),0),u=1,c=(e.macroOrders||[]).reduce((f,p)=>f+this.macroOrderEncoder.calculateSize(p),0),d=1,h=(e.postProcessOrders||[]).reduce((f,p)=>f+this.postProcessOrderEncoder.calculateSize(p),0);return 9+t+n+i+s+o+a+l+u+c+d+h}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=ie.allocUnsafe(15),n=typeof e=="bigint"?e:BigInt(e);return t.writeBigUInt64BE(n,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()}};J(vv,"UpdatePacketEncoder");var EI=vv,MI=(r=>(r[r.ColorPalette=1]="ColorPalette",r[r.Sprite=2]="Sprite",r[r.MulticolorSprite=3]="MulticolorSprite",r[r.Sound=5]="Sound",r[r.Macro=7]="Macro",r[r.ImageFont=8]="ImageFont",r[r.ImageFontBlock=9]="ImageFontBlock",r))(MI||{}),wv=class{encode(e){let t=JSON.stringify(e.template),n=new TextEncoder().encode(t);if(n.length>65535)throw new Error(`Macro template JSON too large: ${n.length} bytes (max 65535)`);let i=4+n.length,s=ie.allocUnsafe(i),o=0;return s.writeUInt8(7,o++),s.writeUInt8(e.macroId,o++),s.writeUInt16BE(n.length,o),o+=2,s.toUint8Array().set(n,o),s.toUint8Array()}calculateSize(e){let t=JSON.stringify(e.template);return 4+new TextEncoder().encode(t).length}};J(wv,"MacroLoadEncoder");var UI=wv,Cv=class{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 n=e.slotId!==void 0,i=n?4:3,s=ie.allocUnsafe(i+t*6),o=0;s.writeUInt8(1,o++),s.writeUInt8(n?255:0,o++),n&&s.writeUInt8(e.slotId,o++),s.writeUInt8(t,o++);for(let a of e.colors)s.writeUInt8(a.colorId,o++),s.writeUInt8(a.r,o++),s.writeUInt8(a.g,o++),s.writeUInt8(a.b,o++),s.writeUInt8(a.a??255,o++),s.writeUInt8(a.e??0,o++);return s.toUint8Array()}encodeSprite(e){let t=e.sprites.length;if(t>255)throw new Error(`Sprite count ${t} exceeds maximum of 255`);let n=2;for(let o of e.sprites)n+=3,n+=o.data.length;let i=ie.allocUnsafe(n),s=0;i.writeUInt8(2,s++),i.writeUInt8(t,s++);for(let o of e.sprites){if(o.data.length!==o.sizeX*o.sizeY)throw new Error(`Sprite ${o.spriteId}: data length ${o.data.length} does not match size ${o.sizeX}x${o.sizeY}`);i.writeUInt8(o.spriteId,s++),i.writeUInt8(o.sizeX,s++),i.writeUInt8(o.sizeY,s++);for(let a of o.data)i.writeUInt8(a,s++)}return i.toUint8Array()}encodeMulticolorSprite(e){let t=e.sprites.length;if(t>255)throw new Error(`Sprite count ${t} exceeds maximum of 255`);let n=2;for(let o of e.sprites)n+=3,n+=o.data.length*3;let i=ie.allocUnsafe(n),s=0;i.writeUInt8(3,s++),i.writeUInt8(t,s++);for(let o of e.sprites){if(o.data.length!==o.sizeX*o.sizeY)throw new Error(`Sprite ${o.spriteId}: data length ${o.data.length} does not match size ${o.sizeX}x${o.sizeY}`);i.writeUInt8(o.spriteId,s++),i.writeUInt8(o.sizeX,s++),i.writeUInt8(o.sizeY,s++);for(let a of o.data)i.writeUInt8(a.charCode,s++),i.writeUInt8(a.fgColorId,s++),i.writeUInt8(a.bgColorId,s++)}return i.toUint8Array()}encodeSound(e){let t=e.sounds.length;if(t>255)throw new Error(`Sound count ${t} exceeds maximum of 255`);let n=2;for(let o of e.sounds){if(o.midiData.length>65535)throw new Error(`Sound ${o.soundId}: MIDI data size ${o.midiData.length} exceeds maximum of 65535 bytes`);n+=3,n+=o.midiData.length}let i=ie.allocUnsafe(n),s=0;i.writeUInt8(5,s++),i.writeUInt8(t,s++);for(let o of e.sounds){i.writeUInt8(o.soundId,s++),i.writeUInt16BE(o.midiData.length,s),s+=2;for(let a=0;a<o.midiData.length;a++)i.writeUInt8(o.midiData[a],s++)}return i.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 t=ie.allocUnsafe(6),n=0;return t.writeUInt8(8,n++),t.writeUInt8(e.glyphWidth,n++),t.writeUInt8(e.glyphHeight,n++),t.writeUInt8(e.cellWidth,n++),t.writeUInt8(e.cellHeight,n++),t.writeUInt8(e.atlasBlocks,n++),t.toUint8Array()}encodeImageFontBlock(e){let t=6+e.imageData.length,n=ie.allocUnsafe(t),i=0;n.writeUInt8(9,i++),n.writeUInt8(e.blockIndex,i++),n.writeUInt32LE(e.imageData.length,i),i+=4;for(let s=0;s<e.imageData.length;s++)n.writeUInt8(e.imageData[s],i++);return n.toUint8Array()}};J(Cv,"LoadEncoder");var Lc=Cv,bv=class{decode(e,t=0){let n=t,i=e.readUInt8(t++);if(i!==7)throw new Error(`Expected LoadType.Macro (0x07), got 0x${i.toString(16)}`);let s=e.readUInt8(t++),o=e.readUInt16BE(t);t+=2;let a=e.toUint8Array().subarray(t,t+o);t+=o;let l=new TextDecoder().decode(a),u=JSON.parse(l);return{load:{loadType:7,macroId:s,template:u},bytesRead:t-n}}};J(bv,"MacroLoadDecoder");var AI=bv,Sv=class{decode(e,t=0){let n=ie.from(e);if(t>=n.length)throw new Error("Buffer too short to decode load type");let i=n.readUInt8(t);switch(i){case 1:return this.decodeColorPalette(n,t);case 2:return this.decodeSprite(n,t);case 3:return this.decodeMulticolorSprite(n,t);case 5:return this.decodeSound(n,t);case 7:return this.decodeMacro(n,t);case 8:return this.decodeImageFont(n,t);case 9:return this.decodeImageFontBlock(n,t);default:throw new Error(`Unknown load type: 0x${i.toString(16)}`)}}decodeColorPalette(e,t){let n=t;this.checkSize(e,t,3,"ColorPalette header"),e.readUInt8(t++);let i=e.readUInt8(t++)===255,s;i&&(this.checkSize(e,t,1,"ColorPalette slotId"),s=e.readUInt8(t++));let o=e.readUInt8(t++);this.checkSize(e,t,o*6,`ColorPalette ${o} colors`);let a=[];for(let l=0;l<o;l++)a.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:a},bytesRead:t-n}}decodeSprite(e,t){let n=t;this.checkSize(e,t,2,"Sprite header"),e.readUInt8(t++);let i=e.readUInt8(t++),s=[];for(let o=0;o<i;o++){this.checkSize(e,t,3,`Sprite ${o} header`);let a=e.readUInt8(t++),l=e.readUInt8(t++),u=e.readUInt8(t++),c=l*u;this.checkSize(e,t,c,`Sprite ${o} data`);let d=[];for(let h=0;h<c;h++)d.push(e.readUInt8(t++));s.push({spriteId:a,sizeX:l,sizeY:u,data:d})}return{load:{loadType:2,sprites:s},bytesRead:t-n}}decodeMulticolorSprite(e,t){let n=t;this.checkSize(e,t,2,"MulticolorSprite header"),e.readUInt8(t++);let i=e.readUInt8(t++),s=[];for(let o=0;o<i;o++){this.checkSize(e,t,3,`MulticolorSprite ${o} header`);let a=e.readUInt8(t++),l=e.readUInt8(t++),u=e.readUInt8(t++),c=l*u;this.checkSize(e,t,c*3,`MulticolorSprite ${o} data`);let d=[];for(let h=0;h<c;h++)d.push({charCode:e.readUInt8(t++),fgColorId:e.readUInt8(t++),bgColorId:e.readUInt8(t++)});s.push({spriteId:a,sizeX:l,sizeY:u,data:d})}return{load:{loadType:3,sprites:s},bytesRead:t-n}}decodeSound(e,t){let n=t;this.checkSize(e,t,2,"Sound header"),e.readUInt8(t++);let i=e.readUInt8(t++),s=[];for(let o=0;o<i;o++){this.checkSize(e,t,3,`Sound ${o} header`);let a=e.readUInt8(t++),l=e.readUInt16BE(t);t+=2,this.checkSize(e,t,l,`Sound ${o} MIDI data`);let u=new Uint8Array(l);for(let c=0;c<l;c++)u[c]=e.readUInt8(t++);s.push({soundId:a,midiData:u})}return{load:{loadType:5,sounds:s},bytesRead:t-n}}checkSize(e,t,n,i){if(t+n>e.length)throw new Error(`Buffer too short for ${i}: need ${n} bytes at offset ${t}, but only ${e.length-t} bytes remaining`)}decodeMacro(e,t){return new AI().decode(e,t)}decodeImageFont(e,t){let n=t;this.checkSize(e,t,6,"ImageFont header"),e.readUInt8(t++);let i=e.readUInt8(t++),s=e.readUInt8(t++),o=e.readUInt8(t++),a=e.readUInt8(t++),l=e.readUInt8(t++);if(![1,4,16].includes(l))throw new Error(`Invalid atlasBlocks value: ${l}. Must be 1, 4, or 16.`);return{load:{loadType:8,glyphWidth:i,glyphHeight:s,cellWidth:o,cellHeight:a,atlasBlocks:l},bytesRead:t-n}}decodeImageFontBlock(e,t){let n=t;this.checkSize(e,t,2,"ImageFontBlock header"),e.readUInt8(t++);let i=e.readUInt8(t++);this.checkSize(e,t,4,"ImageFontBlock data size");let s=e.readUInt32LE(t);t+=4,this.checkSize(e,t,s,"ImageFontBlock data");let o=new Uint8Array(s);for(let a=0;a<s;a++)o[a]=e.readUInt8(t++);return{load:{loadType:9,blockIndex:i,imageData:o},bytesRead:t-n}}};J(Sv,"LoadDecoder");var TI=Sv,RI=4,Kg=4,Zg=8,xv=class{decode(e,t=0){this.checkSize(e,t,Zg);let n=t,i=e.readUInt8(n++),s=e.readUInt16BE(n);n+=2;let o=e.readUInt16BE(n);n+=2;let a=e.readUInt8(n++)+1,l=e.readUInt8(n++)+1,u=e.readUInt8(n++);if(u>Kg)throw new Error(`Invalid renderPass count: ${u} (max ${Kg})`);let c=u*RI;this.checkSize(e,n,c);let d=[];for(let h=0;h<u;h++){let f=e.readUInt8(n++),p=e.readUInt8(n++),m=e.readUInt8(n++),S=e.readUInt8(n++);d.push({id:f,zMin:p,zMax:m,enabled:(S&1)!==0})}return{display:{id:i,originX:s,originY:o,sizeX:a,sizeY:l,renderPasses:d.length>0?d:void 0},bytesRead:Zg+c}}checkSize(e,t,n){if(t+n>e.length)throw new Error(`Buffer too short for display: need ${n} bytes at offset ${t}, but only ${e.length-t} bytes available`)}};J(xv,"DisplayDecoder");var PI=xv,Iv=class{constructor(){D(this,"charCodeSize",_1)}decode(e,t=0,n=!1){if(t>=e.length)throw new Error("Buffer too short to decode order type");let i=e.readUInt8(t);switch(i){case 1:return this.decodeCharOrder(e,t,n);case 2:return this.decodeTextOrder(e,t);case 23:return this.decodeTextMultilineOrder(e,t);case 3:return this.decodeSubFrameOrder(e,t,n);case 4:return this.decodeSubFrameMultiColorOrder(e,t,n);case 5:return this.decodeFullFrameOrder(e,t,n);case 6:return this.decodeFullFrameMultiColorOrder(e,t,n);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,n);case 11:return this.decodeDotCloudOrder(e,t,n);case 12:return this.decodeDotCloudMultiColorOrder(e,t,n);case 17:return this.decodeBitmaskOrder(e,t,n);case 18:return this.decodeBitmask4Order(e,t,n);case 24:return this.decodeBitmask16Order(e,t,n);case 25:return this.decodePolylineOrder(e,t,n);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,n);case 20:return this.decodeFillCharOrder(e,t,n);case 21:return this.decodeFillSpriteOrder(e,t);case 22:return this.decodeFillSpriteMultiColorOrder(e,t);default:throw new Error(`Unknown order type: 0x${i.toString(16)}`)}}readCharCode(e,t,n){return n?[e.readUInt16LE(t),t+2]:[e.readUInt8(t),t+1]}decodeCharOrder(e,t,n){let i=5+this.charCodeSize(n);this.checkSize(e,t,i);let s=t;e.readUInt8(s++);let o=e.readUInt8(s++),a=e.readUInt8(s++),[l,u]=this.readCharCode(e,s,n);s=u;let c=e.readUInt8(s++),d=e.readUInt8(s++);return{order:{type:1,posX:o,posY:a,charCode:l,bgColorCode:c,fgColorCode:d},bytesRead:i}}decodeTextOrder(e,t){this.checkSize(e,t,5);let n=t,i=e.readUInt8(n+3);this.checkSize(e,t,5+i);let s=e.subarray(n+4,n+4+i),o=new TextDecoder().decode(s.toUint8Array());return{order:{type:2,posX:e.readUInt8(n+1),posY:e.readUInt8(n+2),text:o,bgColorCode:e.readUInt8(n+4+i),fgColorCode:e.readUInt8(n+5+i)},bytesRead:6+i}}decodeTextMultilineOrder(e,t){this.checkSize(e,t,5);let n=t,i=e.readUInt8(n+3);this.checkSize(e,t,5+i);let s=e.subarray(n+4,n+4+i),o=new TextDecoder().decode(s.toUint8Array());return{order:{type:23,posX:e.readUInt8(n+1),posY:e.readUInt8(n+2),text:o,bgColorCode:e.readUInt8(n+4+i),fgColorCode:e.readUInt8(n+5+i)},bytesRead:6+i}}decodeSubFrameOrder(e,t,n){this.checkSize(e,t,7);let i=t,s=this.charCodeSize(n),o=e.readUInt8(i+3)+1,a=e.readUInt8(i+4)+1,l=o*a;this.checkSize(e,t,7+l*s);let u=[],c=i+7;for(let d=0;d<l;d++){let[h,f]=this.readCharCode(e,c,n);u.push(h),c=f}return{order:{type:3,posX:e.readUInt8(i+1),posY:e.readUInt8(i+2),sizeX:o,sizeY:a,bgColorCode:e.readUInt8(i+5),fgColorCode:e.readUInt8(i+6),frame:u},bytesRead:7+l*s}}decodeSubFrameMultiColorOrder(e,t,n){this.checkSize(e,t,5);let i=t,s=this.charCodeSize(n),o=e.readUInt8(i+3)+1,a=e.readUInt8(i+4)+1,l=o*a,u=s+2;this.checkSize(e,t,5+l*u);let c=[],d=i+5;for(let h=0;h<l;h++){let[f,p]=this.readCharCode(e,d,n);d=p,c.push({charCode:f,bgColorCode:e.readUInt8(d++),fgColorCode:e.readUInt8(d++)})}return{order:{type:4,posX:e.readUInt8(i+1),posY:e.readUInt8(i+2),sizeX:o,sizeY:a,frame:c},bytesRead:5+l*u}}decodeFullFrameOrder(e,t,n,i){this.checkSize(e,t,3);let s=t,o=this.charCodeSize(n),a=i||Math.floor((e.length-t-3)/o);this.checkSize(e,t,3+a*o);let l=[],u=s+3;for(let c=0;c<a;c++){let[d,h]=this.readCharCode(e,u,n);l.push(d),u=h}return{order:{type:5,bgColorCode:e.readUInt8(s+1),fgColorCode:e.readUInt8(s+2),frame:l},bytesRead:3+a*o}}decodeFullFrameMultiColorOrder(e,t,n,i){this.checkSize(e,t,1);let s=t,o=this.charCodeSize(n)+2,a=i||Math.floor((e.length-t-1)/o);this.checkSize(e,t,1+a*o);let l=[],u=s+1;for(let c=0;c<a;c++){let[d,h]=this.readCharCode(e,u,n);u=h,l.push({charCode:d,bgColorCode:e.readUInt8(u++),fgColorCode:e.readUInt8(u++)})}return{order:{type:6,frame:l},bytesRead:1+a*o}}decodeSpriteOrder(e,t){this.checkSize(e,t,6);let n=t;return{order:{type:7,posX:e.readUInt8(n+1),posY:e.readUInt8(n+2),spriteIndex:e.readUInt8(n+3),bgColorCode:e.readUInt8(n+4),fgColorCode:e.readUInt8(n+5)},bytesRead:6}}decodeSpriteMultiColorOrder(e,t){this.checkSize(e,t,4);let n=t;return{order:{type:8,posX:e.readUInt8(n+1),posY:e.readUInt8(n+2),spriteIndex:e.readUInt8(n+3)},bytesRead:4}}decodeColorMapOrder(e,t){this.checkSize(e,t,5);let n=t,i=e.readUInt8(n+3)+1,s=e.readUInt8(n+4)+1,o=i*s;this.checkSize(e,t,5+o*2);let a=[];for(let l=0;l<o;l++){let u=n+5+l*2;a.push({bgColorCode:e.readUInt8(u),fgColorCode:e.readUInt8(u+1)})}return{order:{type:9,posX:e.readUInt8(n+1),posY:e.readUInt8(n+2),sizeX:i,sizeY:s,colorData:a},bytesRead:5+o*2}}decodeShapeOrder(e,t,n){this.checkSize(e,t,2);let i=t,s=e.readUInt8(i+1),{shapeData:o,bytesRead:a}=this.decodeShapeData(e,i+2,s,n);return{order:{type:10,shapeType:s,shapeData:o},bytesRead:2+a}}decodeShapeData(e,t,n,i){let s=t,o=this.charCodeSize(i);switch(n){case 1:{let a=7+o;this.checkSize(e,t,a);let l=e.readUInt8(s++),u=e.readUInt8(s++),c=e.readUInt8(s++)+1,d=e.readUInt8(s++)+1,h=e.readUInt8(s++)===1,[f,p]=this.readCharCode(e,s,i);s=p;let m=e.readUInt8(s++),S=e.readUInt8(s++);return{shapeData:{posX:l,posY:u,width:c,height:d,filled:h,charCode:f,bgColorCode:m,fgColorCode:S},bytesRead:a}}case 2:{let a=6+o;this.checkSize(e,t,a);let l=e.readUInt8(s++),u=e.readUInt8(s++),c=e.readUInt8(s++)+1,d=e.readUInt8(s++)===1,[h,f]=this.readCharCode(e,s,i);s=f;let p=e.readUInt8(s++),m=e.readUInt8(s++);return{shapeData:{centerX:l,centerY:u,radius:c,filled:d,charCode:h,bgColorCode:p,fgColorCode:m},bytesRead:a}}case 3:{let a=6+o;this.checkSize(e,t,a);let l=e.readUInt8(s++),u=e.readUInt8(s++),c=e.readUInt8(s++),d=e.readUInt8(s++),[h,f]=this.readCharCode(e,s,i);s=f;let p=e.readUInt8(s++),m=e.readUInt8(s++);return{shapeData:{x1:l,y1:u,x2:c,y2:d,charCode:h,bgColorCode:p,fgColorCode:m},bytesRead:a}}case 4:{let a=7+o;this.checkSize(e,t,a);let l=e.readUInt8(s++),u=e.readUInt8(s++),c=e.readUInt8(s++)+1,d=e.readUInt8(s++)+1,h=e.readUInt8(s++)===1,[f,p]=this.readCharCode(e,s,i);s=p;let m=e.readUInt8(s++),S=e.readUInt8(s++);return{shapeData:{centerX:l,centerY:u,radiusX:c,radiusY:d,filled:h,charCode:f,bgColorCode:m,fgColorCode:S},bytesRead:a}}case 5:{let a=9+o;this.checkSize(e,t,a);let l=e.readUInt8(s++),u=e.readUInt8(s++),c=e.readUInt8(s++),d=e.readUInt8(s++),h=e.readUInt8(s++),f=e.readUInt8(s++),p=e.readUInt8(s++)===1,[m,S]=this.readCharCode(e,s,i);s=S;let w=e.readUInt8(s++),g=e.readUInt8(s++);return{shapeData:{x1:l,y1:u,x2:c,y2:d,x3:h,y3:f,filled:p,charCode:m,bgColorCode:w,fgColorCode:g},bytesRead:a}}default:throw new Error(`Unknown shape type: ${n}`)}}decodeDotCloudOrder(e,t,n){let i=1+this.charCodeSize(n)+2+2;this.checkSize(e,t,i);let s=t;e.readUInt8(s++);let[o,a]=this.readCharCode(e,s,n);s=a;let l=e.readUInt8(s++),u=e.readUInt8(s++),c=e.readUInt16BE(s);s+=2,this.checkSize(e,t,i+c*2);let d=[];for(let h=0;h<c;h++)d.push({posX:e.readUInt8(s++),posY:e.readUInt8(s++)});return{order:{type:11,charCode:o,bgColorCode:l,fgColorCode:u,positions:d},bytesRead:i+c*2}}decodeDotCloudMultiColorOrder(e,t,n){this.checkSize(e,t,3);let i=this.charCodeSize(n),s=t,o=e.readUInt16BE(s+1),a=i+4;this.checkSize(e,t,3+o*a);let l=[],u=s+3;for(let c=0;c<o;c++){let[d,h]=this.readCharCode(e,u,n);u=h,l.push({charCode:d,bgColorCode:e.readUInt8(u++),fgColorCode:e.readUInt8(u++),posX:e.readUInt8(u++),posY:e.readUInt8(u++)})}return{order:{type:12,dots:l},bytesRead:3+o*a}}decodeBitmaskOrder(e,t,n){let i=8+this.charCodeSize(n);this.checkSize(e,t,i);let s=t;e.readUInt8(s++);let o=e.readUInt8(s++),a=e.readUInt8(s++),l=e.readUInt8(s++)+1,u=e.readUInt8(s++)+1,[c,d]=this.readCharCode(e,s,n);s=d;let h=e.readUInt8(s++),f=e.readUInt8(s++),p=e.readUInt8(s++)===1,m=Math.ceil(l*u/8);this.checkSize(e,t,i+m);let S=new Uint8Array(m);for(let w=0;w<m;w++)S[w]=e.readUInt8(s+w);return{order:{type:17,posX:o,posY:a,sizeX:l,sizeY:u,charCode:c,bgColorCode:h,fgColorCode:f,override:p,mask:S},bytesRead:i+m}}decodeBitmask4Order(e,t,n){let i=6+3*(this.charCodeSize(n)+2);this.checkSize(e,t,i);let s=t;e.readUInt8(s++);let o=e.readUInt8(s++),a=e.readUInt8(s++),l=e.readUInt8(s++)+1,u=e.readUInt8(s++)+1,c=e.readUInt8(s++)===1,d=Math.ceil(l*u/4);this.checkSize(e,t,i+d);let h=[];for(let p=0;p<3;p++){let[m,S]=this.readCharCode(e,s,n);s=S,h.push({charCode:m,bgColorCode:e.readUInt8(s++),fgColorCode:e.readUInt8(s++)})}let f=new Uint8Array(d);for(let p=0;p<d;p++)f[p]=e.readUInt8(s+p);return{order:{type:18,posX:o,posY:a,sizeX:l,sizeY:u,override:c,variants:h,mask:f},bytesRead:i+d}}decodeBitmask16Order(e,t,n){let i=6+15*(this.charCodeSize(n)+2);this.checkSize(e,t,i);let s=t;e.readUInt8(s++);let o=e.readUInt8(s++),a=e.readUInt8(s++),l=e.readUInt8(s++)+1,u=e.readUInt8(s++)+1,c=e.readUInt8(s++)===1,d=Math.ceil(l*u/2);this.checkSize(e,t,i+d);let h=[];for(let p=0;p<15;p++){let[m,S]=this.readCharCode(e,s,n);s=S,h.push({charCode:m,bgColorCode:e.readUInt8(s++),fgColorCode:e.readUInt8(s++)})}let f=new Uint8Array(d);for(let p=0;p<d;p++)f[p]=e.readUInt8(s+p);return{order:{type:24,posX:o,posY:a,sizeX:l,sizeY:u,override:c,variants:h,mask:f},bytesRead:i+d}}decodePolylineOrder(e,t,n){let i=4+this.charCodeSize(n);this.checkSize(e,t,i);let s=t;e.readUInt8(s++);let[o,a]=this.readCharCode(e,s,n);s=a;let l=e.readUInt8(s++),u=e.readUInt8(s++),c=e.readUInt8(s++);this.checkSize(e,t,i+c*2);let d=[];for(let h=0;h<c;h++)d.push({x:e.readUInt8(s++),y:e.readUInt8(s++)});return{order:{type:25,charCode:o,fgColorCode:l,bgColorCode:u,points:d},bytesRead:i+c*2}}decodeSpriteCloudOrder(e,t){this.checkSize(e,t,6);let n=t,i=e.readUInt16BE(n+4);this.checkSize(e,t,6+i*2);let s=[];for(let o=0;o<i;o++){let a=n+6+o*2;s.push({posX:e.readUInt8(a),posY:e.readUInt8(a+1)})}return{order:{type:13,spriteIndex:e.readUInt8(n+1),bgColorCode:e.readUInt8(n+2),fgColorCode:e.readUInt8(n+3),positions:s},bytesRead:6+i*2}}decodeSpriteCloudMultiColorOrder(e,t){this.checkSize(e,t,4);let n=t,i=e.readUInt16BE(n+2);this.checkSize(e,t,4+i*2);let s=[];for(let o=0;o<i;o++){let a=n+4+o*2;s.push({posX:e.readUInt8(a),posY:e.readUInt8(a+1)})}return{order:{type:14,spriteIndex:e.readUInt8(n+1),positions:s},bytesRead:4+i*2}}decodeSpriteCloudVariedOrder(e,t){this.checkSize(e,t,3);let n=t,i=e.readUInt16BE(n+1);this.checkSize(e,t,3+i*5);let s=[];for(let o=0;o<i;o++){let a=n+3+o*5;s.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:s},bytesRead:3+i*5}}decodeSpriteCloudVariedMultiColorOrder(e,t){this.checkSize(e,t,3);let n=t,i=e.readUInt16BE(n+1);this.checkSize(e,t,3+i*3);let s=[];for(let o=0;o<i;o++){let a=n+3+o*3;s.push({spriteIndex:e.readUInt8(a),posX:e.readUInt8(a+1),posY:e.readUInt8(a+2)})}return{order:{type:16,sprites:s},bytesRead:3+i*3}}decodeFillOrder(e,t,n){let i=3+this.charCodeSize(n);this.checkSize(e,t,i);let s=t;e.readUInt8(s++);let[o,a]=this.readCharCode(e,s,n);s=a;let l=e.readUInt8(s++),u=e.readUInt8(s++);return{order:{type:19,charCode:o,bgColorCode:l,fgColorCode:u},bytesRead:i}}decodeFillCharOrder(e,t,n){this.checkSize(e,t,5);let i=this.charCodeSize(n),s=t,o=e.readUInt8(s+1)+1,a=e.readUInt8(s+2)+1,l=o*a,u=5+l*i;this.checkSize(e,t,u);let c=[],d=s+5;for(let h=0;h<l;h++){let[f,p]=this.readCharCode(e,d,n);c.push(f),d=p}return{order:{type:20,patternWidth:o,patternHeight:a,bgColorCode:e.readUInt8(s+3),fgColorCode:e.readUInt8(s+4),pattern:c},bytesRead:u}}decodeFillSpriteOrder(e,t){this.checkSize(e,t,4);let n=t;return{order:{type:21,spriteIndex:e.readUInt8(n+1),bgColorCode:e.readUInt8(n+2),fgColorCode:e.readUInt8(n+3)},bytesRead:4}}decodeFillSpriteMultiColorOrder(e,t){this.checkSize(e,t,2);let n=t;return{order:{type:22,spriteIndex:e.readUInt8(n+1)},bytesRead:2}}checkSize(e,t,n){if(t+n>e.length)throw new Error(`Buffer too short: need ${n} bytes at offset ${t}, but only ${e.length-t} bytes available`)}};J(Iv,"OrderDecoder");var BI=Iv,zI=32,DI=64,kv=class{constructor(){D(this,"orderDecoder"),this.orderDecoder=new BI}decode(e,t=0){this.checkSize(e,t,13);let n=t,i=e.readUInt16BE(n);n+=2;let s=e.readUInt8(n++),o=e.readUInt8(n++),a=e.readUInt16BE(n);n+=2;let l=e.readUInt16BE(n);n+=2;let u=e.readUInt16BE(n);n+=2;let c=e.readUInt16BE(n);n+=2;let d=e.readUInt8(n++),h=(s&zI)!==0,f=(s&DI)!==0,p=[],m=n;for(let S=0;S<d;S++){let w=this.orderDecoder.decode(e,m,f);p.push(w.order),m+=w.bytesRead}return{layer:{id:i,updateFlags:s,zIndex:o,originX:a,originY:l,width:u,height:c,orderCount:d,orders:p,isMacroLayer:h,is16bit:f},bytesRead:m-t}}checkSize(e,t,n){if(t+n>e.length)throw new Error(`Buffer too short for layer: need ${n} bytes at offset ${t}, but only ${e.length-t} bytes available`)}};J(kv,"LayerDecoder");var OI=kv,Ev=class{decode(e,t=0){if(t>=e.length)throw new Error("Buffer too short to decode audio order type");let n=e.readUInt8(t);switch(n){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${n.toString(16)}`)}}decodePlaySoundOrder(e,t){this.checkSize(e,t,5);let n=t,i=e.readUInt8(n++),s=e.readUInt8(n++),o=e.readUInt16BE(n);n+=2;let a=e.readUInt8(n++),l={type:i,soundId:s,instanceId:o,flags:a};return a&2&&(this.checkSize(e,n,1),l.volume=e.readUInt8(n++)),a&4&&(this.checkSize(e,n,1),l.pitch=e.readUInt8(n++)),a&8&&(this.checkSize(e,n,1),l.fadeIn=e.readUInt8(n++)),a&16&&(this.checkSize(e,n,4),l.posX=e.readUInt16BE(n),n+=2,l.posY=e.readUInt16BE(n),n+=2),a&32&&(this.checkSize(e,n,1),l.lowpass=e.readUInt8(n++)),a&64&&(this.checkSize(e,n,1),l.highpass=e.readUInt8(n++)),a&128&&(this.checkSize(e,n,1),l.reverb=e.readUInt8(n++)),{order:l,bytesRead:n-t}}decodePlayGlobalSoundOrder(e,t){this.checkSize(e,t,5);let n=t,i=e.readUInt8(n++),s=e.readUInt8(n++),o=e.readUInt16BE(n);n+=2;let a=e.readUInt8(n++),l={type:i,soundId:s,instanceId:o,flags:a};return a&2&&(this.checkSize(e,n,1),l.volume=e.readUInt8(n++)),a&4&&(this.checkSize(e,n,1),l.pitch=e.readUInt8(n++)),a&8&&(this.checkSize(e,n,1),l.fadeIn=e.readUInt8(n++)),a&32&&(this.checkSize(e,n,1),l.lowpass=e.readUInt8(n++)),a&64&&(this.checkSize(e,n,1),l.highpass=e.readUInt8(n++)),a&128&&(this.checkSize(e,n,1),l.reverb=e.readUInt8(n++)),{order:l,bytesRead:n-t}}decodeStopSoundOrder(e,t){this.checkSize(e,t,2);let n=t,i=e.readUInt8(n++),s=e.readUInt8(n++),o={type:i,targetType:s};return s===0?(this.checkSize(e,n,2),o.target=e.readUInt16BE(n),n+=2):s===1&&(this.checkSize(e,n,1),o.target=e.readUInt8(n++)),{order:o,bytesRead:n-t}}decodeFadeOutSoundOrder(e,t){this.checkSize(e,t,3);let n=t,i=e.readUInt8(n++),s=e.readUInt8(n++),o=e.readUInt8(n++),a={type:i,targetType:s,duration:o};return s===0?(this.checkSize(e,n,2),a.target=e.readUInt16BE(n),n+=2):s===1&&(this.checkSize(e,n,1),a.target=e.readUInt8(n++)),{order:a,bytesRead:n-t}}decodePauseSoundOrder(e,t){this.checkSize(e,t,2);let n=t,i=e.readUInt8(n++),s=e.readUInt8(n++),o={type:i,targetType:s};return s===0?(this.checkSize(e,n,2),o.target=e.readUInt16BE(n),n+=2):s===1&&(this.checkSize(e,n,1),o.target=e.readUInt8(n++)),{order:o,bytesRead:n-t}}decodeResumeSoundOrder(e,t){this.checkSize(e,t,2);let n=t,i=e.readUInt8(n++),s=e.readUInt8(n++),o={type:i,targetType:s};return s===0?(this.checkSize(e,n,2),o.target=e.readUInt16BE(n),n+=2):s===1&&(this.checkSize(e,n,1),o.target=e.readUInt8(n++)),{order:o,bytesRead:n-t}}decodeSetListenerPositionOrder(e,t){this.checkSize(e,t,5);let n=t,i=e.readUInt8(n++),s=e.readUInt16BE(n);n+=2;let o=e.readUInt16BE(n);return n+=2,{order:{type:i,x:s,y:o},bytesRead:5}}decodeConfigureSpatialOrder(e,t){this.checkSize(e,t,5);let n=t;return{order:{type:e.readUInt8(n),maxDistance:e.readUInt8(n+1),referenceDistance:e.readUInt8(n+2),rolloffFactor:e.readUInt8(n+3),panSpread:e.readUInt8(n+4)},bytesRead:5}}decodeSetSoundEffectsOrder(e,t){this.checkSize(e,t,4);let n=t,i=e.readUInt8(n++),s=e.readUInt16BE(n);n+=2;let o=e.readUInt8(n++),a={type:i,instanceId:s,flags:o};return o&1&&(this.checkSize(e,n,1),a.lowpass=e.readUInt8(n++)),o&2&&(this.checkSize(e,n,1),a.highpass=e.readUInt8(n++)),o&4&&(this.checkSize(e,n,1),a.reverb=e.readUInt8(n++)),{order:a,bytesRead:n-t}}checkSize(e,t,n){if(t+n>e.length)throw new Error(`Buffer too short for audio order: need ${n} bytes at offset ${t}, but only ${e.length-t} bytes available`)}};J(Ev,"AudioOrderDecoder");var FI=Ev,Mv=class{decode(e,t=0){if(t>=e.length)throw new Error("Buffer too short to decode vibration order type");let n=e.readUInt8(t);switch(n){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${n.toString(16)}`)}}decodeMobileVibrateOrder(e,t){let n=t,i=e.readUInt8(n++),s=e.readUInt8(n++),o=e.readUInt8(n++),a=[];for(let u=0;u<o;u++)a.push(e.readUInt16BE(n)),n+=2;let l={type:i,flags:s,pattern:a};return s&1&&(l.intensity=e.readUInt8(n++)/255),{order:l,bytesRead:n-t}}decodeMobileCancelOrder(e,t){return{order:{type:2},bytesRead:1}}decodeGamepadVibrateOrder(e,t){let n=t,i=e.readUInt8(n++),s=e.readUInt8(n++),o=e.readUInt8(n++),a=e.readUInt16BE(n);n+=2;let l=e.readUInt8(n++),u=e.readUInt8(n++),c={type:i,flags:s,gamepadIndex:o,duration:a,strongMagnitude:l,weakMagnitude:u};return s&1&&(c.startDelay=e.readUInt16BE(n),n+=2),{order:c,bytesRead:n-t}}decodeGamepadCancelOrder(e,t){let n=t,i=e.readUInt8(n++),s=e.readUInt8(n++),o=e.readUInt8(n++);return{order:{type:i,flags:s,gamepadIndex:o},bytesRead:n-t}}};J(Mv,"VibrationOrderDecoder");var LI=Mv,Uv=class{decode(e,t=0){let n=e.readUInt8(t);switch(n){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${n.toString(16)}`)}}decodeAll(e,t,n){let i=[],s=0;for(let o=0;o<n;o++){let{order:a,bytesRead:l}=this.decode(e,t+s);i.push(a),s+=l}return{orders:i,bytesRead:s}}decodeCreateInstance(e,t){let n=t,i=e.readUInt8(t++),s=e.readUInt8(t++),o=e.readUInt8(t++),a=e.readUInt8(t++),l=e.readInt16BE(t);t+=2;let u=e.readInt16BE(t);t+=2;let c=e.readUInt8(t++),d=e.readUInt16BE(t);t+=2;let h=e.toUint8Array().subarray(t,t+d);t+=d;let f=new TextDecoder().decode(h),p=JSON.parse(f);return{order:{type:i,instanceId:s,macroId:o,layerId:a,x:l,y:u,tabIndex:c,params:p},bytesRead:t-n}}decodeUpdateInstance(e,t){let n=t,i=e.readUInt8(t++),s=e.readUInt8(t++),o=e.readUInt16BE(t);t+=2;let a=e.toUint8Array().subarray(t,t+o);t+=o;let l=new TextDecoder().decode(a),u=JSON.parse(l);return{order:{type:i,instanceId:s,params:u},bytesRead:t-n}}decodeRemoveInstance(e,t){let n=e.readUInt8(t),i=e.readUInt8(t+1);return{order:{type:n,instanceId:i},bytesRead:2}}};J(Uv,"MacroOrderDecoder");var _I=Uv,Av=class{decode(e,t){let n=e[t];switch(n){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: ${n}`)}}decodeSetConfigOrder(e,t){let n=t,i=e[n++],s=e[n++],o=e[n++],a={type:i,displayId:s,flags:o};return o&1&&(a.scanlines={enabled:e[n++]===1,opacity:e[n++]/255,pattern:e[n++],colorR:e[n++],colorG:e[n++],colorB:e[n++]}),o&2&&(a.ambientEffect={enabled:e[n++]===1,blur:e[n++],scale:e[n++]/100,opacity:e[n++]/255}),{order:a,bytesRead:n-t}}decodeSetScanlinesOrder(e,t){let n=t;return{order:{type:e[n++],displayId:e[n++],enabled:e[n++]===1,opacity:e[n++]/255,pattern:e[n++],colorR:e[n++],colorG:e[n++],colorB:e[n++]},bytesRead:n-t}}decodeSetAmbientEffectOrder(e,t){let n=t;return{order:{type:e[n++],displayId:e[n++],enabled:e[n++]===1,blur:e[n++],scale:e[n++]/100,opacity:e[n++]/255},bytesRead:n-t}}decodeSetScalingModeOrder(e,t){let n=t;return{order:{type:e[n++],displayId:e[n++],mode:e[n++]},bytesRead:n-t}}decodeSetGridOrder(e,t){let n=t;return{order:{type:e[n++],displayId:e[n++],enabled:e[n++]===1,colorR:e[n++],colorG:e[n++],colorB:e[n++],colorA:e[n++],lineWidth:e[n++]},bytesRead:n-t}}decodeSwitchPaletteOrder(e,t){let n=t;return{order:{type:e[n++],displayId:e[n++],slotId:e[n++]},bytesRead:n-t}}decodeSetCellSizeOrder(e,t){let n=t;return{order:{type:e[n++],displayId:e[n++],cellWidth:e[n++],cellHeight:e[n++]},bytesRead:n-t}}};J(Av,"PostProcessOrderDecoder");var $I=Av,Tv=class{constructor(){D(this,"displayDecoder"),D(this,"layerDecoder"),D(this,"audioOrderDecoder"),D(this,"vibrationOrderDecoder"),D(this,"macroOrderDecoder"),D(this,"postProcessOrderDecoder"),this.displayDecoder=new PI,this.layerDecoder=new OI,this.audioOrderDecoder=new FI,this.vibrationOrderDecoder=new LI,this.macroOrderDecoder=new _I,this.postProcessOrderDecoder=new $I}decode(e,t=0){let n=ie.from(e);this.checkSize(n,t,15);let i=t,s=Number(n.readBigUInt64BE(i));i+=8;let o=n.readUInt8(i);i+=1;let a=[],l=0;for(let A=0;A<o;A++){let R=this.displayDecoder.decode(n,i);a.push(R.display),i+=R.bytesRead,l+=R.bytesRead}this.checkSize(n,i,2);let u=n.readUInt16BE(i);i+=2;let c=[],d=0;for(let A=0;A<u;A++){let R=this.layerDecoder.decode(n,i);c.push({...R.layer,byteSize:R.bytesRead}),i+=R.bytesRead,d+=R.bytesRead}this.checkSize(n,i,1);let h=n.readUInt8(i);i+=1;let f=[],p=0;for(let A=0;A<h;A++){let R=this.audioOrderDecoder.decode(n,i);f.push(R.order),i+=R.bytesRead,p+=R.bytesRead}this.checkSize(n,i,1);let m=n.readUInt8(i);i+=1;let S=[],w=0;for(let A=0;A<m;A++){let R=this.vibrationOrderDecoder.decode(n,i);S.push(R.order),i+=R.bytesRead,w+=R.bytesRead}this.checkSize(n,i,1);let g=n.readUInt8(i);i+=1;let y=[],C=0;for(let A=0;A<g;A++){let R=this.macroOrderDecoder.decode(n,i);y.push(R.order),i+=R.bytesRead,C+=R.bytesRead}this.checkSize(n,i,1);let x=n.readUInt8(i);i+=1;let I=[],E=0;for(let A=0;A<x;A++){let R=this.postProcessOrderDecoder.decode(n.toUint8Array(),i);I.push(R.order),i+=R.bytesRead,E+=R.bytesRead}return{tick:s,displayCount:o,displays:a,layerCount:u,layers:c,audioOrderCount:h,audioOrders:f,vibrationOrderCount:m,vibrationOrders:S,macroOrderCount:g,macroOrders:y,postProcessOrderCount:x,postProcessOrders:I,__byteSizes:{displays:l,layers:d,audioOrders:p,vibrationOrders:w,macroOrders:C,postProcessOrders:E}}}isValid(e,t=0){let n=ie.from(e);try{return this.checkSize(n,t,15),!0}catch{return!1}}decodeHeader(e,t=0){let n=ie.from(e);this.checkSize(n,t,13);let i=t,s=Number(n.readBigUInt64BE(i));i+=8;let o=n.readUInt8(i);i+=1;for(let l=0;l<o;l++){let u=this.displayDecoder.decode(n,i);i+=u.bytesRead}this.checkSize(n,i,2);let a=n.readUInt16BE(i);return{tick:s,displayCount:o,layerCount:a}}checkSize(e,t,n){if(t+n>e.length)throw new Error(`Buffer too short for update packet: need ${n} bytes at offset ${t}, but only ${e.length-t} bytes available`)}};J(Tv,"UpdatePacketDecoder");var NI=Tv,nh=class Ts{constructor(e){this.engine=e,D(this,"colorCache",new Array(256)),D(this,"cellsBuffer",[]),D(this,"opacityBuffer",new Uint8Array(0)),D(this,"visibleLayersBuffer",[]),D(this,"visibleLayerIdsBuffer",[]),D(this,"passCellsBuffers",[]),D(this,"passOpacityBuffers",[]),this.rebuildColorCache()}static getChar(e){let t=Ts.charCache.get(e);return t===void 0&&(t=String.fromCharCode(e),Ts.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 n=e.x,i=e.x+e.width,s=e.y,o=e.y+e.height,a=t.x,l=t.x+256,u=t.y,c=t.y+256;return!(i<=a||n>=l||o<=u||s>=c)}rasterize(e,t,n){let i=this.normalizePasses(n);return this.rasterizeMultiPass(e,t,i)}rasterizeSinglePass(e,t){let n=e.width*e.height,i=this.cellsBuffer;i.length=n;for(let u=0;u<n;u++)i[u]?(i[u].char=" ",i[u].fgColorIndex=255,i[u].bgColorIndex=255,i[u].fgEmission=0,i[u].bgEmission=0):i[u]={char:" ",fgColorIndex:255,bgColorIndex:255,fgEmission:0,bgEmission:0};this.opacityBuffer.length<n?this.opacityBuffer=new Uint8Array(n):this.opacityBuffer.fill(0,0,n);let s=this.opacityBuffer,o=this.visibleLayersBuffer;o.length=0;for(let u=0;u<t.length;u++){let c=t[u];c.isEnabled()&&this.isLayerVisible(e,c.getOrigin())&&o.push(c)}o.sort((u,c)=>c.getZOrder()-u.getZOrder());let a=this.visibleLayerIdsBuffer;a.length=o.length;for(let u=0;u<o.length;u++)a[u]=o[u].getId();for(let u=0;u<e.height;u++)for(let c=0;c<e.width;c++){let d=u*e.width+c;if(s[d])continue;let h=e.x+c,f=e.y+u;for(let p=0;p<o.length;p++){let m=o[p],S=h-m.getOrigin().x,w=f-m.getOrigin().y,g=m.getWidth(),y=m.getHeight();if(S<0||S>=g||w<0||w>=y)continue;let C=w*g+S,x=m.getData(),I=x.getCharCode(C),E=x.getFgColorCode(C),A=x.getBgColorCode(C),R=i[d];if(I!==0&&R.char===" "&&(R.char=Ts.getChar(I)),E!==255&&R.fgColorIndex===255&&(R.fgColorIndex=E,R.fgEmission=this.getColorEmission(E)),A!==255){R.bgColorIndex===255&&(R.bgColorIndex=A,R.bgEmission=this.getColorEmission(A)),s[d]=1;break}}}let l=new Array(n);for(let u=0;u<n;u++)l[u]={char:i[u].char,fgColorIndex:i[u].fgColorIndex,bgColorIndex:i[u].bgColorIndex,fgEmission:i[u].fgEmission,bgEmission:i[u].bgEmission};return{id:e.id,width:e.width,height:e.height,cells:l,palette:this.colorCache}}rasterizeMultiPass(e,t,n){let i=e.width*e.height;this.ensurePassBuffers(n.length,i),this.visibleLayerIdsBuffer.length=0;let s=this.visibleLayersBuffer;s.length=0;for(let c=0;c<t.length;c++){let d=t[c];d.isEnabled()&&this.isLayerVisible(e,d.getOrigin())&&s.push(d)}s.sort((c,d)=>d.getZOrder()-c.getZOrder());for(let c=0;c<n.length;c++){let d=n[c],h=this.passCellsBuffers[c],f=this.preparePassBuffers(h,this.passOpacityBuffers[c],i);this.passOpacityBuffers[c]=f;let p=[];for(let S=0;S<s.length;S++){let w=s[S],g=w.getZOrder();g<d.zMin||g>d.zMax||p.push(w)}let m=this.visibleLayerIdsBuffer.length;for(let S=0;S<p.length;S++)this.visibleLayerIdsBuffer[m+S]=p[S].getId();this.composePass(e,p,h,f)}let o=this.cellsBuffer,a=this.preparePassBuffers(o,this.opacityBuffer,i);this.opacityBuffer=a;let l=new Array(i),u=[];for(let c=0;c<n.length;c++){let d=this.passCellsBuffers[c],h=new Array(i);for(let f=0;f<i;f++){let p=d[f];h[f]={char:p.char,fgColorIndex:p.fgColorIndex,bgColorIndex:p.bgColorIndex,fgEmission:p.fgEmission,bgEmission:p.bgEmission}}u.push({id:n[c].id,zMin:n[c].zMin,zMax:n[c].zMax,cells:h})}for(let c=0;c<i;c++){let d=o[c];for(let h=n.length-1;h>=0;h--){let f=this.passCellsBuffers[h][c];if(d.char===" "&&f.char!==" "&&(d.char=f.char),d.fgColorIndex===255&&f.fgColorIndex!==255&&(d.fgColorIndex=f.fgColorIndex,d.fgEmission=f.fgEmission),f.bgColorIndex!==255){d.bgColorIndex===255&&(d.bgColorIndex=f.bgColorIndex,d.bgEmission=f.bgEmission);break}}l[c]={char:d.char,fgColorIndex:d.fgColorIndex,bgColorIndex:d.bgColorIndex,fgEmission:d.fgEmission,bgEmission:d.bgEmission}}return{id:e.id,width:e.width,height:e.height,cells:l,palette:this.colorCache,passes:u}}composePass(e,t,n,i){let s=e.width,o=e.height;for(let a=0;a<o;a++)for(let l=0;l<s;l++){let u=a*s+l;if(i[u])continue;let c=e.x+l,d=e.y+a;for(let h=0;h<t.length;h++){let f=t[h],p=c-f.getOrigin().x,m=d-f.getOrigin().y,S=f.getWidth(),w=f.getHeight();if(p<0||p>=S||m<0||m>=w)continue;let g=m*S+p,y=f.getData(),C=y.getCharCode(g),x=y.getFgColorCode(g),I=y.getBgColorCode(g),E=n[u];if(C!==0&&E.char===" "&&(E.char=Ts.getChar(C)),x!==255&&E.fgColorIndex===255&&(E.fgColorIndex=x,E.fgEmission=this.getColorEmission(x)),I!==255){E.bgColorIndex===255&&(E.bgColorIndex=I,E.bgEmission=this.getColorEmission(I)),i[u]=1;break}}}}preparePassBuffers(e,t,n){e.length=n;for(let i=0;i<n;i++)e[i]?(e[i].char=" ",e[i].fgColorIndex=255,e[i].bgColorIndex=255,e[i].fgEmission=0,e[i].bgEmission=0):e[i]={char:" ",fgColorIndex:255,bgColorIndex:255,fgEmission:0,bgEmission:0};return t.length<n?t=new Uint8Array(n):t.fill(0,0,n),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 n=0;n<e;n++)this.passOpacityBuffers[n].length<t?this.passOpacityBuffers[n]=new Uint8Array(t):this.passOpacityBuffers[n].fill(0,0,t)}normalizePasses(e){let t={id:0,zMin:0,zMax:255,enabled:!0};if(!e||e.length===0)return[t];let n=e.filter(i=>i.enabled!==!1);return n.length===0?[t]:n.slice(0,4)}rasterizeWithSortedLayers(e,t){let n=e.width*e.height,i=this.cellsBuffer;i.length=n;for(let l=0;l<n;l++)i[l]?(i[l].char=" ",i[l].fgColorIndex=255,i[l].bgColorIndex=255,i[l].fgEmission=0,i[l].bgEmission=0):i[l]={char:" ",fgColorIndex:255,bgColorIndex:255,fgEmission:0,bgEmission:0};this.opacityBuffer.length<n?this.opacityBuffer=new Uint8Array(n):this.opacityBuffer.fill(0,0,n);let s=this.opacityBuffer,o=this.visibleLayersBuffer;o.length=0;for(let l=0;l<t.length;l++){let u=t[l];this.isLayerVisible(e,u.getOrigin())&&o.push(u)}for(let l=0;l<e.height;l++)for(let u=0;u<e.width;u++){let c=l*e.width+u;if(s[c])continue;let d=e.x+u,h=e.y+l;for(let f=0;f<o.length;f++){let p=o[f],m=d-p.getOrigin().x,S=h-p.getOrigin().y,w=p.getWidth(),g=p.getHeight();if(m<0||m>=w||S<0||S>=g)continue;let y=S*w+m,C=p.getData(),x=C.getCharCode(y),I=C.getFgColorCode(y),E=C.getBgColorCode(y),A=i[c];if(x!==0&&A.char===" "&&(A.char=Ts.getChar(x)),I!==255&&A.fgColorIndex===255&&(A.fgColorIndex=I,A.fgEmission=this.getColorEmission(I)),E!==255){A.bgColorIndex===255&&(A.bgColorIndex=E,A.bgEmission=this.getColorEmission(E)),s[c]=1;break}}}let a=new Array(n);for(let l=0;l<n;l++)a[l]={char:i[l].char,fgColorIndex:i[l].fgColorIndex,bgColorIndex:i[l].bgColorIndex,fgEmission:i[l].fgEmission,bgEmission:i[l].bgEmission};return{id:e.id,width:e.width,height:e.height,cells:a,palette:this.colorCache}}calculateIntersection(e,t){let n=e.x,i=e.x+e.width,s=e.y,o=e.y+e.height,a=t.x,l=t.x+256,u=t.y,c=t.y+256,d=Math.max(n,a),h=Math.min(i,l),f=Math.max(s,u),p=Math.min(o,c);return{visible:d<h&&f<p,originStart:{x:d-e.x,y:f-e.y},originEnd:{x:h-e.x,y:p-e.y},layerStart:{x:d-t.x,y:f-t.y},layerEnd:{x:h-t.x,y:p-t.y}}}};J(nh,"DisplayRasterizer"),D(nh,"charCache",(()=>{let r=new Map;for(let e=0;e<256;e++)r.set(e,String.fromCharCode(e));return r})());var VI=nh,Rv=class{constructor(){D(this,"enabled",!1),D(this,"currentStats",null)}setEnabled(e){this.enabled=e,e||(this.currentStats=null)}isEnabled(){return this.enabled}get tick(){var e;return((e=this.currentStats)==null?void 0:e.tick)??0}get timestamp(){var e;return((e=this.currentStats)==null?void 0:e.timestamp)??0}get totalOrders(){var e;return((e=this.currentStats)==null?void 0:e.totalOrders)??0}get ordersByLayer(){var e;return((e=this.currentStats)==null?void 0:e.ordersByLayer)??new Map}get ordersByType(){var e;return((e=this.currentStats)==null?void 0:e.ordersByType)??new Map}get totalLayers(){var e;return((e=this.currentStats)==null?void 0:e.totalLayers)??0}get visibleLayers(){var e;return((e=this.currentStats)==null?void 0:e.visibleLayers)??0}get layersPerDisplay(){var e;return((e=this.currentStats)==null?void 0:e.layersPerDisplay)??new Map}get displayCompositeLayerIds(){var e;return((e=this.currentStats)==null?void 0:e.displayCompositeLayerIds)??new Map}get updatePacketSize(){var e;return((e=this.currentStats)==null?void 0:e.updatePacketSize)??0}get displayHeaderSize(){var e;return((e=this.currentStats)==null?void 0:e.displayHeaderSize)??0}get layerHeaderSize(){var e;return((e=this.currentStats)==null?void 0:e.layerHeaderSize)??0}get orderDataSize(){var e;return((e=this.currentStats)==null?void 0:e.orderDataSize)??0}get compressionRatio(){var e;return((e=this.currentStats)==null?void 0:e.compressionRatio)??0}get compressedPacketSize(){return Math.round(this.updatePacketSize*this.compressionRatio)}get totalCells(){var e;return((e=this.currentStats)==null?void 0:e.totalCells)??0}get nonEmptyCells(){var e;return((e=this.currentStats)==null?void 0:e.nonEmptyCells)??0}get cellsWithBackground(){var e;return((e=this.currentStats)==null?void 0:e.cellsWithBackground)??0}get rasterizationTimeMs(){var e;return((e=this.currentStats)==null?void 0:e.rasterizationTimeMs)??0}get encodingTimeMs(){var e;return((e=this.currentStats)==null?void 0:e.encodingTimeMs)??0}get packetSplit(){var e;return(e=this.currentStats)==null?void 0:e.packetSplit}get layerDetails(){var e;return(e=this.currentStats)==null?void 0:e.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 n of t){let i=this.currentStats.ordersByType.get(n.type)||0;this.currentStats.ordersByType.set(n.type,i+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,n,i){!this.enabled||!this.currentStats||(this.currentStats.updatePacketSize=e,this.currentStats.displayHeaderSize=t,this.currentStats.layerHeaderSize=n,this.currentStats.orderDataSize=i,this.currentStats.compressionRatio=.25)}recordPacketSplit(e,t,n,i){!this.enabled||!this.currentStats||(this.currentStats.packetSplit={userId:e,displayCount:t,staticLayerCount:n,dynamicLayerCount:i})}recordLayerInfo(e,t,n,i){!this.enabled||!this.currentStats||(this.currentStats.layerDetails||(this.currentStats.layerDetails=[]),this.currentStats.layerDetails.push({layerId:e,mustBeReliable:t,orderCount:n,updateFlags:i}))}recordRenderStats(e,t,n){!this.enabled||!this.currentStats||(this.currentStats.totalCells=e,this.currentStats.nonEmptyCells=t,this.currentStats.cellsWithBackground=n)}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}};J(Rv,"CoreStats");var HI=Rv,Pv=[[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]],jI=new Map(Pv);new Map(Pv.map(([r,e])=>[e,r]));function Qs(r){if(r<128)return r;let e=jI.get(r);return e!==void 0?e:r&255}J(Qs,"unicodeToCp437");var Bv=class{constructor(){D(this,"unicolorSprites",new Map),D(this,"multicolorSprites",new Map)}loadUnicolorSprites(e){if("loadType"in e){this.loadUnicolorSpritesFromPacket(e);return}for(let t of e){let{spriteId:n,sizeX:i,sizeY:s,data:o}=t,a=new Vg(i*s);if(typeof o=="string"){let u=o.replace(/\n/g,"");for(let c=0;c<Math.min(u.length,i*s);c++)a.set(c,Qs(u.charCodeAt(c)))}else if(Array.isArray(o)&&o.length>0&&typeof o[0]=="string"){let u=o;for(let c=0;c<Math.min(u.length,s);c++){let d=u[c];if(d)for(let h=0;h<Math.min(d.length,i);h++)a.set(c*i+h,Qs(d.charCodeAt(h)))}}else{let u=o;for(let c=0;c<Math.min(u.length,i*s);c++)a.set(c,u[c])}let l={id:n,sizeX:i,sizeY:s,data:a};this.unicolorSprites.set(l.id,l)}}loadUnicolorSpritesFromPacket(e){for(let t of e.sprites){let n=new Vg(t.sizeX*t.sizeY);for(let s=0;s<t.data.length;s++)n.set(s,t.data[s]);let i={id:t.spriteId,sizeX:t.sizeX,sizeY:t.sizeY,data:n};this.unicolorSprites.set(i.id,i)}}loadMulticolorSprites(e){if("loadType"in e){this.loadMulticolorSpritesFromPacket(e);return}for(let t of e){let{spriteId:n,sizeX:i,sizeY:s,data:o}=t,a=new th(i*s);for(let u=0;u<Math.min(o.length,i*s);u++){let c=o[u],d=typeof c.charCode=="string"?Qs(c.charCode.charCodeAt(0)):c.charCode;a.set(u,d,c.fgColorId,c.bgColorId)}let l={id:n,sizeX:i,sizeY:s,data:a};this.multicolorSprites.set(l.id,l)}}loadMulticolorSpritesFromPacket(e){for(let t of e.sprites){let n=new th(t.sizeX*t.sizeY);for(let s=0;s<t.data.length;s++){let o=t.data[s];n.set(s,o.charCode,o.fgColorId,o.bgColorId)}let i={id:t.spriteId,sizeX:t.sizeX,sizeY:t.sizeY,data:n};this.multicolorSprites.set(i.id,i)}}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}};J(Bv,"SpriteRegistry");var YI=Bv,WI=(r=>(r.Bitmap="bitmap",r.Image="image",r))(WI||{});function Ef(r){return Math.sqrt(r)*16}J(Ef,"getAtlasColumns");function zv(r){return r*256-1}J(zv,"getMaxCharCode");function GI(r,e){let t=Ef(r)*e;return{width:t,height:t}}J(GI,"getAtlasDimensions");var Dv=class{constructor(e,t){this.fontId=e,this.config=t,D(this,"atlasColumns"),D(this,"maxCharCode"),D(this,"blocks",new Map),this.atlasColumns=Ef(t.atlasBlocks),this.maxCharCode=zv(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,n=Math.floor(e/this.atlasColumns),i=t/this.atlasColumns,s=n/this.atlasColumns,o=(t+1)/this.atlasColumns,a=(n+1)/this.atlasColumns;return{u1:i,v1:s,u2:o,v2:a}}isValidCharCode(e){return e>=0&&e<=this.maxCharCode}};J(Dv,"ImageFont");var qg=Dv,Ov=class{constructor(){D(this,"fonts",new Map),D(this,"nameToId",new Map),D(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 n=this.allocateId(e),i={glyphWidth:t.glyphWidth,glyphHeight:t.glyphHeight,cellWidth:t.cellWidth,cellHeight:t.cellHeight,atlasBlocks:t.atlasBlocks??1},s=new qg(n,i);return this.fonts.set(n,s),this.nameToId.set(e,n),n}addBlock(e,t,n){let i=this.fonts.get(e);if(!i)throw new Error(`ImageFont with ID ${e} not found`);i.addBlock(t,n)}loadFont(e,t){if(this.fonts.has(e))throw new Error(`ImageFont with ID ${e} already exists`);let n=new qg(e,t);this.fonts.set(e,n),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,n]of this.nameToId.entries())if(n===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[t,n]of this.nameToId.entries())if(n===e){this.nameToId.delete(t);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}};J(Ov,"ImageFontRegistry");var XI=Ov,Fv=class{constructor(){D(this,"sounds",new Map),D(this,"nameToId",new Map),D(this,"nextId",0)}registerFile(e,t,n){let i=this.allocateId(e),s={soundId:i,name:e,loadType:"file",format:t,data:n};return this.sounds.set(i,s),this.nameToId.set(e,i),i}registerFileWithId(e,t,n,i){this.validateId(e),this.checkIdAvailable(e,t);let s={soundId:e,name:t,loadType:"file",format:n,data:i};this.sounds.set(e,s),this.nameToId.set(t,e)}registerExternal(e,t,n,i,s){let o=this.allocateId(e),a={soundId:o,name:e,loadType:"external",format:t,url:n,size:i,checksum:s};return this.sounds.set(o,a),this.nameToId.set(e,o),o}registerExternalWithId(e,t,n,i,s,o){this.validateId(e),this.checkIdAvailable(e,t);let a={soundId:e,name:t,loadType:"external",format:n,url:i,size:s,checksum:o};this.sounds.set(e,a),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,n=this.getFileSounds();if(n.length>0){let s=n.map(o=>({soundId:o.soundId,name:o.name,format:o.format,data:o.data}));e.push({type:"sound",mode:"file",sounds:s,totalSounds:t})}let i=this.getExternalSounds();if(i.length>0){let s=i.map(o=>({soundId:o.soundId,name:o.name,format:o.format,url:o.url,size:o.size,checksum:o.checksum}));e.push({type:"sound",mode:"external",sounds:s,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(i=>i.loadType==="file"),n=t.reduce((i,s)=>{var o;return i+(((o=s.data)==null?void 0:o.length)??0)},0);return{total:e.length,file:t.length,external:e.length-t.length,totalFileSize:n}}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 n=this.sounds.get(e);throw new Error(`Sound ID ${e} is already used by "${n.name}". Cannot register "${t}".`)}if(this.nameToId.has(t))throw new Error(`Sound with name "${t}" already exists`)}};J(Fv,"SoundRegistry");var KI=Fv,Lv=class{constructor(e){this.soundRegistry=e}collectFromUser(e){let t=[],n=e.flushSoundCommands();for(let s of n){let o=this.convertSoundCommand(s);o&&t.push(o)}let i=e.flushAudioConfigCommands();for(let s of i){let o=this.convertConfigCommand(s);o&&t.push(o)}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 n=0;e.loop&&(n|=1),e.volume!==void 0&&(n|=2),e.pitch!==void 0&&(n|=4),e.fadeIn!==void 0&&(n|=8),e.lowpass!==void 0&&e.lowpass>0&&(n|=32),e.highpass!==void 0&&e.highpass>0&&(n|=64),e.reverb!==void 0&&e.reverb>0&&(n|=128);let i=e.x!==void 0&&e.y!==void 0;return i&&(n|=16),i?{type:1,soundId:t,instanceId:e.instanceId??0,flags:n,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:n&-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:n}=this.resolveTarget(e.sound);return{type:3,targetType:t,target:n}}convertFadeOutCommand(e){let{targetType:t,target:n}=this.resolveTarget(e.sound);return{type:4,targetType:t,duration:this.encodeFadeTime(e.duration),target:n}}convertPauseCommand(e){let{targetType:t,target:n}=this.resolveTarget(e.sound);return{type:5,targetType:t,target:n}}convertResumeCommand(e){let{targetType:t,target:n}=this.resolveTarget(e.sound);return{type:6,targetType:t,target:n}}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)),n=64*Math.log2(t/.25);return Math.round(Math.max(0,Math.min(255,n)))}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)}};J(Lv,"AudioOrderCollector");var ZI=Lv,_v=class{collectFromUser(e){let t=[];if(e.hasMobileVibrationCommands()){let n=e.flushMobileVibrationCommands();for(let i of n){let s=this.convertMobileCommand(i);s&&t.push(s)}}if(e.hasGamepadVibrationCommands()){let n=e.flushGamepadVibrationCommands();for(let i of n){let s=this.convertGamepadCommand(i);s&&t.push(s)}}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 n=e.pattern,i=Array.isArray(n)?[...n]:[n],s={type:1,flags:t,pattern:i.map(o=>Math.round(o))};return t&1&&(s.intensity=Math.round(Math.min(1,Math.max(0,e.intensity))*255)/255),s}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:n}=e,i=0;n.startDelay!==void 0&&n.startDelay>0&&(i|=1);let s=t==="all"?255:t;t==="all"&&(i|=2);let o={type:16,flags:i,gamepadIndex:s,duration:Math.round(n.duration),strongMagnitude:Math.round(Math.min(1,Math.max(0,n.strongMagnitude??1))*255),weakMagnitude:Math.round(Math.min(1,Math.max(0,n.weakMagnitude??.5))*255)};return n.startDelay!==void 0&&n.startDelay>0&&(o.startDelay=Math.round(n.startDelay)),o}convertGamepadCancelCommand(e){let{gamepadIndex:t}=e,n=0,i=t==="all"?255:t;return t==="all"&&(n|=2),{type:17,flags:n,gamepadIndex:i}}};J(_v,"VibrationOrderCollector");var qI=_v,$v=class{collectFromUser(e){let t=e.flushPostProcessCommands();return this.convertCommands(t)}convertCommands(e){let t=[];for(let n of e){let i=this.convertCommand(n);i&&t.push(i)}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??Ge.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){var s,o,a;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 n=0,i={type:1,displayId:t,flags:0};if(e.config.scanlines){n|=1;let l=e.config.scanlines;i.scanlines={enabled:l.enabled,opacity:l.opacity??Ge.scanlines.opacity,pattern:this.patternToType(l.pattern??"horizontal"),colorR:((s=l.color)==null?void 0:s.r)??0,colorG:((o=l.color)==null?void 0:o.g)??0,colorB:((a=l.color)==null?void 0:a.b)??0}}if(e.config.ambientEffect){n|=2;let l=e.config.ambientEffect;i.ambientEffect={enabled:l.enabled,blur:l.blur??Ge.ambientEffect.blur,scale:l.scale??Ge.ambientEffect.scale,opacity:l.opacity??Ge.ambientEffect.opacity}}return i.flags=n,i}createSetScanlinesOrder(e,t,n){return{type:2,displayId:e,enabled:t,opacity:n??Ge.scanlines.opacity,pattern:0,colorR:0,colorG:0,colorB:0}}createSetAmbientEffectOrder(e,t,n,i){return{type:3,displayId:e,enabled:t,blur:n??Ge.ambientEffect.blur,scale:i??Ge.ambientEffect.scale,opacity:Ge.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:E1(t)}}createSetGridOrder(e,t){let{r:n,g:i,b:s,a:o}=this.parseColor(t.color??js.color);return{type:5,displayId:e,enabled:t.enabled,colorR:n,colorG:i,colorB:s,colorA:o,lineWidth:t.lineWidth??js.lineWidth}}createSwitchPaletteOrder(e,t){return{type:6,displayId:e,slotId:t}}createSetCellSizeOrder(e,t,n){return{type:7,displayId:e,cellWidth:t,cellHeight:n}}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 n=e.match(/^#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})$/);if(n){let i=n[1];return i.length===3?{r:parseInt(i[0]+i[0],16),g:parseInt(i[1]+i[1],16),b:parseInt(i[2]+i[2],16),a:255}:{r:parseInt(i.slice(0,2),16),g:parseInt(i.slice(2,4),16),b:parseInt(i.slice(4,6),16),a:255}}return{r:144,g:24,b:24,a:255}}};J($v,"PostProcessOrderCollector");var Mf=$v,ih=class sh{constructor(e={}){D(this,"mode"),D(this,"maxUsers"),D(this,"strictMode",!1),D(this,"currentTick",0),D(this,"stats",new HI),D(this,"spriteRegistry",new YI),D(this,"imageFontRegistry",new XI),D(this,"soundRegistry",new KI),D(this,"audioOrderCollector",new ZI(this.soundRegistry)),D(this,"vibrationOrderCollector",new qI),D(this,"postProcessOrderCollector",new Mf),D(this,"encoder",new EI),D(this,"users",new Map),D(this,"colorPalette",new Map),D(this,"paletteSlots",new Map),D(this,"displayRasterizer",new VI(this)),D(this,"updatePacketDecoder",new NI),D(this,"loadDecoder",new TI),D(this,"cachedLoadPackets",null),D(this,"_renderCallCount",0),D(this,"onPaletteChangedCallback"),D(this,"onFontAllocatedCallback"),D(this,"onFontBlockAddedCallback"),D(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((e,t)=>this.colorPalette.set(t,{...e,a:255,e:0})),sh.ANSI_VGA_COLORS.forEach(e=>this.colorPalette.set(e.colorId,e)),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 n=new vI(e,t,this.mode);return n.setSpriteRegistry(this.spriteRegistry),this.users.set(e,n),n}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,n,i,s=255,o=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||n<0||n>255||i<0||i>255||s<0||s>255||o<0||o>255)throw new Error("Color components must be between 0 and 255");this.colorPalette.set(e,{r:t,g:n,b:i,a:s,e:o}),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 n=new Map;for(let i of t)i.colorId<0||i.colorId>255||n.set(i.colorId,{r:i.r,g:i.g,b:i.b,a:i.a??255,e:i.e??0});sh.ANSI_VGA_COLORS.forEach(i=>{n.set(i.colorId,{r:i.r,g:i.g,b:i.b,a:i.a,e:i.e})}),n.set(255,{r:0,g:0,b:0,a:0,e:0}),this.paletteSlots.set(e,n)}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 n=t.a/255;return`rgba(${t.r}, ${t.g}, ${t.b}, ${n})`}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,n=0;return this.users.forEach((i,s)=>{let o=i.getLayers(),a=i.getDisplays();t+=o.length,i.getStats().isEnabled()&&i.getStats().startTick(this.currentTick);let l=a.map(w=>{let g=w.getOrigin(),y=w.getSize();return{id:w.getId(),originX:g.x,originY:g.y,sizeX:y.x,sizeY:y.y,renderPasses:w.getRenderPasses()}});a.forEach(w=>w.resetChangeTracking());let u=[],c=[];o.forEach((w,g)=>{if(!w.getNeedsCommit())return;let y=w.getOrigin(),C=w.getOrders(),x=w.getMustBeReliable(),I=w.calculateUpdateFlags();w.resetChangeTracking(),w.resetCommit(),w.getId()===0&&Aa(w,g);let E={id:w.getId(),updateFlags:I,zIndex:w.getZOrder(),originX:y.x,originY:y.y,width:w.getWidth(),height:w.getHeight(),isMacroLayer:w.getIsMacroLayer(),is16bit:w.getCharCodeMode()==="16bit",orderCount:C.length,orders:C};C.length>0&&this.stats.isEnabled()&&this.stats.recordLayerInfo(w.getId(),x,C.length,I),x?u.push(E):c.push(E)}),n+=u.length+c.length;let d=this.audioOrderCollector.collectFromUser(i),h=this.vibrationOrderCollector.collectFromUser(i),f=this.postProcessOrderCollector.collectFromUser(i),p=i.flushMacroOrders(),m=null,S=null;if(this.stats.isEnabled()&&this.stats.recordPacketSplit(s,l.length,u.length,c.length),(u.length>0||d.length>0||p.length>0)&&(m=this.encoder.encode({tick:this.currentTick,displayCount:l.length,displays:l,layerCount:u.length,layers:u,audioOrderCount:d.length,audioOrders:d,vibrationOrderCount:0,vibrationOrders:[],macroOrderCount:p.length,macroOrders:p,postProcessOrderCount:0,postProcessOrders:[]})),S=this.encoder.encode({tick:this.currentTick,displayCount:l.length,displays:l,layerCount:c.length,layers:c,audioOrderCount:0,audioOrders:[],vibrationOrderCount:h.length,vibrationOrders:h,macroOrderCount:0,macroOrders:[],postProcessOrderCount:f.length,postProcessOrders:f}),e.set(s,{static:m,dynamic:S}),i.getStats().isEnabled()){let w=a.reduce((x,I)=>{let E=I.getSize();return x+E.x*E.y},0);i.getStats().recordDisplays(a.length,w),i.getStats().recordLayers(o.length,u.length+c.length,u.length,c.length),[...u,...c].forEach(x=>{i.getStats().recordLayerOrders(x.id,x.orders.length)});let g=(m==null?void 0:m.length)||0,y=(S==null?void 0:S.length)||0;i.getStats().recordPacketSizes(g,y);let C=i.getInputBindingRegistry();i.getStats().recordInput(!1,C.getAxisCount(),C.getButtonCount()),i.getStats().endTick()}if(i.endTickBytes(),this.stats.isEnabled()){let w=[...u,...c];w.forEach((I,E)=>{this.stats.recordLayerOrders(E,I.orders)}),a.forEach((I,E)=>{this.stats.recordDisplayLayers(E,w.length)});let g=((m==null?void 0:m.length)||0)+((S==null?void 0:S.length)||0),y=l.reduce((I,E)=>{var R;let A=Math.min(((R=E.renderPasses)==null?void 0:R.length)??0,4);return I+8+A*4},0),C=w.length*20,x=g-y-C;this.stats.recordUpdatePacketSize(g,y,C,x>0?x:0)}}),this.stats.isEnabled()&&(this.stats.recordLayers(t,n),this.stats.endTick()),this.currentTick++,e}getSnapshot(e){let t=this.getUser(e);if(!t)return null;let n=t.getDisplays(),i=t.getLayers(),s=n.map((a,l)=>{let u=a.getOrigin(),c=a.getSize();return{id:l,originX:u.x,originY:u.y,sizeX:c.x,sizeY:c.y,renderPasses:a.getRenderPasses()}}),o=i.map((a,l)=>{let u=a.getOrigin(),c=a.getOrders();return a.getId()===0&&Aa(a,l),{id:a.getId(),updateFlags:7,zIndex:a.getZOrder(),originX:u.x,originY:u.y,width:a.getWidth(),height:a.getHeight(),isMacroLayer:a.getIsMacroLayer(),is16bit:a.getCharCodeMode()==="16bit",orderCount:c.length,orders:c}});return this.encoder.encode({tick:this.currentTick,displayCount:s.length,displays:s,layerCount:o.length,layers:o,audioOrderCount:0,audioOrders:[],vibrationOrderCount:0,vibrationOrders:[],macroOrderCount:0,macroOrders:[],postProcessOrderCount:0,postProcessOrders:[]})}resetTick(){this.currentTick=0}applyUpdatePacket(e,t){let n=this.getUser(e);if(!n){if(this.strictMode)throw new Error(`Cannot apply update packet: user ${e} does not exist`);return!1}return n.applyUpdate(t),t.audioOrders&&t.audioOrders.length>0&&n.applyAudioOrders(t.audioOrders),t.vibrationOrders&&t.vibrationOrders.length>0&&n.applyVibrationOrders(t.vibrationOrders),!0}applyUpdatePacketBuffer(e,t){let n=this.updatePacketDecoder.decode(t);return this.applyUpdatePacket(e,n)?n:null}applyLoadPacket(e){try{let t=this.loadDecoder.decode(e).load;switch(t.loadType){case 1:t.slotId!==void 0?this.loadPaletteToSlot(t.slotId,t.colors):(console.warn("[Core] ColorPalette load without slotId is deprecated. Loading into slot 0."),this.loadPaletteToSlot(0,t.colors));break;case 2:this.spriteRegistry.loadUnicolorSprites(t);break;case 3:this.spriteRegistry.loadMulticolorSprites(t);break;case 5:console.warn("[Core] Sound loading not yet implemented");break;case 8:this.loadFont(t.glyphWidth,t.glyphHeight,t.atlasBlocks,t.cellWidth,t.cellHeight);break;case 9:this.loadFontBlock(t.blockIndex,t.imageData);break;case 7:{for(let n of this.users.values())n.loadMacroTemplate(t.macroId,t.template);break}default:return console.error(`[Core] Unknown LoadType: ${t.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 n=new Lc,i=[];return t.forEach((s,o)=>{o!==255&&i.push({colorId:o,r:s.r,g:s.g,b:s.b,a:s.a,e:s.e})}),n.encode({loadType:1,slotId:e,colors:i})}generateAllPaletteSlotLoadPackets(){let e=[];return this.paletteSlots.forEach((t,n)=>{let i=this.generatePaletteSlotLoadPacket(n);i&&e.push(i)}),e}generateUnicolorSpritesLoadPacket(){if(this.spriteRegistry.getUnicolorSpriteCount()===0)return null;let e=[];for(let t=0;t<=255;t++){let n=this.spriteRegistry.getUnicolorSprite(t);if(n){let i=[];for(let s=0;s<n.sizeX*n.sizeY;s++)i.push(n.data.get(s));e.push({spriteId:n.id,sizeX:n.sizeX,sizeY:n.sizeY,data:i})}}return e.length===0?null:new Lc().encode({loadType:2,sprites:e})}generateMulticolorSpritesLoadPacket(){let e=this.getSpriteRegistry(),t=[];for(let n=0;n<=255;n++){let i=e.getMulticolorSprite(n);if(i){let s=[];for(let o=0;o<i.sizeX*i.sizeY;o++){let a=i.data.get(o);s.push({charCode:a.charCode,fgColorId:a.fgColorCode,bgColorId:a.bgColorCode})}t.push({spriteId:i.id,sizeX:i.sizeX,sizeY:i.sizeY,data:s})}}return t.length===0?null:new Lc().encode({loadType:3,sprites:t})}generateAllLoadPackets(){if(this.cachedLoadPackets)return this.cachedLoadPackets;let e=[],t=this.generateAllPaletteSlotLoadPackets();e.push(...t);let n=this.generateUnicolorSpritesLoadPacket();n&&e.push(n);let i=this.generateMulticolorSpritesLoadPacket();return i&&e.push(i),this.cachedLoadPackets=e,e}generateMacroLoadPackets(e){let t=this.getUser(e);if(!t)return[];let n=t.getMacroLoads();if(n.length===0)return[];let i=new UI;return n.map(s=>i.encode(s))}generateInitialUpdatePacket(e){let t=this.getUser(e);if(!t||!t.hasPostProcessCommands())return null;let n=this.postProcessOrderCollector.collectFromUser(t);if(n.length===0)return null;let i=t.getDisplays().map(s=>{let o=s.getSize();return{id:s.getId(),originX:0,originY:0,sizeX:o.x,sizeY:o.y}});return this.encoder.encode({tick:0,displayCount:i.length,displays:i,layerCount:0,layers:[],audioOrderCount:0,audioOrders:[],vibrationOrderCount:0,vibrationOrders:[],macroOrderCount:0,macroOrders:[],postProcessOrderCount:n.length,postProcessOrders:n})}applyInputBindingsLoadPacket(e,t){let n=this.getUser(e);if(!n){if(this.strictMode)throw new Error(`Cannot apply input bindings: user ${e} does not exist`);return!1}try{return n.applyInputBindingsLoadPacket(t),!0}catch(i){return console.error(`[Core] Failed to apply input bindings for user ${e}:`,i),!1}}getRenderState(e,t){let n=this.getUser(e);if(!n)return null;let i=n.getDisplays(),s=t?n.getLayers().filter(t):n.getLayers(),o=performance.now(),a=[];for(let l of i){if(!l)continue;let u=l.getOrigin(),c=l.getSize();if(a.push(this.displayRasterizer.rasterize({id:l.getId(),x:u.x,y:u.y,width:c.x,height:c.y},s,l.getRenderPasses())),this.stats.isEnabled()){let d=l.getId();this.stats.recordDisplayComposite(d,this.displayRasterizer.getLastVisibleLayerIds())}}return performance.now()-o,this._renderCallCount||(this._renderCallCount=0),this._renderCallCount++,{userId:n.id,userName:n.name,tick:this.currentTick,displays:a}}getAllRenderStates(){let e=new Map;return this.users.forEach((t,n)=>{let i=this.getRenderState(n);i&&e.set(n,i)}),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,n,i,s){let o={glyphWidth:e,glyphHeight:t,cellWidth:i,cellHeight:s,atlasBlocks:n};this.imageFontRegistry.hasFont(0)&&this.imageFontRegistry.unloadFont(0),this.imageFontRegistry.loadFont(0,o),this.onFontAllocatedCallback&&this.onFontAllocatedCallback()}loadFontBlock(e,t){if(typeof t=="string")return this.readResource(t).then(n=>{this.imageFontRegistry.addBlock(0,e,n),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 n=this.detectSoundFormat(t),i=await this.readResource(t);return this.soundRegistry.registerFile(e,n,i)}async loadSounds(e){let t={},n=Object.entries(e).map(async([i,s])=>{let o=await this.loadSound(i,s);t[i]=o});return await Promise.all(n),t}detectSoundFormat(e){var s;let t=((s=e.split(".").pop())==null?void 0:s.toLowerCase())??"",n={mp3:"mp3",wav:"wav",ogg:"ogg",webm:"webm",aac:"aac",m4a:"aac"},i=n[t];if(!i)throw new Error(`Unsupported audio format: .${t}. Supported: ${Object.keys(n).join(", ")}`);return i}async readResource(e){let t=globalThis,n=typeof t.window<"u"||typeof t.document<"u",i=typeof t.fetch=="function",s=/^https?:\/\//i.test(e),o=e.startsWith("file:");if(n)try{let f=await fetch(e);if(!f.ok)throw new Error(`HTTP ${f.status}: ${f.statusText}`);let p=await f.arrayBuffer();return new Uint8Array(p)}catch(f){let p=f instanceof Error?f.message:String(f);throw new Error(`Failed to load resource "${e}": ${p}`)}if((s||o)&&i)try{let f=await fetch(e);if(!f.ok)throw new Error(`HTTP ${f.status}: ${f.statusText}`);let p=await f.arrayBuffer();return new Uint8Array(p)}catch(f){let p=f instanceof Error?f.message:String(f);throw new Error(`Failed to load resource "${e}": ${p}`)}let a=typeof ll<"u"?ll:null;if(!a)throw new Error("Node.js require is not available");let l="fs",u=a("path"),c=a(l),d=u.resolve(e),h=c.readFileSync(d);return new Uint8Array(h)}registerSound(e,t,n){return this.soundRegistry.registerFile(e,t,n)}registerExternalSound(e,t,n,i){return this.soundRegistry.registerExternal(e,t,n,i)}hasSound(e){return this.soundRegistry.has(e)}generateSoundLoadPackets(){return this.soundRegistry.toLoadPackets()}async loadImageFont(e,t,n){let i=await this.loadImageData(t),s=this.imageFontRegistry.registerFont(e,n);return this.imageFontRegistry.addBlock(0,0,i),this.onFontAllocatedCallback&&this.onFontAllocatedCallback(),this.onFontBlockAddedCallback&&this.onFontBlockAddedCallback(0),this.onImageFontChangedCallback&&this.onImageFontChangedCallback(0),s}async loadImageFonts(e){let t={},n=Object.entries(e).map(async([i,{path:s,options:o}])=>{let a=await this.loadImageFont(i,s,o);t[i]=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 i=await n.arrayBuffer();return new Uint8Array(i)}catch(n){let i=n instanceof Error?n.message:String(n);throw new Error(`Failed to load image font "${e}": ${i}`)}else{let n=typeof ll<"u"?ll:null;if(!n)throw new Error("Node.js require is not available");let i=n("fs").readFileSync(e);return new Uint8Array(i)}}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()}};J(ih,"Core"),D(ih,"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 Nv=ih,Ru=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 QI(r){return Ru.get(r)}J(QI,"getCharBitmap");function JI(r){return Ru.has(r)}J(JI,"hasChar");function ek(){return Array.from(Ru.keys()).sort((r,e)=>r-e)}J(ek,"getAllCharCodes");function tk(){return{charWidth:8,charHeight:8,glyphs:new Map(Ru)}}J(tk,"getASCII8x8FontConfig");var Vv=class{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=ie.allocUnsafe(2);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.toUint8Array()}encodeChange(e){if(typeof e.value=="boolean"){let t=ie.allocUnsafe(4);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.writeUInt8(1,2),t.writeUInt8(e.value?1:0,3),t.toUint8Array()}else{let t=ie.allocUnsafe(7);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.writeUInt8(0,2),t.writeFloatBE(e.value,3),t.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 n=4+t.length,i=ie.allocUnsafe(n),s=0;return i.writeUInt8(e.type,s++),i.writeUInt8(e.instanceId,s++),i.writeUInt16BE(t.length,s),s+=2,i.toUint8Array().set(t,s),i.toUint8Array()}calculateSubmitSize(e){return 4+new TextEncoder().encode(e.text).length}encodeSelect(e){let t=ie.allocUnsafe(4);return t.writeUInt8(e.type,0),t.writeUInt8(e.instanceId,1),t.writeUInt16BE(e.index,2),t.toUint8Array()}};J(Vv,"MacroEventEncoder");var rk=Vv;function Hv(r,e,t,n,i,s,o,a=[],l=[],u=[],c=[],d=!1){let h=Array.from(e.entries()).sort((T,_)=>T[0]-_[0]),f=Array.from(t.entries()).sort((T,_)=>T[0]-_[0]),p=h.length,m=f.length,S=sv(p,m),w=new TextEncoder,g=a.map(T=>w.encode(T)),y=1+g.reduce((T,_)=>T+1+_.length,0),C=new rk,x=l.map(T=>C.encode(T)),I=1+x.reduce((T,_)=>T+_.length,0),E=Math.min(u.length,255),A=1+E*5,R=Math.min(c.length,10),F=1+R*4,z=S+y+I+A+F,P=new Uint8Array(z),O=new DataView(P.buffer),L=0;O.setBigUint64(L,r,!0),L+=8;for(let[,T]of h){let _=nv(T);P[L]=_+256&255,L+=1}let V=Tu(m);for(let T=0;T<V;T++){let _=0;for(let j=0;j<8;j++){let G=T*8+j;if(G<m){let[,ee]=f[G];ee&&(_|=1<<j)}}P[L]=_,L+=1}P[L]=n&255,L+=1,P[L]=i&255,L+=1,P[L]=s&255,L+=1;let X=0;o&&(X|=1),d&&(X|=2),P[L]=X,L+=1,P[L]=Math.min(a.length,255),L+=1;for(let T of g)P[L]=Math.min(T.length,255),L+=1,P.set(T.slice(0,255),L),L+=T.length;P[L]=Math.min(l.length,255),L+=1;for(let T of x)P.set(T,L),L+=T.length;P[L]=E,L+=1;for(let T=0;T<E;T++){let _=u[T];P[L]=_.displayId&255,L+=1,O.setUint16(L,Math.min(_.pixelWidth,65535),!1),L+=2,O.setUint16(L,Math.min(_.pixelHeight,65535),!1),L+=2}P[L]=R,L+=1;for(let T=0;T<R;T++){let _=c[T];P[L]=_.id&15,L+=1,P[L]=_.x&255,L+=1,P[L]=_.y&255,L+=1,P[L]=_.over?1:0,L+=1}return P}J(Hv,"encodeCompressedInput");var nk=class gt{static toCharCode(e){if(typeof e=="number")return e&65535;if(e.length===0)return 0;let t=e.charCodeAt(0);return Qs(t)}static dedent(e){let t=e.split(`
|
|
53
53
|
`);if(t.length>0&&t[0].trim()===""&&t.shift(),t.length>0&&t[t.length-1].trim()===""&&t.pop(),t.length===0)return"";let n=t.filter(s=>s.trim().length>0);if(n.length===0)return"";let i=Math.min(...n.map(s=>{let o=s.match(/^(\s*)/);return o?o[1].length:0}));return t.map(s=>s.slice(i)).join(`
|
|
54
54
|
`)}static encodeString(e){let t="";for(let n=0;n<e.length;n++){let i=e.charCodeAt(n),s=Qs(i);t+=String.fromCharCode(s)}return t}static char(e,t,n,i=15,s=0){return{type:1,posX:e,posY:t,charCode:gt.toCharCode(n),bgColorCode:s,fgColorCode:i}}static text(e,t,n,i=15,s=0){return{type:2,posX:e,posY:t,text:gt.encodeString(n),bgColorCode:s,fgColorCode:i}}static textMultiline(e,t,n,i=15,s=0){return{type:23,posX:e,posY:t,text:gt.encodeString(gt.dedent(n)),bgColorCode:s,fgColorCode:i}}static subFrame(e,t,n,i,s,o=15,a=0){return{type:3,posX:e,posY:t,sizeX:n,sizeY:i,frame:s.map(l=>gt.toCharCode(l)),bgColorCode:a,fgColorCode:o}}static subFrameMultiColor(e,t,n,i,s){return{type:4,posX:e,posY:t,sizeX:n,sizeY:i,frame:s.map(o=>({charCode:gt.toCharCode(o.charCode),bgColorCode:o.bgColorCode,fgColorCode:o.fgColorCode}))}}static fullFrame(e,t=15,n=0){return{type:5,frame:e.map(i=>gt.toCharCode(i)),bgColorCode:n,fgColorCode:t}}static fullFrameMultiColor(e){return{type:6,frame:e.map(t=>({charCode:gt.toCharCode(t.charCode),bgColorCode:t.bgColorCode,fgColorCode:t.fgColorCode}))}}static sprite(e,t,n,i=15,s=0){return{type:7,posX:e,posY:t,spriteIndex:n,bgColorCode:s,fgColorCode:i}}static spriteMultiColor(e,t,n){return{type:8,posX:e,posY:t,spriteIndex:n}}static colorMap(e,t,n,i,s){return{type:9,posX:e,posY:t,sizeX:n,sizeY:i,colorData:s}}static rectangle(e,t,n,i,s={}){return{type:10,shapeType:1,shapeData:{posX:e,posY:t,width:n,height:i,filled:s.filled??!0,charCode:gt.toCharCode(s.charCode??219),bgColorCode:s.bgColor??0,fgColorCode:s.fgColor??15}}}static circle(e,t,n,i={}){return{type:10,shapeType:2,shapeData:{centerX:e,centerY:t,radius:n,filled:i.filled??!0,charCode:gt.toCharCode(i.charCode??219),bgColorCode:i.bgColor??0,fgColorCode:i.fgColor??15}}}static line(e,t,n,i,s={}){return{type:10,shapeType:3,shapeData:{x1:e,y1:t,x2:n,y2:i,charCode:gt.toCharCode(s.charCode??219),bgColorCode:s.bgColor??0,fgColorCode:s.fgColor??15}}}static ellipse(e,t,n,i,s={}){return{type:10,shapeType:4,shapeData:{centerX:e,centerY:t,radiusX:n,radiusY:i,filled:s.filled??!0,charCode:gt.toCharCode(s.charCode??219),bgColorCode:s.bgColor??0,fgColorCode:s.fgColor??15}}}static triangle(e,t,n,i,s,o,a={}){return{type:10,shapeType:5,shapeData:{x1:e,y1:t,x2:n,y2:i,x3:s,y3:o,filled:a.filled??!0,charCode:gt.toCharCode(a.charCode??219),bgColorCode:a.bgColor??0,fgColorCode:a.fgColor??15}}}static dotCloud(e,t,n=15,i=0){return{type:11,charCode:gt.toCharCode(t),bgColorCode:i,fgColorCode:n,positions:e}}static dotCloudMultiColor(e){return{type:12,dots:e.map(t=>({...t,charCode:gt.toCharCode(t.charCode)}))}}static bitmask(e,t,n,i,s,o,a=15,l=0,u=!1){let c=n*i,d=Math.ceil(c/8),h=new Uint8Array(d);for(let f=0;f<c;f++)if(s[f]){let p=Math.floor(f/8),m=f%8;h[p]|=1<<m}return{type:17,posX:e,posY:t,sizeX:n,sizeY:i,charCode:gt.toCharCode(o),bgColorCode:l,fgColorCode:a,override:u,mask:h}}static bitmask4(e,t,n,i,s,o,a=!1){let l={char:"?",fgColor:15,bgColor:0},u=[o[0]??l,o[1]??l,o[2]??l],c=n*i,d=Math.ceil(c/4),h=new Uint8Array(d);for(let f=0;f<c;f++){let p=s[f]&3,m=Math.floor(f/4),S=f%4*2;h[m]|=p<<S}return{type:18,posX:e,posY:t,sizeX:n,sizeY:i,override:a,variants:[{charCode:gt.toCharCode(u[0].char),fgColorCode:u[0].fgColor,bgColorCode:u[0].bgColor},{charCode:gt.toCharCode(u[1].char),fgColorCode:u[1].fgColor,bgColorCode:u[1].bgColor},{charCode:gt.toCharCode(u[2].char),fgColorCode:u[2].fgColor,bgColorCode:u[2].bgColor}],mask:h}}static bitmask16(e,t,n,i,s,o,a=!1){let l={char:"?",fgColor:15,bgColor:0},u=[];for(let f=0;f<15;f++)u.push(o[f]??l);let c=n*i,d=Math.ceil(c/2),h=new Uint8Array(d);for(let f=0;f<c;f++){let p=s[f]&15,m=Math.floor(f/2),S=f%2*4;h[m]|=p<<S}return{type:24,posX:e,posY:t,sizeX:n,sizeY:i,override:a,variants:u.map(f=>({charCode:gt.toCharCode(f.char),fgColorCode:f.fgColor,bgColorCode:f.bgColor})),mask:h}}static spriteCloud(e,t,n=15,i=0){return{type:13,spriteIndex:e,bgColorCode:i,fgColorCode:n,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,n=0){return{type:19,charCode:gt.toCharCode(e),bgColorCode:n,fgColorCode:t}}static fillChar(e,t,n,i=15,s=0){return{type:20,patternWidth:e,patternHeight:t,pattern:n.map(o=>gt.toCharCode(o)),bgColorCode:s,fgColorCode:i}}static fillSprite(e,t=15,n=0){return{type:21,spriteIndex:e,bgColorCode:n,fgColorCode:t}}static fillSpriteMultiColor(e){return{type:22,spriteIndex:e}}static boxWithBorder(e,t,n,i,s,o){return[this.rectangle(e+1,t+1,n-2,i-2,{charCode:o.charCode??219,bgColor:o.bgColor??0,fgColor:o.fgColor??8,filled:!0}),this.rectangle(e,t,n,i,{charCode:s.charCode??219,bgColor:s.bgColor??0,fgColor:s.fgColor??15,filled:!1})]}static grid(e,t,n,i,s,o,a={}){let l=[];for(let u=0;u<=s;u++)for(let c=0;c<=o;c++)l.push({posX:e+c*n,posY:t+u*i});return this.dotCloud(l,a.charCode??"+",a.fgColor??15,a.bgColor??0)}static polyline(e,t="*",n=15,i=0){return{type:25,charCode:gt.toCharCode(t),fgColorCode:n,bgColorCode:i,points:e.map(s=>({x:s.x&255,y:s.y&255}))}}static polylineFromCoords(e,t="*",n=15,i=0){let s=[];for(let o=0;o<e.length-1;o+=2)s.push({x:e[o],y:e[o+1]});return this.polyline(s,t,n,i)}static polygon(e,t="*",n=15,i=0){if(e.length<2)return this.polyline(e,t,n,i);let s=[...e,e[0]];return this.polyline(s,t,n,i)}};J(nk,"OrderBuilder");D1();var ik=(r=>(r[r.LayerEnabled=1]="LayerEnabled",r[r.SetMode=2]="SetMode",r[r.UpdatePosition=4]="UpdatePosition",r[r.UpdateZOrder=8]="UpdateZOrder",r[r.IsMacroLayer=32]="IsMacroLayer",r[r.CharCode16Bit=64]="CharCode16Bit",r[r.Disabled=0]="Disabled",r[r.EnabledAddMode=1]="EnabledAddMode",r[r.EnabledSetMode=3]="EnabledSetMode",r[r.EnabledAddMoveOnly=5]="EnabledAddMoveOnly",r[r.EnabledSetMoveOnly=7]="EnabledSetMoveOnly",r[r.EnabledAddReorderOnly=9]="EnabledAddReorderOnly",r[r.EnabledSetReorderOnly=11]="EnabledSetReorderOnly",r[r.FullUpdate=15]="FullUpdate",r))(ik||{}),Qg;(r=>{function e(d,h){return(d&h)!==0}r.hasFlag=e,J(e,"hasFlag");function t(d,h){return d|h}r.addFlag=t,J(t,"addFlag");function n(d,h){return d&~h}r.removeFlag=n,J(n,"removeFlag");function i(...d){return d.reduce((h,f)=>h|f,0)}r.combine=i,J(i,"combine");function s(d){return(d&144)===0}r.isValid=s,J(s,"isValid");function o(d){return e(d,1)}r.isEnabled=o,J(o,"isEnabled");function a(d){return e(d,2)}r.isSetMode=a,J(a,"isSetMode");function l(d){return e(d,4)}r.hasPositionChanged=l,J(l,"hasPositionChanged");function u(d){return e(d,8)}r.hasZOrderChanged=u,J(u,"hasZOrderChanged");function c(d){if(d===0)return"Disabled";let h=[];return e(d,1)?h.push("Enabled"):h.push("Disabled"),e(d,2)?h.push("SET"):h.push("ADD"),e(d,4)&&h.push("Position"),e(d,8)&&h.push("ZOrder"),e(d,32)&&h.push("Macro"),e(d,64)&&h.push("16bit"),h.join(" | ")}r.describe=c,J(c,"describe")})(Qg||(Qg={}));F1();A1();R1();var jv=Object.defineProperty,sk=(r,e,t)=>e in r?jv(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Pr=(r,e)=>jv(r,"name",{value:e,configurable:!0}),H=(r,e,t)=>(sk(r,typeof e!="symbol"?e+"":e,t),t),Yv=["#000000","#800000","#008000","#808000","#000080","#800080","#008080","#c0c0c0","#808080","#ff0000","#00ff00","#ffff00","#0000ff","#ff00ff","#00ffff","#ffffff","#080808","#121212","#1c1c1c","#262626","#303030","#3a3a3a","#444444","#4e4e4e","#585858","#626262","#6c6c6c","#767676","#808080","#8a8a8a","#949494","#9e9e9e","#a80000","#00a800","#a8a800","#0000a8","#a800a8","#00a8a8","#a8a8a8","#545454","#fc5454","#54fc54","#fcfc54","#5454fc","#fc54fc","#54fcfc","#fcfcfc","#000000",...Array(192).fill("#808080")];function ok(r,e=Yv){return r<0||r>=e.length?"#ff00ff":e[r]}Pr(ok,"paletteIndexToColor");function ak(r,e=Yv){let t=e.indexOf(r.toLowerCase());return t>=0?t:0}Pr(ak,"colorToPaletteIndex");var Wv=class{constructor(e,t){H(this,"canvas"),H(this,"ctx"),H(this,"container"),H(this,"cols",0),H(this,"rows",0),H(this,"cellWidth",0),H(this,"cellHeight",0),H(this,"offsetX",0),H(this,"offsetY",0),H(this,"strokeColor","rgba(80, 80, 80, 0.4)"),H(this,"lineWidth",1),this.container=e,this.canvas=document.createElement("canvas"),this.canvas.className="grid-overlay-canvas";let n=(t==null?void 0:t.zIndex)??10;this.canvas.style.cssText=`
|
|
55
55
|
display: block !important;
|
|
@@ -270,6 +270,6 @@ Orders breakdown: ${this.getOrdersBreakdown()}`),this.orders=this.orders.slice(0
|
|
|
270
270
|
*
|
|
271
271
|
* This source code is licensed under the MIT license found in the
|
|
272
272
|
* LICENSE file in the root directory of this source tree.
|
|
273
|
-
*/var zu=N,WE=YE;function GE(r,e){return r===e&&(r!==0||1/r===1/e)||r!==r&&e!==e}var XE=typeof Object.is=="function"?Object.is:GE,KE=WE.useSyncExternalStore,ZE=zu.useRef,qE=zu.useEffect,QE=zu.useMemo,JE=zu.useDebugValue;Hw.useSyncExternalStoreWithSelector=function(r,e,t,n,i){var s=ZE(null);if(s.current===null){var o={hasValue:!1,value:null};s.current=o}else o=s.current;s=QE(function(){function l(f){if(!u){if(u=!0,c=f,f=n(f),i!==void 0&&o.hasValue){var p=o.value;if(i(p,f))return d=p}return d=f}if(p=d,XE(c,f))return p;var m=n(f);return i!==void 0&&i(p,m)?(c=f,p):(c=f,d=m)}var u=!1,c,d,h=t===void 0?null:t;return[function(){return l(e())},h===null?void 0:function(){return l(h())}]},[e,t,n,i]);var a=KE(r,s[0],s[1]);return qE(function(){o.hasValue=!0,o.value=a},[a]),JE(a),a};Vw.exports=Hw;var e5=Vw.exports;const t5=uy(e5),Ww={},{useDebugValue:r5}=Cy,{useSyncExternalStoreWithSelector:n5}=t5;let hm=!1;const i5=r=>r;function s5(r,e=i5,t){(Ww?"production":void 0)!=="production"&&t&&!hm&&(console.warn("[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937"),hm=!0);const n=n5(r.subscribe,r.getState,r.getServerState||r.getInitialState,e,t);return r5(n),n}const fm=r=>{(Ww?"production":void 0)!=="production"&&typeof r!="function"&&console.warn("[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`.");const e=typeof r=="function"?DE(r):r,t=(n,i)=>s5(e,n,i);return Object.assign(t,e),t},o5=r=>r?fm(r):fm,Ys=o5(r=>({connected:!1,lastSnapshot:void 0,setConnected:e=>r({connected:e}),setSnapshot:e=>r({lastSnapshot:e})}));class a5{constructor(){Wi(this,"runtime",null);Wi(this,"layerTraffic",{});Wi(this,"miscTraffic",{});Wi(this,"displayTraffic",{});Wi(this,"visibleLayerIds",null);Wi(this,"visibleLayerIdsDisplay255",null)}setMuted(e){var n;const t=(n=this.runtime)==null?void 0:n.getAudioManager();t&&t.setMasterVolume(e?0:1)}setVisibleLayers(e){var i;this.visibleLayerIds=e&&e.length>0?[...e]:null;const t=(i=this.runtime)==null?void 0:i.getRendererManager(0);if(!t)return;if(this.visibleLayerIds==null){t.setLayerFilter(null);return}const n=new Set(this.visibleLayerIds);t.setLayerFilter(s=>n.has(s.getId()))}setVisibleLayersDisplay255(e){var i;this.visibleLayerIdsDisplay255=e&&e.length>0?[...e]:null;const t=(i=this.runtime)==null?void 0:i.getRendererManager(255);if(!t)return;if(this.visibleLayerIdsDisplay255==null){t.setLayerFilter(null);return}const n=new Set(this.visibleLayerIdsDisplay255);t.setLayerFilter(s=>n.has(s.getId()))}sendDisplayTransform(e){var t;(t=this.runtime)==null||t.sendBridge("__debug_display_255",{origin:{x:e.x,y:e.y},size:{x:e.width,y:e.height}})}async start(e){Ys.getState().setConnected(!1),this.runtime&&this.destroy();const t={mode:"socketio",socketio:{url:e.serverUrl},container:e.container,displayContainers:e.displayContainers,renderer:e.renderer??Df.TerminalGL,inputEnabled:e.inputEnabled??!0,captureInput:e.captureInput??!0,debug:!1,autoplay:!1};try{if(this.runtime=new TE(t),this.visibleLayerIds&&this.visibleLayerIds.length>0){const n=new Set(this.visibleLayerIds);this.runtime.getRendererManager().setLayerFilter(i=>n.has(i.getId()))}if(this.visibleLayerIdsDisplay255&&this.visibleLayerIdsDisplay255.length>0){const n=new Set(this.visibleLayerIdsDisplay255);this.runtime.getRendererManager(255).setLayerFilter(i=>n.has(i.getId()))}this.runtime.onBridge("__debug_meta",n=>{var i,s,o,a;try{let l=n;if(this.runtime&&n&&typeof n=="object"){try{this.layerTraffic=this.runtime.getLayerTrafficStats()}catch{this.layerTraffic={}}try{this.miscTraffic=((s=(i=this.runtime).getMiscTrafficStats)==null?void 0:s.call(i))??{}}catch{this.miscTraffic={}}try{this.displayTraffic=((a=(o=this.runtime).getDisplayTrafficStats)==null?void 0:a.call(o))??{}}catch{this.displayTraffic={}}const u=n;if(u.users&&Array.isArray(u.users))for(const c of u.users)c.layers&&Array.isArray(c.layers)&&(c.layers=c.layers.map(d=>{const h=this.layerTraffic[d.id];return h?{...d,bytesTotal:h.total,bytesPerSec1s:h.bytesPerSec1s}:d})),c.miscTraffic=this.miscTraffic,c.displayTraffic=this.displayTraffic;l=u}Ys.getState().setConnected(!0),Ys.getState().setSnapshot(l)}catch{}}),await this.runtime.start(),this.runtime.sendBridge("__debug_auth",{})}catch(n){throw Ys.getState().setConnected(!1),n}}destroy(){var e,t,n,i;if(this.runtime){try{(t=(e=this.runtime.getAudioManager())==null?void 0:e.stopAll)==null||t.call(e)}catch{}try{(i=(n=this.runtime).destroy)==null||i.call(n)}catch{}this.runtime=null}}getAssetsSnapshot(){var u;const e=this.runtime;if(!e)return{audio:[],atlases:[],palettes:[]};const t=e.getAudioManager(),n=(u=t==null?void 0:t.getSoundBank)==null?void 0:u.call(t),i=n?n.getAll().map(c=>({id:c.soundId,name:c.name,duration:c.duration,source:c.metadata.source,originalSize:c.metadata.originalSize,originalUrl:c.metadata.originalUrl})):[],s=e.getCore(),o=s.getImageFontRegistry(),a=o.getAllFonts().map(c=>({id:c.getFontId(),name:o.getFontName(c.getFontId())??`Font ${c.getFontId()}`,glyphSize:`${c.getGlyphWidth()}×${c.getGlyphHeight()}`,cellSize:`${c.getCellWidth()}×${c.getCellHeight()}`,atlasBlocks:c.getAtlasBlocks(),maxCharCode:c.getMaxCharCode()}));a.length===0&&a.push({id:0,name:"Default CP437 (builtin)",glyphSize:"8×8",cellSize:"8×8",atlasBlocks:1,maxCharCode:255});const l=[];for(let c=0;c<256;c++){if(!s.hasPaletteSlot(c))continue;const d=s.getPaletteFromSlot(c);l.push({slotId:c,colors:(d==null?void 0:d.size)??0})}return{audio:i,atlases:a,palettes:l}}}function l5({connected:r,muted:e,rendererPlacement:t,centerTab:n,frameRect:i,rendererHeaderHeight:s,rendererContentSize:o,rendererContainerRef:a,onTogglePlacement:l,onToggleMuted:u,onStartDrag:c,onStartResize:d}){const h=t==="float";return k.jsxs("div",{style:{position:"fixed",left:i.left,top:i.top,width:i.width,height:i.height,zIndex:h?1e3:10,background:"#1a1a1a",border:"1px solid #3c3c3c",boxShadow:h?"0 8px 24px rgba(0,0,0,0.45)":"none",userSelect:"none",pointerEvents:h||n==="renderer"?"auto":"none",display:h||n==="renderer"?"block":"none"},children:[k.jsxs("div",{style:{height:s,background:"#2d2d2d",borderBottom:"1px solid #3c3c3c",display:"flex",alignItems:"center",justifyContent:"space-between",padding:"0 10px",cursor:h?"move":"default",fontSize:12,color:"#cccccc"},onMouseDown:f=>{h&&c(f.clientX,f.clientY)},children:[k.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[k.jsx("div",{style:{width:8,height:8,borderRadius:4,background:r?"#4fc1ff":"#a0a0a0"}}),k.jsx("div",{children:"UTSP Client"}),k.jsxs("div",{style:{color:"#888888",fontSize:11},children:[o.width,"×",o.height," px"]})]}),k.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,cursor:"default"},onMouseDown:f=>f.stopPropagation(),children:[k.jsx("button",{onClick:f=>{f.stopPropagation(),l()},style:{height:24,padding:"0 8px",border:"1px solid #3c3c3c",background:"#3c3c3c",color:"#ffffff",cursor:"pointer",fontSize:12},title:h?"Embed into layout":"Float window",children:h?"Embed":"Float"}),k.jsx("button",{onClick:f=>{f.stopPropagation(),u()},style:{width:28,height:24,border:"1px solid #3c3c3c",background:e?"#3c3c3c":"#0e639c",color:"#ffffff",cursor:"pointer",fontSize:12,display:"flex",alignItems:"center",justifyContent:"center",padding:0},title:e?"Unmute audio":"Mute audio",children:k.jsxs("svg",{width:14,height:14,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",children:[k.jsx("path",{d:"M4 9v6h4l5 4V5L8 9H4z"}),!e&&k.jsx("path",{d:"M16 9a5 5 0 0 1 0 6"}),!e&&k.jsx("path",{d:"M18 5a9 9 0 0 1 0 14"}),e&&k.jsx("line",{x1:"17",y1:"9",x2:"21",y2:"13"}),e&&k.jsx("line",{x1:"21",y1:"9",x2:"17",y2:"13"})]})})]})]}),k.jsx("div",{ref:a,style:{position:"absolute",top:s,left:0,right:0,bottom:0,background:"#0d0d0d",overflow:"hidden",opacity:1,pointerEvents:"auto",outline:"1px solid #3c3c3c"},tabIndex:0,onMouseDown:f=>{var p;f.stopPropagation(),(p=a.current)==null||p.focus()}}),h&&k.jsx("div",{onMouseDown:f=>{f.stopPropagation(),d(f.clientX,f.clientY)},style:{position:"absolute",width:14,height:14,right:2,bottom:2,cursor:"nwse-resize",background:"#2d2d2d",border:"1px solid #3c3c3c",borderRadius:2}})]})}function Kr(r){if(r==null||Number.isNaN(r))return"—";const e=["B","KB","MB","GB"];let t=r,n=0;for(;t>=1024&&n<e.length-1;)t/=1024,n++;return`${t.toFixed(t>=10?0:1)} ${e[n]}`}function u5(r){return`${r.toFixed(2)} s`}const c5={muted:{background:"#1a1a1a",border:"#2f2f2f",color:"#cfcfcf"},info:{background:"#1a2531",border:"#2f4f6b",color:"#8dc8ff"},success:{background:"#182420",border:"#2b4d37",color:"#7dd19c"},warning:{background:"#292114",border:"#514021",color:"#eac172"}};function Lo({label:r,tone:e="muted"}){const t=c5[e];return k.jsx("span",{style:{display:"inline-flex",alignItems:"center",padding:"1px 6px",borderRadius:6,fontSize:10,fontWeight:600,letterSpacing:"0.05px",background:t.background,border:`1px solid ${t.border}`,color:t.color},children:r})}function pm({children:r}){return k.jsx("div",{style:{border:"1px solid #2a2a2a",borderRadius:6,background:"#161616"},children:r})}function Xn({label:r,value:e,divider:t}){return k.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"6px 8px",fontSize:11,color:"#d6d6d6",borderBottom:t?"1px solid #222":"none"},children:[k.jsx("span",{style:{color:"#9a9a9a",letterSpacing:"0.05px"},children:r}),k.jsx("span",{style:{fontWeight:600,textAlign:"right"},children:e})]})}function d5({detailTarget:r}){return k.jsxs("div",{style:{background:"transparent",padding:0,minHeight:0,display:"flex",flexDirection:"column"},children:[k.jsx("div",{style:{padding:"8px 12px",borderBottom:"1px solid #3c3c3c"},children:k.jsx("div",{style:{fontSize:11,color:"#bbbbbb",textTransform:"uppercase",letterSpacing:"0.5px"},children:"Properties"})}),k.jsxs("div",{style:{padding:"8px 12px",flex:1,overflowY:"auto"},children:[!r&&k.jsx("div",{style:{fontSize:12,color:"#858585"},children:"Hover or select an item"}),(r==null?void 0:r.type)==="display"&&k.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[k.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:6,padding:"2px 0"},children:[k.jsxs("div",{style:{color:"#e7f3ff",fontWeight:600},children:["Display ",r.item.id]}),k.jsx(Lo,{label:"Active",tone:"info"})]}),k.jsxs(pm,{children:[k.jsx(Xn,{label:"Origin",value:`(${r.item.origin.x}, ${r.item.origin.y})`,divider:!0}),k.jsx(Xn,{label:"Size",value:`${r.item.size.x} × ${r.item.size.y}`})]})]}),(r==null?void 0:r.type)==="layer"&&k.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[k.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:6,padding:"2px 0"},children:[k.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[k.jsx("div",{style:{color:"#e7f3ff",fontWeight:700},children:r.item.name??"Layer"}),k.jsx(Lo,{label:`#${r.item.id}`,tone:"info"})]}),k.jsx(Lo,{label:`z ${r.item.z}`,tone:"muted"})]}),k.jsxs(pm,{children:[k.jsx(Xn,{label:"Mode",value:r.item.charCodeMode,divider:!0}),k.jsx(Xn,{label:"Orders",value:r.item.ordersCount,divider:!0}),k.jsx(Xn,{label:"Size",value:`${r.item.width} × ${r.item.height}`,divider:!0}),k.jsx(Xn,{label:"Origin",value:`(${r.item.origin.x}, ${r.item.origin.y})`,divider:!0}),k.jsx(Xn,{label:"Channel",value:r.item.mustBeReliable?k.jsx(Lo,{label:"Reliable",tone:"success"}):k.jsx(Lo,{label:"Volatile",tone:"muted"}),divider:!0}),r.item.bytesTotal!==void 0&&k.jsxs(k.Fragment,{children:[k.jsx(Xn,{label:"Total",value:Kr(r.item.bytesTotal),divider:!0}),k.jsx(Xn,{label:"Throughput",value:`${Kr(r.item.bytesPerSec1s)} /s`})]})]})]})]})]})}function gm({isSelected:r,onClick:e,children:t}){return k.jsx("div",{onClick:e,style:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"2px 12px",cursor:"pointer",fontSize:12,background:r?"#094771":"transparent",color:r?"#ffffff":"#cccccc",userSelect:"none"},children:t})}function h5(r){return r<1e3?`${r} B`:r<1e6?`${(r/1e3).toFixed(2)} KB`:`${(r/1e6).toFixed(2)} MB`}const Ms={id:"1fr",net:"90px",gap:4};function f5({displays:r,layers:e,selectedDisplayId:t,selectedLayerIds:n,onSelectDisplay:i,onSelectLayer:s}){const o=new Set(n),[a,l]=N.useState("id"),[u,c]=N.useState("asc"),d=N.useMemo(()=>{const f=[...e];return f.sort((p,m)=>{const S=a==="id"?p.id:p.bytesTotal??0,w=a==="id"?m.id:m.bytesTotal??0,g=S===w?0:S<w?-1:1;return u==="asc"?g:-g}),f},[e,u,a]),h=f=>{l(p=>p===f?(c(m=>m==="asc"?"desc":"asc"),p):(c("asc"),f))};return k.jsxs("div",{style:{padding:"4px 0",overflowY:"auto",flex:1,display:"flex",flexDirection:"column",gap:0,userSelect:"none"},children:[r.length===0&&e.length===0&&k.jsx("div",{style:{fontSize:12,color:"#858585",padding:"4px 12px"},children:"No items"}),r.length>0&&k.jsxs(k.Fragment,{children:[k.jsx("div",{style:{fontSize:10,color:"#858585",padding:"6px 12px 2px",textTransform:"uppercase"},children:"Displays"}),r.map(f=>k.jsxs(gm,{isSelected:t===f.id,onClick:()=>i(f.id),children:[k.jsxs("span",{children:["Display ",f.id,f.id===255?" (debug)":""]}),k.jsxs("span",{style:{color:"#858585",fontSize:11},children:[f.size.x,"×",f.size.y]})]},`display-${f.id}`))]}),e.length>0&&k.jsxs(k.Fragment,{children:[k.jsx("div",{style:{fontSize:10,color:"#858585",padding:"8px 12px 4px",textTransform:"uppercase"},children:"Layers"}),k.jsxs("div",{style:{display:"grid",gridTemplateColumns:`${Ms.id} ${Ms.net}`,alignItems:"center",columnGap:Ms.gap,padding:"0 12px 4px",fontSize:11,color:"#858585",userSelect:"none"},children:[k.jsxs("button",{type:"button",onClick:()=>h("id"),style:{all:"unset",cursor:"pointer",display:"inline-flex",alignItems:"center",gap:4,color:"#858585",justifySelf:"start",whiteSpace:"nowrap"},children:["ID",k.jsx("span",{style:{fontSize:10,opacity:a==="id"?1:.3},children:a==="id"?u==="asc"?"▲":"▼":"▲"})]}),k.jsxs("button",{type:"button",onClick:()=>h("net"),style:{all:"unset",cursor:"pointer",display:"inline-flex",alignItems:"center",gap:4,color:"#858585",justifySelf:"end",whiteSpace:"nowrap"},children:["Network",k.jsx("span",{style:{fontSize:10,opacity:a==="net"?1:.3},children:a==="net"?u==="asc"?"▲":"▼":"▲"})]})]}),d.map(f=>{const p=o.has(f.id),m=f.name?`${f.id}:${f.name}`:String(f.id);return k.jsx(gm,{isSelected:p,onClick:S=>s(f.id,S),children:k.jsxs("span",{style:{display:"grid",gridTemplateColumns:`${Ms.id} ${Ms.net}`,alignItems:"center",columnGap:Ms.gap,width:"100%"},children:[k.jsx("span",{style:{display:"inline-flex",alignItems:"center",gap:6},children:k.jsx("span",{style:{color:"inherit"},children:m})}),k.jsx("span",{style:{color:"#858585",fontSize:11,textAlign:"right",whiteSpace:"nowrap"},children:f.bytesTotal!==void 0&&h5(f.bytesTotal)})]})},`layer-${f.id}-${p}`)})]})]})}function p5({primaryUser:r,selectedDisplayId:e,selectedLayerIds:t,onSelectDisplay:n,onSelectLayer:i}){var s;return k.jsxs("div",{style:{borderRight:"1px solid #3c3c3c",background:"#252526",display:"flex",flexDirection:"column",minHeight:0},children:[k.jsx("div",{style:{padding:"8px 12px",borderBottom:"1px solid #3c3c3c"},children:k.jsx("div",{style:{fontSize:11,color:"#bbbbbb",textTransform:"uppercase",letterSpacing:"0.5px"},children:"Explorer"})}),k.jsxs("div",{style:{padding:"4px 0",overflowY:"auto",flex:1,display:"flex",flexDirection:"column",gap:0,userSelect:"none"},children:[!r&&k.jsx("div",{style:{fontSize:12,color:"#858585",padding:"4px 12px"},children:"No items"}),r&&k.jsx(f5,{displays:(s=r.displays)==null?void 0:s.filter(o=>o.id!==255),layers:r.layers,selectedDisplayId:e,selectedLayerIds:t,onSelectDisplay:n,onSelectLayer:i})]})]})}function g5({connected:r,serverUrl:e,onServerUrlChange:t,onReconnect:n}){return k.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",height:34,padding:"0 10px",borderBottom:"1px solid #3c3c3c",background:"#252526"},children:[k.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[k.jsx("img",{src:"/logo_debugger.png",alt:"UTSP logo",style:{width:18,height:18,objectFit:"contain"}}),k.jsx("div",{style:{fontSize:13,color:"#cccccc",fontWeight:600},children:"UTSP Visual Debugger"})]}),k.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[k.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,fontSize:11,color:r?"#9adcff":"#bbbbbb"},children:[k.jsx("span",{style:{width:8,height:8,borderRadius:4,background:r?"#4fc1ff":"#a0a0a0",display:"inline-block"}}),k.jsx("span",{children:r?"Connected":"Disconnected"})]}),k.jsx("input",{value:e,onChange:i=>t(i.target.value),style:{width:220,padding:"4px 8px",borderRadius:0,border:"1px solid #3c3c3c",background:"#3c3c3c",color:"#cccccc",fontSize:12},placeholder:"http://localhost:3000"}),k.jsx("button",{onClick:n,style:{padding:"4px 10px",borderRadius:0,border:"1px solid #0e639c",background:"#0e639c",color:"#ffffff",fontWeight:500,cursor:"pointer",fontSize:12},children:"Reconnect"})]})]})}function Yc({title:r,headers:e,rows:t,emptyLabel:n}){const i=t.length>0;return k.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[k.jsx("div",{style:{fontSize:12,color:"#bbbbbb"},children:r}),k.jsxs("div",{style:{border:"1px solid #3c3c3c",borderRadius:2,overflow:"hidden",background:"#1e1e1e"},children:[k.jsx("div",{style:{display:"grid",gridTemplateColumns:`repeat(${e.length}, minmax(0, 1fr))`,gap:0,background:"#252526",borderBottom:"1px solid #3c3c3c",fontSize:11,color:"#aaaaaa"},children:e.map(s=>k.jsx("div",{style:{padding:"6px 8px",whiteSpace:"nowrap"},children:s},s))}),!i&&k.jsx("div",{style:{padding:"8px 10px",color:"#858585",fontSize:12},children:n}),i&&k.jsx("div",{children:t.map((s,o)=>k.jsx("div",{style:{display:"grid",gridTemplateColumns:`repeat(${e.length}, minmax(0, 1fr))`,gap:0,borderTop:o===0?"none":"1px solid #2e2e2e",fontSize:12,color:"#cccccc"},children:s.map((a,l)=>k.jsx("div",{style:{padding:"6px 8px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:a,children:a},l))},`${r}-${o}`))})]})]})}function m5({assetsSnapshot:r}){return k.jsxs("div",{style:{height:"100%",overflow:"auto",padding:"8px 10px",display:"flex",flexDirection:"column",gap:12,color:"#cccccc",fontSize:12},children:[k.jsx(Yc,{title:"Audio",emptyLabel:"No audio loaded",headers:["Name","Source","Duration","Size","URL"],rows:r.audio.map(e=>[e.name,e.source,u5(e.duration),Kr(e.originalSize),e.originalUrl??"—"])}),k.jsx(Yc,{title:"Atlas",emptyLabel:"No atlas",headers:["ID","Name","Glyph","Cell","Blocks","Max char"],rows:r.atlases.map(e=>[String(e.id),e.name,e.glyphSize,e.cellSize,String(e.atlasBlocks),String(e.maxCharCode)])}),k.jsx(Yc,{title:"Palettes",emptyLabel:"No palette",headers:["Slot","Colors"],rows:r.palettes.map(e=>[String(e.slotId),String(e.colors)])})]})}const y5=!0,Gt="u-",v5="uplot",w5=Gt+"hz",C5=Gt+"vt",b5=Gt+"title",S5=Gt+"wrap",x5=Gt+"under",I5=Gt+"over",k5=Gt+"axis",Ji=Gt+"off",E5=Gt+"select",M5=Gt+"cursor-x",U5=Gt+"cursor-y",A5=Gt+"cursor-pt",T5=Gt+"legend",R5=Gt+"live",P5=Gt+"inline",B5=Gt+"series",z5=Gt+"marker",mm=Gt+"label",D5=Gt+"value",Go="width",Xo="height",_o="top",ym="bottom",Us="left",Wc="right",Of="#000",vm=Of+"0",Gc="mousemove",wm="mousedown",Xc="mouseup",Cm="mouseenter",bm="mouseleave",Sm="dblclick",O5="resize",F5="scroll",xm="change",uu="dppxchange",Ff="--",yo=typeof window<"u",gh=yo?document:null,Js=yo?window:null,L5=yo?navigator:null;let je,hl;function mh(){let r=devicePixelRatio;je!=r&&(je=r,hl&&vh(xm,hl,mh),hl=matchMedia(`(min-resolution: ${je-.001}dppx) and (max-resolution: ${je+.001}dppx)`),ss(xm,hl,mh),Js.dispatchEvent(new CustomEvent(uu)))}function Wr(r,e){if(e!=null){let t=r.classList;!t.contains(e)&&t.add(e)}}function yh(r,e){let t=r.classList;t.contains(e)&&t.remove(e)}function lt(r,e,t){r.style[e]=t+"px"}function Cn(r,e,t,n){let i=gh.createElement(r);return e!=null&&Wr(i,e),t!=null&&t.insertBefore(i,n),i}function on(r,e){return Cn("div",r,e)}const Im=new WeakMap;function _n(r,e,t,n,i){let s="translate("+e+"px,"+t+"px)",o=Im.get(r);s!=o&&(r.style.transform=s,Im.set(r,s),e<0||t<0||e>n||t>i?Wr(r,Ji):yh(r,Ji))}const km=new WeakMap;function Em(r,e,t){let n=e+t,i=km.get(r);n!=i&&(km.set(r,n),r.style.background=e,r.style.borderColor=t)}const Mm=new WeakMap;function Um(r,e,t,n){let i=e+""+t,s=Mm.get(r);i!=s&&(Mm.set(r,i),r.style.height=t+"px",r.style.width=e+"px",r.style.marginLeft=n?-e/2+"px":0,r.style.marginTop=n?-t/2+"px":0)}const Lf={passive:!0},_5={...Lf,capture:!0};function ss(r,e,t,n){e.addEventListener(r,t,n?_5:Lf)}function vh(r,e,t,n){e.removeEventListener(r,t,Lf)}yo&&mh();function In(r,e,t,n){let i;t=t||0,n=n||e.length-1;let s=n<=2147483647;for(;n-t>1;)i=s?t+n>>1:Qr((t+n)/2),e[i]<r?t=i:n=i;return r-e[t]<=e[n]-r?t:n}function Gw(r){return(t,n,i)=>{let s=-1,o=-1;for(let a=n;a<=i;a++)if(r(t[a])){s=a;break}for(let a=i;a>=n;a--)if(r(t[a])){o=a;break}return[s,o]}}const Xw=r=>r!=null,Kw=r=>r!=null&&r>0,Du=Gw(Xw),$5=Gw(Kw);function N5(r,e,t,n=0,i=!1){let s=i?$5:Du,o=i?Kw:Xw;[e,t]=s(r,e,t);let a=r[e],l=r[e];if(e>-1)if(n==1)a=r[e],l=r[t];else if(n==-1)a=r[t],l=r[e];else for(let u=e;u<=t;u++){let c=r[u];o(c)&&(c<a?a=c:c>l&&(l=c))}return[a??Qe,l??-Qe]}function Ou(r,e,t,n){let i=Rm(r),s=Rm(e);r==e&&(i==-1?(r*=t,e/=t):(r/=t,e*=t));let o=t==10?ei:Zw,a=i==1?Qr:an,l=s==1?an:Qr,u=a(o(jt(r))),c=l(o(jt(e))),d=lo(t,u),h=lo(t,c);return t==10&&(u<0&&(d=Je(d,-u)),c<0&&(h=Je(h,-c))),n||t==2?(r=d*i,e=h*s):(r=eC(r,d),e=Fu(e,h)),[r,e]}function _f(r,e,t,n){let i=Ou(r,e,t,n);return r==0&&(i[0]=0),e==0&&(i[1]=0),i}const $f=.1,Am={mode:3,pad:$f},ca={pad:0,soft:null,mode:0},V5={min:ca,max:ca};function cu(r,e,t,n){return Lu(t)?Tm(r,e,t):(ca.pad=t,ca.soft=n?0:null,ca.mode=n?3:0,Tm(r,e,V5))}function _e(r,e){return r??e}function H5(r,e,t){for(e=_e(e,0),t=_e(t,r.length-1);e<=t;){if(r[e]!=null)return!0;e++}return!1}function Tm(r,e,t){let n=t.min,i=t.max,s=_e(n.pad,0),o=_e(i.pad,0),a=_e(n.hard,-Qe),l=_e(i.hard,Qe),u=_e(n.soft,Qe),c=_e(i.soft,-Qe),d=_e(n.mode,0),h=_e(i.mode,0),f=e-r,p=ei(f),m=Mr(jt(r),jt(e)),S=ei(m),w=jt(S-p);(f<1e-24||w>10)&&(f=0,(r==0||e==0)&&(f=1e-24,d==2&&u!=Qe&&(s=0),h==2&&c!=-Qe&&(o=0)));let g=f||m||1e3,y=ei(g),C=lo(10,Qr(y)),x=g*(f==0?r==0?.1:1:s),I=Je(eC(r-x,C/10),24),E=r>=u&&(d==1||d==3&&I<=u||d==2&&I>=u)?u:Qe,A=Mr(a,I<E&&r>=E?E:En(E,I)),R=g*(f==0?e==0?.1:1:o),F=Je(Fu(e+R,C/10),24),z=e<=c&&(h==1||h==3&&F>=c||h==2&&F<=c)?c:-Qe,P=En(l,F>z&&e<=z?z:Mr(z,F));return A==P&&A==0&&(P=100),[A,P]}const j5=new Intl.NumberFormat(yo?L5.language:"en-US"),Nf=r=>j5.format(r),rn=Math,zl=rn.PI,jt=rn.abs,Qr=rn.floor,$t=rn.round,an=rn.ceil,En=rn.min,Mr=rn.max,lo=rn.pow,Rm=rn.sign,ei=rn.log10,Zw=rn.log2,Y5=(r,e=1)=>rn.sinh(r)*e,Kc=(r,e=1)=>rn.asinh(r/e),Qe=1/0;function Pm(r){return(ei((r^r>>31)-(r>>31))|0)+1}function wh(r,e,t){return En(Mr(r,e),t)}function qw(r){return typeof r=="function"}function Pe(r){return qw(r)?r:()=>r}const W5=()=>{},Qw=r=>r,Jw=(r,e)=>e,G5=r=>null,Bm=r=>!0,zm=(r,e)=>r==e,X5=/\.\d*?(?=9{6,}|0{6,})/gm,ds=r=>{if(rC(r)||zi.has(r))return r;const e=`${r}`,t=e.match(X5);if(t==null)return r;let n=t[0].length-1;if(e.indexOf("e-")!=-1){let[i,s]=e.split("e");return+`${ds(i)}e${s}`}return Je(r,n)};function qi(r,e){return ds(Je(ds(r/e))*e)}function Fu(r,e){return ds(an(ds(r/e))*e)}function eC(r,e){return ds(Qr(ds(r/e))*e)}function Je(r,e=0){if(rC(r))return r;let t=10**e,n=r*t*(1+Number.EPSILON);return $t(n)/t}const zi=new Map;function tC(r){return((""+r).split(".")[1]||"").length}function Ta(r,e,t,n){let i=[],s=n.map(tC);for(let o=e;o<t;o++){let a=jt(o),l=Je(lo(r,o),a);for(let u=0;u<n.length;u++){let c=r==10?+`${n[u]}e${o}`:n[u]*l,d=(o>=0?0:a)+(o>=s[u]?0:s[u]),h=r==10?c:Je(c,d);i.push(h),zi.set(h,d)}}return i}const da={},Vf=[],uo=[null,null],mi=Array.isArray,rC=Number.isInteger,K5=r=>r===void 0;function Dm(r){return typeof r=="string"}function Lu(r){let e=!1;if(r!=null){let t=r.constructor;e=t==null||t==Object}return e}function Z5(r){return r!=null&&typeof r=="object"}const q5=Object.getPrototypeOf(Uint8Array),nC="__proto__";function co(r,e=Lu){let t;if(mi(r)){let n=r.find(i=>i!=null);if(mi(n)||e(n)){t=Array(r.length);for(let i=0;i<r.length;i++)t[i]=co(r[i],e)}else t=r.slice()}else if(r instanceof q5)t=r.slice();else if(e(r)){t={};for(let n in r)n!=nC&&(t[n]=co(r[n],e))}else t=r;return t}function zt(r){let e=arguments;for(let t=1;t<e.length;t++){let n=e[t];for(let i in n)i!=nC&&(Lu(r[i])?zt(r[i],co(n[i])):r[i]=co(n[i]))}return r}const Q5=0,J5=1,eM=2;function tM(r,e,t){for(let n=0,i,s=-1;n<e.length;n++){let o=e[n];if(o>s){for(i=o-1;i>=0&&r[i]==null;)r[i--]=null;for(i=o+1;i<t&&r[i]==null;)r[s=i++]=null}}}function rM(r,e){if(sM(r)){let o=r[0].slice();for(let a=1;a<r.length;a++)o.push(...r[a].slice(1));return oM(o[0])||(o=iM(o)),o}let t=new Set;for(let o=0;o<r.length;o++){let l=r[o][0],u=l.length;for(let c=0;c<u;c++)t.add(l[c])}let n=[Array.from(t).sort((o,a)=>o-a)],i=n[0].length,s=new Map;for(let o=0;o<i;o++)s.set(n[0][o],o);for(let o=0;o<r.length;o++){let a=r[o],l=a[0];for(let u=1;u<a.length;u++){let c=a[u],d=Array(i).fill(void 0),h=e?e[o][u]:J5,f=[];for(let p=0;p<c.length;p++){let m=c[p],S=s.get(l[p]);m===null?h!=Q5&&(d[S]=m,h==eM&&f.push(S)):d[S]=m}tM(d,f,i),n.push(d)}}return n}const nM=typeof queueMicrotask>"u"?r=>Promise.resolve().then(r):queueMicrotask;function iM(r){let e=r[0],t=e.length,n=Array(t);for(let s=0;s<n.length;s++)n[s]=s;n.sort((s,o)=>e[s]-e[o]);let i=[];for(let s=0;s<r.length;s++){let o=r[s],a=Array(t);for(let l=0;l<t;l++)a[l]=o[n[l]];i.push(a)}return i}function sM(r){let e=r[0][0],t=e.length;for(let n=1;n<r.length;n++){let i=r[n][0];if(i.length!=t)return!1;if(i!=e){for(let s=0;s<t;s++)if(i[s]!=e[s])return!1}}return!0}function oM(r,e=100){const t=r.length;if(t<=1)return!0;let n=0,i=t-1;for(;n<=i&&r[n]==null;)n++;for(;i>=n&&r[i]==null;)i--;if(i<=n)return!0;const s=Mr(1,Qr((i-n+1)/e));for(let o=r[n],a=n+s;a<=i;a+=s){const l=r[a];if(l!=null){if(l<=o)return!1;o=l}}return!0}const iC=["January","February","March","April","May","June","July","August","September","October","November","December"],sC=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function oC(r){return r.slice(0,3)}const aM=sC.map(oC),lM=iC.map(oC),uM={MMMM:iC,MMM:lM,WWWW:sC,WWW:aM};function $o(r){return(r<10?"0":"")+r}function cM(r){return(r<10?"00":r<100?"0":"")+r}const dM={YYYY:r=>r.getFullYear(),YY:r=>(r.getFullYear()+"").slice(2),MMMM:(r,e)=>e.MMMM[r.getMonth()],MMM:(r,e)=>e.MMM[r.getMonth()],MM:r=>$o(r.getMonth()+1),M:r=>r.getMonth()+1,DD:r=>$o(r.getDate()),D:r=>r.getDate(),WWWW:(r,e)=>e.WWWW[r.getDay()],WWW:(r,e)=>e.WWW[r.getDay()],HH:r=>$o(r.getHours()),H:r=>r.getHours(),h:r=>{let e=r.getHours();return e==0?12:e>12?e-12:e},AA:r=>r.getHours()>=12?"PM":"AM",aa:r=>r.getHours()>=12?"pm":"am",a:r=>r.getHours()>=12?"p":"a",mm:r=>$o(r.getMinutes()),m:r=>r.getMinutes(),ss:r=>$o(r.getSeconds()),s:r=>r.getSeconds(),fff:r=>cM(r.getMilliseconds())};function Hf(r,e){e=e||uM;let t=[],n=/\{([a-z]+)\}|[^{]+/gi,i;for(;i=n.exec(r);)t.push(i[0][0]=="{"?dM[i[1]]:i[0]);return s=>{let o="";for(let a=0;a<t.length;a++)o+=typeof t[a]=="string"?t[a]:t[a](s,e);return o}}const hM=new Intl.DateTimeFormat().resolvedOptions().timeZone;function fM(r,e){let t;return e=="UTC"||e=="Etc/UTC"?t=new Date(+r+r.getTimezoneOffset()*6e4):e==hM?t=r:(t=new Date(r.toLocaleString("en-US",{timeZone:e})),t.setMilliseconds(r.getMilliseconds())),t}const aC=r=>r%1==0,du=[1,2,2.5,5],pM=Ta(10,-32,0,du),lC=Ta(10,0,32,du),gM=lC.filter(aC),Qi=pM.concat(lC),jf=`
|
|
274
|
-
`,uC="{YYYY}",Om=jf+uC,cC="{M}/{D}",Ko=jf+cC,fl=Ko+"/{YY}",dC="{aa}",mM="{h}:{mm}",Rs=mM+dC,Fm=jf+Rs,Lm=":{ss}",We=null;function hC(r){let e=r*1e3,t=e*60,n=t*60,i=n*24,s=i*30,o=i*365,l=(r==1?Ta(10,0,3,du).filter(aC):Ta(10,-3,0,du)).concat([e,e*5,e*10,e*15,e*30,t,t*5,t*10,t*15,t*30,n,n*2,n*3,n*4,n*6,n*8,n*12,i,i*2,i*3,i*4,i*5,i*6,i*7,i*8,i*9,i*10,i*15,s,s*2,s*3,s*4,s*6,o,o*2,o*5,o*10,o*25,o*50,o*100]);const u=[[o,uC,We,We,We,We,We,We,1],[i*28,"{MMM}",Om,We,We,We,We,We,1],[i,cC,Om,We,We,We,We,We,1],[n,"{h}"+dC,fl,We,Ko,We,We,We,1],[t,Rs,fl,We,Ko,We,We,We,1],[e,Lm,fl+" "+Rs,We,Ko+" "+Rs,We,Fm,We,1],[r,Lm+".{fff}",fl+" "+Rs,We,Ko+" "+Rs,We,Fm,We,1]];function c(d){return(h,f,p,m,S,w)=>{let g=[],y=S>=o,C=S>=s&&S<o,x=d(p),I=Je(x*r,3),E=Zc(x.getFullYear(),y?0:x.getMonth(),C||y?1:x.getDate()),A=Je(E*r,3);if(C||y){let R=C?S/s:0,F=y?S/o:0,z=I==A?I:Je(Zc(E.getFullYear()+F,E.getMonth()+R,1)*r,3),P=new Date($t(z/r)),O=P.getFullYear(),L=P.getMonth();for(let V=0;z<=m;V++){let X=Zc(O+F*V,L+R*V,1),T=X-d(Je(X*r,3));z=Je((+X+T)*r,3),z<=m&&g.push(z)}}else{let R=S>=i?i:S,F=Qr(p)-Qr(I),z=A+F+Fu(I-A,R);g.push(z);let P=d(z),O=P.getHours()+P.getMinutes()/t+P.getSeconds()/n,L=S/n,V=h.axes[f]._space,X=w/V;for(;z=Je(z+S,r==1?0:3),!(z>m);)if(L>1){let T=Qr(Je(O+L,6))%24,G=d(z).getHours()-T;G>1&&(G=-1),z-=G*n,O=(O+L)%24;let ee=g[g.length-1];Je((z-ee)/S,3)*X>=.7&&g.push(z)}else g.push(z)}return g}}return[l,u,c]}const[yM,vM,wM]=hC(1),[CM,bM,SM]=hC(.001);Ta(2,-53,53,[1]);function _m(r,e){return r.map(t=>t.map((n,i)=>i==0||i==8||n==null?n:e(i==1||t[8]==0?n:t[1]+n)))}function $m(r,e){return(t,n,i,s,o)=>{let a=e.find(p=>o>=p[0])||e[e.length-1],l,u,c,d,h,f;return n.map(p=>{let m=r(p),S=m.getFullYear(),w=m.getMonth(),g=m.getDate(),y=m.getHours(),C=m.getMinutes(),x=m.getSeconds(),I=S!=l&&a[2]||w!=u&&a[3]||g!=c&&a[4]||y!=d&&a[5]||C!=h&&a[6]||x!=f&&a[7]||a[1];return l=S,u=w,c=g,d=y,h=C,f=x,I(m)})}}function xM(r,e){let t=Hf(e);return(n,i,s,o,a)=>i.map(l=>t(r(l)))}function Zc(r,e,t){return new Date(r,e,t)}function Nm(r,e){return e(r)}const IM="{YYYY}-{MM}-{DD} {h}:{mm}{aa}";function Vm(r,e){return(t,n,i,s)=>s==null?Ff:e(r(n))}function kM(r,e){let t=r.series[e];return t.width?t.stroke(r,e):t.points.width?t.points.stroke(r,e):null}function EM(r,e){return r.series[e].fill(r,e)}const MM={show:!0,live:!0,isolate:!1,mount:W5,markers:{show:!0,width:2,stroke:kM,fill:EM,dash:"solid"},idx:null,idxs:null,values:[]};function UM(r,e){let t=r.cursor.points,n=on(),i=t.size(r,e);lt(n,Go,i),lt(n,Xo,i);let s=i/-2;lt(n,"marginLeft",s),lt(n,"marginTop",s);let o=t.width(r,e,i);return o&<(n,"borderWidth",o),n}function AM(r,e){let t=r.series[e].points;return t._fill||t._stroke}function TM(r,e){let t=r.series[e].points;return t._stroke||t._fill}function RM(r,e){return r.series[e].points.size}const qc=[0,0];function PM(r,e,t){return qc[0]=e,qc[1]=t,qc}function pl(r,e,t,n=!0){return i=>{i.button==0&&(!n||i.target==e)&&t(i)}}function Qc(r,e,t,n=!0){return i=>{(!n||i.target==e)&&t(i)}}const BM={show:!0,x:!0,y:!0,lock:!1,move:PM,points:{one:!1,show:UM,size:RM,width:0,stroke:TM,fill:AM},bind:{mousedown:pl,mouseup:pl,click:pl,dblclick:pl,mousemove:Qc,mouseleave:Qc,mouseenter:Qc},drag:{setScale:!0,x:!0,y:!1,dist:0,uni:null,click:(r,e)=>{e.stopPropagation(),e.stopImmediatePropagation()},_x:!1,_y:!1},focus:{dist:(r,e,t,n,i)=>n-i,prox:-1,bias:0},hover:{skip:[void 0],prox:null,bias:0},left:-10,top:-10,idx:null,dataIdx:null,idxs:null,event:null},fC={show:!0,stroke:"rgba(0,0,0,0.07)",width:2},Yf=zt({},fC,{filter:Jw}),pC=zt({},Yf,{size:10}),gC=zt({},fC,{show:!1}),Wf='12px system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"',mC="bold "+Wf,yC=1.5,Hm={show:!0,scale:"x",stroke:Of,space:50,gap:5,alignTo:1,size:50,labelGap:0,labelSize:30,labelFont:mC,side:2,grid:Yf,ticks:pC,border:gC,font:Wf,lineGap:yC,rotate:0},zM="Value",DM="Time",jm={show:!0,scale:"x",auto:!1,sorted:1,min:Qe,max:-Qe,idxs:[]};function OM(r,e,t,n,i){return e.map(s=>s==null?"":Nf(s))}function FM(r,e,t,n,i,s,o){let a=[],l=zi.get(i)||0;t=o?t:Je(Fu(t,i),l);for(let u=t;u<=n;u=Je(u+i,l))a.push(Object.is(u,-0)?0:u);return a}function Ch(r,e,t,n,i,s,o){const a=[],l=r.scales[r.axes[e].scale].log,u=l==10?ei:Zw,c=Qr(u(t));i=lo(l,c),l==10&&(i=Qi[In(i,Qi)]);let d=t,h=i*l;l==10&&(h=Qi[In(h,Qi)]);do a.push(d),d=d+i,l==10&&!zi.has(d)&&(d=Je(d,zi.get(i))),d>=h&&(i=d,h=i*l,l==10&&(h=Qi[In(h,Qi)]));while(d<=n);return a}function LM(r,e,t,n,i,s,o){let l=r.scales[r.axes[e].scale].asinh,u=n>l?Ch(r,e,Mr(l,t),n,i):[l],c=n>=0&&t<=0?[0]:[];return(t<-l?Ch(r,e,Mr(l,-n),-t,i):[l]).reverse().map(h=>-h).concat(c,u)}const vC=/./,_M=/[12357]/,$M=/[125]/,Ym=/1/,bh=(r,e,t,n)=>r.map((i,s)=>e==4&&i==0||s%n==0&&t.test(i.toExponential()[i<0?1:0])?i:null);function NM(r,e,t,n,i){let s=r.axes[t],o=s.scale,a=r.scales[o],l=r.valToPos,u=s._space,c=l(10,o),d=l(9,o)-c>=u?vC:l(7,o)-c>=u?_M:l(5,o)-c>=u?$M:Ym;if(d==Ym){let h=jt(l(1,o)-c);if(h<u)return bh(e.slice().reverse(),a.distr,d,an(u/h)).reverse()}return bh(e,a.distr,d,1)}function VM(r,e,t,n,i){let s=r.axes[t],o=s.scale,a=s._space,l=r.valToPos,u=jt(l(1,o)-l(2,o));return u<a?bh(e.slice().reverse(),3,vC,an(a/u)).reverse():e}function HM(r,e,t,n){return n==null?Ff:e==null?"":Nf(e)}const Wm={show:!0,scale:"y",stroke:Of,space:30,gap:5,alignTo:1,size:50,labelGap:0,labelSize:30,labelFont:mC,side:3,grid:Yf,ticks:pC,border:gC,font:Wf,lineGap:yC,rotate:0};function jM(r,e){let t=3+(r||1)*2;return Je(t*e,3)}function YM(r,e){let{scale:t,idxs:n}=r.series[0],i=r._data[0],s=r.valToPos(i[n[0]],t,!0),o=r.valToPos(i[n[1]],t,!0),a=jt(o-s),l=r.series[e],u=a/(l.points.space*je);return n[1]-n[0]<=u}const Gm={scale:null,auto:!0,sorted:0,min:Qe,max:-Qe},wC=(r,e,t,n,i)=>i,Xm={show:!0,auto:!0,sorted:0,gaps:wC,alpha:1,facets:[zt({},Gm,{scale:"x"}),zt({},Gm,{scale:"y"})]},Km={scale:"y",auto:!0,sorted:0,show:!0,spanGaps:!1,gaps:wC,alpha:1,points:{show:YM,filter:null},values:null,min:Qe,max:-Qe,idxs:[],path:null,clip:null};function WM(r,e,t,n,i){return t/10}const CC={time:y5,auto:!0,distr:1,log:10,asinh:1,min:null,max:null,dir:1,ori:0},GM=zt({},CC,{time:!1,ori:1}),Zm={};function bC(r,e){let t=Zm[r];return t||(t={key:r,plots:[],sub(n){t.plots.push(n)},unsub(n){t.plots=t.plots.filter(i=>i!=n)},pub(n,i,s,o,a,l,u){for(let c=0;c<t.plots.length;c++)t.plots[c]!=i&&t.plots[c].pub(n,i,s,o,a,l,u)}},r!=null&&(Zm[r]=t)),t}const ho=1,Sh=2;function ps(r,e,t){const n=r.mode,i=r.series[e],s=n==2?r._data[e]:r._data,o=r.scales,a=r.bbox;let l=s[0],u=n==2?s[1]:s[e],c=n==2?o[i.facets[0].scale]:o[r.series[0].scale],d=n==2?o[i.facets[1].scale]:o[i.scale],h=a.left,f=a.top,p=a.width,m=a.height,S=r.valToPosH,w=r.valToPosV;return c.ori==0?t(i,l,u,c,d,S,w,h,f,p,m,$u,vo,Vu,xC,kC):t(i,l,u,c,d,w,S,f,h,m,p,Nu,wo,Kf,IC,EC)}function Gf(r,e){let t=0,n=0,i=_e(r.bands,Vf);for(let s=0;s<i.length;s++){let o=i[s];o.series[0]==e?t=o.dir:o.series[1]==e&&(o.dir==1?n|=1:n|=2)}return[t,n==1?-1:n==2?1:n==3?2:0]}function XM(r,e,t,n,i){let s=r.mode,o=r.series[e],a=s==2?o.facets[1].scale:o.scale,l=r.scales[a];return i==-1?l.min:i==1?l.max:l.distr==3?l.dir==1?l.min:l.max:0}function ti(r,e,t,n,i,s){return ps(r,e,(o,a,l,u,c,d,h,f,p,m,S)=>{let w=o.pxRound;const g=u.dir*(u.ori==0?1:-1),y=u.ori==0?vo:wo;let C,x;g==1?(C=t,x=n):(C=n,x=t);let I=w(d(a[C],u,m,f)),E=w(h(l[C],c,S,p)),A=w(d(a[x],u,m,f)),R=w(h(s==1?c.max:c.min,c,S,p)),F=new Path2D(i);return y(F,A,R),y(F,I,R),y(F,I,E),F})}function _u(r,e,t,n,i,s){let o=null;if(r.length>0){o=new Path2D;const a=e==0?Vu:Kf;let l=t;for(let d=0;d<r.length;d++){let h=r[d];if(h[1]>h[0]){let f=h[0]-l;f>0&&a(o,l,n,f,n+s),l=h[1]}}let u=t+i-l,c=10;u>0&&a(o,l,n-c/2,u,n+s+c)}return o}function KM(r,e,t){let n=r[r.length-1];n&&n[0]==e?n[1]=t:r.push([e,t])}function Xf(r,e,t,n,i,s,o){let a=[],l=r.length;for(let u=i==1?t:n;u>=t&&u<=n;u+=i)if(e[u]===null){let d=u,h=u;if(i==1)for(;++u<=n&&e[u]===null;)h=u;else for(;--u>=t&&e[u]===null;)h=u;let f=s(r[d]),p=h==d?f:s(r[h]),m=d-i;f=o<=0&&m>=0&&m<l?s(r[m]):f;let w=h+i;p=o>=0&&w>=0&&w<l?s(r[w]):p,p>=f&&a.push([f,p])}return a}function qm(r){return r==0?Qw:r==1?$t:e=>qi(e,r)}function SC(r){let e=r==0?$u:Nu,t=r==0?(i,s,o,a,l,u)=>{i.arcTo(s,o,a,l,u)}:(i,s,o,a,l,u)=>{i.arcTo(o,s,l,a,u)},n=r==0?(i,s,o,a,l)=>{i.rect(s,o,a,l)}:(i,s,o,a,l)=>{i.rect(o,s,l,a)};return(i,s,o,a,l,u=0,c=0)=>{u==0&&c==0?n(i,s,o,a,l):(u=En(u,a/2,l/2),c=En(c,a/2,l/2),e(i,s+u,o),t(i,s+a,o,s+a,o+l,u),t(i,s+a,o+l,s,o+l,c),t(i,s,o+l,s,o,c),t(i,s,o,s+a,o,u),i.closePath())}}const $u=(r,e,t)=>{r.moveTo(e,t)},Nu=(r,e,t)=>{r.moveTo(t,e)},vo=(r,e,t)=>{r.lineTo(e,t)},wo=(r,e,t)=>{r.lineTo(t,e)},Vu=SC(0),Kf=SC(1),xC=(r,e,t,n,i,s)=>{r.arc(e,t,n,i,s)},IC=(r,e,t,n,i,s)=>{r.arc(t,e,n,i,s)},kC=(r,e,t,n,i,s,o)=>{r.bezierCurveTo(e,t,n,i,s,o)},EC=(r,e,t,n,i,s,o)=>{r.bezierCurveTo(t,e,i,n,o,s)};function MC(r){return(e,t,n,i,s)=>ps(e,t,(o,a,l,u,c,d,h,f,p,m,S)=>{let{pxRound:w,points:g}=o,y,C;u.ori==0?(y=$u,C=xC):(y=Nu,C=IC);const x=Je(g.width*je,3);let I=(g.size-g.width)/2*je,E=Je(I*2,3),A=new Path2D,R=new Path2D,{left:F,top:z,width:P,height:O}=e.bbox;Vu(R,F-E,z-E,P+E*2,O+E*2);const L=V=>{if(l[V]!=null){let X=w(d(a[V],u,m,f)),T=w(h(l[V],c,S,p));y(A,X+I,T),C(A,X,T,I,0,zl*2)}};if(s)s.forEach(L);else for(let V=n;V<=i;V++)L(V);return{stroke:x>0?A:null,fill:A,clip:R,flags:ho|Sh}})}function UC(r){return(e,t,n,i,s,o)=>{n!=i&&(s!=n&&o!=n&&r(e,t,n),s!=i&&o!=i&&r(e,t,i),r(e,t,o))}}const ZM=UC(vo),qM=UC(wo);function AC(r){const e=_e(r==null?void 0:r.alignGaps,0);return(t,n,i,s)=>ps(t,n,(o,a,l,u,c,d,h,f,p,m,S)=>{[i,s]=Du(l,i,s);let w=o.pxRound,g=O=>w(d(O,u,m,f)),y=O=>w(h(O,c,S,p)),C,x;u.ori==0?(C=vo,x=ZM):(C=wo,x=qM);const I=u.dir*(u.ori==0?1:-1),E={stroke:new Path2D,fill:null,clip:null,band:null,gaps:null,flags:ho},A=E.stroke;let R=!1;if(s-i>=m*4){let O=K=>t.posToVal(K,u.key,!0),L=null,V=null,X,T,_,j=g(a[I==1?i:s]),G=g(a[i]),ee=g(a[s]),q=O(I==1?G+1:ee-1);for(let K=I==1?i:s;K>=i&&K<=s;K+=I){let oe=a[K],ge=(I==1?oe<q:oe>q)?j:g(oe),Ce=l[K];ge==j?Ce!=null?(T=Ce,L==null?(C(A,ge,y(T)),X=L=V=T):T<L?L=T:T>V&&(V=T)):Ce===null&&(R=!0):(L!=null&&x(A,j,y(L),y(V),y(X),y(T)),Ce!=null?(T=Ce,C(A,ge,y(T)),L=V=X=T):(L=V=null,Ce===null&&(R=!0)),j=ge,q=O(j+I))}L!=null&&L!=V&&_!=j&&x(A,j,y(L),y(V),y(X),y(T))}else for(let O=I==1?i:s;O>=i&&O<=s;O+=I){let L=l[O];L===null?R=!0:L!=null&&C(A,g(a[O]),y(L))}let[z,P]=Gf(t,n);if(o.fill!=null||z!=0){let O=E.fill=new Path2D(A),L=o.fillTo(t,n,o.min,o.max,z),V=y(L),X=g(a[i]),T=g(a[s]);I==-1&&([T,X]=[X,T]),C(O,T,V),C(O,X,V)}if(!o.spanGaps){let O=[];R&&O.push(...Xf(a,l,i,s,I,g,e)),E.gaps=O=o.gaps(t,n,i,s,O),E.clip=_u(O,u.ori,f,p,m,S)}return P!=0&&(E.band=P==2?[ti(t,n,i,s,A,-1),ti(t,n,i,s,A,1)]:ti(t,n,i,s,A,P)),E})}function QM(r){const e=_e(r.align,1),t=_e(r.ascDesc,!1),n=_e(r.alignGaps,0),i=_e(r.extend,!1);return(s,o,a,l)=>ps(s,o,(u,c,d,h,f,p,m,S,w,g,y)=>{[a,l]=Du(d,a,l);let C=u.pxRound,{left:x,width:I}=s.bbox,E=G=>C(p(G,h,g,S)),A=G=>C(m(G,f,y,w)),R=h.ori==0?vo:wo;const F={stroke:new Path2D,fill:null,clip:null,band:null,gaps:null,flags:ho},z=F.stroke,P=h.dir*(h.ori==0?1:-1);let O=A(d[P==1?a:l]),L=E(c[P==1?a:l]),V=L,X=L;i&&e==-1&&(X=x,R(z,X,O)),R(z,L,O);for(let G=P==1?a:l;G>=a&&G<=l;G+=P){let ee=d[G];if(ee==null)continue;let q=E(c[G]),K=A(ee);e==1?R(z,q,O):R(z,V,K),R(z,q,K),O=K,V=q}let T=V;i&&e==1&&(T=x+I,R(z,T,O));let[_,j]=Gf(s,o);if(u.fill!=null||_!=0){let G=F.fill=new Path2D(z),ee=u.fillTo(s,o,u.min,u.max,_),q=A(ee);R(G,T,q),R(G,X,q)}if(!u.spanGaps){let G=[];G.push(...Xf(c,d,a,l,P,E,n));let ee=u.width*je/2,q=t||e==1?ee:-ee,K=t||e==-1?-ee:ee;G.forEach(oe=>{oe[0]+=q,oe[1]+=K}),F.gaps=G=u.gaps(s,o,a,l,G),F.clip=_u(G,h.ori,S,w,g,y)}return j!=0&&(F.band=j==2?[ti(s,o,a,l,z,-1),ti(s,o,a,l,z,1)]:ti(s,o,a,l,z,j)),F})}function Qm(r,e,t,n,i,s,o=Qe){if(r.length>1){let a=null;for(let l=0,u=1/0;l<r.length;l++)if(e[l]!==void 0){if(a!=null){let c=jt(r[l]-r[a]);c<u&&(u=c,o=jt(t(r[l],n,i,s)-t(r[a],n,i,s)))}a=l}}return o}function JM(r){r=r||da;const e=_e(r.size,[.6,Qe,1]),t=r.align||0,n=r.gap||0;let i=r.radius;i=i==null?[0,0]:typeof i=="number"?[i,0]:i;const s=Pe(i),o=1-e[0],a=_e(e[1],Qe),l=_e(e[2],1),u=_e(r.disp,da),c=_e(r.each,f=>{}),{fill:d,stroke:h}=u;return(f,p,m,S)=>ps(f,p,(w,g,y,C,x,I,E,A,R,F,z)=>{let P=w.pxRound,O=t,L=n*je,V=a*je,X=l*je,T,_;C.ori==0?[T,_]=s(f,p):[_,T]=s(f,p);const j=C.dir*(C.ori==0?1:-1);let G=C.ori==0?Vu:Kf,ee=C.ori==0?c:(ne,$e,ht,Q,W,le,ye)=>{c(ne,$e,ht,W,Q,ye,le)},q=_e(f.bands,Vf).find(ne=>ne.series[0]==p),K=q!=null?q.dir:0,oe=w.fillTo(f,p,w.min,w.max,K),ve=P(E(oe,x,z,R)),ge,Ce,ct,dt=F,xe=P(w.width*je),et=!1,Ke=null,qe=null,At=null,wt=null;d!=null&&(xe==0||h!=null)&&(et=!0,Ke=d.values(f,p,m,S),qe=new Map,new Set(Ke).forEach(ne=>{ne!=null&&qe.set(ne,new Path2D)}),xe>0&&(At=h.values(f,p,m,S),wt=new Map,new Set(At).forEach(ne=>{ne!=null&&wt.set(ne,new Path2D)})));let{x0:Ft,size:cr}=u;if(Ft!=null&&cr!=null){O=1,g=Ft.values(f,p,m,S),Ft.unit==2&&(g=g.map(ht=>f.posToVal(A+ht*F,C.key,!0)));let ne=cr.values(f,p,m,S);cr.unit==2?Ce=ne[0]*F:Ce=I(ne[0],C,F,A)-I(0,C,F,A),dt=Qm(g,y,I,C,F,A,dt),ct=dt-Ce+L}else dt=Qm(g,y,I,C,F,A,dt),ct=dt*o+L,Ce=dt-ct;ct<1&&(ct=0),xe>=Ce/2&&(xe=0),ct<5&&(P=Qw);let tt=ct>0,kt=dt-ct-(tt?xe:0);Ce=P(wh(kt,X,V)),ge=(O==0?Ce/2:O==j?0:Ce)-O*j*((O==0?L/2:0)+(tt?xe/2:0));const nt={stroke:null,fill:null,clip:null,band:null,gaps:null,flags:0},Cr=et?null:new Path2D;let Se=null;if(q!=null)Se=f.data[q.series[1]];else{let{y0:ne,y1:$e}=u;ne!=null&&$e!=null&&(y=$e.values(f,p,m,S),Se=ne.values(f,p,m,S))}let Re=T*Ce,pe=_*Ce;for(let ne=j==1?m:S;ne>=m&&ne<=S;ne+=j){let $e=y[ne];if($e==null)continue;if(Se!=null){let Ee=Se[ne]??0;if($e-Ee==0)continue;ve=E(Ee,x,z,R)}let ht=C.distr!=2||u!=null?g[ne]:ne,Q=I(ht,C,F,A),W=E(_e($e,oe),x,z,R),le=P(Q-ge),ye=P(Mr(W,ve)),de=P(En(W,ve)),Ue=ye-de;if($e!=null){let Ee=$e<0?pe:Re,Me=$e<0?Re:pe;et?(xe>0&&At[ne]!=null&&G(wt.get(At[ne]),le,de+Qr(xe/2),Ce,Mr(0,Ue-xe),Ee,Me),Ke[ne]!=null&&G(qe.get(Ke[ne]),le,de+Qr(xe/2),Ce,Mr(0,Ue-xe),Ee,Me)):G(Cr,le,de+Qr(xe/2),Ce,Mr(0,Ue-xe),Ee,Me),ee(f,p,ne,le-xe/2,de,Ce+xe,Ue)}}return xe>0?nt.stroke=et?wt:Cr:et||(nt._fill=w.width==0?w._fill:w._stroke??w._fill,nt.width=0),nt.fill=et?qe:Cr,nt})}function eU(r,e){const t=_e(e==null?void 0:e.alignGaps,0);return(n,i,s,o)=>ps(n,i,(a,l,u,c,d,h,f,p,m,S,w)=>{[s,o]=Du(u,s,o);let g=a.pxRound,y=T=>g(h(T,c,S,p)),C=T=>g(f(T,d,w,m)),x,I,E;c.ori==0?(x=$u,E=vo,I=kC):(x=Nu,E=wo,I=EC);const A=c.dir*(c.ori==0?1:-1);let R=y(l[A==1?s:o]),F=R,z=[],P=[];for(let T=A==1?s:o;T>=s&&T<=o;T+=A)if(u[T]!=null){let j=l[T],G=y(j);z.push(F=G),P.push(C(u[T]))}const O={stroke:r(z,P,x,E,I,g),fill:null,clip:null,band:null,gaps:null,flags:ho},L=O.stroke;let[V,X]=Gf(n,i);if(a.fill!=null||V!=0){let T=O.fill=new Path2D(L),_=a.fillTo(n,i,a.min,a.max,V),j=C(_);E(T,F,j),E(T,R,j)}if(!a.spanGaps){let T=[];T.push(...Xf(l,u,s,o,A,y,t)),O.gaps=T=a.gaps(n,i,s,o,T),O.clip=_u(T,c.ori,p,m,S,w)}return X!=0&&(O.band=X==2?[ti(n,i,s,o,L,-1),ti(n,i,s,o,L,1)]:ti(n,i,s,o,L,X)),O})}function tU(r){return eU(rU,r)}function rU(r,e,t,n,i,s){const o=r.length;if(o<2)return null;const a=new Path2D;if(t(a,r[0],e[0]),o==2)n(a,r[1],e[1]);else{let l=Array(o),u=Array(o-1),c=Array(o-1),d=Array(o-1);for(let h=0;h<o-1;h++)c[h]=e[h+1]-e[h],d[h]=r[h+1]-r[h],u[h]=c[h]/d[h];l[0]=u[0];for(let h=1;h<o-1;h++)u[h]===0||u[h-1]===0||u[h-1]>0!=u[h]>0?l[h]=0:(l[h]=3*(d[h-1]+d[h])/((2*d[h]+d[h-1])/u[h-1]+(d[h]+2*d[h-1])/u[h]),isFinite(l[h])||(l[h]=0));l[o-1]=u[o-2];for(let h=0;h<o-1;h++)i(a,r[h]+d[h]/3,e[h]+l[h]*d[h]/3,r[h+1]-d[h]/3,e[h+1]-l[h+1]*d[h]/3,r[h+1],e[h+1])}return a}const xh=new Set;function Jm(){for(let r of xh)r.syncRect(!0)}yo&&(ss(O5,Js,Jm),ss(F5,Js,Jm,!0),ss(uu,Js,()=>{yr.pxRatio=je}));const nU=AC(),iU=MC();function ey(r,e,t,n){return(n?[r[0],r[1]].concat(r.slice(2)):[r[0]].concat(r.slice(1))).map((s,o)=>Ih(s,o,e,t))}function sU(r,e){return r.map((t,n)=>n==0?{}:zt({},e,t))}function Ih(r,e,t,n){return zt({},e==0?t:n,r)}function TC(r,e,t){return e==null?uo:[e,t]}const oU=TC;function aU(r,e,t){return e==null?uo:cu(e,t,$f,!0)}function RC(r,e,t,n){return e==null?uo:Ou(e,t,r.scales[n].log,!1)}const lU=RC;function PC(r,e,t,n){return e==null?uo:_f(e,t,r.scales[n].log,!1)}const uU=PC;function cU(r,e,t,n,i){let s=Mr(Pm(r),Pm(e)),o=e-r,a=In(i/n*o,t);do{let l=t[a],u=n*l/o;if(u>=i&&s+(l<5?zi.get(l):0)<=17)return[l,u]}while(++a<t.length);return[0,0]}function ty(r){let e,t;return r=r.replace(/(\d+)px/,(n,i)=>(e=$t((t=+i)*je))+"px"),[r,e,t]}function dU(r){r.show&&[r.font,r.labelFont].forEach(e=>{let t=Je(e[2]*je,1);e[0]=e[0].replace(/[0-9.]+px/,t+"px"),e[1]=t})}function yr(r,e,t){const n={mode:_e(r.mode,1)},i=n.mode;function s(v,b,M,U){let B=b.valToPct(v);return U+M*(b.dir==-1?1-B:B)}function o(v,b,M,U){let B=b.valToPct(v);return U+M*(b.dir==-1?B:1-B)}function a(v,b,M,U){return b.ori==0?s(v,b,M,U):o(v,b,M,U)}n.valToPosH=s,n.valToPosV=o;let l=!1;n.status=0;const u=n.root=on(v5);if(r.id!=null&&(u.id=r.id),Wr(u,r.class),r.title){let v=on(b5,u);v.textContent=r.title}const c=Cn("canvas"),d=n.ctx=c.getContext("2d"),h=on(S5,u);ss("click",h,v=>{v.target===p&&(it!=bs||pt!=Ss)&&sr.click(n,v)},!0);const f=n.under=on(x5,h);h.appendChild(c);const p=n.over=on(I5,h);r=co(r);const m=+_e(r.pxAlign,1),S=qm(m);(r.plugins||[]).forEach(v=>{v.opts&&(r=v.opts(n,r)||r)});const w=r.ms||.001,g=n.series=i==1?ey(r.series||[],jm,Km,!1):sU(r.series||[null],Xm),y=n.axes=ey(r.axes||[],Hm,Wm,!0),C=n.scales={},x=n.bands=r.bands||[];x.forEach(v=>{v.fill=Pe(v.fill||null),v.dir=_e(v.dir,-1)});const I=i==2?g[1].facets[0].scale:g[0].scale,E={axes:YC,series:$C},A=(r.drawOrder||["axes","series"]).map(v=>E[v]);function R(v){const b=v.distr==3?M=>ei(M>0?M:v.clamp(n,M,v.min,v.max,v.key)):v.distr==4?M=>Kc(M,v.asinh):v.distr==100?M=>v.fwd(M):M=>M;return M=>{let U=b(M),{_min:B,_max:$}=v,Y=$-B;return(U-B)/Y}}function F(v){let b=C[v];if(b==null){let M=(r.scales||da)[v]||da;if(M.from!=null){F(M.from);let U=zt({},C[M.from],M,{key:v});U.valToPct=R(U),C[v]=U}else{b=C[v]=zt({},v==I?CC:GM,M),b.key=v;let U=b.time,B=b.range,$=mi(B);if((v!=I||i==2&&!U)&&($&&(B[0]==null||B[1]==null)&&(B={min:B[0]==null?Am:{mode:1,hard:B[0],soft:B[0]},max:B[1]==null?Am:{mode:1,hard:B[1],soft:B[1]}},$=!1),!$&&Lu(B))){let Y=B;B=(Z,re,ae)=>re==null?uo:cu(re,ae,Y)}b.range=Pe(B||(U?oU:v==I?b.distr==3?lU:b.distr==4?uU:TC:b.distr==3?RC:b.distr==4?PC:aU)),b.auto=Pe($?!1:b.auto),b.clamp=Pe(b.clamp||WM),b._min=b._max=null,b.valToPct=R(b)}}}F("x"),F("y"),i==1&&g.forEach(v=>{F(v.scale)}),y.forEach(v=>{F(v.scale)});for(let v in r.scales)F(v);const z=C[I],P=z.distr;let O,L;z.ori==0?(Wr(u,w5),O=s,L=o):(Wr(u,C5),O=o,L=s);const V={};for(let v in C){let b=C[v];(b.min!=null||b.max!=null)&&(V[v]={min:b.min,max:b.max},b.min=b.max=null)}const X=r.tzDate||(v=>new Date($t(v/w))),T=r.fmtDate||Hf,_=w==1?wM(X):SM(X),j=$m(X,_m(w==1?vM:bM,T)),G=Vm(X,Nm(IM,T)),ee=[],q=n.legend=zt({},MM,r.legend),K=n.cursor=zt({},BM,{drag:{y:i==2}},r.cursor),oe=q.show,ve=K.show,ge=q.markers;q.idxs=ee,ge.width=Pe(ge.width),ge.dash=Pe(ge.dash),ge.stroke=Pe(ge.stroke),ge.fill=Pe(ge.fill);let Ce,ct,dt,xe=[],et=[],Ke,qe=!1,At={};if(q.live){const v=g[1]?g[1].values:null;qe=v!=null,Ke=qe?v(n,1,0):{_:0};for(let b in Ke)At[b]=Ff}if(oe)if(Ce=Cn("table",T5,u),dt=Cn("tbody",null,Ce),q.mount(n,Ce),qe){ct=Cn("thead",null,Ce,dt);let v=Cn("tr",null,ct);Cn("th",null,v);for(var wt in Ke)Cn("th",mm,v).textContent=wt}else Wr(Ce,P5),q.live&&Wr(Ce,R5);const Ft={show:!0},cr={show:!1};function tt(v,b){if(b==0&&(qe||!q.live||i==2))return uo;let M=[],U=Cn("tr",B5,dt,dt.childNodes[b]);Wr(U,v.class),v.show||Wr(U,Ji);let B=Cn("th",null,U);if(ge.show){let Z=on(z5,B);if(b>0){let re=ge.width(n,b);re&&(Z.style.border=re+"px "+ge.dash(n,b)+" "+ge.stroke(n,b)),Z.style.background=ge.fill(n,b)}}let $=on(mm,B);v.label instanceof HTMLElement?$.appendChild(v.label):$.textContent=v.label,b>0&&(ge.show||($.style.color=v.width>0?ge.stroke(n,b):ge.fill(n,b)),nt("click",B,Z=>{if(K._lock)return;Br(Z);let re=g.indexOf(v);if((Z.ctrlKey||Z.metaKey)!=q.isolate){let ae=g.some((ue,he)=>he>0&&he!=re&&ue.show);g.forEach((ue,he)=>{he>0&&zn(he,ae?he==re?Ft:cr:Ft,!0,Bt.setSeries)})}else zn(re,{show:!v.show},!0,Bt.setSeries)},!1),Tn&&nt(Cm,B,Z=>{K._lock||(Br(Z),zn(g.indexOf(v),Is,!0,Bt.setSeries))},!1));for(var Y in Ke){let Z=Cn("td",D5,U);Z.textContent="--",M.push(Z)}return[U,M]}const kt=new Map;function nt(v,b,M,U=!0){const B=kt.get(b)||{},$=K.bind[v](n,b,M,U);$&&(ss(v,b,B[v]=$),kt.set(b,B))}function Cr(v,b,M){const U=kt.get(b)||{};for(let B in U)(v==null||B==v)&&(vh(B,b,U[B]),delete U[B]);v==null&&kt.delete(b)}let Se=0,Re=0,pe=0,ne=0,$e=0,ht=0,Q=$e,W=ht,le=pe,ye=ne,de=0,Ue=0,Ee=0,Me=0;n.bbox={};let Ne=!1,we=!1,Oe=!1,Tt=!1,ft=!1,Ve=!1;function Xt(v,b,M){(M||v!=n.width||b!=n.height)&&Lt(v,b),ys(!1),Oe=!0,we=!0,vs()}function Lt(v,b){n.width=Se=pe=v,n.height=Re=ne=b,$e=ht=0,Fe(),$i();let M=n.bbox;de=M.left=qi($e*je,.5),Ue=M.top=qi(ht*je,.5),Ee=M.width=qi(pe*je,.5),Me=M.height=qi(ne*je,.5)}const ai=3;function Li(){let v=!1,b=0;for(;!v;){b++;let M=HC(b),U=jC(b);v=b==ai||M&&U,v||(Lt(n.width,n.height),we=!0)}}function _i({width:v,height:b}){Xt(v,b)}n.setSize=_i;function Fe(){let v=!1,b=!1,M=!1,U=!1;y.forEach((B,$)=>{if(B.show&&B._show){let{side:Y,_size:Z}=B,re=Y%2,ae=B.label!=null?B.labelSize:0,ue=Z+ae;ue>0&&(re?(pe-=ue,Y==3?($e+=ue,U=!0):M=!0):(ne-=ue,Y==0?(ht+=ue,v=!0):b=!0))}}),Vi[0]=v,Vi[1]=M,Vi[2]=b,Vi[3]=U,pe-=li[1]+li[3],$e+=li[3],ne-=li[2]+li[0],ht+=li[0]}function $i(){let v=$e+pe,b=ht+ne,M=$e,U=ht;function B($,Y){switch($){case 1:return v+=Y,v-Y;case 2:return b+=Y,b-Y;case 3:return M-=Y,M+Y;case 0:return U-=Y,U+Y}}y.forEach(($,Y)=>{if($.show&&$._show){let Z=$.side;$._pos=B(Z,$._size),$.label!=null&&($._lpos=B(Z,$.labelSize))}})}if(K.dataIdx==null){let v=K.hover,b=v.skip=new Set(v.skip??[]);b.add(void 0);let M=v.prox=Pe(v.prox),U=v.bias??(v.bias=0);K.dataIdx=(B,$,Y,Z)=>{if($==0)return Y;let re=Y,ae=M(B,$,Y,Z)??Qe,ue=ae>=0&&ae<Qe,he=z.ori==0?pe:ne,Ie=K.left,He=e[0],Le=e[$];if(b.has(Le[Y])){re=null;let Ae=null,be=null,me;if(U==0||U==-1)for(me=Y;Ae==null&&me-- >0;)b.has(Le[me])||(Ae=me);if(U==0||U==1)for(me=Y;be==null&&me++<Le.length;)b.has(Le[me])||(be=me);if(Ae!=null||be!=null)if(ue){let ot=Ae==null?-1/0:O(He[Ae],z,he,0),Et=be==null?1/0:O(He[be],z,he,0),er=Ie-ot,Ze=Et-Ie;er<=Ze?er<=ae&&(re=Ae):Ze<=ae&&(re=be)}else re=be==null?Ae:Ae==null?be:Y-Ae<=be-Y?Ae:be}else ue&&jt(Ie-O(He[Y],z,he,0))>ae&&(re=null);return re}}const Br=v=>{K.event=v};K.idxs=ee,K._lock=!1;let Ct=K.points;Ct.show=Pe(Ct.show),Ct.size=Pe(Ct.size),Ct.stroke=Pe(Ct.stroke),Ct.width=Pe(Ct.width),Ct.fill=Pe(Ct.fill);const dr=n.focus=zt({},r.focus||{alpha:.3},K.focus),Tn=dr.prox>=0,Rn=Tn&&Ct.one;let hr=[],Pn=[],Bn=[];function gs(v,b){let M=Ct.show(n,b);if(M instanceof HTMLElement)return Wr(M,A5),Wr(M,v.class),_n(M,-10,-10,pe,ne),p.insertBefore(M,hr[b]),M}function Pt(v,b){if(i==1||b>0){let M=i==1&&C[v.scale].time,U=v.value;v.value=M?Dm(U)?Vm(X,Nm(U,T)):U||G:U||HM,v.label=v.label||(M?DM:zM)}if(Rn||b>0){v.width=v.width==null?1:v.width,v.paths=v.paths||nU||G5,v.fillTo=Pe(v.fillTo||XM),v.pxAlign=+_e(v.pxAlign,m),v.pxRound=qm(v.pxAlign),v.stroke=Pe(v.stroke||null),v.fill=Pe(v.fill||null),v._stroke=v._fill=v._paths=v._focus=null;let M=jM(Mr(1,v.width),1),U=v.points=zt({},{size:M,width:Mr(1,M*.2),stroke:v.stroke,space:M*2,paths:iU,_stroke:null,_fill:null},v.points);U.show=Pe(U.show),U.filter=Pe(U.filter),U.fill=Pe(U.fill),U.stroke=Pe(U.stroke),U.paths=Pe(U.paths),U.pxAlign=v.pxAlign}if(oe){let M=tt(v,b);xe.splice(b,0,M[0]),et.splice(b,0,M[1]),q.values.push(null)}if(ve){ee.splice(b,0,null);let M=null;Rn?b==0&&(M=gs(v,b)):b>0&&(M=gs(v,b)),hr.splice(b,0,M),Pn.splice(b,0,0),Bn.splice(b,0,0)}Jt("addSeries",b)}function bt(v,b){b=b??g.length,v=i==1?Ih(v,b,jm,Km):Ih(v,b,{},Xm),g.splice(b,0,v),Pt(g[b],b)}n.addSeries=bt;function Ni(v){if(g.splice(v,1),oe){q.values.splice(v,1),et.splice(v,1);let b=xe.splice(v,1)[0];Cr(null,b.firstChild),b.remove()}ve&&(ee.splice(v,1),hr.splice(v,1)[0].remove(),Pn.splice(v,1),Bn.splice(v,1)),Jt("delSeries",v)}n.delSeries=Ni;const Vi=[!1,!1,!1,!1];function FC(v,b){if(v._show=v.show,v.show){let M=v.side%2,U=C[v.scale];U==null&&(v.scale=M?g[1].scale:I,U=C[v.scale]);let B=U.time;v.size=Pe(v.size),v.space=Pe(v.space),v.rotate=Pe(v.rotate),mi(v.incrs)&&v.incrs.forEach(Y=>{!zi.has(Y)&&zi.set(Y,tC(Y))}),v.incrs=Pe(v.incrs||(U.distr==2?gM:B?w==1?yM:CM:Qi)),v.splits=Pe(v.splits||(B&&U.distr==1?_:U.distr==3?Ch:U.distr==4?LM:FM)),v.stroke=Pe(v.stroke),v.grid.stroke=Pe(v.grid.stroke),v.ticks.stroke=Pe(v.ticks.stroke),v.border.stroke=Pe(v.border.stroke);let $=v.values;v.values=mi($)&&!mi($[0])?Pe($):B?mi($)?$m(X,_m($,T)):Dm($)?xM(X,$):$||j:$||OM,v.filter=Pe(v.filter||(U.distr>=3&&U.log==10?NM:U.distr==3&&U.log==2?VM:Jw)),v.font=ty(v.font),v.labelFont=ty(v.labelFont),v._size=v.size(n,null,b,0),v._space=v._rotate=v._incrs=v._found=v._splits=v._values=null,v._size>0&&(Vi[b]=!0,v._el=on(k5,h))}}function bo(v,b,M,U){let[B,$,Y,Z]=M,re=b%2,ae=0;return re==0&&(Z||$)&&(ae=b==0&&!B||b==2&&!Y?$t(Hm.size/3):0),re==1&&(B||Y)&&(ae=b==1&&!$||b==3&&!Z?$t(Wm.size/2):0),ae}const Qf=n.padding=(r.padding||[bo,bo,bo,bo]).map(v=>Pe(_e(v,bo))),li=n._padding=Qf.map((v,b)=>v(n,b,Vi,0));let ir,Kt=null,Zt=null;const La=i==1?g[0].idxs:null;let gn=null,So=!1;function Jf(v,b){if(e=v??[],n.data=n._data=e,i==2){ir=0;for(let M=1;M<g.length;M++)ir+=e[M][0].length}else{e.length==0&&(n.data=n._data=e=[[]]),gn=e[0],ir=gn.length;let M=e;if(P==2){M=e.slice();let U=M[0]=Array(ir);for(let B=0;B<ir;B++)U[B]=B}n._data=e=M}if(ys(!0),Jt("setData"),P==2&&(Oe=!0),b!==!1){let M=z;M.auto(n,So)?Hu():ci(I,M.min,M.max),Tt=Tt||K.left>=0,Ve=!0,vs()}}n.setData=Jf;function Hu(){So=!0;let v,b;i==1&&(ir>0?(Kt=La[0]=0,Zt=La[1]=ir-1,v=e[0][Kt],b=e[0][Zt],P==2?(v=Kt,b=Zt):v==b&&(P==3?[v,b]=Ou(v,v,z.log,!1):P==4?[v,b]=_f(v,v,z.log,!1):z.time?b=v+$t(86400/w):[v,b]=cu(v,b,$f,!0))):(Kt=La[0]=v=null,Zt=La[1]=b=null)),ci(I,v,b)}let _a,ms,ju,Yu,Wu,Gu,Xu,Ku,Zu,zr;function ep(v,b,M,U,B,$){v??(v=vm),M??(M=Vf),U??(U="butt"),B??(B=vm),$??($="round"),v!=_a&&(d.strokeStyle=_a=v),B!=ms&&(d.fillStyle=ms=B),b!=ju&&(d.lineWidth=ju=b),$!=Wu&&(d.lineJoin=Wu=$),U!=Gu&&(d.lineCap=Gu=U),M!=Yu&&d.setLineDash(Yu=M)}function tp(v,b,M,U){b!=ms&&(d.fillStyle=ms=b),v!=Xu&&(d.font=Xu=v),M!=Ku&&(d.textAlign=Ku=M),U!=Zu&&(d.textBaseline=Zu=U)}function qu(v,b,M,U,B=0){if(U.length>0&&v.auto(n,So)&&(b==null||b.min==null)){let $=_e(Kt,0),Y=_e(Zt,U.length-1),Z=M.min==null?N5(U,$,Y,B,v.distr==3):[M.min,M.max];v.min=En(v.min,M.min=Z[0]),v.max=Mr(v.max,M.max=Z[1])}}const rp={min:null,max:null};function LC(){for(let U in C){let B=C[U];V[U]==null&&(B.min==null||V[I]!=null&&B.auto(n,So))&&(V[U]=rp)}for(let U in C){let B=C[U];V[U]==null&&B.from!=null&&V[B.from]!=null&&(V[U]=rp)}V[I]!=null&&ys(!0);let v={};for(let U in V){let B=V[U];if(B!=null){let $=v[U]=co(C[U],Z5);if(B.min!=null)zt($,B);else if(U!=I||i==2)if(ir==0&&$.from==null){let Y=$.range(n,null,null,U);$.min=Y[0],$.max=Y[1]}else $.min=Qe,$.max=-Qe}}if(ir>0){g.forEach((U,B)=>{if(i==1){let $=U.scale,Y=V[$];if(Y==null)return;let Z=v[$];if(B==0){let re=Z.range(n,Z.min,Z.max,$);Z.min=re[0],Z.max=re[1],Kt=In(Z.min,e[0]),Zt=In(Z.max,e[0]),Zt-Kt>1&&(e[0][Kt]<Z.min&&Kt++,e[0][Zt]>Z.max&&Zt--),U.min=gn[Kt],U.max=gn[Zt]}else U.show&&U.auto&&qu(Z,Y,U,e[B],U.sorted);U.idxs[0]=Kt,U.idxs[1]=Zt}else if(B>0&&U.show&&U.auto){let[$,Y]=U.facets,Z=$.scale,re=Y.scale,[ae,ue]=e[B],he=v[Z],Ie=v[re];he!=null&&qu(he,V[Z],$,ae,$.sorted),Ie!=null&&qu(Ie,V[re],Y,ue,Y.sorted),U.min=Y.min,U.max=Y.max}});for(let U in v){let B=v[U],$=V[U];if(B.from==null&&($==null||$.min==null)){let Y=B.range(n,B.min==Qe?null:B.min,B.max==-Qe?null:B.max,U);B.min=Y[0],B.max=Y[1]}}}for(let U in v){let B=v[U];if(B.from!=null){let $=v[B.from];if($.min==null)B.min=B.max=null;else{let Y=B.range(n,$.min,$.max,U);B.min=Y[0],B.max=Y[1]}}}let b={},M=!1;for(let U in v){let B=v[U],$=C[U];if($.min!=B.min||$.max!=B.max){$.min=B.min,$.max=B.max;let Y=$.distr;$._min=Y==3?ei($.min):Y==4?Kc($.min,$.asinh):Y==100?$.fwd($.min):$.min,$._max=Y==3?ei($.max):Y==4?Kc($.max,$.asinh):Y==100?$.fwd($.max):$.max,b[U]=M=!0}}if(M){g.forEach((U,B)=>{i==2?B>0&&b.y&&(U._paths=null):b[U.scale]&&(U._paths=null)});for(let U in b)Oe=!0,Jt("setScale",U);ve&&K.left>=0&&(Tt=Ve=!0)}for(let U in V)V[U]=null}function _C(v){let b=wh(Kt-1,0,ir-1),M=wh(Zt+1,0,ir-1);for(;v[b]==null&&b>0;)b--;for(;v[M]==null&&M<ir-1;)M++;return[b,M]}function $C(){if(ir>0){let v=g.some(b=>b._focus)&&zr!=dr.alpha;v&&(d.globalAlpha=zr=dr.alpha),g.forEach((b,M)=>{if(M>0&&b.show&&(np(M,!1),np(M,!0),b._paths==null)){let U=zr;zr!=b.alpha&&(d.globalAlpha=zr=b.alpha);let B=i==2?[0,e[M][0].length-1]:_C(e[M]);b._paths=b.paths(n,M,B[0],B[1]),zr!=U&&(d.globalAlpha=zr=U)}}),g.forEach((b,M)=>{if(M>0&&b.show){let U=zr;zr!=b.alpha&&(d.globalAlpha=zr=b.alpha),b._paths!=null&&ip(M,!1);{let B=b._paths!=null?b._paths.gaps:null,$=b.points.show(n,M,Kt,Zt,B),Y=b.points.filter(n,M,$,B);($||Y)&&(b.points._paths=b.points.paths(n,M,Kt,Zt,Y),ip(M,!0))}zr!=U&&(d.globalAlpha=zr=U),Jt("drawSeries",M)}}),v&&(d.globalAlpha=zr=1)}}function np(v,b){let M=b?g[v].points:g[v];M._stroke=M.stroke(n,v),M._fill=M.fill(n,v)}function ip(v,b){let M=b?g[v].points:g[v],{stroke:U,fill:B,clip:$,flags:Y,_stroke:Z=M._stroke,_fill:re=M._fill,_width:ae=M.width}=M._paths;ae=Je(ae*je,3);let ue=null,he=ae%2/2;b&&re==null&&(re=ae>0?"#fff":Z);let Ie=M.pxAlign==1&&he>0;if(Ie&&d.translate(he,he),!b){let He=de-ae/2,Le=Ue-ae/2,Ae=Ee+ae,be=Me+ae;ue=new Path2D,ue.rect(He,Le,Ae,be)}b?Qu(Z,ae,M.dash,M.cap,re,U,B,Y,$):NC(v,Z,ae,M.dash,M.cap,re,U,B,Y,ue,$),Ie&&d.translate(-he,-he)}function NC(v,b,M,U,B,$,Y,Z,re,ae,ue){let he=!1;re!=0&&x.forEach((Ie,He)=>{if(Ie.series[0]==v){let Le=g[Ie.series[1]],Ae=e[Ie.series[1]],be=(Le._paths||da).band;mi(be)&&(be=Ie.dir==1?be[0]:be[1]);let me,ot=null;Le.show&&be&&H5(Ae,Kt,Zt)?(ot=Ie.fill(n,He)||$,me=Le._paths.clip):be=null,Qu(b,M,U,B,ot,Y,Z,re,ae,ue,me,be),he=!0}}),he||Qu(b,M,U,B,$,Y,Z,re,ae,ue)}const sp=ho|Sh;function Qu(v,b,M,U,B,$,Y,Z,re,ae,ue,he){ep(v,b,M,U,B),(re||ae||he)&&(d.save(),re&&d.clip(re),ae&&d.clip(ae)),he?(Z&sp)==sp?(d.clip(he),ue&&d.clip(ue),Na(B,Y),$a(v,$,b)):Z&Sh?(Na(B,Y),d.clip(he),$a(v,$,b)):Z&ho&&(d.save(),d.clip(he),ue&&d.clip(ue),Na(B,Y),d.restore(),$a(v,$,b)):(Na(B,Y),$a(v,$,b)),(re||ae||he)&&d.restore()}function $a(v,b,M){M>0&&(b instanceof Map?b.forEach((U,B)=>{d.strokeStyle=_a=B,d.stroke(U)}):b!=null&&v&&d.stroke(b))}function Na(v,b){b instanceof Map?b.forEach((M,U)=>{d.fillStyle=ms=U,d.fill(M)}):b!=null&&v&&d.fill(b)}function VC(v,b,M,U){let B=y[v],$;if(U<=0)$=[0,0];else{let Y=B._space=B.space(n,v,b,M,U),Z=B._incrs=B.incrs(n,v,b,M,U,Y);$=cU(b,M,Z,U,Y)}return B._found=$}function Ju(v,b,M,U,B,$,Y,Z,re,ae){let ue=Y%2/2;m==1&&d.translate(ue,ue),ep(Z,Y,re,ae,Z),d.beginPath();let he,Ie,He,Le,Ae=B+(U==0||U==3?-$:$);M==0?(Ie=B,Le=Ae):(he=B,He=Ae);for(let be=0;be<v.length;be++)b[be]!=null&&(M==0?he=He=v[be]:Ie=Le=v[be],d.moveTo(he,Ie),d.lineTo(He,Le));d.stroke(),m==1&&d.translate(-ue,-ue)}function HC(v){let b=!0;return y.forEach((M,U)=>{if(!M.show)return;let B=C[M.scale];if(B.min==null){M._show&&(b=!1,M._show=!1,ys(!1));return}else M._show||(b=!1,M._show=!0,ys(!1));let $=M.side,Y=$%2,{min:Z,max:re}=B,[ae,ue]=VC(U,Z,re,Y==0?pe:ne);if(ue==0)return;let he=B.distr==2,Ie=M._splits=M.splits(n,U,Z,re,ae,ue,he),He=B.distr==2?Ie.map(me=>gn[me]):Ie,Le=B.distr==2?gn[Ie[1]]-gn[Ie[0]]:ae,Ae=M._values=M.values(n,M.filter(n,He,U,ue,Le),U,ue,Le);M._rotate=$==2?M.rotate(n,Ae,U,ue):0;let be=M._size;M._size=an(M.size(n,Ae,U,v)),be!=null&&M._size!=be&&(b=!1)}),b}function jC(v){let b=!0;return Qf.forEach((M,U)=>{let B=M(n,U,Vi,v);B!=li[U]&&(b=!1),li[U]=B}),b}function YC(){for(let v=0;v<y.length;v++){let b=y[v];if(!b.show||!b._show)continue;let M=b.side,U=M%2,B,$,Y=b.stroke(n,v),Z=M==0||M==3?-1:1,[re,ae]=b._found;if(b.label!=null){let Sr=b.labelGap*Z,jr=$t((b._lpos+Sr)*je);tp(b.labelFont[0],Y,"center",M==2?_o:ym),d.save(),U==1?(B=$=0,d.translate(jr,$t(Ue+Me/2)),d.rotate((M==3?-zl:zl)/2)):(B=$t(de+Ee/2),$=jr);let Yi=qw(b.label)?b.label(n,v,re,ae):b.label;d.fillText(Yi,B,$),d.restore()}if(ae==0)continue;let ue=C[b.scale],he=U==0?Ee:Me,Ie=U==0?de:Ue,He=b._splits,Le=ue.distr==2?He.map(Sr=>gn[Sr]):He,Ae=ue.distr==2?gn[He[1]]-gn[He[0]]:re,be=b.ticks,me=b.border,ot=be.show?be.size:0,Et=$t(ot*je),er=$t((b.alignTo==2?b._size-ot-b.gap:b.gap)*je),Ze=b._rotate*-zl/180,Mt=S(b._pos*je),Vr=(Et+er)*Z,br=Mt+Vr;$=U==0?br:0,B=U==1?br:0;let nn=b.font[0],mn=b.align==1?Us:b.align==2?Wc:Ze>0?Us:Ze<0?Wc:U==0?"center":M==3?Wc:Us,On=Ze||U==1?"middle":M==2?_o:ym;tp(nn,Y,mn,On);let Hr=b.font[1]*b.lineGap,sn=He.map(Sr=>S(a(Sr,ue,he,Ie))),yn=b._values;for(let Sr=0;Sr<yn.length;Sr++){let jr=yn[Sr];if(jr!=null){U==0?B=sn[Sr]:$=sn[Sr],jr=""+jr;let Yi=jr.indexOf(`
|
|
275
|
-
`)==-1?[jr]:jr.split(/\n/gm);for(let xr=0;xr<Yi.length;xr++){let Ip=Yi[xr];Ze?(d.save(),d.translate(B,$+xr*Hr),d.rotate(Ze),d.fillText(Ip,0,0),d.restore()):d.fillText(Ip,B,$+xr*Hr)}}}be.show&&Ju(sn,be.filter(n,Le,v,ae,Ae),U,M,Mt,Et,Je(be.width*je,3),be.stroke(n,v),be.dash,be.cap);let Fn=b.grid;Fn.show&&Ju(sn,Fn.filter(n,Le,v,ae,Ae),U,U==0?2:1,U==0?Ue:de,U==0?Me:Ee,Je(Fn.width*je,3),Fn.stroke(n,v),Fn.dash,Fn.cap),me.show&&Ju([Mt],[1],U==0?1:0,U==0?1:2,U==1?Ue:de,U==1?Me:Ee,Je(me.width*je,3),me.stroke(n,v),me.dash,me.cap)}Jt("drawAxes")}function ys(v){g.forEach((b,M)=>{M>0&&(b._paths=null,v&&(i==1?(b.min=null,b.max=null):b.facets.forEach(U=>{U.min=null,U.max=null})))})}let Va=!1,ec=!1,xo=[];function WC(){ec=!1;for(let v=0;v<xo.length;v++)Jt(...xo[v]);xo.length=0}function vs(){Va||(nM(op),Va=!0)}function GC(v,b=!1){Va=!0,ec=b,v(n),op(),b&&xo.length>0&&queueMicrotask(WC)}n.batch=GC;function op(){if(Ne&&(LC(),Ne=!1),Oe&&(Li(),Oe=!1),we){if(lt(f,Us,$e),lt(f,_o,ht),lt(f,Go,pe),lt(f,Xo,ne),lt(p,Us,$e),lt(p,_o,ht),lt(p,Go,pe),lt(p,Xo,ne),lt(h,Go,Se),lt(h,Xo,Re),c.width=$t(Se*je),c.height=$t(Re*je),y.forEach(({_el:v,_show:b,_size:M,_pos:U,side:B})=>{if(v!=null)if(b){let $=B===3||B===0?M:0,Y=B%2==1;lt(v,Y?"left":"top",U-$),lt(v,Y?"width":"height",M),lt(v,Y?"top":"left",Y?ht:$e),lt(v,Y?"height":"width",Y?ne:pe),yh(v,Ji)}else Wr(v,Ji)}),_a=ms=ju=Wu=Gu=Xu=Ku=Zu=Yu=null,zr=1,Eo(!0),$e!=Q||ht!=W||pe!=le||ne!=ye){ys(!1);let v=pe/le,b=ne/ye;if(ve&&!Tt&&K.left>=0){K.left*=v,K.top*=b,ws&&_n(ws,$t(K.left),0,pe,ne),Cs&&_n(Cs,0,$t(K.top),pe,ne);for(let M=0;M<hr.length;M++){let U=hr[M];U!=null&&(Pn[M]*=v,Bn[M]*=b,_n(U,an(Pn[M]),an(Bn[M]),pe,ne))}}if(st.show&&!ft&&st.left>=0&&st.width>0){st.left*=v,st.width*=v,st.top*=b,st.height*=b;for(let M in oc)lt(xs,M,st[M])}Q=$e,W=ht,le=pe,ye=ne}Jt("setSize"),we=!1}Se>0&&Re>0&&(d.clearRect(0,0,c.width,c.height),Jt("drawClear"),A.forEach(v=>v()),Jt("draw")),st.show&&ft&&(Ha(st),ft=!1),ve&&Tt&&(ji(null,!0,!1),Tt=!1),q.show&&q.live&&Ve&&(ic(),Ve=!1),l||(l=!0,n.status=1,Jt("ready")),So=!1,Va=!1}n.redraw=(v,b)=>{Oe=b||!1,v!==!1?ci(I,z.min,z.max):vs()};function tc(v,b){let M=C[v];if(M.from==null){if(ir==0){let U=M.range(n,b.min,b.max,v);b.min=U[0],b.max=U[1]}if(b.min>b.max){let U=b.min;b.min=b.max,b.max=U}if(ir>1&&b.min!=null&&b.max!=null&&b.max-b.min<1e-16)return;v==I&&M.distr==2&&ir>0&&(b.min=In(b.min,e[0]),b.max=In(b.max,e[0]),b.min==b.max&&b.max++),V[v]=b,Ne=!0,vs()}}n.setScale=tc;let rc,nc,ws,Cs,ap,lp,bs,Ss,up,cp,it,pt,ui=!1;const sr=K.drag;let qt=sr.x,Qt=sr.y;ve&&(K.x&&(rc=on(M5,p)),K.y&&(nc=on(U5,p)),z.ori==0?(ws=rc,Cs=nc):(ws=nc,Cs=rc),it=K.left,pt=K.top);const st=n.select=zt({show:!0,over:!0,left:0,width:0,top:0,height:0},r.select),xs=st.show?on(E5,st.over?p:f):null;function Ha(v,b){if(st.show){for(let M in v)st[M]=v[M],M in oc&<(xs,M,v[M]);b!==!1&&Jt("setSelect")}}n.setSelect=Ha;function XC(v){if(g[v].show)oe&&yh(xe[v],Ji);else if(oe&&Wr(xe[v],Ji),ve){let M=Rn?hr[0]:hr[v];M!=null&&_n(M,-10,-10,pe,ne)}}function ci(v,b,M){tc(v,{min:b,max:M})}function zn(v,b,M,U){b.focus!=null&&JC(v),b.show!=null&&g.forEach((B,$)=>{$>0&&(v==$||v==null)&&(B.show=b.show,XC($),i==2?(ci(B.facets[0].scale,null,null),ci(B.facets[1].scale,null,null)):ci(B.scale,null,null),vs())}),M!==!1&&Jt("setSeries",v,b),U&&Mo("setSeries",n,v,b)}n.setSeries=zn;function KC(v,b){zt(x[v],b)}function ZC(v,b){v.fill=Pe(v.fill||null),v.dir=_e(v.dir,-1),b=b??x.length,x.splice(b,0,v)}function qC(v){v==null?x.length=0:x.splice(v,1)}n.addBand=ZC,n.setBand=KC,n.delBand=qC;function QC(v,b){g[v].alpha=b,ve&&hr[v]!=null&&(hr[v].style.opacity=b),oe&&xe[v]&&(xe[v].style.opacity=b)}let Wn,di,Hi;const Is={focus:!0};function JC(v){if(v!=Hi){let b=v==null,M=dr.alpha!=1;g.forEach((U,B)=>{if(i==1||B>0){let $=b||B==0||B==v;U._focus=b?null:$,M&&QC(B,$?1:dr.alpha)}}),Hi=v,M&&vs()}}oe&&Tn&&nt(bm,Ce,v=>{K._lock||(Br(v),Hi!=null&&zn(null,Is,!0,Bt.setSeries))});function Dn(v,b,M){let U=C[b];M&&(v=v/je-(U.ori==1?ht:$e));let B=pe;U.ori==1&&(B=ne,v=B-v),U.dir==-1&&(v=B-v);let $=U._min,Y=U._max,Z=v/B,re=$+(Y-$)*Z,ae=U.distr;return ae==3?lo(10,re):ae==4?Y5(re,U.asinh):ae==100?U.bwd(re):re}function eb(v,b){let M=Dn(v,I,b);return In(M,e[0],Kt,Zt)}n.valToIdx=v=>In(v,e[0]),n.posToIdx=eb,n.posToVal=Dn,n.valToPos=(v,b,M)=>C[b].ori==0?s(v,C[b],M?Ee:pe,M?de:0):o(v,C[b],M?Me:ne,M?Ue:0),n.setCursor=(v,b,M)=>{it=v.left,pt=v.top,ji(null,b,M)};function dp(v,b){lt(xs,Us,st.left=v),lt(xs,Go,st.width=b)}function hp(v,b){lt(xs,_o,st.top=v),lt(xs,Xo,st.height=b)}let Io=z.ori==0?dp:hp,ko=z.ori==1?dp:hp;function tb(){if(oe&&q.live)for(let v=i==2?1:0;v<g.length;v++){if(v==0&&qe)continue;let b=q.values[v],M=0;for(let U in b)et[v][M++].firstChild.nodeValue=b[U]}}function ic(v,b){if(v!=null&&(v.idxs?v.idxs.forEach((M,U)=>{ee[U]=M}):K5(v.idx)||ee.fill(v.idx),q.idx=ee[0]),oe&&q.live){for(let M=0;M<g.length;M++)(M>0||i==1&&!qe)&&rb(M,ee[M]);tb()}Ve=!1,b!==!1&&Jt("setLegend")}n.setLegend=ic;function rb(v,b){let M=g[v],U=v==0&&P==2?gn:e[v],B;qe?B=M.values(n,v,b)??At:(B=M.value(n,b==null?null:U[b],v,b),B=B==null?At:{_:B}),q.values[v]=B}function ji(v,b,M){up=it,cp=pt,[it,pt]=K.move(n,it,pt),K.left=it,K.top=pt,ve&&(ws&&_n(ws,$t(it),0,pe,ne),Cs&&_n(Cs,0,$t(pt),pe,ne));let U,B=Kt>Zt;Wn=Qe,di=null;let $=z.ori==0?pe:ne,Y=z.ori==1?pe:ne;if(it<0||ir==0||B){U=K.idx=null;for(let Z=0;Z<g.length;Z++){let re=hr[Z];re!=null&&_n(re,-10,-10,pe,ne)}Tn&&zn(null,Is,!0,v==null&&Bt.setSeries),q.live&&(ee.fill(U),Ve=!0)}else{let Z,re,ae;i==1&&(Z=z.ori==0?it:pt,re=Dn(Z,I),U=K.idx=In(re,e[0],Kt,Zt),ae=O(e[0][U],z,$,0));let ue=-10,he=-10,Ie=0,He=0,Le=!0,Ae="",be="";for(let me=i==2?1:0;me<g.length;me++){let ot=g[me],Et=ee[me],er=Et==null?null:i==1?e[me][Et]:e[me][1][Et],Ze=K.dataIdx(n,me,U,re),Mt=Ze==null?null:i==1?e[me][Ze]:e[me][1][Ze];if(Ve=Ve||Mt!=er||Ze!=Et,ee[me]=Ze,me>0&&ot.show){let Vr=Ze==null?-10:Ze==U?ae:O(i==1?e[0][Ze]:e[me][0][Ze],z,$,0),br=Mt==null?-10:L(Mt,i==1?C[ot.scale]:C[ot.facets[1].scale],Y,0);if(Tn&&Mt!=null){let nn=z.ori==1?it:pt,mn=jt(dr.dist(n,me,Ze,br,nn));if(mn<Wn){let On=dr.bias;if(On!=0){let Hr=Dn(nn,ot.scale),sn=Mt>=0?1:-1,yn=Hr>=0?1:-1;yn==sn&&(yn==1?On==1?Mt>=Hr:Mt<=Hr:On==1?Mt<=Hr:Mt>=Hr)&&(Wn=mn,di=me)}else Wn=mn,di=me}}if(Ve||Rn){let nn,mn;z.ori==0?(nn=Vr,mn=br):(nn=br,mn=Vr);let On,Hr,sn,yn,Fn,Sr,jr=!0,Yi=Ct.bbox;if(Yi!=null){jr=!1;let xr=Yi(n,me);sn=xr.left,yn=xr.top,On=xr.width,Hr=xr.height}else sn=nn,yn=mn,On=Hr=Ct.size(n,me);if(Sr=Ct.fill(n,me),Fn=Ct.stroke(n,me),Rn)me==di&&Wn<=dr.prox&&(ue=sn,he=yn,Ie=On,He=Hr,Le=jr,Ae=Sr,be=Fn);else{let xr=hr[me];xr!=null&&(Pn[me]=sn,Bn[me]=yn,Um(xr,On,Hr,jr),Em(xr,Sr,Fn),_n(xr,an(sn),an(yn),pe,ne))}}}}if(Rn){let me=dr.prox,ot=Hi==null?Wn<=me:Wn>me||di!=Hi;if(Ve||ot){let Et=hr[0];Et!=null&&(Pn[0]=ue,Bn[0]=he,Um(Et,Ie,He,Le),Em(Et,Ae,be),_n(Et,an(ue),an(he),pe,ne))}}}if(st.show&&ui)if(v!=null){let[Z,re]=Bt.scales,[ae,ue]=Bt.match,[he,Ie]=v.cursor.sync.scales,He=v.cursor.drag;if(qt=He._x,Qt=He._y,qt||Qt){let{left:Le,top:Ae,width:be,height:me}=v.select,ot=v.scales[he].ori,Et=v.posToVal,er,Ze,Mt,Vr,br,nn=Z!=null&&ae(Z,he),mn=re!=null&&ue(re,Ie);nn&&qt?(ot==0?(er=Le,Ze=be):(er=Ae,Ze=me),Mt=C[Z],Vr=O(Et(er,he),Mt,$,0),br=O(Et(er+Ze,he),Mt,$,0),Io(En(Vr,br),jt(br-Vr))):Io(0,$),mn&&Qt?(ot==1?(er=Le,Ze=be):(er=Ae,Ze=me),Mt=C[re],Vr=L(Et(er,Ie),Mt,Y,0),br=L(Et(er+Ze,Ie),Mt,Y,0),ko(En(Vr,br),jt(br-Vr))):ko(0,Y)}else ac()}else{let Z=jt(up-ap),re=jt(cp-lp);if(z.ori==1){let Ie=Z;Z=re,re=Ie}qt=sr.x&&Z>=sr.dist,Qt=sr.y&&re>=sr.dist;let ae=sr.uni;ae!=null?qt&&Qt&&(qt=Z>=ae,Qt=re>=ae,!qt&&!Qt&&(re>Z?Qt=!0:qt=!0)):sr.x&&sr.y&&(qt||Qt)&&(qt=Qt=!0);let ue,he;qt&&(z.ori==0?(ue=bs,he=it):(ue=Ss,he=pt),Io(En(ue,he),jt(he-ue)),Qt||ko(0,Y)),Qt&&(z.ori==1?(ue=bs,he=it):(ue=Ss,he=pt),ko(En(ue,he),jt(he-ue)),qt||Io(0,$)),!qt&&!Qt&&(Io(0,0),ko(0,0))}if(sr._x=qt,sr._y=Qt,v==null){if(M){if(xp!=null){let[Z,re]=Bt.scales;Bt.values[0]=Z!=null?Dn(z.ori==0?it:pt,Z):null,Bt.values[1]=re!=null?Dn(z.ori==1?it:pt,re):null}Mo(Gc,n,it,pt,pe,ne,U)}if(Tn){let Z=M&&Bt.setSeries,re=dr.prox;Hi==null?Wn<=re&&zn(di,Is,!0,Z):Wn>re?zn(null,Is,!0,Z):di!=Hi&&zn(di,Is,!0,Z)}}Ve&&(q.idx=U,ic()),b!==!1&&Jt("setCursor")}let hi=null;Object.defineProperty(n,"rect",{get(){return hi==null&&Eo(!1),hi}});function Eo(v=!1){v?hi=null:(hi=p.getBoundingClientRect(),Jt("syncRect",hi))}function fp(v,b,M,U,B,$,Y){K._lock||ui&&v!=null&&v.movementX==0&&v.movementY==0||(sc(v,b,M,U,B,$,Y,!1,v!=null),v!=null?ji(null,!0,!0):ji(b,!0,!1))}function sc(v,b,M,U,B,$,Y,Z,re){if(hi==null&&Eo(!1),Br(v),v!=null)M=v.clientX-hi.left,U=v.clientY-hi.top;else{if(M<0||U<0){it=-10,pt=-10;return}let[ae,ue]=Bt.scales,he=b.cursor.sync,[Ie,He]=he.values,[Le,Ae]=he.scales,[be,me]=Bt.match,ot=b.axes[0].side%2==1,Et=z.ori==0?pe:ne,er=z.ori==1?pe:ne,Ze=ot?$:B,Mt=ot?B:$,Vr=ot?U:M,br=ot?M:U;if(Le!=null?M=be(ae,Le)?a(Ie,C[ae],Et,0):-10:M=Et*(Vr/Ze),Ae!=null?U=me(ue,Ae)?a(He,C[ue],er,0):-10:U=er*(br/Mt),z.ori==1){let nn=M;M=U,U=nn}}re&&(b==null||b.cursor.event.type==Gc)&&((M<=1||M>=pe-1)&&(M=qi(M,pe)),(U<=1||U>=ne-1)&&(U=qi(U,ne))),Z?(ap=M,lp=U,[bs,Ss]=K.move(n,M,U)):(it=M,pt=U)}const oc={width:0,height:0,left:0,top:0};function ac(){Ha(oc,!1)}let pp,gp,mp,yp;function vp(v,b,M,U,B,$,Y){ui=!0,qt=Qt=sr._x=sr._y=!1,sc(v,b,M,U,B,$,Y,!0,!1),v!=null&&(nt(Xc,gh,wp,!1),Mo(wm,n,bs,Ss,pe,ne,null));let{left:Z,top:re,width:ae,height:ue}=st;pp=Z,gp=re,mp=ae,yp=ue}function wp(v,b,M,U,B,$,Y){ui=sr._x=sr._y=!1,sc(v,b,M,U,B,$,Y,!1,!0);let{left:Z,top:re,width:ae,height:ue}=st,he=ae>0||ue>0,Ie=pp!=Z||gp!=re||mp!=ae||yp!=ue;if(he&&Ie&&Ha(st),sr.setScale&&he&&Ie){let He=Z,Le=ae,Ae=re,be=ue;if(z.ori==1&&(He=re,Le=ue,Ae=Z,be=ae),qt&&ci(I,Dn(He,I),Dn(He+Le,I)),Qt)for(let me in C){let ot=C[me];me!=I&&ot.from==null&&ot.min!=Qe&&ci(me,Dn(Ae+be,me),Dn(Ae,me))}ac()}else K.lock&&(K._lock=!K._lock,ji(b,!0,v!=null));v!=null&&(Cr(Xc,gh),Mo(Xc,n,it,pt,pe,ne,null))}function nb(v,b,M,U,B,$,Y){if(K._lock)return;Br(v);let Z=ui;if(ui){let re=!0,ae=!0,ue=10,he,Ie;z.ori==0?(he=qt,Ie=Qt):(he=Qt,Ie=qt),he&&Ie&&(re=it<=ue||it>=pe-ue,ae=pt<=ue||pt>=ne-ue),he&&re&&(it=it<bs?0:pe),Ie&&ae&&(pt=pt<Ss?0:ne),ji(null,!0,!0),ui=!1}it=-10,pt=-10,ee.fill(null),ji(null,!0,!0),Z&&(ui=Z)}function Cp(v,b,M,U,B,$,Y){K._lock||(Br(v),Hu(),ac(),v!=null&&Mo(Sm,n,it,pt,pe,ne,null))}function bp(){y.forEach(dU),Xt(n.width,n.height,!0)}ss(uu,Js,bp);const ks={};ks.mousedown=vp,ks.mousemove=fp,ks.mouseup=wp,ks.dblclick=Cp,ks.setSeries=(v,b,M,U)=>{let B=Bt.match[2];M=B(n,b,M),M!=-1&&zn(M,U,!0,!1)},ve&&(nt(wm,p,vp),nt(Gc,p,fp),nt(Cm,p,v=>{Br(v),Eo(!1)}),nt(bm,p,nb),nt(Sm,p,Cp),xh.add(n),n.syncRect=Eo);const ja=n.hooks=r.hooks||{};function Jt(v,b,M){ec?xo.push([v,b,M]):v in ja&&ja[v].forEach(U=>{U.call(null,n,b,M)})}(r.plugins||[]).forEach(v=>{for(let b in v.hooks)ja[b]=(ja[b]||[]).concat(v.hooks[b])});const Sp=(v,b,M)=>M,Bt=zt({key:null,setSeries:!1,filters:{pub:Bm,sub:Bm},scales:[I,g[1]?g[1].scale:null],match:[zm,zm,Sp],values:[null,null]},K.sync);Bt.match.length==2&&Bt.match.push(Sp),K.sync=Bt;const xp=Bt.key,lc=bC(xp);function Mo(v,b,M,U,B,$,Y){Bt.filters.pub(v,b,M,U,B,$,Y)&&lc.pub(v,b,M,U,B,$,Y)}lc.sub(n);function ib(v,b,M,U,B,$,Y){Bt.filters.sub(v,b,M,U,B,$,Y)&&ks[v](null,b,M,U,B,$,Y)}n.pub=ib;function sb(){lc.unsub(n),xh.delete(n),kt.clear(),vh(uu,Js,bp),u.remove(),Ce==null||Ce.remove(),Jt("destroy")}n.destroy=sb;function uc(){Jt("init",r,e),Jf(e||r.data,!1),V[I]?tc(I,V[I]):Hu(),ft=st.show&&(st.width>0||st.height>0),Tt=Ve=!0,Xt(r.width,r.height)}return g.forEach(Pt),y.forEach(FC),t?t instanceof HTMLElement?(t.appendChild(u),uc()):t(n,uc):uc(),n}yr.assign=zt;yr.fmtNum=Nf;yr.rangeNum=cu;yr.rangeLog=Ou;yr.rangeAsinh=_f;yr.orient=ps;yr.pxRatio=je;yr.join=rM;yr.fmtDate=Hf,yr.tzDate=fM;yr.sync=bC;{yr.addGap=KM,yr.clipGaps=_u;let r=yr.paths={points:MC};r.linear=AC,r.stepped=QM,r.bars=JM,r.spline=tU}function hU(r,e){const t=/^#([0-9a-fA-F]{6})([0-9a-fA-F]{2})?$/.exec(r.trim());return t?`#${t[1]}${e}`:r}function BC({data:r,seriesKeys:e,seriesLabels:t,colors:n,height:i=300,tickRate:s=60,windowSeconds:o=20,hoveredKey:a=null,onHoverKey:l}){const u=N.useRef(null),c=N.useRef(null),d=N.useRef(null),h=N.useMemo(()=>e.join("|"),[e]),f=N.useMemo(()=>{const w=Math.max(1,Math.round(o*s)),g=Math.max(0,r.length-w),y=r.slice(g),C=Math.max(0,w-y.length),x=new Array(w);for(let E=0;E<w;E++)x[E]=E;const I=e.map(()=>new Array(w).fill(0));for(let E=0;E<y.length;E++){const A=y[E],R=C+E;for(let F=0;F<e.length;F++){const z=e[F],P=Number(A[z]??0);I[F][R]=Number.isFinite(P)?P:0}}return{x,series:I,windowPoints:w}},[r,e,s,o]),p=N.useMemo(()=>[f.x,...f.series],[f]),m=N.useMemo(()=>{const w=typeof globalThis.devicePixelRatio=="number"?globalThis.devicePixelRatio:1,g=[{label:"t"},...e.map((y,C)=>{const x=n[C%n.length]??"#4fc1ff";return{label:t[y]??y,stroke:x,width:2,points:{show:!1}}})];return{width:800,height:i,pxAlign:0,pxRatio:w,padding:[10,10,10,10],scales:{x:{time:!1},y:{}},axes:[{stroke:"#555",grid:{stroke:"#222",width:1},size:0,values:(y,C)=>C.map(()=>"")},{stroke:"#555",grid:{stroke:"#222",width:1}}],series:g,legend:{show:!1},cursor:{drag:{x:!1,y:!1}},hooks:{setCursor:[y=>{var F;if(!l)return;const C=y.cursor.idx;if(C==null||C<0){d.current!==null&&(d.current=null,l(null));return}const x=y.cursor.top;if(x==null||!Number.isFinite(x)){d.current!==null&&(d.current=null,l(null));return}let I=null,E=Number.POSITIVE_INFINITY;for(let z=1;z<y.series.length;z++){const P=e[z-1],O=(F=y.data[z])==null?void 0:F[C];if(O==null||!Number.isFinite(O))continue;const L=y.valToPos(O,"y",!0),V=Math.abs(L-x);V<E&&(E=V,I=P)}const R=E<=12?I:null;d.current!==R&&(d.current=R,l(R))}]}}},[n,i,l,e,t]),S=N.useMemo(()=>e.map((w,g)=>{const y=n[g%n.length]??"#4fc1ff",C=a!=null&&a===w;return{stroke:a!=null&&a!==w?hU(y,"66"):y,width:C?3:2}}),[n,a,e]);return N.useEffect(()=>{var I;const w=u.current;if(!w)return;const g=()=>{l&&d.current!==null&&(d.current=null,l(null))};w.addEventListener("mouseleave",g),(I=c.current)==null||I.destroy(),c.current=null;const y=new yr(m,p,w);c.current=y;const C=new ResizeObserver(()=>{const E=w.getBoundingClientRect();y.setSize({width:Math.max(1,Math.floor(E.width)),height:i})});C.observe(w);const x=w.getBoundingClientRect();return y.setSize({width:Math.max(1,Math.floor(x.width)),height:i}),()=>{w.removeEventListener("mouseleave",g),C.disconnect(),y.destroy(),c.current=null}},[m,p,i,l,h]),N.useEffect(()=>{var w;(w=c.current)==null||w.setData(p)},[p]),N.useEffect(()=>{const w=c.current;if(w)for(let g=0;g<S.length;g++){const y=g+1,C=S[g],x=w.series[y];!x||!C||(x.stroke!==C.stroke||x.width!==C.width)&&w.setSeries(y,{stroke:C.stroke,width:C.width})}},[S]),k.jsx("div",{ref:u,style:{width:"100%",height:i}})}const Dr=(r,e)=>r===e?0:r<e?-1:1,ry=(r,e)=>r.localeCompare(e,void 0,{numeric:!0}),gl=r=>(r??"").trim();function fU({sortedTraffic:r,topTraffic:e,chartData:t,topKeys:n,keyToLabel:i,keyToColor:s,tickRate:o,hoveredTrafficKey:a,setHoveredTrafficKey:l}){const[u,c]=N.useState("bps"),[d,h]=N.useState("desc"),[f,p]=N.useState("bps"),[m,S]=N.useState("desc"),[w,g]=N.useState("bps"),[y,C]=N.useState("desc"),x=T=>{if(T===u){h(_=>_==="asc"?"desc":"asc");return}c(T),h(T==="name"?"asc":"desc")},I=T=>{if(T===w){C(_=>_==="asc"?"desc":"asc");return}g(T),C(T==="name"?"asc":"desc")},E=T=>{if(T===f){S(_=>_==="asc"?"desc":"asc");return}p(T),S(T==="name"?"asc":"desc")},A=(T,_,j)=>{const G=j==="asc"?1:-1,ee=[...T];return ee.sort((q,K)=>{let oe=0;switch(_){case"id":oe=Dr(q.id,K.id);break;case"name":{const ve=gl(q.name),ge=gl(K.name);oe=ry(ve,ge),oe===0&&(oe=Dr(q.id,K.id));break}case"encoding":{const ve=gl(q.encoding),ge=gl(K.encoding);oe=ry(ve,ge),oe===0&&(oe=Dr(q.id,K.id));break}case"bps":oe=Dr(q.bps,K.bps),oe===0&&(oe=Dr(q.total,K.total));break;case"total":oe=Dr(q.total,K.total),oe===0&&(oe=Dr(q.bps,K.bps));break;case"size":{const ve=q.size.x*q.size.y,ge=K.size.x*K.size.y;oe=Dr(ve,ge),oe===0&&(oe=Dr(q.id,K.id));break}case"position":{oe=Dr(q.position.x,K.position.x),oe===0&&(oe=Dr(q.position.y,K.position.y)),oe===0&&(oe=Dr(q.id,K.id));break}case"zIndex":oe=Dr(q.zIndex,K.zIndex),oe===0&&(oe=Dr(q.id,K.id));break}return oe*G}),ee},R=N.useMemo(()=>r.filter(T=>T.key.startsWith("layer-")),[r]),F=N.useMemo(()=>r.filter(T=>T.key.startsWith("misc-")),[r]),z=N.useMemo(()=>r.filter(T=>T.key.startsWith("display-")),[r]),P=N.useMemo(()=>A(R,u,d),[R,d,u]),O=N.useMemo(()=>A(F,w,y),[F,y,w]),L=N.useMemo(()=>A(z,f,m),[z,m,f]),V={userSelect:"none",cursor:"pointer"},X=(T,_,j)=>T!==_?"":j==="asc"?" ▲":" ▼";return k.jsxs("div",{style:{position:"absolute",inset:0,display:"flex",flexDirection:"column",gap:12,padding:12,overflow:"auto",background:"#1b1b1b",color:"#cccccc"},children:[k.jsx("div",{style:{fontSize:13,color:"#e0e0e0",fontWeight:600},children:"Bandwidth"}),R.length===0&&F.length===0&&k.jsx("div",{style:{color:"#888",fontSize:12},children:"No bandwidth data yet. Move the client or send data to see traffic."}),R.length>0&&e.length>0&&k.jsxs("div",{style:{width:"100%",height:300,border:"1px solid #333",background:"#111",padding:"8px 12px 12px",boxSizing:"border-box"},children:[k.jsx("div",{style:{marginBottom:8,color:"#aaa",fontSize:12},children:"Lines — per-layer bandwidth (B/s, last samples)"}),k.jsx(BC,{data:t,seriesKeys:n,seriesLabels:i,colors:n.map(T=>s[T]??"#4fc1ff"),height:260,tickRate:o,windowSeconds:60,hoveredKey:a,onHoverKey:l})]}),R.length>0&&k.jsxs("div",{style:{border:"1px solid #333",background:"#111",padding:"10px 12px",display:"flex",flexDirection:"column",gap:6},children:[k.jsx("div",{style:{color:"#aaa",fontSize:12,marginBottom:2},children:"Layers"}),k.jsxs("div",{style:{display:"grid",gridTemplateColumns:"70px 1.1fr 0.55fr 0.7fr 0.7fr 0.8fr 0.9fr 0.6fr",gap:6,color:"#aaa",fontSize:12},children:[k.jsxs("div",{style:V,onClick:()=>x("id"),title:"Sort by ID",children:["ID",X("id",u,d)]}),k.jsxs("div",{style:V,onClick:()=>x("name"),title:"Sort by name",children:["Name",X("name",u,d)]}),k.jsxs("div",{style:V,onClick:()=>x("encoding"),title:"Sort by encoding",children:["Encoding",X("encoding",u,d)]}),k.jsxs("div",{style:{...V,textAlign:"right"},onClick:()=>x("bps"),title:"Sort by Network/s",children:["Network/s",X("bps",u,d)]}),k.jsxs("div",{style:{...V,textAlign:"right"},onClick:()=>x("total"),title:"Sort by Network",children:["Network",X("total",u,d)]}),k.jsxs("div",{style:{...V,textAlign:"right"},onClick:()=>x("size"),title:"Sort by size",children:["Size",X("size",u,d)]}),k.jsxs("div",{style:{...V,textAlign:"right"},onClick:()=>x("position"),title:"Sort by position",children:["Position",X("position",u,d)]}),k.jsxs("div",{style:{...V,textAlign:"right"},onClick:()=>x("zIndex"),title:"Sort by zIndex",children:["zIndex",X("zIndex",u,d)]})]}),P.map(T=>k.jsxs("div",{onMouseEnter:()=>l(T.key),onMouseLeave:()=>l(null),style:{display:"grid",gridTemplateColumns:"70px 1.1fr 0.55fr 0.7fr 0.7fr 0.8fr 0.9fr 0.6fr",gap:6,fontSize:12,color:a===T.key?"#fff":"#ccc",borderTop:"1px solid #222",paddingTop:4,background:a===T.key?"#1a1a1a":"transparent",outline:a===T.key?"1px solid #2a2a2a":"none",cursor:"default"},children:[k.jsx("div",{style:{color:"#ccc"},children:T.id}),k.jsxs("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[k.jsx("span",{style:{display:"inline-block",width:10,height:10,borderRadius:2,marginRight:8,verticalAlign:"middle",background:s[T.key]??"#666",boxShadow:a===T.key?`0 0 0 1px #000, 0 0 0 2px ${s[T.key]??"#666"}`:"0 0 0 1px #000"}}),(()=>{var j;const _=((j=T.name)==null?void 0:j.trim())||`Layer ${T.id}`;return T.id===255?`${_} (debug)`:_})()]}),k.jsx("div",{style:{color:"#bbb"},children:T.encoding??""}),k.jsxs("div",{style:{textAlign:"right"},children:[Kr(T.bps),"/s"]}),k.jsx("div",{style:{textAlign:"right"},children:Kr(T.total)}),k.jsxs("div",{style:{textAlign:"right",color:"#999"},children:[T.size.x,"×",T.size.y]}),k.jsxs("div",{style:{textAlign:"right",color:"#999"},children:[T.position.x,"/",T.position.y]}),k.jsx("div",{style:{textAlign:"right",color:"#999"},children:T.zIndex})]},T.key))]}),z.length>0&&k.jsxs("div",{style:{border:"1px solid #333",background:"#111",padding:"10px 12px",display:"flex",flexDirection:"column",gap:6},children:[k.jsx("div",{style:{color:"#aaa",fontSize:12,marginBottom:2},children:"Displays"}),k.jsxs("div",{style:{display:"grid",gridTemplateColumns:"70px 1.2fr 0.7fr 0.7fr 0.8fr 0.9fr 0.6fr",gap:6,color:"#aaa",fontSize:12},children:[k.jsxs("div",{style:V,onClick:()=>E("id"),title:"Sort by ID",children:["ID",X("id",f,m)]}),k.jsxs("div",{style:V,onClick:()=>E("name"),title:"Sort by name",children:["Name",X("name",f,m)]}),k.jsxs("div",{style:{...V,textAlign:"right"},onClick:()=>E("bps"),title:"Sort by Network/s",children:["Network/s",X("bps",f,m)]}),k.jsxs("div",{style:{...V,textAlign:"right"},onClick:()=>E("total"),title:"Sort by Network",children:["Network",X("total",f,m)]}),k.jsxs("div",{style:{...V,textAlign:"right"},onClick:()=>E("size"),title:"Sort by size",children:["Size",X("size",f,m)]}),k.jsxs("div",{style:{...V,textAlign:"right"},onClick:()=>E("position"),title:"Sort by position",children:["Position",X("position",f,m)]}),k.jsx("div",{style:{textAlign:"right",opacity:.6},children:"zIndex"})]}),L.map(T=>{var _;return k.jsxs("div",{onMouseEnter:()=>l(T.key),onMouseLeave:()=>l(null),style:{display:"grid",gridTemplateColumns:"70px 1.2fr 0.7fr 0.7fr 0.8fr 0.9fr 0.6fr",gap:6,fontSize:12,color:a===T.key?"#fff":"#ccc",borderTop:"1px solid #222",paddingTop:4,background:a===T.key?"#1a1a1a":"transparent",outline:a===T.key?"1px solid #2a2a2a":"none",cursor:"default"},children:[k.jsx("div",{style:{color:"#ccc"},children:T.id}),k.jsxs("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[k.jsx("span",{style:{display:"inline-block",width:10,height:10,borderRadius:2,marginRight:8,verticalAlign:"middle",background:s[T.key]??"#666",boxShadow:a===T.key?`0 0 0 1px #000, 0 0 0 2px ${s[T.key]??"#666"}`:"0 0 0 1px #000"}}),((_=T.name)==null?void 0:_.trim())||`Display ${T.id}`]}),k.jsxs("div",{style:{textAlign:"right"},children:[Kr(T.bps),"/s"]}),k.jsx("div",{style:{textAlign:"right"},children:Kr(T.total)}),k.jsxs("div",{style:{textAlign:"right",color:"#999"},children:[T.size.x,"×",T.size.y]}),k.jsxs("div",{style:{textAlign:"right",color:"#999"},children:[T.position.x,"/",T.position.y]}),k.jsx("div",{style:{textAlign:"right",color:"#666"},children:"—"})]},T.key)})]}),F.length>0&&k.jsxs("div",{style:{border:"1px solid #333",background:"#111",padding:"10px 12px",display:"flex",flexDirection:"column",gap:6},children:[k.jsx("div",{style:{color:"#aaa",fontSize:12,marginBottom:2},children:"Updates (non-layer)"}),k.jsxs("div",{style:{display:"grid",gridTemplateColumns:"70px 1.2fr 0.7fr 0.7fr 0.8fr 0.9fr 0.6fr",gap:6,color:"#aaa",fontSize:12},children:[k.jsxs("div",{style:V,onClick:()=>I("id"),title:"Sort by ID",children:["ID",X("id",w,y)]}),k.jsxs("div",{style:V,onClick:()=>I("name"),title:"Sort by name",children:["Name",X("name",w,y)]}),k.jsxs("div",{style:{...V,textAlign:"right"},onClick:()=>I("bps"),title:"Sort by Network/s",children:["Network/s",X("bps",w,y)]}),k.jsxs("div",{style:{...V,textAlign:"right"},onClick:()=>I("total"),title:"Sort by Network",children:["Network",X("total",w,y)]}),k.jsx("div",{style:{textAlign:"right",opacity:.6},children:"Size"}),k.jsx("div",{style:{textAlign:"right",opacity:.6},children:"Position"}),k.jsx("div",{style:{textAlign:"right",opacity:.6},children:"zIndex"})]}),O.map(T=>k.jsxs("div",{onMouseEnter:()=>l(T.key),onMouseLeave:()=>l(null),style:{display:"grid",gridTemplateColumns:"70px 1.2fr 0.7fr 0.7fr 0.8fr 0.9fr 0.6fr",gap:6,fontSize:12,color:a===T.key?"#fff":"#ccc",borderTop:"1px solid #222",paddingTop:4,background:a===T.key?"#1a1a1a":"transparent",outline:a===T.key?"1px solid #2a2a2a":"none",cursor:"default"},children:[k.jsx("div",{style:{color:"#ccc"},children:T.id}),k.jsxs("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[k.jsx("span",{style:{display:"inline-block",width:10,height:10,borderRadius:2,marginRight:8,verticalAlign:"middle",background:s[T.key]??"#666",boxShadow:a===T.key?`0 0 0 1px #000, 0 0 0 2px ${s[T.key]??"#666"}`:"0 0 0 1px #000"}}),T.name??"—"]}),k.jsxs("div",{style:{textAlign:"right"},children:[Kr(T.bps),"/s"]}),k.jsx("div",{style:{textAlign:"right"},children:Kr(T.total)}),k.jsx("div",{style:{textAlign:"right",color:"#666"},children:"—"}),k.jsx("div",{style:{textAlign:"right",color:"#666"},children:"—"}),k.jsx("div",{style:{textAlign:"right",color:"#666"},children:"—"})]},T.key))]})]})}const tr=65536,Jc=.005,ed=32;function pU({layers:r,displays:e=[],width:t,height:n,hoveredLayerId:i=null,selectedLayerIds:s=null,hoveredDisplayId:o=null,selectedDisplayId:a=null,focusRect:l=null,focusKey:u="",onSelectLayer:c,onSelectDisplay:d,onToolRectCommit:h}){const f=N.useRef(null),[p,m]=N.useState(1),[S,w]=N.useState({x:0,y:0}),g=N.useRef(!1),y=N.useRef({x:0,y:0}),C=N.useRef(""),[x,I]=N.useState(!1),[E,A]=N.useState(null),[R,F]=N.useState(null),[z,P]=N.useState("none"),[O,L]=N.useState(null),V=N.useRef(null),[X,T]=N.useState(!1),_=N.useRef(!1),j=N.useRef(!1),G=N.useCallback((Q,W,le)=>{const ye=t/le,de=n/le,Ue=ye*.5,Ee=de*.5,Me=Math.max(0,tr-ye)+Ue,Ne=Math.max(0,tr-de)+Ee,we=-Ue,Oe=-Ee;return{x:Math.max(we,Math.min(Me,Q)),y:Math.max(Oe,Math.min(Ne,W))}},[t,n]),ee=N.useCallback(()=>{const Q=tr*p,W=tr*p,le=Q<t?(t-Q)/2:0,ye=W<n?(n-W)/2:0;return{toScreenX:Ne=>(Ne-S.x)*p+le,toScreenY:Ne=>(Ne-S.y)*p+ye,toWorldX:Ne=>(Ne-le)/p+S.x,toWorldY:Ne=>(Ne-ye)/p+S.y}},[n,S.x,S.y,p,t]),q=N.useCallback((Q,W)=>{let le=null;for(let ye=0;ye<r.length;ye++){const de=r[ye];if(Q<de.x||Q>de.x+de.width||W<de.y||W>de.y+de.height)continue;const Ue=de.zIndex??0;(!le||Ue>le.z)&&(le={id:de.id,z:Ue})}if(le)return{kind:"layer",id:le.id,zIndex:le.z};for(let ye=e.length-1;ye>=0;ye--){const de=e[ye];if(Q>=de.x&&Q<=de.x+de.width&&W>=de.y&&W<=de.y+de.height)return{kind:"display",id:de.id}}return null},[e,r]),K=N.useCallback((Q,W)=>{const le=[];for(let ye=0;ye<r.length;ye++){const de=r[ye];Q<de.x||Q>de.x+de.width||W<de.y||W>de.y+de.height||le.push({id:de.id,zIndex:de.zIndex??0,name:de.name})}return le.sort((ye,de)=>de.zIndex-ye.zIndex),le},[r]);N.useEffect(()=>{const Q=f.current;if(!Q)return;const W=Q.getContext("2d");if(!W)return;W.clearRect(0,0,t,n),W.fillStyle="#0a0e14",W.fillRect(0,0,t,n);const le=tr*p,ye=tr*p,de=le<t?(t-le)/2:0,Ue=ye<n?(n-ye)/2:0,Ee=we=>(we-S.x)*p+de,Me=we=>(we-S.y)*p+Ue;{const we=Ee(0),Oe=Ee(tr),Tt=Me(0),ft=Me(tr),Ve=Math.max(0,we),Xt=Math.min(t,Oe),Lt=Math.max(0,Tt),ai=Math.min(n,ft);if(!(Xt<=Ve||ai<=Lt)){const Li=[{step:1,alpha:.06,lineWidth:1,minGapPx:8},{step:16,alpha:.1,lineWidth:1,minGapPx:10},{step:256,alpha:.16,lineWidth:1.25,minGapPx:12},{step:4096,alpha:.22,lineWidth:1.5,minGapPx:14}];W.save(),W.beginPath(),W.rect(Ve,Lt,Xt-Ve,ai-Lt),W.clip();let _i=!1;for(const Fe of Li){if(Fe.step*p<Fe.minGapPx)continue;_i=!0,W.strokeStyle=`rgba(255,255,255,${Fe.alpha})`,W.lineWidth=Fe.lineWidth;const Br=bt=>(bt-de)/p+S.x,Ct=bt=>(bt-Ue)/p+S.y,dr=Math.max(0,Br(0)),Tn=Math.min(tr,Br(t)),Rn=Math.max(0,Ct(0)),hr=Math.min(tr,Ct(n)),Pn=Math.floor(dr/Fe.step)*Fe.step,Bn=Math.ceil(Tn/Fe.step)*Fe.step,gs=Math.floor(Rn/Fe.step)*Fe.step,Pt=Math.ceil(hr/Fe.step)*Fe.step;W.beginPath();for(let bt=Pn;bt<=Bn;bt+=Fe.step){if(bt<0||bt>tr)continue;const Ni=Ee(bt);W.moveTo(Ni,Lt),W.lineTo(Ni,ai)}for(let bt=gs;bt<=Pt;bt+=Fe.step){if(bt<0||bt>tr)continue;const Ni=Me(bt);W.moveTo(Ve,Ni),W.lineTo(Xt,Ni)}W.stroke()}if(!_i){const Fe=Li[Li.length-1];W.strokeStyle=`rgba(255,255,255,${Fe.alpha})`,W.lineWidth=Fe.lineWidth;const $i=Pt=>(Pt-de)/p+S.x,Br=Pt=>(Pt-Ue)/p+S.y,Ct=Math.max(0,$i(0)),dr=Math.min(tr,$i(t)),Tn=Math.max(0,Br(0)),Rn=Math.min(tr,Br(n)),hr=Math.floor(Ct/Fe.step)*Fe.step,Pn=Math.ceil(dr/Fe.step)*Fe.step,Bn=Math.floor(Tn/Fe.step)*Fe.step,gs=Math.ceil(Rn/Fe.step)*Fe.step;W.beginPath();for(let Pt=hr;Pt<=Pn;Pt+=Fe.step){if(Pt<0||Pt>tr)continue;const bt=Ee(Pt);W.moveTo(bt,Lt),W.lineTo(bt,ai)}for(let Pt=Bn;Pt<=gs;Pt+=Fe.step){if(Pt<0||Pt>tr)continue;const bt=Me(Pt);W.moveTo(Ve,bt),W.lineTo(Xt,bt)}W.stroke()}W.restore()}}const Ne=[...r].sort((we,Oe)=>(we.zIndex??0)-(Oe.zIndex??0));for(const we of Ne){const Oe=s!=null&&s.includes(we.id),Tt=i!=null&&we.id===i,ft=Ee(we.x),Ve=Me(we.y),Xt=we.width*p,Lt=we.height*p;if(ft+Xt<0||Ve+Lt<0||ft>t||Ve>n)continue;const ai=we.zIndex??0,Li=we.color??(Oe?"rgba(43, 140, 255, 0.60)":Tt?"rgba(102, 217, 239, 0.40)":"rgba(43, 140, 255, 0.42)");if(W.fillStyle=Li,W.fillRect(ft,Ve,Math.max(Xt,1),Math.max(Lt,1)),W.strokeStyle=Oe?"#66d9ef":Tt?"rgba(102, 217, 239, 0.70)":"rgba(255,255,255,0.30)",W.lineWidth=Oe?2:1,W.strokeRect(ft,Ve,Math.max(Xt,1),Math.max(Lt,1)),p>=3&&Xt>=40&&Lt>=16){W.font="11px monospace",W.textBaseline="top";const _i=`z=${ai}`,Fe=4,$i=3,Ct=W.measureText(_i).width+Fe*2,dr=14;W.fillStyle="rgba(0,0,0,0.55)",W.fillRect(ft+3,Ve+3,Ct,dr),W.fillStyle="rgba(255,255,255,0.85)",W.fillText(_i,ft+3+Fe,Ve+3+$i)}}for(const we of e){const Oe=a!=null&&we.id===a,Tt=o!=null&&we.id===o,ft=Ee(we.x),Ve=Me(we.y),Xt=we.width*p,Lt=we.height*p;ft+Xt<0||Ve+Lt<0||ft>t||Ve>n||(W.strokeStyle=Oe?"rgba(255, 120, 120, 1)":Tt?"rgba(255, 120, 120, 0.8)":"rgba(255, 80, 80, 0.9)",W.lineWidth=Oe?3:2,W.strokeRect(ft,Ve,Math.max(Xt,1),Math.max(Lt,1)))}if(O){const we=Ee(O.x),Oe=Me(O.y),Tt=O.width*p,ft=O.height*p;W.strokeStyle="rgba(43, 140, 255, 1)",W.lineWidth=2,W.setLineDash([6,4]),W.strokeRect(we,Oe,Math.max(Tt,1),Math.max(ft,1)),W.setLineDash([])}},[r,e,t,n,p,S,i,s,o,a,O]);const oe=N.useCallback((Q,W)=>{var we;const le=(we=f.current)==null?void 0:we.getBoundingClientRect();if(!le)return null;const ye=Q-le.left,de=W-le.top,{toWorldX:Ue,toWorldY:Ee}=ee(),Me=Ue(ye),Ne=Ee(de);return{x:Me,y:Ne}},[ee]),ve=N.useCallback((Q,W)=>{const le=Math.floor(Math.min(Q.x,W.x)),ye=Math.floor(Math.min(Q.y,W.y)),de=Math.ceil(Math.max(Q.x,W.x)),Ue=Math.ceil(Math.max(Q.y,W.y));return{x:le,y:ye,width:Math.max(1,de-le),height:Math.max(1,Ue-ye)}},[]);N.useEffect(()=>{if(!l){C.current="";return}const Q=`${u}-${l.id}-${l.x}-${l.y}-${l.width}-${l.height}-${t}-${n}`;if(Q===C.current)return;if(j.current){j.current=!1,C.current=Q;return}C.current=Q;const W=1.25,le=Math.max(Jc,Math.min(ed,Math.min(t/(l.width*W),n/(l.height*W)))),ye=t/le,de=n/le,Ue=l.x+l.width/2,Ee=l.y+l.height/2,Me=G(Ue-ye/2,Ee-de/2,le);m(le),w(Me)},[l,u,t,n,G]);const ge=N.useCallback(Q=>{var Lt;const W=(Lt=f.current)==null?void 0:Lt.getBoundingClientRect();if(!W)return;Q.preventDefault();const le=Q.clientX-W.left,ye=Q.clientY-W.top,{toWorldX:de,toWorldY:Ue}=ee(),Ee=de(le),Me=Ue(ye),Ne=Q.deltaY<0?1.15:1/1.15,we=Math.max(Jc,Math.min(ed,p*Ne)),Oe=tr*we,Tt=tr*we,ft=Oe<t?(t-Oe)/2:0,Ve=Tt<n?(n-Tt)/2:0,Xt=G(Ee-(le-ft)/we,Me-(ye-Ve)/we,we);m(we),w(Xt)},[G,ee,n,S,p,t]);N.useEffect(()=>{const Q=f.current;if(!Q)return;const W=le=>ge(le);return Q.addEventListener("wheel",W,{passive:!1}),()=>Q.removeEventListener("wheel",W)},[ge]);const Ce=N.useCallback(Q=>{g.current=!0,I(!0),y.current={x:Q.clientX,y:Q.clientY}},[]),ct=N.useCallback(()=>{g.current=!1,I(!1)},[]),dt=N.useCallback(()=>{g.current=!1,I(!1),A(null)},[]),xe=N.useCallback(Q=>{const W=oe(Q.clientX,Q.clientY);if(!W||z!=="rect"||!h)return;Q.preventDefault(),Q.stopPropagation(),_.current=!0;const le={x:Math.floor(W.x),y:Math.floor(W.y)};V.current={startWorld:le,moved:!1},T(!0),L({x:le.x,y:le.y,width:1,height:1})},[z,oe,h]),et=N.useCallback(Q=>{if(!V.current)return;const W=oe(Q.clientX,Q.clientY);if(!W)return;const le=ve(V.current.startWorld,W);if(!V.current.moved){const ye=Math.abs(W.x-V.current.startWorld.x),de=Math.abs(W.y-V.current.startWorld.y);(ye>0||de>0)&&(V.current.moved=!0)}L(le)},[oe,ve]),Ke=N.useCallback(()=>{!V.current||!O||(_.current=!0,h==null||h(O),j.current=!0,V.current=null,L(null),T(!1),P("none"))},[O,h]),qe=N.useCallback(Q=>{if(V.current){if(Q.preventDefault(),Q.stopPropagation(),!V.current.moved){_.current=!0,V.current=null,L(null),T(!1),P("none");return}Ke()}},[Ke]);N.useEffect(()=>{if(!X)return;const Q=le=>{et(le)},W=le=>{qe(le)};return window.addEventListener("mousemove",Q,!0),window.addEventListener("mouseup",W,!0),()=>{window.removeEventListener("mousemove",Q,!0),window.removeEventListener("mouseup",W,!0)}},[X,et,qe]),N.useEffect(()=>{if(!V.current)return;const Q=W=>{W.key==="Enter"&&Ke()};return window.addEventListener("keydown",Q),()=>window.removeEventListener("keydown",Q)},[Ke]);const At=N.useCallback(Q=>{var we;if(V.current){et(Q);return}if(g.current){const Oe=Q.clientX-y.current.x,Tt=Q.clientY-y.current.y;y.current={x:Q.clientX,y:Q.clientY},w(ft=>G(ft.x-Oe/p,ft.y-Tt/p,p));return}const W=(we=f.current)==null?void 0:we.getBoundingClientRect();if(!W)return;const le=Q.clientX-W.left,ye=Q.clientY-W.top,{toWorldX:de,toWorldY:Ue}=ee(),Ee=Math.floor(de(le)),Me=Math.floor(Ue(ye)),Ne=q(Ee,Me);if(!Ne){A({kind:"layer",id:-1,world:{x:Ee,y:Me},screen:{x:le,y:ye}});return}A({kind:Ne.kind,id:Ne.id,world:{x:Ee,y:Me},screen:{x:le,y:ye}})},[G,ee,q,p]),wt=N.useCallback(Q=>{var Oe;if(_.current){_.current=!1;return}if(z==="rect"||V.current||x)return;const W=(Oe=f.current)==null?void 0:Oe.getBoundingClientRect();if(!W)return;const le=Q.clientX-W.left,ye=Q.clientY-W.top,{toWorldX:de,toWorldY:Ue}=ee(),Ee=Math.floor(de(le)),Me=Math.floor(Ue(ye)),Ne=K(Ee,Me);if(Ne.length>=2){F({open:!0,anchorScreen:{x:le,y:ye},world:{x:Ee,y:Me},layers:Ne});return}const we=q(Ee,Me);we&&(we.kind==="layer"&&(c==null||c(we.id,{metaKey:Q.metaKey,ctrlKey:Q.ctrlKey})),we.kind==="display"&&(d==null||d(we.id)))},[z,ee,q,K,x,d,c]);N.useEffect(()=>{const Q=W=>{W.key==="Escape"&&F(null)};return window.addEventListener("keydown",Q),()=>window.removeEventListener("keydown",Q)},[]);const Ft=N.useCallback(()=>{m(1),w(G(0,0,1))},[G]),cr=N.useCallback(Q=>{var Oe;const W=(Oe=f.current)==null?void 0:Oe.getBoundingClientRect();if(!W)return;const le=W.width/2,ye=W.height/2,{toWorldX:de,toWorldY:Ue}=ee(),Ee=de(le),Me=Ue(ye),Ne=Math.max(Jc,Math.min(ed,p*Q)),we=G(Ee-le/Ne,Me-ye/Ne,Ne);m(Ne),w(we)},[G,ee,p]),tt=E&&E.id!==-1?E:null,kt=n<520?6:10,nt=Math.max(40,n-kt*2),Cr=88,Se=42,Re=nt<150,pe=nt<240,ne=nt<200,$e=Math.min(1,Math.max(.7,nt/(Re?64:Cr))),ht=Math.min(1,Math.max(.7,nt/Se));return k.jsxs("div",{style:{position:"absolute",inset:0},children:[k.jsx("canvas",{ref:f,width:t,height:n,style:{display:"block",cursor:z==="rect"?(V.current,"crosshair"):g.current?"grabbing":"grab"},onMouseDown:Q=>{if(z==="rect"&&h){xe(Q);return}Ce(Q)},onMouseMove:At,onMouseUp:Q=>{if(V.current){qe(Q);return}ct()},onMouseLeave:dt,onClick:wt}),k.jsxs("div",{style:{position:"absolute",right:kt,bottom:pe?void 0:kt,top:pe?kt:void 0,display:"flex",flexDirection:Re?"row":"column",alignItems:"center",gap:6,padding:6,background:"rgba(20, 22, 26, 0.85)",border:"1px solid rgba(255,255,255,0.14)",borderRadius:10,boxShadow:"0 10px 26px rgba(0,0,0,0.45)",pointerEvents:"auto",transform:$e===1?void 0:`scale(${$e})`,transformOrigin:pe?"top right":"bottom right",maxWidth:`calc(100% - ${kt*2}px)`},onMouseDown:Q=>Q.stopPropagation(),children:[k.jsx("button",{onClick:()=>{const Q=z==="rect"?"none":"rect";V.current=null,T(!1),P(Q)},style:{width:34,height:34,borderRadius:8,border:z==="rect"?"1px solid rgba(79, 193, 255, 0.9)":"1px solid rgba(255,255,255,0.18)",background:z==="rect"?"rgba(14, 99, 156, 0.7)":"rgba(255,255,255,0.06)",color:"#e6e6e6",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",padding:0},title:z==="rect"?"Rectangle tool (active)":"Rectangle tool",children:k.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:k.jsx("rect",{x:"5",y:"7",width:"14",height:"10",rx:"1"})})}),k.jsx("button",{onClick:()=>{V.current=null,T(!1),P("none")},style:{width:34,height:34,borderRadius:8,border:"1px solid rgba(255,255,255,0.18)",background:z==="none"?"rgba(255,255,255,0.10)":"rgba(255,255,255,0.06)",color:"#e6e6e6",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",padding:0},title:"Drag/Pan",children:"↔"})]}),(R==null?void 0:R.open)&&R.layers.length>=2&&k.jsxs("div",{style:{position:"absolute",left:Math.min(t-220,R.anchorScreen.x+12),top:Math.min(n-260,R.anchorScreen.y-12),width:210,padding:8,background:"rgba(10, 12, 16, 0.94)",border:"1px solid rgba(255,255,255,0.14)",borderRadius:10,boxShadow:"0 10px 30px rgba(0,0,0,0.55)",color:"#e6e6e6",fontSize:12},children:[k.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[k.jsx("div",{style:{fontWeight:700},children:"Stack"}),k.jsx("button",{onClick:()=>F(null),style:{...ml,padding:"2px 6px",borderRadius:8},title:"Close",children:"✕"})]}),k.jsxs("div",{style:{color:"#9aa7b2",marginTop:4},children:["World: ",R.world.x.toFixed(0),",",R.world.y.toFixed(0)]}),k.jsx("div",{style:{marginTop:8,display:"flex",flexDirection:"column",gap:6,maxHeight:220,overflow:"auto",paddingRight:2},children:R.layers.map((Q,W)=>{var le;return k.jsx("button",{onClick:ye=>{c==null||c(Q.id,{metaKey:ye.metaKey,ctrlKey:ye.ctrlKey}),F(null)},style:{textAlign:"left",width:"100%",background:"rgba(255,255,255,0.04)",border:"1px solid rgba(255,255,255,0.10)",borderRadius:10,padding:"8px 10px",cursor:"pointer",color:"#e6e6e6",position:"relative"},title:"Select layer",children:k.jsxs("div",{style:{fontWeight:650},children:[(le=Q.name)!=null&&le.trim()?Q.name:`Layer ${Q.id}`," ",k.jsxs("span",{style:{color:"#9aa7b2",fontWeight:500},children:["z=",Q.zIndex]}),W===0&&k.jsx("span",{style:{marginLeft:6,color:"#66d9ef",fontWeight:650},children:"top"})]})},Q.id)})})]}),k.jsxs("div",{style:{position:"absolute",top:10,left:10,display:"flex",gap:6,padding:6,background:"rgba(15, 18, 24, 0.85)",border:"1px solid rgba(255,255,255,0.12)",borderRadius:8,backdropFilter:"blur(6px)",fontSize:12,color:"#cfcfcf"},children:[k.jsx("button",{onClick:()=>cr(1.15),style:ml,title:"Zoom in",children:"+"}),k.jsx("button",{onClick:()=>cr(1/1.15),style:ml,title:"Zoom out",children:"−"}),k.jsx("button",{onClick:Ft,style:ml,title:"Reset view",children:"Reset"})]}),k.jsxs("div",{style:{position:"absolute",left:kt,bottom:ne?void 0:kt,top:ne?kt:void 0,padding:"6px 8px",background:"rgba(15, 18, 24, 0.75)",border:"1px solid rgba(255,255,255,0.10)",borderRadius:8,backdropFilter:"blur(6px)",fontSize:12,color:"#cfcfcf",transform:ht===1?void 0:`scale(${ht})`,transformOrigin:ne?"top left":"bottom left",maxWidth:`calc(100% - ${kt*2}px)`,overflow:"hidden",whiteSpace:"nowrap"},children:[k.jsx("span",{style:{color:"#9aa7b2"},children:"Zoom:"})," ",p.toFixed(3),"x"," ",k.jsx("span",{style:{color:"#9aa7b2"},children:"| Offset:"})," (",S.x.toFixed(0),","," ",S.y.toFixed(0),")",E&&k.jsxs(k.Fragment,{children:[k.jsx("span",{style:{color:"#9aa7b2"},children:"| Mouse:"})," (",E.world.x.toFixed(0),",",E.world.y.toFixed(0),")"]})]}),tt&&k.jsxs("div",{style:{position:"absolute",left:Math.min(t-260,tt.screen.x+12),top:Math.min(n-80,tt.screen.y+12),width:240,padding:"8px 10px",background:"rgba(10, 12, 16, 0.92)",border:"1px solid rgba(255,255,255,0.14)",borderRadius:8,fontSize:12,color:"#e6e6e6",pointerEvents:"none"},children:[k.jsx("div",{style:{fontWeight:600,marginBottom:4},children:tt.kind==="layer"?`Layer ${tt.id}`:`Display ${tt.id}`}),tt.kind==="layer"&&typeof tt.zIndex=="number"&&k.jsxs("div",{style:{color:"#b7c0c8"},children:["zIndex: ",tt.zIndex]}),k.jsxs("div",{style:{color:"#b7c0c8"},children:["World: ",tt.world.x.toFixed(0),",",tt.world.y.toFixed(0)]}),k.jsxs("div",{style:{color:"#b7c0c8"},children:["Screen: ",tt.screen.x.toFixed(0),",",tt.screen.y.toFixed(0)]})]})]})}const ml={background:"rgba(255,255,255,0.06)",border:"1px solid rgba(255,255,255,0.14)",color:"#ddd",borderRadius:6,padding:"4px 8px",cursor:"pointer",lineHeight:1};var zC={},Zf={},qf={},Co={};Object.defineProperty(Co,"__esModule",{value:!0});Co.Direction=void 0;var ny;(function(r){r.Right="to right",r.Left="to left",r.Down="to bottom",r.Up="to top"})(ny||(Co.Direction=ny={}));(function(r){var e=Nr&&Nr.__spreadArray||function(P,O,L){if(L||arguments.length===2)for(var V=0,X=O.length,T;V<X;V++)(T||!(V in O))&&(T||(T=Array.prototype.slice.call(O,0,V)),T[V]=O[V]);return P.concat(T||Array.prototype.slice.call(O))};Object.defineProperty(r,"__esModule",{value:!0}),r.isIOS=r.useThumbOverlap=r.assertUnreachable=r.voidFn=r.getTrackBackground=r.replaceAt=r.schd=r.translate=r.getClosestThumbIndex=r.translateThumbs=r.getPaddingAndBorder=r.getMargin=r.checkInitialOverlap=r.checkValuesAgainstBoundaries=r.checkBoundaries=r.isVertical=r.relativeValue=r.normalizeValue=r.isStepDivisible=r.isTouchEvent=r.getStepDecimals=void 0;var t=N,n=Co,i=function(P){var O=P.toString().split(".")[1];return O?O.length:0};r.getStepDecimals=i;function s(P){return P.touches&&P.touches.length||P.changedTouches&&P.changedTouches.length}r.isTouchEvent=s;function o(P,O,L){var V=(O-P)/L,X=8,T=Number(V.toFixed(X));return parseInt(T.toString(),10)===T}r.isStepDivisible=o;function a(P,O,L,V,X,T,_){var j=1e11;if(P=Math.round(P*j)/j,!T){var G=_[O-1],ee=_[O+1];if(G&&G>P)return G;if(ee&&ee<P)return ee}if(P>V)return V;if(P<L)return L;var q=Math.floor(P*j-L*j)%Math.floor(X*j),K=Math.floor(P*j-Math.abs(q)),oe=q===0?P:K/j,ve=Math.abs(q/j)<X/2?oe:oe+X,ge=(0,r.getStepDecimals)(X);return parseFloat(ve.toFixed(ge))}r.normalizeValue=a;function l(P,O,L){return(P-O)/(L-O)}r.relativeValue=l;function u(P){return P===n.Direction.Up||P===n.Direction.Down}r.isVertical=u;function c(P,O,L){if(O>=L)throw new RangeError("min (".concat(O,") is equal/bigger than max (").concat(L,")"));if(P<O)throw new RangeError("value (".concat(P,") is smaller than min (").concat(O,")"));if(P>L)throw new RangeError("value (".concat(P,") is bigger than max (").concat(L,")"))}r.checkBoundaries=c;function d(P,O,L){return P<O?O:P>L?L:P}r.checkValuesAgainstBoundaries=d;function h(P){if(!(P.length<2)&&!P.slice(1).every(function(O,L){return P[L]<=O}))throw new RangeError("values={[".concat(P,"]} needs to be sorted when allowOverlap={false}"))}r.checkInitialOverlap=h;function f(P){var O=window.getComputedStyle(P);return{top:parseInt(O["margin-top"],10),bottom:parseInt(O["margin-bottom"],10),left:parseInt(O["margin-left"],10),right:parseInt(O["margin-right"],10)}}r.getMargin=f;function p(P){var O=window.getComputedStyle(P);return{top:parseInt(O["padding-top"],10)+parseInt(O["border-top-width"],10),bottom:parseInt(O["padding-bottom"],10)+parseInt(O["border-bottom-width"],10),left:parseInt(O["padding-left"],10)+parseInt(O["border-left-width"],10),right:parseInt(O["padding-right"],10)+parseInt(O["border-right-width"],10)}}r.getPaddingAndBorder=p;function m(P,O,L){var V=L?-1:1;P.forEach(function(X,T){return w(X,V*O[T].x,O[T].y)})}r.translateThumbs=m;function S(P,O,L,V){for(var X=0,T=F(P[0],O,L,V),_=1;_<P.length;_++){var j=F(P[_],O,L,V);j<T&&(T=j,X=_)}return X}r.getClosestThumbIndex=S;function w(P,O,L){P.style.transform="translate(".concat(O,"px, ").concat(L,"px)")}r.translate=w;var g=function(P){var O=[],L=null,V=function(){for(var X=[],T=0;T<arguments.length;T++)X[T]=arguments[T];O=X,!L&&(L=requestAnimationFrame(function(){L=null,P.apply(void 0,O)}))};return V};r.schd=g;function y(P,O,L){var V=P.slice(0);return V[O]=L,V}r.replaceAt=y;function C(P){var O=P.values,L=P.colors,V=P.min,X=P.max,T=P.direction,_=T===void 0?n.Direction.Right:T,j=P.rtl,G=j===void 0?!1:j;G&&_===n.Direction.Right?_=n.Direction.Left:G&&n.Direction.Left&&(_=n.Direction.Right);var ee=O.slice(0).sort(function(K,oe){return K-oe}).map(function(K){return(K-V)/(X-V)*100}),q=ee.reduce(function(K,oe,ve){return"".concat(K,", ").concat(L[ve]," ").concat(oe,"%, ").concat(L[ve+1]," ").concat(oe,"%")},"");return"linear-gradient(".concat(_,", ").concat(L[0]," 0%").concat(q,", ").concat(L[L.length-1]," 100%)")}r.getTrackBackground=C;function x(){}r.voidFn=x;function I(P){throw new Error("Didn't expect to get here")}r.assertUnreachable=I;var E=function(P,O,L,V,X){X===void 0&&(X=function(_){return _});var T=Math.ceil(e([P],Array.from(P.children),!0).reduce(function(_,j){var G=Math.ceil(j.getBoundingClientRect().width);if(j.innerText&&j.innerText.includes(L)&&j.childElementCount===0){var ee=j.cloneNode(!0);ee.innerHTML=X(O.toFixed(V)),ee.style.visibility="hidden",document.body.appendChild(ee),G=Math.ceil(ee.getBoundingClientRect().width),document.body.removeChild(ee)}return G>_?G:_},P.getBoundingClientRect().width));return T},A=function(P,O,L,V,X,T,_){_===void 0&&(_=function(ee){return ee});var j=[],G=function(ee){var q=E(L[ee],V[ee],X,T,_),K=O[ee].x;O.forEach(function(oe,ve){var ge=oe.x,Ce=E(L[ve],V[ve],X,T,_);ee!==ve&&(K>=ge&&K<=ge+Ce||K+q>=ge&&K+q<=ge+Ce)&&(j.includes(ve)||(j.push(ee),j.push(ve),j=e(e([],j,!0),[ee,ve],!1),G(ve)))})};return G(P),Array.from(new Set(j.sort()))},R=function(P,O,L,V,X,T){V===void 0&&(V=.1),X===void 0&&(X=" - "),T===void 0&&(T=function(ve){return ve});var _=(0,r.getStepDecimals)(V),j=(0,t.useState)({}),G=j[0],ee=j[1],q=(0,t.useState)(T(O[L].toFixed(_))),K=q[0],oe=q[1];return(0,t.useEffect)(function(){if(P){var ve=P.getThumbs();if(ve.length<1)return;var ge={},Ce=P.getOffsets(),ct=A(L,Ce,ve,O,X,_,T),dt=T(O[L].toFixed(_));if(ct.length){var xe=ct.reduce(function(wt,Ft,cr,tt){return wt.length?e(e([],wt,!0),[Ce[tt[cr]].x],!1):[Ce[tt[cr]].x]},[]);if(Math.min.apply(Math,xe)===Ce[L].x){var et=[];ct.forEach(function(wt){et.push(O[wt].toFixed(_))}),dt=Array.from(new Set(et.sort(function(wt,Ft){return parseFloat(wt)-parseFloat(Ft)}))).map(T).join(X);var Ke=Math.min.apply(Math,xe),qe=Math.max.apply(Math,xe),At=ve[ct[xe.indexOf(qe)]].getBoundingClientRect().width;ge.left="".concat(Math.abs(Ke-(qe+At))/2,"px"),ge.transform="translate(-50%, 0)"}else ge.visibility="hidden"}oe(dt),ee(ge)}},[P,O]),[K,G]};r.useThumbOverlap=R;function F(P,O,L,V){var X=P.getBoundingClientRect(),T=X.left,_=X.top,j=X.width,G=X.height;return u(V)?Math.abs(L-(_+G/2)):Math.abs(O-(T+j/2))}var z=function(){var P,O=((P=navigator.userAgentData)===null||P===void 0?void 0:P.platform)||navigator.platform;return["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(O)||navigator.userAgent.includes("Mac")&&"ontouchend"in document};r.isIOS=z})(qf);var gU=Nr&&Nr.__extends||function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&(n[s]=i[s])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),mU=Nr&&Nr.__createBinding||(Object.create?function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,i)}:function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]}),yU=Nr&&Nr.__setModuleDefault||(Object.create?function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}:function(r,e){r.default=e}),vU=Nr&&Nr.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&mU(e,r,t);return yU(e,r),e},iy=Nr&&Nr.__spreadArray||function(r,e,t){if(t||arguments.length===2)for(var n=0,i=e.length,s;n<i;n++)(s||!(n in e))&&(s||(s=Array.prototype.slice.call(e,0,n)),s[n]=e[n]);return r.concat(s||Array.prototype.slice.call(e))};Object.defineProperty(Zf,"__esModule",{value:!0});var yl=vU(N),ze=qf,_t=Co,wU=["ArrowRight","ArrowUp","k","PageUp"],CU=["ArrowLeft","ArrowDown","j","PageDown"],bU=function(r){gU(e,r);function e(t){var n=r.call(this,t)||this;if(n.trackRef=yl.createRef(),n.thumbRefs=[],n.state={draggedTrackPos:[-1,-1],draggedThumbIndex:-1,thumbZIndexes:new Array(n.props.values.length).fill(0).map(function(i,s){return s}),isChanged:!1,markOffsets:[]},n.getOffsets=function(){var i=n.props,s=i.direction,o=i.values,a=i.min,l=i.max,u=n.trackRef.current;if(!u)return console.warn("No track element found."),[];var c=u.getBoundingClientRect(),d=(0,ze.getPaddingAndBorder)(u);return n.getThumbs().map(function(h,f){var p={x:0,y:0},m=h.getBoundingClientRect(),S=(0,ze.getMargin)(h);switch(s){case _t.Direction.Right:return p.x=(S.left+d.left)*-1,p.y=((m.height-c.height)/2+d.top)*-1,p.x+=c.width*(0,ze.relativeValue)(o[f],a,l)-m.width/2,p;case _t.Direction.Left:return p.x=(S.right+d.right)*-1,p.y=((m.height-c.height)/2+d.top)*-1,p.x+=c.width-c.width*(0,ze.relativeValue)(o[f],a,l)-m.width/2,p;case _t.Direction.Up:return p.x=((m.width-c.width)/2+S.left+d.left)*-1,p.y=-d.left,p.y+=c.height-c.height*(0,ze.relativeValue)(o[f],a,l)-m.height/2,p;case _t.Direction.Down:return p.x=((m.width-c.width)/2+S.left+d.left)*-1,p.y=-d.left,p.y+=c.height*(0,ze.relativeValue)(o[f],a,l)-m.height/2,p;default:return(0,ze.assertUnreachable)(s)}})},n.getThumbs=function(){return n.trackRef&&n.trackRef.current?Array.from(n.trackRef.current.children).filter(function(i){return i.hasAttribute("aria-valuenow")}):(console.warn("No thumbs found in the track container. Did you forget to pass & spread the `props` param in renderTrack?"),[])},n.getTargetIndex=function(i){return n.getThumbs().findIndex(function(s){return s===i.target||s.contains(i.target)})},n.addTouchEvents=function(i){document.addEventListener("touchmove",n.schdOnTouchMove,{passive:!1}),document.addEventListener("touchend",n.schdOnEnd,{passive:!1}),document.addEventListener("touchcancel",n.schdOnEnd,{passive:!1})},n.addMouseEvents=function(i){document.addEventListener("mousemove",n.schdOnMouseMove),document.addEventListener("mouseup",n.schdOnEnd)},n.onMouseDownTrack=function(i){var s;if(!(i.button!==0||(0,ze.isIOS)()))if(i.persist(),i.preventDefault(),n.addMouseEvents(i.nativeEvent),n.props.values.length>1&&n.props.draggableTrack){if(n.thumbRefs.some(function(a){var l;return(l=a.current)===null||l===void 0?void 0:l.contains(i.target)}))return;n.setState({draggedTrackPos:[i.clientX,i.clientY]},function(){return n.onMove(i.clientX,i.clientY)})}else{var o=(0,ze.getClosestThumbIndex)(n.thumbRefs.map(function(a){return a.current}),i.clientX,i.clientY,n.props.direction);(s=n.thumbRefs[o].current)===null||s===void 0||s.focus(),n.setState({draggedThumbIndex:o},function(){return n.onMove(i.clientX,i.clientY)})}},n.onResize=function(){(0,ze.translateThumbs)(n.getThumbs(),n.getOffsets(),n.props.rtl),n.calculateMarkOffsets()},n.onTouchStartTrack=function(i){var s;if(i.persist(),n.addTouchEvents(i.nativeEvent),n.props.values.length>1&&n.props.draggableTrack){if(n.thumbRefs.some(function(a){var l;return(l=a.current)===null||l===void 0?void 0:l.contains(i.target)}))return;n.setState({draggedTrackPos:[i.touches[0].clientX,i.touches[0].clientY]},function(){return n.onMove(i.touches[0].clientX,i.touches[0].clientY)})}else{var o=(0,ze.getClosestThumbIndex)(n.thumbRefs.map(function(a){return a.current}),i.touches[0].clientX,i.touches[0].clientY,n.props.direction);(s=n.thumbRefs[o].current)===null||s===void 0||s.focus(),n.setState({draggedThumbIndex:o},function(){return n.onMove(i.touches[0].clientX,i.touches[0].clientY)})}},n.onMouseOrTouchStart=function(i){if(!n.props.disabled){var s=(0,ze.isTouchEvent)(i);if(!(!s&&i.button!==0)){var o=n.getTargetIndex(i);o!==-1&&(s?n.addTouchEvents(i):n.addMouseEvents(i),n.setState({draggedThumbIndex:o,thumbZIndexes:n.state.thumbZIndexes.map(function(a,l){return l===o?Math.max.apply(Math,n.state.thumbZIndexes):a<=n.state.thumbZIndexes[o]?a:a-1})}))}}},n.onMouseMove=function(i){i.preventDefault(),n.onMove(i.clientX,i.clientY)},n.onTouchMove=function(i){i.preventDefault(),n.onMove(i.touches[0].clientX,i.touches[0].clientY)},n.onKeyDown=function(i){var s=n.props,o=s.values,a=s.onChange,l=s.step,u=s.rtl,c=s.direction,d=n.state.isChanged,h=n.getTargetIndex(i.nativeEvent),f=u||c===_t.Direction.Left||c===_t.Direction.Down?-1:1;h!==-1&&(wU.includes(i.key)?(i.preventDefault(),n.setState({draggedThumbIndex:h,isChanged:!0}),a((0,ze.replaceAt)(o,h,n.normalizeValue(o[h]+f*(i.key==="PageUp"?l*10:l),h)))):CU.includes(i.key)?(i.preventDefault(),n.setState({draggedThumbIndex:h,isChanged:!0}),a((0,ze.replaceAt)(o,h,n.normalizeValue(o[h]-f*(i.key==="PageDown"?l*10:l),h)))):i.key==="Tab"?n.setState({draggedThumbIndex:-1},function(){d&&n.fireOnFinalChange()}):d&&n.fireOnFinalChange())},n.onKeyUp=function(i){var s=n.state.isChanged;n.setState({draggedThumbIndex:-1},function(){s&&n.fireOnFinalChange()})},n.onMove=function(i,s){var o=n.state,a=o.draggedThumbIndex,l=o.draggedTrackPos,u=n.props,c=u.direction,d=u.min,h=u.max,f=u.onChange,p=u.values,m=u.step,S=u.rtl;if(a===-1&&l[0]===-1&&l[1]===-1)return null;var w=n.trackRef.current;if(!w)return null;var g=w.getBoundingClientRect(),y=(0,ze.isVertical)(c)?g.height:g.width;if(l[0]!==-1&&l[1]!==-1){var C=i-l[0],x=s-l[1],I=0;switch(c){case _t.Direction.Right:case _t.Direction.Left:I=C/y*(h-d);break;case _t.Direction.Down:case _t.Direction.Up:I=x/y*(h-d);break;default:(0,ze.assertUnreachable)(c)}if(S&&(I*=-1),Math.abs(I)>=m/2){for(var E=0;E<n.thumbRefs.length;E++){if(p[E]===h&&Math.sign(I)===1||p[E]===d&&Math.sign(I)===-1)return;var A=p[E]+I;A>h?I=h-p[E]:A<d&&(I=d-p[E])}for(var R=p.slice(0),E=0;E<n.thumbRefs.length;E++)R=(0,ze.replaceAt)(R,E,n.normalizeValue(p[E]+I,E));n.setState({draggedTrackPos:[i,s]}),f(R)}}else{var F=0;switch(c){case _t.Direction.Right:F=(i-g.left)/y*(h-d)+d;break;case _t.Direction.Left:F=(y-(i-g.left))/y*(h-d)+d;break;case _t.Direction.Down:F=(s-g.top)/y*(h-d)+d;break;case _t.Direction.Up:F=(y-(s-g.top))/y*(h-d)+d;break;default:(0,ze.assertUnreachable)(c)}S&&(F=h+d-F),Math.abs(p[a]-F)>=m/2&&f((0,ze.replaceAt)(p,a,n.normalizeValue(F,a)))}},n.normalizeValue=function(i,s){var o=n.props,a=o.min,l=o.max,u=o.step,c=o.allowOverlap,d=o.values;return(0,ze.normalizeValue)(i,s,a,l,u,c,d)},n.onEnd=function(i){if(i.preventDefault(),document.removeEventListener("mousemove",n.schdOnMouseMove),document.removeEventListener("touchmove",n.schdOnTouchMove),document.removeEventListener("mouseup",n.schdOnEnd),document.removeEventListener("touchend",n.schdOnEnd),document.removeEventListener("touchcancel",n.schdOnEnd),n.state.draggedThumbIndex===-1&&n.state.draggedTrackPos[0]===-1&&n.state.draggedTrackPos[1]===-1)return null;n.setState({draggedThumbIndex:-1,draggedTrackPos:[-1,-1]},function(){n.fireOnFinalChange()})},n.fireOnFinalChange=function(){n.setState({isChanged:!1});var i=n.props,s=i.onFinalChange,o=i.values;s&&s(o)},n.updateMarkRefs=function(i){if(!i.renderMark){n.numOfMarks=void 0,n.markRefs=void 0;return}n.numOfMarks=(i.max-i.min)/n.props.step,n.markRefs=[];for(var s=0;s<n.numOfMarks+1;s++)n.markRefs[s]=yl.createRef()},n.calculateMarkOffsets=function(){if(!(!n.props.renderMark||!n.trackRef||!n.numOfMarks||!n.markRefs||n.trackRef.current===null)){for(var i=window.getComputedStyle(n.trackRef.current),s=parseInt(i.width,10),o=parseInt(i.height,10),a=parseInt(i.paddingLeft,10),l=parseInt(i.paddingTop,10),u=[],c=0;c<n.numOfMarks+1;c++){var d=9999,h=9999;if(n.markRefs[c].current){var f=n.markRefs[c].current.getBoundingClientRect();d=f.height,h=f.width}n.props.direction===_t.Direction.Left||n.props.direction===_t.Direction.Right?u.push([Math.round(s/n.numOfMarks*c+a-h/2),-Math.round((d-o)/2)]):u.push([Math.round(o/n.numOfMarks*c+l-d/2),-Math.round((h-s)/2)])}n.setState({markOffsets:u})}},t.step===0)throw new Error('"step" property should be a positive number');return n.schdOnMouseMove=(0,ze.schd)(n.onMouseMove),n.schdOnTouchMove=(0,ze.schd)(n.onTouchMove),n.schdOnEnd=(0,ze.schd)(n.onEnd),n.thumbRefs=t.values.map(function(){return yl.createRef()}),n.updateMarkRefs(t),n}return e.prototype.componentDidMount=function(){var t=this,n=this.props,i=n.values,s=n.min,o=n.step;this.resizeObserver=window.ResizeObserver?new window.ResizeObserver(this.onResize):{observe:function(){return window.addEventListener("resize",t.onResize)},unobserve:function(){return window.removeEventListener("resize",t.onResize)}},document.addEventListener("touchstart",this.onMouseOrTouchStart,{passive:!1}),document.addEventListener("mousedown",this.onMouseOrTouchStart,{passive:!1}),!this.props.allowOverlap&&(0,ze.checkInitialOverlap)(this.props.values),this.props.values.forEach(function(a){return(0,ze.checkBoundaries)(a,t.props.min,t.props.max)}),this.resizeObserver.observe(this.trackRef.current),(0,ze.translateThumbs)(this.getThumbs(),this.getOffsets(),this.props.rtl),this.calculateMarkOffsets(),i.forEach(function(a){(0,ze.isStepDivisible)(s,a,o)||console.warn("The `values` property is in conflict with the current `step`, `min`, and `max` properties. Please provide values that are accessible using the min, max, and step values.")})},e.prototype.componentDidUpdate=function(t,n){var i=this.props,s=i.max,o=i.min,a=i.step,l=i.values,u=i.rtl;(t.max!==s||t.min!==o||t.step!==a)&&this.updateMarkRefs(this.props),(0,ze.translateThumbs)(this.getThumbs(),this.getOffsets(),u),(t.max!==s||t.min!==o||t.step!==a||n.markOffsets.length!==this.state.markOffsets.length)&&(this.calculateMarkOffsets(),l.forEach(function(c){(0,ze.isStepDivisible)(o,c,a)||console.warn("The `values` property is in conflict with the current `step`, `min`, and `max` properties. Please provide values that are accessible using the min, max, and step values.")}))},e.prototype.componentWillUnmount=function(){var t={passive:!1};document.removeEventListener("mousedown",this.onMouseOrTouchStart,t),document.removeEventListener("mousemove",this.schdOnMouseMove),document.removeEventListener("touchmove",this.schdOnTouchMove),document.removeEventListener("touchstart",this.onMouseOrTouchStart),document.removeEventListener("mouseup",this.schdOnEnd),document.removeEventListener("touchend",this.schdOnEnd),this.resizeObserver.unobserve(this.trackRef.current)},e.prototype.render=function(){var t=this,n=this.props,i=n.label,s=n.labelledBy,o=n.renderTrack,a=n.renderThumb,l=n.renderMark,u=l===void 0?function(){return null}:l,c=n.values,d=n.min,h=n.max,f=n.allowOverlap,p=n.disabled,m=this.state,S=m.draggedThumbIndex,w=m.thumbZIndexes,g=m.markOffsets;return o({props:{style:{transform:"scale(1)",cursor:S>-1?"grabbing":this.props.draggableTrack?(0,ze.isVertical)(this.props.direction)?"ns-resize":"ew-resize":c.length===1&&!p?"pointer":"inherit"},onMouseDown:p?ze.voidFn:this.onMouseDownTrack,onTouchStart:p?ze.voidFn:this.onTouchStartTrack,ref:this.trackRef},isDragged:this.state.draggedThumbIndex>-1,disabled:p,children:iy(iy([],g.map(function(y,C,x){return u({props:{style:t.props.direction===_t.Direction.Left||t.props.direction===_t.Direction.Right?{position:"absolute",left:"".concat(y[0],"px"),marginTop:"".concat(y[1],"px")}:{position:"absolute",top:"".concat(y[0],"px"),marginLeft:"".concat(y[1],"px")},key:"mark".concat(C),ref:t.markRefs[C]},index:C})}),!0),c.map(function(y,C){var x=t.state.draggedThumbIndex===C;return a({index:C,value:y,isDragged:x,props:{style:{position:"absolute",zIndex:w[C],cursor:p?"inherit":x?"grabbing":"grab",userSelect:"none",touchAction:"none",WebkitUserSelect:"none",MozUserSelect:"none",msUserSelect:"none"},key:C,tabIndex:p?void 0:0,"aria-valuemax":f?h:c[C+1]||h,"aria-valuemin":f?d:c[C-1]||d,"aria-valuenow":y,draggable:!1,ref:t.thumbRefs[C],"aria-label":i,"aria-labelledby":s,role:"slider",onKeyDown:p?ze.voidFn:t.onKeyDown,onKeyUp:p?ze.voidFn:t.onKeyUp}})}),!0)})},e.defaultProps={label:"Accessibility label",labelledBy:null,step:1,direction:_t.Direction.Right,rtl:!1,disabled:!1,allowOverlap:!1,draggableTrack:!1,min:0,max:100},e}(yl.Component);Zf.default=bU;(function(r){var e=Nr&&Nr.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(r,"__esModule",{value:!0}),r.checkValuesAgainstBoundaries=r.relativeValue=r.useThumbOverlap=r.Direction=r.getTrackBackground=r.Range=void 0;var t=e(Zf);r.Range=t.default;var n=qf;Object.defineProperty(r,"getTrackBackground",{enumerable:!0,get:function(){return n.getTrackBackground}}),Object.defineProperty(r,"useThumbOverlap",{enumerable:!0,get:function(){return n.useThumbOverlap}}),Object.defineProperty(r,"relativeValue",{enumerable:!0,get:function(){return n.relativeValue}}),Object.defineProperty(r,"checkValuesAgainstBoundaries",{enumerable:!0,get:function(){return n.checkValuesAgainstBoundaries}});var i=Co;Object.defineProperty(r,"Direction",{enumerable:!0,get:function(){return i.Direction}})})(zC);const Yr={fontSize:12,color:"#9aa7b2"},sy={background:"rgba(255,255,255,0.04)",border:"1px solid rgba(255,255,255,0.12)",borderRadius:10};function Zo(r,e,t){return Math.max(e,Math.min(t,r))}function oy(r,e){const t=r.replace("#",""),n=parseInt(t.slice(0,2),16),i=parseInt(t.slice(2,4),16),s=parseInt(t.slice(4,6),16);return`rgba(${n},${i},${s},${Zo(e,0,1)})`}function SU(r){const e=["#66d9ef","#a6e22e","#fd971f","#e6db74","#f92672","#ae81ff","#2aa198"];return e[Math.abs(r)%e.length]}function DC(r,e){const t=(r??"").trim();return t.length?t:e}function xU(r,e){return r.map(t=>{const n=e.get(t);return n?{id:t,name:DC(n.name,`Layer ${t}`),z:n.z,layer:{id:n.id,name:n.name,z:n.z,origin:n.origin,width:n.width,height:n.height}}:null}).filter(Boolean)}function IU({user:r,selectedDisplayId:e,selectedLayerIds:t,onSelectLayer:n,onSelectDisplay:i,setVisibleLayers:s}){var C;const o=N.useMemo(()=>r.displays.filter(x=>x.id!==255),[r.displays]),[a,l]=N.useState(null),[u,c]=N.useState([0,0]),d=N.useRef(null),h=N.useMemo(()=>{var E,A,R;const x=(E=o.find(F=>F.id===e))==null?void 0:E.id;if(x!=null)return x;const I=(A=o.find(F=>F.id===a))==null?void 0:A.id;return I??((R=o[0])==null?void 0:R.id)??null},[a,o,e]),f=N.useMemo(()=>h==null?null:o.find(x=>x.id===h)??null,[o,h]),p=N.useMemo(()=>{var I,E;if(h==null)return null;const x=(E=(I=r.displayComposite)==null?void 0:I[h])==null?void 0:E.layerIdsTopToBottom;return x&&x.length?x:null},[h,r.displayComposite]),m=N.useMemo(()=>{const x=new Map;for(const I of r.layers)x.set(I.id,{id:I.id,name:I.name,z:I.z,origin:I.origin,width:I.width,height:I.height});return x},[r.layers]),S=N.useMemo(()=>{var z,P;if(h==null)return[];const x=(P=(z=r.displayComposite)==null?void 0:z[h])==null?void 0:P.layerIdsTopToBottom;if(x&&x.length)return xU(x,m);if(!f)return[];const I=f.origin.x,E=f.origin.y,A=I+f.size.x,R=E+f.size.y,F=[];for(const O of r.layers){const L=O.origin.x,V=O.origin.y,X=O.origin.x+O.width,T=O.origin.y+O.height;A<=L||I>=X||R<=V||E>=T||F.push({id:O.id,name:DC(O.name,`Layer ${O.id}`),z:O.z,layer:O})}return F.sort((O,L)=>L.z-O.z),F},[h,f,m,r.displayComposite,r.layers]);N.useEffect(()=>{const x=S.length;if(!x){c([0,0]);return}const I=Math.max(0,x-1);c([0,I])},[h,S.length]);const w=N.useMemo(()=>{const x=Math.max(0,S.length-1);let I=Zo(u[0],0,x),E=Zo(u[1],0,x);return I>E&&([I,E]=[E,I]),[I,E]},[S.length,u]),g=N.useMemo(()=>{if(!S.length)return S;const[x,I]=w;return S.slice(x,I+1)},[S,w]);N.useEffect(()=>{if(!s)return;if(!S.length){s(null);return}const[x,I]=w;if(x===0&&I===S.length-1){s(null);return}s(g.map(A=>A.id))},[S.length,w,s,g]);const y=N.useMemo(()=>{if(!f)return null;const x=g;if(!S.length)return{visible:[],minY:f.origin.y,maxY:f.origin.y+f.size.y,range:[0,0]};const[I,E]=w,A=x;let R=f.origin.y,F=f.origin.y+f.size.y;for(const z of A){const P=z.layer;P&&(R=Math.min(R,P.origin.y),F=Math.max(F,P.origin.y+P.height))}return{visible:A,minY:R,maxY:F,range:[I,E]}},[f,S.length,w,g]);return N.useEffect(()=>{const x=d.current;if(!x||!f||!y)return;const I=x.getContext("2d");if(!I)return;const E=window.devicePixelRatio||1,A=x.clientWidth,R=x.clientHeight,F=Math.max(1,Math.floor(A*E)),z=Math.max(1,Math.floor(R*E));(x.width!==F||x.height!==z)&&(x.width=F,x.height=z),I.setTransform(E,0,0,E,0,0),I.clearRect(0,0,A,R);const P=14,O=Math.max(1,A-P*2),L=Math.max(1,R-P*2),V=y.minY,X=y.maxY,T=Math.max(1,X-V),_=f.origin.x,j=f.origin.x+f.size.x,G=Math.max(1,j-_),ee=xe=>P+(xe-_)/G*O,q=xe=>xe/G*O,K=xe=>P+(xe-V)/T*L,oe=xe=>xe/T*L;I.fillStyle="rgba(0,0,0,0.20)",I.fillRect(0,0,A,R);const ve=ee(f.origin.x),ge=K(f.origin.y),Ce=q(f.size.x),ct=oe(f.size.y);I.strokeStyle="rgba(255,120,120,0.75)",I.lineWidth=1,I.strokeRect(ve,ge,Ce,ct),I.fillStyle="rgba(255,120,120,0.08)",I.fillRect(ve,ge,Ce,ct);const dt=y.visible;for(let xe=dt.length-1;xe>=0;xe--){const et=dt[xe],Ke=et.layer;if(!Ke)continue;const qe=ee(Ke.origin.x),At=K(Ke.origin.y),wt=Math.max(2,q(Ke.width)),Ft=Math.max(2,oe(Ke.height)),cr=SU(et.id),tt=t.includes(et.id);I.fillStyle=oy(cr,1),I.strokeStyle=oy(cr,tt?.95:.55),I.lineWidth=tt?2:1,I.fillRect(qe,At,wt,Ft),I.strokeRect(qe,At,wt,Ft),I.save(),I.beginPath(),I.rect(qe,At,wt,Ft),I.clip(),I.fillStyle="rgba(15,15,15,0.95)",I.font="12px Segoe UI, sans-serif";const kt=[`${et.name}`,`id ${et.id} • z ${et.z}`,`pos ${Ke.origin.x},${Ke.origin.y}`,`size ${Ke.width}×${Ke.height}`],nt=14;let Cr=At+16;const Se=qe+8;for(let Re=0;Re<kt.length&&!(Cr>At+Ft-4);Re++){const pe=kt[Re];I.fillText(pe,Se,Cr),Cr+=nt}I.restore()}dt.length===0&&(I.fillStyle="rgba(154,167,178,0.9)",I.font="12px Segoe UI, sans-serif",I.fillText("No layers in this range",P+8,P+18))},[f,t,y]),k.jsxs("div",{style:{position:"absolute",inset:0,display:"flex",flexDirection:"column",minHeight:0},children:[k.jsxs("div",{style:{padding:"10px 12px",borderBottom:"1px solid #2f2f2f",background:"#1b1d22",display:"flex",alignItems:"center",justifyContent:"space-between",gap:12},children:[k.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2},children:[k.jsx("div",{style:{fontSize:13,fontWeight:700,color:"#e6e6e6"},children:"Composer"}),k.jsx("div",{style:Yr,children:"Side stack per display (core-derived)"})]}),k.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[k.jsx("div",{style:Yr,children:"Display"}),k.jsx("select",{value:h??"",onChange:x=>{const I=x.target.value===""?null:Number(x.target.value);l(I),I!=null&&i(I)},style:{height:28,background:"#252526",color:"#cccccc",border:"1px solid #3c3c3c",borderRadius:8,padding:"0 8px",fontSize:12,outline:"none"},children:o.map(x=>k.jsx("option",{value:x.id,children:x.id},x.id))})]})]}),k.jsx("div",{style:{flex:1,minHeight:0,overflow:"auto",padding:12,background:"#14161a"},children:h==null?k.jsx("div",{style:{...Yr,padding:16},children:"No display."}):k.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 280px",gap:12,alignItems:"start"},children:[k.jsxs("div",{style:{...sy,padding:12,display:"flex",flexDirection:"column",gap:10},children:[k.jsxs("div",{style:{display:"flex",alignItems:"baseline",justifyContent:"space-between"},children:[k.jsx("div",{style:{fontWeight:700,color:"#e6e6e6"},children:"Cut-away"}),k.jsx("div",{style:Yr,children:f?`origin ${f.origin.x},${f.origin.y} • size ${f.size.x}×${f.size.y}`:""})]}),f&&k.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[k.jsx("div",{style:Yr,children:"Z range"}),k.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",gap:6},children:[k.jsx("div",{style:{padding:"6px 0"},children:k.jsx(zC.Range,{step:1,min:0,max:Math.max(0,S.length-1),values:(()=>{const x=Math.max(0,S.length-1),I=x-w[1],E=x-w[0];return[I,E]})(),onChange:x=>{const I=Math.max(0,S.length-1),E=Math.round(x[0]??0),A=Math.round(x[1]??0),R=Zo(I-A,0,I),F=Zo(I-E,0,I);c([R,F])},renderTrack:({props:x,children:I})=>k.jsxs("div",{...x,style:{...x.style,height:6,width:"100%",borderRadius:999,background:"rgba(255,255,255,0.10)",border:"1px solid rgba(255,255,255,0.12)",position:"relative"},children:[(()=>{const E=Math.max(1,S.length-1),A=(E-w[1])/E,R=(E-w[0])/E,F=A*100,z=R*100;return k.jsx("div",{style:{position:"absolute",left:`${Math.min(F,z)}%`,width:`${Math.max(0,Math.abs(z-F))}%`,top:-1,bottom:-1,borderRadius:999,background:"linear-gradient(90deg, rgba(102,217,239,0.70), rgba(253,151,31,0.70))",boxShadow:"0 0 0 1px rgba(0,0,0,0.18) inset"}})})(),I]}),renderThumb:({props:x,index:I})=>k.jsx("div",{...x,style:{...x.style,height:14,width:14,borderRadius:999,background:I===0?"#66d9ef":"#fd971f",border:"1px solid rgba(0,0,0,0.35)",boxShadow:"0 2px 10px rgba(0,0,0,0.35)"},title:I===0?"Bottom handle":"Top handle"})})}),k.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:10},children:[k.jsx("div",{style:Yr,children:"BOTTOM"}),k.jsxs("div",{style:Yr,children:[S.length?`${w[0]} → ${w[1]}`:"—",S.length?` • ${g.length}/${S.length}`:""]}),k.jsx("div",{style:Yr,children:"TOP"})]})]})]}),k.jsx("div",{style:{position:"relative",flex:1,minHeight:260},children:k.jsx("canvas",{ref:d,style:{width:"100%",height:"100%",display:"block",borderRadius:10,background:"rgba(0,0,0,0.12)",cursor:"default",pointerEvents:"none",maxWidth:800,margin:"0 auto"}})})]}),k.jsxs("div",{style:{...sy,padding:12},children:[k.jsxs("div",{style:{display:"flex",alignItems:"baseline",justifyContent:"space-between"},children:[k.jsx("div",{style:{fontWeight:700,color:"#e6e6e6"},children:"Side stack"}),k.jsxs("div",{style:Yr,children:[g.length," / ",S.length," layers"]})]}),p&&k.jsxs("div",{style:{...Yr,marginTop:6},children:["core order: top→bottom • [",p.join(", "),"]"]}),k.jsxs("div",{style:{marginTop:10,display:"flex",flexDirection:"column",gap:8},children:[S.map((x,I)=>{const E=t.includes(x.id),A=I>=w[0]&&I<=w[1];return k.jsx("button",{onClick:R=>{n(x.id,{metaKey:R.metaKey,ctrlKey:R.ctrlKey});const F=S.findIndex(z=>z.id===x.id);F>=0&&c([F,F])},style:{textAlign:"left",width:"100%",background:E?"rgba(102, 217, 239, 0.10)":A?"rgba(255,255,255,0.03)":"rgba(255,255,255,0.01)",border:E?"1px solid rgba(102, 217, 239, 0.65)":A?"1px solid rgba(255,255,255,0.10)":"1px solid rgba(255,255,255,0.06)",borderRadius:10,padding:"8px 10px",cursor:"pointer",color:A?"#e6e6e6":"rgba(230,230,230,0.55)"},title:"Select layer",children:k.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:10},children:[k.jsx("div",{style:{fontWeight:650,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:x.name}),k.jsxs("div",{style:{...Yr,whiteSpace:"nowrap"},children:["z=",x.z]})]})},x.id)}),S.length===0&&k.jsx("div",{style:{...Yr,padding:10},children:"No layers."}),((C=r.displayComposite)==null?void 0:C[h])==null&&k.jsx("div",{style:{...Yr,paddingTop:8},children:"Using fallback intersection (core composition not present)."})]})]})]})})]})}function kU({centerTab:r,setCenterTab:e,centerPanelRef:t,centerSize:n,worldLayers:i,worldDisplays:s,selectedLayerIds:o,setVisibleLayers:a,selectedDisplayId:l,focusRect:u,focusKey:c,onSelectLayer:d,onSelectDisplay:h,assetsSnapshot:f,primaryUser:p,isFloating:m,sortedTraffic:S,topTraffic:w,chartData:g,topKeys:y,keyToLabel:C,keyToColor:x,tickRate:I,hoveredTrafficKey:E,setHoveredTrafficKey:A}){return k.jsxs("div",{style:{background:"#1e1e1e",padding:0,minHeight:0,overflow:"hidden",display:"flex",flexDirection:"column"},children:[k.jsx("div",{style:{display:"flex",alignItems:"center",gap:2,padding:"4px 6px 0",background:"#252526",borderBottom:"1px solid #3c3c3c"},children:[{id:"grid",label:"World"},{id:"assets",label:"Assets"},{id:"network",label:"Network Details"},{id:"composer",label:"Composer"},{id:"renderer",label:"Renderer"}].map(R=>{const F=r===R.id;return k.jsx("button",{onClick:()=>e(R.id),style:{border:"1px solid #3c3c3c",borderBottom:F?"1px solid #1e1e1e":"1px solid #3c3c3c",background:F?"#1e1e1e":"#2d2d2d",color:"#cccccc",padding:"4px 10px",cursor:"pointer",fontSize:12,borderRadius:"4px 4px 0 0",marginBottom:"-1px"},children:R.label},R.id)})}),k.jsxs("div",{ref:t,style:{position:"relative",flex:1,minHeight:0,overflow:"hidden",background:"#1e1e1e"},children:[r==="grid"&&k.jsx(pU,{layers:i,displays:s,width:n.width,height:n.height,selectedLayerIds:o,selectedDisplayId:l,focusRect:u,focusKey:c,onSelectLayer:d,onSelectDisplay:h,onToolRectCommit:R=>{window.dispatchEvent(new window.CustomEvent("__utsp_debug_display255_rect",{detail:R}))}}),r==="composer"&&p&&k.jsx(IU,{user:p,selectedDisplayId:l,selectedLayerIds:o,onSelectLayer:d,onSelectDisplay:h,setVisibleLayers:a}),r==="composer"&&!p&&k.jsx("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",color:"#9aa7b2",fontSize:13,background:"#111"},children:"No user in snapshot."}),r==="assets"&&k.jsx(m5,{assetsSnapshot:f}),r==="renderer"&&!m&&k.jsx("div",{style:{position:"absolute",inset:0,background:"#111"}}),r==="renderer"&&m&&k.jsx("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",color:"#bbbbbb",fontSize:13,background:"#111",textAlign:"center",padding:24,lineHeight:1.5},children:'Press "Embed" on the floating renderer window to dock it here.'}),r==="network"&&k.jsx(fU,{sortedTraffic:S,topTraffic:w,chartData:g,topKeys:y,keyToLabel:C,keyToColor:x,tickRate:I,hoveredTrafficKey:E,setHoveredTrafficKey:A})]})]})}function EU(r){var d,h;const{enabled:e,snapshot:t,layers:n}=r,[i,s]=N.useState([]),o=N.useRef(null),a=N.useRef(0),l=N.useMemo(()=>{let f=0;for(let p=0;p<n.length;p++){const m=n[p].bytesPerSec1s;typeof m=="number"&&(f+=m)}return f},[n]);N.useEffect(()=>{e&&s(f=>f.length>0?f:[{time:"—",total:0}])},[e]),N.useEffect(()=>{var y,C;if(!e)return;const f=((y=t==null?void 0:t.tick)==null?void 0:y.tickRate)??((C=t==null?void 0:t.tick)==null?void 0:C.tps)??60,p=Math.max(1,Math.round(f*10)),m=performance.now?performance.now():Date.now(),S=Math.max(1,Math.round(1e3/f));if(m-a.current<S)return;a.current=m;const g={time:new Date().toLocaleTimeString("en-US",{hour12:!1,minute:"2-digit",second:"2-digit"}),total:l};s(x=>{if(o.current!==f)return o.current=f,[g];const I=x.length===0?[g]:[...x,g];return I.length>p?I.slice(I.length-p):I})},[e,l,t]);const u=o.current??((d=t==null?void 0:t.tick)==null?void 0:d.tickRate)??((h=t==null?void 0:t.tick)==null?void 0:h.tps)??60,c=N.useMemo(()=>{for(let f=0;f<i.length;f++)if(Number(i[f].total??0)>0)return!0;return!1},[i]);return{tickRate:u,data:i,hasData:c,latestBps:l}}function MU({primaryUser:r,tickRate:e,snapshot:t,assetsSnapshot:n}){const{totalBytesAll:i,totalBytesAssets:s,totalBytesNonAssets:o,totalBpsNonAssets:a}=N.useMemo(()=>{var y;const u=(r==null?void 0:r.layers)??[],c=(r==null?void 0:r.miscTraffic)??{},d=(r==null?void 0:r.displayTraffic)??{};let h=0,f=0;for(let C=0;C<u.length;C++){const x=u[C];typeof x.bytesTotal=="number"&&(h+=x.bytesTotal),typeof x.bytesPerSec1s=="number"&&(f+=x.bytesPerSec1s)}for(const C of Object.values(c))typeof(C==null?void 0:C.total)=="number"&&(h+=C.total),typeof(C==null?void 0:C.bytesPerSec1s)=="number"&&(f+=C.bytesPerSec1s);for(const C of Object.values(d))typeof(C==null?void 0:C.total)=="number"&&(h+=C.total),typeof(C==null?void 0:C.bytesPerSec1s)=="number"&&(f+=C.bytesPerSec1s);const p=Array.isArray(n==null?void 0:n.audio)?n.audio:[];let m=0;for(let C=0;C<p.length;C++){const x=(y=p[C])==null?void 0:y.originalSize;typeof x=="number"&&Number.isFinite(x)&&x>0&&(m+=x)}const S=Math.max(0,h),w=m>0?m:void 0;return{totalBytesAll:w!=null?w+S:S,totalBytesAssets:w,totalBytesNonAssets:S,totalBpsNonAssets:Math.max(0,f)}},[r,t,n]),{data:l}=EU({enabled:!0,snapshot:t,layers:(r==null?void 0:r.layers)??[]});return k.jsxs("div",{style:{borderLeft:"1px solid #3c3c3c",background:"#252526",padding:0,minHeight:0,display:"flex",flexDirection:"column"},children:[k.jsx("div",{style:{padding:"8px 12px",borderBottom:"1px solid #3c3c3c"},children:k.jsx("div",{style:{fontSize:11,color:"#bbbbbb",textTransform:"uppercase",letterSpacing:"0.5px"},children:"Network"})}),k.jsxs("div",{style:{padding:"8px 12px",display:"flex",flexDirection:"column",gap:10},children:[k.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:12},children:[k.jsx("div",{style:{fontSize:12,color:"#858585"},children:"Total assets"}),k.jsx("div",{style:{fontSize:12,color:"#cccccc"},children:Kr(s)})]}),k.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:12},children:[k.jsx("div",{style:{fontSize:12,color:"#858585"},children:"Total (non-assets)"}),k.jsx("div",{style:{fontSize:12,color:"#cccccc"},children:Kr(o)})]}),k.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:12},children:[k.jsx("div",{style:{fontSize:12,color:"#858585"},children:"Total"}),k.jsx("div",{style:{fontSize:12,color:"#cccccc"},children:Kr(i)})]}),k.jsx("div",{style:{height:1,background:"#3c3c3c",opacity:.5}}),k.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:12},children:[k.jsx("div",{style:{fontSize:12,color:"#858585"},children:"Per second"}),k.jsxs("div",{style:{fontSize:12,color:"#cccccc"},children:[Kr(a),"/s"]})]}),k.jsxs("div",{style:{width:"100%",height:160,border:"1px solid #3c3c3c",background:"#111",padding:"8px 10px 10px",boxSizing:"border-box"},children:[k.jsx("div",{style:{marginBottom:6,color:"#aaa",fontSize:12},children:"Bandwidth (total)"}),k.jsx(BC,{data:l,seriesKeys:["total"],seriesLabels:{total:"Total"},colors:["#4fc1ff"],height:120,tickRate:e,windowSeconds:10})]})]})]})}function ay({enabled:r,initialRect:e,minSize:t}){const[n,i]=N.useState(e),[s,o]=N.useState(!1),a=N.useRef({x:0,y:0}),l=N.useRef({resizing:!1,startX:0,startY:0,startW:0,startH:0});return N.useEffect(()=>{if(!r)return;const d=()=>{i(h=>{const p=Math.max(t.width,window.innerWidth-16),m=Math.max(t.height,window.innerHeight-8*2),S=Math.min(Math.max(t.width,h.width),p),w=Math.min(Math.max(t.height,h.height),m),g=Math.min(Math.max(8,h.x),Math.max(8,window.innerWidth-8-S)),y=Math.min(Math.max(8,h.y),Math.max(8,window.innerHeight-8-w));return{x:g,y,width:S,height:w}})};return d(),window.addEventListener("resize",d),()=>window.removeEventListener("resize",d)},[r,t.height,t.width]),N.useEffect(()=>{if(!r)return;const d=f=>{if(s){i(p=>({...p,x:Math.max(0,f.clientX-a.current.x),y:Math.max(0,f.clientY-a.current.y)}));return}if(l.current.resizing){const p=f.clientX-l.current.startX,m=f.clientY-l.current.startY;i(S=>({...S,width:Math.max(t.width,l.current.startW+p),height:Math.max(t.height,l.current.startH+m)}))}},h=()=>{o(!1),l.current.resizing=!1};return window.addEventListener("mousemove",d),window.addEventListener("mouseup",h),()=>{window.removeEventListener("mousemove",d),window.removeEventListener("mouseup",h)}},[r,s,t.height,t.width]),{rect:n,setRect:i,isDragging:s,startDrag:(d,h)=>{r&&(o(!0),i(f=>(a.current={x:d-f.x,y:h-f.y},f)))},startResize:(d,h)=>{r&&i(f=>(l.current={resizing:!0,startX:d,startY:h,startW:f.width,startH:f.height},f))}}}function ly(r){const[e,t]=N.useState({width:600,height:400}),[n,i]=N.useState({left:0,top:0}),[s,o]=N.useState(null);return N.useLayoutEffect(()=>{const a=r.current??null;o(l=>l===a?l:a)},[r]),N.useEffect(()=>{const a=s;if(!a)return;const l=()=>{const c=a.getBoundingClientRect();i({left:c.left,top:c.top})},u=new ResizeObserver(c=>{const d=c[0];d&&(t({width:d.contentRect.width,height:d.contentRect.height}),l())});return u.observe(a),l(),window.addEventListener("resize",l),()=>{window.removeEventListener("resize",l),u.disconnect()}},[s]),{size:e,rect:n}}function UU(r,e){const[t,n]=N.useState(null),[i,s]=N.useState([]),[o,a]=N.useState(null),[l,u]=N.useState(0),c=N.useMemo(()=>r?r.layers.map(y=>({id:y.id,x:y.origin.x,y:y.origin.y,width:y.width,height:y.height,color:i.includes(y.id)?"rgba(43, 140, 255, 0.7)":void 0})):[],[r,i]),d=N.useMemo(()=>r?r.displays.map(y=>({id:y.id,x:y.origin.x,y:y.origin.y,width:y.size.x,height:y.size.y})):[],[r]),h=N.useMemo(()=>o!=null?c.find(y=>y.id===o)??null:t!=null?d.find(y=>y.id===t)??null:null,[o,t,d,c]),f=N.useMemo(()=>`${t??"none"}-${i.join(",")}-${l}`,[t,i,l]),p=y=>{r!=null&&r.displays.some(C=>C.id===y)&&(u(C=>C+1),n(y),s([]),a(null),e.setVisibleLayers(null))},m=y=>{const C=r==null?void 0:r.layers.find(x=>x.id===y);return C?{x:C.origin.x,y:C.origin.y,width:C.width,height:C.height}:null},S=(y,C)=>{if(e.setVisibleLayersDisplay255(y.length>0?y:null),C!=null){const x=m(C);x&&e.sendDisplayTransform(x)}},w=(y,C)=>{if(!(r!=null&&r.layers.some(I=>I.id===y)))return;const x=!!(C&&(C.metaKey||C.ctrlKey));u(I=>I+1),n(null),s(I=>{if(!x)return I.includes(y)?(a(null),S([],null),[]):(a(y),S([y],y),[y]);const E=I.includes(y)?I.filter(R=>R!==y):[...I,y],A=E.length>0?E[E.length-1]:null;return a(A),S(E,A),E})},g=(y,C)=>{if(!(r!=null&&r.layers.some(I=>I.id===y)))return;const x=!!(C&&(C.metaKey||C.ctrlKey));u(I=>I+1),n(null),s(I=>{if(!x)return I.includes(y)?(a(null),S([],null),[]):(a(y),S([y],y),[y]);const E=I.includes(y)?I.filter(R=>R!==y):[...I,y],A=E.length>0?E[E.length-1]:null;return a(A),S(E,A),E})};return N.useEffect(()=>{if(!r){n(null),s([]),a(null),e.setVisibleLayers(null),e.setVisibleLayersDisplay255(null);return}const y=new Set(r.layers.map(x=>x.id)),C=new Set(r.displays.map(x=>x.id));s(x=>{const I=x.filter(A=>y.has(A)),E=I.length>0?I[I.length-1]:null;return a(E),S(I,E),I}),n(x=>x!=null&&C.has(x)?x:null)},[r,e]),{selectedDisplayId:t,selectedLayerIds:i,lastSelectedLayerId:o,focusKey:f,focusRect:h,handleSelectDisplay:p,handleSelectLayer:w,handleSelectLayerDisplay255Only:g,setFocusNonce:u}}function AU(r){const{enabled:e,snapshot:t,topKeys:n,topTraffic:i}=r,[s,o]=N.useState([]),a=N.useRef(null),l=N.useRef(0),u=N.useRef(i);u.current=i;const c=N.useMemo(()=>n.join(","),[n]);N.useEffect(()=>{e&&o(f=>{if(f.length>0)return f;const p={time:"—"};for(let m=0;m<n.length;m++)p[n[m]]=0;return[p]})},[e,c]),N.useEffect(()=>{var C,x;if(!e||!t)return;const f=((C=t==null?void 0:t.tick)==null?void 0:C.tickRate)??((x=t==null?void 0:t.tick)==null?void 0:x.tps)??60,p=Math.max(1,Math.round(f*60)),m=performance.now?performance.now():Date.now(),S=Math.max(1,Math.round(1e3/f));if(m-l.current<S)return;l.current=m;const g={time:new Date().toLocaleTimeString("en-US",{hour12:!1,minute:"2-digit",second:"2-digit"})},y=u.current;for(let I=0;I<y.length;I++){const E=y[I];g[E.key]=E.bps??0}o(I=>{if(a.current!==f)return a.current=f,[g];const E=I.length===0?[g]:[...I,g];return E.length>p?E.slice(E.length-p):E})},[e,t,c]);const d=a.current??60,h=N.useMemo(()=>{if(!e)return[];const f=new Array(s.length);for(let p=0;p<s.length;p++){const m=s[p],S={time:m.time};for(let w=0;w<n.length;w++){const g=n[w];S[g]=Number(m[g]??0)}f[p]=S}return f},[e,s,n]);return{trafficHistory:s,tickRate:d,chartData:h}}const TU=r=>typeof r!="string"?"8-bit":r.includes("16")?"16-bit":"8-bit";function RU(r){var w;const{primaryUser:e,selection:t,selectedDisplayId:n,lastSelectedLayerId:i,selectedLayerIds:s}=r,o=N.useMemo(()=>((e==null?void 0:e.displays)??[]).map(y=>({id:y.id,x:y.origin.x,y:y.origin.y,width:y.size.x,height:y.size.y})),[e]),a=((w=e==null?void 0:e.layers)==null?void 0:w.length)??0,l=N.useMemo(()=>e?!t.selectedLayerIds.length&&!e?[]:e.layers.map(g=>({id:g.id,x:g.origin.x,y:g.origin.y,width:g.width,height:g.height,zIndex:g.z??0,name:g.name})):[],[e,t.selectedLayerIds.length]),u=N.useMemo(()=>{if(!e)return null;if(s.length){const g=e.layers.find(y=>y.id===i);return g?{type:"layer",item:g}:null}if(n!=null){const g=e.displays.find(y=>y.id===n);return g?{type:"display",item:g}:null}return null},[i,e,n,s.length]),c=N.useMemo(()=>{const y=((e==null?void 0:e.layers)??[]).filter(F=>typeof F.bytesPerSec1s=="number").map(F=>({key:`layer-${F.id}`,id:F.id,name:F.name,encoding:TU(F.charCodeMode),total:F.bytesTotal??0,bps:F.bytesPerSec1s??0,size:{x:F.width,y:F.height},position:{x:F.origin.x,y:F.origin.y},zIndex:F.z??0})),C=(e==null?void 0:e.miscTraffic)??{},x=F=>{switch(F){case"update.audioOrders":return"Audio";case"update.vibrationOrders":return"Vibration";case"update.macroOrders":return"Macro";case"update.postProcessOrders":return"PostProcess";default:return F}},I=Object.entries(C).map(([F,z],P)=>({key:`misc-${F}`,id:1e5+P,name:x(F),total:z.total??0,bps:z.bytesPerSec1s??0,size:{x:0,y:0},position:{x:0,y:0},zIndex:0})),E=((e==null?void 0:e.displays)??[]).filter(F=>F.id!==255),A=(e==null?void 0:e.displayTraffic)??{},R=E.map(F=>{const z=A[F.id];return{key:`display-${F.id}`,id:F.id,name:`Display ${F.id}`,total:(z==null?void 0:z.total)??0,bps:(z==null?void 0:z.bytesPerSec1s)??0,size:{x:F.size.x,y:F.size.y},position:{x:F.origin.x,y:F.origin.y},zIndex:0}}).filter(F=>typeof F.bps=="number");return[...y,...R,...I]},[e]),d=N.useMemo(()=>[...c].sort((g,y)=>y.total-g.total),[c]),h=N.useMemo(()=>d.slice(0,6),[d]),f=N.useMemo(()=>h.map(g=>g.key),[h]),p=N.useMemo(()=>Object.fromEntries(d.map(g=>[g.key,g.name??String(g.id)])),[d]),m=["#4fc1ff","#9cdcfe","#7bd389","#f9d85c","#f38ba8","#c586c0"],S=N.useMemo(()=>{const g={},y=new Set(d.map(x=>x.key)),C=x=>{let I=2166136261;for(let E=0;E<x.length;E++)I^=x.charCodeAt(E),I=Math.imul(I,16777619);return I>>>0};return y.forEach(x=>{const I=/^layer-(\d+)$/.exec(x),E=I?Number(I[1]):NaN,A=Number.isFinite(E)?E:C(x);g[x]=m[A%m.length]??"#4fc1ff"}),g},[d]);return{worldDisplays:o,worldLayers:l,layerCount:a,detailTarget:u,trafficItems:c,sortedTraffic:d,topTraffic:h,topKeys:f,keyToLabel:p,keyToColor:S}}function PU(r){const{runtimeClient:e,serverUrl:t,renderer:n,muted:i,snapshot:s}=r,o=N.useRef(null),a=N.useRef(null),l=N.useRef(null),[u,c]=N.useState({audio:[],atlases:[],palettes:[]}),d=N.useCallback(async()=>{const h=o.current,f=a.current;h&&(l.current=t,e.start({serverUrl:t,container:h,displayContainers:f?[{id:255,container:f}]:void 0,renderer:n,inputEnabled:!0,captureInput:!0}).catch(()=>{}))},[n,e,t]);return N.useEffect(()=>{const h=o.current,f=a.current;h&&l.current!==t&&(l.current=t,e.start({serverUrl:t,container:h,displayContainers:f?[{id:255,container:f}]:void 0,renderer:n,inputEnabled:!0,captureInput:!0}).catch(()=>{}))},[n,e,t]),N.useEffect(()=>{e.setMuted(i)},[i,e]),N.useEffect(()=>{c(e.getAssetsSnapshot())},[e,s]),{rendererContainerRef:o,debugDisplay255ContainerRef:a,connect:d,assetsSnapshot:u,setAssetsSnapshot:c}}function BU({connected:r,placement:e,headerHeight:t,frameRect:n,containerRef:i,onTogglePlacement:s,onStartDrag:o,onStartResize:a}){const l=e==="float";return k.jsxs("div",{style:{position:"fixed",left:n.x,top:n.y,width:n.width,height:n.height,zIndex:l?950:1,background:"#1a1a1a",border:"1px solid #3c3c3c",boxShadow:l?"0 8px 24px rgba(0,0,0,0.35)":"none",display:"flex",flexDirection:"column",userSelect:"none"},children:[k.jsxs("div",{style:{height:t,background:"#2d2d2d",borderBottom:"1px solid #3c3c3c",display:"flex",alignItems:"center",justifyContent:"space-between",padding:"0 10px",fontSize:12,color:"#cccccc",cursor:l?"move":"default"},onMouseDown:u=>{l&&o(u.clientX,u.clientY)},children:[k.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[k.jsx("div",{style:{width:8,height:8,borderRadius:4,background:r?"#4fc1ff":"#a0a0a0"}}),k.jsx("div",{children:"Debug View"})]}),k.jsx("button",{onClick:u=>{u.stopPropagation(),s()},style:{height:22,padding:"0 8px",border:"1px solid #3c3c3c",background:"#3c3c3c",color:"#ffffff",cursor:"pointer",fontSize:12},title:l?"Embed into layout":"Float window",children:l?"Embed":"Float"})]}),k.jsx("div",{ref:i,style:{flex:1,backgroundColor:"#0f0f0f",backgroundImage:"linear-gradient(45deg, rgba(255,255,255,0.05) 25%, transparent 25%),linear-gradient(-45deg, rgba(255,255,255,0.05) 25%, transparent 25%),linear-gradient(45deg, transparent 75%, rgba(255,255,255,0.05) 75%),linear-gradient(-45deg, transparent 75%, rgba(255,255,255,0.05) 75%)",backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0",overflow:"hidden",outline:"1px solid rgba(255,255,255,0.06)"}}),l&&k.jsx("div",{onMouseDown:u=>{u.stopPropagation(),a(u.clientX,u.clientY)},style:{position:"absolute",width:14,height:14,right:2,bottom:2,cursor:"nwse-resize",background:"#2d2d2d",border:"1px solid #3c3c3c",borderRadius:2}})]})}const vl=new a5;function zU(){var Cr;const[r,e]=N.useState(()=>{if(typeof window>"u")return"http://localhost:3200";const{protocol:Se,hostname:Re,port:pe}=window.location;return pe==="4173"||pe==="5173"?`${Se}//${Re}:3200`:`${Se}//${Re}${pe?`:${pe}`:""}`}),t=Ys(Se=>Se.lastSnapshot),n=Ys(Se=>Se.connected),[i,s]=N.useState(!1),[o,a]=N.useState("grid"),[l,u]=N.useState(null),[c,d]=N.useState("float"),[h,f]=N.useState({width:0,height:0}),[p,m]=N.useState("embedded"),[S,w]=N.useState("network"),g=28,y={width:220,height:160},C=c==="float",x=24,I={width:220,height:160},E=ay({enabled:C,initialRect:{x:12,y:80,width:360,height:220},minSize:y}),A=ay({enabled:p==="float",initialRect:{x:12,y:360,width:360,height:260},minSize:I}),R=((Cr=t==null?void 0:t.users)==null?void 0:Cr[0])??null,F=p==="float",z=UU(R,vl),P=z.selectedDisplayId,O=z.selectedLayerIds,L=z.lastSelectedLayerId,V=z.focusRect,X=z.focusKey,T=N.useRef(null),{rect:_,size:j}=ly(T),{worldDisplays:G,worldLayers:ee,detailTarget:q,sortedTraffic:K,topTraffic:oe,topKeys:ve,keyToLabel:ge,keyToColor:Ce}=RU({primaryUser:R,selection:z,selectedDisplayId:P,lastSelectedLayerId:L,selectedLayerIds:O}),{tickRate:ct,chartData:dt}=AU({enabled:!0,snapshot:t,topKeys:ve,topTraffic:oe}),{rendererContainerRef:xe,debugDisplay255ContainerRef:et,connect:Ke,assetsSnapshot:qe}=PU({runtimeClient:vl,serverUrl:r,renderer:Df.TerminalGL,muted:i,snapshot:t});N.useEffect(()=>{const Se="/logo_debugger.ico",Re=document.querySelector("link[rel='icon']");if(Re)Re.href=Se;else{const pe=document.createElement("link");pe.rel="icon",pe.href=Se,document.head.appendChild(pe)}},[]),N.useEffect(()=>{const Se=Re=>{const pe=Re.detail;pe&&vl.sendDisplayTransform(pe)};return window.addEventListener("__utsp_debug_display255_rect",Se),()=>window.removeEventListener("__utsp_debug_display255_rect",Se)},[]),N.useEffect(()=>{const Se=document.documentElement.style.overflow,Re=document.body.style.overflow,pe=document.documentElement.style.margin,ne=document.body.style.margin,$e=document.documentElement.style.padding,ht=document.body.style.padding;return document.documentElement.style.overflow="hidden",document.body.style.overflow="hidden",document.documentElement.style.margin="0",document.body.style.margin="0",document.documentElement.style.padding="0",document.body.style.padding="0",()=>{document.documentElement.style.overflow=Se,document.body.style.overflow=Re,document.documentElement.style.margin=pe,document.body.style.margin=ne,document.documentElement.style.padding=$e,document.body.style.padding=ht}},[]);const At=N.useRef(null),{size:wt,rect:Ft}=ly(At);N.useEffect(()=>{const Se=xe.current;if(!Se)return;const Re=new ResizeObserver(pe=>{const ne=pe[0];ne&&f({width:Math.round(ne.contentRect.width),height:Math.round(ne.contentRect.height)})});return Re.observe(Se),()=>Re.disconnect()},[]);const cr=wt.width,tt=wt.height,kt={left:C?E.rect.x:Ft.left,top:C?E.rect.y:Ft.top,width:C?E.rect.width:cr,height:C?E.rect.height:tt},nt=F?A.rect:{x:_.left??0,y:_.top??0,width:j.width||280,height:j.height||260};return k.jsxs("div",{style:{fontFamily:"'Segoe UI', 'Helvetica Neue', sans-serif",background:"#1e1e1e",color:"#cccccc",minHeight:"100vh",margin:0,display:"flex",flexDirection:"column"},children:[k.jsx(g5,{connected:n,serverUrl:r,onServerUrlChange:e,onReconnect:()=>{Ke()}}),k.jsxs("div",{style:{display:"grid",gridTemplateColumns:"240px 1fr 280px",gap:0,padding:0,boxSizing:"border-box",flex:1,minHeight:0,overflow:"hidden"},children:[k.jsx("div",{style:{borderRight:"1px solid #3c3c3c",background:"#252526",display:"flex",flexDirection:"column",minHeight:0},children:k.jsx(p5,{primaryUser:R??null,selectedDisplayId:P,selectedLayerIds:O,onSelectDisplay:z.handleSelectDisplay,onSelectLayer:z.handleSelectLayerDisplay255Only})}),k.jsx(kU,{centerTab:o,setCenterTab:a,centerPanelRef:At,centerSize:wt,worldLayers:ee,worldDisplays:G,selectedLayerIds:O,setVisibleLayers:Se=>vl.setVisibleLayers(Se),selectedDisplayId:P,focusRect:V,focusKey:X,onSelectLayer:z.handleSelectLayer,onSelectDisplay:z.handleSelectDisplay,assetsSnapshot:qe,primaryUser:R,isFloating:C,sortedTraffic:K,topTraffic:oe,chartData:dt,topKeys:ve,keyToLabel:ge,keyToColor:Ce,tickRate:ct,hoveredTrafficKey:l,setHoveredTrafficKey:u}),k.jsxs("div",{style:{borderLeft:"1px solid #3c3c3c",background:"#252526",minHeight:0,display:"flex",flexDirection:"column",overflowY:"auto",overflowX:"hidden"},children:[k.jsx("div",{ref:T,style:{padding:0,borderBottom:"1px solid #3c3c3c",height:260,minHeight:260,width:"100%",boxSizing:"border-box"}}),k.jsx("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"6px 8px",borderBottom:"1px solid #3c3c3c"},children:[{id:"network",label:"Network"},{id:"layer",label:"Selected Layer"}].map(Se=>{const Re=S===Se.id;return k.jsx("button",{onClick:()=>w(Se.id),style:{border:"1px solid #3c3c3c",background:Re?"#1e1e1e":"#2d2d2d",color:"#cccccc",padding:"4px 10px",cursor:"pointer",fontSize:12,borderRadius:6},children:Se.label},Se.id)})}),k.jsx("div",{style:{flex:1,minHeight:0},children:S==="network"?k.jsx(MU,{primaryUser:R,tickRate:ct,snapshot:t,assetsSnapshot:qe}):k.jsx("div",{style:{height:"100%",minHeight:0},children:k.jsx(d5,{detailTarget:q})})})]})]}),k.jsx(l5,{connected:n,muted:i,rendererPlacement:c,centerTab:o,frameRect:kt,rendererHeaderHeight:g,rendererContentSize:h,rendererContainerRef:xe,onTogglePlacement:()=>{d(Se=>{const Re=Se==="float"?"embedded":"float";return Re==="embedded"&&a("renderer"),Re})},onToggleMuted:()=>{s(Se=>!Se)},onStartDrag:(Se,Re)=>{E.startDrag(Se,Re)},onStartResize:(Se,Re)=>{E.startResize(Se,Re)}}),k.jsx(BU,{connected:n,placement:p,headerHeight:x,frameRect:nt,containerRef:et,onTogglePlacement:()=>m(Se=>Se==="float"?"embedded":"float"),onStartDrag:A.startDrag,onStartResize:A.startResize})]})}const OC=document.getElementById("root");if(!OC)throw new Error("Root container not found");td.createRoot(OC).render(k.jsx(Cy.StrictMode,{children:k.jsx(zU,{})}));
|
|
273
|
+
*/var zu=N,WE=YE;function GE(r,e){return r===e&&(r!==0||1/r===1/e)||r!==r&&e!==e}var XE=typeof Object.is=="function"?Object.is:GE,KE=WE.useSyncExternalStore,ZE=zu.useRef,qE=zu.useEffect,QE=zu.useMemo,JE=zu.useDebugValue;Hw.useSyncExternalStoreWithSelector=function(r,e,t,n,i){var s=ZE(null);if(s.current===null){var o={hasValue:!1,value:null};s.current=o}else o=s.current;s=QE(function(){function l(f){if(!u){if(u=!0,c=f,f=n(f),i!==void 0&&o.hasValue){var p=o.value;if(i(p,f))return d=p}return d=f}if(p=d,XE(c,f))return p;var m=n(f);return i!==void 0&&i(p,m)?(c=f,p):(c=f,d=m)}var u=!1,c,d,h=t===void 0?null:t;return[function(){return l(e())},h===null?void 0:function(){return l(h())}]},[e,t,n,i]);var a=KE(r,s[0],s[1]);return qE(function(){o.hasValue=!0,o.value=a},[a]),JE(a),a};Vw.exports=Hw;var eM=Vw.exports;const tM=uy(eM),Ww={},{useDebugValue:rM}=Cy,{useSyncExternalStoreWithSelector:nM}=tM;let hm=!1;const iM=r=>r;function sM(r,e=iM,t){(Ww?"production":void 0)!=="production"&&t&&!hm&&(console.warn("[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937"),hm=!0);const n=nM(r.subscribe,r.getState,r.getServerState||r.getInitialState,e,t);return rM(n),n}const fm=r=>{(Ww?"production":void 0)!=="production"&&typeof r!="function"&&console.warn("[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`.");const e=typeof r=="function"?DE(r):r,t=(n,i)=>sM(e,n,i);return Object.assign(t,e),t},oM=r=>r?fm(r):fm,Ys=oM(r=>({connected:!1,lastSnapshot:void 0,setConnected:e=>r({connected:e}),setSnapshot:e=>r({lastSnapshot:e})}));class aM{constructor(){Wi(this,"runtime",null);Wi(this,"layerTraffic",{});Wi(this,"miscTraffic",{});Wi(this,"displayTraffic",{});Wi(this,"visibleLayerIds",null);Wi(this,"visibleLayerIdsDisplay255",null)}setMuted(e){var n;const t=(n=this.runtime)==null?void 0:n.getAudioManager();t&&t.setMasterVolume(e?0:1)}setVisibleLayers(e){var i;this.visibleLayerIds=e&&e.length>0?[...e]:null;const t=(i=this.runtime)==null?void 0:i.getRendererManager(0);if(!t)return;if(this.visibleLayerIds==null){t.setLayerFilter(null);return}const n=new Set(this.visibleLayerIds);t.setLayerFilter(s=>n.has(s.getId()))}setVisibleLayersDisplay255(e){var i;this.visibleLayerIdsDisplay255=e&&e.length>0?[...e]:null;const t=(i=this.runtime)==null?void 0:i.getRendererManager(255);if(!t)return;if(this.visibleLayerIdsDisplay255==null){t.setLayerFilter(null);return}const n=new Set(this.visibleLayerIdsDisplay255);t.setLayerFilter(s=>n.has(s.getId()))}sendDisplayTransform(e){var t;(t=this.runtime)==null||t.sendBridge("__debug_display_255",{origin:{x:e.x,y:e.y},size:{x:e.width,y:e.height}})}async start(e){Ys.getState().setConnected(!1),this.runtime&&this.destroy();const t={mode:"socketio",socketio:{url:e.serverUrl},container:e.container,displayContainers:e.displayContainers,renderer:e.renderer??Df.TerminalGL,inputEnabled:e.inputEnabled??!0,captureInput:e.captureInput??!0,debug:!1,autoplay:!1};try{if(this.runtime=new TE(t),this.visibleLayerIds&&this.visibleLayerIds.length>0){const n=new Set(this.visibleLayerIds);this.runtime.getRendererManager().setLayerFilter(i=>n.has(i.getId()))}if(this.visibleLayerIdsDisplay255&&this.visibleLayerIdsDisplay255.length>0){const n=new Set(this.visibleLayerIdsDisplay255);this.runtime.getRendererManager(255).setLayerFilter(i=>n.has(i.getId()))}this.runtime.onBridge("__debug_meta",n=>{var i,s,o,a;try{let l=n;if(this.runtime&&n&&typeof n=="object"){try{this.layerTraffic=this.runtime.getLayerTrafficStats()}catch{this.layerTraffic={}}try{this.miscTraffic=((s=(i=this.runtime).getMiscTrafficStats)==null?void 0:s.call(i))??{}}catch{this.miscTraffic={}}try{this.displayTraffic=((a=(o=this.runtime).getDisplayTrafficStats)==null?void 0:a.call(o))??{}}catch{this.displayTraffic={}}const u=n;if(u.users&&Array.isArray(u.users))for(const c of u.users)c.layers&&Array.isArray(c.layers)&&(c.layers=c.layers.map(d=>{const h=this.layerTraffic[d.id];return h?{...d,bytesTotal:h.total,bytesPerSec1s:h.bytesPerSec1s}:d})),c.miscTraffic=this.miscTraffic,c.displayTraffic=this.displayTraffic;l=u}Ys.getState().setConnected(!0),Ys.getState().setSnapshot(l)}catch{}}),await this.runtime.start(),this.runtime.sendBridge("__debug_auth",{})}catch(n){throw Ys.getState().setConnected(!1),n}}destroy(){var e,t,n,i;if(this.runtime){try{(t=(e=this.runtime.getAudioManager())==null?void 0:e.stopAll)==null||t.call(e)}catch{}try{(i=(n=this.runtime).destroy)==null||i.call(n)}catch{}this.runtime=null}}getAssetsSnapshot(){var u;const e=this.runtime;if(!e)return{audio:[],atlases:[],palettes:[]};const t=e.getAudioManager(),n=(u=t==null?void 0:t.getSoundBank)==null?void 0:u.call(t),i=n?n.getAll().map(c=>({id:c.soundId,name:c.name,duration:c.duration,source:c.metadata.source,originalSize:c.metadata.originalSize,originalUrl:c.metadata.originalUrl})):[],s=e.getCore(),o=s.getImageFontRegistry(),a=o.getAllFonts().map(c=>({id:c.getFontId(),name:o.getFontName(c.getFontId())??`Font ${c.getFontId()}`,glyphSize:`${c.getGlyphWidth()}×${c.getGlyphHeight()}`,cellSize:`${c.getCellWidth()}×${c.getCellHeight()}`,atlasBlocks:c.getAtlasBlocks(),maxCharCode:c.getMaxCharCode()}));a.length===0&&a.push({id:0,name:"Default CP437 (builtin)",glyphSize:"8×8",cellSize:"8×8",atlasBlocks:1,maxCharCode:255});const l=[];for(let c=0;c<256;c++){if(!s.hasPaletteSlot(c))continue;const d=s.getPaletteFromSlot(c);l.push({slotId:c,colors:(d==null?void 0:d.size)??0})}return{audio:i,atlases:a,palettes:l}}}function lM({connected:r,muted:e,rendererPlacement:t,centerTab:n,frameRect:i,rendererHeaderHeight:s,rendererContentSize:o,rendererContainerRef:a,onTogglePlacement:l,onToggleMuted:u,onStartDrag:c,onStartResize:d}){const h=t==="float";return k.jsxs("div",{style:{position:"fixed",left:i.left,top:i.top,width:i.width,height:i.height,zIndex:h?1e3:10,background:"#1a1a1a",border:"1px solid #3c3c3c",boxShadow:h?"0 8px 24px rgba(0,0,0,0.45)":"none",userSelect:"none",pointerEvents:h||n==="renderer"?"auto":"none",display:h||n==="renderer"?"block":"none"},children:[k.jsxs("div",{style:{height:s,background:"#2d2d2d",borderBottom:"1px solid #3c3c3c",display:"flex",alignItems:"center",justifyContent:"space-between",padding:"0 10px",cursor:h?"move":"default",fontSize:12,color:"#cccccc"},onMouseDown:f=>{h&&c(f.clientX,f.clientY)},children:[k.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[k.jsx("div",{style:{width:8,height:8,borderRadius:4,background:r?"#4fc1ff":"#a0a0a0"}}),k.jsx("div",{children:"UTSP Client"}),k.jsxs("div",{style:{color:"#888888",fontSize:11},children:[o.width,"×",o.height," px"]})]}),k.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,cursor:"default"},onMouseDown:f=>f.stopPropagation(),children:[k.jsx("button",{onClick:f=>{f.stopPropagation(),l()},style:{height:24,padding:"0 8px",border:"1px solid #3c3c3c",background:"#3c3c3c",color:"#ffffff",cursor:"pointer",fontSize:12},title:h?"Embed into layout":"Float window",children:h?"Embed":"Float"}),k.jsx("button",{onClick:f=>{f.stopPropagation(),u()},style:{width:28,height:24,border:"1px solid #3c3c3c",background:e?"#3c3c3c":"#0e639c",color:"#ffffff",cursor:"pointer",fontSize:12,display:"flex",alignItems:"center",justifyContent:"center",padding:0},title:e?"Unmute audio":"Mute audio",children:k.jsxs("svg",{width:14,height:14,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",children:[k.jsx("path",{d:"M4 9v6h4l5 4V5L8 9H4z"}),!e&&k.jsx("path",{d:"M16 9a5 5 0 0 1 0 6"}),!e&&k.jsx("path",{d:"M18 5a9 9 0 0 1 0 14"}),e&&k.jsx("line",{x1:"17",y1:"9",x2:"21",y2:"13"}),e&&k.jsx("line",{x1:"21",y1:"9",x2:"17",y2:"13"})]})})]})]}),k.jsx("div",{ref:a,style:{position:"absolute",top:s,left:0,right:0,bottom:0,background:"#0d0d0d",overflow:"hidden",opacity:1,pointerEvents:"auto",outline:"1px solid #3c3c3c"},tabIndex:0,onMouseDown:f=>{var p;f.stopPropagation(),(p=a.current)==null||p.focus()}}),h&&k.jsx("div",{onMouseDown:f=>{f.stopPropagation(),d(f.clientX,f.clientY)},style:{position:"absolute",width:14,height:14,right:2,bottom:2,cursor:"nwse-resize",background:"#2d2d2d",border:"1px solid #3c3c3c",borderRadius:2}})]})}function Kr(r){if(r==null||Number.isNaN(r))return"—";const e=["B","KB","MB","GB"];let t=r,n=0;for(;t>=1024&&n<e.length-1;)t/=1024,n++;return`${t.toFixed(t>=10?0:1)} ${e[n]}`}function uM(r){return`${r.toFixed(2)} s`}const cM={muted:{background:"#1a1a1a",border:"#2f2f2f",color:"#cfcfcf"},info:{background:"#1a2531",border:"#2f4f6b",color:"#8dc8ff"},success:{background:"#182420",border:"#2b4d37",color:"#7dd19c"},warning:{background:"#292114",border:"#514021",color:"#eac172"}};function Lo({label:r,tone:e="muted"}){const t=cM[e];return k.jsx("span",{style:{display:"inline-flex",alignItems:"center",padding:"1px 6px",borderRadius:6,fontSize:10,fontWeight:600,letterSpacing:"0.05px",background:t.background,border:`1px solid ${t.border}`,color:t.color},children:r})}function pm({children:r}){return k.jsx("div",{style:{border:"1px solid #2a2a2a",borderRadius:6,background:"#161616"},children:r})}function Xn({label:r,value:e,divider:t}){return k.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"6px 8px",fontSize:11,color:"#d6d6d6",borderBottom:t?"1px solid #222":"none"},children:[k.jsx("span",{style:{color:"#9a9a9a",letterSpacing:"0.05px"},children:r}),k.jsx("span",{style:{fontWeight:600,textAlign:"right"},children:e})]})}function dM({detailTarget:r}){return k.jsxs("div",{style:{background:"transparent",padding:0,minHeight:0,display:"flex",flexDirection:"column"},children:[k.jsx("div",{style:{padding:"8px 12px",borderBottom:"1px solid #3c3c3c"},children:k.jsx("div",{style:{fontSize:11,color:"#bbbbbb",textTransform:"uppercase",letterSpacing:"0.5px"},children:"Properties"})}),k.jsxs("div",{style:{padding:"8px 12px",flex:1,overflowY:"auto"},children:[!r&&k.jsx("div",{style:{fontSize:12,color:"#858585"},children:"Hover or select an item"}),(r==null?void 0:r.type)==="display"&&k.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[k.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:6,padding:"2px 0"},children:[k.jsxs("div",{style:{color:"#e7f3ff",fontWeight:600},children:["Display ",r.item.id]}),k.jsx(Lo,{label:"Active",tone:"info"})]}),k.jsxs(pm,{children:[k.jsx(Xn,{label:"Origin",value:`(${r.item.origin.x}, ${r.item.origin.y})`,divider:!0}),k.jsx(Xn,{label:"Size",value:`${r.item.size.x} × ${r.item.size.y}`})]})]}),(r==null?void 0:r.type)==="layer"&&k.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[k.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:6,padding:"2px 0"},children:[k.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[k.jsx("div",{style:{color:"#e7f3ff",fontWeight:700},children:r.item.name??"Layer"}),k.jsx(Lo,{label:`#${r.item.id}`,tone:"info"})]}),k.jsx(Lo,{label:`z ${r.item.z}`,tone:"muted"})]}),k.jsxs(pm,{children:[k.jsx(Xn,{label:"Mode",value:r.item.charCodeMode,divider:!0}),k.jsx(Xn,{label:"Orders",value:r.item.ordersCount,divider:!0}),k.jsx(Xn,{label:"Size",value:`${r.item.width} × ${r.item.height}`,divider:!0}),k.jsx(Xn,{label:"Origin",value:`(${r.item.origin.x}, ${r.item.origin.y})`,divider:!0}),k.jsx(Xn,{label:"Channel",value:r.item.mustBeReliable?k.jsx(Lo,{label:"Reliable",tone:"success"}):k.jsx(Lo,{label:"Volatile",tone:"muted"}),divider:!0}),r.item.bytesTotal!==void 0&&k.jsxs(k.Fragment,{children:[k.jsx(Xn,{label:"Total",value:Kr(r.item.bytesTotal),divider:!0}),k.jsx(Xn,{label:"Throughput",value:`${Kr(r.item.bytesPerSec1s)} /s`})]})]})]})]})]})}function gm({isSelected:r,onClick:e,children:t}){return k.jsx("div",{onClick:e,style:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"2px 12px",cursor:"pointer",fontSize:12,background:r?"#094771":"transparent",color:r?"#ffffff":"#cccccc",userSelect:"none"},children:t})}function hM(r){return r<1e3?`${r} B`:r<1e6?`${(r/1e3).toFixed(2)} KB`:`${(r/1e6).toFixed(2)} MB`}const Ms={id:"1fr",net:"90px",gap:4};function fM({displays:r,layers:e,selectedDisplayId:t,selectedLayerIds:n,onSelectDisplay:i,onSelectLayer:s}){const o=new Set(n),[a,l]=N.useState("id"),[u,c]=N.useState("asc"),d=N.useMemo(()=>{const f=[...e];return f.sort((p,m)=>{const S=a==="id"?p.id:p.bytesTotal??0,w=a==="id"?m.id:m.bytesTotal??0,g=S===w?0:S<w?-1:1;return u==="asc"?g:-g}),f},[e,u,a]),h=f=>{l(p=>p===f?(c(m=>m==="asc"?"desc":"asc"),p):(c("asc"),f))};return k.jsxs("div",{style:{padding:"4px 0",overflowY:"auto",flex:1,display:"flex",flexDirection:"column",gap:0,userSelect:"none"},children:[r.length===0&&e.length===0&&k.jsx("div",{style:{fontSize:12,color:"#858585",padding:"4px 12px"},children:"No items"}),r.length>0&&k.jsxs(k.Fragment,{children:[k.jsx("div",{style:{fontSize:10,color:"#858585",padding:"6px 12px 2px",textTransform:"uppercase"},children:"Displays"}),r.map(f=>k.jsxs(gm,{isSelected:t===f.id,onClick:()=>i(f.id),children:[k.jsxs("span",{children:["Display ",f.id,f.id===255?" (debug)":""]}),k.jsxs("span",{style:{color:"#858585",fontSize:11},children:[f.size.x,"×",f.size.y]})]},`display-${f.id}`))]}),e.length>0&&k.jsxs(k.Fragment,{children:[k.jsx("div",{style:{fontSize:10,color:"#858585",padding:"8px 12px 4px",textTransform:"uppercase"},children:"Layers"}),k.jsxs("div",{style:{display:"grid",gridTemplateColumns:`${Ms.id} ${Ms.net}`,alignItems:"center",columnGap:Ms.gap,padding:"0 12px 4px",fontSize:11,color:"#858585",userSelect:"none"},children:[k.jsxs("button",{type:"button",onClick:()=>h("id"),style:{all:"unset",cursor:"pointer",display:"inline-flex",alignItems:"center",gap:4,color:"#858585",justifySelf:"start",whiteSpace:"nowrap"},children:["ID",k.jsx("span",{style:{fontSize:10,opacity:a==="id"?1:.3},children:a==="id"?u==="asc"?"▲":"▼":"▲"})]}),k.jsxs("button",{type:"button",onClick:()=>h("net"),style:{all:"unset",cursor:"pointer",display:"inline-flex",alignItems:"center",gap:4,color:"#858585",justifySelf:"end",whiteSpace:"nowrap"},children:["Network",k.jsx("span",{style:{fontSize:10,opacity:a==="net"?1:.3},children:a==="net"?u==="asc"?"▲":"▼":"▲"})]})]}),d.map(f=>{const p=o.has(f.id),m=f.name?`${f.id}:${f.name}`:String(f.id);return k.jsx(gm,{isSelected:p,onClick:S=>s(f.id,S),children:k.jsxs("span",{style:{display:"grid",gridTemplateColumns:`${Ms.id} ${Ms.net}`,alignItems:"center",columnGap:Ms.gap,width:"100%"},children:[k.jsx("span",{style:{display:"inline-flex",alignItems:"center",gap:6},children:k.jsx("span",{style:{color:"inherit"},children:m})}),k.jsx("span",{style:{color:"#858585",fontSize:11,textAlign:"right",whiteSpace:"nowrap"},children:f.bytesTotal!==void 0&&hM(f.bytesTotal)})]})},`layer-${f.id}-${p}`)})]})]})}function pM({primaryUser:r,selectedDisplayId:e,selectedLayerIds:t,onSelectDisplay:n,onSelectLayer:i}){var s;return k.jsxs("div",{style:{borderRight:"1px solid #3c3c3c",background:"#252526",display:"flex",flexDirection:"column",minHeight:0},children:[k.jsx("div",{style:{padding:"8px 12px",borderBottom:"1px solid #3c3c3c"},children:k.jsx("div",{style:{fontSize:11,color:"#bbbbbb",textTransform:"uppercase",letterSpacing:"0.5px"},children:"Explorer"})}),k.jsxs("div",{style:{padding:"4px 0",overflowY:"auto",flex:1,display:"flex",flexDirection:"column",gap:0,userSelect:"none"},children:[!r&&k.jsx("div",{style:{fontSize:12,color:"#858585",padding:"4px 12px"},children:"No items"}),r&&k.jsx(fM,{displays:(s=r.displays)==null?void 0:s.filter(o=>o.id!==255),layers:r.layers,selectedDisplayId:e,selectedLayerIds:t,onSelectDisplay:n,onSelectLayer:i})]})]})}function gM({connected:r,serverUrl:e,onServerUrlChange:t,onReconnect:n}){return k.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",height:34,padding:"0 10px",borderBottom:"1px solid #3c3c3c",background:"#252526"},children:[k.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[k.jsx("img",{src:"/logo_debugger.png",alt:"UTSP logo",style:{width:18,height:18,objectFit:"contain"}}),k.jsx("div",{style:{fontSize:13,color:"#cccccc",fontWeight:600},children:"UTSP Visual Debugger"})]}),k.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[k.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,fontSize:11,color:r?"#9adcff":"#bbbbbb"},children:[k.jsx("span",{style:{width:8,height:8,borderRadius:4,background:r?"#4fc1ff":"#a0a0a0",display:"inline-block"}}),k.jsx("span",{children:r?"Connected":"Disconnected"})]}),k.jsx("input",{value:e,onChange:i=>t(i.target.value),style:{width:220,padding:"4px 8px",borderRadius:0,border:"1px solid #3c3c3c",background:"#3c3c3c",color:"#cccccc",fontSize:12},placeholder:"http://localhost:3000"}),k.jsx("button",{onClick:n,style:{padding:"4px 10px",borderRadius:0,border:"1px solid #0e639c",background:"#0e639c",color:"#ffffff",fontWeight:500,cursor:"pointer",fontSize:12},children:"Reconnect"})]})]})}function Yc({title:r,headers:e,rows:t,emptyLabel:n}){const i=t.length>0;return k.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[k.jsx("div",{style:{fontSize:12,color:"#bbbbbb"},children:r}),k.jsxs("div",{style:{border:"1px solid #3c3c3c",borderRadius:2,overflow:"hidden",background:"#1e1e1e"},children:[k.jsx("div",{style:{display:"grid",gridTemplateColumns:`repeat(${e.length}, minmax(0, 1fr))`,gap:0,background:"#252526",borderBottom:"1px solid #3c3c3c",fontSize:11,color:"#aaaaaa"},children:e.map(s=>k.jsx("div",{style:{padding:"6px 8px",whiteSpace:"nowrap"},children:s},s))}),!i&&k.jsx("div",{style:{padding:"8px 10px",color:"#858585",fontSize:12},children:n}),i&&k.jsx("div",{children:t.map((s,o)=>k.jsx("div",{style:{display:"grid",gridTemplateColumns:`repeat(${e.length}, minmax(0, 1fr))`,gap:0,borderTop:o===0?"none":"1px solid #2e2e2e",fontSize:12,color:"#cccccc"},children:s.map((a,l)=>k.jsx("div",{style:{padding:"6px 8px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:a,children:a},l))},`${r}-${o}`))})]})]})}function mM({assetsSnapshot:r}){return k.jsxs("div",{style:{height:"100%",overflow:"auto",padding:"8px 10px",display:"flex",flexDirection:"column",gap:12,color:"#cccccc",fontSize:12},children:[k.jsx(Yc,{title:"Audio",emptyLabel:"No audio loaded",headers:["Name","Source","Duration","Size","URL"],rows:r.audio.map(e=>[e.name,e.source,uM(e.duration),Kr(e.originalSize),e.originalUrl??"—"])}),k.jsx(Yc,{title:"Atlas",emptyLabel:"No atlas",headers:["ID","Name","Glyph","Cell","Blocks","Max char"],rows:r.atlases.map(e=>[String(e.id),e.name,e.glyphSize,e.cellSize,String(e.atlasBlocks),String(e.maxCharCode)])}),k.jsx(Yc,{title:"Palettes",emptyLabel:"No palette",headers:["Slot","Colors"],rows:r.palettes.map(e=>[String(e.slotId),String(e.colors)])})]})}const yM=!0,Gt="u-",vM="uplot",wM=Gt+"hz",CM=Gt+"vt",bM=Gt+"title",SM=Gt+"wrap",xM=Gt+"under",IM=Gt+"over",kM=Gt+"axis",Ji=Gt+"off",EM=Gt+"select",MM=Gt+"cursor-x",UM=Gt+"cursor-y",AM=Gt+"cursor-pt",TM=Gt+"legend",RM=Gt+"live",PM=Gt+"inline",BM=Gt+"series",zM=Gt+"marker",mm=Gt+"label",DM=Gt+"value",Go="width",Xo="height",_o="top",ym="bottom",Us="left",Wc="right",Of="#000",vm=Of+"0",Gc="mousemove",wm="mousedown",Xc="mouseup",Cm="mouseenter",bm="mouseleave",Sm="dblclick",OM="resize",FM="scroll",xm="change",uu="dppxchange",Ff="--",yo=typeof window<"u",gh=yo?document:null,Js=yo?window:null,LM=yo?navigator:null;let je,hl;function mh(){let r=devicePixelRatio;je!=r&&(je=r,hl&&vh(xm,hl,mh),hl=matchMedia(`(min-resolution: ${je-.001}dppx) and (max-resolution: ${je+.001}dppx)`),ss(xm,hl,mh),Js.dispatchEvent(new CustomEvent(uu)))}function Wr(r,e){if(e!=null){let t=r.classList;!t.contains(e)&&t.add(e)}}function yh(r,e){let t=r.classList;t.contains(e)&&t.remove(e)}function lt(r,e,t){r.style[e]=t+"px"}function Cn(r,e,t,n){let i=gh.createElement(r);return e!=null&&Wr(i,e),t!=null&&t.insertBefore(i,n),i}function on(r,e){return Cn("div",r,e)}const Im=new WeakMap;function _n(r,e,t,n,i){let s="translate("+e+"px,"+t+"px)",o=Im.get(r);s!=o&&(r.style.transform=s,Im.set(r,s),e<0||t<0||e>n||t>i?Wr(r,Ji):yh(r,Ji))}const km=new WeakMap;function Em(r,e,t){let n=e+t,i=km.get(r);n!=i&&(km.set(r,n),r.style.background=e,r.style.borderColor=t)}const Mm=new WeakMap;function Um(r,e,t,n){let i=e+""+t,s=Mm.get(r);i!=s&&(Mm.set(r,i),r.style.height=t+"px",r.style.width=e+"px",r.style.marginLeft=n?-e/2+"px":0,r.style.marginTop=n?-t/2+"px":0)}const Lf={passive:!0},_M={...Lf,capture:!0};function ss(r,e,t,n){e.addEventListener(r,t,n?_M:Lf)}function vh(r,e,t,n){e.removeEventListener(r,t,Lf)}yo&&mh();function In(r,e,t,n){let i;t=t||0,n=n||e.length-1;let s=n<=2147483647;for(;n-t>1;)i=s?t+n>>1:Qr((t+n)/2),e[i]<r?t=i:n=i;return r-e[t]<=e[n]-r?t:n}function Gw(r){return(t,n,i)=>{let s=-1,o=-1;for(let a=n;a<=i;a++)if(r(t[a])){s=a;break}for(let a=i;a>=n;a--)if(r(t[a])){o=a;break}return[s,o]}}const Xw=r=>r!=null,Kw=r=>r!=null&&r>0,Du=Gw(Xw),$M=Gw(Kw);function NM(r,e,t,n=0,i=!1){let s=i?$M:Du,o=i?Kw:Xw;[e,t]=s(r,e,t);let a=r[e],l=r[e];if(e>-1)if(n==1)a=r[e],l=r[t];else if(n==-1)a=r[t],l=r[e];else for(let u=e;u<=t;u++){let c=r[u];o(c)&&(c<a?a=c:c>l&&(l=c))}return[a??Qe,l??-Qe]}function Ou(r,e,t,n){let i=Rm(r),s=Rm(e);r==e&&(i==-1?(r*=t,e/=t):(r/=t,e*=t));let o=t==10?ei:Zw,a=i==1?Qr:an,l=s==1?an:Qr,u=a(o(jt(r))),c=l(o(jt(e))),d=lo(t,u),h=lo(t,c);return t==10&&(u<0&&(d=Je(d,-u)),c<0&&(h=Je(h,-c))),n||t==2?(r=d*i,e=h*s):(r=eC(r,d),e=Fu(e,h)),[r,e]}function _f(r,e,t,n){let i=Ou(r,e,t,n);return r==0&&(i[0]=0),e==0&&(i[1]=0),i}const $f=.1,Am={mode:3,pad:$f},ca={pad:0,soft:null,mode:0},VM={min:ca,max:ca};function cu(r,e,t,n){return Lu(t)?Tm(r,e,t):(ca.pad=t,ca.soft=n?0:null,ca.mode=n?3:0,Tm(r,e,VM))}function _e(r,e){return r??e}function HM(r,e,t){for(e=_e(e,0),t=_e(t,r.length-1);e<=t;){if(r[e]!=null)return!0;e++}return!1}function Tm(r,e,t){let n=t.min,i=t.max,s=_e(n.pad,0),o=_e(i.pad,0),a=_e(n.hard,-Qe),l=_e(i.hard,Qe),u=_e(n.soft,Qe),c=_e(i.soft,-Qe),d=_e(n.mode,0),h=_e(i.mode,0),f=e-r,p=ei(f),m=Mr(jt(r),jt(e)),S=ei(m),w=jt(S-p);(f<1e-24||w>10)&&(f=0,(r==0||e==0)&&(f=1e-24,d==2&&u!=Qe&&(s=0),h==2&&c!=-Qe&&(o=0)));let g=f||m||1e3,y=ei(g),C=lo(10,Qr(y)),x=g*(f==0?r==0?.1:1:s),I=Je(eC(r-x,C/10),24),E=r>=u&&(d==1||d==3&&I<=u||d==2&&I>=u)?u:Qe,A=Mr(a,I<E&&r>=E?E:En(E,I)),R=g*(f==0?e==0?.1:1:o),F=Je(Fu(e+R,C/10),24),z=e<=c&&(h==1||h==3&&F>=c||h==2&&F<=c)?c:-Qe,P=En(l,F>z&&e<=z?z:Mr(z,F));return A==P&&A==0&&(P=100),[A,P]}const jM=new Intl.NumberFormat(yo?LM.language:"en-US"),Nf=r=>jM.format(r),rn=Math,zl=rn.PI,jt=rn.abs,Qr=rn.floor,$t=rn.round,an=rn.ceil,En=rn.min,Mr=rn.max,lo=rn.pow,Rm=rn.sign,ei=rn.log10,Zw=rn.log2,YM=(r,e=1)=>rn.sinh(r)*e,Kc=(r,e=1)=>rn.asinh(r/e),Qe=1/0;function Pm(r){return(ei((r^r>>31)-(r>>31))|0)+1}function wh(r,e,t){return En(Mr(r,e),t)}function qw(r){return typeof r=="function"}function Pe(r){return qw(r)?r:()=>r}const WM=()=>{},Qw=r=>r,Jw=(r,e)=>e,GM=r=>null,Bm=r=>!0,zm=(r,e)=>r==e,XM=/\.\d*?(?=9{6,}|0{6,})/gm,ds=r=>{if(rC(r)||zi.has(r))return r;const e=`${r}`,t=e.match(XM);if(t==null)return r;let n=t[0].length-1;if(e.indexOf("e-")!=-1){let[i,s]=e.split("e");return+`${ds(i)}e${s}`}return Je(r,n)};function qi(r,e){return ds(Je(ds(r/e))*e)}function Fu(r,e){return ds(an(ds(r/e))*e)}function eC(r,e){return ds(Qr(ds(r/e))*e)}function Je(r,e=0){if(rC(r))return r;let t=10**e,n=r*t*(1+Number.EPSILON);return $t(n)/t}const zi=new Map;function tC(r){return((""+r).split(".")[1]||"").length}function Ta(r,e,t,n){let i=[],s=n.map(tC);for(let o=e;o<t;o++){let a=jt(o),l=Je(lo(r,o),a);for(let u=0;u<n.length;u++){let c=r==10?+`${n[u]}e${o}`:n[u]*l,d=(o>=0?0:a)+(o>=s[u]?0:s[u]),h=r==10?c:Je(c,d);i.push(h),zi.set(h,d)}}return i}const da={},Vf=[],uo=[null,null],mi=Array.isArray,rC=Number.isInteger,KM=r=>r===void 0;function Dm(r){return typeof r=="string"}function Lu(r){let e=!1;if(r!=null){let t=r.constructor;e=t==null||t==Object}return e}function ZM(r){return r!=null&&typeof r=="object"}const qM=Object.getPrototypeOf(Uint8Array),nC="__proto__";function co(r,e=Lu){let t;if(mi(r)){let n=r.find(i=>i!=null);if(mi(n)||e(n)){t=Array(r.length);for(let i=0;i<r.length;i++)t[i]=co(r[i],e)}else t=r.slice()}else if(r instanceof qM)t=r.slice();else if(e(r)){t={};for(let n in r)n!=nC&&(t[n]=co(r[n],e))}else t=r;return t}function zt(r){let e=arguments;for(let t=1;t<e.length;t++){let n=e[t];for(let i in n)i!=nC&&(Lu(r[i])?zt(r[i],co(n[i])):r[i]=co(n[i]))}return r}const QM=0,JM=1,e5=2;function t5(r,e,t){for(let n=0,i,s=-1;n<e.length;n++){let o=e[n];if(o>s){for(i=o-1;i>=0&&r[i]==null;)r[i--]=null;for(i=o+1;i<t&&r[i]==null;)r[s=i++]=null}}}function r5(r,e){if(s5(r)){let o=r[0].slice();for(let a=1;a<r.length;a++)o.push(...r[a].slice(1));return o5(o[0])||(o=i5(o)),o}let t=new Set;for(let o=0;o<r.length;o++){let l=r[o][0],u=l.length;for(let c=0;c<u;c++)t.add(l[c])}let n=[Array.from(t).sort((o,a)=>o-a)],i=n[0].length,s=new Map;for(let o=0;o<i;o++)s.set(n[0][o],o);for(let o=0;o<r.length;o++){let a=r[o],l=a[0];for(let u=1;u<a.length;u++){let c=a[u],d=Array(i).fill(void 0),h=e?e[o][u]:JM,f=[];for(let p=0;p<c.length;p++){let m=c[p],S=s.get(l[p]);m===null?h!=QM&&(d[S]=m,h==e5&&f.push(S)):d[S]=m}t5(d,f,i),n.push(d)}}return n}const n5=typeof queueMicrotask>"u"?r=>Promise.resolve().then(r):queueMicrotask;function i5(r){let e=r[0],t=e.length,n=Array(t);for(let s=0;s<n.length;s++)n[s]=s;n.sort((s,o)=>e[s]-e[o]);let i=[];for(let s=0;s<r.length;s++){let o=r[s],a=Array(t);for(let l=0;l<t;l++)a[l]=o[n[l]];i.push(a)}return i}function s5(r){let e=r[0][0],t=e.length;for(let n=1;n<r.length;n++){let i=r[n][0];if(i.length!=t)return!1;if(i!=e){for(let s=0;s<t;s++)if(i[s]!=e[s])return!1}}return!0}function o5(r,e=100){const t=r.length;if(t<=1)return!0;let n=0,i=t-1;for(;n<=i&&r[n]==null;)n++;for(;i>=n&&r[i]==null;)i--;if(i<=n)return!0;const s=Mr(1,Qr((i-n+1)/e));for(let o=r[n],a=n+s;a<=i;a+=s){const l=r[a];if(l!=null){if(l<=o)return!1;o=l}}return!0}const iC=["January","February","March","April","May","June","July","August","September","October","November","December"],sC=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function oC(r){return r.slice(0,3)}const a5=sC.map(oC),l5=iC.map(oC),u5={MMMM:iC,MMM:l5,WWWW:sC,WWW:a5};function $o(r){return(r<10?"0":"")+r}function c5(r){return(r<10?"00":r<100?"0":"")+r}const d5={YYYY:r=>r.getFullYear(),YY:r=>(r.getFullYear()+"").slice(2),MMMM:(r,e)=>e.MMMM[r.getMonth()],MMM:(r,e)=>e.MMM[r.getMonth()],MM:r=>$o(r.getMonth()+1),M:r=>r.getMonth()+1,DD:r=>$o(r.getDate()),D:r=>r.getDate(),WWWW:(r,e)=>e.WWWW[r.getDay()],WWW:(r,e)=>e.WWW[r.getDay()],HH:r=>$o(r.getHours()),H:r=>r.getHours(),h:r=>{let e=r.getHours();return e==0?12:e>12?e-12:e},AA:r=>r.getHours()>=12?"PM":"AM",aa:r=>r.getHours()>=12?"pm":"am",a:r=>r.getHours()>=12?"p":"a",mm:r=>$o(r.getMinutes()),m:r=>r.getMinutes(),ss:r=>$o(r.getSeconds()),s:r=>r.getSeconds(),fff:r=>c5(r.getMilliseconds())};function Hf(r,e){e=e||u5;let t=[],n=/\{([a-z]+)\}|[^{]+/gi,i;for(;i=n.exec(r);)t.push(i[0][0]=="{"?d5[i[1]]:i[0]);return s=>{let o="";for(let a=0;a<t.length;a++)o+=typeof t[a]=="string"?t[a]:t[a](s,e);return o}}const h5=new Intl.DateTimeFormat().resolvedOptions().timeZone;function f5(r,e){let t;return e=="UTC"||e=="Etc/UTC"?t=new Date(+r+r.getTimezoneOffset()*6e4):e==h5?t=r:(t=new Date(r.toLocaleString("en-US",{timeZone:e})),t.setMilliseconds(r.getMilliseconds())),t}const aC=r=>r%1==0,du=[1,2,2.5,5],p5=Ta(10,-32,0,du),lC=Ta(10,0,32,du),g5=lC.filter(aC),Qi=p5.concat(lC),jf=`
|
|
274
|
+
`,uC="{YYYY}",Om=jf+uC,cC="{M}/{D}",Ko=jf+cC,fl=Ko+"/{YY}",dC="{aa}",m5="{h}:{mm}",Rs=m5+dC,Fm=jf+Rs,Lm=":{ss}",We=null;function hC(r){let e=r*1e3,t=e*60,n=t*60,i=n*24,s=i*30,o=i*365,l=(r==1?Ta(10,0,3,du).filter(aC):Ta(10,-3,0,du)).concat([e,e*5,e*10,e*15,e*30,t,t*5,t*10,t*15,t*30,n,n*2,n*3,n*4,n*6,n*8,n*12,i,i*2,i*3,i*4,i*5,i*6,i*7,i*8,i*9,i*10,i*15,s,s*2,s*3,s*4,s*6,o,o*2,o*5,o*10,o*25,o*50,o*100]);const u=[[o,uC,We,We,We,We,We,We,1],[i*28,"{MMM}",Om,We,We,We,We,We,1],[i,cC,Om,We,We,We,We,We,1],[n,"{h}"+dC,fl,We,Ko,We,We,We,1],[t,Rs,fl,We,Ko,We,We,We,1],[e,Lm,fl+" "+Rs,We,Ko+" "+Rs,We,Fm,We,1],[r,Lm+".{fff}",fl+" "+Rs,We,Ko+" "+Rs,We,Fm,We,1]];function c(d){return(h,f,p,m,S,w)=>{let g=[],y=S>=o,C=S>=s&&S<o,x=d(p),I=Je(x*r,3),E=Zc(x.getFullYear(),y?0:x.getMonth(),C||y?1:x.getDate()),A=Je(E*r,3);if(C||y){let R=C?S/s:0,F=y?S/o:0,z=I==A?I:Je(Zc(E.getFullYear()+F,E.getMonth()+R,1)*r,3),P=new Date($t(z/r)),O=P.getFullYear(),L=P.getMonth();for(let V=0;z<=m;V++){let X=Zc(O+F*V,L+R*V,1),T=X-d(Je(X*r,3));z=Je((+X+T)*r,3),z<=m&&g.push(z)}}else{let R=S>=i?i:S,F=Qr(p)-Qr(I),z=A+F+Fu(I-A,R);g.push(z);let P=d(z),O=P.getHours()+P.getMinutes()/t+P.getSeconds()/n,L=S/n,V=h.axes[f]._space,X=w/V;for(;z=Je(z+S,r==1?0:3),!(z>m);)if(L>1){let T=Qr(Je(O+L,6))%24,G=d(z).getHours()-T;G>1&&(G=-1),z-=G*n,O=(O+L)%24;let ee=g[g.length-1];Je((z-ee)/S,3)*X>=.7&&g.push(z)}else g.push(z)}return g}}return[l,u,c]}const[y5,v5,w5]=hC(1),[C5,b5,S5]=hC(.001);Ta(2,-53,53,[1]);function _m(r,e){return r.map(t=>t.map((n,i)=>i==0||i==8||n==null?n:e(i==1||t[8]==0?n:t[1]+n)))}function $m(r,e){return(t,n,i,s,o)=>{let a=e.find(p=>o>=p[0])||e[e.length-1],l,u,c,d,h,f;return n.map(p=>{let m=r(p),S=m.getFullYear(),w=m.getMonth(),g=m.getDate(),y=m.getHours(),C=m.getMinutes(),x=m.getSeconds(),I=S!=l&&a[2]||w!=u&&a[3]||g!=c&&a[4]||y!=d&&a[5]||C!=h&&a[6]||x!=f&&a[7]||a[1];return l=S,u=w,c=g,d=y,h=C,f=x,I(m)})}}function x5(r,e){let t=Hf(e);return(n,i,s,o,a)=>i.map(l=>t(r(l)))}function Zc(r,e,t){return new Date(r,e,t)}function Nm(r,e){return e(r)}const I5="{YYYY}-{MM}-{DD} {h}:{mm}{aa}";function Vm(r,e){return(t,n,i,s)=>s==null?Ff:e(r(n))}function k5(r,e){let t=r.series[e];return t.width?t.stroke(r,e):t.points.width?t.points.stroke(r,e):null}function E5(r,e){return r.series[e].fill(r,e)}const M5={show:!0,live:!0,isolate:!1,mount:WM,markers:{show:!0,width:2,stroke:k5,fill:E5,dash:"solid"},idx:null,idxs:null,values:[]};function U5(r,e){let t=r.cursor.points,n=on(),i=t.size(r,e);lt(n,Go,i),lt(n,Xo,i);let s=i/-2;lt(n,"marginLeft",s),lt(n,"marginTop",s);let o=t.width(r,e,i);return o&<(n,"borderWidth",o),n}function A5(r,e){let t=r.series[e].points;return t._fill||t._stroke}function T5(r,e){let t=r.series[e].points;return t._stroke||t._fill}function R5(r,e){return r.series[e].points.size}const qc=[0,0];function P5(r,e,t){return qc[0]=e,qc[1]=t,qc}function pl(r,e,t,n=!0){return i=>{i.button==0&&(!n||i.target==e)&&t(i)}}function Qc(r,e,t,n=!0){return i=>{(!n||i.target==e)&&t(i)}}const B5={show:!0,x:!0,y:!0,lock:!1,move:P5,points:{one:!1,show:U5,size:R5,width:0,stroke:T5,fill:A5},bind:{mousedown:pl,mouseup:pl,click:pl,dblclick:pl,mousemove:Qc,mouseleave:Qc,mouseenter:Qc},drag:{setScale:!0,x:!0,y:!1,dist:0,uni:null,click:(r,e)=>{e.stopPropagation(),e.stopImmediatePropagation()},_x:!1,_y:!1},focus:{dist:(r,e,t,n,i)=>n-i,prox:-1,bias:0},hover:{skip:[void 0],prox:null,bias:0},left:-10,top:-10,idx:null,dataIdx:null,idxs:null,event:null},fC={show:!0,stroke:"rgba(0,0,0,0.07)",width:2},Yf=zt({},fC,{filter:Jw}),pC=zt({},Yf,{size:10}),gC=zt({},fC,{show:!1}),Wf='12px system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"',mC="bold "+Wf,yC=1.5,Hm={show:!0,scale:"x",stroke:Of,space:50,gap:5,alignTo:1,size:50,labelGap:0,labelSize:30,labelFont:mC,side:2,grid:Yf,ticks:pC,border:gC,font:Wf,lineGap:yC,rotate:0},z5="Value",D5="Time",jm={show:!0,scale:"x",auto:!1,sorted:1,min:Qe,max:-Qe,idxs:[]};function O5(r,e,t,n,i){return e.map(s=>s==null?"":Nf(s))}function F5(r,e,t,n,i,s,o){let a=[],l=zi.get(i)||0;t=o?t:Je(Fu(t,i),l);for(let u=t;u<=n;u=Je(u+i,l))a.push(Object.is(u,-0)?0:u);return a}function Ch(r,e,t,n,i,s,o){const a=[],l=r.scales[r.axes[e].scale].log,u=l==10?ei:Zw,c=Qr(u(t));i=lo(l,c),l==10&&(i=Qi[In(i,Qi)]);let d=t,h=i*l;l==10&&(h=Qi[In(h,Qi)]);do a.push(d),d=d+i,l==10&&!zi.has(d)&&(d=Je(d,zi.get(i))),d>=h&&(i=d,h=i*l,l==10&&(h=Qi[In(h,Qi)]));while(d<=n);return a}function L5(r,e,t,n,i,s,o){let l=r.scales[r.axes[e].scale].asinh,u=n>l?Ch(r,e,Mr(l,t),n,i):[l],c=n>=0&&t<=0?[0]:[];return(t<-l?Ch(r,e,Mr(l,-n),-t,i):[l]).reverse().map(h=>-h).concat(c,u)}const vC=/./,_5=/[12357]/,$5=/[125]/,Ym=/1/,bh=(r,e,t,n)=>r.map((i,s)=>e==4&&i==0||s%n==0&&t.test(i.toExponential()[i<0?1:0])?i:null);function N5(r,e,t,n,i){let s=r.axes[t],o=s.scale,a=r.scales[o],l=r.valToPos,u=s._space,c=l(10,o),d=l(9,o)-c>=u?vC:l(7,o)-c>=u?_5:l(5,o)-c>=u?$5:Ym;if(d==Ym){let h=jt(l(1,o)-c);if(h<u)return bh(e.slice().reverse(),a.distr,d,an(u/h)).reverse()}return bh(e,a.distr,d,1)}function V5(r,e,t,n,i){let s=r.axes[t],o=s.scale,a=s._space,l=r.valToPos,u=jt(l(1,o)-l(2,o));return u<a?bh(e.slice().reverse(),3,vC,an(a/u)).reverse():e}function H5(r,e,t,n){return n==null?Ff:e==null?"":Nf(e)}const Wm={show:!0,scale:"y",stroke:Of,space:30,gap:5,alignTo:1,size:50,labelGap:0,labelSize:30,labelFont:mC,side:3,grid:Yf,ticks:pC,border:gC,font:Wf,lineGap:yC,rotate:0};function j5(r,e){let t=3+(r||1)*2;return Je(t*e,3)}function Y5(r,e){let{scale:t,idxs:n}=r.series[0],i=r._data[0],s=r.valToPos(i[n[0]],t,!0),o=r.valToPos(i[n[1]],t,!0),a=jt(o-s),l=r.series[e],u=a/(l.points.space*je);return n[1]-n[0]<=u}const Gm={scale:null,auto:!0,sorted:0,min:Qe,max:-Qe},wC=(r,e,t,n,i)=>i,Xm={show:!0,auto:!0,sorted:0,gaps:wC,alpha:1,facets:[zt({},Gm,{scale:"x"}),zt({},Gm,{scale:"y"})]},Km={scale:"y",auto:!0,sorted:0,show:!0,spanGaps:!1,gaps:wC,alpha:1,points:{show:Y5,filter:null},values:null,min:Qe,max:-Qe,idxs:[],path:null,clip:null};function W5(r,e,t,n,i){return t/10}const CC={time:yM,auto:!0,distr:1,log:10,asinh:1,min:null,max:null,dir:1,ori:0},G5=zt({},CC,{time:!1,ori:1}),Zm={};function bC(r,e){let t=Zm[r];return t||(t={key:r,plots:[],sub(n){t.plots.push(n)},unsub(n){t.plots=t.plots.filter(i=>i!=n)},pub(n,i,s,o,a,l,u){for(let c=0;c<t.plots.length;c++)t.plots[c]!=i&&t.plots[c].pub(n,i,s,o,a,l,u)}},r!=null&&(Zm[r]=t)),t}const ho=1,Sh=2;function ps(r,e,t){const n=r.mode,i=r.series[e],s=n==2?r._data[e]:r._data,o=r.scales,a=r.bbox;let l=s[0],u=n==2?s[1]:s[e],c=n==2?o[i.facets[0].scale]:o[r.series[0].scale],d=n==2?o[i.facets[1].scale]:o[i.scale],h=a.left,f=a.top,p=a.width,m=a.height,S=r.valToPosH,w=r.valToPosV;return c.ori==0?t(i,l,u,c,d,S,w,h,f,p,m,$u,vo,Vu,xC,kC):t(i,l,u,c,d,w,S,f,h,m,p,Nu,wo,Kf,IC,EC)}function Gf(r,e){let t=0,n=0,i=_e(r.bands,Vf);for(let s=0;s<i.length;s++){let o=i[s];o.series[0]==e?t=o.dir:o.series[1]==e&&(o.dir==1?n|=1:n|=2)}return[t,n==1?-1:n==2?1:n==3?2:0]}function X5(r,e,t,n,i){let s=r.mode,o=r.series[e],a=s==2?o.facets[1].scale:o.scale,l=r.scales[a];return i==-1?l.min:i==1?l.max:l.distr==3?l.dir==1?l.min:l.max:0}function ti(r,e,t,n,i,s){return ps(r,e,(o,a,l,u,c,d,h,f,p,m,S)=>{let w=o.pxRound;const g=u.dir*(u.ori==0?1:-1),y=u.ori==0?vo:wo;let C,x;g==1?(C=t,x=n):(C=n,x=t);let I=w(d(a[C],u,m,f)),E=w(h(l[C],c,S,p)),A=w(d(a[x],u,m,f)),R=w(h(s==1?c.max:c.min,c,S,p)),F=new Path2D(i);return y(F,A,R),y(F,I,R),y(F,I,E),F})}function _u(r,e,t,n,i,s){let o=null;if(r.length>0){o=new Path2D;const a=e==0?Vu:Kf;let l=t;for(let d=0;d<r.length;d++){let h=r[d];if(h[1]>h[0]){let f=h[0]-l;f>0&&a(o,l,n,f,n+s),l=h[1]}}let u=t+i-l,c=10;u>0&&a(o,l,n-c/2,u,n+s+c)}return o}function K5(r,e,t){let n=r[r.length-1];n&&n[0]==e?n[1]=t:r.push([e,t])}function Xf(r,e,t,n,i,s,o){let a=[],l=r.length;for(let u=i==1?t:n;u>=t&&u<=n;u+=i)if(e[u]===null){let d=u,h=u;if(i==1)for(;++u<=n&&e[u]===null;)h=u;else for(;--u>=t&&e[u]===null;)h=u;let f=s(r[d]),p=h==d?f:s(r[h]),m=d-i;f=o<=0&&m>=0&&m<l?s(r[m]):f;let w=h+i;p=o>=0&&w>=0&&w<l?s(r[w]):p,p>=f&&a.push([f,p])}return a}function qm(r){return r==0?Qw:r==1?$t:e=>qi(e,r)}function SC(r){let e=r==0?$u:Nu,t=r==0?(i,s,o,a,l,u)=>{i.arcTo(s,o,a,l,u)}:(i,s,o,a,l,u)=>{i.arcTo(o,s,l,a,u)},n=r==0?(i,s,o,a,l)=>{i.rect(s,o,a,l)}:(i,s,o,a,l)=>{i.rect(o,s,l,a)};return(i,s,o,a,l,u=0,c=0)=>{u==0&&c==0?n(i,s,o,a,l):(u=En(u,a/2,l/2),c=En(c,a/2,l/2),e(i,s+u,o),t(i,s+a,o,s+a,o+l,u),t(i,s+a,o+l,s,o+l,c),t(i,s,o+l,s,o,c),t(i,s,o,s+a,o,u),i.closePath())}}const $u=(r,e,t)=>{r.moveTo(e,t)},Nu=(r,e,t)=>{r.moveTo(t,e)},vo=(r,e,t)=>{r.lineTo(e,t)},wo=(r,e,t)=>{r.lineTo(t,e)},Vu=SC(0),Kf=SC(1),xC=(r,e,t,n,i,s)=>{r.arc(e,t,n,i,s)},IC=(r,e,t,n,i,s)=>{r.arc(t,e,n,i,s)},kC=(r,e,t,n,i,s,o)=>{r.bezierCurveTo(e,t,n,i,s,o)},EC=(r,e,t,n,i,s,o)=>{r.bezierCurveTo(t,e,i,n,o,s)};function MC(r){return(e,t,n,i,s)=>ps(e,t,(o,a,l,u,c,d,h,f,p,m,S)=>{let{pxRound:w,points:g}=o,y,C;u.ori==0?(y=$u,C=xC):(y=Nu,C=IC);const x=Je(g.width*je,3);let I=(g.size-g.width)/2*je,E=Je(I*2,3),A=new Path2D,R=new Path2D,{left:F,top:z,width:P,height:O}=e.bbox;Vu(R,F-E,z-E,P+E*2,O+E*2);const L=V=>{if(l[V]!=null){let X=w(d(a[V],u,m,f)),T=w(h(l[V],c,S,p));y(A,X+I,T),C(A,X,T,I,0,zl*2)}};if(s)s.forEach(L);else for(let V=n;V<=i;V++)L(V);return{stroke:x>0?A:null,fill:A,clip:R,flags:ho|Sh}})}function UC(r){return(e,t,n,i,s,o)=>{n!=i&&(s!=n&&o!=n&&r(e,t,n),s!=i&&o!=i&&r(e,t,i),r(e,t,o))}}const Z5=UC(vo),q5=UC(wo);function AC(r){const e=_e(r==null?void 0:r.alignGaps,0);return(t,n,i,s)=>ps(t,n,(o,a,l,u,c,d,h,f,p,m,S)=>{[i,s]=Du(l,i,s);let w=o.pxRound,g=O=>w(d(O,u,m,f)),y=O=>w(h(O,c,S,p)),C,x;u.ori==0?(C=vo,x=Z5):(C=wo,x=q5);const I=u.dir*(u.ori==0?1:-1),E={stroke:new Path2D,fill:null,clip:null,band:null,gaps:null,flags:ho},A=E.stroke;let R=!1;if(s-i>=m*4){let O=K=>t.posToVal(K,u.key,!0),L=null,V=null,X,T,_,j=g(a[I==1?i:s]),G=g(a[i]),ee=g(a[s]),q=O(I==1?G+1:ee-1);for(let K=I==1?i:s;K>=i&&K<=s;K+=I){let oe=a[K],ge=(I==1?oe<q:oe>q)?j:g(oe),Ce=l[K];ge==j?Ce!=null?(T=Ce,L==null?(C(A,ge,y(T)),X=L=V=T):T<L?L=T:T>V&&(V=T)):Ce===null&&(R=!0):(L!=null&&x(A,j,y(L),y(V),y(X),y(T)),Ce!=null?(T=Ce,C(A,ge,y(T)),L=V=X=T):(L=V=null,Ce===null&&(R=!0)),j=ge,q=O(j+I))}L!=null&&L!=V&&_!=j&&x(A,j,y(L),y(V),y(X),y(T))}else for(let O=I==1?i:s;O>=i&&O<=s;O+=I){let L=l[O];L===null?R=!0:L!=null&&C(A,g(a[O]),y(L))}let[z,P]=Gf(t,n);if(o.fill!=null||z!=0){let O=E.fill=new Path2D(A),L=o.fillTo(t,n,o.min,o.max,z),V=y(L),X=g(a[i]),T=g(a[s]);I==-1&&([T,X]=[X,T]),C(O,T,V),C(O,X,V)}if(!o.spanGaps){let O=[];R&&O.push(...Xf(a,l,i,s,I,g,e)),E.gaps=O=o.gaps(t,n,i,s,O),E.clip=_u(O,u.ori,f,p,m,S)}return P!=0&&(E.band=P==2?[ti(t,n,i,s,A,-1),ti(t,n,i,s,A,1)]:ti(t,n,i,s,A,P)),E})}function Q5(r){const e=_e(r.align,1),t=_e(r.ascDesc,!1),n=_e(r.alignGaps,0),i=_e(r.extend,!1);return(s,o,a,l)=>ps(s,o,(u,c,d,h,f,p,m,S,w,g,y)=>{[a,l]=Du(d,a,l);let C=u.pxRound,{left:x,width:I}=s.bbox,E=G=>C(p(G,h,g,S)),A=G=>C(m(G,f,y,w)),R=h.ori==0?vo:wo;const F={stroke:new Path2D,fill:null,clip:null,band:null,gaps:null,flags:ho},z=F.stroke,P=h.dir*(h.ori==0?1:-1);let O=A(d[P==1?a:l]),L=E(c[P==1?a:l]),V=L,X=L;i&&e==-1&&(X=x,R(z,X,O)),R(z,L,O);for(let G=P==1?a:l;G>=a&&G<=l;G+=P){let ee=d[G];if(ee==null)continue;let q=E(c[G]),K=A(ee);e==1?R(z,q,O):R(z,V,K),R(z,q,K),O=K,V=q}let T=V;i&&e==1&&(T=x+I,R(z,T,O));let[_,j]=Gf(s,o);if(u.fill!=null||_!=0){let G=F.fill=new Path2D(z),ee=u.fillTo(s,o,u.min,u.max,_),q=A(ee);R(G,T,q),R(G,X,q)}if(!u.spanGaps){let G=[];G.push(...Xf(c,d,a,l,P,E,n));let ee=u.width*je/2,q=t||e==1?ee:-ee,K=t||e==-1?-ee:ee;G.forEach(oe=>{oe[0]+=q,oe[1]+=K}),F.gaps=G=u.gaps(s,o,a,l,G),F.clip=_u(G,h.ori,S,w,g,y)}return j!=0&&(F.band=j==2?[ti(s,o,a,l,z,-1),ti(s,o,a,l,z,1)]:ti(s,o,a,l,z,j)),F})}function Qm(r,e,t,n,i,s,o=Qe){if(r.length>1){let a=null;for(let l=0,u=1/0;l<r.length;l++)if(e[l]!==void 0){if(a!=null){let c=jt(r[l]-r[a]);c<u&&(u=c,o=jt(t(r[l],n,i,s)-t(r[a],n,i,s)))}a=l}}return o}function J5(r){r=r||da;const e=_e(r.size,[.6,Qe,1]),t=r.align||0,n=r.gap||0;let i=r.radius;i=i==null?[0,0]:typeof i=="number"?[i,0]:i;const s=Pe(i),o=1-e[0],a=_e(e[1],Qe),l=_e(e[2],1),u=_e(r.disp,da),c=_e(r.each,f=>{}),{fill:d,stroke:h}=u;return(f,p,m,S)=>ps(f,p,(w,g,y,C,x,I,E,A,R,F,z)=>{let P=w.pxRound,O=t,L=n*je,V=a*je,X=l*je,T,_;C.ori==0?[T,_]=s(f,p):[_,T]=s(f,p);const j=C.dir*(C.ori==0?1:-1);let G=C.ori==0?Vu:Kf,ee=C.ori==0?c:(ne,$e,ht,Q,W,le,ye)=>{c(ne,$e,ht,W,Q,ye,le)},q=_e(f.bands,Vf).find(ne=>ne.series[0]==p),K=q!=null?q.dir:0,oe=w.fillTo(f,p,w.min,w.max,K),ve=P(E(oe,x,z,R)),ge,Ce,ct,dt=F,xe=P(w.width*je),et=!1,Ke=null,qe=null,At=null,wt=null;d!=null&&(xe==0||h!=null)&&(et=!0,Ke=d.values(f,p,m,S),qe=new Map,new Set(Ke).forEach(ne=>{ne!=null&&qe.set(ne,new Path2D)}),xe>0&&(At=h.values(f,p,m,S),wt=new Map,new Set(At).forEach(ne=>{ne!=null&&wt.set(ne,new Path2D)})));let{x0:Ft,size:cr}=u;if(Ft!=null&&cr!=null){O=1,g=Ft.values(f,p,m,S),Ft.unit==2&&(g=g.map(ht=>f.posToVal(A+ht*F,C.key,!0)));let ne=cr.values(f,p,m,S);cr.unit==2?Ce=ne[0]*F:Ce=I(ne[0],C,F,A)-I(0,C,F,A),dt=Qm(g,y,I,C,F,A,dt),ct=dt-Ce+L}else dt=Qm(g,y,I,C,F,A,dt),ct=dt*o+L,Ce=dt-ct;ct<1&&(ct=0),xe>=Ce/2&&(xe=0),ct<5&&(P=Qw);let tt=ct>0,kt=dt-ct-(tt?xe:0);Ce=P(wh(kt,X,V)),ge=(O==0?Ce/2:O==j?0:Ce)-O*j*((O==0?L/2:0)+(tt?xe/2:0));const nt={stroke:null,fill:null,clip:null,band:null,gaps:null,flags:0},Cr=et?null:new Path2D;let Se=null;if(q!=null)Se=f.data[q.series[1]];else{let{y0:ne,y1:$e}=u;ne!=null&&$e!=null&&(y=$e.values(f,p,m,S),Se=ne.values(f,p,m,S))}let Re=T*Ce,pe=_*Ce;for(let ne=j==1?m:S;ne>=m&&ne<=S;ne+=j){let $e=y[ne];if($e==null)continue;if(Se!=null){let Ee=Se[ne]??0;if($e-Ee==0)continue;ve=E(Ee,x,z,R)}let ht=C.distr!=2||u!=null?g[ne]:ne,Q=I(ht,C,F,A),W=E(_e($e,oe),x,z,R),le=P(Q-ge),ye=P(Mr(W,ve)),de=P(En(W,ve)),Ue=ye-de;if($e!=null){let Ee=$e<0?pe:Re,Me=$e<0?Re:pe;et?(xe>0&&At[ne]!=null&&G(wt.get(At[ne]),le,de+Qr(xe/2),Ce,Mr(0,Ue-xe),Ee,Me),Ke[ne]!=null&&G(qe.get(Ke[ne]),le,de+Qr(xe/2),Ce,Mr(0,Ue-xe),Ee,Me)):G(Cr,le,de+Qr(xe/2),Ce,Mr(0,Ue-xe),Ee,Me),ee(f,p,ne,le-xe/2,de,Ce+xe,Ue)}}return xe>0?nt.stroke=et?wt:Cr:et||(nt._fill=w.width==0?w._fill:w._stroke??w._fill,nt.width=0),nt.fill=et?qe:Cr,nt})}function eU(r,e){const t=_e(e==null?void 0:e.alignGaps,0);return(n,i,s,o)=>ps(n,i,(a,l,u,c,d,h,f,p,m,S,w)=>{[s,o]=Du(u,s,o);let g=a.pxRound,y=T=>g(h(T,c,S,p)),C=T=>g(f(T,d,w,m)),x,I,E;c.ori==0?(x=$u,E=vo,I=kC):(x=Nu,E=wo,I=EC);const A=c.dir*(c.ori==0?1:-1);let R=y(l[A==1?s:o]),F=R,z=[],P=[];for(let T=A==1?s:o;T>=s&&T<=o;T+=A)if(u[T]!=null){let j=l[T],G=y(j);z.push(F=G),P.push(C(u[T]))}const O={stroke:r(z,P,x,E,I,g),fill:null,clip:null,band:null,gaps:null,flags:ho},L=O.stroke;let[V,X]=Gf(n,i);if(a.fill!=null||V!=0){let T=O.fill=new Path2D(L),_=a.fillTo(n,i,a.min,a.max,V),j=C(_);E(T,F,j),E(T,R,j)}if(!a.spanGaps){let T=[];T.push(...Xf(l,u,s,o,A,y,t)),O.gaps=T=a.gaps(n,i,s,o,T),O.clip=_u(T,c.ori,p,m,S,w)}return X!=0&&(O.band=X==2?[ti(n,i,s,o,L,-1),ti(n,i,s,o,L,1)]:ti(n,i,s,o,L,X)),O})}function tU(r){return eU(rU,r)}function rU(r,e,t,n,i,s){const o=r.length;if(o<2)return null;const a=new Path2D;if(t(a,r[0],e[0]),o==2)n(a,r[1],e[1]);else{let l=Array(o),u=Array(o-1),c=Array(o-1),d=Array(o-1);for(let h=0;h<o-1;h++)c[h]=e[h+1]-e[h],d[h]=r[h+1]-r[h],u[h]=c[h]/d[h];l[0]=u[0];for(let h=1;h<o-1;h++)u[h]===0||u[h-1]===0||u[h-1]>0!=u[h]>0?l[h]=0:(l[h]=3*(d[h-1]+d[h])/((2*d[h]+d[h-1])/u[h-1]+(d[h]+2*d[h-1])/u[h]),isFinite(l[h])||(l[h]=0));l[o-1]=u[o-2];for(let h=0;h<o-1;h++)i(a,r[h]+d[h]/3,e[h]+l[h]*d[h]/3,r[h+1]-d[h]/3,e[h+1]-l[h+1]*d[h]/3,r[h+1],e[h+1])}return a}const xh=new Set;function Jm(){for(let r of xh)r.syncRect(!0)}yo&&(ss(OM,Js,Jm),ss(FM,Js,Jm,!0),ss(uu,Js,()=>{yr.pxRatio=je}));const nU=AC(),iU=MC();function ey(r,e,t,n){return(n?[r[0],r[1]].concat(r.slice(2)):[r[0]].concat(r.slice(1))).map((s,o)=>Ih(s,o,e,t))}function sU(r,e){return r.map((t,n)=>n==0?{}:zt({},e,t))}function Ih(r,e,t,n){return zt({},e==0?t:n,r)}function TC(r,e,t){return e==null?uo:[e,t]}const oU=TC;function aU(r,e,t){return e==null?uo:cu(e,t,$f,!0)}function RC(r,e,t,n){return e==null?uo:Ou(e,t,r.scales[n].log,!1)}const lU=RC;function PC(r,e,t,n){return e==null?uo:_f(e,t,r.scales[n].log,!1)}const uU=PC;function cU(r,e,t,n,i){let s=Mr(Pm(r),Pm(e)),o=e-r,a=In(i/n*o,t);do{let l=t[a],u=n*l/o;if(u>=i&&s+(l<5?zi.get(l):0)<=17)return[l,u]}while(++a<t.length);return[0,0]}function ty(r){let e,t;return r=r.replace(/(\d+)px/,(n,i)=>(e=$t((t=+i)*je))+"px"),[r,e,t]}function dU(r){r.show&&[r.font,r.labelFont].forEach(e=>{let t=Je(e[2]*je,1);e[0]=e[0].replace(/[0-9.]+px/,t+"px"),e[1]=t})}function yr(r,e,t){const n={mode:_e(r.mode,1)},i=n.mode;function s(v,b,M,U){let B=b.valToPct(v);return U+M*(b.dir==-1?1-B:B)}function o(v,b,M,U){let B=b.valToPct(v);return U+M*(b.dir==-1?B:1-B)}function a(v,b,M,U){return b.ori==0?s(v,b,M,U):o(v,b,M,U)}n.valToPosH=s,n.valToPosV=o;let l=!1;n.status=0;const u=n.root=on(vM);if(r.id!=null&&(u.id=r.id),Wr(u,r.class),r.title){let v=on(bM,u);v.textContent=r.title}const c=Cn("canvas"),d=n.ctx=c.getContext("2d"),h=on(SM,u);ss("click",h,v=>{v.target===p&&(it!=bs||pt!=Ss)&&sr.click(n,v)},!0);const f=n.under=on(xM,h);h.appendChild(c);const p=n.over=on(IM,h);r=co(r);const m=+_e(r.pxAlign,1),S=qm(m);(r.plugins||[]).forEach(v=>{v.opts&&(r=v.opts(n,r)||r)});const w=r.ms||.001,g=n.series=i==1?ey(r.series||[],jm,Km,!1):sU(r.series||[null],Xm),y=n.axes=ey(r.axes||[],Hm,Wm,!0),C=n.scales={},x=n.bands=r.bands||[];x.forEach(v=>{v.fill=Pe(v.fill||null),v.dir=_e(v.dir,-1)});const I=i==2?g[1].facets[0].scale:g[0].scale,E={axes:YC,series:$C},A=(r.drawOrder||["axes","series"]).map(v=>E[v]);function R(v){const b=v.distr==3?M=>ei(M>0?M:v.clamp(n,M,v.min,v.max,v.key)):v.distr==4?M=>Kc(M,v.asinh):v.distr==100?M=>v.fwd(M):M=>M;return M=>{let U=b(M),{_min:B,_max:$}=v,Y=$-B;return(U-B)/Y}}function F(v){let b=C[v];if(b==null){let M=(r.scales||da)[v]||da;if(M.from!=null){F(M.from);let U=zt({},C[M.from],M,{key:v});U.valToPct=R(U),C[v]=U}else{b=C[v]=zt({},v==I?CC:G5,M),b.key=v;let U=b.time,B=b.range,$=mi(B);if((v!=I||i==2&&!U)&&($&&(B[0]==null||B[1]==null)&&(B={min:B[0]==null?Am:{mode:1,hard:B[0],soft:B[0]},max:B[1]==null?Am:{mode:1,hard:B[1],soft:B[1]}},$=!1),!$&&Lu(B))){let Y=B;B=(Z,re,ae)=>re==null?uo:cu(re,ae,Y)}b.range=Pe(B||(U?oU:v==I?b.distr==3?lU:b.distr==4?uU:TC:b.distr==3?RC:b.distr==4?PC:aU)),b.auto=Pe($?!1:b.auto),b.clamp=Pe(b.clamp||W5),b._min=b._max=null,b.valToPct=R(b)}}}F("x"),F("y"),i==1&&g.forEach(v=>{F(v.scale)}),y.forEach(v=>{F(v.scale)});for(let v in r.scales)F(v);const z=C[I],P=z.distr;let O,L;z.ori==0?(Wr(u,wM),O=s,L=o):(Wr(u,CM),O=o,L=s);const V={};for(let v in C){let b=C[v];(b.min!=null||b.max!=null)&&(V[v]={min:b.min,max:b.max},b.min=b.max=null)}const X=r.tzDate||(v=>new Date($t(v/w))),T=r.fmtDate||Hf,_=w==1?w5(X):S5(X),j=$m(X,_m(w==1?v5:b5,T)),G=Vm(X,Nm(I5,T)),ee=[],q=n.legend=zt({},M5,r.legend),K=n.cursor=zt({},B5,{drag:{y:i==2}},r.cursor),oe=q.show,ve=K.show,ge=q.markers;q.idxs=ee,ge.width=Pe(ge.width),ge.dash=Pe(ge.dash),ge.stroke=Pe(ge.stroke),ge.fill=Pe(ge.fill);let Ce,ct,dt,xe=[],et=[],Ke,qe=!1,At={};if(q.live){const v=g[1]?g[1].values:null;qe=v!=null,Ke=qe?v(n,1,0):{_:0};for(let b in Ke)At[b]=Ff}if(oe)if(Ce=Cn("table",TM,u),dt=Cn("tbody",null,Ce),q.mount(n,Ce),qe){ct=Cn("thead",null,Ce,dt);let v=Cn("tr",null,ct);Cn("th",null,v);for(var wt in Ke)Cn("th",mm,v).textContent=wt}else Wr(Ce,PM),q.live&&Wr(Ce,RM);const Ft={show:!0},cr={show:!1};function tt(v,b){if(b==0&&(qe||!q.live||i==2))return uo;let M=[],U=Cn("tr",BM,dt,dt.childNodes[b]);Wr(U,v.class),v.show||Wr(U,Ji);let B=Cn("th",null,U);if(ge.show){let Z=on(zM,B);if(b>0){let re=ge.width(n,b);re&&(Z.style.border=re+"px "+ge.dash(n,b)+" "+ge.stroke(n,b)),Z.style.background=ge.fill(n,b)}}let $=on(mm,B);v.label instanceof HTMLElement?$.appendChild(v.label):$.textContent=v.label,b>0&&(ge.show||($.style.color=v.width>0?ge.stroke(n,b):ge.fill(n,b)),nt("click",B,Z=>{if(K._lock)return;Br(Z);let re=g.indexOf(v);if((Z.ctrlKey||Z.metaKey)!=q.isolate){let ae=g.some((ue,he)=>he>0&&he!=re&&ue.show);g.forEach((ue,he)=>{he>0&&zn(he,ae?he==re?Ft:cr:Ft,!0,Bt.setSeries)})}else zn(re,{show:!v.show},!0,Bt.setSeries)},!1),Tn&&nt(Cm,B,Z=>{K._lock||(Br(Z),zn(g.indexOf(v),Is,!0,Bt.setSeries))},!1));for(var Y in Ke){let Z=Cn("td",DM,U);Z.textContent="--",M.push(Z)}return[U,M]}const kt=new Map;function nt(v,b,M,U=!0){const B=kt.get(b)||{},$=K.bind[v](n,b,M,U);$&&(ss(v,b,B[v]=$),kt.set(b,B))}function Cr(v,b,M){const U=kt.get(b)||{};for(let B in U)(v==null||B==v)&&(vh(B,b,U[B]),delete U[B]);v==null&&kt.delete(b)}let Se=0,Re=0,pe=0,ne=0,$e=0,ht=0,Q=$e,W=ht,le=pe,ye=ne,de=0,Ue=0,Ee=0,Me=0;n.bbox={};let Ne=!1,we=!1,Oe=!1,Tt=!1,ft=!1,Ve=!1;function Xt(v,b,M){(M||v!=n.width||b!=n.height)&&Lt(v,b),ys(!1),Oe=!0,we=!0,vs()}function Lt(v,b){n.width=Se=pe=v,n.height=Re=ne=b,$e=ht=0,Fe(),$i();let M=n.bbox;de=M.left=qi($e*je,.5),Ue=M.top=qi(ht*je,.5),Ee=M.width=qi(pe*je,.5),Me=M.height=qi(ne*je,.5)}const ai=3;function Li(){let v=!1,b=0;for(;!v;){b++;let M=HC(b),U=jC(b);v=b==ai||M&&U,v||(Lt(n.width,n.height),we=!0)}}function _i({width:v,height:b}){Xt(v,b)}n.setSize=_i;function Fe(){let v=!1,b=!1,M=!1,U=!1;y.forEach((B,$)=>{if(B.show&&B._show){let{side:Y,_size:Z}=B,re=Y%2,ae=B.label!=null?B.labelSize:0,ue=Z+ae;ue>0&&(re?(pe-=ue,Y==3?($e+=ue,U=!0):M=!0):(ne-=ue,Y==0?(ht+=ue,v=!0):b=!0))}}),Vi[0]=v,Vi[1]=M,Vi[2]=b,Vi[3]=U,pe-=li[1]+li[3],$e+=li[3],ne-=li[2]+li[0],ht+=li[0]}function $i(){let v=$e+pe,b=ht+ne,M=$e,U=ht;function B($,Y){switch($){case 1:return v+=Y,v-Y;case 2:return b+=Y,b-Y;case 3:return M-=Y,M+Y;case 0:return U-=Y,U+Y}}y.forEach(($,Y)=>{if($.show&&$._show){let Z=$.side;$._pos=B(Z,$._size),$.label!=null&&($._lpos=B(Z,$.labelSize))}})}if(K.dataIdx==null){let v=K.hover,b=v.skip=new Set(v.skip??[]);b.add(void 0);let M=v.prox=Pe(v.prox),U=v.bias??(v.bias=0);K.dataIdx=(B,$,Y,Z)=>{if($==0)return Y;let re=Y,ae=M(B,$,Y,Z)??Qe,ue=ae>=0&&ae<Qe,he=z.ori==0?pe:ne,Ie=K.left,He=e[0],Le=e[$];if(b.has(Le[Y])){re=null;let Ae=null,be=null,me;if(U==0||U==-1)for(me=Y;Ae==null&&me-- >0;)b.has(Le[me])||(Ae=me);if(U==0||U==1)for(me=Y;be==null&&me++<Le.length;)b.has(Le[me])||(be=me);if(Ae!=null||be!=null)if(ue){let ot=Ae==null?-1/0:O(He[Ae],z,he,0),Et=be==null?1/0:O(He[be],z,he,0),er=Ie-ot,Ze=Et-Ie;er<=Ze?er<=ae&&(re=Ae):Ze<=ae&&(re=be)}else re=be==null?Ae:Ae==null?be:Y-Ae<=be-Y?Ae:be}else ue&&jt(Ie-O(He[Y],z,he,0))>ae&&(re=null);return re}}const Br=v=>{K.event=v};K.idxs=ee,K._lock=!1;let Ct=K.points;Ct.show=Pe(Ct.show),Ct.size=Pe(Ct.size),Ct.stroke=Pe(Ct.stroke),Ct.width=Pe(Ct.width),Ct.fill=Pe(Ct.fill);const dr=n.focus=zt({},r.focus||{alpha:.3},K.focus),Tn=dr.prox>=0,Rn=Tn&&Ct.one;let hr=[],Pn=[],Bn=[];function gs(v,b){let M=Ct.show(n,b);if(M instanceof HTMLElement)return Wr(M,AM),Wr(M,v.class),_n(M,-10,-10,pe,ne),p.insertBefore(M,hr[b]),M}function Pt(v,b){if(i==1||b>0){let M=i==1&&C[v.scale].time,U=v.value;v.value=M?Dm(U)?Vm(X,Nm(U,T)):U||G:U||H5,v.label=v.label||(M?D5:z5)}if(Rn||b>0){v.width=v.width==null?1:v.width,v.paths=v.paths||nU||GM,v.fillTo=Pe(v.fillTo||X5),v.pxAlign=+_e(v.pxAlign,m),v.pxRound=qm(v.pxAlign),v.stroke=Pe(v.stroke||null),v.fill=Pe(v.fill||null),v._stroke=v._fill=v._paths=v._focus=null;let M=j5(Mr(1,v.width),1),U=v.points=zt({},{size:M,width:Mr(1,M*.2),stroke:v.stroke,space:M*2,paths:iU,_stroke:null,_fill:null},v.points);U.show=Pe(U.show),U.filter=Pe(U.filter),U.fill=Pe(U.fill),U.stroke=Pe(U.stroke),U.paths=Pe(U.paths),U.pxAlign=v.pxAlign}if(oe){let M=tt(v,b);xe.splice(b,0,M[0]),et.splice(b,0,M[1]),q.values.push(null)}if(ve){ee.splice(b,0,null);let M=null;Rn?b==0&&(M=gs(v,b)):b>0&&(M=gs(v,b)),hr.splice(b,0,M),Pn.splice(b,0,0),Bn.splice(b,0,0)}Jt("addSeries",b)}function bt(v,b){b=b??g.length,v=i==1?Ih(v,b,jm,Km):Ih(v,b,{},Xm),g.splice(b,0,v),Pt(g[b],b)}n.addSeries=bt;function Ni(v){if(g.splice(v,1),oe){q.values.splice(v,1),et.splice(v,1);let b=xe.splice(v,1)[0];Cr(null,b.firstChild),b.remove()}ve&&(ee.splice(v,1),hr.splice(v,1)[0].remove(),Pn.splice(v,1),Bn.splice(v,1)),Jt("delSeries",v)}n.delSeries=Ni;const Vi=[!1,!1,!1,!1];function FC(v,b){if(v._show=v.show,v.show){let M=v.side%2,U=C[v.scale];U==null&&(v.scale=M?g[1].scale:I,U=C[v.scale]);let B=U.time;v.size=Pe(v.size),v.space=Pe(v.space),v.rotate=Pe(v.rotate),mi(v.incrs)&&v.incrs.forEach(Y=>{!zi.has(Y)&&zi.set(Y,tC(Y))}),v.incrs=Pe(v.incrs||(U.distr==2?g5:B?w==1?y5:C5:Qi)),v.splits=Pe(v.splits||(B&&U.distr==1?_:U.distr==3?Ch:U.distr==4?L5:F5)),v.stroke=Pe(v.stroke),v.grid.stroke=Pe(v.grid.stroke),v.ticks.stroke=Pe(v.ticks.stroke),v.border.stroke=Pe(v.border.stroke);let $=v.values;v.values=mi($)&&!mi($[0])?Pe($):B?mi($)?$m(X,_m($,T)):Dm($)?x5(X,$):$||j:$||O5,v.filter=Pe(v.filter||(U.distr>=3&&U.log==10?N5:U.distr==3&&U.log==2?V5:Jw)),v.font=ty(v.font),v.labelFont=ty(v.labelFont),v._size=v.size(n,null,b,0),v._space=v._rotate=v._incrs=v._found=v._splits=v._values=null,v._size>0&&(Vi[b]=!0,v._el=on(kM,h))}}function bo(v,b,M,U){let[B,$,Y,Z]=M,re=b%2,ae=0;return re==0&&(Z||$)&&(ae=b==0&&!B||b==2&&!Y?$t(Hm.size/3):0),re==1&&(B||Y)&&(ae=b==1&&!$||b==3&&!Z?$t(Wm.size/2):0),ae}const Qf=n.padding=(r.padding||[bo,bo,bo,bo]).map(v=>Pe(_e(v,bo))),li=n._padding=Qf.map((v,b)=>v(n,b,Vi,0));let ir,Kt=null,Zt=null;const La=i==1?g[0].idxs:null;let gn=null,So=!1;function Jf(v,b){if(e=v??[],n.data=n._data=e,i==2){ir=0;for(let M=1;M<g.length;M++)ir+=e[M][0].length}else{e.length==0&&(n.data=n._data=e=[[]]),gn=e[0],ir=gn.length;let M=e;if(P==2){M=e.slice();let U=M[0]=Array(ir);for(let B=0;B<ir;B++)U[B]=B}n._data=e=M}if(ys(!0),Jt("setData"),P==2&&(Oe=!0),b!==!1){let M=z;M.auto(n,So)?Hu():ci(I,M.min,M.max),Tt=Tt||K.left>=0,Ve=!0,vs()}}n.setData=Jf;function Hu(){So=!0;let v,b;i==1&&(ir>0?(Kt=La[0]=0,Zt=La[1]=ir-1,v=e[0][Kt],b=e[0][Zt],P==2?(v=Kt,b=Zt):v==b&&(P==3?[v,b]=Ou(v,v,z.log,!1):P==4?[v,b]=_f(v,v,z.log,!1):z.time?b=v+$t(86400/w):[v,b]=cu(v,b,$f,!0))):(Kt=La[0]=v=null,Zt=La[1]=b=null)),ci(I,v,b)}let _a,ms,ju,Yu,Wu,Gu,Xu,Ku,Zu,zr;function ep(v,b,M,U,B,$){v??(v=vm),M??(M=Vf),U??(U="butt"),B??(B=vm),$??($="round"),v!=_a&&(d.strokeStyle=_a=v),B!=ms&&(d.fillStyle=ms=B),b!=ju&&(d.lineWidth=ju=b),$!=Wu&&(d.lineJoin=Wu=$),U!=Gu&&(d.lineCap=Gu=U),M!=Yu&&d.setLineDash(Yu=M)}function tp(v,b,M,U){b!=ms&&(d.fillStyle=ms=b),v!=Xu&&(d.font=Xu=v),M!=Ku&&(d.textAlign=Ku=M),U!=Zu&&(d.textBaseline=Zu=U)}function qu(v,b,M,U,B=0){if(U.length>0&&v.auto(n,So)&&(b==null||b.min==null)){let $=_e(Kt,0),Y=_e(Zt,U.length-1),Z=M.min==null?NM(U,$,Y,B,v.distr==3):[M.min,M.max];v.min=En(v.min,M.min=Z[0]),v.max=Mr(v.max,M.max=Z[1])}}const rp={min:null,max:null};function LC(){for(let U in C){let B=C[U];V[U]==null&&(B.min==null||V[I]!=null&&B.auto(n,So))&&(V[U]=rp)}for(let U in C){let B=C[U];V[U]==null&&B.from!=null&&V[B.from]!=null&&(V[U]=rp)}V[I]!=null&&ys(!0);let v={};for(let U in V){let B=V[U];if(B!=null){let $=v[U]=co(C[U],ZM);if(B.min!=null)zt($,B);else if(U!=I||i==2)if(ir==0&&$.from==null){let Y=$.range(n,null,null,U);$.min=Y[0],$.max=Y[1]}else $.min=Qe,$.max=-Qe}}if(ir>0){g.forEach((U,B)=>{if(i==1){let $=U.scale,Y=V[$];if(Y==null)return;let Z=v[$];if(B==0){let re=Z.range(n,Z.min,Z.max,$);Z.min=re[0],Z.max=re[1],Kt=In(Z.min,e[0]),Zt=In(Z.max,e[0]),Zt-Kt>1&&(e[0][Kt]<Z.min&&Kt++,e[0][Zt]>Z.max&&Zt--),U.min=gn[Kt],U.max=gn[Zt]}else U.show&&U.auto&&qu(Z,Y,U,e[B],U.sorted);U.idxs[0]=Kt,U.idxs[1]=Zt}else if(B>0&&U.show&&U.auto){let[$,Y]=U.facets,Z=$.scale,re=Y.scale,[ae,ue]=e[B],he=v[Z],Ie=v[re];he!=null&&qu(he,V[Z],$,ae,$.sorted),Ie!=null&&qu(Ie,V[re],Y,ue,Y.sorted),U.min=Y.min,U.max=Y.max}});for(let U in v){let B=v[U],$=V[U];if(B.from==null&&($==null||$.min==null)){let Y=B.range(n,B.min==Qe?null:B.min,B.max==-Qe?null:B.max,U);B.min=Y[0],B.max=Y[1]}}}for(let U in v){let B=v[U];if(B.from!=null){let $=v[B.from];if($.min==null)B.min=B.max=null;else{let Y=B.range(n,$.min,$.max,U);B.min=Y[0],B.max=Y[1]}}}let b={},M=!1;for(let U in v){let B=v[U],$=C[U];if($.min!=B.min||$.max!=B.max){$.min=B.min,$.max=B.max;let Y=$.distr;$._min=Y==3?ei($.min):Y==4?Kc($.min,$.asinh):Y==100?$.fwd($.min):$.min,$._max=Y==3?ei($.max):Y==4?Kc($.max,$.asinh):Y==100?$.fwd($.max):$.max,b[U]=M=!0}}if(M){g.forEach((U,B)=>{i==2?B>0&&b.y&&(U._paths=null):b[U.scale]&&(U._paths=null)});for(let U in b)Oe=!0,Jt("setScale",U);ve&&K.left>=0&&(Tt=Ve=!0)}for(let U in V)V[U]=null}function _C(v){let b=wh(Kt-1,0,ir-1),M=wh(Zt+1,0,ir-1);for(;v[b]==null&&b>0;)b--;for(;v[M]==null&&M<ir-1;)M++;return[b,M]}function $C(){if(ir>0){let v=g.some(b=>b._focus)&&zr!=dr.alpha;v&&(d.globalAlpha=zr=dr.alpha),g.forEach((b,M)=>{if(M>0&&b.show&&(np(M,!1),np(M,!0),b._paths==null)){let U=zr;zr!=b.alpha&&(d.globalAlpha=zr=b.alpha);let B=i==2?[0,e[M][0].length-1]:_C(e[M]);b._paths=b.paths(n,M,B[0],B[1]),zr!=U&&(d.globalAlpha=zr=U)}}),g.forEach((b,M)=>{if(M>0&&b.show){let U=zr;zr!=b.alpha&&(d.globalAlpha=zr=b.alpha),b._paths!=null&&ip(M,!1);{let B=b._paths!=null?b._paths.gaps:null,$=b.points.show(n,M,Kt,Zt,B),Y=b.points.filter(n,M,$,B);($||Y)&&(b.points._paths=b.points.paths(n,M,Kt,Zt,Y),ip(M,!0))}zr!=U&&(d.globalAlpha=zr=U),Jt("drawSeries",M)}}),v&&(d.globalAlpha=zr=1)}}function np(v,b){let M=b?g[v].points:g[v];M._stroke=M.stroke(n,v),M._fill=M.fill(n,v)}function ip(v,b){let M=b?g[v].points:g[v],{stroke:U,fill:B,clip:$,flags:Y,_stroke:Z=M._stroke,_fill:re=M._fill,_width:ae=M.width}=M._paths;ae=Je(ae*je,3);let ue=null,he=ae%2/2;b&&re==null&&(re=ae>0?"#fff":Z);let Ie=M.pxAlign==1&&he>0;if(Ie&&d.translate(he,he),!b){let He=de-ae/2,Le=Ue-ae/2,Ae=Ee+ae,be=Me+ae;ue=new Path2D,ue.rect(He,Le,Ae,be)}b?Qu(Z,ae,M.dash,M.cap,re,U,B,Y,$):NC(v,Z,ae,M.dash,M.cap,re,U,B,Y,ue,$),Ie&&d.translate(-he,-he)}function NC(v,b,M,U,B,$,Y,Z,re,ae,ue){let he=!1;re!=0&&x.forEach((Ie,He)=>{if(Ie.series[0]==v){let Le=g[Ie.series[1]],Ae=e[Ie.series[1]],be=(Le._paths||da).band;mi(be)&&(be=Ie.dir==1?be[0]:be[1]);let me,ot=null;Le.show&&be&&HM(Ae,Kt,Zt)?(ot=Ie.fill(n,He)||$,me=Le._paths.clip):be=null,Qu(b,M,U,B,ot,Y,Z,re,ae,ue,me,be),he=!0}}),he||Qu(b,M,U,B,$,Y,Z,re,ae,ue)}const sp=ho|Sh;function Qu(v,b,M,U,B,$,Y,Z,re,ae,ue,he){ep(v,b,M,U,B),(re||ae||he)&&(d.save(),re&&d.clip(re),ae&&d.clip(ae)),he?(Z&sp)==sp?(d.clip(he),ue&&d.clip(ue),Na(B,Y),$a(v,$,b)):Z&Sh?(Na(B,Y),d.clip(he),$a(v,$,b)):Z&ho&&(d.save(),d.clip(he),ue&&d.clip(ue),Na(B,Y),d.restore(),$a(v,$,b)):(Na(B,Y),$a(v,$,b)),(re||ae||he)&&d.restore()}function $a(v,b,M){M>0&&(b instanceof Map?b.forEach((U,B)=>{d.strokeStyle=_a=B,d.stroke(U)}):b!=null&&v&&d.stroke(b))}function Na(v,b){b instanceof Map?b.forEach((M,U)=>{d.fillStyle=ms=U,d.fill(M)}):b!=null&&v&&d.fill(b)}function VC(v,b,M,U){let B=y[v],$;if(U<=0)$=[0,0];else{let Y=B._space=B.space(n,v,b,M,U),Z=B._incrs=B.incrs(n,v,b,M,U,Y);$=cU(b,M,Z,U,Y)}return B._found=$}function Ju(v,b,M,U,B,$,Y,Z,re,ae){let ue=Y%2/2;m==1&&d.translate(ue,ue),ep(Z,Y,re,ae,Z),d.beginPath();let he,Ie,He,Le,Ae=B+(U==0||U==3?-$:$);M==0?(Ie=B,Le=Ae):(he=B,He=Ae);for(let be=0;be<v.length;be++)b[be]!=null&&(M==0?he=He=v[be]:Ie=Le=v[be],d.moveTo(he,Ie),d.lineTo(He,Le));d.stroke(),m==1&&d.translate(-ue,-ue)}function HC(v){let b=!0;return y.forEach((M,U)=>{if(!M.show)return;let B=C[M.scale];if(B.min==null){M._show&&(b=!1,M._show=!1,ys(!1));return}else M._show||(b=!1,M._show=!0,ys(!1));let $=M.side,Y=$%2,{min:Z,max:re}=B,[ae,ue]=VC(U,Z,re,Y==0?pe:ne);if(ue==0)return;let he=B.distr==2,Ie=M._splits=M.splits(n,U,Z,re,ae,ue,he),He=B.distr==2?Ie.map(me=>gn[me]):Ie,Le=B.distr==2?gn[Ie[1]]-gn[Ie[0]]:ae,Ae=M._values=M.values(n,M.filter(n,He,U,ue,Le),U,ue,Le);M._rotate=$==2?M.rotate(n,Ae,U,ue):0;let be=M._size;M._size=an(M.size(n,Ae,U,v)),be!=null&&M._size!=be&&(b=!1)}),b}function jC(v){let b=!0;return Qf.forEach((M,U)=>{let B=M(n,U,Vi,v);B!=li[U]&&(b=!1),li[U]=B}),b}function YC(){for(let v=0;v<y.length;v++){let b=y[v];if(!b.show||!b._show)continue;let M=b.side,U=M%2,B,$,Y=b.stroke(n,v),Z=M==0||M==3?-1:1,[re,ae]=b._found;if(b.label!=null){let Sr=b.labelGap*Z,jr=$t((b._lpos+Sr)*je);tp(b.labelFont[0],Y,"center",M==2?_o:ym),d.save(),U==1?(B=$=0,d.translate(jr,$t(Ue+Me/2)),d.rotate((M==3?-zl:zl)/2)):(B=$t(de+Ee/2),$=jr);let Yi=qw(b.label)?b.label(n,v,re,ae):b.label;d.fillText(Yi,B,$),d.restore()}if(ae==0)continue;let ue=C[b.scale],he=U==0?Ee:Me,Ie=U==0?de:Ue,He=b._splits,Le=ue.distr==2?He.map(Sr=>gn[Sr]):He,Ae=ue.distr==2?gn[He[1]]-gn[He[0]]:re,be=b.ticks,me=b.border,ot=be.show?be.size:0,Et=$t(ot*je),er=$t((b.alignTo==2?b._size-ot-b.gap:b.gap)*je),Ze=b._rotate*-zl/180,Mt=S(b._pos*je),Vr=(Et+er)*Z,br=Mt+Vr;$=U==0?br:0,B=U==1?br:0;let nn=b.font[0],mn=b.align==1?Us:b.align==2?Wc:Ze>0?Us:Ze<0?Wc:U==0?"center":M==3?Wc:Us,On=Ze||U==1?"middle":M==2?_o:ym;tp(nn,Y,mn,On);let Hr=b.font[1]*b.lineGap,sn=He.map(Sr=>S(a(Sr,ue,he,Ie))),yn=b._values;for(let Sr=0;Sr<yn.length;Sr++){let jr=yn[Sr];if(jr!=null){U==0?B=sn[Sr]:$=sn[Sr],jr=""+jr;let Yi=jr.indexOf(`
|
|
275
|
+
`)==-1?[jr]:jr.split(/\n/gm);for(let xr=0;xr<Yi.length;xr++){let Ip=Yi[xr];Ze?(d.save(),d.translate(B,$+xr*Hr),d.rotate(Ze),d.fillText(Ip,0,0),d.restore()):d.fillText(Ip,B,$+xr*Hr)}}}be.show&&Ju(sn,be.filter(n,Le,v,ae,Ae),U,M,Mt,Et,Je(be.width*je,3),be.stroke(n,v),be.dash,be.cap);let Fn=b.grid;Fn.show&&Ju(sn,Fn.filter(n,Le,v,ae,Ae),U,U==0?2:1,U==0?Ue:de,U==0?Me:Ee,Je(Fn.width*je,3),Fn.stroke(n,v),Fn.dash,Fn.cap),me.show&&Ju([Mt],[1],U==0?1:0,U==0?1:2,U==1?Ue:de,U==1?Me:Ee,Je(me.width*je,3),me.stroke(n,v),me.dash,me.cap)}Jt("drawAxes")}function ys(v){g.forEach((b,M)=>{M>0&&(b._paths=null,v&&(i==1?(b.min=null,b.max=null):b.facets.forEach(U=>{U.min=null,U.max=null})))})}let Va=!1,ec=!1,xo=[];function WC(){ec=!1;for(let v=0;v<xo.length;v++)Jt(...xo[v]);xo.length=0}function vs(){Va||(n5(op),Va=!0)}function GC(v,b=!1){Va=!0,ec=b,v(n),op(),b&&xo.length>0&&queueMicrotask(WC)}n.batch=GC;function op(){if(Ne&&(LC(),Ne=!1),Oe&&(Li(),Oe=!1),we){if(lt(f,Us,$e),lt(f,_o,ht),lt(f,Go,pe),lt(f,Xo,ne),lt(p,Us,$e),lt(p,_o,ht),lt(p,Go,pe),lt(p,Xo,ne),lt(h,Go,Se),lt(h,Xo,Re),c.width=$t(Se*je),c.height=$t(Re*je),y.forEach(({_el:v,_show:b,_size:M,_pos:U,side:B})=>{if(v!=null)if(b){let $=B===3||B===0?M:0,Y=B%2==1;lt(v,Y?"left":"top",U-$),lt(v,Y?"width":"height",M),lt(v,Y?"top":"left",Y?ht:$e),lt(v,Y?"height":"width",Y?ne:pe),yh(v,Ji)}else Wr(v,Ji)}),_a=ms=ju=Wu=Gu=Xu=Ku=Zu=Yu=null,zr=1,Eo(!0),$e!=Q||ht!=W||pe!=le||ne!=ye){ys(!1);let v=pe/le,b=ne/ye;if(ve&&!Tt&&K.left>=0){K.left*=v,K.top*=b,ws&&_n(ws,$t(K.left),0,pe,ne),Cs&&_n(Cs,0,$t(K.top),pe,ne);for(let M=0;M<hr.length;M++){let U=hr[M];U!=null&&(Pn[M]*=v,Bn[M]*=b,_n(U,an(Pn[M]),an(Bn[M]),pe,ne))}}if(st.show&&!ft&&st.left>=0&&st.width>0){st.left*=v,st.width*=v,st.top*=b,st.height*=b;for(let M in oc)lt(xs,M,st[M])}Q=$e,W=ht,le=pe,ye=ne}Jt("setSize"),we=!1}Se>0&&Re>0&&(d.clearRect(0,0,c.width,c.height),Jt("drawClear"),A.forEach(v=>v()),Jt("draw")),st.show&&ft&&(Ha(st),ft=!1),ve&&Tt&&(ji(null,!0,!1),Tt=!1),q.show&&q.live&&Ve&&(ic(),Ve=!1),l||(l=!0,n.status=1,Jt("ready")),So=!1,Va=!1}n.redraw=(v,b)=>{Oe=b||!1,v!==!1?ci(I,z.min,z.max):vs()};function tc(v,b){let M=C[v];if(M.from==null){if(ir==0){let U=M.range(n,b.min,b.max,v);b.min=U[0],b.max=U[1]}if(b.min>b.max){let U=b.min;b.min=b.max,b.max=U}if(ir>1&&b.min!=null&&b.max!=null&&b.max-b.min<1e-16)return;v==I&&M.distr==2&&ir>0&&(b.min=In(b.min,e[0]),b.max=In(b.max,e[0]),b.min==b.max&&b.max++),V[v]=b,Ne=!0,vs()}}n.setScale=tc;let rc,nc,ws,Cs,ap,lp,bs,Ss,up,cp,it,pt,ui=!1;const sr=K.drag;let qt=sr.x,Qt=sr.y;ve&&(K.x&&(rc=on(MM,p)),K.y&&(nc=on(UM,p)),z.ori==0?(ws=rc,Cs=nc):(ws=nc,Cs=rc),it=K.left,pt=K.top);const st=n.select=zt({show:!0,over:!0,left:0,width:0,top:0,height:0},r.select),xs=st.show?on(EM,st.over?p:f):null;function Ha(v,b){if(st.show){for(let M in v)st[M]=v[M],M in oc&<(xs,M,v[M]);b!==!1&&Jt("setSelect")}}n.setSelect=Ha;function XC(v){if(g[v].show)oe&&yh(xe[v],Ji);else if(oe&&Wr(xe[v],Ji),ve){let M=Rn?hr[0]:hr[v];M!=null&&_n(M,-10,-10,pe,ne)}}function ci(v,b,M){tc(v,{min:b,max:M})}function zn(v,b,M,U){b.focus!=null&&JC(v),b.show!=null&&g.forEach((B,$)=>{$>0&&(v==$||v==null)&&(B.show=b.show,XC($),i==2?(ci(B.facets[0].scale,null,null),ci(B.facets[1].scale,null,null)):ci(B.scale,null,null),vs())}),M!==!1&&Jt("setSeries",v,b),U&&Mo("setSeries",n,v,b)}n.setSeries=zn;function KC(v,b){zt(x[v],b)}function ZC(v,b){v.fill=Pe(v.fill||null),v.dir=_e(v.dir,-1),b=b??x.length,x.splice(b,0,v)}function qC(v){v==null?x.length=0:x.splice(v,1)}n.addBand=ZC,n.setBand=KC,n.delBand=qC;function QC(v,b){g[v].alpha=b,ve&&hr[v]!=null&&(hr[v].style.opacity=b),oe&&xe[v]&&(xe[v].style.opacity=b)}let Wn,di,Hi;const Is={focus:!0};function JC(v){if(v!=Hi){let b=v==null,M=dr.alpha!=1;g.forEach((U,B)=>{if(i==1||B>0){let $=b||B==0||B==v;U._focus=b?null:$,M&&QC(B,$?1:dr.alpha)}}),Hi=v,M&&vs()}}oe&&Tn&&nt(bm,Ce,v=>{K._lock||(Br(v),Hi!=null&&zn(null,Is,!0,Bt.setSeries))});function Dn(v,b,M){let U=C[b];M&&(v=v/je-(U.ori==1?ht:$e));let B=pe;U.ori==1&&(B=ne,v=B-v),U.dir==-1&&(v=B-v);let $=U._min,Y=U._max,Z=v/B,re=$+(Y-$)*Z,ae=U.distr;return ae==3?lo(10,re):ae==4?YM(re,U.asinh):ae==100?U.bwd(re):re}function eb(v,b){let M=Dn(v,I,b);return In(M,e[0],Kt,Zt)}n.valToIdx=v=>In(v,e[0]),n.posToIdx=eb,n.posToVal=Dn,n.valToPos=(v,b,M)=>C[b].ori==0?s(v,C[b],M?Ee:pe,M?de:0):o(v,C[b],M?Me:ne,M?Ue:0),n.setCursor=(v,b,M)=>{it=v.left,pt=v.top,ji(null,b,M)};function dp(v,b){lt(xs,Us,st.left=v),lt(xs,Go,st.width=b)}function hp(v,b){lt(xs,_o,st.top=v),lt(xs,Xo,st.height=b)}let Io=z.ori==0?dp:hp,ko=z.ori==1?dp:hp;function tb(){if(oe&&q.live)for(let v=i==2?1:0;v<g.length;v++){if(v==0&&qe)continue;let b=q.values[v],M=0;for(let U in b)et[v][M++].firstChild.nodeValue=b[U]}}function ic(v,b){if(v!=null&&(v.idxs?v.idxs.forEach((M,U)=>{ee[U]=M}):KM(v.idx)||ee.fill(v.idx),q.idx=ee[0]),oe&&q.live){for(let M=0;M<g.length;M++)(M>0||i==1&&!qe)&&rb(M,ee[M]);tb()}Ve=!1,b!==!1&&Jt("setLegend")}n.setLegend=ic;function rb(v,b){let M=g[v],U=v==0&&P==2?gn:e[v],B;qe?B=M.values(n,v,b)??At:(B=M.value(n,b==null?null:U[b],v,b),B=B==null?At:{_:B}),q.values[v]=B}function ji(v,b,M){up=it,cp=pt,[it,pt]=K.move(n,it,pt),K.left=it,K.top=pt,ve&&(ws&&_n(ws,$t(it),0,pe,ne),Cs&&_n(Cs,0,$t(pt),pe,ne));let U,B=Kt>Zt;Wn=Qe,di=null;let $=z.ori==0?pe:ne,Y=z.ori==1?pe:ne;if(it<0||ir==0||B){U=K.idx=null;for(let Z=0;Z<g.length;Z++){let re=hr[Z];re!=null&&_n(re,-10,-10,pe,ne)}Tn&&zn(null,Is,!0,v==null&&Bt.setSeries),q.live&&(ee.fill(U),Ve=!0)}else{let Z,re,ae;i==1&&(Z=z.ori==0?it:pt,re=Dn(Z,I),U=K.idx=In(re,e[0],Kt,Zt),ae=O(e[0][U],z,$,0));let ue=-10,he=-10,Ie=0,He=0,Le=!0,Ae="",be="";for(let me=i==2?1:0;me<g.length;me++){let ot=g[me],Et=ee[me],er=Et==null?null:i==1?e[me][Et]:e[me][1][Et],Ze=K.dataIdx(n,me,U,re),Mt=Ze==null?null:i==1?e[me][Ze]:e[me][1][Ze];if(Ve=Ve||Mt!=er||Ze!=Et,ee[me]=Ze,me>0&&ot.show){let Vr=Ze==null?-10:Ze==U?ae:O(i==1?e[0][Ze]:e[me][0][Ze],z,$,0),br=Mt==null?-10:L(Mt,i==1?C[ot.scale]:C[ot.facets[1].scale],Y,0);if(Tn&&Mt!=null){let nn=z.ori==1?it:pt,mn=jt(dr.dist(n,me,Ze,br,nn));if(mn<Wn){let On=dr.bias;if(On!=0){let Hr=Dn(nn,ot.scale),sn=Mt>=0?1:-1,yn=Hr>=0?1:-1;yn==sn&&(yn==1?On==1?Mt>=Hr:Mt<=Hr:On==1?Mt<=Hr:Mt>=Hr)&&(Wn=mn,di=me)}else Wn=mn,di=me}}if(Ve||Rn){let nn,mn;z.ori==0?(nn=Vr,mn=br):(nn=br,mn=Vr);let On,Hr,sn,yn,Fn,Sr,jr=!0,Yi=Ct.bbox;if(Yi!=null){jr=!1;let xr=Yi(n,me);sn=xr.left,yn=xr.top,On=xr.width,Hr=xr.height}else sn=nn,yn=mn,On=Hr=Ct.size(n,me);if(Sr=Ct.fill(n,me),Fn=Ct.stroke(n,me),Rn)me==di&&Wn<=dr.prox&&(ue=sn,he=yn,Ie=On,He=Hr,Le=jr,Ae=Sr,be=Fn);else{let xr=hr[me];xr!=null&&(Pn[me]=sn,Bn[me]=yn,Um(xr,On,Hr,jr),Em(xr,Sr,Fn),_n(xr,an(sn),an(yn),pe,ne))}}}}if(Rn){let me=dr.prox,ot=Hi==null?Wn<=me:Wn>me||di!=Hi;if(Ve||ot){let Et=hr[0];Et!=null&&(Pn[0]=ue,Bn[0]=he,Um(Et,Ie,He,Le),Em(Et,Ae,be),_n(Et,an(ue),an(he),pe,ne))}}}if(st.show&&ui)if(v!=null){let[Z,re]=Bt.scales,[ae,ue]=Bt.match,[he,Ie]=v.cursor.sync.scales,He=v.cursor.drag;if(qt=He._x,Qt=He._y,qt||Qt){let{left:Le,top:Ae,width:be,height:me}=v.select,ot=v.scales[he].ori,Et=v.posToVal,er,Ze,Mt,Vr,br,nn=Z!=null&&ae(Z,he),mn=re!=null&&ue(re,Ie);nn&&qt?(ot==0?(er=Le,Ze=be):(er=Ae,Ze=me),Mt=C[Z],Vr=O(Et(er,he),Mt,$,0),br=O(Et(er+Ze,he),Mt,$,0),Io(En(Vr,br),jt(br-Vr))):Io(0,$),mn&&Qt?(ot==1?(er=Le,Ze=be):(er=Ae,Ze=me),Mt=C[re],Vr=L(Et(er,Ie),Mt,Y,0),br=L(Et(er+Ze,Ie),Mt,Y,0),ko(En(Vr,br),jt(br-Vr))):ko(0,Y)}else ac()}else{let Z=jt(up-ap),re=jt(cp-lp);if(z.ori==1){let Ie=Z;Z=re,re=Ie}qt=sr.x&&Z>=sr.dist,Qt=sr.y&&re>=sr.dist;let ae=sr.uni;ae!=null?qt&&Qt&&(qt=Z>=ae,Qt=re>=ae,!qt&&!Qt&&(re>Z?Qt=!0:qt=!0)):sr.x&&sr.y&&(qt||Qt)&&(qt=Qt=!0);let ue,he;qt&&(z.ori==0?(ue=bs,he=it):(ue=Ss,he=pt),Io(En(ue,he),jt(he-ue)),Qt||ko(0,Y)),Qt&&(z.ori==1?(ue=bs,he=it):(ue=Ss,he=pt),ko(En(ue,he),jt(he-ue)),qt||Io(0,$)),!qt&&!Qt&&(Io(0,0),ko(0,0))}if(sr._x=qt,sr._y=Qt,v==null){if(M){if(xp!=null){let[Z,re]=Bt.scales;Bt.values[0]=Z!=null?Dn(z.ori==0?it:pt,Z):null,Bt.values[1]=re!=null?Dn(z.ori==1?it:pt,re):null}Mo(Gc,n,it,pt,pe,ne,U)}if(Tn){let Z=M&&Bt.setSeries,re=dr.prox;Hi==null?Wn<=re&&zn(di,Is,!0,Z):Wn>re?zn(null,Is,!0,Z):di!=Hi&&zn(di,Is,!0,Z)}}Ve&&(q.idx=U,ic()),b!==!1&&Jt("setCursor")}let hi=null;Object.defineProperty(n,"rect",{get(){return hi==null&&Eo(!1),hi}});function Eo(v=!1){v?hi=null:(hi=p.getBoundingClientRect(),Jt("syncRect",hi))}function fp(v,b,M,U,B,$,Y){K._lock||ui&&v!=null&&v.movementX==0&&v.movementY==0||(sc(v,b,M,U,B,$,Y,!1,v!=null),v!=null?ji(null,!0,!0):ji(b,!0,!1))}function sc(v,b,M,U,B,$,Y,Z,re){if(hi==null&&Eo(!1),Br(v),v!=null)M=v.clientX-hi.left,U=v.clientY-hi.top;else{if(M<0||U<0){it=-10,pt=-10;return}let[ae,ue]=Bt.scales,he=b.cursor.sync,[Ie,He]=he.values,[Le,Ae]=he.scales,[be,me]=Bt.match,ot=b.axes[0].side%2==1,Et=z.ori==0?pe:ne,er=z.ori==1?pe:ne,Ze=ot?$:B,Mt=ot?B:$,Vr=ot?U:M,br=ot?M:U;if(Le!=null?M=be(ae,Le)?a(Ie,C[ae],Et,0):-10:M=Et*(Vr/Ze),Ae!=null?U=me(ue,Ae)?a(He,C[ue],er,0):-10:U=er*(br/Mt),z.ori==1){let nn=M;M=U,U=nn}}re&&(b==null||b.cursor.event.type==Gc)&&((M<=1||M>=pe-1)&&(M=qi(M,pe)),(U<=1||U>=ne-1)&&(U=qi(U,ne))),Z?(ap=M,lp=U,[bs,Ss]=K.move(n,M,U)):(it=M,pt=U)}const oc={width:0,height:0,left:0,top:0};function ac(){Ha(oc,!1)}let pp,gp,mp,yp;function vp(v,b,M,U,B,$,Y){ui=!0,qt=Qt=sr._x=sr._y=!1,sc(v,b,M,U,B,$,Y,!0,!1),v!=null&&(nt(Xc,gh,wp,!1),Mo(wm,n,bs,Ss,pe,ne,null));let{left:Z,top:re,width:ae,height:ue}=st;pp=Z,gp=re,mp=ae,yp=ue}function wp(v,b,M,U,B,$,Y){ui=sr._x=sr._y=!1,sc(v,b,M,U,B,$,Y,!1,!0);let{left:Z,top:re,width:ae,height:ue}=st,he=ae>0||ue>0,Ie=pp!=Z||gp!=re||mp!=ae||yp!=ue;if(he&&Ie&&Ha(st),sr.setScale&&he&&Ie){let He=Z,Le=ae,Ae=re,be=ue;if(z.ori==1&&(He=re,Le=ue,Ae=Z,be=ae),qt&&ci(I,Dn(He,I),Dn(He+Le,I)),Qt)for(let me in C){let ot=C[me];me!=I&&ot.from==null&&ot.min!=Qe&&ci(me,Dn(Ae+be,me),Dn(Ae,me))}ac()}else K.lock&&(K._lock=!K._lock,ji(b,!0,v!=null));v!=null&&(Cr(Xc,gh),Mo(Xc,n,it,pt,pe,ne,null))}function nb(v,b,M,U,B,$,Y){if(K._lock)return;Br(v);let Z=ui;if(ui){let re=!0,ae=!0,ue=10,he,Ie;z.ori==0?(he=qt,Ie=Qt):(he=Qt,Ie=qt),he&&Ie&&(re=it<=ue||it>=pe-ue,ae=pt<=ue||pt>=ne-ue),he&&re&&(it=it<bs?0:pe),Ie&&ae&&(pt=pt<Ss?0:ne),ji(null,!0,!0),ui=!1}it=-10,pt=-10,ee.fill(null),ji(null,!0,!0),Z&&(ui=Z)}function Cp(v,b,M,U,B,$,Y){K._lock||(Br(v),Hu(),ac(),v!=null&&Mo(Sm,n,it,pt,pe,ne,null))}function bp(){y.forEach(dU),Xt(n.width,n.height,!0)}ss(uu,Js,bp);const ks={};ks.mousedown=vp,ks.mousemove=fp,ks.mouseup=wp,ks.dblclick=Cp,ks.setSeries=(v,b,M,U)=>{let B=Bt.match[2];M=B(n,b,M),M!=-1&&zn(M,U,!0,!1)},ve&&(nt(wm,p,vp),nt(Gc,p,fp),nt(Cm,p,v=>{Br(v),Eo(!1)}),nt(bm,p,nb),nt(Sm,p,Cp),xh.add(n),n.syncRect=Eo);const ja=n.hooks=r.hooks||{};function Jt(v,b,M){ec?xo.push([v,b,M]):v in ja&&ja[v].forEach(U=>{U.call(null,n,b,M)})}(r.plugins||[]).forEach(v=>{for(let b in v.hooks)ja[b]=(ja[b]||[]).concat(v.hooks[b])});const Sp=(v,b,M)=>M,Bt=zt({key:null,setSeries:!1,filters:{pub:Bm,sub:Bm},scales:[I,g[1]?g[1].scale:null],match:[zm,zm,Sp],values:[null,null]},K.sync);Bt.match.length==2&&Bt.match.push(Sp),K.sync=Bt;const xp=Bt.key,lc=bC(xp);function Mo(v,b,M,U,B,$,Y){Bt.filters.pub(v,b,M,U,B,$,Y)&&lc.pub(v,b,M,U,B,$,Y)}lc.sub(n);function ib(v,b,M,U,B,$,Y){Bt.filters.sub(v,b,M,U,B,$,Y)&&ks[v](null,b,M,U,B,$,Y)}n.pub=ib;function sb(){lc.unsub(n),xh.delete(n),kt.clear(),vh(uu,Js,bp),u.remove(),Ce==null||Ce.remove(),Jt("destroy")}n.destroy=sb;function uc(){Jt("init",r,e),Jf(e||r.data,!1),V[I]?tc(I,V[I]):Hu(),ft=st.show&&(st.width>0||st.height>0),Tt=Ve=!0,Xt(r.width,r.height)}return g.forEach(Pt),y.forEach(FC),t?t instanceof HTMLElement?(t.appendChild(u),uc()):t(n,uc):uc(),n}yr.assign=zt;yr.fmtNum=Nf;yr.rangeNum=cu;yr.rangeLog=Ou;yr.rangeAsinh=_f;yr.orient=ps;yr.pxRatio=je;yr.join=r5;yr.fmtDate=Hf,yr.tzDate=f5;yr.sync=bC;{yr.addGap=K5,yr.clipGaps=_u;let r=yr.paths={points:MC};r.linear=AC,r.stepped=Q5,r.bars=J5,r.spline=tU}function hU(r,e){const t=/^#([0-9a-fA-F]{6})([0-9a-fA-F]{2})?$/.exec(r.trim());return t?`#${t[1]}${e}`:r}function BC({data:r,seriesKeys:e,seriesLabels:t,colors:n,height:i=300,tickRate:s=60,windowSeconds:o=20,hoveredKey:a=null,onHoverKey:l}){const u=N.useRef(null),c=N.useRef(null),d=N.useRef(null),h=N.useMemo(()=>e.join("|"),[e]),f=N.useMemo(()=>{const w=Math.max(1,Math.round(o*s)),g=Math.max(0,r.length-w),y=r.slice(g),C=Math.max(0,w-y.length),x=new Array(w);for(let E=0;E<w;E++)x[E]=E;const I=e.map(()=>new Array(w).fill(0));for(let E=0;E<y.length;E++){const A=y[E],R=C+E;for(let F=0;F<e.length;F++){const z=e[F],P=Number(A[z]??0);I[F][R]=Number.isFinite(P)?P:0}}return{x,series:I,windowPoints:w}},[r,e,s,o]),p=N.useMemo(()=>[f.x,...f.series],[f]),m=N.useMemo(()=>{const w=typeof globalThis.devicePixelRatio=="number"?globalThis.devicePixelRatio:1,g=[{label:"t"},...e.map((y,C)=>{const x=n[C%n.length]??"#4fc1ff";return{label:t[y]??y,stroke:x,width:2,points:{show:!1}}})];return{width:800,height:i,pxAlign:0,pxRatio:w,padding:[10,10,10,10],scales:{x:{time:!1},y:{}},axes:[{stroke:"#555",grid:{stroke:"#222",width:1},size:0,values:(y,C)=>C.map(()=>"")},{stroke:"#555",grid:{stroke:"#222",width:1}}],series:g,legend:{show:!1},cursor:{drag:{x:!1,y:!1}},hooks:{setCursor:[y=>{var F;if(!l)return;const C=y.cursor.idx;if(C==null||C<0){d.current!==null&&(d.current=null,l(null));return}const x=y.cursor.top;if(x==null||!Number.isFinite(x)){d.current!==null&&(d.current=null,l(null));return}let I=null,E=Number.POSITIVE_INFINITY;for(let z=1;z<y.series.length;z++){const P=e[z-1],O=(F=y.data[z])==null?void 0:F[C];if(O==null||!Number.isFinite(O))continue;const L=y.valToPos(O,"y",!0),V=Math.abs(L-x);V<E&&(E=V,I=P)}const R=E<=12?I:null;d.current!==R&&(d.current=R,l(R))}]}}},[n,i,l,e,t]),S=N.useMemo(()=>e.map((w,g)=>{const y=n[g%n.length]??"#4fc1ff",C=a!=null&&a===w;return{stroke:a!=null&&a!==w?hU(y,"66"):y,width:C?3:2}}),[n,a,e]);return N.useEffect(()=>{var I;const w=u.current;if(!w)return;const g=()=>{l&&d.current!==null&&(d.current=null,l(null))};w.addEventListener("mouseleave",g),(I=c.current)==null||I.destroy(),c.current=null;const y=new yr(m,p,w);c.current=y;const C=new ResizeObserver(()=>{const E=w.getBoundingClientRect();y.setSize({width:Math.max(1,Math.floor(E.width)),height:i})});C.observe(w);const x=w.getBoundingClientRect();return y.setSize({width:Math.max(1,Math.floor(x.width)),height:i}),()=>{w.removeEventListener("mouseleave",g),C.disconnect(),y.destroy(),c.current=null}},[m,p,i,l,h]),N.useEffect(()=>{var w;(w=c.current)==null||w.setData(p)},[p]),N.useEffect(()=>{const w=c.current;if(w)for(let g=0;g<S.length;g++){const y=g+1,C=S[g],x=w.series[y];!x||!C||(x.stroke!==C.stroke||x.width!==C.width)&&w.setSeries(y,{stroke:C.stroke,width:C.width})}},[S]),k.jsx("div",{ref:u,style:{width:"100%",height:i}})}const Dr=(r,e)=>r===e?0:r<e?-1:1,ry=(r,e)=>r.localeCompare(e,void 0,{numeric:!0}),gl=r=>(r??"").trim();function fU({sortedTraffic:r,topTraffic:e,chartData:t,topKeys:n,keyToLabel:i,keyToColor:s,tickRate:o,hoveredTrafficKey:a,setHoveredTrafficKey:l}){const[u,c]=N.useState("bps"),[d,h]=N.useState("desc"),[f,p]=N.useState("bps"),[m,S]=N.useState("desc"),[w,g]=N.useState("bps"),[y,C]=N.useState("desc"),x=T=>{if(T===u){h(_=>_==="asc"?"desc":"asc");return}c(T),h(T==="name"?"asc":"desc")},I=T=>{if(T===w){C(_=>_==="asc"?"desc":"asc");return}g(T),C(T==="name"?"asc":"desc")},E=T=>{if(T===f){S(_=>_==="asc"?"desc":"asc");return}p(T),S(T==="name"?"asc":"desc")},A=(T,_,j)=>{const G=j==="asc"?1:-1,ee=[...T];return ee.sort((q,K)=>{let oe=0;switch(_){case"id":oe=Dr(q.id,K.id);break;case"name":{const ve=gl(q.name),ge=gl(K.name);oe=ry(ve,ge),oe===0&&(oe=Dr(q.id,K.id));break}case"encoding":{const ve=gl(q.encoding),ge=gl(K.encoding);oe=ry(ve,ge),oe===0&&(oe=Dr(q.id,K.id));break}case"bps":oe=Dr(q.bps,K.bps),oe===0&&(oe=Dr(q.total,K.total));break;case"total":oe=Dr(q.total,K.total),oe===0&&(oe=Dr(q.bps,K.bps));break;case"size":{const ve=q.size.x*q.size.y,ge=K.size.x*K.size.y;oe=Dr(ve,ge),oe===0&&(oe=Dr(q.id,K.id));break}case"position":{oe=Dr(q.position.x,K.position.x),oe===0&&(oe=Dr(q.position.y,K.position.y)),oe===0&&(oe=Dr(q.id,K.id));break}case"zIndex":oe=Dr(q.zIndex,K.zIndex),oe===0&&(oe=Dr(q.id,K.id));break}return oe*G}),ee},R=N.useMemo(()=>r.filter(T=>T.key.startsWith("layer-")),[r]),F=N.useMemo(()=>r.filter(T=>T.key.startsWith("misc-")),[r]),z=N.useMemo(()=>r.filter(T=>T.key.startsWith("display-")),[r]),P=N.useMemo(()=>A(R,u,d),[R,d,u]),O=N.useMemo(()=>A(F,w,y),[F,y,w]),L=N.useMemo(()=>A(z,f,m),[z,m,f]),V={userSelect:"none",cursor:"pointer"},X=(T,_,j)=>T!==_?"":j==="asc"?" ▲":" ▼";return k.jsxs("div",{style:{position:"absolute",inset:0,display:"flex",flexDirection:"column",gap:12,padding:12,overflow:"auto",background:"#1b1b1b",color:"#cccccc"},children:[k.jsx("div",{style:{fontSize:13,color:"#e0e0e0",fontWeight:600},children:"Bandwidth"}),R.length===0&&F.length===0&&k.jsx("div",{style:{color:"#888",fontSize:12},children:"No bandwidth data yet. Move the client or send data to see traffic."}),R.length>0&&e.length>0&&k.jsxs("div",{style:{width:"100%",height:300,border:"1px solid #333",background:"#111",padding:"8px 12px 12px",boxSizing:"border-box"},children:[k.jsx("div",{style:{marginBottom:8,color:"#aaa",fontSize:12},children:"Lines — per-layer bandwidth (B/s, last samples)"}),k.jsx(BC,{data:t,seriesKeys:n,seriesLabels:i,colors:n.map(T=>s[T]??"#4fc1ff"),height:260,tickRate:o,windowSeconds:60,hoveredKey:a,onHoverKey:l})]}),R.length>0&&k.jsxs("div",{style:{border:"1px solid #333",background:"#111",padding:"10px 12px",display:"flex",flexDirection:"column",gap:6},children:[k.jsx("div",{style:{color:"#aaa",fontSize:12,marginBottom:2},children:"Layers"}),k.jsxs("div",{style:{display:"grid",gridTemplateColumns:"70px 1.1fr 0.55fr 0.7fr 0.7fr 0.8fr 0.9fr 0.6fr",gap:6,color:"#aaa",fontSize:12},children:[k.jsxs("div",{style:V,onClick:()=>x("id"),title:"Sort by ID",children:["ID",X("id",u,d)]}),k.jsxs("div",{style:V,onClick:()=>x("name"),title:"Sort by name",children:["Name",X("name",u,d)]}),k.jsxs("div",{style:V,onClick:()=>x("encoding"),title:"Sort by encoding",children:["Encoding",X("encoding",u,d)]}),k.jsxs("div",{style:{...V,textAlign:"right"},onClick:()=>x("bps"),title:"Sort by Network/s",children:["Network/s",X("bps",u,d)]}),k.jsxs("div",{style:{...V,textAlign:"right"},onClick:()=>x("total"),title:"Sort by Network",children:["Network",X("total",u,d)]}),k.jsxs("div",{style:{...V,textAlign:"right"},onClick:()=>x("size"),title:"Sort by size",children:["Size",X("size",u,d)]}),k.jsxs("div",{style:{...V,textAlign:"right"},onClick:()=>x("position"),title:"Sort by position",children:["Position",X("position",u,d)]}),k.jsxs("div",{style:{...V,textAlign:"right"},onClick:()=>x("zIndex"),title:"Sort by zIndex",children:["zIndex",X("zIndex",u,d)]})]}),P.map(T=>k.jsxs("div",{onMouseEnter:()=>l(T.key),onMouseLeave:()=>l(null),style:{display:"grid",gridTemplateColumns:"70px 1.1fr 0.55fr 0.7fr 0.7fr 0.8fr 0.9fr 0.6fr",gap:6,fontSize:12,color:a===T.key?"#fff":"#ccc",borderTop:"1px solid #222",paddingTop:4,background:a===T.key?"#1a1a1a":"transparent",outline:a===T.key?"1px solid #2a2a2a":"none",cursor:"default"},children:[k.jsx("div",{style:{color:"#ccc"},children:T.id}),k.jsxs("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[k.jsx("span",{style:{display:"inline-block",width:10,height:10,borderRadius:2,marginRight:8,verticalAlign:"middle",background:s[T.key]??"#666",boxShadow:a===T.key?`0 0 0 1px #000, 0 0 0 2px ${s[T.key]??"#666"}`:"0 0 0 1px #000"}}),(()=>{var j;const _=((j=T.name)==null?void 0:j.trim())||`Layer ${T.id}`;return T.id===255?`${_} (debug)`:_})()]}),k.jsx("div",{style:{color:"#bbb"},children:T.encoding??""}),k.jsxs("div",{style:{textAlign:"right"},children:[Kr(T.bps),"/s"]}),k.jsx("div",{style:{textAlign:"right"},children:Kr(T.total)}),k.jsxs("div",{style:{textAlign:"right",color:"#999"},children:[T.size.x,"×",T.size.y]}),k.jsxs("div",{style:{textAlign:"right",color:"#999"},children:[T.position.x,"/",T.position.y]}),k.jsx("div",{style:{textAlign:"right",color:"#999"},children:T.zIndex})]},T.key))]}),z.length>0&&k.jsxs("div",{style:{border:"1px solid #333",background:"#111",padding:"10px 12px",display:"flex",flexDirection:"column",gap:6},children:[k.jsx("div",{style:{color:"#aaa",fontSize:12,marginBottom:2},children:"Displays"}),k.jsxs("div",{style:{display:"grid",gridTemplateColumns:"70px 1.2fr 0.7fr 0.7fr 0.8fr 0.9fr 0.6fr",gap:6,color:"#aaa",fontSize:12},children:[k.jsxs("div",{style:V,onClick:()=>E("id"),title:"Sort by ID",children:["ID",X("id",f,m)]}),k.jsxs("div",{style:V,onClick:()=>E("name"),title:"Sort by name",children:["Name",X("name",f,m)]}),k.jsxs("div",{style:{...V,textAlign:"right"},onClick:()=>E("bps"),title:"Sort by Network/s",children:["Network/s",X("bps",f,m)]}),k.jsxs("div",{style:{...V,textAlign:"right"},onClick:()=>E("total"),title:"Sort by Network",children:["Network",X("total",f,m)]}),k.jsxs("div",{style:{...V,textAlign:"right"},onClick:()=>E("size"),title:"Sort by size",children:["Size",X("size",f,m)]}),k.jsxs("div",{style:{...V,textAlign:"right"},onClick:()=>E("position"),title:"Sort by position",children:["Position",X("position",f,m)]}),k.jsx("div",{style:{textAlign:"right",opacity:.6},children:"zIndex"})]}),L.map(T=>{var _;return k.jsxs("div",{onMouseEnter:()=>l(T.key),onMouseLeave:()=>l(null),style:{display:"grid",gridTemplateColumns:"70px 1.2fr 0.7fr 0.7fr 0.8fr 0.9fr 0.6fr",gap:6,fontSize:12,color:a===T.key?"#fff":"#ccc",borderTop:"1px solid #222",paddingTop:4,background:a===T.key?"#1a1a1a":"transparent",outline:a===T.key?"1px solid #2a2a2a":"none",cursor:"default"},children:[k.jsx("div",{style:{color:"#ccc"},children:T.id}),k.jsxs("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[k.jsx("span",{style:{display:"inline-block",width:10,height:10,borderRadius:2,marginRight:8,verticalAlign:"middle",background:s[T.key]??"#666",boxShadow:a===T.key?`0 0 0 1px #000, 0 0 0 2px ${s[T.key]??"#666"}`:"0 0 0 1px #000"}}),((_=T.name)==null?void 0:_.trim())||`Display ${T.id}`]}),k.jsxs("div",{style:{textAlign:"right"},children:[Kr(T.bps),"/s"]}),k.jsx("div",{style:{textAlign:"right"},children:Kr(T.total)}),k.jsxs("div",{style:{textAlign:"right",color:"#999"},children:[T.size.x,"×",T.size.y]}),k.jsxs("div",{style:{textAlign:"right",color:"#999"},children:[T.position.x,"/",T.position.y]}),k.jsx("div",{style:{textAlign:"right",color:"#666"},children:"—"})]},T.key)})]}),F.length>0&&k.jsxs("div",{style:{border:"1px solid #333",background:"#111",padding:"10px 12px",display:"flex",flexDirection:"column",gap:6},children:[k.jsx("div",{style:{color:"#aaa",fontSize:12,marginBottom:2},children:"Updates (non-layer)"}),k.jsxs("div",{style:{display:"grid",gridTemplateColumns:"70px 1.2fr 0.7fr 0.7fr 0.8fr 0.9fr 0.6fr",gap:6,color:"#aaa",fontSize:12},children:[k.jsxs("div",{style:V,onClick:()=>I("id"),title:"Sort by ID",children:["ID",X("id",w,y)]}),k.jsxs("div",{style:V,onClick:()=>I("name"),title:"Sort by name",children:["Name",X("name",w,y)]}),k.jsxs("div",{style:{...V,textAlign:"right"},onClick:()=>I("bps"),title:"Sort by Network/s",children:["Network/s",X("bps",w,y)]}),k.jsxs("div",{style:{...V,textAlign:"right"},onClick:()=>I("total"),title:"Sort by Network",children:["Network",X("total",w,y)]}),k.jsx("div",{style:{textAlign:"right",opacity:.6},children:"Size"}),k.jsx("div",{style:{textAlign:"right",opacity:.6},children:"Position"}),k.jsx("div",{style:{textAlign:"right",opacity:.6},children:"zIndex"})]}),O.map(T=>k.jsxs("div",{onMouseEnter:()=>l(T.key),onMouseLeave:()=>l(null),style:{display:"grid",gridTemplateColumns:"70px 1.2fr 0.7fr 0.7fr 0.8fr 0.9fr 0.6fr",gap:6,fontSize:12,color:a===T.key?"#fff":"#ccc",borderTop:"1px solid #222",paddingTop:4,background:a===T.key?"#1a1a1a":"transparent",outline:a===T.key?"1px solid #2a2a2a":"none",cursor:"default"},children:[k.jsx("div",{style:{color:"#ccc"},children:T.id}),k.jsxs("div",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[k.jsx("span",{style:{display:"inline-block",width:10,height:10,borderRadius:2,marginRight:8,verticalAlign:"middle",background:s[T.key]??"#666",boxShadow:a===T.key?`0 0 0 1px #000, 0 0 0 2px ${s[T.key]??"#666"}`:"0 0 0 1px #000"}}),T.name??"—"]}),k.jsxs("div",{style:{textAlign:"right"},children:[Kr(T.bps),"/s"]}),k.jsx("div",{style:{textAlign:"right"},children:Kr(T.total)}),k.jsx("div",{style:{textAlign:"right",color:"#666"},children:"—"}),k.jsx("div",{style:{textAlign:"right",color:"#666"},children:"—"}),k.jsx("div",{style:{textAlign:"right",color:"#666"},children:"—"})]},T.key))]})]})}const tr=65536,Jc=.005,ed=32;function pU({layers:r,displays:e=[],width:t,height:n,hoveredLayerId:i=null,selectedLayerIds:s=null,hoveredDisplayId:o=null,selectedDisplayId:a=null,focusRect:l=null,focusKey:u="",onSelectLayer:c,onSelectDisplay:d,onToolRectCommit:h}){const f=N.useRef(null),[p,m]=N.useState(1),[S,w]=N.useState({x:0,y:0}),g=N.useRef(!1),y=N.useRef({x:0,y:0}),C=N.useRef(""),[x,I]=N.useState(!1),[E,A]=N.useState(null),[R,F]=N.useState(null),[z,P]=N.useState("none"),[O,L]=N.useState(null),V=N.useRef(null),[X,T]=N.useState(!1),_=N.useRef(!1),j=N.useRef(!1),G=N.useCallback((Q,W,le)=>{const ye=t/le,de=n/le,Ue=ye*.5,Ee=de*.5,Me=Math.max(0,tr-ye)+Ue,Ne=Math.max(0,tr-de)+Ee,we=-Ue,Oe=-Ee;return{x:Math.max(we,Math.min(Me,Q)),y:Math.max(Oe,Math.min(Ne,W))}},[t,n]),ee=N.useCallback(()=>{const Q=tr*p,W=tr*p,le=Q<t?(t-Q)/2:0,ye=W<n?(n-W)/2:0;return{toScreenX:Ne=>(Ne-S.x)*p+le,toScreenY:Ne=>(Ne-S.y)*p+ye,toWorldX:Ne=>(Ne-le)/p+S.x,toWorldY:Ne=>(Ne-ye)/p+S.y}},[n,S.x,S.y,p,t]),q=N.useCallback((Q,W)=>{let le=null;for(let ye=0;ye<r.length;ye++){const de=r[ye];if(Q<de.x||Q>de.x+de.width||W<de.y||W>de.y+de.height)continue;const Ue=de.zIndex??0;(!le||Ue>le.z)&&(le={id:de.id,z:Ue})}if(le)return{kind:"layer",id:le.id,zIndex:le.z};for(let ye=e.length-1;ye>=0;ye--){const de=e[ye];if(Q>=de.x&&Q<=de.x+de.width&&W>=de.y&&W<=de.y+de.height)return{kind:"display",id:de.id}}return null},[e,r]),K=N.useCallback((Q,W)=>{const le=[];for(let ye=0;ye<r.length;ye++){const de=r[ye];Q<de.x||Q>de.x+de.width||W<de.y||W>de.y+de.height||le.push({id:de.id,zIndex:de.zIndex??0,name:de.name})}return le.sort((ye,de)=>de.zIndex-ye.zIndex),le},[r]);N.useEffect(()=>{const Q=f.current;if(!Q)return;const W=Q.getContext("2d");if(!W)return;W.clearRect(0,0,t,n),W.fillStyle="#0a0e14",W.fillRect(0,0,t,n);const le=tr*p,ye=tr*p,de=le<t?(t-le)/2:0,Ue=ye<n?(n-ye)/2:0,Ee=we=>(we-S.x)*p+de,Me=we=>(we-S.y)*p+Ue;{const we=Ee(0),Oe=Ee(tr),Tt=Me(0),ft=Me(tr),Ve=Math.max(0,we),Xt=Math.min(t,Oe),Lt=Math.max(0,Tt),ai=Math.min(n,ft);if(!(Xt<=Ve||ai<=Lt)){const Li=[{step:1,alpha:.06,lineWidth:1,minGapPx:8},{step:16,alpha:.1,lineWidth:1,minGapPx:10},{step:256,alpha:.16,lineWidth:1.25,minGapPx:12},{step:4096,alpha:.22,lineWidth:1.5,minGapPx:14}];W.save(),W.beginPath(),W.rect(Ve,Lt,Xt-Ve,ai-Lt),W.clip();let _i=!1;for(const Fe of Li){if(Fe.step*p<Fe.minGapPx)continue;_i=!0,W.strokeStyle=`rgba(255,255,255,${Fe.alpha})`,W.lineWidth=Fe.lineWidth;const Br=bt=>(bt-de)/p+S.x,Ct=bt=>(bt-Ue)/p+S.y,dr=Math.max(0,Br(0)),Tn=Math.min(tr,Br(t)),Rn=Math.max(0,Ct(0)),hr=Math.min(tr,Ct(n)),Pn=Math.floor(dr/Fe.step)*Fe.step,Bn=Math.ceil(Tn/Fe.step)*Fe.step,gs=Math.floor(Rn/Fe.step)*Fe.step,Pt=Math.ceil(hr/Fe.step)*Fe.step;W.beginPath();for(let bt=Pn;bt<=Bn;bt+=Fe.step){if(bt<0||bt>tr)continue;const Ni=Ee(bt);W.moveTo(Ni,Lt),W.lineTo(Ni,ai)}for(let bt=gs;bt<=Pt;bt+=Fe.step){if(bt<0||bt>tr)continue;const Ni=Me(bt);W.moveTo(Ve,Ni),W.lineTo(Xt,Ni)}W.stroke()}if(!_i){const Fe=Li[Li.length-1];W.strokeStyle=`rgba(255,255,255,${Fe.alpha})`,W.lineWidth=Fe.lineWidth;const $i=Pt=>(Pt-de)/p+S.x,Br=Pt=>(Pt-Ue)/p+S.y,Ct=Math.max(0,$i(0)),dr=Math.min(tr,$i(t)),Tn=Math.max(0,Br(0)),Rn=Math.min(tr,Br(n)),hr=Math.floor(Ct/Fe.step)*Fe.step,Pn=Math.ceil(dr/Fe.step)*Fe.step,Bn=Math.floor(Tn/Fe.step)*Fe.step,gs=Math.ceil(Rn/Fe.step)*Fe.step;W.beginPath();for(let Pt=hr;Pt<=Pn;Pt+=Fe.step){if(Pt<0||Pt>tr)continue;const bt=Ee(Pt);W.moveTo(bt,Lt),W.lineTo(bt,ai)}for(let Pt=Bn;Pt<=gs;Pt+=Fe.step){if(Pt<0||Pt>tr)continue;const bt=Me(Pt);W.moveTo(Ve,bt),W.lineTo(Xt,bt)}W.stroke()}W.restore()}}const Ne=[...r].sort((we,Oe)=>(we.zIndex??0)-(Oe.zIndex??0));for(const we of Ne){const Oe=s!=null&&s.includes(we.id),Tt=i!=null&&we.id===i,ft=Ee(we.x),Ve=Me(we.y),Xt=we.width*p,Lt=we.height*p;if(ft+Xt<0||Ve+Lt<0||ft>t||Ve>n)continue;const ai=we.zIndex??0,Li=we.color??(Oe?"rgba(43, 140, 255, 0.60)":Tt?"rgba(102, 217, 239, 0.40)":"rgba(43, 140, 255, 0.42)");if(W.fillStyle=Li,W.fillRect(ft,Ve,Math.max(Xt,1),Math.max(Lt,1)),W.strokeStyle=Oe?"#66d9ef":Tt?"rgba(102, 217, 239, 0.70)":"rgba(255,255,255,0.30)",W.lineWidth=Oe?2:1,W.strokeRect(ft,Ve,Math.max(Xt,1),Math.max(Lt,1)),p>=3&&Xt>=40&&Lt>=16){W.font="11px monospace",W.textBaseline="top";const _i=`z=${ai}`,Fe=4,$i=3,Ct=W.measureText(_i).width+Fe*2,dr=14;W.fillStyle="rgba(0,0,0,0.55)",W.fillRect(ft+3,Ve+3,Ct,dr),W.fillStyle="rgba(255,255,255,0.85)",W.fillText(_i,ft+3+Fe,Ve+3+$i)}}for(const we of e){const Oe=a!=null&&we.id===a,Tt=o!=null&&we.id===o,ft=Ee(we.x),Ve=Me(we.y),Xt=we.width*p,Lt=we.height*p;ft+Xt<0||Ve+Lt<0||ft>t||Ve>n||(W.strokeStyle=Oe?"rgba(255, 120, 120, 1)":Tt?"rgba(255, 120, 120, 0.8)":"rgba(255, 80, 80, 0.9)",W.lineWidth=Oe?3:2,W.strokeRect(ft,Ve,Math.max(Xt,1),Math.max(Lt,1)))}if(O){const we=Ee(O.x),Oe=Me(O.y),Tt=O.width*p,ft=O.height*p;W.strokeStyle="rgba(43, 140, 255, 1)",W.lineWidth=2,W.setLineDash([6,4]),W.strokeRect(we,Oe,Math.max(Tt,1),Math.max(ft,1)),W.setLineDash([])}},[r,e,t,n,p,S,i,s,o,a,O]);const oe=N.useCallback((Q,W)=>{var we;const le=(we=f.current)==null?void 0:we.getBoundingClientRect();if(!le)return null;const ye=Q-le.left,de=W-le.top,{toWorldX:Ue,toWorldY:Ee}=ee(),Me=Ue(ye),Ne=Ee(de);return{x:Me,y:Ne}},[ee]),ve=N.useCallback((Q,W)=>{const le=Math.floor(Math.min(Q.x,W.x)),ye=Math.floor(Math.min(Q.y,W.y)),de=Math.ceil(Math.max(Q.x,W.x)),Ue=Math.ceil(Math.max(Q.y,W.y));return{x:le,y:ye,width:Math.max(1,de-le),height:Math.max(1,Ue-ye)}},[]);N.useEffect(()=>{if(!l){C.current="";return}const Q=`${u}-${l.id}-${l.x}-${l.y}-${l.width}-${l.height}-${t}-${n}`;if(Q===C.current)return;if(j.current){j.current=!1,C.current=Q;return}C.current=Q;const W=1.25,le=Math.max(Jc,Math.min(ed,Math.min(t/(l.width*W),n/(l.height*W)))),ye=t/le,de=n/le,Ue=l.x+l.width/2,Ee=l.y+l.height/2,Me=G(Ue-ye/2,Ee-de/2,le);m(le),w(Me)},[l,u,t,n,G]);const ge=N.useCallback(Q=>{var Lt;const W=(Lt=f.current)==null?void 0:Lt.getBoundingClientRect();if(!W)return;Q.preventDefault();const le=Q.clientX-W.left,ye=Q.clientY-W.top,{toWorldX:de,toWorldY:Ue}=ee(),Ee=de(le),Me=Ue(ye),Ne=Q.deltaY<0?1.15:1/1.15,we=Math.max(Jc,Math.min(ed,p*Ne)),Oe=tr*we,Tt=tr*we,ft=Oe<t?(t-Oe)/2:0,Ve=Tt<n?(n-Tt)/2:0,Xt=G(Ee-(le-ft)/we,Me-(ye-Ve)/we,we);m(we),w(Xt)},[G,ee,n,S,p,t]);N.useEffect(()=>{const Q=f.current;if(!Q)return;const W=le=>ge(le);return Q.addEventListener("wheel",W,{passive:!1}),()=>Q.removeEventListener("wheel",W)},[ge]);const Ce=N.useCallback(Q=>{g.current=!0,I(!0),y.current={x:Q.clientX,y:Q.clientY}},[]),ct=N.useCallback(()=>{g.current=!1,I(!1)},[]),dt=N.useCallback(()=>{g.current=!1,I(!1),A(null)},[]),xe=N.useCallback(Q=>{const W=oe(Q.clientX,Q.clientY);if(!W||z!=="rect"||!h)return;Q.preventDefault(),Q.stopPropagation(),_.current=!0;const le={x:Math.floor(W.x),y:Math.floor(W.y)};V.current={startWorld:le,moved:!1},T(!0),L({x:le.x,y:le.y,width:1,height:1})},[z,oe,h]),et=N.useCallback(Q=>{if(!V.current)return;const W=oe(Q.clientX,Q.clientY);if(!W)return;const le=ve(V.current.startWorld,W);if(!V.current.moved){const ye=Math.abs(W.x-V.current.startWorld.x),de=Math.abs(W.y-V.current.startWorld.y);(ye>0||de>0)&&(V.current.moved=!0)}L(le)},[oe,ve]),Ke=N.useCallback(()=>{!V.current||!O||(_.current=!0,h==null||h(O),j.current=!0,V.current=null,L(null),T(!1),P("none"))},[O,h]),qe=N.useCallback(Q=>{if(V.current){if(Q.preventDefault(),Q.stopPropagation(),!V.current.moved){_.current=!0,V.current=null,L(null),T(!1),P("none");return}Ke()}},[Ke]);N.useEffect(()=>{if(!X)return;const Q=le=>{et(le)},W=le=>{qe(le)};return window.addEventListener("mousemove",Q,!0),window.addEventListener("mouseup",W,!0),()=>{window.removeEventListener("mousemove",Q,!0),window.removeEventListener("mouseup",W,!0)}},[X,et,qe]),N.useEffect(()=>{if(!V.current)return;const Q=W=>{W.key==="Enter"&&Ke()};return window.addEventListener("keydown",Q),()=>window.removeEventListener("keydown",Q)},[Ke]);const At=N.useCallback(Q=>{var we;if(V.current){et(Q);return}if(g.current){const Oe=Q.clientX-y.current.x,Tt=Q.clientY-y.current.y;y.current={x:Q.clientX,y:Q.clientY},w(ft=>G(ft.x-Oe/p,ft.y-Tt/p,p));return}const W=(we=f.current)==null?void 0:we.getBoundingClientRect();if(!W)return;const le=Q.clientX-W.left,ye=Q.clientY-W.top,{toWorldX:de,toWorldY:Ue}=ee(),Ee=Math.floor(de(le)),Me=Math.floor(Ue(ye)),Ne=q(Ee,Me);if(!Ne){A({kind:"layer",id:-1,world:{x:Ee,y:Me},screen:{x:le,y:ye}});return}A({kind:Ne.kind,id:Ne.id,world:{x:Ee,y:Me},screen:{x:le,y:ye}})},[G,ee,q,p]),wt=N.useCallback(Q=>{var Oe;if(_.current){_.current=!1;return}if(z==="rect"||V.current||x)return;const W=(Oe=f.current)==null?void 0:Oe.getBoundingClientRect();if(!W)return;const le=Q.clientX-W.left,ye=Q.clientY-W.top,{toWorldX:de,toWorldY:Ue}=ee(),Ee=Math.floor(de(le)),Me=Math.floor(Ue(ye)),Ne=K(Ee,Me);if(Ne.length>=2){F({open:!0,anchorScreen:{x:le,y:ye},world:{x:Ee,y:Me},layers:Ne});return}const we=q(Ee,Me);we&&(we.kind==="layer"&&(c==null||c(we.id,{metaKey:Q.metaKey,ctrlKey:Q.ctrlKey})),we.kind==="display"&&(d==null||d(we.id)))},[z,ee,q,K,x,d,c]);N.useEffect(()=>{const Q=W=>{W.key==="Escape"&&F(null)};return window.addEventListener("keydown",Q),()=>window.removeEventListener("keydown",Q)},[]);const Ft=N.useCallback(()=>{m(1),w(G(0,0,1))},[G]),cr=N.useCallback(Q=>{var Oe;const W=(Oe=f.current)==null?void 0:Oe.getBoundingClientRect();if(!W)return;const le=W.width/2,ye=W.height/2,{toWorldX:de,toWorldY:Ue}=ee(),Ee=de(le),Me=Ue(ye),Ne=Math.max(Jc,Math.min(ed,p*Q)),we=G(Ee-le/Ne,Me-ye/Ne,Ne);m(Ne),w(we)},[G,ee,p]),tt=E&&E.id!==-1?E:null,kt=n<520?6:10,nt=Math.max(40,n-kt*2),Cr=88,Se=42,Re=nt<150,pe=nt<240,ne=nt<200,$e=Math.min(1,Math.max(.7,nt/(Re?64:Cr))),ht=Math.min(1,Math.max(.7,nt/Se));return k.jsxs("div",{style:{position:"absolute",inset:0},children:[k.jsx("canvas",{ref:f,width:t,height:n,style:{display:"block",cursor:z==="rect"?(V.current,"crosshair"):g.current?"grabbing":"grab"},onMouseDown:Q=>{if(z==="rect"&&h){xe(Q);return}Ce(Q)},onMouseMove:At,onMouseUp:Q=>{if(V.current){qe(Q);return}ct()},onMouseLeave:dt,onClick:wt}),k.jsxs("div",{style:{position:"absolute",right:kt,bottom:pe?void 0:kt,top:pe?kt:void 0,display:"flex",flexDirection:Re?"row":"column",alignItems:"center",gap:6,padding:6,background:"rgba(20, 22, 26, 0.85)",border:"1px solid rgba(255,255,255,0.14)",borderRadius:10,boxShadow:"0 10px 26px rgba(0,0,0,0.45)",pointerEvents:"auto",transform:$e===1?void 0:`scale(${$e})`,transformOrigin:pe?"top right":"bottom right",maxWidth:`calc(100% - ${kt*2}px)`},onMouseDown:Q=>Q.stopPropagation(),children:[k.jsx("button",{onClick:()=>{const Q=z==="rect"?"none":"rect";V.current=null,T(!1),P(Q)},style:{width:34,height:34,borderRadius:8,border:z==="rect"?"1px solid rgba(79, 193, 255, 0.9)":"1px solid rgba(255,255,255,0.18)",background:z==="rect"?"rgba(14, 99, 156, 0.7)":"rgba(255,255,255,0.06)",color:"#e6e6e6",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",padding:0},title:z==="rect"?"Rectangle tool (active)":"Rectangle tool",children:k.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:k.jsx("rect",{x:"5",y:"7",width:"14",height:"10",rx:"1"})})}),k.jsx("button",{onClick:()=>{V.current=null,T(!1),P("none")},style:{width:34,height:34,borderRadius:8,border:"1px solid rgba(255,255,255,0.18)",background:z==="none"?"rgba(255,255,255,0.10)":"rgba(255,255,255,0.06)",color:"#e6e6e6",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",padding:0},title:"Drag/Pan",children:"↔"})]}),(R==null?void 0:R.open)&&R.layers.length>=2&&k.jsxs("div",{style:{position:"absolute",left:Math.min(t-220,R.anchorScreen.x+12),top:Math.min(n-260,R.anchorScreen.y-12),width:210,padding:8,background:"rgba(10, 12, 16, 0.94)",border:"1px solid rgba(255,255,255,0.14)",borderRadius:10,boxShadow:"0 10px 30px rgba(0,0,0,0.55)",color:"#e6e6e6",fontSize:12},children:[k.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[k.jsx("div",{style:{fontWeight:700},children:"Stack"}),k.jsx("button",{onClick:()=>F(null),style:{...ml,padding:"2px 6px",borderRadius:8},title:"Close",children:"✕"})]}),k.jsxs("div",{style:{color:"#9aa7b2",marginTop:4},children:["World: ",R.world.x.toFixed(0),",",R.world.y.toFixed(0)]}),k.jsx("div",{style:{marginTop:8,display:"flex",flexDirection:"column",gap:6,maxHeight:220,overflow:"auto",paddingRight:2},children:R.layers.map((Q,W)=>{var le;return k.jsx("button",{onClick:ye=>{c==null||c(Q.id,{metaKey:ye.metaKey,ctrlKey:ye.ctrlKey}),F(null)},style:{textAlign:"left",width:"100%",background:"rgba(255,255,255,0.04)",border:"1px solid rgba(255,255,255,0.10)",borderRadius:10,padding:"8px 10px",cursor:"pointer",color:"#e6e6e6",position:"relative"},title:"Select layer",children:k.jsxs("div",{style:{fontWeight:650},children:[(le=Q.name)!=null&&le.trim()?Q.name:`Layer ${Q.id}`," ",k.jsxs("span",{style:{color:"#9aa7b2",fontWeight:500},children:["z=",Q.zIndex]}),W===0&&k.jsx("span",{style:{marginLeft:6,color:"#66d9ef",fontWeight:650},children:"top"})]})},Q.id)})})]}),k.jsxs("div",{style:{position:"absolute",top:10,left:10,display:"flex",gap:6,padding:6,background:"rgba(15, 18, 24, 0.85)",border:"1px solid rgba(255,255,255,0.12)",borderRadius:8,backdropFilter:"blur(6px)",fontSize:12,color:"#cfcfcf"},children:[k.jsx("button",{onClick:()=>cr(1.15),style:ml,title:"Zoom in",children:"+"}),k.jsx("button",{onClick:()=>cr(1/1.15),style:ml,title:"Zoom out",children:"−"}),k.jsx("button",{onClick:Ft,style:ml,title:"Reset view",children:"Reset"})]}),k.jsxs("div",{style:{position:"absolute",left:kt,bottom:ne?void 0:kt,top:ne?kt:void 0,padding:"6px 8px",background:"rgba(15, 18, 24, 0.75)",border:"1px solid rgba(255,255,255,0.10)",borderRadius:8,backdropFilter:"blur(6px)",fontSize:12,color:"#cfcfcf",transform:ht===1?void 0:`scale(${ht})`,transformOrigin:ne?"top left":"bottom left",maxWidth:`calc(100% - ${kt*2}px)`,overflow:"hidden",whiteSpace:"nowrap"},children:[k.jsx("span",{style:{color:"#9aa7b2"},children:"Zoom:"})," ",p.toFixed(3),"x"," ",k.jsx("span",{style:{color:"#9aa7b2"},children:"| Offset:"})," (",S.x.toFixed(0),","," ",S.y.toFixed(0),")",E&&k.jsxs(k.Fragment,{children:[k.jsx("span",{style:{color:"#9aa7b2"},children:"| Mouse:"})," (",E.world.x.toFixed(0),",",E.world.y.toFixed(0),")"]})]}),tt&&k.jsxs("div",{style:{position:"absolute",left:Math.min(t-260,tt.screen.x+12),top:Math.min(n-80,tt.screen.y+12),width:240,padding:"8px 10px",background:"rgba(10, 12, 16, 0.92)",border:"1px solid rgba(255,255,255,0.14)",borderRadius:8,fontSize:12,color:"#e6e6e6",pointerEvents:"none"},children:[k.jsx("div",{style:{fontWeight:600,marginBottom:4},children:tt.kind==="layer"?`Layer ${tt.id}`:`Display ${tt.id}`}),tt.kind==="layer"&&typeof tt.zIndex=="number"&&k.jsxs("div",{style:{color:"#b7c0c8"},children:["zIndex: ",tt.zIndex]}),k.jsxs("div",{style:{color:"#b7c0c8"},children:["World: ",tt.world.x.toFixed(0),",",tt.world.y.toFixed(0)]}),k.jsxs("div",{style:{color:"#b7c0c8"},children:["Screen: ",tt.screen.x.toFixed(0),",",tt.screen.y.toFixed(0)]})]})]})}const ml={background:"rgba(255,255,255,0.06)",border:"1px solid rgba(255,255,255,0.14)",color:"#ddd",borderRadius:6,padding:"4px 8px",cursor:"pointer",lineHeight:1};var zC={},Zf={},qf={},Co={};Object.defineProperty(Co,"__esModule",{value:!0});Co.Direction=void 0;var ny;(function(r){r.Right="to right",r.Left="to left",r.Down="to bottom",r.Up="to top"})(ny||(Co.Direction=ny={}));(function(r){var e=Nr&&Nr.__spreadArray||function(P,O,L){if(L||arguments.length===2)for(var V=0,X=O.length,T;V<X;V++)(T||!(V in O))&&(T||(T=Array.prototype.slice.call(O,0,V)),T[V]=O[V]);return P.concat(T||Array.prototype.slice.call(O))};Object.defineProperty(r,"__esModule",{value:!0}),r.isIOS=r.useThumbOverlap=r.assertUnreachable=r.voidFn=r.getTrackBackground=r.replaceAt=r.schd=r.translate=r.getClosestThumbIndex=r.translateThumbs=r.getPaddingAndBorder=r.getMargin=r.checkInitialOverlap=r.checkValuesAgainstBoundaries=r.checkBoundaries=r.isVertical=r.relativeValue=r.normalizeValue=r.isStepDivisible=r.isTouchEvent=r.getStepDecimals=void 0;var t=N,n=Co,i=function(P){var O=P.toString().split(".")[1];return O?O.length:0};r.getStepDecimals=i;function s(P){return P.touches&&P.touches.length||P.changedTouches&&P.changedTouches.length}r.isTouchEvent=s;function o(P,O,L){var V=(O-P)/L,X=8,T=Number(V.toFixed(X));return parseInt(T.toString(),10)===T}r.isStepDivisible=o;function a(P,O,L,V,X,T,_){var j=1e11;if(P=Math.round(P*j)/j,!T){var G=_[O-1],ee=_[O+1];if(G&&G>P)return G;if(ee&&ee<P)return ee}if(P>V)return V;if(P<L)return L;var q=Math.floor(P*j-L*j)%Math.floor(X*j),K=Math.floor(P*j-Math.abs(q)),oe=q===0?P:K/j,ve=Math.abs(q/j)<X/2?oe:oe+X,ge=(0,r.getStepDecimals)(X);return parseFloat(ve.toFixed(ge))}r.normalizeValue=a;function l(P,O,L){return(P-O)/(L-O)}r.relativeValue=l;function u(P){return P===n.Direction.Up||P===n.Direction.Down}r.isVertical=u;function c(P,O,L){if(O>=L)throw new RangeError("min (".concat(O,") is equal/bigger than max (").concat(L,")"));if(P<O)throw new RangeError("value (".concat(P,") is smaller than min (").concat(O,")"));if(P>L)throw new RangeError("value (".concat(P,") is bigger than max (").concat(L,")"))}r.checkBoundaries=c;function d(P,O,L){return P<O?O:P>L?L:P}r.checkValuesAgainstBoundaries=d;function h(P){if(!(P.length<2)&&!P.slice(1).every(function(O,L){return P[L]<=O}))throw new RangeError("values={[".concat(P,"]} needs to be sorted when allowOverlap={false}"))}r.checkInitialOverlap=h;function f(P){var O=window.getComputedStyle(P);return{top:parseInt(O["margin-top"],10),bottom:parseInt(O["margin-bottom"],10),left:parseInt(O["margin-left"],10),right:parseInt(O["margin-right"],10)}}r.getMargin=f;function p(P){var O=window.getComputedStyle(P);return{top:parseInt(O["padding-top"],10)+parseInt(O["border-top-width"],10),bottom:parseInt(O["padding-bottom"],10)+parseInt(O["border-bottom-width"],10),left:parseInt(O["padding-left"],10)+parseInt(O["border-left-width"],10),right:parseInt(O["padding-right"],10)+parseInt(O["border-right-width"],10)}}r.getPaddingAndBorder=p;function m(P,O,L){var V=L?-1:1;P.forEach(function(X,T){return w(X,V*O[T].x,O[T].y)})}r.translateThumbs=m;function S(P,O,L,V){for(var X=0,T=F(P[0],O,L,V),_=1;_<P.length;_++){var j=F(P[_],O,L,V);j<T&&(T=j,X=_)}return X}r.getClosestThumbIndex=S;function w(P,O,L){P.style.transform="translate(".concat(O,"px, ").concat(L,"px)")}r.translate=w;var g=function(P){var O=[],L=null,V=function(){for(var X=[],T=0;T<arguments.length;T++)X[T]=arguments[T];O=X,!L&&(L=requestAnimationFrame(function(){L=null,P.apply(void 0,O)}))};return V};r.schd=g;function y(P,O,L){var V=P.slice(0);return V[O]=L,V}r.replaceAt=y;function C(P){var O=P.values,L=P.colors,V=P.min,X=P.max,T=P.direction,_=T===void 0?n.Direction.Right:T,j=P.rtl,G=j===void 0?!1:j;G&&_===n.Direction.Right?_=n.Direction.Left:G&&n.Direction.Left&&(_=n.Direction.Right);var ee=O.slice(0).sort(function(K,oe){return K-oe}).map(function(K){return(K-V)/(X-V)*100}),q=ee.reduce(function(K,oe,ve){return"".concat(K,", ").concat(L[ve]," ").concat(oe,"%, ").concat(L[ve+1]," ").concat(oe,"%")},"");return"linear-gradient(".concat(_,", ").concat(L[0]," 0%").concat(q,", ").concat(L[L.length-1]," 100%)")}r.getTrackBackground=C;function x(){}r.voidFn=x;function I(P){throw new Error("Didn't expect to get here")}r.assertUnreachable=I;var E=function(P,O,L,V,X){X===void 0&&(X=function(_){return _});var T=Math.ceil(e([P],Array.from(P.children),!0).reduce(function(_,j){var G=Math.ceil(j.getBoundingClientRect().width);if(j.innerText&&j.innerText.includes(L)&&j.childElementCount===0){var ee=j.cloneNode(!0);ee.innerHTML=X(O.toFixed(V)),ee.style.visibility="hidden",document.body.appendChild(ee),G=Math.ceil(ee.getBoundingClientRect().width),document.body.removeChild(ee)}return G>_?G:_},P.getBoundingClientRect().width));return T},A=function(P,O,L,V,X,T,_){_===void 0&&(_=function(ee){return ee});var j=[],G=function(ee){var q=E(L[ee],V[ee],X,T,_),K=O[ee].x;O.forEach(function(oe,ve){var ge=oe.x,Ce=E(L[ve],V[ve],X,T,_);ee!==ve&&(K>=ge&&K<=ge+Ce||K+q>=ge&&K+q<=ge+Ce)&&(j.includes(ve)||(j.push(ee),j.push(ve),j=e(e([],j,!0),[ee,ve],!1),G(ve)))})};return G(P),Array.from(new Set(j.sort()))},R=function(P,O,L,V,X,T){V===void 0&&(V=.1),X===void 0&&(X=" - "),T===void 0&&(T=function(ve){return ve});var _=(0,r.getStepDecimals)(V),j=(0,t.useState)({}),G=j[0],ee=j[1],q=(0,t.useState)(T(O[L].toFixed(_))),K=q[0],oe=q[1];return(0,t.useEffect)(function(){if(P){var ve=P.getThumbs();if(ve.length<1)return;var ge={},Ce=P.getOffsets(),ct=A(L,Ce,ve,O,X,_,T),dt=T(O[L].toFixed(_));if(ct.length){var xe=ct.reduce(function(wt,Ft,cr,tt){return wt.length?e(e([],wt,!0),[Ce[tt[cr]].x],!1):[Ce[tt[cr]].x]},[]);if(Math.min.apply(Math,xe)===Ce[L].x){var et=[];ct.forEach(function(wt){et.push(O[wt].toFixed(_))}),dt=Array.from(new Set(et.sort(function(wt,Ft){return parseFloat(wt)-parseFloat(Ft)}))).map(T).join(X);var Ke=Math.min.apply(Math,xe),qe=Math.max.apply(Math,xe),At=ve[ct[xe.indexOf(qe)]].getBoundingClientRect().width;ge.left="".concat(Math.abs(Ke-(qe+At))/2,"px"),ge.transform="translate(-50%, 0)"}else ge.visibility="hidden"}oe(dt),ee(ge)}},[P,O]),[K,G]};r.useThumbOverlap=R;function F(P,O,L,V){var X=P.getBoundingClientRect(),T=X.left,_=X.top,j=X.width,G=X.height;return u(V)?Math.abs(L-(_+G/2)):Math.abs(O-(T+j/2))}var z=function(){var P,O=((P=navigator.userAgentData)===null||P===void 0?void 0:P.platform)||navigator.platform;return["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(O)||navigator.userAgent.includes("Mac")&&"ontouchend"in document};r.isIOS=z})(qf);var gU=Nr&&Nr.__extends||function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&(n[s]=i[s])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}}(),mU=Nr&&Nr.__createBinding||(Object.create?function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,i)}:function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]}),yU=Nr&&Nr.__setModuleDefault||(Object.create?function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}:function(r,e){r.default=e}),vU=Nr&&Nr.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&mU(e,r,t);return yU(e,r),e},iy=Nr&&Nr.__spreadArray||function(r,e,t){if(t||arguments.length===2)for(var n=0,i=e.length,s;n<i;n++)(s||!(n in e))&&(s||(s=Array.prototype.slice.call(e,0,n)),s[n]=e[n]);return r.concat(s||Array.prototype.slice.call(e))};Object.defineProperty(Zf,"__esModule",{value:!0});var yl=vU(N),ze=qf,_t=Co,wU=["ArrowRight","ArrowUp","k","PageUp"],CU=["ArrowLeft","ArrowDown","j","PageDown"],bU=function(r){gU(e,r);function e(t){var n=r.call(this,t)||this;if(n.trackRef=yl.createRef(),n.thumbRefs=[],n.state={draggedTrackPos:[-1,-1],draggedThumbIndex:-1,thumbZIndexes:new Array(n.props.values.length).fill(0).map(function(i,s){return s}),isChanged:!1,markOffsets:[]},n.getOffsets=function(){var i=n.props,s=i.direction,o=i.values,a=i.min,l=i.max,u=n.trackRef.current;if(!u)return console.warn("No track element found."),[];var c=u.getBoundingClientRect(),d=(0,ze.getPaddingAndBorder)(u);return n.getThumbs().map(function(h,f){var p={x:0,y:0},m=h.getBoundingClientRect(),S=(0,ze.getMargin)(h);switch(s){case _t.Direction.Right:return p.x=(S.left+d.left)*-1,p.y=((m.height-c.height)/2+d.top)*-1,p.x+=c.width*(0,ze.relativeValue)(o[f],a,l)-m.width/2,p;case _t.Direction.Left:return p.x=(S.right+d.right)*-1,p.y=((m.height-c.height)/2+d.top)*-1,p.x+=c.width-c.width*(0,ze.relativeValue)(o[f],a,l)-m.width/2,p;case _t.Direction.Up:return p.x=((m.width-c.width)/2+S.left+d.left)*-1,p.y=-d.left,p.y+=c.height-c.height*(0,ze.relativeValue)(o[f],a,l)-m.height/2,p;case _t.Direction.Down:return p.x=((m.width-c.width)/2+S.left+d.left)*-1,p.y=-d.left,p.y+=c.height*(0,ze.relativeValue)(o[f],a,l)-m.height/2,p;default:return(0,ze.assertUnreachable)(s)}})},n.getThumbs=function(){return n.trackRef&&n.trackRef.current?Array.from(n.trackRef.current.children).filter(function(i){return i.hasAttribute("aria-valuenow")}):(console.warn("No thumbs found in the track container. Did you forget to pass & spread the `props` param in renderTrack?"),[])},n.getTargetIndex=function(i){return n.getThumbs().findIndex(function(s){return s===i.target||s.contains(i.target)})},n.addTouchEvents=function(i){document.addEventListener("touchmove",n.schdOnTouchMove,{passive:!1}),document.addEventListener("touchend",n.schdOnEnd,{passive:!1}),document.addEventListener("touchcancel",n.schdOnEnd,{passive:!1})},n.addMouseEvents=function(i){document.addEventListener("mousemove",n.schdOnMouseMove),document.addEventListener("mouseup",n.schdOnEnd)},n.onMouseDownTrack=function(i){var s;if(!(i.button!==0||(0,ze.isIOS)()))if(i.persist(),i.preventDefault(),n.addMouseEvents(i.nativeEvent),n.props.values.length>1&&n.props.draggableTrack){if(n.thumbRefs.some(function(a){var l;return(l=a.current)===null||l===void 0?void 0:l.contains(i.target)}))return;n.setState({draggedTrackPos:[i.clientX,i.clientY]},function(){return n.onMove(i.clientX,i.clientY)})}else{var o=(0,ze.getClosestThumbIndex)(n.thumbRefs.map(function(a){return a.current}),i.clientX,i.clientY,n.props.direction);(s=n.thumbRefs[o].current)===null||s===void 0||s.focus(),n.setState({draggedThumbIndex:o},function(){return n.onMove(i.clientX,i.clientY)})}},n.onResize=function(){(0,ze.translateThumbs)(n.getThumbs(),n.getOffsets(),n.props.rtl),n.calculateMarkOffsets()},n.onTouchStartTrack=function(i){var s;if(i.persist(),n.addTouchEvents(i.nativeEvent),n.props.values.length>1&&n.props.draggableTrack){if(n.thumbRefs.some(function(a){var l;return(l=a.current)===null||l===void 0?void 0:l.contains(i.target)}))return;n.setState({draggedTrackPos:[i.touches[0].clientX,i.touches[0].clientY]},function(){return n.onMove(i.touches[0].clientX,i.touches[0].clientY)})}else{var o=(0,ze.getClosestThumbIndex)(n.thumbRefs.map(function(a){return a.current}),i.touches[0].clientX,i.touches[0].clientY,n.props.direction);(s=n.thumbRefs[o].current)===null||s===void 0||s.focus(),n.setState({draggedThumbIndex:o},function(){return n.onMove(i.touches[0].clientX,i.touches[0].clientY)})}},n.onMouseOrTouchStart=function(i){if(!n.props.disabled){var s=(0,ze.isTouchEvent)(i);if(!(!s&&i.button!==0)){var o=n.getTargetIndex(i);o!==-1&&(s?n.addTouchEvents(i):n.addMouseEvents(i),n.setState({draggedThumbIndex:o,thumbZIndexes:n.state.thumbZIndexes.map(function(a,l){return l===o?Math.max.apply(Math,n.state.thumbZIndexes):a<=n.state.thumbZIndexes[o]?a:a-1})}))}}},n.onMouseMove=function(i){i.preventDefault(),n.onMove(i.clientX,i.clientY)},n.onTouchMove=function(i){i.preventDefault(),n.onMove(i.touches[0].clientX,i.touches[0].clientY)},n.onKeyDown=function(i){var s=n.props,o=s.values,a=s.onChange,l=s.step,u=s.rtl,c=s.direction,d=n.state.isChanged,h=n.getTargetIndex(i.nativeEvent),f=u||c===_t.Direction.Left||c===_t.Direction.Down?-1:1;h!==-1&&(wU.includes(i.key)?(i.preventDefault(),n.setState({draggedThumbIndex:h,isChanged:!0}),a((0,ze.replaceAt)(o,h,n.normalizeValue(o[h]+f*(i.key==="PageUp"?l*10:l),h)))):CU.includes(i.key)?(i.preventDefault(),n.setState({draggedThumbIndex:h,isChanged:!0}),a((0,ze.replaceAt)(o,h,n.normalizeValue(o[h]-f*(i.key==="PageDown"?l*10:l),h)))):i.key==="Tab"?n.setState({draggedThumbIndex:-1},function(){d&&n.fireOnFinalChange()}):d&&n.fireOnFinalChange())},n.onKeyUp=function(i){var s=n.state.isChanged;n.setState({draggedThumbIndex:-1},function(){s&&n.fireOnFinalChange()})},n.onMove=function(i,s){var o=n.state,a=o.draggedThumbIndex,l=o.draggedTrackPos,u=n.props,c=u.direction,d=u.min,h=u.max,f=u.onChange,p=u.values,m=u.step,S=u.rtl;if(a===-1&&l[0]===-1&&l[1]===-1)return null;var w=n.trackRef.current;if(!w)return null;var g=w.getBoundingClientRect(),y=(0,ze.isVertical)(c)?g.height:g.width;if(l[0]!==-1&&l[1]!==-1){var C=i-l[0],x=s-l[1],I=0;switch(c){case _t.Direction.Right:case _t.Direction.Left:I=C/y*(h-d);break;case _t.Direction.Down:case _t.Direction.Up:I=x/y*(h-d);break;default:(0,ze.assertUnreachable)(c)}if(S&&(I*=-1),Math.abs(I)>=m/2){for(var E=0;E<n.thumbRefs.length;E++){if(p[E]===h&&Math.sign(I)===1||p[E]===d&&Math.sign(I)===-1)return;var A=p[E]+I;A>h?I=h-p[E]:A<d&&(I=d-p[E])}for(var R=p.slice(0),E=0;E<n.thumbRefs.length;E++)R=(0,ze.replaceAt)(R,E,n.normalizeValue(p[E]+I,E));n.setState({draggedTrackPos:[i,s]}),f(R)}}else{var F=0;switch(c){case _t.Direction.Right:F=(i-g.left)/y*(h-d)+d;break;case _t.Direction.Left:F=(y-(i-g.left))/y*(h-d)+d;break;case _t.Direction.Down:F=(s-g.top)/y*(h-d)+d;break;case _t.Direction.Up:F=(y-(s-g.top))/y*(h-d)+d;break;default:(0,ze.assertUnreachable)(c)}S&&(F=h+d-F),Math.abs(p[a]-F)>=m/2&&f((0,ze.replaceAt)(p,a,n.normalizeValue(F,a)))}},n.normalizeValue=function(i,s){var o=n.props,a=o.min,l=o.max,u=o.step,c=o.allowOverlap,d=o.values;return(0,ze.normalizeValue)(i,s,a,l,u,c,d)},n.onEnd=function(i){if(i.preventDefault(),document.removeEventListener("mousemove",n.schdOnMouseMove),document.removeEventListener("touchmove",n.schdOnTouchMove),document.removeEventListener("mouseup",n.schdOnEnd),document.removeEventListener("touchend",n.schdOnEnd),document.removeEventListener("touchcancel",n.schdOnEnd),n.state.draggedThumbIndex===-1&&n.state.draggedTrackPos[0]===-1&&n.state.draggedTrackPos[1]===-1)return null;n.setState({draggedThumbIndex:-1,draggedTrackPos:[-1,-1]},function(){n.fireOnFinalChange()})},n.fireOnFinalChange=function(){n.setState({isChanged:!1});var i=n.props,s=i.onFinalChange,o=i.values;s&&s(o)},n.updateMarkRefs=function(i){if(!i.renderMark){n.numOfMarks=void 0,n.markRefs=void 0;return}n.numOfMarks=(i.max-i.min)/n.props.step,n.markRefs=[];for(var s=0;s<n.numOfMarks+1;s++)n.markRefs[s]=yl.createRef()},n.calculateMarkOffsets=function(){if(!(!n.props.renderMark||!n.trackRef||!n.numOfMarks||!n.markRefs||n.trackRef.current===null)){for(var i=window.getComputedStyle(n.trackRef.current),s=parseInt(i.width,10),o=parseInt(i.height,10),a=parseInt(i.paddingLeft,10),l=parseInt(i.paddingTop,10),u=[],c=0;c<n.numOfMarks+1;c++){var d=9999,h=9999;if(n.markRefs[c].current){var f=n.markRefs[c].current.getBoundingClientRect();d=f.height,h=f.width}n.props.direction===_t.Direction.Left||n.props.direction===_t.Direction.Right?u.push([Math.round(s/n.numOfMarks*c+a-h/2),-Math.round((d-o)/2)]):u.push([Math.round(o/n.numOfMarks*c+l-d/2),-Math.round((h-s)/2)])}n.setState({markOffsets:u})}},t.step===0)throw new Error('"step" property should be a positive number');return n.schdOnMouseMove=(0,ze.schd)(n.onMouseMove),n.schdOnTouchMove=(0,ze.schd)(n.onTouchMove),n.schdOnEnd=(0,ze.schd)(n.onEnd),n.thumbRefs=t.values.map(function(){return yl.createRef()}),n.updateMarkRefs(t),n}return e.prototype.componentDidMount=function(){var t=this,n=this.props,i=n.values,s=n.min,o=n.step;this.resizeObserver=window.ResizeObserver?new window.ResizeObserver(this.onResize):{observe:function(){return window.addEventListener("resize",t.onResize)},unobserve:function(){return window.removeEventListener("resize",t.onResize)}},document.addEventListener("touchstart",this.onMouseOrTouchStart,{passive:!1}),document.addEventListener("mousedown",this.onMouseOrTouchStart,{passive:!1}),!this.props.allowOverlap&&(0,ze.checkInitialOverlap)(this.props.values),this.props.values.forEach(function(a){return(0,ze.checkBoundaries)(a,t.props.min,t.props.max)}),this.resizeObserver.observe(this.trackRef.current),(0,ze.translateThumbs)(this.getThumbs(),this.getOffsets(),this.props.rtl),this.calculateMarkOffsets(),i.forEach(function(a){(0,ze.isStepDivisible)(s,a,o)||console.warn("The `values` property is in conflict with the current `step`, `min`, and `max` properties. Please provide values that are accessible using the min, max, and step values.")})},e.prototype.componentDidUpdate=function(t,n){var i=this.props,s=i.max,o=i.min,a=i.step,l=i.values,u=i.rtl;(t.max!==s||t.min!==o||t.step!==a)&&this.updateMarkRefs(this.props),(0,ze.translateThumbs)(this.getThumbs(),this.getOffsets(),u),(t.max!==s||t.min!==o||t.step!==a||n.markOffsets.length!==this.state.markOffsets.length)&&(this.calculateMarkOffsets(),l.forEach(function(c){(0,ze.isStepDivisible)(o,c,a)||console.warn("The `values` property is in conflict with the current `step`, `min`, and `max` properties. Please provide values that are accessible using the min, max, and step values.")}))},e.prototype.componentWillUnmount=function(){var t={passive:!1};document.removeEventListener("mousedown",this.onMouseOrTouchStart,t),document.removeEventListener("mousemove",this.schdOnMouseMove),document.removeEventListener("touchmove",this.schdOnTouchMove),document.removeEventListener("touchstart",this.onMouseOrTouchStart),document.removeEventListener("mouseup",this.schdOnEnd),document.removeEventListener("touchend",this.schdOnEnd),this.resizeObserver.unobserve(this.trackRef.current)},e.prototype.render=function(){var t=this,n=this.props,i=n.label,s=n.labelledBy,o=n.renderTrack,a=n.renderThumb,l=n.renderMark,u=l===void 0?function(){return null}:l,c=n.values,d=n.min,h=n.max,f=n.allowOverlap,p=n.disabled,m=this.state,S=m.draggedThumbIndex,w=m.thumbZIndexes,g=m.markOffsets;return o({props:{style:{transform:"scale(1)",cursor:S>-1?"grabbing":this.props.draggableTrack?(0,ze.isVertical)(this.props.direction)?"ns-resize":"ew-resize":c.length===1&&!p?"pointer":"inherit"},onMouseDown:p?ze.voidFn:this.onMouseDownTrack,onTouchStart:p?ze.voidFn:this.onTouchStartTrack,ref:this.trackRef},isDragged:this.state.draggedThumbIndex>-1,disabled:p,children:iy(iy([],g.map(function(y,C,x){return u({props:{style:t.props.direction===_t.Direction.Left||t.props.direction===_t.Direction.Right?{position:"absolute",left:"".concat(y[0],"px"),marginTop:"".concat(y[1],"px")}:{position:"absolute",top:"".concat(y[0],"px"),marginLeft:"".concat(y[1],"px")},key:"mark".concat(C),ref:t.markRefs[C]},index:C})}),!0),c.map(function(y,C){var x=t.state.draggedThumbIndex===C;return a({index:C,value:y,isDragged:x,props:{style:{position:"absolute",zIndex:w[C],cursor:p?"inherit":x?"grabbing":"grab",userSelect:"none",touchAction:"none",WebkitUserSelect:"none",MozUserSelect:"none",msUserSelect:"none"},key:C,tabIndex:p?void 0:0,"aria-valuemax":f?h:c[C+1]||h,"aria-valuemin":f?d:c[C-1]||d,"aria-valuenow":y,draggable:!1,ref:t.thumbRefs[C],"aria-label":i,"aria-labelledby":s,role:"slider",onKeyDown:p?ze.voidFn:t.onKeyDown,onKeyUp:p?ze.voidFn:t.onKeyUp}})}),!0)})},e.defaultProps={label:"Accessibility label",labelledBy:null,step:1,direction:_t.Direction.Right,rtl:!1,disabled:!1,allowOverlap:!1,draggableTrack:!1,min:0,max:100},e}(yl.Component);Zf.default=bU;(function(r){var e=Nr&&Nr.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(r,"__esModule",{value:!0}),r.checkValuesAgainstBoundaries=r.relativeValue=r.useThumbOverlap=r.Direction=r.getTrackBackground=r.Range=void 0;var t=e(Zf);r.Range=t.default;var n=qf;Object.defineProperty(r,"getTrackBackground",{enumerable:!0,get:function(){return n.getTrackBackground}}),Object.defineProperty(r,"useThumbOverlap",{enumerable:!0,get:function(){return n.useThumbOverlap}}),Object.defineProperty(r,"relativeValue",{enumerable:!0,get:function(){return n.relativeValue}}),Object.defineProperty(r,"checkValuesAgainstBoundaries",{enumerable:!0,get:function(){return n.checkValuesAgainstBoundaries}});var i=Co;Object.defineProperty(r,"Direction",{enumerable:!0,get:function(){return i.Direction}})})(zC);const Yr={fontSize:12,color:"#9aa7b2"},sy={background:"rgba(255,255,255,0.04)",border:"1px solid rgba(255,255,255,0.12)",borderRadius:10};function Zo(r,e,t){return Math.max(e,Math.min(t,r))}function oy(r,e){const t=r.replace("#",""),n=parseInt(t.slice(0,2),16),i=parseInt(t.slice(2,4),16),s=parseInt(t.slice(4,6),16);return`rgba(${n},${i},${s},${Zo(e,0,1)})`}function SU(r){const e=["#66d9ef","#a6e22e","#fd971f","#e6db74","#f92672","#ae81ff","#2aa198"];return e[Math.abs(r)%e.length]}function DC(r,e){const t=(r??"").trim();return t.length?t:e}function xU(r,e){return r.map(t=>{const n=e.get(t);return n?{id:t,name:DC(n.name,`Layer ${t}`),z:n.z,layer:{id:n.id,name:n.name,z:n.z,origin:n.origin,width:n.width,height:n.height}}:null}).filter(Boolean)}function IU({user:r,selectedDisplayId:e,selectedLayerIds:t,onSelectLayer:n,onSelectDisplay:i,setVisibleLayers:s}){var C;const o=N.useMemo(()=>r.displays.filter(x=>x.id!==255),[r.displays]),[a,l]=N.useState(null),[u,c]=N.useState([0,0]),d=N.useRef(null),h=N.useMemo(()=>{var E,A,R;const x=(E=o.find(F=>F.id===e))==null?void 0:E.id;if(x!=null)return x;const I=(A=o.find(F=>F.id===a))==null?void 0:A.id;return I??((R=o[0])==null?void 0:R.id)??null},[a,o,e]),f=N.useMemo(()=>h==null?null:o.find(x=>x.id===h)??null,[o,h]),p=N.useMemo(()=>{var I,E;if(h==null)return null;const x=(E=(I=r.displayComposite)==null?void 0:I[h])==null?void 0:E.layerIdsTopToBottom;return x&&x.length?x:null},[h,r.displayComposite]),m=N.useMemo(()=>{const x=new Map;for(const I of r.layers)x.set(I.id,{id:I.id,name:I.name,z:I.z,origin:I.origin,width:I.width,height:I.height});return x},[r.layers]),S=N.useMemo(()=>{var z,P;if(h==null)return[];const x=(P=(z=r.displayComposite)==null?void 0:z[h])==null?void 0:P.layerIdsTopToBottom;if(x&&x.length)return xU(x,m);if(!f)return[];const I=f.origin.x,E=f.origin.y,A=I+f.size.x,R=E+f.size.y,F=[];for(const O of r.layers){const L=O.origin.x,V=O.origin.y,X=O.origin.x+O.width,T=O.origin.y+O.height;A<=L||I>=X||R<=V||E>=T||F.push({id:O.id,name:DC(O.name,`Layer ${O.id}`),z:O.z,layer:O})}return F.sort((O,L)=>L.z-O.z),F},[h,f,m,r.displayComposite,r.layers]);N.useEffect(()=>{const x=S.length;if(!x){c([0,0]);return}const I=Math.max(0,x-1);c([0,I])},[h,S.length]);const w=N.useMemo(()=>{const x=Math.max(0,S.length-1);let I=Zo(u[0],0,x),E=Zo(u[1],0,x);return I>E&&([I,E]=[E,I]),[I,E]},[S.length,u]),g=N.useMemo(()=>{if(!S.length)return S;const[x,I]=w;return S.slice(x,I+1)},[S,w]);N.useEffect(()=>{if(!s)return;if(!S.length){s(null);return}const[x,I]=w;if(x===0&&I===S.length-1){s(null);return}s(g.map(A=>A.id))},[S.length,w,s,g]);const y=N.useMemo(()=>{if(!f)return null;const x=g;if(!S.length)return{visible:[],minY:f.origin.y,maxY:f.origin.y+f.size.y,range:[0,0]};const[I,E]=w,A=x;let R=f.origin.y,F=f.origin.y+f.size.y;for(const z of A){const P=z.layer;P&&(R=Math.min(R,P.origin.y),F=Math.max(F,P.origin.y+P.height))}return{visible:A,minY:R,maxY:F,range:[I,E]}},[f,S.length,w,g]);return N.useEffect(()=>{const x=d.current;if(!x||!f||!y)return;const I=x.getContext("2d");if(!I)return;const E=window.devicePixelRatio||1,A=x.clientWidth,R=x.clientHeight,F=Math.max(1,Math.floor(A*E)),z=Math.max(1,Math.floor(R*E));(x.width!==F||x.height!==z)&&(x.width=F,x.height=z),I.setTransform(E,0,0,E,0,0),I.clearRect(0,0,A,R);const P=14,O=Math.max(1,A-P*2),L=Math.max(1,R-P*2),V=y.minY,X=y.maxY,T=Math.max(1,X-V),_=f.origin.x,j=f.origin.x+f.size.x,G=Math.max(1,j-_),ee=xe=>P+(xe-_)/G*O,q=xe=>xe/G*O,K=xe=>P+(xe-V)/T*L,oe=xe=>xe/T*L;I.fillStyle="rgba(0,0,0,0.20)",I.fillRect(0,0,A,R);const ve=ee(f.origin.x),ge=K(f.origin.y),Ce=q(f.size.x),ct=oe(f.size.y);I.strokeStyle="rgba(255,120,120,0.75)",I.lineWidth=1,I.strokeRect(ve,ge,Ce,ct),I.fillStyle="rgba(255,120,120,0.08)",I.fillRect(ve,ge,Ce,ct);const dt=y.visible;for(let xe=dt.length-1;xe>=0;xe--){const et=dt[xe],Ke=et.layer;if(!Ke)continue;const qe=ee(Ke.origin.x),At=K(Ke.origin.y),wt=Math.max(2,q(Ke.width)),Ft=Math.max(2,oe(Ke.height)),cr=SU(et.id),tt=t.includes(et.id);I.fillStyle=oy(cr,1),I.strokeStyle=oy(cr,tt?.95:.55),I.lineWidth=tt?2:1,I.fillRect(qe,At,wt,Ft),I.strokeRect(qe,At,wt,Ft),I.save(),I.beginPath(),I.rect(qe,At,wt,Ft),I.clip(),I.fillStyle="rgba(15,15,15,0.95)",I.font="12px Segoe UI, sans-serif";const kt=[`${et.name}`,`id ${et.id} • z ${et.z}`,`pos ${Ke.origin.x},${Ke.origin.y}`,`size ${Ke.width}×${Ke.height}`],nt=14;let Cr=At+16;const Se=qe+8;for(let Re=0;Re<kt.length&&!(Cr>At+Ft-4);Re++){const pe=kt[Re];I.fillText(pe,Se,Cr),Cr+=nt}I.restore()}dt.length===0&&(I.fillStyle="rgba(154,167,178,0.9)",I.font="12px Segoe UI, sans-serif",I.fillText("No layers in this range",P+8,P+18))},[f,t,y]),k.jsxs("div",{style:{position:"absolute",inset:0,display:"flex",flexDirection:"column",minHeight:0},children:[k.jsxs("div",{style:{padding:"10px 12px",borderBottom:"1px solid #2f2f2f",background:"#1b1d22",display:"flex",alignItems:"center",justifyContent:"space-between",gap:12},children:[k.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2},children:[k.jsx("div",{style:{fontSize:13,fontWeight:700,color:"#e6e6e6"},children:"Composer"}),k.jsx("div",{style:Yr,children:"Side stack per display (core-derived)"})]}),k.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[k.jsx("div",{style:Yr,children:"Display"}),k.jsx("select",{value:h??"",onChange:x=>{const I=x.target.value===""?null:Number(x.target.value);l(I),I!=null&&i(I)},style:{height:28,background:"#252526",color:"#cccccc",border:"1px solid #3c3c3c",borderRadius:8,padding:"0 8px",fontSize:12,outline:"none"},children:o.map(x=>k.jsx("option",{value:x.id,children:x.id},x.id))})]})]}),k.jsx("div",{style:{flex:1,minHeight:0,overflow:"auto",padding:12,background:"#14161a"},children:h==null?k.jsx("div",{style:{...Yr,padding:16},children:"No display."}):k.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 280px",gap:12,alignItems:"start"},children:[k.jsxs("div",{style:{...sy,padding:12,display:"flex",flexDirection:"column",gap:10},children:[k.jsxs("div",{style:{display:"flex",alignItems:"baseline",justifyContent:"space-between"},children:[k.jsx("div",{style:{fontWeight:700,color:"#e6e6e6"},children:"Cut-away"}),k.jsx("div",{style:Yr,children:f?`origin ${f.origin.x},${f.origin.y} • size ${f.size.x}×${f.size.y}`:""})]}),f&&k.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[k.jsx("div",{style:Yr,children:"Z range"}),k.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",gap:6},children:[k.jsx("div",{style:{padding:"6px 0"},children:k.jsx(zC.Range,{step:1,min:0,max:Math.max(0,S.length-1),values:(()=>{const x=Math.max(0,S.length-1),I=x-w[1],E=x-w[0];return[I,E]})(),onChange:x=>{const I=Math.max(0,S.length-1),E=Math.round(x[0]??0),A=Math.round(x[1]??0),R=Zo(I-A,0,I),F=Zo(I-E,0,I);c([R,F])},renderTrack:({props:x,children:I})=>k.jsxs("div",{...x,style:{...x.style,height:6,width:"100%",borderRadius:999,background:"rgba(255,255,255,0.10)",border:"1px solid rgba(255,255,255,0.12)",position:"relative"},children:[(()=>{const E=Math.max(1,S.length-1),A=(E-w[1])/E,R=(E-w[0])/E,F=A*100,z=R*100;return k.jsx("div",{style:{position:"absolute",left:`${Math.min(F,z)}%`,width:`${Math.max(0,Math.abs(z-F))}%`,top:-1,bottom:-1,borderRadius:999,background:"linear-gradient(90deg, rgba(102,217,239,0.70), rgba(253,151,31,0.70))",boxShadow:"0 0 0 1px rgba(0,0,0,0.18) inset"}})})(),I]}),renderThumb:({props:x,index:I})=>k.jsx("div",{...x,style:{...x.style,height:14,width:14,borderRadius:999,background:I===0?"#66d9ef":"#fd971f",border:"1px solid rgba(0,0,0,0.35)",boxShadow:"0 2px 10px rgba(0,0,0,0.35)"},title:I===0?"Bottom handle":"Top handle"})})}),k.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:10},children:[k.jsx("div",{style:Yr,children:"BOTTOM"}),k.jsxs("div",{style:Yr,children:[S.length?`${w[0]} → ${w[1]}`:"—",S.length?` • ${g.length}/${S.length}`:""]}),k.jsx("div",{style:Yr,children:"TOP"})]})]})]}),k.jsx("div",{style:{position:"relative",flex:1,minHeight:260},children:k.jsx("canvas",{ref:d,style:{width:"100%",height:"100%",display:"block",borderRadius:10,background:"rgba(0,0,0,0.12)",cursor:"default",pointerEvents:"none",maxWidth:800,margin:"0 auto"}})})]}),k.jsxs("div",{style:{...sy,padding:12},children:[k.jsxs("div",{style:{display:"flex",alignItems:"baseline",justifyContent:"space-between"},children:[k.jsx("div",{style:{fontWeight:700,color:"#e6e6e6"},children:"Side stack"}),k.jsxs("div",{style:Yr,children:[g.length," / ",S.length," layers"]})]}),p&&k.jsxs("div",{style:{...Yr,marginTop:6},children:["core order: top→bottom • [",p.join(", "),"]"]}),k.jsxs("div",{style:{marginTop:10,display:"flex",flexDirection:"column",gap:8},children:[S.map((x,I)=>{const E=t.includes(x.id),A=I>=w[0]&&I<=w[1];return k.jsx("button",{onClick:R=>{n(x.id,{metaKey:R.metaKey,ctrlKey:R.ctrlKey});const F=S.findIndex(z=>z.id===x.id);F>=0&&c([F,F])},style:{textAlign:"left",width:"100%",background:E?"rgba(102, 217, 239, 0.10)":A?"rgba(255,255,255,0.03)":"rgba(255,255,255,0.01)",border:E?"1px solid rgba(102, 217, 239, 0.65)":A?"1px solid rgba(255,255,255,0.10)":"1px solid rgba(255,255,255,0.06)",borderRadius:10,padding:"8px 10px",cursor:"pointer",color:A?"#e6e6e6":"rgba(230,230,230,0.55)"},title:"Select layer",children:k.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:10},children:[k.jsx("div",{style:{fontWeight:650,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:x.name}),k.jsxs("div",{style:{...Yr,whiteSpace:"nowrap"},children:["z=",x.z]})]})},x.id)}),S.length===0&&k.jsx("div",{style:{...Yr,padding:10},children:"No layers."}),((C=r.displayComposite)==null?void 0:C[h])==null&&k.jsx("div",{style:{...Yr,paddingTop:8},children:"Using fallback intersection (core composition not present)."})]})]})]})})]})}function kU({centerTab:r,setCenterTab:e,centerPanelRef:t,centerSize:n,worldLayers:i,worldDisplays:s,selectedLayerIds:o,setVisibleLayers:a,selectedDisplayId:l,focusRect:u,focusKey:c,onSelectLayer:d,onSelectDisplay:h,assetsSnapshot:f,primaryUser:p,isFloating:m,sortedTraffic:S,topTraffic:w,chartData:g,topKeys:y,keyToLabel:C,keyToColor:x,tickRate:I,hoveredTrafficKey:E,setHoveredTrafficKey:A}){return k.jsxs("div",{style:{background:"#1e1e1e",padding:0,minHeight:0,overflow:"hidden",display:"flex",flexDirection:"column"},children:[k.jsx("div",{style:{display:"flex",alignItems:"center",gap:2,padding:"4px 6px 0",background:"#252526",borderBottom:"1px solid #3c3c3c"},children:[{id:"grid",label:"World"},{id:"assets",label:"Assets"},{id:"network",label:"Network Details"},{id:"composer",label:"Composer"},{id:"renderer",label:"Renderer"}].map(R=>{const F=r===R.id;return k.jsx("button",{onClick:()=>e(R.id),style:{border:"1px solid #3c3c3c",borderBottom:F?"1px solid #1e1e1e":"1px solid #3c3c3c",background:F?"#1e1e1e":"#2d2d2d",color:"#cccccc",padding:"4px 10px",cursor:"pointer",fontSize:12,borderRadius:"4px 4px 0 0",marginBottom:"-1px"},children:R.label},R.id)})}),k.jsxs("div",{ref:t,style:{position:"relative",flex:1,minHeight:0,overflow:"hidden",background:"#1e1e1e"},children:[r==="grid"&&k.jsx(pU,{layers:i,displays:s,width:n.width,height:n.height,selectedLayerIds:o,selectedDisplayId:l,focusRect:u,focusKey:c,onSelectLayer:d,onSelectDisplay:h,onToolRectCommit:R=>{window.dispatchEvent(new window.CustomEvent("__utsp_debug_display255_rect",{detail:R}))}}),r==="composer"&&p&&k.jsx(IU,{user:p,selectedDisplayId:l,selectedLayerIds:o,onSelectLayer:d,onSelectDisplay:h,setVisibleLayers:a}),r==="composer"&&!p&&k.jsx("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",color:"#9aa7b2",fontSize:13,background:"#111"},children:"No user in snapshot."}),r==="assets"&&k.jsx(mM,{assetsSnapshot:f}),r==="renderer"&&!m&&k.jsx("div",{style:{position:"absolute",inset:0,background:"#111"}}),r==="renderer"&&m&&k.jsx("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",color:"#bbbbbb",fontSize:13,background:"#111",textAlign:"center",padding:24,lineHeight:1.5},children:'Press "Embed" on the floating renderer window to dock it here.'}),r==="network"&&k.jsx(fU,{sortedTraffic:S,topTraffic:w,chartData:g,topKeys:y,keyToLabel:C,keyToColor:x,tickRate:I,hoveredTrafficKey:E,setHoveredTrafficKey:A})]})]})}function EU(r){var d,h;const{enabled:e,snapshot:t,layers:n}=r,[i,s]=N.useState([]),o=N.useRef(null),a=N.useRef(0),l=N.useMemo(()=>{let f=0;for(let p=0;p<n.length;p++){const m=n[p].bytesPerSec1s;typeof m=="number"&&(f+=m)}return f},[n]);N.useEffect(()=>{e&&s(f=>f.length>0?f:[{time:"—",total:0}])},[e]),N.useEffect(()=>{var y,C;if(!e)return;const f=((y=t==null?void 0:t.tick)==null?void 0:y.tickRate)??((C=t==null?void 0:t.tick)==null?void 0:C.tps)??60,p=Math.max(1,Math.round(f*10)),m=performance.now?performance.now():Date.now(),S=Math.max(1,Math.round(1e3/f));if(m-a.current<S)return;a.current=m;const g={time:new Date().toLocaleTimeString("en-US",{hour12:!1,minute:"2-digit",second:"2-digit"}),total:l};s(x=>{if(o.current!==f)return o.current=f,[g];const I=x.length===0?[g]:[...x,g];return I.length>p?I.slice(I.length-p):I})},[e,l,t]);const u=o.current??((d=t==null?void 0:t.tick)==null?void 0:d.tickRate)??((h=t==null?void 0:t.tick)==null?void 0:h.tps)??60,c=N.useMemo(()=>{for(let f=0;f<i.length;f++)if(Number(i[f].total??0)>0)return!0;return!1},[i]);return{tickRate:u,data:i,hasData:c,latestBps:l}}function MU({primaryUser:r,tickRate:e,snapshot:t,assetsSnapshot:n}){const{totalBytesAll:i,totalBytesAssets:s,totalBytesNonAssets:o,totalBpsNonAssets:a}=N.useMemo(()=>{var y;const u=(r==null?void 0:r.layers)??[],c=(r==null?void 0:r.miscTraffic)??{},d=(r==null?void 0:r.displayTraffic)??{};let h=0,f=0;for(let C=0;C<u.length;C++){const x=u[C];typeof x.bytesTotal=="number"&&(h+=x.bytesTotal),typeof x.bytesPerSec1s=="number"&&(f+=x.bytesPerSec1s)}for(const C of Object.values(c))typeof(C==null?void 0:C.total)=="number"&&(h+=C.total),typeof(C==null?void 0:C.bytesPerSec1s)=="number"&&(f+=C.bytesPerSec1s);for(const C of Object.values(d))typeof(C==null?void 0:C.total)=="number"&&(h+=C.total),typeof(C==null?void 0:C.bytesPerSec1s)=="number"&&(f+=C.bytesPerSec1s);const p=Array.isArray(n==null?void 0:n.audio)?n.audio:[];let m=0;for(let C=0;C<p.length;C++){const x=(y=p[C])==null?void 0:y.originalSize;typeof x=="number"&&Number.isFinite(x)&&x>0&&(m+=x)}const S=Math.max(0,h),w=m>0?m:void 0;return{totalBytesAll:w!=null?w+S:S,totalBytesAssets:w,totalBytesNonAssets:S,totalBpsNonAssets:Math.max(0,f)}},[r,t,n]),{data:l}=EU({enabled:!0,snapshot:t,layers:(r==null?void 0:r.layers)??[]});return k.jsxs("div",{style:{borderLeft:"1px solid #3c3c3c",background:"#252526",padding:0,minHeight:0,display:"flex",flexDirection:"column"},children:[k.jsx("div",{style:{padding:"8px 12px",borderBottom:"1px solid #3c3c3c"},children:k.jsx("div",{style:{fontSize:11,color:"#bbbbbb",textTransform:"uppercase",letterSpacing:"0.5px"},children:"Network"})}),k.jsxs("div",{style:{padding:"8px 12px",display:"flex",flexDirection:"column",gap:10},children:[k.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:12},children:[k.jsx("div",{style:{fontSize:12,color:"#858585"},children:"Total assets"}),k.jsx("div",{style:{fontSize:12,color:"#cccccc"},children:Kr(s)})]}),k.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:12},children:[k.jsx("div",{style:{fontSize:12,color:"#858585"},children:"Total (non-assets)"}),k.jsx("div",{style:{fontSize:12,color:"#cccccc"},children:Kr(o)})]}),k.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:12},children:[k.jsx("div",{style:{fontSize:12,color:"#858585"},children:"Total"}),k.jsx("div",{style:{fontSize:12,color:"#cccccc"},children:Kr(i)})]}),k.jsx("div",{style:{height:1,background:"#3c3c3c",opacity:.5}}),k.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:12},children:[k.jsx("div",{style:{fontSize:12,color:"#858585"},children:"Per second"}),k.jsxs("div",{style:{fontSize:12,color:"#cccccc"},children:[Kr(a),"/s"]})]}),k.jsxs("div",{style:{width:"100%",height:160,border:"1px solid #3c3c3c",background:"#111",padding:"8px 10px 10px",boxSizing:"border-box"},children:[k.jsx("div",{style:{marginBottom:6,color:"#aaa",fontSize:12},children:"Bandwidth (total)"}),k.jsx(BC,{data:l,seriesKeys:["total"],seriesLabels:{total:"Total"},colors:["#4fc1ff"],height:120,tickRate:e,windowSeconds:10})]})]})]})}function ay({enabled:r,initialRect:e,minSize:t}){const[n,i]=N.useState(e),[s,o]=N.useState(!1),a=N.useRef({x:0,y:0}),l=N.useRef({resizing:!1,startX:0,startY:0,startW:0,startH:0});return N.useEffect(()=>{if(!r)return;const d=()=>{i(h=>{const p=Math.max(t.width,window.innerWidth-16),m=Math.max(t.height,window.innerHeight-8*2),S=Math.min(Math.max(t.width,h.width),p),w=Math.min(Math.max(t.height,h.height),m),g=Math.min(Math.max(8,h.x),Math.max(8,window.innerWidth-8-S)),y=Math.min(Math.max(8,h.y),Math.max(8,window.innerHeight-8-w));return{x:g,y,width:S,height:w}})};return d(),window.addEventListener("resize",d),()=>window.removeEventListener("resize",d)},[r,t.height,t.width]),N.useEffect(()=>{if(!r)return;const d=f=>{if(s){i(p=>({...p,x:Math.max(0,f.clientX-a.current.x),y:Math.max(0,f.clientY-a.current.y)}));return}if(l.current.resizing){const p=f.clientX-l.current.startX,m=f.clientY-l.current.startY;i(S=>({...S,width:Math.max(t.width,l.current.startW+p),height:Math.max(t.height,l.current.startH+m)}))}},h=()=>{o(!1),l.current.resizing=!1};return window.addEventListener("mousemove",d),window.addEventListener("mouseup",h),()=>{window.removeEventListener("mousemove",d),window.removeEventListener("mouseup",h)}},[r,s,t.height,t.width]),{rect:n,setRect:i,isDragging:s,startDrag:(d,h)=>{r&&(o(!0),i(f=>(a.current={x:d-f.x,y:h-f.y},f)))},startResize:(d,h)=>{r&&i(f=>(l.current={resizing:!0,startX:d,startY:h,startW:f.width,startH:f.height},f))}}}function ly(r){const[e,t]=N.useState({width:600,height:400}),[n,i]=N.useState({left:0,top:0}),[s,o]=N.useState(null);return N.useLayoutEffect(()=>{const a=r.current??null;o(l=>l===a?l:a)},[r]),N.useEffect(()=>{const a=s;if(!a)return;const l=()=>{const c=a.getBoundingClientRect();i({left:c.left,top:c.top})},u=new ResizeObserver(c=>{const d=c[0];d&&(t({width:d.contentRect.width,height:d.contentRect.height}),l())});return u.observe(a),l(),window.addEventListener("resize",l),()=>{window.removeEventListener("resize",l),u.disconnect()}},[s]),{size:e,rect:n}}function UU(r,e){const[t,n]=N.useState(null),[i,s]=N.useState([]),[o,a]=N.useState(null),[l,u]=N.useState(0),c=N.useMemo(()=>r?r.layers.map(y=>({id:y.id,x:y.origin.x,y:y.origin.y,width:y.width,height:y.height,color:i.includes(y.id)?"rgba(43, 140, 255, 0.7)":void 0})):[],[r,i]),d=N.useMemo(()=>r?r.displays.map(y=>({id:y.id,x:y.origin.x,y:y.origin.y,width:y.size.x,height:y.size.y})):[],[r]),h=N.useMemo(()=>o!=null?c.find(y=>y.id===o)??null:t!=null?d.find(y=>y.id===t)??null:null,[o,t,d,c]),f=N.useMemo(()=>`${t??"none"}-${i.join(",")}-${l}`,[t,i,l]),p=y=>{r!=null&&r.displays.some(C=>C.id===y)&&(u(C=>C+1),n(y),s([]),a(null),e.setVisibleLayers(null))},m=y=>{const C=r==null?void 0:r.layers.find(x=>x.id===y);return C?{x:C.origin.x,y:C.origin.y,width:C.width,height:C.height}:null},S=(y,C)=>{if(e.setVisibleLayersDisplay255(y.length>0?y:null),C!=null){const x=m(C);x&&e.sendDisplayTransform(x)}},w=(y,C)=>{if(!(r!=null&&r.layers.some(I=>I.id===y)))return;const x=!!(C&&(C.metaKey||C.ctrlKey));u(I=>I+1),n(null),s(I=>{if(!x)return I.includes(y)?(a(null),S([],null),[]):(a(y),S([y],y),[y]);const E=I.includes(y)?I.filter(R=>R!==y):[...I,y],A=E.length>0?E[E.length-1]:null;return a(A),S(E,A),E})},g=(y,C)=>{if(!(r!=null&&r.layers.some(I=>I.id===y)))return;const x=!!(C&&(C.metaKey||C.ctrlKey));u(I=>I+1),n(null),s(I=>{if(!x)return I.includes(y)?(a(null),S([],null),[]):(a(y),S([y],y),[y]);const E=I.includes(y)?I.filter(R=>R!==y):[...I,y],A=E.length>0?E[E.length-1]:null;return a(A),S(E,A),E})};return N.useEffect(()=>{if(!r){n(null),s([]),a(null),e.setVisibleLayers(null),e.setVisibleLayersDisplay255(null);return}const y=new Set(r.layers.map(x=>x.id)),C=new Set(r.displays.map(x=>x.id));s(x=>{const I=x.filter(A=>y.has(A)),E=I.length>0?I[I.length-1]:null;return a(E),S(I,E),I}),n(x=>x!=null&&C.has(x)?x:null)},[r,e]),{selectedDisplayId:t,selectedLayerIds:i,lastSelectedLayerId:o,focusKey:f,focusRect:h,handleSelectDisplay:p,handleSelectLayer:w,handleSelectLayerDisplay255Only:g,setFocusNonce:u}}function AU(r){const{enabled:e,snapshot:t,topKeys:n,topTraffic:i}=r,[s,o]=N.useState([]),a=N.useRef(null),l=N.useRef(0),u=N.useRef(i);u.current=i;const c=N.useMemo(()=>n.join(","),[n]);N.useEffect(()=>{e&&o(f=>{if(f.length>0)return f;const p={time:"—"};for(let m=0;m<n.length;m++)p[n[m]]=0;return[p]})},[e,c]),N.useEffect(()=>{var C,x;if(!e||!t)return;const f=((C=t==null?void 0:t.tick)==null?void 0:C.tickRate)??((x=t==null?void 0:t.tick)==null?void 0:x.tps)??60,p=Math.max(1,Math.round(f*60)),m=performance.now?performance.now():Date.now(),S=Math.max(1,Math.round(1e3/f));if(m-l.current<S)return;l.current=m;const g={time:new Date().toLocaleTimeString("en-US",{hour12:!1,minute:"2-digit",second:"2-digit"})},y=u.current;for(let I=0;I<y.length;I++){const E=y[I];g[E.key]=E.bps??0}o(I=>{if(a.current!==f)return a.current=f,[g];const E=I.length===0?[g]:[...I,g];return E.length>p?E.slice(E.length-p):E})},[e,t,c]);const d=a.current??60,h=N.useMemo(()=>{if(!e)return[];const f=new Array(s.length);for(let p=0;p<s.length;p++){const m=s[p],S={time:m.time};for(let w=0;w<n.length;w++){const g=n[w];S[g]=Number(m[g]??0)}f[p]=S}return f},[e,s,n]);return{trafficHistory:s,tickRate:d,chartData:h}}const TU=r=>typeof r!="string"?"8-bit":r.includes("16")?"16-bit":"8-bit";function RU(r){var w;const{primaryUser:e,selection:t,selectedDisplayId:n,lastSelectedLayerId:i,selectedLayerIds:s}=r,o=N.useMemo(()=>((e==null?void 0:e.displays)??[]).map(y=>({id:y.id,x:y.origin.x,y:y.origin.y,width:y.size.x,height:y.size.y})),[e]),a=((w=e==null?void 0:e.layers)==null?void 0:w.length)??0,l=N.useMemo(()=>e?!t.selectedLayerIds.length&&!e?[]:e.layers.map(g=>({id:g.id,x:g.origin.x,y:g.origin.y,width:g.width,height:g.height,zIndex:g.z??0,name:g.name})):[],[e,t.selectedLayerIds.length]),u=N.useMemo(()=>{if(!e)return null;if(s.length){const g=e.layers.find(y=>y.id===i);return g?{type:"layer",item:g}:null}if(n!=null){const g=e.displays.find(y=>y.id===n);return g?{type:"display",item:g}:null}return null},[i,e,n,s.length]),c=N.useMemo(()=>{const y=((e==null?void 0:e.layers)??[]).filter(F=>typeof F.bytesPerSec1s=="number").map(F=>({key:`layer-${F.id}`,id:F.id,name:F.name,encoding:TU(F.charCodeMode),total:F.bytesTotal??0,bps:F.bytesPerSec1s??0,size:{x:F.width,y:F.height},position:{x:F.origin.x,y:F.origin.y},zIndex:F.z??0})),C=(e==null?void 0:e.miscTraffic)??{},x=F=>{switch(F){case"update.audioOrders":return"Audio";case"update.vibrationOrders":return"Vibration";case"update.macroOrders":return"Macro";case"update.postProcessOrders":return"PostProcess";default:return F}},I=Object.entries(C).map(([F,z],P)=>({key:`misc-${F}`,id:1e5+P,name:x(F),total:z.total??0,bps:z.bytesPerSec1s??0,size:{x:0,y:0},position:{x:0,y:0},zIndex:0})),E=((e==null?void 0:e.displays)??[]).filter(F=>F.id!==255),A=(e==null?void 0:e.displayTraffic)??{},R=E.map(F=>{const z=A[F.id];return{key:`display-${F.id}`,id:F.id,name:`Display ${F.id}`,total:(z==null?void 0:z.total)??0,bps:(z==null?void 0:z.bytesPerSec1s)??0,size:{x:F.size.x,y:F.size.y},position:{x:F.origin.x,y:F.origin.y},zIndex:0}}).filter(F=>typeof F.bps=="number");return[...y,...R,...I]},[e]),d=N.useMemo(()=>[...c].sort((g,y)=>y.total-g.total),[c]),h=N.useMemo(()=>d.slice(0,6),[d]),f=N.useMemo(()=>h.map(g=>g.key),[h]),p=N.useMemo(()=>Object.fromEntries(d.map(g=>[g.key,g.name??String(g.id)])),[d]),m=["#4fc1ff","#9cdcfe","#7bd389","#f9d85c","#f38ba8","#c586c0"],S=N.useMemo(()=>{const g={},y=new Set(d.map(x=>x.key)),C=x=>{let I=2166136261;for(let E=0;E<x.length;E++)I^=x.charCodeAt(E),I=Math.imul(I,16777619);return I>>>0};return y.forEach(x=>{const I=/^layer-(\d+)$/.exec(x),E=I?Number(I[1]):NaN,A=Number.isFinite(E)?E:C(x);g[x]=m[A%m.length]??"#4fc1ff"}),g},[d]);return{worldDisplays:o,worldLayers:l,layerCount:a,detailTarget:u,trafficItems:c,sortedTraffic:d,topTraffic:h,topKeys:f,keyToLabel:p,keyToColor:S}}function PU(r){const{runtimeClient:e,serverUrl:t,renderer:n,muted:i,snapshot:s}=r,o=N.useRef(null),a=N.useRef(null),l=N.useRef(null),[u,c]=N.useState({audio:[],atlases:[],palettes:[]}),d=N.useCallback(async()=>{const h=o.current,f=a.current;h&&(l.current=t,e.start({serverUrl:t,container:h,displayContainers:f?[{id:255,container:f}]:void 0,renderer:n,inputEnabled:!0,captureInput:!0}).catch(()=>{}))},[n,e,t]);return N.useEffect(()=>{const h=o.current,f=a.current;h&&l.current!==t&&(l.current=t,e.start({serverUrl:t,container:h,displayContainers:f?[{id:255,container:f}]:void 0,renderer:n,inputEnabled:!0,captureInput:!0}).catch(()=>{}))},[n,e,t]),N.useEffect(()=>{e.setMuted(i)},[i,e]),N.useEffect(()=>{c(e.getAssetsSnapshot())},[e,s]),{rendererContainerRef:o,debugDisplay255ContainerRef:a,connect:d,assetsSnapshot:u,setAssetsSnapshot:c}}function BU({connected:r,placement:e,headerHeight:t,frameRect:n,containerRef:i,onTogglePlacement:s,onStartDrag:o,onStartResize:a}){const l=e==="float";return k.jsxs("div",{style:{position:"fixed",left:n.x,top:n.y,width:n.width,height:n.height,zIndex:l?950:1,background:"#1a1a1a",border:"1px solid #3c3c3c",boxShadow:l?"0 8px 24px rgba(0,0,0,0.35)":"none",display:"flex",flexDirection:"column",userSelect:"none"},children:[k.jsxs("div",{style:{height:t,background:"#2d2d2d",borderBottom:"1px solid #3c3c3c",display:"flex",alignItems:"center",justifyContent:"space-between",padding:"0 10px",fontSize:12,color:"#cccccc",cursor:l?"move":"default"},onMouseDown:u=>{l&&o(u.clientX,u.clientY)},children:[k.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[k.jsx("div",{style:{width:8,height:8,borderRadius:4,background:r?"#4fc1ff":"#a0a0a0"}}),k.jsx("div",{children:"Debug View"})]}),k.jsx("button",{onClick:u=>{u.stopPropagation(),s()},style:{height:22,padding:"0 8px",border:"1px solid #3c3c3c",background:"#3c3c3c",color:"#ffffff",cursor:"pointer",fontSize:12},title:l?"Embed into layout":"Float window",children:l?"Embed":"Float"})]}),k.jsx("div",{ref:i,style:{flex:1,backgroundColor:"#0f0f0f",backgroundImage:"linear-gradient(45deg, rgba(255,255,255,0.05) 25%, transparent 25%),linear-gradient(-45deg, rgba(255,255,255,0.05) 25%, transparent 25%),linear-gradient(45deg, transparent 75%, rgba(255,255,255,0.05) 75%),linear-gradient(-45deg, transparent 75%, rgba(255,255,255,0.05) 75%)",backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0",overflow:"hidden",outline:"1px solid rgba(255,255,255,0.06)"}}),l&&k.jsx("div",{onMouseDown:u=>{u.stopPropagation(),a(u.clientX,u.clientY)},style:{position:"absolute",width:14,height:14,right:2,bottom:2,cursor:"nwse-resize",background:"#2d2d2d",border:"1px solid #3c3c3c",borderRadius:2}})]})}const vl=new aM;function zU(){var Cr;const[r,e]=N.useState(()=>{if(typeof window>"u")return"http://localhost:3200";const{protocol:Se,hostname:Re,port:pe}=window.location;return pe==="4173"||pe==="5173"?`${Se}//${Re}:3200`:`${Se}//${Re}${pe?`:${pe}`:""}`}),t=Ys(Se=>Se.lastSnapshot),n=Ys(Se=>Se.connected),[i,s]=N.useState(!1),[o,a]=N.useState("grid"),[l,u]=N.useState(null),[c,d]=N.useState("float"),[h,f]=N.useState({width:0,height:0}),[p,m]=N.useState("embedded"),[S,w]=N.useState("network"),g=28,y={width:220,height:160},C=c==="float",x=24,I={width:220,height:160},E=ay({enabled:C,initialRect:{x:12,y:80,width:360,height:220},minSize:y}),A=ay({enabled:p==="float",initialRect:{x:12,y:360,width:360,height:260},minSize:I}),R=((Cr=t==null?void 0:t.users)==null?void 0:Cr[0])??null,F=p==="float",z=UU(R,vl),P=z.selectedDisplayId,O=z.selectedLayerIds,L=z.lastSelectedLayerId,V=z.focusRect,X=z.focusKey,T=N.useRef(null),{rect:_,size:j}=ly(T),{worldDisplays:G,worldLayers:ee,detailTarget:q,sortedTraffic:K,topTraffic:oe,topKeys:ve,keyToLabel:ge,keyToColor:Ce}=RU({primaryUser:R,selection:z,selectedDisplayId:P,lastSelectedLayerId:L,selectedLayerIds:O}),{tickRate:ct,chartData:dt}=AU({enabled:!0,snapshot:t,topKeys:ve,topTraffic:oe}),{rendererContainerRef:xe,debugDisplay255ContainerRef:et,connect:Ke,assetsSnapshot:qe}=PU({runtimeClient:vl,serverUrl:r,renderer:Df.TerminalGL,muted:i,snapshot:t});N.useEffect(()=>{const Se="/logo_debugger.ico",Re=document.querySelector("link[rel='icon']");if(Re)Re.href=Se;else{const pe=document.createElement("link");pe.rel="icon",pe.href=Se,document.head.appendChild(pe)}},[]),N.useEffect(()=>{const Se=Re=>{const pe=Re.detail;pe&&vl.sendDisplayTransform(pe)};return window.addEventListener("__utsp_debug_display255_rect",Se),()=>window.removeEventListener("__utsp_debug_display255_rect",Se)},[]),N.useEffect(()=>{const Se=document.documentElement.style.overflow,Re=document.body.style.overflow,pe=document.documentElement.style.margin,ne=document.body.style.margin,$e=document.documentElement.style.padding,ht=document.body.style.padding;return document.documentElement.style.overflow="hidden",document.body.style.overflow="hidden",document.documentElement.style.margin="0",document.body.style.margin="0",document.documentElement.style.padding="0",document.body.style.padding="0",()=>{document.documentElement.style.overflow=Se,document.body.style.overflow=Re,document.documentElement.style.margin=pe,document.body.style.margin=ne,document.documentElement.style.padding=$e,document.body.style.padding=ht}},[]);const At=N.useRef(null),{size:wt,rect:Ft}=ly(At);N.useEffect(()=>{const Se=xe.current;if(!Se)return;const Re=new ResizeObserver(pe=>{const ne=pe[0];ne&&f({width:Math.round(ne.contentRect.width),height:Math.round(ne.contentRect.height)})});return Re.observe(Se),()=>Re.disconnect()},[]);const cr=wt.width,tt=wt.height,kt={left:C?E.rect.x:Ft.left,top:C?E.rect.y:Ft.top,width:C?E.rect.width:cr,height:C?E.rect.height:tt},nt=F?A.rect:{x:_.left??0,y:_.top??0,width:j.width||280,height:j.height||260};return k.jsxs("div",{style:{fontFamily:"'Segoe UI', 'Helvetica Neue', sans-serif",background:"#1e1e1e",color:"#cccccc",minHeight:"100vh",margin:0,display:"flex",flexDirection:"column"},children:[k.jsx(gM,{connected:n,serverUrl:r,onServerUrlChange:e,onReconnect:()=>{Ke()}}),k.jsxs("div",{style:{display:"grid",gridTemplateColumns:"240px 1fr 280px",gap:0,padding:0,boxSizing:"border-box",flex:1,minHeight:0,overflow:"hidden"},children:[k.jsx("div",{style:{borderRight:"1px solid #3c3c3c",background:"#252526",display:"flex",flexDirection:"column",minHeight:0},children:k.jsx(pM,{primaryUser:R??null,selectedDisplayId:P,selectedLayerIds:O,onSelectDisplay:z.handleSelectDisplay,onSelectLayer:z.handleSelectLayerDisplay255Only})}),k.jsx(kU,{centerTab:o,setCenterTab:a,centerPanelRef:At,centerSize:wt,worldLayers:ee,worldDisplays:G,selectedLayerIds:O,setVisibleLayers:Se=>vl.setVisibleLayers(Se),selectedDisplayId:P,focusRect:V,focusKey:X,onSelectLayer:z.handleSelectLayer,onSelectDisplay:z.handleSelectDisplay,assetsSnapshot:qe,primaryUser:R,isFloating:C,sortedTraffic:K,topTraffic:oe,chartData:dt,topKeys:ve,keyToLabel:ge,keyToColor:Ce,tickRate:ct,hoveredTrafficKey:l,setHoveredTrafficKey:u}),k.jsxs("div",{style:{borderLeft:"1px solid #3c3c3c",background:"#252526",minHeight:0,display:"flex",flexDirection:"column",overflowY:"auto",overflowX:"hidden"},children:[k.jsx("div",{ref:T,style:{padding:0,borderBottom:"1px solid #3c3c3c",height:260,minHeight:260,width:"100%",boxSizing:"border-box"}}),k.jsx("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"6px 8px",borderBottom:"1px solid #3c3c3c"},children:[{id:"network",label:"Network"},{id:"layer",label:"Selected Layer"}].map(Se=>{const Re=S===Se.id;return k.jsx("button",{onClick:()=>w(Se.id),style:{border:"1px solid #3c3c3c",background:Re?"#1e1e1e":"#2d2d2d",color:"#cccccc",padding:"4px 10px",cursor:"pointer",fontSize:12,borderRadius:6},children:Se.label},Se.id)})}),k.jsx("div",{style:{flex:1,minHeight:0},children:S==="network"?k.jsx(MU,{primaryUser:R,tickRate:ct,snapshot:t,assetsSnapshot:qe}):k.jsx("div",{style:{height:"100%",minHeight:0},children:k.jsx(dM,{detailTarget:q})})})]})]}),k.jsx(lM,{connected:n,muted:i,rendererPlacement:c,centerTab:o,frameRect:kt,rendererHeaderHeight:g,rendererContentSize:h,rendererContainerRef:xe,onTogglePlacement:()=>{d(Se=>{const Re=Se==="float"?"embedded":"float";return Re==="embedded"&&a("renderer"),Re})},onToggleMuted:()=>{s(Se=>!Se)},onStartDrag:(Se,Re)=>{E.startDrag(Se,Re)},onStartResize:(Se,Re)=>{E.startResize(Se,Re)}}),k.jsx(BU,{connected:n,placement:p,headerHeight:x,frameRect:nt,containerRef:et,onTogglePlacement:()=>m(Se=>Se==="float"?"embedded":"float"),onStartDrag:A.startDrag,onStartResize:A.startResize})]})}const OC=document.getElementById("root");if(!OC)throw new Error("Root container not found");td.createRoot(OC).render(k.jsx(Cy.StrictMode,{children:k.jsx(zU,{})}));
|