tasmota-esp-web-tools 9.0.1 → 9.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/flash.js +9 -10
- package/dist/web/install-button.js +1 -1
- package/dist/web/{install-dialog-DKwe1AGe.js → install-dialog-Xo7JovVA.js} +1 -1
- package/js/modules/install-button.js +1 -1
- package/js/modules/{install-dialog-DKwe1AGe.js → install-dialog-Xo7JovVA.js} +1 -1
- package/package.json +2 -2
- package/src/flash.ts +11 -12
package/dist/flash.js
CHANGED
|
@@ -2,18 +2,13 @@ import { ESPLoader } from "tasmota-webserial-esptool";
|
|
|
2
2
|
import { getChipFamilyName } from "./util/chip-family-name";
|
|
3
3
|
import { sleep } from "./util/sleep";
|
|
4
4
|
/**
|
|
5
|
-
* Check if a serial port is an ESP32-S2 Native USB device
|
|
5
|
+
* Check if a serial port is an ESP32-S2 Native USB device in TinyUSB CDC mode
|
|
6
6
|
* VID 0x303a = Espressif
|
|
7
|
-
* PID 0x0002 = ESP32-S2 TinyUSB CDC
|
|
8
|
-
* PID 0x1001 = ESP32-S2 ROM Bootloader (before flash)
|
|
9
|
-
*
|
|
10
|
-
* When user connects to ROM bootloader (0x1001), the device will
|
|
11
|
-
* switch to TinyUSB CDC (0x0002) after flashing, requiring port reselection.
|
|
7
|
+
* PID 0x0002 = ESP32-S2 TinyUSB CDC
|
|
12
8
|
*/
|
|
13
9
|
const isESP32S2NativeUSB = (port) => {
|
|
14
10
|
const info = port.getInfo();
|
|
15
|
-
return
|
|
16
|
-
(info.usbProductId === 0x0002 || info.usbProductId === 0x1001));
|
|
11
|
+
return info.usbVendorId === 0x303a && info.usbProductId === 0x0002;
|
|
17
12
|
};
|
|
18
13
|
export const flash = async (onEvent, port, logger, manifestPath, eraseFirst, firmwareBuffer, baudRate) => {
|
|
19
14
|
let manifest;
|
|
@@ -68,7 +63,11 @@ export const flash = async (onEvent, port, logger, manifestPath, eraseFirst, fir
|
|
|
68
63
|
catch (err) {
|
|
69
64
|
logger.error(err);
|
|
70
65
|
// Check if this is an ESP32-S2 Native USB reconnect situation
|
|
71
|
-
|
|
66
|
+
// This happens when:
|
|
67
|
+
// 1. ESP32-S2 in TinyUSB CDC mode was reset to bootloader
|
|
68
|
+
// 2. ESP32-S2 disconnected during initialization
|
|
69
|
+
if (isS2NativeUSB &&
|
|
70
|
+
(esp32s2ReconnectRequired || String(err).includes("reconnect required"))) {
|
|
72
71
|
cleanup();
|
|
73
72
|
// Close the old port if still accessible
|
|
74
73
|
try {
|
|
@@ -87,7 +86,7 @@ export const flash = async (onEvent, port, logger, manifestPath, eraseFirst, fir
|
|
|
87
86
|
// Fire reconnect event to trigger port reselection dialog
|
|
88
87
|
fireStateEvent({
|
|
89
88
|
state: "esp32_s2_usb_reconnect" /* FlashStateType.ESP32_S2_USB_RECONNECT */,
|
|
90
|
-
message: "ESP32-S2
|
|
89
|
+
message: "ESP32-S2 USB port changed - please select the new port",
|
|
91
90
|
details: { oldPort: port },
|
|
92
91
|
});
|
|
93
92
|
return;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const e=async t=>{let n;import("./install-dialog-
|
|
1
|
+
const e=async t=>{let n;import("./install-dialog-Xo7JovVA.js");try{n=await navigator.serial.requestPort()}catch(n){return"NotFoundError"===n.name?void import("./index-BK6drzlv.js").then(n=>n.openNoPortPickedDialog(()=>e(t))):void alert(`Error: ${n.message}`)}if(!n)return;try{await n.open({baudRate:115200})}catch(e){return void alert(e.message)}const o=document.createElement("ewt-install-dialog");o.port=n,o.manifestPath=t.manifest||t.getAttribute("manifest"),o.overrides=t.overrides,o.firmwareFile=t.firmwareFile;const r=t.getAttribute("baud-rate");if(r){const e=parseInt(r,10);isNaN(e)||(o.baudRate=e)}else void 0!==t.baudRate&&(o.baudRate=t.baudRate);o.addEventListener("closed",()=>{n.close()},{once:!0}),document.body.appendChild(o)};class t extends HTMLElement{connectedCallback(){if(this.renderRoot)return;if(this.renderRoot=this.attachShadow({mode:"open"}),!t.isSupported||!t.isAllowed)return this.toggleAttribute("install-unsupported",!0),void(this.renderRoot.innerHTML=t.isAllowed?"<slot name='unsupported'>Your browser does not support installing things on ESP devices. Use Google Chrome or Microsoft Edge.</slot>":"<slot name='not-allowed'>You can only install ESP devices on HTTPS websites or on the localhost.</slot>");this.toggleAttribute("install-supported",!0);const n=document.createElement("slot");n.addEventListener("click",async t=>{t.preventDefault(),e(this)}),n.name="activate";const o=document.createElement("button");if(o.innerText="CONNECT",n.append(o),"adoptedStyleSheets"in Document.prototype&&"replaceSync"in CSSStyleSheet.prototype){const e=new CSSStyleSheet;e.replaceSync(t.style),this.renderRoot.adoptedStyleSheets=[e]}else{const e=document.createElement("style");e.innerText=t.style,this.renderRoot.append(e)}this.renderRoot.append(n)}}t.isSupported="serial"in navigator,t.isAllowed=window.isSecureContext,t.style='\n button {\n position: relative;\n cursor: pointer;\n font-size: 14px;\n padding: 8px 28px;\n color: var(--esp-tools-button-text-color, #fff);\n background-color: var(--esp-tools-button-color, #03a9f4);\n border: none;\n border-radius: 4px;\n box-shadow: 0 2px 2px 0 rgba(0,0,0,.14), 0 3px 1px -2px rgba(0,0,0,.12), 0 1px 5px 0 rgba(0,0,0,.2);\n }\n button::before {\n content: " ";\n position: absolute;\n top: 0;\n bottom: 0;\n left: 0;\n right: 0;\n opacity: 0.2;\n border-radius: 4px;\n }\n button:hover {\n box-shadow: 0 4px 8px 0 rgba(0,0,0,.14), 0 1px 7px 0 rgba(0,0,0,.12), 0 3px 1px -1px rgba(0,0,0,.2);\n }\n button:hover::before {\n background-color: rgba(255,255,255,.8);\n }\n button:focus {\n outline: none;\n }\n button:focus::before {\n background-color: white;\n }\n button:active::before {\n background-color: grey;\n }\n :host([active]) button {\n color: rgba(0, 0, 0, 0.38);\n background-color: rgba(0, 0, 0, 0.12);\n box-shadow: none;\n cursor: unset;\n pointer-events: none;\n }\n improv-wifi-launch-button {\n display: block;\n margin-top: 16px;\n }\n .hidden {\n display: none;\n }',customElements.define("esp-web-install-button",t);
|
|
@@ -414,7 +414,7 @@ import{l as e,o as t,_ as i,n,B as o,i as r,a,t as d,e as s,b as l,R as c,x as h
|
|
|
414
414
|
d="M6,4H18V5H21V7H18V9H21V11H18V13H21V15H18V17H21V19H18V20H6V19H3V17H6V15H3V13H6V11H3V9H6V7H3V5H6V4M11,15V18H12V15H11M13,15V18H14V15H13M15,15V18H16V15H15Z"
|
|
415
415
|
/>
|
|
416
416
|
</svg>
|
|
417
|
-
`,xi=["I".charCodeAt(0),"M".charCodeAt(0),"P".charCodeAt(0),"R".charCodeAt(0),"O".charCodeAt(0),"V".charCodeAt(0),1];var vi,yi;!function(e){e[e.CURRENT_STATE=1]="CURRENT_STATE",e[e.ERROR_STATE=2]="ERROR_STATE",e[e.RPC=3]="RPC",e[e.RPC_RESULT=4]="RPC_RESULT"}(vi||(vi={})),function(e){e[e.READY=2]="READY",e[e.PROVISIONING=3]="PROVISIONING",e[e.PROVISIONED=4]="PROVISIONED"}(yi||(yi={}));const wi={0:"NO_ERROR",1:"INVALID_RPC_PACKET",2:"UNKNOWN_RPC_COMMAND",3:"UNABLE_TO_CONNECT",254:"TIMEOUT",255:"UNKNOWN_ERROR"};class ki extends Error{constructor(){super("Port is not ready")}}const Ei=e=>"["+e.map(e=>((e,t=2)=>{let i=e.toString(16).toUpperCase();return i.startsWith("-")?"-0x"+i.substring(1).padStart(t,"0"):"0x"+i.padStart(t,"0")})(e)).join(", ")+"]";class Ii extends EventTarget{constructor(e,t){if(super(),this.port=e,this.logger=t,this.error=0,null===e.readable)throw new Error("Port is not readable");if(null===e.writable)throw new Error("Port is not writable")}async initialize(e=1e3){var t;if(this.logger.log("Initializing Improv Serial"),this._processInput(),await(t=1e3,new Promise(e=>setTimeout(e,t))),void 0===this._reader)throw new ki;try{await new Promise(async(t,i)=>{setTimeout(()=>i(new Error("Improv Wi-Fi Serial not detected")),e),await this.requestCurrentState(),t(void 0)}),await this.requestInfo()}catch(e){throw await this.close(),e}return this.info}async close(){this._reader&&await new Promise(e=>{this._reader.cancel(),this.addEventListener("disconnect",e,{once:!0})})}async requestCurrentState(){let e;try{await new Promise(async(t,i)=>{this.addEventListener("state-changed",t,{once:!0});e=this._sendRPCWithResponse(2,[]),e.catch(e=>{this.removeEventListener("state-changed",t),i(e)})})}catch(e){throw this._rpcFeedback=void 0,new Error(`Error fetching current state: ${e}`)}if(this.state!==yi.PROVISIONED)return void(this._rpcFeedback=void 0);const t=await e;this.nextUrl=t[0]}async requestInfo(e){const t=await this._sendRPCWithResponse(3,[],e);this.info={firmware:t[0],version:t[1],name:t[3],chipFamily:t[2]}}async provision(e,t,i){const n=new TextEncoder,o=n.encode(e),r=n.encode(t),a=[o.length,...o,r.length,...r],d=await this._sendRPCWithResponse(1,a,i);this.nextUrl=d[0]}async scan(){const e=(await this._sendRPCWithMultipleResponses(4,[])).map(([e,t,i])=>({name:e,rssi:parseInt(t),secured:"YES"===i}));return e.sort((e,t)=>e.name.toLocaleLowerCase().localeCompare(t.name.toLocaleLowerCase())),e}_sendRPC(e,t){this.writePacketToStream(vi.RPC,[e,t.length,...t])}async _sendRPCWithResponse(e,t,i){if(this._rpcFeedback)throw new Error("Only 1 RPC command that requires feedback can be active");return await this._awaitRPCResultWithTimeout(new Promise((i,n)=>{this._rpcFeedback={command:e,resolve:i,reject:n},this._sendRPC(e,t)}),i)}async _sendRPCWithMultipleResponses(e,t,i){if(this._rpcFeedback)throw new Error("Only 1 RPC command that requires feedback can be active");return await this._awaitRPCResultWithTimeout(new Promise((i,n)=>{this._rpcFeedback={command:e,resolve:i,reject:n,receivedData:[]},this._sendRPC(e,t)}),i)}async _awaitRPCResultWithTimeout(e,t){return t?await new Promise((i,n)=>{const o=setTimeout(()=>this._setError(254),t);e.finally(()=>clearTimeout(o)),e.then(i,n)}):await e}async _processInput(){this.logger.debug("Starting read loop"),this._reader=this.port.readable.getReader();try{let e,t=[],i=0;for(;;){const{value:n,done:o}=await this._reader.read();if(o)break;if(n&&0!==n.length)for(const o of n){if(!1===e){10===o&&(e=void 0);continue}if(!0===e){t.push(o),t.length===i&&(this._handleIncomingPacket(t),e=void 0,t=[]);continue}if(10===o){t=[];continue}if(t.push(o),9!==t.length)continue;if(e="IMPROV"===String.fromCharCode(...t.slice(0,6)),!e){t=[];continue}i=9+t[8]+1}}}catch(e){this.logger.error("Error while reading serial port",e)}finally{this._reader.releaseLock(),this._reader=void 0}this.logger.debug("Finished read loop"),this.dispatchEvent(new Event("disconnect"))}_handleIncomingPacket(e){const t=e.slice(6),i=t[0],n=t[1],o=t[2],r=t.slice(3,3+o);if(this.logger.debug("PROCESS",{version:i,packetType:n,packetLength:o,data:Ei(r)}),1!==i)return void this.logger.error("Received unsupported version",i);let a=t[3+o],d=0;for(let t=0;t<e.length-1;t++)d+=e[t];if(d&=255,d===a)if(n===vi.CURRENT_STATE)this.state=r[0],this.dispatchEvent(new CustomEvent("state-changed",{detail:this.state}));else if(n===vi.ERROR_STATE)this._setError(r[0]);else if(n===vi.RPC_RESULT){if(!this._rpcFeedback)return void this.logger.error("Received result while not waiting for one");const e=r[0];if(e!==this._rpcFeedback.command)return void this.logger.error(`Received result for command ${e} but expected ${this._rpcFeedback.command}`);const t=[],i=r[1];let n=2;for(;n<2+i;)t.push(String.fromCodePoint(...r.slice(n+1,n+r[n]+1))),n+=r[n]+1;"receivedData"in this._rpcFeedback?t.length>0?this._rpcFeedback.receivedData.push(t):(this._rpcFeedback.resolve(this._rpcFeedback.receivedData),this._rpcFeedback=void 0):(this._rpcFeedback.resolve(t),this._rpcFeedback=void 0)}else this.logger.error("Unable to handle packet",t);else this.logger.error(`Received invalid checksum ${a}. Expected ${d}`)}async writePacketToStream(e,t){const i=new Uint8Array([...xi,e,t.length,...t,0,0]);i[i.length-2]=255&i.reduce((e,t)=>e+t,0),i[i.length-1]=10,this.logger.debug("Writing to stream:",Ei(new Array(...i)));const n=this.port.writable.getWriter();await n.write(i);try{n.releaseLock()}catch(e){console.error("Ignoring release lock error",e)}}_setError(e){this.error=e,e>0&&this._rpcFeedback&&(this._rpcFeedback.reject(wi[e]||`UNKNOWN_ERROR (${e})`),this._rpcFeedback=void 0),this.dispatchEvent(new CustomEvent("error-changed",{detail:this.error}))}}const Si=e=>{let t=[192];for(const i of e)219==i?t=t.concat([219,221]):192==i?t=t.concat([219,220]):t.push(i);return t.push(192),t},Ci=e=>{const t=[];for(let i=0;i<e.length;i++){const n=e.charCodeAt(i);n<=255&&t.push(n)}return t},Ri=e=>"["+e.map(e=>Ti(e)).join(", ")+"]",Ti=(e,t=2)=>{const i=e.toString(16).toUpperCase();return i.startsWith("-")?"-0x"+i.substring(1).padStart(t,"0"):"0x"+i.padStart(t,"0")},Ai=e=>new Promise(t=>setTimeout(t,e)),Oi={18:"256KB",19:"512KB",20:"1MB",21:"2MB",22:"4MB",23:"8MB",24:"16MB",25:"32MB",26:"64MB",27:"128MB",28:"256MB",32:"64MB",33:"128MB",34:"256MB",50:"256KB",51:"512KB",52:"1MB",53:"2MB",54:"4MB",55:"8MB",56:"16MB",57:"32MB",58:"64MB"},Fi=115200,Li=1343410176,Bi=Ci(" UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU"),zi=33382,Di=50,$i=12882,Ni=12883,Pi=12994,Mi=12995,Ui=12997,Hi=12998,Vi=207969,Wi=12914,Xi=12916,qi=12917,Yi=12928,Gi=12849,ji={5:{name:"ESP32-C3",family:Mi},9:{name:"ESP32-S3",family:Ni},12:{name:"ESP32-C2",family:Pi},13:{name:"ESP32-C6",family:Hi},16:{name:"ESP32-H2",family:Wi},18:{name:"ESP32-P4",family:Yi},20:{name:"ESP32-C61",family:Vi},23:{name:"ESP32-C5",family:Ui},25:{name:"ESP32-H21",family:qi},28:{name:"ESP32-H4",family:Xi},32:{name:"ESP32-S31",family:Gi}},Ki={4293968129:{name:"ESP8266",family:zi},15736195:{name:"ESP32",family:Di},1990:{name:"ESP32-S2",family:$i}},Zi=3e3,Qi=15e4,Ji=100,en=(e,t)=>{const i=Math.floor(e*(t/486));return i<Zi?Zi:i},tn=e=>{switch(e){case Di:return{regBase:1072963584,baseFuse:1073061888,macFuse:1073061888,usrOffs:28,usr1Offs:32,usr2Offs:36,mosiDlenOffs:40,misoDlenOffs:44,w0Offs:128,uartDateReg:1610612856,flashOffs:4096};case $i:return{regBase:1061167104,baseFuse:1061265408,macFuse:1061265476,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612856,flashOffs:4096};case Ni:return{regBase:1610620928,usrOffs:24,baseFuse:1610641408,macFuse:1610641476,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612864,flashOffs:0};case zi:return{regBase:1610613248,usrOffs:28,baseFuse:1072693328,macFuse:1072693328,usr1Offs:32,usr2Offs:36,mosiDlenOffs:-1,misoDlenOffs:-1,w0Offs:64,uartDateReg:1610612856,flashOffs:0};case Pi:case Mi:return{regBase:1610620928,baseFuse:1610647552,macFuse:1610647620,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case Ui:return{regBase:1610625024,baseFuse:1611352064,macFuse:1611352132,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:8192};case Hi:return{regBase:1610625024,baseFuse:1611335680,macFuse:1611335748,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case Vi:return{regBase:1610625024,baseFuse:1611352064,macFuse:1611352132,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case Wi:return{regBase:1610625024,baseFuse:1611335680,macFuse:1611335748,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case Xi:return{regBase:1611239424,baseFuse:1611339776,macFuse:1611339844,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610686588,flashOffs:8192};case qi:return{regBase:1610625024,baseFuse:1611350016,macFuse:1611350084,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case Yi:return{regBase:1342754816,baseFuse:Li,macFuse:1343410244,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1343004812,flashOffs:8192};case Gi:return{regBase:542113792,baseFuse:544296960,macFuse:544297028,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:540582028,flashOffs:8192};default:return{regBase:-1,baseFuse:-1,macFuse:-1,usrOffs:-1,usr1Offs:-1,usr2Offs:-1,mosiDlenOffs:-1,misoDlenOffs:-1,w0Offs:-1,uartDateReg:-1,flashOffs:-1}}};class nn extends Error{constructor(e){super(e),this.name="SlipReadError"}}const on=async(e,t)=>{let i;return e==Xi||e==qi||e==Gi?null:(e==Di?i=await import("./esp32-CijhsJH1.js"):e==$i?i=await import("./esp32s2-IiDBtXxo.js"):e==Ni?i=await import("./esp32s3-6yv5yxum.js"):e==zi?i=await import("./esp8266-CUwxJpGa.js"):e==Pi?i=await import("./esp32c2-C17SM4gO.js"):e==Mi?i=await import("./esp32c3-DxRGijbg.js"):e==Ui?i=await import("./esp32c5-3mDOIGa4.js"):e==Hi?i=await import("./esp32c6-h6U0SQTm.js"):e==Vi?i=await import("./esp32c61-BKtexhPZ.js"):e==Wi?i=await import("./esp32h2-RtuWSEmP.js"):e==Yi&&(i=null!=t&&t>=300?await import("./esp32p4r3-CpHBYEwI.js"):await import("./esp32p4-5nkIjxqJ.js")),{...i,text:Ci(atob(i.text)),data:Ci(atob(i.data))})};function rn(e){let t=e.length;for(;--t>=0;)e[t]=0}const an=256,dn=286,sn=30,ln=15,cn=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]),hn=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]),mn=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),pn=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),un=new Array(576);rn(un);const fn=new Array(60);rn(fn);const gn=new Array(512);rn(gn);const bn=new Array(256);rn(bn);const _n=new Array(29);rn(_n);const xn=new Array(sn);function vn(e,t,i,n,o){this.static_tree=e,this.extra_bits=t,this.extra_base=i,this.elems=n,this.max_length=o,this.has_stree=e&&e.length}let yn,wn,kn;function En(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}rn(xn);const In=e=>e<256?gn[e]:gn[256+(e>>>7)],Sn=(e,t)=>{e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255},Cn=(e,t,i)=>{e.bi_valid>16-i?(e.bi_buf|=t<<e.bi_valid&65535,Sn(e,e.bi_buf),e.bi_buf=t>>16-e.bi_valid,e.bi_valid+=i-16):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=i)},Rn=(e,t,i)=>{Cn(e,i[2*t],i[2*t+1])},Tn=(e,t)=>{let i=0;do{i|=1&e,e>>>=1,i<<=1}while(--t>0);return i>>>1},An=(e,t,i)=>{const n=new Array(16);let o,r,a=0;for(o=1;o<=ln;o++)a=a+i[o-1]<<1,n[o]=a;for(r=0;r<=t;r++){let t=e[2*r+1];0!==t&&(e[2*r]=Tn(n[t]++,t))}},On=e=>{let t;for(t=0;t<dn;t++)e.dyn_ltree[2*t]=0;for(t=0;t<sn;t++)e.dyn_dtree[2*t]=0;for(t=0;t<19;t++)e.bl_tree[2*t]=0;e.dyn_ltree[512]=1,e.opt_len=e.static_len=0,e.sym_next=e.matches=0},Fn=e=>{e.bi_valid>8?Sn(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0},Ln=(e,t,i,n)=>{const o=2*t,r=2*i;return e[o]<e[r]||e[o]===e[r]&&n[t]<=n[i]},Bn=(e,t,i)=>{const n=e.heap[i];let o=i<<1;for(;o<=e.heap_len&&(o<e.heap_len&&Ln(t,e.heap[o+1],e.heap[o],e.depth)&&o++,!Ln(t,n,e.heap[o],e.depth));)e.heap[i]=e.heap[o],i=o,o<<=1;e.heap[i]=n},zn=(e,t,i)=>{let n,o,r,a,d=0;if(0!==e.sym_next)do{n=255&e.pending_buf[e.sym_buf+d++],n+=(255&e.pending_buf[e.sym_buf+d++])<<8,o=e.pending_buf[e.sym_buf+d++],0===n?Rn(e,o,t):(r=bn[o],Rn(e,r+an+1,t),a=cn[r],0!==a&&(o-=_n[r],Cn(e,o,a)),n--,r=In(n),Rn(e,r,i),a=hn[r],0!==a&&(n-=xn[r],Cn(e,n,a)))}while(d<e.sym_next);Rn(e,256,t)},Dn=(e,t)=>{const i=t.dyn_tree,n=t.stat_desc.static_tree,o=t.stat_desc.has_stree,r=t.stat_desc.elems;let a,d,s,l=-1;for(e.heap_len=0,e.heap_max=573,a=0;a<r;a++)0!==i[2*a]?(e.heap[++e.heap_len]=l=a,e.depth[a]=0):i[2*a+1]=0;for(;e.heap_len<2;)s=e.heap[++e.heap_len]=l<2?++l:0,i[2*s]=1,e.depth[s]=0,e.opt_len--,o&&(e.static_len-=n[2*s+1]);for(t.max_code=l,a=e.heap_len>>1;a>=1;a--)Bn(e,i,a);s=r;do{a=e.heap[1],e.heap[1]=e.heap[e.heap_len--],Bn(e,i,1),d=e.heap[1],e.heap[--e.heap_max]=a,e.heap[--e.heap_max]=d,i[2*s]=i[2*a]+i[2*d],e.depth[s]=(e.depth[a]>=e.depth[d]?e.depth[a]:e.depth[d])+1,i[2*a+1]=i[2*d+1]=s,e.heap[1]=s++,Bn(e,i,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],((e,t)=>{const i=t.dyn_tree,n=t.max_code,o=t.stat_desc.static_tree,r=t.stat_desc.has_stree,a=t.stat_desc.extra_bits,d=t.stat_desc.extra_base,s=t.stat_desc.max_length;let l,c,h,m,p,u,f=0;for(m=0;m<=ln;m++)e.bl_count[m]=0;for(i[2*e.heap[e.heap_max]+1]=0,l=e.heap_max+1;l<573;l++)c=e.heap[l],m=i[2*i[2*c+1]+1]+1,m>s&&(m=s,f++),i[2*c+1]=m,c>n||(e.bl_count[m]++,p=0,c>=d&&(p=a[c-d]),u=i[2*c],e.opt_len+=u*(m+p),r&&(e.static_len+=u*(o[2*c+1]+p)));if(0!==f){do{for(m=s-1;0===e.bl_count[m];)m--;e.bl_count[m]--,e.bl_count[m+1]+=2,e.bl_count[s]--,f-=2}while(f>0);for(m=s;0!==m;m--)for(c=e.bl_count[m];0!==c;)h=e.heap[--l],h>n||(i[2*h+1]!==m&&(e.opt_len+=(m-i[2*h+1])*i[2*h],i[2*h+1]=m),c--)}})(e,t),An(i,l,e.bl_count)},$n=(e,t,i)=>{let n,o,r=-1,a=t[1],d=0,s=7,l=4;for(0===a&&(s=138,l=3),t[2*(i+1)+1]=65535,n=0;n<=i;n++)o=a,a=t[2*(n+1)+1],++d<s&&o===a||(d<l?e.bl_tree[2*o]+=d:0!==o?(o!==r&&e.bl_tree[2*o]++,e.bl_tree[32]++):d<=10?e.bl_tree[34]++:e.bl_tree[36]++,d=0,r=o,0===a?(s=138,l=3):o===a?(s=6,l=3):(s=7,l=4))},Nn=(e,t,i)=>{let n,o,r=-1,a=t[1],d=0,s=7,l=4;for(0===a&&(s=138,l=3),n=0;n<=i;n++)if(o=a,a=t[2*(n+1)+1],!(++d<s&&o===a)){if(d<l)do{Rn(e,o,e.bl_tree)}while(0!==--d);else 0!==o?(o!==r&&(Rn(e,o,e.bl_tree),d--),Rn(e,16,e.bl_tree),Cn(e,d-3,2)):d<=10?(Rn(e,17,e.bl_tree),Cn(e,d-3,3)):(Rn(e,18,e.bl_tree),Cn(e,d-11,7));d=0,r=o,0===a?(s=138,l=3):o===a?(s=6,l=3):(s=7,l=4)}};let Pn=!1;const Mn=(e,t,i,n)=>{Cn(e,0+(n?1:0),3),Fn(e),Sn(e,i),Sn(e,~i),i&&e.pending_buf.set(e.window.subarray(t,t+i),e.pending),e.pending+=i};var Un=e=>{Pn||((()=>{let e,t,i,n,o;const r=new Array(16);for(i=0,n=0;n<28;n++)for(_n[n]=i,e=0;e<1<<cn[n];e++)bn[i++]=n;for(bn[i-1]=n,o=0,n=0;n<16;n++)for(xn[n]=o,e=0;e<1<<hn[n];e++)gn[o++]=n;for(o>>=7;n<sn;n++)for(xn[n]=o<<7,e=0;e<1<<hn[n]-7;e++)gn[256+o++]=n;for(t=0;t<=ln;t++)r[t]=0;for(e=0;e<=143;)un[2*e+1]=8,e++,r[8]++;for(;e<=255;)un[2*e+1]=9,e++,r[9]++;for(;e<=279;)un[2*e+1]=7,e++,r[7]++;for(;e<=287;)un[2*e+1]=8,e++,r[8]++;for(An(un,287,r),e=0;e<sn;e++)fn[2*e+1]=5,fn[2*e]=Tn(e,5);yn=new vn(un,cn,257,dn,ln),wn=new vn(fn,hn,0,sn,ln),kn=new vn(new Array(0),mn,0,19,7)})(),Pn=!0),e.l_desc=new En(e.dyn_ltree,yn),e.d_desc=new En(e.dyn_dtree,wn),e.bl_desc=new En(e.bl_tree,kn),e.bi_buf=0,e.bi_valid=0,On(e)},Hn=(e,t,i,n)=>{let o,r,a=0;e.level>0?(2===e.strm.data_type&&(e.strm.data_type=(e=>{let t,i=4093624447;for(t=0;t<=31;t++,i>>>=1)if(1&i&&0!==e.dyn_ltree[2*t])return 0;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return 1;for(t=32;t<an;t++)if(0!==e.dyn_ltree[2*t])return 1;return 0})(e)),Dn(e,e.l_desc),Dn(e,e.d_desc),a=(e=>{let t;for($n(e,e.dyn_ltree,e.l_desc.max_code),$n(e,e.dyn_dtree,e.d_desc.max_code),Dn(e,e.bl_desc),t=18;t>=3&&0===e.bl_tree[2*pn[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t})(e),o=e.opt_len+3+7>>>3,r=e.static_len+3+7>>>3,r<=o&&(o=r)):o=r=i+5,i+4<=o&&-1!==t?Mn(e,t,i,n):4===e.strategy||r===o?(Cn(e,2+(n?1:0),3),zn(e,un,fn)):(Cn(e,4+(n?1:0),3),((e,t,i,n)=>{let o;for(Cn(e,t-257,5),Cn(e,i-1,5),Cn(e,n-4,4),o=0;o<n;o++)Cn(e,e.bl_tree[2*pn[o]+1],3);Nn(e,e.dyn_ltree,t-1),Nn(e,e.dyn_dtree,i-1)})(e,e.l_desc.max_code+1,e.d_desc.max_code+1,a+1),zn(e,e.dyn_ltree,e.dyn_dtree)),On(e),n&&Fn(e)},Vn=(e,t,i)=>(e.pending_buf[e.sym_buf+e.sym_next++]=t,e.pending_buf[e.sym_buf+e.sym_next++]=t>>8,e.pending_buf[e.sym_buf+e.sym_next++]=i,0===t?e.dyn_ltree[2*i]++:(e.matches++,t--,e.dyn_ltree[2*(bn[i]+an+1)]++,e.dyn_dtree[2*In(t)]++),e.sym_next===e.sym_end),Wn=e=>{Cn(e,2,3),Rn(e,256,un),(e=>{16===e.bi_valid?(Sn(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)})(e)},Xn={_tr_init:Un,_tr_stored_block:Mn,_tr_flush_block:Hn,_tr_tally:Vn,_tr_align:Wn};var qn=(e,t,i,n)=>{let o=65535&e,r=e>>>16&65535,a=0;for(;0!==i;){a=i>2e3?2e3:i,i-=a;do{o=o+t[n++]|0,r=r+o|0}while(--a);o%=65521,r%=65521}return o|r<<16};const Yn=new Uint32Array((()=>{let e,t=[];for(var i=0;i<256;i++){e=i;for(var n=0;n<8;n++)e=1&e?3988292384^e>>>1:e>>>1;t[i]=e}return t})());var Gn=(e,t,i,n)=>{const o=Yn,r=n+i;e^=-1;for(let i=n;i<r;i++)e=e>>>8^o[255&(e^t[i])];return-1^e},jn={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"},Kn={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_OK:0,Z_STREAM_END:1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,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:Zn,_tr_stored_block:Qn,_tr_flush_block:Jn,_tr_tally:eo,_tr_align:to}=Xn,{Z_NO_FLUSH:io,Z_PARTIAL_FLUSH:no,Z_FULL_FLUSH:oo,Z_FINISH:ro,Z_BLOCK:ao,Z_OK:so,Z_STREAM_END:lo,Z_STREAM_ERROR:co,Z_DATA_ERROR:ho,Z_BUF_ERROR:mo,Z_DEFAULT_COMPRESSION:po,Z_FILTERED:uo,Z_HUFFMAN_ONLY:fo,Z_RLE:go,Z_FIXED:bo,Z_DEFAULT_STRATEGY:_o,Z_UNKNOWN:xo,Z_DEFLATED:vo}=Kn,yo=258,wo=262,ko=42,Eo=113,Io=666,So=(e,t)=>(e.msg=jn[t],t),Co=e=>2*e-(e>4?9:0),Ro=e=>{let t=e.length;for(;--t>=0;)e[t]=0},To=e=>{let t,i,n,o=e.w_size;t=e.hash_size,n=t;do{i=e.head[--n],e.head[n]=i>=o?i-o:0}while(--t);t=o,n=t;do{i=e.prev[--n],e.prev[n]=i>=o?i-o:0}while(--t)};let Ao=(e,t,i)=>(t<<e.hash_shift^i)&e.hash_mask;const Oo=e=>{const t=e.state;let i=t.pending;i>e.avail_out&&(i=e.avail_out),0!==i&&(e.output.set(t.pending_buf.subarray(t.pending_out,t.pending_out+i),e.next_out),e.next_out+=i,t.pending_out+=i,e.total_out+=i,e.avail_out-=i,t.pending-=i,0===t.pending&&(t.pending_out=0))},Fo=(e,t)=>{Jn(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,Oo(e.strm)},Lo=(e,t)=>{e.pending_buf[e.pending++]=t},Bo=(e,t)=>{e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t},zo=(e,t,i,n)=>{let o=e.avail_in;return o>n&&(o=n),0===o?0:(e.avail_in-=o,t.set(e.input.subarray(e.next_in,e.next_in+o),i),1===e.state.wrap?e.adler=qn(e.adler,t,o,i):2===e.state.wrap&&(e.adler=Gn(e.adler,t,o,i)),e.next_in+=o,e.total_in+=o,o)},Do=(e,t)=>{let i,n,o=e.max_chain_length,r=e.strstart,a=e.prev_length,d=e.nice_match;const s=e.strstart>e.w_size-wo?e.strstart-(e.w_size-wo):0,l=e.window,c=e.w_mask,h=e.prev,m=e.strstart+yo;let p=l[r+a-1],u=l[r+a];e.prev_length>=e.good_match&&(o>>=2),d>e.lookahead&&(d=e.lookahead);do{if(i=t,l[i+a]===u&&l[i+a-1]===p&&l[i]===l[r]&&l[++i]===l[r+1]){r+=2,i++;do{}while(l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&r<m);if(n=yo-(m-r),r=m-yo,n>a){if(e.match_start=t,a=n,n>=d)break;p=l[r+a-1],u=l[r+a]}}}while((t=h[t&c])>s&&0!==--o);return a<=e.lookahead?a:e.lookahead},$o=e=>{const t=e.w_size;let i,n,o;do{if(n=e.window_size-e.lookahead-e.strstart,e.strstart>=t+(t-wo)&&(e.window.set(e.window.subarray(t,t+t-n),0),e.match_start-=t,e.strstart-=t,e.block_start-=t,e.insert>e.strstart&&(e.insert=e.strstart),To(e),n+=t),0===e.strm.avail_in)break;if(i=zo(e.strm,e.window,e.strstart+e.lookahead,n),e.lookahead+=i,e.lookahead+e.insert>=3)for(o=e.strstart-e.insert,e.ins_h=e.window[o],e.ins_h=Ao(e,e.ins_h,e.window[o+1]);e.insert&&(e.ins_h=Ao(e,e.ins_h,e.window[o+3-1]),e.prev[o&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=o,o++,e.insert--,!(e.lookahead+e.insert<3)););}while(e.lookahead<wo&&0!==e.strm.avail_in)},No=(e,t)=>{let i,n,o,r=e.pending_buf_size-5>e.w_size?e.w_size:e.pending_buf_size-5,a=0,d=e.strm.avail_in;do{if(i=65535,o=e.bi_valid+42>>3,e.strm.avail_out<o)break;if(o=e.strm.avail_out-o,n=e.strstart-e.block_start,i>n+e.strm.avail_in&&(i=n+e.strm.avail_in),i>o&&(i=o),i<r&&(0===i&&t!==ro||t===io||i!==n+e.strm.avail_in))break;a=t===ro&&i===n+e.strm.avail_in?1:0,Qn(e,0,0,a),e.pending_buf[e.pending-4]=i,e.pending_buf[e.pending-3]=i>>8,e.pending_buf[e.pending-2]=~i,e.pending_buf[e.pending-1]=~i>>8,Oo(e.strm),n&&(n>i&&(n=i),e.strm.output.set(e.window.subarray(e.block_start,e.block_start+n),e.strm.next_out),e.strm.next_out+=n,e.strm.avail_out-=n,e.strm.total_out+=n,e.block_start+=n,i-=n),i&&(zo(e.strm,e.strm.output,e.strm.next_out,i),e.strm.next_out+=i,e.strm.avail_out-=i,e.strm.total_out+=i)}while(0===a);return d-=e.strm.avail_in,d&&(d>=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<=d&&(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-d,e.strm.next_in),e.strstart),e.strstart+=d,e.insert+=d>e.w_size-e.insert?e.w_size-e.insert:d),e.block_start=e.strstart),e.high_water<e.strstart&&(e.high_water=e.strstart),a?4:t!==io&&t!==ro&&0===e.strm.avail_in&&e.strstart===e.block_start?2:(o=e.window_size-e.strstart,e.strm.avail_in>o&&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++,o+=e.w_size,e.insert>e.strstart&&(e.insert=e.strstart)),o>e.strm.avail_in&&(o=e.strm.avail_in),o&&(zo(e.strm,e.window,e.strstart,o),e.strstart+=o,e.insert+=o>e.w_size-e.insert?e.w_size-e.insert:o),e.high_water<e.strstart&&(e.high_water=e.strstart),o=e.bi_valid+42>>3,o=e.pending_buf_size-o>65535?65535:e.pending_buf_size-o,r=o>e.w_size?e.w_size:o,n=e.strstart-e.block_start,(n>=r||(n||t===ro)&&t!==io&&0===e.strm.avail_in&&n<=o)&&(i=n>o?o:n,a=t===ro&&0===e.strm.avail_in&&i===n?1:0,Qn(e,e.block_start,i,a),e.block_start+=i,Oo(e.strm)),a?3:1)},Po=(e,t)=>{let i,n;for(;;){if(e.lookahead<wo){if($o(e),e.lookahead<wo&&t===io)return 1;if(0===e.lookahead)break}if(i=0,e.lookahead>=3&&(e.ins_h=Ao(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!==i&&e.strstart-i<=e.w_size-wo&&(e.match_length=Do(e,i)),e.match_length>=3)if(n=eo(e,e.strstart-e.match_start,e.match_length-3),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=3){e.match_length--;do{e.strstart++,e.ins_h=Ao(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart}while(0!==--e.match_length);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=Ao(e,e.ins_h,e.window[e.strstart+1]);else n=eo(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(n&&(Fo(e,!1),0===e.strm.avail_out))return 1}return e.insert=e.strstart<2?e.strstart:2,t===ro?(Fo(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(Fo(e,!1),0===e.strm.avail_out)?1:2},Mo=(e,t)=>{let i,n,o;for(;;){if(e.lookahead<wo){if($o(e),e.lookahead<wo&&t===io)return 1;if(0===e.lookahead)break}if(i=0,e.lookahead>=3&&(e.ins_h=Ao(e,e.ins_h,e.window[e.strstart+3-1]),i=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=2,0!==i&&e.prev_length<e.max_lazy_match&&e.strstart-i<=e.w_size-wo&&(e.match_length=Do(e,i),e.match_length<=5&&(e.strategy===uo||3===e.match_length&&e.strstart-e.match_start>4096)&&(e.match_length=2)),e.prev_length>=3&&e.match_length<=e.prev_length){o=e.strstart+e.lookahead-3,n=eo(e,e.strstart-1-e.prev_match,e.prev_length-3),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=o&&(e.ins_h=Ao(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart)}while(0!==--e.prev_length);if(e.match_available=0,e.match_length=2,e.strstart++,n&&(Fo(e,!1),0===e.strm.avail_out))return 1}else if(e.match_available){if(n=eo(e,0,e.window[e.strstart-1]),n&&Fo(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return 1}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(n=eo(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<2?e.strstart:2,t===ro?(Fo(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(Fo(e,!1),0===e.strm.avail_out)?1:2};function Uo(e,t,i,n,o){this.good_length=e,this.max_lazy=t,this.nice_length=i,this.max_chain=n,this.func=o}const Ho=[new Uo(0,0,0,0,No),new Uo(4,4,8,4,Po),new Uo(4,5,16,8,Po),new Uo(4,6,32,32,Po),new Uo(4,4,16,16,Mo),new Uo(8,16,32,32,Mo),new Uo(8,16,128,128,Mo),new Uo(8,32,128,256,Mo),new Uo(32,128,258,1024,Mo),new Uo(32,258,258,4096,Mo)];function Vo(){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=vo,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(1146),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),Ro(this.dyn_ltree),Ro(this.dyn_dtree),Ro(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),Ro(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),Ro(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 Wo=e=>{if(!e)return 1;const t=e.state;return!t||t.strm!==e||t.status!==ko&&57!==t.status&&69!==t.status&&73!==t.status&&91!==t.status&&103!==t.status&&t.status!==Eo&&t.status!==Io?1:0},Xo=e=>{if(Wo(e))return So(e,co);e.total_in=e.total_out=0,e.data_type=xo;const t=e.state;return t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=2===t.wrap?57:t.wrap?ko:Eo,e.adler=2===t.wrap?0:1,t.last_flush=-2,Zn(t),so},qo=e=>{const t=Xo(e);return t===so&&(e=>{e.window_size=2*e.w_size,Ro(e.head),e.max_lazy_match=Ho[e.level].max_lazy,e.good_match=Ho[e.level].good_length,e.nice_match=Ho[e.level].nice_length,e.max_chain_length=Ho[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=2,e.match_available=0,e.ins_h=0})(e.state),t},Yo=(e,t,i,n,o,r)=>{if(!e)return co;let a=1;if(t===po&&(t=6),n<0?(a=0,n=-n):n>15&&(a=2,n-=16),o<1||o>9||i!==vo||n<8||n>15||t<0||t>9||r<0||r>bo||8===n&&1!==a)return So(e,co);8===n&&(n=9);const d=new Vo;return e.state=d,d.strm=e,d.status=ko,d.wrap=a,d.gzhead=null,d.w_bits=n,d.w_size=1<<d.w_bits,d.w_mask=d.w_size-1,d.hash_bits=o+7,d.hash_size=1<<d.hash_bits,d.hash_mask=d.hash_size-1,d.hash_shift=~~((d.hash_bits+3-1)/3),d.window=new Uint8Array(2*d.w_size),d.head=new Uint16Array(d.hash_size),d.prev=new Uint16Array(d.w_size),d.lit_bufsize=1<<o+6,d.pending_buf_size=4*d.lit_bufsize,d.pending_buf=new Uint8Array(d.pending_buf_size),d.sym_buf=d.lit_bufsize,d.sym_end=3*(d.lit_bufsize-1),d.level=t,d.strategy=r,d.method=i,qo(e)};var Go=(e,t)=>{if(Wo(e)||t>ao||t<0)return e?So(e,co):co;const i=e.state;if(!e.output||0!==e.avail_in&&!e.input||i.status===Io&&t!==ro)return So(e,0===e.avail_out?mo:co);const n=i.last_flush;if(i.last_flush=t,0!==i.pending){if(Oo(e),0===e.avail_out)return i.last_flush=-1,so}else if(0===e.avail_in&&Co(t)<=Co(n)&&t!==ro)return So(e,mo);if(i.status===Io&&0!==e.avail_in)return So(e,mo);if(i.status===ko&&0===i.wrap&&(i.status=Eo),i.status===ko){let t=vo+(i.w_bits-8<<4)<<8,n=-1;if(n=i.strategy>=fo||i.level<2?0:i.level<6?1:6===i.level?2:3,t|=n<<6,0!==i.strstart&&(t|=32),t+=31-t%31,Bo(i,t),0!==i.strstart&&(Bo(i,e.adler>>>16),Bo(i,65535&e.adler)),e.adler=1,i.status=Eo,Oo(e),0!==i.pending)return i.last_flush=-1,so}if(57===i.status)if(e.adler=0,Lo(i,31),Lo(i,139),Lo(i,8),i.gzhead)Lo(i,(i.gzhead.text?1:0)+(i.gzhead.hcrc?2:0)+(i.gzhead.extra?4:0)+(i.gzhead.name?8:0)+(i.gzhead.comment?16:0)),Lo(i,255&i.gzhead.time),Lo(i,i.gzhead.time>>8&255),Lo(i,i.gzhead.time>>16&255),Lo(i,i.gzhead.time>>24&255),Lo(i,9===i.level?2:i.strategy>=fo||i.level<2?4:0),Lo(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(Lo(i,255&i.gzhead.extra.length),Lo(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(e.adler=Gn(e.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=69;else if(Lo(i,0),Lo(i,0),Lo(i,0),Lo(i,0),Lo(i,0),Lo(i,9===i.level?2:i.strategy>=fo||i.level<2?4:0),Lo(i,3),i.status=Eo,Oo(e),0!==i.pending)return i.last_flush=-1,so;if(69===i.status){if(i.gzhead.extra){let t=i.pending,n=(65535&i.gzhead.extra.length)-i.gzindex;for(;i.pending+n>i.pending_buf_size;){let o=i.pending_buf_size-i.pending;if(i.pending_buf.set(i.gzhead.extra.subarray(i.gzindex,i.gzindex+o),i.pending),i.pending=i.pending_buf_size,i.gzhead.hcrc&&i.pending>t&&(e.adler=Gn(e.adler,i.pending_buf,i.pending-t,t)),i.gzindex+=o,Oo(e),0!==i.pending)return i.last_flush=-1,so;t=0,n-=o}let o=new Uint8Array(i.gzhead.extra);i.pending_buf.set(o.subarray(i.gzindex,i.gzindex+n),i.pending),i.pending+=n,i.gzhead.hcrc&&i.pending>t&&(e.adler=Gn(e.adler,i.pending_buf,i.pending-t,t)),i.gzindex=0}i.status=73}if(73===i.status){if(i.gzhead.name){let t,n=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>n&&(e.adler=Gn(e.adler,i.pending_buf,i.pending-n,n)),Oo(e),0!==i.pending)return i.last_flush=-1,so;n=0}t=i.gzindex<i.gzhead.name.length?255&i.gzhead.name.charCodeAt(i.gzindex++):0,Lo(i,t)}while(0!==t);i.gzhead.hcrc&&i.pending>n&&(e.adler=Gn(e.adler,i.pending_buf,i.pending-n,n)),i.gzindex=0}i.status=91}if(91===i.status){if(i.gzhead.comment){let t,n=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>n&&(e.adler=Gn(e.adler,i.pending_buf,i.pending-n,n)),Oo(e),0!==i.pending)return i.last_flush=-1,so;n=0}t=i.gzindex<i.gzhead.comment.length?255&i.gzhead.comment.charCodeAt(i.gzindex++):0,Lo(i,t)}while(0!==t);i.gzhead.hcrc&&i.pending>n&&(e.adler=Gn(e.adler,i.pending_buf,i.pending-n,n))}i.status=103}if(103===i.status){if(i.gzhead.hcrc){if(i.pending+2>i.pending_buf_size&&(Oo(e),0!==i.pending))return i.last_flush=-1,so;Lo(i,255&e.adler),Lo(i,e.adler>>8&255),e.adler=0}if(i.status=Eo,Oo(e),0!==i.pending)return i.last_flush=-1,so}if(0!==e.avail_in||0!==i.lookahead||t!==io&&i.status!==Io){let n=0===i.level?No(i,t):i.strategy===fo?((e,t)=>{let i;for(;;){if(0===e.lookahead&&($o(e),0===e.lookahead)){if(t===io)return 1;break}if(e.match_length=0,i=eo(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,i&&(Fo(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===ro?(Fo(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(Fo(e,!1),0===e.strm.avail_out)?1:2})(i,t):i.strategy===go?((e,t)=>{let i,n,o,r;const a=e.window;for(;;){if(e.lookahead<=yo){if($o(e),e.lookahead<=yo&&t===io)return 1;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=3&&e.strstart>0&&(o=e.strstart-1,n=a[o],n===a[++o]&&n===a[++o]&&n===a[++o])){r=e.strstart+yo;do{}while(n===a[++o]&&n===a[++o]&&n===a[++o]&&n===a[++o]&&n===a[++o]&&n===a[++o]&&n===a[++o]&&n===a[++o]&&o<r);e.match_length=yo-(r-o),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=3?(i=eo(e,1,e.match_length-3),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(i=eo(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),i&&(Fo(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===ro?(Fo(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(Fo(e,!1),0===e.strm.avail_out)?1:2})(i,t):Ho[i.level].func(i,t);if(3!==n&&4!==n||(i.status=Io),1===n||3===n)return 0===e.avail_out&&(i.last_flush=-1),so;if(2===n&&(t===no?to(i):t!==ao&&(Qn(i,0,0,!1),t===oo&&(Ro(i.head),0===i.lookahead&&(i.strstart=0,i.block_start=0,i.insert=0))),Oo(e),0===e.avail_out))return i.last_flush=-1,so}return t!==ro?so:i.wrap<=0?lo:(2===i.wrap?(Lo(i,255&e.adler),Lo(i,e.adler>>8&255),Lo(i,e.adler>>16&255),Lo(i,e.adler>>24&255),Lo(i,255&e.total_in),Lo(i,e.total_in>>8&255),Lo(i,e.total_in>>16&255),Lo(i,e.total_in>>24&255)):(Bo(i,e.adler>>>16),Bo(i,65535&e.adler)),Oo(e),i.wrap>0&&(i.wrap=-i.wrap),0!==i.pending?so:lo)},jo=(e,t)=>{let i=t.length;if(Wo(e))return co;const n=e.state,o=n.wrap;if(2===o||1===o&&n.status!==ko||n.lookahead)return co;if(1===o&&(e.adler=qn(e.adler,t,i,0)),n.wrap=0,i>=n.w_size){0===o&&(Ro(n.head),n.strstart=0,n.block_start=0,n.insert=0);let e=new Uint8Array(n.w_size);e.set(t.subarray(i-n.w_size,i),0),t=e,i=n.w_size}const r=e.avail_in,a=e.next_in,d=e.input;for(e.avail_in=i,e.next_in=0,e.input=t,$o(n);n.lookahead>=3;){let e=n.strstart,t=n.lookahead-2;do{n.ins_h=Ao(n,n.ins_h,n.window[e+3-1]),n.prev[e&n.w_mask]=n.head[n.ins_h],n.head[n.ins_h]=e,e++}while(--t);n.strstart=e,n.lookahead=2,$o(n)}return n.strstart+=n.lookahead,n.block_start=n.strstart,n.insert=n.lookahead,n.lookahead=0,n.match_length=n.prev_length=2,n.match_available=0,e.next_in=a,e.input=d,e.avail_in=r,n.wrap=o,so},Ko={deflateInit:(e,t)=>Yo(e,t,vo,15,8,_o),deflateInit2:Yo,deflateReset:qo,deflateResetKeep:Xo,deflateSetHeader:(e,t)=>Wo(e)||2!==e.state.wrap?co:(e.state.gzhead=t,so),deflate:Go,deflateEnd:e=>{if(Wo(e))return co;const t=e.state.status;return e.state=null,t===Eo?So(e,ho):so},deflateSetDictionary:jo,deflateInfo:"pako deflate (from Nodeca project)"};const Zo=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var Qo=function(e){const t=Array.prototype.slice.call(arguments,1);for(;t.length;){const i=t.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(const t in i)Zo(i,t)&&(e[t]=i[t])}}return e},Jo=e=>{let t=0;for(let i=0,n=e.length;i<n;i++)t+=e[i].length;const i=new Uint8Array(t);for(let t=0,n=0,o=e.length;t<o;t++){let o=e[t];i.set(o,n),n+=o.length}return i};let er=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){er=!1}const tr=new Uint8Array(256);for(let e=0;e<256;e++)tr[e]=e>=252?6:e>=248?5:e>=240?4:e>=224?3:e>=192?2:1;tr[254]=tr[254]=1;var ir=e=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(e);let t,i,n,o,r,a=e.length,d=0;for(o=0;o<a;o++)i=e.charCodeAt(o),55296==(64512&i)&&o+1<a&&(n=e.charCodeAt(o+1),56320==(64512&n)&&(i=65536+(i-55296<<10)+(n-56320),o++)),d+=i<128?1:i<2048?2:i<65536?3:4;for(t=new Uint8Array(d),r=0,o=0;r<d;o++)i=e.charCodeAt(o),55296==(64512&i)&&o+1<a&&(n=e.charCodeAt(o+1),56320==(64512&n)&&(i=65536+(i-55296<<10)+(n-56320),o++)),i<128?t[r++]=i:i<2048?(t[r++]=192|i>>>6,t[r++]=128|63&i):i<65536?(t[r++]=224|i>>>12,t[r++]=128|i>>>6&63,t[r++]=128|63&i):(t[r++]=240|i>>>18,t[r++]=128|i>>>12&63,t[r++]=128|i>>>6&63,t[r++]=128|63&i);return t};var nr=function(){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};const or=Object.prototype.toString,{Z_NO_FLUSH:rr,Z_SYNC_FLUSH:ar,Z_FULL_FLUSH:dr,Z_FINISH:sr,Z_OK:lr,Z_STREAM_END:cr,Z_DEFAULT_COMPRESSION:hr,Z_DEFAULT_STRATEGY:mr,Z_DEFLATED:pr}=Kn;function ur(e){this.options=Qo({level:hr,method:pr,chunkSize:16384,windowBits:15,memLevel:8,strategy:mr},e||{});let t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new nr,this.strm.avail_out=0;let i=Ko.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(i!==lr)throw new Error(jn[i]);if(t.header&&Ko.deflateSetHeader(this.strm,t.header),t.dictionary){let e;if(e="string"==typeof t.dictionary?ir(t.dictionary):"[object ArrayBuffer]"===or.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,i=Ko.deflateSetDictionary(this.strm,e),i!==lr)throw new Error(jn[i]);this._dict_set=!0}}ur.prototype.push=function(e,t){const i=this.strm,n=this.options.chunkSize;let o,r;if(this.ended)return!1;for(r=t===~~t?t:!0===t?sr:rr,"string"==typeof e?i.input=ir(e):"[object ArrayBuffer]"===or.call(e)?i.input=new Uint8Array(e):i.input=e,i.next_in=0,i.avail_in=i.input.length;;)if(0===i.avail_out&&(i.output=new Uint8Array(n),i.next_out=0,i.avail_out=n),(r===ar||r===dr)&&i.avail_out<=6)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else{if(o=Ko.deflate(i,r),o===cr)return i.next_out>0&&this.onData(i.output.subarray(0,i.next_out)),o=Ko.deflateEnd(this.strm),this.onEnd(o),this.ended=!0,o===lr;if(0!==i.avail_out){if(r>0&&i.next_out>0)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else if(0===i.avail_in)break}else this.onData(i.output)}return!0},ur.prototype.onData=function(e){this.chunks.push(e)},ur.prototype.onEnd=function(e){e===lr&&(this.result=Jo(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var fr={deflate:function(e,t){const i=new ur(t);if(i.push(e,!0),i.err)throw i.msg||jn[i.err];return i.result}};const{deflate:gr}=fr;var br=gr;const _r={b:{u:DataView.prototype.getInt8,p:DataView.prototype.setInt8,bytes:1},B:{u:DataView.prototype.getUint8,p:DataView.prototype.setUint8,bytes:1},h:{u:DataView.prototype.getInt16,p:DataView.prototype.setInt16,bytes:2},H:{u:DataView.prototype.getUint16,p:DataView.prototype.setUint16,bytes:2},i:{u:DataView.prototype.getInt32,p:DataView.prototype.setInt32,bytes:4},I:{u:DataView.prototype.getUint32,p:DataView.prototype.setUint32,bytes:4}},xr=(e,...t)=>{let i=0;if(e.replace(/[<>]/,"").length!=t.length)throw"Pack format to Argument count mismatch";const n=[];let o=!0;for(let n=0;n<e.length;n++)"<"==e[n]?o=!0:">"==e[n]?o=!1:(r(e[n],t[i]),i++);function r(e,t){if(!(e in _r))throw"Unhandled character '"+e+"' in pack format";const i=_r[e].bytes,r=new DataView(new ArrayBuffer(i));_r[e].p.bind(r)(0,t,o);for(let e=0;e<i;e++)n.push(r.getUint8(e))}return n},vr=(e,t)=>{let i=0;const n=[];let o=!0;for(const t of e)"<"==t?o=!0:">"==t?o=!1:r(t);function r(e){if(!(e in _r))throw"Unhandled character '"+e+"' in unpack format";const r=_r[e].bytes,a=new DataView(new ArrayBuffer(r));for(let e=0;e<r;e++)a.setUint8(e,255&t[i+e]);const d=_r[e].u.bind(a);n.push(d(0,o)),i+=r}return n};class yr extends EventTarget{constructor(e,t,i){super(),this.port=e,this.logger=t,this._parent=i,this.chipName=null,this.chipRevision=null,this.chipVariant=null,this._efuses=new Array(4).fill(0),this._flashsize=4194304,this.debug=!1,this.IS_STUB=!1,this.connected=!0,this.flashSize=null,this._currentBaudRate=Fi,this._isESP32S2NativeUSB=!1,this._initializationSucceeded=!1,this.state_DTR=!1}get _inputBuffer(){return this._parent?this._parent._inputBuffer:this.__inputBuffer}get _totalBytesRead(){return this._parent?this._parent._totalBytesRead:this.__totalBytesRead||0}set _totalBytesRead(e){this._parent?this._parent._totalBytesRead=e:this.__totalBytesRead=e}detectUSBSerialChip(e,t){const i={6790:{29986:{name:"CH340",maxBaudrate:460800},29987:{name:"CH340",maxBaudrate:460800},30084:{name:"CH340",maxBaudrate:460800},21795:{name:"CH341",maxBaudrate:2e6},21971:{name:"CH343",maxBaudrate:6e6},21972:{name:"CH9102",maxBaudrate:6e6},21976:{name:"CH9101",maxBaudrate:3e6}},4292:{6e4:{name:"CP2102(n)",maxBaudrate:3e6},60016:{name:"CP2105",maxBaudrate:2e6},60017:{name:"CP2108",maxBaudrate:2e6}},1027:{24577:{name:"FT232R",maxBaudrate:3e6},24592:{name:"FT2232",maxBaudrate:3e6},24593:{name:"FT4232",maxBaudrate:3e6},24596:{name:"FT232H",maxBaudrate:12e6},24597:{name:"FT230X",maxBaudrate:3e6}},12346:{2:{name:"ESP32-S2 Native USB",maxBaudrate:2e6},4097:{name:"ESP32 Native USB",maxBaudrate:2e6},4098:{name:"ESP32 Native USB",maxBaudrate:2e6},16386:{name:"ESP32 Native USB",maxBaudrate:2e6},4096:{name:"ESP32 Native USB",maxBaudrate:2e6}}}[e];return i&&i[t]?i[t]:{name:`Unknown (VID: 0x${e.toString(16)}, PID: 0x${t.toString(16)})`}}async initialize(){if(await this.hardReset(!0),!this._parent){this.__inputBuffer=[],this.__totalBytesRead=0;const e=this.port.getInfo();if(e.usbVendorId&&e.usbProductId){const t=this.detectUSBSerialChip(e.usbVendorId,e.usbProductId);this.logger.log(`USB-Serial: ${t.name} (VID: 0x${e.usbVendorId.toString(16)}, PID: 0x${e.usbProductId.toString(16)})`),t.maxBaudrate&&(this._maxUSBSerialBaudrate=t.maxBaudrate,this.logger.log(`Max baudrate: ${t.maxBaudrate}`)),12346!==e.usbVendorId||2!==e.usbProductId&&4097!==e.usbProductId||(this._isESP32S2NativeUSB=!0)}this.readLoop()}await this.flushSerialBuffers(),await this.sync(),await this.detectChip();const e=tn(this.getChipFamily()),t=e.macFuse;for(let e=0;e<4;e++)this._efuses[e]=await this.readRegister(t+4*e);this.logger.log(`Chip type ${this.chipName}`),this.logger.debug(`Bootloader flash offset: 0x${e.flashOffs.toString(16)}`),this._initializationSucceeded=!0}async detectChip(){try{const e=(await this.getSecurityInfo()).chipId,t=ji[e];if(t)return this.chipName=t.name,this.chipFamily=t.family,this.chipFamily===Yi&&(this.chipRevision=await this.getChipRevision(),this.logger.debug(`ESP32-P4 revision: ${this.chipRevision}`),this.chipRevision>=300?this.chipVariant="rev300":this.chipVariant="rev0",this.logger.debug(`ESP32-P4 variant: ${this.chipVariant}`)),void this.logger.debug(`Detected chip via IMAGE_CHIP_ID: ${e} (${this.chipName})`);this.logger.debug(`Unknown IMAGE_CHIP_ID: ${e}, falling back to magic value detection`)}catch(e){this.logger.debug(`GET_SECURITY_INFO failed, using magic value detection: ${e}`),this._inputBuffer.length=0,await Ai(Ji);try{await this.sync()}catch(e){this.logger.debug(`Re-sync after GET_SECURITY_INFO failure: ${e}`)}}const e=await this.readRegister(1073745920),t=Ki[e>>>0];if(void 0===t)throw new Error(`Unknown Chip: Hex: ${Ti(e>>>0,8).toLowerCase()} Number: ${e}`);this.chipName=t.name,this.chipFamily=t.family,this.chipFamily===Yi&&(this.chipRevision=await this.getChipRevision(),this.logger.debug(`ESP32-P4 revision: ${this.chipRevision}`),this.chipRevision>=300?this.chipVariant="rev300":this.chipVariant="rev0",this.logger.debug(`ESP32-P4 variant: ${this.chipVariant}`)),this.logger.debug(`Detected chip via magic value: ${Ti(e>>>0,8)} (${this.chipName})`)}async getChipRevision(){if(this.chipFamily!==Yi)return 0;const e=await this.readRegister(1343410252);return 100*((e>>23&1)<<2|e>>4&3)+(15&e)}async getSecurityInfo(){const[,e]=await this.checkCommand(20,[],0);if(0===e.length)throw new Error("GET_SECURITY_INFO not supported or returned empty response");if(e.length<12)throw new Error(`Invalid security info response length: ${e.length} (expected at least 12 bytes)`);return{flags:vr("<I",e.slice(0,4))[0],flashCryptCnt:e[4],keyPurposes:Array.from(e.slice(5,12)),chipId:e.length>=16?vr("<I",e.slice(12,16))[0]:0,apiVersion:e.length>=20?vr("<I",e.slice(16,20))[0]:0}}async readLoop(){this.debug&&this.logger.debug("Starting read loop"),this._reader=this.port.readable.getReader();try{let e=!0;for(;e;){const{value:t,done:i}=await this._reader.read();if(i){this._reader.releaseLock(),e=!1;break}if(!t||0===t.length)continue;const n=Array.from(t);Array.prototype.push.apply(this._inputBuffer,n),this._totalBytesRead+=t.length}}catch{this.logger.error("Read loop got disconnected")}this.connected=!1,this._isESP32S2NativeUSB&&!this._initializationSucceeded&&(this.logger.log("ESP32-S2 Native USB detected - requesting port reselection"),this.dispatchEvent(new CustomEvent("esp32s2-usb-reconnect",{detail:{message:"ESP32-S2 Native USB requires port reselection"}}))),this.dispatchEvent(new Event("disconnect")),this.logger.debug("Finished read loop")}sleep(e=100){return new Promise(t=>setTimeout(t,e))}async setRTS(e){await this.port.setSignals({requestToSend:e}),await this.setDTR(this.state_DTR)}async setDTR(e){this.state_DTR=e,await this.port.setSignals({dataTerminalReady:e})}async hardReset(e=!1){e?4097===this.port.getInfo().usbProductId?(await this.setDTR(!1),await this.setRTS(!1),await this.sleep(100),await this.setDTR(!0),await this.setRTS(!1),await this.sleep(100),await this.setRTS(!0),await this.setDTR(!1),await this.setRTS(!0),await this.sleep(100),await this.setDTR(!1),await this.setRTS(!1),this.logger.log("USB MCU reset.")):(await this.setDTR(!1),await this.setRTS(!0),await this.sleep(100),await this.setDTR(!0),await this.setRTS(!1),await this.sleep(50),await this.setDTR(!1),this.logger.log("DTR/RTS USB serial chip reset.")):(await this.setRTS(!0),await this.sleep(100),await this.setRTS(!1),this.logger.log("Hard reset.")),await new Promise(e=>setTimeout(e,1e3))}macAddr(){const e=new Array(6).fill(0),t=this._efuses[0],i=this._efuses[1],n=this._efuses[2],o=this._efuses[3];let r;if(this.chipFamily==zi){if(0!=o)r=[o>>16&255,o>>8&255,255&o];else if(i>>16&255){if(1!=(i>>16&255))throw new Error("Couldnt determine OUI");r=[172,208,116]}else r=[24,254,52];e[0]=r[0],e[1]=r[1],e[2]=r[2],e[3]=i>>8&255,e[4]=255&i,e[5]=t>>24&255}else if(this.chipFamily==Di)e[0]=n>>8&255,e[1]=255&n,e[2]=i>>24&255,e[3]=i>>16&255,e[4]=i>>8&255,e[5]=255&i;else{if(this.chipFamily!=$i&&this.chipFamily!=Ni&&this.chipFamily!=Pi&&this.chipFamily!=Mi&&this.chipFamily!=Ui&&this.chipFamily!=Hi&&this.chipFamily!=Vi&&this.chipFamily!=Wi&&this.chipFamily!=Xi&&this.chipFamily!=qi&&this.chipFamily!=Yi&&this.chipFamily!=Gi)throw new Error("Unknown chip family");e[0]=i>>8&255,e[1]=255&i,e[2]=t>>24&255,e[3]=t>>16&255,e[4]=t>>8&255,e[5]=255&t}return e}async readRegister(e){this.debug&&this.logger.debug("Reading from Register "+Ti(e,8));const t=xr("<I",e);await this.sendCommand(10,t);const[i]=await this.getResponse(10);return i}async checkCommand(e,t,i=0,n=3e3){n=Math.min(n,3e5),await this.sendCommand(e,t,i);const[o,r]=await this.getResponse(e,n);if(null===r)throw new Error("Didn't get enough status bytes");let a=r,d=0;if(this.IS_STUB||this.chipFamily==zi?d=2:[Di,$i,Ni,Pi,Mi,Ui,Hi,Vi,Wi,Xi,qi,Yi,Gi].includes(this.chipFamily)||20===e?d=4:[2,4].includes(a.length)&&(d=a.length),a.length<d)throw new Error("Didn't get enough status bytes");const s=a.slice(-d,a.length);if(a=a.slice(0,-d),this.debug&&(this.logger.debug("status",s),this.logger.debug("value",o),this.logger.debug("data",a)),1==s[0])throw 5==s[1]?new Error("Invalid (unsupported) command "+Ti(e)):new Error("Command failure error code "+Ti(s[1]));return[o,a]}async sendCommand(e,t,i=0){const n=Si([...xr("<BBHI",0,e,t.length,i),...t]);this.debug&&this.logger.debug(`Writing ${n.length} byte${1==n.length?"":"s"}:`,n),await this.writeToStream(n)}async readPacket(e){let t=null,i=!1,n=[];for(;;){const o=Date.now();for(n=[];Date.now()-o<e;){if(this._inputBuffer.length>0){n.push(this._inputBuffer.shift());break}await Ai(1)}if(0==n.length){throw new nn("Timed out waiting for packet "+(null===t?"header":"content"))}this.debug&&this.logger.debug("Read "+n.length+" bytes: "+Ri(n));for(const e of n)if(null===t){if(192!=e)throw this.debug&&(this.logger.debug("Read invalid data: "+Ri(n)),this.logger.debug("Remaining data in serial buffer: "+Ri(this._inputBuffer))),new nn("Invalid head of packet ("+Ti(e)+")");t=[]}else if(i)if(i=!1,220==e)t.push(192);else{if(221!=e)throw this.debug&&(this.logger.debug("Read invalid data: "+Ri(n)),this.logger.debug("Remaining data in serial buffer: "+Ri(this._inputBuffer))),new nn("Invalid SLIP escape (0xdb, "+Ti(e)+")");t.push(219)}else if(219==e)i=!0;else{if(192==e)return this.debug&&this.logger.debug("Received full packet: "+Ri(t)),t;t.push(e)}}throw new nn("Invalid state")}async getResponse(e,t=3e3){for(let i=0;i<100;i++){const i=await this.readPacket(t);if(i.length<8)continue;const[n,o,,r]=vr("<BBHI",i.slice(0,8));if(1!=n)continue;const a=i.slice(8);if(null==e||o==e)return[r,a];if(0!=a[0]&&5==a[1])throw this._inputBuffer.length=0,new Error(`Invalid (unsupported) command ${Ti(e)}`)}throw"Response doesn't match request"}checksum(e,t=239){for(const i of e)t^=i;return t}async setBaudrate(e){if(this.chipFamily==zi)throw new Error("Changing baud rate is not supported on the ESP8266");try{const t=xr("<II",e,this.IS_STUB?Fi:0);await this.checkCommand(15,t)}catch(t){throw this.logger.error(`Baudrate change error: ${t}`),new Error(`Unable to change the baud rate to ${e}: No response from set baud rate command.`)}this._parent?await this._parent.reconfigurePort(e):await this.reconfigurePort(e),this._parent?this._parent._currentBaudRate=e:this._currentBaudRate=e;const t=this._parent?this._parent._maxUSBSerialBaudrate:this._maxUSBSerialBaudrate;t&&e>t&&(this.logger.log(`⚠️ WARNING: Baudrate ${e} exceeds USB-Serial chip limit (${t})!`),this.logger.log("⚠️ This may cause data corruption or connection failures!")),this.logger.log(`Changed baud rate to ${e}`)}async reconfigurePort(e){var t;try{await(null===(t=this._reader)||void 0===t?void 0:t.cancel()),await this.port.close(),await this.port.open({baudRate:e}),await this.flushSerialBuffers(),this.readLoop()}catch(t){throw this.logger.error(`Reconfigure port error: ${t}`),new Error(`Unable to change the baud rate to ${e}: ${t}`)}}async sync(){for(let e=0;e<5;e++){this._inputBuffer.length=0;if(await this._sync())return await Ai(Ji),!0;await Ai(Ji)}throw new Error("Couldn't sync to ESP. Try resetting.")}async _sync(){await this.sendCommand(8,Bi);for(let e=0;e<8;e++)try{const[,e]=await this.getResponse(8,Ji);if(e.length>1&&0==e[0]&&0==e[1])return!0}catch{}return!1}getFlashWriteSize(){return this.IS_STUB?16384:1024}async flashData(e,t,i=0,n=!1){if(e.byteLength>=8){const t=Array.from(new Uint8Array(e,0,4)),i=t[0],n=t[2],o=t[3];this.logger.log(`Image header, Magic=${Ti(i)}, FlashMode=${Ti(n)}, FlashSizeFreq=${Ti(o)}`)}const o=e.byteLength;let r,a=0,d=Zi;n?(r=br(new Uint8Array(e),{level:9}).buffer,a=r.byteLength,this.logger.log(`Writing data with filesize: ${o}. Compressed Size: ${a}`),d=await this.flashDeflBegin(o,a,i)):(this.logger.log(`Writing data with filesize: ${o}`),r=e,await this.flashBegin(o,i));let s=[],l=0,c=0,h=0;const m=Date.now(),p=this.getFlashWriteSize(),u=n?a:o;for(;u-h>0;)this.debug&&this.logger.log(`Writing at ${Ti(i+l*p,8)} `),u-h>=p?s=Array.from(new Uint8Array(r,h,p)):(s=Array.from(new Uint8Array(r,h,u-h)),n||(s=s.concat(new Array(p-s.length).fill(255)))),n?await this.flashDeflBlock(s,l,d):await this.flashBlock(s,l),l+=1,c+=n?Math.round(s.length*o/a):s.length,h+=p,t(Math.min(c,o),o);this.logger.log("Took "+(Date.now()-m)+"ms to write "+u+" bytes"),this.IS_STUB&&(await this.flashBegin(0,0),n?await this.flashDeflFinish():await this.flashFinish())}async flashBlock(e,t,i=3e3){await this.checkCommand(3,xr("<IIII",e.length,t,0,0).concat(e),this.checksum(e),i)}async flashDeflBlock(e,t,i=3e3){await this.checkCommand(17,xr("<IIII",e.length,t,0,0).concat(e),this.checksum(e),i)}async flashBegin(e=0,t=0,i=!1){let n;await this.flushSerialBuffers();const o=this.getFlashWriteSize();!this.IS_STUB&&[Di,$i,Ni,Pi,Mi,Ui,Hi,Vi,Wi,Xi,qi,Yi,Gi].includes(this.chipFamily)&&await this.checkCommand(13,new Array(8).fill(0));const r=Math.floor((e+o-1)/o);n=this.chipFamily==zi?this.getEraseSize(t,e):e;const a=this.IS_STUB?Zi:en(3e4,e),d=Date.now();let s=xr("<IIII",n,r,o,t);return this.chipFamily!=Di&&this.chipFamily!=$i&&this.chipFamily!=Ni&&this.chipFamily!=Pi&&this.chipFamily!=Mi&&this.chipFamily!=Ui&&this.chipFamily!=Hi&&this.chipFamily!=Vi&&this.chipFamily!=Wi&&this.chipFamily!=Xi&&this.chipFamily!=qi&&this.chipFamily!=Yi&&this.chipFamily!=Gi||(s=s.concat(xr("<I",i?1:0))),this.logger.log("Erase size "+n+", blocks "+r+", block size "+Ti(o,4)+", offset "+Ti(t,4)+", encrypted "+(i?"yes":"no")),await this.checkCommand(2,s,0,a),0==e||this.IS_STUB||this.logger.log("Took "+(Date.now()-d)+"ms to erase "+r+" bytes"),r}async flashDeflBegin(e=0,t=0,i=0){const n=this.getFlashWriteSize(),o=Math.floor((t+n-1)/n),r=Math.floor((e+n-1)/n);let a=0,d=0;this.IS_STUB?(a=e,d=en(3e4,a)):(a=r*n,d=Zi);const s=xr("<IIII",a,o,n,i);return await this.checkCommand(16,s,0,d),d}async flashFinish(){const e=xr("<I",1);await this.checkCommand(4,e)}async flashDeflFinish(){const e=xr("<I",1);await this.checkCommand(18,e)}getBootloaderOffset(){return tn(this.getChipFamily()).flashOffs}async flashId(){return await this.runSpiFlashCommand(159,[],24)}getChipFamily(){return this._parent?this._parent.chipFamily:this.chipFamily}async writeRegister(e,t,i=4294967295,n=0,o=0){let r=xr("<IIII",e,t,i,n);o>0&&(r=r.concat(xr("<IIII",tn(this.getChipFamily()).uartDateReg,0,0,o))),await this.checkCommand(9,r)}async setDataLengths(e,t,i){if(-1!=e.mosiDlenOffs){const n=e.regBase+e.mosiDlenOffs,o=e.regBase+e.misoDlenOffs;t>0&&await this.writeRegister(n,t-1),i>0&&await this.writeRegister(o,i-1)}else{const n=e.regBase+e.usr1Offs,o=(0==i?0:i-1)<<8|(0==t?0:t-1)<<17;await this.writeRegister(n,o)}}async waitDone(e,t){for(let i=0;i<10;i++){if(0==(await this.readRegister(e)&t))return}throw Error("SPI command did not complete in time")}async runSpiFlashCommand(e,t,i=0){const n=tn(this.getChipFamily()),o=n.regBase,r=o,a=o+n.usrOffs,d=o+n.usr2Offs,s=o+n.w0Offs,l=1<<18;if(i>32)throw new Error("Reading more than 32 bits back from a SPI flash operation is unsupported");if(t.length>64)throw new Error("Writing more than 64 bytes of data with one SPI command is unsupported");const c=8*t.length,h=await this.readRegister(a),m=await this.readRegister(d);let p=1<<31;if(i>0&&(p|=268435456),c>0&&(p|=134217728),await this.setDataLengths(n,c,i),await this.writeRegister(a,p),await this.writeRegister(d,7<<28|e),0==c)await this.writeRegister(s,0);else{const e=(4-t.length%4)%4;t=t.concat(new Array(e).fill(0));const i=vr("I".repeat(Math.floor(t.length/4)),t);let n=s;this.logger.debug(`Words Length: ${i.length}`);for(const e of i)this.logger.debug(`Writing word ${Ti(e)} to register offset ${Ti(n)}`),await this.writeRegister(n,e),n+=4}await this.writeRegister(r,l),await this.waitDone(r,l);const u=await this.readRegister(s);return await this.writeRegister(a,h),await this.writeRegister(d,m),u}async detectFlashSize(){this.logger.log("Detecting Flash Size");const e=await this.flashId(),t=255&e,i=e>>16&255;this.logger.log(`FlashId: ${Ti(e)}`),this.logger.log(`Flash Manufacturer: ${t.toString(16)}`),this.logger.log(`Flash Device: ${(e>>8&255).toString(16)}${i.toString(16)}`),this.flashSize=Oi[i],this.logger.log(`Auto-detected Flash size: ${this.flashSize}`)}getEraseSize(e,t){const i=4096,n=Math.floor((t+i-1)/i);let o=16-Math.floor(e/i)%16;return n<o&&(o=n),n<2*o?Math.floor((n+1)/2*i):(n-o)*i}async memBegin(e,t,i,n){return await this.checkCommand(5,xr("<IIII",e,t,i,n))}async memBlock(e,t){return await this.checkCommand(7,xr("<IIII",e.length,t,0,0).concat(e),this.checksum(e))}async memFinish(e=0){const t=this.IS_STUB?Zi:500,i=xr("<II",0==e?1:0,e);return await this.checkCommand(6,i,0,t)}async runStub(e=!1){const t=await on(this.chipFamily,this.chipRevision);if(null===t)return this.logger.log(`Stub flasher is not yet supported on ${this.chipName}, using ROM loader`),this;const i=2048;this.logger.log("Uploading stub...");for(const e of["text","data"]){const n=t[e],o=t[`${e}_start`],r=n.length,a=Math.floor((r+i-1)/i);await this.memBegin(r,a,i,o);for(const e of Array(a).keys()){const t=e*i;let o=t+i;o>r&&(o=r),await this.memBlock(n.slice(t,o),e)}}await this.memFinish(t.entry);const n=await this.readPacket(500),o=String.fromCharCode(...n);if("OHAI"!=o)throw new Error("Failed to start stub. Unexpected response: "+o);this.logger.log("Stub is now running...");const r=new wr(this.port,this.logger,this);return e||await r.detectFlashSize(),r}async writeToStream(e){if(!this.port.writable)return void this.logger.debug("Port writable stream not available, skipping write");const t=this.port.writable.getWriter();await t.write(new Uint8Array(e));try{t.releaseLock()}catch(e){this.logger.error(`Ignoring release lock error: ${e}`)}}async disconnect(){this._parent?await this._parent.disconnect():this.port.writable?(await this.port.writable.getWriter().close(),await new Promise(e=>{this._reader||e(void 0),this.addEventListener("disconnect",e,{once:!0}),this._reader.cancel()}),this.connected=!1):this.logger.debug("Port already closed, skipping disconnect")}async reconnect(){if(this._parent)return void await this._parent.reconnect();if(this.logger.log("Reconnecting serial port..."),this.connected=!1,this.__inputBuffer=[],this._reader){try{await this._reader.cancel()}catch(e){this.logger.debug(`Reader cancel error: ${e}`)}this._reader=void 0}try{await this.port.close(),this.logger.log("Port closed")}catch(e){this.logger.debug(`Port close error: ${e}`)}this.logger.debug("Opening port...");try{await this.port.open({baudRate:Fi}),this.connected=!0}catch(e){throw new Error(`Failed to open port: ${e}`)}if(!this.port.readable||!this.port.writable)throw new Error(`Port streams not available after open (readable: ${!!this.port.readable}, writable: ${!!this.port.writable})`);const e=this.chipFamily,t=this.chipName,i=this.chipRevision,n=this.chipVariant,o=this.flashSize;if(await this.hardReset(!0),this._parent||(this.__inputBuffer=[],this.__totalBytesRead=0,this.readLoop()),await this.flushSerialBuffers(),await this.sync(),this.chipFamily=e,this.chipName=t,this.chipRevision=i,this.chipVariant=n,this.flashSize=o,this.logger.debug(`Reconnect complete (chip: ${this.chipName})`),!this.port.writable||!this.port.readable)throw new Error("Port not ready after reconnect");const r=await this.runStub(!0);if(this.logger.debug("Stub loaded"),this._currentBaudRate!==Fi&&(await r.setBaudrate(this._currentBaudRate),!this.port.writable||!this.port.readable))throw new Error(`Port not ready after baudrate change (readable: ${!!this.port.readable}, writable: ${!!this.port.writable})`);this.IS_STUB&&Object.assign(this,r),this.logger.debug("Reconnection successful")}async flushSerialBuffers(){this._parent||(this.__inputBuffer=[]),await Ai(Ji),this._parent||(this.__inputBuffer=[]),this.logger.debug("Serial buffers flushed")}async readFlash(e,t,i){if(!this.IS_STUB)throw new Error("Reading flash is only supported in stub mode. Please run runStub() first.");await this.flushSerialBuffers(),this.logger.log(`Reading ${t} bytes from flash at address 0x${e.toString(16)}...`);let n=new Uint8Array(0),o=e,r=t;for(;r>0;){const e=Math.min(65536,r);let a=!1,d=0;const s=3;for(;!a&&d<=s;)try{this.logger.debug(`Reading chunk at 0x${o.toString(16)}, size: 0x${e.toString(16)}`);const t=xr("<IIII",o,e,4096,1024),[i]=await this.checkCommand(210,t);if(0!=i)throw new Error("Failed to read memory: "+i);let r=new Uint8Array(0);for(;r.length<e;){let t;try{t=await this.readPacket(100)}catch(t){if(t instanceof nn&&(this.logger.debug(`SLIP read error at ${r.length} bytes: ${t.message}`),r.length>=e))break;throw t}if(t&&t.length>0){const e=new Uint8Array(t),i=new Uint8Array(r.length+e.length);i.set(r),i.set(e,r.length),r=i;const n=xr("<I",r.length),o=Si(n);await this.writeToStream(o)}}const d=new Uint8Array(n.length+r.length);d.set(n),d.set(r,n.length),n=d,a=!0}catch(e){if(d++,!(e instanceof nn&&e.message.includes("Timed out")))throw e;if(!(d<=s))throw new Error(`Failed to read chunk at 0x${o.toString(16)} after ${s} retries: ${e}`);this.logger.log(`⚠️ Timeout error at 0x${o.toString(16)}. Reconnecting and retrying (attempt ${d}/${s})...`);try{await this.reconnect()}catch(e){throw new Error(`Reconnect failed: ${e}`)}}i&&i(new Uint8Array(e),n.length,t),o+=e,r-=e,this.logger.debug(`Total progress: 0x${n.length.toString(16)} from 0x${t.toString(16)} bytes`)}return this.logger.debug(`Successfully read ${n.length} bytes from flash`),n}}class wr extends yr{constructor(){super(...arguments),this.IS_STUB=!0}async memBegin(e,t,i,n){const o=await on(this.chipFamily,this.chipRevision);if(null===o)return[0,[]];const r=n,a=n+e;this.logger.debug(`Load range: ${Ti(r,8)}-${Ti(a,8)}`),this.logger.debug(`Stub data: ${Ti(o.data_start,8)}, len: ${o.data.length}, text: ${Ti(o.text_start,8)}, len: ${o.text.length}`);for(const[e,t]of[[o.data_start,o.data_start+o.data.length],[o.text_start,o.text_start+o.text.length]])if(r<t&&a>e)throw new Error("Software loader is resident at "+Ti(e,8)+"-"+Ti(t,8)+". Can't load binary at overlapping address range "+Ti(r,8)+"-"+Ti(a,8)+". Try changing the binary loading address.");return[0,[]]}async eraseFlash(){await this.checkCommand(208,[],0,Qi)}}const kr=async(e,t,i,n,o,r,a)=>{let d,s,l,c=null,h=!1;const m=(e=>{const t=e.getInfo();return 12346===t.usbVendorId&&(2===t.usbProductId||4097===t.usbProductId)})(t),p=t=>e({...t,manifest:d,build:s,chipFamily:l,chipVariant:c});var u=null,f="";try{u=JSON.parse(n)}catch{f=new URL(n,location.toString()).toString(),u=fetch(f).then(e=>e.json())}const g=new yr(t,i);window.esploader=g;const b=()=>{h=!0,i.log("ESP32-S2 Native USB disconnect detected - reconnection required")};m&&(g.addEventListener("esp32s2-usb-reconnect",b),i.log("ESP32-S2 Native USB detected - monitoring for port switch"));const _=()=>{m&&g.removeEventListener("esp32s2-usb-reconnect",b)};p({state:"initializing",message:"Initializing...",details:{done:!1}});try{await g.initialize()}catch(e){if(i.error(e),m&&h){_();try{await t.close()}catch{}try{await t.forget()}catch{}return void p({state:"esp32_s2_usb_reconnect",message:"ESP32-S2 Native USB detected - please select the new port",details:{oldPort:t}})}return _(),p({state:"error",message:"Failed to initialize. Try resetting your device or holding the BOOT button while clicking INSTALL.",details:{error:"failed_initialize",details:e}}),void(g.connected&&await g.disconnect())}l=(e=>{switch(e.chipFamily){case Di:return"ESP32";case $i:return"ESP32-S2";case Ni:return"ESP32-S3";case Pi:return"ESP32-C2";case Mi:return"ESP32-C3";case Ui:return"ESP32-C5";case Hi:return"ESP32-C6";case Vi:return"ESP32-C61";case Wi:return"ESP32-H2";case Yi:return"ESP32-P4";case zi:return"ESP8266";default:return"Unknown Chip"}})(g),c=g.chipVariant,p({state:"initializing",message:`Initialized. Found ${l}${c?` (${c})`:""}`,details:{done:!0}}),p({state:"manifest",message:"Fetching manifest...",details:{done:!1}});try{d=await u}catch(e){return _(),p({state:"error",message:`Unable to fetch manifest: ${e}`,details:{error:"fetch_manifest_failed",details:e}}),void await g.disconnect()}if(s=d.builds.find(e=>e.chipFamily===l&&(void 0===e.chipVariant||e.chipVariant===c)),p({state:"manifest",message:`Found manifest for ${d.name}`,details:{done:!0}}),!s){const e=c?`${l} (${c})`:l;return _(),p({state:"error",message:`Your ${e} board is not supported.`,details:{error:"not_supported",details:e}}),void await g.disconnect()}p({state:"preparing",message:"Preparing installation...",details:{done:!1}});const x=s.parts.map(async e=>{if(0==r.length){const t=new URL(e.path,f).toString(),i=await fetch(t);if(!i.ok)throw new Error(`Downlading firmware ${e.path} failed: ${i.status}`);return i.arrayBuffer()}return r}),v=await g.runStub();if(void 0!==a&&a>115200)try{await v.setBaudrate(a)}catch(e){i.log(`Could not change baud rate to ${a}: ${e.message}`)}const y=[];let w=0;for(const e of x)try{const t=await e;y.push(t instanceof ArrayBuffer?new Uint8Array(t):t),w+=t.byteLength}catch(e){return _(),p({state:"error",message:e.message,details:{error:"failed_firmware_download",details:e.message}}),void await g.disconnect()}p({state:"preparing",message:"Installation prepared",details:{done:!0}}),o&&(p({state:"erasing",message:"Erasing device...",details:{done:!1}}),await v.eraseFlash(),p({state:"erasing",message:"Device erased",details:{done:!0}}));let k=0;p({state:"writing",message:`Writing progress: ${k}%`,details:{bytesTotal:w,bytesWritten:0,percentage:k}});let E=0;for(const e of s.parts){const t=y.shift(),i=t instanceof Uint8Array?new Uint8Array(t).buffer:t;try{await v.flashData(i,e=>{const t=Math.floor((E+e)/w*100);t!==k&&(k=t,p({state:"writing",message:`Writing progress: ${t}%`,details:{bytesTotal:w,bytesWritten:E+e,percentage:t}}))},e.offset,!0)}catch(e){return _(),p({state:"error",message:e.message,details:{error:"write_failed",details:e}}),void await g.disconnect()}E+=t.byteLength}p({state:"writing",message:"Writing complete",details:{bytesTotal:w,bytesWritten:E,percentage:100}}),await V(100),console.log("DISCONNECT"),await g.disconnect(),console.log("HARD RESET"),await g.hardReset(),_(),p({state:"finished",message:"All done!"})},Er=(e,t="")=>{const i=new Blob([e],{type:"text/plain"}),n=URL.createObjectURL(i);((e,t="")=>{const i=document.createElement("a");i.target="_blank",i.href=e,i.download=t,document.body.appendChild(i),i.dispatchEvent(new MouseEvent("click")),document.body.removeChild(i)})(n,t),setTimeout(()=>URL.revokeObjectURL(n),0)};class Ir extends x{constructor(){super(...arguments),this.logger=console,this._state="DASHBOARD",this._installErase=!1,this._installConfirmed=!1,this._provisionForce=!1,this._wasProvisioned=!1,this._busy=!1,this._esp32s2ReconnectInProgress=!1,this._selectedSsid=-1,this._handleDisconnect=()=>{this._state="ERROR",this._error="Disconnected"}}render(){if(!this.port)return h``;let e,t,i=!1,n=!1;return void 0===this._client&&"INSTALL"!==this._state&&"LOGS"!==this._state?this._error?[e,t,i]=this._renderError(this._error):(t=this._renderProgress("Connecting"),i=!0):"INSTALL"===this._state?[e,t,i,n]=this._renderInstall():"ASK_ERASE"===this._state?[e,t]=this._renderAskErase():"ERROR"===this._state?[e,t,i]=this._renderError(this._error):"DASHBOARD"===this._state?[e,t,i,n]=this._client?this._renderDashboard():this._renderDashboardNoImprov():"PROVISION"===this._state?[e,t,i]=this._renderProvision():"LOGS"===this._state&&([e,t,i]=this._renderLogs()),h`
|
|
417
|
+
`,xi=["I".charCodeAt(0),"M".charCodeAt(0),"P".charCodeAt(0),"R".charCodeAt(0),"O".charCodeAt(0),"V".charCodeAt(0),1];var vi,yi;!function(e){e[e.CURRENT_STATE=1]="CURRENT_STATE",e[e.ERROR_STATE=2]="ERROR_STATE",e[e.RPC=3]="RPC",e[e.RPC_RESULT=4]="RPC_RESULT"}(vi||(vi={})),function(e){e[e.READY=2]="READY",e[e.PROVISIONING=3]="PROVISIONING",e[e.PROVISIONED=4]="PROVISIONED"}(yi||(yi={}));const wi={0:"NO_ERROR",1:"INVALID_RPC_PACKET",2:"UNKNOWN_RPC_COMMAND",3:"UNABLE_TO_CONNECT",254:"TIMEOUT",255:"UNKNOWN_ERROR"};class ki extends Error{constructor(){super("Port is not ready")}}const Ei=e=>"["+e.map(e=>((e,t=2)=>{let i=e.toString(16).toUpperCase();return i.startsWith("-")?"-0x"+i.substring(1).padStart(t,"0"):"0x"+i.padStart(t,"0")})(e)).join(", ")+"]";class Ii extends EventTarget{constructor(e,t){if(super(),this.port=e,this.logger=t,this.error=0,null===e.readable)throw new Error("Port is not readable");if(null===e.writable)throw new Error("Port is not writable")}async initialize(e=1e3){var t;if(this.logger.log("Initializing Improv Serial"),this._processInput(),await(t=1e3,new Promise(e=>setTimeout(e,t))),void 0===this._reader)throw new ki;try{await new Promise(async(t,i)=>{setTimeout(()=>i(new Error("Improv Wi-Fi Serial not detected")),e),await this.requestCurrentState(),t(void 0)}),await this.requestInfo()}catch(e){throw await this.close(),e}return this.info}async close(){this._reader&&await new Promise(e=>{this._reader.cancel(),this.addEventListener("disconnect",e,{once:!0})})}async requestCurrentState(){let e;try{await new Promise(async(t,i)=>{this.addEventListener("state-changed",t,{once:!0});e=this._sendRPCWithResponse(2,[]),e.catch(e=>{this.removeEventListener("state-changed",t),i(e)})})}catch(e){throw this._rpcFeedback=void 0,new Error(`Error fetching current state: ${e}`)}if(this.state!==yi.PROVISIONED)return void(this._rpcFeedback=void 0);const t=await e;this.nextUrl=t[0]}async requestInfo(e){const t=await this._sendRPCWithResponse(3,[],e);this.info={firmware:t[0],version:t[1],name:t[3],chipFamily:t[2]}}async provision(e,t,i){const n=new TextEncoder,o=n.encode(e),r=n.encode(t),a=[o.length,...o,r.length,...r],d=await this._sendRPCWithResponse(1,a,i);this.nextUrl=d[0]}async scan(){const e=(await this._sendRPCWithMultipleResponses(4,[])).map(([e,t,i])=>({name:e,rssi:parseInt(t),secured:"YES"===i}));return e.sort((e,t)=>e.name.toLocaleLowerCase().localeCompare(t.name.toLocaleLowerCase())),e}_sendRPC(e,t){this.writePacketToStream(vi.RPC,[e,t.length,...t])}async _sendRPCWithResponse(e,t,i){if(this._rpcFeedback)throw new Error("Only 1 RPC command that requires feedback can be active");return await this._awaitRPCResultWithTimeout(new Promise((i,n)=>{this._rpcFeedback={command:e,resolve:i,reject:n},this._sendRPC(e,t)}),i)}async _sendRPCWithMultipleResponses(e,t,i){if(this._rpcFeedback)throw new Error("Only 1 RPC command that requires feedback can be active");return await this._awaitRPCResultWithTimeout(new Promise((i,n)=>{this._rpcFeedback={command:e,resolve:i,reject:n,receivedData:[]},this._sendRPC(e,t)}),i)}async _awaitRPCResultWithTimeout(e,t){return t?await new Promise((i,n)=>{const o=setTimeout(()=>this._setError(254),t);e.finally(()=>clearTimeout(o)),e.then(i,n)}):await e}async _processInput(){this.logger.debug("Starting read loop"),this._reader=this.port.readable.getReader();try{let e,t=[],i=0;for(;;){const{value:n,done:o}=await this._reader.read();if(o)break;if(n&&0!==n.length)for(const o of n){if(!1===e){10===o&&(e=void 0);continue}if(!0===e){t.push(o),t.length===i&&(this._handleIncomingPacket(t),e=void 0,t=[]);continue}if(10===o){t=[];continue}if(t.push(o),9!==t.length)continue;if(e="IMPROV"===String.fromCharCode(...t.slice(0,6)),!e){t=[];continue}i=9+t[8]+1}}}catch(e){this.logger.error("Error while reading serial port",e)}finally{this._reader.releaseLock(),this._reader=void 0}this.logger.debug("Finished read loop"),this.dispatchEvent(new Event("disconnect"))}_handleIncomingPacket(e){const t=e.slice(6),i=t[0],n=t[1],o=t[2],r=t.slice(3,3+o);if(this.logger.debug("PROCESS",{version:i,packetType:n,packetLength:o,data:Ei(r)}),1!==i)return void this.logger.error("Received unsupported version",i);let a=t[3+o],d=0;for(let t=0;t<e.length-1;t++)d+=e[t];if(d&=255,d===a)if(n===vi.CURRENT_STATE)this.state=r[0],this.dispatchEvent(new CustomEvent("state-changed",{detail:this.state}));else if(n===vi.ERROR_STATE)this._setError(r[0]);else if(n===vi.RPC_RESULT){if(!this._rpcFeedback)return void this.logger.error("Received result while not waiting for one");const e=r[0];if(e!==this._rpcFeedback.command)return void this.logger.error(`Received result for command ${e} but expected ${this._rpcFeedback.command}`);const t=[],i=r[1];let n=2;for(;n<2+i;)t.push(String.fromCodePoint(...r.slice(n+1,n+r[n]+1))),n+=r[n]+1;"receivedData"in this._rpcFeedback?t.length>0?this._rpcFeedback.receivedData.push(t):(this._rpcFeedback.resolve(this._rpcFeedback.receivedData),this._rpcFeedback=void 0):(this._rpcFeedback.resolve(t),this._rpcFeedback=void 0)}else this.logger.error("Unable to handle packet",t);else this.logger.error(`Received invalid checksum ${a}. Expected ${d}`)}async writePacketToStream(e,t){const i=new Uint8Array([...xi,e,t.length,...t,0,0]);i[i.length-2]=255&i.reduce((e,t)=>e+t,0),i[i.length-1]=10,this.logger.debug("Writing to stream:",Ei(new Array(...i)));const n=this.port.writable.getWriter();await n.write(i);try{n.releaseLock()}catch(e){console.error("Ignoring release lock error",e)}}_setError(e){this.error=e,e>0&&this._rpcFeedback&&(this._rpcFeedback.reject(wi[e]||`UNKNOWN_ERROR (${e})`),this._rpcFeedback=void 0),this.dispatchEvent(new CustomEvent("error-changed",{detail:this.error}))}}const Si=e=>{let t=[192];for(const i of e)219==i?t=t.concat([219,221]):192==i?t=t.concat([219,220]):t.push(i);return t.push(192),t},Ci=e=>{const t=[];for(let i=0;i<e.length;i++){const n=e.charCodeAt(i);n<=255&&t.push(n)}return t},Ri=e=>"["+e.map(e=>Ti(e)).join(", ")+"]",Ti=(e,t=2)=>{const i=e.toString(16).toUpperCase();return i.startsWith("-")?"-0x"+i.substring(1).padStart(t,"0"):"0x"+i.padStart(t,"0")},Ai=e=>new Promise(t=>setTimeout(t,e)),Oi={18:"256KB",19:"512KB",20:"1MB",21:"2MB",22:"4MB",23:"8MB",24:"16MB",25:"32MB",26:"64MB",27:"128MB",28:"256MB",32:"64MB",33:"128MB",34:"256MB",50:"256KB",51:"512KB",52:"1MB",53:"2MB",54:"4MB",55:"8MB",56:"16MB",57:"32MB",58:"64MB"},Fi=115200,Li=1343410176,Bi=Ci(" UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU"),zi=33382,Di=50,$i=12882,Ni=12883,Pi=12994,Mi=12995,Ui=12997,Hi=12998,Vi=207969,Wi=12914,Xi=12916,qi=12917,Yi=12928,Gi=12849,ji={5:{name:"ESP32-C3",family:Mi},9:{name:"ESP32-S3",family:Ni},12:{name:"ESP32-C2",family:Pi},13:{name:"ESP32-C6",family:Hi},16:{name:"ESP32-H2",family:Wi},18:{name:"ESP32-P4",family:Yi},20:{name:"ESP32-C61",family:Vi},23:{name:"ESP32-C5",family:Ui},25:{name:"ESP32-H21",family:qi},28:{name:"ESP32-H4",family:Xi},32:{name:"ESP32-S31",family:Gi}},Ki={4293968129:{name:"ESP8266",family:zi},15736195:{name:"ESP32",family:Di},1990:{name:"ESP32-S2",family:$i}},Zi=3e3,Qi=15e4,Ji=100,en=(e,t)=>{const i=Math.floor(e*(t/486));return i<Zi?Zi:i},tn=e=>{switch(e){case Di:return{regBase:1072963584,baseFuse:1073061888,macFuse:1073061888,usrOffs:28,usr1Offs:32,usr2Offs:36,mosiDlenOffs:40,misoDlenOffs:44,w0Offs:128,uartDateReg:1610612856,flashOffs:4096};case $i:return{regBase:1061167104,baseFuse:1061265408,macFuse:1061265476,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612856,flashOffs:4096};case Ni:return{regBase:1610620928,usrOffs:24,baseFuse:1610641408,macFuse:1610641476,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612864,flashOffs:0};case zi:return{regBase:1610613248,usrOffs:28,baseFuse:1072693328,macFuse:1072693328,usr1Offs:32,usr2Offs:36,mosiDlenOffs:-1,misoDlenOffs:-1,w0Offs:64,uartDateReg:1610612856,flashOffs:0};case Pi:case Mi:return{regBase:1610620928,baseFuse:1610647552,macFuse:1610647620,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case Ui:return{regBase:1610625024,baseFuse:1611352064,macFuse:1611352132,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:8192};case Hi:return{regBase:1610625024,baseFuse:1611335680,macFuse:1611335748,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case Vi:return{regBase:1610625024,baseFuse:1611352064,macFuse:1611352132,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case Wi:return{regBase:1610625024,baseFuse:1611335680,macFuse:1611335748,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case Xi:return{regBase:1611239424,baseFuse:1611339776,macFuse:1611339844,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610686588,flashOffs:8192};case qi:return{regBase:1610625024,baseFuse:1611350016,macFuse:1611350084,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case Yi:return{regBase:1342754816,baseFuse:Li,macFuse:1343410244,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1343004812,flashOffs:8192};case Gi:return{regBase:542113792,baseFuse:544296960,macFuse:544297028,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:540582028,flashOffs:8192};default:return{regBase:-1,baseFuse:-1,macFuse:-1,usrOffs:-1,usr1Offs:-1,usr2Offs:-1,mosiDlenOffs:-1,misoDlenOffs:-1,w0Offs:-1,uartDateReg:-1,flashOffs:-1}}};class nn extends Error{constructor(e){super(e),this.name="SlipReadError"}}const on=async(e,t)=>{let i;return e==Xi||e==qi||e==Gi?null:(e==Di?i=await import("./esp32-CijhsJH1.js"):e==$i?i=await import("./esp32s2-IiDBtXxo.js"):e==Ni?i=await import("./esp32s3-6yv5yxum.js"):e==zi?i=await import("./esp8266-CUwxJpGa.js"):e==Pi?i=await import("./esp32c2-C17SM4gO.js"):e==Mi?i=await import("./esp32c3-DxRGijbg.js"):e==Ui?i=await import("./esp32c5-3mDOIGa4.js"):e==Hi?i=await import("./esp32c6-h6U0SQTm.js"):e==Vi?i=await import("./esp32c61-BKtexhPZ.js"):e==Wi?i=await import("./esp32h2-RtuWSEmP.js"):e==Yi&&(i=null!=t&&t>=300?await import("./esp32p4r3-CpHBYEwI.js"):await import("./esp32p4-5nkIjxqJ.js")),{...i,text:Ci(atob(i.text)),data:Ci(atob(i.data))})};function rn(e){let t=e.length;for(;--t>=0;)e[t]=0}const an=256,dn=286,sn=30,ln=15,cn=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]),hn=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]),mn=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),pn=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),un=new Array(576);rn(un);const fn=new Array(60);rn(fn);const gn=new Array(512);rn(gn);const bn=new Array(256);rn(bn);const _n=new Array(29);rn(_n);const xn=new Array(sn);function vn(e,t,i,n,o){this.static_tree=e,this.extra_bits=t,this.extra_base=i,this.elems=n,this.max_length=o,this.has_stree=e&&e.length}let yn,wn,kn;function En(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}rn(xn);const In=e=>e<256?gn[e]:gn[256+(e>>>7)],Sn=(e,t)=>{e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255},Cn=(e,t,i)=>{e.bi_valid>16-i?(e.bi_buf|=t<<e.bi_valid&65535,Sn(e,e.bi_buf),e.bi_buf=t>>16-e.bi_valid,e.bi_valid+=i-16):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=i)},Rn=(e,t,i)=>{Cn(e,i[2*t],i[2*t+1])},Tn=(e,t)=>{let i=0;do{i|=1&e,e>>>=1,i<<=1}while(--t>0);return i>>>1},An=(e,t,i)=>{const n=new Array(16);let o,r,a=0;for(o=1;o<=ln;o++)a=a+i[o-1]<<1,n[o]=a;for(r=0;r<=t;r++){let t=e[2*r+1];0!==t&&(e[2*r]=Tn(n[t]++,t))}},On=e=>{let t;for(t=0;t<dn;t++)e.dyn_ltree[2*t]=0;for(t=0;t<sn;t++)e.dyn_dtree[2*t]=0;for(t=0;t<19;t++)e.bl_tree[2*t]=0;e.dyn_ltree[512]=1,e.opt_len=e.static_len=0,e.sym_next=e.matches=0},Fn=e=>{e.bi_valid>8?Sn(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0},Ln=(e,t,i,n)=>{const o=2*t,r=2*i;return e[o]<e[r]||e[o]===e[r]&&n[t]<=n[i]},Bn=(e,t,i)=>{const n=e.heap[i];let o=i<<1;for(;o<=e.heap_len&&(o<e.heap_len&&Ln(t,e.heap[o+1],e.heap[o],e.depth)&&o++,!Ln(t,n,e.heap[o],e.depth));)e.heap[i]=e.heap[o],i=o,o<<=1;e.heap[i]=n},zn=(e,t,i)=>{let n,o,r,a,d=0;if(0!==e.sym_next)do{n=255&e.pending_buf[e.sym_buf+d++],n+=(255&e.pending_buf[e.sym_buf+d++])<<8,o=e.pending_buf[e.sym_buf+d++],0===n?Rn(e,o,t):(r=bn[o],Rn(e,r+an+1,t),a=cn[r],0!==a&&(o-=_n[r],Cn(e,o,a)),n--,r=In(n),Rn(e,r,i),a=hn[r],0!==a&&(n-=xn[r],Cn(e,n,a)))}while(d<e.sym_next);Rn(e,256,t)},Dn=(e,t)=>{const i=t.dyn_tree,n=t.stat_desc.static_tree,o=t.stat_desc.has_stree,r=t.stat_desc.elems;let a,d,s,l=-1;for(e.heap_len=0,e.heap_max=573,a=0;a<r;a++)0!==i[2*a]?(e.heap[++e.heap_len]=l=a,e.depth[a]=0):i[2*a+1]=0;for(;e.heap_len<2;)s=e.heap[++e.heap_len]=l<2?++l:0,i[2*s]=1,e.depth[s]=0,e.opt_len--,o&&(e.static_len-=n[2*s+1]);for(t.max_code=l,a=e.heap_len>>1;a>=1;a--)Bn(e,i,a);s=r;do{a=e.heap[1],e.heap[1]=e.heap[e.heap_len--],Bn(e,i,1),d=e.heap[1],e.heap[--e.heap_max]=a,e.heap[--e.heap_max]=d,i[2*s]=i[2*a]+i[2*d],e.depth[s]=(e.depth[a]>=e.depth[d]?e.depth[a]:e.depth[d])+1,i[2*a+1]=i[2*d+1]=s,e.heap[1]=s++,Bn(e,i,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],((e,t)=>{const i=t.dyn_tree,n=t.max_code,o=t.stat_desc.static_tree,r=t.stat_desc.has_stree,a=t.stat_desc.extra_bits,d=t.stat_desc.extra_base,s=t.stat_desc.max_length;let l,c,h,m,p,u,f=0;for(m=0;m<=ln;m++)e.bl_count[m]=0;for(i[2*e.heap[e.heap_max]+1]=0,l=e.heap_max+1;l<573;l++)c=e.heap[l],m=i[2*i[2*c+1]+1]+1,m>s&&(m=s,f++),i[2*c+1]=m,c>n||(e.bl_count[m]++,p=0,c>=d&&(p=a[c-d]),u=i[2*c],e.opt_len+=u*(m+p),r&&(e.static_len+=u*(o[2*c+1]+p)));if(0!==f){do{for(m=s-1;0===e.bl_count[m];)m--;e.bl_count[m]--,e.bl_count[m+1]+=2,e.bl_count[s]--,f-=2}while(f>0);for(m=s;0!==m;m--)for(c=e.bl_count[m];0!==c;)h=e.heap[--l],h>n||(i[2*h+1]!==m&&(e.opt_len+=(m-i[2*h+1])*i[2*h],i[2*h+1]=m),c--)}})(e,t),An(i,l,e.bl_count)},$n=(e,t,i)=>{let n,o,r=-1,a=t[1],d=0,s=7,l=4;for(0===a&&(s=138,l=3),t[2*(i+1)+1]=65535,n=0;n<=i;n++)o=a,a=t[2*(n+1)+1],++d<s&&o===a||(d<l?e.bl_tree[2*o]+=d:0!==o?(o!==r&&e.bl_tree[2*o]++,e.bl_tree[32]++):d<=10?e.bl_tree[34]++:e.bl_tree[36]++,d=0,r=o,0===a?(s=138,l=3):o===a?(s=6,l=3):(s=7,l=4))},Nn=(e,t,i)=>{let n,o,r=-1,a=t[1],d=0,s=7,l=4;for(0===a&&(s=138,l=3),n=0;n<=i;n++)if(o=a,a=t[2*(n+1)+1],!(++d<s&&o===a)){if(d<l)do{Rn(e,o,e.bl_tree)}while(0!==--d);else 0!==o?(o!==r&&(Rn(e,o,e.bl_tree),d--),Rn(e,16,e.bl_tree),Cn(e,d-3,2)):d<=10?(Rn(e,17,e.bl_tree),Cn(e,d-3,3)):(Rn(e,18,e.bl_tree),Cn(e,d-11,7));d=0,r=o,0===a?(s=138,l=3):o===a?(s=6,l=3):(s=7,l=4)}};let Pn=!1;const Mn=(e,t,i,n)=>{Cn(e,0+(n?1:0),3),Fn(e),Sn(e,i),Sn(e,~i),i&&e.pending_buf.set(e.window.subarray(t,t+i),e.pending),e.pending+=i};var Un=e=>{Pn||((()=>{let e,t,i,n,o;const r=new Array(16);for(i=0,n=0;n<28;n++)for(_n[n]=i,e=0;e<1<<cn[n];e++)bn[i++]=n;for(bn[i-1]=n,o=0,n=0;n<16;n++)for(xn[n]=o,e=0;e<1<<hn[n];e++)gn[o++]=n;for(o>>=7;n<sn;n++)for(xn[n]=o<<7,e=0;e<1<<hn[n]-7;e++)gn[256+o++]=n;for(t=0;t<=ln;t++)r[t]=0;for(e=0;e<=143;)un[2*e+1]=8,e++,r[8]++;for(;e<=255;)un[2*e+1]=9,e++,r[9]++;for(;e<=279;)un[2*e+1]=7,e++,r[7]++;for(;e<=287;)un[2*e+1]=8,e++,r[8]++;for(An(un,287,r),e=0;e<sn;e++)fn[2*e+1]=5,fn[2*e]=Tn(e,5);yn=new vn(un,cn,257,dn,ln),wn=new vn(fn,hn,0,sn,ln),kn=new vn(new Array(0),mn,0,19,7)})(),Pn=!0),e.l_desc=new En(e.dyn_ltree,yn),e.d_desc=new En(e.dyn_dtree,wn),e.bl_desc=new En(e.bl_tree,kn),e.bi_buf=0,e.bi_valid=0,On(e)},Hn=(e,t,i,n)=>{let o,r,a=0;e.level>0?(2===e.strm.data_type&&(e.strm.data_type=(e=>{let t,i=4093624447;for(t=0;t<=31;t++,i>>>=1)if(1&i&&0!==e.dyn_ltree[2*t])return 0;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return 1;for(t=32;t<an;t++)if(0!==e.dyn_ltree[2*t])return 1;return 0})(e)),Dn(e,e.l_desc),Dn(e,e.d_desc),a=(e=>{let t;for($n(e,e.dyn_ltree,e.l_desc.max_code),$n(e,e.dyn_dtree,e.d_desc.max_code),Dn(e,e.bl_desc),t=18;t>=3&&0===e.bl_tree[2*pn[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t})(e),o=e.opt_len+3+7>>>3,r=e.static_len+3+7>>>3,r<=o&&(o=r)):o=r=i+5,i+4<=o&&-1!==t?Mn(e,t,i,n):4===e.strategy||r===o?(Cn(e,2+(n?1:0),3),zn(e,un,fn)):(Cn(e,4+(n?1:0),3),((e,t,i,n)=>{let o;for(Cn(e,t-257,5),Cn(e,i-1,5),Cn(e,n-4,4),o=0;o<n;o++)Cn(e,e.bl_tree[2*pn[o]+1],3);Nn(e,e.dyn_ltree,t-1),Nn(e,e.dyn_dtree,i-1)})(e,e.l_desc.max_code+1,e.d_desc.max_code+1,a+1),zn(e,e.dyn_ltree,e.dyn_dtree)),On(e),n&&Fn(e)},Vn=(e,t,i)=>(e.pending_buf[e.sym_buf+e.sym_next++]=t,e.pending_buf[e.sym_buf+e.sym_next++]=t>>8,e.pending_buf[e.sym_buf+e.sym_next++]=i,0===t?e.dyn_ltree[2*i]++:(e.matches++,t--,e.dyn_ltree[2*(bn[i]+an+1)]++,e.dyn_dtree[2*In(t)]++),e.sym_next===e.sym_end),Wn=e=>{Cn(e,2,3),Rn(e,256,un),(e=>{16===e.bi_valid?(Sn(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)})(e)},Xn={_tr_init:Un,_tr_stored_block:Mn,_tr_flush_block:Hn,_tr_tally:Vn,_tr_align:Wn};var qn=(e,t,i,n)=>{let o=65535&e,r=e>>>16&65535,a=0;for(;0!==i;){a=i>2e3?2e3:i,i-=a;do{o=o+t[n++]|0,r=r+o|0}while(--a);o%=65521,r%=65521}return o|r<<16};const Yn=new Uint32Array((()=>{let e,t=[];for(var i=0;i<256;i++){e=i;for(var n=0;n<8;n++)e=1&e?3988292384^e>>>1:e>>>1;t[i]=e}return t})());var Gn=(e,t,i,n)=>{const o=Yn,r=n+i;e^=-1;for(let i=n;i<r;i++)e=e>>>8^o[255&(e^t[i])];return-1^e},jn={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"},Kn={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_OK:0,Z_STREAM_END:1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,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:Zn,_tr_stored_block:Qn,_tr_flush_block:Jn,_tr_tally:eo,_tr_align:to}=Xn,{Z_NO_FLUSH:io,Z_PARTIAL_FLUSH:no,Z_FULL_FLUSH:oo,Z_FINISH:ro,Z_BLOCK:ao,Z_OK:so,Z_STREAM_END:lo,Z_STREAM_ERROR:co,Z_DATA_ERROR:ho,Z_BUF_ERROR:mo,Z_DEFAULT_COMPRESSION:po,Z_FILTERED:uo,Z_HUFFMAN_ONLY:fo,Z_RLE:go,Z_FIXED:bo,Z_DEFAULT_STRATEGY:_o,Z_UNKNOWN:xo,Z_DEFLATED:vo}=Kn,yo=258,wo=262,ko=42,Eo=113,Io=666,So=(e,t)=>(e.msg=jn[t],t),Co=e=>2*e-(e>4?9:0),Ro=e=>{let t=e.length;for(;--t>=0;)e[t]=0},To=e=>{let t,i,n,o=e.w_size;t=e.hash_size,n=t;do{i=e.head[--n],e.head[n]=i>=o?i-o:0}while(--t);t=o,n=t;do{i=e.prev[--n],e.prev[n]=i>=o?i-o:0}while(--t)};let Ao=(e,t,i)=>(t<<e.hash_shift^i)&e.hash_mask;const Oo=e=>{const t=e.state;let i=t.pending;i>e.avail_out&&(i=e.avail_out),0!==i&&(e.output.set(t.pending_buf.subarray(t.pending_out,t.pending_out+i),e.next_out),e.next_out+=i,t.pending_out+=i,e.total_out+=i,e.avail_out-=i,t.pending-=i,0===t.pending&&(t.pending_out=0))},Fo=(e,t)=>{Jn(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,Oo(e.strm)},Lo=(e,t)=>{e.pending_buf[e.pending++]=t},Bo=(e,t)=>{e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t},zo=(e,t,i,n)=>{let o=e.avail_in;return o>n&&(o=n),0===o?0:(e.avail_in-=o,t.set(e.input.subarray(e.next_in,e.next_in+o),i),1===e.state.wrap?e.adler=qn(e.adler,t,o,i):2===e.state.wrap&&(e.adler=Gn(e.adler,t,o,i)),e.next_in+=o,e.total_in+=o,o)},Do=(e,t)=>{let i,n,o=e.max_chain_length,r=e.strstart,a=e.prev_length,d=e.nice_match;const s=e.strstart>e.w_size-wo?e.strstart-(e.w_size-wo):0,l=e.window,c=e.w_mask,h=e.prev,m=e.strstart+yo;let p=l[r+a-1],u=l[r+a];e.prev_length>=e.good_match&&(o>>=2),d>e.lookahead&&(d=e.lookahead);do{if(i=t,l[i+a]===u&&l[i+a-1]===p&&l[i]===l[r]&&l[++i]===l[r+1]){r+=2,i++;do{}while(l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&r<m);if(n=yo-(m-r),r=m-yo,n>a){if(e.match_start=t,a=n,n>=d)break;p=l[r+a-1],u=l[r+a]}}}while((t=h[t&c])>s&&0!==--o);return a<=e.lookahead?a:e.lookahead},$o=e=>{const t=e.w_size;let i,n,o;do{if(n=e.window_size-e.lookahead-e.strstart,e.strstart>=t+(t-wo)&&(e.window.set(e.window.subarray(t,t+t-n),0),e.match_start-=t,e.strstart-=t,e.block_start-=t,e.insert>e.strstart&&(e.insert=e.strstart),To(e),n+=t),0===e.strm.avail_in)break;if(i=zo(e.strm,e.window,e.strstart+e.lookahead,n),e.lookahead+=i,e.lookahead+e.insert>=3)for(o=e.strstart-e.insert,e.ins_h=e.window[o],e.ins_h=Ao(e,e.ins_h,e.window[o+1]);e.insert&&(e.ins_h=Ao(e,e.ins_h,e.window[o+3-1]),e.prev[o&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=o,o++,e.insert--,!(e.lookahead+e.insert<3)););}while(e.lookahead<wo&&0!==e.strm.avail_in)},No=(e,t)=>{let i,n,o,r=e.pending_buf_size-5>e.w_size?e.w_size:e.pending_buf_size-5,a=0,d=e.strm.avail_in;do{if(i=65535,o=e.bi_valid+42>>3,e.strm.avail_out<o)break;if(o=e.strm.avail_out-o,n=e.strstart-e.block_start,i>n+e.strm.avail_in&&(i=n+e.strm.avail_in),i>o&&(i=o),i<r&&(0===i&&t!==ro||t===io||i!==n+e.strm.avail_in))break;a=t===ro&&i===n+e.strm.avail_in?1:0,Qn(e,0,0,a),e.pending_buf[e.pending-4]=i,e.pending_buf[e.pending-3]=i>>8,e.pending_buf[e.pending-2]=~i,e.pending_buf[e.pending-1]=~i>>8,Oo(e.strm),n&&(n>i&&(n=i),e.strm.output.set(e.window.subarray(e.block_start,e.block_start+n),e.strm.next_out),e.strm.next_out+=n,e.strm.avail_out-=n,e.strm.total_out+=n,e.block_start+=n,i-=n),i&&(zo(e.strm,e.strm.output,e.strm.next_out,i),e.strm.next_out+=i,e.strm.avail_out-=i,e.strm.total_out+=i)}while(0===a);return d-=e.strm.avail_in,d&&(d>=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<=d&&(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-d,e.strm.next_in),e.strstart),e.strstart+=d,e.insert+=d>e.w_size-e.insert?e.w_size-e.insert:d),e.block_start=e.strstart),e.high_water<e.strstart&&(e.high_water=e.strstart),a?4:t!==io&&t!==ro&&0===e.strm.avail_in&&e.strstart===e.block_start?2:(o=e.window_size-e.strstart,e.strm.avail_in>o&&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++,o+=e.w_size,e.insert>e.strstart&&(e.insert=e.strstart)),o>e.strm.avail_in&&(o=e.strm.avail_in),o&&(zo(e.strm,e.window,e.strstart,o),e.strstart+=o,e.insert+=o>e.w_size-e.insert?e.w_size-e.insert:o),e.high_water<e.strstart&&(e.high_water=e.strstart),o=e.bi_valid+42>>3,o=e.pending_buf_size-o>65535?65535:e.pending_buf_size-o,r=o>e.w_size?e.w_size:o,n=e.strstart-e.block_start,(n>=r||(n||t===ro)&&t!==io&&0===e.strm.avail_in&&n<=o)&&(i=n>o?o:n,a=t===ro&&0===e.strm.avail_in&&i===n?1:0,Qn(e,e.block_start,i,a),e.block_start+=i,Oo(e.strm)),a?3:1)},Po=(e,t)=>{let i,n;for(;;){if(e.lookahead<wo){if($o(e),e.lookahead<wo&&t===io)return 1;if(0===e.lookahead)break}if(i=0,e.lookahead>=3&&(e.ins_h=Ao(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!==i&&e.strstart-i<=e.w_size-wo&&(e.match_length=Do(e,i)),e.match_length>=3)if(n=eo(e,e.strstart-e.match_start,e.match_length-3),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=3){e.match_length--;do{e.strstart++,e.ins_h=Ao(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart}while(0!==--e.match_length);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=Ao(e,e.ins_h,e.window[e.strstart+1]);else n=eo(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(n&&(Fo(e,!1),0===e.strm.avail_out))return 1}return e.insert=e.strstart<2?e.strstart:2,t===ro?(Fo(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(Fo(e,!1),0===e.strm.avail_out)?1:2},Mo=(e,t)=>{let i,n,o;for(;;){if(e.lookahead<wo){if($o(e),e.lookahead<wo&&t===io)return 1;if(0===e.lookahead)break}if(i=0,e.lookahead>=3&&(e.ins_h=Ao(e,e.ins_h,e.window[e.strstart+3-1]),i=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=2,0!==i&&e.prev_length<e.max_lazy_match&&e.strstart-i<=e.w_size-wo&&(e.match_length=Do(e,i),e.match_length<=5&&(e.strategy===uo||3===e.match_length&&e.strstart-e.match_start>4096)&&(e.match_length=2)),e.prev_length>=3&&e.match_length<=e.prev_length){o=e.strstart+e.lookahead-3,n=eo(e,e.strstart-1-e.prev_match,e.prev_length-3),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=o&&(e.ins_h=Ao(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart)}while(0!==--e.prev_length);if(e.match_available=0,e.match_length=2,e.strstart++,n&&(Fo(e,!1),0===e.strm.avail_out))return 1}else if(e.match_available){if(n=eo(e,0,e.window[e.strstart-1]),n&&Fo(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return 1}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(n=eo(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<2?e.strstart:2,t===ro?(Fo(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(Fo(e,!1),0===e.strm.avail_out)?1:2};function Uo(e,t,i,n,o){this.good_length=e,this.max_lazy=t,this.nice_length=i,this.max_chain=n,this.func=o}const Ho=[new Uo(0,0,0,0,No),new Uo(4,4,8,4,Po),new Uo(4,5,16,8,Po),new Uo(4,6,32,32,Po),new Uo(4,4,16,16,Mo),new Uo(8,16,32,32,Mo),new Uo(8,16,128,128,Mo),new Uo(8,32,128,256,Mo),new Uo(32,128,258,1024,Mo),new Uo(32,258,258,4096,Mo)];function Vo(){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=vo,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(1146),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),Ro(this.dyn_ltree),Ro(this.dyn_dtree),Ro(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),Ro(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),Ro(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 Wo=e=>{if(!e)return 1;const t=e.state;return!t||t.strm!==e||t.status!==ko&&57!==t.status&&69!==t.status&&73!==t.status&&91!==t.status&&103!==t.status&&t.status!==Eo&&t.status!==Io?1:0},Xo=e=>{if(Wo(e))return So(e,co);e.total_in=e.total_out=0,e.data_type=xo;const t=e.state;return t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=2===t.wrap?57:t.wrap?ko:Eo,e.adler=2===t.wrap?0:1,t.last_flush=-2,Zn(t),so},qo=e=>{const t=Xo(e);return t===so&&(e=>{e.window_size=2*e.w_size,Ro(e.head),e.max_lazy_match=Ho[e.level].max_lazy,e.good_match=Ho[e.level].good_length,e.nice_match=Ho[e.level].nice_length,e.max_chain_length=Ho[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=2,e.match_available=0,e.ins_h=0})(e.state),t},Yo=(e,t,i,n,o,r)=>{if(!e)return co;let a=1;if(t===po&&(t=6),n<0?(a=0,n=-n):n>15&&(a=2,n-=16),o<1||o>9||i!==vo||n<8||n>15||t<0||t>9||r<0||r>bo||8===n&&1!==a)return So(e,co);8===n&&(n=9);const d=new Vo;return e.state=d,d.strm=e,d.status=ko,d.wrap=a,d.gzhead=null,d.w_bits=n,d.w_size=1<<d.w_bits,d.w_mask=d.w_size-1,d.hash_bits=o+7,d.hash_size=1<<d.hash_bits,d.hash_mask=d.hash_size-1,d.hash_shift=~~((d.hash_bits+3-1)/3),d.window=new Uint8Array(2*d.w_size),d.head=new Uint16Array(d.hash_size),d.prev=new Uint16Array(d.w_size),d.lit_bufsize=1<<o+6,d.pending_buf_size=4*d.lit_bufsize,d.pending_buf=new Uint8Array(d.pending_buf_size),d.sym_buf=d.lit_bufsize,d.sym_end=3*(d.lit_bufsize-1),d.level=t,d.strategy=r,d.method=i,qo(e)};var Go=(e,t)=>{if(Wo(e)||t>ao||t<0)return e?So(e,co):co;const i=e.state;if(!e.output||0!==e.avail_in&&!e.input||i.status===Io&&t!==ro)return So(e,0===e.avail_out?mo:co);const n=i.last_flush;if(i.last_flush=t,0!==i.pending){if(Oo(e),0===e.avail_out)return i.last_flush=-1,so}else if(0===e.avail_in&&Co(t)<=Co(n)&&t!==ro)return So(e,mo);if(i.status===Io&&0!==e.avail_in)return So(e,mo);if(i.status===ko&&0===i.wrap&&(i.status=Eo),i.status===ko){let t=vo+(i.w_bits-8<<4)<<8,n=-1;if(n=i.strategy>=fo||i.level<2?0:i.level<6?1:6===i.level?2:3,t|=n<<6,0!==i.strstart&&(t|=32),t+=31-t%31,Bo(i,t),0!==i.strstart&&(Bo(i,e.adler>>>16),Bo(i,65535&e.adler)),e.adler=1,i.status=Eo,Oo(e),0!==i.pending)return i.last_flush=-1,so}if(57===i.status)if(e.adler=0,Lo(i,31),Lo(i,139),Lo(i,8),i.gzhead)Lo(i,(i.gzhead.text?1:0)+(i.gzhead.hcrc?2:0)+(i.gzhead.extra?4:0)+(i.gzhead.name?8:0)+(i.gzhead.comment?16:0)),Lo(i,255&i.gzhead.time),Lo(i,i.gzhead.time>>8&255),Lo(i,i.gzhead.time>>16&255),Lo(i,i.gzhead.time>>24&255),Lo(i,9===i.level?2:i.strategy>=fo||i.level<2?4:0),Lo(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(Lo(i,255&i.gzhead.extra.length),Lo(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(e.adler=Gn(e.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=69;else if(Lo(i,0),Lo(i,0),Lo(i,0),Lo(i,0),Lo(i,0),Lo(i,9===i.level?2:i.strategy>=fo||i.level<2?4:0),Lo(i,3),i.status=Eo,Oo(e),0!==i.pending)return i.last_flush=-1,so;if(69===i.status){if(i.gzhead.extra){let t=i.pending,n=(65535&i.gzhead.extra.length)-i.gzindex;for(;i.pending+n>i.pending_buf_size;){let o=i.pending_buf_size-i.pending;if(i.pending_buf.set(i.gzhead.extra.subarray(i.gzindex,i.gzindex+o),i.pending),i.pending=i.pending_buf_size,i.gzhead.hcrc&&i.pending>t&&(e.adler=Gn(e.adler,i.pending_buf,i.pending-t,t)),i.gzindex+=o,Oo(e),0!==i.pending)return i.last_flush=-1,so;t=0,n-=o}let o=new Uint8Array(i.gzhead.extra);i.pending_buf.set(o.subarray(i.gzindex,i.gzindex+n),i.pending),i.pending+=n,i.gzhead.hcrc&&i.pending>t&&(e.adler=Gn(e.adler,i.pending_buf,i.pending-t,t)),i.gzindex=0}i.status=73}if(73===i.status){if(i.gzhead.name){let t,n=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>n&&(e.adler=Gn(e.adler,i.pending_buf,i.pending-n,n)),Oo(e),0!==i.pending)return i.last_flush=-1,so;n=0}t=i.gzindex<i.gzhead.name.length?255&i.gzhead.name.charCodeAt(i.gzindex++):0,Lo(i,t)}while(0!==t);i.gzhead.hcrc&&i.pending>n&&(e.adler=Gn(e.adler,i.pending_buf,i.pending-n,n)),i.gzindex=0}i.status=91}if(91===i.status){if(i.gzhead.comment){let t,n=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>n&&(e.adler=Gn(e.adler,i.pending_buf,i.pending-n,n)),Oo(e),0!==i.pending)return i.last_flush=-1,so;n=0}t=i.gzindex<i.gzhead.comment.length?255&i.gzhead.comment.charCodeAt(i.gzindex++):0,Lo(i,t)}while(0!==t);i.gzhead.hcrc&&i.pending>n&&(e.adler=Gn(e.adler,i.pending_buf,i.pending-n,n))}i.status=103}if(103===i.status){if(i.gzhead.hcrc){if(i.pending+2>i.pending_buf_size&&(Oo(e),0!==i.pending))return i.last_flush=-1,so;Lo(i,255&e.adler),Lo(i,e.adler>>8&255),e.adler=0}if(i.status=Eo,Oo(e),0!==i.pending)return i.last_flush=-1,so}if(0!==e.avail_in||0!==i.lookahead||t!==io&&i.status!==Io){let n=0===i.level?No(i,t):i.strategy===fo?((e,t)=>{let i;for(;;){if(0===e.lookahead&&($o(e),0===e.lookahead)){if(t===io)return 1;break}if(e.match_length=0,i=eo(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,i&&(Fo(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===ro?(Fo(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(Fo(e,!1),0===e.strm.avail_out)?1:2})(i,t):i.strategy===go?((e,t)=>{let i,n,o,r;const a=e.window;for(;;){if(e.lookahead<=yo){if($o(e),e.lookahead<=yo&&t===io)return 1;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=3&&e.strstart>0&&(o=e.strstart-1,n=a[o],n===a[++o]&&n===a[++o]&&n===a[++o])){r=e.strstart+yo;do{}while(n===a[++o]&&n===a[++o]&&n===a[++o]&&n===a[++o]&&n===a[++o]&&n===a[++o]&&n===a[++o]&&n===a[++o]&&o<r);e.match_length=yo-(r-o),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=3?(i=eo(e,1,e.match_length-3),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(i=eo(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),i&&(Fo(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===ro?(Fo(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(Fo(e,!1),0===e.strm.avail_out)?1:2})(i,t):Ho[i.level].func(i,t);if(3!==n&&4!==n||(i.status=Io),1===n||3===n)return 0===e.avail_out&&(i.last_flush=-1),so;if(2===n&&(t===no?to(i):t!==ao&&(Qn(i,0,0,!1),t===oo&&(Ro(i.head),0===i.lookahead&&(i.strstart=0,i.block_start=0,i.insert=0))),Oo(e),0===e.avail_out))return i.last_flush=-1,so}return t!==ro?so:i.wrap<=0?lo:(2===i.wrap?(Lo(i,255&e.adler),Lo(i,e.adler>>8&255),Lo(i,e.adler>>16&255),Lo(i,e.adler>>24&255),Lo(i,255&e.total_in),Lo(i,e.total_in>>8&255),Lo(i,e.total_in>>16&255),Lo(i,e.total_in>>24&255)):(Bo(i,e.adler>>>16),Bo(i,65535&e.adler)),Oo(e),i.wrap>0&&(i.wrap=-i.wrap),0!==i.pending?so:lo)},jo=(e,t)=>{let i=t.length;if(Wo(e))return co;const n=e.state,o=n.wrap;if(2===o||1===o&&n.status!==ko||n.lookahead)return co;if(1===o&&(e.adler=qn(e.adler,t,i,0)),n.wrap=0,i>=n.w_size){0===o&&(Ro(n.head),n.strstart=0,n.block_start=0,n.insert=0);let e=new Uint8Array(n.w_size);e.set(t.subarray(i-n.w_size,i),0),t=e,i=n.w_size}const r=e.avail_in,a=e.next_in,d=e.input;for(e.avail_in=i,e.next_in=0,e.input=t,$o(n);n.lookahead>=3;){let e=n.strstart,t=n.lookahead-2;do{n.ins_h=Ao(n,n.ins_h,n.window[e+3-1]),n.prev[e&n.w_mask]=n.head[n.ins_h],n.head[n.ins_h]=e,e++}while(--t);n.strstart=e,n.lookahead=2,$o(n)}return n.strstart+=n.lookahead,n.block_start=n.strstart,n.insert=n.lookahead,n.lookahead=0,n.match_length=n.prev_length=2,n.match_available=0,e.next_in=a,e.input=d,e.avail_in=r,n.wrap=o,so},Ko={deflateInit:(e,t)=>Yo(e,t,vo,15,8,_o),deflateInit2:Yo,deflateReset:qo,deflateResetKeep:Xo,deflateSetHeader:(e,t)=>Wo(e)||2!==e.state.wrap?co:(e.state.gzhead=t,so),deflate:Go,deflateEnd:e=>{if(Wo(e))return co;const t=e.state.status;return e.state=null,t===Eo?So(e,ho):so},deflateSetDictionary:jo,deflateInfo:"pako deflate (from Nodeca project)"};const Zo=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var Qo=function(e){const t=Array.prototype.slice.call(arguments,1);for(;t.length;){const i=t.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(const t in i)Zo(i,t)&&(e[t]=i[t])}}return e},Jo=e=>{let t=0;for(let i=0,n=e.length;i<n;i++)t+=e[i].length;const i=new Uint8Array(t);for(let t=0,n=0,o=e.length;t<o;t++){let o=e[t];i.set(o,n),n+=o.length}return i};let er=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){er=!1}const tr=new Uint8Array(256);for(let e=0;e<256;e++)tr[e]=e>=252?6:e>=248?5:e>=240?4:e>=224?3:e>=192?2:1;tr[254]=tr[254]=1;var ir=e=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(e);let t,i,n,o,r,a=e.length,d=0;for(o=0;o<a;o++)i=e.charCodeAt(o),55296==(64512&i)&&o+1<a&&(n=e.charCodeAt(o+1),56320==(64512&n)&&(i=65536+(i-55296<<10)+(n-56320),o++)),d+=i<128?1:i<2048?2:i<65536?3:4;for(t=new Uint8Array(d),r=0,o=0;r<d;o++)i=e.charCodeAt(o),55296==(64512&i)&&o+1<a&&(n=e.charCodeAt(o+1),56320==(64512&n)&&(i=65536+(i-55296<<10)+(n-56320),o++)),i<128?t[r++]=i:i<2048?(t[r++]=192|i>>>6,t[r++]=128|63&i):i<65536?(t[r++]=224|i>>>12,t[r++]=128|i>>>6&63,t[r++]=128|63&i):(t[r++]=240|i>>>18,t[r++]=128|i>>>12&63,t[r++]=128|i>>>6&63,t[r++]=128|63&i);return t};var nr=function(){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};const or=Object.prototype.toString,{Z_NO_FLUSH:rr,Z_SYNC_FLUSH:ar,Z_FULL_FLUSH:dr,Z_FINISH:sr,Z_OK:lr,Z_STREAM_END:cr,Z_DEFAULT_COMPRESSION:hr,Z_DEFAULT_STRATEGY:mr,Z_DEFLATED:pr}=Kn;function ur(e){this.options=Qo({level:hr,method:pr,chunkSize:16384,windowBits:15,memLevel:8,strategy:mr},e||{});let t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new nr,this.strm.avail_out=0;let i=Ko.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(i!==lr)throw new Error(jn[i]);if(t.header&&Ko.deflateSetHeader(this.strm,t.header),t.dictionary){let e;if(e="string"==typeof t.dictionary?ir(t.dictionary):"[object ArrayBuffer]"===or.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,i=Ko.deflateSetDictionary(this.strm,e),i!==lr)throw new Error(jn[i]);this._dict_set=!0}}ur.prototype.push=function(e,t){const i=this.strm,n=this.options.chunkSize;let o,r;if(this.ended)return!1;for(r=t===~~t?t:!0===t?sr:rr,"string"==typeof e?i.input=ir(e):"[object ArrayBuffer]"===or.call(e)?i.input=new Uint8Array(e):i.input=e,i.next_in=0,i.avail_in=i.input.length;;)if(0===i.avail_out&&(i.output=new Uint8Array(n),i.next_out=0,i.avail_out=n),(r===ar||r===dr)&&i.avail_out<=6)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else{if(o=Ko.deflate(i,r),o===cr)return i.next_out>0&&this.onData(i.output.subarray(0,i.next_out)),o=Ko.deflateEnd(this.strm),this.onEnd(o),this.ended=!0,o===lr;if(0!==i.avail_out){if(r>0&&i.next_out>0)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else if(0===i.avail_in)break}else this.onData(i.output)}return!0},ur.prototype.onData=function(e){this.chunks.push(e)},ur.prototype.onEnd=function(e){e===lr&&(this.result=Jo(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var fr={deflate:function(e,t){const i=new ur(t);if(i.push(e,!0),i.err)throw i.msg||jn[i.err];return i.result}};const{deflate:gr}=fr;var br=gr;const _r={b:{u:DataView.prototype.getInt8,p:DataView.prototype.setInt8,bytes:1},B:{u:DataView.prototype.getUint8,p:DataView.prototype.setUint8,bytes:1},h:{u:DataView.prototype.getInt16,p:DataView.prototype.setInt16,bytes:2},H:{u:DataView.prototype.getUint16,p:DataView.prototype.setUint16,bytes:2},i:{u:DataView.prototype.getInt32,p:DataView.prototype.setInt32,bytes:4},I:{u:DataView.prototype.getUint32,p:DataView.prototype.setUint32,bytes:4}},xr=(e,...t)=>{let i=0;if(e.replace(/[<>]/,"").length!=t.length)throw"Pack format to Argument count mismatch";const n=[];let o=!0;for(let n=0;n<e.length;n++)"<"==e[n]?o=!0:">"==e[n]?o=!1:(r(e[n],t[i]),i++);function r(e,t){if(!(e in _r))throw"Unhandled character '"+e+"' in pack format";const i=_r[e].bytes,r=new DataView(new ArrayBuffer(i));_r[e].p.bind(r)(0,t,o);for(let e=0;e<i;e++)n.push(r.getUint8(e))}return n},vr=(e,t)=>{let i=0;const n=[];let o=!0;for(const t of e)"<"==t?o=!0:">"==t?o=!1:r(t);function r(e){if(!(e in _r))throw"Unhandled character '"+e+"' in unpack format";const r=_r[e].bytes,a=new DataView(new ArrayBuffer(r));for(let e=0;e<r;e++)a.setUint8(e,255&t[i+e]);const d=_r[e].u.bind(a);n.push(d(0,o)),i+=r}return n};class yr extends EventTarget{constructor(e,t,i){super(),this.port=e,this.logger=t,this._parent=i,this.chipName=null,this.chipRevision=null,this.chipVariant=null,this._efuses=new Array(4).fill(0),this._flashsize=4194304,this.debug=!1,this.IS_STUB=!1,this.connected=!0,this.flashSize=null,this._currentBaudRate=Fi,this._isESP32S2NativeUSB=!1,this._initializationSucceeded=!1,this.state_DTR=!1}get _inputBuffer(){return this._parent?this._parent._inputBuffer:this.__inputBuffer}get _totalBytesRead(){return this._parent?this._parent._totalBytesRead:this.__totalBytesRead||0}set _totalBytesRead(e){this._parent?this._parent._totalBytesRead=e:this.__totalBytesRead=e}detectUSBSerialChip(e,t){const i={6790:{29986:{name:"CH340",maxBaudrate:460800},29987:{name:"CH340",maxBaudrate:460800},30084:{name:"CH340",maxBaudrate:460800},21795:{name:"CH341",maxBaudrate:2e6},21971:{name:"CH343",maxBaudrate:6e6},21972:{name:"CH9102",maxBaudrate:6e6},21976:{name:"CH9101",maxBaudrate:3e6}},4292:{6e4:{name:"CP2102(n)",maxBaudrate:3e6},60016:{name:"CP2105",maxBaudrate:2e6},60017:{name:"CP2108",maxBaudrate:2e6}},1027:{24577:{name:"FT232R",maxBaudrate:3e6},24592:{name:"FT2232",maxBaudrate:3e6},24593:{name:"FT4232",maxBaudrate:3e6},24596:{name:"FT232H",maxBaudrate:12e6},24597:{name:"FT230X",maxBaudrate:3e6}},12346:{2:{name:"ESP32-S2 Native USB",maxBaudrate:2e6},4097:{name:"ESP32 Native USB",maxBaudrate:2e6},4098:{name:"ESP32 Native USB",maxBaudrate:2e6},16386:{name:"ESP32 Native USB",maxBaudrate:2e6},4096:{name:"ESP32 Native USB",maxBaudrate:2e6}}}[e];return i&&i[t]?i[t]:{name:`Unknown (VID: 0x${e.toString(16)}, PID: 0x${t.toString(16)})`}}async initialize(){if(await this.hardReset(!0),!this._parent){this.__inputBuffer=[],this.__totalBytesRead=0;const e=this.port.getInfo();if(e.usbVendorId&&e.usbProductId){const t=this.detectUSBSerialChip(e.usbVendorId,e.usbProductId);this.logger.log(`USB-Serial: ${t.name} (VID: 0x${e.usbVendorId.toString(16)}, PID: 0x${e.usbProductId.toString(16)})`),t.maxBaudrate&&(this._maxUSBSerialBaudrate=t.maxBaudrate,this.logger.log(`Max baudrate: ${t.maxBaudrate}`)),12346===e.usbVendorId&&2===e.usbProductId&&(this._isESP32S2NativeUSB=!0)}this.readLoop()}await this.flushSerialBuffers(),await this.sync(),await this.detectChip();const e=tn(this.getChipFamily()),t=e.macFuse;for(let e=0;e<4;e++)this._efuses[e]=await this.readRegister(t+4*e);this.logger.log(`Chip type ${this.chipName}`),this.logger.debug(`Bootloader flash offset: 0x${e.flashOffs.toString(16)}`),this._initializationSucceeded=!0}async detectChip(){try{const e=(await this.getSecurityInfo()).chipId,t=ji[e];if(t)return this.chipName=t.name,this.chipFamily=t.family,this.chipFamily===Yi&&(this.chipRevision=await this.getChipRevision(),this.logger.debug(`ESP32-P4 revision: ${this.chipRevision}`),this.chipRevision>=300?this.chipVariant="rev300":this.chipVariant="rev0",this.logger.debug(`ESP32-P4 variant: ${this.chipVariant}`)),void this.logger.debug(`Detected chip via IMAGE_CHIP_ID: ${e} (${this.chipName})`);this.logger.debug(`Unknown IMAGE_CHIP_ID: ${e}, falling back to magic value detection`)}catch(e){this.logger.debug(`GET_SECURITY_INFO failed, using magic value detection: ${e}`),this._inputBuffer.length=0,await Ai(Ji);try{await this.sync()}catch(e){this.logger.debug(`Re-sync after GET_SECURITY_INFO failure: ${e}`)}}const e=await this.readRegister(1073745920),t=Ki[e>>>0];if(void 0===t)throw new Error(`Unknown Chip: Hex: ${Ti(e>>>0,8).toLowerCase()} Number: ${e}`);this.chipName=t.name,this.chipFamily=t.family,this.chipFamily===Yi&&(this.chipRevision=await this.getChipRevision(),this.logger.debug(`ESP32-P4 revision: ${this.chipRevision}`),this.chipRevision>=300?this.chipVariant="rev300":this.chipVariant="rev0",this.logger.debug(`ESP32-P4 variant: ${this.chipVariant}`)),this.logger.debug(`Detected chip via magic value: ${Ti(e>>>0,8)} (${this.chipName})`)}async getChipRevision(){if(this.chipFamily!==Yi)return 0;const e=await this.readRegister(1343410252);return 100*((e>>23&1)<<2|e>>4&3)+(15&e)}async getSecurityInfo(){const[,e]=await this.checkCommand(20,[],0);if(0===e.length)throw new Error("GET_SECURITY_INFO not supported or returned empty response");if(e.length<12)throw new Error(`Invalid security info response length: ${e.length} (expected at least 12 bytes)`);return{flags:vr("<I",e.slice(0,4))[0],flashCryptCnt:e[4],keyPurposes:Array.from(e.slice(5,12)),chipId:e.length>=16?vr("<I",e.slice(12,16))[0]:0,apiVersion:e.length>=20?vr("<I",e.slice(16,20))[0]:0}}async readLoop(){this.debug&&this.logger.debug("Starting read loop"),this._reader=this.port.readable.getReader();try{let e=!0;for(;e;){const{value:t,done:i}=await this._reader.read();if(i){this._reader.releaseLock(),e=!1;break}if(!t||0===t.length)continue;const n=Array.from(t);Array.prototype.push.apply(this._inputBuffer,n),this._totalBytesRead+=t.length}}catch{this.logger.error("Read loop got disconnected")}this.connected=!1,this._isESP32S2NativeUSB&&!this._initializationSucceeded&&(this.logger.log("ESP32-S2 Native USB detected - requesting port reselection"),this.dispatchEvent(new CustomEvent("esp32s2-usb-reconnect",{detail:{message:"ESP32-S2 Native USB requires port reselection"}}))),this.dispatchEvent(new Event("disconnect")),this.logger.debug("Finished read loop")}sleep(e=100){return new Promise(t=>setTimeout(t,e))}async setRTS(e){await this.port.setSignals({requestToSend:e}),await this.setDTR(this.state_DTR)}async setDTR(e){this.state_DTR=e,await this.port.setSignals({dataTerminalReady:e})}async hardReset(e=!1){e?4097===this.port.getInfo().usbProductId?(await this.setDTR(!1),await this.setRTS(!1),await this.sleep(100),await this.setDTR(!0),await this.setRTS(!1),await this.sleep(100),await this.setRTS(!0),await this.setDTR(!1),await this.setRTS(!0),await this.sleep(100),await this.setDTR(!1),await this.setRTS(!1),this.logger.log("USB MCU reset.")):(await this.setDTR(!1),await this.setRTS(!0),await this.sleep(100),await this.setDTR(!0),await this.setRTS(!1),await this.sleep(50),await this.setDTR(!1),this.logger.log("DTR/RTS USB serial chip reset.")):(await this.setRTS(!0),await this.sleep(100),await this.setRTS(!1),this.logger.log("Hard reset.")),await new Promise(e=>setTimeout(e,1e3))}macAddr(){const e=new Array(6).fill(0),t=this._efuses[0],i=this._efuses[1],n=this._efuses[2],o=this._efuses[3];let r;if(this.chipFamily==zi){if(0!=o)r=[o>>16&255,o>>8&255,255&o];else if(i>>16&255){if(1!=(i>>16&255))throw new Error("Couldnt determine OUI");r=[172,208,116]}else r=[24,254,52];e[0]=r[0],e[1]=r[1],e[2]=r[2],e[3]=i>>8&255,e[4]=255&i,e[5]=t>>24&255}else if(this.chipFamily==Di)e[0]=n>>8&255,e[1]=255&n,e[2]=i>>24&255,e[3]=i>>16&255,e[4]=i>>8&255,e[5]=255&i;else{if(this.chipFamily!=$i&&this.chipFamily!=Ni&&this.chipFamily!=Pi&&this.chipFamily!=Mi&&this.chipFamily!=Ui&&this.chipFamily!=Hi&&this.chipFamily!=Vi&&this.chipFamily!=Wi&&this.chipFamily!=Xi&&this.chipFamily!=qi&&this.chipFamily!=Yi&&this.chipFamily!=Gi)throw new Error("Unknown chip family");e[0]=i>>8&255,e[1]=255&i,e[2]=t>>24&255,e[3]=t>>16&255,e[4]=t>>8&255,e[5]=255&t}return e}async readRegister(e){this.debug&&this.logger.debug("Reading from Register "+Ti(e,8));const t=xr("<I",e);await this.sendCommand(10,t);const[i]=await this.getResponse(10);return i}async checkCommand(e,t,i=0,n=3e3){n=Math.min(n,3e5),await this.sendCommand(e,t,i);const[o,r]=await this.getResponse(e,n);if(null===r)throw new Error("Didn't get enough status bytes");let a=r,d=0;if(this.IS_STUB||this.chipFamily==zi?d=2:[Di,$i,Ni,Pi,Mi,Ui,Hi,Vi,Wi,Xi,qi,Yi,Gi].includes(this.chipFamily)||20===e?d=4:[2,4].includes(a.length)&&(d=a.length),a.length<d)throw new Error("Didn't get enough status bytes");const s=a.slice(-d,a.length);if(a=a.slice(0,-d),this.debug&&(this.logger.debug("status",s),this.logger.debug("value",o),this.logger.debug("data",a)),1==s[0])throw 5==s[1]?new Error("Invalid (unsupported) command "+Ti(e)):new Error("Command failure error code "+Ti(s[1]));return[o,a]}async sendCommand(e,t,i=0){const n=Si([...xr("<BBHI",0,e,t.length,i),...t]);this.debug&&this.logger.debug(`Writing ${n.length} byte${1==n.length?"":"s"}:`,n),await this.writeToStream(n)}async readPacket(e){let t=null,i=!1,n=[];for(;;){const o=Date.now();for(n=[];Date.now()-o<e;){if(this._inputBuffer.length>0){n.push(this._inputBuffer.shift());break}await Ai(1)}if(0==n.length){throw new nn("Timed out waiting for packet "+(null===t?"header":"content"))}this.debug&&this.logger.debug("Read "+n.length+" bytes: "+Ri(n));for(const e of n)if(null===t){if(192!=e)throw this.debug&&(this.logger.debug("Read invalid data: "+Ri(n)),this.logger.debug("Remaining data in serial buffer: "+Ri(this._inputBuffer))),new nn("Invalid head of packet ("+Ti(e)+")");t=[]}else if(i)if(i=!1,220==e)t.push(192);else{if(221!=e)throw this.debug&&(this.logger.debug("Read invalid data: "+Ri(n)),this.logger.debug("Remaining data in serial buffer: "+Ri(this._inputBuffer))),new nn("Invalid SLIP escape (0xdb, "+Ti(e)+")");t.push(219)}else if(219==e)i=!0;else{if(192==e)return this.debug&&this.logger.debug("Received full packet: "+Ri(t)),t;t.push(e)}}throw new nn("Invalid state")}async getResponse(e,t=3e3){for(let i=0;i<100;i++){const i=await this.readPacket(t);if(i.length<8)continue;const[n,o,,r]=vr("<BBHI",i.slice(0,8));if(1!=n)continue;const a=i.slice(8);if(null==e||o==e)return[r,a];if(0!=a[0]&&5==a[1])throw this._inputBuffer.length=0,new Error(`Invalid (unsupported) command ${Ti(e)}`)}throw"Response doesn't match request"}checksum(e,t=239){for(const i of e)t^=i;return t}async setBaudrate(e){if(this.chipFamily==zi)throw new Error("Changing baud rate is not supported on the ESP8266");try{const t=xr("<II",e,this.IS_STUB?Fi:0);await this.checkCommand(15,t)}catch(t){throw this.logger.error(`Baudrate change error: ${t}`),new Error(`Unable to change the baud rate to ${e}: No response from set baud rate command.`)}this._parent?await this._parent.reconfigurePort(e):await this.reconfigurePort(e),this._parent?this._parent._currentBaudRate=e:this._currentBaudRate=e;const t=this._parent?this._parent._maxUSBSerialBaudrate:this._maxUSBSerialBaudrate;t&&e>t&&(this.logger.log(`⚠️ WARNING: Baudrate ${e} exceeds USB-Serial chip limit (${t})!`),this.logger.log("⚠️ This may cause data corruption or connection failures!")),this.logger.log(`Changed baud rate to ${e}`)}async reconfigurePort(e){var t;try{await(null===(t=this._reader)||void 0===t?void 0:t.cancel()),await this.port.close(),await this.port.open({baudRate:e}),await this.flushSerialBuffers(),this.readLoop()}catch(t){throw this.logger.error(`Reconfigure port error: ${t}`),new Error(`Unable to change the baud rate to ${e}: ${t}`)}}async sync(){for(let e=0;e<5;e++){this._inputBuffer.length=0;if(await this._sync())return await Ai(Ji),!0;await Ai(Ji)}throw new Error("Couldn't sync to ESP. Try resetting.")}async _sync(){await this.sendCommand(8,Bi);for(let e=0;e<8;e++)try{const[,e]=await this.getResponse(8,Ji);if(e.length>1&&0==e[0]&&0==e[1])return!0}catch{}return!1}getFlashWriteSize(){return this.IS_STUB?16384:1024}async flashData(e,t,i=0,n=!1){if(e.byteLength>=8){const t=Array.from(new Uint8Array(e,0,4)),i=t[0],n=t[2],o=t[3];this.logger.log(`Image header, Magic=${Ti(i)}, FlashMode=${Ti(n)}, FlashSizeFreq=${Ti(o)}`)}const o=e.byteLength;let r,a=0,d=Zi;n?(r=br(new Uint8Array(e),{level:9}).buffer,a=r.byteLength,this.logger.log(`Writing data with filesize: ${o}. Compressed Size: ${a}`),d=await this.flashDeflBegin(o,a,i)):(this.logger.log(`Writing data with filesize: ${o}`),r=e,await this.flashBegin(o,i));let s=[],l=0,c=0,h=0;const m=Date.now(),p=this.getFlashWriteSize(),u=n?a:o;for(;u-h>0;)this.debug&&this.logger.log(`Writing at ${Ti(i+l*p,8)} `),u-h>=p?s=Array.from(new Uint8Array(r,h,p)):(s=Array.from(new Uint8Array(r,h,u-h)),n||(s=s.concat(new Array(p-s.length).fill(255)))),n?await this.flashDeflBlock(s,l,d):await this.flashBlock(s,l),l+=1,c+=n?Math.round(s.length*o/a):s.length,h+=p,t(Math.min(c,o),o);this.logger.log("Took "+(Date.now()-m)+"ms to write "+u+" bytes"),this.IS_STUB&&(await this.flashBegin(0,0),n?await this.flashDeflFinish():await this.flashFinish())}async flashBlock(e,t,i=3e3){await this.checkCommand(3,xr("<IIII",e.length,t,0,0).concat(e),this.checksum(e),i)}async flashDeflBlock(e,t,i=3e3){await this.checkCommand(17,xr("<IIII",e.length,t,0,0).concat(e),this.checksum(e),i)}async flashBegin(e=0,t=0,i=!1){let n;await this.flushSerialBuffers();const o=this.getFlashWriteSize();!this.IS_STUB&&[Di,$i,Ni,Pi,Mi,Ui,Hi,Vi,Wi,Xi,qi,Yi,Gi].includes(this.chipFamily)&&await this.checkCommand(13,new Array(8).fill(0));const r=Math.floor((e+o-1)/o);n=this.chipFamily==zi?this.getEraseSize(t,e):e;const a=this.IS_STUB?Zi:en(3e4,e),d=Date.now();let s=xr("<IIII",n,r,o,t);return this.chipFamily!=Di&&this.chipFamily!=$i&&this.chipFamily!=Ni&&this.chipFamily!=Pi&&this.chipFamily!=Mi&&this.chipFamily!=Ui&&this.chipFamily!=Hi&&this.chipFamily!=Vi&&this.chipFamily!=Wi&&this.chipFamily!=Xi&&this.chipFamily!=qi&&this.chipFamily!=Yi&&this.chipFamily!=Gi||(s=s.concat(xr("<I",i?1:0))),this.logger.log("Erase size "+n+", blocks "+r+", block size "+Ti(o,4)+", offset "+Ti(t,4)+", encrypted "+(i?"yes":"no")),await this.checkCommand(2,s,0,a),0==e||this.IS_STUB||this.logger.log("Took "+(Date.now()-d)+"ms to erase "+r+" bytes"),r}async flashDeflBegin(e=0,t=0,i=0){const n=this.getFlashWriteSize(),o=Math.floor((t+n-1)/n),r=Math.floor((e+n-1)/n);let a=0,d=0;this.IS_STUB?(a=e,d=en(3e4,a)):(a=r*n,d=Zi);const s=xr("<IIII",a,o,n,i);return await this.checkCommand(16,s,0,d),d}async flashFinish(){const e=xr("<I",1);await this.checkCommand(4,e)}async flashDeflFinish(){const e=xr("<I",1);await this.checkCommand(18,e)}getBootloaderOffset(){return tn(this.getChipFamily()).flashOffs}async flashId(){return await this.runSpiFlashCommand(159,[],24)}getChipFamily(){return this._parent?this._parent.chipFamily:this.chipFamily}async writeRegister(e,t,i=4294967295,n=0,o=0){let r=xr("<IIII",e,t,i,n);o>0&&(r=r.concat(xr("<IIII",tn(this.getChipFamily()).uartDateReg,0,0,o))),await this.checkCommand(9,r)}async setDataLengths(e,t,i){if(-1!=e.mosiDlenOffs){const n=e.regBase+e.mosiDlenOffs,o=e.regBase+e.misoDlenOffs;t>0&&await this.writeRegister(n,t-1),i>0&&await this.writeRegister(o,i-1)}else{const n=e.regBase+e.usr1Offs,o=(0==i?0:i-1)<<8|(0==t?0:t-1)<<17;await this.writeRegister(n,o)}}async waitDone(e,t){for(let i=0;i<10;i++){if(0==(await this.readRegister(e)&t))return}throw Error("SPI command did not complete in time")}async runSpiFlashCommand(e,t,i=0){const n=tn(this.getChipFamily()),o=n.regBase,r=o,a=o+n.usrOffs,d=o+n.usr2Offs,s=o+n.w0Offs,l=1<<18;if(i>32)throw new Error("Reading more than 32 bits back from a SPI flash operation is unsupported");if(t.length>64)throw new Error("Writing more than 64 bytes of data with one SPI command is unsupported");const c=8*t.length,h=await this.readRegister(a),m=await this.readRegister(d);let p=1<<31;if(i>0&&(p|=268435456),c>0&&(p|=134217728),await this.setDataLengths(n,c,i),await this.writeRegister(a,p),await this.writeRegister(d,7<<28|e),0==c)await this.writeRegister(s,0);else{const e=(4-t.length%4)%4;t=t.concat(new Array(e).fill(0));const i=vr("I".repeat(Math.floor(t.length/4)),t);let n=s;this.logger.debug(`Words Length: ${i.length}`);for(const e of i)this.logger.debug(`Writing word ${Ti(e)} to register offset ${Ti(n)}`),await this.writeRegister(n,e),n+=4}await this.writeRegister(r,l),await this.waitDone(r,l);const u=await this.readRegister(s);return await this.writeRegister(a,h),await this.writeRegister(d,m),u}async detectFlashSize(){this.logger.log("Detecting Flash Size");const e=await this.flashId(),t=255&e,i=e>>16&255;this.logger.log(`FlashId: ${Ti(e)}`),this.logger.log(`Flash Manufacturer: ${t.toString(16)}`),this.logger.log(`Flash Device: ${(e>>8&255).toString(16)}${i.toString(16)}`),this.flashSize=Oi[i],this.logger.log(`Auto-detected Flash size: ${this.flashSize}`)}getEraseSize(e,t){const i=4096,n=Math.floor((t+i-1)/i);let o=16-Math.floor(e/i)%16;return n<o&&(o=n),n<2*o?Math.floor((n+1)/2*i):(n-o)*i}async memBegin(e,t,i,n){return await this.checkCommand(5,xr("<IIII",e,t,i,n))}async memBlock(e,t){return await this.checkCommand(7,xr("<IIII",e.length,t,0,0).concat(e),this.checksum(e))}async memFinish(e=0){const t=this.IS_STUB?Zi:500,i=xr("<II",0==e?1:0,e);return await this.checkCommand(6,i,0,t)}async runStub(e=!1){const t=await on(this.chipFamily,this.chipRevision);if(null===t)return this.logger.log(`Stub flasher is not yet supported on ${this.chipName}, using ROM loader`),this;const i=2048;this.logger.log("Uploading stub...");for(const e of["text","data"]){const n=t[e],o=t[`${e}_start`],r=n.length,a=Math.floor((r+i-1)/i);await this.memBegin(r,a,i,o);for(const e of Array(a).keys()){const t=e*i;let o=t+i;o>r&&(o=r),await this.memBlock(n.slice(t,o),e)}}await this.memFinish(t.entry);const n=await this.readPacket(500),o=String.fromCharCode(...n);if("OHAI"!=o)throw new Error("Failed to start stub. Unexpected response: "+o);this.logger.log("Stub is now running...");const r=new wr(this.port,this.logger,this);return e||await r.detectFlashSize(),r}async writeToStream(e){if(!this.port.writable)return void this.logger.debug("Port writable stream not available, skipping write");const t=this.port.writable.getWriter();await t.write(new Uint8Array(e));try{t.releaseLock()}catch(e){this.logger.error(`Ignoring release lock error: ${e}`)}}async disconnect(){this._parent?await this._parent.disconnect():this.port.writable?(await this.port.writable.getWriter().close(),await new Promise(e=>{this._reader||e(void 0),this.addEventListener("disconnect",e,{once:!0}),this._reader.cancel()}),this.connected=!1):this.logger.debug("Port already closed, skipping disconnect")}async reconnect(){if(this._parent)return void await this._parent.reconnect();if(this.logger.log("Reconnecting serial port..."),this.connected=!1,this.__inputBuffer=[],this._reader){try{await this._reader.cancel()}catch(e){this.logger.debug(`Reader cancel error: ${e}`)}this._reader=void 0}try{await this.port.close(),this.logger.log("Port closed")}catch(e){this.logger.debug(`Port close error: ${e}`)}this.logger.debug("Opening port...");try{await this.port.open({baudRate:Fi}),this.connected=!0}catch(e){throw new Error(`Failed to open port: ${e}`)}if(!this.port.readable||!this.port.writable)throw new Error(`Port streams not available after open (readable: ${!!this.port.readable}, writable: ${!!this.port.writable})`);const e=this.chipFamily,t=this.chipName,i=this.chipRevision,n=this.chipVariant,o=this.flashSize;if(await this.hardReset(!0),this._parent||(this.__inputBuffer=[],this.__totalBytesRead=0,this.readLoop()),await this.flushSerialBuffers(),await this.sync(),this.chipFamily=e,this.chipName=t,this.chipRevision=i,this.chipVariant=n,this.flashSize=o,this.logger.debug(`Reconnect complete (chip: ${this.chipName})`),!this.port.writable||!this.port.readable)throw new Error("Port not ready after reconnect");const r=await this.runStub(!0);if(this.logger.debug("Stub loaded"),this._currentBaudRate!==Fi&&(await r.setBaudrate(this._currentBaudRate),!this.port.writable||!this.port.readable))throw new Error(`Port not ready after baudrate change (readable: ${!!this.port.readable}, writable: ${!!this.port.writable})`);this.IS_STUB&&Object.assign(this,r),this.logger.debug("Reconnection successful")}async flushSerialBuffers(){this._parent||(this.__inputBuffer=[]),await Ai(Ji),this._parent||(this.__inputBuffer=[]),this.logger.debug("Serial buffers flushed")}async readFlash(e,t,i){if(!this.IS_STUB)throw new Error("Reading flash is only supported in stub mode. Please run runStub() first.");await this.flushSerialBuffers(),this.logger.log(`Reading ${t} bytes from flash at address 0x${e.toString(16)}...`);let n=new Uint8Array(0),o=e,r=t;for(;r>0;){const e=Math.min(65536,r);let a=!1,d=0;const s=3;for(;!a&&d<=s;)try{this.logger.debug(`Reading chunk at 0x${o.toString(16)}, size: 0x${e.toString(16)}`);const t=xr("<IIII",o,e,4096,1024),[i]=await this.checkCommand(210,t);if(0!=i)throw new Error("Failed to read memory: "+i);let r=new Uint8Array(0);for(;r.length<e;){let t;try{t=await this.readPacket(100)}catch(t){if(t instanceof nn&&(this.logger.debug(`SLIP read error at ${r.length} bytes: ${t.message}`),r.length>=e))break;throw t}if(t&&t.length>0){const e=new Uint8Array(t),i=new Uint8Array(r.length+e.length);i.set(r),i.set(e,r.length),r=i;const n=xr("<I",r.length),o=Si(n);await this.writeToStream(o)}}const d=new Uint8Array(n.length+r.length);d.set(n),d.set(r,n.length),n=d,a=!0}catch(e){if(d++,!(e instanceof nn&&e.message.includes("Timed out")))throw e;if(!(d<=s))throw new Error(`Failed to read chunk at 0x${o.toString(16)} after ${s} retries: ${e}`);this.logger.log(`⚠️ Timeout error at 0x${o.toString(16)}. Reconnecting and retrying (attempt ${d}/${s})...`);try{await this.reconnect()}catch(e){throw new Error(`Reconnect failed: ${e}`)}}i&&i(new Uint8Array(e),n.length,t),o+=e,r-=e,this.logger.debug(`Total progress: 0x${n.length.toString(16)} from 0x${t.toString(16)} bytes`)}return this.logger.debug(`Successfully read ${n.length} bytes from flash`),n}}class wr extends yr{constructor(){super(...arguments),this.IS_STUB=!0}async memBegin(e,t,i,n){const o=await on(this.chipFamily,this.chipRevision);if(null===o)return[0,[]];const r=n,a=n+e;this.logger.debug(`Load range: ${Ti(r,8)}-${Ti(a,8)}`),this.logger.debug(`Stub data: ${Ti(o.data_start,8)}, len: ${o.data.length}, text: ${Ti(o.text_start,8)}, len: ${o.text.length}`);for(const[e,t]of[[o.data_start,o.data_start+o.data.length],[o.text_start,o.text_start+o.text.length]])if(r<t&&a>e)throw new Error("Software loader is resident at "+Ti(e,8)+"-"+Ti(t,8)+". Can't load binary at overlapping address range "+Ti(r,8)+"-"+Ti(a,8)+". Try changing the binary loading address.");return[0,[]]}async eraseFlash(){await this.checkCommand(208,[],0,Qi)}}const kr=async(e,t,i,n,o,r,a)=>{let d,s,l,c=null,h=!1;const m=(e=>{const t=e.getInfo();return 12346===t.usbVendorId&&2===t.usbProductId})(t),p=t=>e({...t,manifest:d,build:s,chipFamily:l,chipVariant:c});var u=null,f="";try{u=JSON.parse(n)}catch{f=new URL(n,location.toString()).toString(),u=fetch(f).then(e=>e.json())}const g=new yr(t,i);window.esploader=g;const b=()=>{h=!0,i.log("ESP32-S2 Native USB disconnect detected - reconnection required")};m&&(g.addEventListener("esp32s2-usb-reconnect",b),i.log("ESP32-S2 Native USB detected - monitoring for port switch"));const _=()=>{m&&g.removeEventListener("esp32s2-usb-reconnect",b)};p({state:"initializing",message:"Initializing...",details:{done:!1}});try{await g.initialize()}catch(e){if(i.error(e),m&&(h||String(e).includes("reconnect required"))){_();try{await t.close()}catch{}try{await t.forget()}catch{}return void p({state:"esp32_s2_usb_reconnect",message:"ESP32-S2 USB port changed - please select the new port",details:{oldPort:t}})}return _(),p({state:"error",message:"Failed to initialize. Try resetting your device or holding the BOOT button while clicking INSTALL.",details:{error:"failed_initialize",details:e}}),void(g.connected&&await g.disconnect())}l=(e=>{switch(e.chipFamily){case Di:return"ESP32";case $i:return"ESP32-S2";case Ni:return"ESP32-S3";case Pi:return"ESP32-C2";case Mi:return"ESP32-C3";case Ui:return"ESP32-C5";case Hi:return"ESP32-C6";case Vi:return"ESP32-C61";case Wi:return"ESP32-H2";case Yi:return"ESP32-P4";case zi:return"ESP8266";default:return"Unknown Chip"}})(g),c=g.chipVariant,p({state:"initializing",message:`Initialized. Found ${l}${c?` (${c})`:""}`,details:{done:!0}}),p({state:"manifest",message:"Fetching manifest...",details:{done:!1}});try{d=await u}catch(e){return _(),p({state:"error",message:`Unable to fetch manifest: ${e}`,details:{error:"fetch_manifest_failed",details:e}}),void await g.disconnect()}if(s=d.builds.find(e=>e.chipFamily===l&&(void 0===e.chipVariant||e.chipVariant===c)),p({state:"manifest",message:`Found manifest for ${d.name}`,details:{done:!0}}),!s){const e=c?`${l} (${c})`:l;return _(),p({state:"error",message:`Your ${e} board is not supported.`,details:{error:"not_supported",details:e}}),void await g.disconnect()}p({state:"preparing",message:"Preparing installation...",details:{done:!1}});const x=s.parts.map(async e=>{if(0==r.length){const t=new URL(e.path,f).toString(),i=await fetch(t);if(!i.ok)throw new Error(`Downlading firmware ${e.path} failed: ${i.status}`);return i.arrayBuffer()}return r}),v=await g.runStub();if(void 0!==a&&a>115200)try{await v.setBaudrate(a)}catch(e){i.log(`Could not change baud rate to ${a}: ${e.message}`)}const y=[];let w=0;for(const e of x)try{const t=await e;y.push(t instanceof ArrayBuffer?new Uint8Array(t):t),w+=t.byteLength}catch(e){return _(),p({state:"error",message:e.message,details:{error:"failed_firmware_download",details:e.message}}),void await g.disconnect()}p({state:"preparing",message:"Installation prepared",details:{done:!0}}),o&&(p({state:"erasing",message:"Erasing device...",details:{done:!1}}),await v.eraseFlash(),p({state:"erasing",message:"Device erased",details:{done:!0}}));let k=0;p({state:"writing",message:`Writing progress: ${k}%`,details:{bytesTotal:w,bytesWritten:0,percentage:k}});let E=0;for(const e of s.parts){const t=y.shift(),i=t instanceof Uint8Array?new Uint8Array(t).buffer:t;try{await v.flashData(i,e=>{const t=Math.floor((E+e)/w*100);t!==k&&(k=t,p({state:"writing",message:`Writing progress: ${t}%`,details:{bytesTotal:w,bytesWritten:E+e,percentage:t}}))},e.offset,!0)}catch(e){return _(),p({state:"error",message:e.message,details:{error:"write_failed",details:e}}),void await g.disconnect()}E+=t.byteLength}p({state:"writing",message:"Writing complete",details:{bytesTotal:w,bytesWritten:E,percentage:100}}),await V(100),console.log("DISCONNECT"),await g.disconnect(),console.log("HARD RESET"),await g.hardReset(),_(),p({state:"finished",message:"All done!"})},Er=(e,t="")=>{const i=new Blob([e],{type:"text/plain"}),n=URL.createObjectURL(i);((e,t="")=>{const i=document.createElement("a");i.target="_blank",i.href=e,i.download=t,document.body.appendChild(i),i.dispatchEvent(new MouseEvent("click")),document.body.removeChild(i)})(n,t),setTimeout(()=>URL.revokeObjectURL(n),0)};class Ir extends x{constructor(){super(...arguments),this.logger=console,this._state="DASHBOARD",this._installErase=!1,this._installConfirmed=!1,this._provisionForce=!1,this._wasProvisioned=!1,this._busy=!1,this._esp32s2ReconnectInProgress=!1,this._selectedSsid=-1,this._handleDisconnect=()=>{this._state="ERROR",this._error="Disconnected"}}render(){if(!this.port)return h``;let e,t,i=!1,n=!1;return void 0===this._client&&"INSTALL"!==this._state&&"LOGS"!==this._state?this._error?[e,t,i]=this._renderError(this._error):(t=this._renderProgress("Connecting"),i=!0):"INSTALL"===this._state?[e,t,i,n]=this._renderInstall():"ASK_ERASE"===this._state?[e,t]=this._renderAskErase():"ERROR"===this._state?[e,t,i]=this._renderError(this._error):"DASHBOARD"===this._state?[e,t,i,n]=this._client?this._renderDashboard():this._renderDashboardNoImprov():"PROVISION"===this._state?[e,t,i]=this._renderProvision():"LOGS"===this._state&&([e,t,i]=this._renderLogs()),h`
|
|
418
418
|
<ewt-dialog
|
|
419
419
|
open
|
|
420
420
|
.heading=${e}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const e=async t=>{let n;import("./install-dialog-
|
|
1
|
+
const e=async t=>{let n;import("./install-dialog-Xo7JovVA.js");try{n=await navigator.serial.requestPort()}catch(n){return"NotFoundError"===n.name?void import("./index-BK6drzlv.js").then(n=>n.openNoPortPickedDialog(()=>e(t))):void alert(`Error: ${n.message}`)}if(!n)return;try{await n.open({baudRate:115200})}catch(e){return void alert(e.message)}const o=document.createElement("ewt-install-dialog");o.port=n,o.manifestPath=t.manifest||t.getAttribute("manifest"),o.overrides=t.overrides,o.firmwareFile=t.firmwareFile;const r=t.getAttribute("baud-rate");if(r){const e=parseInt(r,10);isNaN(e)||(o.baudRate=e)}else void 0!==t.baudRate&&(o.baudRate=t.baudRate);o.addEventListener("closed",()=>{n.close()},{once:!0}),document.body.appendChild(o)};class t extends HTMLElement{connectedCallback(){if(this.renderRoot)return;if(this.renderRoot=this.attachShadow({mode:"open"}),!t.isSupported||!t.isAllowed)return this.toggleAttribute("install-unsupported",!0),void(this.renderRoot.innerHTML=t.isAllowed?"<slot name='unsupported'>Your browser does not support installing things on ESP devices. Use Google Chrome or Microsoft Edge.</slot>":"<slot name='not-allowed'>You can only install ESP devices on HTTPS websites or on the localhost.</slot>");this.toggleAttribute("install-supported",!0);const n=document.createElement("slot");n.addEventListener("click",async t=>{t.preventDefault(),e(this)}),n.name="activate";const o=document.createElement("button");if(o.innerText="CONNECT",n.append(o),"adoptedStyleSheets"in Document.prototype&&"replaceSync"in CSSStyleSheet.prototype){const e=new CSSStyleSheet;e.replaceSync(t.style),this.renderRoot.adoptedStyleSheets=[e]}else{const e=document.createElement("style");e.innerText=t.style,this.renderRoot.append(e)}this.renderRoot.append(n)}}t.isSupported="serial"in navigator,t.isAllowed=window.isSecureContext,t.style='\n button {\n position: relative;\n cursor: pointer;\n font-size: 14px;\n padding: 8px 28px;\n color: var(--esp-tools-button-text-color, #fff);\n background-color: var(--esp-tools-button-color, #03a9f4);\n border: none;\n border-radius: 4px;\n box-shadow: 0 2px 2px 0 rgba(0,0,0,.14), 0 3px 1px -2px rgba(0,0,0,.12), 0 1px 5px 0 rgba(0,0,0,.2);\n }\n button::before {\n content: " ";\n position: absolute;\n top: 0;\n bottom: 0;\n left: 0;\n right: 0;\n opacity: 0.2;\n border-radius: 4px;\n }\n button:hover {\n box-shadow: 0 4px 8px 0 rgba(0,0,0,.14), 0 1px 7px 0 rgba(0,0,0,.12), 0 3px 1px -1px rgba(0,0,0,.2);\n }\n button:hover::before {\n background-color: rgba(255,255,255,.8);\n }\n button:focus {\n outline: none;\n }\n button:focus::before {\n background-color: white;\n }\n button:active::before {\n background-color: grey;\n }\n :host([active]) button {\n color: rgba(0, 0, 0, 0.38);\n background-color: rgba(0, 0, 0, 0.12);\n box-shadow: none;\n cursor: unset;\n pointer-events: none;\n }\n improv-wifi-launch-button {\n display: block;\n margin-top: 16px;\n }\n .hidden {\n display: none;\n }',customElements.define("esp-web-install-button",t);
|
|
@@ -414,7 +414,7 @@ import{l as e,o as t,_ as i,n,B as o,i as r,a,t as d,e as s,b as l,R as c,x as h
|
|
|
414
414
|
d="M6,4H18V5H21V7H18V9H21V11H18V13H21V15H18V17H21V19H18V20H6V19H3V17H6V15H3V13H6V11H3V9H6V7H3V5H6V4M11,15V18H12V15H11M13,15V18H14V15H13M15,15V18H16V15H15Z"
|
|
415
415
|
/>
|
|
416
416
|
</svg>
|
|
417
|
-
`,xi=["I".charCodeAt(0),"M".charCodeAt(0),"P".charCodeAt(0),"R".charCodeAt(0),"O".charCodeAt(0),"V".charCodeAt(0),1];var vi,yi;!function(e){e[e.CURRENT_STATE=1]="CURRENT_STATE",e[e.ERROR_STATE=2]="ERROR_STATE",e[e.RPC=3]="RPC",e[e.RPC_RESULT=4]="RPC_RESULT"}(vi||(vi={})),function(e){e[e.READY=2]="READY",e[e.PROVISIONING=3]="PROVISIONING",e[e.PROVISIONED=4]="PROVISIONED"}(yi||(yi={}));const wi={0:"NO_ERROR",1:"INVALID_RPC_PACKET",2:"UNKNOWN_RPC_COMMAND",3:"UNABLE_TO_CONNECT",254:"TIMEOUT",255:"UNKNOWN_ERROR"};class ki extends Error{constructor(){super("Port is not ready")}}const Ei=e=>"["+e.map(e=>((e,t=2)=>{let i=e.toString(16).toUpperCase();return i.startsWith("-")?"-0x"+i.substring(1).padStart(t,"0"):"0x"+i.padStart(t,"0")})(e)).join(", ")+"]";class Ii extends EventTarget{constructor(e,t){if(super(),this.port=e,this.logger=t,this.error=0,null===e.readable)throw new Error("Port is not readable");if(null===e.writable)throw new Error("Port is not writable")}async initialize(e=1e3){var t;if(this.logger.log("Initializing Improv Serial"),this._processInput(),await(t=1e3,new Promise(e=>setTimeout(e,t))),void 0===this._reader)throw new ki;try{await new Promise(async(t,i)=>{setTimeout(()=>i(new Error("Improv Wi-Fi Serial not detected")),e),await this.requestCurrentState(),t(void 0)}),await this.requestInfo()}catch(e){throw await this.close(),e}return this.info}async close(){this._reader&&await new Promise(e=>{this._reader.cancel(),this.addEventListener("disconnect",e,{once:!0})})}async requestCurrentState(){let e;try{await new Promise(async(t,i)=>{this.addEventListener("state-changed",t,{once:!0});e=this._sendRPCWithResponse(2,[]),e.catch(e=>{this.removeEventListener("state-changed",t),i(e)})})}catch(e){throw this._rpcFeedback=void 0,new Error(`Error fetching current state: ${e}`)}if(this.state!==yi.PROVISIONED)return void(this._rpcFeedback=void 0);const t=await e;this.nextUrl=t[0]}async requestInfo(e){const t=await this._sendRPCWithResponse(3,[],e);this.info={firmware:t[0],version:t[1],name:t[3],chipFamily:t[2]}}async provision(e,t,i){const n=new TextEncoder,o=n.encode(e),r=n.encode(t),a=[o.length,...o,r.length,...r],d=await this._sendRPCWithResponse(1,a,i);this.nextUrl=d[0]}async scan(){const e=(await this._sendRPCWithMultipleResponses(4,[])).map(([e,t,i])=>({name:e,rssi:parseInt(t),secured:"YES"===i}));return e.sort((e,t)=>e.name.toLocaleLowerCase().localeCompare(t.name.toLocaleLowerCase())),e}_sendRPC(e,t){this.writePacketToStream(vi.RPC,[e,t.length,...t])}async _sendRPCWithResponse(e,t,i){if(this._rpcFeedback)throw new Error("Only 1 RPC command that requires feedback can be active");return await this._awaitRPCResultWithTimeout(new Promise((i,n)=>{this._rpcFeedback={command:e,resolve:i,reject:n},this._sendRPC(e,t)}),i)}async _sendRPCWithMultipleResponses(e,t,i){if(this._rpcFeedback)throw new Error("Only 1 RPC command that requires feedback can be active");return await this._awaitRPCResultWithTimeout(new Promise((i,n)=>{this._rpcFeedback={command:e,resolve:i,reject:n,receivedData:[]},this._sendRPC(e,t)}),i)}async _awaitRPCResultWithTimeout(e,t){return t?await new Promise((i,n)=>{const o=setTimeout(()=>this._setError(254),t);e.finally(()=>clearTimeout(o)),e.then(i,n)}):await e}async _processInput(){this.logger.debug("Starting read loop"),this._reader=this.port.readable.getReader();try{let e,t=[],i=0;for(;;){const{value:n,done:o}=await this._reader.read();if(o)break;if(n&&0!==n.length)for(const o of n){if(!1===e){10===o&&(e=void 0);continue}if(!0===e){t.push(o),t.length===i&&(this._handleIncomingPacket(t),e=void 0,t=[]);continue}if(10===o){t=[];continue}if(t.push(o),9!==t.length)continue;if(e="IMPROV"===String.fromCharCode(...t.slice(0,6)),!e){t=[];continue}i=9+t[8]+1}}}catch(e){this.logger.error("Error while reading serial port",e)}finally{this._reader.releaseLock(),this._reader=void 0}this.logger.debug("Finished read loop"),this.dispatchEvent(new Event("disconnect"))}_handleIncomingPacket(e){const t=e.slice(6),i=t[0],n=t[1],o=t[2],r=t.slice(3,3+o);if(this.logger.debug("PROCESS",{version:i,packetType:n,packetLength:o,data:Ei(r)}),1!==i)return void this.logger.error("Received unsupported version",i);let a=t[3+o],d=0;for(let t=0;t<e.length-1;t++)d+=e[t];if(d&=255,d===a)if(n===vi.CURRENT_STATE)this.state=r[0],this.dispatchEvent(new CustomEvent("state-changed",{detail:this.state}));else if(n===vi.ERROR_STATE)this._setError(r[0]);else if(n===vi.RPC_RESULT){if(!this._rpcFeedback)return void this.logger.error("Received result while not waiting for one");const e=r[0];if(e!==this._rpcFeedback.command)return void this.logger.error(`Received result for command ${e} but expected ${this._rpcFeedback.command}`);const t=[],i=r[1];let n=2;for(;n<2+i;)t.push(String.fromCodePoint(...r.slice(n+1,n+r[n]+1))),n+=r[n]+1;"receivedData"in this._rpcFeedback?t.length>0?this._rpcFeedback.receivedData.push(t):(this._rpcFeedback.resolve(this._rpcFeedback.receivedData),this._rpcFeedback=void 0):(this._rpcFeedback.resolve(t),this._rpcFeedback=void 0)}else this.logger.error("Unable to handle packet",t);else this.logger.error(`Received invalid checksum ${a}. Expected ${d}`)}async writePacketToStream(e,t){const i=new Uint8Array([...xi,e,t.length,...t,0,0]);i[i.length-2]=255&i.reduce((e,t)=>e+t,0),i[i.length-1]=10,this.logger.debug("Writing to stream:",Ei(new Array(...i)));const n=this.port.writable.getWriter();await n.write(i);try{n.releaseLock()}catch(e){console.error("Ignoring release lock error",e)}}_setError(e){this.error=e,e>0&&this._rpcFeedback&&(this._rpcFeedback.reject(wi[e]||`UNKNOWN_ERROR (${e})`),this._rpcFeedback=void 0),this.dispatchEvent(new CustomEvent("error-changed",{detail:this.error}))}}const Si=e=>{let t=[192];for(const i of e)219==i?t=t.concat([219,221]):192==i?t=t.concat([219,220]):t.push(i);return t.push(192),t},Ci=e=>{const t=[];for(let i=0;i<e.length;i++){const n=e.charCodeAt(i);n<=255&&t.push(n)}return t},Ri=e=>"["+e.map(e=>Ti(e)).join(", ")+"]",Ti=(e,t=2)=>{const i=e.toString(16).toUpperCase();return i.startsWith("-")?"-0x"+i.substring(1).padStart(t,"0"):"0x"+i.padStart(t,"0")},Ai=e=>new Promise(t=>setTimeout(t,e)),Oi={18:"256KB",19:"512KB",20:"1MB",21:"2MB",22:"4MB",23:"8MB",24:"16MB",25:"32MB",26:"64MB",27:"128MB",28:"256MB",32:"64MB",33:"128MB",34:"256MB",50:"256KB",51:"512KB",52:"1MB",53:"2MB",54:"4MB",55:"8MB",56:"16MB",57:"32MB",58:"64MB"},Fi=115200,Li=1343410176,Bi=Ci(" UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU"),zi=33382,Di=50,$i=12882,Ni=12883,Pi=12994,Mi=12995,Ui=12997,Hi=12998,Vi=207969,Wi=12914,Xi=12916,qi=12917,Yi=12928,Gi=12849,ji={5:{name:"ESP32-C3",family:Mi},9:{name:"ESP32-S3",family:Ni},12:{name:"ESP32-C2",family:Pi},13:{name:"ESP32-C6",family:Hi},16:{name:"ESP32-H2",family:Wi},18:{name:"ESP32-P4",family:Yi},20:{name:"ESP32-C61",family:Vi},23:{name:"ESP32-C5",family:Ui},25:{name:"ESP32-H21",family:qi},28:{name:"ESP32-H4",family:Xi},32:{name:"ESP32-S31",family:Gi}},Ki={4293968129:{name:"ESP8266",family:zi},15736195:{name:"ESP32",family:Di},1990:{name:"ESP32-S2",family:$i}},Zi=3e3,Qi=15e4,Ji=100,en=(e,t)=>{const i=Math.floor(e*(t/486));return i<Zi?Zi:i},tn=e=>{switch(e){case Di:return{regBase:1072963584,baseFuse:1073061888,macFuse:1073061888,usrOffs:28,usr1Offs:32,usr2Offs:36,mosiDlenOffs:40,misoDlenOffs:44,w0Offs:128,uartDateReg:1610612856,flashOffs:4096};case $i:return{regBase:1061167104,baseFuse:1061265408,macFuse:1061265476,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612856,flashOffs:4096};case Ni:return{regBase:1610620928,usrOffs:24,baseFuse:1610641408,macFuse:1610641476,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612864,flashOffs:0};case zi:return{regBase:1610613248,usrOffs:28,baseFuse:1072693328,macFuse:1072693328,usr1Offs:32,usr2Offs:36,mosiDlenOffs:-1,misoDlenOffs:-1,w0Offs:64,uartDateReg:1610612856,flashOffs:0};case Pi:case Mi:return{regBase:1610620928,baseFuse:1610647552,macFuse:1610647620,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case Ui:return{regBase:1610625024,baseFuse:1611352064,macFuse:1611352132,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:8192};case Hi:return{regBase:1610625024,baseFuse:1611335680,macFuse:1611335748,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case Vi:return{regBase:1610625024,baseFuse:1611352064,macFuse:1611352132,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case Wi:return{regBase:1610625024,baseFuse:1611335680,macFuse:1611335748,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case Xi:return{regBase:1611239424,baseFuse:1611339776,macFuse:1611339844,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610686588,flashOffs:8192};case qi:return{regBase:1610625024,baseFuse:1611350016,macFuse:1611350084,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case Yi:return{regBase:1342754816,baseFuse:Li,macFuse:1343410244,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1343004812,flashOffs:8192};case Gi:return{regBase:542113792,baseFuse:544296960,macFuse:544297028,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:540582028,flashOffs:8192};default:return{regBase:-1,baseFuse:-1,macFuse:-1,usrOffs:-1,usr1Offs:-1,usr2Offs:-1,mosiDlenOffs:-1,misoDlenOffs:-1,w0Offs:-1,uartDateReg:-1,flashOffs:-1}}};class nn extends Error{constructor(e){super(e),this.name="SlipReadError"}}const on=async(e,t)=>{let i;return e==Xi||e==qi||e==Gi?null:(e==Di?i=await import("./esp32-CijhsJH1.js"):e==$i?i=await import("./esp32s2-IiDBtXxo.js"):e==Ni?i=await import("./esp32s3-6yv5yxum.js"):e==zi?i=await import("./esp8266-CUwxJpGa.js"):e==Pi?i=await import("./esp32c2-C17SM4gO.js"):e==Mi?i=await import("./esp32c3-DxRGijbg.js"):e==Ui?i=await import("./esp32c5-3mDOIGa4.js"):e==Hi?i=await import("./esp32c6-h6U0SQTm.js"):e==Vi?i=await import("./esp32c61-BKtexhPZ.js"):e==Wi?i=await import("./esp32h2-RtuWSEmP.js"):e==Yi&&(i=null!=t&&t>=300?await import("./esp32p4r3-CpHBYEwI.js"):await import("./esp32p4-5nkIjxqJ.js")),{...i,text:Ci(atob(i.text)),data:Ci(atob(i.data))})};function rn(e){let t=e.length;for(;--t>=0;)e[t]=0}const an=256,dn=286,sn=30,ln=15,cn=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]),hn=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]),mn=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),pn=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),un=new Array(576);rn(un);const fn=new Array(60);rn(fn);const gn=new Array(512);rn(gn);const bn=new Array(256);rn(bn);const _n=new Array(29);rn(_n);const xn=new Array(sn);function vn(e,t,i,n,o){this.static_tree=e,this.extra_bits=t,this.extra_base=i,this.elems=n,this.max_length=o,this.has_stree=e&&e.length}let yn,wn,kn;function En(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}rn(xn);const In=e=>e<256?gn[e]:gn[256+(e>>>7)],Sn=(e,t)=>{e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255},Cn=(e,t,i)=>{e.bi_valid>16-i?(e.bi_buf|=t<<e.bi_valid&65535,Sn(e,e.bi_buf),e.bi_buf=t>>16-e.bi_valid,e.bi_valid+=i-16):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=i)},Rn=(e,t,i)=>{Cn(e,i[2*t],i[2*t+1])},Tn=(e,t)=>{let i=0;do{i|=1&e,e>>>=1,i<<=1}while(--t>0);return i>>>1},An=(e,t,i)=>{const n=new Array(16);let o,r,a=0;for(o=1;o<=ln;o++)a=a+i[o-1]<<1,n[o]=a;for(r=0;r<=t;r++){let t=e[2*r+1];0!==t&&(e[2*r]=Tn(n[t]++,t))}},On=e=>{let t;for(t=0;t<dn;t++)e.dyn_ltree[2*t]=0;for(t=0;t<sn;t++)e.dyn_dtree[2*t]=0;for(t=0;t<19;t++)e.bl_tree[2*t]=0;e.dyn_ltree[512]=1,e.opt_len=e.static_len=0,e.sym_next=e.matches=0},Fn=e=>{e.bi_valid>8?Sn(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0},Ln=(e,t,i,n)=>{const o=2*t,r=2*i;return e[o]<e[r]||e[o]===e[r]&&n[t]<=n[i]},Bn=(e,t,i)=>{const n=e.heap[i];let o=i<<1;for(;o<=e.heap_len&&(o<e.heap_len&&Ln(t,e.heap[o+1],e.heap[o],e.depth)&&o++,!Ln(t,n,e.heap[o],e.depth));)e.heap[i]=e.heap[o],i=o,o<<=1;e.heap[i]=n},zn=(e,t,i)=>{let n,o,r,a,d=0;if(0!==e.sym_next)do{n=255&e.pending_buf[e.sym_buf+d++],n+=(255&e.pending_buf[e.sym_buf+d++])<<8,o=e.pending_buf[e.sym_buf+d++],0===n?Rn(e,o,t):(r=bn[o],Rn(e,r+an+1,t),a=cn[r],0!==a&&(o-=_n[r],Cn(e,o,a)),n--,r=In(n),Rn(e,r,i),a=hn[r],0!==a&&(n-=xn[r],Cn(e,n,a)))}while(d<e.sym_next);Rn(e,256,t)},Dn=(e,t)=>{const i=t.dyn_tree,n=t.stat_desc.static_tree,o=t.stat_desc.has_stree,r=t.stat_desc.elems;let a,d,s,l=-1;for(e.heap_len=0,e.heap_max=573,a=0;a<r;a++)0!==i[2*a]?(e.heap[++e.heap_len]=l=a,e.depth[a]=0):i[2*a+1]=0;for(;e.heap_len<2;)s=e.heap[++e.heap_len]=l<2?++l:0,i[2*s]=1,e.depth[s]=0,e.opt_len--,o&&(e.static_len-=n[2*s+1]);for(t.max_code=l,a=e.heap_len>>1;a>=1;a--)Bn(e,i,a);s=r;do{a=e.heap[1],e.heap[1]=e.heap[e.heap_len--],Bn(e,i,1),d=e.heap[1],e.heap[--e.heap_max]=a,e.heap[--e.heap_max]=d,i[2*s]=i[2*a]+i[2*d],e.depth[s]=(e.depth[a]>=e.depth[d]?e.depth[a]:e.depth[d])+1,i[2*a+1]=i[2*d+1]=s,e.heap[1]=s++,Bn(e,i,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],((e,t)=>{const i=t.dyn_tree,n=t.max_code,o=t.stat_desc.static_tree,r=t.stat_desc.has_stree,a=t.stat_desc.extra_bits,d=t.stat_desc.extra_base,s=t.stat_desc.max_length;let l,c,h,m,p,u,f=0;for(m=0;m<=ln;m++)e.bl_count[m]=0;for(i[2*e.heap[e.heap_max]+1]=0,l=e.heap_max+1;l<573;l++)c=e.heap[l],m=i[2*i[2*c+1]+1]+1,m>s&&(m=s,f++),i[2*c+1]=m,c>n||(e.bl_count[m]++,p=0,c>=d&&(p=a[c-d]),u=i[2*c],e.opt_len+=u*(m+p),r&&(e.static_len+=u*(o[2*c+1]+p)));if(0!==f){do{for(m=s-1;0===e.bl_count[m];)m--;e.bl_count[m]--,e.bl_count[m+1]+=2,e.bl_count[s]--,f-=2}while(f>0);for(m=s;0!==m;m--)for(c=e.bl_count[m];0!==c;)h=e.heap[--l],h>n||(i[2*h+1]!==m&&(e.opt_len+=(m-i[2*h+1])*i[2*h],i[2*h+1]=m),c--)}})(e,t),An(i,l,e.bl_count)},$n=(e,t,i)=>{let n,o,r=-1,a=t[1],d=0,s=7,l=4;for(0===a&&(s=138,l=3),t[2*(i+1)+1]=65535,n=0;n<=i;n++)o=a,a=t[2*(n+1)+1],++d<s&&o===a||(d<l?e.bl_tree[2*o]+=d:0!==o?(o!==r&&e.bl_tree[2*o]++,e.bl_tree[32]++):d<=10?e.bl_tree[34]++:e.bl_tree[36]++,d=0,r=o,0===a?(s=138,l=3):o===a?(s=6,l=3):(s=7,l=4))},Nn=(e,t,i)=>{let n,o,r=-1,a=t[1],d=0,s=7,l=4;for(0===a&&(s=138,l=3),n=0;n<=i;n++)if(o=a,a=t[2*(n+1)+1],!(++d<s&&o===a)){if(d<l)do{Rn(e,o,e.bl_tree)}while(0!==--d);else 0!==o?(o!==r&&(Rn(e,o,e.bl_tree),d--),Rn(e,16,e.bl_tree),Cn(e,d-3,2)):d<=10?(Rn(e,17,e.bl_tree),Cn(e,d-3,3)):(Rn(e,18,e.bl_tree),Cn(e,d-11,7));d=0,r=o,0===a?(s=138,l=3):o===a?(s=6,l=3):(s=7,l=4)}};let Pn=!1;const Mn=(e,t,i,n)=>{Cn(e,0+(n?1:0),3),Fn(e),Sn(e,i),Sn(e,~i),i&&e.pending_buf.set(e.window.subarray(t,t+i),e.pending),e.pending+=i};var Un=e=>{Pn||((()=>{let e,t,i,n,o;const r=new Array(16);for(i=0,n=0;n<28;n++)for(_n[n]=i,e=0;e<1<<cn[n];e++)bn[i++]=n;for(bn[i-1]=n,o=0,n=0;n<16;n++)for(xn[n]=o,e=0;e<1<<hn[n];e++)gn[o++]=n;for(o>>=7;n<sn;n++)for(xn[n]=o<<7,e=0;e<1<<hn[n]-7;e++)gn[256+o++]=n;for(t=0;t<=ln;t++)r[t]=0;for(e=0;e<=143;)un[2*e+1]=8,e++,r[8]++;for(;e<=255;)un[2*e+1]=9,e++,r[9]++;for(;e<=279;)un[2*e+1]=7,e++,r[7]++;for(;e<=287;)un[2*e+1]=8,e++,r[8]++;for(An(un,287,r),e=0;e<sn;e++)fn[2*e+1]=5,fn[2*e]=Tn(e,5);yn=new vn(un,cn,257,dn,ln),wn=new vn(fn,hn,0,sn,ln),kn=new vn(new Array(0),mn,0,19,7)})(),Pn=!0),e.l_desc=new En(e.dyn_ltree,yn),e.d_desc=new En(e.dyn_dtree,wn),e.bl_desc=new En(e.bl_tree,kn),e.bi_buf=0,e.bi_valid=0,On(e)},Hn=(e,t,i,n)=>{let o,r,a=0;e.level>0?(2===e.strm.data_type&&(e.strm.data_type=(e=>{let t,i=4093624447;for(t=0;t<=31;t++,i>>>=1)if(1&i&&0!==e.dyn_ltree[2*t])return 0;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return 1;for(t=32;t<an;t++)if(0!==e.dyn_ltree[2*t])return 1;return 0})(e)),Dn(e,e.l_desc),Dn(e,e.d_desc),a=(e=>{let t;for($n(e,e.dyn_ltree,e.l_desc.max_code),$n(e,e.dyn_dtree,e.d_desc.max_code),Dn(e,e.bl_desc),t=18;t>=3&&0===e.bl_tree[2*pn[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t})(e),o=e.opt_len+3+7>>>3,r=e.static_len+3+7>>>3,r<=o&&(o=r)):o=r=i+5,i+4<=o&&-1!==t?Mn(e,t,i,n):4===e.strategy||r===o?(Cn(e,2+(n?1:0),3),zn(e,un,fn)):(Cn(e,4+(n?1:0),3),((e,t,i,n)=>{let o;for(Cn(e,t-257,5),Cn(e,i-1,5),Cn(e,n-4,4),o=0;o<n;o++)Cn(e,e.bl_tree[2*pn[o]+1],3);Nn(e,e.dyn_ltree,t-1),Nn(e,e.dyn_dtree,i-1)})(e,e.l_desc.max_code+1,e.d_desc.max_code+1,a+1),zn(e,e.dyn_ltree,e.dyn_dtree)),On(e),n&&Fn(e)},Vn=(e,t,i)=>(e.pending_buf[e.sym_buf+e.sym_next++]=t,e.pending_buf[e.sym_buf+e.sym_next++]=t>>8,e.pending_buf[e.sym_buf+e.sym_next++]=i,0===t?e.dyn_ltree[2*i]++:(e.matches++,t--,e.dyn_ltree[2*(bn[i]+an+1)]++,e.dyn_dtree[2*In(t)]++),e.sym_next===e.sym_end),Wn=e=>{Cn(e,2,3),Rn(e,256,un),(e=>{16===e.bi_valid?(Sn(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)})(e)},Xn={_tr_init:Un,_tr_stored_block:Mn,_tr_flush_block:Hn,_tr_tally:Vn,_tr_align:Wn};var qn=(e,t,i,n)=>{let o=65535&e,r=e>>>16&65535,a=0;for(;0!==i;){a=i>2e3?2e3:i,i-=a;do{o=o+t[n++]|0,r=r+o|0}while(--a);o%=65521,r%=65521}return o|r<<16};const Yn=new Uint32Array((()=>{let e,t=[];for(var i=0;i<256;i++){e=i;for(var n=0;n<8;n++)e=1&e?3988292384^e>>>1:e>>>1;t[i]=e}return t})());var Gn=(e,t,i,n)=>{const o=Yn,r=n+i;e^=-1;for(let i=n;i<r;i++)e=e>>>8^o[255&(e^t[i])];return-1^e},jn={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"},Kn={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_OK:0,Z_STREAM_END:1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,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:Zn,_tr_stored_block:Qn,_tr_flush_block:Jn,_tr_tally:eo,_tr_align:to}=Xn,{Z_NO_FLUSH:io,Z_PARTIAL_FLUSH:no,Z_FULL_FLUSH:oo,Z_FINISH:ro,Z_BLOCK:ao,Z_OK:so,Z_STREAM_END:lo,Z_STREAM_ERROR:co,Z_DATA_ERROR:ho,Z_BUF_ERROR:mo,Z_DEFAULT_COMPRESSION:po,Z_FILTERED:uo,Z_HUFFMAN_ONLY:fo,Z_RLE:go,Z_FIXED:bo,Z_DEFAULT_STRATEGY:_o,Z_UNKNOWN:xo,Z_DEFLATED:vo}=Kn,yo=258,wo=262,ko=42,Eo=113,Io=666,So=(e,t)=>(e.msg=jn[t],t),Co=e=>2*e-(e>4?9:0),Ro=e=>{let t=e.length;for(;--t>=0;)e[t]=0},To=e=>{let t,i,n,o=e.w_size;t=e.hash_size,n=t;do{i=e.head[--n],e.head[n]=i>=o?i-o:0}while(--t);t=o,n=t;do{i=e.prev[--n],e.prev[n]=i>=o?i-o:0}while(--t)};let Ao=(e,t,i)=>(t<<e.hash_shift^i)&e.hash_mask;const Oo=e=>{const t=e.state;let i=t.pending;i>e.avail_out&&(i=e.avail_out),0!==i&&(e.output.set(t.pending_buf.subarray(t.pending_out,t.pending_out+i),e.next_out),e.next_out+=i,t.pending_out+=i,e.total_out+=i,e.avail_out-=i,t.pending-=i,0===t.pending&&(t.pending_out=0))},Fo=(e,t)=>{Jn(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,Oo(e.strm)},Lo=(e,t)=>{e.pending_buf[e.pending++]=t},Bo=(e,t)=>{e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t},zo=(e,t,i,n)=>{let o=e.avail_in;return o>n&&(o=n),0===o?0:(e.avail_in-=o,t.set(e.input.subarray(e.next_in,e.next_in+o),i),1===e.state.wrap?e.adler=qn(e.adler,t,o,i):2===e.state.wrap&&(e.adler=Gn(e.adler,t,o,i)),e.next_in+=o,e.total_in+=o,o)},Do=(e,t)=>{let i,n,o=e.max_chain_length,r=e.strstart,a=e.prev_length,d=e.nice_match;const s=e.strstart>e.w_size-wo?e.strstart-(e.w_size-wo):0,l=e.window,c=e.w_mask,h=e.prev,m=e.strstart+yo;let p=l[r+a-1],u=l[r+a];e.prev_length>=e.good_match&&(o>>=2),d>e.lookahead&&(d=e.lookahead);do{if(i=t,l[i+a]===u&&l[i+a-1]===p&&l[i]===l[r]&&l[++i]===l[r+1]){r+=2,i++;do{}while(l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&r<m);if(n=yo-(m-r),r=m-yo,n>a){if(e.match_start=t,a=n,n>=d)break;p=l[r+a-1],u=l[r+a]}}}while((t=h[t&c])>s&&0!==--o);return a<=e.lookahead?a:e.lookahead},$o=e=>{const t=e.w_size;let i,n,o;do{if(n=e.window_size-e.lookahead-e.strstart,e.strstart>=t+(t-wo)&&(e.window.set(e.window.subarray(t,t+t-n),0),e.match_start-=t,e.strstart-=t,e.block_start-=t,e.insert>e.strstart&&(e.insert=e.strstart),To(e),n+=t),0===e.strm.avail_in)break;if(i=zo(e.strm,e.window,e.strstart+e.lookahead,n),e.lookahead+=i,e.lookahead+e.insert>=3)for(o=e.strstart-e.insert,e.ins_h=e.window[o],e.ins_h=Ao(e,e.ins_h,e.window[o+1]);e.insert&&(e.ins_h=Ao(e,e.ins_h,e.window[o+3-1]),e.prev[o&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=o,o++,e.insert--,!(e.lookahead+e.insert<3)););}while(e.lookahead<wo&&0!==e.strm.avail_in)},No=(e,t)=>{let i,n,o,r=e.pending_buf_size-5>e.w_size?e.w_size:e.pending_buf_size-5,a=0,d=e.strm.avail_in;do{if(i=65535,o=e.bi_valid+42>>3,e.strm.avail_out<o)break;if(o=e.strm.avail_out-o,n=e.strstart-e.block_start,i>n+e.strm.avail_in&&(i=n+e.strm.avail_in),i>o&&(i=o),i<r&&(0===i&&t!==ro||t===io||i!==n+e.strm.avail_in))break;a=t===ro&&i===n+e.strm.avail_in?1:0,Qn(e,0,0,a),e.pending_buf[e.pending-4]=i,e.pending_buf[e.pending-3]=i>>8,e.pending_buf[e.pending-2]=~i,e.pending_buf[e.pending-1]=~i>>8,Oo(e.strm),n&&(n>i&&(n=i),e.strm.output.set(e.window.subarray(e.block_start,e.block_start+n),e.strm.next_out),e.strm.next_out+=n,e.strm.avail_out-=n,e.strm.total_out+=n,e.block_start+=n,i-=n),i&&(zo(e.strm,e.strm.output,e.strm.next_out,i),e.strm.next_out+=i,e.strm.avail_out-=i,e.strm.total_out+=i)}while(0===a);return d-=e.strm.avail_in,d&&(d>=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<=d&&(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-d,e.strm.next_in),e.strstart),e.strstart+=d,e.insert+=d>e.w_size-e.insert?e.w_size-e.insert:d),e.block_start=e.strstart),e.high_water<e.strstart&&(e.high_water=e.strstart),a?4:t!==io&&t!==ro&&0===e.strm.avail_in&&e.strstart===e.block_start?2:(o=e.window_size-e.strstart,e.strm.avail_in>o&&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++,o+=e.w_size,e.insert>e.strstart&&(e.insert=e.strstart)),o>e.strm.avail_in&&(o=e.strm.avail_in),o&&(zo(e.strm,e.window,e.strstart,o),e.strstart+=o,e.insert+=o>e.w_size-e.insert?e.w_size-e.insert:o),e.high_water<e.strstart&&(e.high_water=e.strstart),o=e.bi_valid+42>>3,o=e.pending_buf_size-o>65535?65535:e.pending_buf_size-o,r=o>e.w_size?e.w_size:o,n=e.strstart-e.block_start,(n>=r||(n||t===ro)&&t!==io&&0===e.strm.avail_in&&n<=o)&&(i=n>o?o:n,a=t===ro&&0===e.strm.avail_in&&i===n?1:0,Qn(e,e.block_start,i,a),e.block_start+=i,Oo(e.strm)),a?3:1)},Po=(e,t)=>{let i,n;for(;;){if(e.lookahead<wo){if($o(e),e.lookahead<wo&&t===io)return 1;if(0===e.lookahead)break}if(i=0,e.lookahead>=3&&(e.ins_h=Ao(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!==i&&e.strstart-i<=e.w_size-wo&&(e.match_length=Do(e,i)),e.match_length>=3)if(n=eo(e,e.strstart-e.match_start,e.match_length-3),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=3){e.match_length--;do{e.strstart++,e.ins_h=Ao(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart}while(0!==--e.match_length);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=Ao(e,e.ins_h,e.window[e.strstart+1]);else n=eo(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(n&&(Fo(e,!1),0===e.strm.avail_out))return 1}return e.insert=e.strstart<2?e.strstart:2,t===ro?(Fo(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(Fo(e,!1),0===e.strm.avail_out)?1:2},Mo=(e,t)=>{let i,n,o;for(;;){if(e.lookahead<wo){if($o(e),e.lookahead<wo&&t===io)return 1;if(0===e.lookahead)break}if(i=0,e.lookahead>=3&&(e.ins_h=Ao(e,e.ins_h,e.window[e.strstart+3-1]),i=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=2,0!==i&&e.prev_length<e.max_lazy_match&&e.strstart-i<=e.w_size-wo&&(e.match_length=Do(e,i),e.match_length<=5&&(e.strategy===uo||3===e.match_length&&e.strstart-e.match_start>4096)&&(e.match_length=2)),e.prev_length>=3&&e.match_length<=e.prev_length){o=e.strstart+e.lookahead-3,n=eo(e,e.strstart-1-e.prev_match,e.prev_length-3),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=o&&(e.ins_h=Ao(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart)}while(0!==--e.prev_length);if(e.match_available=0,e.match_length=2,e.strstart++,n&&(Fo(e,!1),0===e.strm.avail_out))return 1}else if(e.match_available){if(n=eo(e,0,e.window[e.strstart-1]),n&&Fo(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return 1}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(n=eo(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<2?e.strstart:2,t===ro?(Fo(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(Fo(e,!1),0===e.strm.avail_out)?1:2};function Uo(e,t,i,n,o){this.good_length=e,this.max_lazy=t,this.nice_length=i,this.max_chain=n,this.func=o}const Ho=[new Uo(0,0,0,0,No),new Uo(4,4,8,4,Po),new Uo(4,5,16,8,Po),new Uo(4,6,32,32,Po),new Uo(4,4,16,16,Mo),new Uo(8,16,32,32,Mo),new Uo(8,16,128,128,Mo),new Uo(8,32,128,256,Mo),new Uo(32,128,258,1024,Mo),new Uo(32,258,258,4096,Mo)];function Vo(){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=vo,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(1146),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),Ro(this.dyn_ltree),Ro(this.dyn_dtree),Ro(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),Ro(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),Ro(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 Wo=e=>{if(!e)return 1;const t=e.state;return!t||t.strm!==e||t.status!==ko&&57!==t.status&&69!==t.status&&73!==t.status&&91!==t.status&&103!==t.status&&t.status!==Eo&&t.status!==Io?1:0},Xo=e=>{if(Wo(e))return So(e,co);e.total_in=e.total_out=0,e.data_type=xo;const t=e.state;return t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=2===t.wrap?57:t.wrap?ko:Eo,e.adler=2===t.wrap?0:1,t.last_flush=-2,Zn(t),so},qo=e=>{const t=Xo(e);return t===so&&(e=>{e.window_size=2*e.w_size,Ro(e.head),e.max_lazy_match=Ho[e.level].max_lazy,e.good_match=Ho[e.level].good_length,e.nice_match=Ho[e.level].nice_length,e.max_chain_length=Ho[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=2,e.match_available=0,e.ins_h=0})(e.state),t},Yo=(e,t,i,n,o,r)=>{if(!e)return co;let a=1;if(t===po&&(t=6),n<0?(a=0,n=-n):n>15&&(a=2,n-=16),o<1||o>9||i!==vo||n<8||n>15||t<0||t>9||r<0||r>bo||8===n&&1!==a)return So(e,co);8===n&&(n=9);const d=new Vo;return e.state=d,d.strm=e,d.status=ko,d.wrap=a,d.gzhead=null,d.w_bits=n,d.w_size=1<<d.w_bits,d.w_mask=d.w_size-1,d.hash_bits=o+7,d.hash_size=1<<d.hash_bits,d.hash_mask=d.hash_size-1,d.hash_shift=~~((d.hash_bits+3-1)/3),d.window=new Uint8Array(2*d.w_size),d.head=new Uint16Array(d.hash_size),d.prev=new Uint16Array(d.w_size),d.lit_bufsize=1<<o+6,d.pending_buf_size=4*d.lit_bufsize,d.pending_buf=new Uint8Array(d.pending_buf_size),d.sym_buf=d.lit_bufsize,d.sym_end=3*(d.lit_bufsize-1),d.level=t,d.strategy=r,d.method=i,qo(e)};var Go=(e,t)=>{if(Wo(e)||t>ao||t<0)return e?So(e,co):co;const i=e.state;if(!e.output||0!==e.avail_in&&!e.input||i.status===Io&&t!==ro)return So(e,0===e.avail_out?mo:co);const n=i.last_flush;if(i.last_flush=t,0!==i.pending){if(Oo(e),0===e.avail_out)return i.last_flush=-1,so}else if(0===e.avail_in&&Co(t)<=Co(n)&&t!==ro)return So(e,mo);if(i.status===Io&&0!==e.avail_in)return So(e,mo);if(i.status===ko&&0===i.wrap&&(i.status=Eo),i.status===ko){let t=vo+(i.w_bits-8<<4)<<8,n=-1;if(n=i.strategy>=fo||i.level<2?0:i.level<6?1:6===i.level?2:3,t|=n<<6,0!==i.strstart&&(t|=32),t+=31-t%31,Bo(i,t),0!==i.strstart&&(Bo(i,e.adler>>>16),Bo(i,65535&e.adler)),e.adler=1,i.status=Eo,Oo(e),0!==i.pending)return i.last_flush=-1,so}if(57===i.status)if(e.adler=0,Lo(i,31),Lo(i,139),Lo(i,8),i.gzhead)Lo(i,(i.gzhead.text?1:0)+(i.gzhead.hcrc?2:0)+(i.gzhead.extra?4:0)+(i.gzhead.name?8:0)+(i.gzhead.comment?16:0)),Lo(i,255&i.gzhead.time),Lo(i,i.gzhead.time>>8&255),Lo(i,i.gzhead.time>>16&255),Lo(i,i.gzhead.time>>24&255),Lo(i,9===i.level?2:i.strategy>=fo||i.level<2?4:0),Lo(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(Lo(i,255&i.gzhead.extra.length),Lo(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(e.adler=Gn(e.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=69;else if(Lo(i,0),Lo(i,0),Lo(i,0),Lo(i,0),Lo(i,0),Lo(i,9===i.level?2:i.strategy>=fo||i.level<2?4:0),Lo(i,3),i.status=Eo,Oo(e),0!==i.pending)return i.last_flush=-1,so;if(69===i.status){if(i.gzhead.extra){let t=i.pending,n=(65535&i.gzhead.extra.length)-i.gzindex;for(;i.pending+n>i.pending_buf_size;){let o=i.pending_buf_size-i.pending;if(i.pending_buf.set(i.gzhead.extra.subarray(i.gzindex,i.gzindex+o),i.pending),i.pending=i.pending_buf_size,i.gzhead.hcrc&&i.pending>t&&(e.adler=Gn(e.adler,i.pending_buf,i.pending-t,t)),i.gzindex+=o,Oo(e),0!==i.pending)return i.last_flush=-1,so;t=0,n-=o}let o=new Uint8Array(i.gzhead.extra);i.pending_buf.set(o.subarray(i.gzindex,i.gzindex+n),i.pending),i.pending+=n,i.gzhead.hcrc&&i.pending>t&&(e.adler=Gn(e.adler,i.pending_buf,i.pending-t,t)),i.gzindex=0}i.status=73}if(73===i.status){if(i.gzhead.name){let t,n=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>n&&(e.adler=Gn(e.adler,i.pending_buf,i.pending-n,n)),Oo(e),0!==i.pending)return i.last_flush=-1,so;n=0}t=i.gzindex<i.gzhead.name.length?255&i.gzhead.name.charCodeAt(i.gzindex++):0,Lo(i,t)}while(0!==t);i.gzhead.hcrc&&i.pending>n&&(e.adler=Gn(e.adler,i.pending_buf,i.pending-n,n)),i.gzindex=0}i.status=91}if(91===i.status){if(i.gzhead.comment){let t,n=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>n&&(e.adler=Gn(e.adler,i.pending_buf,i.pending-n,n)),Oo(e),0!==i.pending)return i.last_flush=-1,so;n=0}t=i.gzindex<i.gzhead.comment.length?255&i.gzhead.comment.charCodeAt(i.gzindex++):0,Lo(i,t)}while(0!==t);i.gzhead.hcrc&&i.pending>n&&(e.adler=Gn(e.adler,i.pending_buf,i.pending-n,n))}i.status=103}if(103===i.status){if(i.gzhead.hcrc){if(i.pending+2>i.pending_buf_size&&(Oo(e),0!==i.pending))return i.last_flush=-1,so;Lo(i,255&e.adler),Lo(i,e.adler>>8&255),e.adler=0}if(i.status=Eo,Oo(e),0!==i.pending)return i.last_flush=-1,so}if(0!==e.avail_in||0!==i.lookahead||t!==io&&i.status!==Io){let n=0===i.level?No(i,t):i.strategy===fo?((e,t)=>{let i;for(;;){if(0===e.lookahead&&($o(e),0===e.lookahead)){if(t===io)return 1;break}if(e.match_length=0,i=eo(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,i&&(Fo(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===ro?(Fo(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(Fo(e,!1),0===e.strm.avail_out)?1:2})(i,t):i.strategy===go?((e,t)=>{let i,n,o,r;const a=e.window;for(;;){if(e.lookahead<=yo){if($o(e),e.lookahead<=yo&&t===io)return 1;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=3&&e.strstart>0&&(o=e.strstart-1,n=a[o],n===a[++o]&&n===a[++o]&&n===a[++o])){r=e.strstart+yo;do{}while(n===a[++o]&&n===a[++o]&&n===a[++o]&&n===a[++o]&&n===a[++o]&&n===a[++o]&&n===a[++o]&&n===a[++o]&&o<r);e.match_length=yo-(r-o),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=3?(i=eo(e,1,e.match_length-3),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(i=eo(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),i&&(Fo(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===ro?(Fo(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(Fo(e,!1),0===e.strm.avail_out)?1:2})(i,t):Ho[i.level].func(i,t);if(3!==n&&4!==n||(i.status=Io),1===n||3===n)return 0===e.avail_out&&(i.last_flush=-1),so;if(2===n&&(t===no?to(i):t!==ao&&(Qn(i,0,0,!1),t===oo&&(Ro(i.head),0===i.lookahead&&(i.strstart=0,i.block_start=0,i.insert=0))),Oo(e),0===e.avail_out))return i.last_flush=-1,so}return t!==ro?so:i.wrap<=0?lo:(2===i.wrap?(Lo(i,255&e.adler),Lo(i,e.adler>>8&255),Lo(i,e.adler>>16&255),Lo(i,e.adler>>24&255),Lo(i,255&e.total_in),Lo(i,e.total_in>>8&255),Lo(i,e.total_in>>16&255),Lo(i,e.total_in>>24&255)):(Bo(i,e.adler>>>16),Bo(i,65535&e.adler)),Oo(e),i.wrap>0&&(i.wrap=-i.wrap),0!==i.pending?so:lo)},jo=(e,t)=>{let i=t.length;if(Wo(e))return co;const n=e.state,o=n.wrap;if(2===o||1===o&&n.status!==ko||n.lookahead)return co;if(1===o&&(e.adler=qn(e.adler,t,i,0)),n.wrap=0,i>=n.w_size){0===o&&(Ro(n.head),n.strstart=0,n.block_start=0,n.insert=0);let e=new Uint8Array(n.w_size);e.set(t.subarray(i-n.w_size,i),0),t=e,i=n.w_size}const r=e.avail_in,a=e.next_in,d=e.input;for(e.avail_in=i,e.next_in=0,e.input=t,$o(n);n.lookahead>=3;){let e=n.strstart,t=n.lookahead-2;do{n.ins_h=Ao(n,n.ins_h,n.window[e+3-1]),n.prev[e&n.w_mask]=n.head[n.ins_h],n.head[n.ins_h]=e,e++}while(--t);n.strstart=e,n.lookahead=2,$o(n)}return n.strstart+=n.lookahead,n.block_start=n.strstart,n.insert=n.lookahead,n.lookahead=0,n.match_length=n.prev_length=2,n.match_available=0,e.next_in=a,e.input=d,e.avail_in=r,n.wrap=o,so},Ko={deflateInit:(e,t)=>Yo(e,t,vo,15,8,_o),deflateInit2:Yo,deflateReset:qo,deflateResetKeep:Xo,deflateSetHeader:(e,t)=>Wo(e)||2!==e.state.wrap?co:(e.state.gzhead=t,so),deflate:Go,deflateEnd:e=>{if(Wo(e))return co;const t=e.state.status;return e.state=null,t===Eo?So(e,ho):so},deflateSetDictionary:jo,deflateInfo:"pako deflate (from Nodeca project)"};const Zo=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var Qo=function(e){const t=Array.prototype.slice.call(arguments,1);for(;t.length;){const i=t.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(const t in i)Zo(i,t)&&(e[t]=i[t])}}return e},Jo=e=>{let t=0;for(let i=0,n=e.length;i<n;i++)t+=e[i].length;const i=new Uint8Array(t);for(let t=0,n=0,o=e.length;t<o;t++){let o=e[t];i.set(o,n),n+=o.length}return i};let er=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){er=!1}const tr=new Uint8Array(256);for(let e=0;e<256;e++)tr[e]=e>=252?6:e>=248?5:e>=240?4:e>=224?3:e>=192?2:1;tr[254]=tr[254]=1;var ir=e=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(e);let t,i,n,o,r,a=e.length,d=0;for(o=0;o<a;o++)i=e.charCodeAt(o),55296==(64512&i)&&o+1<a&&(n=e.charCodeAt(o+1),56320==(64512&n)&&(i=65536+(i-55296<<10)+(n-56320),o++)),d+=i<128?1:i<2048?2:i<65536?3:4;for(t=new Uint8Array(d),r=0,o=0;r<d;o++)i=e.charCodeAt(o),55296==(64512&i)&&o+1<a&&(n=e.charCodeAt(o+1),56320==(64512&n)&&(i=65536+(i-55296<<10)+(n-56320),o++)),i<128?t[r++]=i:i<2048?(t[r++]=192|i>>>6,t[r++]=128|63&i):i<65536?(t[r++]=224|i>>>12,t[r++]=128|i>>>6&63,t[r++]=128|63&i):(t[r++]=240|i>>>18,t[r++]=128|i>>>12&63,t[r++]=128|i>>>6&63,t[r++]=128|63&i);return t};var nr=function(){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};const or=Object.prototype.toString,{Z_NO_FLUSH:rr,Z_SYNC_FLUSH:ar,Z_FULL_FLUSH:dr,Z_FINISH:sr,Z_OK:lr,Z_STREAM_END:cr,Z_DEFAULT_COMPRESSION:hr,Z_DEFAULT_STRATEGY:mr,Z_DEFLATED:pr}=Kn;function ur(e){this.options=Qo({level:hr,method:pr,chunkSize:16384,windowBits:15,memLevel:8,strategy:mr},e||{});let t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new nr,this.strm.avail_out=0;let i=Ko.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(i!==lr)throw new Error(jn[i]);if(t.header&&Ko.deflateSetHeader(this.strm,t.header),t.dictionary){let e;if(e="string"==typeof t.dictionary?ir(t.dictionary):"[object ArrayBuffer]"===or.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,i=Ko.deflateSetDictionary(this.strm,e),i!==lr)throw new Error(jn[i]);this._dict_set=!0}}ur.prototype.push=function(e,t){const i=this.strm,n=this.options.chunkSize;let o,r;if(this.ended)return!1;for(r=t===~~t?t:!0===t?sr:rr,"string"==typeof e?i.input=ir(e):"[object ArrayBuffer]"===or.call(e)?i.input=new Uint8Array(e):i.input=e,i.next_in=0,i.avail_in=i.input.length;;)if(0===i.avail_out&&(i.output=new Uint8Array(n),i.next_out=0,i.avail_out=n),(r===ar||r===dr)&&i.avail_out<=6)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else{if(o=Ko.deflate(i,r),o===cr)return i.next_out>0&&this.onData(i.output.subarray(0,i.next_out)),o=Ko.deflateEnd(this.strm),this.onEnd(o),this.ended=!0,o===lr;if(0!==i.avail_out){if(r>0&&i.next_out>0)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else if(0===i.avail_in)break}else this.onData(i.output)}return!0},ur.prototype.onData=function(e){this.chunks.push(e)},ur.prototype.onEnd=function(e){e===lr&&(this.result=Jo(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var fr={deflate:function(e,t){const i=new ur(t);if(i.push(e,!0),i.err)throw i.msg||jn[i.err];return i.result}};const{deflate:gr}=fr;var br=gr;const _r={b:{u:DataView.prototype.getInt8,p:DataView.prototype.setInt8,bytes:1},B:{u:DataView.prototype.getUint8,p:DataView.prototype.setUint8,bytes:1},h:{u:DataView.prototype.getInt16,p:DataView.prototype.setInt16,bytes:2},H:{u:DataView.prototype.getUint16,p:DataView.prototype.setUint16,bytes:2},i:{u:DataView.prototype.getInt32,p:DataView.prototype.setInt32,bytes:4},I:{u:DataView.prototype.getUint32,p:DataView.prototype.setUint32,bytes:4}},xr=(e,...t)=>{let i=0;if(e.replace(/[<>]/,"").length!=t.length)throw"Pack format to Argument count mismatch";const n=[];let o=!0;for(let n=0;n<e.length;n++)"<"==e[n]?o=!0:">"==e[n]?o=!1:(r(e[n],t[i]),i++);function r(e,t){if(!(e in _r))throw"Unhandled character '"+e+"' in pack format";const i=_r[e].bytes,r=new DataView(new ArrayBuffer(i));_r[e].p.bind(r)(0,t,o);for(let e=0;e<i;e++)n.push(r.getUint8(e))}return n},vr=(e,t)=>{let i=0;const n=[];let o=!0;for(const t of e)"<"==t?o=!0:">"==t?o=!1:r(t);function r(e){if(!(e in _r))throw"Unhandled character '"+e+"' in unpack format";const r=_r[e].bytes,a=new DataView(new ArrayBuffer(r));for(let e=0;e<r;e++)a.setUint8(e,255&t[i+e]);const d=_r[e].u.bind(a);n.push(d(0,o)),i+=r}return n};class yr extends EventTarget{constructor(e,t,i){super(),this.port=e,this.logger=t,this._parent=i,this.chipName=null,this.chipRevision=null,this.chipVariant=null,this._efuses=new Array(4).fill(0),this._flashsize=4194304,this.debug=!1,this.IS_STUB=!1,this.connected=!0,this.flashSize=null,this._currentBaudRate=Fi,this._isESP32S2NativeUSB=!1,this._initializationSucceeded=!1,this.state_DTR=!1}get _inputBuffer(){return this._parent?this._parent._inputBuffer:this.__inputBuffer}get _totalBytesRead(){return this._parent?this._parent._totalBytesRead:this.__totalBytesRead||0}set _totalBytesRead(e){this._parent?this._parent._totalBytesRead=e:this.__totalBytesRead=e}detectUSBSerialChip(e,t){const i={6790:{29986:{name:"CH340",maxBaudrate:460800},29987:{name:"CH340",maxBaudrate:460800},30084:{name:"CH340",maxBaudrate:460800},21795:{name:"CH341",maxBaudrate:2e6},21971:{name:"CH343",maxBaudrate:6e6},21972:{name:"CH9102",maxBaudrate:6e6},21976:{name:"CH9101",maxBaudrate:3e6}},4292:{6e4:{name:"CP2102(n)",maxBaudrate:3e6},60016:{name:"CP2105",maxBaudrate:2e6},60017:{name:"CP2108",maxBaudrate:2e6}},1027:{24577:{name:"FT232R",maxBaudrate:3e6},24592:{name:"FT2232",maxBaudrate:3e6},24593:{name:"FT4232",maxBaudrate:3e6},24596:{name:"FT232H",maxBaudrate:12e6},24597:{name:"FT230X",maxBaudrate:3e6}},12346:{2:{name:"ESP32-S2 Native USB",maxBaudrate:2e6},4097:{name:"ESP32 Native USB",maxBaudrate:2e6},4098:{name:"ESP32 Native USB",maxBaudrate:2e6},16386:{name:"ESP32 Native USB",maxBaudrate:2e6},4096:{name:"ESP32 Native USB",maxBaudrate:2e6}}}[e];return i&&i[t]?i[t]:{name:`Unknown (VID: 0x${e.toString(16)}, PID: 0x${t.toString(16)})`}}async initialize(){if(await this.hardReset(!0),!this._parent){this.__inputBuffer=[],this.__totalBytesRead=0;const e=this.port.getInfo();if(e.usbVendorId&&e.usbProductId){const t=this.detectUSBSerialChip(e.usbVendorId,e.usbProductId);this.logger.log(`USB-Serial: ${t.name} (VID: 0x${e.usbVendorId.toString(16)}, PID: 0x${e.usbProductId.toString(16)})`),t.maxBaudrate&&(this._maxUSBSerialBaudrate=t.maxBaudrate,this.logger.log(`Max baudrate: ${t.maxBaudrate}`)),12346!==e.usbVendorId||2!==e.usbProductId&&4097!==e.usbProductId||(this._isESP32S2NativeUSB=!0)}this.readLoop()}await this.flushSerialBuffers(),await this.sync(),await this.detectChip();const e=tn(this.getChipFamily()),t=e.macFuse;for(let e=0;e<4;e++)this._efuses[e]=await this.readRegister(t+4*e);this.logger.log(`Chip type ${this.chipName}`),this.logger.debug(`Bootloader flash offset: 0x${e.flashOffs.toString(16)}`),this._initializationSucceeded=!0}async detectChip(){try{const e=(await this.getSecurityInfo()).chipId,t=ji[e];if(t)return this.chipName=t.name,this.chipFamily=t.family,this.chipFamily===Yi&&(this.chipRevision=await this.getChipRevision(),this.logger.debug(`ESP32-P4 revision: ${this.chipRevision}`),this.chipRevision>=300?this.chipVariant="rev300":this.chipVariant="rev0",this.logger.debug(`ESP32-P4 variant: ${this.chipVariant}`)),void this.logger.debug(`Detected chip via IMAGE_CHIP_ID: ${e} (${this.chipName})`);this.logger.debug(`Unknown IMAGE_CHIP_ID: ${e}, falling back to magic value detection`)}catch(e){this.logger.debug(`GET_SECURITY_INFO failed, using magic value detection: ${e}`),this._inputBuffer.length=0,await Ai(Ji);try{await this.sync()}catch(e){this.logger.debug(`Re-sync after GET_SECURITY_INFO failure: ${e}`)}}const e=await this.readRegister(1073745920),t=Ki[e>>>0];if(void 0===t)throw new Error(`Unknown Chip: Hex: ${Ti(e>>>0,8).toLowerCase()} Number: ${e}`);this.chipName=t.name,this.chipFamily=t.family,this.chipFamily===Yi&&(this.chipRevision=await this.getChipRevision(),this.logger.debug(`ESP32-P4 revision: ${this.chipRevision}`),this.chipRevision>=300?this.chipVariant="rev300":this.chipVariant="rev0",this.logger.debug(`ESP32-P4 variant: ${this.chipVariant}`)),this.logger.debug(`Detected chip via magic value: ${Ti(e>>>0,8)} (${this.chipName})`)}async getChipRevision(){if(this.chipFamily!==Yi)return 0;const e=await this.readRegister(1343410252);return 100*((e>>23&1)<<2|e>>4&3)+(15&e)}async getSecurityInfo(){const[,e]=await this.checkCommand(20,[],0);if(0===e.length)throw new Error("GET_SECURITY_INFO not supported or returned empty response");if(e.length<12)throw new Error(`Invalid security info response length: ${e.length} (expected at least 12 bytes)`);return{flags:vr("<I",e.slice(0,4))[0],flashCryptCnt:e[4],keyPurposes:Array.from(e.slice(5,12)),chipId:e.length>=16?vr("<I",e.slice(12,16))[0]:0,apiVersion:e.length>=20?vr("<I",e.slice(16,20))[0]:0}}async readLoop(){this.debug&&this.logger.debug("Starting read loop"),this._reader=this.port.readable.getReader();try{let e=!0;for(;e;){const{value:t,done:i}=await this._reader.read();if(i){this._reader.releaseLock(),e=!1;break}if(!t||0===t.length)continue;const n=Array.from(t);Array.prototype.push.apply(this._inputBuffer,n),this._totalBytesRead+=t.length}}catch{this.logger.error("Read loop got disconnected")}this.connected=!1,this._isESP32S2NativeUSB&&!this._initializationSucceeded&&(this.logger.log("ESP32-S2 Native USB detected - requesting port reselection"),this.dispatchEvent(new CustomEvent("esp32s2-usb-reconnect",{detail:{message:"ESP32-S2 Native USB requires port reselection"}}))),this.dispatchEvent(new Event("disconnect")),this.logger.debug("Finished read loop")}sleep(e=100){return new Promise(t=>setTimeout(t,e))}async setRTS(e){await this.port.setSignals({requestToSend:e}),await this.setDTR(this.state_DTR)}async setDTR(e){this.state_DTR=e,await this.port.setSignals({dataTerminalReady:e})}async hardReset(e=!1){e?4097===this.port.getInfo().usbProductId?(await this.setDTR(!1),await this.setRTS(!1),await this.sleep(100),await this.setDTR(!0),await this.setRTS(!1),await this.sleep(100),await this.setRTS(!0),await this.setDTR(!1),await this.setRTS(!0),await this.sleep(100),await this.setDTR(!1),await this.setRTS(!1),this.logger.log("USB MCU reset.")):(await this.setDTR(!1),await this.setRTS(!0),await this.sleep(100),await this.setDTR(!0),await this.setRTS(!1),await this.sleep(50),await this.setDTR(!1),this.logger.log("DTR/RTS USB serial chip reset.")):(await this.setRTS(!0),await this.sleep(100),await this.setRTS(!1),this.logger.log("Hard reset.")),await new Promise(e=>setTimeout(e,1e3))}macAddr(){const e=new Array(6).fill(0),t=this._efuses[0],i=this._efuses[1],n=this._efuses[2],o=this._efuses[3];let r;if(this.chipFamily==zi){if(0!=o)r=[o>>16&255,o>>8&255,255&o];else if(i>>16&255){if(1!=(i>>16&255))throw new Error("Couldnt determine OUI");r=[172,208,116]}else r=[24,254,52];e[0]=r[0],e[1]=r[1],e[2]=r[2],e[3]=i>>8&255,e[4]=255&i,e[5]=t>>24&255}else if(this.chipFamily==Di)e[0]=n>>8&255,e[1]=255&n,e[2]=i>>24&255,e[3]=i>>16&255,e[4]=i>>8&255,e[5]=255&i;else{if(this.chipFamily!=$i&&this.chipFamily!=Ni&&this.chipFamily!=Pi&&this.chipFamily!=Mi&&this.chipFamily!=Ui&&this.chipFamily!=Hi&&this.chipFamily!=Vi&&this.chipFamily!=Wi&&this.chipFamily!=Xi&&this.chipFamily!=qi&&this.chipFamily!=Yi&&this.chipFamily!=Gi)throw new Error("Unknown chip family");e[0]=i>>8&255,e[1]=255&i,e[2]=t>>24&255,e[3]=t>>16&255,e[4]=t>>8&255,e[5]=255&t}return e}async readRegister(e){this.debug&&this.logger.debug("Reading from Register "+Ti(e,8));const t=xr("<I",e);await this.sendCommand(10,t);const[i]=await this.getResponse(10);return i}async checkCommand(e,t,i=0,n=3e3){n=Math.min(n,3e5),await this.sendCommand(e,t,i);const[o,r]=await this.getResponse(e,n);if(null===r)throw new Error("Didn't get enough status bytes");let a=r,d=0;if(this.IS_STUB||this.chipFamily==zi?d=2:[Di,$i,Ni,Pi,Mi,Ui,Hi,Vi,Wi,Xi,qi,Yi,Gi].includes(this.chipFamily)||20===e?d=4:[2,4].includes(a.length)&&(d=a.length),a.length<d)throw new Error("Didn't get enough status bytes");const s=a.slice(-d,a.length);if(a=a.slice(0,-d),this.debug&&(this.logger.debug("status",s),this.logger.debug("value",o),this.logger.debug("data",a)),1==s[0])throw 5==s[1]?new Error("Invalid (unsupported) command "+Ti(e)):new Error("Command failure error code "+Ti(s[1]));return[o,a]}async sendCommand(e,t,i=0){const n=Si([...xr("<BBHI",0,e,t.length,i),...t]);this.debug&&this.logger.debug(`Writing ${n.length} byte${1==n.length?"":"s"}:`,n),await this.writeToStream(n)}async readPacket(e){let t=null,i=!1,n=[];for(;;){const o=Date.now();for(n=[];Date.now()-o<e;){if(this._inputBuffer.length>0){n.push(this._inputBuffer.shift());break}await Ai(1)}if(0==n.length){throw new nn("Timed out waiting for packet "+(null===t?"header":"content"))}this.debug&&this.logger.debug("Read "+n.length+" bytes: "+Ri(n));for(const e of n)if(null===t){if(192!=e)throw this.debug&&(this.logger.debug("Read invalid data: "+Ri(n)),this.logger.debug("Remaining data in serial buffer: "+Ri(this._inputBuffer))),new nn("Invalid head of packet ("+Ti(e)+")");t=[]}else if(i)if(i=!1,220==e)t.push(192);else{if(221!=e)throw this.debug&&(this.logger.debug("Read invalid data: "+Ri(n)),this.logger.debug("Remaining data in serial buffer: "+Ri(this._inputBuffer))),new nn("Invalid SLIP escape (0xdb, "+Ti(e)+")");t.push(219)}else if(219==e)i=!0;else{if(192==e)return this.debug&&this.logger.debug("Received full packet: "+Ri(t)),t;t.push(e)}}throw new nn("Invalid state")}async getResponse(e,t=3e3){for(let i=0;i<100;i++){const i=await this.readPacket(t);if(i.length<8)continue;const[n,o,,r]=vr("<BBHI",i.slice(0,8));if(1!=n)continue;const a=i.slice(8);if(null==e||o==e)return[r,a];if(0!=a[0]&&5==a[1])throw this._inputBuffer.length=0,new Error(`Invalid (unsupported) command ${Ti(e)}`)}throw"Response doesn't match request"}checksum(e,t=239){for(const i of e)t^=i;return t}async setBaudrate(e){if(this.chipFamily==zi)throw new Error("Changing baud rate is not supported on the ESP8266");try{const t=xr("<II",e,this.IS_STUB?Fi:0);await this.checkCommand(15,t)}catch(t){throw this.logger.error(`Baudrate change error: ${t}`),new Error(`Unable to change the baud rate to ${e}: No response from set baud rate command.`)}this._parent?await this._parent.reconfigurePort(e):await this.reconfigurePort(e),this._parent?this._parent._currentBaudRate=e:this._currentBaudRate=e;const t=this._parent?this._parent._maxUSBSerialBaudrate:this._maxUSBSerialBaudrate;t&&e>t&&(this.logger.log(`⚠️ WARNING: Baudrate ${e} exceeds USB-Serial chip limit (${t})!`),this.logger.log("⚠️ This may cause data corruption or connection failures!")),this.logger.log(`Changed baud rate to ${e}`)}async reconfigurePort(e){var t;try{await(null===(t=this._reader)||void 0===t?void 0:t.cancel()),await this.port.close(),await this.port.open({baudRate:e}),await this.flushSerialBuffers(),this.readLoop()}catch(t){throw this.logger.error(`Reconfigure port error: ${t}`),new Error(`Unable to change the baud rate to ${e}: ${t}`)}}async sync(){for(let e=0;e<5;e++){this._inputBuffer.length=0;if(await this._sync())return await Ai(Ji),!0;await Ai(Ji)}throw new Error("Couldn't sync to ESP. Try resetting.")}async _sync(){await this.sendCommand(8,Bi);for(let e=0;e<8;e++)try{const[,e]=await this.getResponse(8,Ji);if(e.length>1&&0==e[0]&&0==e[1])return!0}catch{}return!1}getFlashWriteSize(){return this.IS_STUB?16384:1024}async flashData(e,t,i=0,n=!1){if(e.byteLength>=8){const t=Array.from(new Uint8Array(e,0,4)),i=t[0],n=t[2],o=t[3];this.logger.log(`Image header, Magic=${Ti(i)}, FlashMode=${Ti(n)}, FlashSizeFreq=${Ti(o)}`)}const o=e.byteLength;let r,a=0,d=Zi;n?(r=br(new Uint8Array(e),{level:9}).buffer,a=r.byteLength,this.logger.log(`Writing data with filesize: ${o}. Compressed Size: ${a}`),d=await this.flashDeflBegin(o,a,i)):(this.logger.log(`Writing data with filesize: ${o}`),r=e,await this.flashBegin(o,i));let s=[],l=0,c=0,h=0;const m=Date.now(),p=this.getFlashWriteSize(),u=n?a:o;for(;u-h>0;)this.debug&&this.logger.log(`Writing at ${Ti(i+l*p,8)} `),u-h>=p?s=Array.from(new Uint8Array(r,h,p)):(s=Array.from(new Uint8Array(r,h,u-h)),n||(s=s.concat(new Array(p-s.length).fill(255)))),n?await this.flashDeflBlock(s,l,d):await this.flashBlock(s,l),l+=1,c+=n?Math.round(s.length*o/a):s.length,h+=p,t(Math.min(c,o),o);this.logger.log("Took "+(Date.now()-m)+"ms to write "+u+" bytes"),this.IS_STUB&&(await this.flashBegin(0,0),n?await this.flashDeflFinish():await this.flashFinish())}async flashBlock(e,t,i=3e3){await this.checkCommand(3,xr("<IIII",e.length,t,0,0).concat(e),this.checksum(e),i)}async flashDeflBlock(e,t,i=3e3){await this.checkCommand(17,xr("<IIII",e.length,t,0,0).concat(e),this.checksum(e),i)}async flashBegin(e=0,t=0,i=!1){let n;await this.flushSerialBuffers();const o=this.getFlashWriteSize();!this.IS_STUB&&[Di,$i,Ni,Pi,Mi,Ui,Hi,Vi,Wi,Xi,qi,Yi,Gi].includes(this.chipFamily)&&await this.checkCommand(13,new Array(8).fill(0));const r=Math.floor((e+o-1)/o);n=this.chipFamily==zi?this.getEraseSize(t,e):e;const a=this.IS_STUB?Zi:en(3e4,e),d=Date.now();let s=xr("<IIII",n,r,o,t);return this.chipFamily!=Di&&this.chipFamily!=$i&&this.chipFamily!=Ni&&this.chipFamily!=Pi&&this.chipFamily!=Mi&&this.chipFamily!=Ui&&this.chipFamily!=Hi&&this.chipFamily!=Vi&&this.chipFamily!=Wi&&this.chipFamily!=Xi&&this.chipFamily!=qi&&this.chipFamily!=Yi&&this.chipFamily!=Gi||(s=s.concat(xr("<I",i?1:0))),this.logger.log("Erase size "+n+", blocks "+r+", block size "+Ti(o,4)+", offset "+Ti(t,4)+", encrypted "+(i?"yes":"no")),await this.checkCommand(2,s,0,a),0==e||this.IS_STUB||this.logger.log("Took "+(Date.now()-d)+"ms to erase "+r+" bytes"),r}async flashDeflBegin(e=0,t=0,i=0){const n=this.getFlashWriteSize(),o=Math.floor((t+n-1)/n),r=Math.floor((e+n-1)/n);let a=0,d=0;this.IS_STUB?(a=e,d=en(3e4,a)):(a=r*n,d=Zi);const s=xr("<IIII",a,o,n,i);return await this.checkCommand(16,s,0,d),d}async flashFinish(){const e=xr("<I",1);await this.checkCommand(4,e)}async flashDeflFinish(){const e=xr("<I",1);await this.checkCommand(18,e)}getBootloaderOffset(){return tn(this.getChipFamily()).flashOffs}async flashId(){return await this.runSpiFlashCommand(159,[],24)}getChipFamily(){return this._parent?this._parent.chipFamily:this.chipFamily}async writeRegister(e,t,i=4294967295,n=0,o=0){let r=xr("<IIII",e,t,i,n);o>0&&(r=r.concat(xr("<IIII",tn(this.getChipFamily()).uartDateReg,0,0,o))),await this.checkCommand(9,r)}async setDataLengths(e,t,i){if(-1!=e.mosiDlenOffs){const n=e.regBase+e.mosiDlenOffs,o=e.regBase+e.misoDlenOffs;t>0&&await this.writeRegister(n,t-1),i>0&&await this.writeRegister(o,i-1)}else{const n=e.regBase+e.usr1Offs,o=(0==i?0:i-1)<<8|(0==t?0:t-1)<<17;await this.writeRegister(n,o)}}async waitDone(e,t){for(let i=0;i<10;i++){if(0==(await this.readRegister(e)&t))return}throw Error("SPI command did not complete in time")}async runSpiFlashCommand(e,t,i=0){const n=tn(this.getChipFamily()),o=n.regBase,r=o,a=o+n.usrOffs,d=o+n.usr2Offs,s=o+n.w0Offs,l=1<<18;if(i>32)throw new Error("Reading more than 32 bits back from a SPI flash operation is unsupported");if(t.length>64)throw new Error("Writing more than 64 bytes of data with one SPI command is unsupported");const c=8*t.length,h=await this.readRegister(a),m=await this.readRegister(d);let p=1<<31;if(i>0&&(p|=268435456),c>0&&(p|=134217728),await this.setDataLengths(n,c,i),await this.writeRegister(a,p),await this.writeRegister(d,7<<28|e),0==c)await this.writeRegister(s,0);else{const e=(4-t.length%4)%4;t=t.concat(new Array(e).fill(0));const i=vr("I".repeat(Math.floor(t.length/4)),t);let n=s;this.logger.debug(`Words Length: ${i.length}`);for(const e of i)this.logger.debug(`Writing word ${Ti(e)} to register offset ${Ti(n)}`),await this.writeRegister(n,e),n+=4}await this.writeRegister(r,l),await this.waitDone(r,l);const u=await this.readRegister(s);return await this.writeRegister(a,h),await this.writeRegister(d,m),u}async detectFlashSize(){this.logger.log("Detecting Flash Size");const e=await this.flashId(),t=255&e,i=e>>16&255;this.logger.log(`FlashId: ${Ti(e)}`),this.logger.log(`Flash Manufacturer: ${t.toString(16)}`),this.logger.log(`Flash Device: ${(e>>8&255).toString(16)}${i.toString(16)}`),this.flashSize=Oi[i],this.logger.log(`Auto-detected Flash size: ${this.flashSize}`)}getEraseSize(e,t){const i=4096,n=Math.floor((t+i-1)/i);let o=16-Math.floor(e/i)%16;return n<o&&(o=n),n<2*o?Math.floor((n+1)/2*i):(n-o)*i}async memBegin(e,t,i,n){return await this.checkCommand(5,xr("<IIII",e,t,i,n))}async memBlock(e,t){return await this.checkCommand(7,xr("<IIII",e.length,t,0,0).concat(e),this.checksum(e))}async memFinish(e=0){const t=this.IS_STUB?Zi:500,i=xr("<II",0==e?1:0,e);return await this.checkCommand(6,i,0,t)}async runStub(e=!1){const t=await on(this.chipFamily,this.chipRevision);if(null===t)return this.logger.log(`Stub flasher is not yet supported on ${this.chipName}, using ROM loader`),this;const i=2048;this.logger.log("Uploading stub...");for(const e of["text","data"]){const n=t[e],o=t[`${e}_start`],r=n.length,a=Math.floor((r+i-1)/i);await this.memBegin(r,a,i,o);for(const e of Array(a).keys()){const t=e*i;let o=t+i;o>r&&(o=r),await this.memBlock(n.slice(t,o),e)}}await this.memFinish(t.entry);const n=await this.readPacket(500),o=String.fromCharCode(...n);if("OHAI"!=o)throw new Error("Failed to start stub. Unexpected response: "+o);this.logger.log("Stub is now running...");const r=new wr(this.port,this.logger,this);return e||await r.detectFlashSize(),r}async writeToStream(e){if(!this.port.writable)return void this.logger.debug("Port writable stream not available, skipping write");const t=this.port.writable.getWriter();await t.write(new Uint8Array(e));try{t.releaseLock()}catch(e){this.logger.error(`Ignoring release lock error: ${e}`)}}async disconnect(){this._parent?await this._parent.disconnect():this.port.writable?(await this.port.writable.getWriter().close(),await new Promise(e=>{this._reader||e(void 0),this.addEventListener("disconnect",e,{once:!0}),this._reader.cancel()}),this.connected=!1):this.logger.debug("Port already closed, skipping disconnect")}async reconnect(){if(this._parent)return void await this._parent.reconnect();if(this.logger.log("Reconnecting serial port..."),this.connected=!1,this.__inputBuffer=[],this._reader){try{await this._reader.cancel()}catch(e){this.logger.debug(`Reader cancel error: ${e}`)}this._reader=void 0}try{await this.port.close(),this.logger.log("Port closed")}catch(e){this.logger.debug(`Port close error: ${e}`)}this.logger.debug("Opening port...");try{await this.port.open({baudRate:Fi}),this.connected=!0}catch(e){throw new Error(`Failed to open port: ${e}`)}if(!this.port.readable||!this.port.writable)throw new Error(`Port streams not available after open (readable: ${!!this.port.readable}, writable: ${!!this.port.writable})`);const e=this.chipFamily,t=this.chipName,i=this.chipRevision,n=this.chipVariant,o=this.flashSize;if(await this.hardReset(!0),this._parent||(this.__inputBuffer=[],this.__totalBytesRead=0,this.readLoop()),await this.flushSerialBuffers(),await this.sync(),this.chipFamily=e,this.chipName=t,this.chipRevision=i,this.chipVariant=n,this.flashSize=o,this.logger.debug(`Reconnect complete (chip: ${this.chipName})`),!this.port.writable||!this.port.readable)throw new Error("Port not ready after reconnect");const r=await this.runStub(!0);if(this.logger.debug("Stub loaded"),this._currentBaudRate!==Fi&&(await r.setBaudrate(this._currentBaudRate),!this.port.writable||!this.port.readable))throw new Error(`Port not ready after baudrate change (readable: ${!!this.port.readable}, writable: ${!!this.port.writable})`);this.IS_STUB&&Object.assign(this,r),this.logger.debug("Reconnection successful")}async flushSerialBuffers(){this._parent||(this.__inputBuffer=[]),await Ai(Ji),this._parent||(this.__inputBuffer=[]),this.logger.debug("Serial buffers flushed")}async readFlash(e,t,i){if(!this.IS_STUB)throw new Error("Reading flash is only supported in stub mode. Please run runStub() first.");await this.flushSerialBuffers(),this.logger.log(`Reading ${t} bytes from flash at address 0x${e.toString(16)}...`);let n=new Uint8Array(0),o=e,r=t;for(;r>0;){const e=Math.min(65536,r);let a=!1,d=0;const s=3;for(;!a&&d<=s;)try{this.logger.debug(`Reading chunk at 0x${o.toString(16)}, size: 0x${e.toString(16)}`);const t=xr("<IIII",o,e,4096,1024),[i]=await this.checkCommand(210,t);if(0!=i)throw new Error("Failed to read memory: "+i);let r=new Uint8Array(0);for(;r.length<e;){let t;try{t=await this.readPacket(100)}catch(t){if(t instanceof nn&&(this.logger.debug(`SLIP read error at ${r.length} bytes: ${t.message}`),r.length>=e))break;throw t}if(t&&t.length>0){const e=new Uint8Array(t),i=new Uint8Array(r.length+e.length);i.set(r),i.set(e,r.length),r=i;const n=xr("<I",r.length),o=Si(n);await this.writeToStream(o)}}const d=new Uint8Array(n.length+r.length);d.set(n),d.set(r,n.length),n=d,a=!0}catch(e){if(d++,!(e instanceof nn&&e.message.includes("Timed out")))throw e;if(!(d<=s))throw new Error(`Failed to read chunk at 0x${o.toString(16)} after ${s} retries: ${e}`);this.logger.log(`⚠️ Timeout error at 0x${o.toString(16)}. Reconnecting and retrying (attempt ${d}/${s})...`);try{await this.reconnect()}catch(e){throw new Error(`Reconnect failed: ${e}`)}}i&&i(new Uint8Array(e),n.length,t),o+=e,r-=e,this.logger.debug(`Total progress: 0x${n.length.toString(16)} from 0x${t.toString(16)} bytes`)}return this.logger.debug(`Successfully read ${n.length} bytes from flash`),n}}class wr extends yr{constructor(){super(...arguments),this.IS_STUB=!0}async memBegin(e,t,i,n){const o=await on(this.chipFamily,this.chipRevision);if(null===o)return[0,[]];const r=n,a=n+e;this.logger.debug(`Load range: ${Ti(r,8)}-${Ti(a,8)}`),this.logger.debug(`Stub data: ${Ti(o.data_start,8)}, len: ${o.data.length}, text: ${Ti(o.text_start,8)}, len: ${o.text.length}`);for(const[e,t]of[[o.data_start,o.data_start+o.data.length],[o.text_start,o.text_start+o.text.length]])if(r<t&&a>e)throw new Error("Software loader is resident at "+Ti(e,8)+"-"+Ti(t,8)+". Can't load binary at overlapping address range "+Ti(r,8)+"-"+Ti(a,8)+". Try changing the binary loading address.");return[0,[]]}async eraseFlash(){await this.checkCommand(208,[],0,Qi)}}const kr=async(e,t,i,n,o,r,a)=>{let d,s,l,c=null,h=!1;const m=(e=>{const t=e.getInfo();return 12346===t.usbVendorId&&(2===t.usbProductId||4097===t.usbProductId)})(t),p=t=>e({...t,manifest:d,build:s,chipFamily:l,chipVariant:c});var u=null,f="";try{u=JSON.parse(n)}catch{f=new URL(n,location.toString()).toString(),u=fetch(f).then(e=>e.json())}const g=new yr(t,i);window.esploader=g;const b=()=>{h=!0,i.log("ESP32-S2 Native USB disconnect detected - reconnection required")};m&&(g.addEventListener("esp32s2-usb-reconnect",b),i.log("ESP32-S2 Native USB detected - monitoring for port switch"));const _=()=>{m&&g.removeEventListener("esp32s2-usb-reconnect",b)};p({state:"initializing",message:"Initializing...",details:{done:!1}});try{await g.initialize()}catch(e){if(i.error(e),m&&h){_();try{await t.close()}catch{}try{await t.forget()}catch{}return void p({state:"esp32_s2_usb_reconnect",message:"ESP32-S2 Native USB detected - please select the new port",details:{oldPort:t}})}return _(),p({state:"error",message:"Failed to initialize. Try resetting your device or holding the BOOT button while clicking INSTALL.",details:{error:"failed_initialize",details:e}}),void(g.connected&&await g.disconnect())}l=(e=>{switch(e.chipFamily){case Di:return"ESP32";case $i:return"ESP32-S2";case Ni:return"ESP32-S3";case Pi:return"ESP32-C2";case Mi:return"ESP32-C3";case Ui:return"ESP32-C5";case Hi:return"ESP32-C6";case Vi:return"ESP32-C61";case Wi:return"ESP32-H2";case Yi:return"ESP32-P4";case zi:return"ESP8266";default:return"Unknown Chip"}})(g),c=g.chipVariant,p({state:"initializing",message:`Initialized. Found ${l}${c?` (${c})`:""}`,details:{done:!0}}),p({state:"manifest",message:"Fetching manifest...",details:{done:!1}});try{d=await u}catch(e){return _(),p({state:"error",message:`Unable to fetch manifest: ${e}`,details:{error:"fetch_manifest_failed",details:e}}),void await g.disconnect()}if(s=d.builds.find(e=>e.chipFamily===l&&(void 0===e.chipVariant||e.chipVariant===c)),p({state:"manifest",message:`Found manifest for ${d.name}`,details:{done:!0}}),!s){const e=c?`${l} (${c})`:l;return _(),p({state:"error",message:`Your ${e} board is not supported.`,details:{error:"not_supported",details:e}}),void await g.disconnect()}p({state:"preparing",message:"Preparing installation...",details:{done:!1}});const x=s.parts.map(async e=>{if(0==r.length){const t=new URL(e.path,f).toString(),i=await fetch(t);if(!i.ok)throw new Error(`Downlading firmware ${e.path} failed: ${i.status}`);return i.arrayBuffer()}return r}),v=await g.runStub();if(void 0!==a&&a>115200)try{await v.setBaudrate(a)}catch(e){i.log(`Could not change baud rate to ${a}: ${e.message}`)}const y=[];let w=0;for(const e of x)try{const t=await e;y.push(t instanceof ArrayBuffer?new Uint8Array(t):t),w+=t.byteLength}catch(e){return _(),p({state:"error",message:e.message,details:{error:"failed_firmware_download",details:e.message}}),void await g.disconnect()}p({state:"preparing",message:"Installation prepared",details:{done:!0}}),o&&(p({state:"erasing",message:"Erasing device...",details:{done:!1}}),await v.eraseFlash(),p({state:"erasing",message:"Device erased",details:{done:!0}}));let k=0;p({state:"writing",message:`Writing progress: ${k}%`,details:{bytesTotal:w,bytesWritten:0,percentage:k}});let E=0;for(const e of s.parts){const t=y.shift(),i=t instanceof Uint8Array?new Uint8Array(t).buffer:t;try{await v.flashData(i,e=>{const t=Math.floor((E+e)/w*100);t!==k&&(k=t,p({state:"writing",message:`Writing progress: ${t}%`,details:{bytesTotal:w,bytesWritten:E+e,percentage:t}}))},e.offset,!0)}catch(e){return _(),p({state:"error",message:e.message,details:{error:"write_failed",details:e}}),void await g.disconnect()}E+=t.byteLength}p({state:"writing",message:"Writing complete",details:{bytesTotal:w,bytesWritten:E,percentage:100}}),await V(100),console.log("DISCONNECT"),await g.disconnect(),console.log("HARD RESET"),await g.hardReset(),_(),p({state:"finished",message:"All done!"})},Er=(e,t="")=>{const i=new Blob([e],{type:"text/plain"}),n=URL.createObjectURL(i);((e,t="")=>{const i=document.createElement("a");i.target="_blank",i.href=e,i.download=t,document.body.appendChild(i),i.dispatchEvent(new MouseEvent("click")),document.body.removeChild(i)})(n,t),setTimeout(()=>URL.revokeObjectURL(n),0)};class Ir extends x{constructor(){super(...arguments),this.logger=console,this._state="DASHBOARD",this._installErase=!1,this._installConfirmed=!1,this._provisionForce=!1,this._wasProvisioned=!1,this._busy=!1,this._esp32s2ReconnectInProgress=!1,this._selectedSsid=-1,this._handleDisconnect=()=>{this._state="ERROR",this._error="Disconnected"}}render(){if(!this.port)return h``;let e,t,i=!1,n=!1;return void 0===this._client&&"INSTALL"!==this._state&&"LOGS"!==this._state?this._error?[e,t,i]=this._renderError(this._error):(t=this._renderProgress("Connecting"),i=!0):"INSTALL"===this._state?[e,t,i,n]=this._renderInstall():"ASK_ERASE"===this._state?[e,t]=this._renderAskErase():"ERROR"===this._state?[e,t,i]=this._renderError(this._error):"DASHBOARD"===this._state?[e,t,i,n]=this._client?this._renderDashboard():this._renderDashboardNoImprov():"PROVISION"===this._state?[e,t,i]=this._renderProvision():"LOGS"===this._state&&([e,t,i]=this._renderLogs()),h`
|
|
417
|
+
`,xi=["I".charCodeAt(0),"M".charCodeAt(0),"P".charCodeAt(0),"R".charCodeAt(0),"O".charCodeAt(0),"V".charCodeAt(0),1];var vi,yi;!function(e){e[e.CURRENT_STATE=1]="CURRENT_STATE",e[e.ERROR_STATE=2]="ERROR_STATE",e[e.RPC=3]="RPC",e[e.RPC_RESULT=4]="RPC_RESULT"}(vi||(vi={})),function(e){e[e.READY=2]="READY",e[e.PROVISIONING=3]="PROVISIONING",e[e.PROVISIONED=4]="PROVISIONED"}(yi||(yi={}));const wi={0:"NO_ERROR",1:"INVALID_RPC_PACKET",2:"UNKNOWN_RPC_COMMAND",3:"UNABLE_TO_CONNECT",254:"TIMEOUT",255:"UNKNOWN_ERROR"};class ki extends Error{constructor(){super("Port is not ready")}}const Ei=e=>"["+e.map(e=>((e,t=2)=>{let i=e.toString(16).toUpperCase();return i.startsWith("-")?"-0x"+i.substring(1).padStart(t,"0"):"0x"+i.padStart(t,"0")})(e)).join(", ")+"]";class Ii extends EventTarget{constructor(e,t){if(super(),this.port=e,this.logger=t,this.error=0,null===e.readable)throw new Error("Port is not readable");if(null===e.writable)throw new Error("Port is not writable")}async initialize(e=1e3){var t;if(this.logger.log("Initializing Improv Serial"),this._processInput(),await(t=1e3,new Promise(e=>setTimeout(e,t))),void 0===this._reader)throw new ki;try{await new Promise(async(t,i)=>{setTimeout(()=>i(new Error("Improv Wi-Fi Serial not detected")),e),await this.requestCurrentState(),t(void 0)}),await this.requestInfo()}catch(e){throw await this.close(),e}return this.info}async close(){this._reader&&await new Promise(e=>{this._reader.cancel(),this.addEventListener("disconnect",e,{once:!0})})}async requestCurrentState(){let e;try{await new Promise(async(t,i)=>{this.addEventListener("state-changed",t,{once:!0});e=this._sendRPCWithResponse(2,[]),e.catch(e=>{this.removeEventListener("state-changed",t),i(e)})})}catch(e){throw this._rpcFeedback=void 0,new Error(`Error fetching current state: ${e}`)}if(this.state!==yi.PROVISIONED)return void(this._rpcFeedback=void 0);const t=await e;this.nextUrl=t[0]}async requestInfo(e){const t=await this._sendRPCWithResponse(3,[],e);this.info={firmware:t[0],version:t[1],name:t[3],chipFamily:t[2]}}async provision(e,t,i){const n=new TextEncoder,o=n.encode(e),r=n.encode(t),a=[o.length,...o,r.length,...r],d=await this._sendRPCWithResponse(1,a,i);this.nextUrl=d[0]}async scan(){const e=(await this._sendRPCWithMultipleResponses(4,[])).map(([e,t,i])=>({name:e,rssi:parseInt(t),secured:"YES"===i}));return e.sort((e,t)=>e.name.toLocaleLowerCase().localeCompare(t.name.toLocaleLowerCase())),e}_sendRPC(e,t){this.writePacketToStream(vi.RPC,[e,t.length,...t])}async _sendRPCWithResponse(e,t,i){if(this._rpcFeedback)throw new Error("Only 1 RPC command that requires feedback can be active");return await this._awaitRPCResultWithTimeout(new Promise((i,n)=>{this._rpcFeedback={command:e,resolve:i,reject:n},this._sendRPC(e,t)}),i)}async _sendRPCWithMultipleResponses(e,t,i){if(this._rpcFeedback)throw new Error("Only 1 RPC command that requires feedback can be active");return await this._awaitRPCResultWithTimeout(new Promise((i,n)=>{this._rpcFeedback={command:e,resolve:i,reject:n,receivedData:[]},this._sendRPC(e,t)}),i)}async _awaitRPCResultWithTimeout(e,t){return t?await new Promise((i,n)=>{const o=setTimeout(()=>this._setError(254),t);e.finally(()=>clearTimeout(o)),e.then(i,n)}):await e}async _processInput(){this.logger.debug("Starting read loop"),this._reader=this.port.readable.getReader();try{let e,t=[],i=0;for(;;){const{value:n,done:o}=await this._reader.read();if(o)break;if(n&&0!==n.length)for(const o of n){if(!1===e){10===o&&(e=void 0);continue}if(!0===e){t.push(o),t.length===i&&(this._handleIncomingPacket(t),e=void 0,t=[]);continue}if(10===o){t=[];continue}if(t.push(o),9!==t.length)continue;if(e="IMPROV"===String.fromCharCode(...t.slice(0,6)),!e){t=[];continue}i=9+t[8]+1}}}catch(e){this.logger.error("Error while reading serial port",e)}finally{this._reader.releaseLock(),this._reader=void 0}this.logger.debug("Finished read loop"),this.dispatchEvent(new Event("disconnect"))}_handleIncomingPacket(e){const t=e.slice(6),i=t[0],n=t[1],o=t[2],r=t.slice(3,3+o);if(this.logger.debug("PROCESS",{version:i,packetType:n,packetLength:o,data:Ei(r)}),1!==i)return void this.logger.error("Received unsupported version",i);let a=t[3+o],d=0;for(let t=0;t<e.length-1;t++)d+=e[t];if(d&=255,d===a)if(n===vi.CURRENT_STATE)this.state=r[0],this.dispatchEvent(new CustomEvent("state-changed",{detail:this.state}));else if(n===vi.ERROR_STATE)this._setError(r[0]);else if(n===vi.RPC_RESULT){if(!this._rpcFeedback)return void this.logger.error("Received result while not waiting for one");const e=r[0];if(e!==this._rpcFeedback.command)return void this.logger.error(`Received result for command ${e} but expected ${this._rpcFeedback.command}`);const t=[],i=r[1];let n=2;for(;n<2+i;)t.push(String.fromCodePoint(...r.slice(n+1,n+r[n]+1))),n+=r[n]+1;"receivedData"in this._rpcFeedback?t.length>0?this._rpcFeedback.receivedData.push(t):(this._rpcFeedback.resolve(this._rpcFeedback.receivedData),this._rpcFeedback=void 0):(this._rpcFeedback.resolve(t),this._rpcFeedback=void 0)}else this.logger.error("Unable to handle packet",t);else this.logger.error(`Received invalid checksum ${a}. Expected ${d}`)}async writePacketToStream(e,t){const i=new Uint8Array([...xi,e,t.length,...t,0,0]);i[i.length-2]=255&i.reduce((e,t)=>e+t,0),i[i.length-1]=10,this.logger.debug("Writing to stream:",Ei(new Array(...i)));const n=this.port.writable.getWriter();await n.write(i);try{n.releaseLock()}catch(e){console.error("Ignoring release lock error",e)}}_setError(e){this.error=e,e>0&&this._rpcFeedback&&(this._rpcFeedback.reject(wi[e]||`UNKNOWN_ERROR (${e})`),this._rpcFeedback=void 0),this.dispatchEvent(new CustomEvent("error-changed",{detail:this.error}))}}const Si=e=>{let t=[192];for(const i of e)219==i?t=t.concat([219,221]):192==i?t=t.concat([219,220]):t.push(i);return t.push(192),t},Ci=e=>{const t=[];for(let i=0;i<e.length;i++){const n=e.charCodeAt(i);n<=255&&t.push(n)}return t},Ri=e=>"["+e.map(e=>Ti(e)).join(", ")+"]",Ti=(e,t=2)=>{const i=e.toString(16).toUpperCase();return i.startsWith("-")?"-0x"+i.substring(1).padStart(t,"0"):"0x"+i.padStart(t,"0")},Ai=e=>new Promise(t=>setTimeout(t,e)),Oi={18:"256KB",19:"512KB",20:"1MB",21:"2MB",22:"4MB",23:"8MB",24:"16MB",25:"32MB",26:"64MB",27:"128MB",28:"256MB",32:"64MB",33:"128MB",34:"256MB",50:"256KB",51:"512KB",52:"1MB",53:"2MB",54:"4MB",55:"8MB",56:"16MB",57:"32MB",58:"64MB"},Fi=115200,Li=1343410176,Bi=Ci(" UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU"),zi=33382,Di=50,$i=12882,Ni=12883,Pi=12994,Mi=12995,Ui=12997,Hi=12998,Vi=207969,Wi=12914,Xi=12916,qi=12917,Yi=12928,Gi=12849,ji={5:{name:"ESP32-C3",family:Mi},9:{name:"ESP32-S3",family:Ni},12:{name:"ESP32-C2",family:Pi},13:{name:"ESP32-C6",family:Hi},16:{name:"ESP32-H2",family:Wi},18:{name:"ESP32-P4",family:Yi},20:{name:"ESP32-C61",family:Vi},23:{name:"ESP32-C5",family:Ui},25:{name:"ESP32-H21",family:qi},28:{name:"ESP32-H4",family:Xi},32:{name:"ESP32-S31",family:Gi}},Ki={4293968129:{name:"ESP8266",family:zi},15736195:{name:"ESP32",family:Di},1990:{name:"ESP32-S2",family:$i}},Zi=3e3,Qi=15e4,Ji=100,en=(e,t)=>{const i=Math.floor(e*(t/486));return i<Zi?Zi:i},tn=e=>{switch(e){case Di:return{regBase:1072963584,baseFuse:1073061888,macFuse:1073061888,usrOffs:28,usr1Offs:32,usr2Offs:36,mosiDlenOffs:40,misoDlenOffs:44,w0Offs:128,uartDateReg:1610612856,flashOffs:4096};case $i:return{regBase:1061167104,baseFuse:1061265408,macFuse:1061265476,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612856,flashOffs:4096};case Ni:return{regBase:1610620928,usrOffs:24,baseFuse:1610641408,macFuse:1610641476,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612864,flashOffs:0};case zi:return{regBase:1610613248,usrOffs:28,baseFuse:1072693328,macFuse:1072693328,usr1Offs:32,usr2Offs:36,mosiDlenOffs:-1,misoDlenOffs:-1,w0Offs:64,uartDateReg:1610612856,flashOffs:0};case Pi:case Mi:return{regBase:1610620928,baseFuse:1610647552,macFuse:1610647620,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case Ui:return{regBase:1610625024,baseFuse:1611352064,macFuse:1611352132,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:8192};case Hi:return{regBase:1610625024,baseFuse:1611335680,macFuse:1611335748,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case Vi:return{regBase:1610625024,baseFuse:1611352064,macFuse:1611352132,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case Wi:return{regBase:1610625024,baseFuse:1611335680,macFuse:1611335748,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case Xi:return{regBase:1611239424,baseFuse:1611339776,macFuse:1611339844,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610686588,flashOffs:8192};case qi:return{regBase:1610625024,baseFuse:1611350016,macFuse:1611350084,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case Yi:return{regBase:1342754816,baseFuse:Li,macFuse:1343410244,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1343004812,flashOffs:8192};case Gi:return{regBase:542113792,baseFuse:544296960,macFuse:544297028,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:540582028,flashOffs:8192};default:return{regBase:-1,baseFuse:-1,macFuse:-1,usrOffs:-1,usr1Offs:-1,usr2Offs:-1,mosiDlenOffs:-1,misoDlenOffs:-1,w0Offs:-1,uartDateReg:-1,flashOffs:-1}}};class nn extends Error{constructor(e){super(e),this.name="SlipReadError"}}const on=async(e,t)=>{let i;return e==Xi||e==qi||e==Gi?null:(e==Di?i=await import("./esp32-CijhsJH1.js"):e==$i?i=await import("./esp32s2-IiDBtXxo.js"):e==Ni?i=await import("./esp32s3-6yv5yxum.js"):e==zi?i=await import("./esp8266-CUwxJpGa.js"):e==Pi?i=await import("./esp32c2-C17SM4gO.js"):e==Mi?i=await import("./esp32c3-DxRGijbg.js"):e==Ui?i=await import("./esp32c5-3mDOIGa4.js"):e==Hi?i=await import("./esp32c6-h6U0SQTm.js"):e==Vi?i=await import("./esp32c61-BKtexhPZ.js"):e==Wi?i=await import("./esp32h2-RtuWSEmP.js"):e==Yi&&(i=null!=t&&t>=300?await import("./esp32p4r3-CpHBYEwI.js"):await import("./esp32p4-5nkIjxqJ.js")),{...i,text:Ci(atob(i.text)),data:Ci(atob(i.data))})};function rn(e){let t=e.length;for(;--t>=0;)e[t]=0}const an=256,dn=286,sn=30,ln=15,cn=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]),hn=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]),mn=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),pn=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),un=new Array(576);rn(un);const fn=new Array(60);rn(fn);const gn=new Array(512);rn(gn);const bn=new Array(256);rn(bn);const _n=new Array(29);rn(_n);const xn=new Array(sn);function vn(e,t,i,n,o){this.static_tree=e,this.extra_bits=t,this.extra_base=i,this.elems=n,this.max_length=o,this.has_stree=e&&e.length}let yn,wn,kn;function En(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}rn(xn);const In=e=>e<256?gn[e]:gn[256+(e>>>7)],Sn=(e,t)=>{e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255},Cn=(e,t,i)=>{e.bi_valid>16-i?(e.bi_buf|=t<<e.bi_valid&65535,Sn(e,e.bi_buf),e.bi_buf=t>>16-e.bi_valid,e.bi_valid+=i-16):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=i)},Rn=(e,t,i)=>{Cn(e,i[2*t],i[2*t+1])},Tn=(e,t)=>{let i=0;do{i|=1&e,e>>>=1,i<<=1}while(--t>0);return i>>>1},An=(e,t,i)=>{const n=new Array(16);let o,r,a=0;for(o=1;o<=ln;o++)a=a+i[o-1]<<1,n[o]=a;for(r=0;r<=t;r++){let t=e[2*r+1];0!==t&&(e[2*r]=Tn(n[t]++,t))}},On=e=>{let t;for(t=0;t<dn;t++)e.dyn_ltree[2*t]=0;for(t=0;t<sn;t++)e.dyn_dtree[2*t]=0;for(t=0;t<19;t++)e.bl_tree[2*t]=0;e.dyn_ltree[512]=1,e.opt_len=e.static_len=0,e.sym_next=e.matches=0},Fn=e=>{e.bi_valid>8?Sn(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0},Ln=(e,t,i,n)=>{const o=2*t,r=2*i;return e[o]<e[r]||e[o]===e[r]&&n[t]<=n[i]},Bn=(e,t,i)=>{const n=e.heap[i];let o=i<<1;for(;o<=e.heap_len&&(o<e.heap_len&&Ln(t,e.heap[o+1],e.heap[o],e.depth)&&o++,!Ln(t,n,e.heap[o],e.depth));)e.heap[i]=e.heap[o],i=o,o<<=1;e.heap[i]=n},zn=(e,t,i)=>{let n,o,r,a,d=0;if(0!==e.sym_next)do{n=255&e.pending_buf[e.sym_buf+d++],n+=(255&e.pending_buf[e.sym_buf+d++])<<8,o=e.pending_buf[e.sym_buf+d++],0===n?Rn(e,o,t):(r=bn[o],Rn(e,r+an+1,t),a=cn[r],0!==a&&(o-=_n[r],Cn(e,o,a)),n--,r=In(n),Rn(e,r,i),a=hn[r],0!==a&&(n-=xn[r],Cn(e,n,a)))}while(d<e.sym_next);Rn(e,256,t)},Dn=(e,t)=>{const i=t.dyn_tree,n=t.stat_desc.static_tree,o=t.stat_desc.has_stree,r=t.stat_desc.elems;let a,d,s,l=-1;for(e.heap_len=0,e.heap_max=573,a=0;a<r;a++)0!==i[2*a]?(e.heap[++e.heap_len]=l=a,e.depth[a]=0):i[2*a+1]=0;for(;e.heap_len<2;)s=e.heap[++e.heap_len]=l<2?++l:0,i[2*s]=1,e.depth[s]=0,e.opt_len--,o&&(e.static_len-=n[2*s+1]);for(t.max_code=l,a=e.heap_len>>1;a>=1;a--)Bn(e,i,a);s=r;do{a=e.heap[1],e.heap[1]=e.heap[e.heap_len--],Bn(e,i,1),d=e.heap[1],e.heap[--e.heap_max]=a,e.heap[--e.heap_max]=d,i[2*s]=i[2*a]+i[2*d],e.depth[s]=(e.depth[a]>=e.depth[d]?e.depth[a]:e.depth[d])+1,i[2*a+1]=i[2*d+1]=s,e.heap[1]=s++,Bn(e,i,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],((e,t)=>{const i=t.dyn_tree,n=t.max_code,o=t.stat_desc.static_tree,r=t.stat_desc.has_stree,a=t.stat_desc.extra_bits,d=t.stat_desc.extra_base,s=t.stat_desc.max_length;let l,c,h,m,p,u,f=0;for(m=0;m<=ln;m++)e.bl_count[m]=0;for(i[2*e.heap[e.heap_max]+1]=0,l=e.heap_max+1;l<573;l++)c=e.heap[l],m=i[2*i[2*c+1]+1]+1,m>s&&(m=s,f++),i[2*c+1]=m,c>n||(e.bl_count[m]++,p=0,c>=d&&(p=a[c-d]),u=i[2*c],e.opt_len+=u*(m+p),r&&(e.static_len+=u*(o[2*c+1]+p)));if(0!==f){do{for(m=s-1;0===e.bl_count[m];)m--;e.bl_count[m]--,e.bl_count[m+1]+=2,e.bl_count[s]--,f-=2}while(f>0);for(m=s;0!==m;m--)for(c=e.bl_count[m];0!==c;)h=e.heap[--l],h>n||(i[2*h+1]!==m&&(e.opt_len+=(m-i[2*h+1])*i[2*h],i[2*h+1]=m),c--)}})(e,t),An(i,l,e.bl_count)},$n=(e,t,i)=>{let n,o,r=-1,a=t[1],d=0,s=7,l=4;for(0===a&&(s=138,l=3),t[2*(i+1)+1]=65535,n=0;n<=i;n++)o=a,a=t[2*(n+1)+1],++d<s&&o===a||(d<l?e.bl_tree[2*o]+=d:0!==o?(o!==r&&e.bl_tree[2*o]++,e.bl_tree[32]++):d<=10?e.bl_tree[34]++:e.bl_tree[36]++,d=0,r=o,0===a?(s=138,l=3):o===a?(s=6,l=3):(s=7,l=4))},Nn=(e,t,i)=>{let n,o,r=-1,a=t[1],d=0,s=7,l=4;for(0===a&&(s=138,l=3),n=0;n<=i;n++)if(o=a,a=t[2*(n+1)+1],!(++d<s&&o===a)){if(d<l)do{Rn(e,o,e.bl_tree)}while(0!==--d);else 0!==o?(o!==r&&(Rn(e,o,e.bl_tree),d--),Rn(e,16,e.bl_tree),Cn(e,d-3,2)):d<=10?(Rn(e,17,e.bl_tree),Cn(e,d-3,3)):(Rn(e,18,e.bl_tree),Cn(e,d-11,7));d=0,r=o,0===a?(s=138,l=3):o===a?(s=6,l=3):(s=7,l=4)}};let Pn=!1;const Mn=(e,t,i,n)=>{Cn(e,0+(n?1:0),3),Fn(e),Sn(e,i),Sn(e,~i),i&&e.pending_buf.set(e.window.subarray(t,t+i),e.pending),e.pending+=i};var Un=e=>{Pn||((()=>{let e,t,i,n,o;const r=new Array(16);for(i=0,n=0;n<28;n++)for(_n[n]=i,e=0;e<1<<cn[n];e++)bn[i++]=n;for(bn[i-1]=n,o=0,n=0;n<16;n++)for(xn[n]=o,e=0;e<1<<hn[n];e++)gn[o++]=n;for(o>>=7;n<sn;n++)for(xn[n]=o<<7,e=0;e<1<<hn[n]-7;e++)gn[256+o++]=n;for(t=0;t<=ln;t++)r[t]=0;for(e=0;e<=143;)un[2*e+1]=8,e++,r[8]++;for(;e<=255;)un[2*e+1]=9,e++,r[9]++;for(;e<=279;)un[2*e+1]=7,e++,r[7]++;for(;e<=287;)un[2*e+1]=8,e++,r[8]++;for(An(un,287,r),e=0;e<sn;e++)fn[2*e+1]=5,fn[2*e]=Tn(e,5);yn=new vn(un,cn,257,dn,ln),wn=new vn(fn,hn,0,sn,ln),kn=new vn(new Array(0),mn,0,19,7)})(),Pn=!0),e.l_desc=new En(e.dyn_ltree,yn),e.d_desc=new En(e.dyn_dtree,wn),e.bl_desc=new En(e.bl_tree,kn),e.bi_buf=0,e.bi_valid=0,On(e)},Hn=(e,t,i,n)=>{let o,r,a=0;e.level>0?(2===e.strm.data_type&&(e.strm.data_type=(e=>{let t,i=4093624447;for(t=0;t<=31;t++,i>>>=1)if(1&i&&0!==e.dyn_ltree[2*t])return 0;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return 1;for(t=32;t<an;t++)if(0!==e.dyn_ltree[2*t])return 1;return 0})(e)),Dn(e,e.l_desc),Dn(e,e.d_desc),a=(e=>{let t;for($n(e,e.dyn_ltree,e.l_desc.max_code),$n(e,e.dyn_dtree,e.d_desc.max_code),Dn(e,e.bl_desc),t=18;t>=3&&0===e.bl_tree[2*pn[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t})(e),o=e.opt_len+3+7>>>3,r=e.static_len+3+7>>>3,r<=o&&(o=r)):o=r=i+5,i+4<=o&&-1!==t?Mn(e,t,i,n):4===e.strategy||r===o?(Cn(e,2+(n?1:0),3),zn(e,un,fn)):(Cn(e,4+(n?1:0),3),((e,t,i,n)=>{let o;for(Cn(e,t-257,5),Cn(e,i-1,5),Cn(e,n-4,4),o=0;o<n;o++)Cn(e,e.bl_tree[2*pn[o]+1],3);Nn(e,e.dyn_ltree,t-1),Nn(e,e.dyn_dtree,i-1)})(e,e.l_desc.max_code+1,e.d_desc.max_code+1,a+1),zn(e,e.dyn_ltree,e.dyn_dtree)),On(e),n&&Fn(e)},Vn=(e,t,i)=>(e.pending_buf[e.sym_buf+e.sym_next++]=t,e.pending_buf[e.sym_buf+e.sym_next++]=t>>8,e.pending_buf[e.sym_buf+e.sym_next++]=i,0===t?e.dyn_ltree[2*i]++:(e.matches++,t--,e.dyn_ltree[2*(bn[i]+an+1)]++,e.dyn_dtree[2*In(t)]++),e.sym_next===e.sym_end),Wn=e=>{Cn(e,2,3),Rn(e,256,un),(e=>{16===e.bi_valid?(Sn(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)})(e)},Xn={_tr_init:Un,_tr_stored_block:Mn,_tr_flush_block:Hn,_tr_tally:Vn,_tr_align:Wn};var qn=(e,t,i,n)=>{let o=65535&e,r=e>>>16&65535,a=0;for(;0!==i;){a=i>2e3?2e3:i,i-=a;do{o=o+t[n++]|0,r=r+o|0}while(--a);o%=65521,r%=65521}return o|r<<16};const Yn=new Uint32Array((()=>{let e,t=[];for(var i=0;i<256;i++){e=i;for(var n=0;n<8;n++)e=1&e?3988292384^e>>>1:e>>>1;t[i]=e}return t})());var Gn=(e,t,i,n)=>{const o=Yn,r=n+i;e^=-1;for(let i=n;i<r;i++)e=e>>>8^o[255&(e^t[i])];return-1^e},jn={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"},Kn={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_OK:0,Z_STREAM_END:1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,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:Zn,_tr_stored_block:Qn,_tr_flush_block:Jn,_tr_tally:eo,_tr_align:to}=Xn,{Z_NO_FLUSH:io,Z_PARTIAL_FLUSH:no,Z_FULL_FLUSH:oo,Z_FINISH:ro,Z_BLOCK:ao,Z_OK:so,Z_STREAM_END:lo,Z_STREAM_ERROR:co,Z_DATA_ERROR:ho,Z_BUF_ERROR:mo,Z_DEFAULT_COMPRESSION:po,Z_FILTERED:uo,Z_HUFFMAN_ONLY:fo,Z_RLE:go,Z_FIXED:bo,Z_DEFAULT_STRATEGY:_o,Z_UNKNOWN:xo,Z_DEFLATED:vo}=Kn,yo=258,wo=262,ko=42,Eo=113,Io=666,So=(e,t)=>(e.msg=jn[t],t),Co=e=>2*e-(e>4?9:0),Ro=e=>{let t=e.length;for(;--t>=0;)e[t]=0},To=e=>{let t,i,n,o=e.w_size;t=e.hash_size,n=t;do{i=e.head[--n],e.head[n]=i>=o?i-o:0}while(--t);t=o,n=t;do{i=e.prev[--n],e.prev[n]=i>=o?i-o:0}while(--t)};let Ao=(e,t,i)=>(t<<e.hash_shift^i)&e.hash_mask;const Oo=e=>{const t=e.state;let i=t.pending;i>e.avail_out&&(i=e.avail_out),0!==i&&(e.output.set(t.pending_buf.subarray(t.pending_out,t.pending_out+i),e.next_out),e.next_out+=i,t.pending_out+=i,e.total_out+=i,e.avail_out-=i,t.pending-=i,0===t.pending&&(t.pending_out=0))},Fo=(e,t)=>{Jn(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,Oo(e.strm)},Lo=(e,t)=>{e.pending_buf[e.pending++]=t},Bo=(e,t)=>{e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t},zo=(e,t,i,n)=>{let o=e.avail_in;return o>n&&(o=n),0===o?0:(e.avail_in-=o,t.set(e.input.subarray(e.next_in,e.next_in+o),i),1===e.state.wrap?e.adler=qn(e.adler,t,o,i):2===e.state.wrap&&(e.adler=Gn(e.adler,t,o,i)),e.next_in+=o,e.total_in+=o,o)},Do=(e,t)=>{let i,n,o=e.max_chain_length,r=e.strstart,a=e.prev_length,d=e.nice_match;const s=e.strstart>e.w_size-wo?e.strstart-(e.w_size-wo):0,l=e.window,c=e.w_mask,h=e.prev,m=e.strstart+yo;let p=l[r+a-1],u=l[r+a];e.prev_length>=e.good_match&&(o>>=2),d>e.lookahead&&(d=e.lookahead);do{if(i=t,l[i+a]===u&&l[i+a-1]===p&&l[i]===l[r]&&l[++i]===l[r+1]){r+=2,i++;do{}while(l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&l[++r]===l[++i]&&r<m);if(n=yo-(m-r),r=m-yo,n>a){if(e.match_start=t,a=n,n>=d)break;p=l[r+a-1],u=l[r+a]}}}while((t=h[t&c])>s&&0!==--o);return a<=e.lookahead?a:e.lookahead},$o=e=>{const t=e.w_size;let i,n,o;do{if(n=e.window_size-e.lookahead-e.strstart,e.strstart>=t+(t-wo)&&(e.window.set(e.window.subarray(t,t+t-n),0),e.match_start-=t,e.strstart-=t,e.block_start-=t,e.insert>e.strstart&&(e.insert=e.strstart),To(e),n+=t),0===e.strm.avail_in)break;if(i=zo(e.strm,e.window,e.strstart+e.lookahead,n),e.lookahead+=i,e.lookahead+e.insert>=3)for(o=e.strstart-e.insert,e.ins_h=e.window[o],e.ins_h=Ao(e,e.ins_h,e.window[o+1]);e.insert&&(e.ins_h=Ao(e,e.ins_h,e.window[o+3-1]),e.prev[o&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=o,o++,e.insert--,!(e.lookahead+e.insert<3)););}while(e.lookahead<wo&&0!==e.strm.avail_in)},No=(e,t)=>{let i,n,o,r=e.pending_buf_size-5>e.w_size?e.w_size:e.pending_buf_size-5,a=0,d=e.strm.avail_in;do{if(i=65535,o=e.bi_valid+42>>3,e.strm.avail_out<o)break;if(o=e.strm.avail_out-o,n=e.strstart-e.block_start,i>n+e.strm.avail_in&&(i=n+e.strm.avail_in),i>o&&(i=o),i<r&&(0===i&&t!==ro||t===io||i!==n+e.strm.avail_in))break;a=t===ro&&i===n+e.strm.avail_in?1:0,Qn(e,0,0,a),e.pending_buf[e.pending-4]=i,e.pending_buf[e.pending-3]=i>>8,e.pending_buf[e.pending-2]=~i,e.pending_buf[e.pending-1]=~i>>8,Oo(e.strm),n&&(n>i&&(n=i),e.strm.output.set(e.window.subarray(e.block_start,e.block_start+n),e.strm.next_out),e.strm.next_out+=n,e.strm.avail_out-=n,e.strm.total_out+=n,e.block_start+=n,i-=n),i&&(zo(e.strm,e.strm.output,e.strm.next_out,i),e.strm.next_out+=i,e.strm.avail_out-=i,e.strm.total_out+=i)}while(0===a);return d-=e.strm.avail_in,d&&(d>=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<=d&&(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-d,e.strm.next_in),e.strstart),e.strstart+=d,e.insert+=d>e.w_size-e.insert?e.w_size-e.insert:d),e.block_start=e.strstart),e.high_water<e.strstart&&(e.high_water=e.strstart),a?4:t!==io&&t!==ro&&0===e.strm.avail_in&&e.strstart===e.block_start?2:(o=e.window_size-e.strstart,e.strm.avail_in>o&&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++,o+=e.w_size,e.insert>e.strstart&&(e.insert=e.strstart)),o>e.strm.avail_in&&(o=e.strm.avail_in),o&&(zo(e.strm,e.window,e.strstart,o),e.strstart+=o,e.insert+=o>e.w_size-e.insert?e.w_size-e.insert:o),e.high_water<e.strstart&&(e.high_water=e.strstart),o=e.bi_valid+42>>3,o=e.pending_buf_size-o>65535?65535:e.pending_buf_size-o,r=o>e.w_size?e.w_size:o,n=e.strstart-e.block_start,(n>=r||(n||t===ro)&&t!==io&&0===e.strm.avail_in&&n<=o)&&(i=n>o?o:n,a=t===ro&&0===e.strm.avail_in&&i===n?1:0,Qn(e,e.block_start,i,a),e.block_start+=i,Oo(e.strm)),a?3:1)},Po=(e,t)=>{let i,n;for(;;){if(e.lookahead<wo){if($o(e),e.lookahead<wo&&t===io)return 1;if(0===e.lookahead)break}if(i=0,e.lookahead>=3&&(e.ins_h=Ao(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!==i&&e.strstart-i<=e.w_size-wo&&(e.match_length=Do(e,i)),e.match_length>=3)if(n=eo(e,e.strstart-e.match_start,e.match_length-3),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=3){e.match_length--;do{e.strstart++,e.ins_h=Ao(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart}while(0!==--e.match_length);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=Ao(e,e.ins_h,e.window[e.strstart+1]);else n=eo(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(n&&(Fo(e,!1),0===e.strm.avail_out))return 1}return e.insert=e.strstart<2?e.strstart:2,t===ro?(Fo(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(Fo(e,!1),0===e.strm.avail_out)?1:2},Mo=(e,t)=>{let i,n,o;for(;;){if(e.lookahead<wo){if($o(e),e.lookahead<wo&&t===io)return 1;if(0===e.lookahead)break}if(i=0,e.lookahead>=3&&(e.ins_h=Ao(e,e.ins_h,e.window[e.strstart+3-1]),i=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=2,0!==i&&e.prev_length<e.max_lazy_match&&e.strstart-i<=e.w_size-wo&&(e.match_length=Do(e,i),e.match_length<=5&&(e.strategy===uo||3===e.match_length&&e.strstart-e.match_start>4096)&&(e.match_length=2)),e.prev_length>=3&&e.match_length<=e.prev_length){o=e.strstart+e.lookahead-3,n=eo(e,e.strstart-1-e.prev_match,e.prev_length-3),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=o&&(e.ins_h=Ao(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart)}while(0!==--e.prev_length);if(e.match_available=0,e.match_length=2,e.strstart++,n&&(Fo(e,!1),0===e.strm.avail_out))return 1}else if(e.match_available){if(n=eo(e,0,e.window[e.strstart-1]),n&&Fo(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return 1}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(n=eo(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<2?e.strstart:2,t===ro?(Fo(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(Fo(e,!1),0===e.strm.avail_out)?1:2};function Uo(e,t,i,n,o){this.good_length=e,this.max_lazy=t,this.nice_length=i,this.max_chain=n,this.func=o}const Ho=[new Uo(0,0,0,0,No),new Uo(4,4,8,4,Po),new Uo(4,5,16,8,Po),new Uo(4,6,32,32,Po),new Uo(4,4,16,16,Mo),new Uo(8,16,32,32,Mo),new Uo(8,16,128,128,Mo),new Uo(8,32,128,256,Mo),new Uo(32,128,258,1024,Mo),new Uo(32,258,258,4096,Mo)];function Vo(){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=vo,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(1146),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),Ro(this.dyn_ltree),Ro(this.dyn_dtree),Ro(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),Ro(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),Ro(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 Wo=e=>{if(!e)return 1;const t=e.state;return!t||t.strm!==e||t.status!==ko&&57!==t.status&&69!==t.status&&73!==t.status&&91!==t.status&&103!==t.status&&t.status!==Eo&&t.status!==Io?1:0},Xo=e=>{if(Wo(e))return So(e,co);e.total_in=e.total_out=0,e.data_type=xo;const t=e.state;return t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=2===t.wrap?57:t.wrap?ko:Eo,e.adler=2===t.wrap?0:1,t.last_flush=-2,Zn(t),so},qo=e=>{const t=Xo(e);return t===so&&(e=>{e.window_size=2*e.w_size,Ro(e.head),e.max_lazy_match=Ho[e.level].max_lazy,e.good_match=Ho[e.level].good_length,e.nice_match=Ho[e.level].nice_length,e.max_chain_length=Ho[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=2,e.match_available=0,e.ins_h=0})(e.state),t},Yo=(e,t,i,n,o,r)=>{if(!e)return co;let a=1;if(t===po&&(t=6),n<0?(a=0,n=-n):n>15&&(a=2,n-=16),o<1||o>9||i!==vo||n<8||n>15||t<0||t>9||r<0||r>bo||8===n&&1!==a)return So(e,co);8===n&&(n=9);const d=new Vo;return e.state=d,d.strm=e,d.status=ko,d.wrap=a,d.gzhead=null,d.w_bits=n,d.w_size=1<<d.w_bits,d.w_mask=d.w_size-1,d.hash_bits=o+7,d.hash_size=1<<d.hash_bits,d.hash_mask=d.hash_size-1,d.hash_shift=~~((d.hash_bits+3-1)/3),d.window=new Uint8Array(2*d.w_size),d.head=new Uint16Array(d.hash_size),d.prev=new Uint16Array(d.w_size),d.lit_bufsize=1<<o+6,d.pending_buf_size=4*d.lit_bufsize,d.pending_buf=new Uint8Array(d.pending_buf_size),d.sym_buf=d.lit_bufsize,d.sym_end=3*(d.lit_bufsize-1),d.level=t,d.strategy=r,d.method=i,qo(e)};var Go=(e,t)=>{if(Wo(e)||t>ao||t<0)return e?So(e,co):co;const i=e.state;if(!e.output||0!==e.avail_in&&!e.input||i.status===Io&&t!==ro)return So(e,0===e.avail_out?mo:co);const n=i.last_flush;if(i.last_flush=t,0!==i.pending){if(Oo(e),0===e.avail_out)return i.last_flush=-1,so}else if(0===e.avail_in&&Co(t)<=Co(n)&&t!==ro)return So(e,mo);if(i.status===Io&&0!==e.avail_in)return So(e,mo);if(i.status===ko&&0===i.wrap&&(i.status=Eo),i.status===ko){let t=vo+(i.w_bits-8<<4)<<8,n=-1;if(n=i.strategy>=fo||i.level<2?0:i.level<6?1:6===i.level?2:3,t|=n<<6,0!==i.strstart&&(t|=32),t+=31-t%31,Bo(i,t),0!==i.strstart&&(Bo(i,e.adler>>>16),Bo(i,65535&e.adler)),e.adler=1,i.status=Eo,Oo(e),0!==i.pending)return i.last_flush=-1,so}if(57===i.status)if(e.adler=0,Lo(i,31),Lo(i,139),Lo(i,8),i.gzhead)Lo(i,(i.gzhead.text?1:0)+(i.gzhead.hcrc?2:0)+(i.gzhead.extra?4:0)+(i.gzhead.name?8:0)+(i.gzhead.comment?16:0)),Lo(i,255&i.gzhead.time),Lo(i,i.gzhead.time>>8&255),Lo(i,i.gzhead.time>>16&255),Lo(i,i.gzhead.time>>24&255),Lo(i,9===i.level?2:i.strategy>=fo||i.level<2?4:0),Lo(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(Lo(i,255&i.gzhead.extra.length),Lo(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(e.adler=Gn(e.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=69;else if(Lo(i,0),Lo(i,0),Lo(i,0),Lo(i,0),Lo(i,0),Lo(i,9===i.level?2:i.strategy>=fo||i.level<2?4:0),Lo(i,3),i.status=Eo,Oo(e),0!==i.pending)return i.last_flush=-1,so;if(69===i.status){if(i.gzhead.extra){let t=i.pending,n=(65535&i.gzhead.extra.length)-i.gzindex;for(;i.pending+n>i.pending_buf_size;){let o=i.pending_buf_size-i.pending;if(i.pending_buf.set(i.gzhead.extra.subarray(i.gzindex,i.gzindex+o),i.pending),i.pending=i.pending_buf_size,i.gzhead.hcrc&&i.pending>t&&(e.adler=Gn(e.adler,i.pending_buf,i.pending-t,t)),i.gzindex+=o,Oo(e),0!==i.pending)return i.last_flush=-1,so;t=0,n-=o}let o=new Uint8Array(i.gzhead.extra);i.pending_buf.set(o.subarray(i.gzindex,i.gzindex+n),i.pending),i.pending+=n,i.gzhead.hcrc&&i.pending>t&&(e.adler=Gn(e.adler,i.pending_buf,i.pending-t,t)),i.gzindex=0}i.status=73}if(73===i.status){if(i.gzhead.name){let t,n=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>n&&(e.adler=Gn(e.adler,i.pending_buf,i.pending-n,n)),Oo(e),0!==i.pending)return i.last_flush=-1,so;n=0}t=i.gzindex<i.gzhead.name.length?255&i.gzhead.name.charCodeAt(i.gzindex++):0,Lo(i,t)}while(0!==t);i.gzhead.hcrc&&i.pending>n&&(e.adler=Gn(e.adler,i.pending_buf,i.pending-n,n)),i.gzindex=0}i.status=91}if(91===i.status){if(i.gzhead.comment){let t,n=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>n&&(e.adler=Gn(e.adler,i.pending_buf,i.pending-n,n)),Oo(e),0!==i.pending)return i.last_flush=-1,so;n=0}t=i.gzindex<i.gzhead.comment.length?255&i.gzhead.comment.charCodeAt(i.gzindex++):0,Lo(i,t)}while(0!==t);i.gzhead.hcrc&&i.pending>n&&(e.adler=Gn(e.adler,i.pending_buf,i.pending-n,n))}i.status=103}if(103===i.status){if(i.gzhead.hcrc){if(i.pending+2>i.pending_buf_size&&(Oo(e),0!==i.pending))return i.last_flush=-1,so;Lo(i,255&e.adler),Lo(i,e.adler>>8&255),e.adler=0}if(i.status=Eo,Oo(e),0!==i.pending)return i.last_flush=-1,so}if(0!==e.avail_in||0!==i.lookahead||t!==io&&i.status!==Io){let n=0===i.level?No(i,t):i.strategy===fo?((e,t)=>{let i;for(;;){if(0===e.lookahead&&($o(e),0===e.lookahead)){if(t===io)return 1;break}if(e.match_length=0,i=eo(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,i&&(Fo(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===ro?(Fo(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(Fo(e,!1),0===e.strm.avail_out)?1:2})(i,t):i.strategy===go?((e,t)=>{let i,n,o,r;const a=e.window;for(;;){if(e.lookahead<=yo){if($o(e),e.lookahead<=yo&&t===io)return 1;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=3&&e.strstart>0&&(o=e.strstart-1,n=a[o],n===a[++o]&&n===a[++o]&&n===a[++o])){r=e.strstart+yo;do{}while(n===a[++o]&&n===a[++o]&&n===a[++o]&&n===a[++o]&&n===a[++o]&&n===a[++o]&&n===a[++o]&&n===a[++o]&&o<r);e.match_length=yo-(r-o),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=3?(i=eo(e,1,e.match_length-3),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(i=eo(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),i&&(Fo(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===ro?(Fo(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(Fo(e,!1),0===e.strm.avail_out)?1:2})(i,t):Ho[i.level].func(i,t);if(3!==n&&4!==n||(i.status=Io),1===n||3===n)return 0===e.avail_out&&(i.last_flush=-1),so;if(2===n&&(t===no?to(i):t!==ao&&(Qn(i,0,0,!1),t===oo&&(Ro(i.head),0===i.lookahead&&(i.strstart=0,i.block_start=0,i.insert=0))),Oo(e),0===e.avail_out))return i.last_flush=-1,so}return t!==ro?so:i.wrap<=0?lo:(2===i.wrap?(Lo(i,255&e.adler),Lo(i,e.adler>>8&255),Lo(i,e.adler>>16&255),Lo(i,e.adler>>24&255),Lo(i,255&e.total_in),Lo(i,e.total_in>>8&255),Lo(i,e.total_in>>16&255),Lo(i,e.total_in>>24&255)):(Bo(i,e.adler>>>16),Bo(i,65535&e.adler)),Oo(e),i.wrap>0&&(i.wrap=-i.wrap),0!==i.pending?so:lo)},jo=(e,t)=>{let i=t.length;if(Wo(e))return co;const n=e.state,o=n.wrap;if(2===o||1===o&&n.status!==ko||n.lookahead)return co;if(1===o&&(e.adler=qn(e.adler,t,i,0)),n.wrap=0,i>=n.w_size){0===o&&(Ro(n.head),n.strstart=0,n.block_start=0,n.insert=0);let e=new Uint8Array(n.w_size);e.set(t.subarray(i-n.w_size,i),0),t=e,i=n.w_size}const r=e.avail_in,a=e.next_in,d=e.input;for(e.avail_in=i,e.next_in=0,e.input=t,$o(n);n.lookahead>=3;){let e=n.strstart,t=n.lookahead-2;do{n.ins_h=Ao(n,n.ins_h,n.window[e+3-1]),n.prev[e&n.w_mask]=n.head[n.ins_h],n.head[n.ins_h]=e,e++}while(--t);n.strstart=e,n.lookahead=2,$o(n)}return n.strstart+=n.lookahead,n.block_start=n.strstart,n.insert=n.lookahead,n.lookahead=0,n.match_length=n.prev_length=2,n.match_available=0,e.next_in=a,e.input=d,e.avail_in=r,n.wrap=o,so},Ko={deflateInit:(e,t)=>Yo(e,t,vo,15,8,_o),deflateInit2:Yo,deflateReset:qo,deflateResetKeep:Xo,deflateSetHeader:(e,t)=>Wo(e)||2!==e.state.wrap?co:(e.state.gzhead=t,so),deflate:Go,deflateEnd:e=>{if(Wo(e))return co;const t=e.state.status;return e.state=null,t===Eo?So(e,ho):so},deflateSetDictionary:jo,deflateInfo:"pako deflate (from Nodeca project)"};const Zo=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var Qo=function(e){const t=Array.prototype.slice.call(arguments,1);for(;t.length;){const i=t.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(const t in i)Zo(i,t)&&(e[t]=i[t])}}return e},Jo=e=>{let t=0;for(let i=0,n=e.length;i<n;i++)t+=e[i].length;const i=new Uint8Array(t);for(let t=0,n=0,o=e.length;t<o;t++){let o=e[t];i.set(o,n),n+=o.length}return i};let er=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){er=!1}const tr=new Uint8Array(256);for(let e=0;e<256;e++)tr[e]=e>=252?6:e>=248?5:e>=240?4:e>=224?3:e>=192?2:1;tr[254]=tr[254]=1;var ir=e=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(e);let t,i,n,o,r,a=e.length,d=0;for(o=0;o<a;o++)i=e.charCodeAt(o),55296==(64512&i)&&o+1<a&&(n=e.charCodeAt(o+1),56320==(64512&n)&&(i=65536+(i-55296<<10)+(n-56320),o++)),d+=i<128?1:i<2048?2:i<65536?3:4;for(t=new Uint8Array(d),r=0,o=0;r<d;o++)i=e.charCodeAt(o),55296==(64512&i)&&o+1<a&&(n=e.charCodeAt(o+1),56320==(64512&n)&&(i=65536+(i-55296<<10)+(n-56320),o++)),i<128?t[r++]=i:i<2048?(t[r++]=192|i>>>6,t[r++]=128|63&i):i<65536?(t[r++]=224|i>>>12,t[r++]=128|i>>>6&63,t[r++]=128|63&i):(t[r++]=240|i>>>18,t[r++]=128|i>>>12&63,t[r++]=128|i>>>6&63,t[r++]=128|63&i);return t};var nr=function(){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};const or=Object.prototype.toString,{Z_NO_FLUSH:rr,Z_SYNC_FLUSH:ar,Z_FULL_FLUSH:dr,Z_FINISH:sr,Z_OK:lr,Z_STREAM_END:cr,Z_DEFAULT_COMPRESSION:hr,Z_DEFAULT_STRATEGY:mr,Z_DEFLATED:pr}=Kn;function ur(e){this.options=Qo({level:hr,method:pr,chunkSize:16384,windowBits:15,memLevel:8,strategy:mr},e||{});let t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new nr,this.strm.avail_out=0;let i=Ko.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(i!==lr)throw new Error(jn[i]);if(t.header&&Ko.deflateSetHeader(this.strm,t.header),t.dictionary){let e;if(e="string"==typeof t.dictionary?ir(t.dictionary):"[object ArrayBuffer]"===or.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,i=Ko.deflateSetDictionary(this.strm,e),i!==lr)throw new Error(jn[i]);this._dict_set=!0}}ur.prototype.push=function(e,t){const i=this.strm,n=this.options.chunkSize;let o,r;if(this.ended)return!1;for(r=t===~~t?t:!0===t?sr:rr,"string"==typeof e?i.input=ir(e):"[object ArrayBuffer]"===or.call(e)?i.input=new Uint8Array(e):i.input=e,i.next_in=0,i.avail_in=i.input.length;;)if(0===i.avail_out&&(i.output=new Uint8Array(n),i.next_out=0,i.avail_out=n),(r===ar||r===dr)&&i.avail_out<=6)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else{if(o=Ko.deflate(i,r),o===cr)return i.next_out>0&&this.onData(i.output.subarray(0,i.next_out)),o=Ko.deflateEnd(this.strm),this.onEnd(o),this.ended=!0,o===lr;if(0!==i.avail_out){if(r>0&&i.next_out>0)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else if(0===i.avail_in)break}else this.onData(i.output)}return!0},ur.prototype.onData=function(e){this.chunks.push(e)},ur.prototype.onEnd=function(e){e===lr&&(this.result=Jo(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var fr={deflate:function(e,t){const i=new ur(t);if(i.push(e,!0),i.err)throw i.msg||jn[i.err];return i.result}};const{deflate:gr}=fr;var br=gr;const _r={b:{u:DataView.prototype.getInt8,p:DataView.prototype.setInt8,bytes:1},B:{u:DataView.prototype.getUint8,p:DataView.prototype.setUint8,bytes:1},h:{u:DataView.prototype.getInt16,p:DataView.prototype.setInt16,bytes:2},H:{u:DataView.prototype.getUint16,p:DataView.prototype.setUint16,bytes:2},i:{u:DataView.prototype.getInt32,p:DataView.prototype.setInt32,bytes:4},I:{u:DataView.prototype.getUint32,p:DataView.prototype.setUint32,bytes:4}},xr=(e,...t)=>{let i=0;if(e.replace(/[<>]/,"").length!=t.length)throw"Pack format to Argument count mismatch";const n=[];let o=!0;for(let n=0;n<e.length;n++)"<"==e[n]?o=!0:">"==e[n]?o=!1:(r(e[n],t[i]),i++);function r(e,t){if(!(e in _r))throw"Unhandled character '"+e+"' in pack format";const i=_r[e].bytes,r=new DataView(new ArrayBuffer(i));_r[e].p.bind(r)(0,t,o);for(let e=0;e<i;e++)n.push(r.getUint8(e))}return n},vr=(e,t)=>{let i=0;const n=[];let o=!0;for(const t of e)"<"==t?o=!0:">"==t?o=!1:r(t);function r(e){if(!(e in _r))throw"Unhandled character '"+e+"' in unpack format";const r=_r[e].bytes,a=new DataView(new ArrayBuffer(r));for(let e=0;e<r;e++)a.setUint8(e,255&t[i+e]);const d=_r[e].u.bind(a);n.push(d(0,o)),i+=r}return n};class yr extends EventTarget{constructor(e,t,i){super(),this.port=e,this.logger=t,this._parent=i,this.chipName=null,this.chipRevision=null,this.chipVariant=null,this._efuses=new Array(4).fill(0),this._flashsize=4194304,this.debug=!1,this.IS_STUB=!1,this.connected=!0,this.flashSize=null,this._currentBaudRate=Fi,this._isESP32S2NativeUSB=!1,this._initializationSucceeded=!1,this.state_DTR=!1}get _inputBuffer(){return this._parent?this._parent._inputBuffer:this.__inputBuffer}get _totalBytesRead(){return this._parent?this._parent._totalBytesRead:this.__totalBytesRead||0}set _totalBytesRead(e){this._parent?this._parent._totalBytesRead=e:this.__totalBytesRead=e}detectUSBSerialChip(e,t){const i={6790:{29986:{name:"CH340",maxBaudrate:460800},29987:{name:"CH340",maxBaudrate:460800},30084:{name:"CH340",maxBaudrate:460800},21795:{name:"CH341",maxBaudrate:2e6},21971:{name:"CH343",maxBaudrate:6e6},21972:{name:"CH9102",maxBaudrate:6e6},21976:{name:"CH9101",maxBaudrate:3e6}},4292:{6e4:{name:"CP2102(n)",maxBaudrate:3e6},60016:{name:"CP2105",maxBaudrate:2e6},60017:{name:"CP2108",maxBaudrate:2e6}},1027:{24577:{name:"FT232R",maxBaudrate:3e6},24592:{name:"FT2232",maxBaudrate:3e6},24593:{name:"FT4232",maxBaudrate:3e6},24596:{name:"FT232H",maxBaudrate:12e6},24597:{name:"FT230X",maxBaudrate:3e6}},12346:{2:{name:"ESP32-S2 Native USB",maxBaudrate:2e6},4097:{name:"ESP32 Native USB",maxBaudrate:2e6},4098:{name:"ESP32 Native USB",maxBaudrate:2e6},16386:{name:"ESP32 Native USB",maxBaudrate:2e6},4096:{name:"ESP32 Native USB",maxBaudrate:2e6}}}[e];return i&&i[t]?i[t]:{name:`Unknown (VID: 0x${e.toString(16)}, PID: 0x${t.toString(16)})`}}async initialize(){if(await this.hardReset(!0),!this._parent){this.__inputBuffer=[],this.__totalBytesRead=0;const e=this.port.getInfo();if(e.usbVendorId&&e.usbProductId){const t=this.detectUSBSerialChip(e.usbVendorId,e.usbProductId);this.logger.log(`USB-Serial: ${t.name} (VID: 0x${e.usbVendorId.toString(16)}, PID: 0x${e.usbProductId.toString(16)})`),t.maxBaudrate&&(this._maxUSBSerialBaudrate=t.maxBaudrate,this.logger.log(`Max baudrate: ${t.maxBaudrate}`)),12346===e.usbVendorId&&2===e.usbProductId&&(this._isESP32S2NativeUSB=!0)}this.readLoop()}await this.flushSerialBuffers(),await this.sync(),await this.detectChip();const e=tn(this.getChipFamily()),t=e.macFuse;for(let e=0;e<4;e++)this._efuses[e]=await this.readRegister(t+4*e);this.logger.log(`Chip type ${this.chipName}`),this.logger.debug(`Bootloader flash offset: 0x${e.flashOffs.toString(16)}`),this._initializationSucceeded=!0}async detectChip(){try{const e=(await this.getSecurityInfo()).chipId,t=ji[e];if(t)return this.chipName=t.name,this.chipFamily=t.family,this.chipFamily===Yi&&(this.chipRevision=await this.getChipRevision(),this.logger.debug(`ESP32-P4 revision: ${this.chipRevision}`),this.chipRevision>=300?this.chipVariant="rev300":this.chipVariant="rev0",this.logger.debug(`ESP32-P4 variant: ${this.chipVariant}`)),void this.logger.debug(`Detected chip via IMAGE_CHIP_ID: ${e} (${this.chipName})`);this.logger.debug(`Unknown IMAGE_CHIP_ID: ${e}, falling back to magic value detection`)}catch(e){this.logger.debug(`GET_SECURITY_INFO failed, using magic value detection: ${e}`),this._inputBuffer.length=0,await Ai(Ji);try{await this.sync()}catch(e){this.logger.debug(`Re-sync after GET_SECURITY_INFO failure: ${e}`)}}const e=await this.readRegister(1073745920),t=Ki[e>>>0];if(void 0===t)throw new Error(`Unknown Chip: Hex: ${Ti(e>>>0,8).toLowerCase()} Number: ${e}`);this.chipName=t.name,this.chipFamily=t.family,this.chipFamily===Yi&&(this.chipRevision=await this.getChipRevision(),this.logger.debug(`ESP32-P4 revision: ${this.chipRevision}`),this.chipRevision>=300?this.chipVariant="rev300":this.chipVariant="rev0",this.logger.debug(`ESP32-P4 variant: ${this.chipVariant}`)),this.logger.debug(`Detected chip via magic value: ${Ti(e>>>0,8)} (${this.chipName})`)}async getChipRevision(){if(this.chipFamily!==Yi)return 0;const e=await this.readRegister(1343410252);return 100*((e>>23&1)<<2|e>>4&3)+(15&e)}async getSecurityInfo(){const[,e]=await this.checkCommand(20,[],0);if(0===e.length)throw new Error("GET_SECURITY_INFO not supported or returned empty response");if(e.length<12)throw new Error(`Invalid security info response length: ${e.length} (expected at least 12 bytes)`);return{flags:vr("<I",e.slice(0,4))[0],flashCryptCnt:e[4],keyPurposes:Array.from(e.slice(5,12)),chipId:e.length>=16?vr("<I",e.slice(12,16))[0]:0,apiVersion:e.length>=20?vr("<I",e.slice(16,20))[0]:0}}async readLoop(){this.debug&&this.logger.debug("Starting read loop"),this._reader=this.port.readable.getReader();try{let e=!0;for(;e;){const{value:t,done:i}=await this._reader.read();if(i){this._reader.releaseLock(),e=!1;break}if(!t||0===t.length)continue;const n=Array.from(t);Array.prototype.push.apply(this._inputBuffer,n),this._totalBytesRead+=t.length}}catch{this.logger.error("Read loop got disconnected")}this.connected=!1,this._isESP32S2NativeUSB&&!this._initializationSucceeded&&(this.logger.log("ESP32-S2 Native USB detected - requesting port reselection"),this.dispatchEvent(new CustomEvent("esp32s2-usb-reconnect",{detail:{message:"ESP32-S2 Native USB requires port reselection"}}))),this.dispatchEvent(new Event("disconnect")),this.logger.debug("Finished read loop")}sleep(e=100){return new Promise(t=>setTimeout(t,e))}async setRTS(e){await this.port.setSignals({requestToSend:e}),await this.setDTR(this.state_DTR)}async setDTR(e){this.state_DTR=e,await this.port.setSignals({dataTerminalReady:e})}async hardReset(e=!1){e?4097===this.port.getInfo().usbProductId?(await this.setDTR(!1),await this.setRTS(!1),await this.sleep(100),await this.setDTR(!0),await this.setRTS(!1),await this.sleep(100),await this.setRTS(!0),await this.setDTR(!1),await this.setRTS(!0),await this.sleep(100),await this.setDTR(!1),await this.setRTS(!1),this.logger.log("USB MCU reset.")):(await this.setDTR(!1),await this.setRTS(!0),await this.sleep(100),await this.setDTR(!0),await this.setRTS(!1),await this.sleep(50),await this.setDTR(!1),this.logger.log("DTR/RTS USB serial chip reset.")):(await this.setRTS(!0),await this.sleep(100),await this.setRTS(!1),this.logger.log("Hard reset.")),await new Promise(e=>setTimeout(e,1e3))}macAddr(){const e=new Array(6).fill(0),t=this._efuses[0],i=this._efuses[1],n=this._efuses[2],o=this._efuses[3];let r;if(this.chipFamily==zi){if(0!=o)r=[o>>16&255,o>>8&255,255&o];else if(i>>16&255){if(1!=(i>>16&255))throw new Error("Couldnt determine OUI");r=[172,208,116]}else r=[24,254,52];e[0]=r[0],e[1]=r[1],e[2]=r[2],e[3]=i>>8&255,e[4]=255&i,e[5]=t>>24&255}else if(this.chipFamily==Di)e[0]=n>>8&255,e[1]=255&n,e[2]=i>>24&255,e[3]=i>>16&255,e[4]=i>>8&255,e[5]=255&i;else{if(this.chipFamily!=$i&&this.chipFamily!=Ni&&this.chipFamily!=Pi&&this.chipFamily!=Mi&&this.chipFamily!=Ui&&this.chipFamily!=Hi&&this.chipFamily!=Vi&&this.chipFamily!=Wi&&this.chipFamily!=Xi&&this.chipFamily!=qi&&this.chipFamily!=Yi&&this.chipFamily!=Gi)throw new Error("Unknown chip family");e[0]=i>>8&255,e[1]=255&i,e[2]=t>>24&255,e[3]=t>>16&255,e[4]=t>>8&255,e[5]=255&t}return e}async readRegister(e){this.debug&&this.logger.debug("Reading from Register "+Ti(e,8));const t=xr("<I",e);await this.sendCommand(10,t);const[i]=await this.getResponse(10);return i}async checkCommand(e,t,i=0,n=3e3){n=Math.min(n,3e5),await this.sendCommand(e,t,i);const[o,r]=await this.getResponse(e,n);if(null===r)throw new Error("Didn't get enough status bytes");let a=r,d=0;if(this.IS_STUB||this.chipFamily==zi?d=2:[Di,$i,Ni,Pi,Mi,Ui,Hi,Vi,Wi,Xi,qi,Yi,Gi].includes(this.chipFamily)||20===e?d=4:[2,4].includes(a.length)&&(d=a.length),a.length<d)throw new Error("Didn't get enough status bytes");const s=a.slice(-d,a.length);if(a=a.slice(0,-d),this.debug&&(this.logger.debug("status",s),this.logger.debug("value",o),this.logger.debug("data",a)),1==s[0])throw 5==s[1]?new Error("Invalid (unsupported) command "+Ti(e)):new Error("Command failure error code "+Ti(s[1]));return[o,a]}async sendCommand(e,t,i=0){const n=Si([...xr("<BBHI",0,e,t.length,i),...t]);this.debug&&this.logger.debug(`Writing ${n.length} byte${1==n.length?"":"s"}:`,n),await this.writeToStream(n)}async readPacket(e){let t=null,i=!1,n=[];for(;;){const o=Date.now();for(n=[];Date.now()-o<e;){if(this._inputBuffer.length>0){n.push(this._inputBuffer.shift());break}await Ai(1)}if(0==n.length){throw new nn("Timed out waiting for packet "+(null===t?"header":"content"))}this.debug&&this.logger.debug("Read "+n.length+" bytes: "+Ri(n));for(const e of n)if(null===t){if(192!=e)throw this.debug&&(this.logger.debug("Read invalid data: "+Ri(n)),this.logger.debug("Remaining data in serial buffer: "+Ri(this._inputBuffer))),new nn("Invalid head of packet ("+Ti(e)+")");t=[]}else if(i)if(i=!1,220==e)t.push(192);else{if(221!=e)throw this.debug&&(this.logger.debug("Read invalid data: "+Ri(n)),this.logger.debug("Remaining data in serial buffer: "+Ri(this._inputBuffer))),new nn("Invalid SLIP escape (0xdb, "+Ti(e)+")");t.push(219)}else if(219==e)i=!0;else{if(192==e)return this.debug&&this.logger.debug("Received full packet: "+Ri(t)),t;t.push(e)}}throw new nn("Invalid state")}async getResponse(e,t=3e3){for(let i=0;i<100;i++){const i=await this.readPacket(t);if(i.length<8)continue;const[n,o,,r]=vr("<BBHI",i.slice(0,8));if(1!=n)continue;const a=i.slice(8);if(null==e||o==e)return[r,a];if(0!=a[0]&&5==a[1])throw this._inputBuffer.length=0,new Error(`Invalid (unsupported) command ${Ti(e)}`)}throw"Response doesn't match request"}checksum(e,t=239){for(const i of e)t^=i;return t}async setBaudrate(e){if(this.chipFamily==zi)throw new Error("Changing baud rate is not supported on the ESP8266");try{const t=xr("<II",e,this.IS_STUB?Fi:0);await this.checkCommand(15,t)}catch(t){throw this.logger.error(`Baudrate change error: ${t}`),new Error(`Unable to change the baud rate to ${e}: No response from set baud rate command.`)}this._parent?await this._parent.reconfigurePort(e):await this.reconfigurePort(e),this._parent?this._parent._currentBaudRate=e:this._currentBaudRate=e;const t=this._parent?this._parent._maxUSBSerialBaudrate:this._maxUSBSerialBaudrate;t&&e>t&&(this.logger.log(`⚠️ WARNING: Baudrate ${e} exceeds USB-Serial chip limit (${t})!`),this.logger.log("⚠️ This may cause data corruption or connection failures!")),this.logger.log(`Changed baud rate to ${e}`)}async reconfigurePort(e){var t;try{await(null===(t=this._reader)||void 0===t?void 0:t.cancel()),await this.port.close(),await this.port.open({baudRate:e}),await this.flushSerialBuffers(),this.readLoop()}catch(t){throw this.logger.error(`Reconfigure port error: ${t}`),new Error(`Unable to change the baud rate to ${e}: ${t}`)}}async sync(){for(let e=0;e<5;e++){this._inputBuffer.length=0;if(await this._sync())return await Ai(Ji),!0;await Ai(Ji)}throw new Error("Couldn't sync to ESP. Try resetting.")}async _sync(){await this.sendCommand(8,Bi);for(let e=0;e<8;e++)try{const[,e]=await this.getResponse(8,Ji);if(e.length>1&&0==e[0]&&0==e[1])return!0}catch{}return!1}getFlashWriteSize(){return this.IS_STUB?16384:1024}async flashData(e,t,i=0,n=!1){if(e.byteLength>=8){const t=Array.from(new Uint8Array(e,0,4)),i=t[0],n=t[2],o=t[3];this.logger.log(`Image header, Magic=${Ti(i)}, FlashMode=${Ti(n)}, FlashSizeFreq=${Ti(o)}`)}const o=e.byteLength;let r,a=0,d=Zi;n?(r=br(new Uint8Array(e),{level:9}).buffer,a=r.byteLength,this.logger.log(`Writing data with filesize: ${o}. Compressed Size: ${a}`),d=await this.flashDeflBegin(o,a,i)):(this.logger.log(`Writing data with filesize: ${o}`),r=e,await this.flashBegin(o,i));let s=[],l=0,c=0,h=0;const m=Date.now(),p=this.getFlashWriteSize(),u=n?a:o;for(;u-h>0;)this.debug&&this.logger.log(`Writing at ${Ti(i+l*p,8)} `),u-h>=p?s=Array.from(new Uint8Array(r,h,p)):(s=Array.from(new Uint8Array(r,h,u-h)),n||(s=s.concat(new Array(p-s.length).fill(255)))),n?await this.flashDeflBlock(s,l,d):await this.flashBlock(s,l),l+=1,c+=n?Math.round(s.length*o/a):s.length,h+=p,t(Math.min(c,o),o);this.logger.log("Took "+(Date.now()-m)+"ms to write "+u+" bytes"),this.IS_STUB&&(await this.flashBegin(0,0),n?await this.flashDeflFinish():await this.flashFinish())}async flashBlock(e,t,i=3e3){await this.checkCommand(3,xr("<IIII",e.length,t,0,0).concat(e),this.checksum(e),i)}async flashDeflBlock(e,t,i=3e3){await this.checkCommand(17,xr("<IIII",e.length,t,0,0).concat(e),this.checksum(e),i)}async flashBegin(e=0,t=0,i=!1){let n;await this.flushSerialBuffers();const o=this.getFlashWriteSize();!this.IS_STUB&&[Di,$i,Ni,Pi,Mi,Ui,Hi,Vi,Wi,Xi,qi,Yi,Gi].includes(this.chipFamily)&&await this.checkCommand(13,new Array(8).fill(0));const r=Math.floor((e+o-1)/o);n=this.chipFamily==zi?this.getEraseSize(t,e):e;const a=this.IS_STUB?Zi:en(3e4,e),d=Date.now();let s=xr("<IIII",n,r,o,t);return this.chipFamily!=Di&&this.chipFamily!=$i&&this.chipFamily!=Ni&&this.chipFamily!=Pi&&this.chipFamily!=Mi&&this.chipFamily!=Ui&&this.chipFamily!=Hi&&this.chipFamily!=Vi&&this.chipFamily!=Wi&&this.chipFamily!=Xi&&this.chipFamily!=qi&&this.chipFamily!=Yi&&this.chipFamily!=Gi||(s=s.concat(xr("<I",i?1:0))),this.logger.log("Erase size "+n+", blocks "+r+", block size "+Ti(o,4)+", offset "+Ti(t,4)+", encrypted "+(i?"yes":"no")),await this.checkCommand(2,s,0,a),0==e||this.IS_STUB||this.logger.log("Took "+(Date.now()-d)+"ms to erase "+r+" bytes"),r}async flashDeflBegin(e=0,t=0,i=0){const n=this.getFlashWriteSize(),o=Math.floor((t+n-1)/n),r=Math.floor((e+n-1)/n);let a=0,d=0;this.IS_STUB?(a=e,d=en(3e4,a)):(a=r*n,d=Zi);const s=xr("<IIII",a,o,n,i);return await this.checkCommand(16,s,0,d),d}async flashFinish(){const e=xr("<I",1);await this.checkCommand(4,e)}async flashDeflFinish(){const e=xr("<I",1);await this.checkCommand(18,e)}getBootloaderOffset(){return tn(this.getChipFamily()).flashOffs}async flashId(){return await this.runSpiFlashCommand(159,[],24)}getChipFamily(){return this._parent?this._parent.chipFamily:this.chipFamily}async writeRegister(e,t,i=4294967295,n=0,o=0){let r=xr("<IIII",e,t,i,n);o>0&&(r=r.concat(xr("<IIII",tn(this.getChipFamily()).uartDateReg,0,0,o))),await this.checkCommand(9,r)}async setDataLengths(e,t,i){if(-1!=e.mosiDlenOffs){const n=e.regBase+e.mosiDlenOffs,o=e.regBase+e.misoDlenOffs;t>0&&await this.writeRegister(n,t-1),i>0&&await this.writeRegister(o,i-1)}else{const n=e.regBase+e.usr1Offs,o=(0==i?0:i-1)<<8|(0==t?0:t-1)<<17;await this.writeRegister(n,o)}}async waitDone(e,t){for(let i=0;i<10;i++){if(0==(await this.readRegister(e)&t))return}throw Error("SPI command did not complete in time")}async runSpiFlashCommand(e,t,i=0){const n=tn(this.getChipFamily()),o=n.regBase,r=o,a=o+n.usrOffs,d=o+n.usr2Offs,s=o+n.w0Offs,l=1<<18;if(i>32)throw new Error("Reading more than 32 bits back from a SPI flash operation is unsupported");if(t.length>64)throw new Error("Writing more than 64 bytes of data with one SPI command is unsupported");const c=8*t.length,h=await this.readRegister(a),m=await this.readRegister(d);let p=1<<31;if(i>0&&(p|=268435456),c>0&&(p|=134217728),await this.setDataLengths(n,c,i),await this.writeRegister(a,p),await this.writeRegister(d,7<<28|e),0==c)await this.writeRegister(s,0);else{const e=(4-t.length%4)%4;t=t.concat(new Array(e).fill(0));const i=vr("I".repeat(Math.floor(t.length/4)),t);let n=s;this.logger.debug(`Words Length: ${i.length}`);for(const e of i)this.logger.debug(`Writing word ${Ti(e)} to register offset ${Ti(n)}`),await this.writeRegister(n,e),n+=4}await this.writeRegister(r,l),await this.waitDone(r,l);const u=await this.readRegister(s);return await this.writeRegister(a,h),await this.writeRegister(d,m),u}async detectFlashSize(){this.logger.log("Detecting Flash Size");const e=await this.flashId(),t=255&e,i=e>>16&255;this.logger.log(`FlashId: ${Ti(e)}`),this.logger.log(`Flash Manufacturer: ${t.toString(16)}`),this.logger.log(`Flash Device: ${(e>>8&255).toString(16)}${i.toString(16)}`),this.flashSize=Oi[i],this.logger.log(`Auto-detected Flash size: ${this.flashSize}`)}getEraseSize(e,t){const i=4096,n=Math.floor((t+i-1)/i);let o=16-Math.floor(e/i)%16;return n<o&&(o=n),n<2*o?Math.floor((n+1)/2*i):(n-o)*i}async memBegin(e,t,i,n){return await this.checkCommand(5,xr("<IIII",e,t,i,n))}async memBlock(e,t){return await this.checkCommand(7,xr("<IIII",e.length,t,0,0).concat(e),this.checksum(e))}async memFinish(e=0){const t=this.IS_STUB?Zi:500,i=xr("<II",0==e?1:0,e);return await this.checkCommand(6,i,0,t)}async runStub(e=!1){const t=await on(this.chipFamily,this.chipRevision);if(null===t)return this.logger.log(`Stub flasher is not yet supported on ${this.chipName}, using ROM loader`),this;const i=2048;this.logger.log("Uploading stub...");for(const e of["text","data"]){const n=t[e],o=t[`${e}_start`],r=n.length,a=Math.floor((r+i-1)/i);await this.memBegin(r,a,i,o);for(const e of Array(a).keys()){const t=e*i;let o=t+i;o>r&&(o=r),await this.memBlock(n.slice(t,o),e)}}await this.memFinish(t.entry);const n=await this.readPacket(500),o=String.fromCharCode(...n);if("OHAI"!=o)throw new Error("Failed to start stub. Unexpected response: "+o);this.logger.log("Stub is now running...");const r=new wr(this.port,this.logger,this);return e||await r.detectFlashSize(),r}async writeToStream(e){if(!this.port.writable)return void this.logger.debug("Port writable stream not available, skipping write");const t=this.port.writable.getWriter();await t.write(new Uint8Array(e));try{t.releaseLock()}catch(e){this.logger.error(`Ignoring release lock error: ${e}`)}}async disconnect(){this._parent?await this._parent.disconnect():this.port.writable?(await this.port.writable.getWriter().close(),await new Promise(e=>{this._reader||e(void 0),this.addEventListener("disconnect",e,{once:!0}),this._reader.cancel()}),this.connected=!1):this.logger.debug("Port already closed, skipping disconnect")}async reconnect(){if(this._parent)return void await this._parent.reconnect();if(this.logger.log("Reconnecting serial port..."),this.connected=!1,this.__inputBuffer=[],this._reader){try{await this._reader.cancel()}catch(e){this.logger.debug(`Reader cancel error: ${e}`)}this._reader=void 0}try{await this.port.close(),this.logger.log("Port closed")}catch(e){this.logger.debug(`Port close error: ${e}`)}this.logger.debug("Opening port...");try{await this.port.open({baudRate:Fi}),this.connected=!0}catch(e){throw new Error(`Failed to open port: ${e}`)}if(!this.port.readable||!this.port.writable)throw new Error(`Port streams not available after open (readable: ${!!this.port.readable}, writable: ${!!this.port.writable})`);const e=this.chipFamily,t=this.chipName,i=this.chipRevision,n=this.chipVariant,o=this.flashSize;if(await this.hardReset(!0),this._parent||(this.__inputBuffer=[],this.__totalBytesRead=0,this.readLoop()),await this.flushSerialBuffers(),await this.sync(),this.chipFamily=e,this.chipName=t,this.chipRevision=i,this.chipVariant=n,this.flashSize=o,this.logger.debug(`Reconnect complete (chip: ${this.chipName})`),!this.port.writable||!this.port.readable)throw new Error("Port not ready after reconnect");const r=await this.runStub(!0);if(this.logger.debug("Stub loaded"),this._currentBaudRate!==Fi&&(await r.setBaudrate(this._currentBaudRate),!this.port.writable||!this.port.readable))throw new Error(`Port not ready after baudrate change (readable: ${!!this.port.readable}, writable: ${!!this.port.writable})`);this.IS_STUB&&Object.assign(this,r),this.logger.debug("Reconnection successful")}async flushSerialBuffers(){this._parent||(this.__inputBuffer=[]),await Ai(Ji),this._parent||(this.__inputBuffer=[]),this.logger.debug("Serial buffers flushed")}async readFlash(e,t,i){if(!this.IS_STUB)throw new Error("Reading flash is only supported in stub mode. Please run runStub() first.");await this.flushSerialBuffers(),this.logger.log(`Reading ${t} bytes from flash at address 0x${e.toString(16)}...`);let n=new Uint8Array(0),o=e,r=t;for(;r>0;){const e=Math.min(65536,r);let a=!1,d=0;const s=3;for(;!a&&d<=s;)try{this.logger.debug(`Reading chunk at 0x${o.toString(16)}, size: 0x${e.toString(16)}`);const t=xr("<IIII",o,e,4096,1024),[i]=await this.checkCommand(210,t);if(0!=i)throw new Error("Failed to read memory: "+i);let r=new Uint8Array(0);for(;r.length<e;){let t;try{t=await this.readPacket(100)}catch(t){if(t instanceof nn&&(this.logger.debug(`SLIP read error at ${r.length} bytes: ${t.message}`),r.length>=e))break;throw t}if(t&&t.length>0){const e=new Uint8Array(t),i=new Uint8Array(r.length+e.length);i.set(r),i.set(e,r.length),r=i;const n=xr("<I",r.length),o=Si(n);await this.writeToStream(o)}}const d=new Uint8Array(n.length+r.length);d.set(n),d.set(r,n.length),n=d,a=!0}catch(e){if(d++,!(e instanceof nn&&e.message.includes("Timed out")))throw e;if(!(d<=s))throw new Error(`Failed to read chunk at 0x${o.toString(16)} after ${s} retries: ${e}`);this.logger.log(`⚠️ Timeout error at 0x${o.toString(16)}. Reconnecting and retrying (attempt ${d}/${s})...`);try{await this.reconnect()}catch(e){throw new Error(`Reconnect failed: ${e}`)}}i&&i(new Uint8Array(e),n.length,t),o+=e,r-=e,this.logger.debug(`Total progress: 0x${n.length.toString(16)} from 0x${t.toString(16)} bytes`)}return this.logger.debug(`Successfully read ${n.length} bytes from flash`),n}}class wr extends yr{constructor(){super(...arguments),this.IS_STUB=!0}async memBegin(e,t,i,n){const o=await on(this.chipFamily,this.chipRevision);if(null===o)return[0,[]];const r=n,a=n+e;this.logger.debug(`Load range: ${Ti(r,8)}-${Ti(a,8)}`),this.logger.debug(`Stub data: ${Ti(o.data_start,8)}, len: ${o.data.length}, text: ${Ti(o.text_start,8)}, len: ${o.text.length}`);for(const[e,t]of[[o.data_start,o.data_start+o.data.length],[o.text_start,o.text_start+o.text.length]])if(r<t&&a>e)throw new Error("Software loader is resident at "+Ti(e,8)+"-"+Ti(t,8)+". Can't load binary at overlapping address range "+Ti(r,8)+"-"+Ti(a,8)+". Try changing the binary loading address.");return[0,[]]}async eraseFlash(){await this.checkCommand(208,[],0,Qi)}}const kr=async(e,t,i,n,o,r,a)=>{let d,s,l,c=null,h=!1;const m=(e=>{const t=e.getInfo();return 12346===t.usbVendorId&&2===t.usbProductId})(t),p=t=>e({...t,manifest:d,build:s,chipFamily:l,chipVariant:c});var u=null,f="";try{u=JSON.parse(n)}catch{f=new URL(n,location.toString()).toString(),u=fetch(f).then(e=>e.json())}const g=new yr(t,i);window.esploader=g;const b=()=>{h=!0,i.log("ESP32-S2 Native USB disconnect detected - reconnection required")};m&&(g.addEventListener("esp32s2-usb-reconnect",b),i.log("ESP32-S2 Native USB detected - monitoring for port switch"));const _=()=>{m&&g.removeEventListener("esp32s2-usb-reconnect",b)};p({state:"initializing",message:"Initializing...",details:{done:!1}});try{await g.initialize()}catch(e){if(i.error(e),m&&(h||String(e).includes("reconnect required"))){_();try{await t.close()}catch{}try{await t.forget()}catch{}return void p({state:"esp32_s2_usb_reconnect",message:"ESP32-S2 USB port changed - please select the new port",details:{oldPort:t}})}return _(),p({state:"error",message:"Failed to initialize. Try resetting your device or holding the BOOT button while clicking INSTALL.",details:{error:"failed_initialize",details:e}}),void(g.connected&&await g.disconnect())}l=(e=>{switch(e.chipFamily){case Di:return"ESP32";case $i:return"ESP32-S2";case Ni:return"ESP32-S3";case Pi:return"ESP32-C2";case Mi:return"ESP32-C3";case Ui:return"ESP32-C5";case Hi:return"ESP32-C6";case Vi:return"ESP32-C61";case Wi:return"ESP32-H2";case Yi:return"ESP32-P4";case zi:return"ESP8266";default:return"Unknown Chip"}})(g),c=g.chipVariant,p({state:"initializing",message:`Initialized. Found ${l}${c?` (${c})`:""}`,details:{done:!0}}),p({state:"manifest",message:"Fetching manifest...",details:{done:!1}});try{d=await u}catch(e){return _(),p({state:"error",message:`Unable to fetch manifest: ${e}`,details:{error:"fetch_manifest_failed",details:e}}),void await g.disconnect()}if(s=d.builds.find(e=>e.chipFamily===l&&(void 0===e.chipVariant||e.chipVariant===c)),p({state:"manifest",message:`Found manifest for ${d.name}`,details:{done:!0}}),!s){const e=c?`${l} (${c})`:l;return _(),p({state:"error",message:`Your ${e} board is not supported.`,details:{error:"not_supported",details:e}}),void await g.disconnect()}p({state:"preparing",message:"Preparing installation...",details:{done:!1}});const x=s.parts.map(async e=>{if(0==r.length){const t=new URL(e.path,f).toString(),i=await fetch(t);if(!i.ok)throw new Error(`Downlading firmware ${e.path} failed: ${i.status}`);return i.arrayBuffer()}return r}),v=await g.runStub();if(void 0!==a&&a>115200)try{await v.setBaudrate(a)}catch(e){i.log(`Could not change baud rate to ${a}: ${e.message}`)}const y=[];let w=0;for(const e of x)try{const t=await e;y.push(t instanceof ArrayBuffer?new Uint8Array(t):t),w+=t.byteLength}catch(e){return _(),p({state:"error",message:e.message,details:{error:"failed_firmware_download",details:e.message}}),void await g.disconnect()}p({state:"preparing",message:"Installation prepared",details:{done:!0}}),o&&(p({state:"erasing",message:"Erasing device...",details:{done:!1}}),await v.eraseFlash(),p({state:"erasing",message:"Device erased",details:{done:!0}}));let k=0;p({state:"writing",message:`Writing progress: ${k}%`,details:{bytesTotal:w,bytesWritten:0,percentage:k}});let E=0;for(const e of s.parts){const t=y.shift(),i=t instanceof Uint8Array?new Uint8Array(t).buffer:t;try{await v.flashData(i,e=>{const t=Math.floor((E+e)/w*100);t!==k&&(k=t,p({state:"writing",message:`Writing progress: ${t}%`,details:{bytesTotal:w,bytesWritten:E+e,percentage:t}}))},e.offset,!0)}catch(e){return _(),p({state:"error",message:e.message,details:{error:"write_failed",details:e}}),void await g.disconnect()}E+=t.byteLength}p({state:"writing",message:"Writing complete",details:{bytesTotal:w,bytesWritten:E,percentage:100}}),await V(100),console.log("DISCONNECT"),await g.disconnect(),console.log("HARD RESET"),await g.hardReset(),_(),p({state:"finished",message:"All done!"})},Er=(e,t="")=>{const i=new Blob([e],{type:"text/plain"}),n=URL.createObjectURL(i);((e,t="")=>{const i=document.createElement("a");i.target="_blank",i.href=e,i.download=t,document.body.appendChild(i),i.dispatchEvent(new MouseEvent("click")),document.body.removeChild(i)})(n,t),setTimeout(()=>URL.revokeObjectURL(n),0)};class Ir extends x{constructor(){super(...arguments),this.logger=console,this._state="DASHBOARD",this._installErase=!1,this._installConfirmed=!1,this._provisionForce=!1,this._wasProvisioned=!1,this._busy=!1,this._esp32s2ReconnectInProgress=!1,this._selectedSsid=-1,this._handleDisconnect=()=>{this._state="ERROR",this._error="Disconnected"}}render(){if(!this.port)return h``;let e,t,i=!1,n=!1;return void 0===this._client&&"INSTALL"!==this._state&&"LOGS"!==this._state?this._error?[e,t,i]=this._renderError(this._error):(t=this._renderProgress("Connecting"),i=!0):"INSTALL"===this._state?[e,t,i,n]=this._renderInstall():"ASK_ERASE"===this._state?[e,t]=this._renderAskErase():"ERROR"===this._state?[e,t,i]=this._renderError(this._error):"DASHBOARD"===this._state?[e,t,i,n]=this._client?this._renderDashboard():this._renderDashboardNoImprov():"PROVISION"===this._state?[e,t,i]=this._renderProvision():"LOGS"===this._state&&([e,t,i]=this._renderLogs()),h`
|
|
418
418
|
<ewt-dialog
|
|
419
419
|
open
|
|
420
420
|
.heading=${e}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tasmota-esp-web-tools",
|
|
3
|
-
"version": "9.0.
|
|
3
|
+
"version": "9.0.2",
|
|
4
4
|
"description": "Web tools for ESP devices",
|
|
5
5
|
"main": "dist/install-button.js",
|
|
6
6
|
"repository": {
|
|
@@ -35,7 +35,7 @@
|
|
|
35
35
|
"@material/mwc-textfield": "^0.27.0",
|
|
36
36
|
"improv-wifi-serial-sdk": "^2.5.0",
|
|
37
37
|
"lit": "^2.8.0",
|
|
38
|
-
"tasmota-webserial-esptool": "^7.2.
|
|
38
|
+
"tasmota-webserial-esptool": "^7.2.2",
|
|
39
39
|
"tslib": "^2.8.1"
|
|
40
40
|
}
|
|
41
41
|
}
|
package/src/flash.ts
CHANGED
|
@@ -10,20 +10,13 @@ import { getChipFamilyName } from "./util/chip-family-name";
|
|
|
10
10
|
import { sleep } from "./util/sleep";
|
|
11
11
|
|
|
12
12
|
/**
|
|
13
|
-
* Check if a serial port is an ESP32-S2 Native USB device
|
|
13
|
+
* Check if a serial port is an ESP32-S2 Native USB device in TinyUSB CDC mode
|
|
14
14
|
* VID 0x303a = Espressif
|
|
15
|
-
* PID 0x0002 = ESP32-S2 TinyUSB CDC
|
|
16
|
-
* PID 0x1001 = ESP32-S2 ROM Bootloader (before flash)
|
|
17
|
-
*
|
|
18
|
-
* When user connects to ROM bootloader (0x1001), the device will
|
|
19
|
-
* switch to TinyUSB CDC (0x0002) after flashing, requiring port reselection.
|
|
15
|
+
* PID 0x0002 = ESP32-S2 TinyUSB CDC
|
|
20
16
|
*/
|
|
21
17
|
const isESP32S2NativeUSB = (port: SerialPort): boolean => {
|
|
22
18
|
const info = port.getInfo();
|
|
23
|
-
return
|
|
24
|
-
info.usbVendorId === 0x303a &&
|
|
25
|
-
(info.usbProductId === 0x0002 || info.usbProductId === 0x1001)
|
|
26
|
-
);
|
|
19
|
+
return info.usbVendorId === 0x303a && info.usbProductId === 0x0002;
|
|
27
20
|
};
|
|
28
21
|
|
|
29
22
|
export const flash = async (
|
|
@@ -104,7 +97,13 @@ export const flash = async (
|
|
|
104
97
|
logger.error(err);
|
|
105
98
|
|
|
106
99
|
// Check if this is an ESP32-S2 Native USB reconnect situation
|
|
107
|
-
|
|
100
|
+
// This happens when:
|
|
101
|
+
// 1. ESP32-S2 in TinyUSB CDC mode was reset to bootloader
|
|
102
|
+
// 2. ESP32-S2 disconnected during initialization
|
|
103
|
+
if (
|
|
104
|
+
isS2NativeUSB &&
|
|
105
|
+
(esp32s2ReconnectRequired || String(err).includes("reconnect required"))
|
|
106
|
+
) {
|
|
108
107
|
cleanup();
|
|
109
108
|
|
|
110
109
|
// Close the old port if still accessible
|
|
@@ -124,7 +123,7 @@ export const flash = async (
|
|
|
124
123
|
// Fire reconnect event to trigger port reselection dialog
|
|
125
124
|
fireStateEvent({
|
|
126
125
|
state: FlashStateType.ESP32_S2_USB_RECONNECT,
|
|
127
|
-
message: "ESP32-S2
|
|
126
|
+
message: "ESP32-S2 USB port changed - please select the new port",
|
|
128
127
|
details: { oldPort: port },
|
|
129
128
|
});
|
|
130
129
|
return;
|