brilliant-msg 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,204 @@
1
+ (function(ct,e){typeof exports=="object"&&typeof module<"u"?e(exports):typeof define=="function"&&define.amd?define(["exports"],e):(ct=typeof globalThis<"u"?globalThis:ct||self,e(ct["brilliant-msg"]={}))})(this,function(exports){"use strict";var Yt=Object.defineProperty;var Bt=ct=>{throw TypeError(ct)};var Zt=(ct,e,i)=>e in ct?Yt(ct,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):ct[e]=i;var we=(ct,e,i)=>Zt(ct,typeof e!="symbol"?e+"":e,i),Tt=(ct,e,i)=>e.has(ct)||Bt("Cannot "+i);var kt=(ct,e,i)=>(Tt(ct,e,"read from private field"),i?i.call(ct):e.get(ct)),It=(ct,e,i)=>e.has(ct)?Bt("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(ct):e.set(ct,i),Dt=(ct,e,i,t)=>(Tt(ct,e,"write to private field"),t?t.call(ct,i):e.set(ct,i),i),Ct=(ct,e,i)=>(Tt(ct,e,"access private method"),i);var p=Object.defineProperty,y$1=(e,i,t)=>i in e?p(e,i,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[i]=t,r=(e,i,t)=>y$1(e,typeof i!="symbol"?i+"":i,t),R=(e=>(e.FRAME="Frame",e.HALO="Halo",e.UNKNOWN="Unknown",e))(R||{});class E{constructor(){r(this,"device"),r(this,"server"),r(this,"txCharacteristic"),r(this,"rxCharacteristic"),r(this,"audioTxCharacteristic"),r(this,"deviceType","Unknown"),r(this,"SERVICE_UUID","7a230001-5475-a6a4-654c-8431f6ad49c4"),r(this,"TX_CHARACTERISTIC_UUID","7a230002-5475-a6a4-654c-8431f6ad49c4"),r(this,"RX_CHARACTERISTIC_UUID","7a230003-5475-a6a4-654c-8431f6ad49c4"),r(this,"AUDIO_TX_CHARACTERISTIC_UUID","7a230005-5475-a6a4-654c-8431f6ad49c4"),r(this,"maxPayload",60),r(this,"awaitingPrintResponse",!1),r(this,"awaitingDataResponse",!1),r(this,"printTimeoutId"),r(this,"printResponsePromise"),r(this,"printResolve"),r(this,"dataResponsePromise"),r(this,"dataResolve"),r(this,"onDataResponse"),r(this,"onPrintResponse"),r(this,"onDisconnectHandler"),r(this,"handleDisconnect",()=>{this.device=void 0,this.server=void 0,this.txCharacteristic=void 0,this.rxCharacteristic=void 0,this.audioTxCharacteristic=void 0,this.deviceType="Unknown",this.onDisconnectHandler&&this.onDisconnectHandler()}),r(this,"notificationHandler",i=>{const t=i.target.value;if(!(!t||t.buffer.byteLength===0))if(t.byteLength>0&&t.getUint8(0)===1){const n=new Uint8Array(t.buffer,t.byteOffset+1,t.byteLength-1);if(this.awaitingDataResponse&&this.dataResolve&&(this.awaitingDataResponse=!1,this.dataResolve(n)),this.onDataResponse){const a=this.onDataResponse(n);a instanceof Promise&&a.catch(console.error)}}else{const n=new TextDecoder().decode(t);if(this.awaitingPrintResponse&&this.printResolve&&(this.awaitingPrintResponse=!1,this.printResolve(n)),this.onPrintResponse){const a=this.onPrintResponse(n);a instanceof Promise&&a.catch(console.error)}}})}get type(){return this.deviceType}setDataResponseHandler(i){this.onDataResponse=i}setPrintResponseHandler(i){this.onPrintResponse=i}setDisconnectHandler(i){this.onDisconnectHandler=i}async _attemptConnection(){var i,t,n,a;if(!this.device||!this.device.gatt)throw new Error("Bluetooth device or GATT interface not available for connection attempt.");this.txCharacteristic=void 0,this.rxCharacteristic=void 0,this.audioTxCharacteristic=void 0,this.deviceType="Unknown",this.server=void 0;try{console.log(`Attempting to connect to GATT server on device: ${this.device.name||this.device.id}...`),this.server=await this.device.gatt.connect(),console.log("GATT server connected."),console.log("Getting primary service...");const s=await this.server.getPrimaryService(this.SERVICE_UUID);console.log("Primary service obtained."),console.log("Getting TX characteristic..."),this.txCharacteristic=await s.getCharacteristic(this.TX_CHARACTERISTIC_UUID),console.log("TX characteristic obtained."),console.log("Getting RX characteristic..."),this.rxCharacteristic=await s.getCharacteristic(this.RX_CHARACTERISTIC_UUID),console.log("RX characteristic obtained.");try{this.audioTxCharacteristic=await s.getCharacteristic(this.AUDIO_TX_CHARACTERISTIC_UUID),this.deviceType="Halo",console.log("Audio TX characteristic obtained — device is Halo.")}catch{this.deviceType="Frame",console.log("No audio TX characteristic — device is Frame.")}console.log("Starting notifications on RX characteristic..."),await this.rxCharacteristic.startNotifications(),this.rxCharacteristic.addEventListener("characteristicvaluechanged",this.notificationHandler),console.log("Notifications started."),await this.sendBreakSignal(!1),console.log("Fetching MTU size (max_length) from device...");const o=await this.sendLua("print(frame.bluetooth.max_length())",{awaitPrint:!0});if(o==null)throw new Error("Failed to get MTU size from device: no response.");const h=parseInt(o);if(isNaN(h)||h<=0)throw new Error(`Invalid MTU size received: '${o}'`);this.maxPayload=h,console.log(`MTU size set to: ${this.maxPayload}`)}catch(s){if(console.error("Error during connection attempt:",s),this.rxCharacteristic){try{(t=(i=this.device)==null?void 0:i.gatt)!=null&&t.connected&&await this.rxCharacteristic.stopNotifications()}catch{}this.rxCharacteristic.removeEventListener("characteristicvaluechanged",this.notificationHandler),this.rxCharacteristic=void 0}throw this.txCharacteristic=void 0,this.audioTxCharacteristic=void 0,this.deviceType="Unknown",(a=(n=this.device)==null?void 0:n.gatt)!=null&&a.connected&&this.device.gatt.disconnect(),this.server=void 0,s}}async connect(i={}){var t;const{name:n,namePrefix:a,numAttempts:s=5,retryDelayMs:o=1e3}=i;if(!navigator.bluetooth)throw new Error("Web Bluetooth API not available.");if(!this.device){const l={filters:[n?{services:[this.SERVICE_UUID],name:n}:a?{services:[this.SERVICE_UUID],namePrefix:a}:{services:[this.SERVICE_UUID]}],optionalServices:[this.SERVICE_UUID]};try{if(console.log("Requesting Bluetooth device from user..."),this.device=await navigator.bluetooth.requestDevice(l),!this.device)throw new Error("No device selected by the user.");console.log(`Device selected: ${this.device.name||this.device.id}`)}catch(u){throw console.error("Bluetooth device request failed:",u),this.device=void 0,u}}if(!this.device)throw new Error("Device not available after selection phase.");const h=this.device;h.removeEventListener("gattserverdisconnected",this.handleDisconnect),h.addEventListener("gattserverdisconnected",this.handleDisconnect);let f;for(let l=1;l<=s;l++){if(!this.device){console.warn(`Device (id: ${h.id}) was disconnected externally during connection attempts.`),f=f||new Error(`Device disconnected externally during connection attempt ${l}.`);break}try{return console.log(`Connection attempt ${l} of ${s} to device '${h.name||h.id}'...`),await this._attemptConnection(),console.log(`Successfully connected to ${h.name||h.id} on attempt ${l}.`),h.name||h.id||"Unknown Device"}catch(u){if(f=u,console.error(`Attempt ${l} to connect to '${h.name||h.id}' failed:`,u),u instanceof Error&&u.name==="NetworkError"&&(u.message.includes("Connection attempt failed.")||u.message.includes("GATT operation failed for unknown reason.")||u.message.includes("GATT Server is disconnected.")||u.message.includes("Bluetooth device is already connected."))&&l<s)console.log(`Retryable error encountered. Retrying in ${o/1e3}s...`),await new Promise(w=>setTimeout(w,o));else{console.log("Non-retryable error or max attempts reached. Aborting connection process.");break}}}throw console.error(`Failed to connect to device '${h.name||h.id}' after ${s} attempts or due to external disconnection.`),h.removeEventListener("gattserverdisconnected",this.handleDisconnect),(t=h.gatt)!=null&&t.connected&&h.gatt.disconnect(),this.server=void 0,this.txCharacteristic=void 0,this.rxCharacteristic=void 0,this.audioTxCharacteristic=void 0,this.deviceType="Unknown",this.device=void 0,f||new Error(`Failed to connect to ${h.name||h.id} after ${s} attempts. No specific error recorded, or device disconnected externally.`)}async disconnect(){var i;this.device&&(i=this.device.gatt)!=null&&i.connected?this.device.gatt.disconnect():this.handleDisconnect()}isConnected(){return!!(this.device&&this.device.gatt&&this.device.gatt.connected)}getMaxPayload(i){return i?this.maxPayload:this.maxPayload-1}async transmit(i,t=!1,n=!0){if(!this.txCharacteristic)throw new Error("Not connected or TX characteristic not available.");if(i.byteLength>this.maxPayload)throw new Error(`Payload length: ${i.byteLength} exceeds maximum BLE packet size: ${this.maxPayload}`);t&&console.log("Transmitting (hex):",Array.from(i).map(a=>a.toString(16).padStart(2,"0")).join(" ")),n?await this.txCharacteristic.writeValueWithResponse(i):await this.txCharacteristic.writeValueWithoutResponse(i)}async sendLua(i,t={}){const{showMe:n=!1,awaitPrint:a=!1,timeout:s=5e3}=t,o=new TextEncoder().encode(i);if(o.byteLength>this.getMaxPayload(!0))throw new Error(`Lua string payload (${o.byteLength} bytes) is too large for max Lua payload (${this.getMaxPayload(!0)} bytes).`);if(a&&(this.printTimeoutId&&clearTimeout(this.printTimeoutId),this.awaitingPrintResponse=!0,this.printResponsePromise=new Promise((h,f)=>{this.printResolve=h,this.printTimeoutId=setTimeout(()=>{this.awaitingPrintResponse&&(this.awaitingPrintResponse=!1,this.printResolve=void 0,f(new Error(`Device didn't respond with a print within ${s}ms.`)))},s)}).finally(()=>{this.printTimeoutId&&(clearTimeout(this.printTimeoutId),this.printTimeoutId=void 0)})),await this.transmit(o,n),a)return this.printResponsePromise}async sendData(i,t={}){const{showMe:n=!1,awaitData:a=!1,timeout:s=5e3,awaitBtResponse:o=!0}=t;if(!this.txCharacteristic)throw new Error("Not connected or TX characteristic not available.");if(i.byteLength>this.getMaxPayload(!1))throw new Error(`Data payload (${i.byteLength} bytes) is too large for max data payload (${this.getMaxPayload(!1)} bytes).`);const h=new Uint8Array([1]),f=new Uint8Array(h.length+i.byteLength);f.set(h,0),f.set(i,h.length);let l;if(a&&(this.awaitingDataResponse=!0,this.dataResponsePromise=new Promise((u,w)=>{this.dataResolve=u,l=setTimeout(()=>{this.awaitingDataResponse&&(this.awaitingDataResponse=!1,this.dataResolve=void 0,w(new Error(`Device didn't respond with data within ${s}ms.`)))},s)}).finally(()=>{l&&clearTimeout(l)})),await this.transmit(f,n,o),a)return this.dataResponsePromise}async sendAudio(i,t=!1){if(!this.audioTxCharacteristic)throw new Error("Audio TX characteristic not available. Is this a Halo device?");const n=this.maxPayload;i.byteLength>n||(t?await this.audioTxCharacteristic.writeValueWithResponse(i):await this.audioTxCharacteristic.writeValueWithoutResponse(i))}async sendResetSignal(i=!1){const t=new Uint8Array([4]);await this.transmit(t,i),await new Promise(n=>setTimeout(n,200))}async sendRemoveSignal(i=!1){const t=new Uint8Array([5]);await this.transmit(t,i),await new Promise(n=>setTimeout(n,200))}async sendBreakSignal(i=!1){const t=new Uint8Array([3]);await this.transmit(t,i),await new Promise(n=>setTimeout(n,200))}async uploadFileFromString(i,t="main.lua"){let n=i.replace(/\r/g,"").replace(/\\/g,"\\\\").replace(/\n/g,"\\n").replace(/\t/g,"\\t").replace(/'/g,"\\'").replace(/"/g,'\\"');const a=await this.sendLua(`f=frame.file.open('${t}','w');print(1)`,{awaitPrint:!0});if(a!=="1")throw new Error(`Failed to open file ${t} on device. Response: ${a}`);const s=this.getMaxPayload(!0)-20;if(s<=0)throw new Error("Max payload size too small for file upload operations.");let o=0;for(;o<n.length;){let h=Math.min(s,n.length-o),f=n.substring(o,o+h);for(;f.endsWith("\\");){let u=0;for(let w=f.length-1;w>=0&&f[w]==="\\";w--)u++;if(u%2!==0)if(h>1)h--,f=n.substring(o,o+h);else throw await this.sendLua("f:close();print(nil)",{awaitPrint:!0}),new Error("Cannot safely chunk content due to isolated escape character at chunk boundary.");else break}const l=await this.sendLua(`f:write("${f}");print(1)`,{awaitPrint:!0});if(l!=="1")throw await this.sendLua("f:close();print(nil)",{awaitPrint:!0}),new Error(`Failed to write chunk to ${t}. Response: ${l}`);o+=h}await this.sendLua("f:close();print(nil)",{awaitPrint:!0})}async uploadFile(i,t="main.lua"){await this.uploadFileFromString(i,t)}async sendMessage(i,t,n=!1,a=!0){if(i<0||i>255)throw new Error(`Message code must be 0-255, got ${i}`);const s=t.byteLength;if(s>65535)throw new Error(`Payload size ${s} exceeds maximum 65535 bytes`);const o=this.getMaxPayload(!1),h=o-1-2,f=o-1;if(h<=0||f<=0)throw new Error("Max payload size too small for message sending protocol.");let l=0;const u=Math.min(h,s),w=new Uint8Array(3+u);for(w[0]=i,w[1]=s>>8,w[2]=s&255,w.set(t.subarray(0,u),3),await this.sendData(w,{showMe:n,awaitData:!0,awaitBtResponse:a}),l+=u;l<s;){const _=s-l,g=Math.min(f,_),v=new Uint8Array(1+g);v[0]=i,v.set(t.subarray(l,l+g),1),await this.sendData(v,{showMe:n,awaitData:!0,awaitBtResponse:a}),l+=g}}}const stdDataMinLua=`local a={}local b={}a.app_data_accum=b;local c={}local d=0;function a.update_app_data_accum(e)rc,err=pcall(function()local f=string.byte(e,1)local g=a.app_data_accum[f]if g==nil or next(g)==nil then g={chunk_table={},num_chunks=0,size=0,recv_bytes=0}a.app_data_accum[f]=g end;if g.num_chunks==0 then g.size=string.byte(e,2)<<8|string.byte(e,3)g.chunk_table[1]=string.sub(e,4)g.num_chunks=1;g.recv_bytes=string.len(e)-3;if g.recv_bytes==g.size then d=d+1;c[d]={f,g.chunk_table[1]}g.size=0;g.recv_bytes=0;g.num_chunks=0;g.chunk_table[1]=nil;b[f]=g end else g.chunk_table[g.num_chunks+1]=string.sub(e,2)g.num_chunks=g.num_chunks+1;g.recv_bytes=g.recv_bytes+string.len(e)-1;if g.recv_bytes==g.size then collectgarbage('collect')d=d+1;c[d]={f,table.concat(g.chunk_table)}for h,i in pairs(g.chunk_table)do g.chunk_table[h]=nil end;collectgarbage('collect')g.size=0;g.recv_bytes=0;g.num_chunks=0;a.app_data_accum[f]=g end end;while true do if pcall(frame.bluetooth.send,'\\x01\\x00\\x00')then break end;frame.sleep(0.0025)end end)if rc==false then print('Error in data accumulator: '..err)while true do if pcall(frame.bluetooth.send,'\\x01\\x00\\x01')then break end;frame.sleep(0.0025)end;error(err)end end;frame.bluetooth.receive_callback(a.update_app_data_accum)function a.process_raw_items()local j={}local k=0;rc,err=pcall(function()collectgarbage('collect')for l=1,d do k=k+1;j[k]=c[l]c[l]=nil end;d=0 end)if rc==false then print('Error processing raw items: '..err)error(err)end;return j end;return a
2
+ `,stdAudioMinLua="local a={}local b=0x06;local c=0x05;local d=frame.bluetooth.max_length()-1;if d%2==1 then d=d-1 end;function a.start(e)local f=e and e.sample_rate or 8000;local g=e and e.bit_depth or 8;pcall(frame.microphone.start,{sample_rate=f,bit_depth=g})end;function a.stop()pcall(frame.microphone.stop)end;function a.read_and_send_audio()audio_data=frame.microphone.read(d)if audio_data==nil then while true do if pcall(frame.bluetooth.send,string.char(b))then break end end;return nil elseif audio_data~=''then while true do if pcall(frame.bluetooth.send,string.char(c)..audio_data)then break end end;return string.len(audio_data)end;return 0 end;return a",stdCameraMinLua=`local a={}local b=0x07;local c=0x08;local d=0x11;local e=0x12;local f={'VERY_LOW','LOW','MEDIUM','HIGH','VERY_HIGH'}local g={'SPOT','CENTER_WEIGHTED','AVERAGE'}local h={metering='CENTER_WEIGHTED',exposure=0.1,exposure_speed=0.45,shutter_limit=16383,analog_gain_limit=16.0,white_balance_speed=0.5,rgb_gain_limit=287}local i={shutter=4096,analog_gain=1,red_gain=121,green_gain=64,blue_gain=140}a.is_auto_exp=true;function update_if_present(j,k)for l,m in pairs(k)do if m~=nil then j[l]=m end end end;function a.set_auto_exp_settings(n)update_if_present(h,n)a.is_auto_exp=true end;function a.set_manual_exp_settings(n)a.is_auto_exp=false;update_if_present(i,n)frame.camera.set_shutter(i.shutter)frame.camera.set_gain(i.analog_gain)frame.camera.set_white_balance(i.red_gain,i.green_gain,i.blue_gain)end;function a.parse_auto_exp_settings(o)local j={}j.metering=g[string.byte(o,1)+1]j.exposure=string.byte(o,2)/255.0;j.exposure_speed=string.byte(o,3)/255.0;j.shutter_limit=string.byte(o,4)<<8|(string.byte(o,5)&0x3FFF)j.analog_gain_limit=string.byte(o,6)&0xFF;j.white_balance_speed=string.byte(o,7)/255.0;j.rgb_gain_limit=string.byte(o,8)<<8|(string.byte(o,9)&0x3FF)return j end;function a.parse_manual_exp_settings(o)local j={}j.shutter=string.byte(o,1)<<8|(string.byte(o,2)&0x3FFF)j.analog_gain=string.byte(o,3)&0xFF;j.red_gain=string.byte(o,4)<<8|(string.byte(o,5)&0x3FF)j.green_gain=string.byte(o,6)<<8|(string.byte(o,7)&0x3FF)j.blue_gain=string.byte(o,8)<<8|(string.byte(o,9)&0x3FF)return j end;function a.parse_capture_settings(o)local j={}j.quality=f[string.byte(o,1)+1]local p=string.byte(o,2)<<8|string.byte(o,3)j.resolution=p*2;local q=string.byte(o,4)<<8|string.byte(o,5)j.pan=q-140;j.raw=string.byte(o,6)>0;return j end;function send_data(o)local r=false;local s=frame.time.utc()+2;while frame.time.utc()<s do if pcall(frame.bluetooth.send,o)then r=true;break end end;if not r then error('Error sending photo data')end end;function a.run_auto_exposure()return frame.camera.auto(h)end;function a.send_autoexp_result(t)local o=string.pack("<Bffffffffffffffff",d,t['error'],t['shutter'],t['analog_gain'],t['red_gain'],t['green_gain'],t['blue_gain'],t['brightness']['center_weighted_average'],t['brightness']['scene'],t['brightness']['matrix']['r'],t['brightness']['matrix']['g'],t['brightness']['matrix']['b'],t['brightness']['matrix']['average'],t['brightness']['spot']['r'],t['brightness']['spot']['g'],t['brightness']['spot']['b'],t['brightness']['spot']['average'])send_data(o)end;function a.send_metering_data()send_data(string.char(e)..frame.fpga_read(0x25,6))end;function a.capture_and_send(n)frame.camera.capture{resolution=n.resolution,quality=n.quality,pan=n.pan}while not frame.camera.image_ready()do frame.sleep(0.005)end;local o=''local u=n.raw;while true do if u then o=frame.camera.read_raw(frame.bluetooth.max_length()-1)else o=frame.camera.read(frame.bluetooth.max_length()-1)end;if o~=nil then send_data(string.char(b)..o)else send_data(string.char(c))break end end end;return a`,stdCodeMinLua="local _M={}function _M.parse_code(a)local b={}b.value=string.byte(a,1)return b end;return _M",stdIMUMinLua=`local a={}local b=0x0A;function a.send_imu_data(c)local d=c or b;local e=frame.imu.raw()local f=nil;if frame.HARDWARE_VERSION=='Frame'then local g=4096;f=string.pack("<Bxffffff",d,e.compass.x,e.compass.y,e.compass.z,e.accelerometer.x/g,e.accelerometer.y/g,e.accelerometer.z/g)else print(-e.accelerometer.z)local g=1000;f=string.pack("<Bxffffff",d,-e.compass.z,e.compass.y,e.compass.x,-e.accelerometer.z/g,e.accelerometer.y/g,e.accelerometer.x/g)end;pcall(frame.bluetooth.send,f)end;return a`,stdImageSpriteBlockMinLua="local a={}function a.parse_image_sprite_block(b,c)if string.byte(b,1)==0xFF then if c~=nil then for d,e in pairs(c.sprites)do c.sprites[d]=nil end;c=nil;collectgarbage('collect')end;local f={}f.width=string.byte(b,2)<<8|string.byte(b,3)f.height=string.byte(b,4)<<8|string.byte(b,5)f.sprite_line_height=string.byte(b,6)<<8|string.byte(b,7)f.progressive_render=string.byte(b,8)==1;f.updatable=string.byte(b,9)==1;f.sprites={}local g=f.height+f.sprite_line_height-1;f.total_sprites=g//f.sprite_line_height;f.active_sprites=0;f.current_sprite_index=0;return f else if c==nil then return nil end;c.current_sprite_index=c.current_sprite_index+1;if c.current_sprite_index>c.total_sprites then if c.updatable then c.current_sprite_index=1 else return c end end;if c.active_sprites<c.total_sprites then c.active_sprites=c.active_sprites+1 end;local h={}h.width=string.byte(b,1)<<8|string.byte(b,2)h.height=string.byte(b,3)<<8|string.byte(b,4)h.compressed=string.byte(b,5)>0;h.bpp=string.byte(b,6)h.num_colors=string.byte(b,7)h.palette_data=string.sub(b,8,8+h.num_colors*3-1)h.pixel_data=string.sub(b,8+h.num_colors*3)c.sprites[c.current_sprite_index]=h;return c end end;function a.set_palette(i,j)local k={'VOID','WHITE','GREY','RED','PINK','DARKBROWN','BROWN','ORANGE','YELLOW','DARKGREEN','GREEN','LIGHTGREEN','NIGHTBLUE','SEABLUE','SKYBLUE','CLOUDBLUE'}for l=1,i do local m=(l-1)*3;local n;if frame.HARDWARE_VERSION=='Frame'then n=k[l]else n=l-1 end;frame.display.assign_color(n,string.byte(j,m+1),string.byte(j,m+2),string.byte(j,m+3))end end;return a",stdPlainTextMinLua="local a={}local b={'VOID','WHITE','GREY','RED','PINK','DARKBROWN','BROWN','ORANGE','YELLOW','DARKGREEN','GREEN','LIGHTGREEN','NIGHTBLUE','SEABLUE','SKYBLUE','CLOUDBLUE'}local c={0x000000,0xFFFFFF,0x808080,0xFF0000,0xFFC0CB,0x654321,0x964B00,0xFFA500,0xFFFF00,0x006400,0x00FF00,0x90EE90,0x191970,0x0000CD,0x87CEEB,0xF0F8FF}function a.parse_plain_text(d)local e={}e.x=string.byte(d,1)<<8|string.byte(d,2)e.y=string.byte(d,3)<<8|string.byte(d,4)e.palette_offset=string.byte(d,5)if frame.HARDWARE_VERSION~='Frame'then e.color=c[e.palette_offset%16+1]else e.color=b[e.palette_offset%16+1]end;e.spacing=string.byte(d,6)e.string=string.sub(d,7)return e end;return a",stdSpriteMinLua="local a={}function a.parse_sprite(b)local c={}c.width=string.byte(b,1)<<8|string.byte(b,2)c.height=string.byte(b,3)<<8|string.byte(b,4)c.compressed=string.byte(b,5)>0;c.bpp=string.byte(b,6)c.num_colors=string.byte(b,7)c.palette_data=string.sub(b,8,8+c.num_colors*3-1)c.pixel_data=string.sub(b,8+c.num_colors*3)return c end;function a.set_palette(d,e)local f={'VOID','WHITE','GREY','RED','PINK','DARKBROWN','BROWN','ORANGE','YELLOW','DARKGREEN','GREEN','LIGHTGREEN','NIGHTBLUE','SEABLUE','SKYBLUE','CLOUDBLUE'}for g=1,d do local h=(g-1)*3;local i;if frame.HARDWARE_VERSION=='Frame'then i=f[g]else i=g-1 end;frame.display.assign_color(i,string.byte(e,h+1),string.byte(e,h+2),string.byte(e,h+3))end end;return a",stdSpriteCoordsMinLua="local a={}function a.parse_sprite_coords(b)local c={}c.code=string.byte(b,1)c.x=string.byte(b,2)<<8|string.byte(b,3)c.y=string.byte(b,4)<<8|string.byte(b,5)c.offset=string.byte(b,6)return c end;return a",stdTapMinLua="local a={}local b=0x09;function a.send_tap()rc,err=pcall(frame.bluetooth.send,string.char(b))if rc==false then print(err)end end;return a",stdTextSpriteBlockMinLua="local a={}function a.parse_text_sprite_block(b,c)if string.byte(b,1)==0xFF then local d={}d.width=string.byte(b,2)<<8|string.byte(b,3)d.line_height=string.byte(b,4)<<8|string.byte(b,5)d.max_display_lines=string.byte(b,6)d.sprites={}return d else if c==nil then return nil end;if#c.sprites>=c.max_display_lines and c.max_display_lines>0 then table.remove(c.sprites,1)end;local e={}e.width=string.byte(b,1)<<8|string.byte(b,2)e.height=string.byte(b,3)<<8|string.byte(b,4)e.compressed=string.byte(b,5)>0;e.bpp=string.byte(b,6)e.num_colors=string.byte(b,7)e.palette_data=string.sub(b,8,8+e.num_colors*3-1)e.pixel_data=string.sub(b,8+e.num_colors*3)table.insert(c.sprites,e)return c end end;return a";var StdLua=(e=>(e.DataMin="stdDataMin",e.AudioMin="stdAudioMin",e.CameraMin="stdCameraMin",e.CodeMin="stdCodeMin",e.IMUMin="stdIMUMin",e.ImageSpriteBlockMin="stdImageSpriteBlockMin",e.PlainTextMin="stdPlainTextMin",e.SpriteMin="stdSpriteMin",e.SpriteCoordsMin="stdSpriteCoordsMin",e.TapMin="stdTapMin",e.TextSpriteBlockMin="stdTextSpriteBlockMin",e))(StdLua||{});const standardLuaLibrarySources={stdDataMin:{content:stdDataMinLua,targetFileName:"data.min.lua"},stdAudioMin:{content:stdAudioMinLua,targetFileName:"audio.min.lua"},stdCameraMin:{content:stdCameraMinLua,targetFileName:"camera.min.lua"},stdCodeMin:{content:stdCodeMinLua,targetFileName:"code.min.lua"},stdIMUMin:{content:stdIMUMinLua,targetFileName:"imu.min.lua"},stdImageSpriteBlockMin:{content:stdImageSpriteBlockMinLua,targetFileName:"image_sprite_block.min.lua"},stdPlainTextMin:{content:stdPlainTextMinLua,targetFileName:"plain_text.min.lua"},stdSpriteMin:{content:stdSpriteMinLua,targetFileName:"sprite.min.lua"},stdSpriteCoordsMin:{content:stdSpriteCoordsMinLua,targetFileName:"sprite_coords.min.lua"},stdTapMin:{content:stdTapMinLua,targetFileName:"tap.min.lua"},stdTextSpriteBlockMin:{content:stdTextSpriteBlockMinLua,targetFileName:"text_sprite_block.min.lua"}};class BrilliantMsg{constructor(){we(this,"ble");we(this,"dataResponseHandlers");this.ble=new E,this.dataResponseHandlers=new Map,this.ble.setDataResponseHandler(this._handleDataResponse.bind(this))}async connect(i=!0,t={}){try{const n={name:t.name,namePrefix:t.namePrefix},a=await this.ble.connect(n);return i&&(await this.ble.sendBreakSignal(),await this.ble.sendResetSignal(),await this.ble.sendBreakSignal()),a}catch(n){throw this.ble.isConnected()&&await this.ble.disconnect(),n}}async disconnect(){this.ble.isConnected()&&await this.ble.disconnect()}isConnected(){return this.ble.isConnected()}async printShortText(i=""){const t=i.replace(/'/g,"\\'").replace(/\n/g,""),n=this.ble.type===R.FRAME?`frame.display.text('${t}',1,1);frame.display.show();print(0)`:`frame.display.clear();frame.display.text('${t}',100,100);print(0)`;return this.ble.sendLua(n,{awaitPrint:!0})}async uploadStdLuaLibs(i){for(const t of i){const n=standardLuaLibrarySources[t];n?await this.ble.uploadFileFromString(n.content,n.targetFileName):console.warn(`Standard Lua library key "${t}" not found. Skipping.`)}}async uploadFrameApp(i,t="frame_app.lua"){await this.ble.uploadFile(i,t)}async startFrameApp(i="frame_app",t=!0){return this.ble.sendLua(`require('${i}')`,{awaitPrint:t})}async stopFrameApp(i=!0){await this.ble.sendBreakSignal(),i&&await this.ble.sendResetSignal()}attachPrintResponseHandler(i=console.log){this.ble.setPrintResponseHandler(i)}detachPrintResponseHandler(){this.ble.setPrintResponseHandler(void 0)}async sendMessage(i,t,n=!1){await this.ble.sendMessage(i,t,n)}registerDataResponseHandler(i,t,n){for(const a of t){this.dataResponseHandlers.has(a)||this.dataResponseHandlers.set(a,[]);const s=this.dataResponseHandlers.get(a);s.find(h=>h.subscriber===i&&h.handler===n)||s.push({subscriber:i,handler:n})}}unregisterDataResponseHandler(i){this.dataResponseHandlers.forEach((t,n)=>{const a=t.filter(s=>s.subscriber!==i);a.length===0?this.dataResponseHandlers.delete(n):this.dataResponseHandlers.set(n,a)})}_handleDataResponse(i){if(i&&i.byteLength>0){const t=i[0];this.dataResponseHandlers.has(t)&&this.dataResponseHandlers.get(t).forEach(n=>{try{n.handler(i)}catch(a){console.error("Error in BrilliantMsg data response handler for msgCode",t,":",a)}})}}async sendLua(i,t={}){return this.ble.sendLua(i,t)}async sendData(i,t={}){return this.ble.sendData(i,t)}async sendResetSignal(i=!1){return this.ble.sendResetSignal(i)}async sendBreakSignal(i=!1){return this.ble.sendBreakSignal(i)}getMaxPayload(i){return this.ble?this.ble.getMaxPayload(i):(console.warn("BrilliantBle instance not initialized or not connected for getMaxPayload."),60)}}class AsyncQueue{constructor(){we(this,"promises");we(this,"resolvers");this.promises=[],this.resolvers=[]}add(){this.promises.push(new Promise(i=>{this.resolvers.push(i)}))}put(i){this.resolvers.length||this.add();const t=this.resolvers.shift();t&&t(i)}async get(){this.promises.length||this.add();const i=this.promises.shift();return i||new Promise(t=>{this.resolvers.push(t),this.promises.push(this.get())})}isEmpty(){return this.promises.length===0}size(){return this.promises.length}clear(){this.resolvers.forEach(i=>{}),this.promises=[],this.resolvers=[]}}class TxPlainText{constructor(i){we(this,"text");we(this,"x");we(this,"y");we(this,"paletteOffset");we(this,"spacing");this.text=i.text,this.x=i.x??1,this.y=i.y??1,this.paletteOffset=i.paletteOffset??1,this.spacing=i.spacing??4}pack(){const t=new TextEncoder().encode(this.text),n=new Uint8Array(6),a=new DataView(n.buffer);a.setUint16(0,this.x,!1),a.setUint16(2,this.y,!1),a.setUint8(4,this.paletteOffset&15),a.setUint8(5,this.spacing&255);const s=new Uint8Array(n.length+t.length);return s.set(n),s.set(t,n.length),s}}class TxCaptureSettings{constructor(i={}){we(this,"resolution");we(this,"qualityIndex");we(this,"pan");we(this,"raw");this.resolution=i.resolution??512,this.qualityIndex=i.qualityIndex??4,this.pan=i.pan??0,this.raw=i.raw??!1}pack(){const i=new ArrayBuffer(6),t=new DataView(i),n=this.resolution/2,a=this.pan+140;return t.setUint8(0,this.qualityIndex&255),t.setUint16(1,n&65535,!1),t.setUint16(3,a&65535,!1),t.setUint8(5,this.raw?1:0),new Uint8Array(i)}}class TxCode{constructor(i={}){we(this,"value");this.value=i.value??0}pack(){const i=this.value&255;return new Uint8Array([i])}}const bitMethods={getBit(e){return this.data[getSlot(e)]&1<<getShift(e)?1:0},setBit(e){this.data[getSlot(e)]|=1<<getShift(e)},clearBit(e){this.data[getSlot(e)]&=~(1<<getShift(e))},toggleBit(e){this.data[getSlot(e)]^=1<<getShift(e)},getBitXY(e,i){return e>=this.width||i>=this.height?0:this.getBit(i*this.width+e)},setBitXY(e,i){this.setBit(i*this.width+e)},clearBitXY(e,i){this.clearBit(i*this.width+e)},toggleBitXY(e,i){this.toggleBit(i*this.width+e)}};function getSlot(e){return e>>3}function getShift(e){return 7-(e&7)}function setBitMethods(e){for(const i in bitMethods)e.prototype[i]=bitMethods[i]}function checkProcessable(e,i={}){let{bitDepth:t,alpha:n,colorModel:a,components:s,channels:o}=i;if(typeof e!="string"||e.length===0)throw new TypeError("processName must be a string");if(t&&(Array.isArray(t)||(t=[t]),!t.includes(this.bitDepth)))throw new TypeError(`The process: ${e} can only be applied if bit depth is in: ${t}`);if(n&&(Array.isArray(n)||(n=[n]),!n.includes(this.alpha)))throw new TypeError(`The process: ${e} can only be applied if alpha is in: ${n}`);if(a&&(Array.isArray(a)||(a=[a]),!a.includes(this.colorModel)))throw new TypeError(`The process: ${e} can only be applied if color model is in: ${a}`);if(s&&(Array.isArray(s)||(s=[s]),!s.includes(this.components))){let h=`The process: ${e} can only be applied if the number of components is in: ${s}`;throw s.length===1&&s[0]===1?new TypeError(`${h}.\rYou should transform your image using "image.grey()" before applying the algorithm.`):new TypeError(h)}if(o&&(Array.isArray(o)||(o=[o]),!o.includes(this.channels)))throw new TypeError(`The process: ${e} can only be applied if the number of channels is in: ${o}`)}function createBlob(e,i){e=e||[],i=i||{},typeof i=="string"&&(i={type:i});try{return new Blob(e,i)}catch(s){if(s.name!=="TypeError")throw s;for(var t=typeof BlobBuilder<"u"?BlobBuilder:typeof MSBlobBuilder<"u"?MSBlobBuilder:typeof MozBlobBuilder<"u"?MozBlobBuilder:WebKitBlobBuilder,n=new t,a=0;a<e.length;a+=1)n.append(e[a]);return n.getBlob(i.type)}}function dataURLToBlob(e){var i=e.match(/data:([^;]+)/)[1],t=e.replace(/^[^,]+,/,""),n=binaryStringToArrayBuffer(atob(t));return createBlob([n],{type:i})}function canvasToBlob(e,i,t){return typeof e.toBlob=="function"?new Promise(function(n){e.toBlob(n,i,t)}):Promise.resolve(dataURLToBlob(e.toDataURL(i,t)))}function binaryStringToArrayBuffer(e){for(var i=e.length,t=new ArrayBuffer(i),n=new Uint8Array(t),a=-1;++a<i;)n[a]=e.charCodeAt(a);return t}function getDefaultExportFromCjs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function getAugmentedNamespace(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var i=e.default;if(typeof i=="function"){var t=function n(){return this instanceof n?Reflect.construct(i,arguments,this.constructor):i.apply(this,arguments)};t.prototype=i.prototype}else t={};return Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(e).forEach(function(n){var a=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,a.get?a:{enumerable:!0,get:function(){return e[n]}})}),t}var src$5={};function decode$2(e,i="utf8"){return new TextDecoder(i).decode(e)}const encoder$1=new TextEncoder;function encode$1(e){return encoder$1.encode(e)}const defaultByteLength=1024*8,hostBigEndian=(()=>{const e=new Uint8Array(4),i=new Uint32Array(e.buffer);return!((i[0]=1)&e[0])})(),typedArrays={int8:globalThis.Int8Array,uint8:globalThis.Uint8Array,int16:globalThis.Int16Array,uint16:globalThis.Uint16Array,int32:globalThis.Int32Array,uint32:globalThis.Uint32Array,uint64:globalThis.BigUint64Array,int64:globalThis.BigInt64Array,float32:globalThis.Float32Array,float64:globalThis.Float64Array};class IOBuffer{constructor(i=defaultByteLength,t={}){we(this,"buffer");we(this,"byteLength");we(this,"byteOffset");we(this,"length");we(this,"offset");we(this,"lastWrittenByte");we(this,"littleEndian");we(this,"_data");we(this,"_mark");we(this,"_marks");let n=!1;typeof i=="number"?i=new ArrayBuffer(i):(n=!0,this.lastWrittenByte=i.byteLength);const a=t.offset?t.offset>>>0:0,s=i.byteLength-a;let o=a;(ArrayBuffer.isView(i)||i instanceof IOBuffer)&&(i.byteLength!==i.buffer.byteLength&&(o=i.byteOffset+a),i=i.buffer),n?this.lastWrittenByte=s:this.lastWrittenByte=0,this.buffer=i,this.length=s,this.byteLength=s,this.byteOffset=o,this.offset=0,this.littleEndian=!0,this._data=new DataView(this.buffer,o,s),this._mark=0,this._marks=[]}available(i=1){return this.offset+i<=this.length}isLittleEndian(){return this.littleEndian}setLittleEndian(){return this.littleEndian=!0,this}isBigEndian(){return!this.littleEndian}setBigEndian(){return this.littleEndian=!1,this}skip(i=1){return this.offset+=i,this}back(i=1){return this.offset-=i,this}seek(i){return this.offset=i,this}mark(){return this._mark=this.offset,this}reset(){return this.offset=this._mark,this}pushMark(){return this._marks.push(this.offset),this}popMark(){const i=this._marks.pop();if(i===void 0)throw new Error("Mark stack empty");return this.seek(i),this}rewind(){return this.offset=0,this}ensureAvailable(i=1){if(!this.available(i)){const n=(this.offset+i)*2,a=new Uint8Array(n);a.set(new Uint8Array(this.buffer)),this.buffer=a.buffer,this.length=n,this.byteLength=n,this._data=new DataView(this.buffer)}return this}readBoolean(){return this.readUint8()!==0}readInt8(){return this._data.getInt8(this.offset++)}readUint8(){return this._data.getUint8(this.offset++)}readByte(){return this.readUint8()}readBytes(i=1){return this.readArray(i,"uint8")}readArray(i,t){const n=typedArrays[t].BYTES_PER_ELEMENT*i,a=this.byteOffset+this.offset,s=this.buffer.slice(a,a+n);if(this.littleEndian===hostBigEndian&&t!=="uint8"&&t!=="int8"){const h=new Uint8Array(this.buffer.slice(a,a+n));h.reverse();const f=new typedArrays[t](h.buffer);return this.offset+=n,f.reverse(),f}const o=new typedArrays[t](s);return this.offset+=n,o}readInt16(){const i=this._data.getInt16(this.offset,this.littleEndian);return this.offset+=2,i}readUint16(){const i=this._data.getUint16(this.offset,this.littleEndian);return this.offset+=2,i}readInt32(){const i=this._data.getInt32(this.offset,this.littleEndian);return this.offset+=4,i}readUint32(){const i=this._data.getUint32(this.offset,this.littleEndian);return this.offset+=4,i}readFloat32(){const i=this._data.getFloat32(this.offset,this.littleEndian);return this.offset+=4,i}readFloat64(){const i=this._data.getFloat64(this.offset,this.littleEndian);return this.offset+=8,i}readBigInt64(){const i=this._data.getBigInt64(this.offset,this.littleEndian);return this.offset+=8,i}readBigUint64(){const i=this._data.getBigUint64(this.offset,this.littleEndian);return this.offset+=8,i}readChar(){return String.fromCharCode(this.readInt8())}readChars(i=1){let t="";for(let n=0;n<i;n++)t+=this.readChar();return t}readUtf8(i=1){return decode$2(this.readBytes(i))}decodeText(i=1,t="utf8"){return decode$2(this.readBytes(i),t)}writeBoolean(i){return this.writeUint8(i?255:0),this}writeInt8(i){return this.ensureAvailable(1),this._data.setInt8(this.offset++,i),this._updateLastWrittenByte(),this}writeUint8(i){return this.ensureAvailable(1),this._data.setUint8(this.offset++,i),this._updateLastWrittenByte(),this}writeByte(i){return this.writeUint8(i)}writeBytes(i){this.ensureAvailable(i.length);for(let t=0;t<i.length;t++)this._data.setUint8(this.offset++,i[t]);return this._updateLastWrittenByte(),this}writeInt16(i){return this.ensureAvailable(2),this._data.setInt16(this.offset,i,this.littleEndian),this.offset+=2,this._updateLastWrittenByte(),this}writeUint16(i){return this.ensureAvailable(2),this._data.setUint16(this.offset,i,this.littleEndian),this.offset+=2,this._updateLastWrittenByte(),this}writeInt32(i){return this.ensureAvailable(4),this._data.setInt32(this.offset,i,this.littleEndian),this.offset+=4,this._updateLastWrittenByte(),this}writeUint32(i){return this.ensureAvailable(4),this._data.setUint32(this.offset,i,this.littleEndian),this.offset+=4,this._updateLastWrittenByte(),this}writeFloat32(i){return this.ensureAvailable(4),this._data.setFloat32(this.offset,i,this.littleEndian),this.offset+=4,this._updateLastWrittenByte(),this}writeFloat64(i){return this.ensureAvailable(8),this._data.setFloat64(this.offset,i,this.littleEndian),this.offset+=8,this._updateLastWrittenByte(),this}writeBigInt64(i){return this.ensureAvailable(8),this._data.setBigInt64(this.offset,i,this.littleEndian),this.offset+=8,this._updateLastWrittenByte(),this}writeBigUint64(i){return this.ensureAvailable(8),this._data.setBigUint64(this.offset,i,this.littleEndian),this.offset+=8,this._updateLastWrittenByte(),this}writeChar(i){return this.writeUint8(i.charCodeAt(0))}writeChars(i){for(let t=0;t<i.length;t++)this.writeUint8(i.charCodeAt(t));return this}writeUtf8(i){return this.writeBytes(encode$1(i))}toArray(){return new Uint8Array(this.buffer,this.byteOffset,this.lastWrittenByte)}getWrittenByteLength(){return this.lastWrittenByte-this.byteOffset}_updateLastWrittenByte(){this.offset>this.lastWrittenByte&&(this.lastWrittenByte=this.offset)}}const IOBuffer$1=Object.freeze(Object.defineProperty({__proto__:null,IOBuffer},Symbol.toStringTag,{value:"Module"})),require$$0$3=getAugmentedNamespace(IOBuffer$1);var constants$1,hasRequiredConstants$1;function requireConstants$1(){return hasRequiredConstants$1||(hasRequiredConstants$1=1,constants$1={BITMAPV5HEADER:{LogicalColorSpace:{LCS_CALIBRATED_RGB:0,LCS_sRGB:1934772034,LCS_WINDOWS_COLOR_SPACE:1466527264},Compression:{BI_RGB:0,BI_RLE8:1,BI_RLE4:2,BI_BITFIELDS:3,BI_JPEG:4,BI_PNG:5,BI_CMYK:11,BI_CMYKRLE8:12,BI_CMYKRLE4:13},GamutMappingIntent:{LCS_GM_ABS_COLORIMETRIC:8,LCS_GM_BUSINESS:1,LCS_GM_GRAPHICS:2,LCS_GM_IMAGES:4}}}),constants$1}var BMPEncoder_1,hasRequiredBMPEncoder;function requireBMPEncoder(){if(hasRequiredBMPEncoder)return BMPEncoder_1;hasRequiredBMPEncoder=1;const{IOBuffer:e}=require$$0$3,i=requireConstants$1(),t=[];for(let a=0;a<=8;a++)t.push(255<<a);class n extends e{constructor(s){if(s.bitDepth!==1)throw new Error("Only bitDepth of 1 is supported");if(!s.height||!s.width)throw new Error("ImageData width and height are required");super(s.data),this.width=s.width,this.height=s.height,this.bitDepth=s.bitDepth,this.channels=s.channels,this.components=s.components}encode(){this.encoded=new e,this.encoded.skip(14),this.writeBitmapV5Header(),this.writeColorTable();const s=this.encoded.offset;return this.writePixelArray(),this.encoded.rewind(),this.writeBitmapFileHeader(s),this.encoded.toArray()}writePixelArray(){let s=this.encoded;const o=Math.floor((this.bitDepth*this.width+31)/32)*4,h=Math.ceil(this.bitDepth*this.width/8),f=o-h,l=this.bitDepth*this.width%8,u=l===0?0:8-l,w=o*this.height;let _,g,v=0,k=0,A=8;s.mark(),g=this.readUint8();for(let T=this.height-1;T>=0;T--){const $=T===0;s.reset(),s.skip(T*o);for(let D=0;D<h;D++){const C=D===h-1;k<=u&&C?(s.writeByte(g<<k),(u===0||u===k)&&!$&&(_=g,g=this.readByte())):k===0?(_=g,g=this.readUint8(),s.writeByte(_)):(_=g,g=this.readUint8(),s.writeByte(_<<k&t[k]|g>>A)),C&&(v+=l||0,s.skip(f),k=v%8,A=8-k)}}o>h&&(s.reset(),s.skip(w-1),s.writeUint8(0))}writeColorTable(){this.encoded.writeUint32(0).writeUint32(16777215)}writeBitmapFileHeader(s){this.encoded.writeChars("BM").writeInt32(this.encoded.lastWrittenByte).writeUint16(0).writeUint16(0).writeUint32(s)}writeBitmapV5Header(){const o=Math.floor((this.bitDepth*this.width+31)/32)*4*this.height;this.encoded.writeUint32(124).writeInt32(this.width).writeInt32(this.height).writeUint16(1).writeUint16(this.bitDepth).writeUint32(i.BITMAPV5HEADER.Compression.BI_RGB).writeUint32(o).writeInt32(0).writeInt32(0).writeUint32(Math.pow(2,this.bitDepth)).writeUint32(Math.pow(2,this.bitDepth)).writeUint32(4278190080).writeUint32(16711680).writeUint32(65280).writeUint32(255).writeUint32(i.BITMAPV5HEADER.LogicalColorSpace.LCS_sRGB).skip(36).skip(12).writeUint32(i.BITMAPV5HEADER.GamutMappingIntent.LCS_GM_IMAGES).skip(12)}}return BMPEncoder_1=n,BMPEncoder_1}var hasRequiredSrc$5;function requireSrc$5(){if(hasRequiredSrc$5)return src$5;hasRequiredSrc$5=1;const e=requireBMPEncoder();return src$5.encode=function(t){return new e(t).encode()},src$5}var srcExports$3=requireSrc$5();/*! pako 2.1.0 https://github.com/nodeca/pako @license (MIT AND Zlib) */const Z_FIXED$1=4,Z_BINARY=0,Z_TEXT=1,Z_UNKNOWN$1=2;function zero$1$1(e){let i=e.length;for(;--i>=0;)e[i]=0}const STORED_BLOCK=0,STATIC_TREES=1,DYN_TREES=2,MIN_MATCH$1$1=3,MAX_MATCH$1$1=258,LENGTH_CODES$1$1=29,LITERALS$1$1=256,L_CODES$1$1=LITERALS$1$1+1+LENGTH_CODES$1$1,D_CODES$1$1=30,BL_CODES$1=19,HEAP_SIZE$1=2*L_CODES$1$1+1,MAX_BITS$1=15,Buf_size=16,MAX_BL_BITS=7,END_BLOCK=256,REP_3_6=16,REPZ_3_10=17,REPZ_11_138=18,extra_lbits=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),extra_dbits=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),extra_blbits=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),bl_order=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),DIST_CODE_LEN$1=512,static_ltree$1=new Array((L_CODES$1$1+2)*2);zero$1$1(static_ltree$1);const static_dtree$1=new Array(D_CODES$1$1*2);zero$1$1(static_dtree$1);const _dist_code$1=new Array(DIST_CODE_LEN$1);zero$1$1(_dist_code$1);const _length_code$1=new Array(MAX_MATCH$1$1-MIN_MATCH$1$1+1);zero$1$1(_length_code$1);const base_length$1=new Array(LENGTH_CODES$1$1);zero$1$1(base_length$1);const base_dist$1=new Array(D_CODES$1$1);zero$1$1(base_dist$1);function StaticTreeDesc(e,i,t,n,a){this.static_tree=e,this.extra_bits=i,this.extra_base=t,this.elems=n,this.max_length=a,this.has_stree=e&&e.length}let static_l_desc,static_d_desc,static_bl_desc;function TreeDesc(e,i){this.dyn_tree=e,this.max_code=0,this.stat_desc=i}const d_code=e=>e<256?_dist_code$1[e]:_dist_code$1[256+(e>>>7)],put_short=(e,i)=>{e.pending_buf[e.pending++]=i&255,e.pending_buf[e.pending++]=i>>>8&255},send_bits=(e,i,t)=>{e.bi_valid>Buf_size-t?(e.bi_buf|=i<<e.bi_valid&65535,put_short(e,e.bi_buf),e.bi_buf=i>>Buf_size-e.bi_valid,e.bi_valid+=t-Buf_size):(e.bi_buf|=i<<e.bi_valid&65535,e.bi_valid+=t)},send_code=(e,i,t)=>{send_bits(e,t[i*2],t[i*2+1])},bi_reverse=(e,i)=>{let t=0;do t|=e&1,e>>>=1,t<<=1;while(--i>0);return t>>>1},bi_flush=e=>{e.bi_valid===16?(put_short(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=e.bi_buf&255,e.bi_buf>>=8,e.bi_valid-=8)},gen_bitlen=(e,i)=>{const t=i.dyn_tree,n=i.max_code,a=i.stat_desc.static_tree,s=i.stat_desc.has_stree,o=i.stat_desc.extra_bits,h=i.stat_desc.extra_base,f=i.stat_desc.max_length;let l,u,w,_,g,v,k=0;for(_=0;_<=MAX_BITS$1;_++)e.bl_count[_]=0;for(t[e.heap[e.heap_max]*2+1]=0,l=e.heap_max+1;l<HEAP_SIZE$1;l++)u=e.heap[l],_=t[t[u*2+1]*2+1]+1,_>f&&(_=f,k++),t[u*2+1]=_,!(u>n)&&(e.bl_count[_]++,g=0,u>=h&&(g=o[u-h]),v=t[u*2],e.opt_len+=v*(_+g),s&&(e.static_len+=v*(a[u*2+1]+g)));if(k!==0){do{for(_=f-1;e.bl_count[_]===0;)_--;e.bl_count[_]--,e.bl_count[_+1]+=2,e.bl_count[f]--,k-=2}while(k>0);for(_=f;_!==0;_--)for(u=e.bl_count[_];u!==0;)w=e.heap[--l],!(w>n)&&(t[w*2+1]!==_&&(e.opt_len+=(_-t[w*2+1])*t[w*2],t[w*2+1]=_),u--)}},gen_codes=(e,i,t)=>{const n=new Array(MAX_BITS$1+1);let a=0,s,o;for(s=1;s<=MAX_BITS$1;s++)a=a+t[s-1]<<1,n[s]=a;for(o=0;o<=i;o++){let h=e[o*2+1];h!==0&&(e[o*2]=bi_reverse(n[h]++,h))}},tr_static_init=()=>{let e,i,t,n,a;const s=new Array(MAX_BITS$1+1);for(t=0,n=0;n<LENGTH_CODES$1$1-1;n++)for(base_length$1[n]=t,e=0;e<1<<extra_lbits[n];e++)_length_code$1[t++]=n;for(_length_code$1[t-1]=n,a=0,n=0;n<16;n++)for(base_dist$1[n]=a,e=0;e<1<<extra_dbits[n];e++)_dist_code$1[a++]=n;for(a>>=7;n<D_CODES$1$1;n++)for(base_dist$1[n]=a<<7,e=0;e<1<<extra_dbits[n]-7;e++)_dist_code$1[256+a++]=n;for(i=0;i<=MAX_BITS$1;i++)s[i]=0;for(e=0;e<=143;)static_ltree$1[e*2+1]=8,e++,s[8]++;for(;e<=255;)static_ltree$1[e*2+1]=9,e++,s[9]++;for(;e<=279;)static_ltree$1[e*2+1]=7,e++,s[7]++;for(;e<=287;)static_ltree$1[e*2+1]=8,e++,s[8]++;for(gen_codes(static_ltree$1,L_CODES$1$1+1,s),e=0;e<D_CODES$1$1;e++)static_dtree$1[e*2+1]=5,static_dtree$1[e*2]=bi_reverse(e,5);static_l_desc=new StaticTreeDesc(static_ltree$1,extra_lbits,LITERALS$1$1+1,L_CODES$1$1,MAX_BITS$1),static_d_desc=new StaticTreeDesc(static_dtree$1,extra_dbits,0,D_CODES$1$1,MAX_BITS$1),static_bl_desc=new StaticTreeDesc(new Array(0),extra_blbits,0,BL_CODES$1,MAX_BL_BITS)},init_block=e=>{let i;for(i=0;i<L_CODES$1$1;i++)e.dyn_ltree[i*2]=0;for(i=0;i<D_CODES$1$1;i++)e.dyn_dtree[i*2]=0;for(i=0;i<BL_CODES$1;i++)e.bl_tree[i*2]=0;e.dyn_ltree[END_BLOCK*2]=1,e.opt_len=e.static_len=0,e.sym_next=e.matches=0},bi_windup=e=>{e.bi_valid>8?put_short(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0},smaller=(e,i,t,n)=>{const a=i*2,s=t*2;return e[a]<e[s]||e[a]===e[s]&&n[i]<=n[t]},pqdownheap=(e,i,t)=>{const n=e.heap[t];let a=t<<1;for(;a<=e.heap_len&&(a<e.heap_len&&smaller(i,e.heap[a+1],e.heap[a],e.depth)&&a++,!smaller(i,n,e.heap[a],e.depth));)e.heap[t]=e.heap[a],t=a,a<<=1;e.heap[t]=n},compress_block=(e,i,t)=>{let n,a,s=0,o,h;if(e.sym_next!==0)do n=e.pending_buf[e.sym_buf+s++]&255,n+=(e.pending_buf[e.sym_buf+s++]&255)<<8,a=e.pending_buf[e.sym_buf+s++],n===0?send_code(e,a,i):(o=_length_code$1[a],send_code(e,o+LITERALS$1$1+1,i),h=extra_lbits[o],h!==0&&(a-=base_length$1[o],send_bits(e,a,h)),n--,o=d_code(n),send_code(e,o,t),h=extra_dbits[o],h!==0&&(n-=base_dist$1[o],send_bits(e,n,h)));while(s<e.sym_next);send_code(e,END_BLOCK,i)},build_tree=(e,i)=>{const t=i.dyn_tree,n=i.stat_desc.static_tree,a=i.stat_desc.has_stree,s=i.stat_desc.elems;let o,h,f=-1,l;for(e.heap_len=0,e.heap_max=HEAP_SIZE$1,o=0;o<s;o++)t[o*2]!==0?(e.heap[++e.heap_len]=f=o,e.depth[o]=0):t[o*2+1]=0;for(;e.heap_len<2;)l=e.heap[++e.heap_len]=f<2?++f:0,t[l*2]=1,e.depth[l]=0,e.opt_len--,a&&(e.static_len-=n[l*2+1]);for(i.max_code=f,o=e.heap_len>>1;o>=1;o--)pqdownheap(e,t,o);l=s;do o=e.heap[1],e.heap[1]=e.heap[e.heap_len--],pqdownheap(e,t,1),h=e.heap[1],e.heap[--e.heap_max]=o,e.heap[--e.heap_max]=h,t[l*2]=t[o*2]+t[h*2],e.depth[l]=(e.depth[o]>=e.depth[h]?e.depth[o]:e.depth[h])+1,t[o*2+1]=t[h*2+1]=l,e.heap[1]=l++,pqdownheap(e,t,1);while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],gen_bitlen(e,i),gen_codes(t,f,e.bl_count)},scan_tree=(e,i,t)=>{let n,a=-1,s,o=i[0*2+1],h=0,f=7,l=4;for(o===0&&(f=138,l=3),i[(t+1)*2+1]=65535,n=0;n<=t;n++)s=o,o=i[(n+1)*2+1],!(++h<f&&s===o)&&(h<l?e.bl_tree[s*2]+=h:s!==0?(s!==a&&e.bl_tree[s*2]++,e.bl_tree[REP_3_6*2]++):h<=10?e.bl_tree[REPZ_3_10*2]++:e.bl_tree[REPZ_11_138*2]++,h=0,a=s,o===0?(f=138,l=3):s===o?(f=6,l=3):(f=7,l=4))},send_tree=(e,i,t)=>{let n,a=-1,s,o=i[0*2+1],h=0,f=7,l=4;for(o===0&&(f=138,l=3),n=0;n<=t;n++)if(s=o,o=i[(n+1)*2+1],!(++h<f&&s===o)){if(h<l)do send_code(e,s,e.bl_tree);while(--h!==0);else s!==0?(s!==a&&(send_code(e,s,e.bl_tree),h--),send_code(e,REP_3_6,e.bl_tree),send_bits(e,h-3,2)):h<=10?(send_code(e,REPZ_3_10,e.bl_tree),send_bits(e,h-3,3)):(send_code(e,REPZ_11_138,e.bl_tree),send_bits(e,h-11,7));h=0,a=s,o===0?(f=138,l=3):s===o?(f=6,l=3):(f=7,l=4)}},build_bl_tree=e=>{let i;for(scan_tree(e,e.dyn_ltree,e.l_desc.max_code),scan_tree(e,e.dyn_dtree,e.d_desc.max_code),build_tree(e,e.bl_desc),i=BL_CODES$1-1;i>=3&&e.bl_tree[bl_order[i]*2+1]===0;i--);return e.opt_len+=3*(i+1)+5+5+4,i},send_all_trees=(e,i,t,n)=>{let a;for(send_bits(e,i-257,5),send_bits(e,t-1,5),send_bits(e,n-4,4),a=0;a<n;a++)send_bits(e,e.bl_tree[bl_order[a]*2+1],3);send_tree(e,e.dyn_ltree,i-1),send_tree(e,e.dyn_dtree,t-1)},detect_data_type=e=>{let i=4093624447,t;for(t=0;t<=31;t++,i>>>=1)if(i&1&&e.dyn_ltree[t*2]!==0)return Z_BINARY;if(e.dyn_ltree[9*2]!==0||e.dyn_ltree[10*2]!==0||e.dyn_ltree[13*2]!==0)return Z_TEXT;for(t=32;t<LITERALS$1$1;t++)if(e.dyn_ltree[t*2]!==0)return Z_TEXT;return Z_BINARY};let static_init_done=!1;const _tr_init$1=e=>{static_init_done||(tr_static_init(),static_init_done=!0),e.l_desc=new TreeDesc(e.dyn_ltree,static_l_desc),e.d_desc=new TreeDesc(e.dyn_dtree,static_d_desc),e.bl_desc=new TreeDesc(e.bl_tree,static_bl_desc),e.bi_buf=0,e.bi_valid=0,init_block(e)},_tr_stored_block$1=(e,i,t,n)=>{send_bits(e,(STORED_BLOCK<<1)+(n?1:0),3),bi_windup(e),put_short(e,t),put_short(e,~t),t&&e.pending_buf.set(e.window.subarray(i,i+t),e.pending),e.pending+=t},_tr_align$1=e=>{send_bits(e,STATIC_TREES<<1,3),send_code(e,END_BLOCK,static_ltree$1),bi_flush(e)},_tr_flush_block$1=(e,i,t,n)=>{let a,s,o=0;e.level>0?(e.strm.data_type===Z_UNKNOWN$1&&(e.strm.data_type=detect_data_type(e)),build_tree(e,e.l_desc),build_tree(e,e.d_desc),o=build_bl_tree(e),a=e.opt_len+3+7>>>3,s=e.static_len+3+7>>>3,s<=a&&(a=s)):a=s=t+5,t+4<=a&&i!==-1?_tr_stored_block$1(e,i,t,n):e.strategy===Z_FIXED$1||s===a?(send_bits(e,(STATIC_TREES<<1)+(n?1:0),3),compress_block(e,static_ltree$1,static_dtree$1)):(send_bits(e,(DYN_TREES<<1)+(n?1:0),3),send_all_trees(e,e.l_desc.max_code+1,e.d_desc.max_code+1,o+1),compress_block(e,e.dyn_ltree,e.dyn_dtree)),init_block(e),n&&bi_windup(e)},_tr_tally$1=(e,i,t)=>(e.pending_buf[e.sym_buf+e.sym_next++]=i,e.pending_buf[e.sym_buf+e.sym_next++]=i>>8,e.pending_buf[e.sym_buf+e.sym_next++]=t,i===0?e.dyn_ltree[t*2]++:(e.matches++,i--,e.dyn_ltree[(_length_code$1[t]+LITERALS$1$1+1)*2]++,e.dyn_dtree[d_code(i)*2]++),e.sym_next===e.sym_end);var _tr_init_1=_tr_init$1,_tr_stored_block_1=_tr_stored_block$1,_tr_flush_block_1=_tr_flush_block$1,_tr_tally_1=_tr_tally$1,_tr_align_1=_tr_align$1,trees$1={_tr_init:_tr_init_1,_tr_stored_block:_tr_stored_block_1,_tr_flush_block:_tr_flush_block_1,_tr_tally:_tr_tally_1,_tr_align:_tr_align_1};const adler32$1=(e,i,t,n)=>{let a=e&65535|0,s=e>>>16&65535|0,o=0;for(;t!==0;){o=t>2e3?2e3:t,t-=o;do a=a+i[n++]|0,s=s+a|0;while(--o);a%=65521,s%=65521}return a|s<<16|0};var adler32_1$2=adler32$1;const makeTable$1=()=>{let e,i=[];for(var t=0;t<256;t++){e=t;for(var n=0;n<8;n++)e=e&1?3988292384^e>>>1:e>>>1;i[t]=e}return i},crcTable$2=new Uint32Array(makeTable$1()),crc32$1=(e,i,t,n)=>{const a=crcTable$2,s=n+t;e^=-1;for(let o=n;o<s;o++)e=e>>>8^a[(e^i[o])&255];return e^-1};var crc32_1$2=crc32$1,messages$2={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},constants$2$1={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_UNKNOWN:2,Z_DEFLATED:8};const{_tr_init,_tr_stored_block,_tr_flush_block,_tr_tally,_tr_align}=trees$1,{Z_NO_FLUSH:Z_NO_FLUSH$2,Z_PARTIAL_FLUSH,Z_FULL_FLUSH:Z_FULL_FLUSH$1,Z_FINISH:Z_FINISH$3,Z_BLOCK:Z_BLOCK$1,Z_OK:Z_OK$3,Z_STREAM_END:Z_STREAM_END$3,Z_STREAM_ERROR:Z_STREAM_ERROR$2,Z_DATA_ERROR:Z_DATA_ERROR$2,Z_BUF_ERROR:Z_BUF_ERROR$1,Z_DEFAULT_COMPRESSION:Z_DEFAULT_COMPRESSION$1,Z_FILTERED,Z_HUFFMAN_ONLY,Z_RLE,Z_FIXED,Z_DEFAULT_STRATEGY:Z_DEFAULT_STRATEGY$1,Z_UNKNOWN,Z_DEFLATED:Z_DEFLATED$2}=constants$2$1,MAX_MEM_LEVEL=9,MAX_WBITS$1=15,DEF_MEM_LEVEL=8,LENGTH_CODES=29,LITERALS=256,L_CODES=LITERALS+1+LENGTH_CODES,D_CODES=30,BL_CODES=19,HEAP_SIZE=2*L_CODES+1,MAX_BITS=15,MIN_MATCH=3,MAX_MATCH=258,MIN_LOOKAHEAD=MAX_MATCH+MIN_MATCH+1,PRESET_DICT=32,INIT_STATE=42,GZIP_STATE=57,EXTRA_STATE=69,NAME_STATE=73,COMMENT_STATE=91,HCRC_STATE=103,BUSY_STATE=113,FINISH_STATE=666,BS_NEED_MORE=1,BS_BLOCK_DONE=2,BS_FINISH_STARTED=3,BS_FINISH_DONE=4,OS_CODE=3,err=(e,i)=>(e.msg=messages$2[i],i),rank=e=>e*2-(e>4?9:0),zero=e=>{let i=e.length;for(;--i>=0;)e[i]=0},slide_hash=e=>{let i,t,n,a=e.w_size;i=e.hash_size,n=i;do t=e.head[--n],e.head[n]=t>=a?t-a:0;while(--i);i=a,n=i;do t=e.prev[--n],e.prev[n]=t>=a?t-a:0;while(--i)};let HASH_ZLIB=(e,i,t)=>(i<<e.hash_shift^t)&e.hash_mask,HASH=HASH_ZLIB;const flush_pending=e=>{const i=e.state;let t=i.pending;t>e.avail_out&&(t=e.avail_out),t!==0&&(e.output.set(i.pending_buf.subarray(i.pending_out,i.pending_out+t),e.next_out),e.next_out+=t,i.pending_out+=t,e.total_out+=t,e.avail_out-=t,i.pending-=t,i.pending===0&&(i.pending_out=0))},flush_block_only=(e,i)=>{_tr_flush_block(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,i),e.block_start=e.strstart,flush_pending(e.strm)},put_byte=(e,i)=>{e.pending_buf[e.pending++]=i},putShortMSB=(e,i)=>{e.pending_buf[e.pending++]=i>>>8&255,e.pending_buf[e.pending++]=i&255},read_buf=(e,i,t,n)=>{let a=e.avail_in;return a>n&&(a=n),a===0?0:(e.avail_in-=a,i.set(e.input.subarray(e.next_in,e.next_in+a),t),e.state.wrap===1?e.adler=adler32_1$2(e.adler,i,a,t):e.state.wrap===2&&(e.adler=crc32_1$2(e.adler,i,a,t)),e.next_in+=a,e.total_in+=a,a)},longest_match=(e,i)=>{let t=e.max_chain_length,n=e.strstart,a,s,o=e.prev_length,h=e.nice_match;const f=e.strstart>e.w_size-MIN_LOOKAHEAD?e.strstart-(e.w_size-MIN_LOOKAHEAD):0,l=e.window,u=e.w_mask,w=e.prev,_=e.strstart+MAX_MATCH;let g=l[n+o-1],v=l[n+o];e.prev_length>=e.good_match&&(t>>=2),h>e.lookahead&&(h=e.lookahead);do if(a=i,!(l[a+o]!==v||l[a+o-1]!==g||l[a]!==l[n]||l[++a]!==l[n+1])){n+=2,a++;do;while(l[++n]===l[++a]&&l[++n]===l[++a]&&l[++n]===l[++a]&&l[++n]===l[++a]&&l[++n]===l[++a]&&l[++n]===l[++a]&&l[++n]===l[++a]&&l[++n]===l[++a]&&n<_);if(s=MAX_MATCH-(_-n),n=_-MAX_MATCH,s>o){if(e.match_start=i,o=s,s>=h)break;g=l[n+o-1],v=l[n+o]}}while((i=w[i&u])>f&&--t!==0);return o<=e.lookahead?o:e.lookahead},fill_window=e=>{const i=e.w_size;let t,n,a;do{if(n=e.window_size-e.lookahead-e.strstart,e.strstart>=i+(i-MIN_LOOKAHEAD)&&(e.window.set(e.window.subarray(i,i+i-n),0),e.match_start-=i,e.strstart-=i,e.block_start-=i,e.insert>e.strstart&&(e.insert=e.strstart),slide_hash(e),n+=i),e.strm.avail_in===0)break;if(t=read_buf(e.strm,e.window,e.strstart+e.lookahead,n),e.lookahead+=t,e.lookahead+e.insert>=MIN_MATCH)for(a=e.strstart-e.insert,e.ins_h=e.window[a],e.ins_h=HASH(e,e.ins_h,e.window[a+1]);e.insert&&(e.ins_h=HASH(e,e.ins_h,e.window[a+MIN_MATCH-1]),e.prev[a&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=a,a++,e.insert--,!(e.lookahead+e.insert<MIN_MATCH)););}while(e.lookahead<MIN_LOOKAHEAD&&e.strm.avail_in!==0)},deflate_stored=(e,i)=>{let t=e.pending_buf_size-5>e.w_size?e.w_size:e.pending_buf_size-5,n,a,s,o=0,h=e.strm.avail_in;do{if(n=65535,s=e.bi_valid+42>>3,e.strm.avail_out<s||(s=e.strm.avail_out-s,a=e.strstart-e.block_start,n>a+e.strm.avail_in&&(n=a+e.strm.avail_in),n>s&&(n=s),n<t&&(n===0&&i!==Z_FINISH$3||i===Z_NO_FLUSH$2||n!==a+e.strm.avail_in)))break;o=i===Z_FINISH$3&&n===a+e.strm.avail_in?1:0,_tr_stored_block(e,0,0,o),e.pending_buf[e.pending-4]=n,e.pending_buf[e.pending-3]=n>>8,e.pending_buf[e.pending-2]=~n,e.pending_buf[e.pending-1]=~n>>8,flush_pending(e.strm),a&&(a>n&&(a=n),e.strm.output.set(e.window.subarray(e.block_start,e.block_start+a),e.strm.next_out),e.strm.next_out+=a,e.strm.avail_out-=a,e.strm.total_out+=a,e.block_start+=a,n-=a),n&&(read_buf(e.strm,e.strm.output,e.strm.next_out,n),e.strm.next_out+=n,e.strm.avail_out-=n,e.strm.total_out+=n)}while(o===0);return h-=e.strm.avail_in,h&&(h>=e.w_size?(e.matches=2,e.window.set(e.strm.input.subarray(e.strm.next_in-e.w_size,e.strm.next_in),0),e.strstart=e.w_size,e.insert=e.strstart):(e.window_size-e.strstart<=h&&(e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,e.insert>e.strstart&&(e.insert=e.strstart)),e.window.set(e.strm.input.subarray(e.strm.next_in-h,e.strm.next_in),e.strstart),e.strstart+=h,e.insert+=h>e.w_size-e.insert?e.w_size-e.insert:h),e.block_start=e.strstart),e.high_water<e.strstart&&(e.high_water=e.strstart),o?BS_FINISH_DONE:i!==Z_NO_FLUSH$2&&i!==Z_FINISH$3&&e.strm.avail_in===0&&e.strstart===e.block_start?BS_BLOCK_DONE:(s=e.window_size-e.strstart,e.strm.avail_in>s&&e.block_start>=e.w_size&&(e.block_start-=e.w_size,e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,s+=e.w_size,e.insert>e.strstart&&(e.insert=e.strstart)),s>e.strm.avail_in&&(s=e.strm.avail_in),s&&(read_buf(e.strm,e.window,e.strstart,s),e.strstart+=s,e.insert+=s>e.w_size-e.insert?e.w_size-e.insert:s),e.high_water<e.strstart&&(e.high_water=e.strstart),s=e.bi_valid+42>>3,s=e.pending_buf_size-s>65535?65535:e.pending_buf_size-s,t=s>e.w_size?e.w_size:s,a=e.strstart-e.block_start,(a>=t||(a||i===Z_FINISH$3)&&i!==Z_NO_FLUSH$2&&e.strm.avail_in===0&&a<=s)&&(n=a>s?s:a,o=i===Z_FINISH$3&&e.strm.avail_in===0&&n===a?1:0,_tr_stored_block(e,e.block_start,n,o),e.block_start+=n,flush_pending(e.strm)),o?BS_FINISH_STARTED:BS_NEED_MORE)},deflate_fast=(e,i)=>{let t,n;for(;;){if(e.lookahead<MIN_LOOKAHEAD){if(fill_window(e),e.lookahead<MIN_LOOKAHEAD&&i===Z_NO_FLUSH$2)return BS_NEED_MORE;if(e.lookahead===0)break}if(t=0,e.lookahead>=MIN_MATCH&&(e.ins_h=HASH(e,e.ins_h,e.window[e.strstart+MIN_MATCH-1]),t=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),t!==0&&e.strstart-t<=e.w_size-MIN_LOOKAHEAD&&(e.match_length=longest_match(e,t)),e.match_length>=MIN_MATCH)if(n=_tr_tally(e,e.strstart-e.match_start,e.match_length-MIN_MATCH),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=MIN_MATCH){e.match_length--;do e.strstart++,e.ins_h=HASH(e,e.ins_h,e.window[e.strstart+MIN_MATCH-1]),t=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart;while(--e.match_length!==0);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=HASH(e,e.ins_h,e.window[e.strstart+1]);else n=_tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(n&&(flush_block_only(e,!1),e.strm.avail_out===0))return BS_NEED_MORE}return e.insert=e.strstart<MIN_MATCH-1?e.strstart:MIN_MATCH-1,i===Z_FINISH$3?(flush_block_only(e,!0),e.strm.avail_out===0?BS_FINISH_STARTED:BS_FINISH_DONE):e.sym_next&&(flush_block_only(e,!1),e.strm.avail_out===0)?BS_NEED_MORE:BS_BLOCK_DONE},deflate_slow=(e,i)=>{let t,n,a;for(;;){if(e.lookahead<MIN_LOOKAHEAD){if(fill_window(e),e.lookahead<MIN_LOOKAHEAD&&i===Z_NO_FLUSH$2)return BS_NEED_MORE;if(e.lookahead===0)break}if(t=0,e.lookahead>=MIN_MATCH&&(e.ins_h=HASH(e,e.ins_h,e.window[e.strstart+MIN_MATCH-1]),t=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=MIN_MATCH-1,t!==0&&e.prev_length<e.max_lazy_match&&e.strstart-t<=e.w_size-MIN_LOOKAHEAD&&(e.match_length=longest_match(e,t),e.match_length<=5&&(e.strategy===Z_FILTERED||e.match_length===MIN_MATCH&&e.strstart-e.match_start>4096)&&(e.match_length=MIN_MATCH-1)),e.prev_length>=MIN_MATCH&&e.match_length<=e.prev_length){a=e.strstart+e.lookahead-MIN_MATCH,n=_tr_tally(e,e.strstart-1-e.prev_match,e.prev_length-MIN_MATCH),e.lookahead-=e.prev_length-1,e.prev_length-=2;do++e.strstart<=a&&(e.ins_h=HASH(e,e.ins_h,e.window[e.strstart+MIN_MATCH-1]),t=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart);while(--e.prev_length!==0);if(e.match_available=0,e.match_length=MIN_MATCH-1,e.strstart++,n&&(flush_block_only(e,!1),e.strm.avail_out===0))return BS_NEED_MORE}else if(e.match_available){if(n=_tr_tally(e,0,e.window[e.strstart-1]),n&&flush_block_only(e,!1),e.strstart++,e.lookahead--,e.strm.avail_out===0)return BS_NEED_MORE}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(n=_tr_tally(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<MIN_MATCH-1?e.strstart:MIN_MATCH-1,i===Z_FINISH$3?(flush_block_only(e,!0),e.strm.avail_out===0?BS_FINISH_STARTED:BS_FINISH_DONE):e.sym_next&&(flush_block_only(e,!1),e.strm.avail_out===0)?BS_NEED_MORE:BS_BLOCK_DONE},deflate_rle=(e,i)=>{let t,n,a,s;const o=e.window;for(;;){if(e.lookahead<=MAX_MATCH){if(fill_window(e),e.lookahead<=MAX_MATCH&&i===Z_NO_FLUSH$2)return BS_NEED_MORE;if(e.lookahead===0)break}if(e.match_length=0,e.lookahead>=MIN_MATCH&&e.strstart>0&&(a=e.strstart-1,n=o[a],n===o[++a]&&n===o[++a]&&n===o[++a])){s=e.strstart+MAX_MATCH;do;while(n===o[++a]&&n===o[++a]&&n===o[++a]&&n===o[++a]&&n===o[++a]&&n===o[++a]&&n===o[++a]&&n===o[++a]&&a<s);e.match_length=MAX_MATCH-(s-a),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=MIN_MATCH?(t=_tr_tally(e,1,e.match_length-MIN_MATCH),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(t=_tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),t&&(flush_block_only(e,!1),e.strm.avail_out===0))return BS_NEED_MORE}return e.insert=0,i===Z_FINISH$3?(flush_block_only(e,!0),e.strm.avail_out===0?BS_FINISH_STARTED:BS_FINISH_DONE):e.sym_next&&(flush_block_only(e,!1),e.strm.avail_out===0)?BS_NEED_MORE:BS_BLOCK_DONE},deflate_huff=(e,i)=>{let t;for(;;){if(e.lookahead===0&&(fill_window(e),e.lookahead===0)){if(i===Z_NO_FLUSH$2)return BS_NEED_MORE;break}if(e.match_length=0,t=_tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,t&&(flush_block_only(e,!1),e.strm.avail_out===0))return BS_NEED_MORE}return e.insert=0,i===Z_FINISH$3?(flush_block_only(e,!0),e.strm.avail_out===0?BS_FINISH_STARTED:BS_FINISH_DONE):e.sym_next&&(flush_block_only(e,!1),e.strm.avail_out===0)?BS_NEED_MORE:BS_BLOCK_DONE};function Config(e,i,t,n,a){this.good_length=e,this.max_lazy=i,this.nice_length=t,this.max_chain=n,this.func=a}const configuration_table=[new Config(0,0,0,0,deflate_stored),new Config(4,4,8,4,deflate_fast),new Config(4,5,16,8,deflate_fast),new Config(4,6,32,32,deflate_fast),new Config(4,4,16,16,deflate_slow),new Config(8,16,32,32,deflate_slow),new Config(8,16,128,128,deflate_slow),new Config(8,32,128,256,deflate_slow),new Config(32,128,258,1024,deflate_slow),new Config(32,258,258,4096,deflate_slow)],lm_init=e=>{e.window_size=2*e.w_size,zero(e.head),e.max_lazy_match=configuration_table[e.level].max_lazy,e.good_match=configuration_table[e.level].good_length,e.nice_match=configuration_table[e.level].nice_length,e.max_chain_length=configuration_table[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=MIN_MATCH-1,e.match_available=0,e.ins_h=0};function DeflateState(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Z_DEFLATED$2,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(HEAP_SIZE*2),this.dyn_dtree=new Uint16Array((2*D_CODES+1)*2),this.bl_tree=new Uint16Array((2*BL_CODES+1)*2),zero(this.dyn_ltree),zero(this.dyn_dtree),zero(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(MAX_BITS+1),this.heap=new Uint16Array(2*L_CODES+1),zero(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(2*L_CODES+1),zero(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}const deflateStateCheck=e=>{if(!e)return 1;const i=e.state;return!i||i.strm!==e||i.status!==INIT_STATE&&i.status!==GZIP_STATE&&i.status!==EXTRA_STATE&&i.status!==NAME_STATE&&i.status!==COMMENT_STATE&&i.status!==HCRC_STATE&&i.status!==BUSY_STATE&&i.status!==FINISH_STATE?1:0},deflateResetKeep=e=>{if(deflateStateCheck(e))return err(e,Z_STREAM_ERROR$2);e.total_in=e.total_out=0,e.data_type=Z_UNKNOWN;const i=e.state;return i.pending=0,i.pending_out=0,i.wrap<0&&(i.wrap=-i.wrap),i.status=i.wrap===2?GZIP_STATE:i.wrap?INIT_STATE:BUSY_STATE,e.adler=i.wrap===2?0:1,i.last_flush=-2,_tr_init(i),Z_OK$3},deflateReset=e=>{const i=deflateResetKeep(e);return i===Z_OK$3&&lm_init(e.state),i},deflateSetHeader=(e,i)=>deflateStateCheck(e)||e.state.wrap!==2?Z_STREAM_ERROR$2:(e.state.gzhead=i,Z_OK$3),deflateInit2=(e,i,t,n,a,s)=>{if(!e)return Z_STREAM_ERROR$2;let o=1;if(i===Z_DEFAULT_COMPRESSION$1&&(i=6),n<0?(o=0,n=-n):n>15&&(o=2,n-=16),a<1||a>MAX_MEM_LEVEL||t!==Z_DEFLATED$2||n<8||n>15||i<0||i>9||s<0||s>Z_FIXED||n===8&&o!==1)return err(e,Z_STREAM_ERROR$2);n===8&&(n=9);const h=new DeflateState;return e.state=h,h.strm=e,h.status=INIT_STATE,h.wrap=o,h.gzhead=null,h.w_bits=n,h.w_size=1<<h.w_bits,h.w_mask=h.w_size-1,h.hash_bits=a+7,h.hash_size=1<<h.hash_bits,h.hash_mask=h.hash_size-1,h.hash_shift=~~((h.hash_bits+MIN_MATCH-1)/MIN_MATCH),h.window=new Uint8Array(h.w_size*2),h.head=new Uint16Array(h.hash_size),h.prev=new Uint16Array(h.w_size),h.lit_bufsize=1<<a+6,h.pending_buf_size=h.lit_bufsize*4,h.pending_buf=new Uint8Array(h.pending_buf_size),h.sym_buf=h.lit_bufsize,h.sym_end=(h.lit_bufsize-1)*3,h.level=i,h.strategy=s,h.method=t,deflateReset(e)},deflateInit=(e,i)=>deflateInit2(e,i,Z_DEFLATED$2,MAX_WBITS$1,DEF_MEM_LEVEL,Z_DEFAULT_STRATEGY$1),deflate$2=(e,i)=>{if(deflateStateCheck(e)||i>Z_BLOCK$1||i<0)return e?err(e,Z_STREAM_ERROR$2):Z_STREAM_ERROR$2;const t=e.state;if(!e.output||e.avail_in!==0&&!e.input||t.status===FINISH_STATE&&i!==Z_FINISH$3)return err(e,e.avail_out===0?Z_BUF_ERROR$1:Z_STREAM_ERROR$2);const n=t.last_flush;if(t.last_flush=i,t.pending!==0){if(flush_pending(e),e.avail_out===0)return t.last_flush=-1,Z_OK$3}else if(e.avail_in===0&&rank(i)<=rank(n)&&i!==Z_FINISH$3)return err(e,Z_BUF_ERROR$1);if(t.status===FINISH_STATE&&e.avail_in!==0)return err(e,Z_BUF_ERROR$1);if(t.status===INIT_STATE&&t.wrap===0&&(t.status=BUSY_STATE),t.status===INIT_STATE){let a=Z_DEFLATED$2+(t.w_bits-8<<4)<<8,s=-1;if(t.strategy>=Z_HUFFMAN_ONLY||t.level<2?s=0:t.level<6?s=1:t.level===6?s=2:s=3,a|=s<<6,t.strstart!==0&&(a|=PRESET_DICT),a+=31-a%31,putShortMSB(t,a),t.strstart!==0&&(putShortMSB(t,e.adler>>>16),putShortMSB(t,e.adler&65535)),e.adler=1,t.status=BUSY_STATE,flush_pending(e),t.pending!==0)return t.last_flush=-1,Z_OK$3}if(t.status===GZIP_STATE){if(e.adler=0,put_byte(t,31),put_byte(t,139),put_byte(t,8),t.gzhead)put_byte(t,(t.gzhead.text?1:0)+(t.gzhead.hcrc?2:0)+(t.gzhead.extra?4:0)+(t.gzhead.name?8:0)+(t.gzhead.comment?16:0)),put_byte(t,t.gzhead.time&255),put_byte(t,t.gzhead.time>>8&255),put_byte(t,t.gzhead.time>>16&255),put_byte(t,t.gzhead.time>>24&255),put_byte(t,t.level===9?2:t.strategy>=Z_HUFFMAN_ONLY||t.level<2?4:0),put_byte(t,t.gzhead.os&255),t.gzhead.extra&&t.gzhead.extra.length&&(put_byte(t,t.gzhead.extra.length&255),put_byte(t,t.gzhead.extra.length>>8&255)),t.gzhead.hcrc&&(e.adler=crc32_1$2(e.adler,t.pending_buf,t.pending,0)),t.gzindex=0,t.status=EXTRA_STATE;else if(put_byte(t,0),put_byte(t,0),put_byte(t,0),put_byte(t,0),put_byte(t,0),put_byte(t,t.level===9?2:t.strategy>=Z_HUFFMAN_ONLY||t.level<2?4:0),put_byte(t,OS_CODE),t.status=BUSY_STATE,flush_pending(e),t.pending!==0)return t.last_flush=-1,Z_OK$3}if(t.status===EXTRA_STATE){if(t.gzhead.extra){let a=t.pending,s=(t.gzhead.extra.length&65535)-t.gzindex;for(;t.pending+s>t.pending_buf_size;){let h=t.pending_buf_size-t.pending;if(t.pending_buf.set(t.gzhead.extra.subarray(t.gzindex,t.gzindex+h),t.pending),t.pending=t.pending_buf_size,t.gzhead.hcrc&&t.pending>a&&(e.adler=crc32_1$2(e.adler,t.pending_buf,t.pending-a,a)),t.gzindex+=h,flush_pending(e),t.pending!==0)return t.last_flush=-1,Z_OK$3;a=0,s-=h}let o=new Uint8Array(t.gzhead.extra);t.pending_buf.set(o.subarray(t.gzindex,t.gzindex+s),t.pending),t.pending+=s,t.gzhead.hcrc&&t.pending>a&&(e.adler=crc32_1$2(e.adler,t.pending_buf,t.pending-a,a)),t.gzindex=0}t.status=NAME_STATE}if(t.status===NAME_STATE){if(t.gzhead.name){let a=t.pending,s;do{if(t.pending===t.pending_buf_size){if(t.gzhead.hcrc&&t.pending>a&&(e.adler=crc32_1$2(e.adler,t.pending_buf,t.pending-a,a)),flush_pending(e),t.pending!==0)return t.last_flush=-1,Z_OK$3;a=0}t.gzindex<t.gzhead.name.length?s=t.gzhead.name.charCodeAt(t.gzindex++)&255:s=0,put_byte(t,s)}while(s!==0);t.gzhead.hcrc&&t.pending>a&&(e.adler=crc32_1$2(e.adler,t.pending_buf,t.pending-a,a)),t.gzindex=0}t.status=COMMENT_STATE}if(t.status===COMMENT_STATE){if(t.gzhead.comment){let a=t.pending,s;do{if(t.pending===t.pending_buf_size){if(t.gzhead.hcrc&&t.pending>a&&(e.adler=crc32_1$2(e.adler,t.pending_buf,t.pending-a,a)),flush_pending(e),t.pending!==0)return t.last_flush=-1,Z_OK$3;a=0}t.gzindex<t.gzhead.comment.length?s=t.gzhead.comment.charCodeAt(t.gzindex++)&255:s=0,put_byte(t,s)}while(s!==0);t.gzhead.hcrc&&t.pending>a&&(e.adler=crc32_1$2(e.adler,t.pending_buf,t.pending-a,a))}t.status=HCRC_STATE}if(t.status===HCRC_STATE){if(t.gzhead.hcrc){if(t.pending+2>t.pending_buf_size&&(flush_pending(e),t.pending!==0))return t.last_flush=-1,Z_OK$3;put_byte(t,e.adler&255),put_byte(t,e.adler>>8&255),e.adler=0}if(t.status=BUSY_STATE,flush_pending(e),t.pending!==0)return t.last_flush=-1,Z_OK$3}if(e.avail_in!==0||t.lookahead!==0||i!==Z_NO_FLUSH$2&&t.status!==FINISH_STATE){let a=t.level===0?deflate_stored(t,i):t.strategy===Z_HUFFMAN_ONLY?deflate_huff(t,i):t.strategy===Z_RLE?deflate_rle(t,i):configuration_table[t.level].func(t,i);if((a===BS_FINISH_STARTED||a===BS_FINISH_DONE)&&(t.status=FINISH_STATE),a===BS_NEED_MORE||a===BS_FINISH_STARTED)return e.avail_out===0&&(t.last_flush=-1),Z_OK$3;if(a===BS_BLOCK_DONE&&(i===Z_PARTIAL_FLUSH?_tr_align(t):i!==Z_BLOCK$1&&(_tr_stored_block(t,0,0,!1),i===Z_FULL_FLUSH$1&&(zero(t.head),t.lookahead===0&&(t.strstart=0,t.block_start=0,t.insert=0))),flush_pending(e),e.avail_out===0))return t.last_flush=-1,Z_OK$3}return i!==Z_FINISH$3?Z_OK$3:t.wrap<=0?Z_STREAM_END$3:(t.wrap===2?(put_byte(t,e.adler&255),put_byte(t,e.adler>>8&255),put_byte(t,e.adler>>16&255),put_byte(t,e.adler>>24&255),put_byte(t,e.total_in&255),put_byte(t,e.total_in>>8&255),put_byte(t,e.total_in>>16&255),put_byte(t,e.total_in>>24&255)):(putShortMSB(t,e.adler>>>16),putShortMSB(t,e.adler&65535)),flush_pending(e),t.wrap>0&&(t.wrap=-t.wrap),t.pending!==0?Z_OK$3:Z_STREAM_END$3)},deflateEnd=e=>{if(deflateStateCheck(e))return Z_STREAM_ERROR$2;const i=e.state.status;return e.state=null,i===BUSY_STATE?err(e,Z_DATA_ERROR$2):Z_OK$3},deflateSetDictionary=(e,i)=>{let t=i.length;if(deflateStateCheck(e))return Z_STREAM_ERROR$2;const n=e.state,a=n.wrap;if(a===2||a===1&&n.status!==INIT_STATE||n.lookahead)return Z_STREAM_ERROR$2;if(a===1&&(e.adler=adler32_1$2(e.adler,i,t,0)),n.wrap=0,t>=n.w_size){a===0&&(zero(n.head),n.strstart=0,n.block_start=0,n.insert=0);let f=new Uint8Array(n.w_size);f.set(i.subarray(t-n.w_size,t),0),i=f,t=n.w_size}const s=e.avail_in,o=e.next_in,h=e.input;for(e.avail_in=t,e.next_in=0,e.input=i,fill_window(n);n.lookahead>=MIN_MATCH;){let f=n.strstart,l=n.lookahead-(MIN_MATCH-1);do n.ins_h=HASH(n,n.ins_h,n.window[f+MIN_MATCH-1]),n.prev[f&n.w_mask]=n.head[n.ins_h],n.head[n.ins_h]=f,f++;while(--l);n.strstart=f,n.lookahead=MIN_MATCH-1,fill_window(n)}return n.strstart+=n.lookahead,n.block_start=n.strstart,n.insert=n.lookahead,n.lookahead=0,n.match_length=n.prev_length=MIN_MATCH-1,n.match_available=0,e.next_in=o,e.input=h,e.avail_in=s,n.wrap=a,Z_OK$3};var deflateInit_1=deflateInit,deflateInit2_1=deflateInit2,deflateReset_1=deflateReset,deflateResetKeep_1=deflateResetKeep,deflateSetHeader_1=deflateSetHeader,deflate_2$1=deflate$2,deflateEnd_1=deflateEnd,deflateSetDictionary_1=deflateSetDictionary,deflateInfo="pako deflate (from Nodeca project)",deflate_1$2={deflateInit:deflateInit_1,deflateInit2:deflateInit2_1,deflateReset:deflateReset_1,deflateResetKeep:deflateResetKeep_1,deflateSetHeader:deflateSetHeader_1,deflate:deflate_2$1,deflateEnd:deflateEnd_1,deflateSetDictionary:deflateSetDictionary_1,deflateInfo};const _has$1=(e,i)=>Object.prototype.hasOwnProperty.call(e,i);var assign$1=function(e){const i=Array.prototype.slice.call(arguments,1);for(;i.length;){const t=i.shift();if(t){if(typeof t!="object")throw new TypeError(t+"must be non-object");for(const n in t)_has$1(t,n)&&(e[n]=t[n])}}return e},flattenChunks$1=e=>{let i=0;for(let n=0,a=e.length;n<a;n++)i+=e[n].length;const t=new Uint8Array(i);for(let n=0,a=0,s=e.length;n<s;n++){let o=e[n];t.set(o,a),a+=o.length}return t},common$2={assign:assign$1,flattenChunks:flattenChunks$1};let STR_APPLY_UIA_OK$1=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){STR_APPLY_UIA_OK$1=!1}const _utf8len$1=new Uint8Array(256);for(let e=0;e<256;e++)_utf8len$1[e]=e>=252?6:e>=248?5:e>=240?4:e>=224?3:e>=192?2:1;_utf8len$1[254]=_utf8len$1[254]=1;var string2buf$1=e=>{if(typeof TextEncoder=="function"&&TextEncoder.prototype.encode)return new TextEncoder().encode(e);let i,t,n,a,s,o=e.length,h=0;for(a=0;a<o;a++)t=e.charCodeAt(a),(t&64512)===55296&&a+1<o&&(n=e.charCodeAt(a+1),(n&64512)===56320&&(t=65536+(t-55296<<10)+(n-56320),a++)),h+=t<128?1:t<2048?2:t<65536?3:4;for(i=new Uint8Array(h),s=0,a=0;s<h;a++)t=e.charCodeAt(a),(t&64512)===55296&&a+1<o&&(n=e.charCodeAt(a+1),(n&64512)===56320&&(t=65536+(t-55296<<10)+(n-56320),a++)),t<128?i[s++]=t:t<2048?(i[s++]=192|t>>>6,i[s++]=128|t&63):t<65536?(i[s++]=224|t>>>12,i[s++]=128|t>>>6&63,i[s++]=128|t&63):(i[s++]=240|t>>>18,i[s++]=128|t>>>12&63,i[s++]=128|t>>>6&63,i[s++]=128|t&63);return i};const buf2binstring$1=(e,i)=>{if(i<65534&&e.subarray&&STR_APPLY_UIA_OK$1)return String.fromCharCode.apply(null,e.length===i?e:e.subarray(0,i));let t="";for(let n=0;n<i;n++)t+=String.fromCharCode(e[n]);return t};var buf2string$1=(e,i)=>{const t=i||e.length;if(typeof TextDecoder=="function"&&TextDecoder.prototype.decode)return new TextDecoder().decode(e.subarray(0,i));let n,a;const s=new Array(t*2);for(a=0,n=0;n<t;){let o=e[n++];if(o<128){s[a++]=o;continue}let h=_utf8len$1[o];if(h>4){s[a++]=65533,n+=h-1;continue}for(o&=h===2?31:h===3?15:7;h>1&&n<t;)o=o<<6|e[n++]&63,h--;if(h>1){s[a++]=65533;continue}o<65536?s[a++]=o:(o-=65536,s[a++]=55296|o>>10&1023,s[a++]=56320|o&1023)}return buf2binstring$1(s,a)},utf8border$1=(e,i)=>{i=i||e.length,i>e.length&&(i=e.length);let t=i-1;for(;t>=0&&(e[t]&192)===128;)t--;return t<0||t===0?i:t+_utf8len$1[e[t]]>i?t:i},strings$2={string2buf:string2buf$1,buf2string:buf2string$1,utf8border:utf8border$1};function ZStream$1(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}var zstream$2=ZStream$1;const toString$1$1=Object.prototype.toString,{Z_NO_FLUSH:Z_NO_FLUSH$1,Z_SYNC_FLUSH,Z_FULL_FLUSH,Z_FINISH:Z_FINISH$2,Z_OK:Z_OK$2,Z_STREAM_END:Z_STREAM_END$2,Z_DEFAULT_COMPRESSION,Z_DEFAULT_STRATEGY,Z_DEFLATED:Z_DEFLATED$1}=constants$2$1;function Deflate$1(e){this.options=common$2.assign({level:Z_DEFAULT_COMPRESSION,method:Z_DEFLATED$1,chunkSize:16384,windowBits:15,memLevel:8,strategy:Z_DEFAULT_STRATEGY},e||{});let i=this.options;i.raw&&i.windowBits>0?i.windowBits=-i.windowBits:i.gzip&&i.windowBits>0&&i.windowBits<16&&(i.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new zstream$2,this.strm.avail_out=0;let t=deflate_1$2.deflateInit2(this.strm,i.level,i.method,i.windowBits,i.memLevel,i.strategy);if(t!==Z_OK$2)throw new Error(messages$2[t]);if(i.header&&deflate_1$2.deflateSetHeader(this.strm,i.header),i.dictionary){let n;if(typeof i.dictionary=="string"?n=strings$2.string2buf(i.dictionary):toString$1$1.call(i.dictionary)==="[object ArrayBuffer]"?n=new Uint8Array(i.dictionary):n=i.dictionary,t=deflate_1$2.deflateSetDictionary(this.strm,n),t!==Z_OK$2)throw new Error(messages$2[t]);this._dict_set=!0}}Deflate$1.prototype.push=function(e,i){const t=this.strm,n=this.options.chunkSize;let a,s;if(this.ended)return!1;for(i===~~i?s=i:s=i===!0?Z_FINISH$2:Z_NO_FLUSH$1,typeof e=="string"?t.input=strings$2.string2buf(e):toString$1$1.call(e)==="[object ArrayBuffer]"?t.input=new Uint8Array(e):t.input=e,t.next_in=0,t.avail_in=t.input.length;;){if(t.avail_out===0&&(t.output=new Uint8Array(n),t.next_out=0,t.avail_out=n),(s===Z_SYNC_FLUSH||s===Z_FULL_FLUSH)&&t.avail_out<=6){this.onData(t.output.subarray(0,t.next_out)),t.avail_out=0;continue}if(a=deflate_1$2.deflate(t,s),a===Z_STREAM_END$2)return t.next_out>0&&this.onData(t.output.subarray(0,t.next_out)),a=deflate_1$2.deflateEnd(this.strm),this.onEnd(a),this.ended=!0,a===Z_OK$2;if(t.avail_out===0){this.onData(t.output);continue}if(s>0&&t.next_out>0){this.onData(t.output.subarray(0,t.next_out)),t.avail_out=0;continue}if(t.avail_in===0)break}return!0},Deflate$1.prototype.onData=function(e){this.chunks.push(e)},Deflate$1.prototype.onEnd=function(e){e===Z_OK$2&&(this.result=common$2.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};function deflate$1$1(e,i){const t=new Deflate$1(i);if(t.push(e,!0),t.err)throw t.msg||messages$2[t.err];return t.result}var deflate_2=deflate$1$1,deflate_1$1={deflate:deflate_2};const BAD$1$1=16209,TYPE$1$1=16191;var inffast$2=function(i,t){let n,a,s,o,h,f,l,u,w,_,g,v,k,A,T,$,D,C,P,z,B,F,L,N;const G=i.state;n=i.next_in,L=i.input,a=n+(i.avail_in-5),s=i.next_out,N=i.output,o=s-(t-i.avail_out),h=s+(i.avail_out-257),f=G.dmax,l=G.wsize,u=G.whave,w=G.wnext,_=G.window,g=G.hold,v=G.bits,k=G.lencode,A=G.distcode,T=(1<<G.lenbits)-1,$=(1<<G.distbits)-1;e:do{v<15&&(g+=L[n++]<<v,v+=8,g+=L[n++]<<v,v+=8),D=k[g&T];t:for(;;){if(C=D>>>24,g>>>=C,v-=C,C=D>>>16&255,C===0)N[s++]=D&65535;else if(C&16){P=D&65535,C&=15,C&&(v<C&&(g+=L[n++]<<v,v+=8),P+=g&(1<<C)-1,g>>>=C,v-=C),v<15&&(g+=L[n++]<<v,v+=8,g+=L[n++]<<v,v+=8),D=A[g&$];i:for(;;){if(C=D>>>24,g>>>=C,v-=C,C=D>>>16&255,C&16){if(z=D&65535,C&=15,v<C&&(g+=L[n++]<<v,v+=8,v<C&&(g+=L[n++]<<v,v+=8)),z+=g&(1<<C)-1,z>f){i.msg="invalid distance too far back",G.mode=BAD$1$1;break e}if(g>>>=C,v-=C,C=s-o,z>C){if(C=z-C,C>u&&G.sane){i.msg="invalid distance too far back",G.mode=BAD$1$1;break e}if(B=0,F=_,w===0){if(B+=l-C,C<P){P-=C;do N[s++]=_[B++];while(--C);B=s-z,F=N}}else if(w<C){if(B+=l+w-C,C-=w,C<P){P-=C;do N[s++]=_[B++];while(--C);if(B=0,w<P){C=w,P-=C;do N[s++]=_[B++];while(--C);B=s-z,F=N}}}else if(B+=w-C,C<P){P-=C;do N[s++]=_[B++];while(--C);B=s-z,F=N}for(;P>2;)N[s++]=F[B++],N[s++]=F[B++],N[s++]=F[B++],P-=3;P&&(N[s++]=F[B++],P>1&&(N[s++]=F[B++]))}else{B=s-z;do N[s++]=N[B++],N[s++]=N[B++],N[s++]=N[B++],P-=3;while(P>2);P&&(N[s++]=N[B++],P>1&&(N[s++]=N[B++]))}}else if((C&64)===0){D=A[(D&65535)+(g&(1<<C)-1)];continue i}else{i.msg="invalid distance code",G.mode=BAD$1$1;break e}break}}else if((C&64)===0){D=k[(D&65535)+(g&(1<<C)-1)];continue t}else if(C&32){G.mode=TYPE$1$1;break e}else{i.msg="invalid literal/length code",G.mode=BAD$1$1;break e}break}}while(n<a&&s<h);P=v>>3,n-=P,v-=P<<3,g&=(1<<v)-1,i.next_in=n,i.next_out=s,i.avail_in=n<a?5+(a-n):5-(n-a),i.avail_out=s<h?257+(h-s):257-(s-h),G.hold=g,G.bits=v};const MAXBITS$1=15,ENOUGH_LENS$1$1=852,ENOUGH_DISTS$1$1=592,CODES$1$1=0,LENS$1$1=1,DISTS$1$1=2,lbase$1=new Uint16Array([3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0]),lext$1=new Uint8Array([16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78]),dbase$1=new Uint16Array([1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0]),dext$1=new Uint8Array([16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64]),inflate_table$1=(e,i,t,n,a,s,o,h)=>{const f=h.bits;let l=0,u=0,w=0,_=0,g=0,v=0,k=0,A=0,T=0,$=0,D,C,P,z,B,F=null,L;const N=new Uint16Array(MAXBITS$1+1),G=new Uint16Array(MAXBITS$1+1);let V=null,J,Q,W;for(l=0;l<=MAXBITS$1;l++)N[l]=0;for(u=0;u<n;u++)N[i[t+u]]++;for(g=f,_=MAXBITS$1;_>=1&&N[_]===0;_--);if(g>_&&(g=_),_===0)return a[s++]=1<<24|64<<16|0,a[s++]=1<<24|64<<16|0,h.bits=1,0;for(w=1;w<_&&N[w]===0;w++);for(g<w&&(g=w),A=1,l=1;l<=MAXBITS$1;l++)if(A<<=1,A-=N[l],A<0)return-1;if(A>0&&(e===CODES$1$1||_!==1))return-1;for(G[1]=0,l=1;l<MAXBITS$1;l++)G[l+1]=G[l]+N[l];for(u=0;u<n;u++)i[t+u]!==0&&(o[G[i[t+u]]++]=u);if(e===CODES$1$1?(F=V=o,L=20):e===LENS$1$1?(F=lbase$1,V=lext$1,L=257):(F=dbase$1,V=dext$1,L=0),$=0,u=0,l=w,B=s,v=g,k=0,P=-1,T=1<<g,z=T-1,e===LENS$1$1&&T>ENOUGH_LENS$1$1||e===DISTS$1$1&&T>ENOUGH_DISTS$1$1)return 1;for(;;){J=l-k,o[u]+1<L?(Q=0,W=o[u]):o[u]>=L?(Q=V[o[u]-L],W=F[o[u]-L]):(Q=96,W=0),D=1<<l-k,C=1<<v,w=C;do C-=D,a[B+($>>k)+C]=J<<24|Q<<16|W|0;while(C!==0);for(D=1<<l-1;$&D;)D>>=1;if(D!==0?($&=D-1,$+=D):$=0,u++,--N[l]===0){if(l===_)break;l=i[t+o[u]]}if(l>g&&($&z)!==P){for(k===0&&(k=g),B+=w,v=l-k,A=1<<v;v+k<_&&(A-=N[v+k],!(A<=0));)v++,A<<=1;if(T+=1<<v,e===LENS$1$1&&T>ENOUGH_LENS$1$1||e===DISTS$1$1&&T>ENOUGH_DISTS$1$1)return 1;P=$&z,a[P]=g<<24|v<<16|B-s|0}}return $!==0&&(a[B+$]=l-k<<24|64<<16|0),h.bits=g,0};var inftrees$2=inflate_table$1;const CODES$2=0,LENS$2=1,DISTS$2=2,{Z_FINISH:Z_FINISH$1$1,Z_BLOCK:Z_BLOCK$2,Z_TREES:Z_TREES$1,Z_OK:Z_OK$1$1,Z_STREAM_END:Z_STREAM_END$1$1,Z_NEED_DICT:Z_NEED_DICT$1$1,Z_STREAM_ERROR:Z_STREAM_ERROR$1$1,Z_DATA_ERROR:Z_DATA_ERROR$1$1,Z_MEM_ERROR:Z_MEM_ERROR$1$1,Z_BUF_ERROR:Z_BUF_ERROR$2,Z_DEFLATED:Z_DEFLATED$3}=constants$2$1,HEAD$1=16180,FLAGS$1=16181,TIME$1=16182,OS$1=16183,EXLEN$1=16184,EXTRA$1=16185,NAME$1=16186,COMMENT$1=16187,HCRC$1=16188,DICTID$1=16189,DICT$1=16190,TYPE$2=16191,TYPEDO$1=16192,STORED$1=16193,COPY_$1=16194,COPY$1=16195,TABLE$1=16196,LENLENS$1=16197,CODELENS$1=16198,LEN_$1=16199,LEN$1=16200,LENEXT$1=16201,DIST$1=16202,DISTEXT$1=16203,MATCH$1=16204,LIT$1=16205,CHECK$1=16206,LENGTH$1=16207,DONE$1=16208,BAD$2=16209,MEM$1=16210,SYNC$1=16211,ENOUGH_LENS$2=852,ENOUGH_DISTS$2=592,MAX_WBITS$2=15,DEF_WBITS$1=MAX_WBITS$2,zswap32$1=e=>(e>>>24&255)+(e>>>8&65280)+((e&65280)<<8)+((e&255)<<24);function InflateState$1(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}const inflateStateCheck$1=e=>{if(!e)return 1;const i=e.state;return!i||i.strm!==e||i.mode<HEAD$1||i.mode>SYNC$1?1:0},inflateResetKeep$1=e=>{if(inflateStateCheck$1(e))return Z_STREAM_ERROR$1$1;const i=e.state;return e.total_in=e.total_out=i.total=0,e.msg="",i.wrap&&(e.adler=i.wrap&1),i.mode=HEAD$1,i.last=0,i.havedict=0,i.flags=-1,i.dmax=32768,i.head=null,i.hold=0,i.bits=0,i.lencode=i.lendyn=new Int32Array(ENOUGH_LENS$2),i.distcode=i.distdyn=new Int32Array(ENOUGH_DISTS$2),i.sane=1,i.back=-1,Z_OK$1$1},inflateReset$1=e=>{if(inflateStateCheck$1(e))return Z_STREAM_ERROR$1$1;const i=e.state;return i.wsize=0,i.whave=0,i.wnext=0,inflateResetKeep$1(e)},inflateReset2$1=(e,i)=>{let t;if(inflateStateCheck$1(e))return Z_STREAM_ERROR$1$1;const n=e.state;return i<0?(t=0,i=-i):(t=(i>>4)+5,i<48&&(i&=15)),i&&(i<8||i>15)?Z_STREAM_ERROR$1$1:(n.window!==null&&n.wbits!==i&&(n.window=null),n.wrap=t,n.wbits=i,inflateReset$1(e))},inflateInit2$1=(e,i)=>{if(!e)return Z_STREAM_ERROR$1$1;const t=new InflateState$1;e.state=t,t.strm=e,t.window=null,t.mode=HEAD$1;const n=inflateReset2$1(e,i);return n!==Z_OK$1$1&&(e.state=null),n},inflateInit$1=e=>inflateInit2$1(e,DEF_WBITS$1);let virgin$1=!0,lenfix$1,distfix$1;const fixedtables$1=e=>{if(virgin$1){lenfix$1=new Int32Array(512),distfix$1=new Int32Array(32);let i=0;for(;i<144;)e.lens[i++]=8;for(;i<256;)e.lens[i++]=9;for(;i<280;)e.lens[i++]=7;for(;i<288;)e.lens[i++]=8;for(inftrees$2(LENS$2,e.lens,0,288,lenfix$1,0,e.work,{bits:9}),i=0;i<32;)e.lens[i++]=5;inftrees$2(DISTS$2,e.lens,0,32,distfix$1,0,e.work,{bits:5}),virgin$1=!1}e.lencode=lenfix$1,e.lenbits=9,e.distcode=distfix$1,e.distbits=5},updatewindow$1=(e,i,t,n)=>{let a;const s=e.state;return s.window===null&&(s.wsize=1<<s.wbits,s.wnext=0,s.whave=0,s.window=new Uint8Array(s.wsize)),n>=s.wsize?(s.window.set(i.subarray(t-s.wsize,t),0),s.wnext=0,s.whave=s.wsize):(a=s.wsize-s.wnext,a>n&&(a=n),s.window.set(i.subarray(t-n,t-n+a),s.wnext),n-=a,n?(s.window.set(i.subarray(t-n,t),0),s.wnext=n,s.whave=s.wsize):(s.wnext+=a,s.wnext===s.wsize&&(s.wnext=0),s.whave<s.wsize&&(s.whave+=a))),0},inflate$2$1=(e,i)=>{let t,n,a,s,o,h,f,l,u,w,_,g,v,k,A=0,T,$,D,C,P,z,B,F;const L=new Uint8Array(4);let N,G;const V=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(inflateStateCheck$1(e)||!e.output||!e.input&&e.avail_in!==0)return Z_STREAM_ERROR$1$1;t=e.state,t.mode===TYPE$2&&(t.mode=TYPEDO$1),o=e.next_out,a=e.output,f=e.avail_out,s=e.next_in,n=e.input,h=e.avail_in,l=t.hold,u=t.bits,w=h,_=f,F=Z_OK$1$1;e:for(;;)switch(t.mode){case HEAD$1:if(t.wrap===0){t.mode=TYPEDO$1;break}for(;u<16;){if(h===0)break e;h--,l+=n[s++]<<u,u+=8}if(t.wrap&2&&l===35615){t.wbits===0&&(t.wbits=15),t.check=0,L[0]=l&255,L[1]=l>>>8&255,t.check=crc32_1$2(t.check,L,2,0),l=0,u=0,t.mode=FLAGS$1;break}if(t.head&&(t.head.done=!1),!(t.wrap&1)||(((l&255)<<8)+(l>>8))%31){e.msg="incorrect header check",t.mode=BAD$2;break}if((l&15)!==Z_DEFLATED$3){e.msg="unknown compression method",t.mode=BAD$2;break}if(l>>>=4,u-=4,B=(l&15)+8,t.wbits===0&&(t.wbits=B),B>15||B>t.wbits){e.msg="invalid window size",t.mode=BAD$2;break}t.dmax=1<<t.wbits,t.flags=0,e.adler=t.check=1,t.mode=l&512?DICTID$1:TYPE$2,l=0,u=0;break;case FLAGS$1:for(;u<16;){if(h===0)break e;h--,l+=n[s++]<<u,u+=8}if(t.flags=l,(t.flags&255)!==Z_DEFLATED$3){e.msg="unknown compression method",t.mode=BAD$2;break}if(t.flags&57344){e.msg="unknown header flags set",t.mode=BAD$2;break}t.head&&(t.head.text=l>>8&1),t.flags&512&&t.wrap&4&&(L[0]=l&255,L[1]=l>>>8&255,t.check=crc32_1$2(t.check,L,2,0)),l=0,u=0,t.mode=TIME$1;case TIME$1:for(;u<32;){if(h===0)break e;h--,l+=n[s++]<<u,u+=8}t.head&&(t.head.time=l),t.flags&512&&t.wrap&4&&(L[0]=l&255,L[1]=l>>>8&255,L[2]=l>>>16&255,L[3]=l>>>24&255,t.check=crc32_1$2(t.check,L,4,0)),l=0,u=0,t.mode=OS$1;case OS$1:for(;u<16;){if(h===0)break e;h--,l+=n[s++]<<u,u+=8}t.head&&(t.head.xflags=l&255,t.head.os=l>>8),t.flags&512&&t.wrap&4&&(L[0]=l&255,L[1]=l>>>8&255,t.check=crc32_1$2(t.check,L,2,0)),l=0,u=0,t.mode=EXLEN$1;case EXLEN$1:if(t.flags&1024){for(;u<16;){if(h===0)break e;h--,l+=n[s++]<<u,u+=8}t.length=l,t.head&&(t.head.extra_len=l),t.flags&512&&t.wrap&4&&(L[0]=l&255,L[1]=l>>>8&255,t.check=crc32_1$2(t.check,L,2,0)),l=0,u=0}else t.head&&(t.head.extra=null);t.mode=EXTRA$1;case EXTRA$1:if(t.flags&1024&&(g=t.length,g>h&&(g=h),g&&(t.head&&(B=t.head.extra_len-t.length,t.head.extra||(t.head.extra=new Uint8Array(t.head.extra_len)),t.head.extra.set(n.subarray(s,s+g),B)),t.flags&512&&t.wrap&4&&(t.check=crc32_1$2(t.check,n,g,s)),h-=g,s+=g,t.length-=g),t.length))break e;t.length=0,t.mode=NAME$1;case NAME$1:if(t.flags&2048){if(h===0)break e;g=0;do B=n[s+g++],t.head&&B&&t.length<65536&&(t.head.name+=String.fromCharCode(B));while(B&&g<h);if(t.flags&512&&t.wrap&4&&(t.check=crc32_1$2(t.check,n,g,s)),h-=g,s+=g,B)break e}else t.head&&(t.head.name=null);t.length=0,t.mode=COMMENT$1;case COMMENT$1:if(t.flags&4096){if(h===0)break e;g=0;do B=n[s+g++],t.head&&B&&t.length<65536&&(t.head.comment+=String.fromCharCode(B));while(B&&g<h);if(t.flags&512&&t.wrap&4&&(t.check=crc32_1$2(t.check,n,g,s)),h-=g,s+=g,B)break e}else t.head&&(t.head.comment=null);t.mode=HCRC$1;case HCRC$1:if(t.flags&512){for(;u<16;){if(h===0)break e;h--,l+=n[s++]<<u,u+=8}if(t.wrap&4&&l!==(t.check&65535)){e.msg="header crc mismatch",t.mode=BAD$2;break}l=0,u=0}t.head&&(t.head.hcrc=t.flags>>9&1,t.head.done=!0),e.adler=t.check=0,t.mode=TYPE$2;break;case DICTID$1:for(;u<32;){if(h===0)break e;h--,l+=n[s++]<<u,u+=8}e.adler=t.check=zswap32$1(l),l=0,u=0,t.mode=DICT$1;case DICT$1:if(t.havedict===0)return e.next_out=o,e.avail_out=f,e.next_in=s,e.avail_in=h,t.hold=l,t.bits=u,Z_NEED_DICT$1$1;e.adler=t.check=1,t.mode=TYPE$2;case TYPE$2:if(i===Z_BLOCK$2||i===Z_TREES$1)break e;case TYPEDO$1:if(t.last){l>>>=u&7,u-=u&7,t.mode=CHECK$1;break}for(;u<3;){if(h===0)break e;h--,l+=n[s++]<<u,u+=8}switch(t.last=l&1,l>>>=1,u-=1,l&3){case 0:t.mode=STORED$1;break;case 1:if(fixedtables$1(t),t.mode=LEN_$1,i===Z_TREES$1){l>>>=2,u-=2;break e}break;case 2:t.mode=TABLE$1;break;case 3:e.msg="invalid block type",t.mode=BAD$2}l>>>=2,u-=2;break;case STORED$1:for(l>>>=u&7,u-=u&7;u<32;){if(h===0)break e;h--,l+=n[s++]<<u,u+=8}if((l&65535)!==(l>>>16^65535)){e.msg="invalid stored block lengths",t.mode=BAD$2;break}if(t.length=l&65535,l=0,u=0,t.mode=COPY_$1,i===Z_TREES$1)break e;case COPY_$1:t.mode=COPY$1;case COPY$1:if(g=t.length,g){if(g>h&&(g=h),g>f&&(g=f),g===0)break e;a.set(n.subarray(s,s+g),o),h-=g,s+=g,f-=g,o+=g,t.length-=g;break}t.mode=TYPE$2;break;case TABLE$1:for(;u<14;){if(h===0)break e;h--,l+=n[s++]<<u,u+=8}if(t.nlen=(l&31)+257,l>>>=5,u-=5,t.ndist=(l&31)+1,l>>>=5,u-=5,t.ncode=(l&15)+4,l>>>=4,u-=4,t.nlen>286||t.ndist>30){e.msg="too many length or distance symbols",t.mode=BAD$2;break}t.have=0,t.mode=LENLENS$1;case LENLENS$1:for(;t.have<t.ncode;){for(;u<3;){if(h===0)break e;h--,l+=n[s++]<<u,u+=8}t.lens[V[t.have++]]=l&7,l>>>=3,u-=3}for(;t.have<19;)t.lens[V[t.have++]]=0;if(t.lencode=t.lendyn,t.lenbits=7,N={bits:t.lenbits},F=inftrees$2(CODES$2,t.lens,0,19,t.lencode,0,t.work,N),t.lenbits=N.bits,F){e.msg="invalid code lengths set",t.mode=BAD$2;break}t.have=0,t.mode=CODELENS$1;case CODELENS$1:for(;t.have<t.nlen+t.ndist;){for(;A=t.lencode[l&(1<<t.lenbits)-1],T=A>>>24,$=A>>>16&255,D=A&65535,!(T<=u);){if(h===0)break e;h--,l+=n[s++]<<u,u+=8}if(D<16)l>>>=T,u-=T,t.lens[t.have++]=D;else{if(D===16){for(G=T+2;u<G;){if(h===0)break e;h--,l+=n[s++]<<u,u+=8}if(l>>>=T,u-=T,t.have===0){e.msg="invalid bit length repeat",t.mode=BAD$2;break}B=t.lens[t.have-1],g=3+(l&3),l>>>=2,u-=2}else if(D===17){for(G=T+3;u<G;){if(h===0)break e;h--,l+=n[s++]<<u,u+=8}l>>>=T,u-=T,B=0,g=3+(l&7),l>>>=3,u-=3}else{for(G=T+7;u<G;){if(h===0)break e;h--,l+=n[s++]<<u,u+=8}l>>>=T,u-=T,B=0,g=11+(l&127),l>>>=7,u-=7}if(t.have+g>t.nlen+t.ndist){e.msg="invalid bit length repeat",t.mode=BAD$2;break}for(;g--;)t.lens[t.have++]=B}}if(t.mode===BAD$2)break;if(t.lens[256]===0){e.msg="invalid code -- missing end-of-block",t.mode=BAD$2;break}if(t.lenbits=9,N={bits:t.lenbits},F=inftrees$2(LENS$2,t.lens,0,t.nlen,t.lencode,0,t.work,N),t.lenbits=N.bits,F){e.msg="invalid literal/lengths set",t.mode=BAD$2;break}if(t.distbits=6,t.distcode=t.distdyn,N={bits:t.distbits},F=inftrees$2(DISTS$2,t.lens,t.nlen,t.ndist,t.distcode,0,t.work,N),t.distbits=N.bits,F){e.msg="invalid distances set",t.mode=BAD$2;break}if(t.mode=LEN_$1,i===Z_TREES$1)break e;case LEN_$1:t.mode=LEN$1;case LEN$1:if(h>=6&&f>=258){e.next_out=o,e.avail_out=f,e.next_in=s,e.avail_in=h,t.hold=l,t.bits=u,inffast$2(e,_),o=e.next_out,a=e.output,f=e.avail_out,s=e.next_in,n=e.input,h=e.avail_in,l=t.hold,u=t.bits,t.mode===TYPE$2&&(t.back=-1);break}for(t.back=0;A=t.lencode[l&(1<<t.lenbits)-1],T=A>>>24,$=A>>>16&255,D=A&65535,!(T<=u);){if(h===0)break e;h--,l+=n[s++]<<u,u+=8}if($&&($&240)===0){for(C=T,P=$,z=D;A=t.lencode[z+((l&(1<<C+P)-1)>>C)],T=A>>>24,$=A>>>16&255,D=A&65535,!(C+T<=u);){if(h===0)break e;h--,l+=n[s++]<<u,u+=8}l>>>=C,u-=C,t.back+=C}if(l>>>=T,u-=T,t.back+=T,t.length=D,$===0){t.mode=LIT$1;break}if($&32){t.back=-1,t.mode=TYPE$2;break}if($&64){e.msg="invalid literal/length code",t.mode=BAD$2;break}t.extra=$&15,t.mode=LENEXT$1;case LENEXT$1:if(t.extra){for(G=t.extra;u<G;){if(h===0)break e;h--,l+=n[s++]<<u,u+=8}t.length+=l&(1<<t.extra)-1,l>>>=t.extra,u-=t.extra,t.back+=t.extra}t.was=t.length,t.mode=DIST$1;case DIST$1:for(;A=t.distcode[l&(1<<t.distbits)-1],T=A>>>24,$=A>>>16&255,D=A&65535,!(T<=u);){if(h===0)break e;h--,l+=n[s++]<<u,u+=8}if(($&240)===0){for(C=T,P=$,z=D;A=t.distcode[z+((l&(1<<C+P)-1)>>C)],T=A>>>24,$=A>>>16&255,D=A&65535,!(C+T<=u);){if(h===0)break e;h--,l+=n[s++]<<u,u+=8}l>>>=C,u-=C,t.back+=C}if(l>>>=T,u-=T,t.back+=T,$&64){e.msg="invalid distance code",t.mode=BAD$2;break}t.offset=D,t.extra=$&15,t.mode=DISTEXT$1;case DISTEXT$1:if(t.extra){for(G=t.extra;u<G;){if(h===0)break e;h--,l+=n[s++]<<u,u+=8}t.offset+=l&(1<<t.extra)-1,l>>>=t.extra,u-=t.extra,t.back+=t.extra}if(t.offset>t.dmax){e.msg="invalid distance too far back",t.mode=BAD$2;break}t.mode=MATCH$1;case MATCH$1:if(f===0)break e;if(g=_-f,t.offset>g){if(g=t.offset-g,g>t.whave&&t.sane){e.msg="invalid distance too far back",t.mode=BAD$2;break}g>t.wnext?(g-=t.wnext,v=t.wsize-g):v=t.wnext-g,g>t.length&&(g=t.length),k=t.window}else k=a,v=o-t.offset,g=t.length;g>f&&(g=f),f-=g,t.length-=g;do a[o++]=k[v++];while(--g);t.length===0&&(t.mode=LEN$1);break;case LIT$1:if(f===0)break e;a[o++]=t.length,f--,t.mode=LEN$1;break;case CHECK$1:if(t.wrap){for(;u<32;){if(h===0)break e;h--,l|=n[s++]<<u,u+=8}if(_-=f,e.total_out+=_,t.total+=_,t.wrap&4&&_&&(e.adler=t.check=t.flags?crc32_1$2(t.check,a,_,o-_):adler32_1$2(t.check,a,_,o-_)),_=f,t.wrap&4&&(t.flags?l:zswap32$1(l))!==t.check){e.msg="incorrect data check",t.mode=BAD$2;break}l=0,u=0}t.mode=LENGTH$1;case LENGTH$1:if(t.wrap&&t.flags){for(;u<32;){if(h===0)break e;h--,l+=n[s++]<<u,u+=8}if(t.wrap&4&&l!==(t.total&4294967295)){e.msg="incorrect length check",t.mode=BAD$2;break}l=0,u=0}t.mode=DONE$1;case DONE$1:F=Z_STREAM_END$1$1;break e;case BAD$2:F=Z_DATA_ERROR$1$1;break e;case MEM$1:return Z_MEM_ERROR$1$1;case SYNC$1:default:return Z_STREAM_ERROR$1$1}return e.next_out=o,e.avail_out=f,e.next_in=s,e.avail_in=h,t.hold=l,t.bits=u,(t.wsize||_!==e.avail_out&&t.mode<BAD$2&&(t.mode<CHECK$1||i!==Z_FINISH$1$1))&&updatewindow$1(e,e.output,e.next_out,_-e.avail_out),w-=e.avail_in,_-=e.avail_out,e.total_in+=w,e.total_out+=_,t.total+=_,t.wrap&4&&_&&(e.adler=t.check=t.flags?crc32_1$2(t.check,a,_,e.next_out-_):adler32_1$2(t.check,a,_,e.next_out-_)),e.data_type=t.bits+(t.last?64:0)+(t.mode===TYPE$2?128:0)+(t.mode===LEN_$1||t.mode===COPY_$1?256:0),(w===0&&_===0||i===Z_FINISH$1$1)&&F===Z_OK$1$1&&(F=Z_BUF_ERROR$2),F},inflateEnd$1=e=>{if(inflateStateCheck$1(e))return Z_STREAM_ERROR$1$1;let i=e.state;return i.window&&(i.window=null),e.state=null,Z_OK$1$1},inflateGetHeader$1=(e,i)=>{if(inflateStateCheck$1(e))return Z_STREAM_ERROR$1$1;const t=e.state;return(t.wrap&2)===0?Z_STREAM_ERROR$1$1:(t.head=i,i.done=!1,Z_OK$1$1)},inflateSetDictionary$1=(e,i)=>{const t=i.length;let n,a,s;return inflateStateCheck$1(e)||(n=e.state,n.wrap!==0&&n.mode!==DICT$1)?Z_STREAM_ERROR$1$1:n.mode===DICT$1&&(a=1,a=adler32_1$2(a,i,t,0),a!==n.check)?Z_DATA_ERROR$1$1:(s=updatewindow$1(e,i,t,t),s?(n.mode=MEM$1,Z_MEM_ERROR$1$1):(n.havedict=1,Z_OK$1$1))};var inflateReset_1$1=inflateReset$1,inflateReset2_1$1=inflateReset2$1,inflateResetKeep_1$1=inflateResetKeep$1,inflateInit_1$1=inflateInit$1,inflateInit2_1$1=inflateInit2$1,inflate_2$1$1=inflate$2$1,inflateEnd_1$1=inflateEnd$1,inflateGetHeader_1$1=inflateGetHeader$1,inflateSetDictionary_1$1=inflateSetDictionary$1,inflateInfo$1="pako inflate (from Nodeca project)",inflate_1$2$1={inflateReset:inflateReset_1$1,inflateReset2:inflateReset2_1$1,inflateResetKeep:inflateResetKeep_1$1,inflateInit:inflateInit_1$1,inflateInit2:inflateInit2_1$1,inflate:inflate_2$1$1,inflateEnd:inflateEnd_1$1,inflateGetHeader:inflateGetHeader_1$1,inflateSetDictionary:inflateSetDictionary_1$1,inflateInfo:inflateInfo$1};function GZheader$1(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}var gzheader$2=GZheader$1;const toString$2=Object.prototype.toString,{Z_NO_FLUSH:Z_NO_FLUSH$3,Z_FINISH:Z_FINISH$4,Z_OK:Z_OK$4,Z_STREAM_END:Z_STREAM_END$4,Z_NEED_DICT:Z_NEED_DICT$2,Z_STREAM_ERROR:Z_STREAM_ERROR$3,Z_DATA_ERROR:Z_DATA_ERROR$3,Z_MEM_ERROR:Z_MEM_ERROR$2}=constants$2$1;function Inflate$1$1(e){this.options=common$2.assign({chunkSize:1024*64,windowBits:15,to:""},e||{});const i=this.options;i.raw&&i.windowBits>=0&&i.windowBits<16&&(i.windowBits=-i.windowBits,i.windowBits===0&&(i.windowBits=-15)),i.windowBits>=0&&i.windowBits<16&&!(e&&e.windowBits)&&(i.windowBits+=32),i.windowBits>15&&i.windowBits<48&&(i.windowBits&15)===0&&(i.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new zstream$2,this.strm.avail_out=0;let t=inflate_1$2$1.inflateInit2(this.strm,i.windowBits);if(t!==Z_OK$4)throw new Error(messages$2[t]);if(this.header=new gzheader$2,inflate_1$2$1.inflateGetHeader(this.strm,this.header),i.dictionary&&(typeof i.dictionary=="string"?i.dictionary=strings$2.string2buf(i.dictionary):toString$2.call(i.dictionary)==="[object ArrayBuffer]"&&(i.dictionary=new Uint8Array(i.dictionary)),i.raw&&(t=inflate_1$2$1.inflateSetDictionary(this.strm,i.dictionary),t!==Z_OK$4)))throw new Error(messages$2[t])}Inflate$1$1.prototype.push=function(e,i){const t=this.strm,n=this.options.chunkSize,a=this.options.dictionary;let s,o,h;if(this.ended)return!1;for(i===~~i?o=i:o=i===!0?Z_FINISH$4:Z_NO_FLUSH$3,toString$2.call(e)==="[object ArrayBuffer]"?t.input=new Uint8Array(e):t.input=e,t.next_in=0,t.avail_in=t.input.length;;){for(t.avail_out===0&&(t.output=new Uint8Array(n),t.next_out=0,t.avail_out=n),s=inflate_1$2$1.inflate(t,o),s===Z_NEED_DICT$2&&a&&(s=inflate_1$2$1.inflateSetDictionary(t,a),s===Z_OK$4?s=inflate_1$2$1.inflate(t,o):s===Z_DATA_ERROR$3&&(s=Z_NEED_DICT$2));t.avail_in>0&&s===Z_STREAM_END$4&&t.state.wrap>0&&e[t.next_in]!==0;)inflate_1$2$1.inflateReset(t),s=inflate_1$2$1.inflate(t,o);switch(s){case Z_STREAM_ERROR$3:case Z_DATA_ERROR$3:case Z_NEED_DICT$2:case Z_MEM_ERROR$2:return this.onEnd(s),this.ended=!0,!1}if(h=t.avail_out,t.next_out&&(t.avail_out===0||s===Z_STREAM_END$4))if(this.options.to==="string"){let f=strings$2.utf8border(t.output,t.next_out),l=t.next_out-f,u=strings$2.buf2string(t.output,f);t.next_out=l,t.avail_out=n-l,l&&t.output.set(t.output.subarray(f,f+l),0),this.onData(u)}else this.onData(t.output.length===t.next_out?t.output:t.output.subarray(0,t.next_out));if(!(s===Z_OK$4&&h===0)){if(s===Z_STREAM_END$4)return s=inflate_1$2$1.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,!0;if(t.avail_in===0)break}}return!0},Inflate$1$1.prototype.onData=function(e){this.chunks.push(e)},Inflate$1$1.prototype.onEnd=function(e){e===Z_OK$4&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=common$2.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};function inflate$1$2(e,i){const t=new Inflate$1$1(i);if(t.push(e),t.err)throw t.msg||messages$2[t.err];return t.result}var Inflate_1$1=Inflate$1$1,inflate_2$2=inflate$1$2,inflate_1$1$1={Inflate:Inflate_1$1,inflate:inflate_2$2};const{deflate:deflate$3}=deflate_1$1,{Inflate,inflate:inflate$4}=inflate_1$1$1;var deflate_1=deflate$3,Inflate_1=Inflate,inflate_1$3=inflate$4;const crcTable$1=[];for(let e=0;e<256;e++){let i=e;for(let t=0;t<8;t++)i&1?i=3988292384^i>>>1:i=i>>>1;crcTable$1[e]=i}const initialCrc=4294967295;function updateCrc(e,i,t){let n=e;for(let a=0;a<t;a++)n=crcTable$1[(n^i[a])&255]^n>>>8;return n}function crc(e,i){return(updateCrc(initialCrc,e,i)^initialCrc)>>>0}function checkCrc(e,i,t){const n=e.readUint32(),a=crc(new Uint8Array(e.buffer,e.byteOffset+e.offset-i-4,i),i);if(a!==n)throw new Error(`CRC mismatch for chunk ${t}. Expected ${n}, found ${a}`)}function writeCrc(e,i){e.writeUint32(crc(new Uint8Array(e.buffer,e.byteOffset+e.offset-i,i),i))}function unfilterNone(e,i,t){for(let n=0;n<t;n++)i[n]=e[n]}function unfilterSub(e,i,t,n){let a=0;for(;a<n;a++)i[a]=e[a];for(;a<t;a++)i[a]=e[a]+i[a-n]&255}function unfilterUp(e,i,t,n){let a=0;if(t.length===0)for(;a<n;a++)i[a]=e[a];else for(;a<n;a++)i[a]=e[a]+t[a]&255}function unfilterAverage(e,i,t,n,a){let s=0;if(t.length===0){for(;s<a;s++)i[s]=e[s];for(;s<n;s++)i[s]=e[s]+(i[s-a]>>1)&255}else{for(;s<a;s++)i[s]=e[s]+(t[s]>>1)&255;for(;s<n;s++)i[s]=e[s]+(i[s-a]+t[s]>>1)&255}}function unfilterPaeth(e,i,t,n,a){let s=0;if(t.length===0){for(;s<a;s++)i[s]=e[s];for(;s<n;s++)i[s]=e[s]+i[s-a]&255}else{for(;s<a;s++)i[s]=e[s]+t[s]&255;for(;s<n;s++)i[s]=e[s]+paethPredictor(i[s-a],t[s],t[s-a])&255}}function paethPredictor(e,i,t){const n=e+i-t,a=Math.abs(n-e),s=Math.abs(n-i),o=Math.abs(n-t);return a<=s&&a<=o?e:s<=o?i:t}const uint16=new Uint16Array([255]),uint8=new Uint8Array(uint16.buffer),osIsLittleEndian=uint8[0]===255,empty=new Uint8Array(0);function decodeInterlaceNull(e){const{data:i,width:t,height:n,channels:a,depth:s}=e,o=a*s/8,h=t*o,f=new Uint8Array(n*h);let l=empty,u=0,w,_;for(let g=0;g<n;g++){switch(w=i.subarray(u+1,u+1+h),_=f.subarray(g*h,(g+1)*h),i[u]){case 0:unfilterNone(w,_,h);break;case 1:unfilterSub(w,_,h,o);break;case 2:unfilterUp(w,_,l,h);break;case 3:unfilterAverage(w,_,l,h,o);break;case 4:unfilterPaeth(w,_,l,h,o);break;default:throw new Error(`Unsupported filter: ${i[u]}`)}l=_,u+=h+1}if(s===16){const g=new Uint16Array(f.buffer);if(osIsLittleEndian)for(let v=0;v<g.length;v++)g[v]=swap16(g[v]);return g}else return f}function swap16(e){return(e&255)<<8|e>>8&255}const pngSignature=Uint8Array.of(137,80,78,71,13,10,26,10);function writeSignature(e){e.writeBytes(pngSignature)}function checkSignature(e){if(!hasPngSignature(e.readBytes(pngSignature.length)))throw new Error("wrong PNG signature")}function hasPngSignature(e){if(e.length<pngSignature.length)return!1;for(let i=0;i<pngSignature.length;i++)if(e[i]!==pngSignature[i])return!1;return!0}const textChunkName="tEXt",NULL=0,latin1Decoder=new TextDecoder("latin1");function validateKeyword(e){if(validateLatin1(e),e.length===0||e.length>79)throw new Error("keyword length must be between 1 and 79")}const latin1Regex=/^[\u0000-\u00FF]*$/;function validateLatin1(e){if(!latin1Regex.test(e))throw new Error("invalid latin1 text")}function decodetEXt(e,i,t){const n=readKeyword(i);e[n]=readLatin1(i,t-n.length-1)}function encodetEXt(e,i,t){validateKeyword(i),validateLatin1(t);const n=i.length+1+t.length;e.writeUint32(n),e.writeChars(textChunkName),e.writeChars(i),e.writeByte(NULL),e.writeChars(t),writeCrc(e,n+4)}function readKeyword(e){for(e.mark();e.readByte()!==NULL;);const i=e.offset;e.reset();const t=latin1Decoder.decode(e.readBytes(i-e.offset-1));return e.skip(1),validateKeyword(t),t}function readLatin1(e,i){return latin1Decoder.decode(e.readBytes(i))}const ColorType={UNKNOWN:-1,GREYSCALE:0,TRUECOLOUR:2,INDEXED_COLOUR:3,GREYSCALE_ALPHA:4,TRUECOLOUR_ALPHA:6},CompressionMethod={UNKNOWN:-1,DEFLATE:0},FilterMethod={UNKNOWN:-1,ADAPTIVE:0},InterlaceMethod={UNKNOWN:-1,NO_INTERLACE:0};class PngDecoder extends IOBuffer{constructor(t,n={}){super(t);we(this,"_checkCrc");we(this,"_inflator");we(this,"_png");we(this,"_end");we(this,"_hasPalette");we(this,"_palette");we(this,"_hasTransparency");we(this,"_transparency");we(this,"_compressionMethod");we(this,"_filterMethod");we(this,"_interlaceMethod");we(this,"_colorType");const{checkCrc:a=!1}=n;this._checkCrc=a,this._inflator=new Inflate_1,this._png={width:-1,height:-1,channels:-1,data:new Uint8Array(0),depth:1,text:{}},this._end=!1,this._hasPalette=!1,this._palette=[],this._hasTransparency=!1,this._transparency=new Uint16Array(0),this._compressionMethod=CompressionMethod.UNKNOWN,this._filterMethod=FilterMethod.UNKNOWN,this._interlaceMethod=InterlaceMethod.UNKNOWN,this._colorType=ColorType.UNKNOWN,this.setBigEndian()}decode(){for(checkSignature(this);!this._end;)this.decodeChunk();return this.decodeImage(),this._png}decodeChunk(){const t=this.readUint32(),n=this.readChars(4),a=this.offset;switch(n){case"IHDR":this.decodeIHDR();break;case"PLTE":this.decodePLTE(t);break;case"IDAT":this.decodeIDAT(t);break;case"IEND":this._end=!0;break;case"tRNS":this.decodetRNS(t);break;case"iCCP":this.decodeiCCP(t);break;case textChunkName:decodetEXt(this._png.text,this,t);break;case"pHYs":this.decodepHYs();break;default:this.skip(t);break}if(this.offset-a!==t)throw new Error(`Length mismatch while decoding chunk ${n}`);this._checkCrc?checkCrc(this,t+4,n):this.skip(4)}decodeIHDR(){const t=this._png;t.width=this.readUint32(),t.height=this.readUint32(),t.depth=checkBitDepth(this.readUint8());const n=this.readUint8();this._colorType=n;let a;switch(n){case ColorType.GREYSCALE:a=1;break;case ColorType.TRUECOLOUR:a=3;break;case ColorType.INDEXED_COLOUR:a=1;break;case ColorType.GREYSCALE_ALPHA:a=2;break;case ColorType.TRUECOLOUR_ALPHA:a=4;break;case ColorType.UNKNOWN:default:throw new Error(`Unknown color type: ${n}`)}if(this._png.channels=a,this._compressionMethod=this.readUint8(),this._compressionMethod!==CompressionMethod.DEFLATE)throw new Error(`Unsupported compression method: ${this._compressionMethod}`);this._filterMethod=this.readUint8(),this._interlaceMethod=this.readUint8()}decodePLTE(t){if(t%3!==0)throw new RangeError(`PLTE field length must be a multiple of 3. Got ${t}`);const n=t/3;this._hasPalette=!0;const a=[];this._palette=a;for(let s=0;s<n;s++)a.push([this.readUint8(),this.readUint8(),this.readUint8()])}decodeIDAT(t){this._inflator.push(new Uint8Array(this.buffer,this.offset+this.byteOffset,t)),this.skip(t)}decodetRNS(t){switch(this._colorType){case ColorType.GREYSCALE:case ColorType.TRUECOLOUR:{if(t%2!==0)throw new RangeError(`tRNS chunk length must be a multiple of 2. Got ${t}`);if(t/2>this._png.width*this._png.height)throw new Error(`tRNS chunk contains more alpha values than there are pixels (${t/2} vs ${this._png.width*this._png.height})`);this._hasTransparency=!0,this._transparency=new Uint16Array(t/2);for(let n=0;n<t/2;n++)this._transparency[n]=this.readUint16();break}case ColorType.INDEXED_COLOUR:{if(t>this._palette.length)throw new Error(`tRNS chunk contains more alpha values than there are palette colors (${t} vs ${this._palette.length})`);let n=0;for(;n<t;n++){const a=this.readByte();this._palette[n].push(a)}for(;n<this._palette.length;n++)this._palette[n].push(255);break}case ColorType.UNKNOWN:case ColorType.GREYSCALE_ALPHA:case ColorType.TRUECOLOUR_ALPHA:default:throw new Error(`tRNS chunk is not supported for color type ${this._colorType}`)}}decodeiCCP(t){const n=readKeyword(this),a=this.readUint8();if(a!==CompressionMethod.DEFLATE)throw new Error(`Unsupported iCCP compression method: ${a}`);const s=this.readBytes(t-n.length-2);this._png.iccEmbeddedProfile={name:n,profile:inflate_1$3(s)}}decodepHYs(){const t=this.readUint32(),n=this.readUint32(),a=this.readByte();this._png.resolution={x:t,y:n,unit:a}}decodeImage(){if(this._inflator.err)throw new Error(`Error while decompressing the data: ${this._inflator.err}`);const t=this._inflator.result;if(this._filterMethod!==FilterMethod.ADAPTIVE)throw new Error(`Filter method ${this._filterMethod} not supported`);if(this._interlaceMethod===InterlaceMethod.NO_INTERLACE)this._png.data=decodeInterlaceNull({data:t,width:this._png.width,height:this._png.height,channels:this._png.channels,depth:this._png.depth});else throw new Error(`Interlace method ${this._interlaceMethod} not supported`);this._hasPalette&&(this._png.palette=this._palette),this._hasTransparency&&(this._png.transparency=this._transparency)}}function checkBitDepth(e){if(e!==1&&e!==2&&e!==4&&e!==8&&e!==16)throw new Error(`invalid bit depth: ${e}`);return e}const defaultZlibOptions={level:3};class PngEncoder extends IOBuffer{constructor(t,n={}){super();we(this,"_png");we(this,"_zlibOptions");we(this,"_colorType");this._colorType=ColorType.UNKNOWN,this._zlibOptions={...defaultZlibOptions,...n.zlib},this._png=this._checkData(t),this.setBigEndian()}encode(){if(writeSignature(this),this.encodeIHDR(),this.encodeData(),this._png.text)for(const[t,n]of Object.entries(this._png.text))encodetEXt(this,t,n);return this.encodeIEND(),this.toArray()}encodeIHDR(){this.writeUint32(13),this.writeChars("IHDR"),this.writeUint32(this._png.width),this.writeUint32(this._png.height),this.writeByte(this._png.depth),this.writeByte(this._colorType),this.writeByte(CompressionMethod.DEFLATE),this.writeByte(FilterMethod.ADAPTIVE),this.writeByte(InterlaceMethod.NO_INTERLACE),writeCrc(this,17)}encodeIEND(){this.writeUint32(0),this.writeChars("IEND"),writeCrc(this,4)}encodeIDAT(t){this.writeUint32(t.length),this.writeChars("IDAT"),this.writeBytes(t),writeCrc(this,t.length+4)}encodeData(){const{width:t,height:n,channels:a,depth:s,data:o}=this._png,h=a*t,f=new IOBuffer().setBigEndian();let l=0;for(let _=0;_<n;_++)if(f.writeByte(0),s===8)l=writeDataBytes(o,f,h,l);else if(s===16)l=writeDataUint16(o,f,h,l);else throw new Error("unreachable");const u=f.toArray(),w=deflate_1(u,this._zlibOptions);this.encodeIDAT(w)}_checkData(t){const{colorType:n,channels:a,depth:s}=getColorType(t),o={width:checkInteger(t.width,"width"),height:checkInteger(t.height,"height"),channels:a,data:t.data,depth:s,text:t.text};this._colorType=n;const h=o.width*o.height*a;if(o.data.length!==h)throw new RangeError(`wrong data size. Found ${o.data.length}, expected ${h}`);return o}}function checkInteger(e,i){if(Number.isInteger(e)&&e>0)return e;throw new TypeError(`${i} must be a positive integer`)}function getColorType(e){const{channels:i=4,depth:t=8}=e;if(i!==4&&i!==3&&i!==2&&i!==1)throw new RangeError(`unsupported number of channels: ${i}`);if(t!==8&&t!==16)throw new RangeError(`unsupported bit depth: ${t}`);const n={channels:i,depth:t,colorType:ColorType.UNKNOWN};switch(i){case 4:n.colorType=ColorType.TRUECOLOUR_ALPHA;break;case 3:n.colorType=ColorType.TRUECOLOUR;break;case 1:n.colorType=ColorType.GREYSCALE;break;case 2:n.colorType=ColorType.GREYSCALE_ALPHA;break;default:throw new Error("unsupported number of channels")}return n}function writeDataBytes(e,i,t,n){for(let a=0;a<t;a++)i.writeByte(e[n++]);return n}function writeDataUint16(e,i,t,n){for(let a=0;a<t;a++)i.writeUint16(e[n++]);return n}var ResolutionUnitSpecifier;(function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.METRE=1]="METRE"})(ResolutionUnitSpecifier||(ResolutionUnitSpecifier={}));function decodePng(e,i){return new PngDecoder(e,i).decode()}function encodePng$1(e,i){return new PngEncoder(e,i).encode()}var encoder={exports:{}},hasRequiredEncoder;function requireEncoder(){return hasRequiredEncoder||(hasRequiredEncoder=1,function(e){function i(n){var a=Math.floor,s=new Array(64),o=new Array(64),h=new Array(64),f=new Array(64),l,u,w,_,g=new Array(65535),v=new Array(65535),k=new Array(64),A=new Array(64),T=[],$=0,D=7,C=new Array(64),P=new Array(64),z=new Array(64),B=new Array(256),F=new Array(2048),L,N=[0,1,5,6,14,15,27,28,2,4,7,13,16,26,29,42,3,8,12,17,25,30,41,43,9,11,18,24,31,40,44,53,10,19,23,32,39,45,52,54,20,22,33,38,46,51,55,60,21,34,37,47,50,56,59,61,35,36,48,49,57,58,62,63],G=[0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0],V=[0,1,2,3,4,5,6,7,8,9,10,11],J=[0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,125],Q=[1,2,3,0,4,17,5,18,33,49,65,6,19,81,97,7,34,113,20,50,129,145,161,8,35,66,177,193,21,82,209,240,36,51,98,114,130,9,10,22,23,24,25,26,37,38,39,40,41,42,52,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,225,226,227,228,229,230,231,232,233,234,241,242,243,244,245,246,247,248,249,250],W=[0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0],ne=[0,1,2,3,4,5,6,7,8,9,10,11],me=[0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,119],ve=[0,1,2,3,17,4,5,33,49,6,18,65,81,7,97,113,19,34,50,129,8,20,66,145,161,177,193,9,35,51,82,240,21,98,114,209,10,22,36,52,225,37,241,23,24,25,26,38,39,40,41,42,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,130,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,226,227,228,229,230,231,232,233,234,242,243,244,245,246,247,248,249,250];function ye(he){for(var Qe=[16,11,10,16,24,40,51,61,12,12,14,19,26,58,60,55,14,13,16,24,40,57,69,56,14,17,22,29,51,87,80,62,18,22,37,56,68,109,103,77,24,35,55,64,81,104,113,92,49,64,78,87,103,121,120,101,72,92,95,98,112,100,103,99],Ze=0;Ze<64;Ze++){var He=a((Qe[Ze]*he+50)/100);He<1?He=1:He>255&&(He=255),s[N[Ze]]=He}for(var Te=[17,18,24,47,99,99,99,99,18,21,26,66,99,99,99,99,24,26,56,99,99,99,99,99,47,66,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99],lt=0;lt<64;lt++){var ot=a((Te[lt]*he+50)/100);ot<1?ot=1:ot>255&&(ot=255),o[N[lt]]=ot}for(var Le=[1,1.387039845,1.306562965,1.175875602,1,.785694958,.5411961,.275899379],ze=0,je=0;je<8;je++)for(var Oe=0;Oe<8;Oe++)h[ze]=1/(s[N[ze]]*Le[je]*Le[Oe]*8),f[ze]=1/(o[N[ze]]*Le[je]*Le[Oe]*8),ze++}function Me(he,Qe){for(var Ze=0,He=0,Te=new Array,lt=1;lt<=16;lt++){for(var ot=1;ot<=he[lt];ot++)Te[Qe[He]]=[],Te[Qe[He]][0]=Ze,Te[Qe[He]][1]=lt,He++,Ze++;Ze*=2}return Te}function Re(){l=Me(G,V),u=Me(W,ne),w=Me(J,Q),_=Me(me,ve)}function _e(){for(var he=1,Qe=2,Ze=1;Ze<=15;Ze++){for(var He=he;He<Qe;He++)v[32767+He]=Ze,g[32767+He]=[],g[32767+He][1]=Ze,g[32767+He][0]=He;for(var Te=-(Qe-1);Te<=-he;Te++)v[32767+Te]=Ze,g[32767+Te]=[],g[32767+Te][1]=Ze,g[32767+Te][0]=Qe-1+Te;he<<=1,Qe<<=1}}function Be(){for(var he=0;he<256;he++)F[he]=19595*he,F[he+256>>0]=38470*he,F[he+512>>0]=7471*he+32768,F[he+768>>0]=-11059*he,F[he+1024>>0]=-21709*he,F[he+1280>>0]=32768*he+8421375,F[he+1536>>0]=-27439*he,F[he+1792>>0]=-5329*he}function Se(he){for(var Qe=he[0],Ze=he[1]-1;Ze>=0;)Qe&1<<Ze&&($|=1<<D),Ze--,D--,D<0&&($==255?(re(255),re(0)):re($),D=7,$=0)}function re(he){T.push(he)}function Ie(he){re(he>>8&255),re(he&255)}function Fe(he,Qe){var Ze,He,Te,lt,ot,Le,ze,je,Oe=0,st,Z=8,ue=64;for(st=0;st<Z;++st){Ze=he[Oe],He=he[Oe+1],Te=he[Oe+2],lt=he[Oe+3],ot=he[Oe+4],Le=he[Oe+5],ze=he[Oe+6],je=he[Oe+7];var xe=Ze+je,Ae=Ze-je,te=He+ze,pe=He-ze,U=Te+Le,Ee=Te-Le,it=lt+ot,I=lt-ot,fe=xe+it,de=xe-it,H=te+U,ee=te-U;he[Oe]=fe+H,he[Oe+4]=fe-H;var oe=(ee+de)*.707106781;he[Oe+2]=de+oe,he[Oe+6]=de-oe,fe=I+Ee,H=Ee+pe,ee=pe+Ae;var We=(fe-ee)*.382683433,M=.5411961*fe+We,m=1.306562965*ee+We,d=H*.707106781,c=Ae+d,b=Ae-d;he[Oe+5]=b+M,he[Oe+3]=b-M,he[Oe+1]=c+m,he[Oe+7]=c-m,Oe+=8}for(Oe=0,st=0;st<Z;++st){Ze=he[Oe],He=he[Oe+8],Te=he[Oe+16],lt=he[Oe+24],ot=he[Oe+32],Le=he[Oe+40],ze=he[Oe+48],je=he[Oe+56];var S=Ze+je,O=Ze-je,q=He+ze,X=He-ze,j=Te+Le,ae=Te-Le,K=lt+ot,ce=lt-ot,be=S+K,le=S-K,ge=q+j,Ue=q-j;he[Oe]=be+ge,he[Oe+32]=be-ge;var ie=(Ue+le)*.707106781;he[Oe+16]=le+ie,he[Oe+48]=le-ie,be=ce+ae,ge=ae+X,Ue=X+O;var $e=(be-Ue)*.382683433,Xe=.5411961*be+$e,ht=1.306562965*Ue+$e,ft=ge*.707106781,gt=O+ft,rt=O-ft;he[Oe+40]=rt+Xe,he[Oe+24]=rt-Xe,he[Oe+8]=gt+ht,he[Oe+56]=gt-ht,Oe++}var at;for(st=0;st<ue;++st)at=he[st]*Qe[st],k[st]=at>0?at+.5|0:at-.5|0;return k}function ke(){Ie(65504),Ie(16),re(74),re(70),re(73),re(70),re(0),re(1),re(1),re(0),Ie(1),Ie(1),re(0),re(0)}function Ye(he){if(he){Ie(65505),he[0]===69&&he[1]===120&&he[2]===105&&he[3]===102?Ie(he.length+2):(Ie(he.length+5+2),re(69),re(120),re(105),re(102),re(0));for(var Qe=0;Qe<he.length;Qe++)re(he[Qe])}}function Je(he,Qe){Ie(65472),Ie(17),re(8),Ie(Qe),Ie(he),re(3),re(1),re(17),re(0),re(2),re(17),re(1),re(3),re(17),re(1)}function et(){Ie(65499),Ie(132),re(0);for(var he=0;he<64;he++)re(s[he]);re(1);for(var Qe=0;Qe<64;Qe++)re(o[Qe])}function Ve(){Ie(65476),Ie(418),re(0);for(var he=0;he<16;he++)re(G[he+1]);for(var Qe=0;Qe<=11;Qe++)re(V[Qe]);re(16);for(var Ze=0;Ze<16;Ze++)re(J[Ze+1]);for(var He=0;He<=161;He++)re(Q[He]);re(1);for(var Te=0;Te<16;Te++)re(W[Te+1]);for(var lt=0;lt<=11;lt++)re(ne[lt]);re(17);for(var ot=0;ot<16;ot++)re(me[ot+1]);for(var Le=0;Le<=161;Le++)re(ve[Le])}function tt(he){typeof he>"u"||he.constructor!==Array||he.forEach(Qe=>{if(typeof Qe=="string"){Ie(65534);var Ze=Qe.length;Ie(Ze+2);var He;for(He=0;He<Ze;He++)re(Qe.charCodeAt(He))}})}function qe(){Ie(65498),Ie(12),re(3),re(1),re(0),re(2),re(17),re(3),re(17),re(0),re(63),re(0)}function De(he,Qe,Ze,He,Te){for(var lt=Te[0],ot=Te[240],Le,ze=16,je=63,Oe=64,st=Fe(he,Qe),Z=0;Z<Oe;++Z)A[N[Z]]=st[Z];var ue=A[0]-Ze;Ze=A[0],ue==0?Se(He[0]):(Le=32767+ue,Se(He[v[Le]]),Se(g[Le]));for(var xe=63;xe>0&&A[xe]==0;xe--);if(xe==0)return Se(lt),Ze;for(var Ae=1,te;Ae<=xe;){for(var pe=Ae;A[Ae]==0&&Ae<=xe;++Ae);var U=Ae-pe;if(U>=ze){te=U>>4;for(var Ee=1;Ee<=te;++Ee)Se(ot);U=U&15}Le=32767+A[Ae],Se(Te[(U<<4)+v[Le]]),Se(g[Le]),Ae++}return xe!=je&&Se(lt),Ze}function nt(){for(var he=String.fromCharCode,Qe=0;Qe<256;Qe++)B[Qe]=he(Qe)}this.encode=function(he,Qe){new Date().getTime(),Qe&&Ge(Qe),T=new Array,$=0,D=7,Ie(65496),ke(),tt(he.comments),Ye(he.exifBuffer),et(),Je(he.width,he.height),Ve(),qe();var Ze=0,He=0,Te=0;$=0,D=7,this.encode.displayName="_encode_";for(var lt=he.data,ot=he.width,Le=he.height,ze=ot*4,je,Oe=0,st,Z,ue,xe,Ae,te,pe,U;Oe<Le;){for(je=0;je<ze;){for(xe=ze*Oe+je,Ae=xe,te=-1,pe=0,U=0;U<64;U++)pe=U>>3,te=(U&7)*4,Ae=xe+pe*ze+te,Oe+pe>=Le&&(Ae-=ze*(Oe+1+pe-Le)),je+te>=ze&&(Ae-=je+te-ze+4),st=lt[Ae++],Z=lt[Ae++],ue=lt[Ae++],C[U]=(F[st]+F[Z+256>>0]+F[ue+512>>0]>>16)-128,P[U]=(F[st+768>>0]+F[Z+1024>>0]+F[ue+1280>>0]>>16)-128,z[U]=(F[st+1280>>0]+F[Z+1536>>0]+F[ue+1792>>0]>>16)-128;Ze=De(C,h,Ze,l,w),He=De(P,f,He,u,_),Te=De(z,f,Te,u,_),je+=32}Oe+=8}if(D>=0){var Ee=[];Ee[1]=D+1,Ee[0]=(1<<D+1)-1,Se(Ee)}return Ie(65497),Buffer.from(T)};function Ge(he){if(he<=0&&(he=1),he>100&&(he=100),L!=he){var Qe=0;he<50?Qe=Math.floor(5e3/he):Qe=Math.floor(200-he*2),ye(Qe),L=he}}function Ne(){var he=new Date().getTime();n||(n=50),nt(),Re(),_e(),Be(),Ge(n),new Date().getTime()-he}Ne()}e.exports=t;function t(n,a){typeof a>"u"&&(a=50);var s=new i(a),o=s.encode(n,a);return{data:o,width:n.width,height:n.height}}}(encoder)),encoder.exports}var decoder={exports:{}},hasRequiredDecoder;function requireDecoder(){return hasRequiredDecoder||(hasRequiredDecoder=1,function(e){var i=function(){var a=new Int32Array([0,1,8,16,9,2,3,10,17,24,32,25,18,11,4,5,12,19,26,33,40,48,41,34,27,20,13,6,7,14,21,28,35,42,49,56,57,50,43,36,29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54,47,55,62,63]),s=4017,o=799,h=3406,f=2276,l=1567,u=3784,w=5793,_=2896;function g(){}function v(P,z){for(var B=0,F=[],L,N,G=16;G>0&&!P[G-1];)G--;F.push({children:[],index:0});var V=F[0],J;for(L=0;L<G;L++){for(N=0;N<P[L];N++){for(V=F.pop(),V.children[V.index]=z[B];V.index>0;){if(F.length===0)throw new Error("Could not recreate Huffman Table");V=F.pop()}for(V.index++,F.push(V);F.length<=L;)F.push(J={children:[],index:0}),V.children[V.index]=J.children,V=J;B++}L+1<G&&(F.push(J={children:[],index:0}),V.children[V.index]=J.children,V=J)}return F[0].children}function k(P,z,B,F,L,N,G,V,J,Q){B.precision,B.samplesPerLine,B.scanLines;var W=B.mcusPerLine,ne=B.progressive;B.maxH,B.maxV;var me=z,ve=0,ye=0;function Me(){if(ye>0)return ye--,ve>>ye&1;if(ve=P[z++],ve==255){var Le=P[z++];if(Le)throw new Error("unexpected marker: "+(ve<<8|Le).toString(16))}return ye=7,ve>>>7}function Re(Le){for(var ze=Le,je;(je=Me())!==null;){if(ze=ze[je],typeof ze=="number")return ze;if(typeof ze!="object")throw new Error("invalid huffman sequence")}return null}function _e(Le){for(var ze=0;Le>0;){var je=Me();if(je===null)return;ze=ze<<1|je,Le--}return ze}function Be(Le){var ze=_e(Le);return ze>=1<<Le-1?ze:ze+(-1<<Le)+1}function Se(Le,ze){var je=Re(Le.huffmanTableDC),Oe=je===0?0:Be(je);ze[0]=Le.pred+=Oe;for(var st=1;st<64;){var Z=Re(Le.huffmanTableAC),ue=Z&15,xe=Z>>4;if(ue===0){if(xe<15)break;st+=16;continue}st+=xe;var Ae=a[st];ze[Ae]=Be(ue),st++}}function re(Le,ze){var je=Re(Le.huffmanTableDC),Oe=je===0?0:Be(je)<<J;ze[0]=Le.pred+=Oe}function Ie(Le,ze){ze[0]|=Me()<<J}var Fe=0;function ke(Le,ze){if(Fe>0){Fe--;return}for(var je=N,Oe=G;je<=Oe;){var st=Re(Le.huffmanTableAC),Z=st&15,ue=st>>4;if(Z===0){if(ue<15){Fe=_e(ue)+(1<<ue)-1;break}je+=16;continue}je+=ue;var xe=a[je];ze[xe]=Be(Z)*(1<<J),je++}}var Ye=0,Je;function et(Le,ze){for(var je=N,Oe=G,st=0;je<=Oe;){var Z=a[je],ue=ze[Z]<0?-1:1;switch(Ye){case 0:var xe=Re(Le.huffmanTableAC),Ae=xe&15,st=xe>>4;if(Ae===0)st<15?(Fe=_e(st)+(1<<st),Ye=4):(st=16,Ye=1);else{if(Ae!==1)throw new Error("invalid ACn encoding");Je=Be(Ae),Ye=st?2:3}continue;case 1:case 2:ze[Z]?ze[Z]+=(Me()<<J)*ue:(st--,st===0&&(Ye=Ye==2?3:0));break;case 3:ze[Z]?ze[Z]+=(Me()<<J)*ue:(ze[Z]=Je<<J,Ye=0);break;case 4:ze[Z]&&(ze[Z]+=(Me()<<J)*ue);break}je++}Ye===4&&(Fe--,Fe===0&&(Ye=0))}function Ve(Le,ze,je,Oe,st){var Z=je/W|0,ue=je%W,xe=Z*Le.v+Oe,Ae=ue*Le.h+st;Le.blocks[xe]===void 0&&Q.tolerantDecoding||ze(Le,Le.blocks[xe][Ae])}function tt(Le,ze,je){var Oe=je/Le.blocksPerLine|0,st=je%Le.blocksPerLine;Le.blocks[Oe]===void 0&&Q.tolerantDecoding||ze(Le,Le.blocks[Oe][st])}var qe=F.length,De,nt,Ge,Ne,he,Qe;ne?N===0?Qe=V===0?re:Ie:Qe=V===0?ke:et:Qe=Se;var Ze=0,He,Te;qe==1?Te=F[0].blocksPerLine*F[0].blocksPerColumn:Te=W*B.mcusPerColumn,L||(L=Te);for(var lt,ot;Ze<Te;){for(nt=0;nt<qe;nt++)F[nt].pred=0;if(Fe=0,qe==1)for(De=F[0],he=0;he<L;he++)tt(De,Qe,Ze),Ze++;else for(he=0;he<L;he++){for(nt=0;nt<qe;nt++)for(De=F[nt],lt=De.h,ot=De.v,Ge=0;Ge<ot;Ge++)for(Ne=0;Ne<lt;Ne++)Ve(De,Qe,Ze,Ge,Ne);if(Ze++,Ze===Te)break}if(Ze===Te)do{if(P[z]===255&&P[z+1]!==0)break;z+=1}while(z<P.length-2);if(ye=0,He=P[z]<<8|P[z+1],He<65280)throw new Error("marker was not found");if(He>=65488&&He<=65495)z+=2;else break}return z-me}function A(P,z){var B=[],F=z.blocksPerLine,L=z.blocksPerColumn,N=F<<3,G=new Int32Array(64),V=new Uint8Array(64);function J(_e,Be,Se){var re=z.quantizationTable,Ie,Fe,ke,Ye,Je,et,Ve,tt,qe,De=Se,nt;for(nt=0;nt<64;nt++)De[nt]=_e[nt]*re[nt];for(nt=0;nt<8;++nt){var Ge=8*nt;if(De[1+Ge]==0&&De[2+Ge]==0&&De[3+Ge]==0&&De[4+Ge]==0&&De[5+Ge]==0&&De[6+Ge]==0&&De[7+Ge]==0){qe=w*De[0+Ge]+512>>10,De[0+Ge]=qe,De[1+Ge]=qe,De[2+Ge]=qe,De[3+Ge]=qe,De[4+Ge]=qe,De[5+Ge]=qe,De[6+Ge]=qe,De[7+Ge]=qe;continue}Ie=w*De[0+Ge]+128>>8,Fe=w*De[4+Ge]+128>>8,ke=De[2+Ge],Ye=De[6+Ge],Je=_*(De[1+Ge]-De[7+Ge])+128>>8,tt=_*(De[1+Ge]+De[7+Ge])+128>>8,et=De[3+Ge]<<4,Ve=De[5+Ge]<<4,qe=Ie-Fe+1>>1,Ie=Ie+Fe+1>>1,Fe=qe,qe=ke*u+Ye*l+128>>8,ke=ke*l-Ye*u+128>>8,Ye=qe,qe=Je-Ve+1>>1,Je=Je+Ve+1>>1,Ve=qe,qe=tt+et+1>>1,et=tt-et+1>>1,tt=qe,qe=Ie-Ye+1>>1,Ie=Ie+Ye+1>>1,Ye=qe,qe=Fe-ke+1>>1,Fe=Fe+ke+1>>1,ke=qe,qe=Je*f+tt*h+2048>>12,Je=Je*h-tt*f+2048>>12,tt=qe,qe=et*o+Ve*s+2048>>12,et=et*s-Ve*o+2048>>12,Ve=qe,De[0+Ge]=Ie+tt,De[7+Ge]=Ie-tt,De[1+Ge]=Fe+Ve,De[6+Ge]=Fe-Ve,De[2+Ge]=ke+et,De[5+Ge]=ke-et,De[3+Ge]=Ye+Je,De[4+Ge]=Ye-Je}for(nt=0;nt<8;++nt){var Ne=nt;if(De[8+Ne]==0&&De[16+Ne]==0&&De[24+Ne]==0&&De[32+Ne]==0&&De[40+Ne]==0&&De[48+Ne]==0&&De[56+Ne]==0){qe=w*Se[nt+0]+8192>>14,De[0+Ne]=qe,De[8+Ne]=qe,De[16+Ne]=qe,De[24+Ne]=qe,De[32+Ne]=qe,De[40+Ne]=qe,De[48+Ne]=qe,De[56+Ne]=qe;continue}Ie=w*De[0+Ne]+2048>>12,Fe=w*De[32+Ne]+2048>>12,ke=De[16+Ne],Ye=De[48+Ne],Je=_*(De[8+Ne]-De[56+Ne])+2048>>12,tt=_*(De[8+Ne]+De[56+Ne])+2048>>12,et=De[24+Ne],Ve=De[40+Ne],qe=Ie-Fe+1>>1,Ie=Ie+Fe+1>>1,Fe=qe,qe=ke*u+Ye*l+2048>>12,ke=ke*l-Ye*u+2048>>12,Ye=qe,qe=Je-Ve+1>>1,Je=Je+Ve+1>>1,Ve=qe,qe=tt+et+1>>1,et=tt-et+1>>1,tt=qe,qe=Ie-Ye+1>>1,Ie=Ie+Ye+1>>1,Ye=qe,qe=Fe-ke+1>>1,Fe=Fe+ke+1>>1,ke=qe,qe=Je*f+tt*h+2048>>12,Je=Je*h-tt*f+2048>>12,tt=qe,qe=et*o+Ve*s+2048>>12,et=et*s-Ve*o+2048>>12,Ve=qe,De[0+Ne]=Ie+tt,De[56+Ne]=Ie-tt,De[8+Ne]=Fe+Ve,De[48+Ne]=Fe-Ve,De[16+Ne]=ke+et,De[40+Ne]=ke-et,De[24+Ne]=Ye+Je,De[32+Ne]=Ye-Je}for(nt=0;nt<64;++nt){var he=128+(De[nt]+8>>4);Be[nt]=he<0?0:he>255?255:he}}C(N*L*8);for(var Q,W,ne=0;ne<L;ne++){var me=ne<<3;for(Q=0;Q<8;Q++)B.push(new Uint8Array(N));for(var ve=0;ve<F;ve++){J(z.blocks[ne][ve],V,G);var ye=0,Me=ve<<3;for(W=0;W<8;W++){var Re=B[me+W];for(Q=0;Q<8;Q++)Re[Me+Q]=V[ye++]}}}return B}function T(P){return P<0?0:P>255?255:P}g.prototype={load:function(z){var B=new XMLHttpRequest;B.open("GET",z,!0),B.responseType="arraybuffer",B.onload=(function(){var F=new Uint8Array(B.response||B.mozResponseArrayBuffer);this.parse(F),this.onload&&this.onload()}).bind(this),B.send(null)},parse:function(z){var B=this.opts.maxResolutionInMP*1e3*1e3,F=0;z.length;function L(){var ue=z[F]<<8|z[F+1];return F+=2,ue}function N(){var ue=L(),xe=z.subarray(F,F+ue-2);return F+=xe.length,xe}function G(ue){var xe=1,Ae=1,te,pe;for(pe in ue.components)ue.components.hasOwnProperty(pe)&&(te=ue.components[pe],xe<te.h&&(xe=te.h),Ae<te.v&&(Ae=te.v));var U=Math.ceil(ue.samplesPerLine/8/xe),Ee=Math.ceil(ue.scanLines/8/Ae);for(pe in ue.components)if(ue.components.hasOwnProperty(pe)){te=ue.components[pe];var it=Math.ceil(Math.ceil(ue.samplesPerLine/8)*te.h/xe),I=Math.ceil(Math.ceil(ue.scanLines/8)*te.v/Ae),fe=U*te.h,de=Ee*te.v,H=de*fe,ee=[];C(H*256);for(var oe=0;oe<de;oe++){for(var We=[],M=0;M<fe;M++)We.push(new Int32Array(64));ee.push(We)}te.blocksPerLine=it,te.blocksPerColumn=I,te.blocks=ee}ue.maxH=xe,ue.maxV=Ae,ue.mcusPerLine=U,ue.mcusPerColumn=Ee}var V=null,J=null,Q,W,ne=[],me=[],ve=[],ye=[],Me=L(),Re=-1;if(this.comments=[],Me!=65496)throw new Error("SOI not found");for(Me=L();Me!=65497;){var _e,Be;switch(Me){case 65280:break;case 65504:case 65505:case 65506:case 65507:case 65508:case 65509:case 65510:case 65511:case 65512:case 65513:case 65514:case 65515:case 65516:case 65517:case 65518:case 65519:case 65534:var Se=N();if(Me===65534){var re=String.fromCharCode.apply(null,Se);this.comments.push(re)}Me===65504&&Se[0]===74&&Se[1]===70&&Se[2]===73&&Se[3]===70&&Se[4]===0&&(V={version:{major:Se[5],minor:Se[6]},densityUnits:Se[7],xDensity:Se[8]<<8|Se[9],yDensity:Se[10]<<8|Se[11],thumbWidth:Se[12],thumbHeight:Se[13],thumbData:Se.subarray(14,14+3*Se[12]*Se[13])}),Me===65505&&Se[0]===69&&Se[1]===120&&Se[2]===105&&Se[3]===102&&Se[4]===0&&(this.exifBuffer=Se.subarray(5,Se.length)),Me===65518&&Se[0]===65&&Se[1]===100&&Se[2]===111&&Se[3]===98&&Se[4]===101&&Se[5]===0&&(J={version:Se[6],flags0:Se[7]<<8|Se[8],flags1:Se[9]<<8|Se[10],transformCode:Se[11]});break;case 65499:for(var Ie=L(),Fe=Ie+F-2;F<Fe;){var ke=z[F++];C(256);var Ye=new Int32Array(64);if(ke>>4===0)for(Be=0;Be<64;Be++){var Je=a[Be];Ye[Je]=z[F++]}else if(ke>>4===1)for(Be=0;Be<64;Be++){var Je=a[Be];Ye[Je]=L()}else throw new Error("DQT: invalid table spec");ne[ke&15]=Ye}break;case 65472:case 65473:case 65474:L(),Q={},Q.extended=Me===65473,Q.progressive=Me===65474,Q.precision=z[F++],Q.scanLines=L(),Q.samplesPerLine=L(),Q.components={},Q.componentsOrder=[];var et=Q.scanLines*Q.samplesPerLine;if(et>B){var Ve=Math.ceil((et-B)/1e6);throw new Error(`maxResolutionInMP limit exceeded by ${Ve}MP`)}var tt=z[F++],qe;for(_e=0;_e<tt;_e++){qe=z[F];var De=z[F+1]>>4,nt=z[F+1]&15,Ge=z[F+2];if(De<=0||nt<=0)throw new Error("Invalid sampling factor, expected values above 0");Q.componentsOrder.push(qe),Q.components[qe]={h:De,v:nt,quantizationIdx:Ge},F+=3}G(Q),me.push(Q);break;case 65476:var Ne=L();for(_e=2;_e<Ne;){var he=z[F++],Qe=new Uint8Array(16),Ze=0;for(Be=0;Be<16;Be++,F++)Ze+=Qe[Be]=z[F];C(16+Ze);var He=new Uint8Array(Ze);for(Be=0;Be<Ze;Be++,F++)He[Be]=z[F];_e+=17+Ze,(he>>4===0?ye:ve)[he&15]=v(Qe,He)}break;case 65501:L(),W=L();break;case 65500:L(),L();break;case 65498:L();var Te=z[F++],lt=[],ot;for(_e=0;_e<Te;_e++){ot=Q.components[z[F++]];var Le=z[F++];ot.huffmanTableDC=ye[Le>>4],ot.huffmanTableAC=ve[Le&15],lt.push(ot)}var ze=z[F++],je=z[F++],Oe=z[F++],st=k(z,F,Q,lt,W,ze,je,Oe>>4,Oe&15,this.opts);F+=st;break;case 65535:z[F]!==255&&F--;break;default:if(z[F-3]==255&&z[F-2]>=192&&z[F-2]<=254){F-=3;break}else if(Me===224||Me==225){if(Re!==-1)throw new Error(`first unknown JPEG marker at offset ${Re.toString(16)}, second unknown JPEG marker ${Me.toString(16)} at offset ${(F-1).toString(16)}`);Re=F-1;const ue=L();if(z[F+ue-2]===255){F+=ue-2;break}}throw new Error("unknown JPEG marker "+Me.toString(16))}Me=L()}if(me.length!=1)throw new Error("only single frame JPEGs supported");for(var _e=0;_e<me.length;_e++){var Z=me[_e].components;for(var Be in Z)Z[Be].quantizationTable=ne[Z[Be].quantizationIdx],delete Z[Be].quantizationIdx}this.width=Q.samplesPerLine,this.height=Q.scanLines,this.jfif=V,this.adobe=J,this.components=[];for(var _e=0;_e<Q.componentsOrder.length;_e++){var ot=Q.components[Q.componentsOrder[_e]];this.components.push({lines:A(Q,ot),scaleX:ot.h/Q.maxH,scaleY:ot.v/Q.maxV})}},getData:function(z,B){var F=this.width/z,L=this.height/B,N,G,V,J,Q,W,ne,me,ve,ye,Me=0,Re,_e,Be,Se,re,Ie,Fe,ke,Ye,Je,et,Ve=z*B*this.components.length;C(Ve);var tt=new Uint8Array(Ve);switch(this.components.length){case 1:for(N=this.components[0],ye=0;ye<B;ye++)for(Q=N.lines[0|ye*N.scaleY*L],ve=0;ve<z;ve++)Re=Q[0|ve*N.scaleX*F],tt[Me++]=Re;break;case 2:for(N=this.components[0],G=this.components[1],ye=0;ye<B;ye++)for(Q=N.lines[0|ye*N.scaleY*L],W=G.lines[0|ye*G.scaleY*L],ve=0;ve<z;ve++)Re=Q[0|ve*N.scaleX*F],tt[Me++]=Re,Re=W[0|ve*G.scaleX*F],tt[Me++]=Re;break;case 3:for(et=!0,this.adobe&&this.adobe.transformCode?et=!0:typeof this.opts.colorTransform<"u"&&(et=!!this.opts.colorTransform),N=this.components[0],G=this.components[1],V=this.components[2],ye=0;ye<B;ye++)for(Q=N.lines[0|ye*N.scaleY*L],W=G.lines[0|ye*G.scaleY*L],ne=V.lines[0|ye*V.scaleY*L],ve=0;ve<z;ve++)et?(Re=Q[0|ve*N.scaleX*F],_e=W[0|ve*G.scaleX*F],Be=ne[0|ve*V.scaleX*F],ke=T(Re+1.402*(Be-128)),Ye=T(Re-.3441363*(_e-128)-.71413636*(Be-128)),Je=T(Re+1.772*(_e-128))):(ke=Q[0|ve*N.scaleX*F],Ye=W[0|ve*G.scaleX*F],Je=ne[0|ve*V.scaleX*F]),tt[Me++]=ke,tt[Me++]=Ye,tt[Me++]=Je;break;case 4:if(!this.adobe)throw new Error("Unsupported color mode (4 components)");for(et=!1,this.adobe&&this.adobe.transformCode?et=!0:typeof this.opts.colorTransform<"u"&&(et=!!this.opts.colorTransform),N=this.components[0],G=this.components[1],V=this.components[2],J=this.components[3],ye=0;ye<B;ye++)for(Q=N.lines[0|ye*N.scaleY*L],W=G.lines[0|ye*G.scaleY*L],ne=V.lines[0|ye*V.scaleY*L],me=J.lines[0|ye*J.scaleY*L],ve=0;ve<z;ve++)et?(Re=Q[0|ve*N.scaleX*F],_e=W[0|ve*G.scaleX*F],Be=ne[0|ve*V.scaleX*F],Se=me[0|ve*J.scaleX*F],re=255-T(Re+1.402*(Be-128)),Ie=255-T(Re-.3441363*(_e-128)-.71413636*(Be-128)),Fe=255-T(Re+1.772*(_e-128))):(re=Q[0|ve*N.scaleX*F],Ie=W[0|ve*G.scaleX*F],Fe=ne[0|ve*V.scaleX*F],Se=me[0|ve*J.scaleX*F]),tt[Me++]=255-re,tt[Me++]=255-Ie,tt[Me++]=255-Fe,tt[Me++]=255-Se;break;default:throw new Error("Unsupported color mode")}return tt},copyToImageData:function(z,B){var F=z.width,L=z.height,N=z.data,G=this.getData(F,L),V=0,J=0,Q,W,ne,me,ve,ye,Me,Re,_e;switch(this.components.length){case 1:for(W=0;W<L;W++)for(Q=0;Q<F;Q++)ne=G[V++],N[J++]=ne,N[J++]=ne,N[J++]=ne,B&&(N[J++]=255);break;case 3:for(W=0;W<L;W++)for(Q=0;Q<F;Q++)Me=G[V++],Re=G[V++],_e=G[V++],N[J++]=Me,N[J++]=Re,N[J++]=_e,B&&(N[J++]=255);break;case 4:for(W=0;W<L;W++)for(Q=0;Q<F;Q++)ve=G[V++],ye=G[V++],ne=G[V++],me=G[V++],Me=255-T(ve*(1-me/255)+me),Re=255-T(ye*(1-me/255)+me),_e=255-T(ne*(1-me/255)+me),N[J++]=Me,N[J++]=Re,N[J++]=_e,B&&(N[J++]=255);break;default:throw new Error("Unsupported color mode")}}};var $=0,D=0;function C(P=0){var z=$+P;if(z>D){var B=Math.ceil((z-D)/1024/1024);throw new Error(`maxMemoryUsageInMB limit exceeded by at least ${B}MB`)}$=z}return g.resetMaxMemoryUsage=function(P){$=0,D=P},g.getBytesAllocated=function(){return $},g.requestMemoryAllocation=C,g}();e.exports=t;function t(n,a={}){var s={colorTransform:void 0,useTArray:!1,formatAsRGBA:!0,tolerantDecoding:!0,maxResolutionInMP:100,maxMemoryUsageInMB:512},o={...s,...a},h=new Uint8Array(n),f=new i;f.opts=o,i.resetMaxMemoryUsage(o.maxMemoryUsageInMB*1024*1024),f.parse(h);var l=o.formatAsRGBA?4:3,u=f.width*f.height*l;try{i.requestMemoryAllocation(u);var w={width:f.width,height:f.height,exifBuffer:f.exifBuffer,data:o.useTArray?new Uint8Array(u):Buffer.alloc(u)};f.comments.length>0&&(w.comments=f.comments)}catch(_){throw _ instanceof RangeError?new Error("Could not allocate enough memory for the image. Required: "+u):_ instanceof ReferenceError&&_.message==="Buffer is not defined"?new Error("Buffer is not globally defined in this environment. Consider setting useTArray to true"):_}return f.copyToImageData(w,o.formatAsRGBA),w}}(decoder)),decoder.exports}var jpegJs,hasRequiredJpegJs;function requireJpegJs(){if(hasRequiredJpegJs)return jpegJs;hasRequiredJpegJs=1;var e=requireEncoder(),i=requireDecoder();return jpegJs={encode:e,decode:i},jpegJs}var jpegJsExports=requireJpegJs();const jpeg=getDefaultExportFromCjs(jpegJsExports);let chars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",lookup=new Uint8Array(256);for(let e=0;e<chars.length;e++)lookup[chars.charCodeAt(e)]=e;function encode(e){let i,t=e.length,n="";for(i=0;i<t;i+=3)n+=chars[e[i]>>2],n+=chars[(e[i]&3)<<4|e[i+1]>>4],n+=chars[(e[i+1]&15)<<2|e[i+2]>>6],n+=chars[e[i+2]&63];return t%3===2?n=`${n.substring(0,n.length-1)}=`:t%3===1&&(n=`${n.substring(0,n.length-2)}==`),n}function decode$1(e){let i=e.length*.75,t=e.length,n=0,a,s,o,h;e[e.length-1]==="="&&(i--,e[e.length-2]==="="&&i--);const f=new Uint8Array(i);for(let l=0;l<t;l+=4)a=lookup[e.charCodeAt(l)],s=lookup[e.charCodeAt(l+1)],o=lookup[e.charCodeAt(l+2)],h=lookup[e.charCodeAt(l+3)],f[n++]=a<<2|s>>4,f[n++]=(s&15)<<4|o>>2,f[n++]=(o&3)<<6|h&63;return f}function toBase64URL(e,i){const t=encode(e);return`data:${i};base64,${t}`}const ImageData$1=self.ImageData,DOMImage=self.Image;function createCanvas(e,i){let t=self.document.createElement("canvas");return t.width=e,t.height=i,t}function fetchBinary(e,{withCredentials:i=!1}={}){return new Promise(function(t,n){let a=new self.XMLHttpRequest;a.open("GET",e,!0),a.responseType="arraybuffer",a.withCredentials=i,a.onload=function(s){this.status!==200?n(s):t(this.response)},a.onerror=n,a.send()})}function createWriteStream(){throw new Error("createWriteStream does not exist in the browser")}function writeFile(){throw new Error("writeFile does not exist in the browser")}function getType(e){return e.includes("/")||(e=`image/${e}`),e}function encodeJpeg(e,i={}){const t={width:e.width,height:e.height,data:e.getRGBAData()};return jpegJsExports.encode(t,i.quality).data}function encodePng(e,i){const t={width:e.width,height:e.height,channels:e.channels,depth:e.bitDepth,data:e.data};return(t.depth===1||t.depth===32)&&(t.depth=8,t.channels=4,t.data=e.getRGBAData()),encodePng$1(t,i)}const exportMethods={save(e,i={}){const{useCanvas:t=!1,encoder:n=void 0}=i;let{format:a}=i;if(!a){const s=/\.(?<format>[a-zA-Z]+)$/.exec(e);s&&(a=s.groups.format.toLowerCase())}if(!a)throw new Error("file format not provided");return new Promise((s,o)=>{let h,f;switch(a.toLowerCase()){case"png":{t?h=this.getCanvas().pngStream():f=encodePng(this,n);break}case"jpg":case"jpeg":t?h=this.getCanvas().jpegStream():f=encodeJpeg(this,n);break;case"bmp":f=srcExports$3.encode(this,n);break;default:throw new RangeError(`invalid output format: ${a}`)}if(h){let l=createWriteStream();l.on("finish",s),l.on("error",o),h.pipe(l)}else f&&writeFile()})},toDataURL(e="image/png",i={}){typeof e=="object"&&(i=e,e="image/png");const{useCanvas:t=!1,encoder:n=void 0}=i;e=getType(e);function a(s,o){const h=s(o,n);return toBase64URL(h,e)}return e==="image/bmp"?a(srcExports$3.encode,this):e==="image/png"&&!t?a(encodePng,this):e==="image/jpeg"&&!t?a(encodeJpeg,this):this.getCanvas().toDataURL(e)},toBuffer(e={}){const{format:i="png",encoder:t=void 0}=e;switch(i.toLowerCase()){case"png":return encodePng(this,t);case"jpeg":case"jpg":return encodeJpeg(this,t);case"bmp":return srcExports$3.encode(this,t);default:throw new RangeError(`invalid output format: ${i}`)}},toBase64(e="image/png",i={}){if(i.async)return this.toDataURL(e,i).then(function(t){return t.substring(t.indexOf(",")+1)});{const t=this.toDataURL(e,i);return t.substring(t.indexOf(",")+1)}},toBlob(e="image/png",i=.8){return canvasToBlob(this.getCanvas(),e,i)},getCanvas(){const e=new ImageData$1(this.getRGBAData({clamped:!0}),this.width,this.height);let i=createCanvas(this.width,this.height);return i.getContext("2d").putImageData(e,0,0),i}};function setExportMethods(e){for(const i in exportMethods)e.prototype[i]=exportMethods[i]}var hasOwn$1={exports:{}};const version="1.0.1",require$$0$2={version};var hasRequiredHasOwn;function requireHasOwn(){return hasRequiredHasOwn||(hasRequiredHasOwn=1,function(e,i){var t=Object.prototype.hasOwnProperty;e.exports=i=function(a,s){return t.call(s,a)},i.version=require$$0$2.version}(hasOwn$1,hasOwn$1.exports)),hasOwn$1.exports}var hasOwnExports=requireHasOwn();const hasOwn=getDefaultExportFromCjs(hasOwnExports);let computedPropertyDescriptor$1={configurable:!0,enumerable:!1,get:void 0};function extendMethod(e,i,t={}){let{inPlace:n=!1,returnThis:a=!0,partialArgs:s=[]}=t;return n?Image.prototype[e]=function(...o){this.computed=null;let h=i.apply(this,[...s,...o]);return a?this:h}:Image.prototype[e]=function(...o){return i.apply(this,[...s,...o])},Image}function extendProperty(e,i,t={}){let{partialArgs:n=[]}=t;return computedPropertyDescriptor$1.get=function(){if(this.computed===null)this.computed={};else if(hasOwn(e,this.computed))return this.computed[e];let a=i.apply(this,n);return this.computed[e]=a,a},Object.defineProperty(Image.prototype,e,computedPropertyDescriptor$1),Image}const GREY$1="GREY",RGB$1="RGB",HSL="HSL",HSV="HSV",CMYK$1="CMYK",ColorModel=Object.freeze(Object.defineProperty({__proto__:null,CMYK:CMYK$1,GREY:GREY$1,HSL,HSV,RGB:RGB$1},Symbol.toStringTag,{value:"Module"}));function getRGBAData(e={}){const{clamped:i}=e;this.checkProcessable("getRGBAData",{components:[1,3],bitDepth:[1,8,16,32]});const t=this.width*this.height*4;let n=i?new Uint8ClampedArray(t):new Uint8Array(t);return this.bitDepth===1?fillDataFromBinary(this,n):this.bitDepth===32?(this.checkProcessable("getRGBAData",{alpha:0}),this.components===1?fillDataFromGrey32(this,n):this.components===3&&(this.checkProcessable("getRGBAData",{colorModel:[RGB$1]}),fillDataFromRGB32(this,n))):this.components===1?fillDataFromGrey(this,n):this.components===3&&(this.checkProcessable("getRGBAData",{colorModel:[RGB$1]}),fillDataFromRGB(this,n)),this.alpha===1?(this.checkProcessable("getRGBAData",{bitDepth:[8,16]}),copyAlpha(this,n)):fillAlpha(this,n),n}function fillDataFromBinary(e,i){for(let t=0;t<e.size;t++){const n=e.getBit(t);i[t*4]=n*255,i[t*4+1]=n*255,i[t*4+2]=n*255}}function fillDataFromGrey32(e,i){const t=e.min[0],a=e.max[0]-t;for(let s=0;s<e.size;s++){const o=Math.floor(255*(e.data[s]-t)/a);i[s*4]=o,i[s*4+1]=o,i[s*4+2]=o}}function fillDataFromRGB32(e,i){const t=Math.min(...e.min),a=Math.max(...e.max)-t;for(let s=0;s<e.size;s++){const o=Math.floor(255*(e.data[s*3]-t)/a),h=Math.floor(255*(e.data[s*3+1]-t)/a),f=Math.floor(255*(e.data[s*3+2]-t)/a);i[s*4]=o,i[s*4+1]=h,i[s*4+2]=f}}function fillDataFromGrey(e,i){for(let t=0;t<e.size;t++)i[t*4]=e.data[t*e.channels]>>>e.bitDepth-8,i[t*4+1]=e.data[t*e.channels]>>>e.bitDepth-8,i[t*4+2]=e.data[t*e.channels]>>>e.bitDepth-8}function fillDataFromRGB(e,i){for(let t=0;t<e.size;t++)i[t*4]=e.data[t*e.channels]>>>e.bitDepth-8,i[t*4+1]=e.data[t*e.channels+1]>>>e.bitDepth-8,i[t*4+2]=e.data[t*e.channels+2]>>>e.bitDepth-8}function copyAlpha(e,i){for(let t=0;t<e.size;t++)i[t*4+3]=e.data[t*e.channels+e.components]>>e.bitDepth-8}function fillAlpha(e,i){for(let t=0;t<e.size;t++)i[t*4+3]=255}const BINARY="BINARY",GREY="GREY",GREYA="GREYA",RGB="RGB",RGBA="RGBA",CMYK="CMYK",CMYKA="CMYKA",kinds={};kinds[BINARY]={components:1,alpha:0,bitDepth:1,colorModel:GREY$1},kinds[GREYA]={components:1,alpha:1,bitDepth:8,colorModel:GREY$1},kinds[GREY]={components:1,alpha:0,bitDepth:8,colorModel:GREY$1},kinds[RGBA]={components:3,alpha:1,bitDepth:8,colorModel:RGB$1},kinds[RGB]={components:3,alpha:0,bitDepth:8,colorModel:RGB$1},kinds[CMYK]={components:4,alpha:0,bitDepth:8,colorModel:CMYK$1},kinds[CMYKA]={components:4,alpha:1,bitDepth:8,colorModel:CMYK$1};function getKind(e){const i=kinds[e];if(!i)throw new RangeError(`invalid image kind: ${e}`);return i}const validBitDepth=[1,8,16,32];function verifyKindDefinition(e){const{components:i,alpha:t,bitDepth:n,colorModel:a}=e;if(!Number.isInteger(i)||i<=0)throw new RangeError(`invalid components: ${i}. Must be a positive integer`);if(t!==0&&t!==1&&typeof t!="boolean")throw new TypeError(`invalid alpha: ${t}: must be a boolean, 0 or 1`);if(!validBitDepth.includes(n))throw new RangeError(`invalid bitDepth: ${n}. Must be one of ${validBitDepth.join(", ")}`);if(!ColorModel[a])throw new RangeError(`invalid colorModel: ${a}. Must be one of ${Object.keys(ColorModel).join(", ")}`)}function getTheoreticalPixelArraySize(e,i,t){let n=i*e;return t===1&&(n=Math.ceil(n/8)),n}function createPixelArray(e,i,t,n,a,s){const o=n*e;let h;switch(a){case 1:h=new Uint8Array(Math.ceil(o/8));break;case 8:h=new Uint8Array(o);break;case 16:h=new Uint16Array(o);break;case 32:h=new Float32Array(o);break;default:throw new Error(`Cannot create pixel array for bit depth ${a}`)}if(t)for(let f=i;f<h.length;f+=n)h[f]=s;return h}var src$4={},IOBuffer_1,hasRequiredIOBuffer;function requireIOBuffer(){if(hasRequiredIOBuffer)return IOBuffer_1;hasRequiredIOBuffer=1;const e=1024*8,i=[];class t{constructor(a,s){s=s||{},a===void 0&&(a=e),typeof a=="number"&&(a=new ArrayBuffer(a));let o=a.byteLength;const h=s.offset?s.offset>>>0:0;a.buffer&&(o=a.byteLength-h,a.byteLength!==a.buffer.byteLength?a=a.buffer.slice(a.byteOffset+h,a.byteOffset+a.byteLength):h?a=a.buffer.slice(h):a=a.buffer),this.buffer=a,this.length=o,this.byteLength=o,this.byteOffset=0,this.offset=0,this.littleEndian=!0,this._data=new DataView(this.buffer),this._increment=o||e,this._mark=0}available(a){return a===void 0&&(a=1),this.offset+a<=this.length}isLittleEndian(){return this.littleEndian}setLittleEndian(){this.littleEndian=!0}isBigEndian(){return!this.littleEndian}setBigEndian(){this.littleEndian=!1}skip(a){a===void 0&&(a=1),this.offset+=a}seek(a){this.offset=a}mark(){this._mark=this.offset}reset(){this.offset=this._mark}rewind(){this.offset=0}ensureAvailable(a){if(a===void 0&&(a=1),!this.available(a)){const s=this._increment+this._increment;this._increment=s;const o=this.length+s,h=new Uint8Array(o);h.set(new Uint8Array(this.buffer)),this.buffer=h.buffer,this.length=o,this._data=new DataView(this.buffer)}}readBoolean(){return this.readUint8()!==0}readInt8(){return this._data.getInt8(this.offset++)}readUint8(){return this._data.getUint8(this.offset++)}readByte(){return this.readUint8()}readBytes(a){a===void 0&&(a=1);for(var s=new Uint8Array(a),o=0;o<a;o++)s[o]=this.readByte();return s}readInt16(){var a=this._data.getInt16(this.offset,this.littleEndian);return this.offset+=2,a}readUint16(){var a=this._data.getUint16(this.offset,this.littleEndian);return this.offset+=2,a}readInt32(){var a=this._data.getInt32(this.offset,this.littleEndian);return this.offset+=4,a}readUint32(){var a=this._data.getUint32(this.offset,this.littleEndian);return this.offset+=4,a}readFloat32(){var a=this._data.getFloat32(this.offset,this.littleEndian);return this.offset+=4,a}readFloat64(){var a=this._data.getFloat64(this.offset,this.littleEndian);return this.offset+=8,a}readChar(){return String.fromCharCode(this.readInt8())}readChars(a){a===void 0&&(a=1),i.length=a;for(var s=0;s<a;s++)i[s]=this.readChar();return i.join("")}writeBoolean(a){this.writeUint8(a?255:0)}writeInt8(a){this.ensureAvailable(1),this._data.setInt8(this.offset++,a)}writeUint8(a){this.ensureAvailable(1),this._data.setUint8(this.offset++,a)}writeByte(a){this.writeUint8(a)}writeBytes(a){this.ensureAvailable(a.length);for(var s=0;s<a.length;s++)this._data.setUint8(this.offset++,a[s])}writeInt16(a){this.ensureAvailable(2),this._data.setInt16(this.offset,a,this.littleEndian),this.offset+=2}writeUint16(a){this.ensureAvailable(2),this._data.setUint16(this.offset,a,this.littleEndian),this.offset+=2}writeInt32(a){this.ensureAvailable(4),this._data.setInt32(this.offset,a,this.littleEndian),this.offset+=4}writeUint32(a){this.ensureAvailable(4),this._data.setUint32(this.offset,a,this.littleEndian),this.offset+=4}writeFloat32(a){this.ensureAvailable(4),this._data.setFloat32(this.offset,a,this.littleEndian),this.offset+=4}writeFloat64(a){this.ensureAvailable(8),this._data.setFloat64(this.offset,a,this.littleEndian),this.offset+=8}writeChar(a){this.writeUint8(a.charCodeAt(0))}writeChars(a){for(var s=0;s<a.length;s++)this.writeUint8(a.charCodeAt(s))}toArray(){return new Uint8Array(this.buffer,0,this.offset)}}return IOBuffer_1=t,IOBuffer_1}var src$3={},standard$1,hasRequiredStandard;function requireStandard(){if(hasRequiredStandard)return standard$1;hasRequiredStandard=1;const e={254:"NewSubfileType",255:"SubfileType",256:"ImageWidth",257:"ImageLength",258:"BitsPerSample",259:"Compression",262:"PhotometricInterpretation",263:"Threshholding",264:"CellWidth",265:"CellLength",266:"FillOrder",270:"ImageDescription",271:"Make",272:"Model",273:"StripOffsets",274:"Orientation",277:"SamplesPerPixel",278:"RowsPerStrip",279:"StripByteCounts",280:"MinSampleValue",281:"MaxSampleValue",282:"XResolution",283:"YResolution",284:"PlanarConfiguration",288:"FreeOffsets",289:"FreeByteCounts",290:"GrayResponseUnit",291:"GrayResponseCurve",296:"ResolutionUnit",305:"Software",306:"DateTime",315:"Artist",316:"HostComputer",320:"ColorMap",338:"ExtraSamples",33432:"Copyright",269:"DocumentName",285:"PageName",286:"XPosition",287:"YPosition",292:"T4Options",293:"T6Options",297:"PageNumber",301:"TransferFunction",317:"Predictor",318:"WhitePoint",319:"PrimaryChromaticities",321:"HalftoneHints",322:"TileWidth",323:"TileLength",324:"TileOffsets",325:"TileByteCounts",326:"BadFaxLines",327:"CleanFaxData",328:"ConsecutiveBadFaxLines",330:"SubIFDs",332:"InkSet",333:"InkNames",334:"NumberOfInks",336:"DotRange",337:"TargetPrinter",339:"SampleFormat",340:"SMinSampleValue",341:"SMaxSampleValue",342:"TransferRange",343:"ClipPath",344:"XClipPathUnits",345:"YClipPathUnits",346:"Indexed",347:"JPEGTables",351:"OPIProxy",400:"GlobalParametersIFD",401:"ProfileType",402:"FaxProfile",403:"CodingMethods",404:"VersionYear",405:"ModeNumber",433:"Decode",434:"DefaultImageColor",512:"JPEGProc",513:"JPEGInterchangeFormat",514:"JPEGInterchangeFormatLength",515:"JPEGRestartInterval",517:"JPEGLosslessPredictors",518:"JPEGPointTransforms",519:"JPEGQTables",520:"JPEGDCTables",521:"JPEGACTables",529:"YCbCrCoefficients",530:"YCbCrSubSampling",531:"YCbCrPositioning",532:"ReferenceBlackWhite",559:"StripRowCounts",700:"XMP",32781:"ImageID",34732:"ImageLayer",32932:"WangAnnotatio",33445:"MDFileTag",33446:"MDScalePixel",33447:"MDColorTable",33448:"MDLabName",33449:"MDSampleInfo",33450:"MDPrepDate",33451:"MDPrepTime",33452:"MDFileUnits",33550:"ModelPixelScaleTag",33723:"IPTC",33918:"INGRPacketDataTag",33919:"INGRFlagRegisters",33920:"IrasBTransformationMatrix",33922:"ModelTiepointTag",34264:"ModelTransformationTag",34377:"Photoshop",34665:"ExifIFD",34675:"ICCProfile",34735:"GeoKeyDirectoryTag",34736:"GeoDoubleParamsTag",34737:"GeoAsciiParamsTag",34853:"GPSIFD",34908:"HylaFAXFaxRecvParams",34909:"HylaFAXFaxSubAddress",34910:"HylaFAXFaxRecvTime",37724:"ImageSourceData",40965:"InteroperabilityIFD",42112:"GDAL_METADATA",42113:"GDAL_NODATA",50215:"OceScanjobDescription",50216:"OceApplicationSelector",50217:"OceIdentificationNumber",50218:"OceImageLogicCharacteristics",50706:"DNGVersion",50707:"DNGBackwardVersion",50708:"UniqueCameraModel",50709:"LocalizedCameraModel",50710:"CFAPlaneColor",50711:"CFALayout",50712:"LinearizationTable",50713:"BlackLevelRepeatDim",50714:"BlackLevel",50715:"BlackLevelDeltaH",50716:"BlackLevelDeltaV",50717:"WhiteLevel",50718:"DefaultScale",50719:"DefaultCropOrigin",50720:"DefaultCropSize",50721:"ColorMatrix1",50722:"ColorMatrix2",50723:"CameraCalibration1",50724:"CameraCalibration2",50725:"ReductionMatrix1",50726:"ReductionMatrix2",50727:"AnalogBalance",50728:"AsShotNeutral",50729:"AsShotWhiteXY",50730:"BaselineExposure",50731:"BaselineNoise",50732:"BaselineSharpness",50733:"BayerGreenSplit",50734:"LinearResponseLimit",50735:"CameraSerialNumber",50736:"LensInfo",50737:"ChromaBlurRadius",50738:"AntiAliasStrength",50740:"DNGPrivateData",50741:"MakerNoteSafety",50778:"CalibrationIlluminant1",50779:"CalibrationIlluminant2",50780:"BestQualityScale",50784:"AliasLayerMetadata"},i={};for(var t in e)i[e[t]]=t;return standard$1={tagsById:e,tagsByName:i},standard$1}var exif$1,hasRequiredExif;function requireExif(){if(hasRequiredExif)return exif$1;hasRequiredExif=1;const e={33434:"ExposureTime",33437:"FNumber",34850:"ExposureProgram",34852:"SpectralSensitivity",34855:"ISOSpeedRatings",34856:"OECF",34864:"SensitivityType",34865:"StandardOutputSensitivity",34866:"RecommendedExposureIndex",34867:"ISOSpeed",34868:"ISOSpeedLatitudeyyy",34869:"ISOSpeedLatitudezzz",36864:"ExifVersion",36867:"DateTimeOriginal",36868:"DateTimeDigitized",37121:"ComponentsConfiguration",37122:"CompressedBitsPerPixel",37377:"ShutterSpeedValue",37378:"ApertureValue",37379:"BrightnessValue",37380:"ExposureBiasValue",37381:"MaxApertureValue",37382:"SubjectDistance",37383:"MeteringMode",37384:"LightSource",37385:"Flash",37386:"FocalLength",37396:"SubjectArea",37500:"MakerNote",37510:"UserComment",37520:"SubsecTime",37521:"SubsecTimeOriginal",37522:"SubsecTimeDigitized",40960:"FlashpixVersion",40961:"ColorSpace",40962:"PixelXDimension",40963:"PixelYDimension",40964:"RelatedSoundFile",41483:"FlashEnergy",41484:"SpatialFrequencyResponse",41486:"FocalPlaneXResolution",41487:"FocalPlaneYResolution",41488:"FocalPlaneResolutionUnit",41492:"SubjectLocation",41493:"ExposureIndex",41495:"SensingMethod",41728:"FileSource",41729:"SceneType",41730:"CFAPattern",41985:"CustomRendered",41986:"ExposureMode",41987:"WhiteBalance",41988:"DigitalZoomRatio",41989:"FocalLengthIn35mmFilm",41990:"SceneCaptureType",41991:"GainControl",41992:"Contrast",41993:"Saturation",41994:"Sharpness",41995:"DeviceSettingDescription",41996:"SubjectDistanceRange",42016:"ImageUniqueID",42032:"CameraOwnerName",42033:"BodySerialNumber",42034:"LensSpecification",42035:"LensMake",42036:"LensModel",42037:"LensSerialNumber",42240:"Gamma"},i={};for(var t in e)i[e[t]]=t;return exif$1={tagsById:e,tagsByName:i},exif$1}var gps$1,hasRequiredGps;function requireGps(){if(hasRequiredGps)return gps$1;hasRequiredGps=1;const e={0:"GPSVersionID",1:"GPSLatitudeRef",2:"GPSLatitude",3:"GPSLongitudeRef",4:"GPSLongitude",5:"GPSAltitudeRef",6:"GPSAltitude",7:"GPSTimeStamp",8:"GPSSatellites",9:"GPSStatus",10:"GPSMeasureMode",11:"GPSDOP",12:"GPSSpeedRef",13:"GPSSpeed",14:"GPSTrackRef",15:"GPSTrack",16:"GPSImgDirectionRef",17:"GPSImgDirection",18:"GPSMapDatum",19:"GPSDestLatitudeRef",20:"GPSDestLatitude",21:"GPSDestLongitudeRef",22:"GPSDestLongitude",23:"GPSDestBearingRef",24:"GPSDestBearing",25:"GPSDestDistanceRef",26:"GPSDestDistance",27:"GPSProcessingMethod",28:"GPSAreaInformation",29:"GPSDateStamp",30:"GPSDifferential",31:"GPSHPositioningError"},i={};for(var t in e)i[e[t]]=t;return gps$1={tagsById:e,tagsByName:i},gps$1}var ifd,hasRequiredIfd;function requireIfd(){if(hasRequiredIfd)return ifd;hasRequiredIfd=1;const e={standard:requireStandard(),exif:requireExif(),gps:requireGps()};class i{constructor(n){if(!n)throw new Error("missing kind");this.data=null,this.fields=new Map,this.kind=n,this._map=null}get(n){if(typeof n=="number")return this.fields.get(n);if(typeof n=="string")return this.fields.get(e[this.kind].tagsByName[n]);throw new Error("expected a number or string")}get map(){if(!this._map){this._map={};const a=e[this.kind].tagsById;for(var n of this.fields.keys())a[n]&&(this._map[a[n]]=this.fields.get(n))}return this._map}}return ifd=i,ifd}var tiffIfd,hasRequiredTiffIfd;function requireTiffIfd(){if(hasRequiredTiffIfd)return tiffIfd;hasRequiredTiffIfd=1;const e=requireIfd(),i=/^(\d{4}):(\d{2}):(\d{2}) (\d{2}):(\d{2}):(\d{2})$/;class t extends e{constructor(){super("standard")}get size(){return this.width*this.height}get width(){return this.imageWidth}get height(){return this.imageLength}get components(){return this.samplesPerPixel}get date(){var s=new Date,o=i.exec(this.dateTime);return s.setFullYear(o[1],o[2]-1,o[3]),s.setHours(o[4],o[5],o[6]),s}get newSubfileType(){return this.get(254)}get imageWidth(){return this.get(256)}get imageLength(){return this.get(257)}get bitsPerSample(){return this.get(258)}get compression(){return this.get(259)||1}get type(){return this.get(262)}get fillOrder(){return this.get(266)||1}get documentName(){return this.get(269)}get imageDescription(){return this.get(270)}get stripOffsets(){return n(this.get(273))}get orientation(){return this.get(274)}get samplesPerPixel(){return this.get(277)}get rowsPerStrip(){return this.get(278)}get stripByteCounts(){return n(this.get(279))}get minSampleValue(){return this.get(280)||0}get maxSampleValue(){return this.get(281)||Math.pow(2,this.bitsPerSample)-1}get xResolution(){return this.get(282)}get yResolution(){return this.get(283)}get planarConfiguration(){return this.get(284)||1}get resolutionUnit(){return this.get(296)||2}get dateTime(){return this.get(306)}get predictor(){return this.get(317)||1}get sampleFormat(){return this.get(339)||1}get sMinSampleValue(){return this.get(340)||this.minSampleValue}get sMaxSampleValue(){return this.get(341)||this.maxSampleValue}}function n(a){return typeof a=="number"?[a]:a}return tiffIfd=t,tiffIfd}var ifdValue={},hasRequiredIfdValue;function requireIfdValue(){if(hasRequiredIfdValue)return ifdValue;hasRequiredIfdValue=1;var e=new Map([[1,[1,i]],[2,[1,t]],[3,[2,n]],[4,[4,a]],[5,[8,s]],[6,[1,o]],[7,[1,i]],[8,[2,h]],[9,[4,f]],[10,[8,l]],[11,[4,u]],[12,[8,w]]]);ifdValue.getByteLength=function(_,g){return e.get(_)[0]*g},ifdValue.readData=function(_,g,v){return e.get(g)[1](_,v)};function i(_,g){if(g===1)return _.readUint8();for(var v=new Uint8Array(g),k=0;k<g;k++)v[k]=_.readUint8();return v}function t(_,g){for(var v=[],k="",A=0;A<g;A++){var T=String.fromCharCode(_.readUint8());T==="\0"?(v.push(k),k=""):k+=T}return v.length===1?v[0]:v}function n(_,g){if(g===1)return _.readUint16();for(var v=new Uint16Array(g),k=0;k<g;k++)v[k]=_.readUint16();return v}function a(_,g){if(g===1)return _.readUint32();for(var v=new Uint32Array(g),k=0;k<g;k++)v[k]=_.readUint32();return v}function s(_,g){if(g===1)return _.readUint32()/_.readUint32();for(var v=new Array(g),k=0;k<g;k++)v[k]=_.readUint32()/_.readUint32();return v}function o(_,g){if(g===1)return _.readInt8();for(var v=new Int8Array(g),k=0;k<g;k++)v[k]=_.readInt8();return v}function h(_,g){if(g===1)return _.readInt16();for(var v=new Int16Array(g),k=0;k<g;k++)v[k]=_.readInt16();return v}function f(_,g){if(g===1)return _.readInt32();for(var v=new Int32Array(g),k=0;k<g;k++)v[k]=_.readInt32();return v}function l(_,g){if(g===1)return _.readInt32()/_.readInt32();for(var v=new Array(g),k=0;k<g;k++)v[k]=_.readInt32()/_.readInt32();return v}function u(_,g){if(g===1)return _.readFloat32();for(var v=new Float32Array(g),k=0;k<g;k++)v[k]=_.readFloat32();return v}function w(_,g){if(g===1)return _.readFloat64();for(var v=new Float64Array(g),k=0;k<g;k++)v[k]=_.readFloat64();return v}return ifdValue}var tiffDecoder,hasRequiredTiffDecoder;function requireTiffDecoder(){if(hasRequiredTiffDecoder)return tiffDecoder;hasRequiredTiffDecoder=1;const e=requireIOBuffer(),i=requireIfd(),t=requireTiffIfd(),n=requireIfdValue(),a={ignoreImageData:!1,onlyFirst:!1};class s extends e{constructor(g,v){super(g,v),this._nextIFD=0}decode(g){g=Object.assign({},a,g);const v=[];for(this.decodeHeader();this._nextIFD;)if(v.push(this.decodeIFD(g)),g.onlyFirst)return v[0];return v}decodeHeader(){let g=this.readUint16();if(g===18761)this.setLittleEndian();else if(g===19789)this.setBigEndian();else throw new Error("invalid byte order: 0x"+g.toString(16));if(g=this.readUint16(),g!==42)throw new Error("not a TIFF file");this._nextIFD=this.readUint32()}decodeIFD(g){this.seek(this._nextIFD);var v;g.kind?v=new i(g.kind):v=new t;const k=this.readUint16();for(var A=0;A<k;A++)this.decodeIFDEntry(v);return g.ignoreImageData||this.decodeImageData(v),this._nextIFD=this.readUint32(),v}decodeIFDEntry(g){const v=this.offset,k=this.readUint16(),A=this.readUint16(),T=this.readUint32();if(A<1||A>12){this.skip(4);return}n.getByteLength(A,T)>4&&this.seek(this.readUint32());const D=n.readData(this,A,T);if(g.fields.set(k,D),k===34665||k===34853){let C=this.offset,P;k===34665?P="exif":k===34853&&(P="gps"),this._nextIFD=D,g[P]=this.decodeIFD({kind:P,ignoreImageData:!0}),this.offset=C}this.seek(v),this.skip(12)}decodeImageData(g){const v=g.orientation;switch(v&&v!==1&&u("orientation",v),g.type){case 1:case 2:this.readStripData(g);break;default:u("image type",g.type);break}}readStripData(g){const v=g.width,k=g.height,A=w(g.bitsPerSample),T=g.sampleFormat;let $=v*k;const D=o($,1,A,T),C=g.compression,z=g.rowsPerStrip*v,B=g.stripOffsets,F=g.stripByteCounts;for(var L=0,N=0;N<B.length;N++){var G=this.getStripData(C,B[N],F[N]),V=$>z?z:$;$-=V,A===8?L=h(D,G,L,V):A===16?L=f(D,G,L,V,this.isLittleEndian()):A===32&&T===3?L=l(D,G,L,V,this.isLittleEndian()):u("bitDepth",A)}g.data=D}getStripData(g,v,k){switch(g){case 1:return new DataView(this.buffer,v,k);case 2:case 32773:return u("Compression",g);default:throw new Error("invalid compression: "+g)}}}tiffDecoder=s;function o(_,g,v,k){return v===8?new Uint8Array(_*g):v===16?new Uint16Array(_*g):v===32&&k===3?new Float32Array(_*g):u("bit depth / sample format",v+" / "+k)}function h(_,g,v,k){for(var A=0;A<k;A++)_[v++]=g.getUint8(A);return v}function f(_,g,v,k,A){for(var T=0;T<k*2;T+=2)_[v++]=g.getUint16(T,A);return v}function l(_,g,v,k,A){for(var T=0;T<k*4;T+=4)_[v++]=g.getFloat32(T,A);return v}function u(_,g){throw new Error("Unsupported "+_+": "+g)}function w(_){if(_.length){const v=_;_=v[0];for(var g=0;g<v.length;g++)v[g]!==_&&u("bit depth",v)}return _}return tiffDecoder}var decode,hasRequiredDecode$1;function requireDecode$1(){if(hasRequiredDecode$1)return decode;hasRequiredDecode$1=1;const e=requireTiffDecoder();return decode=function(t,n){return new e(t,n).decode(n)},decode}var hasRequiredSrc$4;function requireSrc$4(){return hasRequiredSrc$4||(hasRequiredSrc$4=1,src$3.decode=requireDecode$1()),src$3}var decode_1,hasRequiredDecode;function requireDecode(){if(hasRequiredDecode)return decode_1;hasRequiredDecode=1;const e=requireIOBuffer(),i=requireSrc$4();function t(n){const a=new e(n),s={};if(a.setBigEndian(),a.readUint16()!==65496)throw new Error("SOI marker not found. Not a valid JPEG file");if(a.readUint16()===65505){a.readUint16();const f=a.readBytes(6);if(f[0]===69&&f[1]===120&&f[2]===105&&f[3]===102&&f[4]===0&&f[5]===0){const l=i.decode(a,{onlyFirst:!0,ignoreImageData:!0,offset:a.offset});s.exif=l}}return s}return decode_1=t,decode_1}var hasRequiredSrc$3;function requireSrc$3(){return hasRequiredSrc$3||(hasRequiredSrc$3=1,src$4.decode=requireDecode()),src$4}var srcExports$2=requireSrc$3(),imageType$1={exports:{}},fileType={exports:{}},hasRequiredFileType;function requireFileType(){return hasRequiredFileType||(hasRequiredFileType=1,function(module){const toBytes=e=>[...e].map(i=>i.charCodeAt(0)),xpiZipFilename=toBytes("META-INF/mozilla.rsa"),oxmlContentTypes=toBytes("[Content_Types].xml"),oxmlRels=toBytes("_rels/.rels");function readUInt64LE(e,i=0){let t=e[i],n=1,a=0;for(;++a<8;)n*=256,t+=e[i+a]*n;return t}const fileType=e=>{if(!(e instanceof Uint8Array||e instanceof ArrayBuffer||Buffer.isBuffer(e)))throw new TypeError(`Expected the \`input\` argument to be of type \`Uint8Array\` or \`Buffer\` or \`ArrayBuffer\`, got \`${typeof e}\``);const i=e instanceof Uint8Array?e:new Uint8Array(e);if(!(i&&i.length>1))return null;const t=(a,s)=>{s=Object.assign({offset:0},s);for(let o=0;o<a.length;o++)if(s.mask){if(a[o]!==(s.mask[o]&i[o+s.offset]))return!1}else if(a[o]!==i[o+s.offset])return!1;return!0},n=(a,s)=>t(toBytes(a),s);if(t([255,216,255]))return{ext:"jpg",mime:"image/jpeg"};if(t([137,80,78,71,13,10,26,10]))return{ext:"png",mime:"image/png"};if(t([71,73,70]))return{ext:"gif",mime:"image/gif"};if(t([87,69,66,80],{offset:8}))return{ext:"webp",mime:"image/webp"};if(t([70,76,73,70]))return{ext:"flif",mime:"image/flif"};if((t([73,73,42,0])||t([77,77,0,42]))&&t([67,82],{offset:8}))return{ext:"cr2",mime:"image/x-canon-cr2"};if(t([73,73,42,0])||t([77,77,0,42]))return{ext:"tif",mime:"image/tiff"};if(t([66,77]))return{ext:"bmp",mime:"image/bmp"};if(t([73,73,188]))return{ext:"jxr",mime:"image/vnd.ms-photo"};if(t([56,66,80,83]))return{ext:"psd",mime:"image/vnd.adobe.photoshop"};if(t([80,75,3,4])){if(t([109,105,109,101,116,121,112,101,97,112,112,108,105,99,97,116,105,111,110,47,101,112,117,98,43,122,105,112],{offset:30}))return{ext:"epub",mime:"application/epub+zip"};if(t(xpiZipFilename,{offset:30}))return{ext:"xpi",mime:"application/x-xpinstall"};if(n("mimetypeapplication/vnd.oasis.opendocument.text",{offset:30}))return{ext:"odt",mime:"application/vnd.oasis.opendocument.text"};if(n("mimetypeapplication/vnd.oasis.opendocument.spreadsheet",{offset:30}))return{ext:"ods",mime:"application/vnd.oasis.opendocument.spreadsheet"};if(n("mimetypeapplication/vnd.oasis.opendocument.presentation",{offset:30}))return{ext:"odp",mime:"application/vnd.oasis.opendocument.presentation"};const a=(f,l=0)=>f.findIndex((u,w,_)=>w>=l&&_[w]===80&&_[w+1]===75&&_[w+2]===3&&_[w+3]===4);let s=0,o=!1,h=null;do{const f=s+30;if(o||(o=t(oxmlContentTypes,{offset:f})||t(oxmlRels,{offset:f})),h||(n("word/",{offset:f})?h={ext:"docx",mime:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"}:n("ppt/",{offset:f})?h={ext:"pptx",mime:"application/vnd.openxmlformats-officedocument.presentationml.presentation"}:n("xl/",{offset:f})&&(h={ext:"xlsx",mime:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"})),o&&h)return h;s=a(i,f)}while(s>=0);if(h)return h}if(t([80,75])&&(i[2]===3||i[2]===5||i[2]===7)&&(i[3]===4||i[3]===6||i[3]===8))return{ext:"zip",mime:"application/zip"};if(t([117,115,116,97,114],{offset:257}))return{ext:"tar",mime:"application/x-tar"};if(t([82,97,114,33,26,7])&&(i[6]===0||i[6]===1))return{ext:"rar",mime:"application/x-rar-compressed"};if(t([31,139,8]))return{ext:"gz",mime:"application/gzip"};if(t([66,90,104]))return{ext:"bz2",mime:"application/x-bzip2"};if(t([55,122,188,175,39,28]))return{ext:"7z",mime:"application/x-7z-compressed"};if(t([120,1]))return{ext:"dmg",mime:"application/x-apple-diskimage"};if(t([51,103,112,53])||t([0,0,0])&&t([102,116,121,112],{offset:4})&&(t([109,112,52,49],{offset:8})||t([109,112,52,50],{offset:8})||t([105,115,111,109],{offset:8})||t([105,115,111,50],{offset:8})||t([109,109,112,52],{offset:8})||t([77,52,86],{offset:8})||t([100,97,115,104],{offset:8})))return{ext:"mp4",mime:"video/mp4"};if(t([77,84,104,100]))return{ext:"mid",mime:"audio/midi"};if(t([26,69,223,163])){const a=i.subarray(4,4100),s=a.findIndex((o,h,f)=>f[h]===66&&f[h+1]===130);if(s!==-1){const o=s+3,h=f=>[...f].every((l,u)=>a[o+u]===l.charCodeAt(0));if(h("matroska"))return{ext:"mkv",mime:"video/x-matroska"};if(h("webm"))return{ext:"webm",mime:"video/webm"}}}if(t([0,0,0,20,102,116,121,112,113,116,32,32])||t([102,114,101,101],{offset:4})||t([102,116,121,112,113,116,32,32],{offset:4})||t([109,100,97,116],{offset:4})||t([109,111,111,118],{offset:4})||t([119,105,100,101],{offset:4}))return{ext:"mov",mime:"video/quicktime"};if(t([82,73,70,70])){if(t([65,86,73],{offset:8}))return{ext:"avi",mime:"video/vnd.avi"};if(t([87,65,86,69],{offset:8}))return{ext:"wav",mime:"audio/vnd.wave"};if(t([81,76,67,77],{offset:8}))return{ext:"qcp",mime:"audio/qcelp"}}if(t([48,38,178,117,142,102,207,17,166,217])){let a=30;do{const s=readUInt64LE(i,a+16);if(t([145,7,220,183,183,169,207,17,142,230,0,192,12,32,83,101],{offset:a})){if(t([64,158,105,248,77,91,207,17,168,253,0,128,95,92,68,43],{offset:a+24}))return{ext:"wma",mime:"audio/x-ms-wma"};if(t([192,239,25,188,77,91,207,17,168,253,0,128,95,92,68,43],{offset:a+24}))return{ext:"wmv",mime:"video/x-ms-asf"};break}a+=s}while(a+24<=i.length);return{ext:"asf",mime:"application/vnd.ms-asf"}}if(t([0,0,1,186])||t([0,0,1,179]))return{ext:"mpg",mime:"video/mpeg"};if(t([102,116,121,112,51,103],{offset:4}))return{ext:"3gp",mime:"video/3gpp"};for(let a=0;a<2&&a<i.length-16;a++){if(t([73,68,51],{offset:a})||t([255,226],{offset:a,mask:[255,226]}))return{ext:"mp3",mime:"audio/mpeg"};if(t([255,228],{offset:a,mask:[255,228]}))return{ext:"mp2",mime:"audio/mpeg"};if(t([255,248],{offset:a,mask:[255,252]}))return{ext:"mp2",mime:"audio/mpeg"};if(t([255,240],{offset:a,mask:[255,252]}))return{ext:"mp4",mime:"audio/mpeg"}}if(t([102,116,121,112,77,52,65],{offset:4}))return{ext:"m4a",mime:"audio/mp4"};if(t([79,112,117,115,72,101,97,100],{offset:28}))return{ext:"opus",mime:"audio/opus"};if(t([79,103,103,83]))return t([128,116,104,101,111,114,97],{offset:28})?{ext:"ogv",mime:"video/ogg"}:t([1,118,105,100,101,111,0],{offset:28})?{ext:"ogm",mime:"video/ogg"}:t([127,70,76,65,67],{offset:28})?{ext:"oga",mime:"audio/ogg"}:t([83,112,101,101,120,32,32],{offset:28})?{ext:"spx",mime:"audio/ogg"}:t([1,118,111,114,98,105,115],{offset:28})?{ext:"ogg",mime:"audio/ogg"}:{ext:"ogx",mime:"application/ogg"};if(t([102,76,97,67]))return{ext:"flac",mime:"audio/x-flac"};if(t([77,65,67,32]))return{ext:"ape",mime:"audio/ape"};if(t([119,118,112,107]))return{ext:"wv",mime:"audio/wavpack"};if(t([35,33,65,77,82,10]))return{ext:"amr",mime:"audio/amr"};if(t([37,80,68,70]))return{ext:"pdf",mime:"application/pdf"};if(t([77,90]))return{ext:"exe",mime:"application/x-msdownload"};if((i[0]===67||i[0]===70)&&t([87,83],{offset:1}))return{ext:"swf",mime:"application/x-shockwave-flash"};if(t([123,92,114,116,102]))return{ext:"rtf",mime:"application/rtf"};if(t([0,97,115,109]))return{ext:"wasm",mime:"application/wasm"};if(t([119,79,70,70])&&(t([0,1,0,0],{offset:4})||t([79,84,84,79],{offset:4})))return{ext:"woff",mime:"font/woff"};if(t([119,79,70,50])&&(t([0,1,0,0],{offset:4})||t([79,84,84,79],{offset:4})))return{ext:"woff2",mime:"font/woff2"};if(t([76,80],{offset:34})&&(t([0,0,1],{offset:8})||t([1,0,2],{offset:8})||t([2,0,2],{offset:8})))return{ext:"eot",mime:"application/vnd.ms-fontobject"};if(t([0,1,0,0,0]))return{ext:"ttf",mime:"font/ttf"};if(t([79,84,84,79,0]))return{ext:"otf",mime:"font/otf"};if(t([0,0,1,0]))return{ext:"ico",mime:"image/x-icon"};if(t([0,0,2,0]))return{ext:"cur",mime:"image/x-icon"};if(t([70,76,86,1]))return{ext:"flv",mime:"video/x-flv"};if(t([37,33]))return{ext:"ps",mime:"application/postscript"};if(t([253,55,122,88,90,0]))return{ext:"xz",mime:"application/x-xz"};if(t([83,81,76,105]))return{ext:"sqlite",mime:"application/x-sqlite3"};if(t([78,69,83,26]))return{ext:"nes",mime:"application/x-nintendo-nes-rom"};if(t([67,114,50,52]))return{ext:"crx",mime:"application/x-google-chrome-extension"};if(t([77,83,67,70])||t([73,83,99,40]))return{ext:"cab",mime:"application/vnd.ms-cab-compressed"};if(t([33,60,97,114,99,104,62,10,100,101,98,105,97,110,45,98,105,110,97,114,121]))return{ext:"deb",mime:"application/x-deb"};if(t([33,60,97,114,99,104,62]))return{ext:"ar",mime:"application/x-unix-archive"};if(t([237,171,238,219]))return{ext:"rpm",mime:"application/x-rpm"};if(t([31,160])||t([31,157]))return{ext:"Z",mime:"application/x-compress"};if(t([76,90,73,80]))return{ext:"lz",mime:"application/x-lzip"};if(t([208,207,17,224,161,177,26,225]))return{ext:"msi",mime:"application/x-msi"};if(t([6,14,43,52,2,5,1,1,13,1,2,1,1,2]))return{ext:"mxf",mime:"application/mxf"};if(t([71],{offset:4})&&(t([71],{offset:192})||t([71],{offset:196})))return{ext:"mts",mime:"video/mp2t"};if(t([66,76,69,78,68,69,82]))return{ext:"blend",mime:"application/x-blender"};if(t([66,80,71,251]))return{ext:"bpg",mime:"image/bpg"};if(t([0,0,0,12,106,80,32,32,13,10,135,10])){if(t([106,112,50,32],{offset:20}))return{ext:"jp2",mime:"image/jp2"};if(t([106,112,120,32],{offset:20}))return{ext:"jpx",mime:"image/jpx"};if(t([106,112,109,32],{offset:20}))return{ext:"jpm",mime:"image/jpm"};if(t([109,106,112,50],{offset:20}))return{ext:"mj2",mime:"image/mj2"}}if(t([70,79,82,77]))return{ext:"aif",mime:"audio/aiff"};if(n("<?xml "))return{ext:"xml",mime:"application/xml"};if(t([66,79,79,75,77,79,66,73],{offset:60}))return{ext:"mobi",mime:"application/x-mobipocket-ebook"};if(t([102,116,121,112],{offset:4})){if(t([109,105,102,49],{offset:8}))return{ext:"heic",mime:"image/heif"};if(t([109,115,102,49],{offset:8}))return{ext:"heic",mime:"image/heif-sequence"};if(t([104,101,105,99],{offset:8})||t([104,101,105,120],{offset:8}))return{ext:"heic",mime:"image/heic"};if(t([104,101,118,99],{offset:8})||t([104,101,118,120],{offset:8}))return{ext:"heic",mime:"image/heic-sequence"}}return t([171,75,84,88,32,49,49,187,13,10,26,10])?{ext:"ktx",mime:"image/ktx"}:t([68,73,67,77],{offset:128})?{ext:"dcm",mime:"application/dicom"}:t([77,80,43])?{ext:"mpc",mime:"audio/x-musepack"}:t([77,80,67,75])?{ext:"mpc",mime:"audio/x-musepack"}:t([66,69,71,73,78,58])?{ext:"ics",mime:"text/calendar"}:t([103,108,84,70,2,0,0,0])?{ext:"glb",mime:"model/gltf-binary"}:t([212,195,178,161])||t([161,178,195,212])?{ext:"pcap",mime:"application/vnd.tcpdump.pcap"}:null};module.exports=fileType,module.exports.default=fileType,Object.defineProperty(fileType,"minimumBytes",{value:4100}),module.exports.stream=readableStream=>new Promise((resolve,reject)=>{const stream=eval("require")("stream");readableStream.once("readable",()=>{const e=new stream.PassThrough,i=readableStream.read(module.exports.minimumBytes)||readableStream.read();try{e.fileType=fileType(i)}catch(t){reject(t)}readableStream.unshift(i),stream.pipeline?resolve(stream.pipeline(readableStream,e,()=>{})):resolve(readableStream.pipe(e))})})}(fileType)),fileType.exports}var hasRequiredImageType;function requireImageType(){if(hasRequiredImageType)return imageType$1.exports;hasRequiredImageType=1;const e=requireFileType(),i=new Set(["jpg","png","gif","webp","flif","cr2","tif","bmp","jxr","psd","ico","bpg","jp2","jpm","jpx","heic","cur","dcm"]),t=n=>{const a=e(n);return i.has(a&&a.ext)?a:null};return imageType$1.exports=t,imageType$1.exports.default=t,Object.defineProperty(t,"minimumBytes",{value:e.minimumBytes}),imageType$1.exports}var imageTypeExports=requireImageType();const imageType=getDefaultExportFromCjs(imageTypeExports);function guessStripByteCounts(e){if(e.compression!==1)throw new Error("missing mandatory StripByteCounts field in compressed image");const i=e.rowsPerStrip*e.width*e.samplesPerPixel*(e.bitsPerSample/8);return new Array(e.stripOffsets.length).fill(i)}function applyHorizontalDifferencing8Bit(e,i,t){let n=0;for(;n<e.length;){for(let a=t;a<i*t;a+=t)for(let s=0;s<t;s++)e[n+a+s]=e[n+a+s]+e[n+a-(t-s)]&255;n+=i*t}}function applyHorizontalDifferencing16Bit(e,i,t){let n=0;for(;n<e.length;){for(let a=t;a<i*t;a+=t)for(let s=0;s<t;s++)e[n+a+s]=e[n+a+s]+e[n+a-(t-s)]&65535;n+=i*t}}const tagsById$2={33434:"ExposureTime",33437:"FNumber",34850:"ExposureProgram",34852:"SpectralSensitivity",34855:"ISOSpeedRatings",34856:"OECF",34864:"SensitivityType",34865:"StandardOutputSensitivity",34866:"RecommendedExposureIndex",34867:"ISOSpeed",34868:"ISOSpeedLatitudeyyy",34869:"ISOSpeedLatitudezzz",36864:"ExifVersion",36867:"DateTimeOriginal",36868:"DateTimeDigitized",37121:"ComponentsConfiguration",37122:"CompressedBitsPerPixel",37377:"ShutterSpeedValue",37378:"ApertureValue",37379:"BrightnessValue",37380:"ExposureBiasValue",37381:"MaxApertureValue",37382:"SubjectDistance",37383:"MeteringMode",37384:"LightSource",37385:"Flash",37386:"FocalLength",37396:"SubjectArea",37500:"MakerNote",37510:"UserComment",37520:"SubsecTime",37521:"SubsecTimeOriginal",37522:"SubsecTimeDigitized",40960:"FlashpixVersion",40961:"ColorSpace",40962:"PixelXDimension",40963:"PixelYDimension",40964:"RelatedSoundFile",41483:"FlashEnergy",41484:"SpatialFrequencyResponse",41486:"FocalPlaneXResolution",41487:"FocalPlaneYResolution",41488:"FocalPlaneResolutionUnit",41492:"SubjectLocation",41493:"ExposureIndex",41495:"SensingMethod",41728:"FileSource",41729:"SceneType",41730:"CFAPattern",41985:"CustomRendered",41986:"ExposureMode",41987:"WhiteBalance",41988:"DigitalZoomRatio",41989:"FocalLengthIn35mmFilm",41990:"SceneCaptureType",41991:"GainControl",41992:"Contrast",41993:"Saturation",41994:"Sharpness",41995:"DeviceSettingDescription",41996:"SubjectDistanceRange",42016:"ImageUniqueID",42032:"CameraOwnerName",42033:"BodySerialNumber",42034:"LensSpecification",42035:"LensMake",42036:"LensModel",42037:"LensSerialNumber",42240:"Gamma"},tagsByName$2={};for(let e in tagsById$2)tagsByName$2[tagsById$2[e]]=Number(e);const exif=Object.freeze(Object.defineProperty({__proto__:null,tagsById:tagsById$2,tagsByName:tagsByName$2},Symbol.toStringTag,{value:"Module"})),tagsById$1={0:"GPSVersionID",1:"GPSLatitudeRef",2:"GPSLatitude",3:"GPSLongitudeRef",4:"GPSLongitude",5:"GPSAltitudeRef",6:"GPSAltitude",7:"GPSTimeStamp",8:"GPSSatellites",9:"GPSStatus",10:"GPSMeasureMode",11:"GPSDOP",12:"GPSSpeedRef",13:"GPSSpeed",14:"GPSTrackRef",15:"GPSTrack",16:"GPSImgDirectionRef",17:"GPSImgDirection",18:"GPSMapDatum",19:"GPSDestLatitudeRef",20:"GPSDestLatitude",21:"GPSDestLongitudeRef",22:"GPSDestLongitude",23:"GPSDestBearingRef",24:"GPSDestBearing",25:"GPSDestDistanceRef",26:"GPSDestDistance",27:"GPSProcessingMethod",28:"GPSAreaInformation",29:"GPSDateStamp",30:"GPSDifferential",31:"GPSHPositioningError"},tagsByName$1={};for(let e in tagsById$1)tagsByName$1[tagsById$1[e]]=Number(e);const gps=Object.freeze(Object.defineProperty({__proto__:null,tagsById:tagsById$1,tagsByName:tagsByName$1},Symbol.toStringTag,{value:"Module"})),tagsById={254:"NewSubfileType",255:"SubfileType",256:"ImageWidth",257:"ImageLength",258:"BitsPerSample",259:"Compression",262:"PhotometricInterpretation",263:"Threshholding",264:"CellWidth",265:"CellLength",266:"FillOrder",270:"ImageDescription",271:"Make",272:"Model",273:"StripOffsets",274:"Orientation",277:"SamplesPerPixel",278:"RowsPerStrip",279:"StripByteCounts",280:"MinSampleValue",281:"MaxSampleValue",282:"XResolution",283:"YResolution",284:"PlanarConfiguration",288:"FreeOffsets",289:"FreeByteCounts",290:"GrayResponseUnit",291:"GrayResponseCurve",296:"ResolutionUnit",305:"Software",306:"DateTime",315:"Artist",316:"HostComputer",320:"ColorMap",338:"ExtraSamples",33432:"Copyright",269:"DocumentName",285:"PageName",286:"XPosition",287:"YPosition",292:"T4Options",293:"T6Options",297:"PageNumber",301:"TransferFunction",317:"Predictor",318:"WhitePoint",319:"PrimaryChromaticities",321:"HalftoneHints",322:"TileWidth",323:"TileLength",324:"TileOffsets",325:"TileByteCounts",326:"BadFaxLines",327:"CleanFaxData",328:"ConsecutiveBadFaxLines",330:"SubIFDs",332:"InkSet",333:"InkNames",334:"NumberOfInks",336:"DotRange",337:"TargetPrinter",339:"SampleFormat",340:"SMinSampleValue",341:"SMaxSampleValue",342:"TransferRange",343:"ClipPath",344:"XClipPathUnits",345:"YClipPathUnits",346:"Indexed",347:"JPEGTables",351:"OPIProxy",400:"GlobalParametersIFD",401:"ProfileType",402:"FaxProfile",403:"CodingMethods",404:"VersionYear",405:"ModeNumber",433:"Decode",434:"DefaultImageColor",512:"JPEGProc",513:"JPEGInterchangeFormat",514:"JPEGInterchangeFormatLength",515:"JPEGRestartInterval",517:"JPEGLosslessPredictors",518:"JPEGPointTransforms",519:"JPEGQTables",520:"JPEGDCTables",521:"JPEGACTables",529:"YCbCrCoefficients",530:"YCbCrSubSampling",531:"YCbCrPositioning",532:"ReferenceBlackWhite",559:"StripRowCounts",700:"XMP",32781:"ImageID",34732:"ImageLayer",32932:"WangAnnotatio",33445:"MDFileTag",33446:"MDScalePixel",33447:"MDColorTable",33448:"MDLabName",33449:"MDSampleInfo",33450:"MDPrepDate",33451:"MDPrepTime",33452:"MDFileUnits",33550:"ModelPixelScaleTag",33723:"IPTC",33918:"INGRPacketDataTag",33919:"INGRFlagRegisters",33920:"IrasBTransformationMatrix",33922:"ModelTiepointTag",34264:"ModelTransformationTag",34377:"Photoshop",34665:"ExifIFD",34675:"ICCProfile",34735:"GeoKeyDirectoryTag",34736:"GeoDoubleParamsTag",34737:"GeoAsciiParamsTag",34853:"GPSIFD",34908:"HylaFAXFaxRecvParams",34909:"HylaFAXFaxSubAddress",34910:"HylaFAXFaxRecvTime",37724:"ImageSourceData",40965:"InteroperabilityIFD",42112:"GDAL_METADATA",42113:"GDAL_NODATA",50215:"OceScanjobDescription",50216:"OceApplicationSelector",50217:"OceIdentificationNumber",50218:"OceImageLogicCharacteristics",50706:"DNGVersion",50707:"DNGBackwardVersion",50708:"UniqueCameraModel",50709:"LocalizedCameraModel",50710:"CFAPlaneColor",50711:"CFALayout",50712:"LinearizationTable",50713:"BlackLevelRepeatDim",50714:"BlackLevel",50715:"BlackLevelDeltaH",50716:"BlackLevelDeltaV",50717:"WhiteLevel",50718:"DefaultScale",50719:"DefaultCropOrigin",50720:"DefaultCropSize",50721:"ColorMatrix1",50722:"ColorMatrix2",50723:"CameraCalibration1",50724:"CameraCalibration2",50725:"ReductionMatrix1",50726:"ReductionMatrix2",50727:"AnalogBalance",50728:"AsShotNeutral",50729:"AsShotWhiteXY",50730:"BaselineExposure",50731:"BaselineNoise",50732:"BaselineSharpness",50733:"BayerGreenSplit",50734:"LinearResponseLimit",50735:"CameraSerialNumber",50736:"LensInfo",50737:"ChromaBlurRadius",50738:"AntiAliasStrength",50740:"DNGPrivateData",50741:"MakerNoteSafety",50778:"CalibrationIlluminant1",50779:"CalibrationIlluminant2",50780:"BestQualityScale",50784:"AliasLayerMetadata"},tagsByName={};for(let e in tagsById)tagsByName[tagsById[e]]=Number(e);const standard=Object.freeze(Object.defineProperty({__proto__:null,tagsById,tagsByName},Symbol.toStringTag,{value:"Module"})),tags={standard,exif,gps};class IFD{constructor(i){if(!i)throw new Error("missing kind");this.data=new Uint8Array,this.fields=new Map,this.kind=i,this._hasMap=!1,this._map={}}get(i){if(typeof i=="number")return this.fields.get(i);if(typeof i=="string")return this.fields.get(tags[this.kind].tagsByName[i]);throw new Error("expected a number or string")}get map(){if(!this._hasMap){const i=tags[this.kind].tagsById;for(let t of this.fields.keys())i[t]&&(this._map[i[t]]=this.fields.get(t));this._hasMap=!0}return this._map}}let types=new Map([[1,[1,readByte]],[2,[1,readASCII]],[3,[2,readShort]],[4,[4,readLong]],[5,[8,readRational]],[6,[1,readSByte]],[7,[1,readByte]],[8,[2,readSShort]],[9,[4,readSLong]],[10,[8,readSRational]],[11,[4,readFloat]],[12,[8,readDouble]]]);function getByteLength(e,i){const t=types.get(e);if(!t)throw new Error(`type not found: ${e}`);return t[0]*i}function readData(e,i,t){const n=types.get(i);if(!n)throw new Error(`type not found: ${i}`);return n[1](e,t)}function readByte(e,i){if(i===1)return e.readUint8();let t=new Uint8Array(i);for(let n=0;n<i;n++)t[n]=e.readUint8();return t}function readASCII(e,i){let t=[],n="";for(let a=0;a<i;a++){let s=String.fromCharCode(e.readUint8());s==="\0"?(t.push(n),n=""):n+=s}return t.length===1?t[0]:t}function readShort(e,i){if(i===1)return e.readUint16();let t=new Uint16Array(i);for(let n=0;n<i;n++)t[n]=e.readUint16();return t}function readLong(e,i){if(i===1)return e.readUint32();let t=new Uint32Array(i);for(let n=0;n<i;n++)t[n]=e.readUint32();return t}function readRational(e,i){if(i===1)return e.readUint32()/e.readUint32();let t=new Array(i);for(let n=0;n<i;n++)t[n]=e.readUint32()/e.readUint32();return t}function readSByte(e,i){if(i===1)return e.readInt8();let t=new Int8Array(i);for(let n=0;n<i;n++)t[n]=e.readInt8();return t}function readSShort(e,i){if(i===1)return e.readInt16();let t=new Int16Array(i);for(let n=0;n<i;n++)t[n]=e.readInt16();return t}function readSLong(e,i){if(i===1)return e.readInt32();let t=new Int32Array(i);for(let n=0;n<i;n++)t[n]=e.readInt32();return t}function readSRational(e,i){if(i===1)return e.readInt32()/e.readInt32();let t=new Array(i);for(let n=0;n<i;n++)t[n]=e.readInt32()/e.readInt32();return t}function readFloat(e,i){if(i===1)return e.readFloat32();let t=new Float32Array(i);for(let n=0;n<i;n++)t[n]=e.readFloat32();return t}function readDouble(e,i){if(i===1)return e.readFloat64();let t=new Float64Array(i);for(let n=0;n<i;n++)t[n]=e.readFloat64();return t}const CLEAR_CODE=256,EOI_CODE=257,TABLE_START=258,MIN_BIT_LENGTH=9;let stringTable=[];function initializeStringTable(){if(stringTable.length===0){for(let i=0;i<256;i++)stringTable.push([i]);const e=[];for(let i=256;i<4096;i++)stringTable.push(e)}}const andTable=[511,1023,2047,4095],bitJumps=[0,0,0,0,0,0,0,0,0,511,1023,2047,4095];class LzwDecoder{constructor(i){this.nextData=0,this.nextBits=0,this.bytePointer=0,this.tableLength=TABLE_START,this.currentBitLength=MIN_BIT_LENGTH,this.stripArray=new Uint8Array(i.buffer,i.byteOffset,i.byteLength),this.outData=new IOBuffer(i.byteLength),this.initializeTable()}decode(){let i=0,t=0;for(;(i=this.getNextCode())!==EOI_CODE;)if(i===CLEAR_CODE){if(this.initializeTable(),i=this.getNextCode(),i===EOI_CODE)break;this.writeString(this.stringFromCode(i)),t=i}else if(this.isInTable(i))this.writeString(this.stringFromCode(i)),this.addStringToTable(this.stringFromCode(t).concat(this.stringFromCode(i)[0])),t=i;else{const a=this.stringFromCode(t).concat(this.stringFromCode(t)[0]);this.writeString(a),this.addStringToTable(a),t=i}const n=this.outData.toArray();return new DataView(n.buffer,n.byteOffset,n.byteLength)}initializeTable(){initializeStringTable(),this.tableLength=TABLE_START,this.currentBitLength=MIN_BIT_LENGTH}writeString(i){this.outData.writeBytes(i)}stringFromCode(i){return stringTable[i]}isInTable(i){return i<this.tableLength}addStringToTable(i){if(stringTable[this.tableLength++]=i,stringTable.length>4096)throw stringTable=[],new Error("LZW decoding error. Please open an issue at https://github.com/image-js/tiff/issues/new/choose (include a test image).");this.tableLength===bitJumps[this.currentBitLength]&&this.currentBitLength++}getNextCode(){this.nextData=this.nextData<<8|this.stripArray[this.bytePointer++]&255,this.nextBits+=8,this.nextBits<this.currentBitLength&&(this.nextData=this.nextData<<8|this.stripArray[this.bytePointer++]&255,this.nextBits+=8);const i=this.nextData>>this.nextBits-this.currentBitLength&andTable[this.currentBitLength-9];return this.nextBits-=this.currentBitLength,this.bytePointer>this.stripArray.length?257:i}}function decompressLzw(e){return new LzwDecoder(e).decode()}const dateTimeRegex=/^(\d{4}):(\d{2}):(\d{2}) (\d{2}):(\d{2}):(\d{2})$/;class TiffIfd extends IFD{constructor(){super("standard")}get size(){return this.width*this.height}get width(){return this.imageWidth}get height(){return this.imageLength}get components(){return this.samplesPerPixel}get date(){let i=new Date,t=dateTimeRegex.exec(this.dateTime);if(t===null)throw new Error(`invalid dateTime: ${this.dateTime}`);return i.setFullYear(Number(t[1]),Number(t[2])-1,Number(t[3])),i.setHours(Number(t[4]),Number(t[5]),Number(t[6])),i}get newSubfileType(){return this.get("NewSubfileType")}get imageWidth(){return this.get("ImageWidth")}get imageLength(){return this.get("ImageLength")}get bitsPerSample(){const i=this.get("BitsPerSample");return i&&typeof i!="number"?i[0]:i}get alpha(){const i=this.extraSamples;return i?i[0]!==0:!1}get associatedAlpha(){const i=this.extraSamples;return i?i[0]===1:!1}get extraSamples(){return alwaysArray(this.get("ExtraSamples"))}get compression(){return this.get("Compression")||1}get type(){return this.get("PhotometricInterpretation")}get fillOrder(){return this.get("FillOrder")||1}get documentName(){return this.get("DocumentName")}get imageDescription(){return this.get("ImageDescription")}get stripOffsets(){return alwaysArray(this.get("StripOffsets"))}get orientation(){return this.get("Orientation")}get samplesPerPixel(){return this.get("SamplesPerPixel")||1}get rowsPerStrip(){return this.get("RowsPerStrip")}get stripByteCounts(){return alwaysArray(this.get("StripByteCounts"))}get minSampleValue(){return this.get("MinSampleValue")||0}get maxSampleValue(){return this.get("MaxSampleValue")||Math.pow(2,this.bitsPerSample)-1}get xResolution(){return this.get("XResolution")}get yResolution(){return this.get("YResolution")}get planarConfiguration(){return this.get("PlanarConfiguration")||1}get resolutionUnit(){return this.get("ResolutionUnit")||2}get dateTime(){return this.get("DateTime")}get predictor(){return this.get("Predictor")||1}get sampleFormat(){return this.get("SampleFormat")||1}get sMinSampleValue(){return this.get("SMinSampleValue")||this.minSampleValue}get sMaxSampleValue(){return this.get("SMaxSampleValue")||this.maxSampleValue}get palette(){const i=2**this.bitsPerSample,t=this.get("ColorMap");if(!t)return;if(t.length!==3*i)throw new Error(`ColorMap size must be ${i}`);const n=[];for(let a=0;a<i;a++)n.push([t[a],t[a+i],t[a+2*i]]);return n}}function alwaysArray(e){return typeof e=="number"?[e]:e}function zero$1(e){let i=e.length;for(;--i>=0;)e[i]=0}const MIN_MATCH$1=3,MAX_MATCH$1=258,LENGTH_CODES$1=29,LITERALS$1=256,L_CODES$1=LITERALS$1+1+LENGTH_CODES$1,D_CODES$1=30,DIST_CODE_LEN=512,static_ltree=new Array((L_CODES$1+2)*2);zero$1(static_ltree);const static_dtree=new Array(D_CODES$1*2);zero$1(static_dtree);const _dist_code=new Array(DIST_CODE_LEN);zero$1(_dist_code);const _length_code=new Array(MAX_MATCH$1-MIN_MATCH$1+1);zero$1(_length_code);const base_length=new Array(LENGTH_CODES$1);zero$1(base_length);const base_dist=new Array(D_CODES$1);zero$1(base_dist);const adler32=(e,i,t,n)=>{let a=e&65535|0,s=e>>>16&65535|0,o=0;for(;t!==0;){o=t>2e3?2e3:t,t-=o;do a=a+i[n++]|0,s=s+a|0;while(--o);a%=65521,s%=65521}return a|s<<16|0};var adler32_1$1=adler32;const makeTable=()=>{let e,i=[];for(var t=0;t<256;t++){e=t;for(var n=0;n<8;n++)e=e&1?3988292384^e>>>1:e>>>1;i[t]=e}return i},crcTable=new Uint32Array(makeTable()),crc32=(e,i,t,n)=>{const a=crcTable,s=n+t;e^=-1;for(let o=n;o<s;o++)e=e>>>8^a[(e^i[o])&255];return e^-1};var crc32_1$1=crc32,messages$1={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},constants$2={Z_NO_FLUSH:0,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_DEFLATED:8};const _has=(e,i)=>Object.prototype.hasOwnProperty.call(e,i);var assign=function(e){const i=Array.prototype.slice.call(arguments,1);for(;i.length;){const t=i.shift();if(t){if(typeof t!="object")throw new TypeError(t+"must be non-object");for(const n in t)_has(t,n)&&(e[n]=t[n])}}return e},flattenChunks=e=>{let i=0;for(let n=0,a=e.length;n<a;n++)i+=e[n].length;const t=new Uint8Array(i);for(let n=0,a=0,s=e.length;n<s;n++){let o=e[n];t.set(o,a),a+=o.length}return t},common$1={assign,flattenChunks};let STR_APPLY_UIA_OK=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){STR_APPLY_UIA_OK=!1}const _utf8len=new Uint8Array(256);for(let e=0;e<256;e++)_utf8len[e]=e>=252?6:e>=248?5:e>=240?4:e>=224?3:e>=192?2:1;_utf8len[254]=_utf8len[254]=1;var string2buf=e=>{if(typeof TextEncoder=="function"&&TextEncoder.prototype.encode)return new TextEncoder().encode(e);let i,t,n,a,s,o=e.length,h=0;for(a=0;a<o;a++)t=e.charCodeAt(a),(t&64512)===55296&&a+1<o&&(n=e.charCodeAt(a+1),(n&64512)===56320&&(t=65536+(t-55296<<10)+(n-56320),a++)),h+=t<128?1:t<2048?2:t<65536?3:4;for(i=new Uint8Array(h),s=0,a=0;s<h;a++)t=e.charCodeAt(a),(t&64512)===55296&&a+1<o&&(n=e.charCodeAt(a+1),(n&64512)===56320&&(t=65536+(t-55296<<10)+(n-56320),a++)),t<128?i[s++]=t:t<2048?(i[s++]=192|t>>>6,i[s++]=128|t&63):t<65536?(i[s++]=224|t>>>12,i[s++]=128|t>>>6&63,i[s++]=128|t&63):(i[s++]=240|t>>>18,i[s++]=128|t>>>12&63,i[s++]=128|t>>>6&63,i[s++]=128|t&63);return i};const buf2binstring=(e,i)=>{if(i<65534&&e.subarray&&STR_APPLY_UIA_OK)return String.fromCharCode.apply(null,e.length===i?e:e.subarray(0,i));let t="";for(let n=0;n<i;n++)t+=String.fromCharCode(e[n]);return t};var buf2string=(e,i)=>{const t=i||e.length;if(typeof TextDecoder=="function"&&TextDecoder.prototype.decode)return new TextDecoder().decode(e.subarray(0,i));let n,a;const s=new Array(t*2);for(a=0,n=0;n<t;){let o=e[n++];if(o<128){s[a++]=o;continue}let h=_utf8len[o];if(h>4){s[a++]=65533,n+=h-1;continue}for(o&=h===2?31:h===3?15:7;h>1&&n<t;)o=o<<6|e[n++]&63,h--;if(h>1){s[a++]=65533;continue}o<65536?s[a++]=o:(o-=65536,s[a++]=55296|o>>10&1023,s[a++]=56320|o&1023)}return buf2binstring(s,a)},utf8border=(e,i)=>{i=i||e.length,i>e.length&&(i=e.length);let t=i-1;for(;t>=0&&(e[t]&192)===128;)t--;return t<0||t===0?i:t+_utf8len[e[t]]>i?t:i},strings$1={string2buf,buf2string,utf8border};function ZStream(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}var zstream$1=ZStream;const BAD$1=16209,TYPE$1=16191;var inffast$1=function e(i,t){let n,a,s,o,h,f,l,u,w,_,g,v,k,A,T,$,D,C,P,z,B,F,L,N;const G=i.state;n=i.next_in,L=i.input,a=n+(i.avail_in-5),s=i.next_out,N=i.output,o=s-(t-i.avail_out),h=s+(i.avail_out-257),f=G.dmax,l=G.wsize,u=G.whave,w=G.wnext,_=G.window,g=G.hold,v=G.bits,k=G.lencode,A=G.distcode,T=(1<<G.lenbits)-1,$=(1<<G.distbits)-1;e:do{v<15&&(g+=L[n++]<<v,v+=8,g+=L[n++]<<v,v+=8),D=k[g&T];t:for(;;){if(C=D>>>24,g>>>=C,v-=C,C=D>>>16&255,C===0)N[s++]=D&65535;else if(C&16){P=D&65535,C&=15,C&&(v<C&&(g+=L[n++]<<v,v+=8),P+=g&(1<<C)-1,g>>>=C,v-=C),v<15&&(g+=L[n++]<<v,v+=8,g+=L[n++]<<v,v+=8),D=A[g&$];i:for(;;){if(C=D>>>24,g>>>=C,v-=C,C=D>>>16&255,C&16){if(z=D&65535,C&=15,v<C&&(g+=L[n++]<<v,v+=8,v<C&&(g+=L[n++]<<v,v+=8)),z+=g&(1<<C)-1,z>f){i.msg="invalid distance too far back",G.mode=BAD$1;break e}if(g>>>=C,v-=C,C=s-o,z>C){if(C=z-C,C>u&&G.sane){i.msg="invalid distance too far back",G.mode=BAD$1;break e}if(B=0,F=_,w===0){if(B+=l-C,C<P){P-=C;do N[s++]=_[B++];while(--C);B=s-z,F=N}}else if(w<C){if(B+=l+w-C,C-=w,C<P){P-=C;do N[s++]=_[B++];while(--C);if(B=0,w<P){C=w,P-=C;do N[s++]=_[B++];while(--C);B=s-z,F=N}}}else if(B+=w-C,C<P){P-=C;do N[s++]=_[B++];while(--C);B=s-z,F=N}for(;P>2;)N[s++]=F[B++],N[s++]=F[B++],N[s++]=F[B++],P-=3;P&&(N[s++]=F[B++],P>1&&(N[s++]=F[B++]))}else{B=s-z;do N[s++]=N[B++],N[s++]=N[B++],N[s++]=N[B++],P-=3;while(P>2);P&&(N[s++]=N[B++],P>1&&(N[s++]=N[B++]))}}else if((C&64)===0){D=A[(D&65535)+(g&(1<<C)-1)];continue i}else{i.msg="invalid distance code",G.mode=BAD$1;break e}break}}else if((C&64)===0){D=k[(D&65535)+(g&(1<<C)-1)];continue t}else if(C&32){G.mode=TYPE$1;break e}else{i.msg="invalid literal/length code",G.mode=BAD$1;break e}break}}while(n<a&&s<h);P=v>>3,n-=P,v-=P<<3,g&=(1<<v)-1,i.next_in=n,i.next_out=s,i.avail_in=n<a?5+(a-n):5-(n-a),i.avail_out=s<h?257+(h-s):257-(s-h),G.hold=g,G.bits=v};const MAXBITS=15,ENOUGH_LENS$1=852,ENOUGH_DISTS$1=592,CODES$1=0,LENS$1=1,DISTS$1=2,lbase=new Uint16Array([3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0]),lext=new Uint8Array([16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78]),dbase=new Uint16Array([1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0]),dext=new Uint8Array([16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64]),inflate_table=(e,i,t,n,a,s,o,h)=>{const f=h.bits;let l=0,u=0,w=0,_=0,g=0,v=0,k=0,A=0,T=0,$=0,D,C,P,z,B,F=null,L;const N=new Uint16Array(MAXBITS+1),G=new Uint16Array(MAXBITS+1);let V=null,J,Q,W;for(l=0;l<=MAXBITS;l++)N[l]=0;for(u=0;u<n;u++)N[i[t+u]]++;for(g=f,_=MAXBITS;_>=1&&N[_]===0;_--);if(g>_&&(g=_),_===0)return a[s++]=1<<24|64<<16|0,a[s++]=1<<24|64<<16|0,h.bits=1,0;for(w=1;w<_&&N[w]===0;w++);for(g<w&&(g=w),A=1,l=1;l<=MAXBITS;l++)if(A<<=1,A-=N[l],A<0)return-1;if(A>0&&(e===CODES$1||_!==1))return-1;for(G[1]=0,l=1;l<MAXBITS;l++)G[l+1]=G[l]+N[l];for(u=0;u<n;u++)i[t+u]!==0&&(o[G[i[t+u]]++]=u);if(e===CODES$1?(F=V=o,L=20):e===LENS$1?(F=lbase,V=lext,L=257):(F=dbase,V=dext,L=0),$=0,u=0,l=w,B=s,v=g,k=0,P=-1,T=1<<g,z=T-1,e===LENS$1&&T>ENOUGH_LENS$1||e===DISTS$1&&T>ENOUGH_DISTS$1)return 1;for(;;){J=l-k,o[u]+1<L?(Q=0,W=o[u]):o[u]>=L?(Q=V[o[u]-L],W=F[o[u]-L]):(Q=96,W=0),D=1<<l-k,C=1<<v,w=C;do C-=D,a[B+($>>k)+C]=J<<24|Q<<16|W|0;while(C!==0);for(D=1<<l-1;$&D;)D>>=1;if(D!==0?($&=D-1,$+=D):$=0,u++,--N[l]===0){if(l===_)break;l=i[t+o[u]]}if(l>g&&($&z)!==P){for(k===0&&(k=g),B+=w,v=l-k,A=1<<v;v+k<_&&(A-=N[v+k],!(A<=0));)v++,A<<=1;if(T+=1<<v,e===LENS$1&&T>ENOUGH_LENS$1||e===DISTS$1&&T>ENOUGH_DISTS$1)return 1;P=$&z,a[P]=g<<24|v<<16|B-s|0}}return $!==0&&(a[B+$]=l-k<<24|64<<16|0),h.bits=g,0};var inftrees$1=inflate_table;const CODES=0,LENS=1,DISTS=2,{Z_FINISH:Z_FINISH$1,Z_BLOCK,Z_TREES,Z_OK:Z_OK$1,Z_STREAM_END:Z_STREAM_END$1,Z_NEED_DICT:Z_NEED_DICT$1,Z_STREAM_ERROR:Z_STREAM_ERROR$1,Z_DATA_ERROR:Z_DATA_ERROR$1,Z_MEM_ERROR:Z_MEM_ERROR$1,Z_BUF_ERROR,Z_DEFLATED}=constants$2,HEAD=16180,FLAGS=16181,TIME=16182,OS=16183,EXLEN=16184,EXTRA=16185,NAME=16186,COMMENT=16187,HCRC=16188,DICTID=16189,DICT=16190,TYPE=16191,TYPEDO=16192,STORED=16193,COPY_=16194,COPY=16195,TABLE=16196,LENLENS=16197,CODELENS=16198,LEN_=16199,LEN=16200,LENEXT=16201,DIST=16202,DISTEXT=16203,MATCH=16204,LIT=16205,CHECK=16206,LENGTH=16207,DONE=16208,BAD=16209,MEM=16210,SYNC=16211,ENOUGH_LENS=852,ENOUGH_DISTS=592,MAX_WBITS=15,DEF_WBITS=MAX_WBITS,zswap32=e=>(e>>>24&255)+(e>>>8&65280)+((e&65280)<<8)+((e&255)<<24);function InflateState(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}const inflateStateCheck=e=>{if(!e)return 1;const i=e.state;return!i||i.strm!==e||i.mode<HEAD||i.mode>SYNC?1:0},inflateResetKeep=e=>{if(inflateStateCheck(e))return Z_STREAM_ERROR$1;const i=e.state;return e.total_in=e.total_out=i.total=0,e.msg="",i.wrap&&(e.adler=i.wrap&1),i.mode=HEAD,i.last=0,i.havedict=0,i.flags=-1,i.dmax=32768,i.head=null,i.hold=0,i.bits=0,i.lencode=i.lendyn=new Int32Array(ENOUGH_LENS),i.distcode=i.distdyn=new Int32Array(ENOUGH_DISTS),i.sane=1,i.back=-1,Z_OK$1},inflateReset=e=>{if(inflateStateCheck(e))return Z_STREAM_ERROR$1;const i=e.state;return i.wsize=0,i.whave=0,i.wnext=0,inflateResetKeep(e)},inflateReset2=(e,i)=>{let t;if(inflateStateCheck(e))return Z_STREAM_ERROR$1;const n=e.state;return i<0?(t=0,i=-i):(t=(i>>4)+5,i<48&&(i&=15)),i&&(i<8||i>15)?Z_STREAM_ERROR$1:(n.window!==null&&n.wbits!==i&&(n.window=null),n.wrap=t,n.wbits=i,inflateReset(e))},inflateInit2=(e,i)=>{if(!e)return Z_STREAM_ERROR$1;const t=new InflateState;e.state=t,t.strm=e,t.window=null,t.mode=HEAD;const n=inflateReset2(e,i);return n!==Z_OK$1&&(e.state=null),n},inflateInit=e=>inflateInit2(e,DEF_WBITS);let virgin=!0,lenfix,distfix;const fixedtables=e=>{if(virgin){lenfix=new Int32Array(512),distfix=new Int32Array(32);let i=0;for(;i<144;)e.lens[i++]=8;for(;i<256;)e.lens[i++]=9;for(;i<280;)e.lens[i++]=7;for(;i<288;)e.lens[i++]=8;for(inftrees$1(LENS,e.lens,0,288,lenfix,0,e.work,{bits:9}),i=0;i<32;)e.lens[i++]=5;inftrees$1(DISTS,e.lens,0,32,distfix,0,e.work,{bits:5}),virgin=!1}e.lencode=lenfix,e.lenbits=9,e.distcode=distfix,e.distbits=5},updatewindow=(e,i,t,n)=>{let a;const s=e.state;return s.window===null&&(s.wsize=1<<s.wbits,s.wnext=0,s.whave=0,s.window=new Uint8Array(s.wsize)),n>=s.wsize?(s.window.set(i.subarray(t-s.wsize,t),0),s.wnext=0,s.whave=s.wsize):(a=s.wsize-s.wnext,a>n&&(a=n),s.window.set(i.subarray(t-n,t-n+a),s.wnext),n-=a,n?(s.window.set(i.subarray(t-n,t),0),s.wnext=n,s.whave=s.wsize):(s.wnext+=a,s.wnext===s.wsize&&(s.wnext=0),s.whave<s.wsize&&(s.whave+=a))),0},inflate$2=(e,i)=>{let t,n,a,s,o,h,f,l,u,w,_,g,v,k,A=0,T,$,D,C,P,z,B,F;const L=new Uint8Array(4);let N,G;const V=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(inflateStateCheck(e)||!e.output||!e.input&&e.avail_in!==0)return Z_STREAM_ERROR$1;t=e.state,t.mode===TYPE&&(t.mode=TYPEDO),o=e.next_out,a=e.output,f=e.avail_out,s=e.next_in,n=e.input,h=e.avail_in,l=t.hold,u=t.bits,w=h,_=f,F=Z_OK$1;e:for(;;)switch(t.mode){case HEAD:if(t.wrap===0){t.mode=TYPEDO;break}for(;u<16;){if(h===0)break e;h--,l+=n[s++]<<u,u+=8}if(t.wrap&2&&l===35615){t.wbits===0&&(t.wbits=15),t.check=0,L[0]=l&255,L[1]=l>>>8&255,t.check=crc32_1$1(t.check,L,2,0),l=0,u=0,t.mode=FLAGS;break}if(t.head&&(t.head.done=!1),!(t.wrap&1)||(((l&255)<<8)+(l>>8))%31){e.msg="incorrect header check",t.mode=BAD;break}if((l&15)!==Z_DEFLATED){e.msg="unknown compression method",t.mode=BAD;break}if(l>>>=4,u-=4,B=(l&15)+8,t.wbits===0&&(t.wbits=B),B>15||B>t.wbits){e.msg="invalid window size",t.mode=BAD;break}t.dmax=1<<t.wbits,t.flags=0,e.adler=t.check=1,t.mode=l&512?DICTID:TYPE,l=0,u=0;break;case FLAGS:for(;u<16;){if(h===0)break e;h--,l+=n[s++]<<u,u+=8}if(t.flags=l,(t.flags&255)!==Z_DEFLATED){e.msg="unknown compression method",t.mode=BAD;break}if(t.flags&57344){e.msg="unknown header flags set",t.mode=BAD;break}t.head&&(t.head.text=l>>8&1),t.flags&512&&t.wrap&4&&(L[0]=l&255,L[1]=l>>>8&255,t.check=crc32_1$1(t.check,L,2,0)),l=0,u=0,t.mode=TIME;case TIME:for(;u<32;){if(h===0)break e;h--,l+=n[s++]<<u,u+=8}t.head&&(t.head.time=l),t.flags&512&&t.wrap&4&&(L[0]=l&255,L[1]=l>>>8&255,L[2]=l>>>16&255,L[3]=l>>>24&255,t.check=crc32_1$1(t.check,L,4,0)),l=0,u=0,t.mode=OS;case OS:for(;u<16;){if(h===0)break e;h--,l+=n[s++]<<u,u+=8}t.head&&(t.head.xflags=l&255,t.head.os=l>>8),t.flags&512&&t.wrap&4&&(L[0]=l&255,L[1]=l>>>8&255,t.check=crc32_1$1(t.check,L,2,0)),l=0,u=0,t.mode=EXLEN;case EXLEN:if(t.flags&1024){for(;u<16;){if(h===0)break e;h--,l+=n[s++]<<u,u+=8}t.length=l,t.head&&(t.head.extra_len=l),t.flags&512&&t.wrap&4&&(L[0]=l&255,L[1]=l>>>8&255,t.check=crc32_1$1(t.check,L,2,0)),l=0,u=0}else t.head&&(t.head.extra=null);t.mode=EXTRA;case EXTRA:if(t.flags&1024&&(g=t.length,g>h&&(g=h),g&&(t.head&&(B=t.head.extra_len-t.length,t.head.extra||(t.head.extra=new Uint8Array(t.head.extra_len)),t.head.extra.set(n.subarray(s,s+g),B)),t.flags&512&&t.wrap&4&&(t.check=crc32_1$1(t.check,n,g,s)),h-=g,s+=g,t.length-=g),t.length))break e;t.length=0,t.mode=NAME;case NAME:if(t.flags&2048){if(h===0)break e;g=0;do B=n[s+g++],t.head&&B&&t.length<65536&&(t.head.name+=String.fromCharCode(B));while(B&&g<h);if(t.flags&512&&t.wrap&4&&(t.check=crc32_1$1(t.check,n,g,s)),h-=g,s+=g,B)break e}else t.head&&(t.head.name=null);t.length=0,t.mode=COMMENT;case COMMENT:if(t.flags&4096){if(h===0)break e;g=0;do B=n[s+g++],t.head&&B&&t.length<65536&&(t.head.comment+=String.fromCharCode(B));while(B&&g<h);if(t.flags&512&&t.wrap&4&&(t.check=crc32_1$1(t.check,n,g,s)),h-=g,s+=g,B)break e}else t.head&&(t.head.comment=null);t.mode=HCRC;case HCRC:if(t.flags&512){for(;u<16;){if(h===0)break e;h--,l+=n[s++]<<u,u+=8}if(t.wrap&4&&l!==(t.check&65535)){e.msg="header crc mismatch",t.mode=BAD;break}l=0,u=0}t.head&&(t.head.hcrc=t.flags>>9&1,t.head.done=!0),e.adler=t.check=0,t.mode=TYPE;break;case DICTID:for(;u<32;){if(h===0)break e;h--,l+=n[s++]<<u,u+=8}e.adler=t.check=zswap32(l),l=0,u=0,t.mode=DICT;case DICT:if(t.havedict===0)return e.next_out=o,e.avail_out=f,e.next_in=s,e.avail_in=h,t.hold=l,t.bits=u,Z_NEED_DICT$1;e.adler=t.check=1,t.mode=TYPE;case TYPE:if(i===Z_BLOCK||i===Z_TREES)break e;case TYPEDO:if(t.last){l>>>=u&7,u-=u&7,t.mode=CHECK;break}for(;u<3;){if(h===0)break e;h--,l+=n[s++]<<u,u+=8}switch(t.last=l&1,l>>>=1,u-=1,l&3){case 0:t.mode=STORED;break;case 1:if(fixedtables(t),t.mode=LEN_,i===Z_TREES){l>>>=2,u-=2;break e}break;case 2:t.mode=TABLE;break;case 3:e.msg="invalid block type",t.mode=BAD}l>>>=2,u-=2;break;case STORED:for(l>>>=u&7,u-=u&7;u<32;){if(h===0)break e;h--,l+=n[s++]<<u,u+=8}if((l&65535)!==(l>>>16^65535)){e.msg="invalid stored block lengths",t.mode=BAD;break}if(t.length=l&65535,l=0,u=0,t.mode=COPY_,i===Z_TREES)break e;case COPY_:t.mode=COPY;case COPY:if(g=t.length,g){if(g>h&&(g=h),g>f&&(g=f),g===0)break e;a.set(n.subarray(s,s+g),o),h-=g,s+=g,f-=g,o+=g,t.length-=g;break}t.mode=TYPE;break;case TABLE:for(;u<14;){if(h===0)break e;h--,l+=n[s++]<<u,u+=8}if(t.nlen=(l&31)+257,l>>>=5,u-=5,t.ndist=(l&31)+1,l>>>=5,u-=5,t.ncode=(l&15)+4,l>>>=4,u-=4,t.nlen>286||t.ndist>30){e.msg="too many length or distance symbols",t.mode=BAD;break}t.have=0,t.mode=LENLENS;case LENLENS:for(;t.have<t.ncode;){for(;u<3;){if(h===0)break e;h--,l+=n[s++]<<u,u+=8}t.lens[V[t.have++]]=l&7,l>>>=3,u-=3}for(;t.have<19;)t.lens[V[t.have++]]=0;if(t.lencode=t.lendyn,t.lenbits=7,N={bits:t.lenbits},F=inftrees$1(CODES,t.lens,0,19,t.lencode,0,t.work,N),t.lenbits=N.bits,F){e.msg="invalid code lengths set",t.mode=BAD;break}t.have=0,t.mode=CODELENS;case CODELENS:for(;t.have<t.nlen+t.ndist;){for(;A=t.lencode[l&(1<<t.lenbits)-1],T=A>>>24,$=A>>>16&255,D=A&65535,!(T<=u);){if(h===0)break e;h--,l+=n[s++]<<u,u+=8}if(D<16)l>>>=T,u-=T,t.lens[t.have++]=D;else{if(D===16){for(G=T+2;u<G;){if(h===0)break e;h--,l+=n[s++]<<u,u+=8}if(l>>>=T,u-=T,t.have===0){e.msg="invalid bit length repeat",t.mode=BAD;break}B=t.lens[t.have-1],g=3+(l&3),l>>>=2,u-=2}else if(D===17){for(G=T+3;u<G;){if(h===0)break e;h--,l+=n[s++]<<u,u+=8}l>>>=T,u-=T,B=0,g=3+(l&7),l>>>=3,u-=3}else{for(G=T+7;u<G;){if(h===0)break e;h--,l+=n[s++]<<u,u+=8}l>>>=T,u-=T,B=0,g=11+(l&127),l>>>=7,u-=7}if(t.have+g>t.nlen+t.ndist){e.msg="invalid bit length repeat",t.mode=BAD;break}for(;g--;)t.lens[t.have++]=B}}if(t.mode===BAD)break;if(t.lens[256]===0){e.msg="invalid code -- missing end-of-block",t.mode=BAD;break}if(t.lenbits=9,N={bits:t.lenbits},F=inftrees$1(LENS,t.lens,0,t.nlen,t.lencode,0,t.work,N),t.lenbits=N.bits,F){e.msg="invalid literal/lengths set",t.mode=BAD;break}if(t.distbits=6,t.distcode=t.distdyn,N={bits:t.distbits},F=inftrees$1(DISTS,t.lens,t.nlen,t.ndist,t.distcode,0,t.work,N),t.distbits=N.bits,F){e.msg="invalid distances set",t.mode=BAD;break}if(t.mode=LEN_,i===Z_TREES)break e;case LEN_:t.mode=LEN;case LEN:if(h>=6&&f>=258){e.next_out=o,e.avail_out=f,e.next_in=s,e.avail_in=h,t.hold=l,t.bits=u,inffast$1(e,_),o=e.next_out,a=e.output,f=e.avail_out,s=e.next_in,n=e.input,h=e.avail_in,l=t.hold,u=t.bits,t.mode===TYPE&&(t.back=-1);break}for(t.back=0;A=t.lencode[l&(1<<t.lenbits)-1],T=A>>>24,$=A>>>16&255,D=A&65535,!(T<=u);){if(h===0)break e;h--,l+=n[s++]<<u,u+=8}if($&&($&240)===0){for(C=T,P=$,z=D;A=t.lencode[z+((l&(1<<C+P)-1)>>C)],T=A>>>24,$=A>>>16&255,D=A&65535,!(C+T<=u);){if(h===0)break e;h--,l+=n[s++]<<u,u+=8}l>>>=C,u-=C,t.back+=C}if(l>>>=T,u-=T,t.back+=T,t.length=D,$===0){t.mode=LIT;break}if($&32){t.back=-1,t.mode=TYPE;break}if($&64){e.msg="invalid literal/length code",t.mode=BAD;break}t.extra=$&15,t.mode=LENEXT;case LENEXT:if(t.extra){for(G=t.extra;u<G;){if(h===0)break e;h--,l+=n[s++]<<u,u+=8}t.length+=l&(1<<t.extra)-1,l>>>=t.extra,u-=t.extra,t.back+=t.extra}t.was=t.length,t.mode=DIST;case DIST:for(;A=t.distcode[l&(1<<t.distbits)-1],T=A>>>24,$=A>>>16&255,D=A&65535,!(T<=u);){if(h===0)break e;h--,l+=n[s++]<<u,u+=8}if(($&240)===0){for(C=T,P=$,z=D;A=t.distcode[z+((l&(1<<C+P)-1)>>C)],T=A>>>24,$=A>>>16&255,D=A&65535,!(C+T<=u);){if(h===0)break e;h--,l+=n[s++]<<u,u+=8}l>>>=C,u-=C,t.back+=C}if(l>>>=T,u-=T,t.back+=T,$&64){e.msg="invalid distance code",t.mode=BAD;break}t.offset=D,t.extra=$&15,t.mode=DISTEXT;case DISTEXT:if(t.extra){for(G=t.extra;u<G;){if(h===0)break e;h--,l+=n[s++]<<u,u+=8}t.offset+=l&(1<<t.extra)-1,l>>>=t.extra,u-=t.extra,t.back+=t.extra}if(t.offset>t.dmax){e.msg="invalid distance too far back",t.mode=BAD;break}t.mode=MATCH;case MATCH:if(f===0)break e;if(g=_-f,t.offset>g){if(g=t.offset-g,g>t.whave&&t.sane){e.msg="invalid distance too far back",t.mode=BAD;break}g>t.wnext?(g-=t.wnext,v=t.wsize-g):v=t.wnext-g,g>t.length&&(g=t.length),k=t.window}else k=a,v=o-t.offset,g=t.length;g>f&&(g=f),f-=g,t.length-=g;do a[o++]=k[v++];while(--g);t.length===0&&(t.mode=LEN);break;case LIT:if(f===0)break e;a[o++]=t.length,f--,t.mode=LEN;break;case CHECK:if(t.wrap){for(;u<32;){if(h===0)break e;h--,l|=n[s++]<<u,u+=8}if(_-=f,e.total_out+=_,t.total+=_,t.wrap&4&&_&&(e.adler=t.check=t.flags?crc32_1$1(t.check,a,_,o-_):adler32_1$1(t.check,a,_,o-_)),_=f,t.wrap&4&&(t.flags?l:zswap32(l))!==t.check){e.msg="incorrect data check",t.mode=BAD;break}l=0,u=0}t.mode=LENGTH;case LENGTH:if(t.wrap&&t.flags){for(;u<32;){if(h===0)break e;h--,l+=n[s++]<<u,u+=8}if(t.wrap&4&&l!==(t.total&4294967295)){e.msg="incorrect length check",t.mode=BAD;break}l=0,u=0}t.mode=DONE;case DONE:F=Z_STREAM_END$1;break e;case BAD:F=Z_DATA_ERROR$1;break e;case MEM:return Z_MEM_ERROR$1;case SYNC:default:return Z_STREAM_ERROR$1}return e.next_out=o,e.avail_out=f,e.next_in=s,e.avail_in=h,t.hold=l,t.bits=u,(t.wsize||_!==e.avail_out&&t.mode<BAD&&(t.mode<CHECK||i!==Z_FINISH$1))&&updatewindow(e,e.output,e.next_out,_-e.avail_out),w-=e.avail_in,_-=e.avail_out,e.total_in+=w,e.total_out+=_,t.total+=_,t.wrap&4&&_&&(e.adler=t.check=t.flags?crc32_1$1(t.check,a,_,e.next_out-_):adler32_1$1(t.check,a,_,e.next_out-_)),e.data_type=t.bits+(t.last?64:0)+(t.mode===TYPE?128:0)+(t.mode===LEN_||t.mode===COPY_?256:0),(w===0&&_===0||i===Z_FINISH$1)&&F===Z_OK$1&&(F=Z_BUF_ERROR),F},inflateEnd=e=>{if(inflateStateCheck(e))return Z_STREAM_ERROR$1;let i=e.state;return i.window&&(i.window=null),e.state=null,Z_OK$1},inflateGetHeader=(e,i)=>{if(inflateStateCheck(e))return Z_STREAM_ERROR$1;const t=e.state;return(t.wrap&2)===0?Z_STREAM_ERROR$1:(t.head=i,i.done=!1,Z_OK$1)},inflateSetDictionary=(e,i)=>{const t=i.length;let n,a,s;return inflateStateCheck(e)||(n=e.state,n.wrap!==0&&n.mode!==DICT)?Z_STREAM_ERROR$1:n.mode===DICT&&(a=1,a=adler32_1$1(a,i,t,0),a!==n.check)?Z_DATA_ERROR$1:(s=updatewindow(e,i,t,t),s?(n.mode=MEM,Z_MEM_ERROR$1):(n.havedict=1,Z_OK$1))};var inflateReset_1=inflateReset,inflateReset2_1=inflateReset2,inflateResetKeep_1=inflateResetKeep,inflateInit_1=inflateInit,inflateInit2_1=inflateInit2,inflate_2$1=inflate$2,inflateEnd_1=inflateEnd,inflateGetHeader_1=inflateGetHeader,inflateSetDictionary_1=inflateSetDictionary,inflateInfo="pako inflate (from Nodeca project)",inflate_1$2={inflateReset:inflateReset_1,inflateReset2:inflateReset2_1,inflateResetKeep:inflateResetKeep_1,inflateInit:inflateInit_1,inflateInit2:inflateInit2_1,inflate:inflate_2$1,inflateEnd:inflateEnd_1,inflateGetHeader:inflateGetHeader_1,inflateSetDictionary:inflateSetDictionary_1,inflateInfo};function GZheader(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}var gzheader$1=GZheader;const toString$1=Object.prototype.toString,{Z_NO_FLUSH,Z_FINISH,Z_OK,Z_STREAM_END,Z_NEED_DICT,Z_STREAM_ERROR,Z_DATA_ERROR,Z_MEM_ERROR}=constants$2;function Inflate$1(e){this.options=common$1.assign({chunkSize:1024*64,windowBits:15,to:""},e||{});const i=this.options;i.raw&&i.windowBits>=0&&i.windowBits<16&&(i.windowBits=-i.windowBits,i.windowBits===0&&(i.windowBits=-15)),i.windowBits>=0&&i.windowBits<16&&!(e&&e.windowBits)&&(i.windowBits+=32),i.windowBits>15&&i.windowBits<48&&(i.windowBits&15)===0&&(i.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new zstream$1,this.strm.avail_out=0;let t=inflate_1$2.inflateInit2(this.strm,i.windowBits);if(t!==Z_OK)throw new Error(messages$1[t]);if(this.header=new gzheader$1,inflate_1$2.inflateGetHeader(this.strm,this.header),i.dictionary&&(typeof i.dictionary=="string"?i.dictionary=strings$1.string2buf(i.dictionary):toString$1.call(i.dictionary)==="[object ArrayBuffer]"&&(i.dictionary=new Uint8Array(i.dictionary)),i.raw&&(t=inflate_1$2.inflateSetDictionary(this.strm,i.dictionary),t!==Z_OK)))throw new Error(messages$1[t])}Inflate$1.prototype.push=function(e,i){const t=this.strm,n=this.options.chunkSize,a=this.options.dictionary;let s,o,h;if(this.ended)return!1;for(i===~~i?o=i:o=i===!0?Z_FINISH:Z_NO_FLUSH,toString$1.call(e)==="[object ArrayBuffer]"?t.input=new Uint8Array(e):t.input=e,t.next_in=0,t.avail_in=t.input.length;;){for(t.avail_out===0&&(t.output=new Uint8Array(n),t.next_out=0,t.avail_out=n),s=inflate_1$2.inflate(t,o),s===Z_NEED_DICT&&a&&(s=inflate_1$2.inflateSetDictionary(t,a),s===Z_OK?s=inflate_1$2.inflate(t,o):s===Z_DATA_ERROR&&(s=Z_NEED_DICT));t.avail_in>0&&s===Z_STREAM_END&&t.state.wrap>0&&e[t.next_in]!==0;)inflate_1$2.inflateReset(t),s=inflate_1$2.inflate(t,o);switch(s){case Z_STREAM_ERROR:case Z_DATA_ERROR:case Z_NEED_DICT:case Z_MEM_ERROR:return this.onEnd(s),this.ended=!0,!1}if(h=t.avail_out,t.next_out&&(t.avail_out===0||s===Z_STREAM_END))if(this.options.to==="string"){let f=strings$1.utf8border(t.output,t.next_out),l=t.next_out-f,u=strings$1.buf2string(t.output,f);t.next_out=l,t.avail_out=n-l,l&&t.output.set(t.output.subarray(f,f+l),0),this.onData(u)}else this.onData(t.output.length===t.next_out?t.output:t.output.subarray(0,t.next_out));if(!(s===Z_OK&&h===0)){if(s===Z_STREAM_END)return s=inflate_1$2.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,!0;if(t.avail_in===0)break}}return!0},Inflate$1.prototype.onData=function(e){this.chunks.push(e)},Inflate$1.prototype.onEnd=function(e){e===Z_OK&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=common$1.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};function inflate$1$1(e,i){const t=new Inflate$1(i);if(t.push(e),t.err)throw t.msg||messages$1[t.err];return t.result}var inflate_2=inflate$1$1,inflate_1$1={inflate:inflate_2};const{inflate:inflate$3}=inflate_1$1;var inflate_1=inflate$3;function decompressZlib(e){const i=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),t=inflate_1(i);return new DataView(t.buffer,t.byteOffset,t.byteLength)}const defaultOptions$3={ignoreImageData:!1,onlyFirst:!1};class TIFFDecoder extends IOBuffer{constructor(i){super(i),this._nextIFD=0}get isMultiPage(){let i=0;for(this.decodeHeader();this._nextIFD;)if(i++,this.decodeIFD({ignoreImageData:!0},!0),i===2)return!0;if(i===1)return!1;throw unsupported("ifdCount",i)}get pageCount(){let i=0;for(this.decodeHeader();this._nextIFD;)i++,this.decodeIFD({ignoreImageData:!0},!0);if(i>0)return i;throw unsupported("ifdCount",i)}decode(i={}){i=Object.assign({},defaultOptions$3,i);const t=[];for(this.decodeHeader();this._nextIFD;)if(t.push(this.decodeIFD(i,!0)),i.onlyFirst)return[t[0]];return t}decodeHeader(){const i=this.readUint16();if(i===18761)this.setLittleEndian();else if(i===19789)this.setBigEndian();else throw new Error(`invalid byte order: 0x${i.toString(16)}`);if(this.readUint16()!==42)throw new Error("not a TIFF file");this._nextIFD=this.readUint32()}decodeIFD(i,t){this.seek(this._nextIFD);let n;if(t)n=new TiffIfd;else{if(!i.kind)throw new Error("kind is missing");n=new IFD(i.kind)}const a=this.readUint16();for(let s=0;s<a;s++)this.decodeIFDEntry(n);if(!i.ignoreImageData){if(!(n instanceof TiffIfd))throw new Error("must be a tiff ifd");this.decodeImageData(n)}return this._nextIFD=this.readUint32(),n}decodeIFDEntry(i){const t=this.offset,n=this.readUint16(),a=this.readUint16(),s=this.readUint32();if(a<1||a>12){this.skip(4);return}getByteLength(a,s)>4&&this.seek(this.readUint32());const h=readData(this,a,s);if(i.fields.set(n,h),n===34665||n===34853){let f=this.offset,l="exif";n===34665?l="exif":n===34853&&(l="gps"),this._nextIFD=h,i[l]=this.decodeIFD({kind:l,ignoreImageData:!0},!1),this.offset=f}this.seek(t),this.skip(12)}decodeImageData(i){const t=i.orientation;if(t&&t!==1)throw unsupported("orientation",t);switch(i.type){case 0:case 1:case 2:case 3:this.readStripData(i);break;default:throw unsupported("image type",i.type)}if(this.applyPredictor(i),this.convertAlpha(i),i.type===0){const n=i.bitsPerSample,a=Math.pow(2,n)-1;for(let s=0;s<i.data.length;s++)i.data[s]=a-i.data[s]}}readStripData(i){const t=i.width,n=i.height,a=i.bitsPerSample,s=i.sampleFormat,o=t*n*i.samplesPerPixel,h=getDataArray(o,a,s),l=i.rowsPerStrip*t*i.samplesPerPixel,u=i.stripOffsets,w=i.stripByteCounts||guessStripByteCounts(i);let _=o,g=0;for(let v=0;v<u.length;v++){let k=new DataView(this.buffer,this.byteOffset+u[v],w[v]),A=_>l?l:_;_-=A;let T=k;switch(i.compression){case 1:break;case 5:{T=decompressLzw(k);break}case 8:{T=decompressZlib(k);break}case 2:throw unsupported("Compression","CCITT Group 3");case 32773:throw unsupported("Compression","PackBits");default:throw unsupported("Compression",i.compression)}g=this.fillUncompressed(a,s,h,T,g,A)}i.data=h}fillUncompressed(i,t,n,a,s,o){if(i===8)return fill8bit(n,a,s,o);if(i===16)return fill16bit(n,a,s,o,this.isLittleEndian());if(i===32&&t===3)return fillFloat32(n,a,s,o,this.isLittleEndian());throw unsupported("bitDepth",i)}applyPredictor(i){const t=i.bitsPerSample;switch(i.predictor){case 1:break;case 2:{if(t===8)applyHorizontalDifferencing8Bit(i.data,i.width,i.components);else if(t===16)applyHorizontalDifferencing16Bit(i.data,i.width,i.components);else throw new Error(`Horizontal differencing is only supported for images with a bit depth of ${t}`);break}default:throw new Error(`invalid predictor: ${i.predictor}`)}}convertAlpha(i){if(i.alpha&&i.associatedAlpha){const{data:t,components:n,maxSampleValue:a}=i;for(let s=0;s<t.length;s+=n){const o=t[s+n-1];for(let h=0;h<n-1;h++)t[s+h]=Math.round(t[s+h]*a/o)}}}}function getDataArray(e,i,t){if(i===8)return new Uint8Array(e);if(i===16)return new Uint16Array(e);if(i===32&&t===3)return new Float32Array(e);throw unsupported("bit depth / sample format",`${i} / ${t}`)}function fill8bit(e,i,t,n){for(let a=0;a<n;a++)e[t++]=i.getUint8(a);return t}function fill16bit(e,i,t,n,a){for(let s=0;s<n*2;s+=2)e[t++]=i.getUint16(s,a);return t}function fillFloat32(e,i,t,n,a){for(let s=0;s<n*4;s+=4)e[t++]=i.getFloat32(s,a);return t}function unsupported(e,i){return new Error(`Unsupported ${e}: ${i}`)}function decodeTIFF(e,i){return new TIFFDecoder(e).decode(i)}function matchAndCrop(e={}){let{algorithm:i="matchToPrevious",ignoreBorder:t=[0,0]}=e;this.checkProcessable("matchAndCrop",{bitDepth:[8,16]});let n=i==="matchToPrevious",a=this[0],s=[];s[0]={position:[0,0],image:this[0]};let o=[0,0];for(let _=1;_<this.length;_++){let g=a.getBestMatch(this[_],{border:t});s[_]={position:[g[0]+o[0],g[1]+o[1]],image:this[_]},n&&(o[0]+=g[0],o[1]+=g[1],a=this[_])}let h=0,f=0,l=0,u=0;for(let _=0;_<s.length;_++){let g=s[_];g.position[0]>h&&(h=g.position[0]),g.position[0]<f&&(f=g.position[0]),g.position[1]>l&&(l=g.position[1]),g.position[1]<u&&(u=g.position[1])}f=0-f,u=0-u;for(let _=0;_<s.length;_++){let g=s[_];g.crop=g.image.crop({x:h-g.position[0],y:l-g.position[1],width:a.width-f-h,height:a.height-u-l})}let w=[];for(let _=0;_<s.length;_++)w[_]=s[_].crop;return new Stack(w)}function min$2(){this.checkProcessable("min",{bitDepth:[8,16]});let e=this[0].min;for(let i=1;i<this.length;i++)for(let t=0;t<e.length;t++)e[t]=Math.min(e[t],this[i].min[t]);return e}function max$2(){this.checkProcessable("min",{bitDepth:[8,16]});let e=this[0].max;for(let i=1;i<this.length;i++)for(let t=0;t<e.length;t++)e[t]=Math.max(e[t],this[i].max[t]);return e}function median$2(e){let i=e.reduce((o,h)=>o+h);if(i===0)throw new Error("unreachable");let t=0,n=0,a=i/2,s;for(;;){if(e[t]>0){if(s!==void 0)return(s+t)/2;if(n+=e[t],n>a)return t;n===a&&(s=t)}t++}}function mean$2(e){let i=0,t=0;for(let n=0;n<e.length;n++)i+=e[n],t+=e[n]*n;return i===0?0:t/i}function median$1(){this.checkProcessable("median",{bitDepth:[8,16]});let e=this.getHistograms({maxSlots:this[0].maxValue+1}),i=new Array(e.length);for(let t=0;t<e.length;t++){let n=e[t];i[t]=median$2(n)}return i}function histogram(e){this.checkProcessable("min",{bitDepth:[8,16]});let i=this[0].getHistogram(e);for(let t=1;t<this.length;t++){let n=this[t].getHistogram(e);for(let a=0;a<i.length;a++)i[a]+=n[a]}return i}function histograms(e){this.checkProcessable("min",{bitDepth:[8,16]});let i=this[0].getHistograms(e),t=i[0].length;for(let n=1;n<this.length;n++){let a=this[n].getHistograms(e);for(let s=0;s<i.length;s++)for(let o=0;o<t;o++)i[s][o]+=a[s][o]}return i}function averageImage(){this.checkProcessable("averageImage",{bitDepth:[8,16]});let e=new Uint32Array(this[0].data.length);for(let n=0;n<this.length;n++){let a=this[n];for(let s=0;s<this[0].data.length;s++)e[s]+=a.data[s]}let i=Image.createFrom(this[0]),t=i.data;for(let n=0;n<this[0].data.length;n++)t[n]=e[n]/this.length;return i}function maxImage(){this.checkProcessable("max",{bitDepth:[8,16]});let e=Image.createFrom(this[0]);e.data.fill(0);for(const i of this)for(let t=0;t<e.data.length;t++)e.data[t]=Math.max(i.data[t],e.data[t]);return e}function minImage(){this.checkProcessable("max",{bitDepth:[8,16]});let e=Image.createFrom(this[0]);e.data.fill(e.maxValue);for(const i of this)for(let t=0;t<e.data.length;t++)e.data[t]=Math.min(i.data[t],e.data[t]);return e}function extend$2(e){e.extendMethod("matchAndCrop",matchAndCrop),e.extendMethod("getMin",min$2),e.extendMethod("getMax",max$2),e.extendMethod("getMedian",median$1),e.extendMethod("getHistogram",histogram),e.extendMethod("getHistograms",histograms),e.extendMethod("getAverage",averageImage),e.extendMethod("getAverageImage",averageImage),e.extendMethod("getMaxImage",maxImage),e.extendMethod("getMinImage",minImage)}let computedPropertyDescriptor={configurable:!0,enumerable:!1,get:void 0};class Stack extends Array{constructor(i){if(Array.isArray(i)){super(i.length);for(let t=0;t<i.length;t++)this[t]=i[t]}else typeof i=="number"?super(i):super();this.computed=null}static load(i){return Promise.all(i.map(Image.load)).then(t=>new Stack(t))}static extendMethod(i,t,n={}){let{inPlace:a=!1,returnThis:s=!0,partialArgs:o=[]}=n;return a?Stack.prototype[i]=function(...h){this.computed=null;let f=t.apply(this,[...o,...h]);return s?this:f}:Stack.prototype[i]=function(...h){return t.apply(this,[...o,...h])},Stack}static extendProperty(i,t,n={}){let{partialArgs:a=[]}=n;return computedPropertyDescriptor.get=function(){if(this.computed===null)this.computed={};else if(hasOwn(i,this.computed))return this.computed[i];let s=t.apply(this,a);return this.computed[i]=s,s},Object.defineProperty(Stack.prototype,i,computedPropertyDescriptor),Stack}checkProcessable(i,t={}){if(typeof i!="string")throw new TypeError("checkProcessable requires as first parameter the processName (a string)");if(this.size===0)throw new TypeError(`The process: ${i} can not be applied on an empty stack`);this[0].checkProcessable(i,t);for(let n=1;n<this.length;n++){if((t.sameSize===void 0||t.sameSize)&&this[0].width!==this[n].width)throw new TypeError(`The process: ${i} can not be applied if width is not identical in all images`);if((t.sameSize===void 0||t.sameSize)&&this[0].height!==this[n].height)throw new TypeError(`The process: ${i} can not be applied if height is not identical in all images`);if((t.sameAlpha===void 0||t.sameAlpha)&&this[0].alpha!==this[n].alpha)throw new TypeError(`The process: ${i} can not be applied if alpha is not identical in all images`);if((t.sameBitDepth===void 0||t.sameBitDepth)&&this[0].bitDepth!==this[n].bitDepth)throw new TypeError(`The process: ${i} can not be applied if bitDepth is not identical in all images`);if((t.sameColorModel===void 0||t.sameColorModel)&&this[0].colorModel!==this[n].colorModel)throw new TypeError(`The process: ${i} can not be applied if colorModel is not identical in all images`);if((t.sameNumberChannels===void 0||t.sameNumberChannels)&&this[0].channels!==this[n].channels)throw new TypeError(`The process: ${i} can not be applied if channels is not identical in all images`)}}}Array[Symbol.species]||(Stack.prototype.map=function(e,i){if(typeof e!="function")throw new TypeError(`${e} is not a function`);let t=new Stack(this.length);for(let n=0;n<this.length;n++)t[n]=e.call(i,this[n],n,this);return t}),extend$2(Stack);const isDataURL=/^data:[a-z]+\/(?:[a-z]+);base64,/;function load(e,i){if(typeof e=="string")return loadURL(e,i);if(e instanceof ArrayBuffer)return Promise.resolve(loadBinary(new Uint8Array(e),void 0,i&&i.ignorePalette));if(e.buffer)return Promise.resolve(loadBinary(e,void 0,i&&i.ignorePalette));throw new Error('argument to "load" must be a string or buffer.')}function loadBinary(e,i,t){const n=imageType(e);if(n)switch(n.mime){case"image/png":return loadPNG(e);case"image/jpeg":return loadJPEG(e);case"image/tiff":return loadTIFF(e,t);default:return loadGeneric(a(n.mime))}return loadGeneric(a("application/octet-stream"));function a(s){return i||toBase64URL(e,s)}}function loadURL(e,i){const t=e.slice(0,64).match(isDataURL);let n;return t!==null?n=Promise.resolve(decode$1(e.slice(t[0].length))):n=fetchBinary(e,i),n.then(a=>{const s=new Uint8Array(a);return loadBinary(s,t?e:void 0,i&&i.ignorePalette)})}function loadPNG(e){const i=decodePng(e);let t=i.channels,n,a=0;return t===2||t===4?(n=t-1,a=1):n=t,i.palette?loadPNGFromPalette(i):new Image(i.width,i.height,i.data,{components:n,alpha:a,bitDepth:i.depth,meta:{text:i.text}})}function loadPNGFromPalette(e){const i=e.width*e.height,t=e.palette[0].length,n=new Uint8Array(i*t),a=8/e.depth,s=e.depth<8?a:1,o=parseInt("1".repeat(e.depth),2),h=t===4;let f=0;for(let l=0;l<i;l++){const u=Math.floor(l/s);let w=e.data[u];e.depth<8&&(w=w>>>e.depth*(a-1-l%a)&o);const _=e.palette[w];n[f++]=_[0],n[f++]=_[1],n[f++]=_[2],h&&(n[f++]=_[3])}return new Image(e.width,e.height,n,{components:3,alpha:h,bitDepth:8})}function loadJPEG(e){const i=srcExports$2.decode(e);let t;i.exif&&(t=getMetadata(i.exif));const n=jpegJsExports.decode(e,{useTArray:!0,maxMemoryUsageInMB:1024});let a=new Image(n.width,n.height,n.data,{meta:t});if(t&&t.tiff.tags.Orientation){const s=t.tiff.tags.Orientation;s>2&&(a=a.rotate({3:180,4:180,5:90,6:90,7:270,8:270}[s])),[2,4,5,7].includes(s)&&(a=a.flipX())}return a}function loadTIFF(e,i){let t=decodeTIFF(e);return t.length===1?getImageFromIFD(t[0],i):new Stack(t.map(function(n){return getImageFromIFD(n,i)}))}function getMetadata(e){const i={tiff:{fields:e.fields,tags:e.map}};return e.exif&&(i.exif=e.exif),e.gps&&(i.gps=e.gps),i}function getImageFromIFD(e,i){if(!i&&e.type===3){const t=new Uint16Array(3*e.width*e.height),n=e.palette;let a=0;for(let s=0;s<e.data.length;s++){const o=e.data[s],h=n[o];t[a++]=h[0],t[a++]=h[1],t[a++]=h[2]}return new Image(e.width,e.height,t,{components:3,alpha:e.alpha,colorModel:RGB$1,bitDepth:16,meta:getMetadata(e)})}else return new Image(e.width,e.height,e.data,{components:e.type===2?3:1,alpha:e.alpha,colorModel:e.type===2?RGB$1:GREY$1,bitDepth:e.bitsPerSample.length?e.bitsPerSample[0]:e.bitsPerSample,meta:getMetadata(e)})}function loadGeneric(e,i){return i=i||{},new Promise(function(t,n){let a=new DOMImage;a.onload=function(){let s=a.width,o=a.height,f=createCanvas(s,o).getContext("2d");f.drawImage(a,0,0,s,o);let l=f.getImageData(0,0,s,o).data;t(new Image(s,o,l,i))},a.onerror=function(){n(new Error(`Could not load ${e}`))},a.src=e})}const valueMethods={getValueXY(e,i,t){return this.data[(i*this.width+e)*this.channels+t]},setValueXY(e,i,t,n){return this.data[(i*this.width+e)*this.channels+t]=n,this.computed=null,this},getValue(e,i){return this.data[e*this.channels+i]},setValue(e,i,t){return this.data[e*this.channels+i]=t,this.computed=null,this},getPixelXY(e,i){return this.getPixel(i*this.width+e)},setPixelXY(e,i,t){return this.setPixel(i*this.width+e,t)},getPixel(e){const i=new Array(this.channels),t=e*this.channels;for(let n=0;n<this.channels;n++)i[n]=this.data[t+n];return i},setPixel(e,i){const t=e*this.channels;for(let n=0;n<i.length;n++)this.data[t+n]=i[n];return this.computed=null,this}};function setValueMethods(e){for(const i in valueMethods)e.prototype[i]=valueMethods[i]}function getImageParameters(e){return{width:e.width,height:e.height,components:e.components,alpha:e.alpha,colorModel:e.colorModel,bitDepth:e.bitDepth}}function getOutputImage(e,i,t,n={}){const{out:a}=i;if(a===void 0)return n.copy?e.clone():Image.createFrom(e,t);{if(!Image.isImage(a))throw new TypeError("out must be an Image object");const s=Object.assign(getImageParameters(e),t);for(const o in s)if(a[o]!==s[o])throw new RangeError(`cannot use out. Its ${o} must be "${s[o]}" (found "${a[o]}")`);return a}}function getOutputImageOrInPlace(e,i,t){if(i.inPlace!==void 0&&typeof i.inPlace!="boolean")throw new TypeError("inPlace option must be a boolean");if(i.inPlace){if(i.out!==void 0)throw new TypeError("out option must not be set if inPlace option is true");return e}return getOutputImage(e,i,null,t)}function abs(e={}){this.checkProcessable("abs",{bitDepth:[32]});const i=getOutputImageOrInPlace(this,e);return absolute(this,i),i}function absolute(e,i){for(let t=0;t<e.data.length;t++)i.data[t]=Math.abs(e.data[t])}function copyAlphaChannel(e,i){if(e.alpha===1&&i.alpha===1)for(let t=0;t<e.size;t++)i.data[t*i.channels+i.components]=e.data[t*e.channels+e.components]}function invert(e={}){this.checkProcessable("invert",{bitDepth:[1,8,16]});const i=getOutputImageOrInPlace(this,e);return this.bitDepth===1?invertBinary(this,i):(invertColor(this,i),this!==i&&copyAlphaChannel(this,i)),i}function invertBinary(e,i){for(let t=0;t<e.data.length;t++)i.data[t]=~e.data[t]}function invertColor(e,i){for(let t=0;t<e.data.length;t+=e.channels)for(let n=0;n<e.components;n++)i.data[t+n]=e.maxValue-e.data[t+n]}function flipX(){this.checkProcessable("flipX",{bitDepth:[8,16]});for(let e=0;e<this.height;e++){let i=e*this.width*this.channels;for(let t=0;t<Math.floor(this.width/2);t++){let n=t*this.channels+i,a=(this.width-t-1)*this.channels+i;for(let s=0;s<this.channels;s++){let o=this.data[n+s];this.data[n+s]=this.data[a+s],this.data[a+s]=o}}}return this}function flipY(){this.checkProcessable("flipY",{bitDepth:[8,16]});for(let e=0;e<Math.floor(this.height/2);e++)for(let i=0;i<this.width;i++){let t=i*this.channels+e*this.width*this.channels,n=i*this.channels+(this.height-1-e)*this.channels*this.width;for(let a=0;a<this.channels;a++){let s=this.data[t+a];this.data[t+a]=this.data[n+a],this.data[n+a]=s}}return this}function blurFilter(e={}){const{radius:i=1}=e;if(i<1)throw new Error("radius must be greater than 1");const t=2*i+1,n=new Array(t);for(let a=0;a<t;a++){n[a]=new Array(t);for(let s=0;s<t;s++)n[a][s]=1/(t*t)}return this.convolution(n)}var medianQuickselect_min={exports:{}},hasRequiredMedianQuickselect_min;function requireMedianQuickselect_min(){return hasRequiredMedianQuickselect_min||(hasRequiredMedianQuickselect_min=1,function(e){(function(){function i(a){for(var s=0,o=a.length-1,h=void 0,f=void 0,l=void 0,u=n(s,o);;){if(o<=s)return a[u];if(o==s+1)return a[s]>a[o]&&t(a,s,o),a[u];for(h=n(s,o),a[h]>a[o]&&t(a,h,o),a[s]>a[o]&&t(a,s,o),a[h]>a[s]&&t(a,h,s),t(a,h,s+1),f=s+1,l=o;;){do f++;while(a[s]>a[f]);do l--;while(a[l]>a[s]);if(l<f)break;t(a,f,l)}t(a,s,l),l<=u&&(s=f),l>=u&&(o=l-1)}}var t=function(s,o,h){var f;return f=[s[h],s[o]],s[o]=f[0],s[h]=f[1],f},n=function(s,o){return~~((s+o)/2)};e.exports?e.exports=i:window.median=i})()}(medianQuickselect_min)),medianQuickselect_min.exports}var medianQuickselect_minExports=requireMedianQuickselect_min();const quickSelectMedian=getDefaultExportFromCjs(medianQuickselect_minExports);function validateArrayOfChannels(e,i={}){let{channels:t,allowAlpha:n,defaultAlpha:a}=i;return typeof n!="boolean"&&(n=!0),typeof t>"u"?allChannels(e,a):validateChannels(e,t,n)}function allChannels(e,i){let t=i?e.channels:e.components,n=new Array(t);for(let a=0;a<t;a++)n[a]=a;return n}function validateChannels(e,i,t){Array.isArray(i)||(i=[i]);for(let n=0;n<i.length;n++)i[n]=validateChannel(e,i[n],t);return i}function validateChannel(e,i,t=!0){if(i===void 0)throw new RangeError(`validateChannel : the channel has to be >=0 and <${e.channels}`);if(typeof i=="string"){switch(e.colorModel){case GREY$1:break;case RGB$1:if("rgb".includes(i))switch(i){case"r":i=0;break;case"g":i=1;break;case"b":i=2;break}break;case HSL:if("hsl".includes(i))switch(i){case"h":i=0;break;case"s":i=1;break;case"l":i=2;break}break;case HSV:if("hsv".includes(i))switch(i){case"h":i=0;break;case"s":i=1;break;case"v":i=2;break}break;case CMYK$1:if("cmyk".includes(i))switch(i){case"c":i=0;break;case"m":i=1;break;case"y":i=2;break;case"k":i=3;break}break;default:throw new Error(`Unexpected color model: ${e.colorModel}`)}if(i==="a"){if(!e.alpha)throw new Error("validateChannel : the image does not contain alpha channel");i=e.components}if(typeof i=="string")throw new Error(`validateChannel : undefined channel: ${i}`)}if(i>=e.channels)throw new RangeError(`validateChannel : the channel has to be >=0 and <${e.channels}`);if(!t&&i>=e.components)throw new RangeError("validateChannel : alpha channel may not be selected");return i}function medianFilter(e={}){let{radius:i=1,border:t="copy",channels:n}=e;if(this.checkProcessable("medianFilter",{bitDepth:[8,16]}),i<1)throw new Error("radius must be greater than 0");n=validateArrayOfChannels(this,n);let a=i,s=i,o=Image.createFrom(this),h=(a*2+1)*(s*2+1),f=new Array(h);for(let l=0;l<n.length;l++){let u=n[l];for(let w=s;w<this.height-s;w++)for(let _=a;_<this.width-a;_++){let g=0;for(let k=-s;k<=s;k++)for(let A=-a;A<=a;A++){let T=((w+k)*this.width+_+A)*this.channels+u;f[g++]=this.data[T]}let v=(w*this.width+_)*this.channels+u;o.data[v]=quickSelectMedian(f)}}if(this.alpha&&!n.includes(this.channels))for(let l=this.components;l<this.data.length;l=l+this.channels)o.data[l]=this.data[l];return o.setBorder({size:[a,s],algorithm:t}),o}function gaussianFilter(e={}){let{radius:i=1,sigma:t,channels:n,border:a="copy"}=e;this.checkProcessable("gaussian",{bitDepth:[8,16]});const s=getKernel(i,t);return this.convolution([s,s],{border:a,channels:n,algorithm:"separable"})}function getKernel(e,i){const t=e*2+1,n=new Array(t),a=i||((t-1)*.5-1)*.3+.8,s=-.5/(a*a);let o=0;for(let h=0;h<t;h++){const f=h-e,l=Math.exp(s*f*f);n[h]=l,o+=l}for(let h=0;h<t;h++)n[h]/=o;return n}const SOBEL_X=[[-1,0,1],[-2,0,2],[-1,0,1]],SOBEL_Y=[[-1,-2,-1],[0,0,0],[1,2,1]],SCHARR_X=[[3,0,-3],[10,0,-10],[3,0,-3]],SCHARR_Y=[[3,10,3],[0,0,0],[-3,-10,-3]];var src$2={},fftlib={},hasRequiredFftlib;function requireFftlib(){return hasRequiredFftlib||(hasRequiredFftlib=1,function(e){(function(){var i;i=e;var t={release:"0.3.0",date:"2013-03"};i.toString=function(){return"version "+t.release+", released "+t.date};for(var n=0,a=null,s=null,o={init:function(l){if(l!==0&&(l&l-1)===0)n=l,o._initArray(),o._makeBitReversalTable(),o._makeCosSinTable();else throw new Error("init: radix-2 required")},fft1d:function(l,u){o.fft(l,u,1)},ifft1d:function(l,u){var w=1/n;o.fft(l,u,-1);for(var _=0;_<n;_++)l[_]*=w,u[_]*=w},bt1d:function(l,u){o.fft(l,u,-1)},fft2d:function(l,u){for(var w=[],_=[],g=0,v=0;v<n;v++){g=v*n;for(var k=0;k<n;k++)w[k]=l[k+g],_[k]=u[k+g];o.fft1d(w,_);for(var A=0;A<n;A++)l[A+g]=w[A],u[A+g]=_[A]}for(var T=0;T<n;T++){for(var $=0;$<n;$++)g=T+$*n,w[$]=l[g],_[$]=u[g];o.fft1d(w,_);for(var D=0;D<n;D++)g=T+D*n,l[g]=w[D],u[g]=_[D]}},ifft2d:function(l,u){for(var w=[],_=[],g=0,v=0;v<n;v++){g=v*n;for(var k=0;k<n;k++)w[k]=l[k+g],_[k]=u[k+g];o.ifft1d(w,_);for(var A=0;A<n;A++)l[A+g]=w[A],u[A+g]=_[A]}for(var T=0;T<n;T++){for(var $=0;$<n;$++)g=T+$*n,w[$]=l[g],_[$]=u[g];o.ifft1d(w,_);for(var D=0;D<n;D++)g=T+D*n,l[g]=w[D],u[g]=_[D]}},fft:function(l,u,w){for(var _,g,v,k,A,T,$,D,C,P=n>>2,z=0;z<n;z++)k=a[z],z<k&&(A=l[z],l[z]=l[k],l[k]=A,A=u[z],u[z]=u[k],u[k]=A);for(var B=1;B<n;B<<=1){g=0,_=n/(B<<1);for(var F=0;F<B;F++){T=s[g+P],$=w*s[g];for(var L=F;L<n;L+=B<<1)v=L+B,D=T*l[v]+$*u[v],C=T*u[v]-$*l[v],l[v]=l[L]-D,l[L]+=D,u[v]=u[L]-C,u[L]+=C;g+=_}}},_initArray:function(){typeof Uint32Array<"u"?a=new Uint32Array(n):a=[],typeof Float64Array<"u"?s=new Float64Array(n*1.25):s=[]},_paddingZero:function(){},_makeBitReversalTable:function(){var l=0,u=0,w=0;for(a[0]=0;++l<n;){for(w=n>>1;w<=u;)u-=w,w>>=1;u+=w,a[l]=u}},_makeCosSinTable:function(){var l=n>>1,u=n>>2,w=n>>3,_=l+u,g=Math.sin(Math.PI/n),v=2*g*g,k=Math.sqrt(v*(2-v)),A=s[u]=1,T=s[0]=0;g=2*v;for(var $=1;$<w;$++)A-=v,v+=g*A,T+=k,k-=g*T,s[$]=T,s[u-$]=A;w!==0&&(s[w]=Math.sqrt(.5));for(var D=0;D<u;D++)s[l-D]=s[D];for(var C=0;C<_;C++)s[C+l]=-s[C]}},h=["init","fft1d","ifft1d","fft2d","ifft2d"],f=0;f<h.length;f++)i[h[f]]=o[h[f]];return i.bt=o.bt1d,i.fft=o.fft1d,i.ifft=o.ifft1d,i}).call(fftlib)}(fftlib)),fftlib}var FFTUtils_1,hasRequiredFFTUtils;function requireFFTUtils(){if(hasRequiredFFTUtils)return FFTUtils_1;hasRequiredFFTUtils=1;var e=requireFftlib(),i={DEBUG:!1,ifft2DArray:function(t,n,a){var s=new Array(n*a),o=n/2,h=(a-1)*2;e.init(o);for(var f={re:new Array(o),im:new Array(o)},l=0;l<a;l++){for(var u=o-1;u>=0;u--)f.re[u]=t[u*2*a+l],f.im[u]=t[(u*2+1)*a+l];e.bt(f.re,f.im);for(var u=o-1;u>=0;u--)s[u*2*a+l]=f.re[u],s[(u*2+1)*a+l]=f.im[u]}var w=new Array(o*h);e.init(h);for(var _={re:new Array(h),im:new Array(h)},g=h*o,u=0;u<n;u+=2){_.re[0]=s[u*a],_.im[0]=s[(u+1)*a];for(var l=1;l<a;l++)_.re[l]=s[u*a+l],_.im[l]=s[(u+1)*a+l],_.re[h-l]=s[u*a+l],_.im[h-l]=-s[(u+1)*a+l];e.bt(_.re,_.im);for(var v=u/2*h,l=h-1;l>=0;l--)w[v+l]=_.re[l]/g}return w},fft2DArray:function(t,n,a,s){Object.assign({},{inplace:!0});var o=a/2+1,h=n*2,f=new Array(h*o);e.init(a);for(var l={re:new Array(a),im:new Array(a)},u={re:new Array(a),im:new Array(a)},w={re:new Array(a),im:new Array(a)},_,g,v,k,A,T=0;T<n/2;T++){_=T*2*a,l.re=t.slice(_,_+a),_=(T*2+1)*a,l.im=t.slice(_,_+a),e.fft1d(l.re,l.im),this.reconstructTwoRealFFT(l,u,w),g=T*4*o,v=(T*4+1)*o,k=(T*4+2)*o,A=(T*4+3)*o;for(var $=o-1;$>=0;$--)f[g+$]=u.re[$],f[v+$]=u.im[$],f[k+$]=w.re[$],f[A+$]=w.im[$]}u=null,w=null;var D=new Array(h*o);e.init(n);for(var C={re:new Array(n),im:new Array(n)},P=o-1;P>=0;P--){for(var T=n-1;T>=0;T--)C.re[T]=f[T*2*o+P],C.im[T]=f[(T*2+1)*o+P],isNaN(C.re[T])&&(C.re[T]=0),isNaN(C.im[T])&&(C.im[T]=0);e.fft1d(C.re,C.im);for(var T=n-1;T>=0;T--)D[T*2*o+P]=C.re[T],D[(T*2+1)*o+P]=C.im[T]}return D},reconstructTwoRealFFT:function(t,n,a){var s=t.re.length;n.re[0]=t.re[0],n.im[0]=0,a.re[0]=t.im[0],a.im[0]=0;for(var o,h,f,l,u,w=s/2;w>0;w--)u=s-w,o=.5*(t.re[w]-t.re[u]),h=.5*(t.re[w]+t.re[u]),f=.5*(t.im[w]-t.im[u]),l=.5*(t.im[w]+t.im[u]),n.re[w]=h,n.im[w]=f,n.re[u]=h,n.im[u]=-f,a.re[w]=l,a.im[w]=-o,a.re[u]=l,a.im[u]=o},convolute2DI:function(t,n,a,s){for(var o,h,f=0;f<a/2;f++)for(var l=0;l<s;l++)o=t[f*2*s+l]*n[f*2*s+l]-t[(f*2+1)*s+l]*n[(f*2+1)*s+l],h=t[f*2*s+l]*n[(f*2+1)*s+l]+t[(f*2+1)*s+l]*n[f*2*s+l],t[f*2*s+l]=o,t[(f*2+1)*s+l]=h},convolute:function(t,n,a,s,o){for(var h=new Array(s*a),f=0;f<a*s;f++)h[f]=t[f];h=this.fft2DArray(h,a,s);for(var l=n.length,u=n[0].length,w=new Array(s*a),f=0;f<s*a;f++)w[f]=0;for(var _,g,v=Math.floor((l-1)/2),k=Math.floor((u-1)/2),A=0;A<l;A++){_=(A-v+a)%a;for(var T=0;T<u;T++)g=(T-k+s)%s,w[_*s+g]=n[A][T]}w=this.fft2DArray(w,a,s);var $=a*2,D=s/2+1;return this.convolute2DI(h,w,$,D),this.ifft2DArray(h,$,D)},toRadix2:function(t,n,a){var s,o,h,f,l=a,u=n;if(!(a!==0&&(a&a-1)===0)){for(l=0;a>>++l!=0;);l=1<<l}if(!(n!==0&&(n&n-1)===0)){for(u=0;n>>++u!=0;);u=1<<u}if(u==n&&l==a)return{data:t,rows:n,cols:a};var w=new Array(u*l),_=Math.floor((u-n)/2)-n,g=Math.floor((l-a)/2)-a;for(s=0;s<u;s++)for(h=s*l,f=(s-_)%n*a,o=0;o<l;o++)w[h+o]=t[f+(o-g)%a];return{data:w,rows:u,cols:l}},crop:function(t,n,a,s,o,h){if(n==s&&a==o)return t;Object.assign({},h);var f=new Array(o*s),l=Math.floor((n-s)/2),u=Math.floor((a-o)/2),w,_,g,v;for(g=0;g<s;g++)for(w=g*o,_=(g+l)*a,v=0;v<o;v++)f[w+v]=t[_+(v+u)];return f}};return FFTUtils_1=i,FFTUtils_1}var hasRequiredSrc$2;function requireSrc$2(){return hasRequiredSrc$2||(hasRequiredSrc$2=1,src$2.FFTUtils=requireFFTUtils(),src$2.FFT=requireFftlib()),src$2}var src$1,hasRequiredSrc$1;function requireSrc$1(){if(hasRequiredSrc$1)return src$1;hasRequiredSrc$1=1;var e=requireSrc$2().FFTUtils;function i(s,o,h){var f=a(s),l=f.data,u=Object.assign({normalize:!1,divisor:1,rows:f.rows,cols:f.cols},h),w,_;if(u.rows&&u.cols)w=u.rows,_=u.cols;else throw new Error("Invalid number of rows or columns "+w+" "+_);var g=u.divisor,v,k,A=o.length,T=o[0].length;if(u.normalize)for(g=0,v=0;v<A;v++)for(k=0;k<T;k++)g+=o[v][k];if(g===0)throw new RangeError("convolution: The divisor is equal to zero");var $=e.toRadix2(l,w,_),D=e.convolute($.data,o,$.rows,$.cols);if(D=e.crop(D,$.rows,$.cols,w,_),g!=0&&g!=1)for(v=0;v<D.length;v++)D[v]/=g;return D}function t(s,o,h){var f=a(s),l=f.data,u=Object.assign({normalize:!1,divisor:1,rows:f.rows,cols:f.cols},h),w,_;if(u.rows&&u.cols)w=u.rows,_=u.cols;else throw new Error("Invalid number of rows or columns "+w+" "+_);var g=u.divisor,v=o.length,k=o[0].length,A,T,$,D,C,P,z,B,F;if(u.normalize)for(g=0,A=0;A<v;A++)for(T=0;T<k;T++)g+=o[A][T];if(g===0)throw new RangeError("convolution: The divisor is equal to zero");var L=new Array(w*_),N=Math.floor(v/2),G=Math.floor(k/2);for(D=0;D<w;D++)for($=0;$<_;$++){for(P=0,T=0;T<v;T++)for(A=0;A<k;A++)z=o[v-T-1][k-A-1],B=(D+T-N+w)%w,F=($+A-G+_)%_,C=B*_+F,P+=l[C]*z;C=D*_+$,L[C]=P/g}return L}function n(s,o,h){var f=1e3;h&&h.factor&&(f=h.factor);var l=new Array(o),u,w,_,g;f*=-1;var v=(o-1)/2,k=2*s*s;for(u=0;u<o;u++)for(l[u]=new Array(o),g=(u-v)*(u-v),w=0;w<o;w++)_=-((w-v)*(w-v)+g)/k,l[u][w]=Math.round(f*(1+_)*Math.exp(_));return l}function a(s){var o=s,h,f;if(typeof s[0]!="number"){h=s.length,f=s[0].length,o=new Array(h*f);for(var l=0;l<h;l++)for(var u=0;u<f;u++)o[l*f+u]=s[l][u]}else{var w=Math.sqrt(s.length);Number.isInteger(w)&&(h=w,f=w)}return{data:o,rows:h,cols:f}}return src$1={fft:i,direct:t,kernelFactory:{LoG:n},matrix2Array:a},src$1}var srcExports$1=requireSrc$1(),_isFinite,hasRequired_isFinite;function require_isFinite(){return hasRequired_isFinite||(hasRequired_isFinite=1,_isFinite=Number.isFinite||function(e){return!(typeof e!="number"||e!==e||e===1/0||e===-1/0)}),_isFinite}var isInteger$1,hasRequiredIsInteger;function requireIsInteger(){if(hasRequiredIsInteger)return isInteger$1;hasRequiredIsInteger=1;var e=require_isFinite();return isInteger$1=Number.isInteger||function(i){return typeof i=="number"&&e(i)&&Math.floor(i)===i},isInteger$1}var isIntegerExports=requireIsInteger();const isInteger=getDefaultExportFromCjs(isIntegerExports);function validateKernel(e){let i,t;if(Array.isArray(e))if(Array.isArray(e[0])){if((e.length&1)===0||(e[0].length&1)===0)throw new RangeError("validateKernel: Kernel rows and columns should be odd numbers");i=Math.floor(e.length/2),t=Math.floor(e[0].length/2)}else{let n=Math.sqrt(e.length);if(isInteger(n))t=i=Math.floor(Math.sqrt(e.length)/2);else throw new RangeError("validateKernel: Kernel array should be a square");let a=new Array(n);for(let s=0;s<n;s++){a[s]=new Array(n);for(let o=0;o<n;o++)a[s][o]=e[s*n+o]}e=a}else throw new Error(`validateKernel: Invalid Kernel: ${e}`);return{kernel:e,kWidth:t,kHeight:i}}function clamp(e,i){return Math.round(Math.min(Math.max(e,0),i.maxValue))}function directConvolution(e,i,t){if(t===void 0){const s=e.length+i.length-1;t=new Array(s)}fill(t);for(var n=0;n<e.length;n++)for(var a=0;a<i.length;a++)t[n+a]+=e[n]*i[a];return t}function fill(e){for(var i=0;i<e.length;i++)e[i]=0}var fft,hasRequiredFft;function requireFft(){if(hasRequiredFft)return fft;hasRequiredFft=1;function e(i){if(this.size=i|0,this.size<=1||(this.size&this.size-1)!==0)throw new Error("FFT size must be a power of two and bigger than 1");this._csize=i<<1;for(var t=new Array(this.size*2),n=0;n<t.length;n+=2){const l=Math.PI*n/this.size;t[n]=Math.cos(l),t[n+1]=-Math.sin(l)}this.table=t;for(var a=0,s=1;this.size>s;s<<=1)a++;this._width=a%2===0?a-1:a,this._bitrev=new Array(1<<this._width);for(var o=0;o<this._bitrev.length;o++){this._bitrev[o]=0;for(var h=0;h<this._width;h+=2){var f=this._width-h-2;this._bitrev[o]|=(o>>>h&3)<<f}}this._out=null,this._data=null,this._inv=0}return fft=e,e.prototype.fromComplexArray=function(t,n){for(var a=n||new Array(t.length>>>1),s=0;s<t.length;s+=2)a[s>>>1]=t[s];return a},e.prototype.createComplexArray=function(){const t=new Array(this._csize);for(var n=0;n<t.length;n++)t[n]=0;return t},e.prototype.toComplexArray=function(t,n){for(var a=n||this.createComplexArray(),s=0;s<a.length;s+=2)a[s]=t[s>>>1],a[s+1]=0;return a},e.prototype.completeSpectrum=function(t){for(var n=this._csize,a=n>>>1,s=2;s<a;s+=2)t[n-s]=t[s],t[n-s+1]=-t[s+1]},e.prototype.transform=function(t,n){if(t===n)throw new Error("Input and output buffers must be different");this._out=t,this._data=n,this._inv=0,this._transform4(),this._out=null,this._data=null},e.prototype.realTransform=function(t,n){if(t===n)throw new Error("Input and output buffers must be different");this._out=t,this._data=n,this._inv=0,this._realTransform4(),this._out=null,this._data=null},e.prototype.inverseTransform=function(t,n){if(t===n)throw new Error("Input and output buffers must be different");this._out=t,this._data=n,this._inv=1,this._transform4();for(var a=0;a<t.length;a++)t[a]/=this.size;this._out=null,this._data=null},e.prototype._transform4=function(){var t=this._out,n=this._csize,a=this._width,s=1<<a,o=n/s<<1,h,f,l=this._bitrev;if(o===4)for(h=0,f=0;h<n;h+=o,f++){const A=l[f];this._singleTransform2(h,A,s)}else for(h=0,f=0;h<n;h+=o,f++){const A=l[f];this._singleTransform4(h,A,s)}var u=this._inv?-1:1,w=this.table;for(s>>=2;s>=2;s>>=2){o=n/s<<1;var _=o>>>2;for(h=0;h<n;h+=o)for(var g=h+_,v=h,k=0;v<g;v+=2,k+=s){const A=v,T=A+_,$=T+_,D=$+_,C=t[A],P=t[A+1],z=t[T],B=t[T+1],F=t[$],L=t[$+1],N=t[D],G=t[D+1],V=C,J=P,Q=w[k],W=u*w[k+1],ne=z*Q-B*W,me=z*W+B*Q,ve=w[2*k],ye=u*w[2*k+1],Me=F*ve-L*ye,Re=F*ye+L*ve,_e=w[3*k],Be=u*w[3*k+1],Se=N*_e-G*Be,re=N*Be+G*_e,Ie=V+Me,Fe=J+Re,ke=V-Me,Ye=J-Re,Je=ne+Se,et=me+re,Ve=u*(ne-Se),tt=u*(me-re),qe=Ie+Je,De=Fe+et,nt=Ie-Je,Ge=Fe-et,Ne=ke+tt,he=Ye-Ve,Qe=ke-tt,Ze=Ye+Ve;t[A]=qe,t[A+1]=De,t[T]=Ne,t[T+1]=he,t[$]=nt,t[$+1]=Ge,t[D]=Qe,t[D+1]=Ze}}},e.prototype._singleTransform2=function(t,n,a){const s=this._out,o=this._data,h=o[n],f=o[n+1],l=o[n+a],u=o[n+a+1],w=h+l,_=f+u,g=h-l,v=f-u;s[t]=w,s[t+1]=_,s[t+2]=g,s[t+3]=v},e.prototype._singleTransform4=function(t,n,a){const s=this._out,o=this._data,h=this._inv?-1:1,f=a*2,l=a*3,u=o[n],w=o[n+1],_=o[n+a],g=o[n+a+1],v=o[n+f],k=o[n+f+1],A=o[n+l],T=o[n+l+1],$=u+v,D=w+k,C=u-v,P=w-k,z=_+A,B=g+T,F=h*(_-A),L=h*(g-T),N=$+z,G=D+B,V=C+L,J=P-F,Q=$-z,W=D-B,ne=C-L,me=P+F;s[t]=N,s[t+1]=G,s[t+2]=V,s[t+3]=J,s[t+4]=Q,s[t+5]=W,s[t+6]=ne,s[t+7]=me},e.prototype._realTransform4=function(){var t=this._out,n=this._csize,a=this._width,s=1<<a,o=n/s<<1,h,f,l=this._bitrev;if(o===4)for(h=0,f=0;h<n;h+=o,f++){const te=l[f];this._singleRealTransform2(h,te>>>1,s>>>1)}else for(h=0,f=0;h<n;h+=o,f++){const te=l[f];this._singleRealTransform4(h,te>>>1,s>>>1)}var u=this._inv?-1:1,w=this.table;for(s>>=2;s>=2;s>>=2){o=n/s<<1;var _=o>>>1,g=_>>>1,v=g>>>1;for(h=0;h<n;h+=o)for(var k=0,A=0;k<=v;k+=2,A+=s){var T=h+k,$=T+g,D=$+g,C=D+g,P=t[T],z=t[T+1],B=t[$],F=t[$+1],L=t[D],N=t[D+1],G=t[C],V=t[C+1],J=P,Q=z,W=w[A],ne=u*w[A+1],me=B*W-F*ne,ve=B*ne+F*W,ye=w[2*A],Me=u*w[2*A+1],Re=L*ye-N*Me,_e=L*Me+N*ye,Be=w[3*A],Se=u*w[3*A+1],re=G*Be-V*Se,Ie=G*Se+V*Be,Fe=J+Re,ke=Q+_e,Ye=J-Re,Je=Q-_e,et=me+re,Ve=ve+Ie,tt=u*(me-re),qe=u*(ve-Ie),De=Fe+et,nt=ke+Ve,Ge=Ye+qe,Ne=Je-tt;if(t[T]=De,t[T+1]=nt,t[$]=Ge,t[$+1]=Ne,k===0){var he=Fe-et,Qe=ke-Ve;t[D]=he,t[D+1]=Qe;continue}if(k!==v){var Ze=Ye,He=-Je,Te=Fe,lt=-ke,ot=-u*qe,Le=-u*tt,ze=-u*Ve,je=-u*et,Oe=Ze+ot,st=He+Le,Z=Te+je,ue=lt-ze,xe=h+g-k,Ae=h+_-k;t[xe]=Oe,t[xe+1]=st,t[Ae]=Z,t[Ae+1]=ue}}}},e.prototype._singleRealTransform2=function(t,n,a){const s=this._out,o=this._data,h=o[n],f=o[n+a],l=h+f,u=h-f;s[t]=l,s[t+1]=0,s[t+2]=u,s[t+3]=0},e.prototype._singleRealTransform4=function(t,n,a){const s=this._out,o=this._data,h=this._inv?-1:1,f=a*2,l=a*3,u=o[n],w=o[n+a],_=o[n+f],g=o[n+l],v=u+_,k=u-_,A=w+g,T=h*(w-g),$=v+A,D=k,C=-T,P=v-A,z=k,B=T;s[t]=$,s[t+1]=0,s[t+2]=D,s[t+3]=C,s[t+4]=P,s[t+5]=0,s[t+6]=z,s[t+7]=B},fft}requireFft();function convolutionSeparable(e,i,t,n){const a=new Array(e.length);let s,o,h,f;f=i[1],h=(f.length-1)/2,o=new Array(t+f.length-1),s=new Array(t);for(let l=0;l<n;l++){for(let u=0;u<t;u++)s[u]=e[l*t+u];directConvolution(s,f,o);for(let u=0;u<t;u++)a[l*t+u]=o[h+u]}f=i[0],h=(f.length-1)/2,o=new Array(n+f.length-1),s=new Array(n);for(let l=0;l<t;l++){for(let u=0;u<n;u++)s[u]=a[u*t+l];directConvolution(s,f,o);for(let u=0;u<n;u++)a[u*t+l]=o[h+u]}return a}var matrix$1={};const toString=Object.prototype.toString;function isAnyArray(e){const i=toString.call(e);return i.endsWith("Array]")&&!i.includes("Big")}const libEsm=Object.freeze(Object.defineProperty({__proto__:null,isAnyArray},Symbol.toStringTag,{value:"Module"})),require$$0$1=getAugmentedNamespace(libEsm);function max$1(e){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(!isAnyArray(e))throw new TypeError("input must be an array");if(e.length===0)throw new TypeError("input must not be empty");var t=i.fromIndex,n=t===void 0?0:t,a=i.toIndex,s=a===void 0?e.length:a;if(n<0||n>=e.length||!Number.isInteger(n))throw new Error("fromIndex must be a positive integer smaller than length");if(s<=n||s>e.length||!Number.isInteger(s))throw new Error("toIndex must be an integer greater than fromIndex and at most equal to length");for(var o=e[n],h=n+1;h<s;h++)e[h]>o&&(o=e[h]);return o}function min$1(e){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(!isAnyArray(e))throw new TypeError("input must be an array");if(e.length===0)throw new TypeError("input must not be empty");var t=i.fromIndex,n=t===void 0?0:t,a=i.toIndex,s=a===void 0?e.length:a;if(n<0||n>=e.length||!Number.isInteger(n))throw new Error("fromIndex must be a positive integer smaller than length");if(s<=n||s>e.length||!Number.isInteger(s))throw new Error("toIndex must be an integer greater than fromIndex and at most equal to length");for(var o=e[n],h=n+1;h<s;h++)e[h]<o&&(o=e[h]);return o}function rescale(e){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(isAnyArray(e)){if(e.length===0)throw new TypeError("input must not be empty")}else throw new TypeError("input must be an array");var t;if(i.output!==void 0){if(!isAnyArray(i.output))throw new TypeError("output option must be an array if specified");t=i.output}else t=new Array(e.length);var n=min$1(e),a=max$1(e);if(n===a)throw new RangeError("minimum and maximum input values are equal. Cannot rescale a constant array");var s=i.min,o=s===void 0?i.autoMinMax?n:0:s,h=i.max,f=h===void 0?i.autoMinMax?a:1:h;if(o>=f)throw new RangeError("min option must be smaller than max option");for(var l=(f-o)/(a-n),u=0;u<e.length;u++)t[u]=(e[u]-n)*l+o;return t}const libEs6=Object.freeze(Object.defineProperty({__proto__:null,default:rescale},Symbol.toStringTag,{value:"Module"})),require$$1=getAugmentedNamespace(libEs6);var hasRequiredMatrix;function requireMatrix(){var de,$t,oe;if(hasRequiredMatrix)return matrix$1;hasRequiredMatrix=1,Object.defineProperty(matrix$1,"__esModule",{value:!0});var e=require$$0$1,i=require$$1;const t=" ".repeat(2),n=" ".repeat(4);function a(){return s(this)}function s(M,m={}){const{maxRows:d=15,maxColumns:c=10,maxNumSize:b=8,padMinus:S="auto"}=m;return`${M.constructor.name} {
3
+ ${t}[
4
+ ${n}${o(M,d,c,b,S)}
5
+ ${t}]
6
+ ${t}rows: ${M.rows}
7
+ ${t}columns: ${M.columns}
8
+ }`}function o(M,m,d,c,b){const{rows:S,columns:O}=M,q=Math.min(S,m),X=Math.min(O,d),j=[];if(b==="auto"){b=!1;e:for(let ae=0;ae<q;ae++)for(let K=0;K<X;K++)if(M.get(ae,K)<0){b=!0;break e}}for(let ae=0;ae<q;ae++){let K=[];for(let ce=0;ce<X;ce++)K.push(h(M.get(ae,ce),c,b));j.push(`${K.join(" ")}`)}return X!==O&&(j[j.length-1]+=` ... ${O-d} more columns`),q!==S&&j.push(`... ${S-m} more rows`),j.join(`
9
+ ${n}`)}function h(M,m,d){return(M>=0&&d?` ${f(M,m-1)}`:f(M,m)).padEnd(m)}function f(M,m){let d=M.toString();if(d.length<=m)return d;let c=M.toFixed(m);if(c.length>m&&(c=M.toFixed(Math.max(0,m-(c.length-m)))),c.length<=m&&!c.startsWith("0.000")&&!c.startsWith("-0.000"))return c;let b=M.toExponential(m);return b.length>m&&(b=M.toExponential(Math.max(0,m-(b.length-m)))),b.slice(0)}function l(M,m){M.prototype.add=function(c){return typeof c=="number"?this.addS(c):this.addM(c)},M.prototype.addS=function(c){for(let b=0;b<this.rows;b++)for(let S=0;S<this.columns;S++)this.set(b,S,this.get(b,S)+c);return this},M.prototype.addM=function(c){if(c=m.checkMatrix(c),this.rows!==c.rows||this.columns!==c.columns)throw new RangeError("Matrices dimensions must be equal");for(let b=0;b<this.rows;b++)for(let S=0;S<this.columns;S++)this.set(b,S,this.get(b,S)+c.get(b,S));return this},M.add=function(c,b){return new m(c).add(b)},M.prototype.sub=function(c){return typeof c=="number"?this.subS(c):this.subM(c)},M.prototype.subS=function(c){for(let b=0;b<this.rows;b++)for(let S=0;S<this.columns;S++)this.set(b,S,this.get(b,S)-c);return this},M.prototype.subM=function(c){if(c=m.checkMatrix(c),this.rows!==c.rows||this.columns!==c.columns)throw new RangeError("Matrices dimensions must be equal");for(let b=0;b<this.rows;b++)for(let S=0;S<this.columns;S++)this.set(b,S,this.get(b,S)-c.get(b,S));return this},M.sub=function(c,b){return new m(c).sub(b)},M.prototype.subtract=M.prototype.sub,M.prototype.subtractS=M.prototype.subS,M.prototype.subtractM=M.prototype.subM,M.subtract=M.sub,M.prototype.mul=function(c){return typeof c=="number"?this.mulS(c):this.mulM(c)},M.prototype.mulS=function(c){for(let b=0;b<this.rows;b++)for(let S=0;S<this.columns;S++)this.set(b,S,this.get(b,S)*c);return this},M.prototype.mulM=function(c){if(c=m.checkMatrix(c),this.rows!==c.rows||this.columns!==c.columns)throw new RangeError("Matrices dimensions must be equal");for(let b=0;b<this.rows;b++)for(let S=0;S<this.columns;S++)this.set(b,S,this.get(b,S)*c.get(b,S));return this},M.mul=function(c,b){return new m(c).mul(b)},M.prototype.multiply=M.prototype.mul,M.prototype.multiplyS=M.prototype.mulS,M.prototype.multiplyM=M.prototype.mulM,M.multiply=M.mul,M.prototype.div=function(c){return typeof c=="number"?this.divS(c):this.divM(c)},M.prototype.divS=function(c){for(let b=0;b<this.rows;b++)for(let S=0;S<this.columns;S++)this.set(b,S,this.get(b,S)/c);return this},M.prototype.divM=function(c){if(c=m.checkMatrix(c),this.rows!==c.rows||this.columns!==c.columns)throw new RangeError("Matrices dimensions must be equal");for(let b=0;b<this.rows;b++)for(let S=0;S<this.columns;S++)this.set(b,S,this.get(b,S)/c.get(b,S));return this},M.div=function(c,b){return new m(c).div(b)},M.prototype.divide=M.prototype.div,M.prototype.divideS=M.prototype.divS,M.prototype.divideM=M.prototype.divM,M.divide=M.div,M.prototype.mod=function(c){return typeof c=="number"?this.modS(c):this.modM(c)},M.prototype.modS=function(c){for(let b=0;b<this.rows;b++)for(let S=0;S<this.columns;S++)this.set(b,S,this.get(b,S)%c);return this},M.prototype.modM=function(c){if(c=m.checkMatrix(c),this.rows!==c.rows||this.columns!==c.columns)throw new RangeError("Matrices dimensions must be equal");for(let b=0;b<this.rows;b++)for(let S=0;S<this.columns;S++)this.set(b,S,this.get(b,S)%c.get(b,S));return this},M.mod=function(c,b){return new m(c).mod(b)},M.prototype.modulus=M.prototype.mod,M.prototype.modulusS=M.prototype.modS,M.prototype.modulusM=M.prototype.modM,M.modulus=M.mod,M.prototype.and=function(c){return typeof c=="number"?this.andS(c):this.andM(c)},M.prototype.andS=function(c){for(let b=0;b<this.rows;b++)for(let S=0;S<this.columns;S++)this.set(b,S,this.get(b,S)&c);return this},M.prototype.andM=function(c){if(c=m.checkMatrix(c),this.rows!==c.rows||this.columns!==c.columns)throw new RangeError("Matrices dimensions must be equal");for(let b=0;b<this.rows;b++)for(let S=0;S<this.columns;S++)this.set(b,S,this.get(b,S)&c.get(b,S));return this},M.and=function(c,b){return new m(c).and(b)},M.prototype.or=function(c){return typeof c=="number"?this.orS(c):this.orM(c)},M.prototype.orS=function(c){for(let b=0;b<this.rows;b++)for(let S=0;S<this.columns;S++)this.set(b,S,this.get(b,S)|c);return this},M.prototype.orM=function(c){if(c=m.checkMatrix(c),this.rows!==c.rows||this.columns!==c.columns)throw new RangeError("Matrices dimensions must be equal");for(let b=0;b<this.rows;b++)for(let S=0;S<this.columns;S++)this.set(b,S,this.get(b,S)|c.get(b,S));return this},M.or=function(c,b){return new m(c).or(b)},M.prototype.xor=function(c){return typeof c=="number"?this.xorS(c):this.xorM(c)},M.prototype.xorS=function(c){for(let b=0;b<this.rows;b++)for(let S=0;S<this.columns;S++)this.set(b,S,this.get(b,S)^c);return this},M.prototype.xorM=function(c){if(c=m.checkMatrix(c),this.rows!==c.rows||this.columns!==c.columns)throw new RangeError("Matrices dimensions must be equal");for(let b=0;b<this.rows;b++)for(let S=0;S<this.columns;S++)this.set(b,S,this.get(b,S)^c.get(b,S));return this},M.xor=function(c,b){return new m(c).xor(b)},M.prototype.leftShift=function(c){return typeof c=="number"?this.leftShiftS(c):this.leftShiftM(c)},M.prototype.leftShiftS=function(c){for(let b=0;b<this.rows;b++)for(let S=0;S<this.columns;S++)this.set(b,S,this.get(b,S)<<c);return this},M.prototype.leftShiftM=function(c){if(c=m.checkMatrix(c),this.rows!==c.rows||this.columns!==c.columns)throw new RangeError("Matrices dimensions must be equal");for(let b=0;b<this.rows;b++)for(let S=0;S<this.columns;S++)this.set(b,S,this.get(b,S)<<c.get(b,S));return this},M.leftShift=function(c,b){return new m(c).leftShift(b)},M.prototype.signPropagatingRightShift=function(c){return typeof c=="number"?this.signPropagatingRightShiftS(c):this.signPropagatingRightShiftM(c)},M.prototype.signPropagatingRightShiftS=function(c){for(let b=0;b<this.rows;b++)for(let S=0;S<this.columns;S++)this.set(b,S,this.get(b,S)>>c);return this},M.prototype.signPropagatingRightShiftM=function(c){if(c=m.checkMatrix(c),this.rows!==c.rows||this.columns!==c.columns)throw new RangeError("Matrices dimensions must be equal");for(let b=0;b<this.rows;b++)for(let S=0;S<this.columns;S++)this.set(b,S,this.get(b,S)>>c.get(b,S));return this},M.signPropagatingRightShift=function(c,b){return new m(c).signPropagatingRightShift(b)},M.prototype.rightShift=function(c){return typeof c=="number"?this.rightShiftS(c):this.rightShiftM(c)},M.prototype.rightShiftS=function(c){for(let b=0;b<this.rows;b++)for(let S=0;S<this.columns;S++)this.set(b,S,this.get(b,S)>>>c);return this},M.prototype.rightShiftM=function(c){if(c=m.checkMatrix(c),this.rows!==c.rows||this.columns!==c.columns)throw new RangeError("Matrices dimensions must be equal");for(let b=0;b<this.rows;b++)for(let S=0;S<this.columns;S++)this.set(b,S,this.get(b,S)>>>c.get(b,S));return this},M.rightShift=function(c,b){return new m(c).rightShift(b)},M.prototype.zeroFillRightShift=M.prototype.rightShift,M.prototype.zeroFillRightShiftS=M.prototype.rightShiftS,M.prototype.zeroFillRightShiftM=M.prototype.rightShiftM,M.zeroFillRightShift=M.rightShift,M.prototype.not=function(){for(let c=0;c<this.rows;c++)for(let b=0;b<this.columns;b++)this.set(c,b,~this.get(c,b));return this},M.not=function(c){return new m(c).not()},M.prototype.abs=function(){for(let c=0;c<this.rows;c++)for(let b=0;b<this.columns;b++)this.set(c,b,Math.abs(this.get(c,b)));return this},M.abs=function(c){return new m(c).abs()},M.prototype.acos=function(){for(let c=0;c<this.rows;c++)for(let b=0;b<this.columns;b++)this.set(c,b,Math.acos(this.get(c,b)));return this},M.acos=function(c){return new m(c).acos()},M.prototype.acosh=function(){for(let c=0;c<this.rows;c++)for(let b=0;b<this.columns;b++)this.set(c,b,Math.acosh(this.get(c,b)));return this},M.acosh=function(c){return new m(c).acosh()},M.prototype.asin=function(){for(let c=0;c<this.rows;c++)for(let b=0;b<this.columns;b++)this.set(c,b,Math.asin(this.get(c,b)));return this},M.asin=function(c){return new m(c).asin()},M.prototype.asinh=function(){for(let c=0;c<this.rows;c++)for(let b=0;b<this.columns;b++)this.set(c,b,Math.asinh(this.get(c,b)));return this},M.asinh=function(c){return new m(c).asinh()},M.prototype.atan=function(){for(let c=0;c<this.rows;c++)for(let b=0;b<this.columns;b++)this.set(c,b,Math.atan(this.get(c,b)));return this},M.atan=function(c){return new m(c).atan()},M.prototype.atanh=function(){for(let c=0;c<this.rows;c++)for(let b=0;b<this.columns;b++)this.set(c,b,Math.atanh(this.get(c,b)));return this},M.atanh=function(c){return new m(c).atanh()},M.prototype.cbrt=function(){for(let c=0;c<this.rows;c++)for(let b=0;b<this.columns;b++)this.set(c,b,Math.cbrt(this.get(c,b)));return this},M.cbrt=function(c){return new m(c).cbrt()},M.prototype.ceil=function(){for(let c=0;c<this.rows;c++)for(let b=0;b<this.columns;b++)this.set(c,b,Math.ceil(this.get(c,b)));return this},M.ceil=function(c){return new m(c).ceil()},M.prototype.clz32=function(){for(let c=0;c<this.rows;c++)for(let b=0;b<this.columns;b++)this.set(c,b,Math.clz32(this.get(c,b)));return this},M.clz32=function(c){return new m(c).clz32()},M.prototype.cos=function(){for(let c=0;c<this.rows;c++)for(let b=0;b<this.columns;b++)this.set(c,b,Math.cos(this.get(c,b)));return this},M.cos=function(c){return new m(c).cos()},M.prototype.cosh=function(){for(let c=0;c<this.rows;c++)for(let b=0;b<this.columns;b++)this.set(c,b,Math.cosh(this.get(c,b)));return this},M.cosh=function(c){return new m(c).cosh()},M.prototype.exp=function(){for(let c=0;c<this.rows;c++)for(let b=0;b<this.columns;b++)this.set(c,b,Math.exp(this.get(c,b)));return this},M.exp=function(c){return new m(c).exp()},M.prototype.expm1=function(){for(let c=0;c<this.rows;c++)for(let b=0;b<this.columns;b++)this.set(c,b,Math.expm1(this.get(c,b)));return this},M.expm1=function(c){return new m(c).expm1()},M.prototype.floor=function(){for(let c=0;c<this.rows;c++)for(let b=0;b<this.columns;b++)this.set(c,b,Math.floor(this.get(c,b)));return this},M.floor=function(c){return new m(c).floor()},M.prototype.fround=function(){for(let c=0;c<this.rows;c++)for(let b=0;b<this.columns;b++)this.set(c,b,Math.fround(this.get(c,b)));return this},M.fround=function(c){return new m(c).fround()},M.prototype.log=function(){for(let c=0;c<this.rows;c++)for(let b=0;b<this.columns;b++)this.set(c,b,Math.log(this.get(c,b)));return this},M.log=function(c){return new m(c).log()},M.prototype.log1p=function(){for(let c=0;c<this.rows;c++)for(let b=0;b<this.columns;b++)this.set(c,b,Math.log1p(this.get(c,b)));return this},M.log1p=function(c){return new m(c).log1p()},M.prototype.log10=function(){for(let c=0;c<this.rows;c++)for(let b=0;b<this.columns;b++)this.set(c,b,Math.log10(this.get(c,b)));return this},M.log10=function(c){return new m(c).log10()},M.prototype.log2=function(){for(let c=0;c<this.rows;c++)for(let b=0;b<this.columns;b++)this.set(c,b,Math.log2(this.get(c,b)));return this},M.log2=function(c){return new m(c).log2()},M.prototype.round=function(){for(let c=0;c<this.rows;c++)for(let b=0;b<this.columns;b++)this.set(c,b,Math.round(this.get(c,b)));return this},M.round=function(c){return new m(c).round()},M.prototype.sign=function(){for(let c=0;c<this.rows;c++)for(let b=0;b<this.columns;b++)this.set(c,b,Math.sign(this.get(c,b)));return this},M.sign=function(c){return new m(c).sign()},M.prototype.sin=function(){for(let c=0;c<this.rows;c++)for(let b=0;b<this.columns;b++)this.set(c,b,Math.sin(this.get(c,b)));return this},M.sin=function(c){return new m(c).sin()},M.prototype.sinh=function(){for(let c=0;c<this.rows;c++)for(let b=0;b<this.columns;b++)this.set(c,b,Math.sinh(this.get(c,b)));return this},M.sinh=function(c){return new m(c).sinh()},M.prototype.sqrt=function(){for(let c=0;c<this.rows;c++)for(let b=0;b<this.columns;b++)this.set(c,b,Math.sqrt(this.get(c,b)));return this},M.sqrt=function(c){return new m(c).sqrt()},M.prototype.tan=function(){for(let c=0;c<this.rows;c++)for(let b=0;b<this.columns;b++)this.set(c,b,Math.tan(this.get(c,b)));return this},M.tan=function(c){return new m(c).tan()},M.prototype.tanh=function(){for(let c=0;c<this.rows;c++)for(let b=0;b<this.columns;b++)this.set(c,b,Math.tanh(this.get(c,b)));return this},M.tanh=function(c){return new m(c).tanh()},M.prototype.trunc=function(){for(let c=0;c<this.rows;c++)for(let b=0;b<this.columns;b++)this.set(c,b,Math.trunc(this.get(c,b)));return this},M.trunc=function(c){return new m(c).trunc()},M.pow=function(c,b){return new m(c).pow(b)},M.prototype.pow=function(c){return typeof c=="number"?this.powS(c):this.powM(c)},M.prototype.powS=function(c){for(let b=0;b<this.rows;b++)for(let S=0;S<this.columns;S++)this.set(b,S,this.get(b,S)**c);return this},M.prototype.powM=function(c){if(c=m.checkMatrix(c),this.rows!==c.rows||this.columns!==c.columns)throw new RangeError("Matrices dimensions must be equal");for(let b=0;b<this.rows;b++)for(let S=0;S<this.columns;S++)this.set(b,S,this.get(b,S)**c.get(b,S));return this}}function u(M,m,d){let c=d?M.rows:M.rows-1;if(m<0||m>c)throw new RangeError("Row index out of range")}function w(M,m,d){let c=d?M.columns:M.columns-1;if(m<0||m>c)throw new RangeError("Column index out of range")}function _(M,m){if(m.to1DArray&&(m=m.to1DArray()),m.length!==M.columns)throw new RangeError("vector size must be the same as the number of columns");return m}function g(M,m){if(m.to1DArray&&(m=m.to1DArray()),m.length!==M.rows)throw new RangeError("vector size must be the same as the number of rows");return m}function v(M,m){if(!e.isAnyArray(m))throw new TypeError("row indices must be an array");for(let d=0;d<m.length;d++)if(m[d]<0||m[d]>=M.rows)throw new RangeError("row indices are out of range")}function k(M,m){if(!e.isAnyArray(m))throw new TypeError("column indices must be an array");for(let d=0;d<m.length;d++)if(m[d]<0||m[d]>=M.columns)throw new RangeError("column indices are out of range")}function A(M,m,d,c,b){if(arguments.length!==5)throw new RangeError("expected 4 arguments");if($("startRow",m),$("endRow",d),$("startColumn",c),$("endColumn",b),m>d||c>b||m<0||m>=M.rows||d<0||d>=M.rows||c<0||c>=M.columns||b<0||b>=M.columns)throw new RangeError("Submatrix indices are out of range")}function T(M,m=0){let d=[];for(let c=0;c<M;c++)d.push(m);return d}function $(M,m){if(typeof m!="number")throw new TypeError(`${M} must be a number`)}function D(M){if(M.isEmpty())throw new Error("Empty matrix has no elements to index")}function C(M){let m=T(M.rows);for(let d=0;d<M.rows;++d)for(let c=0;c<M.columns;++c)m[d]+=M.get(d,c);return m}function P(M){let m=T(M.columns);for(let d=0;d<M.rows;++d)for(let c=0;c<M.columns;++c)m[c]+=M.get(d,c);return m}function z(M){let m=0;for(let d=0;d<M.rows;d++)for(let c=0;c<M.columns;c++)m+=M.get(d,c);return m}function B(M){let m=T(M.rows,1);for(let d=0;d<M.rows;++d)for(let c=0;c<M.columns;++c)m[d]*=M.get(d,c);return m}function F(M){let m=T(M.columns,1);for(let d=0;d<M.rows;++d)for(let c=0;c<M.columns;++c)m[c]*=M.get(d,c);return m}function L(M){let m=1;for(let d=0;d<M.rows;d++)for(let c=0;c<M.columns;c++)m*=M.get(d,c);return m}function N(M,m,d){const c=M.rows,b=M.columns,S=[];for(let O=0;O<c;O++){let q=0,X=0,j=0;for(let ae=0;ae<b;ae++)j=M.get(O,ae)-d[O],q+=j,X+=j*j;m?S.push((X-q*q/b)/(b-1)):S.push((X-q*q/b)/b)}return S}function G(M,m,d){const c=M.rows,b=M.columns,S=[];for(let O=0;O<b;O++){let q=0,X=0,j=0;for(let ae=0;ae<c;ae++)j=M.get(ae,O)-d[O],q+=j,X+=j*j;m?S.push((X-q*q/c)/(c-1)):S.push((X-q*q/c)/c)}return S}function V(M,m,d){const c=M.rows,b=M.columns,S=c*b;let O=0,q=0,X=0;for(let j=0;j<c;j++)for(let ae=0;ae<b;ae++)X=M.get(j,ae)-d,O+=X,q+=X*X;return m?(q-O*O/S)/(S-1):(q-O*O/S)/S}function J(M,m){for(let d=0;d<M.rows;d++)for(let c=0;c<M.columns;c++)M.set(d,c,M.get(d,c)-m[d])}function Q(M,m){for(let d=0;d<M.rows;d++)for(let c=0;c<M.columns;c++)M.set(d,c,M.get(d,c)-m[c])}function W(M,m){for(let d=0;d<M.rows;d++)for(let c=0;c<M.columns;c++)M.set(d,c,M.get(d,c)-m)}function ne(M){const m=[];for(let d=0;d<M.rows;d++){let c=0;for(let b=0;b<M.columns;b++)c+=M.get(d,b)**2/(M.columns-1);m.push(Math.sqrt(c))}return m}function me(M,m){for(let d=0;d<M.rows;d++)for(let c=0;c<M.columns;c++)M.set(d,c,M.get(d,c)/m[d])}function ve(M){const m=[];for(let d=0;d<M.columns;d++){let c=0;for(let b=0;b<M.rows;b++)c+=M.get(b,d)**2/(M.rows-1);m.push(Math.sqrt(c))}return m}function ye(M,m){for(let d=0;d<M.rows;d++)for(let c=0;c<M.columns;c++)M.set(d,c,M.get(d,c)/m[c])}function Me(M){const m=M.size-1;let d=0;for(let c=0;c<M.columns;c++)for(let b=0;b<M.rows;b++)d+=M.get(b,c)**2/m;return Math.sqrt(d)}function Re(M,m){for(let d=0;d<M.rows;d++)for(let c=0;c<M.columns;c++)M.set(d,c,M.get(d,c)/m)}class _e{static from1DArray(m,d,c){if(m*d!==c.length)throw new RangeError("data length does not match given dimensions");let S=new re(m,d);for(let O=0;O<m;O++)for(let q=0;q<d;q++)S.set(O,q,c[O*d+q]);return S}static rowVector(m){let d=new re(1,m.length);for(let c=0;c<m.length;c++)d.set(0,c,m[c]);return d}static columnVector(m){let d=new re(m.length,1);for(let c=0;c<m.length;c++)d.set(c,0,m[c]);return d}static zeros(m,d){return new re(m,d)}static ones(m,d){return new re(m,d).fill(1)}static rand(m,d,c={}){if(typeof c!="object")throw new TypeError("options must be an object");const{random:b=Math.random}=c;let S=new re(m,d);for(let O=0;O<m;O++)for(let q=0;q<d;q++)S.set(O,q,b());return S}static randInt(m,d,c={}){if(typeof c!="object")throw new TypeError("options must be an object");const{min:b=0,max:S=1e3,random:O=Math.random}=c;if(!Number.isInteger(b))throw new TypeError("min must be an integer");if(!Number.isInteger(S))throw new TypeError("max must be an integer");if(b>=S)throw new RangeError("min must be smaller than max");let q=S-b,X=new re(m,d);for(let j=0;j<m;j++)for(let ae=0;ae<d;ae++){let K=b+Math.round(O()*q);X.set(j,ae,K)}return X}static eye(m,d,c){d===void 0&&(d=m),c===void 0&&(c=1);let b=Math.min(m,d),S=this.zeros(m,d);for(let O=0;O<b;O++)S.set(O,O,c);return S}static diag(m,d,c){let b=m.length;d===void 0&&(d=b),c===void 0&&(c=d);let S=Math.min(b,d,c),O=this.zeros(d,c);for(let q=0;q<S;q++)O.set(q,q,m[q]);return O}static min(m,d){m=this.checkMatrix(m),d=this.checkMatrix(d);let c=m.rows,b=m.columns,S=new re(c,b);for(let O=0;O<c;O++)for(let q=0;q<b;q++)S.set(O,q,Math.min(m.get(O,q),d.get(O,q)));return S}static max(m,d){m=this.checkMatrix(m),d=this.checkMatrix(d);let c=m.rows,b=m.columns,S=new this(c,b);for(let O=0;O<c;O++)for(let q=0;q<b;q++)S.set(O,q,Math.max(m.get(O,q),d.get(O,q)));return S}static checkMatrix(m){return _e.isMatrix(m)?m:new re(m)}static isMatrix(m){return m!=null&&m.klass==="Matrix"}get size(){return this.rows*this.columns}apply(m){if(typeof m!="function")throw new TypeError("callback must be a function");for(let d=0;d<this.rows;d++)for(let c=0;c<this.columns;c++)m.call(this,d,c);return this}to1DArray(){let m=[];for(let d=0;d<this.rows;d++)for(let c=0;c<this.columns;c++)m.push(this.get(d,c));return m}to2DArray(){let m=[];for(let d=0;d<this.rows;d++){m.push([]);for(let c=0;c<this.columns;c++)m[d].push(this.get(d,c))}return m}toJSON(){return this.to2DArray()}isRowVector(){return this.rows===1}isColumnVector(){return this.columns===1}isVector(){return this.rows===1||this.columns===1}isSquare(){return this.rows===this.columns}isEmpty(){return this.rows===0||this.columns===0}isSymmetric(){if(this.isSquare()){for(let m=0;m<this.rows;m++)for(let d=0;d<=m;d++)if(this.get(m,d)!==this.get(d,m))return!1;return!0}return!1}isDistance(){if(!this.isSymmetric())return!1;for(let m=0;m<this.rows;m++)if(this.get(m,m)!==0)return!1;return!0}isEchelonForm(){let m=0,d=0,c=-1,b=!0,S=!1;for(;m<this.rows&&b;){for(d=0,S=!1;d<this.columns&&S===!1;)this.get(m,d)===0?d++:this.get(m,d)===1&&d>c?(S=!0,c=d):(b=!1,S=!0);m++}return b}isReducedEchelonForm(){let m=0,d=0,c=-1,b=!0,S=!1;for(;m<this.rows&&b;){for(d=0,S=!1;d<this.columns&&S===!1;)this.get(m,d)===0?d++:this.get(m,d)===1&&d>c?(S=!0,c=d):(b=!1,S=!0);for(let O=d+1;O<this.rows;O++)this.get(m,O)!==0&&(b=!1);m++}return b}echelonForm(){let m=this.clone(),d=0,c=0;for(;d<m.rows&&c<m.columns;){let b=d;for(let S=d;S<m.rows;S++)m.get(S,c)>m.get(b,c)&&(b=S);if(m.get(b,c)===0)c++;else{m.swapRows(d,b);let S=m.get(d,c);for(let O=c;O<m.columns;O++)m.set(d,O,m.get(d,O)/S);for(let O=d+1;O<m.rows;O++){let q=m.get(O,c)/m.get(d,c);m.set(O,c,0);for(let X=c+1;X<m.columns;X++)m.set(O,X,m.get(O,X)-m.get(d,X)*q)}d++,c++}}return m}reducedEchelonForm(){let m=this.echelonForm(),d=m.columns,c=m.rows,b=c-1;for(;b>=0;)if(m.maxRow(b)===0)b--;else{let S=0,O=!1;for(;S<c&&O===!1;)m.get(b,S)===1?O=!0:S++;for(let q=0;q<b;q++){let X=m.get(q,S);for(let j=S;j<d;j++){let ae=m.get(q,j)-X*m.get(b,j);m.set(q,j,ae)}}b--}return m}set(){throw new Error("set method is unimplemented")}get(){throw new Error("get method is unimplemented")}repeat(m={}){if(typeof m!="object")throw new TypeError("options must be an object");const{rows:d=1,columns:c=1}=m;if(!Number.isInteger(d)||d<=0)throw new TypeError("rows must be a positive integer");if(!Number.isInteger(c)||c<=0)throw new TypeError("columns must be a positive integer");let b=new re(this.rows*d,this.columns*c);for(let S=0;S<d;S++)for(let O=0;O<c;O++)b.setSubMatrix(this,this.rows*S,this.columns*O);return b}fill(m){for(let d=0;d<this.rows;d++)for(let c=0;c<this.columns;c++)this.set(d,c,m);return this}neg(){return this.mulS(-1)}getRow(m){u(this,m);let d=[];for(let c=0;c<this.columns;c++)d.push(this.get(m,c));return d}getRowVector(m){return re.rowVector(this.getRow(m))}setRow(m,d){u(this,m),d=_(this,d);for(let c=0;c<this.columns;c++)this.set(m,c,d[c]);return this}swapRows(m,d){u(this,m),u(this,d);for(let c=0;c<this.columns;c++){let b=this.get(m,c);this.set(m,c,this.get(d,c)),this.set(d,c,b)}return this}getColumn(m){w(this,m);let d=[];for(let c=0;c<this.rows;c++)d.push(this.get(c,m));return d}getColumnVector(m){return re.columnVector(this.getColumn(m))}setColumn(m,d){w(this,m),d=g(this,d);for(let c=0;c<this.rows;c++)this.set(c,m,d[c]);return this}swapColumns(m,d){w(this,m),w(this,d);for(let c=0;c<this.rows;c++){let b=this.get(c,m);this.set(c,m,this.get(c,d)),this.set(c,d,b)}return this}addRowVector(m){m=_(this,m);for(let d=0;d<this.rows;d++)for(let c=0;c<this.columns;c++)this.set(d,c,this.get(d,c)+m[c]);return this}subRowVector(m){m=_(this,m);for(let d=0;d<this.rows;d++)for(let c=0;c<this.columns;c++)this.set(d,c,this.get(d,c)-m[c]);return this}mulRowVector(m){m=_(this,m);for(let d=0;d<this.rows;d++)for(let c=0;c<this.columns;c++)this.set(d,c,this.get(d,c)*m[c]);return this}divRowVector(m){m=_(this,m);for(let d=0;d<this.rows;d++)for(let c=0;c<this.columns;c++)this.set(d,c,this.get(d,c)/m[c]);return this}addColumnVector(m){m=g(this,m);for(let d=0;d<this.rows;d++)for(let c=0;c<this.columns;c++)this.set(d,c,this.get(d,c)+m[d]);return this}subColumnVector(m){m=g(this,m);for(let d=0;d<this.rows;d++)for(let c=0;c<this.columns;c++)this.set(d,c,this.get(d,c)-m[d]);return this}mulColumnVector(m){m=g(this,m);for(let d=0;d<this.rows;d++)for(let c=0;c<this.columns;c++)this.set(d,c,this.get(d,c)*m[d]);return this}divColumnVector(m){m=g(this,m);for(let d=0;d<this.rows;d++)for(let c=0;c<this.columns;c++)this.set(d,c,this.get(d,c)/m[d]);return this}mulRow(m,d){u(this,m);for(let c=0;c<this.columns;c++)this.set(m,c,this.get(m,c)*d);return this}mulColumn(m,d){w(this,m);for(let c=0;c<this.rows;c++)this.set(c,m,this.get(c,m)*d);return this}max(m){if(this.isEmpty())return NaN;switch(m){case"row":{const d=new Array(this.rows).fill(Number.NEGATIVE_INFINITY);for(let c=0;c<this.rows;c++)for(let b=0;b<this.columns;b++)this.get(c,b)>d[c]&&(d[c]=this.get(c,b));return d}case"column":{const d=new Array(this.columns).fill(Number.NEGATIVE_INFINITY);for(let c=0;c<this.rows;c++)for(let b=0;b<this.columns;b++)this.get(c,b)>d[b]&&(d[b]=this.get(c,b));return d}case void 0:{let d=this.get(0,0);for(let c=0;c<this.rows;c++)for(let b=0;b<this.columns;b++)this.get(c,b)>d&&(d=this.get(c,b));return d}default:throw new Error(`invalid option: ${m}`)}}maxIndex(){D(this);let m=this.get(0,0),d=[0,0];for(let c=0;c<this.rows;c++)for(let b=0;b<this.columns;b++)this.get(c,b)>m&&(m=this.get(c,b),d[0]=c,d[1]=b);return d}min(m){if(this.isEmpty())return NaN;switch(m){case"row":{const d=new Array(this.rows).fill(Number.POSITIVE_INFINITY);for(let c=0;c<this.rows;c++)for(let b=0;b<this.columns;b++)this.get(c,b)<d[c]&&(d[c]=this.get(c,b));return d}case"column":{const d=new Array(this.columns).fill(Number.POSITIVE_INFINITY);for(let c=0;c<this.rows;c++)for(let b=0;b<this.columns;b++)this.get(c,b)<d[b]&&(d[b]=this.get(c,b));return d}case void 0:{let d=this.get(0,0);for(let c=0;c<this.rows;c++)for(let b=0;b<this.columns;b++)this.get(c,b)<d&&(d=this.get(c,b));return d}default:throw new Error(`invalid option: ${m}`)}}minIndex(){D(this);let m=this.get(0,0),d=[0,0];for(let c=0;c<this.rows;c++)for(let b=0;b<this.columns;b++)this.get(c,b)<m&&(m=this.get(c,b),d[0]=c,d[1]=b);return d}maxRow(m){if(u(this,m),this.isEmpty())return NaN;let d=this.get(m,0);for(let c=1;c<this.columns;c++)this.get(m,c)>d&&(d=this.get(m,c));return d}maxRowIndex(m){u(this,m),D(this);let d=this.get(m,0),c=[m,0];for(let b=1;b<this.columns;b++)this.get(m,b)>d&&(d=this.get(m,b),c[1]=b);return c}minRow(m){if(u(this,m),this.isEmpty())return NaN;let d=this.get(m,0);for(let c=1;c<this.columns;c++)this.get(m,c)<d&&(d=this.get(m,c));return d}minRowIndex(m){u(this,m),D(this);let d=this.get(m,0),c=[m,0];for(let b=1;b<this.columns;b++)this.get(m,b)<d&&(d=this.get(m,b),c[1]=b);return c}maxColumn(m){if(w(this,m),this.isEmpty())return NaN;let d=this.get(0,m);for(let c=1;c<this.rows;c++)this.get(c,m)>d&&(d=this.get(c,m));return d}maxColumnIndex(m){w(this,m),D(this);let d=this.get(0,m),c=[0,m];for(let b=1;b<this.rows;b++)this.get(b,m)>d&&(d=this.get(b,m),c[0]=b);return c}minColumn(m){if(w(this,m),this.isEmpty())return NaN;let d=this.get(0,m);for(let c=1;c<this.rows;c++)this.get(c,m)<d&&(d=this.get(c,m));return d}minColumnIndex(m){w(this,m),D(this);let d=this.get(0,m),c=[0,m];for(let b=1;b<this.rows;b++)this.get(b,m)<d&&(d=this.get(b,m),c[0]=b);return c}diag(){let m=Math.min(this.rows,this.columns),d=[];for(let c=0;c<m;c++)d.push(this.get(c,c));return d}norm(m="frobenius"){switch(m){case"max":return this.max();case"frobenius":return Math.sqrt(this.dot(this));default:throw new RangeError(`unknown norm type: ${m}`)}}cumulativeSum(){let m=0;for(let d=0;d<this.rows;d++)for(let c=0;c<this.columns;c++)m+=this.get(d,c),this.set(d,c,m);return this}dot(m){_e.isMatrix(m)&&(m=m.to1DArray());let d=this.to1DArray();if(d.length!==m.length)throw new RangeError("vectors do not have the same size");let c=0;for(let b=0;b<d.length;b++)c+=d[b]*m[b];return c}mmul(m){m=re.checkMatrix(m);let d=this.rows,c=this.columns,b=m.columns,S=new re(d,b),O=new Float64Array(c);for(let q=0;q<b;q++){for(let X=0;X<c;X++)O[X]=m.get(X,q);for(let X=0;X<d;X++){let j=0;for(let ae=0;ae<c;ae++)j+=this.get(X,ae)*O[ae];S.set(X,q,j)}}return S}mpow(m){if(!this.isSquare())throw new RangeError("Matrix must be square");if(!Number.isInteger(m)||m<0)throw new RangeError("Exponent must be a non-negative integer");let d=re.eye(this.rows),c=this;for(let b=m;b>=1;b/=2)(b&1)!==0&&(d=d.mmul(c)),c=c.mmul(c);return d}strassen2x2(m){m=re.checkMatrix(m);let d=new re(2,2);const c=this.get(0,0),b=m.get(0,0),S=this.get(0,1),O=m.get(0,1),q=this.get(1,0),X=m.get(1,0),j=this.get(1,1),ae=m.get(1,1),K=(c+j)*(b+ae),ce=(q+j)*b,be=c*(O-ae),le=j*(X-b),ge=(c+S)*ae,Ue=(q-c)*(b+O),ie=(S-j)*(X+ae),$e=K+le-ge+ie,Xe=be+ge,ht=ce+le,ft=K-ce+be+Ue;return d.set(0,0,$e),d.set(0,1,Xe),d.set(1,0,ht),d.set(1,1,ft),d}strassen3x3(m){m=re.checkMatrix(m);let d=new re(3,3);const c=this.get(0,0),b=this.get(0,1),S=this.get(0,2),O=this.get(1,0),q=this.get(1,1),X=this.get(1,2),j=this.get(2,0),ae=this.get(2,1),K=this.get(2,2),ce=m.get(0,0),be=m.get(0,1),le=m.get(0,2),ge=m.get(1,0),Ue=m.get(1,1),ie=m.get(1,2),$e=m.get(2,0),Xe=m.get(2,1),ht=m.get(2,2),ft=(c+b+S-O-q-ae-K)*Ue,gt=(c-O)*(-be+Ue),rt=q*(-ce+be+ge-Ue-ie-$e+ht),at=(-c+O+q)*(ce-be+Ue),mt=(O+q)*(-ce+be),se=c*ce,Ce=(-c+j+ae)*(ce-le+ie),Ke=(-c+j)*(le-ie),Pe=(j+ae)*(-ce+le),_t=(c+b+S-q-X-j-ae)*ie,dt=ae*(-ce+le+ge-Ue-ie-$e+Xe),pt=(-S+ae+K)*(Ue+$e-Xe),xt=(S-K)*(Ue-Xe),vt=S*$e,St=(ae+K)*(-$e+Xe),wt=(-S+q+X)*(ie+$e-ht),At=(S-X)*(ie-ht),Rt=(q+X)*(-$e+ht),ut=b*ge,yt=X*Xe,Et=O*le,Mt=j*be,bt=K*ht,Ft=se+vt+ut,Nt=ft+at+mt+se+pt+vt+St,Ut=se+Ce+Pe+_t+vt+wt+Rt,Ot=gt+rt+at+se+vt+wt+At,Lt=gt+at+mt+se+yt,zt=vt+wt+At+Rt+Et,qt=se+Ce+Ke+dt+pt+xt+vt,Gt=pt+xt+vt+St+Mt,Ht=se+Ce+Ke+Pe+bt;return d.set(0,0,Ft),d.set(0,1,Nt),d.set(0,2,Ut),d.set(1,0,Ot),d.set(1,1,Lt),d.set(1,2,zt),d.set(2,0,qt),d.set(2,1,Gt),d.set(2,2,Ht),d}mmulStrassen(m){m=re.checkMatrix(m);let d=this.clone(),c=d.rows,b=d.columns,S=m.rows,O=m.columns;b!==S&&console.warn(`Multiplying ${c} x ${b} and ${S} x ${O} matrix: dimensions do not match.`);function q(K,ce,be){let le=K.rows,ge=K.columns;if(le===ce&&ge===be)return K;{let Ue=_e.zeros(ce,be);return Ue=Ue.setSubMatrix(K,0,0),Ue}}let X=Math.max(c,S),j=Math.max(b,O);d=q(d,X,j),m=q(m,X,j);function ae(K,ce,be,le){if(be<=512||le<=512)return K.mmul(ce);be%2===1&&le%2===1?(K=q(K,be+1,le+1),ce=q(ce,be+1,le+1)):be%2===1?(K=q(K,be+1,le),ce=q(ce,be+1,le)):le%2===1&&(K=q(K,be,le+1),ce=q(ce,be,le+1));let ge=parseInt(K.rows/2,10),Ue=parseInt(K.columns/2,10),ie=K.subMatrix(0,ge-1,0,Ue-1),$e=ce.subMatrix(0,ge-1,0,Ue-1),Xe=K.subMatrix(0,ge-1,Ue,K.columns-1),ht=ce.subMatrix(0,ge-1,Ue,ce.columns-1),ft=K.subMatrix(ge,K.rows-1,0,Ue-1),gt=ce.subMatrix(ge,ce.rows-1,0,Ue-1),rt=K.subMatrix(ge,K.rows-1,Ue,K.columns-1),at=ce.subMatrix(ge,ce.rows-1,Ue,ce.columns-1),mt=ae(_e.add(ie,rt),_e.add($e,at),ge,Ue),se=ae(_e.add(ft,rt),$e,ge,Ue),Ce=ae(ie,_e.sub(ht,at),ge,Ue),Ke=ae(rt,_e.sub(gt,$e),ge,Ue),Pe=ae(_e.add(ie,Xe),at,ge,Ue),_t=ae(_e.sub(ft,ie),_e.add($e,ht),ge,Ue),dt=ae(_e.sub(Xe,rt),_e.add(gt,at),ge,Ue),pt=_e.add(mt,Ke);pt.sub(Pe),pt.add(dt);let xt=_e.add(Ce,Pe),vt=_e.add(se,Ke),St=_e.sub(mt,se);St.add(Ce),St.add(_t);let wt=_e.zeros(2*pt.rows,2*pt.columns);return wt=wt.setSubMatrix(pt,0,0),wt=wt.setSubMatrix(xt,pt.rows,0),wt=wt.setSubMatrix(vt,0,pt.columns),wt=wt.setSubMatrix(St,pt.rows,pt.columns),wt.subMatrix(0,be-1,0,le-1)}return ae(d,m,X,j)}scaleRows(m={}){if(typeof m!="object")throw new TypeError("options must be an object");const{min:d=0,max:c=1}=m;if(!Number.isFinite(d))throw new TypeError("min must be a number");if(!Number.isFinite(c))throw new TypeError("max must be a number");if(d>=c)throw new RangeError("min must be smaller than max");let b=new re(this.rows,this.columns);for(let S=0;S<this.rows;S++){const O=this.getRow(S);O.length>0&&i(O,{min:d,max:c,output:O}),b.setRow(S,O)}return b}scaleColumns(m={}){if(typeof m!="object")throw new TypeError("options must be an object");const{min:d=0,max:c=1}=m;if(!Number.isFinite(d))throw new TypeError("min must be a number");if(!Number.isFinite(c))throw new TypeError("max must be a number");if(d>=c)throw new RangeError("min must be smaller than max");let b=new re(this.rows,this.columns);for(let S=0;S<this.columns;S++){const O=this.getColumn(S);O.length&&i(O,{min:d,max:c,output:O}),b.setColumn(S,O)}return b}flipRows(){const m=Math.ceil(this.columns/2);for(let d=0;d<this.rows;d++)for(let c=0;c<m;c++){let b=this.get(d,c),S=this.get(d,this.columns-1-c);this.set(d,c,S),this.set(d,this.columns-1-c,b)}return this}flipColumns(){const m=Math.ceil(this.rows/2);for(let d=0;d<this.columns;d++)for(let c=0;c<m;c++){let b=this.get(c,d),S=this.get(this.rows-1-c,d);this.set(c,d,S),this.set(this.rows-1-c,d,b)}return this}kroneckerProduct(m){m=re.checkMatrix(m);let d=this.rows,c=this.columns,b=m.rows,S=m.columns,O=new re(d*b,c*S);for(let q=0;q<d;q++)for(let X=0;X<c;X++)for(let j=0;j<b;j++)for(let ae=0;ae<S;ae++)O.set(b*q+j,S*X+ae,this.get(q,X)*m.get(j,ae));return O}kroneckerSum(m){if(m=re.checkMatrix(m),!this.isSquare()||!m.isSquare())throw new Error("Kronecker Sum needs two Square Matrices");let d=this.rows,c=m.rows,b=this.kroneckerProduct(re.eye(c,c)),S=re.eye(d,d).kroneckerProduct(m);return b.add(S)}transpose(){let m=new re(this.columns,this.rows);for(let d=0;d<this.rows;d++)for(let c=0;c<this.columns;c++)m.set(c,d,this.get(d,c));return m}sortRows(m=Be){for(let d=0;d<this.rows;d++)this.setRow(d,this.getRow(d).sort(m));return this}sortColumns(m=Be){for(let d=0;d<this.columns;d++)this.setColumn(d,this.getColumn(d).sort(m));return this}subMatrix(m,d,c,b){A(this,m,d,c,b);let S=new re(d-m+1,b-c+1);for(let O=m;O<=d;O++)for(let q=c;q<=b;q++)S.set(O-m,q-c,this.get(O,q));return S}subMatrixRow(m,d,c){if(d===void 0&&(d=0),c===void 0&&(c=this.columns-1),d>c||d<0||d>=this.columns||c<0||c>=this.columns)throw new RangeError("Argument out of range");let b=new re(m.length,c-d+1);for(let S=0;S<m.length;S++)for(let O=d;O<=c;O++){if(m[S]<0||m[S]>=this.rows)throw new RangeError(`Row index out of range: ${m[S]}`);b.set(S,O-d,this.get(m[S],O))}return b}subMatrixColumn(m,d,c){if(d===void 0&&(d=0),c===void 0&&(c=this.rows-1),d>c||d<0||d>=this.rows||c<0||c>=this.rows)throw new RangeError("Argument out of range");let b=new re(c-d+1,m.length);for(let S=0;S<m.length;S++)for(let O=d;O<=c;O++){if(m[S]<0||m[S]>=this.columns)throw new RangeError(`Column index out of range: ${m[S]}`);b.set(O-d,S,this.get(O,m[S]))}return b}setSubMatrix(m,d,c){if(m=re.checkMatrix(m),m.isEmpty())return this;let b=d+m.rows-1,S=c+m.columns-1;A(this,d,b,c,S);for(let O=0;O<m.rows;O++)for(let q=0;q<m.columns;q++)this.set(d+O,c+q,m.get(O,q));return this}selection(m,d){v(this,m),k(this,d);let c=new re(m.length,d.length);for(let b=0;b<m.length;b++){let S=m[b];for(let O=0;O<d.length;O++){let q=d[O];c.set(b,O,this.get(S,q))}}return c}trace(){let m=Math.min(this.rows,this.columns),d=0;for(let c=0;c<m;c++)d+=this.get(c,c);return d}clone(){return this.constructor.copy(this,new re(this.rows,this.columns))}static copy(m,d){for(const[c,b,S]of m.entries())d.set(c,b,S);return d}sum(m){switch(m){case"row":return C(this);case"column":return P(this);case void 0:return z(this);default:throw new Error(`invalid option: ${m}`)}}product(m){switch(m){case"row":return B(this);case"column":return F(this);case void 0:return L(this);default:throw new Error(`invalid option: ${m}`)}}mean(m){const d=this.sum(m);switch(m){case"row":{for(let c=0;c<this.rows;c++)d[c]/=this.columns;return d}case"column":{for(let c=0;c<this.columns;c++)d[c]/=this.rows;return d}case void 0:return d/this.size;default:throw new Error(`invalid option: ${m}`)}}variance(m,d={}){if(typeof m=="object"&&(d=m,m=void 0),typeof d!="object")throw new TypeError("options must be an object");const{unbiased:c=!0,mean:b=this.mean(m)}=d;if(typeof c!="boolean")throw new TypeError("unbiased must be a boolean");switch(m){case"row":{if(!e.isAnyArray(b))throw new TypeError("mean must be an array");return N(this,c,b)}case"column":{if(!e.isAnyArray(b))throw new TypeError("mean must be an array");return G(this,c,b)}case void 0:{if(typeof b!="number")throw new TypeError("mean must be a number");return V(this,c,b)}default:throw new Error(`invalid option: ${m}`)}}standardDeviation(m,d){typeof m=="object"&&(d=m,m=void 0);const c=this.variance(m,d);if(m===void 0)return Math.sqrt(c);for(let b=0;b<c.length;b++)c[b]=Math.sqrt(c[b]);return c}center(m,d={}){if(typeof m=="object"&&(d=m,m=void 0),typeof d!="object")throw new TypeError("options must be an object");const{center:c=this.mean(m)}=d;switch(m){case"row":{if(!e.isAnyArray(c))throw new TypeError("center must be an array");return J(this,c),this}case"column":{if(!e.isAnyArray(c))throw new TypeError("center must be an array");return Q(this,c),this}case void 0:{if(typeof c!="number")throw new TypeError("center must be a number");return W(this,c),this}default:throw new Error(`invalid option: ${m}`)}}scale(m,d={}){if(typeof m=="object"&&(d=m,m=void 0),typeof d!="object")throw new TypeError("options must be an object");let c=d.scale;switch(m){case"row":{if(c===void 0)c=ne(this);else if(!e.isAnyArray(c))throw new TypeError("scale must be an array");return me(this,c),this}case"column":{if(c===void 0)c=ve(this);else if(!e.isAnyArray(c))throw new TypeError("scale must be an array");return ye(this,c),this}case void 0:{if(c===void 0)c=Me(this);else if(typeof c!="number")throw new TypeError("scale must be a number");return Re(this,c),this}default:throw new Error(`invalid option: ${m}`)}}toString(m){return s(this,m)}[Symbol.iterator](){return this.entries()}*entries(){for(let m=0;m<this.rows;m++)for(let d=0;d<this.columns;d++)yield[m,d,this.get(m,d)]}*values(){for(let m=0;m<this.rows;m++)for(let d=0;d<this.columns;d++)yield this.get(m,d)}}_e.prototype.klass="Matrix",typeof Symbol<"u"&&(_e.prototype[Symbol.for("nodejs.util.inspect.custom")]=a);function Be(M,m){return M-m}function Se(M){return M.every(m=>typeof m=="number")}_e.random=_e.rand,_e.randomInt=_e.randInt,_e.diagonal=_e.diag,_e.prototype.diagonal=_e.prototype.diag,_e.identity=_e.eye,_e.prototype.negate=_e.prototype.neg,_e.prototype.tensorProduct=_e.prototype.kroneckerProduct;const ee=class ee extends _e{constructor(d,c){super();It(this,de);we(this,"data");if(ee.isMatrix(d))Ct(this,de,$t).call(this,d.rows,d.columns),ee.copy(d,this);else if(Number.isInteger(d)&&d>=0)Ct(this,de,$t).call(this,d,c);else if(e.isAnyArray(d)){const b=d;if(d=b.length,c=d?b[0].length:0,typeof c!="number")throw new TypeError("Data must be a 2D array with at least one element");this.data=[];for(let S=0;S<d;S++){if(b[S].length!==c)throw new RangeError("Inconsistent array dimensions");if(!Se(b[S]))throw new TypeError("Input data contains non-numeric values");this.data.push(Float64Array.from(b[S]))}this.rows=d,this.columns=c}else throw new TypeError("First argument must be a positive number or an array")}set(d,c,b){return this.data[d][c]=b,this}get(d,c){return this.data[d][c]}removeRow(d){return u(this,d),this.data.splice(d,1),this.rows-=1,this}addRow(d,c){return c===void 0&&(c=d,d=this.rows),u(this,d,!0),c=Float64Array.from(_(this,c)),this.data.splice(d,0,c),this.rows+=1,this}removeColumn(d){w(this,d);for(let c=0;c<this.rows;c++){const b=new Float64Array(this.columns-1);for(let S=0;S<d;S++)b[S]=this.data[c][S];for(let S=d+1;S<this.columns;S++)b[S-1]=this.data[c][S];this.data[c]=b}return this.columns-=1,this}addColumn(d,c){typeof c>"u"&&(c=d,d=this.columns),w(this,d,!0),c=g(this,c);for(let b=0;b<this.rows;b++){const S=new Float64Array(this.columns+1);let O=0;for(;O<d;O++)S[O]=this.data[b][O];for(S[O++]=c[b];O<this.columns+1;O++)S[O]=this.data[b][O-1];this.data[b]=S}return this.columns+=1,this}};de=new WeakSet,$t=function(d,c){if(this.data=[],Number.isInteger(c)&&c>=0)for(let b=0;b<d;b++)this.data.push(new Float64Array(c));else throw new TypeError("nColumns must be a positive integer");this.rows=d,this.columns=c};let re=ee;l(_e,re);const We=class We extends _e{constructor(d){super();It(this,oe);if(re.isMatrix(d)){if(!d.isSymmetric())throw new TypeError("not symmetric data");Dt(this,oe,re.copy(d,new re(d.rows,d.rows)))}else if(Number.isInteger(d)&&d>=0)Dt(this,oe,new re(d,d));else if(Dt(this,oe,new re(d)),!this.isSymmetric())throw new TypeError("not symmetric data")}get size(){return kt(this,oe).size}get rows(){return kt(this,oe).rows}get columns(){return kt(this,oe).columns}get diagonalSize(){return this.rows}static isSymmetricMatrix(d){return re.isMatrix(d)&&d.klassType==="SymmetricMatrix"}static zeros(d){return new this(d)}static ones(d){return new this(d).fill(1)}clone(){const d=new We(this.diagonalSize);for(const[c,b,S]of this.upperRightEntries())d.set(c,b,S);return d}toMatrix(){return new re(this)}get(d,c){return kt(this,oe).get(d,c)}set(d,c,b){return kt(this,oe).set(d,c,b),kt(this,oe).set(c,d,b),this}removeCross(d){return kt(this,oe).removeRow(d),kt(this,oe).removeColumn(d),this}addCross(d,c){c===void 0&&(c=d,d=this.diagonalSize);const b=c.slice();return b.splice(d,1),kt(this,oe).addRow(d,b),kt(this,oe).addColumn(d,c),this}applyMask(d){if(d.length!==this.diagonalSize)throw new RangeError("Mask size do not match with matrix size");const c=[];for(const[b,S]of d.entries())S||c.push(b);c.reverse();for(const b of c)this.removeCross(b);return this}toCompact(){const{diagonalSize:d}=this,c=new Array(d*(d+1)/2);for(let b=0,S=0,O=0;O<c.length;O++)c[O]=this.get(S,b),++b>=d&&(b=++S);return c}static fromCompact(d){const c=d.length,b=(Math.sqrt(8*c+1)-1)/2;if(!Number.isInteger(b))throw new TypeError(`This array is not a compact representation of a Symmetric Matrix, ${JSON.stringify(d)}`);const S=new We(b);for(let O=0,q=0,X=0;X<c;X++)S.set(O,q,d[X]),++O>=b&&(O=++q);return S}*upperRightEntries(){for(let d=0,c=0;d<this.diagonalSize;void 0){const b=this.get(d,c);yield[d,c,b],++c>=this.diagonalSize&&(c=++d)}}*upperRightValues(){for(let d=0,c=0;d<this.diagonalSize;void 0)yield this.get(d,c),++c>=this.diagonalSize&&(c=++d)}};oe=new WeakMap;let Ie=We;Ie.prototype.klassType="SymmetricMatrix";class Fe extends Ie{static isDistanceMatrix(m){return Ie.isSymmetricMatrix(m)&&m.klassSubType==="DistanceMatrix"}constructor(m){if(super(m),!this.isDistance())throw new TypeError("Provided arguments do no produce a distance matrix")}set(m,d,c){return m===d&&(c=0),super.set(m,d,c)}addCross(m,d){return d===void 0&&(d=m,m=this.diagonalSize),d=d.slice(),d[m]=0,super.addCross(m,d)}toSymmetricMatrix(){return new Ie(this)}clone(){const m=new Fe(this.diagonalSize);for(const[d,c,b]of this.upperRightEntries())d!==c&&m.set(d,c,b);return m}toCompact(){const{diagonalSize:m}=this,d=(m-1)*m/2,c=new Array(d);for(let b=1,S=0,O=0;O<c.length;O++)c[O]=this.get(S,b),++b>=m&&(b=++S+1);return c}static fromCompact(m){const d=m.length;if(d===0)return new this(0);const c=(Math.sqrt(8*d+1)+1)/2;if(!Number.isInteger(c))throw new TypeError(`This array is not a compact representation of a DistanceMatrix, ${JSON.stringify(m)}`);const b=new this(c);for(let S=1,O=0,q=0;q<d;q++)b.set(S,O,m[q]),++S>=c&&(S=++O+1);return b}}Fe.prototype.klassSubType="DistanceMatrix";class ke extends _e{constructor(m,d,c){super(),this.matrix=m,this.rows=d,this.columns=c}}class Ye extends ke{constructor(m,d){w(m,d),super(m,m.rows,1),this.column=d}set(m,d,c){return this.matrix.set(m,this.column,c),this}get(m){return this.matrix.get(m,this.column)}}class Je extends ke{constructor(m,d){k(m,d),super(m,m.rows,d.length),this.columnIndices=d}set(m,d,c){return this.matrix.set(m,this.columnIndices[d],c),this}get(m,d){return this.matrix.get(m,this.columnIndices[d])}}class et extends ke{constructor(m){super(m,m.rows,m.columns)}set(m,d,c){return this.matrix.set(m,this.columns-d-1,c),this}get(m,d){return this.matrix.get(m,this.columns-d-1)}}class Ve extends ke{constructor(m){super(m,m.rows,m.columns)}set(m,d,c){return this.matrix.set(this.rows-m-1,d,c),this}get(m,d){return this.matrix.get(this.rows-m-1,d)}}class tt extends ke{constructor(m,d){u(m,d),super(m,1,m.columns),this.row=d}set(m,d,c){return this.matrix.set(this.row,d,c),this}get(m,d){return this.matrix.get(this.row,d)}}class qe extends ke{constructor(m,d){v(m,d),super(m,d.length,m.columns),this.rowIndices=d}set(m,d,c){return this.matrix.set(this.rowIndices[m],d,c),this}get(m,d){return this.matrix.get(this.rowIndices[m],d)}}class De extends ke{constructor(m,d,c){v(m,d),k(m,c),super(m,d.length,c.length),this.rowIndices=d,this.columnIndices=c}set(m,d,c){return this.matrix.set(this.rowIndices[m],this.columnIndices[d],c),this}get(m,d){return this.matrix.get(this.rowIndices[m],this.columnIndices[d])}}class nt extends ke{constructor(m,d,c,b,S){A(m,d,c,b,S),super(m,c-d+1,S-b+1),this.startRow=d,this.startColumn=b}set(m,d,c){return this.matrix.set(this.startRow+m,this.startColumn+d,c),this}get(m,d){return this.matrix.get(this.startRow+m,this.startColumn+d)}}class Ge extends ke{constructor(m){super(m,m.columns,m.rows)}set(m,d,c){return this.matrix.set(d,m,c),this}get(m,d){return this.matrix.get(d,m)}}class Ne extends _e{constructor(m,d={}){const{rows:c=1}=d;if(m.length%c!==0)throw new Error("the data length is not divisible by the number of rows");super(),this.rows=c,this.columns=m.length/c,this.data=m}set(m,d,c){let b=this._calculateIndex(m,d);return this.data[b]=c,this}get(m,d){let c=this._calculateIndex(m,d);return this.data[c]}_calculateIndex(m,d){return m*this.columns+d}}class he extends _e{constructor(m){super(),this.data=m,this.rows=m.length,this.columns=m[0].length}set(m,d,c){return this.data[m][d]=c,this}get(m,d){return this.data[m][d]}}function Qe(M,m){if(e.isAnyArray(M))return M[0]&&e.isAnyArray(M[0])?new he(M):new Ne(M,m);throw new Error("the argument is not an array")}class Ze{constructor(m){m=he.checkMatrix(m);let d=m.clone(),c=d.rows,b=d.columns,S=new Float64Array(c),O=1,q,X,j,ae,K,ce,be,le,ge;for(q=0;q<c;q++)S[q]=q;for(le=new Float64Array(c),X=0;X<b;X++){for(q=0;q<c;q++)le[q]=d.get(q,X);for(q=0;q<c;q++){for(ge=Math.min(q,X),K=0,j=0;j<ge;j++)K+=d.get(q,j)*le[j];le[q]-=K,d.set(q,X,le[q])}for(ae=X,q=X+1;q<c;q++)Math.abs(le[q])>Math.abs(le[ae])&&(ae=q);if(ae!==X){for(j=0;j<b;j++)ce=d.get(ae,j),d.set(ae,j,d.get(X,j)),d.set(X,j,ce);be=S[ae],S[ae]=S[X],S[X]=be,O=-O}if(X<c&&d.get(X,X)!==0)for(q=X+1;q<c;q++)d.set(q,X,d.get(q,X)/d.get(X,X))}this.LU=d,this.pivotVector=S,this.pivotSign=O}isSingular(){let m=this.LU,d=m.columns;for(let c=0;c<d;c++)if(m.get(c,c)===0)return!0;return!1}solve(m){m=re.checkMatrix(m);let d=this.LU;if(d.rows!==m.rows)throw new Error("Invalid matrix dimensions");if(this.isSingular())throw new Error("LU matrix is singular");let b=m.columns,S=m.subMatrixRow(this.pivotVector,0,b-1),O=d.columns,q,X,j;for(j=0;j<O;j++)for(q=j+1;q<O;q++)for(X=0;X<b;X++)S.set(q,X,S.get(q,X)-S.get(j,X)*d.get(q,j));for(j=O-1;j>=0;j--){for(X=0;X<b;X++)S.set(j,X,S.get(j,X)/d.get(j,j));for(q=0;q<j;q++)for(X=0;X<b;X++)S.set(q,X,S.get(q,X)-S.get(j,X)*d.get(q,j))}return S}get determinant(){let m=this.LU;if(!m.isSquare())throw new Error("Matrix must be square");let d=this.pivotSign,c=m.columns;for(let b=0;b<c;b++)d*=m.get(b,b);return d}get lowerTriangularMatrix(){let m=this.LU,d=m.rows,c=m.columns,b=new re(d,c);for(let S=0;S<d;S++)for(let O=0;O<c;O++)S>O?b.set(S,O,m.get(S,O)):S===O?b.set(S,O,1):b.set(S,O,0);return b}get upperTriangularMatrix(){let m=this.LU,d=m.rows,c=m.columns,b=new re(d,c);for(let S=0;S<d;S++)for(let O=0;O<c;O++)S<=O?b.set(S,O,m.get(S,O)):b.set(S,O,0);return b}get pivotPermutationVector(){return Array.from(this.pivotVector)}}function He(M,m){let d=0;return Math.abs(M)>Math.abs(m)?(d=m/M,Math.abs(M)*Math.sqrt(1+d*d)):m!==0?(d=M/m,Math.abs(m)*Math.sqrt(1+d*d)):0}class Te{constructor(m){m=he.checkMatrix(m);let d=m.clone(),c=m.rows,b=m.columns,S=new Float64Array(b),O,q,X,j;for(X=0;X<b;X++){let ae=0;for(O=X;O<c;O++)ae=He(ae,d.get(O,X));if(ae!==0){for(d.get(X,X)<0&&(ae=-ae),O=X;O<c;O++)d.set(O,X,d.get(O,X)/ae);for(d.set(X,X,d.get(X,X)+1),q=X+1;q<b;q++){for(j=0,O=X;O<c;O++)j+=d.get(O,X)*d.get(O,q);for(j=-j/d.get(X,X),O=X;O<c;O++)d.set(O,q,d.get(O,q)+j*d.get(O,X))}}S[X]=-ae}this.QR=d,this.Rdiag=S}solve(m){m=re.checkMatrix(m);let d=this.QR,c=d.rows;if(m.rows!==c)throw new Error("Matrix row dimensions must agree");if(!this.isFullRank())throw new Error("Matrix is rank deficient");let b=m.columns,S=m.clone(),O=d.columns,q,X,j,ae;for(j=0;j<O;j++)for(X=0;X<b;X++){for(ae=0,q=j;q<c;q++)ae+=d.get(q,j)*S.get(q,X);for(ae=-ae/d.get(j,j),q=j;q<c;q++)S.set(q,X,S.get(q,X)+ae*d.get(q,j))}for(j=O-1;j>=0;j--){for(X=0;X<b;X++)S.set(j,X,S.get(j,X)/this.Rdiag[j]);for(q=0;q<j;q++)for(X=0;X<b;X++)S.set(q,X,S.get(q,X)-S.get(j,X)*d.get(q,j))}return S.subMatrix(0,O-1,0,b-1)}isFullRank(){let m=this.QR.columns;for(let d=0;d<m;d++)if(this.Rdiag[d]===0)return!1;return!0}get upperTriangularMatrix(){let m=this.QR,d=m.columns,c=new re(d,d),b,S;for(b=0;b<d;b++)for(S=0;S<d;S++)b<S?c.set(b,S,m.get(b,S)):b===S?c.set(b,S,this.Rdiag[b]):c.set(b,S,0);return c}get orthogonalMatrix(){let m=this.QR,d=m.rows,c=m.columns,b=new re(d,c),S,O,q,X;for(q=c-1;q>=0;q--){for(S=0;S<d;S++)b.set(S,q,0);for(b.set(q,q,1),O=q;O<c;O++)if(m.get(q,q)!==0){for(X=0,S=q;S<d;S++)X+=m.get(S,q)*b.get(S,O);for(X=-X/m.get(q,q),S=q;S<d;S++)b.set(S,O,b.get(S,O)+X*m.get(S,q))}}return b}}class lt{constructor(m,d={}){if(m=he.checkMatrix(m),m.isEmpty())throw new Error("Matrix must be non-empty");let c=m.rows,b=m.columns;const{computeLeftSingularVectors:S=!0,computeRightSingularVectors:O=!0,autoTranspose:q=!1}=d;let X=!!S,j=!!O,ae=!1,K;if(c<b)if(!q)K=m.clone(),console.warn("Computing SVD on a matrix with more columns than rows. Consider enabling autoTranspose");else{K=m.transpose(),c=K.rows,b=K.columns,ae=!0;let se=X;X=j,j=se}else K=m.clone();let ce=Math.min(c,b),be=Math.min(c+1,b),le=new Float64Array(be),ge=new re(c,ce),Ue=new re(b,b),ie=new Float64Array(b),$e=new Float64Array(c),Xe=new Float64Array(be);for(let se=0;se<be;se++)Xe[se]=se;let ht=Math.min(c-1,b),ft=Math.max(0,Math.min(b-2,c)),gt=Math.max(ht,ft);for(let se=0;se<gt;se++){if(se<ht){le[se]=0;for(let Ce=se;Ce<c;Ce++)le[se]=He(le[se],K.get(Ce,se));if(le[se]!==0){K.get(se,se)<0&&(le[se]=-le[se]);for(let Ce=se;Ce<c;Ce++)K.set(Ce,se,K.get(Ce,se)/le[se]);K.set(se,se,K.get(se,se)+1)}le[se]=-le[se]}for(let Ce=se+1;Ce<b;Ce++){if(se<ht&&le[se]!==0){let Ke=0;for(let Pe=se;Pe<c;Pe++)Ke+=K.get(Pe,se)*K.get(Pe,Ce);Ke=-Ke/K.get(se,se);for(let Pe=se;Pe<c;Pe++)K.set(Pe,Ce,K.get(Pe,Ce)+Ke*K.get(Pe,se))}ie[Ce]=K.get(se,Ce)}if(X&&se<ht)for(let Ce=se;Ce<c;Ce++)ge.set(Ce,se,K.get(Ce,se));if(se<ft){ie[se]=0;for(let Ce=se+1;Ce<b;Ce++)ie[se]=He(ie[se],ie[Ce]);if(ie[se]!==0){ie[se+1]<0&&(ie[se]=0-ie[se]);for(let Ce=se+1;Ce<b;Ce++)ie[Ce]/=ie[se];ie[se+1]+=1}if(ie[se]=-ie[se],se+1<c&&ie[se]!==0){for(let Ce=se+1;Ce<c;Ce++)$e[Ce]=0;for(let Ce=se+1;Ce<c;Ce++)for(let Ke=se+1;Ke<b;Ke++)$e[Ce]+=ie[Ke]*K.get(Ce,Ke);for(let Ce=se+1;Ce<b;Ce++){let Ke=-ie[Ce]/ie[se+1];for(let Pe=se+1;Pe<c;Pe++)K.set(Pe,Ce,K.get(Pe,Ce)+Ke*$e[Pe])}}if(j)for(let Ce=se+1;Ce<b;Ce++)Ue.set(Ce,se,ie[Ce])}}let rt=Math.min(b,c+1);if(ht<b&&(le[ht]=K.get(ht,ht)),c<rt&&(le[rt-1]=0),ft+1<rt&&(ie[ft]=K.get(ft,rt-1)),ie[rt-1]=0,X){for(let se=ht;se<ce;se++){for(let Ce=0;Ce<c;Ce++)ge.set(Ce,se,0);ge.set(se,se,1)}for(let se=ht-1;se>=0;se--)if(le[se]!==0){for(let Ce=se+1;Ce<ce;Ce++){let Ke=0;for(let Pe=se;Pe<c;Pe++)Ke+=ge.get(Pe,se)*ge.get(Pe,Ce);Ke=-Ke/ge.get(se,se);for(let Pe=se;Pe<c;Pe++)ge.set(Pe,Ce,ge.get(Pe,Ce)+Ke*ge.get(Pe,se))}for(let Ce=se;Ce<c;Ce++)ge.set(Ce,se,-ge.get(Ce,se));ge.set(se,se,1+ge.get(se,se));for(let Ce=0;Ce<se-1;Ce++)ge.set(Ce,se,0)}else{for(let Ce=0;Ce<c;Ce++)ge.set(Ce,se,0);ge.set(se,se,1)}}if(j)for(let se=b-1;se>=0;se--){if(se<ft&&ie[se]!==0)for(let Ce=se+1;Ce<b;Ce++){let Ke=0;for(let Pe=se+1;Pe<b;Pe++)Ke+=Ue.get(Pe,se)*Ue.get(Pe,Ce);Ke=-Ke/Ue.get(se+1,se);for(let Pe=se+1;Pe<b;Pe++)Ue.set(Pe,Ce,Ue.get(Pe,Ce)+Ke*Ue.get(Pe,se))}for(let Ce=0;Ce<b;Ce++)Ue.set(Ce,se,0);Ue.set(se,se,1)}let at=rt-1,mt=Number.EPSILON;for(;rt>0;){let se,Ce;for(se=rt-2;se>=-1&&se!==-1;se--){const Ke=Number.MIN_VALUE+mt*Math.abs(le[se]+Math.abs(le[se+1]));if(Math.abs(ie[se])<=Ke||Number.isNaN(ie[se])){ie[se]=0;break}}if(se===rt-2)Ce=4;else{let Ke;for(Ke=rt-1;Ke>=se&&Ke!==se;Ke--){let Pe=(Ke!==rt?Math.abs(ie[Ke]):0)+(Ke!==se+1?Math.abs(ie[Ke-1]):0);if(Math.abs(le[Ke])<=mt*Pe){le[Ke]=0;break}}Ke===se?Ce=3:Ke===rt-1?Ce=1:(Ce=2,se=Ke)}switch(se++,Ce){case 1:{let Ke=ie[rt-2];ie[rt-2]=0;for(let Pe=rt-2;Pe>=se;Pe--){let _t=He(le[Pe],Ke),dt=le[Pe]/_t,pt=Ke/_t;if(le[Pe]=_t,Pe!==se&&(Ke=-pt*ie[Pe-1],ie[Pe-1]=dt*ie[Pe-1]),j)for(let xt=0;xt<b;xt++)_t=dt*Ue.get(xt,Pe)+pt*Ue.get(xt,rt-1),Ue.set(xt,rt-1,-pt*Ue.get(xt,Pe)+dt*Ue.get(xt,rt-1)),Ue.set(xt,Pe,_t)}break}case 2:{let Ke=ie[se-1];ie[se-1]=0;for(let Pe=se;Pe<rt;Pe++){let _t=He(le[Pe],Ke),dt=le[Pe]/_t,pt=Ke/_t;if(le[Pe]=_t,Ke=-pt*ie[Pe],ie[Pe]=dt*ie[Pe],X)for(let xt=0;xt<c;xt++)_t=dt*ge.get(xt,Pe)+pt*ge.get(xt,se-1),ge.set(xt,se-1,-pt*ge.get(xt,Pe)+dt*ge.get(xt,se-1)),ge.set(xt,Pe,_t)}break}case 3:{const Ke=Math.max(Math.abs(le[rt-1]),Math.abs(le[rt-2]),Math.abs(ie[rt-2]),Math.abs(le[se]),Math.abs(ie[se])),Pe=le[rt-1]/Ke,_t=le[rt-2]/Ke,dt=ie[rt-2]/Ke,pt=le[se]/Ke,xt=ie[se]/Ke,vt=((_t+Pe)*(_t-Pe)+dt*dt)/2,St=Pe*dt*(Pe*dt);let wt=0;(vt!==0||St!==0)&&(vt<0?wt=0-Math.sqrt(vt*vt+St):wt=Math.sqrt(vt*vt+St),wt=St/(vt+wt));let At=(pt+Pe)*(pt-Pe)+wt,Rt=pt*xt;for(let ut=se;ut<rt-1;ut++){let yt=He(At,Rt);yt===0&&(yt=Number.MIN_VALUE);let Et=At/yt,Mt=Rt/yt;if(ut!==se&&(ie[ut-1]=yt),At=Et*le[ut]+Mt*ie[ut],ie[ut]=Et*ie[ut]-Mt*le[ut],Rt=Mt*le[ut+1],le[ut+1]=Et*le[ut+1],j)for(let bt=0;bt<b;bt++)yt=Et*Ue.get(bt,ut)+Mt*Ue.get(bt,ut+1),Ue.set(bt,ut+1,-Mt*Ue.get(bt,ut)+Et*Ue.get(bt,ut+1)),Ue.set(bt,ut,yt);if(yt=He(At,Rt),yt===0&&(yt=Number.MIN_VALUE),Et=At/yt,Mt=Rt/yt,le[ut]=yt,At=Et*ie[ut]+Mt*le[ut+1],le[ut+1]=-Mt*ie[ut]+Et*le[ut+1],Rt=Mt*ie[ut+1],ie[ut+1]=Et*ie[ut+1],X&&ut<c-1)for(let bt=0;bt<c;bt++)yt=Et*ge.get(bt,ut)+Mt*ge.get(bt,ut+1),ge.set(bt,ut+1,-Mt*ge.get(bt,ut)+Et*ge.get(bt,ut+1)),ge.set(bt,ut,yt)}ie[rt-2]=At;break}case 4:{if(le[se]<=0&&(le[se]=le[se]<0?-le[se]:0,j))for(let Ke=0;Ke<=at;Ke++)Ue.set(Ke,se,-Ue.get(Ke,se));for(;se<at&&!(le[se]>=le[se+1]);){let Ke=le[se];if(le[se]=le[se+1],le[se+1]=Ke,j&&se<b-1)for(let Pe=0;Pe<b;Pe++)Ke=Ue.get(Pe,se+1),Ue.set(Pe,se+1,Ue.get(Pe,se)),Ue.set(Pe,se,Ke);if(X&&se<c-1)for(let Pe=0;Pe<c;Pe++)Ke=ge.get(Pe,se+1),ge.set(Pe,se+1,ge.get(Pe,se)),ge.set(Pe,se,Ke);se++}rt--;break}}}if(ae){let se=Ue;Ue=ge,ge=se}this.m=c,this.n=b,this.s=le,this.U=ge,this.V=Ue}solve(m){let d=m,c=this.threshold,b=this.s.length,S=re.zeros(b,b);for(let ce=0;ce<b;ce++)Math.abs(this.s[ce])<=c?S.set(ce,ce,0):S.set(ce,ce,1/this.s[ce]);let O=this.U,q=this.rightSingularVectors,X=q.mmul(S),j=q.rows,ae=O.rows,K=re.zeros(j,ae);for(let ce=0;ce<j;ce++)for(let be=0;be<ae;be++){let le=0;for(let ge=0;ge<b;ge++)le+=X.get(ce,ge)*O.get(be,ge);K.set(ce,be,le)}return K.mmul(d)}solveForDiagonal(m){return this.solve(re.diag(m))}inverse(){let m=this.V,d=this.threshold,c=m.rows,b=m.columns,S=new re(c,this.s.length);for(let ae=0;ae<c;ae++)for(let K=0;K<b;K++)Math.abs(this.s[K])>d&&S.set(ae,K,m.get(ae,K)/this.s[K]);let O=this.U,q=O.rows,X=O.columns,j=new re(c,q);for(let ae=0;ae<c;ae++)for(let K=0;K<q;K++){let ce=0;for(let be=0;be<X;be++)ce+=S.get(ae,be)*O.get(K,be);j.set(ae,K,ce)}return j}get condition(){return this.s[0]/this.s[Math.min(this.m,this.n)-1]}get norm2(){return this.s[0]}get rank(){let m=Math.max(this.m,this.n)*this.s[0]*Number.EPSILON,d=0,c=this.s;for(let b=0,S=c.length;b<S;b++)c[b]>m&&d++;return d}get diagonal(){return Array.from(this.s)}get threshold(){return Number.EPSILON/2*Math.max(this.m,this.n)*this.s[0]}get leftSingularVectors(){return this.U}get rightSingularVectors(){return this.V}get diagonalMatrix(){return re.diag(this.s)}}function ot(M,m=!1){return M=he.checkMatrix(M),m?new lt(M).inverse():Le(M,re.eye(M.rows))}function Le(M,m,d=!1){return M=he.checkMatrix(M),m=he.checkMatrix(m),d?new lt(M).solve(m):M.isSquare()?new Ze(M).solve(m):new Te(M).solve(m)}function ze(M){if(M=re.checkMatrix(M),M.isSquare()){if(M.columns===0)return 1;let m,d,c,b;if(M.columns===2)return m=M.get(0,0),d=M.get(0,1),c=M.get(1,0),b=M.get(1,1),m*b-d*c;if(M.columns===3){let S,O,q;return S=new De(M,[1,2],[1,2]),O=new De(M,[1,2],[0,2]),q=new De(M,[1,2],[0,1]),m=M.get(0,0),d=M.get(0,1),c=M.get(0,2),m*ze(S)-d*ze(O)+c*ze(q)}else return new Ze(M).determinant}else throw Error("determinant can only be calculated for a square matrix")}function je(M,m){let d=[];for(let c=0;c<M;c++)c!==m&&d.push(c);return d}function Oe(M,m,d,c=1e-9,b=1e-9){if(M>b)return new Array(m.rows+1).fill(0);{let S=m.addRow(d,[0]);for(let O=0;O<S.rows;O++)Math.abs(S.get(O,0))<c&&S.set(O,0,0);return S.to1DArray()}}function st(M,m={}){const{thresholdValue:d=1e-9,thresholdError:c=1e-9}=m;M=re.checkMatrix(M);let b=M.rows,S=new re(b,b);for(let O=0;O<b;O++){let q=re.columnVector(M.getRow(O)),X=M.subMatrixRow(je(b,O)).transpose(),ae=new lt(X).solve(q),K=re.sub(q,X.mmul(ae)).abs().max();S.setRow(O,Oe(K,ae,O,d,c))}return S}function Z(M,m=Number.EPSILON){if(M=re.checkMatrix(M),M.isEmpty())return M.transpose();let d=new lt(M,{autoTranspose:!0}),c=d.leftSingularVectors,b=d.rightSingularVectors,S=d.diagonal;for(let O=0;O<S.length;O++)Math.abs(S[O])>m?S[O]=1/S[O]:S[O]=0;return b.mmul(re.diag(S).mmul(c.transpose()))}function ue(M,m=M,d={}){M=new re(M);let c=!1;if(typeof m=="object"&&!re.isMatrix(m)&&!e.isAnyArray(m)?(d=m,m=M,c=!0):m=new re(m),M.rows!==m.rows)throw new TypeError("Both matrices must have the same number of rows");const{center:b=!0}=d;b&&(M=M.center("column"),c||(m=m.center("column")));const S=M.transpose().mmul(m);for(let O=0;O<S.rows;O++)for(let q=0;q<S.columns;q++)S.set(O,q,S.get(O,q)*(1/(M.rows-1)));return S}function xe(M,m=M,d={}){M=new re(M);let c=!1;if(typeof m=="object"&&!re.isMatrix(m)&&!e.isAnyArray(m)?(d=m,m=M,c=!0):m=new re(m),M.rows!==m.rows)throw new TypeError("Both matrices must have the same number of rows");const{center:b=!0,scale:S=!0}=d;b&&(M.center("column"),c||m.center("column")),S&&(M.scale("column"),c||m.scale("column"));const O=M.standardDeviation("column",{unbiased:!0}),q=c?O:m.standardDeviation("column",{unbiased:!0}),X=M.transpose().mmul(m);for(let j=0;j<X.rows;j++)for(let ae=0;ae<X.columns;ae++)X.set(j,ae,X.get(j,ae)*(1/(O[j]*q[ae]))*(1/(M.rows-1)));return X}class Ae{constructor(m,d={}){const{assumeSymmetric:c=!1}=d;if(m=he.checkMatrix(m),!m.isSquare())throw new Error("Matrix is not a square matrix");if(m.isEmpty())throw new Error("Matrix must be non-empty");let b=m.columns,S=new re(b,b),O=new Float64Array(b),q=new Float64Array(b),X=m,j,ae,K=!1;if(c?K=!0:K=m.isSymmetric(),K){for(j=0;j<b;j++)for(ae=0;ae<b;ae++)S.set(j,ae,X.get(j,ae));te(b,q,O,S),pe(b,q,O,S)}else{let ce=new re(b,b),be=new Float64Array(b);for(ae=0;ae<b;ae++)for(j=0;j<b;j++)ce.set(j,ae,X.get(j,ae));U(b,ce,be,S),Ee(b,q,O,S,ce)}this.n=b,this.e=q,this.d=O,this.V=S}get realEigenvalues(){return Array.from(this.d)}get imaginaryEigenvalues(){return Array.from(this.e)}get eigenvectorMatrix(){return this.V}get diagonalMatrix(){let m=this.n,d=this.e,c=this.d,b=new re(m,m),S,O;for(S=0;S<m;S++){for(O=0;O<m;O++)b.set(S,O,0);b.set(S,S,c[S]),d[S]>0?b.set(S,S+1,d[S]):d[S]<0&&b.set(S,S-1,d[S])}return b}}function te(M,m,d,c){let b,S,O,q,X,j,ae,K;for(X=0;X<M;X++)d[X]=c.get(M-1,X);for(q=M-1;q>0;q--){for(K=0,O=0,j=0;j<q;j++)K=K+Math.abs(d[j]);if(K===0)for(m[q]=d[q-1],X=0;X<q;X++)d[X]=c.get(q-1,X),c.set(q,X,0),c.set(X,q,0);else{for(j=0;j<q;j++)d[j]/=K,O+=d[j]*d[j];for(b=d[q-1],S=Math.sqrt(O),b>0&&(S=-S),m[q]=K*S,O=O-b*S,d[q-1]=b-S,X=0;X<q;X++)m[X]=0;for(X=0;X<q;X++){for(b=d[X],c.set(X,q,b),S=m[X]+c.get(X,X)*b,j=X+1;j<=q-1;j++)S+=c.get(j,X)*d[j],m[j]+=c.get(j,X)*b;m[X]=S}for(b=0,X=0;X<q;X++)m[X]/=O,b+=m[X]*d[X];for(ae=b/(O+O),X=0;X<q;X++)m[X]-=ae*d[X];for(X=0;X<q;X++){for(b=d[X],S=m[X],j=X;j<=q-1;j++)c.set(j,X,c.get(j,X)-(b*m[j]+S*d[j]));d[X]=c.get(q-1,X),c.set(q,X,0)}}d[q]=O}for(q=0;q<M-1;q++){if(c.set(M-1,q,c.get(q,q)),c.set(q,q,1),O=d[q+1],O!==0){for(j=0;j<=q;j++)d[j]=c.get(j,q+1)/O;for(X=0;X<=q;X++){for(S=0,j=0;j<=q;j++)S+=c.get(j,q+1)*c.get(j,X);for(j=0;j<=q;j++)c.set(j,X,c.get(j,X)-S*d[j])}}for(j=0;j<=q;j++)c.set(j,q+1,0)}for(X=0;X<M;X++)d[X]=c.get(M-1,X),c.set(M-1,X,0);c.set(M-1,M-1,1),m[0]=0}function pe(M,m,d,c){let b,S,O,q,X,j,ae,K,ce,be,le,ge,Ue,ie,$e,Xe;for(O=1;O<M;O++)m[O-1]=m[O];m[M-1]=0;let ht=0,ft=0,gt=Number.EPSILON;for(j=0;j<M;j++){for(ft=Math.max(ft,Math.abs(d[j])+Math.abs(m[j])),ae=j;ae<M&&!(Math.abs(m[ae])<=gt*ft);)ae++;if(ae>j)do{for(b=d[j],K=(d[j+1]-b)/(2*m[j]),ce=He(K,1),K<0&&(ce=-ce),d[j]=m[j]/(K+ce),d[j+1]=m[j]*(K+ce),be=d[j+1],S=b-d[j],O=j+2;O<M;O++)d[O]-=S;for(ht=ht+S,K=d[ae],le=1,ge=le,Ue=le,ie=m[j+1],$e=0,Xe=0,O=ae-1;O>=j;O--)for(Ue=ge,ge=le,Xe=$e,b=le*m[O],S=le*K,ce=He(K,m[O]),m[O+1]=$e*ce,$e=m[O]/ce,le=K/ce,K=le*d[O]-$e*b,d[O+1]=S+$e*(le*b+$e*d[O]),X=0;X<M;X++)S=c.get(X,O+1),c.set(X,O+1,$e*c.get(X,O)+le*S),c.set(X,O,le*c.get(X,O)-$e*S);K=-$e*Xe*Ue*ie*m[j]/be,m[j]=$e*K,d[j]=le*K}while(Math.abs(m[j])>gt*ft);d[j]=d[j]+ht,m[j]=0}for(O=0;O<M-1;O++){for(X=O,K=d[O],q=O+1;q<M;q++)d[q]<K&&(X=q,K=d[q]);if(X!==O)for(d[X]=d[O],d[O]=K,q=0;q<M;q++)K=c.get(q,O),c.set(q,O,c.get(q,X)),c.set(q,X,K)}}function U(M,m,d,c){let b=0,S=M-1,O,q,X,j,ae,K,ce;for(K=b+1;K<=S-1;K++){for(ce=0,j=K;j<=S;j++)ce=ce+Math.abs(m.get(j,K-1));if(ce!==0){for(X=0,j=S;j>=K;j--)d[j]=m.get(j,K-1)/ce,X+=d[j]*d[j];for(q=Math.sqrt(X),d[K]>0&&(q=-q),X=X-d[K]*q,d[K]=d[K]-q,ae=K;ae<M;ae++){for(O=0,j=S;j>=K;j--)O+=d[j]*m.get(j,ae);for(O=O/X,j=K;j<=S;j++)m.set(j,ae,m.get(j,ae)-O*d[j])}for(j=0;j<=S;j++){for(O=0,ae=S;ae>=K;ae--)O+=d[ae]*m.get(j,ae);for(O=O/X,ae=K;ae<=S;ae++)m.set(j,ae,m.get(j,ae)-O*d[ae])}d[K]=ce*d[K],m.set(K,K-1,ce*q)}}for(j=0;j<M;j++)for(ae=0;ae<M;ae++)c.set(j,ae,j===ae?1:0);for(K=S-1;K>=b+1;K--)if(m.get(K,K-1)!==0){for(j=K+1;j<=S;j++)d[j]=m.get(j,K-1);for(ae=K;ae<=S;ae++){for(q=0,j=K;j<=S;j++)q+=d[j]*c.get(j,ae);for(q=q/d[K]/m.get(K,K-1),j=K;j<=S;j++)c.set(j,ae,c.get(j,ae)+q*d[j])}}}function Ee(M,m,d,c,b){let S=M-1,O=0,q=M-1,X=Number.EPSILON,j=0,ae=0,K=0,ce=0,be=0,le=0,ge=0,Ue=0,ie,$e,Xe,ht,ft,gt,rt,at,mt,se,Ce,Ke,Pe,_t,dt;for(ie=0;ie<M;ie++)for((ie<O||ie>q)&&(d[ie]=b.get(ie,ie),m[ie]=0),$e=Math.max(ie-1,0);$e<M;$e++)ae=ae+Math.abs(b.get(ie,$e));for(;S>=O;){for(ht=S;ht>O&&(le=Math.abs(b.get(ht-1,ht-1))+Math.abs(b.get(ht,ht)),le===0&&(le=ae),!(Math.abs(b.get(ht,ht-1))<X*le));)ht--;if(ht===S)b.set(S,S,b.get(S,S)+j),d[S]=b.get(S,S),m[S]=0,S--,Ue=0;else if(ht===S-1){if(rt=b.get(S,S-1)*b.get(S-1,S),K=(b.get(S-1,S-1)-b.get(S,S))/2,ce=K*K+rt,ge=Math.sqrt(Math.abs(ce)),b.set(S,S,b.get(S,S)+j),b.set(S-1,S-1,b.get(S-1,S-1)+j),at=b.get(S,S),ce>=0){for(ge=K>=0?K+ge:K-ge,d[S-1]=at+ge,d[S]=d[S-1],ge!==0&&(d[S]=at-rt/ge),m[S-1]=0,m[S]=0,at=b.get(S,S-1),le=Math.abs(at)+Math.abs(ge),K=at/le,ce=ge/le,be=Math.sqrt(K*K+ce*ce),K=K/be,ce=ce/be,$e=S-1;$e<M;$e++)ge=b.get(S-1,$e),b.set(S-1,$e,ce*ge+K*b.get(S,$e)),b.set(S,$e,ce*b.get(S,$e)-K*ge);for(ie=0;ie<=S;ie++)ge=b.get(ie,S-1),b.set(ie,S-1,ce*ge+K*b.get(ie,S)),b.set(ie,S,ce*b.get(ie,S)-K*ge);for(ie=O;ie<=q;ie++)ge=c.get(ie,S-1),c.set(ie,S-1,ce*ge+K*c.get(ie,S)),c.set(ie,S,ce*c.get(ie,S)-K*ge)}else d[S-1]=at+K,d[S]=at+K,m[S-1]=ge,m[S]=-ge;S=S-2,Ue=0}else{if(at=b.get(S,S),mt=0,rt=0,ht<S&&(mt=b.get(S-1,S-1),rt=b.get(S,S-1)*b.get(S-1,S)),Ue===10){for(j+=at,ie=O;ie<=S;ie++)b.set(ie,ie,b.get(ie,ie)-at);le=Math.abs(b.get(S,S-1))+Math.abs(b.get(S-1,S-2)),at=mt=.75*le,rt=-.4375*le*le}if(Ue===30&&(le=(mt-at)/2,le=le*le+rt,le>0)){for(le=Math.sqrt(le),mt<at&&(le=-le),le=at-rt/((mt-at)/2+le),ie=O;ie<=S;ie++)b.set(ie,ie,b.get(ie,ie)-le);j+=le,at=mt=rt=.964}for(Ue=Ue+1,ft=S-2;ft>=ht&&(ge=b.get(ft,ft),be=at-ge,le=mt-ge,K=(be*le-rt)/b.get(ft+1,ft)+b.get(ft,ft+1),ce=b.get(ft+1,ft+1)-ge-be-le,be=b.get(ft+2,ft+1),le=Math.abs(K)+Math.abs(ce)+Math.abs(be),K=K/le,ce=ce/le,be=be/le,!(ft===ht||Math.abs(b.get(ft,ft-1))*(Math.abs(ce)+Math.abs(be))<X*(Math.abs(K)*(Math.abs(b.get(ft-1,ft-1))+Math.abs(ge)+Math.abs(b.get(ft+1,ft+1))))));)ft--;for(ie=ft+2;ie<=S;ie++)b.set(ie,ie-2,0),ie>ft+2&&b.set(ie,ie-3,0);for(Xe=ft;Xe<=S-1&&(_t=Xe!==S-1,Xe!==ft&&(K=b.get(Xe,Xe-1),ce=b.get(Xe+1,Xe-1),be=_t?b.get(Xe+2,Xe-1):0,at=Math.abs(K)+Math.abs(ce)+Math.abs(be),at!==0&&(K=K/at,ce=ce/at,be=be/at)),at!==0);Xe++)if(le=Math.sqrt(K*K+ce*ce+be*be),K<0&&(le=-le),le!==0){for(Xe!==ft?b.set(Xe,Xe-1,-le*at):ht!==ft&&b.set(Xe,Xe-1,-b.get(Xe,Xe-1)),K=K+le,at=K/le,mt=ce/le,ge=be/le,ce=ce/K,be=be/K,$e=Xe;$e<M;$e++)K=b.get(Xe,$e)+ce*b.get(Xe+1,$e),_t&&(K=K+be*b.get(Xe+2,$e),b.set(Xe+2,$e,b.get(Xe+2,$e)-K*ge)),b.set(Xe,$e,b.get(Xe,$e)-K*at),b.set(Xe+1,$e,b.get(Xe+1,$e)-K*mt);for(ie=0;ie<=Math.min(S,Xe+3);ie++)K=at*b.get(ie,Xe)+mt*b.get(ie,Xe+1),_t&&(K=K+ge*b.get(ie,Xe+2),b.set(ie,Xe+2,b.get(ie,Xe+2)-K*be)),b.set(ie,Xe,b.get(ie,Xe)-K),b.set(ie,Xe+1,b.get(ie,Xe+1)-K*ce);for(ie=O;ie<=q;ie++)K=at*c.get(ie,Xe)+mt*c.get(ie,Xe+1),_t&&(K=K+ge*c.get(ie,Xe+2),c.set(ie,Xe+2,c.get(ie,Xe+2)-K*be)),c.set(ie,Xe,c.get(ie,Xe)-K),c.set(ie,Xe+1,c.get(ie,Xe+1)-K*ce)}}}if(ae!==0){for(S=M-1;S>=0;S--)if(K=d[S],ce=m[S],ce===0)for(ht=S,b.set(S,S,1),ie=S-1;ie>=0;ie--){for(rt=b.get(ie,ie)-K,be=0,$e=ht;$e<=S;$e++)be=be+b.get(ie,$e)*b.get($e,S);if(m[ie]<0)ge=rt,le=be;else if(ht=ie,m[ie]===0?b.set(ie,S,rt!==0?-be/rt:-be/(X*ae)):(at=b.get(ie,ie+1),mt=b.get(ie+1,ie),ce=(d[ie]-K)*(d[ie]-K)+m[ie]*m[ie],gt=(at*le-ge*be)/ce,b.set(ie,S,gt),b.set(ie+1,S,Math.abs(at)>Math.abs(ge)?(-be-rt*gt)/at:(-le-mt*gt)/ge)),gt=Math.abs(b.get(ie,S)),X*gt*gt>1)for($e=ie;$e<=S;$e++)b.set($e,S,b.get($e,S)/gt)}else if(ce<0)for(ht=S-1,Math.abs(b.get(S,S-1))>Math.abs(b.get(S-1,S))?(b.set(S-1,S-1,ce/b.get(S,S-1)),b.set(S-1,S,-(b.get(S,S)-K)/b.get(S,S-1))):(dt=it(0,-b.get(S-1,S),b.get(S-1,S-1)-K,ce),b.set(S-1,S-1,dt[0]),b.set(S-1,S,dt[1])),b.set(S,S-1,0),b.set(S,S,1),ie=S-2;ie>=0;ie--){for(se=0,Ce=0,$e=ht;$e<=S;$e++)se=se+b.get(ie,$e)*b.get($e,S-1),Ce=Ce+b.get(ie,$e)*b.get($e,S);if(rt=b.get(ie,ie)-K,m[ie]<0)ge=rt,be=se,le=Ce;else if(ht=ie,m[ie]===0?(dt=it(-se,-Ce,rt,ce),b.set(ie,S-1,dt[0]),b.set(ie,S,dt[1])):(at=b.get(ie,ie+1),mt=b.get(ie+1,ie),Ke=(d[ie]-K)*(d[ie]-K)+m[ie]*m[ie]-ce*ce,Pe=(d[ie]-K)*2*ce,Ke===0&&Pe===0&&(Ke=X*ae*(Math.abs(rt)+Math.abs(ce)+Math.abs(at)+Math.abs(mt)+Math.abs(ge))),dt=it(at*be-ge*se+ce*Ce,at*le-ge*Ce-ce*se,Ke,Pe),b.set(ie,S-1,dt[0]),b.set(ie,S,dt[1]),Math.abs(at)>Math.abs(ge)+Math.abs(ce)?(b.set(ie+1,S-1,(-se-rt*b.get(ie,S-1)+ce*b.get(ie,S))/at),b.set(ie+1,S,(-Ce-rt*b.get(ie,S)-ce*b.get(ie,S-1))/at)):(dt=it(-be-mt*b.get(ie,S-1),-le-mt*b.get(ie,S),ge,ce),b.set(ie+1,S-1,dt[0]),b.set(ie+1,S,dt[1]))),gt=Math.max(Math.abs(b.get(ie,S-1)),Math.abs(b.get(ie,S))),X*gt*gt>1)for($e=ie;$e<=S;$e++)b.set($e,S-1,b.get($e,S-1)/gt),b.set($e,S,b.get($e,S)/gt)}for(ie=0;ie<M;ie++)if(ie<O||ie>q)for($e=ie;$e<M;$e++)c.set(ie,$e,b.get(ie,$e));for($e=M-1;$e>=O;$e--)for(ie=O;ie<=q;ie++){for(ge=0,Xe=O;Xe<=Math.min($e,q);Xe++)ge=ge+c.get(ie,Xe)*b.get(Xe,$e);c.set(ie,$e,ge)}}}function it(M,m,d,c){let b,S;return Math.abs(d)>Math.abs(c)?(b=c/d,S=d+b*c,[(M+b*m)/S,(m-b*M)/S]):(b=d/c,S=c+b*d,[(b*M+m)/S,(b*m-M)/S])}class I{constructor(m){if(m=he.checkMatrix(m),!m.isSymmetric())throw new Error("Matrix is not symmetric");let d=m,c=d.rows,b=new re(c,c),S=!0,O,q,X;for(q=0;q<c;q++){let j=0;for(X=0;X<q;X++){let ae=0;for(O=0;O<X;O++)ae+=b.get(X,O)*b.get(q,O);ae=(d.get(q,X)-ae)/b.get(X,X),b.set(q,X,ae),j=j+ae*ae}for(j=d.get(q,q)-j,S&&(S=j>0),b.set(q,q,Math.sqrt(Math.max(j,0))),X=q+1;X<c;X++)b.set(q,X,0)}this.L=b,this.positiveDefinite=S}isPositiveDefinite(){return this.positiveDefinite}solve(m){m=he.checkMatrix(m);let d=this.L,c=d.rows;if(m.rows!==c)throw new Error("Matrix dimensions do not match");if(this.isPositiveDefinite()===!1)throw new Error("Matrix is not positive definite");let b=m.columns,S=m.clone(),O,q,X;for(X=0;X<c;X++)for(q=0;q<b;q++){for(O=0;O<X;O++)S.set(X,q,S.get(X,q)-S.get(O,q)*d.get(X,O));S.set(X,q,S.get(X,q)/d.get(X,X))}for(X=c-1;X>=0;X--)for(q=0;q<b;q++){for(O=X+1;O<c;O++)S.set(X,q,S.get(X,q)-S.get(O,q)*d.get(O,X));S.set(X,q,S.get(X,q)/d.get(X,X))}return S}get lowerTriangularMatrix(){return this.L}}class fe{constructor(m,d={}){m=he.checkMatrix(m);let{Y:c}=d;const{scaleScores:b=!1,maxIterations:S=1e3,terminationCriteria:O=1e-10}=d;let q;if(c){if(e.isAnyArray(c)&&typeof c[0]=="number"?c=re.columnVector(c):c=he.checkMatrix(c),c.rows!==m.rows)throw new Error("Y should have the same number of rows as X");q=c.getColumnVector(0)}else q=m.getColumnVector(0);let X=1,j,ae,K,ce;for(let be=0;be<S&&X>O;be++)K=m.transpose().mmul(q).div(q.transpose().mmul(q).get(0,0)),K=K.div(K.norm()),j=m.mmul(K).div(K.transpose().mmul(K).get(0,0)),be>0&&(X=j.clone().sub(ce).pow(2).sum()),ce=j.clone(),c?(ae=c.transpose().mmul(j).div(j.transpose().mmul(j).get(0,0)),ae=ae.div(ae.norm()),q=c.mmul(ae).div(ae.transpose().mmul(ae).get(0,0))):q=j;if(c){let be=m.transpose().mmul(j).div(j.transpose().mmul(j).get(0,0));be=be.div(be.norm());let le=m.clone().sub(j.clone().mmul(be.transpose())),ge=q.transpose().mmul(j).div(j.transpose().mmul(j).get(0,0)),Ue=c.clone().sub(j.clone().mulS(ge.get(0,0)).mmul(ae.transpose()));this.t=j,this.p=be.transpose(),this.w=K.transpose(),this.q=ae,this.u=q,this.s=j.transpose().mmul(j),this.xResidual=le,this.yResidual=Ue,this.betas=ge}else this.w=K.transpose(),this.s=j.transpose().mmul(j).sqrt(),b?this.t=j.clone().div(this.s.get(0,0)):this.t=j,this.xResidual=m.sub(j.mmul(K.transpose()))}}return matrix$1.AbstractMatrix=_e,matrix$1.CHO=I,matrix$1.CholeskyDecomposition=I,matrix$1.DistanceMatrix=Fe,matrix$1.EVD=Ae,matrix$1.EigenvalueDecomposition=Ae,matrix$1.LU=Ze,matrix$1.LuDecomposition=Ze,matrix$1.Matrix=re,matrix$1.MatrixColumnSelectionView=Je,matrix$1.MatrixColumnView=Ye,matrix$1.MatrixFlipColumnView=et,matrix$1.MatrixFlipRowView=Ve,matrix$1.MatrixRowSelectionView=qe,matrix$1.MatrixRowView=tt,matrix$1.MatrixSelectionView=De,matrix$1.MatrixSubView=nt,matrix$1.MatrixTransposeView=Ge,matrix$1.NIPALS=fe,matrix$1.Nipals=fe,matrix$1.QR=Te,matrix$1.QrDecomposition=Te,matrix$1.SVD=lt,matrix$1.SingularValueDecomposition=lt,matrix$1.SymmetricMatrix=Ie,matrix$1.WrapperMatrix1D=Ne,matrix$1.WrapperMatrix2D=he,matrix$1.correlation=xe,matrix$1.covariance=ue,matrix$1.default=re,matrix$1.determinant=ze,matrix$1.inverse=ot,matrix$1.linearDependencies=st,matrix$1.pseudoInverse=Z,matrix$1.solve=Le,matrix$1.wrap=Qe,matrix$1}var matrixExports=requireMatrix();const matrix=getDefaultExportFromCjs(matrixExports),Matrix$1=matrixExports.Matrix,SVD=matrixExports.SVD,SingularValueDecomposition=matrixExports.SingularValueDecomposition;matrix.Matrix?matrix.Matrix:matrixExports.Matrix;const inverse=matrixExports.inverse,solve=matrixExports.solve;function getSeparatedKernel(e){const i=new SVD(e,{autoTranspose:!0});if(i.rank!==1)return null;const t=Math.sqrt(i.s[0]),n=i.U.to2DArray().map(s=>s[0]*t),a=i.V.to2DArray().map(s=>s[0]*t);return[n,a]}function convolution(e,i={}){let{channels:t,bitDepth:n,normalize:a=!1,divisor:s=1,border:o="copy",algorithm:h="auto"}=i,f={};n&&(f.bitDepth=n);let l=Image.createFrom(this,f);if(t=validateArrayOfChannels(this,t),h!=="separable")({kernel:e}=validateKernel(e));else if(!Array.isArray(e)||e.length!==2)throw new RangeError("separable convolution requires two arrays of numbers to represent the kernel");if(h==="auto"){let C=getSeparatedKernel(e);C!==null?(h="separable",e=C):(e.length>9||e[0].length>9)&&this.width<=4096&&this.height<=4096?h="fft":h="direct"}let u,w;h==="separable"?(u=Math.floor(e[0].length/2),w=Math.floor(e[1].length/2)):(u=Math.floor(e.length/2),w=Math.floor(e[0].length/2));let _=l.isClamped,g=new Array(this.height*this.width),v,k,A,T,$,D;for(T=0;T<t.length;T++){for($=t[T],A=0;A<this.height;A++)for(k=0;k<this.width;k++)v=A*this.width+k,g[v]=this.data[v*this.channels+$];if(h==="direct")D=srcExports$1.direct(g,e,{rows:this.height,cols:this.width,normalize:a,divisor:s});else if(h==="separable"){if(D=convolutionSeparable(g,e,this.width,this.height),a){s=0;for(let C=0;C<e[0].length;C++)for(let P=0;P<e[1].length;P++)s+=e[0][C]*e[1][P]}if(s!==1)for(let C=0;C<D.length;C++)D[C]/=s}else D=srcExports$1.fft(g,e,{rows:this.height,cols:this.width,normalize:a,divisor:s});for(A=0;A<this.height;A++)for(k=0;k<this.width;k++)v=A*this.width+k,_?l.data[v*this.channels+$]=clamp(D[v],l):l.data[v*this.channels+$]=D[v]}if(this.alpha&&!t.includes(this.channels))for(k=this.components;k<this.data.length;k=k+this.channels)l.data[k]=this.data[k];return o!=="periodic"&&l.setBorder({size:[w,u],algorithm:o}),l}function gradientFilter(e={}){let{direction:i="xy",border:t="copy",kernelX:n,kernelY:a,channels:s,bitDepth:o=this.bitDepth}=e;switch(this.checkProcessable("gradientFilter",{bitDepth:[8,16]}),i){case"x":if(!n)throw new Error("kernelX option is missing");return convolution.call(this,n,{channels:s,border:t,bitDepth:o});case"y":if(!a)throw new Error("kernelY option is missing");return convolution.call(this,a,{channels:s,border:t,bitDepth:o});case"xy":{if(!n)throw new Error("kernelX option is missing");if(!a)throw new Error("kernelY option is missing");const h=convolution.call(this,n,{channels:s,border:t,bitDepth:32}),f=convolution.call(this,a,{channels:s,border:t,bitDepth:32});return h.hypotenuse(f,{bitDepth:o,channels:s})}default:throw new Error(`Unknown parameter direction: ${i}`)}}function sobelFilter(e){return gradientFilter.call(this,Object.assign({},e,{kernelX:SOBEL_X,kernelY:SOBEL_Y}))}function scharrFilter(e){return gradientFilter.call(this,Object.assign({},e,{kernelX:SCHARR_X,kernelY:SCHARR_Y}))}var newArray_1,hasRequiredNewArray;function requireNewArray(){if(hasRequiredNewArray)return newArray_1;hasRequiredNewArray=1,newArray_1=e;function e(i,t){i=i||0;for(var n=new Array(i),a=0;a<i;a++)n[a]=t;return n}return newArray_1}var newArrayExports=requireNewArray();const newArray=getDefaultExportFromCjs(newArrayExports);function level(e={}){let{algorithm:i="range",channels:t,min:n=this.min,max:a=this.max}=e;switch(this.checkProcessable("level",{bitDepth:[8,16,32]}),t=validateArrayOfChannels(this,{channels:t}),t.length!==this.channel&&(Array.isArray(n)&&n.length===this.channels&&(n=n.filter((s,o)=>t.includes(o))),Array.isArray(a)&&a.length===this.channels&&(a=a.filter((s,o)=>t.includes(o)))),i){case"range":n<0&&(n=0),a>this.maxValue&&(a=this.maxValue),Array.isArray(n)||(n=newArray(t.length,n)),Array.isArray(a)||(a=newArray(t.length,a)),processImage(this,n,a,t);break;default:throw new Error(`level: algorithm not implement: ${i}`)}return this}function processImage(e,i,t,n){let a=1e-5,s=new Array(n.length);for(let o=0;o<n.length;o++)i[o]===0&&t[o]===e.maxValue||t[o]===i[o]?s[o]=0:s[o]=(e.maxValue+1-a)/(t[o]-i[o]),i[o]+=(.5-a/2)/s[o];for(let o=0;o<n.length;o++){let h=n[o];if(s[o]!==0)for(let f=0;f<e.data.length;f+=e.channels)e.data[f+h]=Math.min(Math.max(0,(e.data[f+h]-i[o])*s[o]+.5|0),e.maxValue)}}var isArrayType,hasRequiredIsArrayType;function requireIsArrayType(){if(hasRequiredIsArrayType)return isArrayType;hasRequiredIsArrayType=1;var e=Object.prototype.toString;return isArrayType=function(t){return e.call(t).substr(-6,5)==="Array"},isArrayType}var isArrayTypeExports=requireIsArrayType();const isArray=getDefaultExportFromCjs(isArrayTypeExports);function checkNumberArray(e){if(isNaN(e)){if(e instanceof Image)return e.data;if(!isArray(e))throw new Error("checkNumberArray: the value should be either a number, array or Image");return e}else{if(e<=0)throw new Error("checkNumberArray: the value must be greater than 0");return e}}function add(e,i={}){let{channels:t}=i;if(this.checkProcessable("add",{bitDepth:[8,16]}),t=validateArrayOfChannels(this,{channels:t}),e=checkNumberArray(e),isNaN(e)){if(this.data.length!==e.length)throw new Error("add: the data size is different");for(let n=0;n<t.length;n++){let a=t[n];for(let s=0;s<this.data.length;s+=this.channels)this.data[s+a]=Math.max(0,Math.min(this.maxValue,this.data[s+a]+e[s+a]>>0))}}else for(let n=0;n<t.length;n++){let a=t[n];for(let s=0;s<this.data.length;s+=this.channels)this.data[s+a]=Math.min(this.maxValue,this.data[s+a]+e>>0)}return this}function subtract(e,i={}){let{channels:t}=i;if(this.checkProcessable("subtract",{bitDepth:[8,16]}),t=validateArrayOfChannels(this,{channels:t}),e=checkNumberArray(e),isNaN(e)){if(this.data.length!==e.length)throw new Error("subtract: the data size is different");for(let n=0;n<t.length;n++){let a=t[n];for(let s=0;s<this.data.length;s+=this.channels)this.data[s+a]=Math.max(0,Math.min(this.maxValue,this.data[s+a]-e[s+a]>>0))}}else for(let n=0;n<t.length;n++){let a=t[n];for(let s=0;s<this.data.length;s+=this.channels)this.data[s+a]=Math.max(0,this.data[s+a]-e>>0)}return this}function subtractImage(e,i={}){let{channels:t,absolute:n=!1}=i;if(this.checkProcessable("subtractImage",{bitDepth:[8,16]}),this.width!==e.width||this.height!==e.height)throw new Error("subtractImage: both images must have the same size");if(this.alpha!==e.alpha||this.bitDepth!==e.bitDepth)throw new Error("subtractImage: both images must have the same alpha and bitDepth");if(this.channels!==e.channels)throw new Error("subtractImage: both images must have the same number of channels");let a=this.clone();t=validateArrayOfChannels(this,{channels:t});for(let s=0;s<t.length;s++){let o=t[s];for(let h=o;h<this.data.length;h+=this.channels){let f=this.data[h]-e.data[h];n?a.data[h]=Math.abs(f):a.data[h]=Math.max(f,0)}}return a}function hypotenuse(e,i={}){let{bitDepth:t=this.bitDepth,channels:n}=i;if(this.checkProcessable("hypotenuse",{bitDepth:[8,16,32]}),this.width!==e.width||this.height!==e.height)throw new Error("hypotenuse: both images must have the same size");if(this.alpha!==e.alpha||this.bitDepth!==e.bitDepth)throw new Error("hypotenuse: both images must have the same alpha and bitDepth");if(this.channels!==e.channels)throw new Error("hypotenuse: both images must have the same number of channels");let a=Image.createFrom(this,{bitDepth:t});n=validateArrayOfChannels(this,{channels:n});let s=a.isClamped;for(let o=0;o<n.length;o++){let h=n[o];for(let f=h;f<this.data.length;f+=this.channels){let l=Math.hypot(this.data[f],e.data[f]);s?a.data[f]=Math.min(Math.max(Math.round(l),0),a.maxValue):a.data[f]=l}}return a}function multiply(e,i={}){let{channels:t}=i;if(this.checkProcessable("multiply",{bitDepth:[8,16]}),e<=0)throw new Error("multiply: the value must be greater than 0");if(t=validateArrayOfChannels(this,{channels:t}),e=checkNumberArray(e),isNaN(e)){if(this.data.length!==e.length)throw new Error("multiply: the data size is different");for(let n=0;n<t.length;n++){let a=t[n];for(let s=0;s<this.data.length;s+=this.channels)this.data[s+a]=Math.max(0,Math.min(this.maxValue,this.data[s+a]*e[s+a]>>0))}}else for(let n=0;n<t.length;n++){let a=t[n];for(let s=0;s<this.data.length;s+=this.channels)this.data[s+a]=Math.min(this.maxValue,this.data[s+a]*e>>0)}return this}function divide(e,i={}){let{channels:t}=i;if(this.checkProcessable("divide",{bitDepth:[8,16]}),t=validateArrayOfChannels(this,{channels:t}),e=checkNumberArray(e),isNaN(e)){if(this.data.length!==e.length)throw new Error("divide: the: the data size is different");for(let n=0;n<t.length;n++){let a=t[n];for(let s=0;s<this.data.length;s+=this.channels)this.data[s+a]=Math.max(0,Math.min(this.maxValue,this.data[s+a]/e[s+a]>>0))}}else for(let n=0;n<t.length;n++){let a=t[n];for(let s=0;s<this.data.length;s+=this.channels)this.data[s+a]=Math.min(this.maxValue,this.data[s+a]/e>>0)}return this}class BaseRegression{constructor(){if(new.target===BaseRegression)throw new Error("BaseRegression must be subclassed")}predict(i){if(typeof i=="number")return this._predict(i);if(isAnyArray(i)){const t=[];for(let n=0;n<i.length;n++)t.push(this._predict(i[n]));return t}else throw new TypeError("x must be a number or array")}_predict(){throw new Error("_predict must be implemented")}train(){}toString(){return""}toLaTeX(){return""}score(i,t){if(!isAnyArray(i)||!isAnyArray(t)||i.length!==t.length)throw new Error("x and y must be arrays of the same length");const n=i.length,a=new Array(n);for(let g=0;g<n;g++)a[g]=this._predict(i[g]);let s=0,o=0,h=0,f=0,l=0,u=0,w=0;for(let g=0;g<n;g++)s+=a[g],o+=t[g],l+=a[g]*a[g],u+=t[g]*t[g],w+=a[g]*t[g],t[g]!==0&&(h+=(t[g]-a[g])*(t[g]-a[g])/t[g]),f+=(t[g]-a[g])*(t[g]-a[g]);const _=(n*w-s*o)/Math.sqrt((n*l-s*s)*(n*u-o*o));return{r:_,r2:_*_,chi2:h,rmsd:Math.sqrt(f/n)}}}function squaredEuclidean(e,i){let t=0;for(let n=0;n<e.length;n++)t+=(e[n]-i[n])*(e[n]-i[n]);return t}function euclidean(e,i){return Math.sqrt(squaredEuclidean(e,i))}const euclidean$1=Object.freeze(Object.defineProperty({__proto__:null,euclidean,squaredEuclidean},Symbol.toStringTag,{value:"Module"})),require$$0=getAugmentedNamespace(euclidean$1);var gaussianKernel,hasRequiredGaussianKernel;function requireGaussianKernel(){if(hasRequiredGaussianKernel)return gaussianKernel;hasRequiredGaussianKernel=1;const{squaredEuclidean:e}=require$$0,i={sigma:1};class t{constructor(a){a=Object.assign({},i,a),this.sigma=a.sigma,this.divisor=2*a.sigma*a.sigma}compute(a,s){const o=e(a,s);return Math.exp(-o/this.divisor)}}return gaussianKernel=t,gaussianKernel}var polynomialKernel,hasRequiredPolynomialKernel;function requirePolynomialKernel(){if(hasRequiredPolynomialKernel)return polynomialKernel;hasRequiredPolynomialKernel=1;const e={degree:1,constant:1,scale:1};class i{constructor(n){n=Object.assign({},e,n),this.degree=n.degree,this.constant=n.constant,this.scale=n.scale}compute(n,a){for(var s=0,o=0;o<n.length;o++)s+=n[o]*a[o];return Math.pow(this.scale*s+this.constant,this.degree)}}return polynomialKernel=i,polynomialKernel}var sigmoidKernel,hasRequiredSigmoidKernel;function requireSigmoidKernel(){if(hasRequiredSigmoidKernel)return sigmoidKernel;hasRequiredSigmoidKernel=1;const e={alpha:.01,constant:-Math.E};class i{constructor(n){n=Object.assign({},e,n),this.alpha=n.alpha,this.constant=n.constant}compute(n,a){for(var s=0,o=0;o<n.length;o++)s+=n[o]*a[o];return Math.tanh(this.alpha*s+this.constant)}}return sigmoidKernel=i,sigmoidKernel}var anovaKernel,hasRequiredAnovaKernel;function requireAnovaKernel(){if(hasRequiredAnovaKernel)return anovaKernel;hasRequiredAnovaKernel=1;const e={sigma:1,degree:1};class i{constructor(n){n=Object.assign({},e,n),this.sigma=n.sigma,this.degree=n.degree}compute(n,a){for(var s=0,o=Math.min(n.length,a.length),h=1;h<=o;++h)s+=Math.pow(Math.exp(-this.sigma*Math.pow(Math.pow(n[h-1],h)-Math.pow(a[h-1],h),2)),this.degree);return s}}return anovaKernel=i,anovaKernel}var cauchyKernel,hasRequiredCauchyKernel;function requireCauchyKernel(){if(hasRequiredCauchyKernel)return cauchyKernel;hasRequiredCauchyKernel=1;const{squaredEuclidean:e}=require$$0,i={sigma:1};class t{constructor(a){a=Object.assign({},i,a),this.sigma=a.sigma}compute(a,s){return 1/(1+e(a,s)/(this.sigma*this.sigma))}}return cauchyKernel=t,cauchyKernel}var exponentialKernel,hasRequiredExponentialKernel;function requireExponentialKernel(){if(hasRequiredExponentialKernel)return exponentialKernel;hasRequiredExponentialKernel=1;const{euclidean:e}=require$$0,i={sigma:1};class t{constructor(a){a=Object.assign({},i,a),this.sigma=a.sigma,this.divisor=2*a.sigma*a.sigma}compute(a,s){const o=e(a,s);return Math.exp(-o/this.divisor)}}return exponentialKernel=t,exponentialKernel}var histogramIntersectionKernel,hasRequiredHistogramIntersectionKernel;function requireHistogramIntersectionKernel(){if(hasRequiredHistogramIntersectionKernel)return histogramIntersectionKernel;hasRequiredHistogramIntersectionKernel=1;class e{compute(t,n){for(var a=Math.min(t.length,n.length),s=0,o=0;o<a;++o)s+=Math.min(t[o],n[o]);return s}}return histogramIntersectionKernel=e,histogramIntersectionKernel}var laplacianKernel,hasRequiredLaplacianKernel;function requireLaplacianKernel(){if(hasRequiredLaplacianKernel)return laplacianKernel;hasRequiredLaplacianKernel=1;const{euclidean:e}=require$$0,i={sigma:1};class t{constructor(a){a=Object.assign({},i,a),this.sigma=a.sigma}compute(a,s){const o=e(a,s);return Math.exp(-o/this.sigma)}}return laplacianKernel=t,laplacianKernel}var multiquadraticKernel,hasRequiredMultiquadraticKernel;function requireMultiquadraticKernel(){if(hasRequiredMultiquadraticKernel)return multiquadraticKernel;hasRequiredMultiquadraticKernel=1;const{squaredEuclidean:e}=require$$0,i={constant:1};class t{constructor(a){a=Object.assign({},i,a),this.constant=a.constant}compute(a,s){return Math.sqrt(e(a,s)+this.constant*this.constant)}}return multiquadraticKernel=t,multiquadraticKernel}var rationalQuadraticKernel,hasRequiredRationalQuadraticKernel;function requireRationalQuadraticKernel(){if(hasRequiredRationalQuadraticKernel)return rationalQuadraticKernel;hasRequiredRationalQuadraticKernel=1;const{squaredEuclidean:e}=require$$0,i={constant:1};class t{constructor(a){a=Object.assign({},i,a),this.constant=a.constant}compute(a,s){const o=e(a,s);return 1-o/(o+this.constant)}}return rationalQuadraticKernel=t,rationalQuadraticKernel}var kernel,hasRequiredKernel;function requireKernel(){if(hasRequiredKernel)return kernel;hasRequiredKernel=1;const{Matrix:e,MatrixTransposeView:i}=requireMatrix(),t=requireGaussianKernel(),n=requirePolynomialKernel(),a=requireSigmoidKernel(),s=requireAnovaKernel(),o=requireCauchyKernel(),h=requireExponentialKernel(),f=requireHistogramIntersectionKernel(),l=requireLaplacianKernel(),u=requireMultiquadraticKernel(),w=requireRationalQuadraticKernel(),_={gaussian:t,rbf:t,polynomial:n,poly:n,anova:s,cauchy:o,exponential:h,histogram:f,min:f,laplacian:l,multiquadratic:u,rational:w,sigmoid:a,mlp:a};class g{constructor(k,A){if(this.kernelType=k,k!=="linear")if(typeof k=="string"){k=k.toLowerCase();var T=_[k];if(T)this.kernelFunction=new T(A);else throw new Error(`unsupported kernel type: ${k}`)}else if(typeof k=="object"&&typeof k.compute=="function")this.kernelFunction=k;else throw new TypeError("first argument must be a valid kernel type or instance")}compute(k,A){if(k=e.checkMatrix(k),A===void 0?A=k:A=e.checkMatrix(A),this.kernelType==="linear")return k.mmul(new i(A));const T=new e(k.rows,A.rows);if(k===A)for(let $=0;$<k.rows;$++)for(let D=$;D<k.rows;D++){const C=this.kernelFunction.compute(k.getRow($),k.getRow(D));T.set($,D,C),T.set(D,$,C)}else for(let $=0;$<k.rows;$++)for(let D=0;D<A.rows;D++)T.set($,D,this.kernelFunction.compute(k.getRow($),A.getRow(D)));return T}}return kernel=g,kernel}var kernelExports=requireKernel();const Kernel=getDefaultExportFromCjs(kernelExports),defaultOptions$2={lambda:.1,kernelType:"gaussian",kernelOptions:{},computeCoefficient:!1};class KernelRidgeRegression extends BaseRegression{constructor(i,t,n){if(super(),i===!0)this.alpha=t.alpha,this.inputs=t.inputs,this.kernelType=t.kernelType,this.kernelOptions=t.kernelOptions,this.kernel=new Kernel(t.kernelType,t.kernelOptions);else{i=Matrix$1.checkMatrix(i),n=Object.assign({},defaultOptions$2,n);const a=new Kernel(n.kernelType,n.kernelOptions),s=a.compute(i),o=i.rows;s.add(Matrix$1.eye(o,o).mul(n.lambda)),this.alpha=solve(s,t),this.inputs=i,this.kernelType=n.kernelType,this.kernelOptions=n.kernelOptions,this.kernel=a}}_predict(i){return this.kernel.compute([i],this.inputs).mmul(this.alpha).getRow(0)}toJSON(){return{name:"kernelRidgeRegression",alpha:this.alpha,inputs:this.inputs,kernelType:this.kernelType,kernelOptions:this.kernelOptions}}static load(i){if(i.name!=="kernelRidgeRegression")throw new TypeError("not a KRR model");return new KernelRidgeRegression(!0,i)}}function background$1(e,i,t){const n=new KernelRidgeRegression(e,i,t),a=new Array(this.size);for(let h=0;h<this.width;h++)for(let f=0;f<this.height;f++)a[f*this.width+h]=[h,f];const s=n.predict(a),o=Image.createFrom(this);for(let h=0;h<this.size;h++)o.data[h]=Math.min(this.maxValue,Math.max(0,s[h][0]));return o}function dilate(e={}){let{kernel:i=[[1,1,1],[1,1,1],[1,1,1]],iterations:t=1}=e;if(this.checkProcessable("dilate",{bitDepth:[1,8,16],components:1,alpha:0}),i.columns%2===0||i.rows%2===0)throw new TypeError("dilate: The number of rows and columns of the kernel must be odd");let n=!0;e:for(const s of i)for(const o of s)if(o!==1){n=!1;break e}let a=this;for(let s=0;s<t;s++)if(this.bitDepth===1)if(n){const o=a.clone();a=dilateOnceBinaryOnlyOnes(a,o,i.length,i[0].length)}else{const o=Image.createFrom(a);a=dilateOnceBinary(a,o,i)}else if(n){const o=Image.createFrom(a);a=dilateOnceGreyOnlyOnes(a,o,i.length,i[0].length)}else{const o=Image.createFrom(a);a=dilateOnceGrey(a,o,i)}return a}function dilateOnceGrey(e,i,t){const n=t.length,a=t[0].length;let s=(n-1)/2,o=(a-1)/2;for(let h=0;h<e.height;h++)for(let f=0;f<e.width;f++){let l=0;for(let u=0;u<a;u++)for(let w=0;w<n;w++){if(t[w][u]!==1)continue;let _=w-s+f,g=u-o+h;if(_<0||g<0||_>=e.width||g>=e.height)continue;const v=e.getValueXY(_,g,0);v>l&&(l=v)}i.setValueXY(f,h,0,l)}return i}function dilateOnceGreyOnlyOnes(e,i,t,n){const a=(t-1)/2,s=(n-1)/2,o=[];for(let h=0;h<e.width;h++)o.push(0);for(let h=0;h<e.height;h++){for(let f=0;f<e.width;f++){let l=0;for(let u=Math.max(0,h-s);u<Math.min(e.height,h+s+1);u++){const w=e.getValueXY(f,u,0);w>l&&(l=w)}o[f]=l}for(let f=0;f<e.width;f++){let l=0;for(let u=Math.max(0,f-a);u<Math.min(e.width,f+a+1);u++)o[u]>l&&(l=o[u]);i.setValueXY(f,h,0,l)}}return i}function dilateOnceBinary(e,i,t){const n=t.length,a=t[0].length;let s=(n-1)/2,o=(a-1)/2;for(let h=0;h<e.height;h++)for(let f=0;f<e.width;f++){let l=0;e:for(let u=0;u<a;u++)for(let w=0;w<n;w++){if(t[w][u]!==1)continue;let _=w-s+f,g=u-o+h;if(g<0||_<0||_>=e.width||g>=e.height)continue;if(e.getBitXY(_,g)===1){l=1;break e}}l===1&&i.setBitXY(f,h)}return i}function dilateOnceBinaryOnlyOnes(e,i,t,n){const a=(t-1)/2,s=(n-1)/2,o=[];for(let h=0;h<e.width;h++)o.push(1);for(let h=0;h<e.height;h++){for(let f=0;f<e.width;f++){o[f]=0;for(let l=Math.max(0,h-s);l<Math.min(e.height,h+s+1);l++)if(e.getBitXY(f,l)===1){o[f]=1;break}}for(let f=0;f<e.width;f++)if(i.getBitXY(f,h)!==1){for(let l=Math.max(0,f-a);l<Math.min(e.width,f+a+1);l++)if(o[l]===1){i.setBitXY(f,h);break}}}return i}function erode(e={}){let{kernel:i=[[1,1,1],[1,1,1],[1,1,1]],iterations:t=1}=e;if(this.checkProcessable("erode",{bitDepth:[1,8,16],components:1,alpha:0}),i.columns%2===0||i.rows%2===0)throw new TypeError("erode: The number of rows and columns of the kernel must be odd");let n=!0;e:for(const s of i)for(const o of s)if(o!==1){n=!1;break e}let a=this;for(let s=0;s<t;s++)if(this.bitDepth===1)if(n){const o=a.clone();a=erodeOnceBinaryOnlyOnes(a,o,i.length,i[0].length)}else{const o=Image.createFrom(a);a=erodeOnceBinary(a,o,i)}else if(n){const o=Image.createFrom(a);a=erodeOnceGreyOnlyOnes(a,o,i.length,i[0].length)}else{const o=Image.createFrom(a);a=erodeOnceGrey(a,o,i)}return a}function erodeOnceGrey(e,i,t){const n=t.length,a=t[0].length;let s=(n-1)/2,o=(a-1)/2;for(let h=0;h<e.height;h++)for(let f=0;f<e.width;f++){let l=e.maxValue;for(let u=0;u<a;u++)for(let w=0;w<n;w++){if(t[w][u]!==1)continue;let _=w-s+f,g=u-o+h;if(_<0||g<0||_>=e.width||g>=e.height)continue;const v=e.getValueXY(_,g,0);v<l&&(l=v)}i.setValueXY(f,h,0,l)}return i}function erodeOnceGreyOnlyOnes(e,i,t,n){const a=(t-1)/2,s=(n-1)/2,o=[];for(let h=0;h<e.width;h++)o.push(0);for(let h=0;h<e.height;h++){for(let f=0;f<e.width;f++){let l=e.maxValue;for(let u=Math.max(0,h-s);u<Math.min(e.height,h+s+1);u++){const w=e.getValueXY(f,u,0);w<l&&(l=w)}o[f]=l}for(let f=0;f<e.width;f++){let l=e.maxValue;for(let u=Math.max(0,f-a);u<Math.min(e.width,f+a+1);u++)o[u]<l&&(l=o[u]);i.setValueXY(f,h,0,l)}}return i}function erodeOnceBinary(e,i,t){const n=t.length,a=t[0].length;let s=(n-1)/2,o=(a-1)/2;for(let h=0;h<e.height;h++)for(let f=0;f<e.width;f++){let l=1;e:for(let u=0;u<a;u++)for(let w=0;w<n;w++){if(t[w][u]!==1)continue;let _=w-s+f,g=u-o+h;if(g<0||_<0||_>=e.width||g>=e.height)continue;if(e.getBitXY(_,g)===0){l=0;break e}}l===1&&i.setBitXY(f,h)}return i}function erodeOnceBinaryOnlyOnes(e,i,t,n){const a=(t-1)/2,s=(n-1)/2,o=[];for(let h=0;h<e.width;h++)o.push(0);for(let h=0;h<e.height;h++){for(let f=0;f<e.width;f++){o[f]=1;for(let l=Math.max(0,h-s);l<Math.min(e.height,h+s+1);l++)if(e.getBitXY(f,l)===0){o[f]=0;break}}for(let f=0;f<e.width;f++)if(i.getBitXY(f,h)!==0){for(let l=Math.max(0,f-a);l<Math.min(e.width,f+a+1);l++)if(o[l]===0){i.clearBitXY(f,h);break}}}return i}function open(e={}){let{kernel:i=[[1,1,1],[1,1,1],[1,1,1]],iterations:t=1}=e;if(this.checkProcessable("open",{bitDepth:[8,16],components:1,alpha:0}),i.columns%2===0||i.rows%2===0)throw new TypeError("open: The number of rows and columns of the kernel must be odd");let n=this;for(let a=0;a<t;a++)n=n.erode({kernel:i}),n=n.dilate({kernel:i});return n}function close(e={}){let{kernel:i=[[1,1,1],[1,1,1],[1,1,1]],iterations:t=1}=e;if(this.checkProcessable("close",{bitDepth:[1,8,16],components:1,alpha:0}),i.columns%2===0||i.rows%2===0)throw new TypeError("close: The number of rows and columns of the kernel must be odd");let n=this;for(let a=0;a<t;a++)n=n.dilate({kernel:i}).erode({kernel:i});return n}function topHat(e={}){let{kernel:i=[[1,1,1],[1,1,1],[1,1,1]],iterations:t=1}=e;if(this.checkProcessable("topHat",{bitDepth:[8,16],components:1,alpha:0}),i.length%2===0||i[0].length%2===0)throw new TypeError("topHat: The number of rows and columns of the kernel must be odd");let n=this;for(let a=0;a<t;a++)n=n.open({kernel:i}).subtractImage(n,{absolute:!0});return n}function blackHat(e={}){let{kernel:i=[[1,1,1],[1,1,1],[1,1,1]],iterations:t=1}=e;if(this.checkProcessable("blackHat",{bitDepth:[8,16],components:1,alpha:0}),i.columns%2===0||i.rows%2===0)throw new TypeError("blackHat: The number of rows and columns of the kernel must be odd");let n=this;for(let a=0;a<t;a++)n=n.close({kernel:i}).subtractImage(n,{absolute:!0});return n}function morphologicalGradient(e={}){let{kernel:i=[[1,1,1],[1,1,1],[1,1,1]],iterations:t=1}=e;if(this.checkProcessable("morphologicalGradient",{bitDepth:[8,16],components:1,alpha:0}),i.columns%2===0||i.rows%2===0)throw new TypeError("morphologicalGradient: The number of rows and columns of the kernel must be odd");let n=this;for(let a=0;a<t;a++){let s=n.dilate({kernel:i}),o=n.erode({kernel:i});n=s.subtractImage(o,{absolute:!0})}return n}function order4Points(e){let i=0,t=0,n=0,a=0,s=e[0][0],o=0;for(let l=1;l<e.length;l++)e[l][0]<s&&(s=e[l][0],o=l);let h=e[(o+1)%e.length][0],f=(o+1)%e.length;for(let l=1;l<e.length;l++)e[l][0]<h&&l!==o&&(h=e[l][0],f=l);return e[f][1]<e[o][1]?(i=e[f],a=e[o],o!==(f+1)%4?(t=e[(f+1)%4],n=e[(f+2)%4]):(t=e[(f+2)%4],n=e[(f+3)%4])):(a=e[f],i=e[o],f!==(o+1)%4?(t=e[(o+1)%4],n=e[(o+2)%4]):(t=e[(o+2)%4],n=e[(o+3)%4])),[i,t,n,a]}function distance2Points(e,i){return Math.sqrt(Math.pow(e[0]-i[0],2)+Math.pow(e[1]-i[1],2))}function crossVect(e,i){return[e[1]*i[2]-e[2]*i[1],e[2]*i[0]-e[0]*i[2],e[0]*i[1]-e[1]*i[0]]}function dotVect(e,i){return e[0]*i[0]+e[1]*i[1]+e[2]*i[2]}function computeWidthAndHeigth(e,i,t,n,a,s){let o=Math.max(distance2Points(e,i),distance2Points(n,t)),h=Math.max(distance2Points(e,n),distance2Points(i,t)),f=0,l=0,u=Math.ceil(a/2),w=Math.ceil(s/2),_=o/h,g=[e[0],e[1],1],v=[i[0],i[1],1],k=[n[0],n[1],1],A=[t[0],t[1],1],T=dotVect(crossVect(g,A),k)/dotVect(crossVect(v,A),k),$=dotVect(crossVect(g,A),v)/dotVect(crossVect(k,A),v),D=[T*v[0]-g[0],T*v[1]-g[1],T*v[2]-g[2]],C=[$*k[0]-g[0],$*k[1]-g[1],$*k[2]-g[2]],P=D[0],z=D[1],B=D[2],F=C[0],L=C[1],N=C[2],G=1/(B*N)*(P*F-(P*N+B*F)*u+B*N*u*u+(z*L-(z*N+B*L)*w+B*N*w*w));G>=0?G=Math.sqrt(G):G=Math.sqrt(-G);let V=new Matrix$1([[G,0,u],[0,G,w],[0,0,1]]),J=V.transpose(),Q=inverse(J),W=inverse(V),ne=Matrix$1.rowVector(D),me=Matrix$1.rowVector(C),ve=Math.sqrt(dotVect(ne.mmul(Q).mmul(W).to1DArray(),D)/dotVect(me.mmul(Q).mmul(W).to1DArray(),C));return ve===0||_===0?(f=Math.ceil(o),l=Math.ceil(h)):ve<_?(f=Math.ceil(o),l=Math.ceil(f/ve)):(l=Math.ceil(h),f=Math.ceil(ve*l)),[f,l]}function projectionPoint(e,i,t,n,a,s,o,h,f,l,u,w){let[_,g]=[(t*e+n*i+a)/(f*e+l*i+1),(s*e+o*i+h)/(f*e+l*i+1)];return u.getValueXY(Math.floor(_),Math.floor(g),w)}function warpingFourPoints(e,i={}){let{calculateRatio:t=!0}=i;if(e.length!==4)throw new Error(`The array pts must have four elements, which are the four corners. Currently, pts have ${e.length} elements`);let[n,a,s,o]=e,h=[n,a,s,o],[f,l,u,w]=order4Points(h),_,g;t?[_,g]=computeWidthAndHeigth(f,l,u,w,this.width,this.height):(_=Math.ceil(Math.max(distance2Points(f,l),distance2Points(w,u))),g=Math.ceil(Math.max(distance2Points(f,w),distance2Points(l,u))));let v=Image.createFrom(this,{width:_,height:g}),[k,A]=f,[T,$]=l,[D,C]=u,[P,z]=w,[B,F]=[0,0],[L,N]=[0,_-1],[G,V]=[g-1,_-1],[J,Q]=[g-1,0],W=new Matrix$1([[B,F,1,0,0,0,-B*k,-F*k],[L,N,1,0,0,0,-L*T,-N*T],[G,V,1,0,0,0,-G*D,-F*D],[J,Q,1,0,0,0,-J*P,-Q*P],[0,0,0,B,F,1,-B*A,-F*A],[0,0,0,L,N,1,-L*$,-N*$],[0,0,0,G,V,1,-G*C,-V*C],[0,0,0,J,Q,1,-J*z,-Q*z]]),ne=Matrix$1.columnVector([k,T,D,P,A,$,C,z]),ve=new SingularValueDecomposition(W).solve(ne),[ye,Me,Re,_e,Be,Se,re,Ie]=ve.to1DArray(),Fe=new Matrix$1(g,_);for(let ke=0;ke<this.channels;ke++){for(let Ye=0;Ye<g;Ye++)for(let Je=0;Je<_;Je++)Fe.set(Ye,Je,projectionPoint(Ye,Je,ye,Me,Re,_e,Be,Se,re,Ie,this,ke));v.setMatrix(Fe,{channel:ke})}return v}function crop(e={}){let{x:i=0,y:t=0,width:n=this.width-i,height:a=this.height-t}=e;if(this.checkProcessable("crop",{bitDepth:[1,8,16]}),i=Math.round(i),t=Math.round(t),n=Math.round(n),a=Math.round(a),i>this.width-1||t>this.height-1)throw new RangeError(`crop: origin (x:${i}, y:${t}) out of range (${this.width-1}; ${this.height-1})`);if(n<=0||a<=0)throw new RangeError(`crop: width and height (width:${n}; height:${a}) must be positive numbers`);if(i<0||t<0)throw new RangeError(`crop: x and y (x:${i}, y:${t}) must be positive numbers`);if(n>this.width-i||a>this.height-t)throw new RangeError(`crop: (x: ${i}, y:${t}, width:${n}, height:${a}) size is out of range`);let s=this;if(this.bitDepth===1){const o=new Image(n,a,{kind:"BINARY",parent:this});s=cropBinary(this,o,i,t,n,a)}else{const o=Image.createFrom(this,{width:n,height:a,position:[i,t]});s=cropDefault(this,o,i,t,n,a)}return s}function cropDefault(e,i,t,n,a,s){let o=a*e.channels,h=n+s,f=0,l=t*e.channels;for(let u=n;u<h;u++){let w=u*e.width*e.channels+l,_=w+o;for(;w<_;w++)i.data[f++]=e.data[w]}return i}function cropBinary(e,i,t,n,a,s){let o=a*e.channels,h=n+s,f=0,l=t*e.channels;for(let u=n;u<h;u++){let w=u*e.width*e.channels+l,_=w+o;for(;w<_;w++)e.getBit(w)&&i.setBit(f),++f}return i}function cropAlpha(e={}){this.checkProcessable("cropAlpha",{alpha:1});const{threshold:i=this.maxValue}=e;let t=findLeft(this,i,this.components);if(t===-1)throw new Error("Could not find new dimensions. Threshold may be too high.");let n=findTop(this,i,this.components,t),a=findBottom(this,i,this.components,t),s=findRight(this,i,this.components,t,n,a);return this.crop({x:t,y:n,width:s-t+1,height:a-n+1})}function findLeft(e,i,t){for(let n=0;n<e.width;n++)for(let a=0;a<e.height;a++)if(e.getValueXY(n,a,t)>=i)return n;return-1}function findTop(e,i,t,n){for(let a=0;a<e.height;a++)for(let s=n;s<e.width;s++)if(e.getValueXY(s,a,t)>=i)return a;return-1}function findBottom(e,i,t,n){for(let a=e.height-1;a>=0;a--)for(let s=n;s<e.width;s++)if(e.getValueXY(s,a,t)>=i)return a;return-1}function findRight(e,i,t,n,a,s){for(let o=e.width-1;o>=n;o--)for(let h=a;h<=s;h++)if(e.getValueXY(o,h,t)>=i)return o;return-1}function getFactor(e){if(typeof e=="string"){const i=e[e.length-1];e=parseFloat(e),i==="%"&&(e/=100)}return e}function getThreshold$1(e,i){if(!i)throw Error("getThreshold : the maxValue should be specified");if(typeof e=="string"){if(e[e.length-1]!=="%")throw Error("getThreshold : if the value is a string it must finish by %");return parseFloat(e)/100*i}else{if(typeof e=="number")return e<1?e*i:e;throw Error("getThreshold : the value is not valid")}}function factorDimensions(e,i,t){e=getFactor(e);let n=Math.round(e*i),a=Math.round(e*t);return n<=0&&(n=1),a<=0&&(a=1),{width:n,height:a}}function checkRow(e,i){if(i<0||i>=e.height)throw new RangeError(`row must be included between 0 and ${e.height-1}. Current value: ${i}`)}function checkColumn(e,i){if(i<0||i>=e.width)throw new RangeError(`column must be included between 0 and ${e.width-1}. Current value: ${i}`)}function checkChannel(e,i){if(i<0||i>=e.channels)throw new RangeError(`channel must be included between 0 and ${e.channels-1}. Current value: ${i}`)}const validInterpolations={nearestneighbor:"nearestNeighbor",nearestneighbour:"nearestNeighbor",bilinear:"bilinear"};function checkInterpolation(e){if(typeof e!="string")throw new TypeError("interpolation must be a string");if(e=e.toLowerCase(),!validInterpolations[e])throw new RangeError(`invalid interpolation algorithm: ${e}`);return validInterpolations[e]}function nearestNeighbor(e,i,t){const n=this.width/i,a=this.height/t;if(this.bitDepth>1)for(let s=0;s<i;s++){const o=Math.floor((s+.5)*n);for(let h=0;h<t;h++){const f=Math.floor((h+.5)*a);for(let l=0;l<this.channels;l++)e.setValueXY(s,h,l,this.getValueXY(o,f,l))}}else for(let s=0;s<i;s++){const o=Math.floor((s+.5)*n);for(let h=0;h<t;h++){const f=Math.floor((h+.5)*a);this.getBitXY(o,f)&&e.setBitXY(s,h)}}}function resize(e={}){const{factor:i=1,interpolation:t=validInterpolations.nearestneighbor,preserveAspectRatio:n=!0}=e,a=checkInterpolation(t);let s=e.width,o=e.height;if(s||(o&&n?s=Math.round(o*(this.width/this.height)):s=this.width),o||(n?o=Math.round(s*(this.height/this.width)):o=this.height),{width:s,height:o}=factorDimensions(i,s,o),s===this.width&&o===this.height){const u=this.clone();return u.position=[0,0],u}let h=Math.round((this.width-s)/2),f=Math.round((this.height-o)/2);const l=Image.createFrom(this,{width:s,height:o,position:[h,f]});switch(a){case validInterpolations.nearestneighbor:nearestNeighbor.call(this,l,s,o);break;default:throw new Error(`unsupported resize interpolation: ${a}`)}return l}function hsv(){this.checkProcessable("hsv",{bitDepth:[8,16],alpha:[0,1],colorModel:[RGB$1]});let e=Image.createFrom(this,{colorModel:HSV}),i=0,t=this.data;for(let n=0;n<t.length;n+=this.channels){let a=t[n],s=t[n+1],o=t[n+2],h=Math.min(a,s,o),f=Math.max(a,s,o),l=f-h,u=0,w=f===0?0:l/f,_=f;if(f!==h){switch(f){case a:u=(s-o)/l+(s<o?6:0);break;case s:u=(o-a)/l+2;break;case o:u=(a-s)/l+4;break;default:throw new Error("unreachable")}u/=6}e.data[i++]=u*this.maxValue,e.data[i++]=w*this.maxValue,e.data[i++]=_,this.alpha&&(e.data[i++]=t[n+3])}return e}function hsl$1(){this.checkProcessable("hsl",{bitDepth:[8,16],alpha:[0,1],colorModel:[RGB$1]});let e=Image.createFrom(this,{colorModel:HSL}),i=Math.floor(this.maxValue/2),t=0,n=this.data;for(let a=0;a<n.length;a+=this.channels){let s=n[a],o=n[a+1],h=n[a+2],f=Math.max(s,o,h),l=Math.min(s,o,h),u=0,w=0,_=(f+l)/2;if(f!==l){let g=f-l;switch(w=_>i?g/(2-f-l):g/(f+l),f){case s:u=(o-h)/g+(o<h?6:0);break;case o:u=(h-s)/g+2;break;case h:u=(s-o)/g+4;break;default:throw new Error("unreachable")}u/=6}e.data[t++]=u*this.maxValue,e.data[t++]=w*this.maxValue,e.data[t++]=_,this.alpha&&(e.data[t++]=n[a+3])}return e}function cmyk(){this.checkProcessable("cmyk",{bitDepth:[8,16],alpha:[0,1],colorModel:[RGB$1]});let e=Image.createFrom(this,{components:4,colorModel:CMYK$1}),i=0,t=this.data;for(let n=0;n<t.length;n+=this.channels){let a=t[n],s=t[n+1],o=t[n+2],h=Math.min(this.maxValue-a,this.maxValue-s,this.maxValue-o),f=(this.maxValue-a-h)/(1-h/this.maxValue),l=(this.maxValue-s-h)/(1-h/this.maxValue),u=(this.maxValue-o-h)/(1-h/this.maxValue);e.data[i++]=Math.round(f),e.data[i++]=Math.round(l),e.data[i++]=Math.round(u),e.data[i++]=Math.round(h),this.alpha&&(e.data[i++]=t[n+3])}return e}function rgba8(){return new Image(this.width,this.height,this.getRGBAData(),{kind:"RGBA",parent:this})}const methods$1={luma709(e,i,t){return e*6966+i*23436+t*2366>>15},luma601(e,i,t){return e*9798+i*19235+t*3735>>15},maximum(e,i,t){return Math.max(e,i,t)},minimum(e,i,t){return Math.min(e,i,t)},average(e,i,t){return(e+i+t)/3>>0},minmax(e,i,t){return(Math.max(e,i,t)+Math.min(e,i,t))/2},red(e){return e},green(e,i){return i},blue(e,i,t){return t},cyan(e,i,t,n){let a=methods$1.black(e,i,t,n);return(n.maxValue-e-a)/(1-a/n.maxValue)>>0},magenta(e,i,t,n){let a=methods$1.black(e,i,t,n);return(n.maxValue-i-a)/(1-a/n.maxValue)>>0},yellow(e,i,t,n){let a=methods$1.black(e,i,t,n);return(n.maxValue-t-a)/(1-a/n.maxValue)>>0},black(e,i,t,n){return Math.min(n.maxValue-e,n.maxValue-i,n.maxValue-t)},hue(e,i,t,n){let a=methods$1.min(e,i,t),s=methods$1.max(e,i,t);if(s===a)return 0;let o=0,h=s-a;switch(s){case e:o=(i-t)/h+(i<t?6:0);break;case i:o=(t-e)/h+2;break;case t:o=(e-i)/h+4;break;default:throw new Error("unreachable")}return o/6*n.maxValue>>0},saturation(e,i,t,n){let a=methods$1.min(e,i,t),s=methods$1.max(e,i,t),o=s-a;return s===0?0:o/s*n.maxValue},lightness(e,i,t){let n=methods$1.min(e,i,t);return(methods$1.max(e,i,t)+n)/2}};Object.defineProperty(methods$1,"luminosity",{enumerable:!1,value:methods$1.lightness}),Object.defineProperty(methods$1,"luminance",{enumerable:!1,value:methods$1.lightness}),Object.defineProperty(methods$1,"min",{enumerable:!1,value:methods$1.minimum}),Object.defineProperty(methods$1,"max",{enumerable:!1,value:methods$1.maximum}),Object.defineProperty(methods$1,"brightness",{enumerable:!1,value:methods$1.maximum}),Object.keys(methods$1).forEach(e=>{});function grey(e={}){let{algorithm:i="luma709",keepAlpha:t=!1,mergeAlpha:n=!0}=e;if(typeof i!="string"&&typeof i!="function")throw new TypeError("algorithm must be a string or a function");this.checkProcessable("grey",{bitDepth:[8,16],alpha:[0,1]}),this.components===1&&(i="red"),t&=this.alpha,n&=this.alpha,t&&(n=!1);let a=getOutputImage(this,e,{components:1,alpha:t,colorModel:GREY$1}),s;if(typeof i=="function")s=i;else if(s=methods$1[i.toLowerCase()],!s)throw new Error(`unsupported grey algorithm: ${i}`);let o=0;for(let h=0;h<this.data.length;h+=this.channels)n?a.data[o++]=clamp(s(this.data[h],this.data[h+1],this.data[h+2],this)*this.data[h+this.components]/this.maxValue,this):(a.data[o++]=clamp(s(this.data[h],this.data[h+1],this.data[h+2],this),this),a.alpha&&(a.data[o++]=this.data[h+this.components]));return a}function huang(e){let i=0;for(let u=0;u<e.length;u++)if(e[u]!==0){i=u;break}let t=e.length-1;for(let u=e.length-1;u>=i;u--)if(e[u]!==0){t=u;break}let n=1/(t-i),a=new Array(e.length),s=0,o=0;for(let u=i;u<e.length;u++)s+=u*e[u],o+=e[u],a[u]=s/o;let h=new Array(e.length);s=o=0;for(let u=t;u>0;u--)s+=u*e[u],o+=e[u],h[u-1]=s/o;let f=-1,l=Number.MAX_VALUE;for(let u=0;u<e.length;u++){let w=0,_;for(let g=0;g<=u;g++)_=1/(1+n*Math.abs(g-a[u])),_<1e-6||_>.999999||(w+=e[g]*(-_*Math.log(_)-(1-_)*Math.log(1-_)));for(let g=u+1;g<e.length;g++)_=1/(1+n*Math.abs(g-h[u])),_<1e-6||_>.999999||(w+=e[g]*(-_*Math.log(_)-(1-_)*Math.log(1-_)));w<l&&(l=w,f=u)}return f}function intermodes(e){let i=e.slice(),t=0;for(;!bimodalTest$1(i);){let a=0,s=0,o=i[0];for(let h=0;h<e.length-1;h++)a=s,s=o,o=i[h+1],i[h]=(a+s+o)/3;if(i[e.length-1]=(s+o)/3,t++,t>1e4)throw new Error("Intermodes Threshold not found after 10000 iterations")}let n=0;for(let a=1;a<e.length-1;a++)i[a-1]<i[a]&&i[a+1]<i[a]&&(n+=a);return Math.floor(n/2)}function bimodalTest$1(e){let i=!1,t=0;for(let n=1;n<e.length-1;n++)if(e[n-1]<e[n]&&e[n+1]<e[n]&&(t++,t>2))return!1;return t===2&&(i=!0),i}function isodata(e){let i,t,n,a,s=0;for(let o=1;o<e.length;o++)if(e[o]>0){s=o+1;break}for(;;){i=0,n=0;for(let o=0;o<s;o++)n=n+e[o],i=i+e[o]*o;a=0,t=0;for(let o=s+1;o<e.length;o++)t+=e[o],a+=e[o]*o;if(n>0&&t>0&&(i/=n,a/=t,s===Math.round((i+a)/2)))break;if(s++,s>e.length-2)throw new Error("Threshold not found")}return s}function li(e,i){let t,n,a,s,o,h,f,l,u,w,_,g;_=.5,w=0;for(let v=0;v<e.length;v++)w+=v*e[v];w/=i,f=w;do{h=f,t=h+.5|0,n=0,s=0;for(let v=0;v<=t;v++)n+=v*e[v],s+=e[v];l=s===0?0:n/s,a=0,o=0;for(let v=t+1;v<e.length;v++)a+=v*e[v],o+=e[v];u=o===0?0:a/o,g=(l-u)/(Math.log(l)-Math.log(u)),g<-Number.EPSILON?f=g-.5|0:f=g+.5|0}while(Math.abs(f-h)>_);return t}function maxEntropy(e,i){let t=new Array(e.length);for(let _=0;_<e.length;_++)t[_]=e[_]/i;let n=new Array(e.length),a=new Array(e.length);n[0]=t[0],a[0]=1-n[0];for(let _=1;_<e.length;_++)n[_]=n[_-1]+t[_],a[_]=1-n[_];let s=0;for(let _=0;_<e.length;_++)if(Math.abs(n[_])>=Number.EPSILON){s=_;break}let o=e.length-1;for(let _=e.length-1;_>=s;_--)if(Math.abs(a[_])>=Number.EPSILON){o=_;break}let h=-1,f,l=Number.MIN_VALUE,u,w;for(let _=s;_<=o;_++){u=0;for(let g=0;g<=_;g++)e[g]!==0&&(u-=t[g]/n[_]*Math.log(t[g]/n[_]));w=0;for(let g=_+1;g<e.length;g++)e[g]!==0&&(w-=t[g]/a[_]*Math.log(t[g]/a[_]));f=u+w,l<f&&(l=f,h=_)}return h}function mean$1(e,i){let t=0;for(let n=0;n<e.length;n++)t+=n*e[n];return Math.floor(t/i)}function minError(e,i){let t,n=-2,a,s,o,h,f,l,u,w,_,g,v,k=0;for(let A=0;A<e.length;A++)k+=A*e[A];for(k/=i,t=k;t!==n;){let A=sumA(e,t),T=sumA(e,e.length-1),$=sumB(e,t),D=sumB(e,e.length-1),C=sumC(e,t),P=sumC(e,e.length-1);if(a=$/A,s=(D-$)/(T-A),o=A/T,h=(T-A)/T,f=C/A-a*a,l=(P-C)/(T-A)-s*s,u=1/f-1/l,w=a/f-s/l,_=a*a/f-s*s/l+Math.log10(f*(h*h)/(l*(o*o))),g=w*w-u*_,g<0)return t;n=t,v=(w+Math.sqrt(g))/u,isNaN(v)?t=n:t=Math.floor(v)}return t}function sumA(e,i){let t=0;for(let n=0;n<=i;n++)t+=e[n];return t}function sumB(e,i){let t=0;for(let n=0;n<=i;n++)t+=n*e[n];return t}function sumC(e,i){let t=0;for(let n=0;n<=i;n++)t+=n*n*e[n];return t}function minimum(e){if(e.length<2)return 0;let i=0,t=-1,n=-1,a=new Array(e.length);for(let s=0;s<e.length;s++)a[s]=e[s],e[s]>0&&(n=s);for(;!bimodalTest(a);)if(a=smoothed(a),i++,i>1e4)return t;return t=minimumBetweenPeeks(a,n),t}function smoothed(e){let i=new Array(e.length);for(let t=1;t<e.length-1;t++)i[t]=(e[t-1]+e[t]+e[t+1])/3;return i[0]=(e[0]+e[1])/3,i[e.length-1]=(e[e.length-2]+e[e.length-1])/3,i}function minimumBetweenPeeks(e,i){let t;for(let n=1;n<i;n++)if(e[n-1]>e[n]&&e[n+1]>=e[n]){t=n;break}return t}function bimodalTest(e){let i=e.length,t=!1,n=0;for(let a=1;a<i-1;a++)if(e[a-1]<e[a]&&e[a+1]<e[a]&&(n++,n>2))return!1;return n===2&&(t=!0),t}function moments(e,i){let t=1,n=0,a=0,s=0,o=0,h,f,l,u,w,_,g=-1,v=e.length,k=new Array(v);for(let A=0;A<v;A++)k[A]=e[A]/i;for(let A=0;A<v;A++)n+=A*k[A],a+=A*A*k[A],s+=A*A*A*k[A];f=t*a-n*n,l=(-a*a+n*s)/f,u=(t*-s+a*n)/f,w=.5*(-u-Math.sqrt(u*u-4*l)),_=.5*(-u+Math.sqrt(u*u-4*l)),h=(_-n)/(_-w);for(let A=0;A<v;A++)if(o+=k[A],o>h){g=A;break}return g}function otsu(e,i){let t=0,n=0,a=0,s=0,o=0;for(let h=0;h<e.length;h++)o+=h*e[h];for(let h=0;h<e.length;h++){n=n+e[h];const f=i-n;if(n===0||f===0)continue;t=t+h*e[h];const l=(o-t)/f,u=n*f*(t/n-l)*(t/n-l);u>=a&&(s=h,a=u)}return s}function percentile(e){let i=-1,t=.5,n=new Array(e.length),a=partialSum(e,e.length-1),s=1;for(let o=0;o<e.length;o++)n[o]=Math.abs(partialSum(e,o)/a-t),n[o]<s&&(s=n[o],i=o);return i}function partialSum(e,i){let t=0;for(let n=0;n<=i;n++)t+=e[n];return t}function renyiEntropy(e,i){let t,n,a,s=new Array(e.length),o=new Array(e.length),h=new Array(e.length),f=0,l=0,u=0,w=0,_=0,g=0,k=1/(1-.5),T=1/(1-2);for(let P=0;P<e.length;P++)s[P]=e[P]/i;o[0]=s[0],h[0]=1-o[0];for(let P=1;P<e.length;P++)o[P]=o[P-1]+s[P],h[P]=1-o[P];n=0;for(let P=0;P<e.length;P++)if(Math.abs(o[P])>=Number.EPSILON){n=P;break}a=e.length-1;for(let P=e.length-1;P>=n;P--)if(Math.abs(h[P])>=Number.EPSILON){a=P;break}for(let P=n;P<=a;P++){let z=0,B=0,F=0;for(let W=0;W<=P;W++)e[W]!==0&&(z-=s[W]/o[P]*Math.log(s[W]/o[P])),B+=Math.sqrt(s[W]/o[P]),F+=s[W]*s[W]/(o[P]*o[P]);let L=0,N=0,G=0;for(let W=P+1;W<e.length;W++)e[W]!==0&&(L-=s[W]/h[P]*Math.log(s[W]/h[P])),N+=Math.sqrt(s[W]/h[P]),G+=s[W]*s[W]/(h[P]*h[P]);let V=z+L,J=k*(B*N>0?Math.log(B*N):0),Q=T*(F*G>0?Math.log(F*G):0);V>w&&(w=V,f=P),J>_&&(_=J,l=P),Q>g&&(g=Q,u=P)}let $=[f,l,u];$.sort((P,z)=>P-z);let D;Math.abs($[0]-$[1])<=5?Math.abs($[1]-$[2])<=5?D=[1,2,1]:D=[0,1,3]:Math.abs($[1]-$[2])<=5?D=[3,1,0]:D=[1,2,1];let C=o[$[2]]-o[$[0]];return t=Math.round($[0]*(o[$[0]]+.25*C*D[0])+.25*$[1]*C*D[1]+$[2]*(h[$[2]]+.25*C*D[2])),t}function shanbhag(e,i){let t=new Array(e.length);for(let g=0;g<e.length;g++)t[g]=e[g]/i;let n=new Array(e.length),a=new Array(e.length);n[0]=t[0],a[0]=1-n[0];for(let g=1;g<e.length;g++)n[g]=n[g-1]+t[g],a[g]=1-n[g];let s=0;for(let g=0;g<e.length;g++)if(Math.abs(n[g])>=Number.EPSILON){s=g;break}let o=e.length-1;for(let g=e.length-1;g>=s;g--)if(Math.abs(a[g])>=Number.EPSILON){o=g;break}let h=-1,f=Number.MAX_VALUE,l,u,w,_;for(let g=s;g<=o;g++){w=0,l=.5/n[g];for(let v=1;v<=g;v++)w-=t[v]*Math.log(1-l*n[v-1]);w*=l,_=0,l=.5/a[g];for(let v=g+1;v<e.length;v++)_-=t[v]*Math.log(1-l*a[v]);_*=l,u=Math.abs(w-_),u<f&&(f=u,h=g)}return h}function triangle$1(e){let i=0,t=0,n=0,a=0;for(let w=0;w<e.length;w++)if(e[w]>0){i=w;break}i>0&&i--;for(let w=e.length-1;w>0;w--)if(e[w]>0){a=w;break}a<e.length-1&&a++;for(let w=0;w<e.length;w++)e[w]>t&&(n=w,t=e[w]);let s=!1;if(n-i<a-n){s=!0;let w=0,_=e.length-1;for(;w<_;){let g=e[w];e[w]=e[_],e[_]=g,w++,_--}i=e.length-1-a,n=e.length-1-n}if(i===n)return i;let o,h,f;o=e[n],h=i-n,f=Math.sqrt(o*o+h*h),o/=f,h/=f,f=o*i+h*e[i];let l=i,u=0;for(let w=i+1;w<=n;w++){let _=o*w+h*e[w]-f;_>u&&(l=w,u=_)}if(l--,s){let w=0,_=e.length-1;for(;w<_;){let g=e[w];e[w]=e[_],e[_]=g,w++,_--}return e.length-1-l}else return l}function yen(e,i){let t=new Array(e.length);for(let l=0;l<e.length;l++)t[l]=e[l]/i;let n=new Array(e.length);n[0]=t[0];for(let l=1;l<e.length;l++)n[l]=n[l-1]+t[l];let a=new Array(e.length);a[0]=t[0]*t[0];for(let l=1;l<e.length;l++)a[l]=a[l-1]+t[l]*t[l];let s=new Array(e.length);s[e.length-1]=0;for(let l=e.length-2;l>=0;l--)s[l]=s[l+1]+t[l+1]*t[l+1];let o=-1,h=Number.MIN_VALUE,f;for(let l=0;l<e.length;l++)f=-1*(a[l]*s[l]>0?Math.log(a[l]*s[l]):0)+2*(n[l]*(1-n[l])>0?Math.log(n[l]*(1-n[l])):0),f>h&&(h=f,o=l);return o}const methods={huang,intermodes,isodata,li,maxentropy:maxEntropy,mean:mean$1,minerror:minError,minimum,moments,otsu,percentile,renyientropy:renyiEntropy,shanbhag,triangle:triangle$1,yen},names={};Object.keys(methods).forEach(e=>{names[e]=e});function getThreshold(e={}){let{algorithm:i=names.otsu}=e;this.checkProcessable("getThreshold",{components:1,bitDepth:[8,16]});let t=methods[i.toLowerCase()];if(t){let n=this.getHistogram();return t(n,this.size)}else throw new Error(`unknown thresholding algorithm: ${i}`)}const THRESHOLD="threshold";function mask(e={}){let{algorithm:i=THRESHOLD,threshold:t=.5,useAlpha:n=!0,invert:a=!1}=e;this.checkProcessable("mask",{components:1,bitDepth:[8,16]}),i===THRESHOLD?t=getThreshold$1(t,this.maxValue):t=getThreshold.call(this,e);let s=new Image(this.width,this.height,{kind:"BINARY",parent:this}),o=0;if(this.alpha&&n)for(let h=0;h<this.data.length;h+=this.channels){let f=this.data[h]+(this.maxValue-this.data[h])*(this.maxValue-this.data[h+1])/this.maxValue;(a&&f<=t||!a&&f>=t)&&s.setBit(o),o++}else for(let h=0;h<this.data.length;h+=this.channels)(a&&this.data[h]<=t||!a&&this.data[h]>=t)&&s.setBit(o),o++;return s}function copyImage(e,i,t,n){let a=e.width,s=e.height,o=i.width,h=e.channels;for(let f=0;f<a;f++)for(let l=0;l<s;l++)for(let u=0;u<h;u++){let w=(l*a+f)*h+u,_=((n+l)*o+t+f)*h+u;i.data[_]=e.data[w]}}function pad(e={}){let{size:i=0,algorithm:t="copy",color:n}=e;if(this.checkProcessable("pad",{bitDepth:[8,16]}),t==="set"){if(n.length!==this.channels)throw new Error(`pad: the color array must have the same length as the number of channels. Here: ${this.channels}`);for(let f=0;f<n.length;f++)n[f]===0&&(n[f]=.001)}else n=newArray(this.channels,null);Array.isArray(i)||(i=[i,i]);let a=this.width+i[0]*2,s=this.height+i[1]*2,o=this.channels,h=Image.createFrom(this,{width:a,height:s});copyImage(this,h,i[0],i[1]);for(let f=i[0];f<a-i[0];f++)for(let l=0;l<o;l++){let u=n[l]||h.data[(i[1]*a+f)*o+l];for(let w=0;w<i[1];w++)h.data[(w*a+f)*o+l]=u;u=n[l]||h.data[((s-i[1]-1)*a+f)*o+l];for(let w=s-i[1];w<s;w++)h.data[(w*a+f)*o+l]=u}for(let f=0;f<s;f++)for(let l=0;l<o;l++){let u=n[l]||h.data[(f*a+i[0])*o+l];for(let w=0;w<i[0];w++)h.data[(f*a+w)*o+l]=u;u=n[l]||h.data[(f*a+a-i[0]-1)*o+l];for(let w=a-i[0];w<a;w++)h.data[(f*a+w)*o+l]=u}return h}function colorDepth(e=8){if(this.checkProcessable("colorDepth",{bitDepth:[1,8,16]}),![8,16].includes(e))throw Error("You need to specify the new colorDepth as 8 or 16");if(this.bitDepth===e)return this.clone();let i=Image.createFrom(this,{bitDepth:e});switch(e){case 8:if(this.bitDepth===1)for(let t=0;t<this.size;t++)this.getBit(t)&&(i.data[t]=255);else for(let t=0;t<this.data.length;t++)i.data[t]=this.data[t]>>8;break;case 16:if(this.bitDepth===1)for(let t=0;t<this.size;t++)this.getBit(t)&&(i.data[t]=65535);else for(let t=0;t<this.data.length;t++)i.data[t]=this.data[t]<<8|this.data[t];break;default:throw new Error("colorDepth conversion unexpected case")}return i}function rotateFree(e,i={}){const{interpolation:t=validInterpolations.nearestneighbor,width:n=this.width,height:a=this.height}=i;if(typeof e!="number")throw new TypeError("degrees must be a number");const s=checkInterpolation(t),o=e*Math.PI/180,h=Math.floor(Math.abs(n*Math.cos(o))+Math.abs(a*Math.sin(o))),f=Math.floor(Math.abs(a*Math.cos(o))+Math.abs(n*Math.sin(o))),l=Math.cos(-o),u=Math.sin(-o);let w=h/2,_=f/2;h%2===0?(w=w-.5,f%2===0?_=_-.5:_=Math.floor(_)):(w=Math.floor(w),f%2===0?_=_-.5:_=Math.floor(_));const g=Math.floor(n/2-w),v=Math.floor(a/2-_);if(this.bitDepth===1){const k=new Image(h,f,{kind:"BINARY",parent:this});switch(s){case validInterpolations.nearestneighbor:return rotateBinaryNearestNeighbor(this,k,g,v,w,_,l,u);case validInterpolations.bilinear:return rotateBinaryBilinear(this,k,g,v,w,_,l,u);default:throw new Error(`unsupported rotate interpolation: ${s}`)}}else{const k=Image.createFrom(this,{width:h,height:f});switch(s){case validInterpolations.nearestneighbor:return rotateNearestNeighbor(this,k,g,v,w,_,l,u);case validInterpolations.bilinear:return rotateBilinear(this,k,g,v,w,_,l,u);default:throw new Error(`unsupported rotate interpolation: ${s}`)}}}function rotateNearestNeighbor(e,i,t,n,a,s,o,h){for(let f=0;f<i.width;f+=1)for(let l=0;l<i.height;l+=1)for(let u=0;u<e.channels;u++){let w=Math.round((f-a)*o-(l-s)*h+a)+t,_=Math.round((l-s)*o+(f-a)*h+s)+n;w<0||w>=e.width||_<0||_>=e.height?e.alpha===1&&u===e.channels-1?i.setValueXY(f,l,u,0):i.setValueXY(f,l,u,e.maxValue):i.setValueXY(f,l,u,e.getValueXY(w,_,u))}return i}function rotateBinaryNearestNeighbor(e,i,t,n,a,s,o,h){for(let f=0;f<i.width;f+=1)for(let l=0;l<i.height;l+=1){let u=Math.round((f-a)*o-(l-s)*h+a)+t,w=Math.round((l-s)*o+(f-a)*h+s)+n;(u<0||u>=e.width||w<0||w>=e.height||e.getBitXY(u,w))&&i.setBitXY(f,l)}return i}function rotateBilinear(e,i,t,n,a,s,o,h){let f=e.width*e.channels;for(let l=0;l<i.height;l++)for(let u=0;u<i.width;u++){let w=(u-a)*o-(l-s)*h+a+t,_=(l-s)*o+(u-a)*h+s+n,g=w|0,v=_|0,k=w-g,A=_-v;for(let T=0;T<e.channels;T++)if(w<0||w>=e.width||_<0||_>=e.height)e.alpha===1&&T===e.channels-1?i.setValueXY(u,l,T,0):i.setValueXY(u,l,T,e.maxValue);else{let $=(v*e.width+g)*e.channels+T,D=e.data[$],C=e.data[$+e.channels],P=e.data[$+f],z=e.data[$+f+e.channels],B=D+k*(C-D)+A*(P-D)+k*A*(D-C-P+z)|0;i.setValueXY(u,l,T,B)}}return i}function rotateBinaryBilinear(e,i,t,n,a,s,o,h){let f=e.width;for(let l=0;l<i.height;l++)for(let u=0;u<i.width;u++){let w=(u-a)*o-(l-s)*h+a+t,_=(l-s)*o+(u-a)*h+s+n,g=w|0,v=_|0,k=w-g,A=_-v;if(w<0||w>=e.width||_<0||_>=e.height)i.setBitXY(u,l);else{let T=v*e.width+g,$=e.getBit(T),D=e.getBit(T+1),C=e.getBit(T+f),P=e.getBit(T+1+f);($|k&D-$|A&C-$|k&A&$-D-C+P)>0&&i.setBitXY(u,l)}}return i}function rotate$1(e,i){if(this.checkProcessable("rotate",{bitDepth:[1,8,16]}),typeof e!="number")throw new TypeError("angle must be a number");switch(e<0&&(e=Math.ceil(-e/360)*360+e),e%360){case 0:return this.clone();case 90:return rotateRight.call(this);case 180:return rotate180.call(this);case 270:return rotateLeft.call(this);default:return rotateFree.call(this,e,i)}}function rotateLeft(){if(this.bitDepth===1){const e=new Image(this.height,this.width,{kind:"BINARY",parent:this}),i=e.height-1;for(let t=0;t<this.height;t++)for(let n=0;n<this.width;n++)this.getBitXY(n,t)&&e.setBitXY(t,i-n);return e}else{const e=Image.createFrom(this,{width:this.height,height:this.width}),i=e.height-1;for(let t=0;t<this.height;t++)for(let n=0;n<this.width;n++)for(let a=0;a<this.channels;a++)e.setValueXY(t,i-n,a,this.getValueXY(n,t,a));return e}}function rotateRight(){if(this.bitDepth===1){const e=new Image(this.height,this.width,{kind:"BINARY",parent:this}),i=e.width-1;for(let t=0;t<this.height;t++)for(let n=0;n<this.width;n++)this.getBitXY(n,t)&&e.setBitXY(i-t,n);return e}else{const e=Image.createFrom(this,{width:this.height,height:this.width}),i=e.width-1;for(let t=0;t<this.height;t++)for(let n=0;n<this.width;n++)for(let a=0;a<this.channels;a++)e.setValueXY(i-t,n,a,this.getValueXY(n,t,a));return e}}function rotate180(){if(this.bitDepth===1){const e=new Image(this.width,this.height,{kind:"BINARY",parent:this}),i=e.width-1,t=e.height-1;for(let n=0;n<this.height;n++)for(let a=0;a<this.width;a++)this.getBitXY(a,n)&&e.setBitXY(i-a,t-n);return e}else{const e=Image.createFrom(this),i=e.width-1,t=e.height-1;for(let n=0;n<this.height;n++)for(let a=0;a<this.width;a++)for(let s=0;s<this.channels;s++)e.setValueXY(i-a,t-n,s,this.getValueXY(a,n,s));return e}}function insert(e,i={}){const t=getImageParameters(e);this.checkProcessable("insert",t);let{x:n=0,y:a=0}=i;const s=getOutputImageOrInPlace(this,i,{copy:!0}),o=Math.min(s.height,a+e.height),h=Math.min(s.width,n+e.width);if(s.bitDepth===1)for(let f=a;f<o;f++)for(let l=n;l<h;l++)e.getBitXY(l-n,f-a)?s.setBitXY(l,f):s.clearBitXY(l,f);else for(let f=a;f<o;f++)for(let l=n;l<h;l++)s.setPixelXY(l,f,e.getPixelXY(l-n,f-a));return s}function setBorder(e={}){let{size:i=0,algorithm:t="copy",color:n}=e;if(this.checkProcessable("setBorder",{bitDepth:[8,16,32,64]}),t==="set"){if(n.length!==this.channels)throw new Error(`setBorder: the color array must have the same length as the number of channels. Here: ${this.channels}`);for(let h=0;h<n.length;h++)n[h]===0&&(n[h]=.001)}else n=newArray(this.channels,null);Array.isArray(i)||(i=[i,i]);let a=i[0],s=i[1],o=this.channels;for(let h=a;h<this.width-a;h++)for(let f=0;f<o;f++){let l=n[f]||this.data[(h+this.width*s)*o+f];for(let u=0;u<s;u++)this.data[(u*this.width+h)*o+f]=l;l=n[f]||this.data[(h+this.width*(this.height-s-1))*o+f];for(let u=this.height-s;u<this.height;u++)this.data[(u*this.width+h)*o+f]=l}for(let h=0;h<this.height;h++)for(let f=0;f<o;f++){let l=n[f]||this.data[(h*this.width+a)*o+f];for(let u=0;u<a;u++)this.data[(h*this.width+u)*o+f]=l;l=n[f]||this.data[(h*this.width+this.width-a-1)*o+f];for(let u=this.width-a;u<this.width;u++)this.data[(h*this.width+u)*o+f]=l}return this}function split(e={}){let{preserveAlpha:i=!0}=e;if(this.checkProcessable("split",{bitDepth:[8,16]}),this.components===1)return new Stack([this.clone()]);let t=new Stack,n=this.data;if(this.alpha&&i)for(let a=0;a<this.components;a++){let s=Image.createFrom(this,{components:1,alpha:!0,colorModel:GREY$1}),o=0;for(let h=0;h<n.length;h+=this.channels)s.data[o++]=n[h+a],s.data[o++]=n[h+this.components];t.push(s)}else for(let a=0;a<this.channels;a++){let s=Image.createFrom(this,{components:1,alpha:!1,colorModel:GREY$1}),o=0;for(let h=0;h<n.length;h+=this.channels)s.data[o++]=n[h+a];t.push(s)}return t}function getChannel(e,i={}){let{keepAlpha:t=!1,mergeAlpha:n=!1}=i;t&=this.alpha,n&=this.alpha,this.checkProcessable("getChannel",{bitDepth:[8,16]}),e=validateChannel(this,e);let a=Image.createFrom(this,{components:1,alpha:t,colorModel:GREY$1}),s=0;for(let o=0;o<this.data.length;o+=this.channels)n?a.data[s++]=this.data[o+e]*this.data[o+this.components]/this.maxValue:(a.data[s++]=this.data[o+e],t&&(a.data[s++]=this.data[o+this.components]));return a}function combineChannels(e=defaultCombineMethod,i={}){let{mergeAlpha:t=!1,keepAlpha:n=!1}=i;t&=this.alpha,n&=this.alpha,this.checkProcessable("combineChannels",{bitDepth:[8,16]});let a=Image.createFrom(this,{components:1,alpha:n,colorModel:GREY$1}),s=0;for(let o=0;o<this.size;o++){let h=e(this.getPixel(o));t?a.data[s++]=h*this.data[o*this.channels+this.components]/this.maxValue:(a.data[s++]=h,n&&(a.data[s++]=this.data[o*this.channels+this.components]))}return a}function defaultCombineMethod(e){return(e[0]+e[1]+e[2])/3}function setChannel(e,i){if(this.checkProcessable("setChannel",{bitDepth:[8,16]}),i.checkProcessable("setChannel (image parameter check)",{bitDepth:[this.bitDepth],alpha:[0],components:[1]}),i.width!==this.width||i.height!==this.height)throw new Error("Images must have exactly the same width and height");e=validateChannel(this,e);let t=e;for(let n=0;n<i.data.length;n++)this.data[t]=i.data[n],t+=this.channels;return this}function getSimilarity(e,i={}){let{shift:t=[0,0],average:n,channels:a,defaultAlpha:s,normalize:o,border:h=[0,0]}=i;if(this.checkProcessable("getSimilarity",{bitDepth:[8,16]}),Array.isArray(h)||(h=[h,h]),a=validateArrayOfChannels(this,{channels:a,defaultAlpha:s}),this.bitDepth!==e.bitDepth)throw new Error("Both images must have the same bitDepth");if(this.channels!==e.channels)throw new Error("Both images must have the same number of channels");if(this.colorModel!==e.colorModel)throw new Error("Both images must have the same colorModel");typeof n>"u"&&(n=!0);let f=Math.max(h[0],-t[0]),l=Math.min(this.width-h[0],this.width-t[0]),u=Math.max(h[1],-t[1]),w=Math.min(this.height-h[1],this.height-t[1]),_=newArray(a.length,0);for(let g=0;g<a.length;g++){let v=a[g],k=o?this.sum[v]:Math.max(this.sum[v],e.sum[v]),A=o?e.sum[v]:Math.max(this.sum[v],e.sum[v]);if(k!==0&&A!==0)for(let T=f;T<l;T++)for(let $=u;$<w;$++){let D=T*this.multiplierX+$*this.multiplierY+v,C=D+t[0]*this.multiplierX+t[1]*this.multiplierY;_[g]+=Math.min(this.data[D]/k,e.data[C]/A)}}return n?_.reduce((g,v)=>g+v)/_.length:_}function getPixelsGrid(e={}){let{sampling:i=[10,10],painted:t=!1,mask:n}=e;this.checkProcessable("getPixelsGrid",{bitDepth:[8,16],channels:1}),Array.isArray(i)||(i=[i,i]);const a=i[0],s=i[1],o=[],h=[],f=this.width/a,l=this.height/s;let u=Math.floor(f/2);for(let _=0;_<a;_++){let g=Math.floor(l/2);for(let v=0;v<s;v++){let k=Math.round(u),A=Math.round(g);(!n||n.getBitXY(k,A))&&(o.push([k,A]),h.push(this.getPixelXY(k,A))),g+=l}u+=f}const w={xyS:o,zS:h};return t&&(w.painted=this.rgba8().paintPoints(o)),w}function Matrix(e,i,t){const n=new Array(e);for(let a=0;a<e;a++)n[a]=new Array(i);if(t)for(let a=0;a<e;a++)for(let s=0;s<i;s++)n[a][s]=t;return n.width=e,n.height=i,Object.setPrototypeOf(n,Matrix.prototype),n}Matrix.prototype.localMin=function(e,i){let t=this[e][i],n=[e,i];for(let a=Math.max(0,e-1);a<Math.min(this.length,e+2);a++)for(let s=Math.max(0,i-1);s<Math.min(this[0].length,i+2);s++)this[a][s]<t&&(t=this[a][s],n=[a,s]);return{position:n,value:t}},Matrix.prototype.localMax=function(e,i){let t=this[e][i],n=[e,i];for(let a=Math.max(0,e-1);a<Math.min(this.length,e+2);a++)for(let s=Math.max(0,i-1);s<Math.min(this[0].length,i+2);s++)this[a][s]>t&&(t=this[a][s],n=[a,s]);return{position:n,value:t}},Matrix.prototype.localSearch=function(e,i,t){let n=[];for(let a=Math.max(0,e-1);a<Math.min(this.length,e+2);a++)for(let s=Math.max(0,i-1);s<Math.min(this[0].length,i+2);s++)this[a][s]===t&&n.push([a,s]);return n};function getBestMatch(e,i={}){let{border:t}=i;if(this.checkProcessable("getChannel",{bitDepth:[8,16]}),this.bitDepth!==e.bitDepth)throw new Error("Both images must have the same bitDepth");if(this.channels!==e.channels)throw new Error("Both images must have the same number of channels");if(this.colorModel!==e.colorModel)throw new Error("Both images must have the same colorModel");let n=new Matrix(e.width,e.height,-1/0),a=Math.floor(e.width/2),s=Math.floor(e.height/2),o=a,h=s,f=!1;for(;!f;){let l=n.localSearch(a,s,-1/0);for(let w=0;w<l.length;w++){let _=l[w],g=this.getSimilarity(e,{border:t,shift:[o-_[0],h-_[1]]});n[_[0]][_[1]]=g}let u=n.localMax(a,s);u.position[0]!==a||u.position[1]!==s?(a=u.position[0],s=u.position[1]):f=!0}return[a-o,s-h]}function getRow(e,i=0){this.checkProcessable("getRow",{bitDepth:[8,16]}),checkRow(this,e),checkChannel(this,i);let t=new Array(this.width),n=0,a=e*this.width*this.channels+i,s=a+this.width*this.channels;for(let o=a;o<s;o+=this.channels)t[n++]=this.data[o];return t}function getColumn(e,i=0){this.checkProcessable("getColumn",{bitDepth:[8,16]}),checkColumn(this,e),checkChannel(this,i);let t=new Array(this.height),n=0,a=this.width*this.channels;for(let s=i+e*this.channels;s<this.data.length;s+=a)t[n++]=this.data[s];return t}function getMatrix(e={}){let{channel:i}=e;if(this.checkProcessable("getMatrix",{bitDepth:[8,16]}),i===void 0){if(this.components>1)throw new RangeError("You need to define the channel for an image that contains more than one channel");i=0}let t=new Matrix$1(this.height,this.width);for(let n=0;n<this.height;n++)for(let a=0;a<this.width;a++)t.set(n,a,this.getValueXY(a,n,i));return t}function setMatrix(e,i={}){e=new Matrix$1(e);let{channel:t}=i;if(this.checkProcessable("getMatrix",{bitDepth:[8,16]}),t===void 0){if(this.components>1)throw new RangeError("You need to define the channel for an image that contains more than one channel");t=0}if(this.width!==e.columns||this.height!==e.rows)throw new RangeError("The size of the matrix must be equal to the size of the image");for(let n=0;n<this.height;n++)for(let a=0;a<this.width;a++)this.setValueXY(a,n,t,e.get(n,a));return this}function getPixelsArray(){this.checkProcessable("getPixelsArray",{bitDepth:[8,16,32]});let e=new Array(this.size),i=0;for(let t=0;t<this.data.length;t+=this.channels){let n=new Array(this.components);for(let a=0;a<this.components;a++)n[a]=this.data[t+a];e[i++]=n}return e}function getIntersection(e){let i=this,t=i.getClosestCommonParent(e),n=i.getRelativePosition(t,{defaultFurther:!0}),a=getRelativePositionForAllPixels(i,n),s=e.getRelativePosition(t,{defaultFurther:!0}),o=getRelativePositionForAllPixels(e,s),h=getCommonSurface(a,o),f={whitePixelsMask1:[],whitePixelsMask2:[],commonWhitePixels:[]};for(let l=0;l<h.length;l++){let u=h[l],w=[u[0]-n[0],u[1]-n[1]],_=[u[0]-s[0],u[1]-s[1]],g=i.getBitXY(w[0],w[1]),v=e.getBitXY(_[0],_[1]);g===1&&v===1&&f.commonWhitePixels.push(u)}for(let l=0;l<a.length;l++){let u,w;l!==0&&(u=Math.floor(l/i.width),w=l%i.width),i.getBitXY(u,w)===1&&f.whitePixelsMask1.push(a[l])}for(let l=0;l<o.length;l++){let u=0,w=0;l!==0&&(u=Math.floor(l/e.width),w=l%e.width),e.getBitXY(u,w)===1&&f.whitePixelsMask2.push(o[l])}return f}function getRelativePositionForAllPixels(e,i){let t=[];for(let n=0;n<e.height;n++)for(let a=0;a<e.width;a++){let s=[n,a];t.push([s[0]+i[0],s[1]+i[1]])}return t}function getCommonSurface(e,i){let t=0,n=0,a=[];for(;t<e.length&&n<i.length;)e[t][0]===i[n][0]&&e[t][1]===i[n][1]?(a.push(e[t]),t++,n++):e[t][0]<i[n][0]||e[t][0]===i[n][0]&&e[t][1]<i[n][1]?t++:n++;return a}function getClosestCommonParent(e){let i=getDepth(this),t=getDepth(e),n;if(i>=t?n=getFurthestParent(this,i):n=getFurthestParent(e,t),i===0||t===0)return n;let a=this,s=e;for(;i!==t;)if(i>t){if(a=a.parent,a===null)return n;i=i-1}else{if(s=s.parent,s===null)return n;t=t-1}for(;a!==s&&a!==null&&s!==null;)if(a=a.parent,s=s.parent,a===null||s===null)return n;return a!==s?n:a}function getDepth(e){let i=0,t=e;for(;t.parent!=null;)t=t.parent,i++;return i}function getFurthestParent(e,i){let t=e;for(;i>0;)t=t.parent,i=i-1;return t}const defaultOptions$1={lowThreshold:10,highThreshold:30,gaussianBlur:1.1},Gx=[[-1,0,1],[-2,0,2],[-1,0,1]],Gy=[[-1,-2,-1],[0,0,0],[1,2,1]],convOptions={bitDepth:32,mode:"periodic"};function cannyEdgeDetector(e,i){e.checkProcessable("Canny edge detector",{bitDepth:8,channels:1,components:1}),i=Object.assign({},defaultOptions$1,i);const t=e.width,n=e.height,a=e.maxValue,s={sigma:i.gaussianBlur,radius:3},o=e.gaussianFilter(s),h=o.convolution(Gy,convOptions),f=o.convolution(Gx,convOptions),l=f.hypotenuse(h),u=e.constructor,w=new u(t,n,{kind:"GREY",bitDepth:32}),_=new u(t,n,{kind:"GREY",bitDepth:32}),g=new u(t,n,{kind:"GREY"});for(var v=1;v<t-1;v++)for(var k=1;k<n-1;k++){var A=(Math.round(Math.atan2(f.getValueXY(v,k,0),h.getValueXY(v,k,0))*(5/Math.PI))+5)%5;A===0&&(l.getValueXY(v,k,0)<=l.getValueXY(v,k-1,0)||l.getValueXY(v,k,0)<=l.getValueXY(v,k+1,0))||A===1&&(l.getValueXY(v,k,0)<=l.getValueXY(v-1,k+1,0)||l.getValueXY(v,k,0)<=l.getValueXY(v+1,k-1,0))||A===2&&(l.getValueXY(v,k,0)<=l.getValueXY(v-1,k,0)||l.getValueXY(v,k,0)<=l.getValueXY(v+1,k,0))||A===3&&(l.getValueXY(v,k,0)<=l.getValueXY(v-1,k-1,0)||l.getValueXY(v,k,0)<=l.getValueXY(v+1,k+1,0))||w.setValueXY(v,k,0,l.getValueXY(v,k,0))}for(v=0;v<t*n;++v){var T=w.data[v],$=0;T>i.highThreshold&&($++,g.data[v]=a),T>i.lowThreshold&&$++,_.data[v]=$}var D=[];for(v=1;v<t-1;++v)for(k=1;k<n-1;++k)if(_.getValueXY(v,k,0)===1){e:for(var C=v-1;C<v+2;++C)for(var P=k-1;P<k+2;++P)if(_.getValueXY(C,P,0)===2){D.push([v,k]),g.setValueXY(v,k,0,a);break e}}for(;D.length>0;){var z=[];for(v=0;v<D.length;++v)for(k=-1;k<2;++k)for(C=-1;C<2;++C)if(!(k===0&&C===0)){var B=D[v][0]+k,F=D[v][1]+C;_.getValueXY(B,F,0)===1&&g.getValueXY(B,F,0)===0&&(z.push([B,F]),g.setValueXY(B,F,0,a))}D=z}return g}function cannyEdge(e){return cannyEdgeDetector(this,e)}function extract(e,i={}){let{position:t}=i;if(this.checkProcessable("extract",{bitDepth:[1,8,16]}),!t&&(t=e.getRelativePosition(this),!t))throw new Error("extract : can not extract an image because the relative position can not be determined, try to specify manually the position as an array of 2 elements [x,y].");if(this.bitDepth>1){let n=Image.createFrom(this,{width:e.width,height:e.height,alpha:1,position:t,parent:this});for(let a=0;a<e.width;a++)for(let s=0;s<e.height;s++){for(let o=0;o<this.channels;o++){let h=this.getValueXY(a+t[0],s+t[1],o);n.setValueXY(a,s,o,h)}e.getBitXY(a,s)||n.setValueXY(a,s,this.components,0)}return n}else{let n=Image.createFrom(this,{width:e.width,height:e.height,position:t,parent:this});for(let a=0;a<e.height;a++)for(let s=0;s<e.width;s++)e.getBitXY(s,a)&&this.getBitXY(s+t[0],a+t[1])&&n.setBitXY(s,a);return n}}var fastList={exports:{}},hasRequiredFastList;function requireFastList(){return hasRequiredFastList||(hasRequiredFastList=1,function(e,i){(function(){function t(a,s,o){this.next=o,o&&(o.prev=this),this.prev=s,s&&(s.next=this),this.data=a}function n(){if(!(this instanceof n))return new n;this._head=null,this._tail=null,this.length=0}n.prototype={push:function(a){this._tail=new t(a,this._tail,null),this._head||(this._head=this._tail),this.length++},pop:function(){if(this.length!==0){var a=this._tail;return this._tail=a.prev,a.prev&&(a.prev=this._tail.next=null),this.length--,this.length===1?this._head=this._tail:this.length===0&&(this._head=this._tail=null),a.data}},unshift:function(a){this._head=new t(a,null,this._head),this._tail||(this._tail=this._head),this.length++},shift:function(){if(this.length!==0){var a=this._head;return this._head=a.next,a.next&&(a.next=this._head.prev=null),this.length--,this.length===1?this._tail=this._head:this.length===0&&(this._head=this._tail=null),a.data}},item:function(a){a<0&&(a=this.length+a);for(var s=this._head;a-- >0&&s;)s=s.next;return s?s.data:void 0},slice:function(a,s){if(a||(a=0),s||(s=this.length),s<0&&(s=this.length+s),a<0&&(a=this.length+a),s===a)return[];if(s<a)throw new Error("invalid offset: "+a+","+s+" (length="+this.length+")");for(var o=s-a,h=new Array(o),f=0,l=this._head;a-- >0&&l;)l=l.next;for(;f<o&&l;)h[f++]=l.data,l=l.next;return h},drop:function(){n.call(this)},forEach:function(a,s){for(var o=this._head,h=0,f=this.length;h<f&&o;)a.call(s||this,o.data,h,this),o=o.next,h++},map:function(a,s){var o=new n;return this.forEach(function(h,f,l){o.push(a.call(s||l,h,f,l))}),o},filter:function(a,s){var o=new n;return this.forEach(function(h,f,l){a.call(s||l,h,f,l)&&o.push(h)}),o},reduce:function(a,s,o){var h=0,f=this._head,l=this.length;for(s||(h=1,s=f&&f.data,f=f&&f.next);h<l&&f;)s=a.call(o||this,s,f.data,this),h++,f=f.next;return s}},e.exports=n})()}(fastList)),fastList.exports}var fastListExports=requireFastList();const LinkedList=getDefaultExportFromCjs(fastListExports);function floodFill(e={}){const{x:i=0,y:t=0,inPlace:n=!0}=e,a=n?this:Image.createFrom(this);if(this.checkProcessable("floodFill",{bitDepth:1}),this.getBitXY(i,t))return a;const o=new LinkedList;for(o.push(new Node(i,t));o.length>0;){const h=o.shift();a.setBitXY(h.x,h.y);for(let f=h.x+1;f<this.width&&(!a.getBitXY(f,h.y)&&!this.getBitXY(f,h.y));f++)a.setBitXY(f,h.y),h.y+1<this.height&&!this.getBitXY(f,h.y+1)&&o.push(new Node(f,h.y+1)),h.y-1>=0&&!this.getBitXY(f,h.y-1)&&o.push(new Node(f,h.y-1));for(let f=h.x-1;f>=0&&(!a.getBitXY(f,h.y)&&!this.getBitXY(f,h.y));f++)a.setBitXY(f,h.y),h.y+1<this.height&&!this.getBitXY(f,h.y+1)&&o.push(new Node(f,h.y+1)),h.y-1>=0&&!this.getBitXY(f,h.y-1)&&o.push(new Node(f,h.y-1))}return a}function Node(e,i){this.x=e,this.y=i}function _extends(){return _extends=Object.assign?Object.assign.bind():function(e){for(var i=1;i<arguments.length;i++){var t=arguments[i];for(var n in t)({}).hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e},_extends.apply(null,arguments)}function hsv2rgb(e,i,t){i=i/100,t=t/100;var n=[],a=t*i,s=e/60,o=a*(1-Math.abs(s%2-1)),h=t-a;return s>=0&&s<1?n=[a,o,0]:s>=1&&s<2?n=[o,a,0]:s>=2&&s<3?n=[0,a,o]:e>=3&&s<4?n=[0,o,a]:e>=4&&s<5?n=[o,0,a]:e>=5&&s<=6?n=[a,0,o]:n=[0,0,0],{r:Math.round(255*(n[0]+h)),g:Math.round(255*(n[1]+h)),b:Math.round(255*(n[2]+h))}}function hsl2hsv(e,i,t){return i*=(t<50?t:100-t)/100,{h:e,s:2*i/(t+i)*100,v:t+i}}function hsl2rgb$1(e,i,t){var n=hsl2hsv(e,i,t);return hsv2rgb(n.h,n.s,n.v)}var colors={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,132,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,255,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,203],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[119,128,144],slategrey:[119,128,144],snow:[255,255,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,5]};function parse(e){return named(e)||hex3(e)||hex6(e)||rgb(e)||rgba$1(e)||hsl(e)||hsla(e)}function named(e){var i=colors[e.toLowerCase()];if(i)return{r:i[0],g:i[1],b:i[2],a:100}}function rgb(e){var i=e.match(/rgb\(([^)]+)\)/);if(i){var t=i[1].split(/ *, */).map(Number);return{r:t[0],g:t[1],b:t[2],a:100}}}function rgba$1(e){var i=e.match(/rgba\(([^)]+)\)/);if(i){var t=i[1].split(/ *, */).map(Number);return{r:t[0],g:t[1],b:t[2],a:t[3]*100}}}function hex6(e){if(e[0]==="#"&&e.length===7)return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16),a:100}}function hex3(e){if(e[0]==="#"&&e.length===4)return{r:parseInt(e[1]+e[1],16),g:parseInt(e[2]+e[2],16),b:parseInt(e[3]+e[3],16),a:100}}function hsl(e){var i=e.match(/hsl\(([^)]+)\)/);if(i){var t=i[1].split(/ *, */),n=parseInt(t[0],10),a=parseInt(t[1],10),s=parseInt(t[2],10),o=hsl2rgb$1(n,a,s);return _extends({},o,{a:100})}}function hsla(e){var i=e.match(/hsla\(([^)]+)\)/);if(i){var t=i[1].split(/ *, */),n=parseInt(t[0],10),a=parseInt(t[1],10),s=parseInt(t[2],10),o=parseInt(parseFloat(t[3])*100,10),h=hsl2rgb$1(n,a,s);return _extends({},h,{a:o})}}function css2array(e){let i=parse(e);return[i.r,i.g,i.b,Math.round(i.a*255/100)]}function hue2rgb(e,i,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?e+(i-e)*6*t:t<1/2?i:t<2/3?e+(i-e)*(2/3-t)*6:e}function hsl2rgb(e,i,t){let n,a,s,o,h,f;return i/=100,t/=100,i===0?o=h=f=t*255:(t<=.5?a=t*(i+1):a=t+i-t*i,n=t*2-a,s=e/360,o=hue2rgb(n,a,s+1/3),h=hue2rgb(n,a,s),f=hue2rgb(n,a,s-1/3)),{r:o,g:h,b:f}}function getDistinctColors(e){let i=new Array(e),t=0;for(let n=0;n<360;n+=360/e){t++;let a=hsl2rgb(n,100,30+t%4*15);i[t-1]=[Math.round(a.r*255),Math.round(a.g*255),Math.round(a.b*255)]}return i}function getRandomColor(){return[Math.floor(Math.random()*256),Math.floor(Math.random()*256),Math.floor(Math.random()*256)]}function getColors(e){let{color:i,colors:t,randomColors:n,numberColors:a=50}=e;if(i&&!Array.isArray(i)&&(i=css2array(i)),i)return[i];if(t)return t=t.map(function(s){return Array.isArray(s)?s:css2array(s)}),t;if(n){t=new Array(a);for(let s=0;s<a;s++)t[s]=getRandomColor()}return getDistinctColors(a)}function paintLabels(e,i,t={}){let{color:n="blue",colors:a,font:s="12px Helvetica",rotate:o=0}=t;if(this.checkProcessable("paintMasks",{channels:[3,4],bitDepth:[8,16],colorModel:RGB$1}),!Array.isArray(e))throw Error("paintLabels: labels must be an array");if(!Array.isArray(i))throw Error("paintLabels: positions must be an array");if(n&&!Array.isArray(n)&&(n=css2array(n)),a?a=a.map(function(l){return Array.isArray(l)?l:css2array(l)}):a=[n],e.length!==i.length)throw Error("paintLabels: positions and labels must be arrays from the same size");Array.isArray(s)||(s=[s]),Array.isArray(o)||(o=[o]);let f=this.getCanvas().getContext("2d");for(let l=0;l<e.length;l++){f.save();let u=a[l%a.length];f.fillStyle=`rgba(${u[0]},${u[1]},${u[2]},${u[3]/this.maxValue})`,f.font=s[l%s.length];let w=i[l];f.translate(w[0],w[1]),f.rotate(o[l%o.length]/180*Math.PI),f.fillText(e[l],0,0),f.restore()}return this.data=Uint8Array.from(f.getImageData(0,0,this.width,this.height).data),this}function paintMasks(e,i={}){let{alpha:t=255,labels:n=[],labelsPosition:a=[],labelColor:s="blue",labelFont:o="12px Helvetica"}=i;this.checkProcessable("paintMasks",{channels:[3,4],bitDepth:[8,16],colorModel:RGB$1});let h=getColors(Object.assign({},i,{numberColors:e.length}));Array.isArray(e)||(e=[e]);for(let f=0;f<e.length;f++){let l=e[f],u=h[f%h.length];for(let w=0;w<l.width;w++)for(let _=0;_<l.height;_++)if(l.getBitXY(w,_))for(let g=0;g<Math.min(this.components,u.length);g++)if(t===255)this.setValueXY(w+l.position[0],_+l.position[1],g,u[g]);else{let v=this.getValueXY(w+l.position[0],_+l.position[1],g);v=Math.round((v*(255-t)+u[g]*t)/255),this.setValueXY(w+l.position[0],_+l.position[1],g,v)}}if(Array.isArray(n)&&n.length>0){let l=this.getCanvas().getContext("2d");l.fillStyle=s,l.font=o;for(let u=0;u<Math.min(e.length,n.length);u++){let w=a[u]?a[u]:e[u].position;l.fillText(n[u],w[0],w[1])}this.data=Uint8Array.from(l.getImageData(0,0,this.width,this.height).data)}return this}function zerosMatrix(e,i){let t=new Array(e);for(let n=0;n<e;n++)t[n]=new Array(i).fill(0);return t}const cross=[[0,0,1,0,0],[0,0,1,0,0],[1,1,1,1,1],[0,0,1,0,0],[0,0,1,0,0]],smallCross=[[0,1,0],[1,1,1],[0,1,0]];class Shape{constructor(i={}){let{kind:t="cross",shape:n,size:a,width:s,height:o,filled:h=!0}=i;if(a&&(s=a,o=a),n)switch(n.toLowerCase()){case"square":case"rectangle":this.matrix=rectangle(s,o,{filled:h});break;case"circle":case"ellipse":this.matrix=ellipse(s,o,{filled:h});break;case"triangle":this.matrix=triangle(s,o,{filled:h});break;default:throw new Error(`Shape: unexpected shape: ${n}`)}else if(t)switch(t.toLowerCase()){case"cross":this.matrix=cross;break;case"smallcross":this.matrix=smallCross;break;default:throw new Error(`Shape: unexpected kind: ${t}`)}else throw new Error("Shape: expected a kind or a shape option");this.height=this.matrix.length,this.width=this.matrix[0].length,this.halfHeight=this.height/2>>0,this.halfWidth=this.width/2>>0}getPoints(){let i=this.matrix,t=[];for(let n=0;n<i.length;n++)for(let a=0;a<i[0].length;a++)i[n][a]&&t.push([a-this.halfWidth,n-this.halfHeight]);return t}getMask(){let i=new Image(this.width,this.height,{kind:BINARY});for(let t=0;t<this.matrix.length;t++)for(let n=0;n<this.matrix[0].length;n++)this.matrix[t][n]&&i.setBitXY(n,t);return i}}function rectangle(e,i,t){const n=zerosMatrix(i,e);if(t.filled)for(let a=0;a<i;a++)for(let s=0;s<e;s++)n[a][s]=1;else{for(let a of[0,i-1])for(let s=0;s<e;s++)n[a][s]=1;for(let a=0;a<i;a++)for(let s of[0,e-1])n[a][s]=1}return n}function ellipse(e,i,t){const n=zerosMatrix(i,e);let a=1-i%2,s=1-e%2,o=Math.floor((e-1)/2),h=Math.floor((i-1)/2),f=o*o,l=h*h;if(t.filled)for(let u=0;u<=h;u++){let w=Math.floor(Math.sqrt(f-f*u*u/l));for(let _=o-w;_<=o;_++)n[h-u][_]=1,n[h+u+a][_]=1,n[h-u][e-_-1]=1,n[h+u+a][e-_-1]=1}else{for(let u=0;u<=h;u++){let w=Math.floor(Math.sqrt(f-f*u*u/l)),_=o-w;n[h-u][_]=1,n[h+u+a][_]=1,n[h-u][e-_-1]=1,n[h+u+a][e-_-1]=1}for(let u=0;u<=o;u++){let w=Math.floor(Math.sqrt(l-l*u*u/f)),_=h-w;n[_][o-u]=1,n[_][o+u+s]=1,n[i-_-1][o-u]=1,n[i-_-1][o+u+s]=1}}return n}function triangle(e,i,t){if(!t.filled)throw new Error("Non filled triangle is not implemented");const n=zerosMatrix(i,e);for(let a=0;a<i;a++){let s=Math.floor((1-a/i)*e/2);for(let o=s;o<e-s;o++)n[a][o]=1}return n}function paintPoints(e,i={}){let{shape:t}=i;this.checkProcessable("paintPoints",{bitDepth:[8,16]});let n=getColors(Object.assign({},i,{numberColors:e.length})),a=new Shape(t).getPoints(),s=Math.min(this.channels,n[0].length);for(let o=0;o<e.length;o++){let h=n[o%n.length],f=e[o][0],l=e[o][1];for(let u=0;u<a.length;u++){let w=a[u][0],_=a[u][1];if(f+w>=0&&l+_>=0&&f+w<this.width&&l+_<this.height){let g=(f+w+(l+_)*this.width)*this.channels;for(let v=0;v<s;v++)this.data[g+v]=h[v]}}}return this}function paintPolyline(e,i={}){let{color:t=[this.maxValue,0,0],closed:n=!1}=i;this.checkProcessable("paintPoints",{bitDepth:[1,8,16]});let a=Math.min(this.channels,t.length);for(let s=0;s<e.length-1+n;s++){let o=e[s],h=e[(s+1)%e.length],f=h[0]-o[0],l=h[1]-o[1],u=Math.max(Math.abs(f),Math.abs(l)),w=f/u,_=l/u,g=o[0],v=o[1];for(let k=0;k<=u;k++){let A=Math.round(g),T=Math.round(v);if(A>=0&&T>=0&&A<this.width&&T<this.height)if(this.bitDepth===1)this.setBitXY(A,T);else{let $=(A+T*this.width)*this.channels;for(let D=0;D<a;D++)this.data[$+D]=t[D]}g=g+w,v=v+_}}return this}function paintPolylines(e,i={}){let t=Object.assign({},i);this.checkProcessable("paintPolylines",{bitDepth:[8,16]});let n=getColors(Object.assign({},i,{numberColors:e.length}));for(let a=0;a<e.length;a++)t.color=n[a%n.length],this.paintPolyline(e[a],t);return this}function paintPolygon(e,i={}){let{color:t=[this.maxValue,0,0],filled:n=!1}=i;this.checkProcessable("paintPoints",{bitDepth:[1,8,16]}),i.closed=!0;let a=deleteDouble(e);if(n===!1)return this.paintPolyline(e,i);{let s=Array(this.height);for(let o=0;o<this.height;o++){s[o]=[];for(let h=0;h<this.width;h++)s[o].push(0)}for(let o=0;o<a.length;o++){const h=lineBetweenTwoPoints(a[o],a[(o+1)%a.length]);for(let f=0;f<this.height;f++)for(let l=0;l<this.width;l++)isAtTheRightOfTheLine(l,f,h,this.height)&&(s[f][l]=s[f][l]===0?1:0)}for(let o=0;o<this.height;o++)for(let h=0;h<this.width;h++)if(s[o][h]===1)if(this.bitDepth===1)this.setBitXY(h,o);else{let f=Math.min(this.channels,t.length),l=(h+o*this.width)*this.channels;for(let u=0;u<f;u++)this.data[l+u]=t[u]}return this.paintPolyline(e,i)}}function deleteDouble(e){let i=[];for(let t=0;t<e.length;t++)if(!(e[t][0]===e[(t+1)%e.length][0]&&e[t][1]===e[(t+1)%e.length][1])){if(e[t][0]===e[(t-1+e.length)%e.length][0]&&e[t][1]===e[(t-1+e.length)%e.length][1])continue;if(e[(t+1)%e.length][0]===e[(t-1+e.length)%e.length][0]&&e[(t-1+e.length)%e.length][1]===e[(t+1)%e.length][1])continue;i.push(e[t])}return i}function lineBetweenTwoPoints(e,i){if(e[0]===i[0])return{a:0,b:e[0],vertical:!0};{const t=(i[1]-e[1])/(i[0]-e[0]),n=e[1]-t*e[0];return{a:t,b:n,vertical:!1}}}function isAtTheRightOfTheLine(e,i,t,n){if(t.vertical===!0)return t.b<=e;if(t.a===0)return!1;{const a=(i-t.b)/t.a;return a<e&&a>=0&&a<=n}}function paintPolygons(e,i={}){let t=Object.assign({},i);this.checkProcessable("paintPolygons",{bitDepth:[8,16]});let n=getColors(Object.assign({},i,{numberColors:e.length}));for(let a=0;a<e.length;a++)t.color=n[a%n.length],this.paintPolygon(e[a],t);return this}function getHistogram(e={}){let{maxSlots:i=256,channel:t,useAlpha:n=!0}=e;if(this.checkProcessable("getHistogram",{bitDepth:[1,8,16]}),t===void 0){if(this.components>1)throw new RangeError("You need to define the channel for an image that contains more than one channel");t=0}return getChannelHistogram.call(this,t,{useAlpha:n,maxSlots:i})}function getHistograms(e={}){const{maxSlots:i=256,useAlpha:t=!0}=e;this.checkProcessable("getHistograms",{bitDepth:[8,16]});let n=new Array(t?this.components:this.channels);for(let a=0;a<n.length;a++)n[a]=getChannelHistogram.call(this,a,{useAlpha:t,maxSlots:i});return n}function getChannelHistogram(e,i){let{useAlpha:t,maxSlots:n}=i;if(this.bitDepth===1){let f=[0,0];for(let l=0;l<this.height;l++)for(let u=0;u<this.width;u++){let w=this.getBitXY(l,u);w===0?f[0]+=1:w===1&&(f[1]+=1)}return f}let a=Math.log2(n);if(!isInteger(a))throw new RangeError("maxSlots must be a power of 2, for example: 64, 256, 1024");let s=0;this.bitDepth>a&&(s=this.bitDepth-a);let o=this.data,h=newArray(Math.pow(2,Math.min(this.bitDepth,a)),0);if(t&&this.alpha){let f=this.channels-e-1;for(let l=e;l<o.length;l+=this.channels)h[o[l]>>s]+=o[l+f]/this.maxValue}else for(let f=e;f<o.length;f+=this.channels)h[o[f]>>s]++;return h}function getColorHistogram(e={}){let{useAlpha:i=!0,nbSlots:t=512}=e;this.checkProcessable("getColorHistogram",{bitDepth:[8,16],components:[3]});let n=Math.log(t)/Math.log(8);if(n!==Math.floor(n))throw new RangeError("nbSlots must be a power of 8. Usually 8, 64, 512 or 4096");let a=this.bitDepth-n,s=this.data,o=newArray(Math.pow(8,n),0),h=Math.pow(2,n*2),f=Math.pow(2,n);for(let l=0;l<s.length;l+=this.channels){let u=(s[l]>>a)*h+(s[l+1]>>a)*f+(s[l+2]>>a);i&&this.alpha?o[u]+=s[l+this.channels-1]/this.maxValue:o[u]++}return o}function min(){this.checkProcessable("min",{bitDepth:[8,16,32]});let e=newArray(this.channels,1/0);for(let i=0;i<this.data.length;i+=this.channels)for(let t=0;t<this.channels;t++)this.data[i+t]<e[t]&&(e[t]=this.data[i+t]);return e}function max(){this.checkProcessable("max",{bitDepth:[8,16,32]});let e=newArray(this.channels,-1/0);for(let i=0;i<this.data.length;i+=this.channels)for(let t=0;t<this.channels;t++)this.data[i+t]>e[t]&&(e[t]=this.data[i+t]);return e}function sum(){this.checkProcessable("sum",{bitDepth:[8,16]});let e=newArray(this.channels,0);for(let i=0;i<this.data.length;i+=this.channels)for(let t=0;t<this.channels;t++)e[t]+=this.data[i+t];return e}function getMoment(e=0,i=0){this.checkProcessable("getMoment",{bitDepth:[1]});let t=0;for(let n=0;n<this.width;n++)for(let a=0;a<this.height;a++)this.getBitXY(n,a)===1&&(t+=n**e*a**i);return t}function localMaxima(e={}){let{mask:i,region:t=3,removeClosePoints:n=0,invert:a=!1,maxEquals:s=2}=e,o=this;this.checkProcessable("localMaxima",{bitDepth:[8,16],components:1}),t*=4;let h=a?0:1,f=[1,0,-1,0,1,1,-1,-1,2,0,-2,0,2,2,-2,-2],l=[0,1,0,-1,1,-1,1,-1,0,2,0,-2,2,-2,2,-2],u=t<=8?1:2,w=[];for(let _=u;_<o.height-u;_++)for(let g=u;g<o.width-u;g++){if(i&&i.getBitXY(g,_)!==h)continue;let v=0,k=0,A=o.data[g+_*o.width];for(let T=0;T<t;T++)a?o.data[g+f[T]+(_+l[T])*o.width]>A&&v++:o.data[g+f[T]+(_+l[T])*o.width]<A&&v++,o.data[g+f[T]+(_+l[T])*o.width]===A&&k++;v+k===t&&k<=s&&w.push([g,_])}if(n>0)for(let _=0;_<w.length;_++)for(let g=_+1;g<w.length;g++)Math.sqrt(Math.pow(w[_][0]-w[g][0],2)+Math.pow(w[_][1]-w[g][1],2))<n&&(w[_][0]=w[_][0]+w[g][0]>>1,w[_][1]=w[_][1]+w[g][1]>>1,w.splice(g,1),g--);return w}function mean(){let e=this.getHistograms({maxSlots:this.maxValue+1}),i=new Array(e.length);for(let t=0;t<e.length;t++){let n=e[t];i[t]=mean$2(n)}return i}function median(){let e=this.getHistograms({maxSlots:this.maxValue+1}),i=new Array(e.length);for(let t=0;t<e.length;t++){let n=e[t];i[t]=median$2(n)}return i}function points(){this.checkProcessable("points",{bitDepth:[1]});const e=[];for(let i=0;i<this.width;i++)for(let t=0;t<this.height;t++)this.getBitXY(i,t)===1&&e.push([i,t]);return e}function extendedPoints(){this.checkProcessable("extendedPoints",{bitDepth:[1]});const e=[];for(let i=0;i<this.height;i++)for(let t=0;t<this.width;t++)if(this.getBitXY(t,i)===1)for(e.push([t,i]),this.getBitXY(t+1,i)!==1?(e.push([t+1,i]),e.push([t+1,i+1]),this.getBitXY(t,i+1)!==1&&e.push([t,i+1])):this.getBitXY(t,i+1)!==1&&(e.push([t,i+1]),e.push([t+1,i+1]));t<this.width-2&&this.getBitXY(t+1,i)===1&&this.getBitXY(t+2,i)===1;)t++;return e}function getRelativePosition(e,i={}){if(this===e)return[0,0];let t=[0,0],n=this;for(;n;){if(n===e)return t;n.position&&(t[0]+=n.position[0],t[1]+=n.position[1]),n=n.parent}return i.defaultFurther?t:!1}function countAlphaPixels(e={}){let{alpha:i=1}=e;this.checkProcessable("countAlphaPixels",{bitDepth:[8,16],alpha:1});let t=0;if(i!==void 0){for(let n=this.components;n<this.data.length;n+=this.channels)this.data[n]===i&&t++;return t}else return this.size}function monotoneChainConvexHull$1(e,i={}){const{sorted:t}=i;t||(e=e.slice().sort(byXThenY));const n=e.length,a=new Array(n*2);let s=0;for(let h=0;h<n;h++){const f=e[h];for(;s>=2&&cw(a[s-2],a[s-1],f)<=0;)s--;a[s++]=f}const o=s+1;for(let h=n-2;h>=0;h--){const f=e[h];for(;s>=o&&cw(a[s-2],a[s-1],f)<=0;)s--;a[s++]=f}return a.slice(0,s-1)}function cw(e,i,t){return(i[1]-e[1])*(t[0]-e[0])-(i[0]-e[0])*(t[1]-e[1])}function byXThenY(e,i){return e[0]===i[0]?e[1]-i[1]:e[0]-i[0]}function monotoneChainConvexHull(){return monotoneChainConvexHull$1(this.extendedPoints,{sorted:!1})}function round(e){for(let i=0;i<e.length;i++)e[i][0]=Math.round(e[i][0]),e[i][1]=Math.round(e[i][1]);return e}function difference(e,i){return[e[0]-i[0],e[1]-i[1]]}function normalize(e){let i=Math.sqrt(e[0]**2+e[1]**2);return[e[0]/i,e[1]/i]}function rotate(e,i,t){t===void 0&&(t=new Array(i.length));let n=Math.cos(e),a=Math.sin(e);for(let s=0;s<t.length;++s)t[s]=[n*i[s][0]-a*i[s][1],a*i[s][0]+n*i[s][1]];return t}function perimeter(e){let i=0;for(let t=0;t<e.length;t++){let n=e[t][0],a=e[t][1],s=e[t===e.length-1?0:t+1][0],o=e[t===e.length-1?0:t+1][1];i+=Math.sqrt((s-n)**2+(o-a)**2)}return i}function surface(e){let i=0;for(let t=0;t<e.length;t++){let n=e[t][0],a=e[t===e.length-1?0:t+1][1],s=e[t===e.length-1?0:t+1][0],o=e[t][1];i+=n*a*.5,i-=s*o*.5}return Math.abs(i)}function minMax(e){let i=1/0,t=1/0,n=-1/0,a=-1/0;for(let s=0;s<e.length;s++)e[s][0]<i&&(i=e[s][0]),e[s][0]>n&&(n=e[s][0]),e[s][1]<t&&(t=e[s][1]),e[s][1]>a&&(a=e[s][1]);return[[i,t],[n,a]]}function moveToZeroZero(e,i){i===void 0&&(i=new Array(e.length).fill(0).map(()=>[]));let t=minMax(e),n=t[0][0],a=t[0][1];for(let s=0;s<e.length;s++)i[s][0]=e[s][0]-n,i[s][1]=e[s][1]-a;return i}function minimalBoundingRectangle(e={}){const{originalPoints:i=monotoneChainConvexHull.call(this)}=e;if(i.length===0)return[];if(i.length===1)return[i[0],i[0],i[0],i[0]];const t=new Array(i.length);let n=1/0,a=0,s;for(let o=0;o<t.length;o++){let h=getAngle$1(i[o],i[(o+1)%t.length]);rotate(-h,i,t);let f=t[o][0],l=t[o][1],u=t[(o+1)%t.length][0],w=t[(o+1)%t.length][1],_=!0,g=0,v=0,k=0;for(let D=0;D<t.length;D++){let C=t[D][0],P=t[D][1],z=(C-f)/(u-f);_===!0?(_=!1,g=z,v=z):(z<g&&(g=z),z>v&&(v=z));let B=(-(u-f)*P+u*l-w*f)/(u-f);Math.abs(B)>Math.abs(k)&&(k=B)}let A=[f+g*(u-f),l],T=[f+v*(u-f),l],$=Math.abs(k*(g-v)*(u-f));$<n&&(a=h,n=$,s=[A,T,[T[0],T[1]-k],[A[0],A[1]-k]])}return rotate(a,s,s),s}function getAngle$1(e,i){let t=difference(i,e),n=normalize(t),a=Math.acos(n[0]);return n[1]<0?-a:a}function extend$1(e){let i={inPlace:!0};e.extendMethod("invert",invert),e.extendMethod("abs",abs),e.extendMethod("level",level,i),e.extendMethod("add",add,i),e.extendMethod("subtract",subtract,i),e.extendMethod("subtractImage",subtractImage),e.extendMethod("multiply",multiply,i),e.extendMethod("divide",divide,i),e.extendMethod("hypotenuse",hypotenuse),e.extendMethod("background",background$1),e.extendMethod("flipX",flipX),e.extendMethod("flipY",flipY),e.extendMethod("blurFilter",blurFilter),e.extendMethod("medianFilter",medianFilter),e.extendMethod("gaussianFilter",gaussianFilter),e.extendMethod("sobelFilter",sobelFilter),e.extendMethod("gradientFilter",gradientFilter),e.extendMethod("scharrFilter",scharrFilter),e.extendMethod("dilate",dilate),e.extendMethod("erode",erode),e.extendMethod("open",open),e.extendMethod("close",close),e.extendMethod("topHat",topHat),e.extendMethod("blackHat",blackHat),e.extendMethod("morphologicalGradient",morphologicalGradient),e.extendMethod("warpingFourPoints",warpingFourPoints),e.extendMethod("crop",crop),e.extendMethod("cropAlpha",cropAlpha),e.extendMethod("resize",resize).extendMethod("scale",resize),e.extendMethod("hsv",hsv),e.extendMethod("hsl",hsl$1),e.extendMethod("cmyk",cmyk),e.extendMethod("rgba8",rgba8),e.extendMethod("grey",grey).extendMethod("gray",grey),e.extendMethod("mask",mask),e.extendMethod("pad",pad),e.extendMethod("colorDepth",colorDepth),e.extendMethod("setBorder",setBorder,i),e.extendMethod("rotate",rotate$1),e.extendMethod("rotateLeft",rotateLeft),e.extendMethod("rotateRight",rotateRight),e.extendMethod("insert",insert),e.extendMethod("getRow",getRow),e.extendMethod("getColumn",getColumn),e.extendMethod("getMatrix",getMatrix),e.extendMethod("setMatrix",setMatrix),e.extendMethod("getPixelsArray",getPixelsArray),e.extendMethod("getIntersection",getIntersection),e.extendMethod("getClosestCommonParent",getClosestCommonParent),e.extendMethod("getThreshold",getThreshold),e.extendMethod("split",split),e.extendMethod("getChannel",getChannel),e.extendMethod("combineChannels",combineChannels),e.extendMethod("setChannel",setChannel),e.extendMethod("getSimilarity",getSimilarity),e.extendMethod("getPixelsGrid",getPixelsGrid),e.extendMethod("getBestMatch",getBestMatch),e.extendMethod("cannyEdge",cannyEdge),e.extendMethod("convolution",convolution),e.extendMethod("extract",extract),e.extendMethod("floodFill",floodFill),e.extendMethod("paintLabels",paintLabels,i),e.extendMethod("paintMasks",paintMasks,i),e.extendMethod("paintPoints",paintPoints,i),e.extendMethod("paintPolyline",paintPolyline,i),e.extendMethod("paintPolylines",paintPolylines,i),e.extendMethod("paintPolygon",paintPolygon,i),e.extendMethod("paintPolygons",paintPolygons,i),e.extendMethod("countAlphaPixels",countAlphaPixels),e.extendMethod("monotoneChainConvexHull",monotoneChainConvexHull),e.extendMethod("minimalBoundingRectangle",minimalBoundingRectangle),e.extendMethod("getHistogram",getHistogram).extendProperty("histogram",getHistogram),e.extendMethod("getHistograms",getHistograms).extendProperty("histograms",getHistograms),e.extendMethod("getColorHistogram",getColorHistogram).extendProperty("colorHistogram",getColorHistogram),e.extendMethod("getMin",min).extendProperty("min",min),e.extendMethod("getMax",max).extendProperty("max",max),e.extendMethod("getSum",sum).extendProperty("sum",sum),e.extendMethod("getMoment",getMoment).extendProperty("moment",getMoment),e.extendMethod("getLocalMaxima",localMaxima),e.extendMethod("getMedian",median).extendProperty("median",median),e.extendMethod("getMean",mean).extendProperty("mean",mean),e.extendMethod("getPoints",points).extendProperty("points",points),e.extendMethod("getExtendedPoints",extendedPoints).extendProperty("extendedPoints",extendedPoints),e.extendMethod("getRelativePosition",getRelativePosition)}var quantities$1={exports:{}},quantities=quantities$1.exports,hasRequiredQuantities;function requireQuantities(){return hasRequiredQuantities||(hasRequiredQuantities=1,function(e,i){(function(t,n){e.exports=n()})(quantities,function(){function t(M){return typeof M=="string"||M instanceof String}var n=Number.isFinite||window.isFinite;function a(M){return n(M)}function s(M){return M}function o(M){var m={};return M.filter(function(d){return m.hasOwnProperty(d)?!1:m[d]=!0})}function h(M,m){if(m.length!==M.length)return!1;for(var d=0;d<M.length;d++)if(m[d].compareArray&&!m[d].compareArray(M[d])||m[d]!==M[d])return!1;return!0}function f(M,m){Object.keys(m).forEach(function(d){M[d]=m[d]})}function l(){for(var M=1,m=0,d=0;d<arguments.length;d++){var c=arguments[d];m=m+_(c),M*=c}return m!==0?w(M,m):M}function u(M,m){if(m===0)throw new Error("Divide by zero");var d=Math.pow(10,_(m)),c=d/(d*m);return l(M,c)}function w(M,m){return Math.round(M*Math.pow(10,m))/Math.pow(10,m)}function _(M){if(!isFinite(M))return 0;for(var m=0;M%1!==0;)M*=10,m++;return m}function g(){var M;if(!this)return M=Object.create(g.prototype),g.apply(M,arguments),M;M=Error.apply(this,arguments),this.name="QtyError",this.message=M.message,this.stack=M.stack}g.prototype=Object.create(Error.prototype,{constructor:{value:g}});function v(M,m){throw new g("Incompatible units: "+M+" and "+m)}var k={"<googol>":[["googol"],1e100,"prefix"],"<kibi>":[["Ki","Kibi","kibi"],Math.pow(2,10),"prefix"],"<mebi>":[["Mi","Mebi","mebi"],Math.pow(2,20),"prefix"],"<gibi>":[["Gi","Gibi","gibi"],Math.pow(2,30),"prefix"],"<tebi>":[["Ti","Tebi","tebi"],Math.pow(2,40),"prefix"],"<pebi>":[["Pi","Pebi","pebi"],Math.pow(2,50),"prefix"],"<exi>":[["Ei","Exi","exi"],Math.pow(2,60),"prefix"],"<zebi>":[["Zi","Zebi","zebi"],Math.pow(2,70),"prefix"],"<yebi>":[["Yi","Yebi","yebi"],Math.pow(2,80),"prefix"],"<yotta>":[["Y","Yotta","yotta"],1e24,"prefix"],"<zetta>":[["Z","Zetta","zetta"],1e21,"prefix"],"<exa>":[["E","Exa","exa"],1e18,"prefix"],"<peta>":[["P","Peta","peta"],1e15,"prefix"],"<tera>":[["T","Tera","tera"],1e12,"prefix"],"<giga>":[["G","Giga","giga"],1e9,"prefix"],"<mega>":[["M","Mega","mega"],1e6,"prefix"],"<kilo>":[["k","kilo"],1e3,"prefix"],"<hecto>":[["h","Hecto","hecto"],100,"prefix"],"<deca>":[["da","Deca","deca","deka"],10,"prefix"],"<deci>":[["d","Deci","deci"],.1,"prefix"],"<centi>":[["c","Centi","centi"],.01,"prefix"],"<milli>":[["m","Milli","milli"],.001,"prefix"],"<micro>":[["u","μ","µ","Micro","mc","micro"],1e-6,"prefix"],"<nano>":[["n","Nano","nano"],1e-9,"prefix"],"<pico>":[["p","Pico","pico"],1e-12,"prefix"],"<femto>":[["f","Femto","femto"],1e-15,"prefix"],"<atto>":[["a","Atto","atto"],1e-18,"prefix"],"<zepto>":[["z","Zepto","zepto"],1e-21,"prefix"],"<yocto>":[["y","Yocto","yocto"],1e-24,"prefix"],"<1>":[["1","<1>"],1,""],"<meter>":[["m","meter","meters","metre","metres"],1,"length",["<meter>"]],"<inch>":[["in","inch","inches",'"'],.0254,"length",["<meter>"]],"<foot>":[["ft","foot","feet","'"],.3048,"length",["<meter>"]],"<yard>":[["yd","yard","yards"],.9144,"length",["<meter>"]],"<mile>":[["mi","mile","miles"],1609.344,"length",["<meter>"]],"<naut-mile>":[["nmi","naut-mile"],1852,"length",["<meter>"]],"<league>":[["league","leagues"],4828,"length",["<meter>"]],"<furlong>":[["furlong","furlongs"],201.2,"length",["<meter>"]],"<rod>":[["rd","rod","rods"],5.029,"length",["<meter>"]],"<mil>":[["mil","mils"],254e-7,"length",["<meter>"]],"<angstrom>":[["ang","angstrom","angstroms"],1e-10,"length",["<meter>"]],"<fathom>":[["fathom","fathoms"],1.829,"length",["<meter>"]],"<pica>":[["pica","picas"],.00423333333,"length",["<meter>"]],"<point>":[["pt","point","points"],.000352777778,"length",["<meter>"]],"<redshift>":[["z","red-shift","redshift"],1302773e20,"length",["<meter>"]],"<AU>":[["AU","astronomical-unit"],1495979e5,"length",["<meter>"]],"<light-second>":[["ls","light-second"],299792500,"length",["<meter>"]],"<light-minute>":[["lmin","light-minute"],1798755e4,"length",["<meter>"]],"<light-year>":[["ly","light-year"],9460528e9,"length",["<meter>"]],"<parsec>":[["pc","parsec","parsecs"],3085678e10,"length",["<meter>"]],"<datamile>":[["DM","datamile"],1828.8,"length",["<meter>"]],"<kilogram>":[["kg","kilogram","kilograms"],1,"mass",["<kilogram>"]],"<AMU>":[["u","AMU","amu"],1660538921e-36,"mass",["<kilogram>"]],"<dalton>":[["Da","Dalton","Daltons","dalton","daltons"],1660538921e-36,"mass",["<kilogram>"]],"<slug>":[["slug","slugs"],14.5939029,"mass",["<kilogram>"]],"<short-ton>":[["tn","ton","short-ton"],907.18474,"mass",["<kilogram>"]],"<metric-ton>":[["t","tonne","metric-ton"],1e3,"mass",["<kilogram>"]],"<carat>":[["ct","carat","carats"],2e-4,"mass",["<kilogram>"]],"<pound>":[["lbs","lb","pound","pounds","#"],.45359237,"mass",["<kilogram>"]],"<ounce>":[["oz","ounce","ounces"],.0283495231,"mass",["<kilogram>"]],"<gram>":[["g","gram","grams","gramme","grammes"],.001,"mass",["<kilogram>"]],"<grain>":[["grain","grains","gr"],6479891e-11,"mass",["<kilogram>"]],"<dram>":[["dram","drams","dr"],.0017718452,"mass",["<kilogram>"]],"<stone>":[["stone","stones","st"],6.35029318,"mass",["<kilogram>"]],"<hectare>":[["hectare"],1e4,"area",["<meter>","<meter>"]],"<acre>":[["acre","acres"],4046.85642,"area",["<meter>","<meter>"]],"<sqft>":[["sqft"],1,"area",["<foot>","<foot>"]],"<liter>":[["l","L","liter","liters","litre","litres"],.001,"volume",["<meter>","<meter>","<meter>"]],"<gallon>":[["gal","gallon","gallons"],.0037854118,"volume",["<meter>","<meter>","<meter>"]],"<gallon-imp>":[["galimp","gallon-imp","gallons-imp"],.00454609,"volume",["<meter>","<meter>","<meter>"]],"<quart>":[["qt","quart","quarts"],.00094635295,"volume",["<meter>","<meter>","<meter>"]],"<pint>":[["pt","pint","pints"],.000473176475,"volume",["<meter>","<meter>","<meter>"]],"<pint-imp>":[["ptimp","pint-imp","pints-imp"],.00056826125,"volume",["<meter>","<meter>","<meter>"]],"<cup>":[["cu","cup","cups"],.000236588238,"volume",["<meter>","<meter>","<meter>"]],"<fluid-ounce>":[["floz","fluid-ounce","fluid-ounces"],295735297e-13,"volume",["<meter>","<meter>","<meter>"]],"<fluid-ounce-imp>":[["flozimp","floz-imp","fluid-ounce-imp","fluid-ounces-imp"],284130625e-13,"volume",["<meter>","<meter>","<meter>"]],"<tablespoon>":[["tb","tbsp","tbs","tablespoon","tablespoons"],147867648e-13,"volume",["<meter>","<meter>","<meter>"]],"<teaspoon>":[["tsp","teaspoon","teaspoons"],492892161e-14,"volume",["<meter>","<meter>","<meter>"]],"<bushel>":[["bu","bsh","bushel","bushels"],.035239072,"volume",["<meter>","<meter>","<meter>"]],"<oilbarrel>":[["bbl","oilbarrel","oilbarrels","oil-barrel","oil-barrels"],.158987294928,"volume",["<meter>","<meter>","<meter>"]],"<beerbarrel>":[["bl","bl-us","beerbarrel","beerbarrels","beer-barrel","beer-barrels"],.1173477658,"volume",["<meter>","<meter>","<meter>"]],"<beerbarrel-imp>":[["blimp","bl-imp","beerbarrel-imp","beerbarrels-imp","beer-barrel-imp","beer-barrels-imp"],.16365924,"volume",["<meter>","<meter>","<meter>"]],"<kph>":[["kph"],.277777778,"speed",["<meter>"],["<second>"]],"<mph>":[["mph"],.44704,"speed",["<meter>"],["<second>"]],"<knot>":[["kt","kn","kts","knot","knots"],.514444444,"speed",["<meter>"],["<second>"]],"<fps>":[["fps"],.3048,"speed",["<meter>"],["<second>"]],"<gee>":[["gee"],9.80665,"acceleration",["<meter>"],["<second>","<second>"]],"<Gal>":[["Gal"],.01,"acceleration",["<meter>"],["<second>","<second>"]],"<kelvin>":[["degK","kelvin"],1,"temperature",["<kelvin>"]],"<celsius>":[["degC","celsius","celsius","centigrade"],1,"temperature",["<kelvin>"]],"<fahrenheit>":[["degF","fahrenheit"],5/9,"temperature",["<kelvin>"]],"<rankine>":[["degR","rankine"],5/9,"temperature",["<kelvin>"]],"<temp-K>":[["tempK","temp-K"],1,"temperature",["<temp-K>"]],"<temp-C>":[["tempC","temp-C"],1,"temperature",["<temp-K>"]],"<temp-F>":[["tempF","temp-F"],5/9,"temperature",["<temp-K>"]],"<temp-R>":[["tempR","temp-R"],5/9,"temperature",["<temp-K>"]],"<second>":[["s","sec","secs","second","seconds"],1,"time",["<second>"]],"<minute>":[["min","mins","minute","minutes"],60,"time",["<second>"]],"<hour>":[["h","hr","hrs","hour","hours"],3600,"time",["<second>"]],"<day>":[["d","day","days"],3600*24,"time",["<second>"]],"<week>":[["wk","week","weeks"],7*3600*24,"time",["<second>"]],"<fortnight>":[["fortnight","fortnights"],1209600,"time",["<second>"]],"<year>":[["y","yr","year","years","annum"],31556926,"time",["<second>"]],"<decade>":[["decade","decades"],315569260,"time",["<second>"]],"<century>":[["century","centuries"],3155692600,"time",["<second>"]],"<pascal>":[["Pa","pascal","Pascal"],1,"pressure",["<kilogram>"],["<meter>","<second>","<second>"]],"<bar>":[["bar","bars"],1e5,"pressure",["<kilogram>"],["<meter>","<second>","<second>"]],"<mmHg>":[["mmHg"],133.322368,"pressure",["<kilogram>"],["<meter>","<second>","<second>"]],"<inHg>":[["inHg"],3386.3881472,"pressure",["<kilogram>"],["<meter>","<second>","<second>"]],"<torr>":[["torr"],133.322368,"pressure",["<kilogram>"],["<meter>","<second>","<second>"]],"<atm>":[["atm","ATM","atmosphere","atmospheres"],101325,"pressure",["<kilogram>"],["<meter>","<second>","<second>"]],"<psi>":[["psi"],6894.76,"pressure",["<kilogram>"],["<meter>","<second>","<second>"]],"<cmh2o>":[["cmH2O","cmh2o"],98.0638,"pressure",["<kilogram>"],["<meter>","<second>","<second>"]],"<inh2o>":[["inH2O","inh2o"],249.082052,"pressure",["<kilogram>"],["<meter>","<second>","<second>"]],"<poise>":[["P","poise"],.1,"viscosity",["<kilogram>"],["<meter>","<second>"]],"<stokes>":[["St","stokes"],1e-4,"viscosity",["<meter>","<meter>"],["<second>"]],"<mole>":[["mol","mole"],1,"substance",["<mole>"]],"<molar>":[["M","molar"],1e3,"molar_concentration",["<mole>"],["<meter>","<meter>","<meter>"]],"<wtpercent>":[["wt%","wtpercent"],10,"molar_concentration",["<kilogram>"],["<meter>","<meter>","<meter>"]],"<katal>":[["kat","katal","Katal"],1,"activity",["<mole>"],["<second>"]],"<unit>":[["U","enzUnit","unit"],16667e-19,"activity",["<mole>"],["<second>"]],"<farad>":[["F","farad","Farad"],1,"capacitance",["<second>","<second>","<second>","<second>","<ampere>","<ampere>"],["<meter>","<meter>","<kilogram>"]],"<coulomb>":[["C","coulomb","Coulomb"],1,"charge",["<ampere>","<second>"]],"<Ah>":[["Ah"],3600,"charge",["<ampere>","<second>"]],"<ampere>":[["A","Ampere","ampere","amp","amps"],1,"current",["<ampere>"]],"<siemens>":[["S","Siemens","siemens"],1,"conductance",["<second>","<second>","<second>","<ampere>","<ampere>"],["<kilogram>","<meter>","<meter>"]],"<henry>":[["H","Henry","henry"],1,"inductance",["<meter>","<meter>","<kilogram>"],["<second>","<second>","<ampere>","<ampere>"]],"<volt>":[["V","Volt","volt","volts"],1,"potential",["<meter>","<meter>","<kilogram>"],["<second>","<second>","<second>","<ampere>"]],"<ohm>":[["Ohm","ohm","Ω","Ω"],1,"resistance",["<meter>","<meter>","<kilogram>"],["<second>","<second>","<second>","<ampere>","<ampere>"]],"<weber>":[["Wb","weber","webers"],1,"magnetism",["<meter>","<meter>","<kilogram>"],["<second>","<second>","<ampere>"]],"<tesla>":[["T","tesla","teslas"],1,"magnetism",["<kilogram>"],["<second>","<second>","<ampere>"]],"<gauss>":[["G","gauss"],1e-4,"magnetism",["<kilogram>"],["<second>","<second>","<ampere>"]],"<maxwell>":[["Mx","maxwell","maxwells"],1e-8,"magnetism",["<meter>","<meter>","<kilogram>"],["<second>","<second>","<ampere>"]],"<oersted>":[["Oe","oersted","oersteds"],250/Math.PI,"magnetism",["<ampere>"],["<meter>"]],"<joule>":[["J","joule","Joule","joules","Joules"],1,"energy",["<meter>","<meter>","<kilogram>"],["<second>","<second>"]],"<erg>":[["erg","ergs"],1e-7,"energy",["<meter>","<meter>","<kilogram>"],["<second>","<second>"]],"<btu>":[["BTU","btu","BTUs"],1055.056,"energy",["<meter>","<meter>","<kilogram>"],["<second>","<second>"]],"<calorie>":[["cal","calorie","calories"],4.184,"energy",["<meter>","<meter>","<kilogram>"],["<second>","<second>"]],"<Calorie>":[["Cal","Calorie","Calories"],4184,"energy",["<meter>","<meter>","<kilogram>"],["<second>","<second>"]],"<therm-US>":[["th","therm","therms","Therm","therm-US"],105480400,"energy",["<meter>","<meter>","<kilogram>"],["<second>","<second>"]],"<Wh>":[["Wh"],3600,"energy",["<meter>","<meter>","<kilogram>"],["<second>","<second>"]],"<electronvolt>":[["eV","electronvolt","electronvolts"],1602176634e-28,"energy",["<meter>","<meter>","<kilogram>"],["<second>","<second>"]],"<newton>":[["N","Newton","newton"],1,"force",["<kilogram>","<meter>"],["<second>","<second>"]],"<dyne>":[["dyn","dyne"],1e-5,"force",["<kilogram>","<meter>"],["<second>","<second>"]],"<pound-force>":[["lbf","pound-force"],4.448222,"force",["<kilogram>","<meter>"],["<second>","<second>"]],"<hertz>":[["Hz","hertz","Hertz"],1,"frequency",["<1>"],["<second>"]],"<radian>":[["rad","radian","radians"],1,"angle",["<radian>"]],"<degree>":[["deg","degree","degrees"],Math.PI/180,"angle",["<radian>"]],"<arcminute>":[["arcmin","arcminute","arcminutes"],Math.PI/10800,"angle",["<radian>"]],"<arcsecond>":[["arcsec","arcsecond","arcseconds"],Math.PI/648e3,"angle",["<radian>"]],"<gradian>":[["gon","grad","gradian","grads"],Math.PI/200,"angle",["<radian>"]],"<steradian>":[["sr","steradian","steradians"],1,"solid_angle",["<steradian>"]],"<rotation>":[["rotation"],2*Math.PI,"angle",["<radian>"]],"<rpm>":[["rpm"],2*Math.PI/60,"angular_velocity",["<radian>"],["<second>"]],"<byte>":[["B","byte","bytes"],1,"information",["<byte>"]],"<bit>":[["b","bit","bits"],.125,"information",["<byte>"]],"<Bps>":[["Bps"],1,"information_rate",["<byte>"],["<second>"]],"<bps>":[["bps"],.125,"information_rate",["<byte>"],["<second>"]],"<dollar>":[["USD","dollar"],1,"currency",["<dollar>"]],"<cents>":[["cents"],.01,"currency",["<dollar>"]],"<candela>":[["cd","candela"],1,"luminosity",["<candela>"]],"<lumen>":[["lm","lumen"],1,"luminous_power",["<candela>","<steradian>"]],"<lux>":[["lux"],1,"illuminance",["<candela>","<steradian>"],["<meter>","<meter>"]],"<watt>":[["W","watt","watts"],1,"power",["<kilogram>","<meter>","<meter>"],["<second>","<second>","<second>"]],"<volt-ampere>":[["VA","volt-ampere"],1,"power",["<kilogram>","<meter>","<meter>"],["<second>","<second>","<second>"]],"<volt-ampere-reactive>":[["var","Var","VAr","VAR","volt-ampere-reactive"],1,"power",["<kilogram>","<meter>","<meter>"],["<second>","<second>","<second>"]],"<horsepower>":[["hp","horsepower"],745.699872,"power",["<kilogram>","<meter>","<meter>"],["<second>","<second>","<second>"]],"<gray>":[["Gy","gray","grays"],1,"radiation",["<meter>","<meter>"],["<second>","<second>"]],"<roentgen>":[["R","roentgen"],.00933,"radiation",["<meter>","<meter>"],["<second>","<second>"]],"<sievert>":[["Sv","sievert","sieverts"],1,"radiation",["<meter>","<meter>"],["<second>","<second>"]],"<becquerel>":[["Bq","becquerel","becquerels"],1,"radiation",["<1>"],["<second>"]],"<curie>":[["Ci","curie","curies"],37e9,"radiation",["<1>"],["<second>"]],"<cpm>":[["cpm"],1/60,"rate",["<count>"],["<second>"]],"<dpm>":[["dpm"],1/60,"rate",["<count>"],["<second>"]],"<bpm>":[["bpm"],1/60,"rate",["<count>"],["<second>"]],"<dot>":[["dot","dots"],1,"resolution",["<each>"]],"<pixel>":[["pixel","px"],1,"resolution",["<each>"]],"<ppi>":[["ppi"],1,"resolution",["<pixel>"],["<inch>"]],"<dpi>":[["dpi"],1,"typography",["<dot>"],["<inch>"]],"<cell>":[["cells","cell"],1,"counting",["<each>"]],"<each>":[["each"],1,"counting",["<each>"]],"<count>":[["count"],1,"counting",["<each>"]],"<base-pair>":[["bp","base-pair"],1,"counting",["<each>"]],"<nucleotide>":[["nt","nucleotide"],1,"counting",["<each>"]],"<molecule>":[["molecule","molecules"],1,"counting",["<1>"]],"<dozen>":[["doz","dz","dozen"],12,"prefix_only",["<each>"]],"<percent>":[["%","percent"],.01,"prefix_only",["<1>"]],"<ppm>":[["ppm"],1e-6,"prefix_only",["<1>"]],"<ppb>":[["ppb"],1e-9,"prefix_only",["<1>"]],"<ppt>":[["ppt"],1e-12,"prefix_only",["<1>"]],"<ppq>":[["ppq"],1e-15,"prefix_only",["<1>"]],"<gross>":[["gr","gross"],144,"prefix_only",["<dozen>","<dozen>"]],"<decibel>":[["dB","decibel","decibels"],1,"logarithmic",["<decibel>"]]},A=["<meter>","<kilogram>","<second>","<mole>","<ampere>","<radian>","<kelvin>","<temp-K>","<byte>","<dollar>","<candela>","<each>","<steradian>","<decibel>"],T="<1>",$=[T];function D(M,m){var d=m[1],c=m[3]||[],b=m[4]||[];if(!a(d))throw new g(M+": Invalid unit definition. 'scalar' must be a number");c.forEach(function(S){if(k[S]===void 0)throw new g(M+": Invalid unit definition. Unit "+S+" in 'numerator' is not recognized")}),b.forEach(function(S){if(k[S]===void 0)throw new g(M+": Invalid unit definition. Unit "+S+" in 'denominator' is not recognized")})}var C={},P={},z={},B={},F={};for(var L in k)if(k.hasOwnProperty(L)){var N=k[L];if(N[2]==="prefix"){C[L]=N[1];for(var G=0;G<N[0].length;G++)P[N[0][G]]=L}else{D(L,N),z[L]={scalar:N[1],numerator:N[3],denominator:N[4]};for(var V=0;V<N[0].length;V++)B[N[0][V]]=L}F[L]=N[0][0]}function J(M){var m,d=[],c=Object.keys(k);if(typeof M>"u")for(m=0;m<c.length;m++)["","prefix"].indexOf(k[c[m]][2])===-1&&d.push(c[m].substr(1,c[m].length-2));else{if(this.getKinds().indexOf(M)===-1)throw new g("Kind not recognized");for(m=0;m<c.length;m++)k[c[m]][2]===M&&d.push(c[m].substr(1,c[m].length-2))}return d.sort(function(b,S){return b.toLowerCase()<S.toLowerCase()?-1:b.toLowerCase()>S.toLowerCase()?1:0})}function Q(M){if(!B[M])throw new g("Unit not recognized");return k[B[M]][0]}var W=["length","time","temperature","mass","current","substance","luminosity","currency","information","angle"];function ne(){if(this.signature)return this.signature;for(var M=me.call(this),m=0;m<M.length;m++)M[m]*=Math.pow(20,m);return M.reduce(function(d,c){return d+c},0)}function me(){if(!this.isBase())return me.call(this.toBase());for(var M=new Array(W.length),m=0;m<M.length;m++)M[m]=0;for(var d,c,b=0;b<this.numerator.length;b++)(d=k[this.numerator[b]])&&(c=W.indexOf(d[2]),c>=0&&(M[c]=M[c]+1));for(var S=0;S<this.denominator.length;S++)(d=k[this.denominator[S]])&&(c=W.indexOf(d[2]),c>=0&&(M[c]=M[c]-1));return M}var ve="[+-]",ye="\\d+",Me=ve+"?"+ye,Re="\\."+ye,_e="(?:"+ye+"(?:"+Re+")?)|(?:"+Re+")",Be="[Ee]"+Me,Se="(?:"+_e+")(?:"+Be+")?",re=ve+"?\\s*"+Se,Ie="("+re+")?\\s*([^/]*)(?:/(.+))?",Fe=new RegExp("^"+Ie+"$"),ke="\\^|\\*{2}",Ye="[01234]",Je=new RegExp("([^ \\*\\d]+?)(?:"+ke+")?(-?"+Ye+"(?![a-zA-Z]))"),et=new RegExp("([^ \\*\\d]+?)(?:"+ke+")?("+Ye+"(?![a-zA-Z]))");function Ve(M){t(M)||(M=M.toString()),M=M.trim();var m=Fe.exec(M);if(!m)throw new g(M+": Quantity not recognized");var d=m[1];d?(d=d.replace(/\s/g,""),this.scalar=parseFloat(d)):this.scalar=1;for(var c=m[2],b=m[3],S,O,q;m=Je.exec(c);){if(S=parseFloat(m[2]),isNaN(S))throw new g("Unit exponent is not a number");if(S===0&&!Ge.test(m[1]))throw new g("Unit not recognized");O=m[1]+" ",q="";for(var X=0;X<Math.abs(S);X++)q+=O;S>=0?c=c.replace(m[0],q):(b=b?b+q:q,c=c.replace(m[0],""))}for(;m=et.exec(b);){if(S=parseFloat(m[2]),isNaN(S))throw new g("Unit exponent is not a number");if(S===0&&!Ge.test(m[1]))throw new g("Unit not recognized");O=m[1]+" ",q="";for(var j=0;j<S;j++)q+=O;b=b.replace(m[0],q)}c&&(this.numerator=Qe(c.trim())),b&&(this.denominator=Qe(b.trim()))}var tt=Object.keys(P).sort(function(M,m){return m.length-M.length}).join("|"),qe=Object.keys(B).sort(function(M,m){return m.length-M.length}).join("|"),De="\\b|$",nt="("+tt+")??("+qe+")(?:"+De+")",Ge=new RegExp("^\\s*("+nt+"[\\s\\*]*)+$"),Ne=new RegExp(nt,"g"),he={};function Qe(M){var m=he[M];if(m)return m;var d,c=[];if(!Ge.test(M))throw new g("Unit not recognized");for(;d=Ne.exec(M);)c.push(d.slice(1));return c=c.map(function(b){return P[b[0]]?[P[b[0]],B[b[1]]]:[B[b[1]]]}),c=c.reduce(function(b,S){return b.concat(S)},[]),c=c.filter(function(b){return b}),he[M]=c,c}function Ze(M){if(!t(M))throw new g("Argument should be a string");try{return this(M)}catch{return null}}function He(M){return M instanceof Te}function Te(M,m){if(lt.apply(null,arguments),!He(this))return new Te(M,m);if(this.scalar=null,this.baseScalar=null,this.signature=null,this._conversionCache={},this.numerator=$,this.denominator=$,ot(M)?(this.scalar=M.scalar,this.numerator=M.numerator&&M.numerator.length!==0?M.numerator:$,this.denominator=M.denominator&&M.denominator.length!==0?M.denominator:$):m?(Ve.call(this,m),this.scalar=M):Ve.call(this,M),this.denominator.join("*").indexOf("temp")>=0)throw new g("Cannot divide with temperatures");if(this.numerator.join("*").indexOf("temp")>=0){if(this.numerator.length>1)throw new g("Cannot multiply by temperatures");if(!h(this.denominator,$))throw new g("Cannot divide with temperatures")}if(this.initValue=M,Le.call(this),this.isTemperature()&&this.baseScalar<0)throw new g("Temperatures must not be less than absolute zero")}Te.prototype={constructor:Te};function lt(M,m){if(m){if(!(a(M)&&t(m)))throw new g("Only number accepted as initialization value when units are explicitly provided")}else if(!(t(M)||a(M)||He(M)||ot(M)))throw new g("Only string, number or quantity accepted as single initialization value")}function ot(M){return M&&typeof M=="object"&&M.hasOwnProperty("scalar")}function Le(){if(this.baseScalar)return this.baseScalar;if(this.isBase())this.baseScalar=this.scalar,this.signature=ne.call(this);else{var M=this.toBase();this.baseScalar=M.scalar,this.signature=M.signature}}var ze={"-312078":"elastance","-312058":"resistance","-312038":"inductance","-152058":"potential","-152040":"magnetism","-152038":"magnetism","-7997":"specific_volume","-79":"snap","-59":"jolt","-39":"acceleration","-38":"radiation","-20":"frequency","-19":"speed","-18":"viscosity","-17":"volumetric_flow","-1":"wavenumber",0:"unitless",1:"length",2:"area",3:"volume",20:"time",400:"temperature",7941:"yank",7942:"power",7959:"pressure",7961:"force",7962:"energy",7979:"viscosity",7981:"momentum",7982:"angular_momentum",7997:"density",7998:"area_density",8e3:"mass",152020:"radiation_exposure",159999:"magnetism",16e4:"current",160020:"charge",312058:"conductance",312078:"capacitance",3199980:"activity",3199997:"molar_concentration",32e5:"substance",63999998:"illuminance",64e6:"luminous_power",128e7:"currency","25599999980":"information_rate","25600000000":"information","511999999980":"angular_velocity","512000000000":"angle"};function je(){return o(Object.keys(ze).map(function(M){return ze[M]}))}Te.prototype.kind=function(){return ze[this.signature.toString()]},f(Te.prototype,{isDegrees:function(){return(this.signature===null||this.signature===400)&&this.numerator.length===1&&h(this.denominator,$)&&(this.numerator[0].match(/<temp-[CFRK]>/)||this.numerator[0].match(/<(kelvin|celsius|rankine|fahrenheit)>/))},isTemperature:function(){return this.isDegrees()&&this.numerator[0].match(/<temp-[CFRK]>/)}});function Oe(M,m){var d=M.units(),c=m.to(d),b=Te(ue(d));return Te({scalar:M.scalar-c.scalar,numerator:b.numerator,denominator:b.denominator})}function st(M,m){var d=m.to(ue(M.units()));return Te({scalar:M.scalar-d.scalar,numerator:M.numerator,denominator:M.denominator})}function Z(M,m){var d=m.to(ue(M.units()));return Te({scalar:M.scalar+d.scalar,numerator:M.numerator,denominator:M.denominator})}function ue(M){if(M==="tempK")return"degK";if(M==="tempC")return"degC";if(M==="tempF")return"degF";if(M==="tempR")return"degR";throw new g("Unknown type for temp conversion from: "+M)}function xe(M,m){var d=Ae(M),c=m.units(),b;if(c==="degK")b=d.scalar;else if(c==="degC")b=d.scalar;else if(c==="degF")b=d.scalar*9/5;else if(c==="degR")b=d.scalar*9/5;else throw new g("Unknown type for degree conversion to: "+c);return Te({scalar:b,numerator:m.numerator,denominator:m.denominator})}function Ae(M){var m=M.units(),d;if(m.match(/(deg)[CFRK]/))d=M.baseScalar;else if(m==="tempK")d=M.scalar;else if(m==="tempC")d=M.scalar;else if(m==="tempF")d=M.scalar*5/9;else if(m==="tempR")d=M.scalar*5/9;else throw new g("Unknown type for temp conversion from: "+m);return Te({scalar:d,numerator:["<kelvin>"],denominator:$})}function te(M,m){var d=m.units(),c;if(d==="tempK")c=M.baseScalar;else if(d==="tempC")c=M.baseScalar-273.15;else if(d==="tempF")c=M.baseScalar*9/5-459.67;else if(d==="tempR")c=M.baseScalar*9/5;else throw new g("Unknown type for temp conversion to: "+d);return Te({scalar:c,numerator:m.numerator,denominator:m.denominator})}function pe(M){var m=M.units(),d;if(m.match(/(deg)[CFRK]/))d=M.baseScalar;else if(m==="tempK")d=M.scalar;else if(m==="tempC")d=M.scalar+273.15;else if(m==="tempF")d=(M.scalar+459.67)*5/9;else if(m==="tempR")d=M.scalar*5/9;else throw new g("Unknown type for temp conversion from: "+m);return Te({scalar:d,numerator:["<temp-K>"],denominator:$})}f(Te.prototype,{to:function(M){var m,d;if(M==null)return this;if(!t(M))return this.to(M.units());if(m=this._conversionCache[M],m)return m;if(d=Te(M),d.units()===this.units())return this;if(!this.isCompatible(d))this.isInverse(d)?d=this.inverse().to(M):v(this.units(),d.units());else if(d.isTemperature())d=te(this,d);else if(d.isDegrees())d=xe(this,d);else{var c=u(this.baseScalar,d.baseScalar);d=Te({scalar:c,numerator:d.numerator,denominator:d.denominator})}return this._conversionCache[M]=d,d},toBase:function(){if(this.isBase())return this;if(this.isTemperature())return pe(this);var M=Ee[this.units()];return M||(M=it(this.numerator,this.denominator),Ee[this.units()]=M),M.mul(this.scalar)},toFloat:function(){if(this.isUnitless())return this.scalar;throw new g("Can't convert to Float unless unitless. Use Unit#scalar")},toPrec:function(M){if(t(M)&&(M=Te(M)),a(M)&&(M=Te(M+" "+this.units())),this.isUnitless()?M.isUnitless()||v(this.units(),M.units()):M=M.to(this.units()),M.scalar===0)throw new g("Divide by zero");var m=l(Math.round(this.scalar/M.scalar),M.scalar);return Te(m+this.units())}});function U(M,m){var d=Te(M),c=Te(m);if(d.eq(c))return s;var b;return d.isTemperature()?b=function(S){return d.mul(S).to(c).scalar}:b=function(S){return S*d.baseScalar/c.baseScalar},function(O){var q,X,j;if(Array.isArray(O)){for(X=O.length,j=[],q=0;q<X;q++)j.push(b(O[q]));return j}else return b(O)}}var Ee={};function it(M,m){for(var d=[],c=[],b=1,S,O=0;O<M.length;O++)S=M[O],C[S]?b=l(b,C[S]):z[S]&&(b*=z[S].scalar,z[S].numerator&&d.push(z[S].numerator),z[S].denominator&&c.push(z[S].denominator));for(var q=0;q<m.length;q++)S=m[q],C[S]?b/=C[S]:z[S]&&(b/=z[S].scalar,z[S].numerator&&c.push(z[S].numerator),z[S].denominator&&d.push(z[S].denominator));return d=d.reduce(function(X,j){return X.concat(j)},[]),c=c.reduce(function(X,j){return X.concat(j)},[]),Te({scalar:b,numerator:d,denominator:c})}Te.parse=Ze,Te.getUnits=J,Te.getAliases=Q,Te.mulSafe=l,Te.divSafe=u,Te.getKinds=je,Te.swiftConverter=U,Te.Error=g,f(Te.prototype,{add:function(M){if(t(M)&&(M=Te(M)),this.isCompatible(M)||v(this.units(),M.units()),this.isTemperature()&&M.isTemperature())throw new g("Cannot add two temperatures");return this.isTemperature()?Z(this,M):M.isTemperature()?Z(M,this):Te({scalar:this.scalar+M.to(this).scalar,numerator:this.numerator,denominator:this.denominator})},sub:function(M){if(t(M)&&(M=Te(M)),this.isCompatible(M)||v(this.units(),M.units()),this.isTemperature()&&M.isTemperature())return Oe(this,M);if(this.isTemperature())return st(this,M);if(M.isTemperature())throw new g("Cannot subtract a temperature from a differential degree unit");return Te({scalar:this.scalar-M.to(this).scalar,numerator:this.numerator,denominator:this.denominator})},mul:function(M){if(a(M))return Te({scalar:l(this.scalar,M),numerator:this.numerator,denominator:this.denominator});if(t(M)&&(M=Te(M)),(this.isTemperature()||M.isTemperature())&&!(this.isUnitless()||M.isUnitless()))throw new g("Cannot multiply by temperatures");var m=this,d=M;m.isCompatible(d)&&m.signature!==400&&(d=d.to(m));var c=I(m.numerator,m.denominator,d.numerator,d.denominator);return Te({scalar:l(m.scalar,d.scalar,c[2]),numerator:c[0],denominator:c[1]})},div:function(M){if(a(M)){if(M===0)throw new g("Divide by zero");return Te({scalar:this.scalar/M,numerator:this.numerator,denominator:this.denominator})}else t(M)&&(M=Te(M));if(M.scalar===0)throw new g("Divide by zero");if(M.isTemperature())throw new g("Cannot divide with temperatures");if(this.isTemperature()&&!M.isUnitless())throw new g("Cannot divide with temperatures");var m=this,d=M;m.isCompatible(d)&&m.signature!==400&&(d=d.to(m));var c=I(m.numerator,m.denominator,d.denominator,d.numerator);return Te({scalar:l(m.scalar,c[2])/d.scalar,numerator:c[0],denominator:c[1]})},inverse:function(){if(this.isTemperature())throw new g("Cannot divide with temperatures");if(this.scalar===0)throw new g("Divide by zero");return Te({scalar:1/this.scalar,numerator:this.denominator,denominator:this.numerator})}});function I(M,m,d,c){function b(be){return be!==T}M=M.filter(b),d=d.filter(b),m=m.filter(b),c=c.filter(b);var S={};function O(be,le){for(var ge,Ue,ie,$e=0;$e<be.length;$e++)if(C[be[$e]]?(ge=be[$e+1],Ue=be[$e],ie=C[Ue],$e++):(ge=be[$e],Ue=null,ie=1),ge&&ge!==T)if(S[ge]){S[ge][0]+=le;var Xe=S[ge][2]?C[S[ge][2]]:1;S[ge][le===1?3:4]*=u(ie,Xe)}else S[ge]=[le,ge,Ue,1,1]}O(M,1),O(m,-1),O(d,1),O(c,-1);var q=[],X=[],j=1;for(var ae in S)if(S.hasOwnProperty(ae)){var K=S[ae],ce;if(K[0]>0)for(ce=0;ce<K[0];ce++)q.push(K[2]===null?K[1]:[K[2],K[1]]);else if(K[0]<0)for(ce=0;ce<-K[0];ce++)X.push(K[2]===null?K[1]:[K[2],K[1]]);j*=u(K[3],K[4])}return q.length===0&&(q=$),X.length===0&&(X=$),q=q.reduce(function(be,le){return be.concat(le)},[]),X=X.reduce(function(be,le){return be.concat(le)},[]),[q,X,j]}f(Te.prototype,{eq:function(M){return this.compareTo(M)===0},lt:function(M){return this.compareTo(M)===-1},lte:function(M){return this.eq(M)||this.lt(M)},gt:function(M){return this.compareTo(M)===1},gte:function(M){return this.eq(M)||this.gt(M)},compareTo:function(M){if(t(M))return this.compareTo(Te(M));if(this.isCompatible(M)||v(this.units(),M.units()),this.baseScalar<M.baseScalar)return-1;if(this.baseScalar===M.baseScalar)return 0;if(this.baseScalar>M.baseScalar)return 1},same:function(M){return this.scalar===M.scalar&&this.units()===M.units()}}),f(Te.prototype,{isUnitless:function(){return[this.numerator,this.denominator].every(function(M){return h(M,$)})},isCompatible:function(M){return t(M)?this.isCompatible(Te(M)):He(M)&&M.signature!==void 0?this.signature===M.signature:!1},isInverse:function(M){return this.inverse().isCompatible(M)},isBase:function(){return this._isBase!==void 0?this._isBase:this.isDegrees()&&this.numerator[0].match(/<(kelvin|temp-K)>/)?(this._isBase=!0,this._isBase):(this.numerator.concat(this.denominator).forEach(function(M){M!==T&&A.indexOf(M)===-1&&(this._isBase=!1)},this),this._isBase===!1?this._isBase:(this._isBase=!0,this._isBase))}});function fe(){}fe.prototype.get=function(M){return arguments.length>1&&(M=Array.apply(null,arguments)),M.reduce(function(m,d,c){if(m){var b=m[d];return c===M.length-1?b?b.data:void 0:b}},this)},fe.prototype.set=function(M,m){return arguments.length>2&&(M=Array.prototype.slice.call(arguments,0,-1),m=arguments[arguments.length-1]),M.reduce(function(d,c,b){var S=d[c];return S===void 0&&(S=d[c]={}),b===M.length-1?(S.data=m,m):S},this)};function de(M,m){return(M+" "+m).trim()}Te.formatter=de,f(Te.prototype,{units:function(){if(this._units!==void 0)return this._units;var M=h(this.numerator,$),m=h(this.denominator,$);if(M&&m)return this._units="",this._units;var d=ee(this.numerator),c=ee(this.denominator);return this._units=d+(m?"":"/"+c),this._units},toString:function(M,m){var d;if(a(M))d=this.units(),m=M;else if(t(M))d=M;else if(He(M))return this.toPrec(M).toString(m);var c=this.to(d),b=m!==void 0?w(c.scalar,m):c.scalar;return c=(b+" "+c.units()).trim(),c},format:function(M,m){arguments.length===1&&typeof M=="function"&&(m=M,M=void 0),m=m||Te.formatter;var d=this.to(M);return m.call(this,d.scalar,d.units())}});var H=new fe;function ee(M){var m=H.get(M);if(m)return m;var d=h(M,$);return d?m="1":m=We(oe(M)).join("*"),H.set(M,m),m}function oe(M){for(var m=[],d,c,b=0;b<M.length;b++)d=M[b],c=M[b+1],C[d]?(m.push(F[d]+F[c]),b++):m.push(F[d]);return m}function We(M){var m=M.reduce(function(d,c){var b=d[c];return b||d.push(b=d[c]=[c,0]),b[1]++,d},[]);return m.map(function(d){return d[0]+(d[1]>1?d[1]:"")})}return Te.version="1.8.0",Te})}(quantities$1)),quantities$1.exports}var quantitiesExports=requireQuantities();const Qty=getDefaultExportFromCjs(quantitiesExports);function deepValue(e,i=""){let t=i.split(".");for(let n of t){if(e[n]===void 0)return;e=e[n]}return e}var orientation={exports:{}},twoProduct_1,hasRequiredTwoProduct;function requireTwoProduct(){if(hasRequiredTwoProduct)return twoProduct_1;hasRequiredTwoProduct=1,twoProduct_1=i;var e=+(Math.pow(2,27)+1);function i(t,n,a){var s=t*n,o=e*t,h=o-t,f=o-h,l=t-f,u=e*n,w=u-n,_=u-w,g=n-_,v=s-f*_,k=v-l*_,A=k-f*g,T=l*g-A;return a?(a[0]=T,a[1]=s,a):[T,s]}return twoProduct_1}var robustSum,hasRequiredRobustSum;function requireRobustSum(){if(hasRequiredRobustSum)return robustSum;hasRequiredRobustSum=1,robustSum=i;function e(t,n){var a=t+n,s=a-t,o=a-s,h=n-s,f=t-o,l=f+h;return l?[l,a]:[a]}function i(t,n){var a=t.length|0,s=n.length|0;if(a===1&&s===1)return e(t[0],n[0]);var o=a+s,h=new Array(o),f=0,l=0,u=0,w=Math.abs,_=t[l],g=w(_),v=n[u],k=w(v),A,T;g<k?(T=_,l+=1,l<a&&(_=t[l],g=w(_))):(T=v,u+=1,u<s&&(v=n[u],k=w(v))),l<a&&g<k||u>=s?(A=_,l+=1,l<a&&(_=t[l],g=w(_))):(A=v,u+=1,u<s&&(v=n[u],k=w(v)));for(var $=A+T,D=$-A,C=T-D,P=C,z=$,B,F,L,N,G;l<a&&u<s;)g<k?(A=_,l+=1,l<a&&(_=t[l],g=w(_))):(A=v,u+=1,u<s&&(v=n[u],k=w(v))),T=P,$=A+T,D=$-A,C=T-D,C&&(h[f++]=C),B=z+$,F=B-z,L=B-F,N=$-F,G=z-L,P=G+N,z=B;for(;l<a;)A=_,T=P,$=A+T,D=$-A,C=T-D,C&&(h[f++]=C),B=z+$,F=B-z,L=B-F,N=$-F,G=z-L,P=G+N,z=B,l+=1,l<a&&(_=t[l]);for(;u<s;)A=v,T=P,$=A+T,D=$-A,C=T-D,C&&(h[f++]=C),B=z+$,F=B-z,L=B-F,N=$-F,G=z-L,P=G+N,z=B,u+=1,u<s&&(v=n[u]);return P&&(h[f++]=P),z&&(h[f++]=z),f||(h[f++]=0),h.length=f,h}return robustSum}var twoSum,hasRequiredTwoSum;function requireTwoSum(){if(hasRequiredTwoSum)return twoSum;hasRequiredTwoSum=1,twoSum=e;function e(i,t,n){var a=i+t,s=a-i,o=a-s,h=t-s,f=i-o;return n?(n[0]=f+h,n[1]=a,n):[f+h,a]}return twoSum}var robustScale,hasRequiredRobustScale;function requireRobustScale(){if(hasRequiredRobustScale)return robustScale;hasRequiredRobustScale=1;var e=requireTwoProduct(),i=requireTwoSum();robustScale=t;function t(n,a){var s=n.length;if(s===1){var o=e(n[0],a);return o[0]?o:[o[1]]}var h=new Array(2*s),f=[.1,.1],l=[.1,.1],u=0;e(n[0],a,f),f[0]&&(h[u++]=f[0]);for(var w=1;w<s;++w){e(n[w],a,l);var _=f[1];i(_,l[0],f),f[0]&&(h[u++]=f[0]);var g=l[1],v=f[1],k=g+v,A=k-g,T=v-A;f[1]=k,T&&(h[u++]=T)}return f[1]&&(h[u++]=f[1]),u===0&&(h[u++]=0),h.length=u,h}return robustScale}var robustDiff,hasRequiredRobustDiff;function requireRobustDiff(){if(hasRequiredRobustDiff)return robustDiff;hasRequiredRobustDiff=1,robustDiff=i;function e(t,n){var a=t+n,s=a-t,o=a-s,h=n-s,f=t-o,l=f+h;return l?[l,a]:[a]}function i(t,n){var a=t.length|0,s=n.length|0;if(a===1&&s===1)return e(t[0],-n[0]);var o=a+s,h=new Array(o),f=0,l=0,u=0,w=Math.abs,_=t[l],g=w(_),v=-n[u],k=w(v),A,T;g<k?(T=_,l+=1,l<a&&(_=t[l],g=w(_))):(T=v,u+=1,u<s&&(v=-n[u],k=w(v))),l<a&&g<k||u>=s?(A=_,l+=1,l<a&&(_=t[l],g=w(_))):(A=v,u+=1,u<s&&(v=-n[u],k=w(v)));for(var $=A+T,D=$-A,C=T-D,P=C,z=$,B,F,L,N,G;l<a&&u<s;)g<k?(A=_,l+=1,l<a&&(_=t[l],g=w(_))):(A=v,u+=1,u<s&&(v=-n[u],k=w(v))),T=P,$=A+T,D=$-A,C=T-D,C&&(h[f++]=C),B=z+$,F=B-z,L=B-F,N=$-F,G=z-L,P=G+N,z=B;for(;l<a;)A=_,T=P,$=A+T,D=$-A,C=T-D,C&&(h[f++]=C),B=z+$,F=B-z,L=B-F,N=$-F,G=z-L,P=G+N,z=B,l+=1,l<a&&(_=t[l]);for(;u<s;)A=v,T=P,$=A+T,D=$-A,C=T-D,C&&(h[f++]=C),B=z+$,F=B-z,L=B-F,N=$-F,G=z-L,P=G+N,z=B,u+=1,u<s&&(v=-n[u]);return P&&(h[f++]=P),z&&(h[f++]=z),f||(h[f++]=0),h.length=f,h}return robustDiff}var hasRequiredOrientation;function requireOrientation(){return hasRequiredOrientation||(hasRequiredOrientation=1,function(e){var i=requireTwoProduct(),t=requireRobustSum(),n=requireRobustScale(),a=requireRobustDiff(),s=5,o=11102230246251565e-32,h=(3+16*o)*o,f=(7+56*o)*o;function l(D,C,P,z){return function(F,L,N){var G=D(D(C(L[1],N[0]),C(-N[1],L[0])),D(C(F[1],L[0]),C(-L[1],F[0]))),V=D(C(F[1],N[0]),C(-N[1],F[0])),J=z(G,V);return J[J.length-1]}}function u(D,C,P,z){return function(F,L,N,G){var V=D(D(P(D(C(N[1],G[0]),C(-G[1],N[0])),L[2]),D(P(D(C(L[1],G[0]),C(-G[1],L[0])),-N[2]),P(D(C(L[1],N[0]),C(-N[1],L[0])),G[2]))),D(P(D(C(L[1],G[0]),C(-G[1],L[0])),F[2]),D(P(D(C(F[1],G[0]),C(-G[1],F[0])),-L[2]),P(D(C(F[1],L[0]),C(-L[1],F[0])),G[2])))),J=D(D(P(D(C(N[1],G[0]),C(-G[1],N[0])),F[2]),D(P(D(C(F[1],G[0]),C(-G[1],F[0])),-N[2]),P(D(C(F[1],N[0]),C(-N[1],F[0])),G[2]))),D(P(D(C(L[1],N[0]),C(-N[1],L[0])),F[2]),D(P(D(C(F[1],N[0]),C(-N[1],F[0])),-L[2]),P(D(C(F[1],L[0]),C(-L[1],F[0])),N[2])))),Q=z(V,J);return Q[Q.length-1]}}function w(D,C,P,z){return function(F,L,N,G,V){var J=D(D(D(P(D(P(D(C(G[1],V[0]),C(-V[1],G[0])),N[2]),D(P(D(C(N[1],V[0]),C(-V[1],N[0])),-G[2]),P(D(C(N[1],G[0]),C(-G[1],N[0])),V[2]))),L[3]),D(P(D(P(D(C(G[1],V[0]),C(-V[1],G[0])),L[2]),D(P(D(C(L[1],V[0]),C(-V[1],L[0])),-G[2]),P(D(C(L[1],G[0]),C(-G[1],L[0])),V[2]))),-N[3]),P(D(P(D(C(N[1],V[0]),C(-V[1],N[0])),L[2]),D(P(D(C(L[1],V[0]),C(-V[1],L[0])),-N[2]),P(D(C(L[1],N[0]),C(-N[1],L[0])),V[2]))),G[3]))),D(P(D(P(D(C(N[1],G[0]),C(-G[1],N[0])),L[2]),D(P(D(C(L[1],G[0]),C(-G[1],L[0])),-N[2]),P(D(C(L[1],N[0]),C(-N[1],L[0])),G[2]))),-V[3]),D(P(D(P(D(C(G[1],V[0]),C(-V[1],G[0])),L[2]),D(P(D(C(L[1],V[0]),C(-V[1],L[0])),-G[2]),P(D(C(L[1],G[0]),C(-G[1],L[0])),V[2]))),F[3]),P(D(P(D(C(G[1],V[0]),C(-V[1],G[0])),F[2]),D(P(D(C(F[1],V[0]),C(-V[1],F[0])),-G[2]),P(D(C(F[1],G[0]),C(-G[1],F[0])),V[2]))),-L[3])))),D(D(P(D(P(D(C(L[1],V[0]),C(-V[1],L[0])),F[2]),D(P(D(C(F[1],V[0]),C(-V[1],F[0])),-L[2]),P(D(C(F[1],L[0]),C(-L[1],F[0])),V[2]))),G[3]),D(P(D(P(D(C(L[1],G[0]),C(-G[1],L[0])),F[2]),D(P(D(C(F[1],G[0]),C(-G[1],F[0])),-L[2]),P(D(C(F[1],L[0]),C(-L[1],F[0])),G[2]))),-V[3]),P(D(P(D(C(N[1],G[0]),C(-G[1],N[0])),L[2]),D(P(D(C(L[1],G[0]),C(-G[1],L[0])),-N[2]),P(D(C(L[1],N[0]),C(-N[1],L[0])),G[2]))),F[3]))),D(P(D(P(D(C(N[1],G[0]),C(-G[1],N[0])),F[2]),D(P(D(C(F[1],G[0]),C(-G[1],F[0])),-N[2]),P(D(C(F[1],N[0]),C(-N[1],F[0])),G[2]))),-L[3]),D(P(D(P(D(C(L[1],G[0]),C(-G[1],L[0])),F[2]),D(P(D(C(F[1],G[0]),C(-G[1],F[0])),-L[2]),P(D(C(F[1],L[0]),C(-L[1],F[0])),G[2]))),N[3]),P(D(P(D(C(L[1],N[0]),C(-N[1],L[0])),F[2]),D(P(D(C(F[1],N[0]),C(-N[1],F[0])),-L[2]),P(D(C(F[1],L[0]),C(-L[1],F[0])),N[2]))),-G[3]))))),Q=D(D(D(P(D(P(D(C(G[1],V[0]),C(-V[1],G[0])),N[2]),D(P(D(C(N[1],V[0]),C(-V[1],N[0])),-G[2]),P(D(C(N[1],G[0]),C(-G[1],N[0])),V[2]))),F[3]),P(D(P(D(C(G[1],V[0]),C(-V[1],G[0])),F[2]),D(P(D(C(F[1],V[0]),C(-V[1],F[0])),-G[2]),P(D(C(F[1],G[0]),C(-G[1],F[0])),V[2]))),-N[3])),D(P(D(P(D(C(N[1],V[0]),C(-V[1],N[0])),F[2]),D(P(D(C(F[1],V[0]),C(-V[1],F[0])),-N[2]),P(D(C(F[1],N[0]),C(-N[1],F[0])),V[2]))),G[3]),P(D(P(D(C(N[1],G[0]),C(-G[1],N[0])),F[2]),D(P(D(C(F[1],G[0]),C(-G[1],F[0])),-N[2]),P(D(C(F[1],N[0]),C(-N[1],F[0])),G[2]))),-V[3]))),D(D(P(D(P(D(C(N[1],V[0]),C(-V[1],N[0])),L[2]),D(P(D(C(L[1],V[0]),C(-V[1],L[0])),-N[2]),P(D(C(L[1],N[0]),C(-N[1],L[0])),V[2]))),F[3]),P(D(P(D(C(N[1],V[0]),C(-V[1],N[0])),F[2]),D(P(D(C(F[1],V[0]),C(-V[1],F[0])),-N[2]),P(D(C(F[1],N[0]),C(-N[1],F[0])),V[2]))),-L[3])),D(P(D(P(D(C(L[1],V[0]),C(-V[1],L[0])),F[2]),D(P(D(C(F[1],V[0]),C(-V[1],F[0])),-L[2]),P(D(C(F[1],L[0]),C(-L[1],F[0])),V[2]))),N[3]),P(D(P(D(C(L[1],N[0]),C(-N[1],L[0])),F[2]),D(P(D(C(F[1],N[0]),C(-N[1],F[0])),-L[2]),P(D(C(F[1],L[0]),C(-L[1],F[0])),N[2]))),-V[3])))),W=z(J,Q);return W[W.length-1]}}function _(D){var C=D===3?l:D===4?u:w;return C(t,i,n,a)}var g=_(3),v=_(4),k=[function(){return 0},function(){return 0},function(C,P){return P[0]-C[0]},function(C,P,z){var B=(C[1]-z[1])*(P[0]-z[0]),F=(C[0]-z[0])*(P[1]-z[1]),L=B-F,N;if(B>0){if(F<=0)return L;N=B+F}else if(B<0){if(F>=0)return L;N=-(B+F)}else return L;var G=h*N;return L>=G||L<=-G?L:g(C,P,z)},function(C,P,z,B){var F=C[0]-B[0],L=P[0]-B[0],N=z[0]-B[0],G=C[1]-B[1],V=P[1]-B[1],J=z[1]-B[1],Q=C[2]-B[2],W=P[2]-B[2],ne=z[2]-B[2],me=L*J,ve=N*V,ye=N*G,Me=F*J,Re=F*V,_e=L*G,Be=Q*(me-ve)+W*(ye-Me)+ne*(Re-_e),Se=(Math.abs(me)+Math.abs(ve))*Math.abs(Q)+(Math.abs(ye)+Math.abs(Me))*Math.abs(W)+(Math.abs(Re)+Math.abs(_e))*Math.abs(ne),re=f*Se;return Be>re||-Be>re?Be:v(C,P,z,B)}];function A(D){var C=k[D.length];return C||(C=k[D.length]=_(D.length)),C.apply(void 0,D)}function T(D,C,P,z,B,F,L){return function(G,V,J,Q,W){switch(arguments.length){case 0:case 1:return 0;case 2:return z(G,V);case 3:return B(G,V,J);case 4:return F(G,V,J,Q);case 5:return L(G,V,J,Q,W)}for(var ne=new Array(arguments.length),me=0;me<arguments.length;++me)ne[me]=arguments[me];return D(ne)}}function $(){for(;k.length<=s;)k.push(_(k.length));e.exports=T.apply(void 0,[A].concat(k));for(var D=0;D<=s;++D)e.exports[D]=k[D]}$()}(orientation)),orientation.exports}var robustPnp,hasRequiredRobustPnp;function requireRobustPnp(){if(hasRequiredRobustPnp)return robustPnp;hasRequiredRobustPnp=1,robustPnp=i;var e=requireOrientation();function i(t,n){for(var a=n[0],s=n[1],o=t.length,h=1,f=o,l=0,u=o-1;l<f;u=l++){var w=t[l],_=t[u],g=w[1],v=_[1];if(v<g){if(v<s&&s<g){var k=e(w,_,n);if(k===0)return 0;h^=0<k|0}else if(s===g){var A=t[(l+1)%o],T=A[1];if(g<T){var k=e(w,_,n);if(k===0)return 0;h^=0<k|0}}}else if(g<v){if(g<s&&s<v){var k=e(w,_,n);if(k===0)return 0;h^=k<0|0}else if(s===g){var A=t[(l+1)%o],T=A[1];if(T<g){var k=e(w,_,n);if(k===0)return 0;h^=k<0|0}}}else if(s===g){var $=Math.min(w[0],_[0]),D=Math.max(w[0],_[0]);if(l===0){for(;u>0;){var C=(u+o-1)%o,P=t[C];if(P[1]!==s)break;var z=P[0];$=Math.min($,z),D=Math.max(D,z),u=C}if(u===0)return $<=a&&a<=D?0:1;f=u+1}for(var B=t[(u+o-1)%o][1];l+1<f;){var P=t[l+1];if(P[1]!==s)break;var z=P[0];$=Math.min($,z),D=Math.max(D,z),l+=1}if($<=a&&a<=D)return 0;var F=t[(l+1)%o][1];a<$&&B<s!=F<s&&(h^=1)}}return 2*h-1}return robustPnp}var robustPnpExports=requireRobustPnp();const robustPointInPolygon=getDefaultExportFromCjs(robustPnpExports);function feretDiameters(e={}){const{originalPoints:i=monotoneChainConvexHull.call(this)}=e;if(i.length===0)return{min:0,max:0,minLine:[],maxLine:[],aspectRatio:1};if(i.length===1)return{min:1,max:1,minLine:[i[0],i[0]],maxLine:[i[0],i[0]],aspectRatio:1};const t=new Array(i.length);let n=1/0,a=0,s=[];for(let l=0;l<i.length;l++){let u=getAngle(i[l],i[(l+1)%i.length]);rotate(-u,i,t);let w=0,_=[];for(let g=0;g<i.length;g++){let v=Math.abs(t[l][1]-t[g][1]);v>w&&(w=v,_=[],_.push([t[g][0],t[l][1]],[t[g][0],t[g][1]]))}w<n&&(n=w,a=u,s=_)}rotate(a,s,s);let o=0,h=[],f=0;for(let l=0;l<i.length-1;l++)for(let u=l+1;u<i.length;u++){let w=(i[l][0]-i[u][0])**2+(i[l][1]-i[u][1])**2;w>f&&(f=w,o=Math.sqrt(w),h=[i[l],i[u]])}return{min:n,minLine:s,max:o,maxLine:h,aspectRatio:n/o}}function getAngle(e,i){let t=difference(i,e),n=normalize(t),a=Math.acos(n[0]);return n[1]<0?-a:a}class Roi{constructor(i,t){this.map=i,this.id=t,this.minX=Number.POSITIVE_INFINITY,this.maxX=Number.NEGATIVE_INFINITY,this.minY=Number.POSITIVE_INFINITY,this.maxY=Number.NEGATIVE_INFINITY,this.meanX=0,this.meanY=0,this.surface=0,this.computed={}}getMask(i={}){const{scale:t=1,kind:n=""}=i;let a;switch(n){case"contour":a=this.contourMask;break;case"box":a=this.boxMask;break;case"filled":a=this.filledMask;break;case"center":a=this.centerMask;break;case"mbr":a=this.mbrFilledMask;break;case"hull":a=this.convexHullFilledMask;break;case"hullContour":a=this.convexHullMask;break;case"mbrContour":a=this.mbrMask;break;case"feret":a=this.feretMask;break;default:a=this.mask}return t<1&&(a=a.resize({factor:t}),a.parent=this.mask.parent,a.position[0]+=this.minX,a.position[1]+=this.minY),a}get mean(){throw new Error("Roi mean not implemented yet")}get center(){return this.computed.center||(this.computed.center=[this.width/2>>0,this.height/2>>0]),this.computed.center}get ratio(){return this.width/this.height}get width(){return this.maxX-this.minX+1}get height(){return this.maxY-this.minY+1}_computExternalIDs(){let i=this.borderIDs,t=this.borderLengths;this.computed.externalIDs=[],this.computed.externalLengths=[];let n=this.internalIDs;for(let a=0;a<i.length;a++)n.includes(i[a])||(this.computed.externalIDs.push(i[a]),this.computed.externalLengths.push(t[a]))}get externalIDs(){return this.computed.externalIDs?this.computed.externalIDs:(this._computExternalIDs(),this.computed.externalIDs)}get externalLengths(){return this.computed.externalLengths?this.computed.externalLengths:(this._computExternalIDs(),this.computed.externalLengths)}_computeBorderIDs(){let i=getBorders(this);this.computed.borderIDs=i.ids,this.computed.borderLengths=i.lengths}get borderIDs(){return this.computed.borderIDs?this.computed.borderIDs:(this._computeBorderIDs(),this.computed.borderIDs)}get borderLengths(){return this.computed.borderLengths?this.computed.borderLengths:(this._computeBorderIDs(),this.computed.borderLengths)}get boxIDs(){return this.computed.boxIDs||(this.computed.boxIDs=getBoxIDs(this)),this.computed.boxIDs}get internalIDs(){return this.computed.internalIDs||(this.computed.internalIDs=getInternalIDs(this)),this.computed.internalIDs}get box(){return this.computed.box||(this.computed.box=getBox(this)),this.computed.box}get external(){return this.computed.external||(this.computed.external=getExternal(this)),this.computed.external}get holesInfo(){return this.computed.holesInfo||(this.computed.holesInfo=getHolesInfo(this)),this.computed.holesInfo}get border(){return this.computed.border||(this.computed.border=getBorder(this)),this.computed.border}get contourMask(){if(!this.computed.contourMask){let i=new Image(this.width,this.height,{kind:BINARY,position:[this.minX,this.minY],parent:this.map.parent});for(let t=0;t<this.width;t++)for(let n=0;n<this.height;n++)this.map.data[t+this.minX+(n+this.minY)*this.map.width]===this.id&&(t>0&&t<this.width-1&&n>0&&n<this.height-1?(this.map.data[t-1+this.minX+(n+this.minY)*this.map.width]!==this.id||this.map.data[t+1+this.minX+(n+this.minY)*this.map.width]!==this.id||this.map.data[t+this.minX+(n-1+this.minY)*this.map.width]!==this.id||this.map.data[t+this.minX+(n+1+this.minY)*this.map.width]!==this.id)&&i.setBitXY(t,n):i.setBitXY(t,n));this.computed.contourMask=i}return this.computed.contourMask}get boxMask(){if(!this.computed.boxMask){let i=new Image(this.width,this.height,{kind:BINARY,position:[this.minX,this.minY],parent:this.map.parent});for(let t=0;t<this.width;t++)i.setBitXY(t,0),i.setBitXY(t,this.height-1);for(let t=0;t<this.height;t++)i.setBitXY(0,t),i.setBitXY(this.width-1,t);this.computed.boxMask=i}return this.computed.boxMask}get mask(){if(!this.computed.mask){let i=new Image(this.width,this.height,{kind:BINARY,position:[this.minX,this.minY],parent:this.map.parent});for(let t=0;t<this.width;t++)for(let n=0;n<this.height;n++)this.map.data[t+this.minX+(n+this.minY)*this.map.width]===this.id&&i.setBitXY(t,n);this.computed.mask=i}return this.computed.mask}get filledMask(){if(!this.computed.filledMask){let i=new Image(this.width,this.height,{kind:BINARY,position:[this.minX,this.minY],parent:this.map.parent});for(let t=0;t<this.width;t++)for(let n=0;n<this.height;n++){let a=t+this.minX+(n+this.minY)*this.map.width;this.internalIDs.includes(this.map.data[a])&&i.setBitXY(t,n)}this.computed.filledMask=i}return this.computed.filledMask}get centerMask(){if(!this.computed.centerMask){let i=new Shape({kind:"smallCross"}).getMask();i.parent=this.map.parent,i.position=[this.minX+this.center[0]-1,this.minY+this.center[1]-1],this.computed.centerMask=i}return this.computed.centerMask}get convexHull(){if(!this.computed.convexHull){const i=[];for(let n=0;n<this.width;n++)for(let a=0;a<this.height;a++)this.map.data[n+this.minX+(a+this.minY)*this.map.width]===this.id&&(n>0&&n<this.width-1&&a>0&&a<this.height-1?(this.map.data[n-1+this.minX+(a+this.minY)*this.map.width]!==this.id||this.map.data[n+1+this.minX+(a+this.minY)*this.map.width]!==this.id||this.map.data[n+this.minX+(a-1+this.minY)*this.map.width]!==this.id||this.map.data[n+this.minX+(a+1+this.minY)*this.map.width]!==this.id)&&(i.push([n,a]),i.push([n+1,a]),i.push([n,a+1]),i.push([n+1,a+1])):(i.push([n,a]),i.push([n+1,a]),i.push([n,a+1]),i.push([n+1,a+1])));const t=monotoneChainConvexHull$1(i);this.computed.convexHull={polyline:t,surface:surface(t),perimeter:perimeter(t)}}return this.computed.convexHull}get convexHullMask(){if(!this.computed.convexHullMask){const i=this.convexHull,t=new Image(this.width+1,this.height+1,{kind:BINARY,position:[this.minX,this.minY],parent:this.map.parent});t.paintPolyline(i.polyline,{closed:!0}),this.computed.convexHullMask=t}return this.computed.convexHullMask}get convexHullFilledMask(){if(!this.computed.convexHullFilledMask){const i=this.convexHull,t=new Image(this.width,this.height,{kind:BINARY,position:[this.minX,this.minY],parent:this.map.parent});for(let n=0;n<this.width;n++)for(let a=0;a<this.height;a++)robustPointInPolygon(i.polyline,[n,a])!==1&&t.setBitXY(n,a);this.computed.convexHullFilledMask=t}return this.computed.convexHullFilledMask}get mbr(){if(!this.computed.mbr){let i=minimalBoundingRectangle({originalPoints:this.convexHull.polyline});if(i.length===0)this.computed.mbr={width:0,height:0,surface:0,perimeter:0,rectangle:i};else{let t=i[0],n=i[1],a=i[2],s=Math.sqrt((t[0]-n[0])**2+(t[1]-n[1])**2),o=Math.sqrt((a[0]-n[0])**2+(a[1]-n[1])**2);this.computed.mbr={width:s,height:o,elongation:1-s/o,aspectRatio:s/o,surface:s*o,perimeter:(s+o)*2,rectangle:i}}}return this.computed.mbr}get filledSurface(){return this.surface+this.holesInfo.surface}get fillRatio(){return this.surface/(this.surface+this.holesInfo.surface)}get feretDiameters(){return this.computed.feretDiameters||(this.computed.feretDiameters=feretDiameters({originalPoints:this.convexHull.polyline})),this.computed.feretDiameters}get eqpc(){return this.computed.eqpc||(this.computed.eqpc=2*Math.sqrt(this.surface/Math.PI)),this.computed.eqpc}get perimeterInfo(){return this.computed.perimeterInfo||(this.computed.perimeterInfo=getPerimeterInfo(this)),this.computed.perimeterInfo}get perimeter(){let i=this.perimeterInfo,t=2-Math.sqrt(2);return i.one+i.two*2+i.three*3+i.four*4-t*(i.two+i.three*2+i.four)}get ped(){return this.computed.ped||(this.computed.ped=this.perimeter/Math.PI),this.computed.ped}get feretMask(){if(!this.computed.feretMask){const i=new Image(this.width+1,this.height+1,{kind:BINARY,position:[this.minX,this.minY],parent:this.map.parent});i.paintPolyline(this.feretDiameters.minLine),i.paintPolyline(this.feretDiameters.maxLine),this.computed.feretMask=i}return this.computed.feretMask}get mbrMask(){if(!this.computed.mbrMask){let i=round(this.mbr.rectangle);if(i.length>0){const t=minMax(i),n=new Image(t[1][0]-t[0][0]+1,t[1][1]-t[0][1]+1,{kind:BINARY,position:[this.minX+t[0][0],this.minY+t[0][1]],parent:this.map.parent});i=moveToZeroZero(i),n.paintPolyline(i,{closed:!0}),this.computed.mbrMask=n}else this.computed.mbrMask=new Image(1,1,{kind:BINARY,position:[this.minX,this.minY],parent:this.map.parent})}return this.computed.mbrMask}get mbrFilledMask(){if(!this.computed.mbrFilledMask){const i=new Image(this.width,this.height,{kind:BINARY,position:[this.minX,this.minY],parent:this.map.parent}),t=this.mask.minimalBoundingRectangle();for(let n=0;n<this.width;n++)for(let a=0;a<this.height;a++)robustPointInPolygon(t,[n,a])!==1&&i.setBitXY(n,a);this.computed.mbrFilledMask=i}return this.computed.mbrFilledMask}get points(){if(!this.computed.points){let i=[];for(let t=0;t<this.height;t++)for(let n=0;n<this.width;n++){let a=(t+this.minY)*this.map.width+n+this.minX;this.map.data[a]===this.id&&i.push([n,t])}this.computed.points=i}return this.computed.points}get maxLengthPoints(){if(!this.computed.maxLengthPoints){let i=0,t;const n=this.points;for(let a=0;a<n.length;a++)for(let s=a+1;s<n.length;s++){let o=Math.pow(n[a][0]-n[s][0],2)+Math.pow(n[a][1]-n[s][1],2);o>=i&&(i=o,t=[n[a],n[s]])}this.computed.maxLengthPoints=t}return this.computed.maxLengthPoints}get maxLength(){if(!this.computed.maxLength){let i=Math.sqrt(Math.pow(this.maxLengthPoints[0][0]-this.maxLengthPoints[1][0],2)+Math.pow(this.maxLengthPoints[0][1]-this.maxLengthPoints[1][1],2));this.computed.maxLength=i}return this.computed.maxLength}get roundness(){return 4*this.surface/(Math.PI*this.feretDiameters.max**2)}get sphericity(){return 2*Math.sqrt(this.surface*Math.PI)/this.perimeter}get solidity(){return this.surface/this.convexHull.surface}get angle(){if(!this.computed.angle){let i=this.maxLengthPoints,t=-Math.atan2(i[0][1]-i[1][1],i[0][0]-i[1][0])*180/Math.PI;this.computed.angle=t}return this.computed.angle}toJSON(){return{id:this.id,minX:this.minX,maxX:this.maxX,minY:this.minY,maxY:this.maxY,meanX:this.meanX,meanY:this.meanY,height:this.height,width:this.width,filledSurface:this.filledSurface,surface:this.surface,hullSurface:this.convexHull.surface,hullPerimeter:this.convexHull.perimeter,mbrWidth:this.mbr.width,mbrHeight:this.mbr.height,mbrSurface:this.mbr.surface,eqpc:this.eqpc,ped:this.ped,feretDiameterMin:this.feretDiameters.min,feretDiameterMax:this.feretDiameters.max,aspectRatio:this.feretDiameters.aspectRatio,fillRatio:this.fillRatio,sphericity:this.sphericity,roundness:this.roundness,solidity:this.solidity,perimeter:this.perimeter}}}function getBorders(e){let i=e.map,t=i.data,n=new Set,a=new Map,s=new Set,o=[1,0,-1,0],h=[0,1,0,-1];for(let u=e.minX;u<=e.maxX;u++)for(let w=e.minY;w<=e.maxY;w++){let _=u+w*i.width;if(t[_]===e.id)for(let g=0;g<4;g++){let v=u+o[g],k=w+h[g];if(v>=0&&k>=0&&v<i.width&&k<i.height){let A=v+k*i.width;if(t[A]!==e.id&&!s.has(A)){s.add(A),n.add(t[A]);let T=a.get(t[A]);T?a.set(t[A],++T):a.set(t[A],1)}}}}let f=Array.from(n),l=f.map(function(u){return a.get(u)});return{ids:f,lengths:l}}function getBoxIDs(e){let i=new Set,t=e.map,n=t.data;for(let a of[0,e.height-1])for(let s=0;s<e.width;s++){let o=(a+e.minY)*t.width+s+e.minX;if(s-e.minX>0&&n[o]===e.id&&n[o-1]!==e.id){let h=n[o-1];i.add(h)}if(t.width-s-e.minX>1&&n[o]===e.id&&n[o+1]!==e.id){let h=n[o+1];i.add(h)}}for(let a of[0,e.width-1])for(let s=0;s<e.height;s++){let o=(s+e.minY)*t.width+a+e.minX;if(s-e.minY>0&&n[o]===e.id&&n[o-t.width]!==e.id){let h=n[o-t.width];i.add(h)}if(t.height-s-e.minY>1&&n[o]===e.id&&n[o+t.width]!==e.id){let h=n[o+t.width];i.add(h)}}return Array.from(i)}function getBox(e){let i=0,t=e.map,n=t.data,a=[0];e.height>1&&(a[1]=e.height-1);for(let o of a)for(let h=1;h<e.width-1;h++){let f=(o+e.minY)*t.width+h+e.minX;n[f]===e.id&&i++}let s=[0];e.width>1&&(s[1]=e.width-1);for(let o of s)for(let h=0;h<e.height;h++){let f=(h+e.minY)*t.width+o+e.minX;n[f]===e.id&&i++}return i}function getBorder(e){let i=0,t=e.map,n=t.data;for(let a=1;a<e.width-1;a++)for(let s=1;s<e.height-1;s++){let o=(s+e.minY)*t.width+a+e.minX;n[o]===e.id&&(n[o-1]!==e.id||n[o+1]!==e.id||n[o-t.width]!==e.id||n[o+t.width]!==e.id)&&i++}return i+e.box}function getPerimeterInfo(e){let i=e.map,t=i.data,n=0,a=0,s=0,o=0;for(let h=0;h<e.width;h++)for(let f=0;f<e.height;f++){let l=(f+e.minY)*i.width+h+e.minX;if(t[l]===e.id){let u=0;switch((h===0||e.externalIDs.includes(t[l-1]))&&u++,(h===e.width-1||e.externalIDs.includes(t[l+1]))&&u++,(f===0||e.externalIDs.includes(t[l-i.width]))&&u++,(f===e.height-1||e.externalIDs.includes(t[l+i.width]))&&u++,u){case 1:n++;break;case 2:a++;break;case 3:s++;break;case 4:o++;break}}}return{one:n,two:a,three:s,four:o}}function getExternal(e){let i=0,t=e.map,n=t.data;for(let a=1;a<e.width-1;a++)for(let s=1;s<e.height-1;s++){let o=(s+e.minY)*t.width+a+e.minX;n[o]===e.id&&(e.externalIDs.includes(n[o-1])||e.externalIDs.includes(n[o+1])||e.externalIDs.includes(n[o-t.width])||e.externalIDs.includes(n[o+t.width]))&&i++}return i+e.box}function getHolesInfo(e){let i=0,t=e.map.width,n=e.map.data;for(let a=1;a<e.width-1;a++)for(let s=1;s<e.height-1;s++){let o=(s+e.minY)*t+a+e.minX;e.internalIDs.includes(n[o])&&n[o]!==e.id&&i++}return{number:e.internalIDs.length-1,surface:i}}function getInternalIDs(e){let i=[e.id],t=e.map,n=t.data;if(e.height>2)for(let s=0;s<e.width;s++){let o=e.minY*t.width+s+e.minX;if(i.includes(n[o])){let h=n[o+t.width];!i.includes(h)&&!e.boxIDs.includes(h)&&i.push(h)}}let a=new Array(4);for(let s=1;s<e.width-1;s++)for(let o=1;o<e.height-1;o++){let h=(o+e.minY)*t.width+s+e.minX;if(i.includes(n[h])){a[0]=n[h-1],a[1]=n[h+1],a[2]=n[h-t.width],a[3]=n[h+t.width];for(let f=0;f<4;f++){let l=a[f];!i.includes(l)&&!e.boxIDs.includes(l)&&i.push(l)}}}return i}class RoiLayer{constructor(i,t){this.roiMap=i,this.options=t,this.roi=this.createRoi()}createRoi(){let i=this.roiMap.data,t={};this.roiMap.positive=0,this.roiMap.negative=0;for(let h=0;h<i.length;h++)i[h]&&!t[i[h]]&&(t[i[h]]=!0,i[h]>0?this.roiMap.positive++:this.roiMap.negative++);let n={};for(let h in t)n[h]=new Roi(this.roiMap,h*1);let a=this.roiMap.width,s=this.roiMap.height;for(let h=0;h<s;h++)for(let f=0;f<a;f++){let l=h*a+f;if(i[l]!==0){const u=i[l],w=n[u];f<w.minX&&(w.minX=f),f>w.maxX&&(w.maxX=f),h<w.minY&&(w.minY=h),h>w.maxY&&(w.maxY=h),w.meanX+=f,w.meanY+=h,w.surface++}}let o=[];for(let h in t)n[h].meanX/=n[h].surface,n[h].meanY/=n[h].surface,o.push(n[h]);return o}}function commonBorderLength(e){let i=e.data,t=[1,0,-1,0],n=[0,1,0,-1],a=e.minMax,s=-a.min,o=a.max+s,h=[];for(let l=0;l<=o;l++)h.push(Object.create(null));for(let l=0;l<e.width;l++)for(let u=0;u<e.height;u++){let w=l+u*e.width,_=i[w];if(_!==0){let g=Object.create(null),v=!1;for(let k=0;k<4;k++){let A=l+t[k],T=u+n[k];if(A>=0&&T>=0&&A<e.width&&T<e.height){let $=i[A+T*e.width];_!==$&&(v=!0,$!==0&&g[$]===void 0&&(g[$]=!0,h[$+s][_]?h[$+s][_]++:h[$+s][_]=1))}else v=!0}v&&(h[_+s][_]?h[_+s][_]++:h[_+s][_]=1)}}let f={};for(let l=0;l<h.length;l++)Object.keys(h[l]).length>0&&(f[l-s]=h[l]);return f}function mergeRoi(e={}){const{algorithm:i="commonBorderLength",minCommonBorderLength:t=5,maxCommonBorderLength:n=100,minCommonBorderRatio:a=.3,maxCommonBorderRatio:s=1}=e;let o=function(A,T,$){return A[$]>=t&&A[$]<=n};typeof i=="function"&&(o=i),i.toLowerCase()==="commonborderratio"&&(o=function(A,T,$){let D=Math.min(A[$]/A[T],1);return D>=a&&D<=s});const h=this,f=h.commonBorderLength;let l={},u={};for(let A of Object.keys(f)){let T=f[A],$=Object.keys(T);for(let D of $)if(D!==A&&o(T,A,D)){let C=D;u[D]&&(C=u[D]);let P=A;if(u[A]&&(P=u[A]),Number(C)!==P){let z=Math.min(C,P),B=Math.max(C,P);if(l[z]||(l[z]={}),l[z][B]=!0,u[B]=z,l[B]){for(let F of Object.keys(l[B]))l[z][F]=!0,u[F]=z;delete l[B]}}}}let w=h.minMax,_=-w.min,g=w.max+_,v=new Array(g+1).fill(0);for(let A of Object.keys(u))v[Number(A)+_]=u[A];let k=h.data;for(let A=0;A<k.length;A++){let T=k[A];if(T!==0){let $=v[T+_];$!==0&&(k[A]=$)}}return h.computed={},h}class RoiMap{constructor(i,t){this.parent=i,this.width=i.width,this.height=i.height,this.data=t,this.negative=0,this.positive=0}get total(){return this.negative+this.positive}get minMax(){let i=Number.MAX_SAFE_INTEGER,t=Number.MIN_SAFE_INTEGER;for(let n=0;n<this.data.length;n++)this.data[n]<i&&(i=this.data[n]),this.data[n]>t&&(t=this.data[n]);return{min:i,max:t}}get commonBorderLength(){return commonBorderLength(this)}mergeRoi(i={}){return mergeRoi.call(this,i)}mergeRois(i){const t=i[0],n=i.slice(1);for(let a=0;a<this.data.length;a++)n.includes(this.data[a])&&(this.data[a]=t)}rowsInfo(){let i=new Array(this.height),t=0;for(let n=0;n<this.data.length;n+=this.width){let a={row:t,positivePixel:0,negativePixel:0,zeroPixel:0,positiveRoi:0,negativeRoi:0,medianChange:0};i[t++]=a;let s={},o={},h=[],f=this.data[n],l=0;for(let u=n;u<n+this.width;u++){let w=this.data[u];f!==w&&(f=w,h.push(l),l=0),l++,w>0?(a.positivePixel++,s[w]||(s[w]=!0)):w<0?(a.negativePixel++,o[w]||(o[w]=!0)):a.zeroPixel++}h.push(l),a.medianChange=h.sort((u,w)=>u-w)[Math.floor(h.length/2)],a.positiveRoiIDs=Object.keys(s),a.negativeRoiIDs=Object.keys(o),a.positiveRoi=a.positiveRoiIDs.length,a.negativeRoi=a.negativeRoiIDs.length}return i}colsInfo(){let i=new Array(this.width),t=0;for(let n=0;n<this.width;n++){let a={col:t,positivePixel:0,negativePixel:0,zeroPixel:0,positiveRoi:0,negativeRoi:0,medianChange:0};i[t++]=a;let s={},o={},h=[],f=this.data[n],l=0;for(let u=n;u<n+this.data.length;u+=this.width){let w=this.data[u];f!==w&&(f=w,h.push(l),l=0),l++,w>0?(a.positivePixel++,s[w]||(s[w]=!0)):w<0?(a.negativePixel++,o[w]||(o[w]=!0)):a.zeroPixel++}h.push(l),a.medianChange=h.sort((u,w)=>u-w)[Math.floor(h.length/2)],a.positiveRoiIDs=Object.keys(s),a.negativeRoiIDs=Object.keys(o),a.positiveRoi=a.positiveRoiIDs.length,a.negativeRoi=a.negativeRoiIDs.length}return i}}function fromMask(e,i={}){const{allowCorners:t=!1}=i,n=65535;let a=new Int16Array(e.size),s=0,o=0,h=new Uint16Array(n+1),f=new Uint16Array(n+1);for(let u=0;u<e.width;u++)for(let w=0;w<e.height;w++)a[w*e.width+u]===0&&l(u,w);function l(u,w){let _=0,g=0,v=e.getBitXY(u,w),k=v?++s:--o;if(s>32767||o<-32768)throw new Error("Too many regions of interest");for(h[0]=u,f[0]=w;_<=g;){let A=h[_&n],T=f[_&n];if(a[T*e.width+A]=k,A>0&&a[T*e.width+A-1]===0&&e.getBitXY(A-1,T)===v&&(g++,h[g&n]=A-1,f[g&n]=T,a[T*e.width+A-1]=-32768),T>0&&a[(T-1)*e.width+A]===0&&e.getBitXY(A,T-1)===v&&(g++,h[g&n]=A,f[g&n]=T-1,a[(T-1)*e.width+A]=-32768),A<e.width-1&&a[T*e.width+A+1]===0&&e.getBitXY(A+1,T)===v&&(g++,h[g&n]=A+1,f[g&n]=T,a[T*e.width+A+1]=-32768),T<e.height-1&&a[(T+1)*e.width+A]===0&&e.getBitXY(A,T+1)===v&&(g++,h[g&n]=A,f[g&n]=T+1,a[(T+1)*e.width+A]=-32768),t&&(A>0&&T>0&&a[(T-1)*e.width+A-1]===0&&e.getBitXY(A-1,T-1)===v&&(g++,h[g&n]=A-1,f[g&n]=T-1,a[(T-1)*e.width+A-1]=-32768),A<e.width-1&&T>0&&a[(T-1)*e.width+A+1]===0&&e.getBitXY(A+1,T-1)===v&&(g++,h[g&n]=A+1,f[g&n]=T-1,a[(T-1)*e.width+A+1]=-32768),A>0&&T<e.height-1&&a[(T+1)*e.width+A-1]===0&&e.getBitXY(A-1,T+1)===v&&(g++,h[g&n]=A-1,f[g&n]=T+1,a[(T+1)*e.width+A-1]=-32768),A<e.width-1&&T<e.height-1&&a[(T+1)*e.width+A+1]===0&&e.getBitXY(A+1,T+1)===v&&(g++,h[g&n]=A+1,f[g&n]=T+1,a[(T+1)*e.width+A+1]=-32768)),_++,g-_>n)throw new Error("analyseMask can not finish, the array to manage internal data is not big enough.You could improve mask by changing MAX_ARRAY")}}return new RoiMap(e,a)}var DisjointSet_1,hasRequiredDisjointSet;function requireDisjointSet(){if(hasRequiredDisjointSet)return DisjointSet_1;hasRequiredDisjointSet=1;class e{constructor(){this.nodes=new Map}add(n){var a=this.nodes.get(n);return a||(a=new i(n),this.nodes.set(n,a)),a}union(n,a){const s=this.find(n),o=this.find(a);s!==o&&(s.rank<o.rank?s.parent=o:s.rank>o.rank?o.parent=s:(o.parent=s,s.rank++))}find(n){for(var a=n;a.parent!==null;)a=a.parent;for(var s=n;s.parent!==null;){var o=s;s=s.parent,o.parent=a}return a}connected(n,a){return this.find(n)===this.find(a)}}DisjointSet_1=e;function i(t){this.value=t,this.parent=null,this.rank=0}return DisjointSet_1}var DisjointSetExports=requireDisjointSet();const DisjointSet=getDefaultExportFromCjs(DisjointSetExports),direction4X=[-1,0],direction4Y=[0,-1],neighbours4=[null,null],direction8X=[-1,-1,0,1],direction8Y=[0,-1,-1,-1],neighbours8=[null,null,null,null];function fromMaskConnectedComponentLabelingAlgorithm(e,i={}){const{allowCorners:t=!1}=i;let n=4;t&&(n=8);let a,s,o;if(n===8)a=direction8X,s=direction8Y,o=neighbours8;else if(n===4)a=direction4X,s=direction4Y,o=neighbours4;else throw new RangeError(`unsupported neighbours count: ${n}`);const h=e.size,f=e.width,l=e.height,u=new Array(h),w=new Uint32Array(h),_=new DisjointSet;let g=1;for(let v=0;v<l;v++)for(let k=0;k<f;k++){const A=k+v*f;if(e.getBit(A)){let T=null;for(let $=0;$<o.length;$++){const D=k+a[$],C=v+s[$];if(D>=0&&C>=0&&D<f&&C<l){const P=D+C*f;let z=u[P];z?(o[$]=z,(!T||o[$].value<T.value)&&(T=o[$])):o[$]=null}}if(!T)u[A]=_.add(g++);else{u[A]=T;for(let $=0;$<o.length;$++)o[$]&&o[$]!==T&&_.union(T,o[$])}}}for(let v=0;v<l;v++)for(let k=0;k<f;k++){const A=k+v*f;e.getBit(A)&&(w[A]=_.find(u[A]).value)}return new RoiMap(e,w)}function fromMaxima(e={}){let{allowCorner:i=!0,onlyTop:t=!1,invert:n=!1}=e,a=this;a.checkProcessable("fromMaxima",{components:[1]});const s=1,o=2;let h=0,f=0,l=new Int16Array(a.size),u=new Int8Array(a.size),w=new Float32Array(a.size),_=1048575,g=new Uint16Array(_+1),v=new Uint16Array(_+1),k=0,A=0,T=new Uint16Array(_+1),$=new Uint16Array(_+1),D=0,C=0;for(P(a);k<A;){let F=g[k&_],L=v[k&_];B(F,L,o),k++}return new RoiMap(a,l);function P({maxima:F=!0}){for(let L=1;L<a.height-1;L++)for(let N=1;N<a.width-1;N++){let G=N+L*a.width;if(u[G]===0){let V=F?a.data[G]:-a.data[N+L*a.width];if(a.data[L*a.width+N-1]>V||a.data[L*a.width+N+1]>V||a.data[(L-1)*a.width+N]>V||a.data[(L+1)*a.width+N]>V||i&&(a.data[(L-1)*a.width+N-1]>V||a.data[(L-1)*a.width+N+1]>V||a.data[(L+1)*a.width+N-1]>V||a.data[(L+1)*a.width+N+1]>V))continue;l[G]=F?++h:--f,z(N,L)||(F?--h:++f)}}}function z(F,L){let N=A;D=0,C=1,T[0]=F,$[0]=L;let G=!0;for(;D<C;){let V=T[D&_],J=$[D&_];G&=B(V,J,s),D++}if(!G){for(let V=0;V<C;V++){let J=T[V&_],W=$[V&_]*a.width+J;l[W]=0}A=N}return G}function B(F,L,N){let G=l[L*a.width+F],V=a.data[L*a.width+F];for(let J=L-1;J<=L+1;J++)for(let Q=F-1;Q<=F+1;Q++){let W=J*a.width+Q;if(u[W]===0)switch(u[W]=1,w[W]=a.data[W]-V,N){case s:if(w[W]===0){if(Q===0||J===0||Q===a.width-1||J===a.height-1)return!1;l[W]=G,T[C&_]=Q,$[C&_]=J,C++}else{if(w[W]>0)return!1;t||(l[W]=G,g[A&_]=Q,v[A&_]=J,A++)}break;case o:w[W]<=0&&(l[W]=G,g[A&_]=Q,v[A&_]=J,A++);break;default:throw new Error("unreachable")}}return!0}}function fromPoints(e,i={}){let t=new Shape(i),n=new Int16Array(this.size),a=0,s=t.getPoints();for(let o=0;o<e.length;o++){a++;let h=e[o][0],f=e[o][1];for(let l=0;l<s.length;l++){let u=s[l][0],w=s[l][1];h+u>=0&&f+w>=0&&h+u<this.width&&f+w<this.height&&(n[h+u+(f+w)*this.width]=a)}}return new RoiMap(this,n)}function commonjsRequire(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var priorityQueue={exports:{}},hasRequiredPriorityQueue;function requirePriorityQueue(){return hasRequiredPriorityQueue||(hasRequiredPriorityQueue=1,function(e,i){(function(t){e.exports=t()})(function(){return function t(n,a,s){function o(l,u){if(!a[l]){if(!n[l]){var w=typeof commonjsRequire=="function"&&commonjsRequire;if(!u&&w)return w(l,!0);if(h)return h(l,!0);var _=new Error("Cannot find module '"+l+"'");throw _.code="MODULE_NOT_FOUND",_}var g=a[l]={exports:{}};n[l][0].call(g.exports,function(v){var k=n[l][1][v];return o(k||v)},g,g.exports,t,n,a,s)}return a[l].exports}for(var h=typeof commonjsRequire=="function"&&commonjsRequire,f=0;f<s.length;f++)o(s[f]);return o}({1:[function(t,n,a){var s,o,h,f,l,u=function(_,g){for(var v in g)w.call(g,v)&&(_[v]=g[v]);function k(){this.constructor=_}return k.prototype=g.prototype,_.prototype=new k,_.__super__=g.prototype,_},w={}.hasOwnProperty;s=t("./PriorityQueue/AbstractPriorityQueue"),o=t("./PriorityQueue/ArrayStrategy"),f=t("./PriorityQueue/BinaryHeapStrategy"),h=t("./PriorityQueue/BHeapStrategy"),l=function(_){u(g,_);function g(v){v||(v={}),v.strategy||(v.strategy=f),v.comparator||(v.comparator=function(k,A){return(k||0)-(A||0)}),g.__super__.constructor.call(this,v)}return g}(s),l.ArrayStrategy=o,l.BinaryHeapStrategy=f,l.BHeapStrategy=h,n.exports=l},{"./PriorityQueue/AbstractPriorityQueue":2,"./PriorityQueue/ArrayStrategy":3,"./PriorityQueue/BHeapStrategy":4,"./PriorityQueue/BinaryHeapStrategy":5}],2:[function(t,n,a){n.exports=function(){function s(o){var h;if((o!=null?o.strategy:void 0)==null)throw"Must pass options.strategy, a strategy";if((o!=null?o.comparator:void 0)==null)throw"Must pass options.comparator, a comparator";this.priv=new o.strategy(o),this.length=(o!=null&&(h=o.initialValues)!=null?h.length:void 0)||0}return s.prototype.queue=function(o){this.length++,this.priv.queue(o)},s.prototype.dequeue=function(o){if(!this.length)throw"Empty queue";return this.length--,this.priv.dequeue()},s.prototype.peek=function(o){if(!this.length)throw"Empty queue";return this.priv.peek()},s.prototype.clear=function(){return this.length=0,this.priv.clear()},s}()},{}],3:[function(t,n,a){var s;s=function(o,h,f){var l,u,w;for(u=0,l=o.length;u<l;)w=u+l>>>1,f(o[w],h)>=0?u=w+1:l=w;return u},n.exports=function(){function o(h){var f;this.options=h,this.comparator=this.options.comparator,this.data=((f=this.options.initialValues)!=null?f.slice(0):void 0)||[],this.data.sort(this.comparator).reverse()}return o.prototype.queue=function(h){var f;f=s(this.data,h,this.comparator),this.data.splice(f,0,h)},o.prototype.dequeue=function(){return this.data.pop()},o.prototype.peek=function(){return this.data[this.data.length-1]},o.prototype.clear=function(){this.data.length=0},o}()},{}],4:[function(t,n,a){n.exports=function(){function s(o){var h,f,l,u,w,_,g,v;for(this.comparator=(o!=null?o.comparator:void 0)||function(k,A){return k-A},this.pageSize=(o!=null?o.pageSize:void 0)||512,this.length=0,g=0;1<<g<this.pageSize;)g+=1;if(1<<g!==this.pageSize)throw"pageSize must be a power of two";for(this._shift=g,this._emptyMemoryPageTemplate=h=[],f=0,w=this.pageSize;0<=w?f<w:f>w;0<=w?++f:--f)h.push(null);if(this._memory=[],this._mask=this.pageSize-1,o.initialValues)for(_=o.initialValues,l=0,u=_.length;l<u;l++)v=_[l],this.queue(v)}return s.prototype.queue=function(o){this.length+=1,this._write(this.length,o),this._bubbleUp(this.length,o)},s.prototype.dequeue=function(){var o,h;return o=this._read(1),h=this._read(this.length),this.length-=1,this.length>0&&(this._write(1,h),this._bubbleDown(1,h)),o},s.prototype.peek=function(){return this._read(1)},s.prototype.clear=function(){this.length=0,this._memory.length=0},s.prototype._write=function(o,h){var f;for(f=o>>this._shift;f>=this._memory.length;)this._memory.push(this._emptyMemoryPageTemplate.slice(0));return this._memory[f][o&this._mask]=h},s.prototype._read=function(o){return this._memory[o>>this._shift][o&this._mask]},s.prototype._bubbleUp=function(o,h){var f,l,u,w;for(f=this.comparator;o>1&&(l=o&this._mask,o<this.pageSize||l>3?u=o&~this._mask|l>>1:l<2?(u=o-this.pageSize>>this._shift,u+=u&~(this._mask>>1),u|=this.pageSize>>1):u=o-2,w=this._read(u),!(f(w,h)<0));)this._write(u,h),this._write(o,w),o=u},s.prototype._bubbleDown=function(o,h){var f,l,u,w,_;for(_=this.comparator;o<this.length;)if(o>this._mask&&!(o&this._mask-1)?f=l=o+2:o&this.pageSize>>1?(f=(o&~this._mask)>>1,f|=o&this._mask>>1,f=f+1<<this._shift,l=f+1):(f=o+(o&this._mask),l=f+1),f!==l&&l<=this.length)if(u=this._read(f),w=this._read(l),_(u,h)<0&&_(u,w)<=0)this._write(f,h),this._write(o,u),o=f;else if(_(w,h)<0)this._write(l,h),this._write(o,w),o=l;else break;else if(f<=this.length)if(u=this._read(f),_(u,h)<0)this._write(f,h),this._write(o,u),o=f;else break;else break},s}()},{}],5:[function(t,n,a){n.exports=function(){function s(o){var h;this.comparator=(o!=null?o.comparator:void 0)||function(f,l){return f-l},this.length=0,this.data=((h=o.initialValues)!=null?h.slice(0):void 0)||[],this._heapify()}return s.prototype._heapify=function(){var o,h,f;if(this.data.length>0)for(o=h=1,f=this.data.length;1<=f?h<f:h>f;o=1<=f?++h:--h)this._bubbleUp(o)},s.prototype.queue=function(o){this.data.push(o),this._bubbleUp(this.data.length-1)},s.prototype.dequeue=function(){var o,h;return h=this.data[0],o=this.data.pop(),this.data.length>0&&(this.data[0]=o,this._bubbleDown(0)),h},s.prototype.peek=function(){return this.data[0]},s.prototype.clear=function(){this.length=0,this.data.length=0},s.prototype._bubbleUp=function(o){for(var h,f;o>0&&(h=o-1>>>1,this.comparator(this.data[o],this.data[h])<0);)f=this.data[h],this.data[h]=this.data[o],this.data[o]=f,o=h},s.prototype._bubbleDown=function(o){var h,f,l,u,w;for(h=this.data.length-1;f=(o<<1)+1,u=f+1,l=o,f<=h&&this.comparator(this.data[f],this.data[l])<0&&(l=f),u<=h&&this.comparator(this.data[u],this.data[l])<0&&(l=u),l!==o;)w=this.data[l],this.data[l]=this.data[o],this.data[o]=w,o=l},s}()},{}]},{},[1])(1)})}(priorityQueue)),priorityQueue.exports}var priorityQueueExports=requirePriorityQueue();const PriorityQueue=getDefaultExportFromCjs(priorityQueueExports),dxs=[1,0,-1,0,1,1,-1,-1],dys=[0,1,0,-1,1,-1,1,-1];function fromWaterShed(e={}){let{points:i,mask:t,image:n,fillMaxValue:a=this.maxValue,invert:s=!1}=e,o=n||this;o.checkProcessable("fromWaterShed",{bitDepth:[8,16],components:1}),s=!s,i||(i=o.getLocalMaxima({invert:s,mask:t}));let h=s?0:1,f=new Int16Array(o.size),l=o.width,u=o.height,w=new PriorityQueue({comparator:(_,g)=>_[2]-g[2],strategy:PriorityQueue.BinaryHeapStrategy});for(let _=0;_<i.length;_++){let g=i[_][0]+i[_][1]*l;f[g]=_+1;let v=o.data[g];(s&&v<=a||!s&&v>=a)&&w.queue([i[_][0],i[_][1],v])}for(;w.length>0;){let _=w.dequeue(),g=_[0]+_[1]*l;for(let v=0;v<4;v++){let k=_[0]+dxs[v],A=_[1]+dys[v];if(k>=0&&A>=0&&k<l&&A<u){let T=k+A*l;if(!t||t.getBit(T)===h){let $=o.data[T];(s&&$<=a||!s&&$>=a)&&f[T]===0&&(f[T]=f[g],w.queue([_[0]+dxs[v],_[1]+dys[v],$]))}}}}return new RoiMap(o,f)}class RoiManager{constructor(i,t={}){this._image=i,this._options=t,this._options.label||(this._options.label="default"),this._layers={},this._painted=null}fromMaxima(i={}){let t=Object.assign({},this._options,i),n=fromMaxima.call(this._image,i);this._layers[t.label]=new RoiLayer(n,t)}fromPoints(i,t={}){let n=Object.assign({},this._options,t),a=fromPoints.call(this._image,i,t);return this._layers[n.label]=new RoiLayer(a,n),this}putMap(i,t={}){let n=new RoiMap(this._image,i),a=Object.assign({},this._options,t);return this._layers[a.label]=new RoiLayer(n,a),this}fromWaterShed(i={}){let t=Object.assign({},this._options,i),n=fromWaterShed.call(this._image,i);this._layers[t.label]=new RoiLayer(n,t)}fromMask(i,t={}){let n=Object.assign({},this._options,t),a=fromMask.call(this._image,i,t);return this._layers[n.label]=new RoiLayer(a,n),this}fromMaskConnectedComponentLabelingAlgorithm(i,t={}){let n=Object.assign({},this._options,t),a=fromMaskConnectedComponentLabelingAlgorithm.call(this._image,i,t);return this._layers[n.label]=new RoiLayer(a,n),this}getMap(i={}){let t=Object.assign({},this._options,i);return this._assertLayerWithLabel(t.label),this._layers[t.label].roiMap}rowsInfo(i={}){return this.getMap(i).rowsInfo()}colsInfo(i={}){return this.getMap(i).rowsInfo()}getRoiIds(i={}){let t=this.getRois(i);if(t){let n=new Array(t.length);for(let a=0;a<t.length;a++)n[a]=t[a].id;return n}throw new Error("ROIs not found")}getRois(i={}){let{label:t=this._options.label,positive:n=!0,negative:a=!0,minSurface:s=0,maxSurface:o=Number.POSITIVE_INFINITY,minWidth:h=0,maxWidth:f=Number.POSITIVE_INFINITY,minHeight:l=0,maxHeight:u=Number.POSITIVE_INFINITY,minRatio:w=0,maxRatio:_=Number.POSITIVE_INFINITY}=i;if(!this._layers[t])throw new Error(`this Roi layer (${t}) does not exist`);const g=this._layers[t].roi,v=[];for(const k of g)(k.id<0&&a||k.id>0&&n)&&k.surface>=s&&k.surface<=o&&k.width>=h&&k.width<=f&&k.height>=l&&k.height<=u&&k.ratio>=w&&k.ratio<=_&&v.push(k);return v}getRoi(i,t={}){const{label:n=this._options.label}=t;if(!this._layers[n])throw new Error(`this Roi layer (${n}) does not exist`);const a=this._layers[n].roi.find(s=>s.id===i);if(!a)throw new Error(`found no Roi with id ${i}`);return a}getMasks(i={}){let t=this.getRois(i),n=new Array(t.length);for(let a=0;a<t.length;a++)n[a]=t[a].getMask(i);return n}getAnalysisMasks(i={}){const{analysisProperty:t}=i;let n=`${t}Mask`,a=this.getRois(i);return a.length===0||!a[0][n]?[]:a.map(s=>s[n])}getData(i={}){let t=Object.assign({},this._options,i);return this._assertLayerWithLabel(t.label),this._layers[t.label].roiMap.data}paint(i={}){let{labelProperty:t,analysisProperty:n}=i;this._painted||(this._painted=this._image.rgba8());let a=this.getMasks(i);if(t){const s=this.getRois(i);i.labels=s.map(l=>deepValue(l,t));const o=Math.max(...i.labels);let h=!1,f=!1;if(t.includes("surface")?h=!0:/(?:perimeter|min|max|external|width|height|length)/.test(t)&&(f=!0),isFinite(o)){let l="";if(i.unit!=="pixel"&&i.pixelSize&&(f||h)){l=h?`${i.unit}^2`:i.unit;let u=h?"m^2":"m",w=h?i.pixelSize**2:i.pixelSize;const _=Qty.swiftConverter(u,l);i.labels=i.labels.map(g=>_(w*g))}o>50?i.labels=i.labels.map(u=>Math.round(u)+l):o>10?i.labels=i.labels.map(u=>u.toFixed(1)+l):i.labels=i.labels.map(u=>u.toFixed(2)+l)}i.labelsPosition=s.map(l=>[l.meanX,l.meanY])}if(this._painted.paintMasks(a,i),n){let s=this.getAnalysisMasks(i);this._painted.paintMasks(s,{color:i.analysisColor,alpha:i.analysisAlpha})}return this._painted}getMask(i={}){let t=new Image(this._image.width,this._image.height,{kind:"BINARY"}),n=this.getMasks(i);for(let a=0;a<n.length;a++){let s=n[a];for(let o=0;o<s.width;o++)for(let h=0;h<s.height;h++)s.getBitXY(o,h)&&t.setBitXY(o+s.position[0],h+s.position[1])}return t}resetPainted(i={}){const{image:t}=i;t?this._painted=this.image.rgba8():this._painted=this._image.rgba8()}mergeRoi(i={}){const t=this.getMap(i);return t.mergeRoi(i),this.putMap(t.data,i),this}mergeRois(i,t={}){if(!Array.isArray(i)||i.some(a=>!Number.isInteger(a)))throw new Error("Roi ids must be an array of integers");if(i.length<2)throw new Error("Roi ids must have at least two elements");if(new Set(i).size!==i.length)throw new Error("Roi ids must be all different");i.forEach(a=>this.getRoi(a));const n=this.getMap(t);return n.mergeRois(i),this.putMap(n.data,t),this}findCorrespondingRoi(i,t={}){let n=this.getRois(t),a=[];for(let s=0;s<n.length;s++){let o=n[s],h=o.minX,f=o.minY,l=o.points,u=Math.sign(o.id),w=correspondingRoisInformation(h,f,l,i,u);a.push(w)}return a}_assertLayerWithLabel(i){if(!this._layers[i])throw new Error(`no layer with label ${i}`)}}function correspondingRoisInformation(e,i,t,n,a){let s={id:[],surface:[],roiSurfaceCovered:[],same:0,opposite:0,total:0};for(let o=0;o<t.length;o++){let h=t[o],f=h[0],l=h[1],u=f+e+(l+i)*n.width,w=n.data[u];(w>0||w<0)&&(s.id.includes(w)?s.surface[s.id.indexOf(w)]+=1:(s.id.push(w),s.surface.push(1)))}for(let o=0;o<s.id.length;o++)Math.sign(s.id[o])===a?s.same+=s.surface[o]:s.opposite+=s.surface[o],s.roiSurfaceCovered[o]=s.surface[o]/t.length;return s.total=s.opposite+s.same,s}const objectToString=Object.prototype.toString;class Image{constructor(i,t,n,a){if(arguments.length===1?(a=i,{width:i,height:t,data:n}=a):n&&!n.length&&(a=n,{data:n}=a),i===void 0&&(i=1),t===void 0&&(t=1),a===void 0&&(a={}),typeof a!="object"||a===null)throw new TypeError("options must be an object");if(!Number.isInteger(i)||i<=0)throw new RangeError("width must be a positive integer");if(!Number.isInteger(t)||t<=0)throw new RangeError("height must be a positive integer");const{kind:s=RGBA}=a;if(typeof s!="string")throw new TypeError("kind must be a string");const o=getKind(s),h=Object.assign({},a);for(const k in o)h[k]===void 0&&(h[k]=o[k]);verifyKindDefinition(h);const{components:f,bitDepth:l,colorModel:u}=h,w=h.alpha+0,_=i*t,g=f+w,v=l===32?Number.MAX_VALUE:2**l-1;if(n===void 0)n=createPixelArray(_,f,w,g,l,v);else{const k=getTheoreticalPixelArraySize(_,g,l);if(n.length!==k)throw new RangeError(`incorrect data size: ${n.length}. Should be ${k}`)}this.width=i,this.height=t,this.data=n,this.size=_,this.components=f,this.alpha=w,this.bitDepth=l,this.maxValue=v,this.colorModel=u,this.channels=g,this.meta=a.meta||{},Object.defineProperty(this,"parent",{enumerable:!1,writable:!0,configurable:!0,value:a.parent||null}),this.position=a.position||[0,0],this.computed=null,this.sizes=[this.width,this.height],this.multiplierX=this.channels,this.multiplierY=this.channels*this.width,this.isClamped=this.bitDepth<32,this.borderSizes=[0,0]}get[Symbol.toStringTag](){return"IJSImage"}static isImage(i){return objectToString.call(i)==="[object IJSImage]"}static fromCanvas(i){const n=i.getContext("2d").getImageData(0,0,i.width,i.height);return new Image(n.width,n.height,n.data)}static createFrom(i,t){const n=getImageParameters(i);return Object.assign(n,{parent:i,position:[0,0]},t),new Image(n)}getRoiManager(i){return new RoiManager(this,i)}clone(){const i=this.data.slice();return new Image(this.width,this.height,i,this)}apply(i){for(let t=0;t<this.height;t++)for(let n=0;n<this.width;n++){let a=(t*this.width+n)*this.channels;i.call(this,a)}}}setValueMethods(Image),setBitMethods(Image),setExportMethods(Image),Image.prototype.checkProcessable=checkProcessable,Image.prototype.getRGBAData=getRGBAData,Image.load=load,Image.extendMethod=extendMethod,Image.extendProperty=extendProperty,extend$1(Image);var workerTemplate={},hasRequiredWorkerTemplate;function requireWorkerTemplate(){if(hasRequiredWorkerTemplate)return workerTemplate;hasRequiredWorkerTemplate=1;var e=function(){self.window=self;function t(){this._listeners={}}t.prototype.on=function(a,s){if(this._listeners[a])throw new RangeError("there is already a listener for "+a);if(typeof s!="function")throw new TypeError("callback argument must be a function");this._listeners[a]=s},t.prototype._send=function(a,s,o){o===void 0?o=[]:Array.isArray(o)||(o=[o]),self.postMessage({id:a,data:s},o)},t.prototype._trigger=function(a,s){if(!this._listeners[a])throw new Error("event "+a+" is not defined");this._listeners[a].apply(null,s)};var n=new t;self.onmessage=function(a){switch(a.data.action){case"exec":a.data.args.unshift(function(s,o){n._send(a.data.id,s,o)}),n._trigger(a.data.event,a.data.args);break;case"ping":n._send(a.data.id,"pong");break;default:throw new Error("unexpected action: "+a.data.action)}}},i=e.toString().split('"CODE";');return workerTemplate.newWorkerURL=function(n,a){var s=new Blob(["(",i[0],"importScripts.apply(self, "+JSON.stringify(a)+`);
10
+ `,"(",n,")();",i[1],")();"],{type:"application/javascript"});return URL.createObjectURL(s)},workerTemplate}var src,hasRequiredSrc;function requireSrc(){if(hasRequiredSrc)return src;hasRequiredSrc=1;var e=requireWorkerTemplate(),i=navigator.hardwareConcurrency||1;function t(n,a){if(typeof n!="string"&&typeof n!="function")throw new TypeError("func argument must be a function");if(a===void 0&&(a={}),typeof a!="object"||a===null)throw new TypeError("options argument must be an object");this._workerCode=n.toString(),a.maxWorkers===void 0||a.maxWorkers==="auto"?this._numWorkers=Math.min(i-1,1):a.maxWorkers>0?this._numWorkers=Math.min(a.maxWorkers,i):this._numWorkers=i,this._workers=new Map,this._timeout=a.timeout||0,this._terminateOnError=!!a.terminateOnError;var s=a.deps;typeof s=="string"&&(s=[s]),Array.isArray(s)||(s=void 0),this._id=0,this._terminated=!1,this._working=0,this._waiting=[],this._init(s)}return t.prototype._init=function(n){for(var a=e.newWorkerURL(this._workerCode,n),s=0;s<this._numWorkers;s++){var o=new Worker(a);o.onmessage=this._onmessage.bind(this,o),o.onerror=this._onerror.bind(this,o),o.running=!1,o.id=s,this._workers.set(o,null)}URL.revokeObjectURL(a)},t.prototype._onerror=function(n,a){if(!this._terminated){this._working--,n.running=!1;var s=this._workers.get(n);s&&s[1](a.message),this._workers.set(n,null),this._terminateOnError?this.terminate():this._exec()}},t.prototype._onmessage=function(n,a){if(!this._terminated){this._working--,n.running=!1;var s=this._workers.get(n);s&&s[0](a.data.data),this._workers.set(n,null),this._exec()}},t.prototype._exec=function(){for(var n of this._workers.keys()){if(this._working===this._numWorkers||this._waiting.length===0)return;if(!n.running)for(var a=0;a<this._waiting.length;a++){var s=this._waiting[a];if(!(typeof s[4]=="number"&&s[4]!==n.id)){this._waiting.splice(a,1),n.postMessage({action:"exec",event:s[0],args:s[1]},s[2]),n.running=!0,n.time=Date.now(),this._workers.set(n,s[3]),this._working++;break}}}},t.prototype.terminate=function(){if(!this._terminated){for(var n of this._workers)n[0].terminate(),n[1]&&n[1][1](new Error("Terminated"));this._workers.clear(),this._waiting=[],this._working=0,this._terminated=!0}},t.prototype.postAll=function(n,a){if(this._terminated)throw new Error("Cannot post (terminated)");var s=[];for(var o of this._workers.keys())s.push(this.post(n,a,[],o.id));return Promise.all(s)},t.prototype.post=function(n,a,s,o){a===void 0&&(a=[]),s===void 0&&(s=[]),Array.isArray(a)||(a=[a]),Array.isArray(s)||(s=[s]);var h=this;return new Promise(function(f,l){if(h._terminated)throw new Error("Cannot post (terminated)");h._waiting.push([n,a,s,[f,l],o]),h._exec()})},src=t,src}var srcExports=requireSrc();const WorkerManager=getDefaultExportFromCjs(srcExports),defaultOptions={regression:{kernelType:"polynomial",kernelOptions:{degree:2,constant:1}},threshold:.02,roi:{minSurface:100,positive:!1},sampling:20,include:[]};function run(e,i,t){i=Object.assign({},defaultOptions,i);const n=this.manager;return Array.isArray(e)?Promise.all(e.map(function(a){const s=runOnce(n,a,i);return typeof t=="function"&&s.then(t),s})):runOnce(n,e,i)}function runOnce(e,i,t){return e.post("data",[i,t]).then(function(n){for(let a in n)n[a]=new Image(n[a]);return n})}function work(){worker.on("data",function(e,i,t){i=new IJS(i);const n={},a=[],s=i.grey(),o=s.sobelFilter();g("sobel",o);const h=o.level().mask({threshold:t.threshold});g("mask",h);const f=o.getRoiManager();f.fromMask(h);const l=f.getMask(t.roi);g("realMask",l);const u=s.getPixelsGrid({sampling:t.sampling,mask:l}),w=i.getBackground(u.xyS,u.zS,t.regression);g("background",w);const _=i.subtract(w);n.result=_,a.push(_.data.buffer),e(n,a);function g(v,k){t.include.includes(v)&&(n[v]=k,a.push(k.data.buffer))}})}const background={run,work};function extend(e){e.extendMethod("background",background)}let Worker$1=class Pt{constructor(){this._url=null,this._deps=[null]}checkUrl(){if(this._url===null)throw new Error("image worker must be initialized with an URL")}get url(){return this._url}set url(i){if(typeof i!="string")throw new TypeError("worker URL must be a string");this._url=i,this._deps[0]=i}static extendMethod(i,t){let n,a,s={};function o(...h){return n||(this.checkUrl(),a=this.url,n=new WorkerManager(t.work,{deps:a}),s.manager=n),t.run.call(s,...h)}o.reset=function(){n&&(n.terminate(),n=new WorkerManager(t.work,{deps:a}),s.manager=n)},Pt.prototype[i]=o}};extend(Worker$1);var lz4$1={},xxh32={},util={},hasRequiredUtil;function requireUtil(){return hasRequiredUtil||(hasRequiredUtil=1,util.hashU32=function(i){return i=i|0,i=i+2127912214+(i<<12)|0,i=i^-949894596^i>>>19,i=i+374761393+(i<<5)|0,i=i+-744332180^i<<9,i=i+-42973499+(i<<3)|0,i^-1252372727^i>>>16|0},util.readU64=function(i,t){var n=0;return n|=i[t++]<<0,n|=i[t++]<<8,n|=i[t++]<<16,n|=i[t++]<<24,n|=i[t++]<<32,n|=i[t++]<<40,n|=i[t++]<<48,n|=i[t++]<<56,n},util.readU32=function(i,t){var n=0;return n|=i[t++]<<0,n|=i[t++]<<8,n|=i[t++]<<16,n|=i[t++]<<24,n},util.writeU32=function(i,t,n){i[t++]=n>>0&255,i[t++]=n>>8&255,i[t++]=n>>16&255,i[t++]=n>>24&255},util.imul=function(i,t){var n=i>>>16,a=i&65535,s=t>>>16,o=t&65535;return a*o+(n*o+a*s<<16)|0}),util}var hasRequiredXxh32;function requireXxh32(){if(hasRequiredXxh32)return xxh32;hasRequiredXxh32=1;var e=requireUtil(),i=2654435761,t=2246822519,n=3266489917,a=668265263,s=374761393;function o(v,k){return v=v|0,k=k|0,v>>>(32-k|0)|v<<k|0}function h(v,k,A){return v=v|0,k=k|0,A=A|0,e.imul(v>>>(32-k|0)|v<<k,A)|0}function f(v,k){return v=v|0,k=k|0,v>>>k^v|0}function l(v,k,A,T,$){return h(e.imul(k,A)+v,T,$)}function u(v,k,A){return h(v+e.imul(k[A],s),11,i)}function w(v,k,A){return l(v,e.readU32(k,A),n,17,a)}function _(v,k,A){return[l(v[0],e.readU32(k,A+0),t,13,i),l(v[1],e.readU32(k,A+4),t,13,i),l(v[2],e.readU32(k,A+8),t,13,i),l(v[3],e.readU32(k,A+12),t,13,i)]}function g(v,k,A,T){var $,D;if(D=T,T>=16){for($=[v+i+t,v+t,v,v-i];T>=16;)$=_($,k,A),A+=16,T-=16;$=o($[0],1)+o($[1],7)+o($[2],12)+o($[3],18)+D}else $=v+s+T>>>0;for(;T>=4;)$=w($,k,A),A+=4,T-=4;for(;T>0;)$=u($,k,A),A++,T--;return $=f(e.imul(f(e.imul(f($,15),t),13),n),16),$>>>0}return xxh32.hash=g,xxh32}var hasRequiredLz4;function requireLz4(){return hasRequiredLz4||(hasRequiredLz4=1,function(e){var i=requireXxh32(),t=requireUtil(),n=4,a=13,s=5,o=6,h=65536,f=4,l=(1<<f)-1,u=4,w=(1<<u)-1,_=G(5<<20),g=L(),v=407708164,k=4,A=8,T=16,$=64,D=192,C=2147483648,P=7,z=4,B=7,F={4:65536,5:262144,6:1048576,7:4194304};function L(){try{return new Uint32Array(h)}catch{for(var J=new Array(h),Q=0;Q<h;Q++)J[Q]=0;return J}}function N(J){for(var Q=0;Q<h;Q++)g[Q]=0}function G(J){try{return new Uint8Array(J)}catch{for(var Q=new Array(J),W=0;W<J;W++)Q[W]=0;return Q}}function V(J,Q,W){if(typeof J.buffer!==void 0){if(Uint8Array.prototype.slice)return J.slice(Q,W);var ne=J.length;Q=Q|0,Q=Q<0?Math.max(ne+Q,0):Math.min(Q,ne),W=W===void 0?ne:W|0,W=W<0?Math.max(ne+W,0):Math.min(W,ne);for(var me=new Uint8Array(W-Q),ve=Q,ye=0;ve<W;)me[ye++]=J[ve++];return me}else return J.slice(Q,W)}e.compressBound=function(Q){return Q+Q/255+16|0},e.decompressBound=function(Q){var W=0;if(t.readU32(Q,W)!==v)throw new Error("invalid magic number");W+=4;var ne=Q[W++];if((ne&D)!==$)throw new Error("incompatible descriptor version "+(ne&D));var me=(ne&T)!==0,ve=(ne&A)!==0,ye=Q[W++]>>z&B;if(F[ye]===void 0)throw new Error("invalid block size "+ye);var Me=F[ye];if(ve)return t.readU64(Q,W);W++;for(var Re=0;;){var _e=t.readU32(Q,W);if(W+=4,_e&C?(_e&=2147483647,Re+=_e):Re+=Me,_e===0)return Re;me&&(W+=4),W+=_e}},e.makeBuffer=G,e.decompressBlock=function(Q,W,ne,me,ve){var ye,Me,Re,_e,Be;for(Re=ne+me;ne<Re;){var Se=Q[ne++],re=Se>>4;if(re>0){if(re===15)for(;re+=Q[ne],Q[ne++]===255;);for(_e=ne+re;ne<_e;)W[ve++]=Q[ne++]}if(ne>=Re)break;if(ye=Se&15,Me=Q[ne++]|Q[ne++]<<8,ye===15)for(;ye+=Q[ne],Q[ne++]===255;);for(ye+=n,Be=ve-Me,_e=Be+ye;Be<_e;)W[ve++]=W[Be++]|0}return ve},e.compressBlock=function(Q,W,ne,me,ve){var ye,Me,Re,_e,Be,Se,re,Ie,Fe;if(re=0,Ie=me+ne,Me=ne,me>=a)for(var ke=(1<<o)+3;ne+n<Ie-s;){var Ye=t.readU32(Q,ne),Je=t.hashU32(Ye)>>>0;if(Je=(Je>>16^Je)>>>0&65535,ye=ve[Je]-1,ve[Je]=ne+1,ye<0||ne-ye>>>16>0||t.readU32(Q,ye)!==Ye){Be=ke++>>o,ne+=Be;continue}for(ke=(1<<o)+3,Se=ne-Me,_e=ne-ye,ne+=n,ye+=n,Re=ne;ne<Ie-s&&Q[ne]===Q[ye];)ne++,ye++;Re=ne-Re;var et=Re<l?Re:l;if(Se>=w){for(W[re++]=(w<<f)+et,Fe=Se-w;Fe>=255;Fe-=255)W[re++]=255;W[re++]=Fe}else W[re++]=(Se<<f)+et;for(var Ve=0;Ve<Se;Ve++)W[re++]=Q[Me+Ve];if(W[re++]=_e,W[re++]=_e>>8,Re>=l){for(Fe=Re-l;Fe>=255;Fe-=255)W[re++]=255;W[re++]=Fe}Me=ne}if(Me===0)return 0;if(Se=Ie-Me,Se>=w){for(W[re++]=w<<f,Fe=Se-w;Fe>=255;Fe-=255)W[re++]=255;W[re++]=Fe}else W[re++]=Se<<f;for(ne=Me;ne<Ie;)W[re++]=Q[ne++];return re},e.decompressFrame=function(Q,W){var ne,me,ve,ye,Me=0,Re=0;if(t.readU32(Q,Me)!==v)throw new Error("invalid magic number");if(Me+=4,ye=Q[Me++],(ye&D)!==$)throw new Error("incompatible descriptor version");ne=(ye&T)!==0,me=(ye&k)!==0,ve=(ye&A)!==0;var _e=Q[Me++]>>z&B;if(F[_e]===void 0)throw new Error("invalid block size");for(ve&&(Me+=8),Me++;;){var Be;if(Be=t.readU32(Q,Me),Me+=4,Be===0)break;if(ne&&(Me+=4),(Be&C)!==0){Be&=2147483647;for(var Se=0;Se<Be;Se++)W[Re++]=Q[Me++]}else Re=e.decompressBlock(Q,W,Me,Be,Re),Me+=Be}return me&&(Me+=4),Re},e.compressFrame=function(Q,W){var ne=0;t.writeU32(W,ne,v),ne+=4,W[ne++]=$,W[ne++]=P<<z,W[ne]=i.hash(0,W,4,ne-4)>>8,ne++;var me=F[P],ve=Q.length,ye=0;for(N();ve>0;){var Me=0,Re=ve>me?me:ve;if(Me=e.compressBlock(Q,_,ye,Re,g),Me>Re||Me===0){t.writeU32(W,ne,2147483648|Re),ne+=4;for(var _e=ye+Re;ye<_e;)W[ne++]=Q[ye++];ve-=Re}else{t.writeU32(W,ne,Me),ne+=4;for(var Be=0;Be<Me;)W[ne++]=_[Be++];ye+=Re,ve-=Re}}return t.writeU32(W,ne,0),ne+=4,ne},e.decompress=function(Q,W){var ne,me;return W===void 0&&(W=e.decompressBound(Q)),ne=e.makeBuffer(W),me=e.decompressFrame(Q,ne),me!==W&&(ne=V(ne,0,me)),ne},e.compress=function(Q,W){var ne,me;return W===void 0&&(W=e.compressBound(Q.length)),ne=e.makeBuffer(W),me=e.compressFrame(Q,ne),me!==W&&(ne=V(ne,0,me)),ne}}(lz4$1)),lz4$1}var lz4Exports=requireLz4();const lz4=getDefaultExportFromCjs(lz4Exports);var __defProp=Object.defineProperty,__defNormalProp=(e,i,t)=>i in e?__defProp(e,i,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[i]=t,__export=(e,i)=>{for(var t in i)__defProp(e,t,{get:i[t],enumerable:!0})},__publicField=(e,i,t)=>(__defNormalProp(e,typeof i!="symbol"?i+"":i,t),t),constants_exports={};__export(constants_exports,{bt709:()=>bt709_exports});var bt709_exports={};__export(bt709_exports,{Y:()=>Y,x:()=>x,y:()=>y});var Y=(e=>(e[e.RED=.2126]="RED",e[e.GREEN=.7152]="GREEN",e[e.BLUE=.0722]="BLUE",e[e.WHITE=1]="WHITE",e))(Y||{}),x=(e=>(e[e.RED=.64]="RED",e[e.GREEN=.3]="GREEN",e[e.BLUE=.15]="BLUE",e[e.WHITE=.3127]="WHITE",e))(x||{}),y=(e=>(e[e.RED=.33]="RED",e[e.GREEN=.6]="GREEN",e[e.BLUE=.06]="BLUE",e[e.WHITE=.329]="WHITE",e))(y||{}),conversion_exports={};__export(conversion_exports,{lab2rgb:()=>lab2rgb,lab2xyz:()=>lab2xyz,rgb2hsl:()=>rgb2hsl,rgb2lab:()=>rgb2lab,rgb2xyz:()=>rgb2xyz,xyz2lab:()=>xyz2lab,xyz2rgb:()=>xyz2rgb});function correctGamma(e){return e>.04045?((e+.055)/1.055)**2.4:e/12.92}function rgb2xyz(e,i,t){return e=correctGamma(e/255),i=correctGamma(i/255),t=correctGamma(t/255),{x:e*.4124+i*.3576+t*.1805,y:e*.2126+i*.7152+t*.0722,z:e*.0193+i*.1192+t*.9505}}var arithmetic_exports={};__export(arithmetic_exports,{degrees2radians:()=>degrees2radians,inRange0to255:()=>inRange0to255,inRange0to255Rounded:()=>inRange0to255Rounded,intInRange:()=>intInRange,max3:()=>max3,min3:()=>min3,stableSort:()=>stableSort});function degrees2radians(e){return e*(Math.PI/180)}function max3(e,i,t){let n=e;return n<i&&(n=i),n<t&&(n=t),n}function min3(e,i,t){let n=e;return n>i&&(n=i),n>t&&(n=t),n}function intInRange(e,i,t){return e>t&&(e=t),e<i&&(e=i),e|0}function inRange0to255Rounded(e){return e=Math.round(e),e>255?e=255:e<0&&(e=0),e}function inRange0to255(e){return e>255?e=255:e<0&&(e=0),e}function stableSort(e,i){const t=typeof e[0];let n;if(t==="number"||t==="string"){const a=Object.create(null);for(let s=0,o=e.length;s<o;s++){const h=e[s];a[h]||a[h]===0||(a[h]=s)}n=e.sort((s,o)=>i(s,o)||a[s]-a[o])}else{const a=e.slice(0);n=e.sort((s,o)=>i(s,o)||a.indexOf(s)-a.indexOf(o))}return n}function rgb2hsl(e,i,t){const n=min3(e,i,t),a=max3(e,i,t),s=a-n,o=(n+a)/510;let h=0;o>0&&o<1&&(h=s/(o<.5?a+n:510-a-n));let f=0;return s>0&&(a===e?f=(i-t)/s:a===i?f=2+(t-e)/s:f=4+(e-i)/s,f*=60,f<0&&(f+=360)),{h:f,s:h,l:o}}var refX=.95047,refY=1,refZ=1.08883;function pivot(e){return e>.008856?e**(1/3):7.787*e+16/116}function xyz2lab(e,i,t){if(e=pivot(e/refX),i=pivot(i/refY),t=pivot(t/refZ),116*i-16<0)throw new Error("xxx");return{L:Math.max(0,116*i-16),a:500*(e-i),b:200*(i-t)}}function rgb2lab(e,i,t){const n=rgb2xyz(e,i,t);return xyz2lab(n.x,n.y,n.z)}var refX2=.95047,refY2=1,refZ2=1.08883;function pivot2(e){return e>.206893034?e**3:(e-16/116)/7.787}function lab2xyz(e,i,t){const n=(e+16)/116,a=i/500+n,s=n-t/200;return{x:refX2*pivot2(a),y:refY2*pivot2(n),z:refZ2*pivot2(s)}}function correctGamma2(e){return e>.0031308?1.055*e**(1/2.4)-.055:12.92*e}function xyz2rgb(e,i,t){const n=correctGamma2(e*3.2406+i*-1.5372+t*-.4986),a=correctGamma2(e*-.9689+i*1.8758+t*.0415),s=correctGamma2(e*.0557+i*-.204+t*1.057);return{r:inRange0to255Rounded(n*255),g:inRange0to255Rounded(a*255),b:inRange0to255Rounded(s*255)}}function lab2rgb(e,i,t){const n=lab2xyz(e,i,t);return xyz2rgb(n.x,n.y,n.z)}var distance_exports={};__export(distance_exports,{AbstractDistanceCalculator:()=>AbstractDistanceCalculator,AbstractEuclidean:()=>AbstractEuclidean,AbstractManhattan:()=>AbstractManhattan,CIE94GraphicArts:()=>CIE94GraphicArts,CIE94Textiles:()=>CIE94Textiles,CIEDE2000:()=>CIEDE2000,CMetric:()=>CMetric,Euclidean:()=>Euclidean,EuclideanBT709:()=>EuclideanBT709,EuclideanBT709NoAlpha:()=>EuclideanBT709NoAlpha,Manhattan:()=>Manhattan,ManhattanBT709:()=>ManhattanBT709,ManhattanNommyde:()=>ManhattanNommyde,PNGQuant:()=>PNGQuant});var AbstractDistanceCalculator=class{constructor(){__publicField(this,"_maxDistance"),__publicField(this,"_whitePoint"),this._setDefaults(),this.setWhitePoint(255,255,255,255)}setWhitePoint(e,i,t,n){this._whitePoint={r:e>0?255/e:0,g:i>0?255/i:0,b:t>0?255/t:0,a:n>0?255/n:0},this._maxDistance=this.calculateRaw(e,i,t,n,0,0,0,0)}calculateNormalized(e,i){return this.calculateRaw(e.r,e.g,e.b,e.a,i.r,i.g,i.b,i.a)/this._maxDistance}},AbstractCIE94=class extends AbstractDistanceCalculator{calculateRaw(e,i,t,n,a,s,o,h){const f=rgb2lab(inRange0to255(e*this._whitePoint.r),inRange0to255(i*this._whitePoint.g),inRange0to255(t*this._whitePoint.b)),l=rgb2lab(inRange0to255(a*this._whitePoint.r),inRange0to255(s*this._whitePoint.g),inRange0to255(o*this._whitePoint.b)),u=f.L-l.L,w=f.a-l.a,_=f.b-l.b,g=Math.sqrt(f.a*f.a+f.b*f.b),v=Math.sqrt(l.a*l.a+l.b*l.b),k=g-v;let A=w*w+_*_-k*k;A=A<0?0:Math.sqrt(A);const T=(h-n)*this._whitePoint.a*this._kA;return Math.sqrt((u/this._Kl)**2+(k/(1+this._K1*g))**2+(A/(1+this._K2*g))**2+T**2)}},CIE94Textiles=class extends AbstractCIE94{_setDefaults(){this._Kl=2,this._K1=.048,this._K2=.014,this._kA=.25*50/255}},CIE94GraphicArts=class extends AbstractCIE94{_setDefaults(){this._Kl=1,this._K1=.045,this._K2=.015,this._kA=.25*100/255}},_CIEDE2000=class extends AbstractDistanceCalculator{_setDefaults(){}static _calculatehp(e,i){const t=Math.atan2(e,i);return t>=0?t:t+_CIEDE2000._deg360InRad}static _calculateRT(e,i){const t=i**7,n=2*Math.sqrt(t/(t+_CIEDE2000._pow25to7)),a=_CIEDE2000._deg30InRad*Math.exp(-(((e-_CIEDE2000._deg275InRad)/_CIEDE2000._deg25InRad)**2));return-Math.sin(2*a)*n}static _calculateT(e){return 1-.17*Math.cos(e-_CIEDE2000._deg30InRad)+.24*Math.cos(e*2)+.32*Math.cos(e*3+_CIEDE2000._deg6InRad)-.2*Math.cos(e*4-_CIEDE2000._deg63InRad)}static _calculate_ahp(e,i,t,n){const a=t+n;return e===0?a:i<=_CIEDE2000._deg180InRad?a/2:a<_CIEDE2000._deg360InRad?(a+_CIEDE2000._deg360InRad)/2:(a-_CIEDE2000._deg360InRad)/2}static _calculate_dHp(e,i,t,n){let a;return e===0?a=0:i<=_CIEDE2000._deg180InRad?a=t-n:t<=n?a=t-n+_CIEDE2000._deg360InRad:a=t-n-_CIEDE2000._deg360InRad,2*Math.sqrt(e)*Math.sin(a/2)}calculateRaw(e,i,t,n,a,s,o,h){const f=rgb2lab(inRange0to255(e*this._whitePoint.r),inRange0to255(i*this._whitePoint.g),inRange0to255(t*this._whitePoint.b)),l=rgb2lab(inRange0to255(a*this._whitePoint.r),inRange0to255(s*this._whitePoint.g),inRange0to255(o*this._whitePoint.b)),u=(h-n)*this._whitePoint.a*_CIEDE2000._kA,w=this.calculateRawInLab(f,l);return Math.sqrt(w+u*u)}calculateRawInLab(e,i){const t=e.L,n=e.a,a=e.b,s=i.L,o=i.a,h=i.b,f=Math.sqrt(n*n+a*a),l=Math.sqrt(o*o+h*h),u=((f+l)/2)**7,w=.5*(1-Math.sqrt(u/(u+_CIEDE2000._pow25to7))),_=(1+w)*n,g=(1+w)*o,v=Math.sqrt(_*_+a*a),k=Math.sqrt(g*g+h*h),A=v*k,T=_CIEDE2000._calculatehp(a,_),$=_CIEDE2000._calculatehp(h,g),D=Math.abs(T-$),C=s-t,P=k-v,z=_CIEDE2000._calculate_dHp(A,D,$,T),B=_CIEDE2000._calculate_ahp(A,D,T,$),F=_CIEDE2000._calculateT(B),L=(v+k)/2,N=((t+s)/2-50)**2,G=1+.015*N/Math.sqrt(20+N),V=1+.045*L,J=1+.015*F*L,Q=_CIEDE2000._calculateRT(B,L),W=C/G,ne=P/V,me=z/J;return W**2+ne**2+me**2+Q*ne*me}},CIEDE2000=_CIEDE2000;__publicField(CIEDE2000,"_kA",.25*100/255),__publicField(CIEDE2000,"_pow25to7",25**7),__publicField(CIEDE2000,"_deg360InRad",degrees2radians(360)),__publicField(CIEDE2000,"_deg180InRad",degrees2radians(180)),__publicField(CIEDE2000,"_deg30InRad",degrees2radians(30)),__publicField(CIEDE2000,"_deg6InRad",degrees2radians(6)),__publicField(CIEDE2000,"_deg63InRad",degrees2radians(63)),__publicField(CIEDE2000,"_deg275InRad",degrees2radians(275)),__publicField(CIEDE2000,"_deg25InRad",degrees2radians(25));var CMetric=class extends AbstractDistanceCalculator{calculateRaw(e,i,t,n,a,s,o,h){const f=(e+a)/2*this._whitePoint.r,l=(e-a)*this._whitePoint.r,u=(i-s)*this._whitePoint.g,w=(t-o)*this._whitePoint.b,_=((512+f)*l*l>>8)+4*u*u+((767-f)*w*w>>8),g=(h-n)*this._whitePoint.a;return Math.sqrt(_+g*g)}_setDefaults(){}},AbstractEuclidean=class extends AbstractDistanceCalculator{calculateRaw(e,i,t,n,a,s,o,h){const f=a-e,l=s-i,u=o-t,w=h-n;return Math.sqrt(this._kR*f*f+this._kG*l*l+this._kB*u*u+this._kA*w*w)}},Euclidean=class extends AbstractEuclidean{_setDefaults(){this._kR=1,this._kG=1,this._kB=1,this._kA=1}},EuclideanBT709=class extends AbstractEuclidean{_setDefaults(){this._kR=.2126,this._kG=.7152,this._kB=.0722,this._kA=1}},EuclideanBT709NoAlpha=class extends AbstractEuclidean{_setDefaults(){this._kR=.2126,this._kG=.7152,this._kB=.0722,this._kA=0}},AbstractManhattan=class extends AbstractDistanceCalculator{calculateRaw(e,i,t,n,a,s,o,h){let f=a-e,l=s-i,u=o-t,w=h-n;return f<0&&(f=0-f),l<0&&(l=0-l),u<0&&(u=0-u),w<0&&(w=0-w),this._kR*f+this._kG*l+this._kB*u+this._kA*w}},Manhattan=class extends AbstractManhattan{_setDefaults(){this._kR=1,this._kG=1,this._kB=1,this._kA=1}},ManhattanNommyde=class extends AbstractManhattan{_setDefaults(){this._kR=.4984,this._kG=.8625,this._kB=.2979,this._kA=1}},ManhattanBT709=class extends AbstractManhattan{_setDefaults(){this._kR=.2126,this._kG=.7152,this._kB=.0722,this._kA=1}},PNGQuant=class extends AbstractDistanceCalculator{calculateRaw(e,i,t,n,a,s,o,h){const f=(h-n)*this._whitePoint.a;return this._colordifferenceCh(e*this._whitePoint.r,a*this._whitePoint.r,f)+this._colordifferenceCh(i*this._whitePoint.g,s*this._whitePoint.g,f)+this._colordifferenceCh(t*this._whitePoint.b,o*this._whitePoint.b,f)}_colordifferenceCh(e,i,t){const n=e-i,a=n+t;return n*n+a*a}_setDefaults(){}},palette_exports={};__export(palette_exports,{AbstractPaletteQuantizer:()=>AbstractPaletteQuantizer,ColorHistogram:()=>ColorHistogram,NeuQuant:()=>NeuQuant,NeuQuantFloat:()=>NeuQuantFloat,RGBQuant:()=>RGBQuant,WuColorCube:()=>WuColorCube,WuQuant:()=>WuQuant});var AbstractPaletteQuantizer=class{quantizeSync(){for(const e of this.quantize())if(e.palette)return e.palette;throw new Error("unreachable")}},Point=class{constructor(){__publicField(this,"r"),__publicField(this,"g"),__publicField(this,"b"),__publicField(this,"a"),__publicField(this,"uint32"),__publicField(this,"rgba"),this.uint32=-1>>>0,this.r=this.g=this.b=this.a=0,this.rgba=new Array(4),this.rgba[0]=0,this.rgba[1]=0,this.rgba[2]=0,this.rgba[3]=0}static createByQuadruplet(e){const i=new Point;return i.r=e[0]|0,i.g=e[1]|0,i.b=e[2]|0,i.a=e[3]|0,i._loadUINT32(),i._loadQuadruplet(),i}static createByRGBA(e,i,t,n){const a=new Point;return a.r=e|0,a.g=i|0,a.b=t|0,a.a=n|0,a._loadUINT32(),a._loadQuadruplet(),a}static createByUint32(e){const i=new Point;return i.uint32=e>>>0,i._loadRGBA(),i._loadQuadruplet(),i}from(e){this.r=e.r,this.g=e.g,this.b=e.b,this.a=e.a,this.uint32=e.uint32,this.rgba[0]=e.r,this.rgba[1]=e.g,this.rgba[2]=e.b,this.rgba[3]=e.a}getLuminosity(e){let i=this.r,t=this.g,n=this.b;return e&&(i=Math.min(255,255-this.a+this.a*i/255),t=Math.min(255,255-this.a+this.a*t/255),n=Math.min(255,255-this.a+this.a*n/255)),i*.2126+t*.7152+n*.0722}_loadUINT32(){this.uint32=(this.a<<24|this.b<<16|this.g<<8|this.r)>>>0}_loadRGBA(){this.r=this.uint32&255,this.g=this.uint32>>>8&255,this.b=this.uint32>>>16&255,this.a=this.uint32>>>24&255}_loadQuadruplet(){this.rgba[0]=this.r,this.rgba[1]=this.g,this.rgba[2]=this.b,this.rgba[3]=this.a}},PointContainer=class{constructor(){__publicField(this,"_pointArray"),__publicField(this,"_width"),__publicField(this,"_height"),this._width=0,this._height=0,this._pointArray=[]}getWidth(){return this._width}getHeight(){return this._height}setWidth(e){this._width=e}setHeight(e){this._height=e}getPointArray(){return this._pointArray}clone(){const e=new PointContainer;e._width=this._width,e._height=this._height;for(let i=0,t=this._pointArray.length;i<t;i++)e._pointArray[i]=Point.createByUint32(this._pointArray[i].uint32|0);return e}toUint32Array(){const e=this._pointArray.length,i=new Uint32Array(e);for(let t=0;t<e;t++)i[t]=this._pointArray[t].uint32;return i}toUint8Array(){return new Uint8Array(this.toUint32Array().buffer)}static fromHTMLImageElement(e){const i=e.naturalWidth,t=e.naturalHeight,n=document.createElement("canvas");return n.width=i,n.height=t,n.getContext("2d").drawImage(e,0,0,i,t,0,0,i,t),PointContainer.fromHTMLCanvasElement(n)}static fromHTMLCanvasElement(e){const i=e.width,t=e.height,a=e.getContext("2d").getImageData(0,0,i,t);return PointContainer.fromImageData(a)}static fromImageData(e){const i=e.width,t=e.height;return PointContainer.fromUint8Array(e.data,i,t)}static fromUint8Array(e,i,t){switch(Object.prototype.toString.call(e)){case"[object Uint8ClampedArray]":case"[object Uint8Array]":break;default:e=new Uint8Array(e)}const n=new Uint32Array(e.buffer);return PointContainer.fromUint32Array(n,i,t)}static fromUint32Array(e,i,t){const n=new PointContainer;n._width=i,n._height=t;for(let a=0,s=e.length;a<s;a++)n._pointArray[a]=Point.createByUint32(e[a]|0);return n}static fromBuffer(e,i,t){const n=new Uint32Array(e.buffer,e.byteOffset,e.byteLength/Uint32Array.BYTES_PER_ELEMENT);return PointContainer.fromUint32Array(n,i,t)}},hueGroups=10;function hueGroup(e,i){const n=360/i,a=n/2;for(let s=1,o=n-a;s<i;s++,o+=n)if(e>=o&&e<o+n)return s;return 0}var Palette=class{constructor(){__publicField(this,"_pointContainer"),__publicField(this,"_pointArray",[]),__publicField(this,"_i32idx",{}),this._pointContainer=new PointContainer,this._pointContainer.setHeight(1),this._pointArray=this._pointContainer.getPointArray()}add(e){this._pointArray.push(e),this._pointContainer.setWidth(this._pointArray.length)}has(e){for(let i=this._pointArray.length-1;i>=0;i--)if(e.uint32===this._pointArray[i].uint32)return!0;return!1}getNearestColor(e,i){return this._pointArray[this._getNearestIndex(e,i)|0]}getPointContainer(){return this._pointContainer}_nearestPointFromCache(e){return typeof this._i32idx[e]=="number"?this._i32idx[e]:-1}_getNearestIndex(e,i){let t=this._nearestPointFromCache(""+i.uint32);if(t>=0)return t;let n=Number.MAX_VALUE;t=0;for(let a=0,s=this._pointArray.length;a<s;a++){const o=this._pointArray[a],h=e.calculateRaw(i.r,i.g,i.b,i.a,o.r,o.g,o.b,o.a);h<n&&(n=h,t=a)}return this._i32idx[i.uint32]=t,t}sort(){this._i32idx={},this._pointArray.sort((e,i)=>{const t=rgb2hsl(e.r,e.g,e.b),n=rgb2hsl(i.r,i.g,i.b),a=e.r===e.g&&e.g===e.b?0:1+hueGroup(t.h,hueGroups),o=(i.r===i.g&&i.g===i.b?0:1+hueGroup(n.h,hueGroups))-a;if(o)return-o;const h=e.getLuminosity(!0),f=i.getLuminosity(!0);if(f-h!==0)return f-h;const l=(n.s*100|0)-(t.s*100|0);return l?-l:0})}},utils_exports={};__export(utils_exports,{HueStatistics:()=>HueStatistics,Palette:()=>Palette,Point:()=>Point,PointContainer:()=>PointContainer,ProgressTracker:()=>ProgressTracker,arithmetic:()=>arithmetic_exports});var HueGroup=class{constructor(){__publicField(this,"num",0),__publicField(this,"cols",[])}},HueStatistics=class{constructor(e,i){__publicField(this,"_numGroups"),__publicField(this,"_minCols"),__publicField(this,"_stats"),__publicField(this,"_groupsFull"),this._numGroups=e,this._minCols=i,this._stats=[];for(let t=0;t<=e;t++)this._stats[t]=new HueGroup;this._groupsFull=0}check(e){this._groupsFull===this._numGroups+1&&(this.check=()=>{});const i=e&255,t=e>>>8&255,n=e>>>16&255,a=i===t&&t===n?0:1+hueGroup(rgb2hsl(i,t,n).h,this._numGroups),s=this._stats[a],o=this._minCols;s.num++,!(s.num>o)&&(s.num===o&&this._groupsFull++,s.num<=o&&this._stats[a].cols.push(e))}injectIntoDictionary(e){for(let i=0;i<=this._numGroups;i++)this._stats[i].num<=this._minCols&&this._stats[i].cols.forEach(t=>{e[t]?e[t]++:e[t]=1})}injectIntoArray(e){for(let i=0;i<=this._numGroups;i++)this._stats[i].num<=this._minCols&&this._stats[i].cols.forEach(t=>{e.indexOf(t)===-1&&e.push(t)})}},_ProgressTracker=class{constructor(e,i){__publicField(this,"progress"),__publicField(this,"_step"),__publicField(this,"_range"),__publicField(this,"_last"),__publicField(this,"_progressRange"),this._range=e,this._progressRange=i,this._step=Math.max(1,this._range/(_ProgressTracker.steps+1)|0),this._last=-this._step,this.progress=0}shouldNotify(e){return e-this._last>=this._step?(this._last=e,this.progress=Math.min(this._progressRange*this._last/this._range,this._progressRange),!0):!1}},ProgressTracker=_ProgressTracker;__publicField(ProgressTracker,"steps",100);var networkBiasShift=3,Neuron=class{constructor(e){__publicField(this,"r"),__publicField(this,"g"),__publicField(this,"b"),__publicField(this,"a"),this.r=this.g=this.b=this.a=e}toPoint(){return Point.createByRGBA(this.r>>networkBiasShift,this.g>>networkBiasShift,this.b>>networkBiasShift,this.a>>networkBiasShift)}subtract(e,i,t,n){this.r-=e|0,this.g-=i|0,this.b-=t|0,this.a-=n|0}},_NeuQuant=class extends AbstractPaletteQuantizer{constructor(e,i=256){super(),__publicField(this,"_pointArray"),__publicField(this,"_networkSize"),__publicField(this,"_network"),__publicField(this,"_sampleFactor"),__publicField(this,"_radPower"),__publicField(this,"_freq"),__publicField(this,"_bias"),__publicField(this,"_distance"),this._distance=e,this._pointArray=[],this._sampleFactor=1,this._networkSize=i,this._distance.setWhitePoint(255<<networkBiasShift,255<<networkBiasShift,255<<networkBiasShift,255<<networkBiasShift)}sample(e){this._pointArray=this._pointArray.concat(e.getPointArray())}*quantize(){this._init(),yield*this._learn(),yield{palette:this._buildPalette(),progress:100}}_init(){this._freq=[],this._bias=[],this._radPower=[],this._network=[];for(let e=0;e<this._networkSize;e++)this._network[e]=new Neuron((e<<networkBiasShift+8)/this._networkSize|0),this._freq[e]=_NeuQuant._initialBias/this._networkSize|0,this._bias[e]=0}*_learn(){let e=this._sampleFactor;const i=this._pointArray.length;i<_NeuQuant._minpicturebytes&&(e=1);const t=30+(e-1)/3|0,n=i/e|0;let a=n/_NeuQuant._nCycles|0,s=_NeuQuant._initAlpha,o=(this._networkSize>>3)*_NeuQuant._radiusBias,h=o>>_NeuQuant._radiusBiasShift;h<=1&&(h=0);for(let u=0;u<h;u++)this._radPower[u]=s*((h*h-u*u)*_NeuQuant._radBias/(h*h))>>>0;let f;i<_NeuQuant._minpicturebytes?f=1:i%_NeuQuant._prime1!==0?f=_NeuQuant._prime1:i%_NeuQuant._prime2!==0?f=_NeuQuant._prime2:i%_NeuQuant._prime3!==0?f=_NeuQuant._prime3:f=_NeuQuant._prime4;const l=new ProgressTracker(n,99);for(let u=0,w=0;u<n;){l.shouldNotify(u)&&(yield{progress:l.progress});const _=this._pointArray[w],g=_.b<<networkBiasShift,v=_.g<<networkBiasShift,k=_.r<<networkBiasShift,A=_.a<<networkBiasShift,T=this._contest(g,v,k,A);if(this._alterSingle(s,T,g,v,k,A),h!==0&&this._alterNeighbour(h,T,g,v,k,A),w+=f,w>=i&&(w-=i),u++,a===0&&(a=1),u%a===0){s-=s/t|0,o-=o/_NeuQuant._radiusDecrease|0,h=o>>_NeuQuant._radiusBiasShift,h<=1&&(h=0);for(let $=0;$<h;$++)this._radPower[$]=s*((h*h-$*$)*_NeuQuant._radBias/(h*h))>>>0}}}_buildPalette(){const e=new Palette;return this._network.forEach(i=>{e.add(i.toPoint())}),e.sort(),e}_alterNeighbour(e,i,t,n,a,s){let o=i-e;o<-1&&(o=-1);let h=i+e;h>this._networkSize&&(h=this._networkSize);let f=i+1,l=i-1,u=1;for(;f<h||l>o;){const w=this._radPower[u++]/_NeuQuant._alphaRadBias;if(f<h){const _=this._network[f++];_.subtract(w*(_.r-a),w*(_.g-n),w*(_.b-t),w*(_.a-s))}if(l>o){const _=this._network[l--];_.subtract(w*(_.r-a),w*(_.g-n),w*(_.b-t),w*(_.a-s))}}}_alterSingle(e,i,t,n,a,s){e/=_NeuQuant._initAlpha;const o=this._network[i];o.subtract(e*(o.r-a),e*(o.g-n),e*(o.b-t),e*(o.a-s))}_contest(e,i,t,n){const a=1020<<networkBiasShift;let s=2147483647,o=s,h=-1,f=h;for(let l=0;l<this._networkSize;l++){const u=this._network[l],w=this._distance.calculateNormalized(u,{r:t,g:i,b:e,a:n})*a|0;w<s&&(s=w,h=l);const _=w-(this._bias[l]>>_NeuQuant._initialBiasShift-networkBiasShift);_<o&&(o=_,f=l);const g=this._freq[l]>>_NeuQuant._betaShift;this._freq[l]-=g,this._bias[l]+=g<<_NeuQuant._gammaShift}return this._freq[h]+=_NeuQuant._beta,this._bias[h]-=_NeuQuant._betaGamma,f}},NeuQuant=_NeuQuant;__publicField(NeuQuant,"_prime1",499),__publicField(NeuQuant,"_prime2",491),__publicField(NeuQuant,"_prime3",487),__publicField(NeuQuant,"_prime4",503),__publicField(NeuQuant,"_minpicturebytes",_NeuQuant._prime4),__publicField(NeuQuant,"_nCycles",100),__publicField(NeuQuant,"_initialBiasShift",16),__publicField(NeuQuant,"_initialBias",1<<_NeuQuant._initialBiasShift),__publicField(NeuQuant,"_gammaShift",10),__publicField(NeuQuant,"_betaShift",10),__publicField(NeuQuant,"_beta",_NeuQuant._initialBias>>_NeuQuant._betaShift),__publicField(NeuQuant,"_betaGamma",_NeuQuant._initialBias<<_NeuQuant._gammaShift-_NeuQuant._betaShift),__publicField(NeuQuant,"_radiusBiasShift",6),__publicField(NeuQuant,"_radiusBias",1<<_NeuQuant._radiusBiasShift),__publicField(NeuQuant,"_radiusDecrease",30),__publicField(NeuQuant,"_alphaBiasShift",10),__publicField(NeuQuant,"_initAlpha",1<<_NeuQuant._alphaBiasShift),__publicField(NeuQuant,"_radBiasShift",8),__publicField(NeuQuant,"_radBias",1<<_NeuQuant._radBiasShift),__publicField(NeuQuant,"_alphaRadBiasShift",_NeuQuant._alphaBiasShift+_NeuQuant._radBiasShift),__publicField(NeuQuant,"_alphaRadBias",1<<_NeuQuant._alphaRadBiasShift);var networkBiasShift2=3,NeuronFloat=class{constructor(e){__publicField(this,"r"),__publicField(this,"g"),__publicField(this,"b"),__publicField(this,"a"),this.r=this.g=this.b=this.a=e}toPoint(){return Point.createByRGBA(this.r>>networkBiasShift2,this.g>>networkBiasShift2,this.b>>networkBiasShift2,this.a>>networkBiasShift2)}subtract(e,i,t,n){this.r-=e,this.g-=i,this.b-=t,this.a-=n}},_NeuQuantFloat=class extends AbstractPaletteQuantizer{constructor(e,i=256){super(),__publicField(this,"_pointArray"),__publicField(this,"_networkSize"),__publicField(this,"_network"),__publicField(this,"_sampleFactor"),__publicField(this,"_radPower"),__publicField(this,"_freq"),__publicField(this,"_bias"),__publicField(this,"_distance"),this._distance=e,this._pointArray=[],this._sampleFactor=1,this._networkSize=i,this._distance.setWhitePoint(255<<networkBiasShift2,255<<networkBiasShift2,255<<networkBiasShift2,255<<networkBiasShift2)}sample(e){this._pointArray=this._pointArray.concat(e.getPointArray())}*quantize(){this._init(),yield*this._learn(),yield{palette:this._buildPalette(),progress:100}}_init(){this._freq=[],this._bias=[],this._radPower=[],this._network=[];for(let e=0;e<this._networkSize;e++)this._network[e]=new NeuronFloat((e<<networkBiasShift2+8)/this._networkSize),this._freq[e]=_NeuQuantFloat._initialBias/this._networkSize,this._bias[e]=0}*_learn(){let e=this._sampleFactor;const i=this._pointArray.length;i<_NeuQuantFloat._minpicturebytes&&(e=1);const t=30+(e-1)/3,n=i/e;let a=n/_NeuQuantFloat._nCycles|0,s=_NeuQuantFloat._initAlpha,o=(this._networkSize>>3)*_NeuQuantFloat._radiusBias,h=o>>_NeuQuantFloat._radiusBiasShift;h<=1&&(h=0);for(let u=0;u<h;u++)this._radPower[u]=s*((h*h-u*u)*_NeuQuantFloat._radBias/(h*h));let f;i<_NeuQuantFloat._minpicturebytes?f=1:i%_NeuQuantFloat._prime1!==0?f=_NeuQuantFloat._prime1:i%_NeuQuantFloat._prime2!==0?f=_NeuQuantFloat._prime2:i%_NeuQuantFloat._prime3!==0?f=_NeuQuantFloat._prime3:f=_NeuQuantFloat._prime4;const l=new ProgressTracker(n,99);for(let u=0,w=0;u<n;){l.shouldNotify(u)&&(yield{progress:l.progress});const _=this._pointArray[w],g=_.b<<networkBiasShift2,v=_.g<<networkBiasShift2,k=_.r<<networkBiasShift2,A=_.a<<networkBiasShift2,T=this._contest(g,v,k,A);if(this._alterSingle(s,T,g,v,k,A),h!==0&&this._alterNeighbour(h,T,g,v,k,A),w+=f,w>=i&&(w-=i),u++,a===0&&(a=1),u%a===0){s-=s/t,o-=o/_NeuQuantFloat._radiusDecrease,h=o>>_NeuQuantFloat._radiusBiasShift,h<=1&&(h=0);for(let $=0;$<h;$++)this._radPower[$]=s*((h*h-$*$)*_NeuQuantFloat._radBias/(h*h))}}}_buildPalette(){const e=new Palette;return this._network.forEach(i=>{e.add(i.toPoint())}),e.sort(),e}_alterNeighbour(e,i,t,n,a,s){let o=i-e;o<-1&&(o=-1);let h=i+e;h>this._networkSize&&(h=this._networkSize);let f=i+1,l=i-1,u=1;for(;f<h||l>o;){const w=this._radPower[u++]/_NeuQuantFloat._alphaRadBias;if(f<h){const _=this._network[f++];_.subtract(w*(_.r-a),w*(_.g-n),w*(_.b-t),w*(_.a-s))}if(l>o){const _=this._network[l--];_.subtract(w*(_.r-a),w*(_.g-n),w*(_.b-t),w*(_.a-s))}}}_alterSingle(e,i,t,n,a,s){e/=_NeuQuantFloat._initAlpha;const o=this._network[i];o.subtract(e*(o.r-a),e*(o.g-n),e*(o.b-t),e*(o.a-s))}_contest(e,i,t,n){const a=1020<<networkBiasShift2;let s=2147483647,o=s,h=-1,f=h;for(let l=0;l<this._networkSize;l++){const u=this._network[l],w=this._distance.calculateNormalized(u,{r:t,g:i,b:e,a:n})*a;w<s&&(s=w,h=l);const _=w-(this._bias[l]>>_NeuQuantFloat._initialBiasShift-networkBiasShift2);_<o&&(o=_,f=l);const g=this._freq[l]>>_NeuQuantFloat._betaShift;this._freq[l]-=g,this._bias[l]+=g<<_NeuQuantFloat._gammaShift}return this._freq[h]+=_NeuQuantFloat._beta,this._bias[h]-=_NeuQuantFloat._betaGamma,f}},NeuQuantFloat=_NeuQuantFloat;__publicField(NeuQuantFloat,"_prime1",499),__publicField(NeuQuantFloat,"_prime2",491),__publicField(NeuQuantFloat,"_prime3",487),__publicField(NeuQuantFloat,"_prime4",503),__publicField(NeuQuantFloat,"_minpicturebytes",_NeuQuantFloat._prime4),__publicField(NeuQuantFloat,"_nCycles",100),__publicField(NeuQuantFloat,"_initialBiasShift",16),__publicField(NeuQuantFloat,"_initialBias",1<<_NeuQuantFloat._initialBiasShift),__publicField(NeuQuantFloat,"_gammaShift",10),__publicField(NeuQuantFloat,"_betaShift",10),__publicField(NeuQuantFloat,"_beta",_NeuQuantFloat._initialBias>>_NeuQuantFloat._betaShift),__publicField(NeuQuantFloat,"_betaGamma",_NeuQuantFloat._initialBias<<_NeuQuantFloat._gammaShift-_NeuQuantFloat._betaShift),__publicField(NeuQuantFloat,"_radiusBiasShift",6),__publicField(NeuQuantFloat,"_radiusBias",1<<_NeuQuantFloat._radiusBiasShift),__publicField(NeuQuantFloat,"_radiusDecrease",30),__publicField(NeuQuantFloat,"_alphaBiasShift",10),__publicField(NeuQuantFloat,"_initAlpha",1<<_NeuQuantFloat._alphaBiasShift),__publicField(NeuQuantFloat,"_radBiasShift",8),__publicField(NeuQuantFloat,"_radBias",1<<_NeuQuantFloat._radBiasShift),__publicField(NeuQuantFloat,"_alphaRadBiasShift",_NeuQuantFloat._alphaBiasShift+_NeuQuantFloat._radBiasShift),__publicField(NeuQuantFloat,"_alphaRadBias",1<<_NeuQuantFloat._alphaRadBiasShift);var _ColorHistogram=class{constructor(e,i){__publicField(this,"_method"),__publicField(this,"_hueStats"),__publicField(this,"_histogram"),__publicField(this,"_initColors"),__publicField(this,"_minHueCols"),this._method=e,this._minHueCols=i<<2,this._initColors=i<<2,this._hueStats=new HueStatistics(_ColorHistogram._hueGroups,this._minHueCols),this._histogram=Object.create(null)}sample(e){switch(this._method){case 1:this._colorStats1D(e);break;case 2:this._colorStats2D(e);break}}getImportanceSortedColorsIDXI32(){const e=stableSort(Object.keys(this._histogram),(t,n)=>this._histogram[n]-this._histogram[t]);if(e.length===0)return[];let i;switch(this._method){case 1:const t=Math.min(e.length,this._initColors),n=e[t-1],a=this._histogram[n];i=e.slice(0,t);let s=t;const o=e.length;for(;s<o&&this._histogram[e[s]]===a;)i.push(e[s++]);this._hueStats.injectIntoArray(i);break;case 2:i=e;break;default:throw new Error("Incorrect method")}return i.map(t=>+t)}_colorStats1D(e){const i=this._histogram,t=e.getPointArray(),n=t.length;for(let a=0;a<n;a++){const s=t[a].uint32;this._hueStats.check(s),s in i?i[s]++:i[s]=1}}_colorStats2D(e){const i=e.getWidth(),t=e.getHeight(),n=e.getPointArray(),a=_ColorHistogram._boxSize[0],s=_ColorHistogram._boxSize[1],o=a*s,h=this._makeBoxes(i,t,a,s),f=this._histogram;h.forEach(l=>{let u=Math.round(l.w*l.h/o)*_ColorHistogram._boxPixels;u<2&&(u=2);const w={};this._iterateBox(l,i,_=>{const g=n[_].uint32;this._hueStats.check(g),g in f?f[g]++:g in w?++w[g]>=u&&(f[g]=w[g]):w[g]=1})}),this._hueStats.injectIntoDictionary(f)}_iterateBox(e,i,t){const n=e,a=n.y*i+n.x,s=(n.y+n.h-1)*i+(n.x+n.w-1),o=i-n.w+1;let h=0,f=a;do t.call(this,f),f+=++h%n.w===0?o:1;while(f<=s)}_makeBoxes(e,i,t,n){const a=e%t,s=i%n,o=e-a,h=i-s,f=[];for(let l=0;l<i;l+=n)for(let u=0;u<e;u+=t)f.push({x:u,y:l,w:u===o?a:t,h:l===h?s:n});return f}},ColorHistogram=_ColorHistogram;__publicField(ColorHistogram,"_boxSize",[64,64]),__publicField(ColorHistogram,"_boxPixels",2),__publicField(ColorHistogram,"_hueGroups",10);var RemovedColor=class{constructor(e,i,t){__publicField(this,"index"),__publicField(this,"color"),__publicField(this,"distance"),this.index=e,this.color=i,this.distance=t}},RGBQuant=class extends AbstractPaletteQuantizer{constructor(e,i=256,t=2){super(),__publicField(this,"_colors"),__publicField(this,"_initialDistance"),__publicField(this,"_distanceIncrement"),__publicField(this,"_histogram"),__publicField(this,"_distance"),this._distance=e,this._colors=i,this._histogram=new ColorHistogram(t,i),this._initialDistance=.01,this._distanceIncrement=.005}sample(e){this._histogram.sample(e)}*quantize(){const e=this._histogram.getImportanceSortedColorsIDXI32();if(e.length===0)throw new Error("No colors in image");yield*this._buildPalette(e)}*_buildPalette(e){const i=new Palette,t=i.getPointContainer().getPointArray(),n=new Array(e.length);for(let u=0;u<e.length;u++)t.push(Point.createByUint32(e[u])),n[u]=1;const a=t.length,s=[];let o=a,h=this._initialDistance;const f=new ProgressTracker(o-this._colors,99);for(;o>this._colors;){s.length=0;for(let u=0;u<a;u++){if(f.shouldNotify(a-o)&&(yield{progress:f.progress}),n[u]===0)continue;const w=t[u];for(let _=u+1;_<a;_++){if(n[_]===0)continue;const g=t[_],v=this._distance.calculateNormalized(w,g);v<h&&(s.push(new RemovedColor(_,g,v)),n[_]=0,o--)}}h+=o>this._colors*3?this._initialDistance:this._distanceIncrement}if(o<this._colors){stableSort(s,(w,_)=>_.distance-w.distance);let u=0;for(;o<this._colors&&u<s.length;){const w=s[u];n[w.index]=1,o++,u++}}let l=t.length;for(let u=l-1;u>=0;u--)n[u]===0&&(u!==l-1&&(t[u]=t[l-1]),--l);t.length=l,i.sort(),yield{palette:i,progress:100}}};function createArray1D(e){const i=[];for(let t=0;t<e;t++)i[t]=0;return i}function createArray4D(e,i,t,n){const a=new Array(e);for(let s=0;s<e;s++){a[s]=new Array(i);for(let o=0;o<i;o++){a[s][o]=new Array(t);for(let h=0;h<t;h++){a[s][o][h]=new Array(n);for(let f=0;f<n;f++)a[s][o][h][f]=0}}}return a}function createArray3D(e,i,t){const n=new Array(e);for(let a=0;a<e;a++){n[a]=new Array(i);for(let s=0;s<i;s++){n[a][s]=new Array(t);for(let o=0;o<t;o++)n[a][s][o]=0}}return n}function fillArray3D(e,i,t,n,a){for(let s=0;s<i;s++){e[s]=[];for(let o=0;o<t;o++){e[s][o]=[];for(let h=0;h<n;h++)e[s][o][h]=a}}}function fillArray1D(e,i,t){for(let n=0;n<i;n++)e[n]=t}var WuColorCube=class{constructor(){__publicField(this,"redMinimum"),__publicField(this,"redMaximum"),__publicField(this,"greenMinimum"),__publicField(this,"greenMaximum"),__publicField(this,"blueMinimum"),__publicField(this,"blueMaximum"),__publicField(this,"volume"),__publicField(this,"alphaMinimum"),__publicField(this,"alphaMaximum")}},_WuQuant=class extends AbstractPaletteQuantizer{constructor(e,i=256,t=5){super(),__publicField(this,"_reds"),__publicField(this,"_greens"),__publicField(this,"_blues"),__publicField(this,"_alphas"),__publicField(this,"_sums"),__publicField(this,"_weights"),__publicField(this,"_momentsRed"),__publicField(this,"_momentsGreen"),__publicField(this,"_momentsBlue"),__publicField(this,"_momentsAlpha"),__publicField(this,"_moments"),__publicField(this,"_table"),__publicField(this,"_pixels"),__publicField(this,"_cubes"),__publicField(this,"_colors"),__publicField(this,"_significantBitsPerChannel"),__publicField(this,"_maxSideIndex"),__publicField(this,"_alphaMaxSideIndex"),__publicField(this,"_sideSize"),__publicField(this,"_alphaSideSize"),__publicField(this,"_distance"),this._distance=e,this._setQuality(t),this._initialize(i)}sample(e){const i=e.getPointArray();for(let t=0,n=i.length;t<n;t++)this._addColor(i[t]);this._pixels=this._pixels.concat(i)}*quantize(){yield*this._preparePalette();const e=new Palette;for(let i=0;i<this._colors;i++)if(this._sums[i]>0){const t=this._sums[i],n=this._reds[i]/t,a=this._greens[i]/t,s=this._blues[i]/t,o=this._alphas[i]/t,h=Point.createByRGBA(n|0,a|0,s|0,o|0);e.add(h)}e.sort(),yield{palette:e,progress:100}}*_preparePalette(){yield*this._calculateMoments();let e=0;const i=createArray1D(this._colors);for(let o=1;o<this._colors;++o){this._cut(this._cubes[e],this._cubes[o])?(i[e]=this._cubes[e].volume>1?this._calculateVariance(this._cubes[e]):0,i[o]=this._cubes[o].volume>1?this._calculateVariance(this._cubes[o]):0):(i[e]=0,o--),e=0;let h=i[0];for(let f=1;f<=o;++f)i[f]>h&&(h=i[f],e=f);if(h<=0){this._colors=o+1;break}}const t=[],n=[],a=[],s=[];for(let o=0;o<this._colors;++o){const h=_WuQuant._volume(this._cubes[o],this._weights);h>0?(t[o]=_WuQuant._volume(this._cubes[o],this._momentsRed)/h|0,n[o]=_WuQuant._volume(this._cubes[o],this._momentsGreen)/h|0,a[o]=_WuQuant._volume(this._cubes[o],this._momentsBlue)/h|0,s[o]=_WuQuant._volume(this._cubes[o],this._momentsAlpha)/h|0):(t[o]=0,n[o]=0,a[o]=0,s[o]=0)}this._reds=createArray1D(this._colors+1),this._greens=createArray1D(this._colors+1),this._blues=createArray1D(this._colors+1),this._alphas=createArray1D(this._colors+1),this._sums=createArray1D(this._colors+1);for(let o=0,h=this._pixels.length;o<h;o++){const f=this._pixels[o];let u=-1,w=Number.MAX_VALUE;for(let _=0;_<this._colors;_++){const g=t[_],v=n[_],k=a[_],A=s[_],T=this._distance.calculateRaw(g,v,k,A,f.r,f.g,f.b,f.a);T<w&&(w=T,u=_)}this._reds[u]+=f.r,this._greens[u]+=f.g,this._blues[u]+=f.b,this._alphas[u]+=f.a,this._sums[u]++}}_addColor(e){const i=8-this._significantBitsPerChannel,t=(e.r>>i)+1,n=(e.g>>i)+1,a=(e.b>>i)+1,s=(e.a>>i)+1;this._weights[s][t][n][a]++,this._momentsRed[s][t][n][a]+=e.r,this._momentsGreen[s][t][n][a]+=e.g,this._momentsBlue[s][t][n][a]+=e.b,this._momentsAlpha[s][t][n][a]+=e.a,this._moments[s][t][n][a]+=this._table[e.r]+this._table[e.g]+this._table[e.b]+this._table[e.a]}*_calculateMoments(){const e=[],i=[],t=[],n=[],a=[],s=[],o=createArray3D(this._sideSize,this._sideSize,this._sideSize),h=createArray3D(this._sideSize,this._sideSize,this._sideSize),f=createArray3D(this._sideSize,this._sideSize,this._sideSize),l=createArray3D(this._sideSize,this._sideSize,this._sideSize),u=createArray3D(this._sideSize,this._sideSize,this._sideSize),w=createArray3D(this._sideSize,this._sideSize,this._sideSize);let _=0;const g=new ProgressTracker(this._alphaMaxSideIndex*this._maxSideIndex,99);for(let v=1;v<=this._alphaMaxSideIndex;++v){fillArray3D(o,this._sideSize,this._sideSize,this._sideSize,0),fillArray3D(h,this._sideSize,this._sideSize,this._sideSize,0),fillArray3D(f,this._sideSize,this._sideSize,this._sideSize,0),fillArray3D(l,this._sideSize,this._sideSize,this._sideSize,0),fillArray3D(u,this._sideSize,this._sideSize,this._sideSize,0),fillArray3D(w,this._sideSize,this._sideSize,this._sideSize,0);for(let k=1;k<=this._maxSideIndex;++k,++_){g.shouldNotify(_)&&(yield{progress:g.progress}),fillArray1D(e,this._sideSize,0),fillArray1D(i,this._sideSize,0),fillArray1D(t,this._sideSize,0),fillArray1D(n,this._sideSize,0),fillArray1D(a,this._sideSize,0),fillArray1D(s,this._sideSize,0);for(let A=1;A<=this._maxSideIndex;++A){let T=0,$=0,D=0,C=0,P=0,z=0;for(let B=1;B<=this._maxSideIndex;++B)T+=this._weights[v][k][A][B],$+=this._momentsRed[v][k][A][B],D+=this._momentsGreen[v][k][A][B],C+=this._momentsBlue[v][k][A][B],P+=this._momentsAlpha[v][k][A][B],z+=this._moments[v][k][A][B],e[B]+=T,i[B]+=$,t[B]+=D,n[B]+=C,a[B]+=P,s[B]+=z,o[k][A][B]=o[k-1][A][B]+e[B],h[k][A][B]=h[k-1][A][B]+i[B],f[k][A][B]=f[k-1][A][B]+t[B],l[k][A][B]=l[k-1][A][B]+n[B],u[k][A][B]=u[k-1][A][B]+a[B],w[k][A][B]=w[k-1][A][B]+s[B],this._weights[v][k][A][B]=this._weights[v-1][k][A][B]+o[k][A][B],this._momentsRed[v][k][A][B]=this._momentsRed[v-1][k][A][B]+h[k][A][B],this._momentsGreen[v][k][A][B]=this._momentsGreen[v-1][k][A][B]+f[k][A][B],this._momentsBlue[v][k][A][B]=this._momentsBlue[v-1][k][A][B]+l[k][A][B],this._momentsAlpha[v][k][A][B]=this._momentsAlpha[v-1][k][A][B]+u[k][A][B],this._moments[v][k][A][B]=this._moments[v-1][k][A][B]+w[k][A][B]}}}}static _volumeFloat(e,i){return i[e.alphaMaximum][e.redMaximum][e.greenMaximum][e.blueMaximum]-i[e.alphaMaximum][e.redMaximum][e.greenMinimum][e.blueMaximum]-i[e.alphaMaximum][e.redMinimum][e.greenMaximum][e.blueMaximum]+i[e.alphaMaximum][e.redMinimum][e.greenMinimum][e.blueMaximum]-i[e.alphaMinimum][e.redMaximum][e.greenMaximum][e.blueMaximum]+i[e.alphaMinimum][e.redMaximum][e.greenMinimum][e.blueMaximum]+i[e.alphaMinimum][e.redMinimum][e.greenMaximum][e.blueMaximum]-i[e.alphaMinimum][e.redMinimum][e.greenMinimum][e.blueMaximum]-(i[e.alphaMaximum][e.redMaximum][e.greenMaximum][e.blueMinimum]-i[e.alphaMinimum][e.redMaximum][e.greenMaximum][e.blueMinimum]-i[e.alphaMaximum][e.redMaximum][e.greenMinimum][e.blueMinimum]+i[e.alphaMinimum][e.redMaximum][e.greenMinimum][e.blueMinimum]-i[e.alphaMaximum][e.redMinimum][e.greenMaximum][e.blueMinimum]+i[e.alphaMinimum][e.redMinimum][e.greenMaximum][e.blueMinimum]+i[e.alphaMaximum][e.redMinimum][e.greenMinimum][e.blueMinimum]-i[e.alphaMinimum][e.redMinimum][e.greenMinimum][e.blueMinimum])}static _volume(e,i){return _WuQuant._volumeFloat(e,i)|0}static _top(e,i,t,n){let a;switch(i){case _WuQuant._alpha:a=n[t][e.redMaximum][e.greenMaximum][e.blueMaximum]-n[t][e.redMaximum][e.greenMinimum][e.blueMaximum]-n[t][e.redMinimum][e.greenMaximum][e.blueMaximum]+n[t][e.redMinimum][e.greenMinimum][e.blueMaximum]-(n[t][e.redMaximum][e.greenMaximum][e.blueMinimum]-n[t][e.redMaximum][e.greenMinimum][e.blueMinimum]-n[t][e.redMinimum][e.greenMaximum][e.blueMinimum]+n[t][e.redMinimum][e.greenMinimum][e.blueMinimum]);break;case _WuQuant._red:a=n[e.alphaMaximum][t][e.greenMaximum][e.blueMaximum]-n[e.alphaMaximum][t][e.greenMinimum][e.blueMaximum]-n[e.alphaMinimum][t][e.greenMaximum][e.blueMaximum]+n[e.alphaMinimum][t][e.greenMinimum][e.blueMaximum]-(n[e.alphaMaximum][t][e.greenMaximum][e.blueMinimum]-n[e.alphaMaximum][t][e.greenMinimum][e.blueMinimum]-n[e.alphaMinimum][t][e.greenMaximum][e.blueMinimum]+n[e.alphaMinimum][t][e.greenMinimum][e.blueMinimum]);break;case _WuQuant._green:a=n[e.alphaMaximum][e.redMaximum][t][e.blueMaximum]-n[e.alphaMaximum][e.redMinimum][t][e.blueMaximum]-n[e.alphaMinimum][e.redMaximum][t][e.blueMaximum]+n[e.alphaMinimum][e.redMinimum][t][e.blueMaximum]-(n[e.alphaMaximum][e.redMaximum][t][e.blueMinimum]-n[e.alphaMaximum][e.redMinimum][t][e.blueMinimum]-n[e.alphaMinimum][e.redMaximum][t][e.blueMinimum]+n[e.alphaMinimum][e.redMinimum][t][e.blueMinimum]);break;case _WuQuant._blue:a=n[e.alphaMaximum][e.redMaximum][e.greenMaximum][t]-n[e.alphaMaximum][e.redMaximum][e.greenMinimum][t]-n[e.alphaMaximum][e.redMinimum][e.greenMaximum][t]+n[e.alphaMaximum][e.redMinimum][e.greenMinimum][t]-(n[e.alphaMinimum][e.redMaximum][e.greenMaximum][t]-n[e.alphaMinimum][e.redMaximum][e.greenMinimum][t]-n[e.alphaMinimum][e.redMinimum][e.greenMaximum][t]+n[e.alphaMinimum][e.redMinimum][e.greenMinimum][t]);break;default:throw new Error("impossible")}return a|0}static _bottom(e,i,t){switch(i){case _WuQuant._alpha:return-t[e.alphaMinimum][e.redMaximum][e.greenMaximum][e.blueMaximum]+t[e.alphaMinimum][e.redMaximum][e.greenMinimum][e.blueMaximum]+t[e.alphaMinimum][e.redMinimum][e.greenMaximum][e.blueMaximum]-t[e.alphaMinimum][e.redMinimum][e.greenMinimum][e.blueMaximum]-(-t[e.alphaMinimum][e.redMaximum][e.greenMaximum][e.blueMinimum]+t[e.alphaMinimum][e.redMaximum][e.greenMinimum][e.blueMinimum]+t[e.alphaMinimum][e.redMinimum][e.greenMaximum][e.blueMinimum]-t[e.alphaMinimum][e.redMinimum][e.greenMinimum][e.blueMinimum]);case _WuQuant._red:return-t[e.alphaMaximum][e.redMinimum][e.greenMaximum][e.blueMaximum]+t[e.alphaMaximum][e.redMinimum][e.greenMinimum][e.blueMaximum]+t[e.alphaMinimum][e.redMinimum][e.greenMaximum][e.blueMaximum]-t[e.alphaMinimum][e.redMinimum][e.greenMinimum][e.blueMaximum]-(-t[e.alphaMaximum][e.redMinimum][e.greenMaximum][e.blueMinimum]+t[e.alphaMaximum][e.redMinimum][e.greenMinimum][e.blueMinimum]+t[e.alphaMinimum][e.redMinimum][e.greenMaximum][e.blueMinimum]-t[e.alphaMinimum][e.redMinimum][e.greenMinimum][e.blueMinimum]);case _WuQuant._green:return-t[e.alphaMaximum][e.redMaximum][e.greenMinimum][e.blueMaximum]+t[e.alphaMaximum][e.redMinimum][e.greenMinimum][e.blueMaximum]+t[e.alphaMinimum][e.redMaximum][e.greenMinimum][e.blueMaximum]-t[e.alphaMinimum][e.redMinimum][e.greenMinimum][e.blueMaximum]-(-t[e.alphaMaximum][e.redMaximum][e.greenMinimum][e.blueMinimum]+t[e.alphaMaximum][e.redMinimum][e.greenMinimum][e.blueMinimum]+t[e.alphaMinimum][e.redMaximum][e.greenMinimum][e.blueMinimum]-t[e.alphaMinimum][e.redMinimum][e.greenMinimum][e.blueMinimum]);case _WuQuant._blue:return-t[e.alphaMaximum][e.redMaximum][e.greenMaximum][e.blueMinimum]+t[e.alphaMaximum][e.redMaximum][e.greenMinimum][e.blueMinimum]+t[e.alphaMaximum][e.redMinimum][e.greenMaximum][e.blueMinimum]-t[e.alphaMaximum][e.redMinimum][e.greenMinimum][e.blueMinimum]-(-t[e.alphaMinimum][e.redMaximum][e.greenMaximum][e.blueMinimum]+t[e.alphaMinimum][e.redMaximum][e.greenMinimum][e.blueMinimum]+t[e.alphaMinimum][e.redMinimum][e.greenMaximum][e.blueMinimum]-t[e.alphaMinimum][e.redMinimum][e.greenMinimum][e.blueMinimum]);default:return 0}}_calculateVariance(e){const i=_WuQuant._volume(e,this._momentsRed),t=_WuQuant._volume(e,this._momentsGreen),n=_WuQuant._volume(e,this._momentsBlue),a=_WuQuant._volume(e,this._momentsAlpha),s=_WuQuant._volumeFloat(e,this._moments),o=_WuQuant._volume(e,this._weights),h=i*i+t*t+n*n+a*a;return s-h/o}_maximize(e,i,t,n,a,s,o,h,f){const l=_WuQuant._bottom(e,i,this._momentsRed)|0,u=_WuQuant._bottom(e,i,this._momentsGreen)|0,w=_WuQuant._bottom(e,i,this._momentsBlue)|0,_=_WuQuant._bottom(e,i,this._momentsAlpha)|0,g=_WuQuant._bottom(e,i,this._weights)|0;let v=0,k=-1;for(let A=t;A<n;++A){let T=l+_WuQuant._top(e,i,A,this._momentsRed),$=u+_WuQuant._top(e,i,A,this._momentsGreen),D=w+_WuQuant._top(e,i,A,this._momentsBlue),C=_+_WuQuant._top(e,i,A,this._momentsAlpha),P=g+_WuQuant._top(e,i,A,this._weights);if(P!==0){let z=T*T+$*$+D*D+C*C,B=z/P;T=a-T,$=s-$,D=o-D,C=h-C,P=f-P,P!==0&&(z=T*T+$*$+D*D+C*C,B+=z/P,B>v&&(v=B,k=A))}}return{max:v,position:k}}_cut(e,i){let t;const n=_WuQuant._volume(e,this._momentsRed),a=_WuQuant._volume(e,this._momentsGreen),s=_WuQuant._volume(e,this._momentsBlue),o=_WuQuant._volume(e,this._momentsAlpha),h=_WuQuant._volume(e,this._weights),f=this._maximize(e,_WuQuant._red,e.redMinimum+1,e.redMaximum,n,a,s,o,h),l=this._maximize(e,_WuQuant._green,e.greenMinimum+1,e.greenMaximum,n,a,s,o,h),u=this._maximize(e,_WuQuant._blue,e.blueMinimum+1,e.blueMaximum,n,a,s,o,h),w=this._maximize(e,_WuQuant._alpha,e.alphaMinimum+1,e.alphaMaximum,n,a,s,o,h);if(w.max>=f.max&&w.max>=l.max&&w.max>=u.max){if(t=_WuQuant._alpha,w.position<0)return!1}else f.max>=w.max&&f.max>=l.max&&f.max>=u.max?t=_WuQuant._red:l.max>=w.max&&l.max>=f.max&&l.max>=u.max?t=_WuQuant._green:t=_WuQuant._blue;switch(i.redMaximum=e.redMaximum,i.greenMaximum=e.greenMaximum,i.blueMaximum=e.blueMaximum,i.alphaMaximum=e.alphaMaximum,t){case _WuQuant._red:i.redMinimum=e.redMaximum=f.position,i.greenMinimum=e.greenMinimum,i.blueMinimum=e.blueMinimum,i.alphaMinimum=e.alphaMinimum;break;case _WuQuant._green:i.greenMinimum=e.greenMaximum=l.position,i.redMinimum=e.redMinimum,i.blueMinimum=e.blueMinimum,i.alphaMinimum=e.alphaMinimum;break;case _WuQuant._blue:i.blueMinimum=e.blueMaximum=u.position,i.redMinimum=e.redMinimum,i.greenMinimum=e.greenMinimum,i.alphaMinimum=e.alphaMinimum;break;case _WuQuant._alpha:i.alphaMinimum=e.alphaMaximum=w.position,i.blueMinimum=e.blueMinimum,i.redMinimum=e.redMinimum,i.greenMinimum=e.greenMinimum;break}return e.volume=(e.redMaximum-e.redMinimum)*(e.greenMaximum-e.greenMinimum)*(e.blueMaximum-e.blueMinimum)*(e.alphaMaximum-e.alphaMinimum),i.volume=(i.redMaximum-i.redMinimum)*(i.greenMaximum-i.greenMinimum)*(i.blueMaximum-i.blueMinimum)*(i.alphaMaximum-i.alphaMinimum),!0}_initialize(e){this._colors=e,this._cubes=[];for(let i=0;i<e;i++)this._cubes[i]=new WuColorCube;this._cubes[0].redMinimum=0,this._cubes[0].greenMinimum=0,this._cubes[0].blueMinimum=0,this._cubes[0].alphaMinimum=0,this._cubes[0].redMaximum=this._maxSideIndex,this._cubes[0].greenMaximum=this._maxSideIndex,this._cubes[0].blueMaximum=this._maxSideIndex,this._cubes[0].alphaMaximum=this._alphaMaxSideIndex,this._weights=createArray4D(this._alphaSideSize,this._sideSize,this._sideSize,this._sideSize),this._momentsRed=createArray4D(this._alphaSideSize,this._sideSize,this._sideSize,this._sideSize),this._momentsGreen=createArray4D(this._alphaSideSize,this._sideSize,this._sideSize,this._sideSize),this._momentsBlue=createArray4D(this._alphaSideSize,this._sideSize,this._sideSize,this._sideSize),this._momentsAlpha=createArray4D(this._alphaSideSize,this._sideSize,this._sideSize,this._sideSize),this._moments=createArray4D(this._alphaSideSize,this._sideSize,this._sideSize,this._sideSize),this._table=[];for(let i=0;i<256;++i)this._table[i]=i*i;this._pixels=[]}_setQuality(e=5){this._significantBitsPerChannel=e,this._maxSideIndex=1<<this._significantBitsPerChannel,this._alphaMaxSideIndex=this._maxSideIndex,this._sideSize=this._maxSideIndex+1,this._alphaSideSize=this._alphaMaxSideIndex+1}},WuQuant=_WuQuant;__publicField(WuQuant,"_alpha",3),__publicField(WuQuant,"_red",2),__publicField(WuQuant,"_green",1),__publicField(WuQuant,"_blue",0);var image_exports={};__export(image_exports,{AbstractImageQuantizer:()=>AbstractImageQuantizer,ErrorDiffusionArray:()=>ErrorDiffusionArray,ErrorDiffusionArrayKernel:()=>ErrorDiffusionArrayKernel,ErrorDiffusionRiemersma:()=>ErrorDiffusionRiemersma,NearestColor:()=>NearestColor});var AbstractImageQuantizer=class{quantizeSync(e,i){for(const t of this.quantize(e,i))if(t.pointContainer)return t.pointContainer;throw new Error("unreachable")}},NearestColor=class extends AbstractImageQuantizer{constructor(e){super(),__publicField(this,"_distance"),this._distance=e}*quantize(e,i){const t=e.getPointArray(),n=e.getWidth(),a=e.getHeight(),s=new ProgressTracker(a,99);for(let o=0;o<a;o++){s.shouldNotify(o)&&(yield{progress:s.progress});for(let h=0,f=o*n;h<n;h++,f++){const l=t[f];l.from(i.getNearestColor(this._distance,l))}}yield{pointContainer:e,progress:100}}},ErrorDiffusionArrayKernel=(e=>(e[e.FloydSteinberg=0]="FloydSteinberg",e[e.FalseFloydSteinberg=1]="FalseFloydSteinberg",e[e.Stucki=2]="Stucki",e[e.Atkinson=3]="Atkinson",e[e.Jarvis=4]="Jarvis",e[e.Burkes=5]="Burkes",e[e.Sierra=6]="Sierra",e[e.TwoSierra=7]="TwoSierra",e[e.SierraLite=8]="SierraLite",e))(ErrorDiffusionArrayKernel||{}),ErrorDiffusionArray=class extends AbstractImageQuantizer{constructor(e,i,t=!0,n=0,a=!1){super(),__publicField(this,"_minColorDistance"),__publicField(this,"_serpentine"),__publicField(this,"_kernel"),__publicField(this,"_calculateErrorLikeGIMP"),__publicField(this,"_distance"),this._setKernel(i),this._distance=e,this._minColorDistance=n,this._serpentine=t,this._calculateErrorLikeGIMP=a}*quantize(e,i){const t=e.getPointArray(),n=new Point,a=e.getWidth(),s=e.getHeight(),o=[];let h=1,f=1;for(const u of this._kernel){const w=u[2]+1;f<w&&(f=w)}for(let u=0;u<f;u++)this._fillErrorLine(o[u]=[],a);const l=new ProgressTracker(s,99);for(let u=0;u<s;u++){l.shouldNotify(u)&&(yield{progress:l.progress}),this._serpentine&&(h*=-1);const w=u*a,_=h===1?0:a-1,g=h===1?a:-1;this._fillErrorLine(o[0],a),o.push(o.shift());const v=o[0];for(let k=_,A=w+_;k!==g;k+=h,A+=h){const T=t[A],$=v[k];n.from(T);const D=Point.createByRGBA(inRange0to255Rounded(T.r+$[0]),inRange0to255Rounded(T.g+$[1]),inRange0to255Rounded(T.b+$[2]),inRange0to255Rounded(T.a+$[3])),C=i.getNearestColor(this._distance,D);if(T.from(C),this._minColorDistance&&this._distance.calculateNormalized(n,C)<this._minColorDistance)continue;let P,z,B,F;this._calculateErrorLikeGIMP?(P=D.r-C.r,z=D.g-C.g,B=D.b-C.b,F=D.a-C.a):(P=n.r-C.r,z=n.g-C.g,B=n.b-C.b,F=n.a-C.a);const L=h===1?0:this._kernel.length-1,N=h===1?this._kernel.length:-1;for(let G=L;G!==N;G+=h){const V=this._kernel[G][1]*h,J=this._kernel[G][2];if(V+k>=0&&V+k<a&&J+u>=0&&J+u<s){const Q=this._kernel[G][0],W=o[J][V+k];W[0]+=P*Q,W[1]+=z*Q,W[2]+=B*Q,W[3]+=F*Q}}}}yield{pointContainer:e,progress:100}}_fillErrorLine(e,i){e.length>i&&(e.length=i);const t=e.length;for(let n=0;n<t;n++){const a=e[n];a[0]=a[1]=a[2]=a[3]=0}for(let n=t;n<i;n++)e[n]=[0,0,0,0]}_setKernel(e){switch(e){case 0:this._kernel=[[7/16,1,0],[3/16,-1,1],[5/16,0,1],[1/16,1,1]];break;case 1:this._kernel=[[3/8,1,0],[3/8,0,1],[2/8,1,1]];break;case 2:this._kernel=[[8/42,1,0],[4/42,2,0],[2/42,-2,1],[4/42,-1,1],[8/42,0,1],[4/42,1,1],[2/42,2,1],[1/42,-2,2],[2/42,-1,2],[4/42,0,2],[2/42,1,2],[1/42,2,2]];break;case 3:this._kernel=[[1/8,1,0],[1/8,2,0],[1/8,-1,1],[1/8,0,1],[1/8,1,1],[1/8,0,2]];break;case 4:this._kernel=[[7/48,1,0],[5/48,2,0],[3/48,-2,1],[5/48,-1,1],[7/48,0,1],[5/48,1,1],[3/48,2,1],[1/48,-2,2],[3/48,-1,2],[5/48,0,2],[3/48,1,2],[1/48,2,2]];break;case 5:this._kernel=[[8/32,1,0],[4/32,2,0],[2/32,-2,1],[4/32,-1,1],[8/32,0,1],[4/32,1,1],[2/32,2,1]];break;case 6:this._kernel=[[5/32,1,0],[3/32,2,0],[2/32,-2,1],[4/32,-1,1],[5/32,0,1],[4/32,1,1],[2/32,2,1],[2/32,-1,2],[3/32,0,2],[2/32,1,2]];break;case 7:this._kernel=[[4/16,1,0],[3/16,2,0],[1/16,-2,1],[2/16,-1,1],[3/16,0,1],[2/16,1,1],[1/16,2,1]];break;case 8:this._kernel=[[2/4,1,0],[1/4,-1,1],[1/4,0,1]];break;default:throw new Error(`ErrorDiffusionArray: unknown kernel = ${e}`)}}};function*hilbertCurve(e,i,t){const n=Math.max(e,i),a=Math.floor(Math.log(n)/Math.log(2)+1),s=new ProgressTracker(e*i,99),o={width:e,height:i,level:a,callback:t,tracker:s,index:0,x:0,y:0};yield*walkHilbert(o,1),visit(o,0)}function*walkHilbert(e,i){if(!(e.level<1)){switch(e.tracker.shouldNotify(e.index)&&(yield{progress:e.tracker.progress}),e.level--,i){case 2:yield*walkHilbert(e,1),visit(e,3),yield*walkHilbert(e,2),visit(e,4),yield*walkHilbert(e,2),visit(e,2),yield*walkHilbert(e,4);break;case 3:yield*walkHilbert(e,4),visit(e,2),yield*walkHilbert(e,3),visit(e,1),yield*walkHilbert(e,3),visit(e,3),yield*walkHilbert(e,1);break;case 1:yield*walkHilbert(e,2),visit(e,4),yield*walkHilbert(e,1),visit(e,3),yield*walkHilbert(e,1),visit(e,1),yield*walkHilbert(e,3);break;case 4:yield*walkHilbert(e,3),visit(e,1),yield*walkHilbert(e,4),visit(e,2),yield*walkHilbert(e,4),visit(e,4),yield*walkHilbert(e,2);break}e.level++}}function visit(e,i){switch(e.x>=0&&e.x<e.width&&e.y>=0&&e.y<e.height&&(e.callback(e.x,e.y),e.index++),i){case 2:e.x--;break;case 3:e.x++;break;case 1:e.y--;break;case 4:e.y++;break}}var ErrorDiffusionRiemersma=class extends AbstractImageQuantizer{constructor(e,i=16,t=1){super(),__publicField(this,"_distance"),__publicField(this,"_weights"),__publicField(this,"_errorQueueSize"),this._distance=e,this._errorQueueSize=i,this._weights=ErrorDiffusionRiemersma._createWeights(t,i)}*quantize(e,i){const t=e.getPointArray(),n=e.getWidth(),a=e.getHeight(),s=[];let o=0;for(let h=0;h<this._errorQueueSize;h++)s[h]={r:0,g:0,b:0,a:0};yield*hilbertCurve(n,a,(h,f)=>{const l=t[h+f*n];let{r:u,g:w,b:_,a:g}=l;for(let T=0;T<this._errorQueueSize;T++){const $=this._weights[T],D=s[(T+o)%this._errorQueueSize];u+=D.r*$,w+=D.g*$,_+=D.b*$,g+=D.a*$}const v=Point.createByRGBA(inRange0to255Rounded(u),inRange0to255Rounded(w),inRange0to255Rounded(_),inRange0to255Rounded(g)),k=i.getNearestColor(this._distance,v);o=(o+1)%this._errorQueueSize;const A=(o+this._errorQueueSize-1)%this._errorQueueSize;s[A].r=l.r-k.r,s[A].g=l.g-k.g,s[A].b=l.b-k.b,s[A].a=l.a-k.a,l.from(k)}),yield{pointContainer:e,progress:100}}static _createWeights(e,i){const t=[],n=Math.exp(Math.log(i)/(i-1));for(let a=0,s=1;a<i;a++)t[a]=(s+.5|0)/i*e,s*=n;return t}},quality_exports={};__export(quality_exports,{ssim:()=>ssim});var K1=.01,K2=.03;function ssim(e,i){if(e.getHeight()!==i.getHeight()||e.getWidth()!==i.getWidth())throw new Error("Images have different sizes!");const n=(1<<8)-1,a=(K1*n)**2,s=(K2*n)**2;let o=0,h=0;return iterate(e,i,(f,l,u,w)=>{let _=0,g=0,v=0;for(let D=0;D<f.length;D++)g+=(f[D]-u)**2,v+=(l[D]-w)**2,_+=(f[D]-u)*(l[D]-w);const k=f.length-1;g/=k,v/=k,_/=k;const A=(2*u*w+a)*(2*_+s),T=(u**2+w**2+a)*(g+v+s),$=A/T;h+=$,o++}),h/o}function iterate(e,i,t){const a=e.getWidth(),s=e.getHeight();for(let o=0;o<s;o+=8)for(let h=0;h<a;h+=8){const f=Math.min(8,a-h),l=Math.min(8,s-o),u=calculateLumaValuesForWindow(e,h,o,f,l),w=calculateLumaValuesForWindow(i,h,o,f,l),_=calculateAverageLuma(u),g=calculateAverageLuma(w);t(u,w,_,g)}}function calculateLumaValuesForWindow(e,i,t,n,a){const s=e.getPointArray(),o=[];let h=0;for(let f=t;f<t+a;f++){const l=f*e.getWidth();for(let u=i;u<i+n;u++){const w=s[l+u];o[h]=w.r*.2126+w.g*.7152+w.b*.0722,h++}}return o}function calculateAverageLuma(e){let i=0;for(const t of e)i+=t;return i/e.length}typeof setImmediate=="function"?setImmediate:typeof process<"u"&&(process==null||process.nextTick);function buildPaletteSync(e,{colorDistanceFormula:i,paletteQuantization:t,colors:n}={}){const a=colorDistanceFormulaToColorDistance(i),s=paletteQuantizationToPaletteQuantizer(a,t,n);return e.forEach(o=>s.sample(o)),s.quantizeSync()}function applyPaletteSync(e,i,{colorDistanceFormula:t,imageQuantization:n}={}){const a=colorDistanceFormulaToColorDistance(t);return imageQuantizationToImageQuantizer(a,n).quantizeSync(e,i)}function colorDistanceFormulaToColorDistance(e="euclidean-bt709"){switch(e){case"cie94-graphic-arts":return new CIE94GraphicArts;case"cie94-textiles":return new CIE94Textiles;case"ciede2000":return new CIEDE2000;case"color-metric":return new CMetric;case"euclidean":return new Euclidean;case"euclidean-bt709":return new EuclideanBT709;case"euclidean-bt709-noalpha":return new EuclideanBT709NoAlpha;case"manhattan":return new Manhattan;case"manhattan-bt709":return new ManhattanBT709;case"manhattan-nommyde":return new ManhattanNommyde;case"pngquant":return new PNGQuant;default:throw new Error(`Unknown colorDistanceFormula ${e}`)}}function imageQuantizationToImageQuantizer(e,i="floyd-steinberg"){switch(i){case"nearest":return new NearestColor(e);case"riemersma":return new ErrorDiffusionRiemersma(e);case"floyd-steinberg":return new ErrorDiffusionArray(e,0);case"false-floyd-steinberg":return new ErrorDiffusionArray(e,1);case"stucki":return new ErrorDiffusionArray(e,2);case"atkinson":return new ErrorDiffusionArray(e,3);case"jarvis":return new ErrorDiffusionArray(e,4);case"burkes":return new ErrorDiffusionArray(e,5);case"sierra":return new ErrorDiffusionArray(e,6);case"two-sierra":return new ErrorDiffusionArray(e,7);case"sierra-lite":return new ErrorDiffusionArray(e,8);default:throw new Error(`Unknown imageQuantization ${i}`)}}function paletteQuantizationToPaletteQuantizer(e,i="wuquant",t=256){switch(i){case"neuquant":return new NeuQuant(e,t);case"rgbquant":return new RGBQuant(e,t);case"wuquant":return new WuQuant(e,t);case"neuquant-float":return new NeuQuantFloat(e,t);default:throw new Error(`Unknown paletteQuantization ${i}`)}}/**
11
+ * @preserve
12
+ * Copyright 2015-2018 Igor Bezkrovnyi
13
+ * All rights reserved. (MIT Licensed)
14
+ *
15
+ * cie94.ts - part of Image Quantization Library
16
+ *//**
17
+ * @preserve
18
+ * Copyright 2015-2018 Igor Bezkrovnyi
19
+ * All rights reserved. (MIT Licensed)
20
+ *
21
+ * ciede2000.ts - part of Image Quantization Library
22
+ *//**
23
+ * @preserve
24
+ * Copyright 2015-2018 Igor Bezkrovnyi
25
+ * All rights reserved. (MIT Licensed)
26
+ *
27
+ * cmetric.ts - part of Image Quantization Library
28
+ *//**
29
+ * @preserve
30
+ * Copyright 2015-2018 Igor Bezkrovnyi
31
+ * All rights reserved. (MIT Licensed)
32
+ *
33
+ * common.ts - part of Image Quantization Library
34
+ *//**
35
+ * @preserve
36
+ * Copyright 2015-2018 Igor Bezkrovnyi
37
+ * All rights reserved. (MIT Licensed)
38
+ *
39
+ * constants.ts - part of Image Quantization Library
40
+ *//**
41
+ * @preserve
42
+ * Copyright 2015-2018 Igor Bezkrovnyi
43
+ * All rights reserved. (MIT Licensed)
44
+ *
45
+ * ditherErrorDiffusionArray.ts - part of Image Quantization Library
46
+ *//**
47
+ * @preserve
48
+ * Copyright 2015-2018 Igor Bezkrovnyi
49
+ * All rights reserved. (MIT Licensed)
50
+ *
51
+ * euclidean.ts - part of Image Quantization Library
52
+ *//**
53
+ * @preserve
54
+ * Copyright 2015-2018 Igor Bezkrovnyi
55
+ * All rights reserved. (MIT Licensed)
56
+ *
57
+ * helper.ts - part of Image Quantization Library
58
+ *//**
59
+ * @preserve
60
+ * Copyright 2015-2018 Igor Bezkrovnyi
61
+ * All rights reserved. (MIT Licensed)
62
+ *
63
+ * hueStatistics.ts - part of Image Quantization Library
64
+ *//**
65
+ * @preserve
66
+ * Copyright 2015-2018 Igor Bezkrovnyi
67
+ * All rights reserved. (MIT Licensed)
68
+ *
69
+ * iq.ts - Image Quantization Library
70
+ *//**
71
+ * @preserve
72
+ * Copyright 2015-2018 Igor Bezkrovnyi
73
+ * All rights reserved. (MIT Licensed)
74
+ *
75
+ * lab2rgb.ts - part of Image Quantization Library
76
+ *//**
77
+ * @preserve
78
+ * Copyright 2015-2018 Igor Bezkrovnyi
79
+ * All rights reserved. (MIT Licensed)
80
+ *
81
+ * lab2xyz.ts - part of Image Quantization Library
82
+ *//**
83
+ * @preserve
84
+ * Copyright 2015-2018 Igor Bezkrovnyi
85
+ * All rights reserved. (MIT Licensed)
86
+ *
87
+ * manhattanNeuQuant.ts - part of Image Quantization Library
88
+ *//**
89
+ * @preserve
90
+ * Copyright 2015-2018 Igor Bezkrovnyi
91
+ * All rights reserved. (MIT Licensed)
92
+ *
93
+ * nearestColor.ts - part of Image Quantization Library
94
+ *//**
95
+ * @preserve
96
+ * Copyright 2015-2018 Igor Bezkrovnyi
97
+ * All rights reserved. (MIT Licensed)
98
+ *
99
+ * palette.ts - part of Image Quantization Library
100
+ *//**
101
+ * @preserve
102
+ * Copyright 2015-2018 Igor Bezkrovnyi
103
+ * All rights reserved. (MIT Licensed)
104
+ *
105
+ * pngQuant.ts - part of Image Quantization Library
106
+ *//**
107
+ * @preserve
108
+ * Copyright 2015-2018 Igor Bezkrovnyi
109
+ * All rights reserved. (MIT Licensed)
110
+ *
111
+ * point.ts - part of Image Quantization Library
112
+ *//**
113
+ * @preserve
114
+ * Copyright 2015-2018 Igor Bezkrovnyi
115
+ * All rights reserved. (MIT Licensed)
116
+ *
117
+ * pointContainer.ts - part of Image Quantization Library
118
+ *//**
119
+ * @preserve
120
+ * Copyright 2015-2018 Igor Bezkrovnyi
121
+ * All rights reserved. (MIT Licensed)
122
+ *
123
+ * rgb2hsl.ts - part of Image Quantization Library
124
+ *//**
125
+ * @preserve
126
+ * Copyright 2015-2018 Igor Bezkrovnyi
127
+ * All rights reserved. (MIT Licensed)
128
+ *
129
+ * rgb2lab.ts - part of Image Quantization Library
130
+ *//**
131
+ * @preserve
132
+ * Copyright 2015-2018 Igor Bezkrovnyi
133
+ * All rights reserved. (MIT Licensed)
134
+ *
135
+ * rgb2xyz.ts - part of Image Quantization Library
136
+ *//**
137
+ * @preserve
138
+ * Copyright 2015-2018 Igor Bezkrovnyi
139
+ * All rights reserved. (MIT Licensed)
140
+ *
141
+ * ssim.ts - part of Image Quantization Library
142
+ *//**
143
+ * @preserve
144
+ * Copyright 2015-2018 Igor Bezkrovnyi
145
+ * All rights reserved. (MIT Licensed)
146
+ *
147
+ * wuQuant.ts - part of Image Quantization Library
148
+ *//**
149
+ * @preserve
150
+ * Copyright 2015-2018 Igor Bezkrovnyi
151
+ * All rights reserved. (MIT Licensed)
152
+ *
153
+ * xyz2lab.ts - part of Image Quantization Library
154
+ *//**
155
+ * @preserve
156
+ * Copyright 2015-2018 Igor Bezkrovnyi
157
+ * All rights reserved. (MIT Licensed)
158
+ *
159
+ * xyz2rgb.ts - part of Image Quantization Library
160
+ *//**
161
+ * @preserve
162
+ * MIT License
163
+ *
164
+ * Copyright 2015-2018 Igor Bezkrovnyi
165
+ *
166
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
167
+ * of this software and associated documentation files (the "Software"), to
168
+ * deal in the Software without restriction, including without limitation the
169
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
170
+ * sell copies of the Software, and to permit persons to whom the Software is
171
+ * furnished to do so, subject to the following conditions:
172
+ *
173
+ * The above copyright notice and this permission notice shall be included in
174
+ * all copies or substantial portions of the Software.
175
+ *
176
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
177
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
178
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
179
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
180
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
181
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
182
+ * IN THE SOFTWARE.
183
+ *
184
+ * riemersma.ts - part of Image Quantization Library
185
+ *//**
186
+ * @preserve TypeScript port:
187
+ * Copyright 2015-2018 Igor Bezkrovnyi
188
+ * All rights reserved. (MIT Licensed)
189
+ *
190
+ * colorHistogram.ts - part of Image Quantization Library
191
+ *//**
192
+ * @preserve TypeScript port:
193
+ * Copyright 2015-2018 Igor Bezkrovnyi
194
+ * All rights reserved. (MIT Licensed)
195
+ *
196
+ * neuquant.ts - part of Image Quantization Library
197
+ *//**
198
+ * @preserve TypeScript port:
199
+ * Copyright 2015-2018 Igor Bezkrovnyi
200
+ * All rights reserved. (MIT Licensed)
201
+ *
202
+ * rgbquant.ts - part of Image Quantization Library
203
+ */var common={},hasRequiredCommon;function requireCommon(){return hasRequiredCommon||(hasRequiredCommon=1,function(e){var i=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Int32Array<"u";function t(s,o){return Object.prototype.hasOwnProperty.call(s,o)}e.assign=function(s){for(var o=Array.prototype.slice.call(arguments,1);o.length;){var h=o.shift();if(h){if(typeof h!="object")throw new TypeError(h+"must be non-object");for(var f in h)t(h,f)&&(s[f]=h[f])}}return s},e.shrinkBuf=function(s,o){return s.length===o?s:s.subarray?s.subarray(0,o):(s.length=o,s)};var n={arraySet:function(s,o,h,f,l){if(o.subarray&&s.subarray){s.set(o.subarray(h,h+f),l);return}for(var u=0;u<f;u++)s[l+u]=o[h+u]},flattenChunks:function(s){var o,h,f,l,u,w;for(f=0,o=0,h=s.length;o<h;o++)f+=s[o].length;for(w=new Uint8Array(f),l=0,o=0,h=s.length;o<h;o++)u=s[o],w.set(u,l),l+=u.length;return w}},a={arraySet:function(s,o,h,f,l){for(var u=0;u<f;u++)s[l+u]=o[h+u]},flattenChunks:function(s){return[].concat.apply([],s)}};e.setTyped=function(s){s?(e.Buf8=Uint8Array,e.Buf16=Uint16Array,e.Buf32=Int32Array,e.assign(e,n)):(e.Buf8=Array,e.Buf16=Array,e.Buf32=Array,e.assign(e,a))},e.setTyped(i)}(common)),common}var deflate$1={},deflate={},trees={},hasRequiredTrees;function requireTrees(){if(hasRequiredTrees)return trees;hasRequiredTrees=1;var e=requireCommon(),i=4,t=0,n=1,a=2;function s(Z){for(var ue=Z.length;--ue>=0;)Z[ue]=0}var o=0,h=1,f=2,l=3,u=258,w=29,_=256,g=_+1+w,v=30,k=19,A=2*g+1,T=15,$=16,D=7,C=256,P=16,z=17,B=18,F=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],L=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],N=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],G=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],V=512,J=new Array((g+2)*2);s(J);var Q=new Array(v*2);s(Q);var W=new Array(V);s(W);var ne=new Array(u-l+1);s(ne);var me=new Array(w);s(me);var ve=new Array(v);s(ve);function ye(Z,ue,xe,Ae,te){this.static_tree=Z,this.extra_bits=ue,this.extra_base=xe,this.elems=Ae,this.max_length=te,this.has_stree=Z&&Z.length}var Me,Re,_e;function Be(Z,ue){this.dyn_tree=Z,this.max_code=0,this.stat_desc=ue}function Se(Z){return Z<256?W[Z]:W[256+(Z>>>7)]}function re(Z,ue){Z.pending_buf[Z.pending++]=ue&255,Z.pending_buf[Z.pending++]=ue>>>8&255}function Ie(Z,ue,xe){Z.bi_valid>$-xe?(Z.bi_buf|=ue<<Z.bi_valid&65535,re(Z,Z.bi_buf),Z.bi_buf=ue>>$-Z.bi_valid,Z.bi_valid+=xe-$):(Z.bi_buf|=ue<<Z.bi_valid&65535,Z.bi_valid+=xe)}function Fe(Z,ue,xe){Ie(Z,xe[ue*2],xe[ue*2+1])}function ke(Z,ue){var xe=0;do xe|=Z&1,Z>>>=1,xe<<=1;while(--ue>0);return xe>>>1}function Ye(Z){Z.bi_valid===16?(re(Z,Z.bi_buf),Z.bi_buf=0,Z.bi_valid=0):Z.bi_valid>=8&&(Z.pending_buf[Z.pending++]=Z.bi_buf&255,Z.bi_buf>>=8,Z.bi_valid-=8)}function Je(Z,ue){var xe=ue.dyn_tree,Ae=ue.max_code,te=ue.stat_desc.static_tree,pe=ue.stat_desc.has_stree,U=ue.stat_desc.extra_bits,Ee=ue.stat_desc.extra_base,it=ue.stat_desc.max_length,I,fe,de,H,ee,oe,We=0;for(H=0;H<=T;H++)Z.bl_count[H]=0;for(xe[Z.heap[Z.heap_max]*2+1]=0,I=Z.heap_max+1;I<A;I++)fe=Z.heap[I],H=xe[xe[fe*2+1]*2+1]+1,H>it&&(H=it,We++),xe[fe*2+1]=H,!(fe>Ae)&&(Z.bl_count[H]++,ee=0,fe>=Ee&&(ee=U[fe-Ee]),oe=xe[fe*2],Z.opt_len+=oe*(H+ee),pe&&(Z.static_len+=oe*(te[fe*2+1]+ee)));if(We!==0){do{for(H=it-1;Z.bl_count[H]===0;)H--;Z.bl_count[H]--,Z.bl_count[H+1]+=2,Z.bl_count[it]--,We-=2}while(We>0);for(H=it;H!==0;H--)for(fe=Z.bl_count[H];fe!==0;)de=Z.heap[--I],!(de>Ae)&&(xe[de*2+1]!==H&&(Z.opt_len+=(H-xe[de*2+1])*xe[de*2],xe[de*2+1]=H),fe--)}}function et(Z,ue,xe){var Ae=new Array(T+1),te=0,pe,U;for(pe=1;pe<=T;pe++)Ae[pe]=te=te+xe[pe-1]<<1;for(U=0;U<=ue;U++){var Ee=Z[U*2+1];Ee!==0&&(Z[U*2]=ke(Ae[Ee]++,Ee))}}function Ve(){var Z,ue,xe,Ae,te,pe=new Array(T+1);for(xe=0,Ae=0;Ae<w-1;Ae++)for(me[Ae]=xe,Z=0;Z<1<<F[Ae];Z++)ne[xe++]=Ae;for(ne[xe-1]=Ae,te=0,Ae=0;Ae<16;Ae++)for(ve[Ae]=te,Z=0;Z<1<<L[Ae];Z++)W[te++]=Ae;for(te>>=7;Ae<v;Ae++)for(ve[Ae]=te<<7,Z=0;Z<1<<L[Ae]-7;Z++)W[256+te++]=Ae;for(ue=0;ue<=T;ue++)pe[ue]=0;for(Z=0;Z<=143;)J[Z*2+1]=8,Z++,pe[8]++;for(;Z<=255;)J[Z*2+1]=9,Z++,pe[9]++;for(;Z<=279;)J[Z*2+1]=7,Z++,pe[7]++;for(;Z<=287;)J[Z*2+1]=8,Z++,pe[8]++;for(et(J,g+1,pe),Z=0;Z<v;Z++)Q[Z*2+1]=5,Q[Z*2]=ke(Z,5);Me=new ye(J,F,_+1,g,T),Re=new ye(Q,L,0,v,T),_e=new ye(new Array(0),N,0,k,D)}function tt(Z){var ue;for(ue=0;ue<g;ue++)Z.dyn_ltree[ue*2]=0;for(ue=0;ue<v;ue++)Z.dyn_dtree[ue*2]=0;for(ue=0;ue<k;ue++)Z.bl_tree[ue*2]=0;Z.dyn_ltree[C*2]=1,Z.opt_len=Z.static_len=0,Z.last_lit=Z.matches=0}function qe(Z){Z.bi_valid>8?re(Z,Z.bi_buf):Z.bi_valid>0&&(Z.pending_buf[Z.pending++]=Z.bi_buf),Z.bi_buf=0,Z.bi_valid=0}function De(Z,ue,xe,Ae){qe(Z),re(Z,xe),re(Z,~xe),e.arraySet(Z.pending_buf,Z.window,ue,xe,Z.pending),Z.pending+=xe}function nt(Z,ue,xe,Ae){var te=ue*2,pe=xe*2;return Z[te]<Z[pe]||Z[te]===Z[pe]&&Ae[ue]<=Ae[xe]}function Ge(Z,ue,xe){for(var Ae=Z.heap[xe],te=xe<<1;te<=Z.heap_len&&(te<Z.heap_len&&nt(ue,Z.heap[te+1],Z.heap[te],Z.depth)&&te++,!nt(ue,Ae,Z.heap[te],Z.depth));)Z.heap[xe]=Z.heap[te],xe=te,te<<=1;Z.heap[xe]=Ae}function Ne(Z,ue,xe){var Ae,te,pe=0,U,Ee;if(Z.last_lit!==0)do Ae=Z.pending_buf[Z.d_buf+pe*2]<<8|Z.pending_buf[Z.d_buf+pe*2+1],te=Z.pending_buf[Z.l_buf+pe],pe++,Ae===0?Fe(Z,te,ue):(U=ne[te],Fe(Z,U+_+1,ue),Ee=F[U],Ee!==0&&(te-=me[U],Ie(Z,te,Ee)),Ae--,U=Se(Ae),Fe(Z,U,xe),Ee=L[U],Ee!==0&&(Ae-=ve[U],Ie(Z,Ae,Ee)));while(pe<Z.last_lit);Fe(Z,C,ue)}function he(Z,ue){var xe=ue.dyn_tree,Ae=ue.stat_desc.static_tree,te=ue.stat_desc.has_stree,pe=ue.stat_desc.elems,U,Ee,it=-1,I;for(Z.heap_len=0,Z.heap_max=A,U=0;U<pe;U++)xe[U*2]!==0?(Z.heap[++Z.heap_len]=it=U,Z.depth[U]=0):xe[U*2+1]=0;for(;Z.heap_len<2;)I=Z.heap[++Z.heap_len]=it<2?++it:0,xe[I*2]=1,Z.depth[I]=0,Z.opt_len--,te&&(Z.static_len-=Ae[I*2+1]);for(ue.max_code=it,U=Z.heap_len>>1;U>=1;U--)Ge(Z,xe,U);I=pe;do U=Z.heap[1],Z.heap[1]=Z.heap[Z.heap_len--],Ge(Z,xe,1),Ee=Z.heap[1],Z.heap[--Z.heap_max]=U,Z.heap[--Z.heap_max]=Ee,xe[I*2]=xe[U*2]+xe[Ee*2],Z.depth[I]=(Z.depth[U]>=Z.depth[Ee]?Z.depth[U]:Z.depth[Ee])+1,xe[U*2+1]=xe[Ee*2+1]=I,Z.heap[1]=I++,Ge(Z,xe,1);while(Z.heap_len>=2);Z.heap[--Z.heap_max]=Z.heap[1],Je(Z,ue),et(xe,it,Z.bl_count)}function Qe(Z,ue,xe){var Ae,te=-1,pe,U=ue[0*2+1],Ee=0,it=7,I=4;for(U===0&&(it=138,I=3),ue[(xe+1)*2+1]=65535,Ae=0;Ae<=xe;Ae++)pe=U,U=ue[(Ae+1)*2+1],!(++Ee<it&&pe===U)&&(Ee<I?Z.bl_tree[pe*2]+=Ee:pe!==0?(pe!==te&&Z.bl_tree[pe*2]++,Z.bl_tree[P*2]++):Ee<=10?Z.bl_tree[z*2]++:Z.bl_tree[B*2]++,Ee=0,te=pe,U===0?(it=138,I=3):pe===U?(it=6,I=3):(it=7,I=4))}function Ze(Z,ue,xe){var Ae,te=-1,pe,U=ue[0*2+1],Ee=0,it=7,I=4;for(U===0&&(it=138,I=3),Ae=0;Ae<=xe;Ae++)if(pe=U,U=ue[(Ae+1)*2+1],!(++Ee<it&&pe===U)){if(Ee<I)do Fe(Z,pe,Z.bl_tree);while(--Ee!==0);else pe!==0?(pe!==te&&(Fe(Z,pe,Z.bl_tree),Ee--),Fe(Z,P,Z.bl_tree),Ie(Z,Ee-3,2)):Ee<=10?(Fe(Z,z,Z.bl_tree),Ie(Z,Ee-3,3)):(Fe(Z,B,Z.bl_tree),Ie(Z,Ee-11,7));Ee=0,te=pe,U===0?(it=138,I=3):pe===U?(it=6,I=3):(it=7,I=4)}}function He(Z){var ue;for(Qe(Z,Z.dyn_ltree,Z.l_desc.max_code),Qe(Z,Z.dyn_dtree,Z.d_desc.max_code),he(Z,Z.bl_desc),ue=k-1;ue>=3&&Z.bl_tree[G[ue]*2+1]===0;ue--);return Z.opt_len+=3*(ue+1)+5+5+4,ue}function Te(Z,ue,xe,Ae){var te;for(Ie(Z,ue-257,5),Ie(Z,xe-1,5),Ie(Z,Ae-4,4),te=0;te<Ae;te++)Ie(Z,Z.bl_tree[G[te]*2+1],3);Ze(Z,Z.dyn_ltree,ue-1),Ze(Z,Z.dyn_dtree,xe-1)}function lt(Z){var ue=4093624447,xe;for(xe=0;xe<=31;xe++,ue>>>=1)if(ue&1&&Z.dyn_ltree[xe*2]!==0)return t;if(Z.dyn_ltree[9*2]!==0||Z.dyn_ltree[10*2]!==0||Z.dyn_ltree[13*2]!==0)return n;for(xe=32;xe<_;xe++)if(Z.dyn_ltree[xe*2]!==0)return n;return t}var ot=!1;function Le(Z){ot||(Ve(),ot=!0),Z.l_desc=new Be(Z.dyn_ltree,Me),Z.d_desc=new Be(Z.dyn_dtree,Re),Z.bl_desc=new Be(Z.bl_tree,_e),Z.bi_buf=0,Z.bi_valid=0,tt(Z)}function ze(Z,ue,xe,Ae){Ie(Z,(o<<1)+(Ae?1:0),3),De(Z,ue,xe)}function je(Z){Ie(Z,h<<1,3),Fe(Z,C,J),Ye(Z)}function Oe(Z,ue,xe,Ae){var te,pe,U=0;Z.level>0?(Z.strm.data_type===a&&(Z.strm.data_type=lt(Z)),he(Z,Z.l_desc),he(Z,Z.d_desc),U=He(Z),te=Z.opt_len+3+7>>>3,pe=Z.static_len+3+7>>>3,pe<=te&&(te=pe)):te=pe=xe+5,xe+4<=te&&ue!==-1?ze(Z,ue,xe,Ae):Z.strategy===i||pe===te?(Ie(Z,(h<<1)+(Ae?1:0),3),Ne(Z,J,Q)):(Ie(Z,(f<<1)+(Ae?1:0),3),Te(Z,Z.l_desc.max_code+1,Z.d_desc.max_code+1,U+1),Ne(Z,Z.dyn_ltree,Z.dyn_dtree)),tt(Z),Ae&&qe(Z)}function st(Z,ue,xe){return Z.pending_buf[Z.d_buf+Z.last_lit*2]=ue>>>8&255,Z.pending_buf[Z.d_buf+Z.last_lit*2+1]=ue&255,Z.pending_buf[Z.l_buf+Z.last_lit]=xe&255,Z.last_lit++,ue===0?Z.dyn_ltree[xe*2]++:(Z.matches++,ue--,Z.dyn_ltree[(ne[xe]+_+1)*2]++,Z.dyn_dtree[Se(ue)*2]++),Z.last_lit===Z.lit_bufsize-1}return trees._tr_init=Le,trees._tr_stored_block=ze,trees._tr_flush_block=Oe,trees._tr_tally=st,trees._tr_align=je,trees}var adler32_1,hasRequiredAdler32;function requireAdler32(){if(hasRequiredAdler32)return adler32_1;hasRequiredAdler32=1;function e(i,t,n,a){for(var s=i&65535|0,o=i>>>16&65535|0,h=0;n!==0;){h=n>2e3?2e3:n,n-=h;do s=s+t[a++]|0,o=o+s|0;while(--h);s%=65521,o%=65521}return s|o<<16|0}return adler32_1=e,adler32_1}var crc32_1,hasRequiredCrc32;function requireCrc32(){if(hasRequiredCrc32)return crc32_1;hasRequiredCrc32=1;function e(){for(var n,a=[],s=0;s<256;s++){n=s;for(var o=0;o<8;o++)n=n&1?3988292384^n>>>1:n>>>1;a[s]=n}return a}var i=e();function t(n,a,s,o){var h=i,f=o+s;n^=-1;for(var l=o;l<f;l++)n=n>>>8^h[(n^a[l])&255];return n^-1}return crc32_1=t,crc32_1}var messages,hasRequiredMessages;function requireMessages(){return hasRequiredMessages||(hasRequiredMessages=1,messages={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}),messages}var hasRequiredDeflate$1;function requireDeflate$1(){if(hasRequiredDeflate$1)return deflate;hasRequiredDeflate$1=1;var e=requireCommon(),i=requireTrees(),t=requireAdler32(),n=requireCrc32(),a=requireMessages(),s=0,o=1,h=3,f=4,l=5,u=0,w=1,_=-2,g=-3,v=-5,k=-1,A=1,T=2,$=3,D=4,C=0,P=2,z=8,B=9,F=15,L=8,N=29,G=256,V=G+1+N,J=30,Q=19,W=2*V+1,ne=15,me=3,ve=258,ye=ve+me+1,Me=32,Re=42,_e=69,Be=73,Se=91,re=103,Ie=113,Fe=666,ke=1,Ye=2,Je=3,et=4,Ve=3;function tt(I,fe){return I.msg=a[fe],fe}function qe(I){return(I<<1)-(I>4?9:0)}function De(I){for(var fe=I.length;--fe>=0;)I[fe]=0}function nt(I){var fe=I.state,de=fe.pending;de>I.avail_out&&(de=I.avail_out),de!==0&&(e.arraySet(I.output,fe.pending_buf,fe.pending_out,de,I.next_out),I.next_out+=de,fe.pending_out+=de,I.total_out+=de,I.avail_out-=de,fe.pending-=de,fe.pending===0&&(fe.pending_out=0))}function Ge(I,fe){i._tr_flush_block(I,I.block_start>=0?I.block_start:-1,I.strstart-I.block_start,fe),I.block_start=I.strstart,nt(I.strm)}function Ne(I,fe){I.pending_buf[I.pending++]=fe}function he(I,fe){I.pending_buf[I.pending++]=fe>>>8&255,I.pending_buf[I.pending++]=fe&255}function Qe(I,fe,de,H){var ee=I.avail_in;return ee>H&&(ee=H),ee===0?0:(I.avail_in-=ee,e.arraySet(fe,I.input,I.next_in,ee,de),I.state.wrap===1?I.adler=t(I.adler,fe,ee,de):I.state.wrap===2&&(I.adler=n(I.adler,fe,ee,de)),I.next_in+=ee,I.total_in+=ee,ee)}function Ze(I,fe){var de=I.max_chain_length,H=I.strstart,ee,oe,We=I.prev_length,M=I.nice_match,m=I.strstart>I.w_size-ye?I.strstart-(I.w_size-ye):0,d=I.window,c=I.w_mask,b=I.prev,S=I.strstart+ve,O=d[H+We-1],q=d[H+We];I.prev_length>=I.good_match&&(de>>=2),M>I.lookahead&&(M=I.lookahead);do if(ee=fe,!(d[ee+We]!==q||d[ee+We-1]!==O||d[ee]!==d[H]||d[++ee]!==d[H+1])){H+=2,ee++;do;while(d[++H]===d[++ee]&&d[++H]===d[++ee]&&d[++H]===d[++ee]&&d[++H]===d[++ee]&&d[++H]===d[++ee]&&d[++H]===d[++ee]&&d[++H]===d[++ee]&&d[++H]===d[++ee]&&H<S);if(oe=ve-(S-H),H=S-ve,oe>We){if(I.match_start=fe,We=oe,oe>=M)break;O=d[H+We-1],q=d[H+We]}}while((fe=b[fe&c])>m&&--de!==0);return We<=I.lookahead?We:I.lookahead}function He(I){var fe=I.w_size,de,H,ee,oe,We;do{if(oe=I.window_size-I.lookahead-I.strstart,I.strstart>=fe+(fe-ye)){e.arraySet(I.window,I.window,fe,fe,0),I.match_start-=fe,I.strstart-=fe,I.block_start-=fe,H=I.hash_size,de=H;do ee=I.head[--de],I.head[de]=ee>=fe?ee-fe:0;while(--H);H=fe,de=H;do ee=I.prev[--de],I.prev[de]=ee>=fe?ee-fe:0;while(--H);oe+=fe}if(I.strm.avail_in===0)break;if(H=Qe(I.strm,I.window,I.strstart+I.lookahead,oe),I.lookahead+=H,I.lookahead+I.insert>=me)for(We=I.strstart-I.insert,I.ins_h=I.window[We],I.ins_h=(I.ins_h<<I.hash_shift^I.window[We+1])&I.hash_mask;I.insert&&(I.ins_h=(I.ins_h<<I.hash_shift^I.window[We+me-1])&I.hash_mask,I.prev[We&I.w_mask]=I.head[I.ins_h],I.head[I.ins_h]=We,We++,I.insert--,!(I.lookahead+I.insert<me)););}while(I.lookahead<ye&&I.strm.avail_in!==0)}function Te(I,fe){var de=65535;for(de>I.pending_buf_size-5&&(de=I.pending_buf_size-5);;){if(I.lookahead<=1){if(He(I),I.lookahead===0&&fe===s)return ke;if(I.lookahead===0)break}I.strstart+=I.lookahead,I.lookahead=0;var H=I.block_start+de;if((I.strstart===0||I.strstart>=H)&&(I.lookahead=I.strstart-H,I.strstart=H,Ge(I,!1),I.strm.avail_out===0)||I.strstart-I.block_start>=I.w_size-ye&&(Ge(I,!1),I.strm.avail_out===0))return ke}return I.insert=0,fe===f?(Ge(I,!0),I.strm.avail_out===0?Je:et):(I.strstart>I.block_start&&(Ge(I,!1),I.strm.avail_out===0),ke)}function lt(I,fe){for(var de,H;;){if(I.lookahead<ye){if(He(I),I.lookahead<ye&&fe===s)return ke;if(I.lookahead===0)break}if(de=0,I.lookahead>=me&&(I.ins_h=(I.ins_h<<I.hash_shift^I.window[I.strstart+me-1])&I.hash_mask,de=I.prev[I.strstart&I.w_mask]=I.head[I.ins_h],I.head[I.ins_h]=I.strstart),de!==0&&I.strstart-de<=I.w_size-ye&&(I.match_length=Ze(I,de)),I.match_length>=me)if(H=i._tr_tally(I,I.strstart-I.match_start,I.match_length-me),I.lookahead-=I.match_length,I.match_length<=I.max_lazy_match&&I.lookahead>=me){I.match_length--;do I.strstart++,I.ins_h=(I.ins_h<<I.hash_shift^I.window[I.strstart+me-1])&I.hash_mask,de=I.prev[I.strstart&I.w_mask]=I.head[I.ins_h],I.head[I.ins_h]=I.strstart;while(--I.match_length!==0);I.strstart++}else I.strstart+=I.match_length,I.match_length=0,I.ins_h=I.window[I.strstart],I.ins_h=(I.ins_h<<I.hash_shift^I.window[I.strstart+1])&I.hash_mask;else H=i._tr_tally(I,0,I.window[I.strstart]),I.lookahead--,I.strstart++;if(H&&(Ge(I,!1),I.strm.avail_out===0))return ke}return I.insert=I.strstart<me-1?I.strstart:me-1,fe===f?(Ge(I,!0),I.strm.avail_out===0?Je:et):I.last_lit&&(Ge(I,!1),I.strm.avail_out===0)?ke:Ye}function ot(I,fe){for(var de,H,ee;;){if(I.lookahead<ye){if(He(I),I.lookahead<ye&&fe===s)return ke;if(I.lookahead===0)break}if(de=0,I.lookahead>=me&&(I.ins_h=(I.ins_h<<I.hash_shift^I.window[I.strstart+me-1])&I.hash_mask,de=I.prev[I.strstart&I.w_mask]=I.head[I.ins_h],I.head[I.ins_h]=I.strstart),I.prev_length=I.match_length,I.prev_match=I.match_start,I.match_length=me-1,de!==0&&I.prev_length<I.max_lazy_match&&I.strstart-de<=I.w_size-ye&&(I.match_length=Ze(I,de),I.match_length<=5&&(I.strategy===A||I.match_length===me&&I.strstart-I.match_start>4096)&&(I.match_length=me-1)),I.prev_length>=me&&I.match_length<=I.prev_length){ee=I.strstart+I.lookahead-me,H=i._tr_tally(I,I.strstart-1-I.prev_match,I.prev_length-me),I.lookahead-=I.prev_length-1,I.prev_length-=2;do++I.strstart<=ee&&(I.ins_h=(I.ins_h<<I.hash_shift^I.window[I.strstart+me-1])&I.hash_mask,de=I.prev[I.strstart&I.w_mask]=I.head[I.ins_h],I.head[I.ins_h]=I.strstart);while(--I.prev_length!==0);if(I.match_available=0,I.match_length=me-1,I.strstart++,H&&(Ge(I,!1),I.strm.avail_out===0))return ke}else if(I.match_available){if(H=i._tr_tally(I,0,I.window[I.strstart-1]),H&&Ge(I,!1),I.strstart++,I.lookahead--,I.strm.avail_out===0)return ke}else I.match_available=1,I.strstart++,I.lookahead--}return I.match_available&&(H=i._tr_tally(I,0,I.window[I.strstart-1]),I.match_available=0),I.insert=I.strstart<me-1?I.strstart:me-1,fe===f?(Ge(I,!0),I.strm.avail_out===0?Je:et):I.last_lit&&(Ge(I,!1),I.strm.avail_out===0)?ke:Ye}function Le(I,fe){for(var de,H,ee,oe,We=I.window;;){if(I.lookahead<=ve){if(He(I),I.lookahead<=ve&&fe===s)return ke;if(I.lookahead===0)break}if(I.match_length=0,I.lookahead>=me&&I.strstart>0&&(ee=I.strstart-1,H=We[ee],H===We[++ee]&&H===We[++ee]&&H===We[++ee])){oe=I.strstart+ve;do;while(H===We[++ee]&&H===We[++ee]&&H===We[++ee]&&H===We[++ee]&&H===We[++ee]&&H===We[++ee]&&H===We[++ee]&&H===We[++ee]&&ee<oe);I.match_length=ve-(oe-ee),I.match_length>I.lookahead&&(I.match_length=I.lookahead)}if(I.match_length>=me?(de=i._tr_tally(I,1,I.match_length-me),I.lookahead-=I.match_length,I.strstart+=I.match_length,I.match_length=0):(de=i._tr_tally(I,0,I.window[I.strstart]),I.lookahead--,I.strstart++),de&&(Ge(I,!1),I.strm.avail_out===0))return ke}return I.insert=0,fe===f?(Ge(I,!0),I.strm.avail_out===0?Je:et):I.last_lit&&(Ge(I,!1),I.strm.avail_out===0)?ke:Ye}function ze(I,fe){for(var de;;){if(I.lookahead===0&&(He(I),I.lookahead===0)){if(fe===s)return ke;break}if(I.match_length=0,de=i._tr_tally(I,0,I.window[I.strstart]),I.lookahead--,I.strstart++,de&&(Ge(I,!1),I.strm.avail_out===0))return ke}return I.insert=0,fe===f?(Ge(I,!0),I.strm.avail_out===0?Je:et):I.last_lit&&(Ge(I,!1),I.strm.avail_out===0)?ke:Ye}function je(I,fe,de,H,ee){this.good_length=I,this.max_lazy=fe,this.nice_length=de,this.max_chain=H,this.func=ee}var Oe;Oe=[new je(0,0,0,0,Te),new je(4,4,8,4,lt),new je(4,5,16,8,lt),new je(4,6,32,32,lt),new je(4,4,16,16,ot),new je(8,16,32,32,ot),new je(8,16,128,128,ot),new je(8,32,128,256,ot),new je(32,128,258,1024,ot),new je(32,258,258,4096,ot)];function st(I){I.window_size=2*I.w_size,De(I.head),I.max_lazy_match=Oe[I.level].max_lazy,I.good_match=Oe[I.level].good_length,I.nice_match=Oe[I.level].nice_length,I.max_chain_length=Oe[I.level].max_chain,I.strstart=0,I.block_start=0,I.lookahead=0,I.insert=0,I.match_length=I.prev_length=me-1,I.match_available=0,I.ins_h=0}function Z(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=z,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new e.Buf16(W*2),this.dyn_dtree=new e.Buf16((2*J+1)*2),this.bl_tree=new e.Buf16((2*Q+1)*2),De(this.dyn_ltree),De(this.dyn_dtree),De(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new e.Buf16(ne+1),this.heap=new e.Buf16(2*V+1),De(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new e.Buf16(2*V+1),De(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function ue(I){var fe;return!I||!I.state?tt(I,_):(I.total_in=I.total_out=0,I.data_type=P,fe=I.state,fe.pending=0,fe.pending_out=0,fe.wrap<0&&(fe.wrap=-fe.wrap),fe.status=fe.wrap?Re:Ie,I.adler=fe.wrap===2?0:1,fe.last_flush=s,i._tr_init(fe),u)}function xe(I){var fe=ue(I);return fe===u&&st(I.state),fe}function Ae(I,fe){return!I||!I.state||I.state.wrap!==2?_:(I.state.gzhead=fe,u)}function te(I,fe,de,H,ee,oe){if(!I)return _;var We=1;if(fe===k&&(fe=6),H<0?(We=0,H=-H):H>15&&(We=2,H-=16),ee<1||ee>B||de!==z||H<8||H>15||fe<0||fe>9||oe<0||oe>D)return tt(I,_);H===8&&(H=9);var M=new Z;return I.state=M,M.strm=I,M.wrap=We,M.gzhead=null,M.w_bits=H,M.w_size=1<<M.w_bits,M.w_mask=M.w_size-1,M.hash_bits=ee+7,M.hash_size=1<<M.hash_bits,M.hash_mask=M.hash_size-1,M.hash_shift=~~((M.hash_bits+me-1)/me),M.window=new e.Buf8(M.w_size*2),M.head=new e.Buf16(M.hash_size),M.prev=new e.Buf16(M.w_size),M.lit_bufsize=1<<ee+6,M.pending_buf_size=M.lit_bufsize*4,M.pending_buf=new e.Buf8(M.pending_buf_size),M.d_buf=1*M.lit_bufsize,M.l_buf=3*M.lit_bufsize,M.level=fe,M.strategy=oe,M.method=de,xe(I)}function pe(I,fe){return te(I,fe,z,F,L,C)}function U(I,fe){var de,H,ee,oe;if(!I||!I.state||fe>l||fe<0)return I?tt(I,_):_;if(H=I.state,!I.output||!I.input&&I.avail_in!==0||H.status===Fe&&fe!==f)return tt(I,I.avail_out===0?v:_);if(H.strm=I,de=H.last_flush,H.last_flush=fe,H.status===Re)if(H.wrap===2)I.adler=0,Ne(H,31),Ne(H,139),Ne(H,8),H.gzhead?(Ne(H,(H.gzhead.text?1:0)+(H.gzhead.hcrc?2:0)+(H.gzhead.extra?4:0)+(H.gzhead.name?8:0)+(H.gzhead.comment?16:0)),Ne(H,H.gzhead.time&255),Ne(H,H.gzhead.time>>8&255),Ne(H,H.gzhead.time>>16&255),Ne(H,H.gzhead.time>>24&255),Ne(H,H.level===9?2:H.strategy>=T||H.level<2?4:0),Ne(H,H.gzhead.os&255),H.gzhead.extra&&H.gzhead.extra.length&&(Ne(H,H.gzhead.extra.length&255),Ne(H,H.gzhead.extra.length>>8&255)),H.gzhead.hcrc&&(I.adler=n(I.adler,H.pending_buf,H.pending,0)),H.gzindex=0,H.status=_e):(Ne(H,0),Ne(H,0),Ne(H,0),Ne(H,0),Ne(H,0),Ne(H,H.level===9?2:H.strategy>=T||H.level<2?4:0),Ne(H,Ve),H.status=Ie);else{var We=z+(H.w_bits-8<<4)<<8,M=-1;H.strategy>=T||H.level<2?M=0:H.level<6?M=1:H.level===6?M=2:M=3,We|=M<<6,H.strstart!==0&&(We|=Me),We+=31-We%31,H.status=Ie,he(H,We),H.strstart!==0&&(he(H,I.adler>>>16),he(H,I.adler&65535)),I.adler=1}if(H.status===_e)if(H.gzhead.extra){for(ee=H.pending;H.gzindex<(H.gzhead.extra.length&65535)&&!(H.pending===H.pending_buf_size&&(H.gzhead.hcrc&&H.pending>ee&&(I.adler=n(I.adler,H.pending_buf,H.pending-ee,ee)),nt(I),ee=H.pending,H.pending===H.pending_buf_size));)Ne(H,H.gzhead.extra[H.gzindex]&255),H.gzindex++;H.gzhead.hcrc&&H.pending>ee&&(I.adler=n(I.adler,H.pending_buf,H.pending-ee,ee)),H.gzindex===H.gzhead.extra.length&&(H.gzindex=0,H.status=Be)}else H.status=Be;if(H.status===Be)if(H.gzhead.name){ee=H.pending;do{if(H.pending===H.pending_buf_size&&(H.gzhead.hcrc&&H.pending>ee&&(I.adler=n(I.adler,H.pending_buf,H.pending-ee,ee)),nt(I),ee=H.pending,H.pending===H.pending_buf_size)){oe=1;break}H.gzindex<H.gzhead.name.length?oe=H.gzhead.name.charCodeAt(H.gzindex++)&255:oe=0,Ne(H,oe)}while(oe!==0);H.gzhead.hcrc&&H.pending>ee&&(I.adler=n(I.adler,H.pending_buf,H.pending-ee,ee)),oe===0&&(H.gzindex=0,H.status=Se)}else H.status=Se;if(H.status===Se)if(H.gzhead.comment){ee=H.pending;do{if(H.pending===H.pending_buf_size&&(H.gzhead.hcrc&&H.pending>ee&&(I.adler=n(I.adler,H.pending_buf,H.pending-ee,ee)),nt(I),ee=H.pending,H.pending===H.pending_buf_size)){oe=1;break}H.gzindex<H.gzhead.comment.length?oe=H.gzhead.comment.charCodeAt(H.gzindex++)&255:oe=0,Ne(H,oe)}while(oe!==0);H.gzhead.hcrc&&H.pending>ee&&(I.adler=n(I.adler,H.pending_buf,H.pending-ee,ee)),oe===0&&(H.status=re)}else H.status=re;if(H.status===re&&(H.gzhead.hcrc?(H.pending+2>H.pending_buf_size&&nt(I),H.pending+2<=H.pending_buf_size&&(Ne(H,I.adler&255),Ne(H,I.adler>>8&255),I.adler=0,H.status=Ie)):H.status=Ie),H.pending!==0){if(nt(I),I.avail_out===0)return H.last_flush=-1,u}else if(I.avail_in===0&&qe(fe)<=qe(de)&&fe!==f)return tt(I,v);if(H.status===Fe&&I.avail_in!==0)return tt(I,v);if(I.avail_in!==0||H.lookahead!==0||fe!==s&&H.status!==Fe){var m=H.strategy===T?ze(H,fe):H.strategy===$?Le(H,fe):Oe[H.level].func(H,fe);if((m===Je||m===et)&&(H.status=Fe),m===ke||m===Je)return I.avail_out===0&&(H.last_flush=-1),u;if(m===Ye&&(fe===o?i._tr_align(H):fe!==l&&(i._tr_stored_block(H,0,0,!1),fe===h&&(De(H.head),H.lookahead===0&&(H.strstart=0,H.block_start=0,H.insert=0))),nt(I),I.avail_out===0))return H.last_flush=-1,u}return fe!==f?u:H.wrap<=0?w:(H.wrap===2?(Ne(H,I.adler&255),Ne(H,I.adler>>8&255),Ne(H,I.adler>>16&255),Ne(H,I.adler>>24&255),Ne(H,I.total_in&255),Ne(H,I.total_in>>8&255),Ne(H,I.total_in>>16&255),Ne(H,I.total_in>>24&255)):(he(H,I.adler>>>16),he(H,I.adler&65535)),nt(I),H.wrap>0&&(H.wrap=-H.wrap),H.pending!==0?u:w)}function Ee(I){var fe;return!I||!I.state?_:(fe=I.state.status,fe!==Re&&fe!==_e&&fe!==Be&&fe!==Se&&fe!==re&&fe!==Ie&&fe!==Fe?tt(I,_):(I.state=null,fe===Ie?tt(I,g):u))}function it(I,fe){var de=fe.length,H,ee,oe,We,M,m,d,c;if(!I||!I.state||(H=I.state,We=H.wrap,We===2||We===1&&H.status!==Re||H.lookahead))return _;for(We===1&&(I.adler=t(I.adler,fe,de,0)),H.wrap=0,de>=H.w_size&&(We===0&&(De(H.head),H.strstart=0,H.block_start=0,H.insert=0),c=new e.Buf8(H.w_size),e.arraySet(c,fe,de-H.w_size,H.w_size,0),fe=c,de=H.w_size),M=I.avail_in,m=I.next_in,d=I.input,I.avail_in=de,I.next_in=0,I.input=fe,He(H);H.lookahead>=me;){ee=H.strstart,oe=H.lookahead-(me-1);do H.ins_h=(H.ins_h<<H.hash_shift^H.window[ee+me-1])&H.hash_mask,H.prev[ee&H.w_mask]=H.head[H.ins_h],H.head[H.ins_h]=ee,ee++;while(--oe);H.strstart=ee,H.lookahead=me-1,He(H)}return H.strstart+=H.lookahead,H.block_start=H.strstart,H.insert=H.lookahead,H.lookahead=0,H.match_length=H.prev_length=me-1,H.match_available=0,I.next_in=m,I.input=d,I.avail_in=M,H.wrap=We,u}return deflate.deflateInit=pe,deflate.deflateInit2=te,deflate.deflateReset=xe,deflate.deflateResetKeep=ue,deflate.deflateSetHeader=Ae,deflate.deflate=U,deflate.deflateEnd=Ee,deflate.deflateSetDictionary=it,deflate.deflateInfo="pako deflate (from Nodeca project)",deflate}var strings={},hasRequiredStrings;function requireStrings(){if(hasRequiredStrings)return strings;hasRequiredStrings=1;var e=requireCommon(),i=!0,t=!0;try{String.fromCharCode.apply(null,[0])}catch{i=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch{t=!1}for(var n=new e.Buf8(256),a=0;a<256;a++)n[a]=a>=252?6:a>=248?5:a>=240?4:a>=224?3:a>=192?2:1;n[254]=n[254]=1,strings.string2buf=function(o){var h,f,l,u,w,_=o.length,g=0;for(u=0;u<_;u++)f=o.charCodeAt(u),(f&64512)===55296&&u+1<_&&(l=o.charCodeAt(u+1),(l&64512)===56320&&(f=65536+(f-55296<<10)+(l-56320),u++)),g+=f<128?1:f<2048?2:f<65536?3:4;for(h=new e.Buf8(g),w=0,u=0;w<g;u++)f=o.charCodeAt(u),(f&64512)===55296&&u+1<_&&(l=o.charCodeAt(u+1),(l&64512)===56320&&(f=65536+(f-55296<<10)+(l-56320),u++)),f<128?h[w++]=f:f<2048?(h[w++]=192|f>>>6,h[w++]=128|f&63):f<65536?(h[w++]=224|f>>>12,h[w++]=128|f>>>6&63,h[w++]=128|f&63):(h[w++]=240|f>>>18,h[w++]=128|f>>>12&63,h[w++]=128|f>>>6&63,h[w++]=128|f&63);return h};function s(o,h){if(h<65534&&(o.subarray&&t||!o.subarray&&i))return String.fromCharCode.apply(null,e.shrinkBuf(o,h));for(var f="",l=0;l<h;l++)f+=String.fromCharCode(o[l]);return f}return strings.buf2binstring=function(o){return s(o,o.length)},strings.binstring2buf=function(o){for(var h=new e.Buf8(o.length),f=0,l=h.length;f<l;f++)h[f]=o.charCodeAt(f);return h},strings.buf2string=function(o,h){var f,l,u,w,_=h||o.length,g=new Array(_*2);for(l=0,f=0;f<_;){if(u=o[f++],u<128){g[l++]=u;continue}if(w=n[u],w>4){g[l++]=65533,f+=w-1;continue}for(u&=w===2?31:w===3?15:7;w>1&&f<_;)u=u<<6|o[f++]&63,w--;if(w>1){g[l++]=65533;continue}u<65536?g[l++]=u:(u-=65536,g[l++]=55296|u>>10&1023,g[l++]=56320|u&1023)}return s(g,l)},strings.utf8border=function(o,h){var f;for(h=h||o.length,h>o.length&&(h=o.length),f=h-1;f>=0&&(o[f]&192)===128;)f--;return f<0||f===0?h:f+n[o[f]]>h?f:h},strings}var zstream,hasRequiredZstream;function requireZstream(){if(hasRequiredZstream)return zstream;hasRequiredZstream=1;function e(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}return zstream=e,zstream}var hasRequiredDeflate;function requireDeflate(){if(hasRequiredDeflate)return deflate$1;hasRequiredDeflate=1;var e=requireDeflate$1(),i=requireCommon(),t=requireStrings(),n=requireMessages(),a=requireZstream(),s=Object.prototype.toString,o=0,h=4,f=0,l=1,u=2,w=-1,_=0,g=8;function v($){if(!(this instanceof v))return new v($);this.options=i.assign({level:w,method:g,chunkSize:16384,windowBits:15,memLevel:8,strategy:_,to:""},$||{});var D=this.options;D.raw&&D.windowBits>0?D.windowBits=-D.windowBits:D.gzip&&D.windowBits>0&&D.windowBits<16&&(D.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new a,this.strm.avail_out=0;var C=e.deflateInit2(this.strm,D.level,D.method,D.windowBits,D.memLevel,D.strategy);if(C!==f)throw new Error(n[C]);if(D.header&&e.deflateSetHeader(this.strm,D.header),D.dictionary){var P;if(typeof D.dictionary=="string"?P=t.string2buf(D.dictionary):s.call(D.dictionary)==="[object ArrayBuffer]"?P=new Uint8Array(D.dictionary):P=D.dictionary,C=e.deflateSetDictionary(this.strm,P),C!==f)throw new Error(n[C]);this._dict_set=!0}}v.prototype.push=function($,D){var C=this.strm,P=this.options.chunkSize,z,B;if(this.ended)return!1;B=D===~~D?D:D===!0?h:o,typeof $=="string"?C.input=t.string2buf($):s.call($)==="[object ArrayBuffer]"?C.input=new Uint8Array($):C.input=$,C.next_in=0,C.avail_in=C.input.length;do{if(C.avail_out===0&&(C.output=new i.Buf8(P),C.next_out=0,C.avail_out=P),z=e.deflate(C,B),z!==l&&z!==f)return this.onEnd(z),this.ended=!0,!1;(C.avail_out===0||C.avail_in===0&&(B===h||B===u))&&(this.options.to==="string"?this.onData(t.buf2binstring(i.shrinkBuf(C.output,C.next_out))):this.onData(i.shrinkBuf(C.output,C.next_out)))}while((C.avail_in>0||C.avail_out===0)&&z!==l);return B===h?(z=e.deflateEnd(this.strm),this.onEnd(z),this.ended=!0,z===f):(B===u&&(this.onEnd(f),C.avail_out=0),!0)},v.prototype.onData=function($){this.chunks.push($)},v.prototype.onEnd=function($){$===f&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=i.flattenChunks(this.chunks)),this.chunks=[],this.err=$,this.msg=this.strm.msg};function k($,D){var C=new v(D);if(C.push($,!0),C.err)throw C.msg||n[C.err];return C.result}function A($,D){return D=D||{},D.raw=!0,k($,D)}function T($,D){return D=D||{},D.gzip=!0,k($,D)}return deflate$1.Deflate=v,deflate$1.deflate=k,deflate$1.deflateRaw=A,deflate$1.gzip=T,deflate$1}var inflate$1={},inflate={},inffast,hasRequiredInffast;function requireInffast(){if(hasRequiredInffast)return inffast;hasRequiredInffast=1;var e=30,i=12;return inffast=function(n,a){var s,o,h,f,l,u,w,_,g,v,k,A,T,$,D,C,P,z,B,F,L,N,G,V,J;s=n.state,o=n.next_in,V=n.input,h=o+(n.avail_in-5),f=n.next_out,J=n.output,l=f-(a-n.avail_out),u=f+(n.avail_out-257),w=s.dmax,_=s.wsize,g=s.whave,v=s.wnext,k=s.window,A=s.hold,T=s.bits,$=s.lencode,D=s.distcode,C=(1<<s.lenbits)-1,P=(1<<s.distbits)-1;e:do{T<15&&(A+=V[o++]<<T,T+=8,A+=V[o++]<<T,T+=8),z=$[A&C];t:for(;;){if(B=z>>>24,A>>>=B,T-=B,B=z>>>16&255,B===0)J[f++]=z&65535;else if(B&16){F=z&65535,B&=15,B&&(T<B&&(A+=V[o++]<<T,T+=8),F+=A&(1<<B)-1,A>>>=B,T-=B),T<15&&(A+=V[o++]<<T,T+=8,A+=V[o++]<<T,T+=8),z=D[A&P];i:for(;;){if(B=z>>>24,A>>>=B,T-=B,B=z>>>16&255,B&16){if(L=z&65535,B&=15,T<B&&(A+=V[o++]<<T,T+=8,T<B&&(A+=V[o++]<<T,T+=8)),L+=A&(1<<B)-1,L>w){n.msg="invalid distance too far back",s.mode=e;break e}if(A>>>=B,T-=B,B=f-l,L>B){if(B=L-B,B>g&&s.sane){n.msg="invalid distance too far back",s.mode=e;break e}if(N=0,G=k,v===0){if(N+=_-B,B<F){F-=B;do J[f++]=k[N++];while(--B);N=f-L,G=J}}else if(v<B){if(N+=_+v-B,B-=v,B<F){F-=B;do J[f++]=k[N++];while(--B);if(N=0,v<F){B=v,F-=B;do J[f++]=k[N++];while(--B);N=f-L,G=J}}}else if(N+=v-B,B<F){F-=B;do J[f++]=k[N++];while(--B);N=f-L,G=J}for(;F>2;)J[f++]=G[N++],J[f++]=G[N++],J[f++]=G[N++],F-=3;F&&(J[f++]=G[N++],F>1&&(J[f++]=G[N++]))}else{N=f-L;do J[f++]=J[N++],J[f++]=J[N++],J[f++]=J[N++],F-=3;while(F>2);F&&(J[f++]=J[N++],F>1&&(J[f++]=J[N++]))}}else if((B&64)===0){z=D[(z&65535)+(A&(1<<B)-1)];continue i}else{n.msg="invalid distance code",s.mode=e;break e}break}}else if((B&64)===0){z=$[(z&65535)+(A&(1<<B)-1)];continue t}else if(B&32){s.mode=i;break e}else{n.msg="invalid literal/length code",s.mode=e;break e}break}}while(o<h&&f<u);F=T>>3,o-=F,T-=F<<3,A&=(1<<T)-1,n.next_in=o,n.next_out=f,n.avail_in=o<h?5+(h-o):5-(o-h),n.avail_out=f<u?257+(u-f):257-(f-u),s.hold=A,s.bits=T},inffast}var inftrees,hasRequiredInftrees;function requireInftrees(){if(hasRequiredInftrees)return inftrees;hasRequiredInftrees=1;var e=requireCommon(),i=15,t=852,n=592,a=0,s=1,o=2,h=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],f=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],l=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],u=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];return inftrees=function(_,g,v,k,A,T,$,D){var C=D.bits,P=0,z=0,B=0,F=0,L=0,N=0,G=0,V=0,J=0,Q=0,W,ne,me,ve,ye,Me=null,Re=0,_e,Be=new e.Buf16(i+1),Se=new e.Buf16(i+1),re=null,Ie=0,Fe,ke,Ye;for(P=0;P<=i;P++)Be[P]=0;for(z=0;z<k;z++)Be[g[v+z]]++;for(L=C,F=i;F>=1&&Be[F]===0;F--);if(L>F&&(L=F),F===0)return A[T++]=1<<24|64<<16|0,A[T++]=1<<24|64<<16|0,D.bits=1,0;for(B=1;B<F&&Be[B]===0;B++);for(L<B&&(L=B),V=1,P=1;P<=i;P++)if(V<<=1,V-=Be[P],V<0)return-1;if(V>0&&(_===a||F!==1))return-1;for(Se[1]=0,P=1;P<i;P++)Se[P+1]=Se[P]+Be[P];for(z=0;z<k;z++)g[v+z]!==0&&($[Se[g[v+z]]++]=z);if(_===a?(Me=re=$,_e=19):_===s?(Me=h,Re-=257,re=f,Ie-=257,_e=256):(Me=l,re=u,_e=-1),Q=0,z=0,P=B,ye=T,N=L,G=0,me=-1,J=1<<L,ve=J-1,_===s&&J>t||_===o&&J>n)return 1;for(;;){Fe=P-G,$[z]<_e?(ke=0,Ye=$[z]):$[z]>_e?(ke=re[Ie+$[z]],Ye=Me[Re+$[z]]):(ke=96,Ye=0),W=1<<P-G,ne=1<<N,B=ne;do ne-=W,A[ye+(Q>>G)+ne]=Fe<<24|ke<<16|Ye|0;while(ne!==0);for(W=1<<P-1;Q&W;)W>>=1;if(W!==0?(Q&=W-1,Q+=W):Q=0,z++,--Be[P]===0){if(P===F)break;P=g[v+$[z]]}if(P>L&&(Q&ve)!==me){for(G===0&&(G=L),ye+=B,N=P-G,V=1<<N;N+G<F&&(V-=Be[N+G],!(V<=0));)N++,V<<=1;if(J+=1<<N,_===s&&J>t||_===o&&J>n)return 1;me=Q&ve,A[me]=L<<24|N<<16|ye-T|0}}return Q!==0&&(A[ye+Q]=P-G<<24|64<<16|0),D.bits=L,0},inftrees}var hasRequiredInflate$1;function requireInflate$1(){if(hasRequiredInflate$1)return inflate;hasRequiredInflate$1=1;var e=requireCommon(),i=requireAdler32(),t=requireCrc32(),n=requireInffast(),a=requireInftrees(),s=0,o=1,h=2,f=4,l=5,u=6,w=0,_=1,g=2,v=-2,k=-3,A=-4,T=-5,$=8,D=1,C=2,P=3,z=4,B=5,F=6,L=7,N=8,G=9,V=10,J=11,Q=12,W=13,ne=14,me=15,ve=16,ye=17,Me=18,Re=19,_e=20,Be=21,Se=22,re=23,Ie=24,Fe=25,ke=26,Ye=27,Je=28,et=29,Ve=30,tt=31,qe=32,De=852,nt=592,Ge=15,Ne=Ge;function he(te){return(te>>>24&255)+(te>>>8&65280)+((te&65280)<<8)+((te&255)<<24)}function Qe(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new e.Buf16(320),this.work=new e.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function Ze(te){var pe;return!te||!te.state?v:(pe=te.state,te.total_in=te.total_out=pe.total=0,te.msg="",pe.wrap&&(te.adler=pe.wrap&1),pe.mode=D,pe.last=0,pe.havedict=0,pe.dmax=32768,pe.head=null,pe.hold=0,pe.bits=0,pe.lencode=pe.lendyn=new e.Buf32(De),pe.distcode=pe.distdyn=new e.Buf32(nt),pe.sane=1,pe.back=-1,w)}function He(te){var pe;return!te||!te.state?v:(pe=te.state,pe.wsize=0,pe.whave=0,pe.wnext=0,Ze(te))}function Te(te,pe){var U,Ee;return!te||!te.state||(Ee=te.state,pe<0?(U=0,pe=-pe):(U=(pe>>4)+1,pe<48&&(pe&=15)),pe&&(pe<8||pe>15))?v:(Ee.window!==null&&Ee.wbits!==pe&&(Ee.window=null),Ee.wrap=U,Ee.wbits=pe,He(te))}function lt(te,pe){var U,Ee;return te?(Ee=new Qe,te.state=Ee,Ee.window=null,U=Te(te,pe),U!==w&&(te.state=null),U):v}function ot(te){return lt(te,Ne)}var Le=!0,ze,je;function Oe(te){if(Le){var pe;for(ze=new e.Buf32(512),je=new e.Buf32(32),pe=0;pe<144;)te.lens[pe++]=8;for(;pe<256;)te.lens[pe++]=9;for(;pe<280;)te.lens[pe++]=7;for(;pe<288;)te.lens[pe++]=8;for(a(o,te.lens,0,288,ze,0,te.work,{bits:9}),pe=0;pe<32;)te.lens[pe++]=5;a(h,te.lens,0,32,je,0,te.work,{bits:5}),Le=!1}te.lencode=ze,te.lenbits=9,te.distcode=je,te.distbits=5}function st(te,pe,U,Ee){var it,I=te.state;return I.window===null&&(I.wsize=1<<I.wbits,I.wnext=0,I.whave=0,I.window=new e.Buf8(I.wsize)),Ee>=I.wsize?(e.arraySet(I.window,pe,U-I.wsize,I.wsize,0),I.wnext=0,I.whave=I.wsize):(it=I.wsize-I.wnext,it>Ee&&(it=Ee),e.arraySet(I.window,pe,U-Ee,it,I.wnext),Ee-=it,Ee?(e.arraySet(I.window,pe,U-Ee,Ee,0),I.wnext=Ee,I.whave=I.wsize):(I.wnext+=it,I.wnext===I.wsize&&(I.wnext=0),I.whave<I.wsize&&(I.whave+=it))),0}function Z(te,pe){var U,Ee,it,I,fe,de,H,ee,oe,We,M,m,d,c,b=0,S,O,q,X,j,ae,K,ce,be=new e.Buf8(4),le,ge,Ue=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!te||!te.state||!te.output||!te.input&&te.avail_in!==0)return v;U=te.state,U.mode===Q&&(U.mode=W),fe=te.next_out,it=te.output,H=te.avail_out,I=te.next_in,Ee=te.input,de=te.avail_in,ee=U.hold,oe=U.bits,We=de,M=H,ce=w;e:for(;;)switch(U.mode){case D:if(U.wrap===0){U.mode=W;break}for(;oe<16;){if(de===0)break e;de--,ee+=Ee[I++]<<oe,oe+=8}if(U.wrap&2&&ee===35615){U.check=0,be[0]=ee&255,be[1]=ee>>>8&255,U.check=t(U.check,be,2,0),ee=0,oe=0,U.mode=C;break}if(U.flags=0,U.head&&(U.head.done=!1),!(U.wrap&1)||(((ee&255)<<8)+(ee>>8))%31){te.msg="incorrect header check",U.mode=Ve;break}if((ee&15)!==$){te.msg="unknown compression method",U.mode=Ve;break}if(ee>>>=4,oe-=4,K=(ee&15)+8,U.wbits===0)U.wbits=K;else if(K>U.wbits){te.msg="invalid window size",U.mode=Ve;break}U.dmax=1<<K,te.adler=U.check=1,U.mode=ee&512?V:Q,ee=0,oe=0;break;case C:for(;oe<16;){if(de===0)break e;de--,ee+=Ee[I++]<<oe,oe+=8}if(U.flags=ee,(U.flags&255)!==$){te.msg="unknown compression method",U.mode=Ve;break}if(U.flags&57344){te.msg="unknown header flags set",U.mode=Ve;break}U.head&&(U.head.text=ee>>8&1),U.flags&512&&(be[0]=ee&255,be[1]=ee>>>8&255,U.check=t(U.check,be,2,0)),ee=0,oe=0,U.mode=P;case P:for(;oe<32;){if(de===0)break e;de--,ee+=Ee[I++]<<oe,oe+=8}U.head&&(U.head.time=ee),U.flags&512&&(be[0]=ee&255,be[1]=ee>>>8&255,be[2]=ee>>>16&255,be[3]=ee>>>24&255,U.check=t(U.check,be,4,0)),ee=0,oe=0,U.mode=z;case z:for(;oe<16;){if(de===0)break e;de--,ee+=Ee[I++]<<oe,oe+=8}U.head&&(U.head.xflags=ee&255,U.head.os=ee>>8),U.flags&512&&(be[0]=ee&255,be[1]=ee>>>8&255,U.check=t(U.check,be,2,0)),ee=0,oe=0,U.mode=B;case B:if(U.flags&1024){for(;oe<16;){if(de===0)break e;de--,ee+=Ee[I++]<<oe,oe+=8}U.length=ee,U.head&&(U.head.extra_len=ee),U.flags&512&&(be[0]=ee&255,be[1]=ee>>>8&255,U.check=t(U.check,be,2,0)),ee=0,oe=0}else U.head&&(U.head.extra=null);U.mode=F;case F:if(U.flags&1024&&(m=U.length,m>de&&(m=de),m&&(U.head&&(K=U.head.extra_len-U.length,U.head.extra||(U.head.extra=new Array(U.head.extra_len)),e.arraySet(U.head.extra,Ee,I,m,K)),U.flags&512&&(U.check=t(U.check,Ee,m,I)),de-=m,I+=m,U.length-=m),U.length))break e;U.length=0,U.mode=L;case L:if(U.flags&2048){if(de===0)break e;m=0;do K=Ee[I+m++],U.head&&K&&U.length<65536&&(U.head.name+=String.fromCharCode(K));while(K&&m<de);if(U.flags&512&&(U.check=t(U.check,Ee,m,I)),de-=m,I+=m,K)break e}else U.head&&(U.head.name=null);U.length=0,U.mode=N;case N:if(U.flags&4096){if(de===0)break e;m=0;do K=Ee[I+m++],U.head&&K&&U.length<65536&&(U.head.comment+=String.fromCharCode(K));while(K&&m<de);if(U.flags&512&&(U.check=t(U.check,Ee,m,I)),de-=m,I+=m,K)break e}else U.head&&(U.head.comment=null);U.mode=G;case G:if(U.flags&512){for(;oe<16;){if(de===0)break e;de--,ee+=Ee[I++]<<oe,oe+=8}if(ee!==(U.check&65535)){te.msg="header crc mismatch",U.mode=Ve;break}ee=0,oe=0}U.head&&(U.head.hcrc=U.flags>>9&1,U.head.done=!0),te.adler=U.check=0,U.mode=Q;break;case V:for(;oe<32;){if(de===0)break e;de--,ee+=Ee[I++]<<oe,oe+=8}te.adler=U.check=he(ee),ee=0,oe=0,U.mode=J;case J:if(U.havedict===0)return te.next_out=fe,te.avail_out=H,te.next_in=I,te.avail_in=de,U.hold=ee,U.bits=oe,g;te.adler=U.check=1,U.mode=Q;case Q:if(pe===l||pe===u)break e;case W:if(U.last){ee>>>=oe&7,oe-=oe&7,U.mode=Ye;break}for(;oe<3;){if(de===0)break e;de--,ee+=Ee[I++]<<oe,oe+=8}switch(U.last=ee&1,ee>>>=1,oe-=1,ee&3){case 0:U.mode=ne;break;case 1:if(Oe(U),U.mode=_e,pe===u){ee>>>=2,oe-=2;break e}break;case 2:U.mode=ye;break;case 3:te.msg="invalid block type",U.mode=Ve}ee>>>=2,oe-=2;break;case ne:for(ee>>>=oe&7,oe-=oe&7;oe<32;){if(de===0)break e;de--,ee+=Ee[I++]<<oe,oe+=8}if((ee&65535)!==(ee>>>16^65535)){te.msg="invalid stored block lengths",U.mode=Ve;break}if(U.length=ee&65535,ee=0,oe=0,U.mode=me,pe===u)break e;case me:U.mode=ve;case ve:if(m=U.length,m){if(m>de&&(m=de),m>H&&(m=H),m===0)break e;e.arraySet(it,Ee,I,m,fe),de-=m,I+=m,H-=m,fe+=m,U.length-=m;break}U.mode=Q;break;case ye:for(;oe<14;){if(de===0)break e;de--,ee+=Ee[I++]<<oe,oe+=8}if(U.nlen=(ee&31)+257,ee>>>=5,oe-=5,U.ndist=(ee&31)+1,ee>>>=5,oe-=5,U.ncode=(ee&15)+4,ee>>>=4,oe-=4,U.nlen>286||U.ndist>30){te.msg="too many length or distance symbols",U.mode=Ve;break}U.have=0,U.mode=Me;case Me:for(;U.have<U.ncode;){for(;oe<3;){if(de===0)break e;de--,ee+=Ee[I++]<<oe,oe+=8}U.lens[Ue[U.have++]]=ee&7,ee>>>=3,oe-=3}for(;U.have<19;)U.lens[Ue[U.have++]]=0;if(U.lencode=U.lendyn,U.lenbits=7,le={bits:U.lenbits},ce=a(s,U.lens,0,19,U.lencode,0,U.work,le),U.lenbits=le.bits,ce){te.msg="invalid code lengths set",U.mode=Ve;break}U.have=0,U.mode=Re;case Re:for(;U.have<U.nlen+U.ndist;){for(;b=U.lencode[ee&(1<<U.lenbits)-1],S=b>>>24,O=b>>>16&255,q=b&65535,!(S<=oe);){if(de===0)break e;de--,ee+=Ee[I++]<<oe,oe+=8}if(q<16)ee>>>=S,oe-=S,U.lens[U.have++]=q;else{if(q===16){for(ge=S+2;oe<ge;){if(de===0)break e;de--,ee+=Ee[I++]<<oe,oe+=8}if(ee>>>=S,oe-=S,U.have===0){te.msg="invalid bit length repeat",U.mode=Ve;break}K=U.lens[U.have-1],m=3+(ee&3),ee>>>=2,oe-=2}else if(q===17){for(ge=S+3;oe<ge;){if(de===0)break e;de--,ee+=Ee[I++]<<oe,oe+=8}ee>>>=S,oe-=S,K=0,m=3+(ee&7),ee>>>=3,oe-=3}else{for(ge=S+7;oe<ge;){if(de===0)break e;de--,ee+=Ee[I++]<<oe,oe+=8}ee>>>=S,oe-=S,K=0,m=11+(ee&127),ee>>>=7,oe-=7}if(U.have+m>U.nlen+U.ndist){te.msg="invalid bit length repeat",U.mode=Ve;break}for(;m--;)U.lens[U.have++]=K}}if(U.mode===Ve)break;if(U.lens[256]===0){te.msg="invalid code -- missing end-of-block",U.mode=Ve;break}if(U.lenbits=9,le={bits:U.lenbits},ce=a(o,U.lens,0,U.nlen,U.lencode,0,U.work,le),U.lenbits=le.bits,ce){te.msg="invalid literal/lengths set",U.mode=Ve;break}if(U.distbits=6,U.distcode=U.distdyn,le={bits:U.distbits},ce=a(h,U.lens,U.nlen,U.ndist,U.distcode,0,U.work,le),U.distbits=le.bits,ce){te.msg="invalid distances set",U.mode=Ve;break}if(U.mode=_e,pe===u)break e;case _e:U.mode=Be;case Be:if(de>=6&&H>=258){te.next_out=fe,te.avail_out=H,te.next_in=I,te.avail_in=de,U.hold=ee,U.bits=oe,n(te,M),fe=te.next_out,it=te.output,H=te.avail_out,I=te.next_in,Ee=te.input,de=te.avail_in,ee=U.hold,oe=U.bits,U.mode===Q&&(U.back=-1);break}for(U.back=0;b=U.lencode[ee&(1<<U.lenbits)-1],S=b>>>24,O=b>>>16&255,q=b&65535,!(S<=oe);){if(de===0)break e;de--,ee+=Ee[I++]<<oe,oe+=8}if(O&&(O&240)===0){for(X=S,j=O,ae=q;b=U.lencode[ae+((ee&(1<<X+j)-1)>>X)],S=b>>>24,O=b>>>16&255,q=b&65535,!(X+S<=oe);){if(de===0)break e;de--,ee+=Ee[I++]<<oe,oe+=8}ee>>>=X,oe-=X,U.back+=X}if(ee>>>=S,oe-=S,U.back+=S,U.length=q,O===0){U.mode=ke;break}if(O&32){U.back=-1,U.mode=Q;break}if(O&64){te.msg="invalid literal/length code",U.mode=Ve;break}U.extra=O&15,U.mode=Se;case Se:if(U.extra){for(ge=U.extra;oe<ge;){if(de===0)break e;de--,ee+=Ee[I++]<<oe,oe+=8}U.length+=ee&(1<<U.extra)-1,ee>>>=U.extra,oe-=U.extra,U.back+=U.extra}U.was=U.length,U.mode=re;case re:for(;b=U.distcode[ee&(1<<U.distbits)-1],S=b>>>24,O=b>>>16&255,q=b&65535,!(S<=oe);){if(de===0)break e;de--,ee+=Ee[I++]<<oe,oe+=8}if((O&240)===0){for(X=S,j=O,ae=q;b=U.distcode[ae+((ee&(1<<X+j)-1)>>X)],S=b>>>24,O=b>>>16&255,q=b&65535,!(X+S<=oe);){if(de===0)break e;de--,ee+=Ee[I++]<<oe,oe+=8}ee>>>=X,oe-=X,U.back+=X}if(ee>>>=S,oe-=S,U.back+=S,O&64){te.msg="invalid distance code",U.mode=Ve;break}U.offset=q,U.extra=O&15,U.mode=Ie;case Ie:if(U.extra){for(ge=U.extra;oe<ge;){if(de===0)break e;de--,ee+=Ee[I++]<<oe,oe+=8}U.offset+=ee&(1<<U.extra)-1,ee>>>=U.extra,oe-=U.extra,U.back+=U.extra}if(U.offset>U.dmax){te.msg="invalid distance too far back",U.mode=Ve;break}U.mode=Fe;case Fe:if(H===0)break e;if(m=M-H,U.offset>m){if(m=U.offset-m,m>U.whave&&U.sane){te.msg="invalid distance too far back",U.mode=Ve;break}m>U.wnext?(m-=U.wnext,d=U.wsize-m):d=U.wnext-m,m>U.length&&(m=U.length),c=U.window}else c=it,d=fe-U.offset,m=U.length;m>H&&(m=H),H-=m,U.length-=m;do it[fe++]=c[d++];while(--m);U.length===0&&(U.mode=Be);break;case ke:if(H===0)break e;it[fe++]=U.length,H--,U.mode=Be;break;case Ye:if(U.wrap){for(;oe<32;){if(de===0)break e;de--,ee|=Ee[I++]<<oe,oe+=8}if(M-=H,te.total_out+=M,U.total+=M,M&&(te.adler=U.check=U.flags?t(U.check,it,M,fe-M):i(U.check,it,M,fe-M)),M=H,(U.flags?ee:he(ee))!==U.check){te.msg="incorrect data check",U.mode=Ve;break}ee=0,oe=0}U.mode=Je;case Je:if(U.wrap&&U.flags){for(;oe<32;){if(de===0)break e;de--,ee+=Ee[I++]<<oe,oe+=8}if(ee!==(U.total&4294967295)){te.msg="incorrect length check",U.mode=Ve;break}ee=0,oe=0}U.mode=et;case et:ce=_;break e;case Ve:ce=k;break e;case tt:return A;case qe:default:return v}return te.next_out=fe,te.avail_out=H,te.next_in=I,te.avail_in=de,U.hold=ee,U.bits=oe,(U.wsize||M!==te.avail_out&&U.mode<Ve&&(U.mode<Ye||pe!==f))&&st(te,te.output,te.next_out,M-te.avail_out),We-=te.avail_in,M-=te.avail_out,te.total_in+=We,te.total_out+=M,U.total+=M,U.wrap&&M&&(te.adler=U.check=U.flags?t(U.check,it,M,te.next_out-M):i(U.check,it,M,te.next_out-M)),te.data_type=U.bits+(U.last?64:0)+(U.mode===Q?128:0)+(U.mode===_e||U.mode===me?256:0),(We===0&&M===0||pe===f)&&ce===w&&(ce=T),ce}function ue(te){if(!te||!te.state)return v;var pe=te.state;return pe.window&&(pe.window=null),te.state=null,w}function xe(te,pe){var U;return!te||!te.state||(U=te.state,(U.wrap&2)===0)?v:(U.head=pe,pe.done=!1,w)}function Ae(te,pe){var U=pe.length,Ee,it,I;return!te||!te.state||(Ee=te.state,Ee.wrap!==0&&Ee.mode!==J)?v:Ee.mode===J&&(it=1,it=i(it,pe,U,0),it!==Ee.check)?k:(I=st(te,pe,U,U),I?(Ee.mode=tt,A):(Ee.havedict=1,w))}return inflate.inflateReset=He,inflate.inflateReset2=Te,inflate.inflateResetKeep=Ze,inflate.inflateInit=ot,inflate.inflateInit2=lt,inflate.inflate=Z,inflate.inflateEnd=ue,inflate.inflateGetHeader=xe,inflate.inflateSetDictionary=Ae,inflate.inflateInfo="pako inflate (from Nodeca project)",inflate}var constants,hasRequiredConstants;function requireConstants(){return hasRequiredConstants||(hasRequiredConstants=1,constants={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}),constants}var gzheader,hasRequiredGzheader;function requireGzheader(){if(hasRequiredGzheader)return gzheader;hasRequiredGzheader=1;function e(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}return gzheader=e,gzheader}var hasRequiredInflate;function requireInflate(){if(hasRequiredInflate)return inflate$1;hasRequiredInflate=1;var e=requireInflate$1(),i=requireCommon(),t=requireStrings(),n=requireConstants(),a=requireMessages(),s=requireZstream(),o=requireGzheader(),h=Object.prototype.toString;function f(w){if(!(this instanceof f))return new f(w);this.options=i.assign({chunkSize:16384,windowBits:0,to:""},w||{});var _=this.options;_.raw&&_.windowBits>=0&&_.windowBits<16&&(_.windowBits=-_.windowBits,_.windowBits===0&&(_.windowBits=-15)),_.windowBits>=0&&_.windowBits<16&&!(w&&w.windowBits)&&(_.windowBits+=32),_.windowBits>15&&_.windowBits<48&&(_.windowBits&15)===0&&(_.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new s,this.strm.avail_out=0;var g=e.inflateInit2(this.strm,_.windowBits);if(g!==n.Z_OK)throw new Error(a[g]);if(this.header=new o,e.inflateGetHeader(this.strm,this.header),_.dictionary&&(typeof _.dictionary=="string"?_.dictionary=t.string2buf(_.dictionary):h.call(_.dictionary)==="[object ArrayBuffer]"&&(_.dictionary=new Uint8Array(_.dictionary)),_.raw&&(g=e.inflateSetDictionary(this.strm,_.dictionary),g!==n.Z_OK)))throw new Error(a[g])}f.prototype.push=function(w,_){var g=this.strm,v=this.options.chunkSize,k=this.options.dictionary,A,T,$,D,C,P=!1;if(this.ended)return!1;T=_===~~_?_:_===!0?n.Z_FINISH:n.Z_NO_FLUSH,typeof w=="string"?g.input=t.binstring2buf(w):h.call(w)==="[object ArrayBuffer]"?g.input=new Uint8Array(w):g.input=w,g.next_in=0,g.avail_in=g.input.length;do{if(g.avail_out===0&&(g.output=new i.Buf8(v),g.next_out=0,g.avail_out=v),A=e.inflate(g,n.Z_NO_FLUSH),A===n.Z_NEED_DICT&&k&&(A=e.inflateSetDictionary(this.strm,k)),A===n.Z_BUF_ERROR&&P===!0&&(A=n.Z_OK,P=!1),A!==n.Z_STREAM_END&&A!==n.Z_OK)return this.onEnd(A),this.ended=!0,!1;g.next_out&&(g.avail_out===0||A===n.Z_STREAM_END||g.avail_in===0&&(T===n.Z_FINISH||T===n.Z_SYNC_FLUSH))&&(this.options.to==="string"?($=t.utf8border(g.output,g.next_out),D=g.next_out-$,C=t.buf2string(g.output,$),g.next_out=D,g.avail_out=v-D,D&&i.arraySet(g.output,g.output,$,D,0),this.onData(C)):this.onData(i.shrinkBuf(g.output,g.next_out))),g.avail_in===0&&g.avail_out===0&&(P=!0)}while((g.avail_in>0||g.avail_out===0)&&A!==n.Z_STREAM_END);return A===n.Z_STREAM_END&&(T=n.Z_FINISH),T===n.Z_FINISH?(A=e.inflateEnd(this.strm),this.onEnd(A),this.ended=!0,A===n.Z_OK):(T===n.Z_SYNC_FLUSH&&(this.onEnd(n.Z_OK),g.avail_out=0),!0)},f.prototype.onData=function(w){this.chunks.push(w)},f.prototype.onEnd=function(w){w===n.Z_OK&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=i.flattenChunks(this.chunks)),this.chunks=[],this.err=w,this.msg=this.strm.msg};function l(w,_){var g=new f(_);if(g.push(w,!0),g.err)throw g.msg||a[g.err];return g.result}function u(w,_){return _=_||{},_.raw=!0,l(w,_)}return inflate$1.Inflate=f,inflate$1.inflate=l,inflate$1.inflateRaw=u,inflate$1.ungzip=l,inflate$1}var pako_1,hasRequiredPako;function requirePako(){if(hasRequiredPako)return pako_1;hasRequiredPako=1;var e=requireCommon().assign,i=requireDeflate(),t=requireInflate(),n=requireConstants(),a={};return e(a,i,t,n),pako_1=a,pako_1}var pakoExports=requirePako();const pako=getDefaultExportFromCjs(pakoExports);var UPNG={};UPNG.toRGBA8=function(e){var i=e.width,t=e.height;if(e.tabs.acTL==null)return[UPNG.toRGBA8.decodeImage(e.data,i,t,e).buffer];var n=[];e.frames[0].data==null&&(e.frames[0].data=e.data);for(var a=i*t*4,s=new Uint8Array(a),o=new Uint8Array(a),h=new Uint8Array(a),f=0;f<e.frames.length;f++){var l=e.frames[f],u=l.rect.x,w=l.rect.y,_=l.rect.width,g=l.rect.height,v=UPNG.toRGBA8.decodeImage(l.data,_,g,e);if(f!=0)for(var k=0;k<a;k++)h[k]=s[k];if(l.blend==0?UPNG._copyTile(v,_,g,s,i,t,u,w,0):l.blend==1&&UPNG._copyTile(v,_,g,s,i,t,u,w,1),n.push(s.buffer.slice(0)),l.dispose!=0){if(l.dispose==1)UPNG._copyTile(o,_,g,s,i,t,u,w,0);else if(l.dispose==2)for(var k=0;k<a;k++)s[k]=h[k]}}return n},UPNG.toRGBA8.decodeImage=function(e,i,t,n){var a=i*t,s=UPNG.decode._getBPP(n),o=Math.ceil(i*s/8),h=new Uint8Array(a*4),f=new Uint32Array(h.buffer),l=n.ctype,u=n.depth,w=UPNG._bin.readUshort;if(l==6){var _=a<<2;if(u==8)for(var g=0;g<_;g+=4)h[g]=e[g],h[g+1]=e[g+1],h[g+2]=e[g+2],h[g+3]=e[g+3];if(u==16)for(var g=0;g<_;g++)h[g]=e[g<<1]}else if(l==2){var v=n.tabs.tRNS;if(v==null){if(u==8)for(var g=0;g<a;g++){var k=g*3;f[g]=255<<24|e[k+2]<<16|e[k+1]<<8|e[k]}if(u==16)for(var g=0;g<a;g++){var k=g*6;f[g]=255<<24|e[k+4]<<16|e[k+2]<<8|e[k]}}else{var A=v[0],T=v[1],$=v[2];if(u==8)for(var g=0;g<a;g++){var D=g<<2,k=g*3;f[g]=255<<24|e[k+2]<<16|e[k+1]<<8|e[k],e[k]==A&&e[k+1]==T&&e[k+2]==$&&(h[D+3]=0)}if(u==16)for(var g=0;g<a;g++){var D=g<<2,k=g*6;f[g]=255<<24|e[k+4]<<16|e[k+2]<<8|e[k],w(e,k)==A&&w(e,k+2)==T&&w(e,k+4)==$&&(h[D+3]=0)}}}else if(l==3){var C=n.tabs.PLTE,P=n.tabs.tRNS,z=P?P.length:0;if(u==1)for(var B=0;B<t;B++)for(var F=B*o,L=B*i,g=0;g<i;g++){var D=L+g<<2,N=e[F+(g>>3)]>>7-((g&7)<<0)&1,G=3*N;h[D]=C[G],h[D+1]=C[G+1],h[D+2]=C[G+2],h[D+3]=N<z?P[N]:255}if(u==2)for(var B=0;B<t;B++)for(var F=B*o,L=B*i,g=0;g<i;g++){var D=L+g<<2,N=e[F+(g>>2)]>>6-((g&3)<<1)&3,G=3*N;h[D]=C[G],h[D+1]=C[G+1],h[D+2]=C[G+2],h[D+3]=N<z?P[N]:255}if(u==4)for(var B=0;B<t;B++)for(var F=B*o,L=B*i,g=0;g<i;g++){var D=L+g<<2,N=e[F+(g>>1)]>>4-((g&1)<<2)&15,G=3*N;h[D]=C[G],h[D+1]=C[G+1],h[D+2]=C[G+2],h[D+3]=N<z?P[N]:255}if(u==8)for(var g=0;g<a;g++){var D=g<<2,N=e[g],G=3*N;h[D]=C[G],h[D+1]=C[G+1],h[D+2]=C[G+2],h[D+3]=N<z?P[N]:255}}else if(l==4){if(u==8)for(var g=0;g<a;g++){var D=g<<2,V=g<<1,J=e[V];h[D]=J,h[D+1]=J,h[D+2]=J,h[D+3]=e[V+1]}if(u==16)for(var g=0;g<a;g++){var D=g<<2,V=g<<2,J=e[V];h[D]=J,h[D+1]=J,h[D+2]=J,h[D+3]=e[V+2]}}else if(l==0)for(var A=n.tabs.tRNS?n.tabs.tRNS:-1,B=0;B<t;B++){var Q=B*o,W=B*i;if(u==1)for(var ne=0;ne<i;ne++){var J=255*(e[Q+(ne>>>3)]>>>7-(ne&7)&1),me=J==A*255?0:255;f[W+ne]=me<<24|J<<16|J<<8|J}else if(u==2)for(var ne=0;ne<i;ne++){var J=85*(e[Q+(ne>>>2)]>>>6-((ne&3)<<1)&3),me=J==A*85?0:255;f[W+ne]=me<<24|J<<16|J<<8|J}else if(u==4)for(var ne=0;ne<i;ne++){var J=17*(e[Q+(ne>>>1)]>>>4-((ne&1)<<2)&15),me=J==A*17?0:255;f[W+ne]=me<<24|J<<16|J<<8|J}else if(u==8)for(var ne=0;ne<i;ne++){var J=e[Q+ne],me=J==A?0:255;f[W+ne]=me<<24|J<<16|J<<8|J}else if(u==16)for(var ne=0;ne<i;ne++){var J=e[Q+(ne<<1)],me=w(e,Q+(ne<<g))==A?0:255;f[W+ne]=me<<24|J<<16|J<<8|J}}return h},UPNG.decode=function(e){for(var i=new Uint8Array(e),t=8,n=UPNG._bin,a=n.readUshort,s=n.readUint,o={tabs:{},frames:[]},h=new Uint8Array(i.length),f=0,l,u=0,w=[137,80,78,71,13,10,26,10],_=0;_<8;_++)if(i[_]!=w[_])throw"The input is not a PNG file!";for(;t<i.length;){var g=n.readUint(i,t);t+=4;var v=n.readASCII(i,t,4);if(t+=4,v=="IHDR")UPNG.decode._IHDR(i,t,o);else if(v=="IDAT"){for(var _=0;_<g;_++)h[f+_]=i[t+_];f+=g}else if(v=="acTL")o.tabs[v]={num_frames:s(i,t),num_plays:s(i,t+4)},l=new Uint8Array(i.length);else if(v=="fcTL"){if(u!=0){var k=o.frames[o.frames.length-1];k.data=UPNG.decode._decompress(o,l.slice(0,u),k.rect.width,k.rect.height),u=0}var A={x:s(i,t+12),y:s(i,t+16),width:s(i,t+4),height:s(i,t+8)},T=a(i,t+22);T=a(i,t+20)/(T==0?100:T);var $={rect:A,delay:Math.round(T*1e3),dispose:i[t+24],blend:i[t+25]};o.frames.push($)}else if(v=="fdAT"){for(var _=0;_<g-4;_++)l[u+_]=i[t+_+4];u+=g-4}else if(v=="pHYs")o.tabs[v]=[n.readUint(i,t),n.readUint(i,t+4),i[t+8]];else if(v=="cHRM"){o.tabs[v]=[];for(var _=0;_<8;_++)o.tabs[v].push(n.readUint(i,t+_*4))}else if(v=="tEXt"){o.tabs[v]==null&&(o.tabs[v]={});var D=n.nextZero(i,t),C=n.readASCII(i,t,D-t),P=n.readASCII(i,D+1,t+g-D-1);o.tabs[v][C]=P}else if(v=="iTXt"){o.tabs[v]==null&&(o.tabs[v]={});var D=0,z=t;D=n.nextZero(i,z);var C=n.readASCII(i,z,D-z);z=D+1,i[z],i[z+1],z+=2,D=n.nextZero(i,z),n.readASCII(i,z,D-z),z=D+1,D=n.nextZero(i,z),n.readUTF8(i,z,D-z),z=D+1;var P=n.readUTF8(i,z,g-(z-t));o.tabs[v][C]=P}else if(v=="PLTE")o.tabs[v]=n.readBytes(i,t,g);else if(v=="hIST"){var B=o.tabs.PLTE.length/3;o.tabs[v]=[];for(var _=0;_<B;_++)o.tabs[v].push(a(i,t+_*2))}else if(v=="tRNS")o.ctype==3?o.tabs[v]=n.readBytes(i,t,g):o.ctype==0?o.tabs[v]=a(i,t):o.ctype==2&&(o.tabs[v]=[a(i,t),a(i,t+2),a(i,t+4)]);else if(v=="gAMA")o.tabs[v]=n.readUint(i,t)/1e5;else if(v=="sRGB")o.tabs[v]=i[t];else if(v=="bKGD")o.ctype==0||o.ctype==4?o.tabs[v]=[a(i,t)]:o.ctype==2||o.ctype==6?o.tabs[v]=[a(i,t),a(i,t+2),a(i,t+4)]:o.ctype==3&&(o.tabs[v]=i[t]);else if(v=="IEND")break;t+=g,n.readUint(i,t),t+=4}if(u!=0){var k=o.frames[o.frames.length-1];k.data=UPNG.decode._decompress(o,l.slice(0,u),k.rect.width,k.rect.height),u=0}return o.data=UPNG.decode._decompress(o,h,o.width,o.height),delete o.compress,delete o.interlace,delete o.filter,o},UPNG.decode._decompress=function(e,i,t,n){var a=UPNG.decode._getBPP(e),s=Math.ceil(t*a/8),o=new Uint8Array((s+1+e.interlace)*n);return i=UPNG.decode._inflate(i,o),e.interlace==0?i=UPNG.decode._filterZero(i,e,0,t,n):e.interlace==1&&(i=UPNG.decode._readInterlace(i,e)),i},UPNG.decode._inflate=function(e,i){var t=UPNG.inflateRaw(new Uint8Array(e.buffer,2,e.length-6),i);return t},UPNG.inflateRaw=function(){var e={};return e.H={},e.H.N=function(i,t){var n=Uint8Array,a=0,s=0,o=0,h=0,f=0,l=0,u=0,w=0,_=0,g,v;if(i[0]==3&&i[1]==0)return t||new n(0);var k=e.H,A=k.b,T=k.e,$=k.R,D=k.n,C=k.A,P=k.Z,z=k.m,B=t==null;for(B&&(t=new n(i.length>>>2<<3));a==0;){if(a=A(i,_,1),s=A(i,_+1,2),_+=3,s==0){(_&7)!=0&&(_+=8-(_&7));var F=(_>>>3)+4,L=i[F-4]|i[F-3]<<8;B&&(t=e.H.W(t,w+L)),t.set(new n(i.buffer,i.byteOffset+F,L),w),_=F+L<<3,w+=L;continue}if(B&&(t=e.H.W(t,w+(1<<17))),s==1&&(g=z.J,v=z.h,l=511,u=31),s==2){o=T(i,_,5)+257,h=T(i,_+5,5)+1,f=T(i,_+10,4)+4,_+=14;for(var N=1,G=0;G<38;G+=2)z.Q[G]=0,z.Q[G+1]=0;for(var G=0;G<f;G++){var V=T(i,_+G*3,3);z.Q[(z.X[G]<<1)+1]=V,V>N&&(N=V)}_+=3*f,D(z.Q,N),C(z.Q,N,z.u),g=z.w,v=z.d,_=$(z.u,(1<<N)-1,o+h,i,_,z.v);var J=k.V(z.v,0,o,z.C);l=(1<<J)-1;var Q=k.V(z.v,o,h,z.D);u=(1<<Q)-1,D(z.C,J),C(z.C,J,g),D(z.D,Q),C(z.D,Q,v)}for(;;){var W=g[P(i,_)&l];_+=W&15;var ne=W>>>4;if(!(ne>>>8))t[w++]=ne;else{if(ne==256)break;var me=w+ne-254;if(ne>264){var ve=z.q[ne-257];me=w+(ve>>>3)+T(i,_,ve&7),_+=ve&7}var ye=v[P(i,_)&u];_+=ye&15;var Me=ye>>>4,Re=z.c[Me],_e=(Re>>>4)+A(i,_,Re&15);for(_+=Re&15;w<me;)t[w]=t[w++-_e],t[w]=t[w++-_e],t[w]=t[w++-_e],t[w]=t[w++-_e];w=me}}}return t.length==w?t:t.slice(0,w)},e.H.W=function(i,t){var n=i.length;if(t<=n)return i;var a=new Uint8Array(n<<1);return a.set(i,0),a},e.H.R=function(i,t,n,a,s,o){for(var h=e.H.e,f=e.H.Z,l=0;l<n;){var u=i[f(a,s)&t];s+=u&15;var w=u>>>4;if(w<=15)o[l]=w,l++;else{var _=0,g=0;w==16?(g=3+h(a,s,2),s+=2,_=o[l-1]):w==17?(g=3+h(a,s,3),s+=3):w==18&&(g=11+h(a,s,7),s+=7);for(var v=l+g;l<v;)o[l]=_,l++}}return s},e.H.V=function(i,t,n,a){for(var s=0,o=0,h=a.length>>>1;o<n;){var f=i[o+t];a[o<<1]=0,a[(o<<1)+1]=f,f>s&&(s=f),o++}for(;o<h;)a[o<<1]=0,a[(o<<1)+1]=0,o++;return s},e.H.n=function(i,t){for(var n=e.H.m,a=i.length,s,o,h,f,l,u=n.j,f=0;f<=t;f++)u[f]=0;for(f=1;f<a;f+=2)u[i[f]]++;var w=n.K;for(s=0,u[0]=0,o=1;o<=t;o++)s=s+u[o-1]<<1,w[o]=s;for(h=0;h<a;h+=2)l=i[h+1],l!=0&&(i[h]=w[l],w[l]++)},e.H.A=function(i,t,n){for(var a=i.length,s=e.H.m,o=s.r,h=0;h<a;h+=2)if(i[h+1]!=0)for(var f=h>>1,l=i[h+1],u=f<<4|l,w=t-l,_=i[h]<<w,g=_+(1<<w);_!=g;){var v=o[_]>>>15-t;n[v]=u,_++}},e.H.l=function(i,t){for(var n=e.H.m.r,a=15-t,s=0;s<i.length;s+=2){var o=i[s]<<t-i[s+1];i[s]=n[o]>>>a}},e.H.M=function(i,t,n){n=n<<(t&7);var a=t>>>3;i[a]|=n,i[a+1]|=n>>>8},e.H.I=function(i,t,n){n=n<<(t&7);var a=t>>>3;i[a]|=n,i[a+1]|=n>>>8,i[a+2]|=n>>>16},e.H.e=function(i,t,n){return(i[t>>>3]|i[(t>>>3)+1]<<8)>>>(t&7)&(1<<n)-1},e.H.b=function(i,t,n){return(i[t>>>3]|i[(t>>>3)+1]<<8|i[(t>>>3)+2]<<16)>>>(t&7)&(1<<n)-1},e.H.Z=function(i,t){return(i[t>>>3]|i[(t>>>3)+1]<<8|i[(t>>>3)+2]<<16)>>>(t&7)},e.H.i=function(i,t){return(i[t>>>3]|i[(t>>>3)+1]<<8|i[(t>>>3)+2]<<16|i[(t>>>3)+3]<<24)>>>(t&7)},e.H.m=function(){var i=Uint16Array,t=Uint32Array;return{K:new i(16),j:new i(16),X:[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],S:[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,999,999,999],T:[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0],q:new i(32),p:[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,65535,65535],z:[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0],c:new t(32),J:new i(512),_:[],h:new i(32),$:[],w:new i(32768),C:[],v:[],d:new i(32768),D:[],u:new i(512),Q:[],r:new i(32768),s:new t(286),Y:new t(30),a:new t(19),t:new t(15e3),k:new i(65536),g:new i(32768)}}(),function(){for(var i=e.H.m,t=32768,n=0;n<t;n++){var a=n;a=(a&2863311530)>>>1|(a&1431655765)<<1,a=(a&3435973836)>>>2|(a&858993459)<<2,a=(a&4042322160)>>>4|(a&252645135)<<4,a=(a&4278255360)>>>8|(a&16711935)<<8,i.r[n]=(a>>>16|a<<16)>>>17}function s(o,h,f){for(;h--!=0;)o.push(0,f)}for(var n=0;n<32;n++)i.q[n]=i.S[n]<<3|i.T[n],i.c[n]=i.p[n]<<4|i.z[n];s(i._,144,8),s(i._,112,9),s(i._,24,7),s(i._,8,8),e.H.n(i._,9),e.H.A(i._,9,i.J),e.H.l(i._,9),s(i.$,32,5),e.H.n(i.$,5),e.H.A(i.$,5,i.h),e.H.l(i.$,5),s(i.Q,19,0),s(i.C,286,0),s(i.D,30,0),s(i.v,320,0)}(),e.H.N}(),UPNG.decode._readInterlace=function(e,i){for(var t=i.width,n=i.height,a=UPNG.decode._getBPP(i),s=a>>3,o=Math.ceil(t*a/8),h=new Uint8Array(n*o),f=0,l=[0,0,4,0,2,0,1],u=[0,4,0,2,0,1,0],w=[8,8,8,4,4,2,2],_=[8,8,4,4,2,2,1],g=0;g<7;){for(var v=w[g],k=_[g],A=0,T=0,$=l[g];$<n;)$+=v,T++;for(var D=u[g];D<t;)D+=k,A++;var C=Math.ceil(A*a/8);UPNG.decode._filterZero(e,i,f,A,T);for(var P=0,z=l[g];z<n;){for(var B=u[g],F=f+P*C<<3;B<t;){if(a==1){var L=e[F>>3];L=L>>7-(F&7)&1,h[z*o+(B>>3)]|=L<<7-((B&7)<<0)}if(a==2){var L=e[F>>3];L=L>>6-(F&7)&3,h[z*o+(B>>2)]|=L<<6-((B&3)<<1)}if(a==4){var L=e[F>>3];L=L>>4-(F&7)&15,h[z*o+(B>>1)]|=L<<4-((B&1)<<2)}if(a>=8)for(var N=z*o+B*s,G=0;G<s;G++)h[N+G]=e[(F>>3)+G];F+=a,B+=k}P++,z+=v}A*T!=0&&(f+=T*(1+C)),g=g+1}return h},UPNG.decode._getBPP=function(e){var i=[1,null,3,1,2,null,4][e.ctype];return i*e.depth},UPNG.decode._filterZero=function(e,i,t,n,a){var s=UPNG.decode._getBPP(i),o=Math.ceil(n*s/8),h=UPNG.decode._paeth;s=Math.ceil(s/8);var f=0,l=1,u=e[t],w=0;if(u>1&&(e[t]=[0,0,1][u-2]),u==3)for(w=s;w<o;w++)e[w+1]=e[w+1]+(e[w+1-s]>>>1)&255;for(var _=0;_<a;_++)if(f=t+_*o,l=f+_+1,u=e[l-1],w=0,u==0)for(;w<o;w++)e[f+w]=e[l+w];else if(u==1){for(;w<s;w++)e[f+w]=e[l+w];for(;w<o;w++)e[f+w]=e[l+w]+e[f+w-s]}else if(u==2)for(;w<o;w++)e[f+w]=e[l+w]+e[f+w-o];else if(u==3){for(;w<s;w++)e[f+w]=e[l+w]+(e[f+w-o]>>>1);for(;w<o;w++)e[f+w]=e[l+w]+(e[f+w-o]+e[f+w-s]>>>1)}else{for(;w<s;w++)e[f+w]=e[l+w]+h(0,e[f+w-o],0);for(;w<o;w++)e[f+w]=e[l+w]+h(e[f+w-s],e[f+w-o],e[f+w-s-o])}return e},UPNG.decode._paeth=function(e,i,t){var n=e+i-t,a=n-e,s=n-i,o=n-t;return a*a<=s*s&&a*a<=o*o?e:s*s<=o*o?i:t},UPNG.decode._IHDR=function(e,i,t){var n=UPNG._bin;t.width=n.readUint(e,i),i+=4,t.height=n.readUint(e,i),i+=4,t.depth=e[i],i++,t.ctype=e[i],i++,t.compress=e[i],i++,t.filter=e[i],i++,t.interlace=e[i],i++},UPNG._bin={nextZero:function(e,i){for(;e[i]!=0;)i++;return i},readUshort:function(e,i){return e[i]<<8|e[i+1]},writeUshort:function(e,i,t){e[i]=t>>8&255,e[i+1]=t&255},readUint:function(e,i){return e[i]*(256*256*256)+(e[i+1]<<16|e[i+2]<<8|e[i+3])},writeUint:function(e,i,t){e[i]=t>>24&255,e[i+1]=t>>16&255,e[i+2]=t>>8&255,e[i+3]=t&255},readASCII:function(e,i,t){for(var n="",a=0;a<t;a++)n+=String.fromCharCode(e[i+a]);return n},writeASCII:function(e,i,t){for(var n=0;n<t.length;n++)e[i+n]=t.charCodeAt(n)},readBytes:function(e,i,t){for(var n=[],a=0;a<t;a++)n.push(e[i+a]);return n},pad:function(e){return e.length<2?"0"+e:e},readUTF8:function(e,i,t){for(var n="",a,s=0;s<t;s++)n+="%"+UPNG._bin.pad(e[i+s].toString(16));try{a=decodeURIComponent(n)}catch{return UPNG._bin.readASCII(e,i,t)}return a}},UPNG._copyTile=function(e,i,t,n,a,s,o,h,f){for(var l=Math.min(i,a),u=Math.min(t,s),w=0,_=0,g=0;g<u;g++)for(var v=0;v<l;v++)if(o>=0&&h>=0?(w=g*i+v<<2,_=(h+g)*a+o+v<<2):(w=(-h+g)*i-o+v<<2,_=g*a+v<<2),f==0)n[_]=e[w],n[_+1]=e[w+1],n[_+2]=e[w+2],n[_+3]=e[w+3];else if(f==1){var k=e[w+3]*.00392156862745098,A=e[w]*k,T=e[w+1]*k,$=e[w+2]*k,D=n[_+3]*(1/255),C=n[_]*D,P=n[_+1]*D,z=n[_+2]*D,B=1-k,F=k+D*B,L=F==0?0:1/F;n[_+3]=255*F,n[_+0]=(A+C*B)*L,n[_+1]=(T+P*B)*L,n[_+2]=($+z*B)*L}else if(f==2){var k=e[w+3],A=e[w],T=e[w+1],$=e[w+2],D=n[_+3],C=n[_],P=n[_+1],z=n[_+2];k==D&&A==C&&T==P&&$==z?(n[_]=0,n[_+1]=0,n[_+2]=0,n[_+3]=0):(n[_]=A,n[_+1]=T,n[_+2]=$,n[_+3]=k)}else if(f==3){var k=e[w+3],A=e[w],T=e[w+1],$=e[w+2],D=n[_+3],C=n[_],P=n[_+1],z=n[_+2];if(k==D&&A==C&&T==P&&$==z)continue;if(k<220&&D>20)return!1}return!0},UPNG.encode=function(e,i,t,n,a,s,o){n==null&&(n=0),o==null&&(o=!1);var h=UPNG.encode.compress(e,i,t,n,[!1,!1,!1,0,o]);return UPNG.encode.compressPNG(h,-1),UPNG.encode._main(h,i,t,a,s)},UPNG.encodeLL=function(e,i,t,n,a,s,o,h){for(var f={ctype:0+(n==1?0:2)+(a==0?0:4),depth:s,frames:[]},l=(n+a)*s,u=l*i,w=0;w<e.length;w++)f.frames.push({rect:{x:0,y:0,width:i,height:t},img:new Uint8Array(e[w]),blend:0,dispose:1,bpp:Math.ceil(l/8),bpl:Math.ceil(u/8)});UPNG.encode.compressPNG(f,0,!0);var _=UPNG.encode._main(f,i,t,o,h);return _},UPNG.encode._main=function(e,i,t,n,a){a==null&&(a={});var s=UPNG.crc.crc,o=UPNG._bin.writeUint,h=UPNG._bin.writeUshort,f=UPNG._bin.writeASCII,l=8,u=e.frames.length>1,w=!1,_=33+(u?20:0);if(a.sRGB!=null&&(_+=13),a.pHYs!=null&&(_+=21),e.ctype==3){for(var g=e.plte.length,v=0;v<g;v++)e.plte[v]>>>24!=255&&(w=!0);_+=8+g*3+4+(w?8+g*1+4:0)}for(var k=0;k<e.frames.length;k++){var A=e.frames[k];u&&(_+=38),_+=A.cimg.length+12,k!=0&&(_+=4)}_+=12;for(var T=new Uint8Array(_),$=[137,80,78,71,13,10,26,10],v=0;v<8;v++)T[v]=$[v];if(o(T,l,13),l+=4,f(T,l,"IHDR"),l+=4,o(T,l,i),l+=4,o(T,l,t),l+=4,T[l]=e.depth,l++,T[l]=e.ctype,l++,T[l]=0,l++,T[l]=0,l++,T[l]=0,l++,o(T,l,s(T,l-17,17)),l+=4,a.sRGB!=null&&(o(T,l,1),l+=4,f(T,l,"sRGB"),l+=4,T[l]=a.sRGB,l++,o(T,l,s(T,l-5,5)),l+=4),a.pHYs!=null&&(o(T,l,9),l+=4,f(T,l,"pHYs"),l+=4,o(T,l,a.pHYs[0]),l+=4,o(T,l,a.pHYs[1]),l+=4,T[l]=a.pHYs[2],l++,o(T,l,s(T,l-13,13)),l+=4),u&&(o(T,l,8),l+=4,f(T,l,"acTL"),l+=4,o(T,l,e.frames.length),l+=4,o(T,l,a.loop!=null?a.loop:0),l+=4,o(T,l,s(T,l-12,12)),l+=4),e.ctype==3){var g=e.plte.length;o(T,l,g*3),l+=4,f(T,l,"PLTE"),l+=4;for(var v=0;v<g;v++){var D=v*3,C=e.plte[v],P=C&255,z=C>>>8&255,B=C>>>16&255;T[l+D+0]=P,T[l+D+1]=z,T[l+D+2]=B}if(l+=g*3,o(T,l,s(T,l-g*3-4,g*3+4)),l+=4,w){o(T,l,g),l+=4,f(T,l,"tRNS"),l+=4;for(var v=0;v<g;v++)T[l+v]=e.plte[v]>>>24&255;l+=g,o(T,l,s(T,l-g-4,g+4)),l+=4}}for(var F=0,k=0;k<e.frames.length;k++){var A=e.frames[k];u&&(o(T,l,26),l+=4,f(T,l,"fcTL"),l+=4,o(T,l,F++),l+=4,o(T,l,A.rect.width),l+=4,o(T,l,A.rect.height),l+=4,o(T,l,A.rect.x),l+=4,o(T,l,A.rect.y),l+=4,h(T,l,n[k]),l+=2,h(T,l,1e3),l+=2,T[l]=A.dispose,l++,T[l]=A.blend,l++,o(T,l,s(T,l-30,30)),l+=4);var L=A.cimg,g=L.length;o(T,l,g+(k==0?0:4)),l+=4;var N=l;f(T,l,k==0?"IDAT":"fdAT"),l+=4,k!=0&&(o(T,l,F++),l+=4),T.set(L,l),l+=g,o(T,l,s(T,N,l-N)),l+=4}return o(T,l,0),l+=4,f(T,l,"IEND"),l+=4,o(T,l,s(T,l-4,4)),l+=4,T.buffer},UPNG.encode.compressPNG=function(e,i,t){for(var n=0;n<e.frames.length;n++){var a=e.frames[n];a.rect.width;var s=a.rect.height,o=new Uint8Array(s*a.bpl+s);a.cimg=UPNG.encode._filterZero(a.img,s,a.bpp,a.bpl,o,i,t)}},UPNG.encode.compress=function(e,i,t,n,a){for(var s=a[0],o=a[1],h=a[2],f=a[3],l=a[4],u=6,w=8,_=255,g=0;g<e.length;g++)for(var v=new Uint8Array(e[g]),k=v.length,A=0;A<k;A+=4)_&=v[A+3];var T=_!=255,$=UPNG.encode.framize(e,i,t,s,o,h),D={},C=[],P=[];if(n!=0){for(var z=[],A=0;A<$.length;A++)z.push($[A].img.buffer);for(var B=UPNG.encode.concatRGBA(z),F=UPNG.quantize(B,n),L=0,N=new Uint8Array(F.abuf),A=0;A<$.length;A++){var G=$[A].img,V=G.length;P.push(new Uint8Array(F.inds.buffer,L>>2,V>>2));for(var g=0;g<V;g+=4)G[g]=N[L+g],G[g+1]=N[L+g+1],G[g+2]=N[L+g+2],G[g+3]=N[L+g+3];L+=V}for(var A=0;A<F.plte.length;A++)C.push(F.plte[A].est.rgba)}else for(var g=0;g<$.length;g++){var J=$[g],Q=new Uint32Array(J.img.buffer),W=J.rect.width,k=Q.length,ne=new Uint8Array(k);P.push(ne);for(var A=0;A<k;A++){var me=Q[A];if(A!=0&&me==Q[A-1])ne[A]=ne[A-1];else if(A>W&&me==Q[A-W])ne[A]=ne[A-W];else{var ve=D[me];if(ve==null&&(D[me]=ve=C.length,C.push(me),C.length>=300))break;ne[A]=ve}}}var ye=C.length;ye<=256&&l==!1&&(ye<=2?w=1:ye<=4?w=2:ye<=16?w=4:w=8,w=Math.max(w,f));for(var g=0;g<$.length;g++){var J=$[g];J.rect.x,J.rect.y;var W=J.rect.width,Me=J.rect.height,Re=J.img;new Uint32Array(Re.buffer);var _e=4*W,Be=4;if(ye<=256&&l==!1){_e=Math.ceil(w*W/8);for(var Se=new Uint8Array(_e*Me),re=P[g],Ie=0;Ie<Me;Ie++){var A=Ie*_e,Fe=Ie*W;if(w==8)for(var ke=0;ke<W;ke++)Se[A+ke]=re[Fe+ke];else if(w==4)for(var ke=0;ke<W;ke++)Se[A+(ke>>1)]|=re[Fe+ke]<<4-(ke&1)*4;else if(w==2)for(var ke=0;ke<W;ke++)Se[A+(ke>>2)]|=re[Fe+ke]<<6-(ke&3)*2;else if(w==1)for(var ke=0;ke<W;ke++)Se[A+(ke>>3)]|=re[Fe+ke]<<7-(ke&7)*1}Re=Se,u=3,Be=1}else if(T==!1&&$.length==1){for(var Se=new Uint8Array(W*Me*3),Ye=W*Me,A=0;A<Ye;A++){var G=A*3,Je=A*4;Se[G]=Re[Je],Se[G+1]=Re[Je+1],Se[G+2]=Re[Je+2]}Re=Se,u=2,Be=3,_e=3*W}J.img=Re,J.bpl=_e,J.bpp=Be}return{ctype:u,depth:w,plte:C,frames:$}},UPNG.encode.framize=function(e,i,t,n,a,s){for(var o=[],h=0;h<e.length;h++){var f=new Uint8Array(e[h]),l=new Uint32Array(f.buffer),u,w=0,_=0,g=i,v=t,k=n?1:0;if(h!=0){for(var A=s||n||h==1||o[h-2].dispose!=0?1:2,T=0,$=1e9,D=0;D<A;D++){for(var J=new Uint8Array(e[h-1-D]),C=new Uint32Array(e[h-1-D]),P=i,z=t,B=-1,F=-1,L=0;L<t;L++)for(var N=0;N<i;N++){var G=L*i+N;l[G]!=C[G]&&(N<P&&(P=N),N>B&&(B=N),L<z&&(z=L),L>F&&(F=L))}B==-1&&(P=z=B=F=0),a&&((P&1)==1&&P--,(z&1)==1&&z--);var V=(B-P+1)*(F-z+1);V<$&&($=V,T=D,w=P,_=z,g=B-P+1,v=F-z+1)}var J=new Uint8Array(e[h-1-T]);T==1&&(o[h-1].dispose=2),u=new Uint8Array(g*v*4),UPNG._copyTile(J,i,t,u,g,v,-w,-_,0),k=UPNG._copyTile(f,i,t,u,g,v,-w,-_,3)?1:0,k==1?UPNG.encode._prepareDiff(f,i,t,u,{x:w,y:_,width:g,height:v}):UPNG._copyTile(f,i,t,u,g,v,-w,-_,0)}else u=f.slice(0);o.push({rect:{x:w,y:_,width:g,height:v},img:u,blend:k,dispose:0})}if(n)for(var h=0;h<o.length;h++){var Q=o[h];if(Q.blend!=1){var W=Q.rect,ne=o[h-1].rect,me=Math.min(W.x,ne.x),ve=Math.min(W.y,ne.y),ye=Math.max(W.x+W.width,ne.x+ne.width),Me=Math.max(W.y+W.height,ne.y+ne.height),Re={x:me,y:ve,width:ye-me,height:Me-ve};o[h-1].dispose=1,h-1!=0&&UPNG.encode._updateFrame(e,i,t,o,h-1,Re,a),UPNG.encode._updateFrame(e,i,t,o,h,Re,a)}}var _e=0;if(e.length!=1)for(var G=0;G<o.length;G++){var Q=o[G];_e+=Q.rect.width*Q.rect.height}return o},UPNG.encode._updateFrame=function(e,i,t,n,a,s,o){for(var h=Uint8Array,f=Uint32Array,l=new h(e[a-1]),u=new f(e[a-1]),w=a+1<e.length?new h(e[a+1]):null,_=new h(e[a]),g=new f(_.buffer),v=i,k=t,A=-1,T=-1,$=0;$<s.height;$++)for(var D=0;D<s.width;D++){var C=s.x+D,P=s.y+$,z=P*i+C,B=g[z];B==0||n[a-1].dispose==0&&u[z]==B&&(w==null||w[z*4+3]!=0)||(C<v&&(v=C),C>A&&(A=C),P<k&&(k=P),P>T&&(T=P))}A==-1&&(v=k=A=T=0),o&&((v&1)==1&&v--,(k&1)==1&&k--),s={x:v,y:k,width:A-v+1,height:T-k+1};var F=n[a];F.rect=s,F.blend=1,F.img=new Uint8Array(s.width*s.height*4),n[a-1].dispose==0?(UPNG._copyTile(l,i,t,F.img,s.width,s.height,-s.x,-s.y,0),UPNG.encode._prepareDiff(_,i,t,F.img,s)):UPNG._copyTile(_,i,t,F.img,s.width,s.height,-s.x,-s.y,0)},UPNG.encode._prepareDiff=function(e,i,t,n,a){UPNG._copyTile(e,i,t,n,a.width,a.height,-a.x,-a.y,2)},UPNG.encode._filterZero=function(e,i,t,n,a,s,o){var h=[],f=[0,1,2,3,4];s!=-1?f=[s]:(i*n>5e5||t==1)&&(f=[0]);var l;o&&(l={level:0});for(var u=o&&UZIP!=null?UZIP:pako,w=0;w<f.length;w++){for(var _=0;_<i;_++)UPNG.encode._filterLine(a,e,_,n,t,f[w]);h.push(u.deflate(a,l))}for(var g,v=1e9,w=0;w<h.length;w++)h[w].length<v&&(g=w,v=h[w].length);return h[g]},UPNG.encode._filterLine=function(e,i,t,n,a,s){var o=t*n,h=o+t,f=UPNG.decode._paeth;if(e[h]=s,h++,s==0)if(n<500)for(var l=0;l<n;l++)e[h+l]=i[o+l];else e.set(new Uint8Array(i.buffer,o,n),h);else if(s==1){for(var l=0;l<a;l++)e[h+l]=i[o+l];for(var l=a;l<n;l++)e[h+l]=i[o+l]-i[o+l-a]+256&255}else if(t==0){for(var l=0;l<a;l++)e[h+l]=i[o+l];if(s==2)for(var l=a;l<n;l++)e[h+l]=i[o+l];if(s==3)for(var l=a;l<n;l++)e[h+l]=i[o+l]-(i[o+l-a]>>1)+256&255;if(s==4)for(var l=a;l<n;l++)e[h+l]=i[o+l]-f(i[o+l-a],0,0)+256&255}else{if(s==2)for(var l=0;l<n;l++)e[h+l]=i[o+l]+256-i[o+l-n]&255;if(s==3){for(var l=0;l<a;l++)e[h+l]=i[o+l]+256-(i[o+l-n]>>1)&255;for(var l=a;l<n;l++)e[h+l]=i[o+l]+256-(i[o+l-n]+i[o+l-a]>>1)&255}if(s==4){for(var l=0;l<a;l++)e[h+l]=i[o+l]+256-f(0,i[o+l-n],0)&255;for(var l=a;l<n;l++)e[h+l]=i[o+l]+256-f(i[o+l-a],i[o+l-n],i[o+l-a-n])&255}}},UPNG.crc={table:function(){for(var e=new Uint32Array(256),i=0;i<256;i++){for(var t=i,n=0;n<8;n++)t&1?t=3988292384^t>>>1:t=t>>>1;e[i]=t}return e}(),update:function(e,i,t,n){for(var a=0;a<n;a++)e=UPNG.crc.table[(e^i[t+a])&255]^e>>>8;return e},crc:function(e,i,t){return UPNG.crc.update(4294967295,e,i,t)^4294967295}},UPNG.quantize=function(e,i){var t=new Uint8Array(e),n=t.slice(0),a=new Uint32Array(n.buffer),s=UPNG.quantize.getKDtree(n,i),o=s[0],h=s[1];UPNG.quantize.planeDst;for(var f=t,l=a,u=f.length,w=new Uint8Array(t.length>>2),_=0;_<u;_+=4){var g=f[_]*.00392156862745098,v=f[_+1]*(1/255),k=f[_+2]*(1/255),A=f[_+3]*(1/255),T=UPNG.quantize.getNearest(o,g,v,k,A);w[_>>2]=T.ind,l[_>>2]=T.est.rgba}return{abuf:n.buffer,inds:w,plte:h}},UPNG.quantize.getKDtree=function(e,i,t){t==null&&(t=1e-4);var n=new Uint32Array(e.buffer),a={i0:0,i1:e.length,bst:null,est:null,tdst:0,left:null,right:null};a.bst=UPNG.quantize.stats(e,a.i0,a.i1),a.est=UPNG.quantize.estats(a.bst);for(var s=[a];s.length<i;){for(var o=0,h=0,f=0;f<s.length;f++)s[f].est.L>o&&(o=s[f].est.L,h=f);if(o<t)break;var l=s[h],u=UPNG.quantize.splitPixels(e,n,l.i0,l.i1,l.est.e,l.est.eMq255),w=l.i0>=u||l.i1<=u;if(w){l.est.L=0;continue}var _={i0:l.i0,i1:u,bst:null,est:null,tdst:0,left:null,right:null};_.bst=UPNG.quantize.stats(e,_.i0,_.i1),_.est=UPNG.quantize.estats(_.bst);var g={i0:u,i1:l.i1,bst:null,est:null,tdst:0,left:null,right:null};g.bst={R:[],m:[],N:l.bst.N-_.bst.N};for(var f=0;f<16;f++)g.bst.R[f]=l.bst.R[f]-_.bst.R[f];for(var f=0;f<4;f++)g.bst.m[f]=l.bst.m[f]-_.bst.m[f];g.est=UPNG.quantize.estats(g.bst),l.left=_,l.right=g,s[h]=_,s.push(g)}s.sort(function(v,k){return k.bst.N-v.bst.N});for(var f=0;f<s.length;f++)s[f].ind=f;return[a,s]},UPNG.quantize.getNearest=function(e,i,t,n,a){if(e.left==null)return e.tdst=UPNG.quantize.dist(e.est.q,i,t,n,a),e;var s=UPNG.quantize.planeDst(e.est,i,t,n,a),o=e.left,h=e.right;s>0&&(o=e.right,h=e.left);var f=UPNG.quantize.getNearest(o,i,t,n,a);if(f.tdst<=s*s)return f;var l=UPNG.quantize.getNearest(h,i,t,n,a);return l.tdst<f.tdst?l:f},UPNG.quantize.planeDst=function(e,i,t,n,a){var s=e.e;return s[0]*i+s[1]*t+s[2]*n+s[3]*a-e.eMq},UPNG.quantize.dist=function(e,i,t,n,a){var s=i-e[0],o=t-e[1],h=n-e[2],f=a-e[3];return s*s+o*o+h*h+f*f},UPNG.quantize.splitPixels=function(e,i,t,n,a,s){var o=UPNG.quantize.vecDot;for(n-=4;t<n;){for(;o(e,t,a)<=s;)t+=4;for(;o(e,n,a)>s;)n-=4;if(t>=n)break;var h=i[t>>2];i[t>>2]=i[n>>2],i[n>>2]=h,t+=4,n-=4}for(;o(e,t,a)>s;)t-=4;return t+4},UPNG.quantize.vecDot=function(e,i,t){return e[i]*t[0]+e[i+1]*t[1]+e[i+2]*t[2]+e[i+3]*t[3]},UPNG.quantize.stats=function(e,i,t){for(var n=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],a=[0,0,0,0],s=t-i>>2,o=i;o<t;o+=4){var h=e[o]*.00392156862745098,f=e[o+1]*(1/255),l=e[o+2]*(1/255),u=e[o+3]*(1/255);a[0]+=h,a[1]+=f,a[2]+=l,a[3]+=u,n[0]+=h*h,n[1]+=h*f,n[2]+=h*l,n[3]+=h*u,n[5]+=f*f,n[6]+=f*l,n[7]+=f*u,n[10]+=l*l,n[11]+=l*u,n[15]+=u*u}return n[4]=n[1],n[8]=n[2],n[9]=n[6],n[12]=n[3],n[13]=n[7],n[14]=n[11],{R:n,m:a,N:s}},UPNG.quantize.estats=function(e){var i=e.R,t=e.m,n=e.N,a=t[0],s=t[1],o=t[2],h=t[3],f=n==0?0:1/n,l=[i[0]-a*a*f,i[1]-a*s*f,i[2]-a*o*f,i[3]-a*h*f,i[4]-s*a*f,i[5]-s*s*f,i[6]-s*o*f,i[7]-s*h*f,i[8]-o*a*f,i[9]-o*s*f,i[10]-o*o*f,i[11]-o*h*f,i[12]-h*a*f,i[13]-h*s*f,i[14]-h*o*f,i[15]-h*h*f],u=l,w=UPNG.M4,_=[.5,.5,.5,.5],g=0,v=0;if(n!=0)for(var k=0;k<10&&(_=w.multVec(u,_),v=Math.sqrt(w.dot(_,_)),_=w.sml(1/v,_),!(Math.abs(v-g)<1e-9));k++)g=v;var A=[a*f,s*f,o*f,h*f],T=w.dot(w.sml(255,A),_);return{Cov:l,q:A,e:_,L:g,eMq255:T,eMq:w.dot(_,A),rgba:(Math.round(255*A[3])<<24|Math.round(255*A[2])<<16|Math.round(255*A[1])<<8|Math.round(255*A[0])<<0)>>>0}},UPNG.M4={multVec:function(e,i){return[e[0]*i[0]+e[1]*i[1]+e[2]*i[2]+e[3]*i[3],e[4]*i[0]+e[5]*i[1]+e[6]*i[2]+e[7]*i[3],e[8]*i[0]+e[9]*i[1]+e[10]*i[2]+e[11]*i[3],e[12]*i[0]+e[13]*i[1]+e[14]*i[2]+e[15]*i[3]]},dot:function(e,i){return e[0]*i[0]+e[1]*i[1]+e[2]*i[2]+e[3]*i[3]},sml:function(e,i){return[e*i[0],e*i[1],e*i[2],e*i[3]]}},UPNG.encode.concatRGBA=function(e){for(var i=0,t=0;t<e.length;t++)i+=e[t].byteLength;for(var n=new Uint8Array(i),a=0,t=0;t<e.length;t++){for(var s=new Uint8Array(e[t]),o=s.length,h=0;h<o;h+=4){var f=s[h],l=s[h+1],u=s[h+2],w=s[h+3];w==0&&(f=l=u=0),n[a+h]=f,n[a+h+1]=l,n[a+h+2]=u,n[a+h+3]=w}a+=o}return n.buffer};class TxSprite{constructor(i){we(this,"width");we(this,"height");we(this,"numColors");we(this,"paletteData");we(this,"pixelData");we(this,"compress");this.width=i.width,this.height=i.height,this.numColors=i.numColors,this.paletteData=i.paletteData,this.pixelData=i.pixelData,this.compress=i.compress??!1,this.paletteData.length/3!==this.numColors&&this.numColors>0&&console.warn(`TxSprite constructor: numColors (${this.numColors}) does not match paletteData length (${this.paletteData.length/3} colors).`),this.pixelData.length!==this.width*this.height&&this.width*this.height>0&&console.warn(`TxSprite constructor: pixelData length (${this.pixelData.length}) does not match width*height (${this.width*this.height}).`)}static async fromIndexedPngBytes(i,t=!1){const n=UPNG.decode(i),{width:a,height:s,data:o,ctype:h,tabs:f}=n;return console.log(`PNG dimensions: ${a}x${s}, data length: ${o.byteLength}, ctype: ${h}, PLTE: ${f.PLTE}`),new TxSprite({width:a,height:s,numColors:f.PLTE?f.PLTE.length/3:0,paletteData:f.PLTE?new Uint8Array(f.PLTE):new Uint8Array,pixelData:new Uint8Array(o.slice(0,a*s)),compress:t})}static async fromImageBytes(i,t=48e3,n=!1){let a=await Image.load(i),s=a.width*a.height;if(s>t){const v=Math.sqrt(t/s);a=a.resize({factor:v})}(a.width>640||a.height>400)&&(a=a.resize({width:640,height:400,preserveAspectRatio:!0,interpolation:"nearestNeighbor"})),console.log(`Resized image to ${a.width}x${a.height}`);const o=utils_exports.PointContainer.fromUint8Array(a.getRGBAData(),a.width,a.height);console.log(`PointContainer created with ${o.getPointArray().length} points.`);const h=buildPaletteSync([o],{colors:15});console.log(`Palette built: ${h.getPointContainer().getPointArray().length} colors.`),h.getPointContainer().getPointArray().unshift(utils_exports.Point.createByQuadruplet([0,0,0,0]));const f=applyPaletteSync(o,h);console.log(`OutPointContainer: ${f.getPointArray().length} points.`);const l=h.getPointContainer().getPointArray(),u=f.getPointArray(),w=new Uint8Array(u.length);for(let v=0;v<u.length;v++){const k=u[v],A=k.r,T=k.g,$=k.b,D=k.a,C=l.findIndex(P=>P.r===A&&P.g===T&&P.b===$&&P.a===D);if(C===-1)throw new Error(`Could not find palette index for pixel ${v} with color (${A},${T},${$},${D})`);w[v]=C}console.log(`Indexed pixel data size: ${w.length}.`);const _=h.getPointContainer().getPointArray().length,g=new Uint8Array(_*3);return h.getPointContainer().getPointArray().forEach((v,k)=>{g[k*3+0]=v.r,g[k*3+1]=v.g,g[k*3+2]=v.b,console.log(`Color ${k}: R=${v.r}, G=${v.g}, B=${v.b}`)}),new TxSprite({width:a.width,height:a.height,numColors:_,paletteData:g,pixelData:w,compress:n})}get bpp(){return this.numColors<=0?4:this.numColors<=2?1:this.numColors<=4?2:(this.numColors<=16||console.warn(`numColors (${this.numColors}) is greater than 16. Defaulting BPP to 4.`),4)}pack(){let i;const t=this.bpp;switch(t){case 1:i=TxSprite._pack_1bit(this.pixelData);break;case 2:i=TxSprite._pack_2bit(this.pixelData);break;case 4:i=TxSprite._pack_4bit(this.pixelData);break;default:throw new Error(`Unsupported bpp: ${t}`)}const n=new Uint8Array(7),a=new DataView(n.buffer);a.setUint16(0,this.width,!1),a.setUint16(2,this.height,!1),a.setUint8(4,this.compress?1:0),a.setUint8(5,t),a.setUint8(6,this.numColors>16?16:this.numColors);let s=i;if(this.compress)try{s=lz4.compress(Buffer.from(i),9)}catch(h){throw console.error("LZ4 compression failed:",h),h}const o=new Uint8Array(n.length+this.paletteData.length+s.length);return o.set(n,0),o.set(this.paletteData,n.length),o.set(s,n.length+this.paletteData.length),o}static _pack_1bit(i){const t=Math.ceil(i.length/8),n=new Uint8Array(t);for(let a=0;a<i.length;a++){const s=Math.floor(a/8),o=7-a%8;i[a]&1&&(n[s]|=1<<o)}return n}static _pack_2bit(i){const t=Math.ceil(i.length/4),n=new Uint8Array(t);for(let a=0;a<i.length;a++){const s=Math.floor(a/4),o=(3-a%4)*2;n[s]|=(i[a]&3)<<o}return n}static _pack_4bit(i){const t=Math.ceil(i.length/2),n=new Uint8Array(t);for(let a=0;a<i.length;a++){const s=Math.floor(a/2),o=(1-a%2)*4;n[s]|=(i[a]&15)<<o}return n}toPngBytes(){return console.log(`Creating PNG: width=${this.width}, height=${this.height}, numColors=${this.numColors}, paletteData length=${this.paletteData.length}, pixelData length=${this.pixelData.length}`),TxSprite._makeRGBAPngFromIndexed(this.width,this.height,this.paletteData,this.pixelData)}static _makeRGBAPngFromIndexed(i,t,n,a){const s=i*t;if(a.length!==s)throw new Error(`Pixel index data (${a.length}) does not match image size (${s}).`);if(n.length%3!==0)throw new Error("Palette must be a flat RGB array of triplets.");const o=new Uint8Array(s*4);for(let h=0;h<s;h++){const f=a[h];if(f<0||f>=n.length/3)throw new Error(`Pixel index ${f} out of bounds for palette of length ${n.length/3}.`);const l=n[f*3]??128,u=n[f*3+1]??128,w=n[f*3+2]??128,_=h*4;o[_]=l,o[_+1]=u,o[_+2]=w,o[_+3]=255}return UPNG.encode([o.buffer],i,t,0)}}class TxImageSpriteBlock{constructor(i){we(this,"image");we(this,"spriteLineHeight");we(this,"progressiveRender");we(this,"updatable");we(this,"spriteLines",[]);if(this.image=i.image,this.progressiveRender=i.progressiveRender??!0,this.updatable=i.updatable??!0,this.image.compress){const t=this.image.bpp,n=t>0?Math.floor((this.image.width+8/t-1)/(8/t)):0;this.spriteLineHeight=n>0?Math.floor(4096/n):0,this.spriteLineHeight===0&&n>0?this.spriteLineHeight=1:n===0&&(this.spriteLineHeight=this.image.height)}else this.spriteLineHeight=i.spriteLineHeight??16;this.image.height>0&&this.spriteLineHeight<1&&(this.spriteLineHeight=1),this._splitIntoLines()}_splitIntoLines(){const i=this.image.pixelData,t=this.image.width;if(this.spriteLineHeight<=0){console.warn("TxImageSpriteBlock: spriteLineHeight is zero or negative, cannot split lines."),this.image.height>0&&this.spriteLines.push(new TxSprite({width:this.image.width,height:this.image.height,numColors:this.image.numColors,paletteData:this.image.paletteData,pixelData:i,compress:this.image.compress}));return}const n=Math.floor(this.image.height/this.spriteLineHeight);for(let s=0;s<n;s++){const o=s*this.spriteLineHeight*t,h=o+this.spriteLineHeight*t,f=i.slice(o,h);this.spriteLines.push(new TxSprite({width:this.image.width,height:this.spriteLineHeight,numColors:this.image.numColors,paletteData:this.image.paletteData,pixelData:f,compress:this.image.compress}))}const a=this.image.height%this.spriteLineHeight;if(a>0){const s=n*this.spriteLineHeight*t,o=i.slice(s);this.spriteLines.push(new TxSprite({width:this.image.width,height:a,numColors:this.image.numColors,paletteData:this.image.paletteData,pixelData:o,compress:this.image.compress}))}}pack(){if(this.spriteLines.length===0&&this.image.height>0)if(console.warn("TxImageSpriteBlock pack: No sprite lines to pack, but image has height. This might indicate an issue in line splitting."),this.spriteLineHeight<=0&&this.image.height>0)console.warn("Attempting to pack header with image.height due to zero spriteLineHeight");else throw new Error("No sprite lines to pack");else this.spriteLines.length===0&&this.image.height;const i=new Uint8Array(9),t=new DataView(i.buffer);let n=this.spriteLineHeight;return this.image.height>0&&this.spriteLineHeight<=0&&(this.spriteLines.length>0?n=this.spriteLines[0].height:n=this.image.height),t.setUint8(0,255),t.setUint16(1,this.image.width,!1),t.setUint16(3,this.image.height,!1),t.setUint16(5,n,!1),t.setUint8(7,this.progressiveRender?1:0),t.setUint8(8,this.updatable?1:0),i}}class TxManualExpSettings{constructor(i={}){we(this,"manualShutter");we(this,"manualAnalogGain");we(this,"manualRedGain");we(this,"manualGreenGain");we(this,"manualBlueGain");this.manualShutter=i.manualShutter??3072,this.manualAnalogGain=i.manualAnalogGain??16,this.manualRedGain=i.manualRedGain??121,this.manualGreenGain=i.manualGreenGain??64,this.manualBlueGain=i.manualBlueGain??140}pack(){const i=new ArrayBuffer(9),t=new DataView(i);return t.setUint16(0,this.manualShutter&16383,!1),t.setUint8(2,this.manualAnalogGain&255),t.setUint16(3,this.manualRedGain&1023,!1),t.setUint16(5,this.manualGreenGain&1023,!1),t.setUint16(7,this.manualBlueGain&1023,!1),new Uint8Array(i)}}class TxAutoExpSettings{constructor(i={}){we(this,"meteringIndex");we(this,"exposure");we(this,"exposureSpeed");we(this,"shutterLimit");we(this,"analogGainLimit");we(this,"whiteBalanceSpeed");we(this,"rgbGainLimit");this.meteringIndex=i.meteringIndex??1,this.exposure=i.exposure??.1,this.exposureSpeed=i.exposureSpeed??.45,this.shutterLimit=i.shutterLimit??16383,this.analogGainLimit=i.analogGainLimit??16,this.whiteBalanceSpeed=i.whiteBalanceSpeed??.5,this.rgbGainLimit=i.rgbGainLimit??287}pack(){const i=new ArrayBuffer(9),t=new DataView(i);return t.setUint8(0,this.meteringIndex&255),t.setUint8(1,Math.trunc(this.exposure*255)&255),t.setUint8(2,Math.trunc(this.exposureSpeed*255)&255),t.setUint16(3,this.shutterLimit&16383,!1),t.setUint8(5,this.analogGainLimit&255),t.setUint8(6,Math.trunc(this.whiteBalanceSpeed*255)&255),t.setUint16(7,this.rgbGainLimit&1023,!1),new Uint8Array(i)}}class TxSpriteCoords{constructor(i){we(this,"code");we(this,"x");we(this,"y");we(this,"offset");this.code=i.code,this.x=i.x,this.y=i.y,this.offset=i.offset??0}pack(){const i=new ArrayBuffer(6),t=new DataView(i);return t.setUint8(0,this.code&255),t.setUint16(1,this.x&65535,!1),t.setUint16(3,this.y&65535,!1),t.setUint8(5,this.offset&255),new Uint8Array(i)}}class TxTextSpriteBlock{constructor(i){we(this,"width");we(this,"fontSize");we(this,"lineHeight");we(this,"maxDisplayLines");we(this,"fontFamily");this.width=i.width,this.fontSize=i.fontSize,this.lineHeight=i.lineHeight,this.maxDisplayLines=i.maxDisplayLines,this.fontFamily=i.fontFamily||"sans-serif"}createTextSprites(i){if(this.width<=0||this.lineHeight<=0)return[];const t=i.split(`
204
+ `),n=[];for(const a of t){if(a.trim()===""){const _=new TxSprite({width:1,height:this.lineHeight,numColors:2,paletteData:new Uint8Array([0,0,0,255,255,255]),pixelData:new Uint8Array(this.lineHeight),compress:!1});n.push(_);continue}const s=document.createElement("canvas");s.width=this.width,s.height=this.lineHeight;const o=s.getContext("2d",{willReadFrequently:!0});if(!o){console.error("TxTextSpriteBlock: Could not get 2D rendering context.");continue}o.fillStyle="black",o.fillRect(0,0,s.width,s.height),o.fillStyle="white",o.font=`${this.fontSize}px ${this.fontFamily}`,o.textBaseline="alphabetic";const h=Math.round(this.lineHeight*.8);o.fillText(a,0,h);const f=o.getImageData(0,0,this.width,this.lineHeight),{data:l}=f,u=new Uint8Array(this.width*this.lineHeight);for(let _=0,g=0;_<l.length;_+=4,g++)u[g]=l[_]>127?1:0;const w=new TxSprite({width:this.width,height:this.lineHeight,numColors:2,paletteData:new Uint8Array([0,0,0,255,255,255]),pixelData:u,compress:!1});n.push(w)}return n}pack(){const i=new Uint8Array(6),t=new DataView(i.buffer);return t.setUint8(0,255),t.setUint16(1,this.width,!1),t.setUint16(3,this.lineHeight,!1),t.setUint8(5,this.maxDisplayLines&255),i}}var RxAudioSampleRate=(e=>(e[e.SAMPLE_RATE_8KHZ=8e3]="SAMPLE_RATE_8KHZ",e[e.SAMPLE_RATE_16KHZ=16e3]="SAMPLE_RATE_16KHZ",e))(RxAudioSampleRate||{}),RxAudioBitDepth=(e=>(e[e.BIT_DEPTH_8=8]="BIT_DEPTH_8",e[e.BIT_DEPTH_16=16]="BIT_DEPTH_16",e))(RxAudioBitDepth||{});class RxAudio{constructor(i={}){we(this,"nonFinalChunkMsgCode");we(this,"finalChunkMsgCode");we(this,"streaming");we(this,"bitDepth");we(this,"sampleRate");we(this,"queue");we(this,"_audioBuffer");this.nonFinalChunkMsgCode=i.nonFinalChunkMsgCode??5,this.finalChunkMsgCode=i.finalChunkMsgCode??6,this.streaming=i.streaming??!1,this.sampleRate=i.sampleRate??8e3,this.bitDepth=i.bitDepth??8,this.queue=null,this._audioBuffer=[]}concatenateAudioData(){let i=0;for(const a of this._audioBuffer)i+=a.length;const t=new Uint8Array(i);let n=0;for(const a of this._audioBuffer)t.set(a,n),n+=a.length;return t}handleData(i){if(!this.queue){console.warn("RxAudio: Received data but queue not initialized - call attach() first");return}const t=i[0],n=i.slice(1);if(this.streaming)n.length>0&&this.queue.put(this.bitDepth===8?Int8Array.from(n):new Int16Array(n.buffer)),t===this.finalChunkMsgCode&&this.queue.put(null);else if(this._audioBuffer.push(n),t===this.finalChunkMsgCode){const a=this.concatenateAudioData();this._audioBuffer=[],this.queue.put(this.bitDepth===8?Int8Array.from(a):new Int16Array(a.buffer)),this.queue.put(null)}}async attach(i){return this.queue=new AsyncQueue,this._audioBuffer=[],i.registerDataResponseHandler(this,[this.nonFinalChunkMsgCode,this.finalChunkMsgCode],this.handleData.bind(this)),this.queue}detach(i){i.unregisterDataResponseHandler(this),this.queue&&this.queue.clear(),this.queue=null,this._audioBuffer=[]}static writeString(i,t,n){for(let a=0;a<n.length;a++)i.setUint8(t+a,n.charCodeAt(a))}static toWavBytes(i,t=8e3,n=8,a=1){const s=t*a*(n/8),o=i.length,h=36+o,f=44,l=new ArrayBuffer(f+o),u=new DataView(l);let w=0;if(RxAudio.writeString(u,w,"RIFF"),w+=4,u.setUint32(w,h,!0),w+=4,RxAudio.writeString(u,w,"WAVE"),w+=4,RxAudio.writeString(u,w,"fmt "),w+=4,u.setUint32(w,16,!0),w+=4,u.setUint16(w,1,!0),w+=2,u.setUint16(w,a,!0),w+=2,u.setUint32(w,t,!0),w+=4,u.setUint32(w,s,!0),w+=4,u.setUint16(w,a*(n/8),!0),w+=2,u.setUint16(w,n,!0),w+=2,RxAudio.writeString(u,w,"data"),w+=4,u.setUint32(w,o,!0),w+=4,n===8){const _=new Uint8Array(l,w,o);for(let g=0;g<o;g++){const v=i[g]<128?i[g]:i[g]-256;_[g]=v+128}}else new Uint8Array(l,w).set(i);return new Uint8Array(l)}static pcm8BitToFloat32(i){const t=i.length,n=new Float32Array(t),a=new Int8Array(i.buffer,i.byteOffset,t);for(let s=0;s<t;s++)n[s]=a[s]/64,n[s]<-1?n[s]=-1:n[s]>1&&(n[s]=1);return n}static pcm16BitToFloat32(i){const t=i.length/2,n=new Float32Array(t),a=new DataView(i.buffer,i.byteOffset,i.byteLength);for(let s=0;s<t;s++){let h=a.getInt16(s*2)/16384;h<-1?h=-1:h>1&&(h=1),n[s]=h}return n}}class SensorBuffer{constructor(i){we(this,"maxSize");we(this,"_buffer");this.maxSize=i,this._buffer=[]}add(i){this._buffer.push(i),this._buffer.length>this.maxSize&&this._buffer.shift()}get average(){if(!this._buffer.length)return[0,0,0];let i=0,t=0,n=0;for(const[s,o,h]of this._buffer)i+=s,t+=o,n+=h;const a=this._buffer.length;return[i/a,t/a,n/a]}}class IMUData{constructor(i,t,n){we(this,"compass");we(this,"accel");we(this,"raw");this.compass=i,this.accel=t,this.raw=n}get pitch(){return Math.atan2(this.accel[1],this.accel[2])*180/Math.PI}get roll(){return Math.atan2(this.accel[0],this.accel[2])*180/Math.PI}}class RxIMU{constructor(i={}){we(this,"msgCode");we(this,"smoothingSamples");we(this,"queue");we(this,"compassBuffer");we(this,"accelBuffer");this.msgCode=i.msgCode??10,this.smoothingSamples=i.smoothingSamples??1,this.queue=null,this.compassBuffer=new SensorBuffer(this.smoothingSamples),this.accelBuffer=new SensorBuffer(this.smoothingSamples)}handleData(i){if(!this.queue){console.warn("RxIMU: Received data but queue not initialized - call attach() first");return}if(i.length<26){console.warn("RxIMU: Data packet too short for IMU float data.");return}const t=new DataView(i.buffer,i.byteOffset),n=t.getFloat32(2,!0),a=t.getFloat32(6,!0),s=t.getFloat32(10,!0),o=t.getFloat32(14,!0),h=t.getFloat32(18,!0),f=t.getFloat32(22,!0),l=[n,a,s],u=[o,h,f];this.compassBuffer.add(l),this.accelBuffer.add(u);const w=new IMUData(this.compassBuffer.average,this.accelBuffer.average,{compass:l,accel:u});this.queue.put(w)}async attach(i){return this.queue=new AsyncQueue,i.registerDataResponseHandler(this,[this.msgCode],this.handleData.bind(this)),this.queue}detach(i){i.unregisterDataResponseHandler(this),this.queue&&this.queue.clear(),this.queue=null}}class RxMeteringData{constructor(i={}){we(this,"msgCode");we(this,"queue");this.msgCode=i.msgCode??18,this.queue=null}handleData(i){if(!this.queue){console.warn("RxMeteringData: Received data but queue not initialized - call attach() first");return}if(i.length<7){console.warn("RxMeteringData: Data packet too short for metering data.");return}const t={spot_r:i[1],spot_g:i[2],spot_b:i[3],matrix_r:i[4],matrix_g:i[5],matrix_b:i[6]};this.queue.put(t)}async attach(i){return this.queue=new AsyncQueue,i.registerDataResponseHandler(this,[this.msgCode],this.handleData.bind(this)),this.queue}detach(i){i.unregisterDataResponseHandler(this),this.queue&&this.queue.clear(),this.queue=null}}class RxAutoExpResult{constructor(i={}){we(this,"msgCode");we(this,"queue");this.msgCode=i.msgCode??17,this.queue=null}handleData(i){if(!this.queue){console.warn("RxAutoExpResult: Received data but queue not initialized - call attach() first");return}if(i.length<65){console.warn(`RxAutoExpResult: Data packet too short for auto exposure result data. Expected 65 bytes, got ${i.length}.`);return}const t=new DataView(i.buffer,i.byteOffset,i.byteLength),n=!0;let a=1;const s=[];for(let h=0;h<16;h++)s.push(t.getFloat32(a,n)),a+=4;const o={error:s[0],shutter:s[1],analog_gain:s[2],red_gain:s[3],green_gain:s[4],blue_gain:s[5],brightness:{center_weighted_average:s[6],scene:s[7],matrix:{r:s[8],g:s[9],b:s[10],average:s[11]},spot:{r:s[12],g:s[13],b:s[14],average:s[15]}}};this.queue.put(o)}async attach(i){return this.queue=new AsyncQueue,i.registerDataResponseHandler(this,[this.msgCode],this.handleData.bind(this)),this.queue}detach(i){i.unregisterDataResponseHandler(this),this.queue&&this.queue.clear(),this.queue=null}}const ct=class ct{constructor(i={}){we(this,"nonFinalChunkMsgCode");we(this,"finalChunkMsgCode");we(this,"upright");we(this,"isRaw");we(this,"quality");we(this,"resolution");we(this,"queue");we(this,"_imageDataChunks");this.nonFinalChunkMsgCode=i.nonFinalChunkMsgCode??7,this.finalChunkMsgCode=i.finalChunkMsgCode??8,this.upright=i.upright??!0,this.isRaw=i.isRaw??!1,this.quality=i.quality??null,this.resolution=i.resolution??null,this.queue=null,this._imageDataChunks=[]}static hasJpegHeader(i,t){return`${i}_${t}`in ct._jpegHeaderMap}concatenateImageData(){let i=0;for(const a of this._imageDataChunks)i+=a.length;const t=new Uint8Array(i);let n=0;for(const a of this._imageDataChunks)t.set(a,n),n+=a.length;return t}handleData(i){if(!this.queue){console.warn("RxPhoto: Received data but queue not initialized - call attach() first");return}const t=i[0],n=i.slice(1);this._imageDataChunks.push(n),t===this.finalChunkMsgCode&&this._processCompleteImage().catch(a=>{console.error("RxPhoto: Error processing complete image:",a),this._imageDataChunks=[]})}async _processCompleteImage(){if(!this.queue)return;let i;const t=this.concatenateImageData();if(this._imageDataChunks=[],this.isRaw){if(!this.quality||!this.resolution)throw new Error("RxPhoto: Quality and resolution must be set for raw images if no header is cached.");const n=`${this.quality}_${this.resolution}`,a=ct._jpegHeaderMap[n];if(!a)throw new Error(`RxPhoto: No JPEG header found for quality ${this.quality} and resolution ${this.resolution} - request full JPEG first to cache header.`);const s=new Uint8Array(a.length+t.length);s.set(a,0),s.set(t,a.length),i=s}else if(i=t,this.quality&&this.resolution){const n=`${this.quality}_${this.resolution}`;if(!ct._jpegHeaderMap[n]){const a=i.slice(0,623);ct._jpegHeaderMap[n]=a}}this.upright?(console.log("Rotating image 90 degrees counter-clockwise"),this.queue.put(await this.rotateJpeg90CounterClockwise(i))):this.queue.put(i)}async attach(i){return this.isRaw&&(!this.quality||!this.resolution)&&console.warn("RxPhoto: Handling raw images without quality/resolution specified. Header must be pre-cached or will fail."),this.queue=new AsyncQueue,this._imageDataChunks=[],i.registerDataResponseHandler(this,[this.nonFinalChunkMsgCode,this.finalChunkMsgCode],this.handleData.bind(this)),this.queue}detach(i){i.unregisterDataResponseHandler(this),this.queue&&this.queue.clear(),this.queue=null,this._imageDataChunks=[]}async rotateJpeg90CounterClockwise(i){const t=jpeg.decode(i,{useTArray:!0});if(!t||!t.data||!t.width||!t.height)throw new Error("Failed to decode JPEG image.");const n=document.createElement("canvas");n.width=t.height,n.height=t.width;const a=n.getContext("2d");if(!a)throw new Error("Failed to get canvas 2D context.");const s=document.createElement("canvas");s.width=t.width,s.height=t.height;const o=s.getContext("2d");if(!o)throw new Error("Failed to get temporary canvas 2D context.");o.putImageData(new ImageData(new Uint8ClampedArray(t.data.buffer),t.width,t.height),0,0),a.clearRect(0,0,n.width,n.height),a.translate(0,n.height),a.rotate(-90*Math.PI/180),a.drawImage(s,0,0);const f=await(await new Promise((l,u)=>{n.toBlob(w=>{w?l(w):u(new Error("Failed to convert canvas to JPEG blob."))},"image/jpeg")})).arrayBuffer();return new Uint8Array(f)}};we(ct,"_jpegHeaderMap",{});let RxPhoto=ct;class RxTap{constructor(i={}){we(this,"msgCode");we(this,"threshold");we(this,"queue");we(this,"lastTapTime");we(this,"tapCount");we(this,"thresholdTimeoutId");this.msgCode=i.msgCode??9,this.threshold=(i.threshold??.3)*1e3,this.queue=null,this.lastTapTime=0,this.tapCount=0,this.thresholdTimeoutId=null}async resetThresholdTimer(){this.thresholdTimeoutId&&(clearTimeout(this.thresholdTimeoutId),this.thresholdTimeoutId=null),this.thresholdTimeoutId=setTimeout(()=>{this.thresholdTimeout()},this.threshold)}thresholdTimeout(){this.queue&&this.tapCount>0&&(this.queue.put(this.tapCount),this.tapCount=0),this.thresholdTimeoutId=null}handleData(i){if(!this.queue){console.warn("RxTap: Received data but queue not initialized - call attach() first");return}const t=Date.now();if(t-this.lastTapTime<40){this.lastTapTime=t;return}this.lastTapTime=t,this.tapCount+=1,this.resetThresholdTimer()}async attach(i){return this.queue=new AsyncQueue,this.lastTapTime=0,this.tapCount=0,i.registerDataResponseHandler(this,[this.msgCode],this.handleData.bind(this)),this.queue}detach(i){i.unregisterDataResponseHandler(this),this.thresholdTimeoutId&&(clearTimeout(this.thresholdTimeoutId),this.thresholdTimeoutId=null),this.queue&&this.queue.clear(),this.queue=null,this.tapCount=0}}var ClickType=(e=>(e[e.SINGLE=1]="SINGLE",e[e.DOUBLE=2]="DOUBLE",e[e.LONG=3]="LONG",e))(ClickType||{});class RxClick{constructor(i={}){we(this,"clickFlag");we(this,"queue");this.clickFlag=i.clickFlag??11,this.queue=null}handleData(i){if(!this.queue){console.warn("RxClick: Received data but queue not initialized - call attach() first");return}if(i.length<2){console.warn("RxClick: Data packet too short for click data.");return}const t=i[1];switch(t){case 1:this.queue.put(1);break;case 2:this.queue.put(2);break;case 3:this.queue.put(3);break;default:console.warn(`RxClick: Unknown click type ${t}`)}}async attach(i){return this.queue=new AsyncQueue,i.registerDataResponseHandler(this,[this.clickFlag],this.handleData.bind(this)),this.queue}detach(i){i.unregisterDataResponseHandler(this),this.queue&&this.queue.clear(),this.queue=null}}class RectangularTextLayout{constructor(i){we(this,"width");we(this,"height");we(this,"fontSize");we(this,"fontFamily");we(this,"textAlign");this.width=i.width,this.height=i.height,this.fontSize=i.fontSize,this.fontFamily=i.fontFamily,this.textAlign=i.textAlign??"left"}get startY(){return 0}getLineLayout(i,t){return i<0||i+t>this.height?null:{width:this.width,xOffset:0}}}class CircularTextLayout{constructor(i){we(this,"width");we(this,"height");we(this,"fontSize");we(this,"fontFamily");we(this,"textAlign");we(this,"circleMargin");we(this,"radius");we(this,"centerX");we(this,"centerY");this.width=i.width,this.height=i.height,this.fontSize=i.fontSize,this.circleMargin=i.circleMargin??15,this.fontFamily=i.fontFamily,this.textAlign=i.textAlign??"center",this.radius=Math.min(this.width,this.height)/2-this.circleMargin,this.centerX=this.width/2,this.centerY=this.height/2}get startY(){return this.centerY-this.radius}getLineLayout(i,t){const n=i+t/2-this.centerY;if(Math.abs(n)>this.radius)return null;const a=Math.sqrt(this.radius*this.radius-n*n),s=Math.floor(a*2),o=Math.floor(this.centerX-a);return s<this.fontSize?null:{width:s,xOffset:o}}}class PageData{constructor(i,t){we(this,"_lines");we(this,"_layout");we(this,"_sprites",[]);we(this,"_isRasterizing",!1);this._lines=i,this._layout=t}get isEmpty(){return this._lines.length===0}get isRasterized(){return this._sprites.length>0}get rasterizedSprites(){return this._sprites}get lineTexts(){return this._lines.map(i=>i.text)}async rasterize(){if(!(this.isRasterized||this._isRasterizing)){this._isRasterizing=!0;try{const i=`${this._layout.fontSize}px ${this._layout.fontFamily??"sans-serif"}`;for(const t of this._lines){if(!t.text||t.lineHeight<=0||t.width<=0)continue;const n=document.createElement("canvas");n.width=t.width,n.height=t.lineHeight;const a=n.getContext("2d",{willReadFrequently:!0});if(!a){console.error("TxTextPage: Could not get 2D rendering context.");continue}a.fillStyle="black",a.fillRect(0,0,n.width,n.height),a.fillStyle="white",a.font=i,a.textAlign=this._layout.textAlign,a.textBaseline="alphabetic";const s=Math.round(t.lineHeight*.8);let o;switch(this._layout.textAlign){case"center":o=t.width/2;break;case"right":case"end":o=t.width;break;default:o=0}a.fillText(t.text,o,s);const h=a.getImageData(0,0,t.width,t.lineHeight),{data:f}=h,l=new Uint8Array(t.width*t.lineHeight);for(let w=0,_=0;w<f.length;w+=4,_++)l[_]=f[w]>=128?1:0;const u=new TxSprite({width:t.width,height:t.lineHeight,numColors:2,paletteData:new Uint8Array([0,0,0,255,255,255]),pixelData:l,compress:!1});this._sprites.push(u)}}finally{this._isRasterizing=!1}}}async toPngBytes(){this.isRasterized||await this.rasterize();const i=this._layout,t=i.width*i.height,n=new Uint8Array(t*4);for(let s=0;s<t;s++)n[s*4+3]=0;for(let s=0;s<this._sprites.length;s++){const o=this._sprites[s],h=this._lines[s],f=o.paletteData;for(let l=0;l<o.height;l++)for(let u=0;u<o.width;u++){const w=l*o.width+u,_=o.pixelData[w],g=h.xOffset+u,v=h.yOffset+l;if(g<0||g>=i.width||v<0||v>=i.height)continue;const k=(v*i.width+g)*4;n[k]=f[_*3],n[k+1]=f[_*3+1],n[k+2]=f[_*3+2],n[k+3]=255}}const a=UPNG.encode([n.buffer],i.width,i.height,0);return new Uint8Array(a)}pack(){if(!this.isRasterized)throw new Error("PageData must be rasterized before packing.");const i=this._sprites.length,t=new Uint8Array(6+i*4);t[0]=255,t[1]=this._layout.width>>8,t[2]=this._layout.width&255,t[3]=this._layout.height>>8,t[4]=this._layout.height&255,t[5]=i&255;for(let n=0;n<i;n++){const a=this._lines[n];t[6+n*4]=a.xOffset>>8,t[6+n*4+1]=a.xOffset&255,t[6+n*4+2]=a.yOffset>>8,t[6+n*4+3]=a.yOffset&255}return t}}class TxTextPage{constructor(i){we(this,"layout");we(this,"text");we(this,"_remainingText");this.layout=i.layout,this.text=i.text,this._remainingText=i.text.trim()}get remainingText(){return this._remainingText}get hasMoreText(){return this._remainingText.length>0}async measureNextPage(){if(!this._remainingText)return null;const i=this.layout,t=i.fontSize*1.4,n=`${i.fontSize}px ${i.fontFamily??"sans-serif"}`,a=document.createElement("canvas");a.width=i.width,a.height=i.height;const s=a.getContext("2d");if(!s)return console.error("TxTextPage: Could not get 2D rendering context for measurement."),null;s.font=n;const o=[];let h=this._remainingText,f=i.startY;for(;h.length>0&&f<i.height;){const l=i.getLineLayout(f,t);if(l===null)break;const{width:u,xOffset:w}=l,_=h.split(/\s+/).filter(A=>A.length>0);if(_.length===0){h="";break}let g="",v=0;for(;v<_.length;v++){const A=g.length===0?_[v]:g+" "+_[v];if(s.measureText(A).width>u){g.length===0&&(g=_[v],v++);break}g=A}g.length>0&&o.push({text:g,width:u,xOffset:w,yOffset:Math.round(f),lineHeight:Math.round(t)}),f+=t;const k=_.slice(v);if(k.length>0){const A=k[0],T=_.slice(0,v),$=T.join(" "),D=h.indexOf(A,$.length>0?h.indexOf(T[T.length-1])+T[T.length-1].length:0);D!==-1?h=h.substring(D):h=k.join(" ")}else h=""}return o.length===0&&this._remainingText.length>0?(this._remainingText=h,null):(this._remainingText=h,new PageData(o,i))}async rasterizeNextPage(){const i=await this.measureNextPage();return i&&await i.rasterize(),i}}exports.AsyncQueue=AsyncQueue,exports.BrilliantMsg=BrilliantMsg,exports.CircularTextLayout=CircularTextLayout,exports.ClickType=ClickType,exports.IMUData=IMUData,exports.PageData=PageData,exports.RectangularTextLayout=RectangularTextLayout,exports.RxAudio=RxAudio,exports.RxAudioBitDepth=RxAudioBitDepth,exports.RxAudioSampleRate=RxAudioSampleRate,exports.RxAutoExpResult=RxAutoExpResult,exports.RxClick=RxClick,exports.RxIMU=RxIMU,exports.RxMeteringData=RxMeteringData,exports.RxPhoto=RxPhoto,exports.RxTap=RxTap,exports.StdLua=StdLua,exports.TxAutoExpSettings=TxAutoExpSettings,exports.TxCaptureSettings=TxCaptureSettings,exports.TxCode=TxCode,exports.TxImageSpriteBlock=TxImageSpriteBlock,exports.TxManualExpSettings=TxManualExpSettings,exports.TxPlainText=TxPlainText,exports.TxSprite=TxSprite,exports.TxSpriteCoords=TxSpriteCoords,exports.TxTextPage=TxTextPage,exports.TxTextSpriteBlock=TxTextSpriteBlock,Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"})});