tasmota-webserial-esptool 9.1.5 → 9.1.6

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.
@@ -83,6 +83,10 @@ export declare class ESPLoader extends EventTarget {
83
83
  chipId: number;
84
84
  apiVersion: number;
85
85
  }>;
86
+ /**
87
+ * Get MAC address from efuses
88
+ */
89
+ getMacAddress(): Promise<string>;
86
90
  /**
87
91
  * @name readLoop
88
92
  * Reads data from the input stream and places it in the inputBuffer
@@ -341,9 +345,14 @@ declare class EspStubLoader extends ESPLoader {
341
345
  */
342
346
  memBegin(size: number, _blocks: number, _blocksize: number, offset: number): Promise<[number, number[]]>;
343
347
  /**
344
- * @name getEraseSize
345
- * depending on flash chip model the erase may take this long (maybe longer!)
348
+ * @name eraseFlash
349
+ * Erase entire flash chip
346
350
  */
347
351
  eraseFlash(): Promise<void>;
352
+ /**
353
+ * @name eraseRegion
354
+ * Erase a specific region of flash
355
+ */
356
+ eraseRegion(offset: number, size: number): Promise<void>;
348
357
  }
349
358
  export {};
@@ -1,5 +1,5 @@
1
1
  /// <reference types="@types/w3c-web-serial" />
2
- import { CHIP_FAMILY_ESP32, CHIP_FAMILY_ESP32S2, CHIP_FAMILY_ESP32S3, CHIP_FAMILY_ESP32C2, CHIP_FAMILY_ESP32C3, CHIP_FAMILY_ESP32C5, CHIP_FAMILY_ESP32C6, CHIP_FAMILY_ESP32C61, CHIP_FAMILY_ESP32H2, CHIP_FAMILY_ESP32H4, CHIP_FAMILY_ESP32H21, CHIP_FAMILY_ESP32P4, CHIP_FAMILY_ESP32S31, CHIP_FAMILY_ESP8266, MAX_TIMEOUT, DEFAULT_TIMEOUT, ERASE_REGION_TIMEOUT_PER_MB, ESP_CHANGE_BAUDRATE, ESP_CHECKSUM_MAGIC, ESP_FLASH_BEGIN, ESP_FLASH_DATA, ESP_FLASH_END, ESP_MEM_BEGIN, ESP_MEM_DATA, ESP_MEM_END, ESP_READ_REG, ESP_WRITE_REG, ESP_SPI_ATTACH, ESP_SYNC, ESP_GET_SECURITY_INFO, FLASH_SECTOR_SIZE, FLASH_WRITE_SIZE, STUB_FLASH_WRITE_SIZE, MEM_END_ROM_TIMEOUT, ROM_INVALID_RECV_MSG, SYNC_PACKET, SYNC_TIMEOUT, USB_RAM_BLOCK, ESP_ERASE_FLASH, ESP_READ_FLASH, CHIP_ERASE_TIMEOUT, FLASH_READ_TIMEOUT, timeoutPerMb, ESP_ROM_BAUD, USB_JTAG_SERIAL_PID, ESP_FLASH_DEFL_BEGIN, ESP_FLASH_DEFL_DATA, ESP_FLASH_DEFL_END, getSpiFlashAddresses, DETECTED_FLASH_SIZES, CHIP_DETECT_MAGIC_REG_ADDR, CHIP_DETECT_MAGIC_VALUES, CHIP_ID_TO_INFO, ESP32P4_EFUSE_BLOCK1_ADDR, SlipReadError, } from "./const";
2
+ import { CHIP_FAMILY_ESP32, CHIP_FAMILY_ESP32S2, CHIP_FAMILY_ESP32S3, CHIP_FAMILY_ESP32C2, CHIP_FAMILY_ESP32C3, CHIP_FAMILY_ESP32C5, CHIP_FAMILY_ESP32C6, CHIP_FAMILY_ESP32C61, CHIP_FAMILY_ESP32H2, CHIP_FAMILY_ESP32H4, CHIP_FAMILY_ESP32H21, CHIP_FAMILY_ESP32P4, CHIP_FAMILY_ESP32S31, CHIP_FAMILY_ESP8266, MAX_TIMEOUT, DEFAULT_TIMEOUT, ERASE_REGION_TIMEOUT_PER_MB, ESP_CHANGE_BAUDRATE, ESP_CHECKSUM_MAGIC, ESP_FLASH_BEGIN, ESP_FLASH_DATA, ESP_FLASH_END, ESP_MEM_BEGIN, ESP_MEM_DATA, ESP_MEM_END, ESP_READ_REG, ESP_WRITE_REG, ESP_SPI_ATTACH, ESP_SYNC, ESP_GET_SECURITY_INFO, FLASH_SECTOR_SIZE, FLASH_WRITE_SIZE, STUB_FLASH_WRITE_SIZE, MEM_END_ROM_TIMEOUT, ROM_INVALID_RECV_MSG, SYNC_PACKET, SYNC_TIMEOUT, USB_RAM_BLOCK, ESP_ERASE_FLASH, ESP_ERASE_REGION, ESP_READ_FLASH, CHIP_ERASE_TIMEOUT, FLASH_READ_TIMEOUT, timeoutPerMb, ESP_ROM_BAUD, USB_JTAG_SERIAL_PID, ESP_FLASH_DEFL_BEGIN, ESP_FLASH_DEFL_DATA, ESP_FLASH_DEFL_END, getSpiFlashAddresses, DETECTED_FLASH_SIZES, CHIP_DETECT_MAGIC_REG_ADDR, CHIP_DETECT_MAGIC_VALUES, CHIP_ID_TO_INFO, ESP32P4_EFUSE_BLOCK1_ADDR, SlipReadError, } from "./const";
3
3
  import { getStubCode } from "./stubs";
4
4
  import { hexFormatter, sleep, slipEncode, toHex } from "./util";
5
5
  import { deflate } from "pako";
@@ -435,6 +435,18 @@ export class ESPLoader extends EventTarget {
435
435
  apiVersion,
436
436
  };
437
437
  }
438
+ /**
439
+ * Get MAC address from efuses
440
+ */
441
+ async getMacAddress() {
442
+ if (!this._initializationSucceeded) {
443
+ throw new Error("getMacAddress() requires initialize() to have completed successfully");
444
+ }
445
+ const macBytes = this.macAddr(); // chip-family-aware
446
+ return macBytes
447
+ .map((b) => b.toString(16).padStart(2, "0").toUpperCase())
448
+ .join(":");
449
+ }
438
450
  /**
439
451
  * @name readLoop
440
452
  * Reads data from the input stream and places it in the inputBuffer
@@ -467,6 +479,12 @@ export class ESPLoader extends EventTarget {
467
479
  catch {
468
480
  this.logger.error("Read loop got disconnected");
469
481
  }
482
+ finally {
483
+ // Always reset reconfiguring flag when read loop ends
484
+ // This prevents "Cannot write during port reconfiguration" errors
485
+ // when the read loop dies unexpectedly
486
+ this._isReconfiguring = false;
487
+ }
470
488
  // Disconnected!
471
489
  this.connected = false;
472
490
  // Check if this is ESP32-S2 Native USB that needs port reselection
@@ -2109,52 +2127,45 @@ export class ESPLoader extends EventTarget {
2109
2127
  this.logger.debug("Port already closed, skipping disconnect");
2110
2128
  return;
2111
2129
  }
2130
+ // Wait for pending writes to complete
2112
2131
  try {
2113
- // Wait for pending writes to complete
2132
+ await this._writeChain;
2133
+ }
2134
+ catch (err) {
2135
+ this.logger.debug(`Pending write error during disconnect: ${err}`);
2136
+ }
2137
+ // Release persistent writer before closing
2138
+ if (this._writer) {
2114
2139
  try {
2115
- await this._writeChain;
2140
+ await this._writer.close();
2141
+ this._writer.releaseLock();
2116
2142
  }
2117
2143
  catch (err) {
2118
- this.logger.debug(`Pending write error during disconnect: ${err}`);
2144
+ this.logger.debug(`Writer close/release error: ${err}`);
2119
2145
  }
2120
- // Block new writes during disconnect
2121
- this._isReconfiguring = true;
2122
- // Release persistent writer before closing
2123
- if (this._writer) {
2124
- try {
2125
- await this._writer.close();
2126
- this._writer.releaseLock();
2127
- }
2128
- catch (err) {
2129
- this.logger.debug(`Writer close/release error: ${err}`);
2130
- }
2131
- this._writer = undefined;
2146
+ this._writer = undefined;
2147
+ }
2148
+ else {
2149
+ // No persistent writer exists, close stream directly
2150
+ // This path is taken when no writes have been queued
2151
+ try {
2152
+ const writer = this.port.writable.getWriter();
2153
+ await writer.close();
2154
+ writer.releaseLock();
2132
2155
  }
2133
- else {
2134
- // No persistent writer exists, close stream directly
2135
- // This path is taken when no writes have been queued
2136
- try {
2137
- const writer = this.port.writable.getWriter();
2138
- await writer.close();
2139
- writer.releaseLock();
2140
- }
2141
- catch (err) {
2142
- this.logger.debug(`Direct writer close error: ${err}`);
2143
- }
2156
+ catch (err) {
2157
+ this.logger.debug(`Direct writer close error: ${err}`);
2144
2158
  }
2145
- await new Promise((resolve) => {
2146
- if (!this._reader) {
2147
- resolve(undefined);
2148
- return;
2149
- }
2150
- this.addEventListener("disconnect", resolve, { once: true });
2151
- this._reader.cancel();
2152
- });
2153
- this.connected = false;
2154
- }
2155
- finally {
2156
- this._isReconfiguring = false;
2157
2159
  }
2160
+ await new Promise((resolve) => {
2161
+ if (!this._reader) {
2162
+ resolve(undefined);
2163
+ return;
2164
+ }
2165
+ this.addEventListener("disconnect", resolve, { once: true });
2166
+ this._reader.cancel();
2167
+ });
2168
+ this.connected = false;
2158
2169
  }
2159
2170
  /**
2160
2171
  * @name reconnectAndResume
@@ -2457,8 +2468,9 @@ export class ESPLoader extends EventTarget {
2457
2468
  newResp.set(resp);
2458
2469
  newResp.set(packetData, resp.length);
2459
2470
  resp = newResp;
2460
- // Send acknowledgment after receiving maxInFlight bytes
2461
- // This unblocks the stub to send the next batch of packets
2471
+ // Send acknowledgment when we've received maxInFlight bytes
2472
+ // The stub sends packets until (num_sent - num_acked) >= max_in_flight
2473
+ // We MUST wait for all packets before sending ACK
2462
2474
  const shouldAck = resp.length >= chunkSize || // End of chunk
2463
2475
  resp.length >= lastAckedLength + maxInFlight; // Received all packets
2464
2476
  if (shouldAck) {
@@ -2634,10 +2646,46 @@ class EspStubLoader extends ESPLoader {
2634
2646
  return [0, []];
2635
2647
  }
2636
2648
  /**
2637
- * @name getEraseSize
2638
- * depending on flash chip model the erase may take this long (maybe longer!)
2649
+ * @name eraseFlash
2650
+ * Erase entire flash chip
2639
2651
  */
2640
2652
  async eraseFlash() {
2641
2653
  await this.checkCommand(ESP_ERASE_FLASH, [], 0, CHIP_ERASE_TIMEOUT);
2642
2654
  }
2655
+ /**
2656
+ * @name eraseRegion
2657
+ * Erase a specific region of flash
2658
+ */
2659
+ async eraseRegion(offset, size) {
2660
+ // Validate inputs
2661
+ if (offset < 0) {
2662
+ throw new Error(`Invalid offset: ${offset} (must be non-negative)`);
2663
+ }
2664
+ if (size < 0) {
2665
+ throw new Error(`Invalid size: ${size} (must be non-negative)`);
2666
+ }
2667
+ // No-op for zero size
2668
+ if (size === 0) {
2669
+ this.logger.log("eraseRegion: size is 0, skipping erase");
2670
+ return;
2671
+ }
2672
+ // Check for sector alignment
2673
+ if (offset % FLASH_SECTOR_SIZE !== 0) {
2674
+ throw new Error(`Offset ${offset} (0x${offset.toString(16)}) is not aligned to flash sector size ${FLASH_SECTOR_SIZE} (0x${FLASH_SECTOR_SIZE.toString(16)})`);
2675
+ }
2676
+ if (size % FLASH_SECTOR_SIZE !== 0) {
2677
+ throw new Error(`Size ${size} (0x${size.toString(16)}) is not aligned to flash sector size ${FLASH_SECTOR_SIZE} (0x${FLASH_SECTOR_SIZE.toString(16)})`);
2678
+ }
2679
+ // Check for reasonable bounds (prevent wrapping in pack)
2680
+ const maxValue = 0xffffffff; // 32-bit unsigned max
2681
+ if (offset > maxValue) {
2682
+ throw new Error(`Offset ${offset} exceeds maximum value ${maxValue}`);
2683
+ }
2684
+ if (size > maxValue) {
2685
+ throw new Error(`Size ${size} exceeds maximum value ${maxValue}`);
2686
+ }
2687
+ const timeout = timeoutPerMb(ERASE_REGION_TIMEOUT_PER_MB, size);
2688
+ const buffer = pack("<II", offset, size);
2689
+ await this.checkCommand(ESP_ERASE_REGION, buffer, 0, timeout);
2690
+ }
2643
2691
  }
package/dist/web/index.js CHANGED
@@ -1 +1 @@
1
- const t=t=>{let e=[192];for(const i of t)219==i?e=e.concat([219,221]):192==i?e=e.concat([219,220]):e.push(i);return e.push(192),e},e=t=>{const e=[];for(let i=0;i<t.length;i++){const a=t.charCodeAt(i);a<=255&&e.push(a)}return e},i=t=>"["+t.map(t=>a(t)).join(", ")+"]",a=(t,e=2)=>{const i=t.toString(16).toUpperCase();return i.startsWith("-")?"-0x"+i.substring(1).padStart(e,"0"):"0x"+i.padStart(e,"0")},s=t=>new Promise(e=>setTimeout(e,t)),r={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"},n=115200,h=1343410176,o=e(" UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU"),l=33382,u=50,d=12882,c=12883,_=12994,f=12995,g=12997,p=12998,w=207969,m=12914,b=12916,y=12917,S=12928,B=12849,v={5:{name:"ESP32-C3",family:f},9:{name:"ESP32-S3",family:c},12:{name:"ESP32-C2",family:_},13:{name:"ESP32-C6",family:p},16:{name:"ESP32-H2",family:m},18:{name:"ESP32-P4",family:S},20:{name:"ESP32-C61",family:w},23:{name:"ESP32-C5",family:g},25:{name:"ESP32-H21",family:y},28:{name:"ESP32-H4",family:b},32:{name:"ESP32-S31",family:B}},R={4293968129:{name:"ESP8266",family:l},15736195:{name:"ESP32",family:u},1990:{name:"ESP32-S2",family:d}},U=3e3,I=15e4,T=100,D=(t,e)=>{const i=Math.floor(t*(e/486));return i<U?U:i},x=t=>{switch(t){case u:return{regBase:1072963584,baseFuse:1073061888,macFuse:1073061888,usrOffs:28,usr1Offs:32,usr2Offs:36,mosiDlenOffs:40,misoDlenOffs:44,w0Offs:128,uartDateReg:1610612856,flashOffs:4096};case d:return{regBase:1061167104,baseFuse:1061265408,macFuse:1061265476,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612856,flashOffs:4096};case c:return{regBase:1610620928,usrOffs:24,baseFuse:1610641408,macFuse:1610641476,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612864,flashOffs:0};case l:return{regBase:1610613248,usrOffs:28,baseFuse:1072693328,macFuse:1072693328,usr1Offs:32,usr2Offs:36,mosiDlenOffs:-1,misoDlenOffs:-1,w0Offs:64,uartDateReg:1610612856,flashOffs:0};case _:case f:return{regBase:1610620928,baseFuse:1610647552,macFuse:1610647620,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case g:return{regBase:1610625024,baseFuse:1611352064,macFuse:1611352132,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:8192};case p:return{regBase:1610625024,baseFuse:1611335680,macFuse:1611335748,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case w:return{regBase:1610625024,baseFuse:1611352064,macFuse:1611352132,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case m:return{regBase:1610625024,baseFuse:1611335680,macFuse:1611335748,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case b:return{regBase:1611239424,baseFuse:1611339776,macFuse:1611339844,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610686588,flashOffs:8192};case y:return{regBase:1610625024,baseFuse:1611350016,macFuse:1611350084,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case S:return{regBase:1342754816,baseFuse:h,macFuse:1343410244,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1343004812,flashOffs:8192};case B: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 k extends Error{constructor(t){super(t),this.name="SlipReadError"}}const C=async(t,i)=>{let a;if(t==b||t==y||t==B)return null;if(t==u)a=await import("./esp32-BRKoi17y.js");else if(t==d)a=await import("./esp32s2-iX3WoDbg.js");else if(t==c)a=await import("./esp32s3-DGwDVIgz.js");else if(t==l)a=await import("./esp8266-CUwxJpGa.js");else if(t==_)a=await import("./esp32c2-Btgr_lwh.js");else if(t==f)a=await import("./esp32c3-CHKfoI8W.js");else if(t==g)a=await import("./esp32c5-BDW4KtLo.js");else if(t==p)a=await import("./esp32c6-il8tTxAG.js");else if(t==w)a=await import("./esp32c61-thKzxBGf.js");else if(t==m)a=await import("./esp32h2-CxoUHv_P.js");else{if(t!=S)return null;a=null!=i&&i>=300?await import("./esp32p4r3-CqI71ojR.js"):await import("./esp32p4-D3jLP-jY.js")}return{...a,text:e(atob(a.text)),data:e(atob(a.data))}};function F(t){let e=t.length;for(;--e>=0;)t[e]=0}const W=256,O=286,z=30,A=15,E=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]),M=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]),P=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),$=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),L=new Array(576);F(L);const N=new Array(60);F(N);const Z=new Array(512);F(Z);const V=new Array(256);F(V);const H=new Array(29);F(H);const G=new Array(z);function j(t,e,i,a,s){this.static_tree=t,this.extra_bits=e,this.extra_base=i,this.elems=a,this.max_length=s,this.has_stree=t&&t.length}let J,q,K;function Y(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}F(G);const X=t=>t<256?Z[t]:Z[256+(t>>>7)],Q=(t,e)=>{t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255},tt=(t,e,i)=>{t.bi_valid>16-i?(t.bi_buf|=e<<t.bi_valid&65535,Q(t,t.bi_buf),t.bi_buf=e>>16-t.bi_valid,t.bi_valid+=i-16):(t.bi_buf|=e<<t.bi_valid&65535,t.bi_valid+=i)},et=(t,e,i)=>{tt(t,i[2*e],i[2*e+1])},it=(t,e)=>{let i=0;do{i|=1&t,t>>>=1,i<<=1}while(--e>0);return i>>>1},at=(t,e,i)=>{const a=new Array(16);let s,r,n=0;for(s=1;s<=A;s++)n=n+i[s-1]<<1,a[s]=n;for(r=0;r<=e;r++){let e=t[2*r+1];0!==e&&(t[2*r]=it(a[e]++,e))}},st=t=>{let e;for(e=0;e<O;e++)t.dyn_ltree[2*e]=0;for(e=0;e<z;e++)t.dyn_dtree[2*e]=0;for(e=0;e<19;e++)t.bl_tree[2*e]=0;t.dyn_ltree[512]=1,t.opt_len=t.static_len=0,t.sym_next=t.matches=0},rt=t=>{t.bi_valid>8?Q(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0},nt=(t,e,i,a)=>{const s=2*e,r=2*i;return t[s]<t[r]||t[s]===t[r]&&a[e]<=a[i]},ht=(t,e,i)=>{const a=t.heap[i];let s=i<<1;for(;s<=t.heap_len&&(s<t.heap_len&&nt(e,t.heap[s+1],t.heap[s],t.depth)&&s++,!nt(e,a,t.heap[s],t.depth));)t.heap[i]=t.heap[s],i=s,s<<=1;t.heap[i]=a},ot=(t,e,i)=>{let a,s,r,n,h=0;if(0!==t.sym_next)do{a=255&t.pending_buf[t.sym_buf+h++],a+=(255&t.pending_buf[t.sym_buf+h++])<<8,s=t.pending_buf[t.sym_buf+h++],0===a?et(t,s,e):(r=V[s],et(t,r+W+1,e),n=E[r],0!==n&&(s-=H[r],tt(t,s,n)),a--,r=X(a),et(t,r,i),n=M[r],0!==n&&(a-=G[r],tt(t,a,n)))}while(h<t.sym_next);et(t,256,e)},lt=(t,e)=>{const i=e.dyn_tree,a=e.stat_desc.static_tree,s=e.stat_desc.has_stree,r=e.stat_desc.elems;let n,h,o,l=-1;for(t.heap_len=0,t.heap_max=573,n=0;n<r;n++)0!==i[2*n]?(t.heap[++t.heap_len]=l=n,t.depth[n]=0):i[2*n+1]=0;for(;t.heap_len<2;)o=t.heap[++t.heap_len]=l<2?++l:0,i[2*o]=1,t.depth[o]=0,t.opt_len--,s&&(t.static_len-=a[2*o+1]);for(e.max_code=l,n=t.heap_len>>1;n>=1;n--)ht(t,i,n);o=r;do{n=t.heap[1],t.heap[1]=t.heap[t.heap_len--],ht(t,i,1),h=t.heap[1],t.heap[--t.heap_max]=n,t.heap[--t.heap_max]=h,i[2*o]=i[2*n]+i[2*h],t.depth[o]=(t.depth[n]>=t.depth[h]?t.depth[n]:t.depth[h])+1,i[2*n+1]=i[2*h+1]=o,t.heap[1]=o++,ht(t,i,1)}while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],((t,e)=>{const i=e.dyn_tree,a=e.max_code,s=e.stat_desc.static_tree,r=e.stat_desc.has_stree,n=e.stat_desc.extra_bits,h=e.stat_desc.extra_base,o=e.stat_desc.max_length;let l,u,d,c,_,f,g=0;for(c=0;c<=A;c++)t.bl_count[c]=0;for(i[2*t.heap[t.heap_max]+1]=0,l=t.heap_max+1;l<573;l++)u=t.heap[l],c=i[2*i[2*u+1]+1]+1,c>o&&(c=o,g++),i[2*u+1]=c,u>a||(t.bl_count[c]++,_=0,u>=h&&(_=n[u-h]),f=i[2*u],t.opt_len+=f*(c+_),r&&(t.static_len+=f*(s[2*u+1]+_)));if(0!==g){do{for(c=o-1;0===t.bl_count[c];)c--;t.bl_count[c]--,t.bl_count[c+1]+=2,t.bl_count[o]--,g-=2}while(g>0);for(c=o;0!==c;c--)for(u=t.bl_count[c];0!==u;)d=t.heap[--l],d>a||(i[2*d+1]!==c&&(t.opt_len+=(c-i[2*d+1])*i[2*d],i[2*d+1]=c),u--)}})(t,e),at(i,l,t.bl_count)},ut=(t,e,i)=>{let a,s,r=-1,n=e[1],h=0,o=7,l=4;for(0===n&&(o=138,l=3),e[2*(i+1)+1]=65535,a=0;a<=i;a++)s=n,n=e[2*(a+1)+1],++h<o&&s===n||(h<l?t.bl_tree[2*s]+=h:0!==s?(s!==r&&t.bl_tree[2*s]++,t.bl_tree[32]++):h<=10?t.bl_tree[34]++:t.bl_tree[36]++,h=0,r=s,0===n?(o=138,l=3):s===n?(o=6,l=3):(o=7,l=4))},dt=(t,e,i)=>{let a,s,r=-1,n=e[1],h=0,o=7,l=4;for(0===n&&(o=138,l=3),a=0;a<=i;a++)if(s=n,n=e[2*(a+1)+1],!(++h<o&&s===n)){if(h<l)do{et(t,s,t.bl_tree)}while(0!==--h);else 0!==s?(s!==r&&(et(t,s,t.bl_tree),h--),et(t,16,t.bl_tree),tt(t,h-3,2)):h<=10?(et(t,17,t.bl_tree),tt(t,h-3,3)):(et(t,18,t.bl_tree),tt(t,h-11,7));h=0,r=s,0===n?(o=138,l=3):s===n?(o=6,l=3):(o=7,l=4)}};let ct=!1;const _t=(t,e,i,a)=>{tt(t,0+(a?1:0),3),rt(t),Q(t,i),Q(t,~i),i&&t.pending_buf.set(t.window.subarray(e,e+i),t.pending),t.pending+=i};var ft=(t,e,i,a)=>{let s,r,n=0;t.level>0?(2===t.strm.data_type&&(t.strm.data_type=(t=>{let e,i=4093624447;for(e=0;e<=31;e++,i>>>=1)if(1&i&&0!==t.dyn_ltree[2*e])return 0;if(0!==t.dyn_ltree[18]||0!==t.dyn_ltree[20]||0!==t.dyn_ltree[26])return 1;for(e=32;e<W;e++)if(0!==t.dyn_ltree[2*e])return 1;return 0})(t)),lt(t,t.l_desc),lt(t,t.d_desc),n=(t=>{let e;for(ut(t,t.dyn_ltree,t.l_desc.max_code),ut(t,t.dyn_dtree,t.d_desc.max_code),lt(t,t.bl_desc),e=18;e>=3&&0===t.bl_tree[2*$[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e})(t),s=t.opt_len+3+7>>>3,r=t.static_len+3+7>>>3,r<=s&&(s=r)):s=r=i+5,i+4<=s&&-1!==e?_t(t,e,i,a):4===t.strategy||r===s?(tt(t,2+(a?1:0),3),ot(t,L,N)):(tt(t,4+(a?1:0),3),((t,e,i,a)=>{let s;for(tt(t,e-257,5),tt(t,i-1,5),tt(t,a-4,4),s=0;s<a;s++)tt(t,t.bl_tree[2*$[s]+1],3);dt(t,t.dyn_ltree,e-1),dt(t,t.dyn_dtree,i-1)})(t,t.l_desc.max_code+1,t.d_desc.max_code+1,n+1),ot(t,t.dyn_ltree,t.dyn_dtree)),st(t),a&&rt(t)},gt={_tr_init:t=>{ct||((()=>{let t,e,i,a,s;const r=new Array(16);for(i=0,a=0;a<28;a++)for(H[a]=i,t=0;t<1<<E[a];t++)V[i++]=a;for(V[i-1]=a,s=0,a=0;a<16;a++)for(G[a]=s,t=0;t<1<<M[a];t++)Z[s++]=a;for(s>>=7;a<z;a++)for(G[a]=s<<7,t=0;t<1<<M[a]-7;t++)Z[256+s++]=a;for(e=0;e<=A;e++)r[e]=0;for(t=0;t<=143;)L[2*t+1]=8,t++,r[8]++;for(;t<=255;)L[2*t+1]=9,t++,r[9]++;for(;t<=279;)L[2*t+1]=7,t++,r[7]++;for(;t<=287;)L[2*t+1]=8,t++,r[8]++;for(at(L,287,r),t=0;t<z;t++)N[2*t+1]=5,N[2*t]=it(t,5);J=new j(L,E,257,O,A),q=new j(N,M,0,z,A),K=new j(new Array(0),P,0,19,7)})(),ct=!0),t.l_desc=new Y(t.dyn_ltree,J),t.d_desc=new Y(t.dyn_dtree,q),t.bl_desc=new Y(t.bl_tree,K),t.bi_buf=0,t.bi_valid=0,st(t)},_tr_stored_block:_t,_tr_flush_block:ft,_tr_tally:(t,e,i)=>(t.pending_buf[t.sym_buf+t.sym_next++]=e,t.pending_buf[t.sym_buf+t.sym_next++]=e>>8,t.pending_buf[t.sym_buf+t.sym_next++]=i,0===e?t.dyn_ltree[2*i]++:(t.matches++,e--,t.dyn_ltree[2*(V[i]+W+1)]++,t.dyn_dtree[2*X(e)]++),t.sym_next===t.sym_end),_tr_align:t=>{tt(t,2,3),et(t,256,L),(t=>{16===t.bi_valid?(Q(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)})(t)}};var pt=(t,e,i,a)=>{let s=65535&t,r=t>>>16&65535,n=0;for(;0!==i;){n=i>2e3?2e3:i,i-=n;do{s=s+e[a++]|0,r=r+s|0}while(--n);s%=65521,r%=65521}return s|r<<16};const wt=new Uint32Array((()=>{let t,e=[];for(var i=0;i<256;i++){t=i;for(var a=0;a<8;a++)t=1&t?3988292384^t>>>1:t>>>1;e[i]=t}return e})());var mt=(t,e,i,a)=>{const s=wt,r=a+i;t^=-1;for(let i=a;i<r;i++)t=t>>>8^s[255&(t^e[i])];return-1^t},bt={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"},yt={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:St,_tr_stored_block:Bt,_tr_flush_block:vt,_tr_tally:Rt,_tr_align:Ut}=gt,{Z_NO_FLUSH:It,Z_PARTIAL_FLUSH:Tt,Z_FULL_FLUSH:Dt,Z_FINISH:xt,Z_BLOCK:kt,Z_OK:Ct,Z_STREAM_END:Ft,Z_STREAM_ERROR:Wt,Z_DATA_ERROR:Ot,Z_BUF_ERROR:zt,Z_DEFAULT_COMPRESSION:At,Z_FILTERED:Et,Z_HUFFMAN_ONLY:Mt,Z_RLE:Pt,Z_FIXED:$t,Z_DEFAULT_STRATEGY:Lt,Z_UNKNOWN:Nt,Z_DEFLATED:Zt}=yt,Vt=258,Ht=262,Gt=42,jt=113,Jt=666,qt=(t,e)=>(t.msg=bt[e],e),Kt=t=>2*t-(t>4?9:0),Yt=t=>{let e=t.length;for(;--e>=0;)t[e]=0},Xt=t=>{let e,i,a,s=t.w_size;e=t.hash_size,a=e;do{i=t.head[--a],t.head[a]=i>=s?i-s:0}while(--e);e=s,a=e;do{i=t.prev[--a],t.prev[a]=i>=s?i-s:0}while(--e)};let Qt=(t,e,i)=>(e<<t.hash_shift^i)&t.hash_mask;const te=t=>{const e=t.state;let i=e.pending;i>t.avail_out&&(i=t.avail_out),0!==i&&(t.output.set(e.pending_buf.subarray(e.pending_out,e.pending_out+i),t.next_out),t.next_out+=i,e.pending_out+=i,t.total_out+=i,t.avail_out-=i,e.pending-=i,0===e.pending&&(e.pending_out=0))},ee=(t,e)=>{vt(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,te(t.strm)},ie=(t,e)=>{t.pending_buf[t.pending++]=e},ae=(t,e)=>{t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e},se=(t,e,i,a)=>{let s=t.avail_in;return s>a&&(s=a),0===s?0:(t.avail_in-=s,e.set(t.input.subarray(t.next_in,t.next_in+s),i),1===t.state.wrap?t.adler=pt(t.adler,e,s,i):2===t.state.wrap&&(t.adler=mt(t.adler,e,s,i)),t.next_in+=s,t.total_in+=s,s)},re=(t,e)=>{let i,a,s=t.max_chain_length,r=t.strstart,n=t.prev_length,h=t.nice_match;const o=t.strstart>t.w_size-Ht?t.strstart-(t.w_size-Ht):0,l=t.window,u=t.w_mask,d=t.prev,c=t.strstart+Vt;let _=l[r+n-1],f=l[r+n];t.prev_length>=t.good_match&&(s>>=2),h>t.lookahead&&(h=t.lookahead);do{if(i=e,l[i+n]===f&&l[i+n-1]===_&&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<c);if(a=Vt-(c-r),r=c-Vt,a>n){if(t.match_start=e,n=a,a>=h)break;_=l[r+n-1],f=l[r+n]}}}while((e=d[e&u])>o&&0!==--s);return n<=t.lookahead?n:t.lookahead},ne=t=>{const e=t.w_size;let i,a,s;do{if(a=t.window_size-t.lookahead-t.strstart,t.strstart>=e+(e-Ht)&&(t.window.set(t.window.subarray(e,e+e-a),0),t.match_start-=e,t.strstart-=e,t.block_start-=e,t.insert>t.strstart&&(t.insert=t.strstart),Xt(t),a+=e),0===t.strm.avail_in)break;if(i=se(t.strm,t.window,t.strstart+t.lookahead,a),t.lookahead+=i,t.lookahead+t.insert>=3)for(s=t.strstart-t.insert,t.ins_h=t.window[s],t.ins_h=Qt(t,t.ins_h,t.window[s+1]);t.insert&&(t.ins_h=Qt(t,t.ins_h,t.window[s+3-1]),t.prev[s&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=s,s++,t.insert--,!(t.lookahead+t.insert<3)););}while(t.lookahead<Ht&&0!==t.strm.avail_in)},he=(t,e)=>{let i,a,s,r=t.pending_buf_size-5>t.w_size?t.w_size:t.pending_buf_size-5,n=0,h=t.strm.avail_in;do{if(i=65535,s=t.bi_valid+42>>3,t.strm.avail_out<s)break;if(s=t.strm.avail_out-s,a=t.strstart-t.block_start,i>a+t.strm.avail_in&&(i=a+t.strm.avail_in),i>s&&(i=s),i<r&&(0===i&&e!==xt||e===It||i!==a+t.strm.avail_in))break;n=e===xt&&i===a+t.strm.avail_in?1:0,Bt(t,0,0,n),t.pending_buf[t.pending-4]=i,t.pending_buf[t.pending-3]=i>>8,t.pending_buf[t.pending-2]=~i,t.pending_buf[t.pending-1]=~i>>8,te(t.strm),a&&(a>i&&(a=i),t.strm.output.set(t.window.subarray(t.block_start,t.block_start+a),t.strm.next_out),t.strm.next_out+=a,t.strm.avail_out-=a,t.strm.total_out+=a,t.block_start+=a,i-=a),i&&(se(t.strm,t.strm.output,t.strm.next_out,i),t.strm.next_out+=i,t.strm.avail_out-=i,t.strm.total_out+=i)}while(0===n);return h-=t.strm.avail_in,h&&(h>=t.w_size?(t.matches=2,t.window.set(t.strm.input.subarray(t.strm.next_in-t.w_size,t.strm.next_in),0),t.strstart=t.w_size,t.insert=t.strstart):(t.window_size-t.strstart<=h&&(t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,t.insert>t.strstart&&(t.insert=t.strstart)),t.window.set(t.strm.input.subarray(t.strm.next_in-h,t.strm.next_in),t.strstart),t.strstart+=h,t.insert+=h>t.w_size-t.insert?t.w_size-t.insert:h),t.block_start=t.strstart),t.high_water<t.strstart&&(t.high_water=t.strstart),n?4:e!==It&&e!==xt&&0===t.strm.avail_in&&t.strstart===t.block_start?2:(s=t.window_size-t.strstart,t.strm.avail_in>s&&t.block_start>=t.w_size&&(t.block_start-=t.w_size,t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,s+=t.w_size,t.insert>t.strstart&&(t.insert=t.strstart)),s>t.strm.avail_in&&(s=t.strm.avail_in),s&&(se(t.strm,t.window,t.strstart,s),t.strstart+=s,t.insert+=s>t.w_size-t.insert?t.w_size-t.insert:s),t.high_water<t.strstart&&(t.high_water=t.strstart),s=t.bi_valid+42>>3,s=t.pending_buf_size-s>65535?65535:t.pending_buf_size-s,r=s>t.w_size?t.w_size:s,a=t.strstart-t.block_start,(a>=r||(a||e===xt)&&e!==It&&0===t.strm.avail_in&&a<=s)&&(i=a>s?s:a,n=e===xt&&0===t.strm.avail_in&&i===a?1:0,Bt(t,t.block_start,i,n),t.block_start+=i,te(t.strm)),n?3:1)},oe=(t,e)=>{let i,a;for(;;){if(t.lookahead<Ht){if(ne(t),t.lookahead<Ht&&e===It)return 1;if(0===t.lookahead)break}if(i=0,t.lookahead>=3&&(t.ins_h=Qt(t,t.ins_h,t.window[t.strstart+3-1]),i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),0!==i&&t.strstart-i<=t.w_size-Ht&&(t.match_length=re(t,i)),t.match_length>=3)if(a=Rt(t,t.strstart-t.match_start,t.match_length-3),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=3){t.match_length--;do{t.strstart++,t.ins_h=Qt(t,t.ins_h,t.window[t.strstart+3-1]),i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart}while(0!==--t.match_length);t.strstart++}else t.strstart+=t.match_length,t.match_length=0,t.ins_h=t.window[t.strstart],t.ins_h=Qt(t,t.ins_h,t.window[t.strstart+1]);else a=Rt(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(a&&(ee(t,!1),0===t.strm.avail_out))return 1}return t.insert=t.strstart<2?t.strstart:2,e===xt?(ee(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ee(t,!1),0===t.strm.avail_out)?1:2},le=(t,e)=>{let i,a,s;for(;;){if(t.lookahead<Ht){if(ne(t),t.lookahead<Ht&&e===It)return 1;if(0===t.lookahead)break}if(i=0,t.lookahead>=3&&(t.ins_h=Qt(t,t.ins_h,t.window[t.strstart+3-1]),i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),t.prev_length=t.match_length,t.prev_match=t.match_start,t.match_length=2,0!==i&&t.prev_length<t.max_lazy_match&&t.strstart-i<=t.w_size-Ht&&(t.match_length=re(t,i),t.match_length<=5&&(t.strategy===Et||3===t.match_length&&t.strstart-t.match_start>4096)&&(t.match_length=2)),t.prev_length>=3&&t.match_length<=t.prev_length){s=t.strstart+t.lookahead-3,a=Rt(t,t.strstart-1-t.prev_match,t.prev_length-3),t.lookahead-=t.prev_length-1,t.prev_length-=2;do{++t.strstart<=s&&(t.ins_h=Qt(t,t.ins_h,t.window[t.strstart+3-1]),i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart)}while(0!==--t.prev_length);if(t.match_available=0,t.match_length=2,t.strstart++,a&&(ee(t,!1),0===t.strm.avail_out))return 1}else if(t.match_available){if(a=Rt(t,0,t.window[t.strstart-1]),a&&ee(t,!1),t.strstart++,t.lookahead--,0===t.strm.avail_out)return 1}else t.match_available=1,t.strstart++,t.lookahead--}return t.match_available&&(a=Rt(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<2?t.strstart:2,e===xt?(ee(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ee(t,!1),0===t.strm.avail_out)?1:2};function ue(t,e,i,a,s){this.good_length=t,this.max_lazy=e,this.nice_length=i,this.max_chain=a,this.func=s}const de=[new ue(0,0,0,0,he),new ue(4,4,8,4,oe),new ue(4,5,16,8,oe),new ue(4,6,32,32,oe),new ue(4,4,16,16,le),new ue(8,16,32,32,le),new ue(8,16,128,128,le),new ue(8,32,128,256,le),new ue(32,128,258,1024,le),new ue(32,258,258,4096,le)];function ce(){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=Zt,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),Yt(this.dyn_ltree),Yt(this.dyn_dtree),Yt(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),Yt(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),Yt(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 _e=t=>{if(!t)return 1;const e=t.state;return!e||e.strm!==t||e.status!==Gt&&57!==e.status&&69!==e.status&&73!==e.status&&91!==e.status&&103!==e.status&&e.status!==jt&&e.status!==Jt?1:0},fe=t=>{if(_e(t))return qt(t,Wt);t.total_in=t.total_out=0,t.data_type=Nt;const e=t.state;return e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=2===e.wrap?57:e.wrap?Gt:jt,t.adler=2===e.wrap?0:1,e.last_flush=-2,St(e),Ct},ge=t=>{const e=fe(t);var i;return e===Ct&&((i=t.state).window_size=2*i.w_size,Yt(i.head),i.max_lazy_match=de[i.level].max_lazy,i.good_match=de[i.level].good_length,i.nice_match=de[i.level].nice_length,i.max_chain_length=de[i.level].max_chain,i.strstart=0,i.block_start=0,i.lookahead=0,i.insert=0,i.match_length=i.prev_length=2,i.match_available=0,i.ins_h=0),e},pe=(t,e,i,a,s,r)=>{if(!t)return Wt;let n=1;if(e===At&&(e=6),a<0?(n=0,a=-a):a>15&&(n=2,a-=16),s<1||s>9||i!==Zt||a<8||a>15||e<0||e>9||r<0||r>$t||8===a&&1!==n)return qt(t,Wt);8===a&&(a=9);const h=new ce;return t.state=h,h.strm=t,h.status=Gt,h.wrap=n,h.gzhead=null,h.w_bits=a,h.w_size=1<<h.w_bits,h.w_mask=h.w_size-1,h.hash_bits=s+7,h.hash_size=1<<h.hash_bits,h.hash_mask=h.hash_size-1,h.hash_shift=~~((h.hash_bits+3-1)/3),h.window=new Uint8Array(2*h.w_size),h.head=new Uint16Array(h.hash_size),h.prev=new Uint16Array(h.w_size),h.lit_bufsize=1<<s+6,h.pending_buf_size=4*h.lit_bufsize,h.pending_buf=new Uint8Array(h.pending_buf_size),h.sym_buf=h.lit_bufsize,h.sym_end=3*(h.lit_bufsize-1),h.level=e,h.strategy=r,h.method=i,ge(t)};var we={deflateInit:(t,e)=>pe(t,e,Zt,15,8,Lt),deflateInit2:pe,deflateReset:ge,deflateResetKeep:fe,deflateSetHeader:(t,e)=>_e(t)||2!==t.state.wrap?Wt:(t.state.gzhead=e,Ct),deflate:(t,e)=>{if(_e(t)||e>kt||e<0)return t?qt(t,Wt):Wt;const i=t.state;if(!t.output||0!==t.avail_in&&!t.input||i.status===Jt&&e!==xt)return qt(t,0===t.avail_out?zt:Wt);const a=i.last_flush;if(i.last_flush=e,0!==i.pending){if(te(t),0===t.avail_out)return i.last_flush=-1,Ct}else if(0===t.avail_in&&Kt(e)<=Kt(a)&&e!==xt)return qt(t,zt);if(i.status===Jt&&0!==t.avail_in)return qt(t,zt);if(i.status===Gt&&0===i.wrap&&(i.status=jt),i.status===Gt){let e=Zt+(i.w_bits-8<<4)<<8,a=-1;if(a=i.strategy>=Mt||i.level<2?0:i.level<6?1:6===i.level?2:3,e|=a<<6,0!==i.strstart&&(e|=32),e+=31-e%31,ae(i,e),0!==i.strstart&&(ae(i,t.adler>>>16),ae(i,65535&t.adler)),t.adler=1,i.status=jt,te(t),0!==i.pending)return i.last_flush=-1,Ct}if(57===i.status)if(t.adler=0,ie(i,31),ie(i,139),ie(i,8),i.gzhead)ie(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)),ie(i,255&i.gzhead.time),ie(i,i.gzhead.time>>8&255),ie(i,i.gzhead.time>>16&255),ie(i,i.gzhead.time>>24&255),ie(i,9===i.level?2:i.strategy>=Mt||i.level<2?4:0),ie(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(ie(i,255&i.gzhead.extra.length),ie(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(t.adler=mt(t.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=69;else if(ie(i,0),ie(i,0),ie(i,0),ie(i,0),ie(i,0),ie(i,9===i.level?2:i.strategy>=Mt||i.level<2?4:0),ie(i,3),i.status=jt,te(t),0!==i.pending)return i.last_flush=-1,Ct;if(69===i.status){if(i.gzhead.extra){let e=i.pending,a=(65535&i.gzhead.extra.length)-i.gzindex;for(;i.pending+a>i.pending_buf_size;){let s=i.pending_buf_size-i.pending;if(i.pending_buf.set(i.gzhead.extra.subarray(i.gzindex,i.gzindex+s),i.pending),i.pending=i.pending_buf_size,i.gzhead.hcrc&&i.pending>e&&(t.adler=mt(t.adler,i.pending_buf,i.pending-e,e)),i.gzindex+=s,te(t),0!==i.pending)return i.last_flush=-1,Ct;e=0,a-=s}let s=new Uint8Array(i.gzhead.extra);i.pending_buf.set(s.subarray(i.gzindex,i.gzindex+a),i.pending),i.pending+=a,i.gzhead.hcrc&&i.pending>e&&(t.adler=mt(t.adler,i.pending_buf,i.pending-e,e)),i.gzindex=0}i.status=73}if(73===i.status){if(i.gzhead.name){let e,a=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>a&&(t.adler=mt(t.adler,i.pending_buf,i.pending-a,a)),te(t),0!==i.pending)return i.last_flush=-1,Ct;a=0}e=i.gzindex<i.gzhead.name.length?255&i.gzhead.name.charCodeAt(i.gzindex++):0,ie(i,e)}while(0!==e);i.gzhead.hcrc&&i.pending>a&&(t.adler=mt(t.adler,i.pending_buf,i.pending-a,a)),i.gzindex=0}i.status=91}if(91===i.status){if(i.gzhead.comment){let e,a=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>a&&(t.adler=mt(t.adler,i.pending_buf,i.pending-a,a)),te(t),0!==i.pending)return i.last_flush=-1,Ct;a=0}e=i.gzindex<i.gzhead.comment.length?255&i.gzhead.comment.charCodeAt(i.gzindex++):0,ie(i,e)}while(0!==e);i.gzhead.hcrc&&i.pending>a&&(t.adler=mt(t.adler,i.pending_buf,i.pending-a,a))}i.status=103}if(103===i.status){if(i.gzhead.hcrc){if(i.pending+2>i.pending_buf_size&&(te(t),0!==i.pending))return i.last_flush=-1,Ct;ie(i,255&t.adler),ie(i,t.adler>>8&255),t.adler=0}if(i.status=jt,te(t),0!==i.pending)return i.last_flush=-1,Ct}if(0!==t.avail_in||0!==i.lookahead||e!==It&&i.status!==Jt){let a=0===i.level?he(i,e):i.strategy===Mt?((t,e)=>{let i;for(;;){if(0===t.lookahead&&(ne(t),0===t.lookahead)){if(e===It)return 1;break}if(t.match_length=0,i=Rt(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,i&&(ee(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===xt?(ee(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ee(t,!1),0===t.strm.avail_out)?1:2})(i,e):i.strategy===Pt?((t,e)=>{let i,a,s,r;const n=t.window;for(;;){if(t.lookahead<=Vt){if(ne(t),t.lookahead<=Vt&&e===It)return 1;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=3&&t.strstart>0&&(s=t.strstart-1,a=n[s],a===n[++s]&&a===n[++s]&&a===n[++s])){r=t.strstart+Vt;do{}while(a===n[++s]&&a===n[++s]&&a===n[++s]&&a===n[++s]&&a===n[++s]&&a===n[++s]&&a===n[++s]&&a===n[++s]&&s<r);t.match_length=Vt-(r-s),t.match_length>t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=3?(i=Rt(t,1,t.match_length-3),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(i=Rt(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),i&&(ee(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===xt?(ee(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ee(t,!1),0===t.strm.avail_out)?1:2})(i,e):de[i.level].func(i,e);if(3!==a&&4!==a||(i.status=Jt),1===a||3===a)return 0===t.avail_out&&(i.last_flush=-1),Ct;if(2===a&&(e===Tt?Ut(i):e!==kt&&(Bt(i,0,0,!1),e===Dt&&(Yt(i.head),0===i.lookahead&&(i.strstart=0,i.block_start=0,i.insert=0))),te(t),0===t.avail_out))return i.last_flush=-1,Ct}return e!==xt?Ct:i.wrap<=0?Ft:(2===i.wrap?(ie(i,255&t.adler),ie(i,t.adler>>8&255),ie(i,t.adler>>16&255),ie(i,t.adler>>24&255),ie(i,255&t.total_in),ie(i,t.total_in>>8&255),ie(i,t.total_in>>16&255),ie(i,t.total_in>>24&255)):(ae(i,t.adler>>>16),ae(i,65535&t.adler)),te(t),i.wrap>0&&(i.wrap=-i.wrap),0!==i.pending?Ct:Ft)},deflateEnd:t=>{if(_e(t))return Wt;const e=t.state.status;return t.state=null,e===jt?qt(t,Ot):Ct},deflateSetDictionary:(t,e)=>{let i=e.length;if(_e(t))return Wt;const a=t.state,s=a.wrap;if(2===s||1===s&&a.status!==Gt||a.lookahead)return Wt;if(1===s&&(t.adler=pt(t.adler,e,i,0)),a.wrap=0,i>=a.w_size){0===s&&(Yt(a.head),a.strstart=0,a.block_start=0,a.insert=0);let t=new Uint8Array(a.w_size);t.set(e.subarray(i-a.w_size,i),0),e=t,i=a.w_size}const r=t.avail_in,n=t.next_in,h=t.input;for(t.avail_in=i,t.next_in=0,t.input=e,ne(a);a.lookahead>=3;){let t=a.strstart,e=a.lookahead-2;do{a.ins_h=Qt(a,a.ins_h,a.window[t+3-1]),a.prev[t&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=t,t++}while(--e);a.strstart=t,a.lookahead=2,ne(a)}return a.strstart+=a.lookahead,a.block_start=a.strstart,a.insert=a.lookahead,a.lookahead=0,a.match_length=a.prev_length=2,a.match_available=0,t.next_in=n,t.input=h,t.avail_in=r,a.wrap=s,Ct},deflateInfo:"pako deflate (from Nodeca project)"};const me=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var be=function(t){const e=Array.prototype.slice.call(arguments,1);for(;e.length;){const i=e.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(const e in i)me(i,e)&&(t[e]=i[e])}}return t},ye=t=>{let e=0;for(let i=0,a=t.length;i<a;i++)e+=t[i].length;const i=new Uint8Array(e);for(let e=0,a=0,s=t.length;e<s;e++){let s=t[e];i.set(s,a),a+=s.length}return i};let Se=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(t){Se=!1}const Be=new Uint8Array(256);for(let t=0;t<256;t++)Be[t]=t>=252?6:t>=248?5:t>=240?4:t>=224?3:t>=192?2:1;Be[254]=Be[254]=1;var ve=t=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(t);let e,i,a,s,r,n=t.length,h=0;for(s=0;s<n;s++)i=t.charCodeAt(s),55296==(64512&i)&&s+1<n&&(a=t.charCodeAt(s+1),56320==(64512&a)&&(i=65536+(i-55296<<10)+(a-56320),s++)),h+=i<128?1:i<2048?2:i<65536?3:4;for(e=new Uint8Array(h),r=0,s=0;r<h;s++)i=t.charCodeAt(s),55296==(64512&i)&&s+1<n&&(a=t.charCodeAt(s+1),56320==(64512&a)&&(i=65536+(i-55296<<10)+(a-56320),s++)),i<128?e[r++]=i:i<2048?(e[r++]=192|i>>>6,e[r++]=128|63&i):i<65536?(e[r++]=224|i>>>12,e[r++]=128|i>>>6&63,e[r++]=128|63&i):(e[r++]=240|i>>>18,e[r++]=128|i>>>12&63,e[r++]=128|i>>>6&63,e[r++]=128|63&i);return e};var Re=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 Ue=Object.prototype.toString,{Z_NO_FLUSH:Ie,Z_SYNC_FLUSH:Te,Z_FULL_FLUSH:De,Z_FINISH:xe,Z_OK:ke,Z_STREAM_END:Ce,Z_DEFAULT_COMPRESSION:Fe,Z_DEFAULT_STRATEGY:We,Z_DEFLATED:Oe}=yt;function ze(t){this.options=be({level:Fe,method:Oe,chunkSize:16384,windowBits:15,memLevel:8,strategy:We},t||{});let e=this.options;e.raw&&e.windowBits>0?e.windowBits=-e.windowBits:e.gzip&&e.windowBits>0&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new Re,this.strm.avail_out=0;let i=we.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(i!==ke)throw new Error(bt[i]);if(e.header&&we.deflateSetHeader(this.strm,e.header),e.dictionary){let t;if(t="string"==typeof e.dictionary?ve(e.dictionary):"[object ArrayBuffer]"===Ue.call(e.dictionary)?new Uint8Array(e.dictionary):e.dictionary,i=we.deflateSetDictionary(this.strm,t),i!==ke)throw new Error(bt[i]);this._dict_set=!0}}ze.prototype.push=function(t,e){const i=this.strm,a=this.options.chunkSize;let s,r;if(this.ended)return!1;for(r=e===~~e?e:!0===e?xe:Ie,"string"==typeof t?i.input=ve(t):"[object ArrayBuffer]"===Ue.call(t)?i.input=new Uint8Array(t):i.input=t,i.next_in=0,i.avail_in=i.input.length;;)if(0===i.avail_out&&(i.output=new Uint8Array(a),i.next_out=0,i.avail_out=a),(r===Te||r===De)&&i.avail_out<=6)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else{if(s=we.deflate(i,r),s===Ce)return i.next_out>0&&this.onData(i.output.subarray(0,i.next_out)),s=we.deflateEnd(this.strm),this.onEnd(s),this.ended=!0,s===ke;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},ze.prototype.onData=function(t){this.chunks.push(t)},ze.prototype.onEnd=function(t){t===ke&&(this.result=ye(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};var Ae={deflate:function(t,e){const i=new ze(e);if(i.push(t,!0),i.err)throw i.msg||bt[i.err];return i.result}};const{deflate:Ee}=Ae;var Me=Ee;const Pe={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}},$e=(t,...e)=>{let i=0;if(t.replace(/[<>]/,"").length!=e.length)throw"Pack format to Argument count mismatch";const a=[];let s=!0;for(let a=0;a<t.length;a++)"<"==t[a]?s=!0:">"==t[a]?s=!1:(r(t[a],e[i]),i++);function r(t,e){if(!(t in Pe))throw"Unhandled character '"+t+"' in pack format";const i=Pe[t].bytes,r=new DataView(new ArrayBuffer(i));Pe[t].p.bind(r)(0,e,s);for(let t=0;t<i;t++)a.push(r.getUint8(t))}return a},Le=(t,e)=>{let i=0;const a=[];let s=!0;for(const e of t)"<"==e?s=!0:">"==e?s=!1:r(e);function r(t){if(!(t in Pe))throw"Unhandled character '"+t+"' in unpack format";const r=Pe[t].bytes,n=new DataView(new ArrayBuffer(r));for(let t=0;t<r;t++)n.setUint8(t,255&e[i+t]);const h=Pe[t].u.bind(n);a.push(h(0,s)),i+=r}return a};class Ne extends EventTarget{constructor(t,e,i){super(),this.port=t,this.logger=e,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=n,this._isESP32S2NativeUSB=!1,this._initializationSucceeded=!1,this.__commandLock=Promise.resolve([0,[]]),this.__isReconfiguring=!1,this.__abandonCurrentOperation=!1,this.__adaptiveBlockMultiplier=1,this.__adaptiveMaxInFlightMultiplier=1,this.__consecutiveSuccessfulChunks=0,this.__lastAdaptiveAdjustment=0,this.__isCDCDevice=!1,this.state_DTR=!1,this.__writeChain=Promise.resolve()}get chipFamily(){return this._parent?this._parent.chipFamily:this.__chipFamily}set chipFamily(t){this._parent?this._parent.chipFamily=t:this.__chipFamily=t}get chipName(){return this._parent?this._parent.chipName:this.__chipName}set chipName(t){this._parent?this._parent.chipName=t:this.__chipName=t}get chipRevision(){return this._parent?this._parent.chipRevision:this.__chipRevision}set chipRevision(t){this._parent?this._parent.chipRevision=t:this.__chipRevision=t}get chipVariant(){return this._parent?this._parent.chipVariant:this.__chipVariant}set chipVariant(t){this._parent?this._parent.chipVariant=t:this.__chipVariant=t}get _inputBuffer(){return this._parent?this._parent._inputBuffer:this.__inputBuffer}get _inputBufferReadIndex(){return this._parent?this._parent._inputBufferReadIndex:this.__inputBufferReadIndex||0}set _inputBufferReadIndex(t){this._parent?this._parent._inputBufferReadIndex=t:this.__inputBufferReadIndex=t}get _inputBufferAvailable(){return this._inputBuffer.length-this._inputBufferReadIndex}_readByte(){if(!(this._inputBufferReadIndex>=this._inputBuffer.length))return this._inputBuffer[this._inputBufferReadIndex++]}_clearInputBuffer(){this._inputBuffer.length=0,this._inputBufferReadIndex=0}_compactInputBuffer(){this._inputBufferReadIndex>1e3&&this._inputBufferReadIndex>this._inputBuffer.length/2&&(this._inputBuffer.splice(0,this._inputBufferReadIndex),this._inputBufferReadIndex=0)}get _totalBytesRead(){return this._parent?this._parent._totalBytesRead:this.__totalBytesRead||0}set _totalBytesRead(t){this._parent?this._parent._totalBytesRead=t:this.__totalBytesRead=t}get _commandLock(){return this._parent?this._parent._commandLock:this.__commandLock}set _commandLock(t){this._parent?this._parent._commandLock=t:this.__commandLock=t}get _isReconfiguring(){return this._parent?this._parent._isReconfiguring:this.__isReconfiguring}set _isReconfiguring(t){this._parent?this._parent._isReconfiguring=t:this.__isReconfiguring=t}get _abandonCurrentOperation(){return this._parent?this._parent._abandonCurrentOperation:this.__abandonCurrentOperation}set _abandonCurrentOperation(t){this._parent?this._parent._abandonCurrentOperation=t:this.__abandonCurrentOperation=t}get _adaptiveBlockMultiplier(){return this._parent?this._parent._adaptiveBlockMultiplier:this.__adaptiveBlockMultiplier}set _adaptiveBlockMultiplier(t){this._parent?this._parent._adaptiveBlockMultiplier=t:this.__adaptiveBlockMultiplier=t}get _adaptiveMaxInFlightMultiplier(){return this._parent?this._parent._adaptiveMaxInFlightMultiplier:this.__adaptiveMaxInFlightMultiplier}set _adaptiveMaxInFlightMultiplier(t){this._parent?this._parent._adaptiveMaxInFlightMultiplier=t:this.__adaptiveMaxInFlightMultiplier=t}get _consecutiveSuccessfulChunks(){return this._parent?this._parent._consecutiveSuccessfulChunks:this.__consecutiveSuccessfulChunks}set _consecutiveSuccessfulChunks(t){this._parent?this._parent._consecutiveSuccessfulChunks=t:this.__consecutiveSuccessfulChunks=t}get _lastAdaptiveAdjustment(){return this._parent?this._parent._lastAdaptiveAdjustment:this.__lastAdaptiveAdjustment}set _lastAdaptiveAdjustment(t){this._parent?this._parent._lastAdaptiveAdjustment=t:this.__lastAdaptiveAdjustment=t}get _isCDCDevice(){return this._parent?this._parent._isCDCDevice:this.__isCDCDevice}set _isCDCDevice(t){this._parent?this._parent._isCDCDevice=t:this.__isCDCDevice=t}detectUSBSerialChip(t,e){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}}}[t];return i&&i[e]?i[e]:{name:`Unknown (VID: 0x${t.toString(16)}, PID: 0x${e.toString(16)})`}}async initialize(){if(!this._parent){this.__inputBuffer=[],this.__inputBufferReadIndex=0,this.__totalBytesRead=0;const t=this.port.getInfo();if(t.usbVendorId&&t.usbProductId){const e=this.detectUSBSerialChip(t.usbVendorId,t.usbProductId);this.logger.log(`USB-Serial: ${e.name} (VID: 0x${t.usbVendorId.toString(16)}, PID: 0x${t.usbProductId.toString(16)})`),e.maxBaudrate&&(this._maxUSBSerialBaudrate=e.maxBaudrate,this.logger.log(`Max baudrate: ${e.maxBaudrate}`)),12346===t.usbVendorId&&2===t.usbProductId&&(this._isESP32S2NativeUSB=!0),(12346===t.usbVendorId||6790===t.usbVendorId&&21971===t.usbProductId)&&(this._isCDCDevice=!0)}this.readLoop()}await this.connectWithResetStrategies(),await this.detectChip();const t=x(this.getChipFamily()),e=t.macFuse;for(let t=0;t<4;t++)this._efuses[t]=await this.readRegister(e+4*t);this.logger.log(`Chip type ${this.chipName}`),this.logger.debug(`Bootloader flash offset: 0x${t.flashOffs.toString(16)}`),this._initializationSucceeded=!0}async detectChip(){try{const t=(await this.getSecurityInfo()).chipId,e=v[t];if(e)return this.chipName=e.name,this.chipFamily=e.family,this.chipFamily===S&&(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: ${t} (${this.chipName})`);this.logger.debug(`Unknown IMAGE_CHIP_ID: ${t}, falling back to magic value detection`)}catch(t){this.logger.debug(`GET_SECURITY_INFO failed, using magic value detection: ${t}`),await this.drainInputBuffer(200),this._clearInputBuffer(),await s(T);try{await this.sync()}catch(t){this.logger.debug(`Re-sync after GET_SECURITY_INFO failure: ${t}`)}}const t=await this.readRegister(1073745920),e=R[t>>>0];if(void 0===e)throw new Error(`Unknown Chip: Hex: ${a(t>>>0,8).toLowerCase()} Number: ${t}`);this.chipName=e.name,this.chipFamily=e.family,this.chipFamily===S&&(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: ${a(t>>>0,8)} (${this.chipName})`)}async getChipRevision(){if(this.chipFamily!==S)return 0;const t=await this.readRegister(1343410252);return 100*((t>>23&1)<<2|t>>4&3)+(15&t)}async getSecurityInfo(){const[,t]=await this.checkCommand(20,[],0);if(0===t.length)throw new Error("GET_SECURITY_INFO not supported or returned empty response");if(t.length<12)throw new Error(`Invalid security info response length: ${t.length} (expected at least 12 bytes)`);return{flags:Le("<I",t.slice(0,4))[0],flashCryptCnt:t[4],keyPurposes:Array.from(t.slice(5,12)),chipId:t.length>=16?Le("<I",t.slice(12,16))[0]:0,apiVersion:t.length>=20?Le("<I",t.slice(16,20))[0]:0}}async readLoop(){this.debug&&this.logger.debug("Starting read loop"),this._reader=this.port.readable.getReader();try{let t=!0;for(;t;){const{value:e,done:i}=await this._reader.read();if(i){this._reader.releaseLock(),t=!1;break}if(!e||0===e.length)continue;const a=Array.from(e);Array.prototype.push.apply(this._inputBuffer,a),this._totalBytesRead+=e.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(t=100){return new Promise(e=>setTimeout(e,t))}async setRTS(t){await this.port.setSignals({requestToSend:t}),await this.setDTR(this.state_DTR)}async setDTR(t){this.state_DTR=t,await this.port.setSignals({dataTerminalReady:t})}async hardResetUSBJTAGSerial(){await this.setRTS(!1),await this.setDTR(!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),await this.sleep(200)}async hardResetClassic(){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),await this.sleep(200)}async setRTSWebUSB(t){await this.port.setSignals({requestToSend:t,dataTerminalReady:this.state_DTR})}async setDTRWebUSB(t){this.state_DTR=t,await this.port.setSignals({dataTerminalReady:t,requestToSend:void 0})}async setDTRandRTSWebUSB(t,e){this.state_DTR=t,await this.port.setSignals({dataTerminalReady:t,requestToSend:e})}async hardResetUSBJTAGSerialWebUSB(){await this.setRTSWebUSB(!1),await this.setDTRWebUSB(!1),await this.sleep(100),await this.setDTRWebUSB(!0),await this.setRTSWebUSB(!1),await this.sleep(100),await this.setRTSWebUSB(!0),await this.setDTRWebUSB(!1),await this.setRTSWebUSB(!0),await this.sleep(100),await this.setDTRWebUSB(!1),await this.setRTSWebUSB(!1),await this.sleep(200)}async hardResetUSBJTAGSerialInvertedDTRWebUSB(){await this.setRTSWebUSB(!1),await this.setDTRWebUSB(!0),await this.sleep(100),await this.setDTRWebUSB(!1),await this.setRTSWebUSB(!1),await this.sleep(100),await this.setRTSWebUSB(!0),await this.setDTRWebUSB(!0),await this.setRTSWebUSB(!0),await this.sleep(100),await this.setDTRWebUSB(!0),await this.setRTSWebUSB(!1),await this.sleep(200)}async hardResetClassicWebUSB(){await this.setDTRWebUSB(!1),await this.setRTSWebUSB(!0),await this.sleep(100),await this.setDTRWebUSB(!0),await this.setRTSWebUSB(!1),await this.sleep(50),await this.setDTRWebUSB(!1),await this.sleep(200)}async hardResetUnixTightWebUSB(){await this.setDTRandRTSWebUSB(!1,!1),await this.setDTRandRTSWebUSB(!0,!0),await this.setDTRandRTSWebUSB(!1,!0),await this.sleep(100),await this.setDTRandRTSWebUSB(!0,!1),await this.sleep(50),await this.setDTRandRTSWebUSB(!1,!1),await this.setDTRWebUSB(!1),await this.sleep(200)}async hardResetClassicLongDelayWebUSB(){await this.setDTRWebUSB(!1),await this.setRTSWebUSB(!0),await this.sleep(500),await this.setDTRWebUSB(!0),await this.setRTSWebUSB(!1),await this.sleep(200),await this.setDTRWebUSB(!1),await this.sleep(500)}async hardResetClassicShortDelayWebUSB(){await this.setDTRWebUSB(!1),await this.setRTSWebUSB(!0),await this.sleep(50),await this.setDTRWebUSB(!0),await this.setRTSWebUSB(!1),await this.sleep(25),await this.setDTRWebUSB(!1),await this.sleep(100)}async hardResetInvertedWebUSB(){await this.setDTRWebUSB(!0),await this.setRTSWebUSB(!1),await this.sleep(100),await this.setDTRWebUSB(!1),await this.setRTSWebUSB(!0),await this.sleep(50),await this.setDTRWebUSB(!0),await this.sleep(200)}async hardResetInvertedDTRWebUSB(){await this.setDTRWebUSB(!0),await this.setRTSWebUSB(!0),await this.sleep(100),await this.setDTRWebUSB(!1),await this.setRTSWebUSB(!1),await this.sleep(50),await this.setDTRWebUSB(!0),await this.sleep(200)}async hardResetInvertedRTSWebUSB(){await this.setDTRWebUSB(!1),await this.setRTSWebUSB(!1),await this.sleep(100),await this.setDTRWebUSB(!0),await this.setRTSWebUSB(!0),await this.sleep(50),await this.setDTRWebUSB(!1),await this.sleep(200)}isWebUSB(){return!0===this.port.isWebUSB}async connectWithResetStrategies(){const t=this.port.getInfo(),e=4097===t.usbProductId,i=12346===t.usbVendorId,a=[],r=this;if(this.isWebUSB()){const s=!e&&!i,n=4292===t.usbVendorId,h=6790===t.usbVendorId,o=12346===t.usbVendorId&&2===t.usbProductId;(e||i)&&(o?(a.push({name:"USB-JTAG/Serial (WebUSB) - ESP32-S2",fn:async function(){return await r.hardResetUSBJTAGSerialWebUSB()}}),a.push({name:"USB-JTAG/Serial Inverted DTR (WebUSB) - ESP32-S2",fn:async function(){return await r.hardResetUSBJTAGSerialInvertedDTRWebUSB()}}),a.push({name:"UnixTight (WebUSB) - ESP32-S2 CDC",fn:async function(){return await r.hardResetUnixTightWebUSB()}}),a.push({name:"Classic (WebUSB) - ESP32-S2 CDC",fn:async function(){return await r.hardResetClassicWebUSB()}})):(a.push({name:"USB-JTAG/Serial Inverted DTR (WebUSB)",fn:async function(){return await r.hardResetUSBJTAGSerialInvertedDTRWebUSB()}}),a.push({name:"USB-JTAG/Serial (WebUSB)",fn:async function(){return await r.hardResetUSBJTAGSerialWebUSB()}}),a.push({name:"Inverted DTR Classic (WebUSB)",fn:async function(){return await r.hardResetInvertedDTRWebUSB()}}))),s&&(h?(a.push({name:"UnixTight (WebUSB) - CH34x",fn:async function(){return await r.hardResetUnixTightWebUSB()}}),a.push({name:"Classic (WebUSB) - CH34x",fn:async function(){return await r.hardResetClassicWebUSB()}}),a.push({name:"Inverted Both (WebUSB) - CH34x",fn:async function(){return await r.hardResetInvertedWebUSB()}}),a.push({name:"Inverted RTS (WebUSB) - CH34x",fn:async function(){return await r.hardResetInvertedRTSWebUSB()}}),a.push({name:"Inverted DTR (WebUSB) - CH34x",fn:async function(){return await r.hardResetInvertedDTRWebUSB()}})):n?(a.push({name:"UnixTight (WebUSB) - CP2102",fn:async function(){return await r.hardResetUnixTightWebUSB()}}),a.push({name:"Classic (WebUSB) - CP2102",fn:async function(){return await r.hardResetClassicWebUSB()}}),a.push({name:"Inverted Both (WebUSB) - CP2102",fn:async function(){return await r.hardResetInvertedWebUSB()}}),a.push({name:"Inverted RTS (WebUSB) - CP2102",fn:async function(){return await r.hardResetInvertedRTSWebUSB()}}),a.push({name:"Inverted DTR (WebUSB) - CP2102",fn:async function(){return await r.hardResetInvertedDTRWebUSB()}})):(a.push({name:"UnixTight (WebUSB)",fn:async function(){return await r.hardResetUnixTightWebUSB()}}),a.push({name:"Classic (WebUSB)",fn:async function(){return await r.hardResetClassicWebUSB()}}),a.push({name:"Inverted Both (WebUSB)",fn:async function(){return await r.hardResetInvertedWebUSB()}}),a.push({name:"Inverted RTS (WebUSB)",fn:async function(){return await r.hardResetInvertedRTSWebUSB()}}),a.push({name:"Inverted DTR (WebUSB)",fn:async function(){return await r.hardResetInvertedDTRWebUSB()}}))),n||o||(6790!==t.usbVendorId&&a.push({name:"Classic (WebUSB)",fn:async function(){return await r.hardResetClassicWebUSB()}}),a.push({name:"UnixTight (WebUSB)",fn:async function(){return await r.hardResetUnixTightWebUSB()}}),a.push({name:"Classic Long Delay (WebUSB)",fn:async function(){return await r.hardResetClassicLongDelayWebUSB()}}),a.push({name:"Classic Short Delay (WebUSB)",fn:async function(){return await r.hardResetClassicShortDelayWebUSB()}}),e||i||a.push({name:"USB-JTAG/Serial fallback (WebUSB)",fn:async function(){return await r.hardResetUSBJTAGSerialWebUSB()}}))}else(e||i)&&a.push({name:"USB-JTAG/Serial",fn:async function(){return await r.hardResetUSBJTAGSerial()}}),a.push({name:"Classic",fn:async function(){return await r.hardResetClassic()}}),e||i||a.push({name:"USB-JTAG/Serial (fallback)",fn:async function(){return await r.hardResetUSBJTAGSerial()}});let n=null;for(const t of a)try{if(!this.connected||!this.port.writable){this.logger.log(`Port disconnected, skipping ${t.name} reset`);continue}this._abandonCurrentOperation=!1,await t.fn();if(await this.syncWithTimeout(3e3))return void this.logger.log(`Connected successfully with ${t.name} reset.`);throw new Error("Sync timeout or abandoned")}catch(e){if(n=e,this.logger.log(`${t.name} reset failed: ${e.message}`),this._abandonCurrentOperation=!0,await s(100),!this.connected||!this.port.writable){this.logger.log("Port disconnected during reset attempt");break}this._clearInputBuffer(),await this.drainInputBuffer(200),await this.flushSerialBuffers()}throw new Error(`Couldn't sync to ESP. Try resetting manually. Last error: ${null==n?void 0:n.message}`)}async hardReset(t=!1){t?4097===this.port.getInfo().usbProductId?(await this.hardResetUSBJTAGSerial(),this.logger.log("USB-JTAG/Serial reset.")):this.isWebUSB()?(await this.hardResetClassicWebUSB(),this.logger.log("Classic reset (WebUSB/Android).")):(await this.hardResetClassic(),this.logger.log("Classic reset.")):this.isWebUSB()?(await this.setRTS(!0),await this.sleep(200),await this.setRTS(!1),await this.sleep(200),this.logger.log("Hard reset (WebUSB).")):(await this.setRTS(!0),await this.sleep(100),await this.setRTS(!1),this.logger.log("Hard reset.")),await new Promise(t=>setTimeout(t,1e3))}macAddr(){const t=new Array(6).fill(0),e=this._efuses[0],i=this._efuses[1],a=this._efuses[2],s=this._efuses[3];let r;if(this.chipFamily==l){if(0!=s)r=[s>>16&255,s>>8&255,255&s];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];t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=i>>8&255,t[4]=255&i,t[5]=e>>24&255}else if(this.chipFamily==u)t[0]=a>>8&255,t[1]=255&a,t[2]=i>>24&255,t[3]=i>>16&255,t[4]=i>>8&255,t[5]=255&i;else{if(this.chipFamily!=d&&this.chipFamily!=c&&this.chipFamily!=_&&this.chipFamily!=f&&this.chipFamily!=g&&this.chipFamily!=p&&this.chipFamily!=w&&this.chipFamily!=m&&this.chipFamily!=b&&this.chipFamily!=y&&this.chipFamily!=S&&this.chipFamily!=B)throw new Error("Unknown chip family");t[0]=i>>8&255,t[1]=255&i,t[2]=e>>24&255,t[3]=e>>16&255,t[4]=e>>8&255,t[5]=255&e}return t}async readRegister(t){this.debug&&this.logger.debug("Reading from Register "+a(t,8));const e=$e("<I",t);await this.sendCommand(10,e);const[i]=await this.getResponse(10);return i}async checkCommand(t,e,i=0,s=3e3){const r=async()=>{s=Math.min(s,3e5),await this.sendCommand(t,e,i);const[r,n]=await this.getResponse(t,s);if(null===n)throw new Error("Didn't get enough status bytes");let h=n,o=0;if(this.IS_STUB||this.chipFamily==l?o=2:[u,d,c,_,f,g,p,w,m,b,y,S,B].includes(this.chipFamily)||20===t?o=4:[2,4].includes(h.length)?o=h.length:(o=2,this.logger.debug(`Unknown chip family, defaulting to 2-byte status (opcode: ${a(t)}, data.length: ${h.length})`)),h.length<o)throw new Error("Didn't get enough status bytes");const v=h.slice(-o,h.length);if(h=h.slice(0,-o),this.debug&&(this.logger.debug("status",v),this.logger.debug("value",r),this.logger.debug("data",h)),1==v[0])throw 5==v[1]?(await this.drainInputBuffer(200),new Error("Invalid (unsupported) command "+a(t))):new Error("Command failure error code "+a(v[1]));return[r,h]};return this._commandLock=this._commandLock.then(r,r),this._commandLock}async sendCommand(e,i,a=0){const s=t([...$e("<BBHI",0,e,i.length,a),...i]);this.debug&&this.logger.debug(`Writing ${s.length} byte${1==s.length?"":"s"}:`,s),await this.writeToStream(s)}async readPacket(t){let e=null,r=!1;if(this._isCDCDevice){const n=Date.now();for(;;){if(this._abandonCurrentOperation)throw new k("Operation abandoned (reset strategy timeout)");if(Date.now()-n>t){throw new k("Timed out waiting for packet "+(null===e?"header":"content"))}if(0!==this._inputBufferAvailable)for(;this._inputBufferAvailable>0;){const t=this._readByte();if(null===e){if(192!=t)throw this.debug&&(this.logger.debug("Read invalid data: "+a(t)),this.logger.debug("Remaining data in serial buffer: "+i(this._inputBuffer))),new k("Invalid head of packet ("+a(t)+")");e=[]}else if(r)if(r=!1,220==t)e.push(192);else{if(221!=t)throw this.debug&&(this.logger.debug("Read invalid data: "+a(t)),this.logger.debug("Remaining data in serial buffer: "+i(this._inputBuffer))),new k("Invalid SLIP escape (0xdb, "+a(t)+")");e.push(219)}else if(219==t)r=!0;else{if(192==t)return this.debug&&this.logger.debug("Received full packet: "+i(e)),this._compactInputBuffer(),e;e.push(t)}}else await s(1)}}else{let n=[];for(;;){if(this._abandonCurrentOperation)throw new k("Operation abandoned (reset strategy timeout)");const h=Date.now();for(n=[];Date.now()-h<t;){if(this._inputBufferAvailable>0){n.push(this._readByte());break}await s(1)}if(0==n.length){throw new k("Timed out waiting for packet "+(null===e?"header":"content"))}this.debug&&this.logger.debug("Read "+n.length+" bytes: "+i(n));for(const t of n)if(null===e){if(192!=t)throw this.debug&&(this.logger.debug("Read invalid data: "+a(t)),this.logger.debug("Remaining data in serial buffer: "+i(this._inputBuffer))),new k("Invalid head of packet ("+a(t)+")");e=[]}else if(r)if(r=!1,220==t)e.push(192);else{if(221!=t)throw this.debug&&(this.logger.debug("Read invalid data: "+a(t)),this.logger.debug("Remaining data in serial buffer: "+i(this._inputBuffer))),new k("Invalid SLIP escape (0xdb, "+a(t)+")");e.push(219)}else if(219==t)r=!0;else{if(192==t)return this.debug&&this.logger.debug("Received full packet: "+i(e)),this._compactInputBuffer(),e;e.push(t)}}}}async getResponse(t,e=3e3){for(let i=0;i<100;i++){const i=await this.readPacket(e);if(i.length<8)continue;const[s,r,,n]=Le("<BBHI",i.slice(0,8));if(1!=s)continue;const h=i.slice(8);if(null==t||r==t)return[n,h];if(0!=h[0]&&5==h[1])throw await this.drainInputBuffer(200),new Error(`Invalid (unsupported) command ${a(t)}`)}throw new Error("Response doesn't match request")}checksum(t,e=239){for(const i of t)e^=i;return e}async setBaudrate(t){if(this.chipFamily==l)throw new Error("Changing baud rate is not supported on the ESP8266");try{const e=$e("<II",t,this.IS_STUB?n:0);await this.checkCommand(15,e)}catch(e){throw this.logger.error(`Baudrate change error: ${e}`),new Error(`Unable to change the baud rate to ${t}: No response from set baud rate command.`)}this._parent?await this._parent.reconfigurePort(t):await this.reconfigurePort(t),await s(T),this._parent?this._parent._currentBaudRate=t:this._currentBaudRate=t;const e=this._parent?this._parent._maxUSBSerialBaudrate:this._maxUSBSerialBaudrate;e&&t>e&&(this.logger.log(`⚠️ WARNING: Baudrate ${t} exceeds USB-Serial chip limit (${e})!`),this.logger.log("⚠️ This may cause data corruption or connection failures!")),this.logger.log(`Changed baud rate to ${t}`)}async reconfigurePort(t){var e;this._isReconfiguring=!0;try{try{await this._writeChain}catch(t){this.logger.debug(`Pending write error during reconfigure: ${t}`)}if(this.isWebUSB()){const e=this.port.getInfo(),i=6790===e.usbVendorId&&21971===e.usbProductId;if(!i&&"function"==typeof this.port.setBaudRate)return await this.port.setBaudRate(t),void await s(100)}if(this._writer){try{this._writer.releaseLock()}catch(t){this.logger.debug(`Writer release error during reconfigure: ${t}`)}this._writer=void 0}await(null===(e=this._reader)||void 0===e?void 0:e.cancel()),await this.port.close(),await this.port.open({baudRate:t}),await this.flushSerialBuffers(),this.readLoop()}catch(e){throw this.logger.error(`Reconfigure port error: ${e}`),new Error(`Unable to change the baud rate to ${t}: ${e}`)}finally{this._isReconfiguring=!1}}async syncWithTimeout(t){const e=Date.now();for(let i=0;i<5;i++){if(Date.now()-e>t)return!1;if(this._abandonCurrentOperation)return!1;this._clearInputBuffer();try{if(await this._sync())return await s(T),!0}catch(t){if(this._abandonCurrentOperation)return!1}await s(T)}return!1}async sync(){for(let t=0;t<5;t++){this._clearInputBuffer();if(await this._sync())return await s(T),!0;await s(T)}throw new Error("Couldn't sync to ESP. Try resetting.")}async _sync(){await this.sendCommand(8,o);for(let t=0;t<8;t++)try{const[,t]=await this.getResponse(8,T);if(t.length>1&&0==t[0]&&0==t[1])return!0}catch(e){this.debug&&this.logger.debug(`Sync attempt ${t+1} failed: ${e}`)}return!1}getFlashWriteSize(){return this.IS_STUB?16384:1024}async flashData(t,e,i=0,s=!1){if(t.byteLength>=8){const e=Array.from(new Uint8Array(t,0,4)),i=e[0],s=e[2],r=e[3];this.logger.log(`Image header, Magic=${a(i)}, FlashMode=${a(s)}, FlashSizeFreq=${a(r)}`)}const r=t.byteLength;let n,h=0,o=U;s?(n=Me(new Uint8Array(t),{level:9}).buffer,h=n.byteLength,this.logger.log(`Writing data with filesize: ${r}. Compressed Size: ${h}`),o=await this.flashDeflBegin(r,h,i)):(this.logger.log(`Writing data with filesize: ${r}`),n=t,await this.flashBegin(r,i));let l=[],u=0,d=0,c=0;const _=Date.now(),f=this.getFlashWriteSize(),g=s?h:r;for(;g-c>0;)this.debug&&this.logger.log(`Writing at ${a(i+u*f,8)} `),g-c>=f?l=Array.from(new Uint8Array(n,c,f)):(l=Array.from(new Uint8Array(n,c,g-c)),s||(l=l.concat(new Array(f-l.length).fill(255)))),s?await this.flashDeflBlock(l,u,o):await this.flashBlock(l,u),u+=1,d+=s?Math.round(l.length*r/h):l.length,c+=f,e(Math.min(d,r),r);this.logger.log("Took "+(Date.now()-_)+"ms to write "+g+" bytes"),this.IS_STUB&&(await this.flashBegin(0,0),s?await this.flashDeflFinish():await this.flashFinish())}async flashBlock(t,e,i=3e3){await this.checkCommand(3,$e("<IIII",t.length,e,0,0).concat(t),this.checksum(t),i)}async flashDeflBlock(t,e,i=3e3){await this.checkCommand(17,$e("<IIII",t.length,e,0,0).concat(t),this.checksum(t),i)}async flashBegin(t=0,e=0,i=!1){let s;await this.flushSerialBuffers();const r=this.getFlashWriteSize();!this.IS_STUB&&[u,d,c,_,f,g,p,w,m,b,y,S,B].includes(this.chipFamily)&&await this.checkCommand(13,new Array(8).fill(0));const n=Math.floor((t+r-1)/r);s=this.chipFamily==l?this.getEraseSize(e,t):t;const h=this.IS_STUB?U:D(3e4,t),o=Date.now();let v=$e("<IIII",s,n,r,e);return this.chipFamily!=u&&this.chipFamily!=d&&this.chipFamily!=c&&this.chipFamily!=_&&this.chipFamily!=f&&this.chipFamily!=g&&this.chipFamily!=p&&this.chipFamily!=w&&this.chipFamily!=m&&this.chipFamily!=b&&this.chipFamily!=y&&this.chipFamily!=S&&this.chipFamily!=B||(v=v.concat($e("<I",i?1:0))),this.logger.log("Erase size "+s+", blocks "+n+", block size "+a(r,4)+", offset "+a(e,4)+", encrypted "+(i?"yes":"no")),await this.checkCommand(2,v,0,h),0==t||this.IS_STUB||this.logger.log("Took "+(Date.now()-o)+"ms to erase "+n+" bytes"),n}async flashDeflBegin(t=0,e=0,i=0){const a=this.getFlashWriteSize(),s=Math.floor((e+a-1)/a),r=Math.floor((t+a-1)/a);let n=0,h=0;this.IS_STUB?(n=t,h=D(3e4,n)):(n=r*a,h=U);const o=$e("<IIII",n,s,a,i);return await this.checkCommand(16,o,0,h),h}async flashFinish(){const t=$e("<I",1);await this.checkCommand(4,t)}async flashDeflFinish(){const t=$e("<I",1);await this.checkCommand(18,t)}getBootloaderOffset(){return x(this.getChipFamily()).flashOffs}async flashId(){return await this.runSpiFlashCommand(159,[],24)}getChipFamily(){return this._parent?this._parent.chipFamily:this.chipFamily}async writeRegister(t,e,i=4294967295,a=0,s=0){let r=$e("<IIII",t,e,i,a);s>0&&(r=r.concat($e("<IIII",x(this.getChipFamily()).uartDateReg,0,0,s))),await this.checkCommand(9,r)}async setDataLengths(t,e,i){if(-1!=t.mosiDlenOffs){const a=t.regBase+t.mosiDlenOffs,s=t.regBase+t.misoDlenOffs;e>0&&await this.writeRegister(a,e-1),i>0&&await this.writeRegister(s,i-1)}else{const a=t.regBase+t.usr1Offs,s=(0==i?0:i-1)<<8|(0==e?0:e-1)<<17;await this.writeRegister(a,s)}}async waitDone(t,e){for(let i=0;i<10;i++){if(0==(await this.readRegister(t)&e))return}throw Error("SPI command did not complete in time")}async runSpiFlashCommand(t,e,i=0){const s=x(this.getChipFamily()),r=s.regBase,n=r,h=r+s.usrOffs,o=r+s.usr2Offs,l=r+s.w0Offs,u=1<<18;if(i>32)throw new Error("Reading more than 32 bits back from a SPI flash operation is unsupported");if(e.length>64)throw new Error("Writing more than 64 bytes of data with one SPI command is unsupported");const d=8*e.length,c=await this.readRegister(h),_=await this.readRegister(o);let f=1<<31;if(i>0&&(f|=268435456),d>0&&(f|=134217728),await this.setDataLengths(s,d,i),await this.writeRegister(h,f),await this.writeRegister(o,7<<28|t),0==d)await this.writeRegister(l,0);else{const t=(4-e.length%4)%4;e=e.concat(new Array(t).fill(0));const i=Le("I".repeat(Math.floor(e.length/4)),e);let s=l;this.logger.debug(`Words Length: ${i.length}`);for(const t of i)this.logger.debug(`Writing word ${a(t)} to register offset ${a(s)}`),await this.writeRegister(s,t),s+=4}await this.writeRegister(n,u),await this.waitDone(n,u);const g=await this.readRegister(l);return await this.writeRegister(h,c),await this.writeRegister(o,_),g}async detectFlashSize(){this.logger.log("Detecting Flash Size");const t=await this.flashId(),e=255&t,i=t>>16&255;this.logger.log(`FlashId: ${a(t)}`),this.logger.log(`Flash Manufacturer: ${e.toString(16)}`),this.logger.log(`Flash Device: ${(t>>8&255).toString(16)}${i.toString(16)}`),this.flashSize=r[i],this.logger.log(`Auto-detected Flash size: ${this.flashSize}`)}getEraseSize(t,e){const i=4096,a=Math.floor((e+i-1)/i);let s=16-Math.floor(t/i)%16;return a<s&&(s=a),a<2*s?Math.floor((a+1)/2*i):(a-s)*i}async memBegin(t,e,i,a){return await this.checkCommand(5,$e("<IIII",t,e,i,a))}async memBlock(t,e){return await this.checkCommand(7,$e("<IIII",t.length,e,0,0).concat(t),this.checksum(t))}async memFinish(t=0){const e=this.IS_STUB?U:500,i=$e("<II",0==t?1:0,t);return await this.checkCommand(6,i,0,e)}async runStub(t=!1){const e=await C(this.chipFamily,this.chipRevision);if(null===e)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 t of["text","data"]){const a=e[t],s=e[`${t}_start`],r=a.length,n=Math.floor((r+i-1)/i);await this.memBegin(r,n,i,s);for(const t of Array(n).keys()){const e=t*i;let s=e+i;s>r&&(s=r),await this.memBlock(a.slice(e,s),t)}}await this.memFinish(e.entry);const a=await this.readPacket(500),s=String.fromCharCode(...a);if("OHAI"!=s)throw new Error("Failed to start stub. Unexpected response: "+s);this.logger.log("Stub is now running...");const r=new Ze(this.port,this.logger,this);return t||await r.detectFlashSize(),r}get _writer(){return this._parent?this._parent._writer:this.__writer}set _writer(t){this._parent?this._parent._writer=t:this.__writer=t}get _writeChain(){return this._parent?this._parent._writeChain:this.__writeChain}set _writeChain(t){this._parent?this._parent._writeChain=t:this.__writeChain=t}async writeToStream(t){if(this.port.writable){if(this._isReconfiguring)throw new Error("Cannot write during port reconfiguration");this._writeChain=this._writeChain.then(async()=>{if(!this.port.writable)throw new Error("Port became unavailable during write");if(!this._writer)try{this._writer=this.port.writable.getWriter()}catch(t){throw this.logger.error(`Failed to get writer: ${t}`),t}await this._writer.write(new Uint8Array(t))},async()=>{if(this.logger.debug("Previous write failed, attempting recovery for current write"),!this.port.writable)throw new Error("Port became unavailable during write");if(!this._writer)try{this._writer=this.port.writable.getWriter()}catch(t){throw this.logger.debug(`Failed to get writer in recovery: ${t}`),new Error("Cannot acquire writer lock")}await this._writer.write(new Uint8Array(t))}).catch(t=>{if(this.logger.error(`Write error: ${t}`),this._writer){try{this._writer.releaseLock()}catch{}this._writer=void 0}throw t}),await this._writeChain}else this.logger.debug("Port writable stream not available, skipping write")}async disconnect(){if(this._parent)await this._parent.disconnect();else if(this.port.writable)try{try{await this._writeChain}catch(t){this.logger.debug(`Pending write error during disconnect: ${t}`)}if(this._isReconfiguring=!0,this._writer){try{await this._writer.close(),this._writer.releaseLock()}catch(t){this.logger.debug(`Writer close/release error: ${t}`)}this._writer=void 0}else try{const t=this.port.writable.getWriter();await t.close(),t.releaseLock()}catch(t){this.logger.debug(`Direct writer close error: ${t}`)}await new Promise(t=>{this._reader?(this.addEventListener("disconnect",t,{once:!0}),this._reader.cancel()):t(void 0)}),this.connected=!1}finally{this._isReconfiguring=!1}else this.logger.debug("Port already closed, skipping disconnect")}async reconnect(){if(this._parent)await this._parent.reconnect();else try{this.logger.log("Reconnecting serial port..."),this.connected=!1,this.__inputBuffer=[],this.__inputBufferReadIndex=0;try{await this._writeChain}catch(t){this.logger.debug(`Pending write error during reconnect: ${t}`)}if(this._isReconfiguring=!0,this._writer){try{this._writer.releaseLock()}catch(t){this.logger.debug(`Writer release error during reconnect: ${t}`)}this._writer=void 0}if(this._reader){try{await this._reader.cancel()}catch(t){this.logger.debug(`Reader cancel error: ${t}`)}this._reader=void 0}try{await this.port.close(),this.logger.log("Port closed")}catch(t){this.logger.debug(`Port close error: ${t}`)}this.logger.debug("Opening port...");try{await this.port.open({baudRate:n}),this.connected=!0}catch(t){throw new Error(`Failed to open port: ${t}`)}if(!this.port.readable||!this.port.writable)throw new Error(`Port streams not available after open (readable: ${!!this.port.readable}, writable: ${!!this.port.writable})`);this._isReconfiguring=!1;const t=this.chipFamily,e=this.chipName,i=this.chipRevision,a=this.chipVariant,s=this.flashSize;if(await this.hardReset(!0),this._parent||(this.__inputBuffer=[],this.__inputBufferReadIndex=0,this.__totalBytesRead=0,this.readLoop()),await this.flushSerialBuffers(),await this.sync(),this.chipFamily=t,this.chipName=e,this.chipRevision=i,this.chipVariant=a,this.flashSize=s,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!==n&&(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=!0,this.logger.debug("Reconnection successful")}catch(t){throw this._isReconfiguring=!1,t}}async drainInputBuffer(t=200){await s(t);let e=0;const i=Date.now();for(;e<112&&Date.now()-i<100;)if(this._inputBufferAvailable>0){void 0!==this._readByte()&&e++}else await s(1);e>0&&this.logger.debug(`Drained ${e} bytes from input buffer`),this._parent||(this.__inputBuffer=[],this.__inputBufferReadIndex=0)}async flushSerialBuffers(){this._parent||(this.__inputBuffer=[],this.__inputBufferReadIndex=0),await s(T),this._parent||(this.__inputBuffer=[],this.__inputBufferReadIndex=0),this.logger.debug("Serial buffers flushed")}async readFlash(e,i,a){if(!this.IS_STUB)throw new Error("Reading flash is only supported in stub mode. Please run runStub() first.");let r;await this.flushSerialBuffers(),this.logger.log(`Reading ${i} bytes from flash at address 0x${e.toString(16)}...`),this.isWebUSB()&&(this._isCDCDevice?(this._adaptiveBlockMultiplier=8,this._adaptiveMaxInFlightMultiplier=8,this._consecutiveSuccessfulChunks=0,this.logger.debug(`CDC device - Initialized: blockMultiplier=${this._adaptiveBlockMultiplier}, maxInFlightMultiplier=${this._adaptiveMaxInFlightMultiplier}`)):(this._adaptiveBlockMultiplier=1,this._adaptiveMaxInFlightMultiplier=1,this._consecutiveSuccessfulChunks=0,this.logger.debug("Non-CDC device - Fixed values: blockSize=31, maxInFlight=31"))),r=this.isWebUSB()?16384:262144;let n=new Uint8Array(0),h=e,o=i;for(;o>0;){const e=Math.min(r,o);let l=!1,u=0;const d=5;let c=!1;for(;!l&&u<=d;){let i=new Uint8Array(0),a=0;try{let r,o;if(0===u&&this.logger.debug(`Reading chunk at 0x${h.toString(16)}, size: 0x${e.toString(16)}`),this.isWebUSB()){const t=this.port.maxTransferSize||64,e=Math.floor((t-2)/2);r=e*this._adaptiveBlockMultiplier,o=e*this._adaptiveMaxInFlightMultiplier}else{const t=63;r=65*t,o=130*t}const d=$e("<IIII",h,e,r,o),[c]=await this.checkCommand(210,d);if(0!=c)throw new Error("Failed to read memory: "+c);for(;i.length<e;){let r;try{r=await this.readPacket(100)}catch(t){if(t instanceof k){this.logger.debug(`SLIP read error at ${i.length} bytes: ${t.message}`);try{const t=[192,192];await this.writeToStream(t),this.logger.debug("Sent abort frame to stub"),await s(50)}catch(t){this.logger.debug(`Abort frame error: ${t}`)}if(await this.drainInputBuffer(200),i.length>=e)break}throw t}if(r&&r.length>0){const s=new Uint8Array(r),n=new Uint8Array(i.length+s.length);n.set(i),n.set(s,i.length),i=n;if(i.length>=e||i.length>=a+o){const e=$e("<I",i.length),s=t(e);await this.writeToStream(s),a=i.length}}}const _=new Uint8Array(n.length+i.length);if(_.set(n),_.set(i,n.length),n=_,l=!0,this.isWebUSB()&&this._isCDCDevice&&0===u&&(this._consecutiveSuccessfulChunks++,this._consecutiveSuccessfulChunks>=2)){const t=this.port.maxTransferSize||64,e=Math.floor((t-2)/2),i=8,a=8;let s=!1;if(this._adaptiveBlockMultiplier<i?(this._adaptiveBlockMultiplier=Math.min(2*this._adaptiveBlockMultiplier,i),s=!0):this._adaptiveMaxInFlightMultiplier<a&&(this._adaptiveMaxInFlightMultiplier=Math.min(2*this._adaptiveMaxInFlightMultiplier,a),s=!0),s){const t=e*this._adaptiveBlockMultiplier,i=e*this._adaptiveMaxInFlightMultiplier;this.logger.debug(`Speed increased: blockSize=${t}, maxInFlight=${i}`),this._lastAdaptiveAdjustment=Date.now()}this._consecutiveSuccessfulChunks=0}}catch(t){if(u++,this.isWebUSB()&&this._isCDCDevice&&1===u)if(this._adaptiveBlockMultiplier>1||this._adaptiveMaxInFlightMultiplier>1){this._adaptiveBlockMultiplier=1,this._adaptiveMaxInFlightMultiplier=1,this._consecutiveSuccessfulChunks=0;const t=this.port.maxTransferSize||64,e=Math.floor((t-2)/2),i=e*this._adaptiveBlockMultiplier,a=e*this._adaptiveMaxInFlightMultiplier;this.logger.debug(`Error at higher speed - reduced to minimum: blockSize=${i}, maxInFlight=${a}`)}else this.logger.debug("Error at minimum speed (blockSize=31, maxInFlight=31) - not a speed issue");if(!(t instanceof k))throw t;if(u<=d){this.logger.log(`${t.message} at 0x${h.toString(16)}. Draining buffer and retrying (attempt ${u}/${d})...`);try{await this.drainInputBuffer(200),await this.flushSerialBuffers(),await s(T)}catch(t){this.logger.debug(`Buffer drain error: ${t}`)}}else{if(c)throw new Error(`Failed to read chunk at 0x${h.toString(16)} after ${d} retries and recovery attempt`);c=!0,this.logger.log(`All retries exhausted at 0x${h.toString(16)}. Attempting recovery (close and reopen port)...`);try{await this.reconnect(),this.logger.log("Deep recovery successful. Resuming read from current position..."),u=0;continue}catch(t){throw new Error(`Failed to read chunk at 0x${h.toString(16)} after ${d} retries and recovery failed: ${t}`)}}}}a&&a(new Uint8Array(e),n.length,i),h+=e,o-=e,this.logger.debug(`Total progress: 0x${n.length.toString(16)} from 0x${i.toString(16)} bytes`)}return n}}class Ze extends Ne{constructor(){super(...arguments),this.IS_STUB=!0}async memBegin(t,e,i,s){const r=await C(this.chipFamily,this.chipRevision);if(null===r)return[0,[]];const n=s,h=s+t;this.logger.debug(`Load range: ${a(n,8)}-${a(h,8)}`),this.logger.debug(`Stub data: ${a(r.data_start,8)}, len: ${r.data.length}, text: ${a(r.text_start,8)}, len: ${r.text.length}`);for(const[t,e]of[[r.data_start,r.data_start+r.data.length],[r.text_start,r.text_start+r.text.length]])if(n<e&&h>t)throw new Error("Software loader is resident at "+a(t,8)+"-"+a(e,8)+". Can't load binary at overlapping address range "+a(n,8)+"-"+a(h,8)+". Try changing the binary loading address.");return[0,[]]}async eraseFlash(){await this.checkCommand(208,[],0,I)}}const Ve=async t=>{let e;const i=globalThis.requestSerialPort;if("function"==typeof i)t.log("Using custom port request function"),e=await i();else{if(!navigator.serial)throw new Error("Web Serial API is not supported in this browser. Please use Chrome 89+, Edge 89+, or Opera on desktop, or Chrome 61+ on Android with USB OTG. Note: The page must be served over HTTPS or localhost.");e=await navigator.serial.requestPort()}return e.readable&&e.writable||await e.open({baudRate:n}),t.log("Connected successfully."),new Ne(e,t)},He=async(t,e)=>{if(!t)throw new Error("Port is required");return t.readable&&t.writable||await t.open({baudRate:n}),e.log("Connected successfully."),new Ne(t,e)};export{u as CHIP_FAMILY_ESP32,_ as CHIP_FAMILY_ESP32C2,f as CHIP_FAMILY_ESP32C3,g as CHIP_FAMILY_ESP32C5,p as CHIP_FAMILY_ESP32C6,w as CHIP_FAMILY_ESP32C61,m as CHIP_FAMILY_ESP32H2,y as CHIP_FAMILY_ESP32H21,b as CHIP_FAMILY_ESP32H4,S as CHIP_FAMILY_ESP32P4,d as CHIP_FAMILY_ESP32S2,c as CHIP_FAMILY_ESP32S3,B as CHIP_FAMILY_ESP32S31,l as CHIP_FAMILY_ESP8266,Ne as ESPLoader,Ve as connect,He as connectWithPort};
1
+ const t=t=>{let e=[192];for(const i of t)219==i?e=e.concat([219,221]):192==i?e=e.concat([219,220]):e.push(i);return e.push(192),e},e=t=>{const e=[];for(let i=0;i<t.length;i++){const a=t.charCodeAt(i);a<=255&&e.push(a)}return e},i=t=>"["+t.map(t=>a(t)).join(", ")+"]",a=(t,e=2)=>{const i=t.toString(16).toUpperCase();return i.startsWith("-")?"-0x"+i.substring(1).padStart(e,"0"):"0x"+i.padStart(e,"0")},s=t=>new Promise(e=>setTimeout(e,t)),r={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"},n=4096,h=115200,o=1343410176,l=e(" UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU"),u=33382,d=50,c=12882,_=12883,f=12994,g=12995,p=12997,w=12998,m=207969,b=12914,y=12916,S=12917,B=12928,v=12849,R={5:{name:"ESP32-C3",family:g},9:{name:"ESP32-S3",family:_},12:{name:"ESP32-C2",family:f},13:{name:"ESP32-C6",family:w},16:{name:"ESP32-H2",family:b},18:{name:"ESP32-P4",family:B},20:{name:"ESP32-C61",family:m},23:{name:"ESP32-C5",family:p},25:{name:"ESP32-H21",family:S},28:{name:"ESP32-H4",family:y},32:{name:"ESP32-S31",family:v}},U={4293968129:{name:"ESP8266",family:u},15736195:{name:"ESP32",family:d},1990:{name:"ESP32-S2",family:c}},I=3e3,T=15e4,x=100,D=3e4,k=(t,e)=>{const i=Math.floor(t*(e/486));return i<I?I:i},C=t=>{switch(t){case d:return{regBase:1072963584,baseFuse:1073061888,macFuse:1073061888,usrOffs:28,usr1Offs:32,usr2Offs:36,mosiDlenOffs:40,misoDlenOffs:44,w0Offs:128,uartDateReg:1610612856,flashOffs:4096};case c:return{regBase:1061167104,baseFuse:1061265408,macFuse:1061265476,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612856,flashOffs:4096};case _:return{regBase:1610620928,usrOffs:24,baseFuse:1610641408,macFuse:1610641476,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612864,flashOffs:0};case u:return{regBase:1610613248,usrOffs:28,baseFuse:1072693328,macFuse:1072693328,usr1Offs:32,usr2Offs:36,mosiDlenOffs:-1,misoDlenOffs:-1,w0Offs:64,uartDateReg:1610612856,flashOffs:0};case f:case g:return{regBase:1610620928,baseFuse:1610647552,macFuse:1610647620,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case p:return{regBase:1610625024,baseFuse:1611352064,macFuse:1611352132,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:8192};case w:return{regBase:1610625024,baseFuse:1611335680,macFuse:1611335748,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case m:return{regBase:1610625024,baseFuse:1611352064,macFuse:1611352132,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case b:return{regBase:1610625024,baseFuse:1611335680,macFuse:1611335748,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case y:return{regBase:1611239424,baseFuse:1611339776,macFuse:1611339844,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610686588,flashOffs:8192};case S:return{regBase:1610625024,baseFuse:1611350016,macFuse:1611350084,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case B:return{regBase:1342754816,baseFuse:o,macFuse:1343410244,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1343004812,flashOffs:8192};case v: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 F extends Error{constructor(t){super(t),this.name="SlipReadError"}}const z=async(t,i)=>{let a;if(t==y||t==S||t==v)return null;if(t==d)a=await import("./esp32-BRKoi17y.js");else if(t==c)a=await import("./esp32s2-iX3WoDbg.js");else if(t==_)a=await import("./esp32s3-DGwDVIgz.js");else if(t==u)a=await import("./esp8266-CUwxJpGa.js");else if(t==f)a=await import("./esp32c2-Btgr_lwh.js");else if(t==g)a=await import("./esp32c3-CHKfoI8W.js");else if(t==p)a=await import("./esp32c5-BDW4KtLo.js");else if(t==w)a=await import("./esp32c6-il8tTxAG.js");else if(t==m)a=await import("./esp32c61-thKzxBGf.js");else if(t==b)a=await import("./esp32h2-CxoUHv_P.js");else{if(t!=B)return null;a=null!=i&&i>=300?await import("./esp32p4r3-CqI71ojR.js"):await import("./esp32p4-D3jLP-jY.js")}return{...a,text:e(atob(a.text)),data:e(atob(a.data))}};function O(t){let e=t.length;for(;--e>=0;)t[e]=0}const W=256,A=286,E=30,$=15,M=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]),P=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]),L=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),N=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Z=new Array(576);O(Z);const V=new Array(60);O(V);const H=new Array(512);O(H);const j=new Array(256);O(j);const G=new Array(29);O(G);const J=new Array(E);function q(t,e,i,a,s){this.static_tree=t,this.extra_bits=e,this.extra_base=i,this.elems=a,this.max_length=s,this.has_stree=t&&t.length}let K,Y,X;function Q(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}O(J);const tt=t=>t<256?H[t]:H[256+(t>>>7)],et=(t,e)=>{t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255},it=(t,e,i)=>{t.bi_valid>16-i?(t.bi_buf|=e<<t.bi_valid&65535,et(t,t.bi_buf),t.bi_buf=e>>16-t.bi_valid,t.bi_valid+=i-16):(t.bi_buf|=e<<t.bi_valid&65535,t.bi_valid+=i)},at=(t,e,i)=>{it(t,i[2*e],i[2*e+1])},st=(t,e)=>{let i=0;do{i|=1&t,t>>>=1,i<<=1}while(--e>0);return i>>>1},rt=(t,e,i)=>{const a=new Array(16);let s,r,n=0;for(s=1;s<=$;s++)n=n+i[s-1]<<1,a[s]=n;for(r=0;r<=e;r++){let e=t[2*r+1];0!==e&&(t[2*r]=st(a[e]++,e))}},nt=t=>{let e;for(e=0;e<A;e++)t.dyn_ltree[2*e]=0;for(e=0;e<E;e++)t.dyn_dtree[2*e]=0;for(e=0;e<19;e++)t.bl_tree[2*e]=0;t.dyn_ltree[512]=1,t.opt_len=t.static_len=0,t.sym_next=t.matches=0},ht=t=>{t.bi_valid>8?et(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0},ot=(t,e,i,a)=>{const s=2*e,r=2*i;return t[s]<t[r]||t[s]===t[r]&&a[e]<=a[i]},lt=(t,e,i)=>{const a=t.heap[i];let s=i<<1;for(;s<=t.heap_len&&(s<t.heap_len&&ot(e,t.heap[s+1],t.heap[s],t.depth)&&s++,!ot(e,a,t.heap[s],t.depth));)t.heap[i]=t.heap[s],i=s,s<<=1;t.heap[i]=a},ut=(t,e,i)=>{let a,s,r,n,h=0;if(0!==t.sym_next)do{a=255&t.pending_buf[t.sym_buf+h++],a+=(255&t.pending_buf[t.sym_buf+h++])<<8,s=t.pending_buf[t.sym_buf+h++],0===a?at(t,s,e):(r=j[s],at(t,r+W+1,e),n=M[r],0!==n&&(s-=G[r],it(t,s,n)),a--,r=tt(a),at(t,r,i),n=P[r],0!==n&&(a-=J[r],it(t,a,n)))}while(h<t.sym_next);at(t,256,e)},dt=(t,e)=>{const i=e.dyn_tree,a=e.stat_desc.static_tree,s=e.stat_desc.has_stree,r=e.stat_desc.elems;let n,h,o,l=-1;for(t.heap_len=0,t.heap_max=573,n=0;n<r;n++)0!==i[2*n]?(t.heap[++t.heap_len]=l=n,t.depth[n]=0):i[2*n+1]=0;for(;t.heap_len<2;)o=t.heap[++t.heap_len]=l<2?++l:0,i[2*o]=1,t.depth[o]=0,t.opt_len--,s&&(t.static_len-=a[2*o+1]);for(e.max_code=l,n=t.heap_len>>1;n>=1;n--)lt(t,i,n);o=r;do{n=t.heap[1],t.heap[1]=t.heap[t.heap_len--],lt(t,i,1),h=t.heap[1],t.heap[--t.heap_max]=n,t.heap[--t.heap_max]=h,i[2*o]=i[2*n]+i[2*h],t.depth[o]=(t.depth[n]>=t.depth[h]?t.depth[n]:t.depth[h])+1,i[2*n+1]=i[2*h+1]=o,t.heap[1]=o++,lt(t,i,1)}while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],((t,e)=>{const i=e.dyn_tree,a=e.max_code,s=e.stat_desc.static_tree,r=e.stat_desc.has_stree,n=e.stat_desc.extra_bits,h=e.stat_desc.extra_base,o=e.stat_desc.max_length;let l,u,d,c,_,f,g=0;for(c=0;c<=$;c++)t.bl_count[c]=0;for(i[2*t.heap[t.heap_max]+1]=0,l=t.heap_max+1;l<573;l++)u=t.heap[l],c=i[2*i[2*u+1]+1]+1,c>o&&(c=o,g++),i[2*u+1]=c,u>a||(t.bl_count[c]++,_=0,u>=h&&(_=n[u-h]),f=i[2*u],t.opt_len+=f*(c+_),r&&(t.static_len+=f*(s[2*u+1]+_)));if(0!==g){do{for(c=o-1;0===t.bl_count[c];)c--;t.bl_count[c]--,t.bl_count[c+1]+=2,t.bl_count[o]--,g-=2}while(g>0);for(c=o;0!==c;c--)for(u=t.bl_count[c];0!==u;)d=t.heap[--l],d>a||(i[2*d+1]!==c&&(t.opt_len+=(c-i[2*d+1])*i[2*d],i[2*d+1]=c),u--)}})(t,e),rt(i,l,t.bl_count)},ct=(t,e,i)=>{let a,s,r=-1,n=e[1],h=0,o=7,l=4;for(0===n&&(o=138,l=3),e[2*(i+1)+1]=65535,a=0;a<=i;a++)s=n,n=e[2*(a+1)+1],++h<o&&s===n||(h<l?t.bl_tree[2*s]+=h:0!==s?(s!==r&&t.bl_tree[2*s]++,t.bl_tree[32]++):h<=10?t.bl_tree[34]++:t.bl_tree[36]++,h=0,r=s,0===n?(o=138,l=3):s===n?(o=6,l=3):(o=7,l=4))},_t=(t,e,i)=>{let a,s,r=-1,n=e[1],h=0,o=7,l=4;for(0===n&&(o=138,l=3),a=0;a<=i;a++)if(s=n,n=e[2*(a+1)+1],!(++h<o&&s===n)){if(h<l)do{at(t,s,t.bl_tree)}while(0!==--h);else 0!==s?(s!==r&&(at(t,s,t.bl_tree),h--),at(t,16,t.bl_tree),it(t,h-3,2)):h<=10?(at(t,17,t.bl_tree),it(t,h-3,3)):(at(t,18,t.bl_tree),it(t,h-11,7));h=0,r=s,0===n?(o=138,l=3):s===n?(o=6,l=3):(o=7,l=4)}};let ft=!1;const gt=(t,e,i,a)=>{it(t,0+(a?1:0),3),ht(t),et(t,i),et(t,~i),i&&t.pending_buf.set(t.window.subarray(e,e+i),t.pending),t.pending+=i};var pt=(t,e,i,a)=>{let s,r,n=0;t.level>0?(2===t.strm.data_type&&(t.strm.data_type=(t=>{let e,i=4093624447;for(e=0;e<=31;e++,i>>>=1)if(1&i&&0!==t.dyn_ltree[2*e])return 0;if(0!==t.dyn_ltree[18]||0!==t.dyn_ltree[20]||0!==t.dyn_ltree[26])return 1;for(e=32;e<W;e++)if(0!==t.dyn_ltree[2*e])return 1;return 0})(t)),dt(t,t.l_desc),dt(t,t.d_desc),n=(t=>{let e;for(ct(t,t.dyn_ltree,t.l_desc.max_code),ct(t,t.dyn_dtree,t.d_desc.max_code),dt(t,t.bl_desc),e=18;e>=3&&0===t.bl_tree[2*N[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e})(t),s=t.opt_len+3+7>>>3,r=t.static_len+3+7>>>3,r<=s&&(s=r)):s=r=i+5,i+4<=s&&-1!==e?gt(t,e,i,a):4===t.strategy||r===s?(it(t,2+(a?1:0),3),ut(t,Z,V)):(it(t,4+(a?1:0),3),((t,e,i,a)=>{let s;for(it(t,e-257,5),it(t,i-1,5),it(t,a-4,4),s=0;s<a;s++)it(t,t.bl_tree[2*N[s]+1],3);_t(t,t.dyn_ltree,e-1),_t(t,t.dyn_dtree,i-1)})(t,t.l_desc.max_code+1,t.d_desc.max_code+1,n+1),ut(t,t.dyn_ltree,t.dyn_dtree)),nt(t),a&&ht(t)},wt={_tr_init:t=>{ft||((()=>{let t,e,i,a,s;const r=new Array(16);for(i=0,a=0;a<28;a++)for(G[a]=i,t=0;t<1<<M[a];t++)j[i++]=a;for(j[i-1]=a,s=0,a=0;a<16;a++)for(J[a]=s,t=0;t<1<<P[a];t++)H[s++]=a;for(s>>=7;a<E;a++)for(J[a]=s<<7,t=0;t<1<<P[a]-7;t++)H[256+s++]=a;for(e=0;e<=$;e++)r[e]=0;for(t=0;t<=143;)Z[2*t+1]=8,t++,r[8]++;for(;t<=255;)Z[2*t+1]=9,t++,r[9]++;for(;t<=279;)Z[2*t+1]=7,t++,r[7]++;for(;t<=287;)Z[2*t+1]=8,t++,r[8]++;for(rt(Z,287,r),t=0;t<E;t++)V[2*t+1]=5,V[2*t]=st(t,5);K=new q(Z,M,257,A,$),Y=new q(V,P,0,E,$),X=new q(new Array(0),L,0,19,7)})(),ft=!0),t.l_desc=new Q(t.dyn_ltree,K),t.d_desc=new Q(t.dyn_dtree,Y),t.bl_desc=new Q(t.bl_tree,X),t.bi_buf=0,t.bi_valid=0,nt(t)},_tr_stored_block:gt,_tr_flush_block:pt,_tr_tally:(t,e,i)=>(t.pending_buf[t.sym_buf+t.sym_next++]=e,t.pending_buf[t.sym_buf+t.sym_next++]=e>>8,t.pending_buf[t.sym_buf+t.sym_next++]=i,0===e?t.dyn_ltree[2*i]++:(t.matches++,e--,t.dyn_ltree[2*(j[i]+W+1)]++,t.dyn_dtree[2*tt(e)]++),t.sym_next===t.sym_end),_tr_align:t=>{it(t,2,3),at(t,256,Z),(t=>{16===t.bi_valid?(et(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)})(t)}};var mt=(t,e,i,a)=>{let s=65535&t,r=t>>>16&65535,n=0;for(;0!==i;){n=i>2e3?2e3:i,i-=n;do{s=s+e[a++]|0,r=r+s|0}while(--n);s%=65521,r%=65521}return s|r<<16};const bt=new Uint32Array((()=>{let t,e=[];for(var i=0;i<256;i++){t=i;for(var a=0;a<8;a++)t=1&t?3988292384^t>>>1:t>>>1;e[i]=t}return e})());var yt=(t,e,i,a)=>{const s=bt,r=a+i;t^=-1;for(let i=a;i<r;i++)t=t>>>8^s[255&(t^e[i])];return-1^t},St={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"},Bt={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:vt,_tr_stored_block:Rt,_tr_flush_block:Ut,_tr_tally:It,_tr_align:Tt}=wt,{Z_NO_FLUSH:xt,Z_PARTIAL_FLUSH:Dt,Z_FULL_FLUSH:kt,Z_FINISH:Ct,Z_BLOCK:Ft,Z_OK:zt,Z_STREAM_END:Ot,Z_STREAM_ERROR:Wt,Z_DATA_ERROR:At,Z_BUF_ERROR:Et,Z_DEFAULT_COMPRESSION:$t,Z_FILTERED:Mt,Z_HUFFMAN_ONLY:Pt,Z_RLE:Lt,Z_FIXED:Nt,Z_DEFAULT_STRATEGY:Zt,Z_UNKNOWN:Vt,Z_DEFLATED:Ht}=Bt,jt=258,Gt=262,Jt=42,qt=113,Kt=666,Yt=(t,e)=>(t.msg=St[e],e),Xt=t=>2*t-(t>4?9:0),Qt=t=>{let e=t.length;for(;--e>=0;)t[e]=0},te=t=>{let e,i,a,s=t.w_size;e=t.hash_size,a=e;do{i=t.head[--a],t.head[a]=i>=s?i-s:0}while(--e);e=s,a=e;do{i=t.prev[--a],t.prev[a]=i>=s?i-s:0}while(--e)};let ee=(t,e,i)=>(e<<t.hash_shift^i)&t.hash_mask;const ie=t=>{const e=t.state;let i=e.pending;i>t.avail_out&&(i=t.avail_out),0!==i&&(t.output.set(e.pending_buf.subarray(e.pending_out,e.pending_out+i),t.next_out),t.next_out+=i,e.pending_out+=i,t.total_out+=i,t.avail_out-=i,e.pending-=i,0===e.pending&&(e.pending_out=0))},ae=(t,e)=>{Ut(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,ie(t.strm)},se=(t,e)=>{t.pending_buf[t.pending++]=e},re=(t,e)=>{t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e},ne=(t,e,i,a)=>{let s=t.avail_in;return s>a&&(s=a),0===s?0:(t.avail_in-=s,e.set(t.input.subarray(t.next_in,t.next_in+s),i),1===t.state.wrap?t.adler=mt(t.adler,e,s,i):2===t.state.wrap&&(t.adler=yt(t.adler,e,s,i)),t.next_in+=s,t.total_in+=s,s)},he=(t,e)=>{let i,a,s=t.max_chain_length,r=t.strstart,n=t.prev_length,h=t.nice_match;const o=t.strstart>t.w_size-Gt?t.strstart-(t.w_size-Gt):0,l=t.window,u=t.w_mask,d=t.prev,c=t.strstart+jt;let _=l[r+n-1],f=l[r+n];t.prev_length>=t.good_match&&(s>>=2),h>t.lookahead&&(h=t.lookahead);do{if(i=e,l[i+n]===f&&l[i+n-1]===_&&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<c);if(a=jt-(c-r),r=c-jt,a>n){if(t.match_start=e,n=a,a>=h)break;_=l[r+n-1],f=l[r+n]}}}while((e=d[e&u])>o&&0!==--s);return n<=t.lookahead?n:t.lookahead},oe=t=>{const e=t.w_size;let i,a,s;do{if(a=t.window_size-t.lookahead-t.strstart,t.strstart>=e+(e-Gt)&&(t.window.set(t.window.subarray(e,e+e-a),0),t.match_start-=e,t.strstart-=e,t.block_start-=e,t.insert>t.strstart&&(t.insert=t.strstart),te(t),a+=e),0===t.strm.avail_in)break;if(i=ne(t.strm,t.window,t.strstart+t.lookahead,a),t.lookahead+=i,t.lookahead+t.insert>=3)for(s=t.strstart-t.insert,t.ins_h=t.window[s],t.ins_h=ee(t,t.ins_h,t.window[s+1]);t.insert&&(t.ins_h=ee(t,t.ins_h,t.window[s+3-1]),t.prev[s&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=s,s++,t.insert--,!(t.lookahead+t.insert<3)););}while(t.lookahead<Gt&&0!==t.strm.avail_in)},le=(t,e)=>{let i,a,s,r=t.pending_buf_size-5>t.w_size?t.w_size:t.pending_buf_size-5,n=0,h=t.strm.avail_in;do{if(i=65535,s=t.bi_valid+42>>3,t.strm.avail_out<s)break;if(s=t.strm.avail_out-s,a=t.strstart-t.block_start,i>a+t.strm.avail_in&&(i=a+t.strm.avail_in),i>s&&(i=s),i<r&&(0===i&&e!==Ct||e===xt||i!==a+t.strm.avail_in))break;n=e===Ct&&i===a+t.strm.avail_in?1:0,Rt(t,0,0,n),t.pending_buf[t.pending-4]=i,t.pending_buf[t.pending-3]=i>>8,t.pending_buf[t.pending-2]=~i,t.pending_buf[t.pending-1]=~i>>8,ie(t.strm),a&&(a>i&&(a=i),t.strm.output.set(t.window.subarray(t.block_start,t.block_start+a),t.strm.next_out),t.strm.next_out+=a,t.strm.avail_out-=a,t.strm.total_out+=a,t.block_start+=a,i-=a),i&&(ne(t.strm,t.strm.output,t.strm.next_out,i),t.strm.next_out+=i,t.strm.avail_out-=i,t.strm.total_out+=i)}while(0===n);return h-=t.strm.avail_in,h&&(h>=t.w_size?(t.matches=2,t.window.set(t.strm.input.subarray(t.strm.next_in-t.w_size,t.strm.next_in),0),t.strstart=t.w_size,t.insert=t.strstart):(t.window_size-t.strstart<=h&&(t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,t.insert>t.strstart&&(t.insert=t.strstart)),t.window.set(t.strm.input.subarray(t.strm.next_in-h,t.strm.next_in),t.strstart),t.strstart+=h,t.insert+=h>t.w_size-t.insert?t.w_size-t.insert:h),t.block_start=t.strstart),t.high_water<t.strstart&&(t.high_water=t.strstart),n?4:e!==xt&&e!==Ct&&0===t.strm.avail_in&&t.strstart===t.block_start?2:(s=t.window_size-t.strstart,t.strm.avail_in>s&&t.block_start>=t.w_size&&(t.block_start-=t.w_size,t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,s+=t.w_size,t.insert>t.strstart&&(t.insert=t.strstart)),s>t.strm.avail_in&&(s=t.strm.avail_in),s&&(ne(t.strm,t.window,t.strstart,s),t.strstart+=s,t.insert+=s>t.w_size-t.insert?t.w_size-t.insert:s),t.high_water<t.strstart&&(t.high_water=t.strstart),s=t.bi_valid+42>>3,s=t.pending_buf_size-s>65535?65535:t.pending_buf_size-s,r=s>t.w_size?t.w_size:s,a=t.strstart-t.block_start,(a>=r||(a||e===Ct)&&e!==xt&&0===t.strm.avail_in&&a<=s)&&(i=a>s?s:a,n=e===Ct&&0===t.strm.avail_in&&i===a?1:0,Rt(t,t.block_start,i,n),t.block_start+=i,ie(t.strm)),n?3:1)},ue=(t,e)=>{let i,a;for(;;){if(t.lookahead<Gt){if(oe(t),t.lookahead<Gt&&e===xt)return 1;if(0===t.lookahead)break}if(i=0,t.lookahead>=3&&(t.ins_h=ee(t,t.ins_h,t.window[t.strstart+3-1]),i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),0!==i&&t.strstart-i<=t.w_size-Gt&&(t.match_length=he(t,i)),t.match_length>=3)if(a=It(t,t.strstart-t.match_start,t.match_length-3),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=3){t.match_length--;do{t.strstart++,t.ins_h=ee(t,t.ins_h,t.window[t.strstart+3-1]),i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart}while(0!==--t.match_length);t.strstart++}else t.strstart+=t.match_length,t.match_length=0,t.ins_h=t.window[t.strstart],t.ins_h=ee(t,t.ins_h,t.window[t.strstart+1]);else a=It(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(a&&(ae(t,!1),0===t.strm.avail_out))return 1}return t.insert=t.strstart<2?t.strstart:2,e===Ct?(ae(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ae(t,!1),0===t.strm.avail_out)?1:2},de=(t,e)=>{let i,a,s;for(;;){if(t.lookahead<Gt){if(oe(t),t.lookahead<Gt&&e===xt)return 1;if(0===t.lookahead)break}if(i=0,t.lookahead>=3&&(t.ins_h=ee(t,t.ins_h,t.window[t.strstart+3-1]),i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),t.prev_length=t.match_length,t.prev_match=t.match_start,t.match_length=2,0!==i&&t.prev_length<t.max_lazy_match&&t.strstart-i<=t.w_size-Gt&&(t.match_length=he(t,i),t.match_length<=5&&(t.strategy===Mt||3===t.match_length&&t.strstart-t.match_start>4096)&&(t.match_length=2)),t.prev_length>=3&&t.match_length<=t.prev_length){s=t.strstart+t.lookahead-3,a=It(t,t.strstart-1-t.prev_match,t.prev_length-3),t.lookahead-=t.prev_length-1,t.prev_length-=2;do{++t.strstart<=s&&(t.ins_h=ee(t,t.ins_h,t.window[t.strstart+3-1]),i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart)}while(0!==--t.prev_length);if(t.match_available=0,t.match_length=2,t.strstart++,a&&(ae(t,!1),0===t.strm.avail_out))return 1}else if(t.match_available){if(a=It(t,0,t.window[t.strstart-1]),a&&ae(t,!1),t.strstart++,t.lookahead--,0===t.strm.avail_out)return 1}else t.match_available=1,t.strstart++,t.lookahead--}return t.match_available&&(a=It(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<2?t.strstart:2,e===Ct?(ae(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ae(t,!1),0===t.strm.avail_out)?1:2};function ce(t,e,i,a,s){this.good_length=t,this.max_lazy=e,this.nice_length=i,this.max_chain=a,this.func=s}const _e=[new ce(0,0,0,0,le),new ce(4,4,8,4,ue),new ce(4,5,16,8,ue),new ce(4,6,32,32,ue),new ce(4,4,16,16,de),new ce(8,16,32,32,de),new ce(8,16,128,128,de),new ce(8,32,128,256,de),new ce(32,128,258,1024,de),new ce(32,258,258,4096,de)];function fe(){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=Ht,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),Qt(this.dyn_ltree),Qt(this.dyn_dtree),Qt(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),Qt(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),Qt(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 ge=t=>{if(!t)return 1;const e=t.state;return!e||e.strm!==t||e.status!==Jt&&57!==e.status&&69!==e.status&&73!==e.status&&91!==e.status&&103!==e.status&&e.status!==qt&&e.status!==Kt?1:0},pe=t=>{if(ge(t))return Yt(t,Wt);t.total_in=t.total_out=0,t.data_type=Vt;const e=t.state;return e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=2===e.wrap?57:e.wrap?Jt:qt,t.adler=2===e.wrap?0:1,e.last_flush=-2,vt(e),zt},we=t=>{const e=pe(t);var i;return e===zt&&((i=t.state).window_size=2*i.w_size,Qt(i.head),i.max_lazy_match=_e[i.level].max_lazy,i.good_match=_e[i.level].good_length,i.nice_match=_e[i.level].nice_length,i.max_chain_length=_e[i.level].max_chain,i.strstart=0,i.block_start=0,i.lookahead=0,i.insert=0,i.match_length=i.prev_length=2,i.match_available=0,i.ins_h=0),e},me=(t,e,i,a,s,r)=>{if(!t)return Wt;let n=1;if(e===$t&&(e=6),a<0?(n=0,a=-a):a>15&&(n=2,a-=16),s<1||s>9||i!==Ht||a<8||a>15||e<0||e>9||r<0||r>Nt||8===a&&1!==n)return Yt(t,Wt);8===a&&(a=9);const h=new fe;return t.state=h,h.strm=t,h.status=Jt,h.wrap=n,h.gzhead=null,h.w_bits=a,h.w_size=1<<h.w_bits,h.w_mask=h.w_size-1,h.hash_bits=s+7,h.hash_size=1<<h.hash_bits,h.hash_mask=h.hash_size-1,h.hash_shift=~~((h.hash_bits+3-1)/3),h.window=new Uint8Array(2*h.w_size),h.head=new Uint16Array(h.hash_size),h.prev=new Uint16Array(h.w_size),h.lit_bufsize=1<<s+6,h.pending_buf_size=4*h.lit_bufsize,h.pending_buf=new Uint8Array(h.pending_buf_size),h.sym_buf=h.lit_bufsize,h.sym_end=3*(h.lit_bufsize-1),h.level=e,h.strategy=r,h.method=i,we(t)};var be={deflateInit:(t,e)=>me(t,e,Ht,15,8,Zt),deflateInit2:me,deflateReset:we,deflateResetKeep:pe,deflateSetHeader:(t,e)=>ge(t)||2!==t.state.wrap?Wt:(t.state.gzhead=e,zt),deflate:(t,e)=>{if(ge(t)||e>Ft||e<0)return t?Yt(t,Wt):Wt;const i=t.state;if(!t.output||0!==t.avail_in&&!t.input||i.status===Kt&&e!==Ct)return Yt(t,0===t.avail_out?Et:Wt);const a=i.last_flush;if(i.last_flush=e,0!==i.pending){if(ie(t),0===t.avail_out)return i.last_flush=-1,zt}else if(0===t.avail_in&&Xt(e)<=Xt(a)&&e!==Ct)return Yt(t,Et);if(i.status===Kt&&0!==t.avail_in)return Yt(t,Et);if(i.status===Jt&&0===i.wrap&&(i.status=qt),i.status===Jt){let e=Ht+(i.w_bits-8<<4)<<8,a=-1;if(a=i.strategy>=Pt||i.level<2?0:i.level<6?1:6===i.level?2:3,e|=a<<6,0!==i.strstart&&(e|=32),e+=31-e%31,re(i,e),0!==i.strstart&&(re(i,t.adler>>>16),re(i,65535&t.adler)),t.adler=1,i.status=qt,ie(t),0!==i.pending)return i.last_flush=-1,zt}if(57===i.status)if(t.adler=0,se(i,31),se(i,139),se(i,8),i.gzhead)se(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)),se(i,255&i.gzhead.time),se(i,i.gzhead.time>>8&255),se(i,i.gzhead.time>>16&255),se(i,i.gzhead.time>>24&255),se(i,9===i.level?2:i.strategy>=Pt||i.level<2?4:0),se(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(se(i,255&i.gzhead.extra.length),se(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(t.adler=yt(t.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=69;else if(se(i,0),se(i,0),se(i,0),se(i,0),se(i,0),se(i,9===i.level?2:i.strategy>=Pt||i.level<2?4:0),se(i,3),i.status=qt,ie(t),0!==i.pending)return i.last_flush=-1,zt;if(69===i.status){if(i.gzhead.extra){let e=i.pending,a=(65535&i.gzhead.extra.length)-i.gzindex;for(;i.pending+a>i.pending_buf_size;){let s=i.pending_buf_size-i.pending;if(i.pending_buf.set(i.gzhead.extra.subarray(i.gzindex,i.gzindex+s),i.pending),i.pending=i.pending_buf_size,i.gzhead.hcrc&&i.pending>e&&(t.adler=yt(t.adler,i.pending_buf,i.pending-e,e)),i.gzindex+=s,ie(t),0!==i.pending)return i.last_flush=-1,zt;e=0,a-=s}let s=new Uint8Array(i.gzhead.extra);i.pending_buf.set(s.subarray(i.gzindex,i.gzindex+a),i.pending),i.pending+=a,i.gzhead.hcrc&&i.pending>e&&(t.adler=yt(t.adler,i.pending_buf,i.pending-e,e)),i.gzindex=0}i.status=73}if(73===i.status){if(i.gzhead.name){let e,a=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>a&&(t.adler=yt(t.adler,i.pending_buf,i.pending-a,a)),ie(t),0!==i.pending)return i.last_flush=-1,zt;a=0}e=i.gzindex<i.gzhead.name.length?255&i.gzhead.name.charCodeAt(i.gzindex++):0,se(i,e)}while(0!==e);i.gzhead.hcrc&&i.pending>a&&(t.adler=yt(t.adler,i.pending_buf,i.pending-a,a)),i.gzindex=0}i.status=91}if(91===i.status){if(i.gzhead.comment){let e,a=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>a&&(t.adler=yt(t.adler,i.pending_buf,i.pending-a,a)),ie(t),0!==i.pending)return i.last_flush=-1,zt;a=0}e=i.gzindex<i.gzhead.comment.length?255&i.gzhead.comment.charCodeAt(i.gzindex++):0,se(i,e)}while(0!==e);i.gzhead.hcrc&&i.pending>a&&(t.adler=yt(t.adler,i.pending_buf,i.pending-a,a))}i.status=103}if(103===i.status){if(i.gzhead.hcrc){if(i.pending+2>i.pending_buf_size&&(ie(t),0!==i.pending))return i.last_flush=-1,zt;se(i,255&t.adler),se(i,t.adler>>8&255),t.adler=0}if(i.status=qt,ie(t),0!==i.pending)return i.last_flush=-1,zt}if(0!==t.avail_in||0!==i.lookahead||e!==xt&&i.status!==Kt){let a=0===i.level?le(i,e):i.strategy===Pt?((t,e)=>{let i;for(;;){if(0===t.lookahead&&(oe(t),0===t.lookahead)){if(e===xt)return 1;break}if(t.match_length=0,i=It(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,i&&(ae(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===Ct?(ae(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ae(t,!1),0===t.strm.avail_out)?1:2})(i,e):i.strategy===Lt?((t,e)=>{let i,a,s,r;const n=t.window;for(;;){if(t.lookahead<=jt){if(oe(t),t.lookahead<=jt&&e===xt)return 1;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=3&&t.strstart>0&&(s=t.strstart-1,a=n[s],a===n[++s]&&a===n[++s]&&a===n[++s])){r=t.strstart+jt;do{}while(a===n[++s]&&a===n[++s]&&a===n[++s]&&a===n[++s]&&a===n[++s]&&a===n[++s]&&a===n[++s]&&a===n[++s]&&s<r);t.match_length=jt-(r-s),t.match_length>t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=3?(i=It(t,1,t.match_length-3),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(i=It(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),i&&(ae(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===Ct?(ae(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ae(t,!1),0===t.strm.avail_out)?1:2})(i,e):_e[i.level].func(i,e);if(3!==a&&4!==a||(i.status=Kt),1===a||3===a)return 0===t.avail_out&&(i.last_flush=-1),zt;if(2===a&&(e===Dt?Tt(i):e!==Ft&&(Rt(i,0,0,!1),e===kt&&(Qt(i.head),0===i.lookahead&&(i.strstart=0,i.block_start=0,i.insert=0))),ie(t),0===t.avail_out))return i.last_flush=-1,zt}return e!==Ct?zt:i.wrap<=0?Ot:(2===i.wrap?(se(i,255&t.adler),se(i,t.adler>>8&255),se(i,t.adler>>16&255),se(i,t.adler>>24&255),se(i,255&t.total_in),se(i,t.total_in>>8&255),se(i,t.total_in>>16&255),se(i,t.total_in>>24&255)):(re(i,t.adler>>>16),re(i,65535&t.adler)),ie(t),i.wrap>0&&(i.wrap=-i.wrap),0!==i.pending?zt:Ot)},deflateEnd:t=>{if(ge(t))return Wt;const e=t.state.status;return t.state=null,e===qt?Yt(t,At):zt},deflateSetDictionary:(t,e)=>{let i=e.length;if(ge(t))return Wt;const a=t.state,s=a.wrap;if(2===s||1===s&&a.status!==Jt||a.lookahead)return Wt;if(1===s&&(t.adler=mt(t.adler,e,i,0)),a.wrap=0,i>=a.w_size){0===s&&(Qt(a.head),a.strstart=0,a.block_start=0,a.insert=0);let t=new Uint8Array(a.w_size);t.set(e.subarray(i-a.w_size,i),0),e=t,i=a.w_size}const r=t.avail_in,n=t.next_in,h=t.input;for(t.avail_in=i,t.next_in=0,t.input=e,oe(a);a.lookahead>=3;){let t=a.strstart,e=a.lookahead-2;do{a.ins_h=ee(a,a.ins_h,a.window[t+3-1]),a.prev[t&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=t,t++}while(--e);a.strstart=t,a.lookahead=2,oe(a)}return a.strstart+=a.lookahead,a.block_start=a.strstart,a.insert=a.lookahead,a.lookahead=0,a.match_length=a.prev_length=2,a.match_available=0,t.next_in=n,t.input=h,t.avail_in=r,a.wrap=s,zt},deflateInfo:"pako deflate (from Nodeca project)"};const ye=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var Se=function(t){const e=Array.prototype.slice.call(arguments,1);for(;e.length;){const i=e.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(const e in i)ye(i,e)&&(t[e]=i[e])}}return t},Be=t=>{let e=0;for(let i=0,a=t.length;i<a;i++)e+=t[i].length;const i=new Uint8Array(e);for(let e=0,a=0,s=t.length;e<s;e++){let s=t[e];i.set(s,a),a+=s.length}return i};let ve=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(t){ve=!1}const Re=new Uint8Array(256);for(let t=0;t<256;t++)Re[t]=t>=252?6:t>=248?5:t>=240?4:t>=224?3:t>=192?2:1;Re[254]=Re[254]=1;var Ue=t=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(t);let e,i,a,s,r,n=t.length,h=0;for(s=0;s<n;s++)i=t.charCodeAt(s),55296==(64512&i)&&s+1<n&&(a=t.charCodeAt(s+1),56320==(64512&a)&&(i=65536+(i-55296<<10)+(a-56320),s++)),h+=i<128?1:i<2048?2:i<65536?3:4;for(e=new Uint8Array(h),r=0,s=0;r<h;s++)i=t.charCodeAt(s),55296==(64512&i)&&s+1<n&&(a=t.charCodeAt(s+1),56320==(64512&a)&&(i=65536+(i-55296<<10)+(a-56320),s++)),i<128?e[r++]=i:i<2048?(e[r++]=192|i>>>6,e[r++]=128|63&i):i<65536?(e[r++]=224|i>>>12,e[r++]=128|i>>>6&63,e[r++]=128|63&i):(e[r++]=240|i>>>18,e[r++]=128|i>>>12&63,e[r++]=128|i>>>6&63,e[r++]=128|63&i);return e};var Ie=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 Te=Object.prototype.toString,{Z_NO_FLUSH:xe,Z_SYNC_FLUSH:De,Z_FULL_FLUSH:ke,Z_FINISH:Ce,Z_OK:Fe,Z_STREAM_END:ze,Z_DEFAULT_COMPRESSION:Oe,Z_DEFAULT_STRATEGY:We,Z_DEFLATED:Ae}=Bt;function Ee(t){this.options=Se({level:Oe,method:Ae,chunkSize:16384,windowBits:15,memLevel:8,strategy:We},t||{});let e=this.options;e.raw&&e.windowBits>0?e.windowBits=-e.windowBits:e.gzip&&e.windowBits>0&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new Ie,this.strm.avail_out=0;let i=be.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(i!==Fe)throw new Error(St[i]);if(e.header&&be.deflateSetHeader(this.strm,e.header),e.dictionary){let t;if(t="string"==typeof e.dictionary?Ue(e.dictionary):"[object ArrayBuffer]"===Te.call(e.dictionary)?new Uint8Array(e.dictionary):e.dictionary,i=be.deflateSetDictionary(this.strm,t),i!==Fe)throw new Error(St[i]);this._dict_set=!0}}Ee.prototype.push=function(t,e){const i=this.strm,a=this.options.chunkSize;let s,r;if(this.ended)return!1;for(r=e===~~e?e:!0===e?Ce:xe,"string"==typeof t?i.input=Ue(t):"[object ArrayBuffer]"===Te.call(t)?i.input=new Uint8Array(t):i.input=t,i.next_in=0,i.avail_in=i.input.length;;)if(0===i.avail_out&&(i.output=new Uint8Array(a),i.next_out=0,i.avail_out=a),(r===De||r===ke)&&i.avail_out<=6)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else{if(s=be.deflate(i,r),s===ze)return i.next_out>0&&this.onData(i.output.subarray(0,i.next_out)),s=be.deflateEnd(this.strm),this.onEnd(s),this.ended=!0,s===Fe;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},Ee.prototype.onData=function(t){this.chunks.push(t)},Ee.prototype.onEnd=function(t){t===Fe&&(this.result=Be(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};var $e={deflate:function(t,e){const i=new Ee(e);if(i.push(t,!0),i.err)throw i.msg||St[i.err];return i.result}};const{deflate:Me}=$e;var Pe=Me;const Le={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}},Ne=(t,...e)=>{let i=0;if(t.replace(/[<>]/,"").length!=e.length)throw"Pack format to Argument count mismatch";const a=[];let s=!0;for(let a=0;a<t.length;a++)"<"==t[a]?s=!0:">"==t[a]?s=!1:(r(t[a],e[i]),i++);function r(t,e){if(!(t in Le))throw"Unhandled character '"+t+"' in pack format";const i=Le[t].bytes,r=new DataView(new ArrayBuffer(i));Le[t].p.bind(r)(0,e,s);for(let t=0;t<i;t++)a.push(r.getUint8(t))}return a},Ze=(t,e)=>{let i=0;const a=[];let s=!0;for(const e of t)"<"==e?s=!0:">"==e?s=!1:r(e);function r(t){if(!(t in Le))throw"Unhandled character '"+t+"' in unpack format";const r=Le[t].bytes,n=new DataView(new ArrayBuffer(r));for(let t=0;t<r;t++)n.setUint8(t,255&e[i+t]);const h=Le[t].u.bind(n);a.push(h(0,s)),i+=r}return a};class Ve extends EventTarget{constructor(t,e,i){super(),this.port=t,this.logger=e,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=h,this._isESP32S2NativeUSB=!1,this._initializationSucceeded=!1,this.__commandLock=Promise.resolve([0,[]]),this.__isReconfiguring=!1,this.__abandonCurrentOperation=!1,this.__adaptiveBlockMultiplier=1,this.__adaptiveMaxInFlightMultiplier=1,this.__consecutiveSuccessfulChunks=0,this.__lastAdaptiveAdjustment=0,this.__isCDCDevice=!1,this.state_DTR=!1,this.__writeChain=Promise.resolve()}get chipFamily(){return this._parent?this._parent.chipFamily:this.__chipFamily}set chipFamily(t){this._parent?this._parent.chipFamily=t:this.__chipFamily=t}get chipName(){return this._parent?this._parent.chipName:this.__chipName}set chipName(t){this._parent?this._parent.chipName=t:this.__chipName=t}get chipRevision(){return this._parent?this._parent.chipRevision:this.__chipRevision}set chipRevision(t){this._parent?this._parent.chipRevision=t:this.__chipRevision=t}get chipVariant(){return this._parent?this._parent.chipVariant:this.__chipVariant}set chipVariant(t){this._parent?this._parent.chipVariant=t:this.__chipVariant=t}get _inputBuffer(){return this._parent?this._parent._inputBuffer:this.__inputBuffer}get _inputBufferReadIndex(){return this._parent?this._parent._inputBufferReadIndex:this.__inputBufferReadIndex||0}set _inputBufferReadIndex(t){this._parent?this._parent._inputBufferReadIndex=t:this.__inputBufferReadIndex=t}get _inputBufferAvailable(){return this._inputBuffer.length-this._inputBufferReadIndex}_readByte(){if(!(this._inputBufferReadIndex>=this._inputBuffer.length))return this._inputBuffer[this._inputBufferReadIndex++]}_clearInputBuffer(){this._inputBuffer.length=0,this._inputBufferReadIndex=0}_compactInputBuffer(){this._inputBufferReadIndex>1e3&&this._inputBufferReadIndex>this._inputBuffer.length/2&&(this._inputBuffer.splice(0,this._inputBufferReadIndex),this._inputBufferReadIndex=0)}get _totalBytesRead(){return this._parent?this._parent._totalBytesRead:this.__totalBytesRead||0}set _totalBytesRead(t){this._parent?this._parent._totalBytesRead=t:this.__totalBytesRead=t}get _commandLock(){return this._parent?this._parent._commandLock:this.__commandLock}set _commandLock(t){this._parent?this._parent._commandLock=t:this.__commandLock=t}get _isReconfiguring(){return this._parent?this._parent._isReconfiguring:this.__isReconfiguring}set _isReconfiguring(t){this._parent?this._parent._isReconfiguring=t:this.__isReconfiguring=t}get _abandonCurrentOperation(){return this._parent?this._parent._abandonCurrentOperation:this.__abandonCurrentOperation}set _abandonCurrentOperation(t){this._parent?this._parent._abandonCurrentOperation=t:this.__abandonCurrentOperation=t}get _adaptiveBlockMultiplier(){return this._parent?this._parent._adaptiveBlockMultiplier:this.__adaptiveBlockMultiplier}set _adaptiveBlockMultiplier(t){this._parent?this._parent._adaptiveBlockMultiplier=t:this.__adaptiveBlockMultiplier=t}get _adaptiveMaxInFlightMultiplier(){return this._parent?this._parent._adaptiveMaxInFlightMultiplier:this.__adaptiveMaxInFlightMultiplier}set _adaptiveMaxInFlightMultiplier(t){this._parent?this._parent._adaptiveMaxInFlightMultiplier=t:this.__adaptiveMaxInFlightMultiplier=t}get _consecutiveSuccessfulChunks(){return this._parent?this._parent._consecutiveSuccessfulChunks:this.__consecutiveSuccessfulChunks}set _consecutiveSuccessfulChunks(t){this._parent?this._parent._consecutiveSuccessfulChunks=t:this.__consecutiveSuccessfulChunks=t}get _lastAdaptiveAdjustment(){return this._parent?this._parent._lastAdaptiveAdjustment:this.__lastAdaptiveAdjustment}set _lastAdaptiveAdjustment(t){this._parent?this._parent._lastAdaptiveAdjustment=t:this.__lastAdaptiveAdjustment=t}get _isCDCDevice(){return this._parent?this._parent._isCDCDevice:this.__isCDCDevice}set _isCDCDevice(t){this._parent?this._parent._isCDCDevice=t:this.__isCDCDevice=t}detectUSBSerialChip(t,e){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}}}[t];return i&&i[e]?i[e]:{name:`Unknown (VID: 0x${t.toString(16)}, PID: 0x${e.toString(16)})`}}async initialize(){if(!this._parent){this.__inputBuffer=[],this.__inputBufferReadIndex=0,this.__totalBytesRead=0;const t=this.port.getInfo();if(t.usbVendorId&&t.usbProductId){const e=this.detectUSBSerialChip(t.usbVendorId,t.usbProductId);this.logger.log(`USB-Serial: ${e.name} (VID: 0x${t.usbVendorId.toString(16)}, PID: 0x${t.usbProductId.toString(16)})`),e.maxBaudrate&&(this._maxUSBSerialBaudrate=e.maxBaudrate,this.logger.log(`Max baudrate: ${e.maxBaudrate}`)),12346===t.usbVendorId&&2===t.usbProductId&&(this._isESP32S2NativeUSB=!0),(12346===t.usbVendorId||6790===t.usbVendorId&&21971===t.usbProductId)&&(this._isCDCDevice=!0)}this.readLoop()}await this.connectWithResetStrategies(),await this.detectChip();const t=C(this.getChipFamily()),e=t.macFuse;for(let t=0;t<4;t++)this._efuses[t]=await this.readRegister(e+4*t);this.logger.log(`Chip type ${this.chipName}`),this.logger.debug(`Bootloader flash offset: 0x${t.flashOffs.toString(16)}`),this._initializationSucceeded=!0}async detectChip(){try{const t=(await this.getSecurityInfo()).chipId,e=R[t];if(e)return this.chipName=e.name,this.chipFamily=e.family,this.chipFamily===B&&(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: ${t} (${this.chipName})`);this.logger.debug(`Unknown IMAGE_CHIP_ID: ${t}, falling back to magic value detection`)}catch(t){this.logger.debug(`GET_SECURITY_INFO failed, using magic value detection: ${t}`),await this.drainInputBuffer(200),this._clearInputBuffer(),await s(x);try{await this.sync()}catch(t){this.logger.debug(`Re-sync after GET_SECURITY_INFO failure: ${t}`)}}const t=await this.readRegister(1073745920),e=U[t>>>0];if(void 0===e)throw new Error(`Unknown Chip: Hex: ${a(t>>>0,8).toLowerCase()} Number: ${t}`);this.chipName=e.name,this.chipFamily=e.family,this.chipFamily===B&&(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: ${a(t>>>0,8)} (${this.chipName})`)}async getChipRevision(){if(this.chipFamily!==B)return 0;const t=await this.readRegister(1343410252);return 100*((t>>23&1)<<2|t>>4&3)+(15&t)}async getSecurityInfo(){const[,t]=await this.checkCommand(20,[],0);if(0===t.length)throw new Error("GET_SECURITY_INFO not supported or returned empty response");if(t.length<12)throw new Error(`Invalid security info response length: ${t.length} (expected at least 12 bytes)`);return{flags:Ze("<I",t.slice(0,4))[0],flashCryptCnt:t[4],keyPurposes:Array.from(t.slice(5,12)),chipId:t.length>=16?Ze("<I",t.slice(12,16))[0]:0,apiVersion:t.length>=20?Ze("<I",t.slice(16,20))[0]:0}}async getMacAddress(){if(!this._initializationSucceeded)throw new Error("getMacAddress() requires initialize() to have completed successfully");return this.macAddr().map(t=>t.toString(16).padStart(2,"0").toUpperCase()).join(":")}async readLoop(){this.debug&&this.logger.debug("Starting read loop"),this._reader=this.port.readable.getReader();try{let t=!0;for(;t;){const{value:e,done:i}=await this._reader.read();if(i){this._reader.releaseLock(),t=!1;break}if(!e||0===e.length)continue;const a=Array.from(e);Array.prototype.push.apply(this._inputBuffer,a),this._totalBytesRead+=e.length}}catch{this.logger.error("Read loop got disconnected")}finally{this._isReconfiguring=!1}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(t=100){return new Promise(e=>setTimeout(e,t))}async setRTS(t){await this.port.setSignals({requestToSend:t}),await this.setDTR(this.state_DTR)}async setDTR(t){this.state_DTR=t,await this.port.setSignals({dataTerminalReady:t})}async hardResetUSBJTAGSerial(){await this.setRTS(!1),await this.setDTR(!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),await this.sleep(200)}async hardResetClassic(){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),await this.sleep(200)}async setRTSWebUSB(t){await this.port.setSignals({requestToSend:t,dataTerminalReady:this.state_DTR})}async setDTRWebUSB(t){this.state_DTR=t,await this.port.setSignals({dataTerminalReady:t,requestToSend:void 0})}async setDTRandRTSWebUSB(t,e){this.state_DTR=t,await this.port.setSignals({dataTerminalReady:t,requestToSend:e})}async hardResetUSBJTAGSerialWebUSB(){await this.setRTSWebUSB(!1),await this.setDTRWebUSB(!1),await this.sleep(100),await this.setDTRWebUSB(!0),await this.setRTSWebUSB(!1),await this.sleep(100),await this.setRTSWebUSB(!0),await this.setDTRWebUSB(!1),await this.setRTSWebUSB(!0),await this.sleep(100),await this.setDTRWebUSB(!1),await this.setRTSWebUSB(!1),await this.sleep(200)}async hardResetUSBJTAGSerialInvertedDTRWebUSB(){await this.setRTSWebUSB(!1),await this.setDTRWebUSB(!0),await this.sleep(100),await this.setDTRWebUSB(!1),await this.setRTSWebUSB(!1),await this.sleep(100),await this.setRTSWebUSB(!0),await this.setDTRWebUSB(!0),await this.setRTSWebUSB(!0),await this.sleep(100),await this.setDTRWebUSB(!0),await this.setRTSWebUSB(!1),await this.sleep(200)}async hardResetClassicWebUSB(){await this.setDTRWebUSB(!1),await this.setRTSWebUSB(!0),await this.sleep(100),await this.setDTRWebUSB(!0),await this.setRTSWebUSB(!1),await this.sleep(50),await this.setDTRWebUSB(!1),await this.sleep(200)}async hardResetUnixTightWebUSB(){await this.setDTRandRTSWebUSB(!1,!1),await this.setDTRandRTSWebUSB(!0,!0),await this.setDTRandRTSWebUSB(!1,!0),await this.sleep(100),await this.setDTRandRTSWebUSB(!0,!1),await this.sleep(50),await this.setDTRandRTSWebUSB(!1,!1),await this.setDTRWebUSB(!1),await this.sleep(200)}async hardResetClassicLongDelayWebUSB(){await this.setDTRWebUSB(!1),await this.setRTSWebUSB(!0),await this.sleep(500),await this.setDTRWebUSB(!0),await this.setRTSWebUSB(!1),await this.sleep(200),await this.setDTRWebUSB(!1),await this.sleep(500)}async hardResetClassicShortDelayWebUSB(){await this.setDTRWebUSB(!1),await this.setRTSWebUSB(!0),await this.sleep(50),await this.setDTRWebUSB(!0),await this.setRTSWebUSB(!1),await this.sleep(25),await this.setDTRWebUSB(!1),await this.sleep(100)}async hardResetInvertedWebUSB(){await this.setDTRWebUSB(!0),await this.setRTSWebUSB(!1),await this.sleep(100),await this.setDTRWebUSB(!1),await this.setRTSWebUSB(!0),await this.sleep(50),await this.setDTRWebUSB(!0),await this.sleep(200)}async hardResetInvertedDTRWebUSB(){await this.setDTRWebUSB(!0),await this.setRTSWebUSB(!0),await this.sleep(100),await this.setDTRWebUSB(!1),await this.setRTSWebUSB(!1),await this.sleep(50),await this.setDTRWebUSB(!0),await this.sleep(200)}async hardResetInvertedRTSWebUSB(){await this.setDTRWebUSB(!1),await this.setRTSWebUSB(!1),await this.sleep(100),await this.setDTRWebUSB(!0),await this.setRTSWebUSB(!0),await this.sleep(50),await this.setDTRWebUSB(!1),await this.sleep(200)}isWebUSB(){return!0===this.port.isWebUSB}async connectWithResetStrategies(){const t=this.port.getInfo(),e=4097===t.usbProductId,i=12346===t.usbVendorId,a=[],r=this;if(this.isWebUSB()){const s=!e&&!i,n=4292===t.usbVendorId,h=6790===t.usbVendorId,o=12346===t.usbVendorId&&2===t.usbProductId;(e||i)&&(o?(a.push({name:"USB-JTAG/Serial (WebUSB) - ESP32-S2",fn:async function(){return await r.hardResetUSBJTAGSerialWebUSB()}}),a.push({name:"USB-JTAG/Serial Inverted DTR (WebUSB) - ESP32-S2",fn:async function(){return await r.hardResetUSBJTAGSerialInvertedDTRWebUSB()}}),a.push({name:"UnixTight (WebUSB) - ESP32-S2 CDC",fn:async function(){return await r.hardResetUnixTightWebUSB()}}),a.push({name:"Classic (WebUSB) - ESP32-S2 CDC",fn:async function(){return await r.hardResetClassicWebUSB()}})):(a.push({name:"USB-JTAG/Serial Inverted DTR (WebUSB)",fn:async function(){return await r.hardResetUSBJTAGSerialInvertedDTRWebUSB()}}),a.push({name:"USB-JTAG/Serial (WebUSB)",fn:async function(){return await r.hardResetUSBJTAGSerialWebUSB()}}),a.push({name:"Inverted DTR Classic (WebUSB)",fn:async function(){return await r.hardResetInvertedDTRWebUSB()}}))),s&&(h?(a.push({name:"UnixTight (WebUSB) - CH34x",fn:async function(){return await r.hardResetUnixTightWebUSB()}}),a.push({name:"Classic (WebUSB) - CH34x",fn:async function(){return await r.hardResetClassicWebUSB()}}),a.push({name:"Inverted Both (WebUSB) - CH34x",fn:async function(){return await r.hardResetInvertedWebUSB()}}),a.push({name:"Inverted RTS (WebUSB) - CH34x",fn:async function(){return await r.hardResetInvertedRTSWebUSB()}}),a.push({name:"Inverted DTR (WebUSB) - CH34x",fn:async function(){return await r.hardResetInvertedDTRWebUSB()}})):n?(a.push({name:"UnixTight (WebUSB) - CP2102",fn:async function(){return await r.hardResetUnixTightWebUSB()}}),a.push({name:"Classic (WebUSB) - CP2102",fn:async function(){return await r.hardResetClassicWebUSB()}}),a.push({name:"Inverted Both (WebUSB) - CP2102",fn:async function(){return await r.hardResetInvertedWebUSB()}}),a.push({name:"Inverted RTS (WebUSB) - CP2102",fn:async function(){return await r.hardResetInvertedRTSWebUSB()}}),a.push({name:"Inverted DTR (WebUSB) - CP2102",fn:async function(){return await r.hardResetInvertedDTRWebUSB()}})):(a.push({name:"UnixTight (WebUSB)",fn:async function(){return await r.hardResetUnixTightWebUSB()}}),a.push({name:"Classic (WebUSB)",fn:async function(){return await r.hardResetClassicWebUSB()}}),a.push({name:"Inverted Both (WebUSB)",fn:async function(){return await r.hardResetInvertedWebUSB()}}),a.push({name:"Inverted RTS (WebUSB)",fn:async function(){return await r.hardResetInvertedRTSWebUSB()}}),a.push({name:"Inverted DTR (WebUSB)",fn:async function(){return await r.hardResetInvertedDTRWebUSB()}}))),n||o||(6790!==t.usbVendorId&&a.push({name:"Classic (WebUSB)",fn:async function(){return await r.hardResetClassicWebUSB()}}),a.push({name:"UnixTight (WebUSB)",fn:async function(){return await r.hardResetUnixTightWebUSB()}}),a.push({name:"Classic Long Delay (WebUSB)",fn:async function(){return await r.hardResetClassicLongDelayWebUSB()}}),a.push({name:"Classic Short Delay (WebUSB)",fn:async function(){return await r.hardResetClassicShortDelayWebUSB()}}),e||i||a.push({name:"USB-JTAG/Serial fallback (WebUSB)",fn:async function(){return await r.hardResetUSBJTAGSerialWebUSB()}}))}else(e||i)&&a.push({name:"USB-JTAG/Serial",fn:async function(){return await r.hardResetUSBJTAGSerial()}}),a.push({name:"Classic",fn:async function(){return await r.hardResetClassic()}}),e||i||a.push({name:"USB-JTAG/Serial (fallback)",fn:async function(){return await r.hardResetUSBJTAGSerial()}});let n=null;for(const t of a)try{if(!this.connected||!this.port.writable){this.logger.log(`Port disconnected, skipping ${t.name} reset`);continue}this._abandonCurrentOperation=!1,await t.fn();if(await this.syncWithTimeout(3e3))return void this.logger.log(`Connected successfully with ${t.name} reset.`);throw new Error("Sync timeout or abandoned")}catch(e){if(n=e,this.logger.log(`${t.name} reset failed: ${e.message}`),this._abandonCurrentOperation=!0,await s(100),!this.connected||!this.port.writable){this.logger.log("Port disconnected during reset attempt");break}this._clearInputBuffer(),await this.drainInputBuffer(200),await this.flushSerialBuffers()}throw new Error(`Couldn't sync to ESP. Try resetting manually. Last error: ${null==n?void 0:n.message}`)}async hardReset(t=!1){t?4097===this.port.getInfo().usbProductId?(await this.hardResetUSBJTAGSerial(),this.logger.log("USB-JTAG/Serial reset.")):this.isWebUSB()?(await this.hardResetClassicWebUSB(),this.logger.log("Classic reset (WebUSB/Android).")):(await this.hardResetClassic(),this.logger.log("Classic reset.")):this.isWebUSB()?(await this.setRTS(!0),await this.sleep(200),await this.setRTS(!1),await this.sleep(200),this.logger.log("Hard reset (WebUSB).")):(await this.setRTS(!0),await this.sleep(100),await this.setRTS(!1),this.logger.log("Hard reset.")),await new Promise(t=>setTimeout(t,1e3))}macAddr(){const t=new Array(6).fill(0),e=this._efuses[0],i=this._efuses[1],a=this._efuses[2],s=this._efuses[3];let r;if(this.chipFamily==u){if(0!=s)r=[s>>16&255,s>>8&255,255&s];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];t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=i>>8&255,t[4]=255&i,t[5]=e>>24&255}else if(this.chipFamily==d)t[0]=a>>8&255,t[1]=255&a,t[2]=i>>24&255,t[3]=i>>16&255,t[4]=i>>8&255,t[5]=255&i;else{if(this.chipFamily!=c&&this.chipFamily!=_&&this.chipFamily!=f&&this.chipFamily!=g&&this.chipFamily!=p&&this.chipFamily!=w&&this.chipFamily!=m&&this.chipFamily!=b&&this.chipFamily!=y&&this.chipFamily!=S&&this.chipFamily!=B&&this.chipFamily!=v)throw new Error("Unknown chip family");t[0]=i>>8&255,t[1]=255&i,t[2]=e>>24&255,t[3]=e>>16&255,t[4]=e>>8&255,t[5]=255&e}return t}async readRegister(t){this.debug&&this.logger.debug("Reading from Register "+a(t,8));const e=Ne("<I",t);await this.sendCommand(10,e);const[i]=await this.getResponse(10);return i}async checkCommand(t,e,i=0,s=3e3){const r=async()=>{s=Math.min(s,3e5),await this.sendCommand(t,e,i);const[r,n]=await this.getResponse(t,s);if(null===n)throw new Error("Didn't get enough status bytes");let h=n,o=0;if(this.IS_STUB||this.chipFamily==u?o=2:[d,c,_,f,g,p,w,m,b,y,S,B,v].includes(this.chipFamily)||20===t?o=4:[2,4].includes(h.length)?o=h.length:(o=2,this.logger.debug(`Unknown chip family, defaulting to 2-byte status (opcode: ${a(t)}, data.length: ${h.length})`)),h.length<o)throw new Error("Didn't get enough status bytes");const l=h.slice(-o,h.length);if(h=h.slice(0,-o),this.debug&&(this.logger.debug("status",l),this.logger.debug("value",r),this.logger.debug("data",h)),1==l[0])throw 5==l[1]?(await this.drainInputBuffer(200),new Error("Invalid (unsupported) command "+a(t))):new Error("Command failure error code "+a(l[1]));return[r,h]};return this._commandLock=this._commandLock.then(r,r),this._commandLock}async sendCommand(e,i,a=0){const s=t([...Ne("<BBHI",0,e,i.length,a),...i]);this.debug&&this.logger.debug(`Writing ${s.length} byte${1==s.length?"":"s"}:`,s),await this.writeToStream(s)}async readPacket(t){let e=null,r=!1;if(this._isCDCDevice){const n=Date.now();for(;;){if(this._abandonCurrentOperation)throw new F("Operation abandoned (reset strategy timeout)");if(Date.now()-n>t){throw new F("Timed out waiting for packet "+(null===e?"header":"content"))}if(0!==this._inputBufferAvailable)for(;this._inputBufferAvailable>0;){const t=this._readByte();if(null===e){if(192!=t)throw this.debug&&(this.logger.debug("Read invalid data: "+a(t)),this.logger.debug("Remaining data in serial buffer: "+i(this._inputBuffer))),new F("Invalid head of packet ("+a(t)+")");e=[]}else if(r)if(r=!1,220==t)e.push(192);else{if(221!=t)throw this.debug&&(this.logger.debug("Read invalid data: "+a(t)),this.logger.debug("Remaining data in serial buffer: "+i(this._inputBuffer))),new F("Invalid SLIP escape (0xdb, "+a(t)+")");e.push(219)}else if(219==t)r=!0;else{if(192==t)return this.debug&&this.logger.debug("Received full packet: "+i(e)),this._compactInputBuffer(),e;e.push(t)}}else await s(1)}}else{let n=[];for(;;){if(this._abandonCurrentOperation)throw new F("Operation abandoned (reset strategy timeout)");const h=Date.now();for(n=[];Date.now()-h<t;){if(this._inputBufferAvailable>0){n.push(this._readByte());break}await s(1)}if(0==n.length){throw new F("Timed out waiting for packet "+(null===e?"header":"content"))}this.debug&&this.logger.debug("Read "+n.length+" bytes: "+i(n));for(const t of n)if(null===e){if(192!=t)throw this.debug&&(this.logger.debug("Read invalid data: "+a(t)),this.logger.debug("Remaining data in serial buffer: "+i(this._inputBuffer))),new F("Invalid head of packet ("+a(t)+")");e=[]}else if(r)if(r=!1,220==t)e.push(192);else{if(221!=t)throw this.debug&&(this.logger.debug("Read invalid data: "+a(t)),this.logger.debug("Remaining data in serial buffer: "+i(this._inputBuffer))),new F("Invalid SLIP escape (0xdb, "+a(t)+")");e.push(219)}else if(219==t)r=!0;else{if(192==t)return this.debug&&this.logger.debug("Received full packet: "+i(e)),this._compactInputBuffer(),e;e.push(t)}}}}async getResponse(t,e=3e3){for(let i=0;i<100;i++){const i=await this.readPacket(e);if(i.length<8)continue;const[s,r,,n]=Ze("<BBHI",i.slice(0,8));if(1!=s)continue;const h=i.slice(8);if(null==t||r==t)return[n,h];if(0!=h[0]&&5==h[1])throw await this.drainInputBuffer(200),new Error(`Invalid (unsupported) command ${a(t)}`)}throw new Error("Response doesn't match request")}checksum(t,e=239){for(const i of t)e^=i;return e}async setBaudrate(t){if(this.chipFamily==u)throw new Error("Changing baud rate is not supported on the ESP8266");try{const e=Ne("<II",t,this.IS_STUB?h:0);await this.checkCommand(15,e)}catch(e){throw this.logger.error(`Baudrate change error: ${e}`),new Error(`Unable to change the baud rate to ${t}: No response from set baud rate command.`)}this._parent?await this._parent.reconfigurePort(t):await this.reconfigurePort(t),await s(x),this._parent?this._parent._currentBaudRate=t:this._currentBaudRate=t;const e=this._parent?this._parent._maxUSBSerialBaudrate:this._maxUSBSerialBaudrate;e&&t>e&&(this.logger.log(`⚠️ WARNING: Baudrate ${t} exceeds USB-Serial chip limit (${e})!`),this.logger.log("⚠️ This may cause data corruption or connection failures!")),this.logger.log(`Changed baud rate to ${t}`)}async reconfigurePort(t){var e;this._isReconfiguring=!0;try{try{await this._writeChain}catch(t){this.logger.debug(`Pending write error during reconfigure: ${t}`)}if(this.isWebUSB()){const e=this.port.getInfo(),i=6790===e.usbVendorId&&21971===e.usbProductId;if(!i&&"function"==typeof this.port.setBaudRate)return await this.port.setBaudRate(t),void await s(100)}if(this._writer){try{this._writer.releaseLock()}catch(t){this.logger.debug(`Writer release error during reconfigure: ${t}`)}this._writer=void 0}await(null===(e=this._reader)||void 0===e?void 0:e.cancel()),await this.port.close(),await this.port.open({baudRate:t}),await this.flushSerialBuffers(),this.readLoop()}catch(e){throw this.logger.error(`Reconfigure port error: ${e}`),new Error(`Unable to change the baud rate to ${t}: ${e}`)}finally{this._isReconfiguring=!1}}async syncWithTimeout(t){const e=Date.now();for(let i=0;i<5;i++){if(Date.now()-e>t)return!1;if(this._abandonCurrentOperation)return!1;this._clearInputBuffer();try{if(await this._sync())return await s(x),!0}catch(t){if(this._abandonCurrentOperation)return!1}await s(x)}return!1}async sync(){for(let t=0;t<5;t++){this._clearInputBuffer();if(await this._sync())return await s(x),!0;await s(x)}throw new Error("Couldn't sync to ESP. Try resetting.")}async _sync(){await this.sendCommand(8,l);for(let t=0;t<8;t++)try{const[,t]=await this.getResponse(8,x);if(t.length>1&&0==t[0]&&0==t[1])return!0}catch(e){this.debug&&this.logger.debug(`Sync attempt ${t+1} failed: ${e}`)}return!1}getFlashWriteSize(){return this.IS_STUB?16384:1024}async flashData(t,e,i=0,s=!1){if(t.byteLength>=8){const e=Array.from(new Uint8Array(t,0,4)),i=e[0],s=e[2],r=e[3];this.logger.log(`Image header, Magic=${a(i)}, FlashMode=${a(s)}, FlashSizeFreq=${a(r)}`)}const r=t.byteLength;let n,h=0,o=I;s?(n=Pe(new Uint8Array(t),{level:9}).buffer,h=n.byteLength,this.logger.log(`Writing data with filesize: ${r}. Compressed Size: ${h}`),o=await this.flashDeflBegin(r,h,i)):(this.logger.log(`Writing data with filesize: ${r}`),n=t,await this.flashBegin(r,i));let l=[],u=0,d=0,c=0;const _=Date.now(),f=this.getFlashWriteSize(),g=s?h:r;for(;g-c>0;)this.debug&&this.logger.log(`Writing at ${a(i+u*f,8)} `),g-c>=f?l=Array.from(new Uint8Array(n,c,f)):(l=Array.from(new Uint8Array(n,c,g-c)),s||(l=l.concat(new Array(f-l.length).fill(255)))),s?await this.flashDeflBlock(l,u,o):await this.flashBlock(l,u),u+=1,d+=s?Math.round(l.length*r/h):l.length,c+=f,e(Math.min(d,r),r);this.logger.log("Took "+(Date.now()-_)+"ms to write "+g+" bytes"),this.IS_STUB&&(await this.flashBegin(0,0),s?await this.flashDeflFinish():await this.flashFinish())}async flashBlock(t,e,i=3e3){await this.checkCommand(3,Ne("<IIII",t.length,e,0,0).concat(t),this.checksum(t),i)}async flashDeflBlock(t,e,i=3e3){await this.checkCommand(17,Ne("<IIII",t.length,e,0,0).concat(t),this.checksum(t),i)}async flashBegin(t=0,e=0,i=!1){let s;await this.flushSerialBuffers();const r=this.getFlashWriteSize();!this.IS_STUB&&[d,c,_,f,g,p,w,m,b,y,S,B,v].includes(this.chipFamily)&&await this.checkCommand(13,new Array(8).fill(0));const n=Math.floor((t+r-1)/r);s=this.chipFamily==u?this.getEraseSize(e,t):t;const h=this.IS_STUB?I:k(D,t),o=Date.now();let l=Ne("<IIII",s,n,r,e);return this.chipFamily!=d&&this.chipFamily!=c&&this.chipFamily!=_&&this.chipFamily!=f&&this.chipFamily!=g&&this.chipFamily!=p&&this.chipFamily!=w&&this.chipFamily!=m&&this.chipFamily!=b&&this.chipFamily!=y&&this.chipFamily!=S&&this.chipFamily!=B&&this.chipFamily!=v||(l=l.concat(Ne("<I",i?1:0))),this.logger.log("Erase size "+s+", blocks "+n+", block size "+a(r,4)+", offset "+a(e,4)+", encrypted "+(i?"yes":"no")),await this.checkCommand(2,l,0,h),0==t||this.IS_STUB||this.logger.log("Took "+(Date.now()-o)+"ms to erase "+n+" bytes"),n}async flashDeflBegin(t=0,e=0,i=0){const a=this.getFlashWriteSize(),s=Math.floor((e+a-1)/a),r=Math.floor((t+a-1)/a);let n=0,h=0;this.IS_STUB?(n=t,h=k(D,n)):(n=r*a,h=I);const o=Ne("<IIII",n,s,a,i);return await this.checkCommand(16,o,0,h),h}async flashFinish(){const t=Ne("<I",1);await this.checkCommand(4,t)}async flashDeflFinish(){const t=Ne("<I",1);await this.checkCommand(18,t)}getBootloaderOffset(){return C(this.getChipFamily()).flashOffs}async flashId(){return await this.runSpiFlashCommand(159,[],24)}getChipFamily(){return this._parent?this._parent.chipFamily:this.chipFamily}async writeRegister(t,e,i=4294967295,a=0,s=0){let r=Ne("<IIII",t,e,i,a);s>0&&(r=r.concat(Ne("<IIII",C(this.getChipFamily()).uartDateReg,0,0,s))),await this.checkCommand(9,r)}async setDataLengths(t,e,i){if(-1!=t.mosiDlenOffs){const a=t.regBase+t.mosiDlenOffs,s=t.regBase+t.misoDlenOffs;e>0&&await this.writeRegister(a,e-1),i>0&&await this.writeRegister(s,i-1)}else{const a=t.regBase+t.usr1Offs,s=(0==i?0:i-1)<<8|(0==e?0:e-1)<<17;await this.writeRegister(a,s)}}async waitDone(t,e){for(let i=0;i<10;i++){if(0==(await this.readRegister(t)&e))return}throw Error("SPI command did not complete in time")}async runSpiFlashCommand(t,e,i=0){const s=C(this.getChipFamily()),r=s.regBase,n=r,h=r+s.usrOffs,o=r+s.usr2Offs,l=r+s.w0Offs,u=1<<18;if(i>32)throw new Error("Reading more than 32 bits back from a SPI flash operation is unsupported");if(e.length>64)throw new Error("Writing more than 64 bytes of data with one SPI command is unsupported");const d=8*e.length,c=await this.readRegister(h),_=await this.readRegister(o);let f=1<<31;if(i>0&&(f|=268435456),d>0&&(f|=134217728),await this.setDataLengths(s,d,i),await this.writeRegister(h,f),await this.writeRegister(o,7<<28|t),0==d)await this.writeRegister(l,0);else{const t=(4-e.length%4)%4;e=e.concat(new Array(t).fill(0));const i=Ze("I".repeat(Math.floor(e.length/4)),e);let s=l;this.logger.debug(`Words Length: ${i.length}`);for(const t of i)this.logger.debug(`Writing word ${a(t)} to register offset ${a(s)}`),await this.writeRegister(s,t),s+=4}await this.writeRegister(n,u),await this.waitDone(n,u);const g=await this.readRegister(l);return await this.writeRegister(h,c),await this.writeRegister(o,_),g}async detectFlashSize(){this.logger.log("Detecting Flash Size");const t=await this.flashId(),e=255&t,i=t>>16&255;this.logger.log(`FlashId: ${a(t)}`),this.logger.log(`Flash Manufacturer: ${e.toString(16)}`),this.logger.log(`Flash Device: ${(t>>8&255).toString(16)}${i.toString(16)}`),this.flashSize=r[i],this.logger.log(`Auto-detected Flash size: ${this.flashSize}`)}getEraseSize(t,e){const i=n,a=Math.floor((e+i-1)/i);let s=16-Math.floor(t/i)%16;return a<s&&(s=a),a<2*s?Math.floor((a+1)/2*i):(a-s)*i}async memBegin(t,e,i,a){return await this.checkCommand(5,Ne("<IIII",t,e,i,a))}async memBlock(t,e){return await this.checkCommand(7,Ne("<IIII",t.length,e,0,0).concat(t),this.checksum(t))}async memFinish(t=0){const e=this.IS_STUB?I:500,i=Ne("<II",0==t?1:0,t);return await this.checkCommand(6,i,0,e)}async runStub(t=!1){const e=await z(this.chipFamily,this.chipRevision);if(null===e)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 t of["text","data"]){const a=e[t],s=e[`${t}_start`],r=a.length,n=Math.floor((r+i-1)/i);await this.memBegin(r,n,i,s);for(const t of Array(n).keys()){const e=t*i;let s=e+i;s>r&&(s=r),await this.memBlock(a.slice(e,s),t)}}await this.memFinish(e.entry);const a=await this.readPacket(500),s=String.fromCharCode(...a);if("OHAI"!=s)throw new Error("Failed to start stub. Unexpected response: "+s);this.logger.log("Stub is now running...");const r=new He(this.port,this.logger,this);return t||await r.detectFlashSize(),r}get _writer(){return this._parent?this._parent._writer:this.__writer}set _writer(t){this._parent?this._parent._writer=t:this.__writer=t}get _writeChain(){return this._parent?this._parent._writeChain:this.__writeChain}set _writeChain(t){this._parent?this._parent._writeChain=t:this.__writeChain=t}async writeToStream(t){if(this.port.writable){if(this._isReconfiguring)throw new Error("Cannot write during port reconfiguration");this._writeChain=this._writeChain.then(async()=>{if(!this.port.writable)throw new Error("Port became unavailable during write");if(!this._writer)try{this._writer=this.port.writable.getWriter()}catch(t){throw this.logger.error(`Failed to get writer: ${t}`),t}await this._writer.write(new Uint8Array(t))},async()=>{if(this.logger.debug("Previous write failed, attempting recovery for current write"),!this.port.writable)throw new Error("Port became unavailable during write");if(!this._writer)try{this._writer=this.port.writable.getWriter()}catch(t){throw this.logger.debug(`Failed to get writer in recovery: ${t}`),new Error("Cannot acquire writer lock")}await this._writer.write(new Uint8Array(t))}).catch(t=>{if(this.logger.error(`Write error: ${t}`),this._writer){try{this._writer.releaseLock()}catch{}this._writer=void 0}throw t}),await this._writeChain}else this.logger.debug("Port writable stream not available, skipping write")}async disconnect(){if(this._parent)await this._parent.disconnect();else if(this.port.writable){try{await this._writeChain}catch(t){this.logger.debug(`Pending write error during disconnect: ${t}`)}if(this._writer){try{await this._writer.close(),this._writer.releaseLock()}catch(t){this.logger.debug(`Writer close/release error: ${t}`)}this._writer=void 0}else try{const t=this.port.writable.getWriter();await t.close(),t.releaseLock()}catch(t){this.logger.debug(`Direct writer close error: ${t}`)}await new Promise(t=>{this._reader?(this.addEventListener("disconnect",t,{once:!0}),this._reader.cancel()):t(void 0)}),this.connected=!1}else this.logger.debug("Port already closed, skipping disconnect")}async reconnect(){if(this._parent)await this._parent.reconnect();else try{this.logger.log("Reconnecting serial port..."),this.connected=!1,this.__inputBuffer=[],this.__inputBufferReadIndex=0;try{await this._writeChain}catch(t){this.logger.debug(`Pending write error during reconnect: ${t}`)}if(this._isReconfiguring=!0,this._writer){try{this._writer.releaseLock()}catch(t){this.logger.debug(`Writer release error during reconnect: ${t}`)}this._writer=void 0}if(this._reader){try{await this._reader.cancel()}catch(t){this.logger.debug(`Reader cancel error: ${t}`)}this._reader=void 0}try{await this.port.close(),this.logger.log("Port closed")}catch(t){this.logger.debug(`Port close error: ${t}`)}this.logger.debug("Opening port...");try{await this.port.open({baudRate:h}),this.connected=!0}catch(t){throw new Error(`Failed to open port: ${t}`)}if(!this.port.readable||!this.port.writable)throw new Error(`Port streams not available after open (readable: ${!!this.port.readable}, writable: ${!!this.port.writable})`);this._isReconfiguring=!1;const t=this.chipFamily,e=this.chipName,i=this.chipRevision,a=this.chipVariant,s=this.flashSize;if(await this.hardReset(!0),this._parent||(this.__inputBuffer=[],this.__inputBufferReadIndex=0,this.__totalBytesRead=0,this.readLoop()),await this.flushSerialBuffers(),await this.sync(),this.chipFamily=t,this.chipName=e,this.chipRevision=i,this.chipVariant=a,this.flashSize=s,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!==h&&(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=!0,this.logger.debug("Reconnection successful")}catch(t){throw this._isReconfiguring=!1,t}}async drainInputBuffer(t=200){await s(t);let e=0;const i=Date.now();for(;e<112&&Date.now()-i<100;)if(this._inputBufferAvailable>0){void 0!==this._readByte()&&e++}else await s(1);e>0&&this.logger.debug(`Drained ${e} bytes from input buffer`),this._parent||(this.__inputBuffer=[],this.__inputBufferReadIndex=0)}async flushSerialBuffers(){this._parent||(this.__inputBuffer=[],this.__inputBufferReadIndex=0),await s(x),this._parent||(this.__inputBuffer=[],this.__inputBufferReadIndex=0),this.logger.debug("Serial buffers flushed")}async readFlash(e,i,a){if(!this.IS_STUB)throw new Error("Reading flash is only supported in stub mode. Please run runStub() first.");let r;await this.flushSerialBuffers(),this.logger.log(`Reading ${i} bytes from flash at address 0x${e.toString(16)}...`),this.isWebUSB()&&(this._isCDCDevice?(this._adaptiveBlockMultiplier=8,this._adaptiveMaxInFlightMultiplier=8,this._consecutiveSuccessfulChunks=0,this.logger.debug(`CDC device - Initialized: blockMultiplier=${this._adaptiveBlockMultiplier}, maxInFlightMultiplier=${this._adaptiveMaxInFlightMultiplier}`)):(this._adaptiveBlockMultiplier=1,this._adaptiveMaxInFlightMultiplier=1,this._consecutiveSuccessfulChunks=0,this.logger.debug("Non-CDC device - Fixed values: blockSize=31, maxInFlight=31"))),r=this.isWebUSB()?16384:262144;let n=new Uint8Array(0),h=e,o=i;for(;o>0;){const e=Math.min(r,o);let l=!1,u=0;const d=5;let c=!1;for(;!l&&u<=d;){let i=new Uint8Array(0),a=0;try{let r,o;if(0===u&&this.logger.debug(`Reading chunk at 0x${h.toString(16)}, size: 0x${e.toString(16)}`),this.isWebUSB()){const t=this.port.maxTransferSize||64,e=Math.floor((t-2)/2);r=e*this._adaptiveBlockMultiplier,o=e*this._adaptiveMaxInFlightMultiplier}else{const t=63;r=65*t,o=130*t}const d=Ne("<IIII",h,e,r,o),[c]=await this.checkCommand(210,d);if(0!=c)throw new Error("Failed to read memory: "+c);for(;i.length<e;){let r;try{r=await this.readPacket(100)}catch(t){if(t instanceof F){this.logger.debug(`SLIP read error at ${i.length} bytes: ${t.message}`);try{const t=[192,192];await this.writeToStream(t),this.logger.debug("Sent abort frame to stub"),await s(50)}catch(t){this.logger.debug(`Abort frame error: ${t}`)}if(await this.drainInputBuffer(200),i.length>=e)break}throw t}if(r&&r.length>0){const s=new Uint8Array(r),n=new Uint8Array(i.length+s.length);n.set(i),n.set(s,i.length),i=n;if(i.length>=e||i.length>=a+o){const e=Ne("<I",i.length),s=t(e);await this.writeToStream(s),a=i.length}}}const _=new Uint8Array(n.length+i.length);if(_.set(n),_.set(i,n.length),n=_,l=!0,this.isWebUSB()&&this._isCDCDevice&&0===u&&(this._consecutiveSuccessfulChunks++,this._consecutiveSuccessfulChunks>=2)){const t=this.port.maxTransferSize||64,e=Math.floor((t-2)/2),i=8,a=8;let s=!1;if(this._adaptiveBlockMultiplier<i?(this._adaptiveBlockMultiplier=Math.min(2*this._adaptiveBlockMultiplier,i),s=!0):this._adaptiveMaxInFlightMultiplier<a&&(this._adaptiveMaxInFlightMultiplier=Math.min(2*this._adaptiveMaxInFlightMultiplier,a),s=!0),s){const t=e*this._adaptiveBlockMultiplier,i=e*this._adaptiveMaxInFlightMultiplier;this.logger.debug(`Speed increased: blockSize=${t}, maxInFlight=${i}`),this._lastAdaptiveAdjustment=Date.now()}this._consecutiveSuccessfulChunks=0}}catch(t){if(u++,this.isWebUSB()&&this._isCDCDevice&&1===u)if(this._adaptiveBlockMultiplier>1||this._adaptiveMaxInFlightMultiplier>1){this._adaptiveBlockMultiplier=1,this._adaptiveMaxInFlightMultiplier=1,this._consecutiveSuccessfulChunks=0;const t=this.port.maxTransferSize||64,e=Math.floor((t-2)/2),i=e*this._adaptiveBlockMultiplier,a=e*this._adaptiveMaxInFlightMultiplier;this.logger.debug(`Error at higher speed - reduced to minimum: blockSize=${i}, maxInFlight=${a}`)}else this.logger.debug("Error at minimum speed (blockSize=31, maxInFlight=31) - not a speed issue");if(!(t instanceof F))throw t;if(u<=d){this.logger.log(`${t.message} at 0x${h.toString(16)}. Draining buffer and retrying (attempt ${u}/${d})...`);try{await this.drainInputBuffer(200),await this.flushSerialBuffers(),await s(x)}catch(t){this.logger.debug(`Buffer drain error: ${t}`)}}else{if(c)throw new Error(`Failed to read chunk at 0x${h.toString(16)} after ${d} retries and recovery attempt`);c=!0,this.logger.log(`All retries exhausted at 0x${h.toString(16)}. Attempting recovery (close and reopen port)...`);try{await this.reconnect(),this.logger.log("Deep recovery successful. Resuming read from current position..."),u=0;continue}catch(t){throw new Error(`Failed to read chunk at 0x${h.toString(16)} after ${d} retries and recovery failed: ${t}`)}}}}a&&a(new Uint8Array(e),n.length,i),h+=e,o-=e,this.logger.debug(`Total progress: 0x${n.length.toString(16)} from 0x${i.toString(16)} bytes`)}return n}}class He extends Ve{constructor(){super(...arguments),this.IS_STUB=!0}async memBegin(t,e,i,s){const r=await z(this.chipFamily,this.chipRevision);if(null===r)return[0,[]];const n=s,h=s+t;this.logger.debug(`Load range: ${a(n,8)}-${a(h,8)}`),this.logger.debug(`Stub data: ${a(r.data_start,8)}, len: ${r.data.length}, text: ${a(r.text_start,8)}, len: ${r.text.length}`);for(const[t,e]of[[r.data_start,r.data_start+r.data.length],[r.text_start,r.text_start+r.text.length]])if(n<e&&h>t)throw new Error("Software loader is resident at "+a(t,8)+"-"+a(e,8)+". Can't load binary at overlapping address range "+a(n,8)+"-"+a(h,8)+". Try changing the binary loading address.");return[0,[]]}async eraseFlash(){await this.checkCommand(208,[],0,T)}async eraseRegion(t,e){if(t<0)throw new Error(`Invalid offset: ${t} (must be non-negative)`);if(e<0)throw new Error(`Invalid size: ${e} (must be non-negative)`);if(0===e)return void this.logger.log("eraseRegion: size is 0, skipping erase");if(t%n!==0)throw new Error(`Offset ${t} (0x${t.toString(16)}) is not aligned to flash sector size 4096 (0x${n.toString(16)})`);if(e%n!==0)throw new Error(`Size ${e} (0x${e.toString(16)}) is not aligned to flash sector size 4096 (0x${n.toString(16)})`);const i=4294967295;if(t>i)throw new Error(`Offset ${t} exceeds maximum value 4294967295`);if(e>i)throw new Error(`Size ${e} exceeds maximum value 4294967295`);const a=k(D,e),s=Ne("<II",t,e);await this.checkCommand(209,s,0,a)}}const je=async t=>{let e;const i=globalThis.requestSerialPort;if("function"==typeof i)t.log("Using custom port request function"),e=await i();else{if(!navigator.serial)throw new Error("Web Serial API is not supported in this browser. Please use Chrome 89+, Edge 89+, or Opera on desktop, or Chrome 61+ on Android with USB OTG. Note: The page must be served over HTTPS or localhost.");e=await navigator.serial.requestPort()}return e.readable&&e.writable||await e.open({baudRate:h}),t.log("Connected successfully."),new Ve(e,t)},Ge=async(t,e)=>{if(!t)throw new Error("Port is required");return t.readable&&t.writable||await t.open({baudRate:h}),e.log("Connected successfully."),new Ve(t,e)};export{d as CHIP_FAMILY_ESP32,f as CHIP_FAMILY_ESP32C2,g as CHIP_FAMILY_ESP32C3,p as CHIP_FAMILY_ESP32C5,w as CHIP_FAMILY_ESP32C6,m as CHIP_FAMILY_ESP32C61,b as CHIP_FAMILY_ESP32H2,S as CHIP_FAMILY_ESP32H21,y as CHIP_FAMILY_ESP32H4,B as CHIP_FAMILY_ESP32P4,c as CHIP_FAMILY_ESP32S2,_ as CHIP_FAMILY_ESP32S3,v as CHIP_FAMILY_ESP32S31,u as CHIP_FAMILY_ESP8266,Ve as ESPLoader,je as connect,Ge as connectWithPort};
@@ -1 +1 @@
1
- const t=t=>{let e=[192];for(const i of t)219==i?e=e.concat([219,221]):192==i?e=e.concat([219,220]):e.push(i);return e.push(192),e},e=t=>{const e=[];for(let i=0;i<t.length;i++){const a=t.charCodeAt(i);a<=255&&e.push(a)}return e},i=t=>"["+t.map(t=>a(t)).join(", ")+"]",a=(t,e=2)=>{const i=t.toString(16).toUpperCase();return i.startsWith("-")?"-0x"+i.substring(1).padStart(e,"0"):"0x"+i.padStart(e,"0")},s=t=>new Promise(e=>setTimeout(e,t)),r={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"},n=115200,h=1343410176,o=e(" UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU"),l=33382,u=50,d=12882,c=12883,_=12994,f=12995,g=12997,p=12998,w=207969,m=12914,b=12916,y=12917,S=12928,B=12849,v={5:{name:"ESP32-C3",family:f},9:{name:"ESP32-S3",family:c},12:{name:"ESP32-C2",family:_},13:{name:"ESP32-C6",family:p},16:{name:"ESP32-H2",family:m},18:{name:"ESP32-P4",family:S},20:{name:"ESP32-C61",family:w},23:{name:"ESP32-C5",family:g},25:{name:"ESP32-H21",family:y},28:{name:"ESP32-H4",family:b},32:{name:"ESP32-S31",family:B}},R={4293968129:{name:"ESP8266",family:l},15736195:{name:"ESP32",family:u},1990:{name:"ESP32-S2",family:d}},U=3e3,I=15e4,T=100,D=(t,e)=>{const i=Math.floor(t*(e/486));return i<U?U:i},x=t=>{switch(t){case u:return{regBase:1072963584,baseFuse:1073061888,macFuse:1073061888,usrOffs:28,usr1Offs:32,usr2Offs:36,mosiDlenOffs:40,misoDlenOffs:44,w0Offs:128,uartDateReg:1610612856,flashOffs:4096};case d:return{regBase:1061167104,baseFuse:1061265408,macFuse:1061265476,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612856,flashOffs:4096};case c:return{regBase:1610620928,usrOffs:24,baseFuse:1610641408,macFuse:1610641476,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612864,flashOffs:0};case l:return{regBase:1610613248,usrOffs:28,baseFuse:1072693328,macFuse:1072693328,usr1Offs:32,usr2Offs:36,mosiDlenOffs:-1,misoDlenOffs:-1,w0Offs:64,uartDateReg:1610612856,flashOffs:0};case _:case f:return{regBase:1610620928,baseFuse:1610647552,macFuse:1610647620,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case g:return{regBase:1610625024,baseFuse:1611352064,macFuse:1611352132,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:8192};case p:return{regBase:1610625024,baseFuse:1611335680,macFuse:1611335748,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case w:return{regBase:1610625024,baseFuse:1611352064,macFuse:1611352132,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case m:return{regBase:1610625024,baseFuse:1611335680,macFuse:1611335748,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case b:return{regBase:1611239424,baseFuse:1611339776,macFuse:1611339844,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610686588,flashOffs:8192};case y:return{regBase:1610625024,baseFuse:1611350016,macFuse:1611350084,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case S:return{regBase:1342754816,baseFuse:h,macFuse:1343410244,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1343004812,flashOffs:8192};case B: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 k extends Error{constructor(t){super(t),this.name="SlipReadError"}}const C=async(t,i)=>{let a;if(t==b||t==y||t==B)return null;if(t==u)a=await import("./esp32-BRKoi17y.js");else if(t==d)a=await import("./esp32s2-iX3WoDbg.js");else if(t==c)a=await import("./esp32s3-DGwDVIgz.js");else if(t==l)a=await import("./esp8266-CUwxJpGa.js");else if(t==_)a=await import("./esp32c2-Btgr_lwh.js");else if(t==f)a=await import("./esp32c3-CHKfoI8W.js");else if(t==g)a=await import("./esp32c5-BDW4KtLo.js");else if(t==p)a=await import("./esp32c6-il8tTxAG.js");else if(t==w)a=await import("./esp32c61-thKzxBGf.js");else if(t==m)a=await import("./esp32h2-CxoUHv_P.js");else{if(t!=S)return null;a=null!=i&&i>=300?await import("./esp32p4r3-CqI71ojR.js"):await import("./esp32p4-D3jLP-jY.js")}return{...a,text:e(atob(a.text)),data:e(atob(a.data))}};function F(t){let e=t.length;for(;--e>=0;)t[e]=0}const W=256,O=286,z=30,A=15,E=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]),M=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]),P=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),$=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),L=new Array(576);F(L);const N=new Array(60);F(N);const Z=new Array(512);F(Z);const V=new Array(256);F(V);const H=new Array(29);F(H);const G=new Array(z);function j(t,e,i,a,s){this.static_tree=t,this.extra_bits=e,this.extra_base=i,this.elems=a,this.max_length=s,this.has_stree=t&&t.length}let J,q,K;function Y(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}F(G);const X=t=>t<256?Z[t]:Z[256+(t>>>7)],Q=(t,e)=>{t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255},tt=(t,e,i)=>{t.bi_valid>16-i?(t.bi_buf|=e<<t.bi_valid&65535,Q(t,t.bi_buf),t.bi_buf=e>>16-t.bi_valid,t.bi_valid+=i-16):(t.bi_buf|=e<<t.bi_valid&65535,t.bi_valid+=i)},et=(t,e,i)=>{tt(t,i[2*e],i[2*e+1])},it=(t,e)=>{let i=0;do{i|=1&t,t>>>=1,i<<=1}while(--e>0);return i>>>1},at=(t,e,i)=>{const a=new Array(16);let s,r,n=0;for(s=1;s<=A;s++)n=n+i[s-1]<<1,a[s]=n;for(r=0;r<=e;r++){let e=t[2*r+1];0!==e&&(t[2*r]=it(a[e]++,e))}},st=t=>{let e;for(e=0;e<O;e++)t.dyn_ltree[2*e]=0;for(e=0;e<z;e++)t.dyn_dtree[2*e]=0;for(e=0;e<19;e++)t.bl_tree[2*e]=0;t.dyn_ltree[512]=1,t.opt_len=t.static_len=0,t.sym_next=t.matches=0},rt=t=>{t.bi_valid>8?Q(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0},nt=(t,e,i,a)=>{const s=2*e,r=2*i;return t[s]<t[r]||t[s]===t[r]&&a[e]<=a[i]},ht=(t,e,i)=>{const a=t.heap[i];let s=i<<1;for(;s<=t.heap_len&&(s<t.heap_len&&nt(e,t.heap[s+1],t.heap[s],t.depth)&&s++,!nt(e,a,t.heap[s],t.depth));)t.heap[i]=t.heap[s],i=s,s<<=1;t.heap[i]=a},ot=(t,e,i)=>{let a,s,r,n,h=0;if(0!==t.sym_next)do{a=255&t.pending_buf[t.sym_buf+h++],a+=(255&t.pending_buf[t.sym_buf+h++])<<8,s=t.pending_buf[t.sym_buf+h++],0===a?et(t,s,e):(r=V[s],et(t,r+W+1,e),n=E[r],0!==n&&(s-=H[r],tt(t,s,n)),a--,r=X(a),et(t,r,i),n=M[r],0!==n&&(a-=G[r],tt(t,a,n)))}while(h<t.sym_next);et(t,256,e)},lt=(t,e)=>{const i=e.dyn_tree,a=e.stat_desc.static_tree,s=e.stat_desc.has_stree,r=e.stat_desc.elems;let n,h,o,l=-1;for(t.heap_len=0,t.heap_max=573,n=0;n<r;n++)0!==i[2*n]?(t.heap[++t.heap_len]=l=n,t.depth[n]=0):i[2*n+1]=0;for(;t.heap_len<2;)o=t.heap[++t.heap_len]=l<2?++l:0,i[2*o]=1,t.depth[o]=0,t.opt_len--,s&&(t.static_len-=a[2*o+1]);for(e.max_code=l,n=t.heap_len>>1;n>=1;n--)ht(t,i,n);o=r;do{n=t.heap[1],t.heap[1]=t.heap[t.heap_len--],ht(t,i,1),h=t.heap[1],t.heap[--t.heap_max]=n,t.heap[--t.heap_max]=h,i[2*o]=i[2*n]+i[2*h],t.depth[o]=(t.depth[n]>=t.depth[h]?t.depth[n]:t.depth[h])+1,i[2*n+1]=i[2*h+1]=o,t.heap[1]=o++,ht(t,i,1)}while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],((t,e)=>{const i=e.dyn_tree,a=e.max_code,s=e.stat_desc.static_tree,r=e.stat_desc.has_stree,n=e.stat_desc.extra_bits,h=e.stat_desc.extra_base,o=e.stat_desc.max_length;let l,u,d,c,_,f,g=0;for(c=0;c<=A;c++)t.bl_count[c]=0;for(i[2*t.heap[t.heap_max]+1]=0,l=t.heap_max+1;l<573;l++)u=t.heap[l],c=i[2*i[2*u+1]+1]+1,c>o&&(c=o,g++),i[2*u+1]=c,u>a||(t.bl_count[c]++,_=0,u>=h&&(_=n[u-h]),f=i[2*u],t.opt_len+=f*(c+_),r&&(t.static_len+=f*(s[2*u+1]+_)));if(0!==g){do{for(c=o-1;0===t.bl_count[c];)c--;t.bl_count[c]--,t.bl_count[c+1]+=2,t.bl_count[o]--,g-=2}while(g>0);for(c=o;0!==c;c--)for(u=t.bl_count[c];0!==u;)d=t.heap[--l],d>a||(i[2*d+1]!==c&&(t.opt_len+=(c-i[2*d+1])*i[2*d],i[2*d+1]=c),u--)}})(t,e),at(i,l,t.bl_count)},ut=(t,e,i)=>{let a,s,r=-1,n=e[1],h=0,o=7,l=4;for(0===n&&(o=138,l=3),e[2*(i+1)+1]=65535,a=0;a<=i;a++)s=n,n=e[2*(a+1)+1],++h<o&&s===n||(h<l?t.bl_tree[2*s]+=h:0!==s?(s!==r&&t.bl_tree[2*s]++,t.bl_tree[32]++):h<=10?t.bl_tree[34]++:t.bl_tree[36]++,h=0,r=s,0===n?(o=138,l=3):s===n?(o=6,l=3):(o=7,l=4))},dt=(t,e,i)=>{let a,s,r=-1,n=e[1],h=0,o=7,l=4;for(0===n&&(o=138,l=3),a=0;a<=i;a++)if(s=n,n=e[2*(a+1)+1],!(++h<o&&s===n)){if(h<l)do{et(t,s,t.bl_tree)}while(0!==--h);else 0!==s?(s!==r&&(et(t,s,t.bl_tree),h--),et(t,16,t.bl_tree),tt(t,h-3,2)):h<=10?(et(t,17,t.bl_tree),tt(t,h-3,3)):(et(t,18,t.bl_tree),tt(t,h-11,7));h=0,r=s,0===n?(o=138,l=3):s===n?(o=6,l=3):(o=7,l=4)}};let ct=!1;const _t=(t,e,i,a)=>{tt(t,0+(a?1:0),3),rt(t),Q(t,i),Q(t,~i),i&&t.pending_buf.set(t.window.subarray(e,e+i),t.pending),t.pending+=i};var ft=(t,e,i,a)=>{let s,r,n=0;t.level>0?(2===t.strm.data_type&&(t.strm.data_type=(t=>{let e,i=4093624447;for(e=0;e<=31;e++,i>>>=1)if(1&i&&0!==t.dyn_ltree[2*e])return 0;if(0!==t.dyn_ltree[18]||0!==t.dyn_ltree[20]||0!==t.dyn_ltree[26])return 1;for(e=32;e<W;e++)if(0!==t.dyn_ltree[2*e])return 1;return 0})(t)),lt(t,t.l_desc),lt(t,t.d_desc),n=(t=>{let e;for(ut(t,t.dyn_ltree,t.l_desc.max_code),ut(t,t.dyn_dtree,t.d_desc.max_code),lt(t,t.bl_desc),e=18;e>=3&&0===t.bl_tree[2*$[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e})(t),s=t.opt_len+3+7>>>3,r=t.static_len+3+7>>>3,r<=s&&(s=r)):s=r=i+5,i+4<=s&&-1!==e?_t(t,e,i,a):4===t.strategy||r===s?(tt(t,2+(a?1:0),3),ot(t,L,N)):(tt(t,4+(a?1:0),3),((t,e,i,a)=>{let s;for(tt(t,e-257,5),tt(t,i-1,5),tt(t,a-4,4),s=0;s<a;s++)tt(t,t.bl_tree[2*$[s]+1],3);dt(t,t.dyn_ltree,e-1),dt(t,t.dyn_dtree,i-1)})(t,t.l_desc.max_code+1,t.d_desc.max_code+1,n+1),ot(t,t.dyn_ltree,t.dyn_dtree)),st(t),a&&rt(t)},gt={_tr_init:t=>{ct||((()=>{let t,e,i,a,s;const r=new Array(16);for(i=0,a=0;a<28;a++)for(H[a]=i,t=0;t<1<<E[a];t++)V[i++]=a;for(V[i-1]=a,s=0,a=0;a<16;a++)for(G[a]=s,t=0;t<1<<M[a];t++)Z[s++]=a;for(s>>=7;a<z;a++)for(G[a]=s<<7,t=0;t<1<<M[a]-7;t++)Z[256+s++]=a;for(e=0;e<=A;e++)r[e]=0;for(t=0;t<=143;)L[2*t+1]=8,t++,r[8]++;for(;t<=255;)L[2*t+1]=9,t++,r[9]++;for(;t<=279;)L[2*t+1]=7,t++,r[7]++;for(;t<=287;)L[2*t+1]=8,t++,r[8]++;for(at(L,287,r),t=0;t<z;t++)N[2*t+1]=5,N[2*t]=it(t,5);J=new j(L,E,257,O,A),q=new j(N,M,0,z,A),K=new j(new Array(0),P,0,19,7)})(),ct=!0),t.l_desc=new Y(t.dyn_ltree,J),t.d_desc=new Y(t.dyn_dtree,q),t.bl_desc=new Y(t.bl_tree,K),t.bi_buf=0,t.bi_valid=0,st(t)},_tr_stored_block:_t,_tr_flush_block:ft,_tr_tally:(t,e,i)=>(t.pending_buf[t.sym_buf+t.sym_next++]=e,t.pending_buf[t.sym_buf+t.sym_next++]=e>>8,t.pending_buf[t.sym_buf+t.sym_next++]=i,0===e?t.dyn_ltree[2*i]++:(t.matches++,e--,t.dyn_ltree[2*(V[i]+W+1)]++,t.dyn_dtree[2*X(e)]++),t.sym_next===t.sym_end),_tr_align:t=>{tt(t,2,3),et(t,256,L),(t=>{16===t.bi_valid?(Q(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)})(t)}};var pt=(t,e,i,a)=>{let s=65535&t,r=t>>>16&65535,n=0;for(;0!==i;){n=i>2e3?2e3:i,i-=n;do{s=s+e[a++]|0,r=r+s|0}while(--n);s%=65521,r%=65521}return s|r<<16};const wt=new Uint32Array((()=>{let t,e=[];for(var i=0;i<256;i++){t=i;for(var a=0;a<8;a++)t=1&t?3988292384^t>>>1:t>>>1;e[i]=t}return e})());var mt=(t,e,i,a)=>{const s=wt,r=a+i;t^=-1;for(let i=a;i<r;i++)t=t>>>8^s[255&(t^e[i])];return-1^t},bt={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"},yt={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:St,_tr_stored_block:Bt,_tr_flush_block:vt,_tr_tally:Rt,_tr_align:Ut}=gt,{Z_NO_FLUSH:It,Z_PARTIAL_FLUSH:Tt,Z_FULL_FLUSH:Dt,Z_FINISH:xt,Z_BLOCK:kt,Z_OK:Ct,Z_STREAM_END:Ft,Z_STREAM_ERROR:Wt,Z_DATA_ERROR:Ot,Z_BUF_ERROR:zt,Z_DEFAULT_COMPRESSION:At,Z_FILTERED:Et,Z_HUFFMAN_ONLY:Mt,Z_RLE:Pt,Z_FIXED:$t,Z_DEFAULT_STRATEGY:Lt,Z_UNKNOWN:Nt,Z_DEFLATED:Zt}=yt,Vt=258,Ht=262,Gt=42,jt=113,Jt=666,qt=(t,e)=>(t.msg=bt[e],e),Kt=t=>2*t-(t>4?9:0),Yt=t=>{let e=t.length;for(;--e>=0;)t[e]=0},Xt=t=>{let e,i,a,s=t.w_size;e=t.hash_size,a=e;do{i=t.head[--a],t.head[a]=i>=s?i-s:0}while(--e);e=s,a=e;do{i=t.prev[--a],t.prev[a]=i>=s?i-s:0}while(--e)};let Qt=(t,e,i)=>(e<<t.hash_shift^i)&t.hash_mask;const te=t=>{const e=t.state;let i=e.pending;i>t.avail_out&&(i=t.avail_out),0!==i&&(t.output.set(e.pending_buf.subarray(e.pending_out,e.pending_out+i),t.next_out),t.next_out+=i,e.pending_out+=i,t.total_out+=i,t.avail_out-=i,e.pending-=i,0===e.pending&&(e.pending_out=0))},ee=(t,e)=>{vt(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,te(t.strm)},ie=(t,e)=>{t.pending_buf[t.pending++]=e},ae=(t,e)=>{t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e},se=(t,e,i,a)=>{let s=t.avail_in;return s>a&&(s=a),0===s?0:(t.avail_in-=s,e.set(t.input.subarray(t.next_in,t.next_in+s),i),1===t.state.wrap?t.adler=pt(t.adler,e,s,i):2===t.state.wrap&&(t.adler=mt(t.adler,e,s,i)),t.next_in+=s,t.total_in+=s,s)},re=(t,e)=>{let i,a,s=t.max_chain_length,r=t.strstart,n=t.prev_length,h=t.nice_match;const o=t.strstart>t.w_size-Ht?t.strstart-(t.w_size-Ht):0,l=t.window,u=t.w_mask,d=t.prev,c=t.strstart+Vt;let _=l[r+n-1],f=l[r+n];t.prev_length>=t.good_match&&(s>>=2),h>t.lookahead&&(h=t.lookahead);do{if(i=e,l[i+n]===f&&l[i+n-1]===_&&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<c);if(a=Vt-(c-r),r=c-Vt,a>n){if(t.match_start=e,n=a,a>=h)break;_=l[r+n-1],f=l[r+n]}}}while((e=d[e&u])>o&&0!==--s);return n<=t.lookahead?n:t.lookahead},ne=t=>{const e=t.w_size;let i,a,s;do{if(a=t.window_size-t.lookahead-t.strstart,t.strstart>=e+(e-Ht)&&(t.window.set(t.window.subarray(e,e+e-a),0),t.match_start-=e,t.strstart-=e,t.block_start-=e,t.insert>t.strstart&&(t.insert=t.strstart),Xt(t),a+=e),0===t.strm.avail_in)break;if(i=se(t.strm,t.window,t.strstart+t.lookahead,a),t.lookahead+=i,t.lookahead+t.insert>=3)for(s=t.strstart-t.insert,t.ins_h=t.window[s],t.ins_h=Qt(t,t.ins_h,t.window[s+1]);t.insert&&(t.ins_h=Qt(t,t.ins_h,t.window[s+3-1]),t.prev[s&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=s,s++,t.insert--,!(t.lookahead+t.insert<3)););}while(t.lookahead<Ht&&0!==t.strm.avail_in)},he=(t,e)=>{let i,a,s,r=t.pending_buf_size-5>t.w_size?t.w_size:t.pending_buf_size-5,n=0,h=t.strm.avail_in;do{if(i=65535,s=t.bi_valid+42>>3,t.strm.avail_out<s)break;if(s=t.strm.avail_out-s,a=t.strstart-t.block_start,i>a+t.strm.avail_in&&(i=a+t.strm.avail_in),i>s&&(i=s),i<r&&(0===i&&e!==xt||e===It||i!==a+t.strm.avail_in))break;n=e===xt&&i===a+t.strm.avail_in?1:0,Bt(t,0,0,n),t.pending_buf[t.pending-4]=i,t.pending_buf[t.pending-3]=i>>8,t.pending_buf[t.pending-2]=~i,t.pending_buf[t.pending-1]=~i>>8,te(t.strm),a&&(a>i&&(a=i),t.strm.output.set(t.window.subarray(t.block_start,t.block_start+a),t.strm.next_out),t.strm.next_out+=a,t.strm.avail_out-=a,t.strm.total_out+=a,t.block_start+=a,i-=a),i&&(se(t.strm,t.strm.output,t.strm.next_out,i),t.strm.next_out+=i,t.strm.avail_out-=i,t.strm.total_out+=i)}while(0===n);return h-=t.strm.avail_in,h&&(h>=t.w_size?(t.matches=2,t.window.set(t.strm.input.subarray(t.strm.next_in-t.w_size,t.strm.next_in),0),t.strstart=t.w_size,t.insert=t.strstart):(t.window_size-t.strstart<=h&&(t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,t.insert>t.strstart&&(t.insert=t.strstart)),t.window.set(t.strm.input.subarray(t.strm.next_in-h,t.strm.next_in),t.strstart),t.strstart+=h,t.insert+=h>t.w_size-t.insert?t.w_size-t.insert:h),t.block_start=t.strstart),t.high_water<t.strstart&&(t.high_water=t.strstart),n?4:e!==It&&e!==xt&&0===t.strm.avail_in&&t.strstart===t.block_start?2:(s=t.window_size-t.strstart,t.strm.avail_in>s&&t.block_start>=t.w_size&&(t.block_start-=t.w_size,t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,s+=t.w_size,t.insert>t.strstart&&(t.insert=t.strstart)),s>t.strm.avail_in&&(s=t.strm.avail_in),s&&(se(t.strm,t.window,t.strstart,s),t.strstart+=s,t.insert+=s>t.w_size-t.insert?t.w_size-t.insert:s),t.high_water<t.strstart&&(t.high_water=t.strstart),s=t.bi_valid+42>>3,s=t.pending_buf_size-s>65535?65535:t.pending_buf_size-s,r=s>t.w_size?t.w_size:s,a=t.strstart-t.block_start,(a>=r||(a||e===xt)&&e!==It&&0===t.strm.avail_in&&a<=s)&&(i=a>s?s:a,n=e===xt&&0===t.strm.avail_in&&i===a?1:0,Bt(t,t.block_start,i,n),t.block_start+=i,te(t.strm)),n?3:1)},oe=(t,e)=>{let i,a;for(;;){if(t.lookahead<Ht){if(ne(t),t.lookahead<Ht&&e===It)return 1;if(0===t.lookahead)break}if(i=0,t.lookahead>=3&&(t.ins_h=Qt(t,t.ins_h,t.window[t.strstart+3-1]),i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),0!==i&&t.strstart-i<=t.w_size-Ht&&(t.match_length=re(t,i)),t.match_length>=3)if(a=Rt(t,t.strstart-t.match_start,t.match_length-3),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=3){t.match_length--;do{t.strstart++,t.ins_h=Qt(t,t.ins_h,t.window[t.strstart+3-1]),i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart}while(0!==--t.match_length);t.strstart++}else t.strstart+=t.match_length,t.match_length=0,t.ins_h=t.window[t.strstart],t.ins_h=Qt(t,t.ins_h,t.window[t.strstart+1]);else a=Rt(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(a&&(ee(t,!1),0===t.strm.avail_out))return 1}return t.insert=t.strstart<2?t.strstart:2,e===xt?(ee(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ee(t,!1),0===t.strm.avail_out)?1:2},le=(t,e)=>{let i,a,s;for(;;){if(t.lookahead<Ht){if(ne(t),t.lookahead<Ht&&e===It)return 1;if(0===t.lookahead)break}if(i=0,t.lookahead>=3&&(t.ins_h=Qt(t,t.ins_h,t.window[t.strstart+3-1]),i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),t.prev_length=t.match_length,t.prev_match=t.match_start,t.match_length=2,0!==i&&t.prev_length<t.max_lazy_match&&t.strstart-i<=t.w_size-Ht&&(t.match_length=re(t,i),t.match_length<=5&&(t.strategy===Et||3===t.match_length&&t.strstart-t.match_start>4096)&&(t.match_length=2)),t.prev_length>=3&&t.match_length<=t.prev_length){s=t.strstart+t.lookahead-3,a=Rt(t,t.strstart-1-t.prev_match,t.prev_length-3),t.lookahead-=t.prev_length-1,t.prev_length-=2;do{++t.strstart<=s&&(t.ins_h=Qt(t,t.ins_h,t.window[t.strstart+3-1]),i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart)}while(0!==--t.prev_length);if(t.match_available=0,t.match_length=2,t.strstart++,a&&(ee(t,!1),0===t.strm.avail_out))return 1}else if(t.match_available){if(a=Rt(t,0,t.window[t.strstart-1]),a&&ee(t,!1),t.strstart++,t.lookahead--,0===t.strm.avail_out)return 1}else t.match_available=1,t.strstart++,t.lookahead--}return t.match_available&&(a=Rt(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<2?t.strstart:2,e===xt?(ee(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ee(t,!1),0===t.strm.avail_out)?1:2};function ue(t,e,i,a,s){this.good_length=t,this.max_lazy=e,this.nice_length=i,this.max_chain=a,this.func=s}const de=[new ue(0,0,0,0,he),new ue(4,4,8,4,oe),new ue(4,5,16,8,oe),new ue(4,6,32,32,oe),new ue(4,4,16,16,le),new ue(8,16,32,32,le),new ue(8,16,128,128,le),new ue(8,32,128,256,le),new ue(32,128,258,1024,le),new ue(32,258,258,4096,le)];function ce(){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=Zt,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),Yt(this.dyn_ltree),Yt(this.dyn_dtree),Yt(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),Yt(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),Yt(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 _e=t=>{if(!t)return 1;const e=t.state;return!e||e.strm!==t||e.status!==Gt&&57!==e.status&&69!==e.status&&73!==e.status&&91!==e.status&&103!==e.status&&e.status!==jt&&e.status!==Jt?1:0},fe=t=>{if(_e(t))return qt(t,Wt);t.total_in=t.total_out=0,t.data_type=Nt;const e=t.state;return e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=2===e.wrap?57:e.wrap?Gt:jt,t.adler=2===e.wrap?0:1,e.last_flush=-2,St(e),Ct},ge=t=>{const e=fe(t);var i;return e===Ct&&((i=t.state).window_size=2*i.w_size,Yt(i.head),i.max_lazy_match=de[i.level].max_lazy,i.good_match=de[i.level].good_length,i.nice_match=de[i.level].nice_length,i.max_chain_length=de[i.level].max_chain,i.strstart=0,i.block_start=0,i.lookahead=0,i.insert=0,i.match_length=i.prev_length=2,i.match_available=0,i.ins_h=0),e},pe=(t,e,i,a,s,r)=>{if(!t)return Wt;let n=1;if(e===At&&(e=6),a<0?(n=0,a=-a):a>15&&(n=2,a-=16),s<1||s>9||i!==Zt||a<8||a>15||e<0||e>9||r<0||r>$t||8===a&&1!==n)return qt(t,Wt);8===a&&(a=9);const h=new ce;return t.state=h,h.strm=t,h.status=Gt,h.wrap=n,h.gzhead=null,h.w_bits=a,h.w_size=1<<h.w_bits,h.w_mask=h.w_size-1,h.hash_bits=s+7,h.hash_size=1<<h.hash_bits,h.hash_mask=h.hash_size-1,h.hash_shift=~~((h.hash_bits+3-1)/3),h.window=new Uint8Array(2*h.w_size),h.head=new Uint16Array(h.hash_size),h.prev=new Uint16Array(h.w_size),h.lit_bufsize=1<<s+6,h.pending_buf_size=4*h.lit_bufsize,h.pending_buf=new Uint8Array(h.pending_buf_size),h.sym_buf=h.lit_bufsize,h.sym_end=3*(h.lit_bufsize-1),h.level=e,h.strategy=r,h.method=i,ge(t)};var we={deflateInit:(t,e)=>pe(t,e,Zt,15,8,Lt),deflateInit2:pe,deflateReset:ge,deflateResetKeep:fe,deflateSetHeader:(t,e)=>_e(t)||2!==t.state.wrap?Wt:(t.state.gzhead=e,Ct),deflate:(t,e)=>{if(_e(t)||e>kt||e<0)return t?qt(t,Wt):Wt;const i=t.state;if(!t.output||0!==t.avail_in&&!t.input||i.status===Jt&&e!==xt)return qt(t,0===t.avail_out?zt:Wt);const a=i.last_flush;if(i.last_flush=e,0!==i.pending){if(te(t),0===t.avail_out)return i.last_flush=-1,Ct}else if(0===t.avail_in&&Kt(e)<=Kt(a)&&e!==xt)return qt(t,zt);if(i.status===Jt&&0!==t.avail_in)return qt(t,zt);if(i.status===Gt&&0===i.wrap&&(i.status=jt),i.status===Gt){let e=Zt+(i.w_bits-8<<4)<<8,a=-1;if(a=i.strategy>=Mt||i.level<2?0:i.level<6?1:6===i.level?2:3,e|=a<<6,0!==i.strstart&&(e|=32),e+=31-e%31,ae(i,e),0!==i.strstart&&(ae(i,t.adler>>>16),ae(i,65535&t.adler)),t.adler=1,i.status=jt,te(t),0!==i.pending)return i.last_flush=-1,Ct}if(57===i.status)if(t.adler=0,ie(i,31),ie(i,139),ie(i,8),i.gzhead)ie(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)),ie(i,255&i.gzhead.time),ie(i,i.gzhead.time>>8&255),ie(i,i.gzhead.time>>16&255),ie(i,i.gzhead.time>>24&255),ie(i,9===i.level?2:i.strategy>=Mt||i.level<2?4:0),ie(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(ie(i,255&i.gzhead.extra.length),ie(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(t.adler=mt(t.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=69;else if(ie(i,0),ie(i,0),ie(i,0),ie(i,0),ie(i,0),ie(i,9===i.level?2:i.strategy>=Mt||i.level<2?4:0),ie(i,3),i.status=jt,te(t),0!==i.pending)return i.last_flush=-1,Ct;if(69===i.status){if(i.gzhead.extra){let e=i.pending,a=(65535&i.gzhead.extra.length)-i.gzindex;for(;i.pending+a>i.pending_buf_size;){let s=i.pending_buf_size-i.pending;if(i.pending_buf.set(i.gzhead.extra.subarray(i.gzindex,i.gzindex+s),i.pending),i.pending=i.pending_buf_size,i.gzhead.hcrc&&i.pending>e&&(t.adler=mt(t.adler,i.pending_buf,i.pending-e,e)),i.gzindex+=s,te(t),0!==i.pending)return i.last_flush=-1,Ct;e=0,a-=s}let s=new Uint8Array(i.gzhead.extra);i.pending_buf.set(s.subarray(i.gzindex,i.gzindex+a),i.pending),i.pending+=a,i.gzhead.hcrc&&i.pending>e&&(t.adler=mt(t.adler,i.pending_buf,i.pending-e,e)),i.gzindex=0}i.status=73}if(73===i.status){if(i.gzhead.name){let e,a=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>a&&(t.adler=mt(t.adler,i.pending_buf,i.pending-a,a)),te(t),0!==i.pending)return i.last_flush=-1,Ct;a=0}e=i.gzindex<i.gzhead.name.length?255&i.gzhead.name.charCodeAt(i.gzindex++):0,ie(i,e)}while(0!==e);i.gzhead.hcrc&&i.pending>a&&(t.adler=mt(t.adler,i.pending_buf,i.pending-a,a)),i.gzindex=0}i.status=91}if(91===i.status){if(i.gzhead.comment){let e,a=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>a&&(t.adler=mt(t.adler,i.pending_buf,i.pending-a,a)),te(t),0!==i.pending)return i.last_flush=-1,Ct;a=0}e=i.gzindex<i.gzhead.comment.length?255&i.gzhead.comment.charCodeAt(i.gzindex++):0,ie(i,e)}while(0!==e);i.gzhead.hcrc&&i.pending>a&&(t.adler=mt(t.adler,i.pending_buf,i.pending-a,a))}i.status=103}if(103===i.status){if(i.gzhead.hcrc){if(i.pending+2>i.pending_buf_size&&(te(t),0!==i.pending))return i.last_flush=-1,Ct;ie(i,255&t.adler),ie(i,t.adler>>8&255),t.adler=0}if(i.status=jt,te(t),0!==i.pending)return i.last_flush=-1,Ct}if(0!==t.avail_in||0!==i.lookahead||e!==It&&i.status!==Jt){let a=0===i.level?he(i,e):i.strategy===Mt?((t,e)=>{let i;for(;;){if(0===t.lookahead&&(ne(t),0===t.lookahead)){if(e===It)return 1;break}if(t.match_length=0,i=Rt(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,i&&(ee(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===xt?(ee(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ee(t,!1),0===t.strm.avail_out)?1:2})(i,e):i.strategy===Pt?((t,e)=>{let i,a,s,r;const n=t.window;for(;;){if(t.lookahead<=Vt){if(ne(t),t.lookahead<=Vt&&e===It)return 1;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=3&&t.strstart>0&&(s=t.strstart-1,a=n[s],a===n[++s]&&a===n[++s]&&a===n[++s])){r=t.strstart+Vt;do{}while(a===n[++s]&&a===n[++s]&&a===n[++s]&&a===n[++s]&&a===n[++s]&&a===n[++s]&&a===n[++s]&&a===n[++s]&&s<r);t.match_length=Vt-(r-s),t.match_length>t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=3?(i=Rt(t,1,t.match_length-3),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(i=Rt(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),i&&(ee(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===xt?(ee(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ee(t,!1),0===t.strm.avail_out)?1:2})(i,e):de[i.level].func(i,e);if(3!==a&&4!==a||(i.status=Jt),1===a||3===a)return 0===t.avail_out&&(i.last_flush=-1),Ct;if(2===a&&(e===Tt?Ut(i):e!==kt&&(Bt(i,0,0,!1),e===Dt&&(Yt(i.head),0===i.lookahead&&(i.strstart=0,i.block_start=0,i.insert=0))),te(t),0===t.avail_out))return i.last_flush=-1,Ct}return e!==xt?Ct:i.wrap<=0?Ft:(2===i.wrap?(ie(i,255&t.adler),ie(i,t.adler>>8&255),ie(i,t.adler>>16&255),ie(i,t.adler>>24&255),ie(i,255&t.total_in),ie(i,t.total_in>>8&255),ie(i,t.total_in>>16&255),ie(i,t.total_in>>24&255)):(ae(i,t.adler>>>16),ae(i,65535&t.adler)),te(t),i.wrap>0&&(i.wrap=-i.wrap),0!==i.pending?Ct:Ft)},deflateEnd:t=>{if(_e(t))return Wt;const e=t.state.status;return t.state=null,e===jt?qt(t,Ot):Ct},deflateSetDictionary:(t,e)=>{let i=e.length;if(_e(t))return Wt;const a=t.state,s=a.wrap;if(2===s||1===s&&a.status!==Gt||a.lookahead)return Wt;if(1===s&&(t.adler=pt(t.adler,e,i,0)),a.wrap=0,i>=a.w_size){0===s&&(Yt(a.head),a.strstart=0,a.block_start=0,a.insert=0);let t=new Uint8Array(a.w_size);t.set(e.subarray(i-a.w_size,i),0),e=t,i=a.w_size}const r=t.avail_in,n=t.next_in,h=t.input;for(t.avail_in=i,t.next_in=0,t.input=e,ne(a);a.lookahead>=3;){let t=a.strstart,e=a.lookahead-2;do{a.ins_h=Qt(a,a.ins_h,a.window[t+3-1]),a.prev[t&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=t,t++}while(--e);a.strstart=t,a.lookahead=2,ne(a)}return a.strstart+=a.lookahead,a.block_start=a.strstart,a.insert=a.lookahead,a.lookahead=0,a.match_length=a.prev_length=2,a.match_available=0,t.next_in=n,t.input=h,t.avail_in=r,a.wrap=s,Ct},deflateInfo:"pako deflate (from Nodeca project)"};const me=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var be=function(t){const e=Array.prototype.slice.call(arguments,1);for(;e.length;){const i=e.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(const e in i)me(i,e)&&(t[e]=i[e])}}return t},ye=t=>{let e=0;for(let i=0,a=t.length;i<a;i++)e+=t[i].length;const i=new Uint8Array(e);for(let e=0,a=0,s=t.length;e<s;e++){let s=t[e];i.set(s,a),a+=s.length}return i};let Se=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(t){Se=!1}const Be=new Uint8Array(256);for(let t=0;t<256;t++)Be[t]=t>=252?6:t>=248?5:t>=240?4:t>=224?3:t>=192?2:1;Be[254]=Be[254]=1;var ve=t=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(t);let e,i,a,s,r,n=t.length,h=0;for(s=0;s<n;s++)i=t.charCodeAt(s),55296==(64512&i)&&s+1<n&&(a=t.charCodeAt(s+1),56320==(64512&a)&&(i=65536+(i-55296<<10)+(a-56320),s++)),h+=i<128?1:i<2048?2:i<65536?3:4;for(e=new Uint8Array(h),r=0,s=0;r<h;s++)i=t.charCodeAt(s),55296==(64512&i)&&s+1<n&&(a=t.charCodeAt(s+1),56320==(64512&a)&&(i=65536+(i-55296<<10)+(a-56320),s++)),i<128?e[r++]=i:i<2048?(e[r++]=192|i>>>6,e[r++]=128|63&i):i<65536?(e[r++]=224|i>>>12,e[r++]=128|i>>>6&63,e[r++]=128|63&i):(e[r++]=240|i>>>18,e[r++]=128|i>>>12&63,e[r++]=128|i>>>6&63,e[r++]=128|63&i);return e};var Re=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 Ue=Object.prototype.toString,{Z_NO_FLUSH:Ie,Z_SYNC_FLUSH:Te,Z_FULL_FLUSH:De,Z_FINISH:xe,Z_OK:ke,Z_STREAM_END:Ce,Z_DEFAULT_COMPRESSION:Fe,Z_DEFAULT_STRATEGY:We,Z_DEFLATED:Oe}=yt;function ze(t){this.options=be({level:Fe,method:Oe,chunkSize:16384,windowBits:15,memLevel:8,strategy:We},t||{});let e=this.options;e.raw&&e.windowBits>0?e.windowBits=-e.windowBits:e.gzip&&e.windowBits>0&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new Re,this.strm.avail_out=0;let i=we.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(i!==ke)throw new Error(bt[i]);if(e.header&&we.deflateSetHeader(this.strm,e.header),e.dictionary){let t;if(t="string"==typeof e.dictionary?ve(e.dictionary):"[object ArrayBuffer]"===Ue.call(e.dictionary)?new Uint8Array(e.dictionary):e.dictionary,i=we.deflateSetDictionary(this.strm,t),i!==ke)throw new Error(bt[i]);this._dict_set=!0}}ze.prototype.push=function(t,e){const i=this.strm,a=this.options.chunkSize;let s,r;if(this.ended)return!1;for(r=e===~~e?e:!0===e?xe:Ie,"string"==typeof t?i.input=ve(t):"[object ArrayBuffer]"===Ue.call(t)?i.input=new Uint8Array(t):i.input=t,i.next_in=0,i.avail_in=i.input.length;;)if(0===i.avail_out&&(i.output=new Uint8Array(a),i.next_out=0,i.avail_out=a),(r===Te||r===De)&&i.avail_out<=6)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else{if(s=we.deflate(i,r),s===Ce)return i.next_out>0&&this.onData(i.output.subarray(0,i.next_out)),s=we.deflateEnd(this.strm),this.onEnd(s),this.ended=!0,s===ke;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},ze.prototype.onData=function(t){this.chunks.push(t)},ze.prototype.onEnd=function(t){t===ke&&(this.result=ye(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};var Ae={deflate:function(t,e){const i=new ze(e);if(i.push(t,!0),i.err)throw i.msg||bt[i.err];return i.result}};const{deflate:Ee}=Ae;var Me=Ee;const Pe={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}},$e=(t,...e)=>{let i=0;if(t.replace(/[<>]/,"").length!=e.length)throw"Pack format to Argument count mismatch";const a=[];let s=!0;for(let a=0;a<t.length;a++)"<"==t[a]?s=!0:">"==t[a]?s=!1:(r(t[a],e[i]),i++);function r(t,e){if(!(t in Pe))throw"Unhandled character '"+t+"' in pack format";const i=Pe[t].bytes,r=new DataView(new ArrayBuffer(i));Pe[t].p.bind(r)(0,e,s);for(let t=0;t<i;t++)a.push(r.getUint8(t))}return a},Le=(t,e)=>{let i=0;const a=[];let s=!0;for(const e of t)"<"==e?s=!0:">"==e?s=!1:r(e);function r(t){if(!(t in Pe))throw"Unhandled character '"+t+"' in unpack format";const r=Pe[t].bytes,n=new DataView(new ArrayBuffer(r));for(let t=0;t<r;t++)n.setUint8(t,255&e[i+t]);const h=Pe[t].u.bind(n);a.push(h(0,s)),i+=r}return a};class Ne extends EventTarget{constructor(t,e,i){super(),this.port=t,this.logger=e,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=n,this._isESP32S2NativeUSB=!1,this._initializationSucceeded=!1,this.__commandLock=Promise.resolve([0,[]]),this.__isReconfiguring=!1,this.__abandonCurrentOperation=!1,this.__adaptiveBlockMultiplier=1,this.__adaptiveMaxInFlightMultiplier=1,this.__consecutiveSuccessfulChunks=0,this.__lastAdaptiveAdjustment=0,this.__isCDCDevice=!1,this.state_DTR=!1,this.__writeChain=Promise.resolve()}get chipFamily(){return this._parent?this._parent.chipFamily:this.__chipFamily}set chipFamily(t){this._parent?this._parent.chipFamily=t:this.__chipFamily=t}get chipName(){return this._parent?this._parent.chipName:this.__chipName}set chipName(t){this._parent?this._parent.chipName=t:this.__chipName=t}get chipRevision(){return this._parent?this._parent.chipRevision:this.__chipRevision}set chipRevision(t){this._parent?this._parent.chipRevision=t:this.__chipRevision=t}get chipVariant(){return this._parent?this._parent.chipVariant:this.__chipVariant}set chipVariant(t){this._parent?this._parent.chipVariant=t:this.__chipVariant=t}get _inputBuffer(){return this._parent?this._parent._inputBuffer:this.__inputBuffer}get _inputBufferReadIndex(){return this._parent?this._parent._inputBufferReadIndex:this.__inputBufferReadIndex||0}set _inputBufferReadIndex(t){this._parent?this._parent._inputBufferReadIndex=t:this.__inputBufferReadIndex=t}get _inputBufferAvailable(){return this._inputBuffer.length-this._inputBufferReadIndex}_readByte(){if(!(this._inputBufferReadIndex>=this._inputBuffer.length))return this._inputBuffer[this._inputBufferReadIndex++]}_clearInputBuffer(){this._inputBuffer.length=0,this._inputBufferReadIndex=0}_compactInputBuffer(){this._inputBufferReadIndex>1e3&&this._inputBufferReadIndex>this._inputBuffer.length/2&&(this._inputBuffer.splice(0,this._inputBufferReadIndex),this._inputBufferReadIndex=0)}get _totalBytesRead(){return this._parent?this._parent._totalBytesRead:this.__totalBytesRead||0}set _totalBytesRead(t){this._parent?this._parent._totalBytesRead=t:this.__totalBytesRead=t}get _commandLock(){return this._parent?this._parent._commandLock:this.__commandLock}set _commandLock(t){this._parent?this._parent._commandLock=t:this.__commandLock=t}get _isReconfiguring(){return this._parent?this._parent._isReconfiguring:this.__isReconfiguring}set _isReconfiguring(t){this._parent?this._parent._isReconfiguring=t:this.__isReconfiguring=t}get _abandonCurrentOperation(){return this._parent?this._parent._abandonCurrentOperation:this.__abandonCurrentOperation}set _abandonCurrentOperation(t){this._parent?this._parent._abandonCurrentOperation=t:this.__abandonCurrentOperation=t}get _adaptiveBlockMultiplier(){return this._parent?this._parent._adaptiveBlockMultiplier:this.__adaptiveBlockMultiplier}set _adaptiveBlockMultiplier(t){this._parent?this._parent._adaptiveBlockMultiplier=t:this.__adaptiveBlockMultiplier=t}get _adaptiveMaxInFlightMultiplier(){return this._parent?this._parent._adaptiveMaxInFlightMultiplier:this.__adaptiveMaxInFlightMultiplier}set _adaptiveMaxInFlightMultiplier(t){this._parent?this._parent._adaptiveMaxInFlightMultiplier=t:this.__adaptiveMaxInFlightMultiplier=t}get _consecutiveSuccessfulChunks(){return this._parent?this._parent._consecutiveSuccessfulChunks:this.__consecutiveSuccessfulChunks}set _consecutiveSuccessfulChunks(t){this._parent?this._parent._consecutiveSuccessfulChunks=t:this.__consecutiveSuccessfulChunks=t}get _lastAdaptiveAdjustment(){return this._parent?this._parent._lastAdaptiveAdjustment:this.__lastAdaptiveAdjustment}set _lastAdaptiveAdjustment(t){this._parent?this._parent._lastAdaptiveAdjustment=t:this.__lastAdaptiveAdjustment=t}get _isCDCDevice(){return this._parent?this._parent._isCDCDevice:this.__isCDCDevice}set _isCDCDevice(t){this._parent?this._parent._isCDCDevice=t:this.__isCDCDevice=t}detectUSBSerialChip(t,e){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}}}[t];return i&&i[e]?i[e]:{name:`Unknown (VID: 0x${t.toString(16)}, PID: 0x${e.toString(16)})`}}async initialize(){if(!this._parent){this.__inputBuffer=[],this.__inputBufferReadIndex=0,this.__totalBytesRead=0;const t=this.port.getInfo();if(t.usbVendorId&&t.usbProductId){const e=this.detectUSBSerialChip(t.usbVendorId,t.usbProductId);this.logger.log(`USB-Serial: ${e.name} (VID: 0x${t.usbVendorId.toString(16)}, PID: 0x${t.usbProductId.toString(16)})`),e.maxBaudrate&&(this._maxUSBSerialBaudrate=e.maxBaudrate,this.logger.log(`Max baudrate: ${e.maxBaudrate}`)),12346===t.usbVendorId&&2===t.usbProductId&&(this._isESP32S2NativeUSB=!0),(12346===t.usbVendorId||6790===t.usbVendorId&&21971===t.usbProductId)&&(this._isCDCDevice=!0)}this.readLoop()}await this.connectWithResetStrategies(),await this.detectChip();const t=x(this.getChipFamily()),e=t.macFuse;for(let t=0;t<4;t++)this._efuses[t]=await this.readRegister(e+4*t);this.logger.log(`Chip type ${this.chipName}`),this.logger.debug(`Bootloader flash offset: 0x${t.flashOffs.toString(16)}`),this._initializationSucceeded=!0}async detectChip(){try{const t=(await this.getSecurityInfo()).chipId,e=v[t];if(e)return this.chipName=e.name,this.chipFamily=e.family,this.chipFamily===S&&(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: ${t} (${this.chipName})`);this.logger.debug(`Unknown IMAGE_CHIP_ID: ${t}, falling back to magic value detection`)}catch(t){this.logger.debug(`GET_SECURITY_INFO failed, using magic value detection: ${t}`),await this.drainInputBuffer(200),this._clearInputBuffer(),await s(T);try{await this.sync()}catch(t){this.logger.debug(`Re-sync after GET_SECURITY_INFO failure: ${t}`)}}const t=await this.readRegister(1073745920),e=R[t>>>0];if(void 0===e)throw new Error(`Unknown Chip: Hex: ${a(t>>>0,8).toLowerCase()} Number: ${t}`);this.chipName=e.name,this.chipFamily=e.family,this.chipFamily===S&&(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: ${a(t>>>0,8)} (${this.chipName})`)}async getChipRevision(){if(this.chipFamily!==S)return 0;const t=await this.readRegister(1343410252);return 100*((t>>23&1)<<2|t>>4&3)+(15&t)}async getSecurityInfo(){const[,t]=await this.checkCommand(20,[],0);if(0===t.length)throw new Error("GET_SECURITY_INFO not supported or returned empty response");if(t.length<12)throw new Error(`Invalid security info response length: ${t.length} (expected at least 12 bytes)`);return{flags:Le("<I",t.slice(0,4))[0],flashCryptCnt:t[4],keyPurposes:Array.from(t.slice(5,12)),chipId:t.length>=16?Le("<I",t.slice(12,16))[0]:0,apiVersion:t.length>=20?Le("<I",t.slice(16,20))[0]:0}}async readLoop(){this.debug&&this.logger.debug("Starting read loop"),this._reader=this.port.readable.getReader();try{let t=!0;for(;t;){const{value:e,done:i}=await this._reader.read();if(i){this._reader.releaseLock(),t=!1;break}if(!e||0===e.length)continue;const a=Array.from(e);Array.prototype.push.apply(this._inputBuffer,a),this._totalBytesRead+=e.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(t=100){return new Promise(e=>setTimeout(e,t))}async setRTS(t){await this.port.setSignals({requestToSend:t}),await this.setDTR(this.state_DTR)}async setDTR(t){this.state_DTR=t,await this.port.setSignals({dataTerminalReady:t})}async hardResetUSBJTAGSerial(){await this.setRTS(!1),await this.setDTR(!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),await this.sleep(200)}async hardResetClassic(){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),await this.sleep(200)}async setRTSWebUSB(t){await this.port.setSignals({requestToSend:t,dataTerminalReady:this.state_DTR})}async setDTRWebUSB(t){this.state_DTR=t,await this.port.setSignals({dataTerminalReady:t,requestToSend:void 0})}async setDTRandRTSWebUSB(t,e){this.state_DTR=t,await this.port.setSignals({dataTerminalReady:t,requestToSend:e})}async hardResetUSBJTAGSerialWebUSB(){await this.setRTSWebUSB(!1),await this.setDTRWebUSB(!1),await this.sleep(100),await this.setDTRWebUSB(!0),await this.setRTSWebUSB(!1),await this.sleep(100),await this.setRTSWebUSB(!0),await this.setDTRWebUSB(!1),await this.setRTSWebUSB(!0),await this.sleep(100),await this.setDTRWebUSB(!1),await this.setRTSWebUSB(!1),await this.sleep(200)}async hardResetUSBJTAGSerialInvertedDTRWebUSB(){await this.setRTSWebUSB(!1),await this.setDTRWebUSB(!0),await this.sleep(100),await this.setDTRWebUSB(!1),await this.setRTSWebUSB(!1),await this.sleep(100),await this.setRTSWebUSB(!0),await this.setDTRWebUSB(!0),await this.setRTSWebUSB(!0),await this.sleep(100),await this.setDTRWebUSB(!0),await this.setRTSWebUSB(!1),await this.sleep(200)}async hardResetClassicWebUSB(){await this.setDTRWebUSB(!1),await this.setRTSWebUSB(!0),await this.sleep(100),await this.setDTRWebUSB(!0),await this.setRTSWebUSB(!1),await this.sleep(50),await this.setDTRWebUSB(!1),await this.sleep(200)}async hardResetUnixTightWebUSB(){await this.setDTRandRTSWebUSB(!1,!1),await this.setDTRandRTSWebUSB(!0,!0),await this.setDTRandRTSWebUSB(!1,!0),await this.sleep(100),await this.setDTRandRTSWebUSB(!0,!1),await this.sleep(50),await this.setDTRandRTSWebUSB(!1,!1),await this.setDTRWebUSB(!1),await this.sleep(200)}async hardResetClassicLongDelayWebUSB(){await this.setDTRWebUSB(!1),await this.setRTSWebUSB(!0),await this.sleep(500),await this.setDTRWebUSB(!0),await this.setRTSWebUSB(!1),await this.sleep(200),await this.setDTRWebUSB(!1),await this.sleep(500)}async hardResetClassicShortDelayWebUSB(){await this.setDTRWebUSB(!1),await this.setRTSWebUSB(!0),await this.sleep(50),await this.setDTRWebUSB(!0),await this.setRTSWebUSB(!1),await this.sleep(25),await this.setDTRWebUSB(!1),await this.sleep(100)}async hardResetInvertedWebUSB(){await this.setDTRWebUSB(!0),await this.setRTSWebUSB(!1),await this.sleep(100),await this.setDTRWebUSB(!1),await this.setRTSWebUSB(!0),await this.sleep(50),await this.setDTRWebUSB(!0),await this.sleep(200)}async hardResetInvertedDTRWebUSB(){await this.setDTRWebUSB(!0),await this.setRTSWebUSB(!0),await this.sleep(100),await this.setDTRWebUSB(!1),await this.setRTSWebUSB(!1),await this.sleep(50),await this.setDTRWebUSB(!0),await this.sleep(200)}async hardResetInvertedRTSWebUSB(){await this.setDTRWebUSB(!1),await this.setRTSWebUSB(!1),await this.sleep(100),await this.setDTRWebUSB(!0),await this.setRTSWebUSB(!0),await this.sleep(50),await this.setDTRWebUSB(!1),await this.sleep(200)}isWebUSB(){return!0===this.port.isWebUSB}async connectWithResetStrategies(){const t=this.port.getInfo(),e=4097===t.usbProductId,i=12346===t.usbVendorId,a=[],r=this;if(this.isWebUSB()){const s=!e&&!i,n=4292===t.usbVendorId,h=6790===t.usbVendorId,o=12346===t.usbVendorId&&2===t.usbProductId;(e||i)&&(o?(a.push({name:"USB-JTAG/Serial (WebUSB) - ESP32-S2",fn:async function(){return await r.hardResetUSBJTAGSerialWebUSB()}}),a.push({name:"USB-JTAG/Serial Inverted DTR (WebUSB) - ESP32-S2",fn:async function(){return await r.hardResetUSBJTAGSerialInvertedDTRWebUSB()}}),a.push({name:"UnixTight (WebUSB) - ESP32-S2 CDC",fn:async function(){return await r.hardResetUnixTightWebUSB()}}),a.push({name:"Classic (WebUSB) - ESP32-S2 CDC",fn:async function(){return await r.hardResetClassicWebUSB()}})):(a.push({name:"USB-JTAG/Serial Inverted DTR (WebUSB)",fn:async function(){return await r.hardResetUSBJTAGSerialInvertedDTRWebUSB()}}),a.push({name:"USB-JTAG/Serial (WebUSB)",fn:async function(){return await r.hardResetUSBJTAGSerialWebUSB()}}),a.push({name:"Inverted DTR Classic (WebUSB)",fn:async function(){return await r.hardResetInvertedDTRWebUSB()}}))),s&&(h?(a.push({name:"UnixTight (WebUSB) - CH34x",fn:async function(){return await r.hardResetUnixTightWebUSB()}}),a.push({name:"Classic (WebUSB) - CH34x",fn:async function(){return await r.hardResetClassicWebUSB()}}),a.push({name:"Inverted Both (WebUSB) - CH34x",fn:async function(){return await r.hardResetInvertedWebUSB()}}),a.push({name:"Inverted RTS (WebUSB) - CH34x",fn:async function(){return await r.hardResetInvertedRTSWebUSB()}}),a.push({name:"Inverted DTR (WebUSB) - CH34x",fn:async function(){return await r.hardResetInvertedDTRWebUSB()}})):n?(a.push({name:"UnixTight (WebUSB) - CP2102",fn:async function(){return await r.hardResetUnixTightWebUSB()}}),a.push({name:"Classic (WebUSB) - CP2102",fn:async function(){return await r.hardResetClassicWebUSB()}}),a.push({name:"Inverted Both (WebUSB) - CP2102",fn:async function(){return await r.hardResetInvertedWebUSB()}}),a.push({name:"Inverted RTS (WebUSB) - CP2102",fn:async function(){return await r.hardResetInvertedRTSWebUSB()}}),a.push({name:"Inverted DTR (WebUSB) - CP2102",fn:async function(){return await r.hardResetInvertedDTRWebUSB()}})):(a.push({name:"UnixTight (WebUSB)",fn:async function(){return await r.hardResetUnixTightWebUSB()}}),a.push({name:"Classic (WebUSB)",fn:async function(){return await r.hardResetClassicWebUSB()}}),a.push({name:"Inverted Both (WebUSB)",fn:async function(){return await r.hardResetInvertedWebUSB()}}),a.push({name:"Inverted RTS (WebUSB)",fn:async function(){return await r.hardResetInvertedRTSWebUSB()}}),a.push({name:"Inverted DTR (WebUSB)",fn:async function(){return await r.hardResetInvertedDTRWebUSB()}}))),n||o||(6790!==t.usbVendorId&&a.push({name:"Classic (WebUSB)",fn:async function(){return await r.hardResetClassicWebUSB()}}),a.push({name:"UnixTight (WebUSB)",fn:async function(){return await r.hardResetUnixTightWebUSB()}}),a.push({name:"Classic Long Delay (WebUSB)",fn:async function(){return await r.hardResetClassicLongDelayWebUSB()}}),a.push({name:"Classic Short Delay (WebUSB)",fn:async function(){return await r.hardResetClassicShortDelayWebUSB()}}),e||i||a.push({name:"USB-JTAG/Serial fallback (WebUSB)",fn:async function(){return await r.hardResetUSBJTAGSerialWebUSB()}}))}else(e||i)&&a.push({name:"USB-JTAG/Serial",fn:async function(){return await r.hardResetUSBJTAGSerial()}}),a.push({name:"Classic",fn:async function(){return await r.hardResetClassic()}}),e||i||a.push({name:"USB-JTAG/Serial (fallback)",fn:async function(){return await r.hardResetUSBJTAGSerial()}});let n=null;for(const t of a)try{if(!this.connected||!this.port.writable){this.logger.log(`Port disconnected, skipping ${t.name} reset`);continue}this._abandonCurrentOperation=!1,await t.fn();if(await this.syncWithTimeout(3e3))return void this.logger.log(`Connected successfully with ${t.name} reset.`);throw new Error("Sync timeout or abandoned")}catch(e){if(n=e,this.logger.log(`${t.name} reset failed: ${e.message}`),this._abandonCurrentOperation=!0,await s(100),!this.connected||!this.port.writable){this.logger.log("Port disconnected during reset attempt");break}this._clearInputBuffer(),await this.drainInputBuffer(200),await this.flushSerialBuffers()}throw new Error(`Couldn't sync to ESP. Try resetting manually. Last error: ${null==n?void 0:n.message}`)}async hardReset(t=!1){t?4097===this.port.getInfo().usbProductId?(await this.hardResetUSBJTAGSerial(),this.logger.log("USB-JTAG/Serial reset.")):this.isWebUSB()?(await this.hardResetClassicWebUSB(),this.logger.log("Classic reset (WebUSB/Android).")):(await this.hardResetClassic(),this.logger.log("Classic reset.")):this.isWebUSB()?(await this.setRTS(!0),await this.sleep(200),await this.setRTS(!1),await this.sleep(200),this.logger.log("Hard reset (WebUSB).")):(await this.setRTS(!0),await this.sleep(100),await this.setRTS(!1),this.logger.log("Hard reset.")),await new Promise(t=>setTimeout(t,1e3))}macAddr(){const t=new Array(6).fill(0),e=this._efuses[0],i=this._efuses[1],a=this._efuses[2],s=this._efuses[3];let r;if(this.chipFamily==l){if(0!=s)r=[s>>16&255,s>>8&255,255&s];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];t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=i>>8&255,t[4]=255&i,t[5]=e>>24&255}else if(this.chipFamily==u)t[0]=a>>8&255,t[1]=255&a,t[2]=i>>24&255,t[3]=i>>16&255,t[4]=i>>8&255,t[5]=255&i;else{if(this.chipFamily!=d&&this.chipFamily!=c&&this.chipFamily!=_&&this.chipFamily!=f&&this.chipFamily!=g&&this.chipFamily!=p&&this.chipFamily!=w&&this.chipFamily!=m&&this.chipFamily!=b&&this.chipFamily!=y&&this.chipFamily!=S&&this.chipFamily!=B)throw new Error("Unknown chip family");t[0]=i>>8&255,t[1]=255&i,t[2]=e>>24&255,t[3]=e>>16&255,t[4]=e>>8&255,t[5]=255&e}return t}async readRegister(t){this.debug&&this.logger.debug("Reading from Register "+a(t,8));const e=$e("<I",t);await this.sendCommand(10,e);const[i]=await this.getResponse(10);return i}async checkCommand(t,e,i=0,s=3e3){const r=async()=>{s=Math.min(s,3e5),await this.sendCommand(t,e,i);const[r,n]=await this.getResponse(t,s);if(null===n)throw new Error("Didn't get enough status bytes");let h=n,o=0;if(this.IS_STUB||this.chipFamily==l?o=2:[u,d,c,_,f,g,p,w,m,b,y,S,B].includes(this.chipFamily)||20===t?o=4:[2,4].includes(h.length)?o=h.length:(o=2,this.logger.debug(`Unknown chip family, defaulting to 2-byte status (opcode: ${a(t)}, data.length: ${h.length})`)),h.length<o)throw new Error("Didn't get enough status bytes");const v=h.slice(-o,h.length);if(h=h.slice(0,-o),this.debug&&(this.logger.debug("status",v),this.logger.debug("value",r),this.logger.debug("data",h)),1==v[0])throw 5==v[1]?(await this.drainInputBuffer(200),new Error("Invalid (unsupported) command "+a(t))):new Error("Command failure error code "+a(v[1]));return[r,h]};return this._commandLock=this._commandLock.then(r,r),this._commandLock}async sendCommand(e,i,a=0){const s=t([...$e("<BBHI",0,e,i.length,a),...i]);this.debug&&this.logger.debug(`Writing ${s.length} byte${1==s.length?"":"s"}:`,s),await this.writeToStream(s)}async readPacket(t){let e=null,r=!1;if(this._isCDCDevice){const n=Date.now();for(;;){if(this._abandonCurrentOperation)throw new k("Operation abandoned (reset strategy timeout)");if(Date.now()-n>t){throw new k("Timed out waiting for packet "+(null===e?"header":"content"))}if(0!==this._inputBufferAvailable)for(;this._inputBufferAvailable>0;){const t=this._readByte();if(null===e){if(192!=t)throw this.debug&&(this.logger.debug("Read invalid data: "+a(t)),this.logger.debug("Remaining data in serial buffer: "+i(this._inputBuffer))),new k("Invalid head of packet ("+a(t)+")");e=[]}else if(r)if(r=!1,220==t)e.push(192);else{if(221!=t)throw this.debug&&(this.logger.debug("Read invalid data: "+a(t)),this.logger.debug("Remaining data in serial buffer: "+i(this._inputBuffer))),new k("Invalid SLIP escape (0xdb, "+a(t)+")");e.push(219)}else if(219==t)r=!0;else{if(192==t)return this.debug&&this.logger.debug("Received full packet: "+i(e)),this._compactInputBuffer(),e;e.push(t)}}else await s(1)}}else{let n=[];for(;;){if(this._abandonCurrentOperation)throw new k("Operation abandoned (reset strategy timeout)");const h=Date.now();for(n=[];Date.now()-h<t;){if(this._inputBufferAvailable>0){n.push(this._readByte());break}await s(1)}if(0==n.length){throw new k("Timed out waiting for packet "+(null===e?"header":"content"))}this.debug&&this.logger.debug("Read "+n.length+" bytes: "+i(n));for(const t of n)if(null===e){if(192!=t)throw this.debug&&(this.logger.debug("Read invalid data: "+a(t)),this.logger.debug("Remaining data in serial buffer: "+i(this._inputBuffer))),new k("Invalid head of packet ("+a(t)+")");e=[]}else if(r)if(r=!1,220==t)e.push(192);else{if(221!=t)throw this.debug&&(this.logger.debug("Read invalid data: "+a(t)),this.logger.debug("Remaining data in serial buffer: "+i(this._inputBuffer))),new k("Invalid SLIP escape (0xdb, "+a(t)+")");e.push(219)}else if(219==t)r=!0;else{if(192==t)return this.debug&&this.logger.debug("Received full packet: "+i(e)),this._compactInputBuffer(),e;e.push(t)}}}}async getResponse(t,e=3e3){for(let i=0;i<100;i++){const i=await this.readPacket(e);if(i.length<8)continue;const[s,r,,n]=Le("<BBHI",i.slice(0,8));if(1!=s)continue;const h=i.slice(8);if(null==t||r==t)return[n,h];if(0!=h[0]&&5==h[1])throw await this.drainInputBuffer(200),new Error(`Invalid (unsupported) command ${a(t)}`)}throw new Error("Response doesn't match request")}checksum(t,e=239){for(const i of t)e^=i;return e}async setBaudrate(t){if(this.chipFamily==l)throw new Error("Changing baud rate is not supported on the ESP8266");try{const e=$e("<II",t,this.IS_STUB?n:0);await this.checkCommand(15,e)}catch(e){throw this.logger.error(`Baudrate change error: ${e}`),new Error(`Unable to change the baud rate to ${t}: No response from set baud rate command.`)}this._parent?await this._parent.reconfigurePort(t):await this.reconfigurePort(t),await s(T),this._parent?this._parent._currentBaudRate=t:this._currentBaudRate=t;const e=this._parent?this._parent._maxUSBSerialBaudrate:this._maxUSBSerialBaudrate;e&&t>e&&(this.logger.log(`⚠️ WARNING: Baudrate ${t} exceeds USB-Serial chip limit (${e})!`),this.logger.log("⚠️ This may cause data corruption or connection failures!")),this.logger.log(`Changed baud rate to ${t}`)}async reconfigurePort(t){var e;this._isReconfiguring=!0;try{try{await this._writeChain}catch(t){this.logger.debug(`Pending write error during reconfigure: ${t}`)}if(this.isWebUSB()){const e=this.port.getInfo(),i=6790===e.usbVendorId&&21971===e.usbProductId;if(!i&&"function"==typeof this.port.setBaudRate)return await this.port.setBaudRate(t),void await s(100)}if(this._writer){try{this._writer.releaseLock()}catch(t){this.logger.debug(`Writer release error during reconfigure: ${t}`)}this._writer=void 0}await(null===(e=this._reader)||void 0===e?void 0:e.cancel()),await this.port.close(),await this.port.open({baudRate:t}),await this.flushSerialBuffers(),this.readLoop()}catch(e){throw this.logger.error(`Reconfigure port error: ${e}`),new Error(`Unable to change the baud rate to ${t}: ${e}`)}finally{this._isReconfiguring=!1}}async syncWithTimeout(t){const e=Date.now();for(let i=0;i<5;i++){if(Date.now()-e>t)return!1;if(this._abandonCurrentOperation)return!1;this._clearInputBuffer();try{if(await this._sync())return await s(T),!0}catch(t){if(this._abandonCurrentOperation)return!1}await s(T)}return!1}async sync(){for(let t=0;t<5;t++){this._clearInputBuffer();if(await this._sync())return await s(T),!0;await s(T)}throw new Error("Couldn't sync to ESP. Try resetting.")}async _sync(){await this.sendCommand(8,o);for(let t=0;t<8;t++)try{const[,t]=await this.getResponse(8,T);if(t.length>1&&0==t[0]&&0==t[1])return!0}catch(e){this.debug&&this.logger.debug(`Sync attempt ${t+1} failed: ${e}`)}return!1}getFlashWriteSize(){return this.IS_STUB?16384:1024}async flashData(t,e,i=0,s=!1){if(t.byteLength>=8){const e=Array.from(new Uint8Array(t,0,4)),i=e[0],s=e[2],r=e[3];this.logger.log(`Image header, Magic=${a(i)}, FlashMode=${a(s)}, FlashSizeFreq=${a(r)}`)}const r=t.byteLength;let n,h=0,o=U;s?(n=Me(new Uint8Array(t),{level:9}).buffer,h=n.byteLength,this.logger.log(`Writing data with filesize: ${r}. Compressed Size: ${h}`),o=await this.flashDeflBegin(r,h,i)):(this.logger.log(`Writing data with filesize: ${r}`),n=t,await this.flashBegin(r,i));let l=[],u=0,d=0,c=0;const _=Date.now(),f=this.getFlashWriteSize(),g=s?h:r;for(;g-c>0;)this.debug&&this.logger.log(`Writing at ${a(i+u*f,8)} `),g-c>=f?l=Array.from(new Uint8Array(n,c,f)):(l=Array.from(new Uint8Array(n,c,g-c)),s||(l=l.concat(new Array(f-l.length).fill(255)))),s?await this.flashDeflBlock(l,u,o):await this.flashBlock(l,u),u+=1,d+=s?Math.round(l.length*r/h):l.length,c+=f,e(Math.min(d,r),r);this.logger.log("Took "+(Date.now()-_)+"ms to write "+g+" bytes"),this.IS_STUB&&(await this.flashBegin(0,0),s?await this.flashDeflFinish():await this.flashFinish())}async flashBlock(t,e,i=3e3){await this.checkCommand(3,$e("<IIII",t.length,e,0,0).concat(t),this.checksum(t),i)}async flashDeflBlock(t,e,i=3e3){await this.checkCommand(17,$e("<IIII",t.length,e,0,0).concat(t),this.checksum(t),i)}async flashBegin(t=0,e=0,i=!1){let s;await this.flushSerialBuffers();const r=this.getFlashWriteSize();!this.IS_STUB&&[u,d,c,_,f,g,p,w,m,b,y,S,B].includes(this.chipFamily)&&await this.checkCommand(13,new Array(8).fill(0));const n=Math.floor((t+r-1)/r);s=this.chipFamily==l?this.getEraseSize(e,t):t;const h=this.IS_STUB?U:D(3e4,t),o=Date.now();let v=$e("<IIII",s,n,r,e);return this.chipFamily!=u&&this.chipFamily!=d&&this.chipFamily!=c&&this.chipFamily!=_&&this.chipFamily!=f&&this.chipFamily!=g&&this.chipFamily!=p&&this.chipFamily!=w&&this.chipFamily!=m&&this.chipFamily!=b&&this.chipFamily!=y&&this.chipFamily!=S&&this.chipFamily!=B||(v=v.concat($e("<I",i?1:0))),this.logger.log("Erase size "+s+", blocks "+n+", block size "+a(r,4)+", offset "+a(e,4)+", encrypted "+(i?"yes":"no")),await this.checkCommand(2,v,0,h),0==t||this.IS_STUB||this.logger.log("Took "+(Date.now()-o)+"ms to erase "+n+" bytes"),n}async flashDeflBegin(t=0,e=0,i=0){const a=this.getFlashWriteSize(),s=Math.floor((e+a-1)/a),r=Math.floor((t+a-1)/a);let n=0,h=0;this.IS_STUB?(n=t,h=D(3e4,n)):(n=r*a,h=U);const o=$e("<IIII",n,s,a,i);return await this.checkCommand(16,o,0,h),h}async flashFinish(){const t=$e("<I",1);await this.checkCommand(4,t)}async flashDeflFinish(){const t=$e("<I",1);await this.checkCommand(18,t)}getBootloaderOffset(){return x(this.getChipFamily()).flashOffs}async flashId(){return await this.runSpiFlashCommand(159,[],24)}getChipFamily(){return this._parent?this._parent.chipFamily:this.chipFamily}async writeRegister(t,e,i=4294967295,a=0,s=0){let r=$e("<IIII",t,e,i,a);s>0&&(r=r.concat($e("<IIII",x(this.getChipFamily()).uartDateReg,0,0,s))),await this.checkCommand(9,r)}async setDataLengths(t,e,i){if(-1!=t.mosiDlenOffs){const a=t.regBase+t.mosiDlenOffs,s=t.regBase+t.misoDlenOffs;e>0&&await this.writeRegister(a,e-1),i>0&&await this.writeRegister(s,i-1)}else{const a=t.regBase+t.usr1Offs,s=(0==i?0:i-1)<<8|(0==e?0:e-1)<<17;await this.writeRegister(a,s)}}async waitDone(t,e){for(let i=0;i<10;i++){if(0==(await this.readRegister(t)&e))return}throw Error("SPI command did not complete in time")}async runSpiFlashCommand(t,e,i=0){const s=x(this.getChipFamily()),r=s.regBase,n=r,h=r+s.usrOffs,o=r+s.usr2Offs,l=r+s.w0Offs,u=1<<18;if(i>32)throw new Error("Reading more than 32 bits back from a SPI flash operation is unsupported");if(e.length>64)throw new Error("Writing more than 64 bytes of data with one SPI command is unsupported");const d=8*e.length,c=await this.readRegister(h),_=await this.readRegister(o);let f=1<<31;if(i>0&&(f|=268435456),d>0&&(f|=134217728),await this.setDataLengths(s,d,i),await this.writeRegister(h,f),await this.writeRegister(o,7<<28|t),0==d)await this.writeRegister(l,0);else{const t=(4-e.length%4)%4;e=e.concat(new Array(t).fill(0));const i=Le("I".repeat(Math.floor(e.length/4)),e);let s=l;this.logger.debug(`Words Length: ${i.length}`);for(const t of i)this.logger.debug(`Writing word ${a(t)} to register offset ${a(s)}`),await this.writeRegister(s,t),s+=4}await this.writeRegister(n,u),await this.waitDone(n,u);const g=await this.readRegister(l);return await this.writeRegister(h,c),await this.writeRegister(o,_),g}async detectFlashSize(){this.logger.log("Detecting Flash Size");const t=await this.flashId(),e=255&t,i=t>>16&255;this.logger.log(`FlashId: ${a(t)}`),this.logger.log(`Flash Manufacturer: ${e.toString(16)}`),this.logger.log(`Flash Device: ${(t>>8&255).toString(16)}${i.toString(16)}`),this.flashSize=r[i],this.logger.log(`Auto-detected Flash size: ${this.flashSize}`)}getEraseSize(t,e){const i=4096,a=Math.floor((e+i-1)/i);let s=16-Math.floor(t/i)%16;return a<s&&(s=a),a<2*s?Math.floor((a+1)/2*i):(a-s)*i}async memBegin(t,e,i,a){return await this.checkCommand(5,$e("<IIII",t,e,i,a))}async memBlock(t,e){return await this.checkCommand(7,$e("<IIII",t.length,e,0,0).concat(t),this.checksum(t))}async memFinish(t=0){const e=this.IS_STUB?U:500,i=$e("<II",0==t?1:0,t);return await this.checkCommand(6,i,0,e)}async runStub(t=!1){const e=await C(this.chipFamily,this.chipRevision);if(null===e)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 t of["text","data"]){const a=e[t],s=e[`${t}_start`],r=a.length,n=Math.floor((r+i-1)/i);await this.memBegin(r,n,i,s);for(const t of Array(n).keys()){const e=t*i;let s=e+i;s>r&&(s=r),await this.memBlock(a.slice(e,s),t)}}await this.memFinish(e.entry);const a=await this.readPacket(500),s=String.fromCharCode(...a);if("OHAI"!=s)throw new Error("Failed to start stub. Unexpected response: "+s);this.logger.log("Stub is now running...");const r=new Ze(this.port,this.logger,this);return t||await r.detectFlashSize(),r}get _writer(){return this._parent?this._parent._writer:this.__writer}set _writer(t){this._parent?this._parent._writer=t:this.__writer=t}get _writeChain(){return this._parent?this._parent._writeChain:this.__writeChain}set _writeChain(t){this._parent?this._parent._writeChain=t:this.__writeChain=t}async writeToStream(t){if(this.port.writable){if(this._isReconfiguring)throw new Error("Cannot write during port reconfiguration");this._writeChain=this._writeChain.then(async()=>{if(!this.port.writable)throw new Error("Port became unavailable during write");if(!this._writer)try{this._writer=this.port.writable.getWriter()}catch(t){throw this.logger.error(`Failed to get writer: ${t}`),t}await this._writer.write(new Uint8Array(t))},async()=>{if(this.logger.debug("Previous write failed, attempting recovery for current write"),!this.port.writable)throw new Error("Port became unavailable during write");if(!this._writer)try{this._writer=this.port.writable.getWriter()}catch(t){throw this.logger.debug(`Failed to get writer in recovery: ${t}`),new Error("Cannot acquire writer lock")}await this._writer.write(new Uint8Array(t))}).catch(t=>{if(this.logger.error(`Write error: ${t}`),this._writer){try{this._writer.releaseLock()}catch{}this._writer=void 0}throw t}),await this._writeChain}else this.logger.debug("Port writable stream not available, skipping write")}async disconnect(){if(this._parent)await this._parent.disconnect();else if(this.port.writable)try{try{await this._writeChain}catch(t){this.logger.debug(`Pending write error during disconnect: ${t}`)}if(this._isReconfiguring=!0,this._writer){try{await this._writer.close(),this._writer.releaseLock()}catch(t){this.logger.debug(`Writer close/release error: ${t}`)}this._writer=void 0}else try{const t=this.port.writable.getWriter();await t.close(),t.releaseLock()}catch(t){this.logger.debug(`Direct writer close error: ${t}`)}await new Promise(t=>{this._reader?(this.addEventListener("disconnect",t,{once:!0}),this._reader.cancel()):t(void 0)}),this.connected=!1}finally{this._isReconfiguring=!1}else this.logger.debug("Port already closed, skipping disconnect")}async reconnect(){if(this._parent)await this._parent.reconnect();else try{this.logger.log("Reconnecting serial port..."),this.connected=!1,this.__inputBuffer=[],this.__inputBufferReadIndex=0;try{await this._writeChain}catch(t){this.logger.debug(`Pending write error during reconnect: ${t}`)}if(this._isReconfiguring=!0,this._writer){try{this._writer.releaseLock()}catch(t){this.logger.debug(`Writer release error during reconnect: ${t}`)}this._writer=void 0}if(this._reader){try{await this._reader.cancel()}catch(t){this.logger.debug(`Reader cancel error: ${t}`)}this._reader=void 0}try{await this.port.close(),this.logger.log("Port closed")}catch(t){this.logger.debug(`Port close error: ${t}`)}this.logger.debug("Opening port...");try{await this.port.open({baudRate:n}),this.connected=!0}catch(t){throw new Error(`Failed to open port: ${t}`)}if(!this.port.readable||!this.port.writable)throw new Error(`Port streams not available after open (readable: ${!!this.port.readable}, writable: ${!!this.port.writable})`);this._isReconfiguring=!1;const t=this.chipFamily,e=this.chipName,i=this.chipRevision,a=this.chipVariant,s=this.flashSize;if(await this.hardReset(!0),this._parent||(this.__inputBuffer=[],this.__inputBufferReadIndex=0,this.__totalBytesRead=0,this.readLoop()),await this.flushSerialBuffers(),await this.sync(),this.chipFamily=t,this.chipName=e,this.chipRevision=i,this.chipVariant=a,this.flashSize=s,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!==n&&(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=!0,this.logger.debug("Reconnection successful")}catch(t){throw this._isReconfiguring=!1,t}}async drainInputBuffer(t=200){await s(t);let e=0;const i=Date.now();for(;e<112&&Date.now()-i<100;)if(this._inputBufferAvailable>0){void 0!==this._readByte()&&e++}else await s(1);e>0&&this.logger.debug(`Drained ${e} bytes from input buffer`),this._parent||(this.__inputBuffer=[],this.__inputBufferReadIndex=0)}async flushSerialBuffers(){this._parent||(this.__inputBuffer=[],this.__inputBufferReadIndex=0),await s(T),this._parent||(this.__inputBuffer=[],this.__inputBufferReadIndex=0),this.logger.debug("Serial buffers flushed")}async readFlash(e,i,a){if(!this.IS_STUB)throw new Error("Reading flash is only supported in stub mode. Please run runStub() first.");let r;await this.flushSerialBuffers(),this.logger.log(`Reading ${i} bytes from flash at address 0x${e.toString(16)}...`),this.isWebUSB()&&(this._isCDCDevice?(this._adaptiveBlockMultiplier=8,this._adaptiveMaxInFlightMultiplier=8,this._consecutiveSuccessfulChunks=0,this.logger.debug(`CDC device - Initialized: blockMultiplier=${this._adaptiveBlockMultiplier}, maxInFlightMultiplier=${this._adaptiveMaxInFlightMultiplier}`)):(this._adaptiveBlockMultiplier=1,this._adaptiveMaxInFlightMultiplier=1,this._consecutiveSuccessfulChunks=0,this.logger.debug("Non-CDC device - Fixed values: blockSize=31, maxInFlight=31"))),r=this.isWebUSB()?16384:262144;let n=new Uint8Array(0),h=e,o=i;for(;o>0;){const e=Math.min(r,o);let l=!1,u=0;const d=5;let c=!1;for(;!l&&u<=d;){let i=new Uint8Array(0),a=0;try{let r,o;if(0===u&&this.logger.debug(`Reading chunk at 0x${h.toString(16)}, size: 0x${e.toString(16)}`),this.isWebUSB()){const t=this.port.maxTransferSize||64,e=Math.floor((t-2)/2);r=e*this._adaptiveBlockMultiplier,o=e*this._adaptiveMaxInFlightMultiplier}else{const t=63;r=65*t,o=130*t}const d=$e("<IIII",h,e,r,o),[c]=await this.checkCommand(210,d);if(0!=c)throw new Error("Failed to read memory: "+c);for(;i.length<e;){let r;try{r=await this.readPacket(100)}catch(t){if(t instanceof k){this.logger.debug(`SLIP read error at ${i.length} bytes: ${t.message}`);try{const t=[192,192];await this.writeToStream(t),this.logger.debug("Sent abort frame to stub"),await s(50)}catch(t){this.logger.debug(`Abort frame error: ${t}`)}if(await this.drainInputBuffer(200),i.length>=e)break}throw t}if(r&&r.length>0){const s=new Uint8Array(r),n=new Uint8Array(i.length+s.length);n.set(i),n.set(s,i.length),i=n;if(i.length>=e||i.length>=a+o){const e=$e("<I",i.length),s=t(e);await this.writeToStream(s),a=i.length}}}const _=new Uint8Array(n.length+i.length);if(_.set(n),_.set(i,n.length),n=_,l=!0,this.isWebUSB()&&this._isCDCDevice&&0===u&&(this._consecutiveSuccessfulChunks++,this._consecutiveSuccessfulChunks>=2)){const t=this.port.maxTransferSize||64,e=Math.floor((t-2)/2),i=8,a=8;let s=!1;if(this._adaptiveBlockMultiplier<i?(this._adaptiveBlockMultiplier=Math.min(2*this._adaptiveBlockMultiplier,i),s=!0):this._adaptiveMaxInFlightMultiplier<a&&(this._adaptiveMaxInFlightMultiplier=Math.min(2*this._adaptiveMaxInFlightMultiplier,a),s=!0),s){const t=e*this._adaptiveBlockMultiplier,i=e*this._adaptiveMaxInFlightMultiplier;this.logger.debug(`Speed increased: blockSize=${t}, maxInFlight=${i}`),this._lastAdaptiveAdjustment=Date.now()}this._consecutiveSuccessfulChunks=0}}catch(t){if(u++,this.isWebUSB()&&this._isCDCDevice&&1===u)if(this._adaptiveBlockMultiplier>1||this._adaptiveMaxInFlightMultiplier>1){this._adaptiveBlockMultiplier=1,this._adaptiveMaxInFlightMultiplier=1,this._consecutiveSuccessfulChunks=0;const t=this.port.maxTransferSize||64,e=Math.floor((t-2)/2),i=e*this._adaptiveBlockMultiplier,a=e*this._adaptiveMaxInFlightMultiplier;this.logger.debug(`Error at higher speed - reduced to minimum: blockSize=${i}, maxInFlight=${a}`)}else this.logger.debug("Error at minimum speed (blockSize=31, maxInFlight=31) - not a speed issue");if(!(t instanceof k))throw t;if(u<=d){this.logger.log(`${t.message} at 0x${h.toString(16)}. Draining buffer and retrying (attempt ${u}/${d})...`);try{await this.drainInputBuffer(200),await this.flushSerialBuffers(),await s(T)}catch(t){this.logger.debug(`Buffer drain error: ${t}`)}}else{if(c)throw new Error(`Failed to read chunk at 0x${h.toString(16)} after ${d} retries and recovery attempt`);c=!0,this.logger.log(`All retries exhausted at 0x${h.toString(16)}. Attempting recovery (close and reopen port)...`);try{await this.reconnect(),this.logger.log("Deep recovery successful. Resuming read from current position..."),u=0;continue}catch(t){throw new Error(`Failed to read chunk at 0x${h.toString(16)} after ${d} retries and recovery failed: ${t}`)}}}}a&&a(new Uint8Array(e),n.length,i),h+=e,o-=e,this.logger.debug(`Total progress: 0x${n.length.toString(16)} from 0x${i.toString(16)} bytes`)}return n}}class Ze extends Ne{constructor(){super(...arguments),this.IS_STUB=!0}async memBegin(t,e,i,s){const r=await C(this.chipFamily,this.chipRevision);if(null===r)return[0,[]];const n=s,h=s+t;this.logger.debug(`Load range: ${a(n,8)}-${a(h,8)}`),this.logger.debug(`Stub data: ${a(r.data_start,8)}, len: ${r.data.length}, text: ${a(r.text_start,8)}, len: ${r.text.length}`);for(const[t,e]of[[r.data_start,r.data_start+r.data.length],[r.text_start,r.text_start+r.text.length]])if(n<e&&h>t)throw new Error("Software loader is resident at "+a(t,8)+"-"+a(e,8)+". Can't load binary at overlapping address range "+a(n,8)+"-"+a(h,8)+". Try changing the binary loading address.");return[0,[]]}async eraseFlash(){await this.checkCommand(208,[],0,I)}}const Ve=async t=>{let e;const i=globalThis.requestSerialPort;if("function"==typeof i)t.log("Using custom port request function"),e=await i();else{if(!navigator.serial)throw new Error("Web Serial API is not supported in this browser. Please use Chrome 89+, Edge 89+, or Opera on desktop, or Chrome 61+ on Android with USB OTG. Note: The page must be served over HTTPS or localhost.");e=await navigator.serial.requestPort()}return e.readable&&e.writable||await e.open({baudRate:n}),t.log("Connected successfully."),new Ne(e,t)},He=async(t,e)=>{if(!t)throw new Error("Port is required");return t.readable&&t.writable||await t.open({baudRate:n}),e.log("Connected successfully."),new Ne(t,e)};export{u as CHIP_FAMILY_ESP32,_ as CHIP_FAMILY_ESP32C2,f as CHIP_FAMILY_ESP32C3,g as CHIP_FAMILY_ESP32C5,p as CHIP_FAMILY_ESP32C6,w as CHIP_FAMILY_ESP32C61,m as CHIP_FAMILY_ESP32H2,y as CHIP_FAMILY_ESP32H21,b as CHIP_FAMILY_ESP32H4,S as CHIP_FAMILY_ESP32P4,d as CHIP_FAMILY_ESP32S2,c as CHIP_FAMILY_ESP32S3,B as CHIP_FAMILY_ESP32S31,l as CHIP_FAMILY_ESP8266,Ne as ESPLoader,Ve as connect,He as connectWithPort};
1
+ const t=t=>{let e=[192];for(const i of t)219==i?e=e.concat([219,221]):192==i?e=e.concat([219,220]):e.push(i);return e.push(192),e},e=t=>{const e=[];for(let i=0;i<t.length;i++){const a=t.charCodeAt(i);a<=255&&e.push(a)}return e},i=t=>"["+t.map(t=>a(t)).join(", ")+"]",a=(t,e=2)=>{const i=t.toString(16).toUpperCase();return i.startsWith("-")?"-0x"+i.substring(1).padStart(e,"0"):"0x"+i.padStart(e,"0")},s=t=>new Promise(e=>setTimeout(e,t)),r={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"},n=4096,h=115200,o=1343410176,l=e(" UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU"),u=33382,d=50,c=12882,_=12883,f=12994,g=12995,p=12997,w=12998,m=207969,b=12914,y=12916,S=12917,B=12928,v=12849,R={5:{name:"ESP32-C3",family:g},9:{name:"ESP32-S3",family:_},12:{name:"ESP32-C2",family:f},13:{name:"ESP32-C6",family:w},16:{name:"ESP32-H2",family:b},18:{name:"ESP32-P4",family:B},20:{name:"ESP32-C61",family:m},23:{name:"ESP32-C5",family:p},25:{name:"ESP32-H21",family:S},28:{name:"ESP32-H4",family:y},32:{name:"ESP32-S31",family:v}},U={4293968129:{name:"ESP8266",family:u},15736195:{name:"ESP32",family:d},1990:{name:"ESP32-S2",family:c}},I=3e3,T=15e4,x=100,D=3e4,k=(t,e)=>{const i=Math.floor(t*(e/486));return i<I?I:i},C=t=>{switch(t){case d:return{regBase:1072963584,baseFuse:1073061888,macFuse:1073061888,usrOffs:28,usr1Offs:32,usr2Offs:36,mosiDlenOffs:40,misoDlenOffs:44,w0Offs:128,uartDateReg:1610612856,flashOffs:4096};case c:return{regBase:1061167104,baseFuse:1061265408,macFuse:1061265476,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612856,flashOffs:4096};case _:return{regBase:1610620928,usrOffs:24,baseFuse:1610641408,macFuse:1610641476,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612864,flashOffs:0};case u:return{regBase:1610613248,usrOffs:28,baseFuse:1072693328,macFuse:1072693328,usr1Offs:32,usr2Offs:36,mosiDlenOffs:-1,misoDlenOffs:-1,w0Offs:64,uartDateReg:1610612856,flashOffs:0};case f:case g:return{regBase:1610620928,baseFuse:1610647552,macFuse:1610647620,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case p:return{regBase:1610625024,baseFuse:1611352064,macFuse:1611352132,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:8192};case w:return{regBase:1610625024,baseFuse:1611335680,macFuse:1611335748,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case m:return{regBase:1610625024,baseFuse:1611352064,macFuse:1611352132,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case b:return{regBase:1610625024,baseFuse:1611335680,macFuse:1611335748,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case y:return{regBase:1611239424,baseFuse:1611339776,macFuse:1611339844,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610686588,flashOffs:8192};case S:return{regBase:1610625024,baseFuse:1611350016,macFuse:1611350084,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case B:return{regBase:1342754816,baseFuse:o,macFuse:1343410244,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1343004812,flashOffs:8192};case v: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 F extends Error{constructor(t){super(t),this.name="SlipReadError"}}const z=async(t,i)=>{let a;if(t==y||t==S||t==v)return null;if(t==d)a=await import("./esp32-BRKoi17y.js");else if(t==c)a=await import("./esp32s2-iX3WoDbg.js");else if(t==_)a=await import("./esp32s3-DGwDVIgz.js");else if(t==u)a=await import("./esp8266-CUwxJpGa.js");else if(t==f)a=await import("./esp32c2-Btgr_lwh.js");else if(t==g)a=await import("./esp32c3-CHKfoI8W.js");else if(t==p)a=await import("./esp32c5-BDW4KtLo.js");else if(t==w)a=await import("./esp32c6-il8tTxAG.js");else if(t==m)a=await import("./esp32c61-thKzxBGf.js");else if(t==b)a=await import("./esp32h2-CxoUHv_P.js");else{if(t!=B)return null;a=null!=i&&i>=300?await import("./esp32p4r3-CqI71ojR.js"):await import("./esp32p4-D3jLP-jY.js")}return{...a,text:e(atob(a.text)),data:e(atob(a.data))}};function O(t){let e=t.length;for(;--e>=0;)t[e]=0}const W=256,A=286,E=30,$=15,M=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]),P=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]),L=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),N=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Z=new Array(576);O(Z);const V=new Array(60);O(V);const H=new Array(512);O(H);const j=new Array(256);O(j);const G=new Array(29);O(G);const J=new Array(E);function q(t,e,i,a,s){this.static_tree=t,this.extra_bits=e,this.extra_base=i,this.elems=a,this.max_length=s,this.has_stree=t&&t.length}let K,Y,X;function Q(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}O(J);const tt=t=>t<256?H[t]:H[256+(t>>>7)],et=(t,e)=>{t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255},it=(t,e,i)=>{t.bi_valid>16-i?(t.bi_buf|=e<<t.bi_valid&65535,et(t,t.bi_buf),t.bi_buf=e>>16-t.bi_valid,t.bi_valid+=i-16):(t.bi_buf|=e<<t.bi_valid&65535,t.bi_valid+=i)},at=(t,e,i)=>{it(t,i[2*e],i[2*e+1])},st=(t,e)=>{let i=0;do{i|=1&t,t>>>=1,i<<=1}while(--e>0);return i>>>1},rt=(t,e,i)=>{const a=new Array(16);let s,r,n=0;for(s=1;s<=$;s++)n=n+i[s-1]<<1,a[s]=n;for(r=0;r<=e;r++){let e=t[2*r+1];0!==e&&(t[2*r]=st(a[e]++,e))}},nt=t=>{let e;for(e=0;e<A;e++)t.dyn_ltree[2*e]=0;for(e=0;e<E;e++)t.dyn_dtree[2*e]=0;for(e=0;e<19;e++)t.bl_tree[2*e]=0;t.dyn_ltree[512]=1,t.opt_len=t.static_len=0,t.sym_next=t.matches=0},ht=t=>{t.bi_valid>8?et(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0},ot=(t,e,i,a)=>{const s=2*e,r=2*i;return t[s]<t[r]||t[s]===t[r]&&a[e]<=a[i]},lt=(t,e,i)=>{const a=t.heap[i];let s=i<<1;for(;s<=t.heap_len&&(s<t.heap_len&&ot(e,t.heap[s+1],t.heap[s],t.depth)&&s++,!ot(e,a,t.heap[s],t.depth));)t.heap[i]=t.heap[s],i=s,s<<=1;t.heap[i]=a},ut=(t,e,i)=>{let a,s,r,n,h=0;if(0!==t.sym_next)do{a=255&t.pending_buf[t.sym_buf+h++],a+=(255&t.pending_buf[t.sym_buf+h++])<<8,s=t.pending_buf[t.sym_buf+h++],0===a?at(t,s,e):(r=j[s],at(t,r+W+1,e),n=M[r],0!==n&&(s-=G[r],it(t,s,n)),a--,r=tt(a),at(t,r,i),n=P[r],0!==n&&(a-=J[r],it(t,a,n)))}while(h<t.sym_next);at(t,256,e)},dt=(t,e)=>{const i=e.dyn_tree,a=e.stat_desc.static_tree,s=e.stat_desc.has_stree,r=e.stat_desc.elems;let n,h,o,l=-1;for(t.heap_len=0,t.heap_max=573,n=0;n<r;n++)0!==i[2*n]?(t.heap[++t.heap_len]=l=n,t.depth[n]=0):i[2*n+1]=0;for(;t.heap_len<2;)o=t.heap[++t.heap_len]=l<2?++l:0,i[2*o]=1,t.depth[o]=0,t.opt_len--,s&&(t.static_len-=a[2*o+1]);for(e.max_code=l,n=t.heap_len>>1;n>=1;n--)lt(t,i,n);o=r;do{n=t.heap[1],t.heap[1]=t.heap[t.heap_len--],lt(t,i,1),h=t.heap[1],t.heap[--t.heap_max]=n,t.heap[--t.heap_max]=h,i[2*o]=i[2*n]+i[2*h],t.depth[o]=(t.depth[n]>=t.depth[h]?t.depth[n]:t.depth[h])+1,i[2*n+1]=i[2*h+1]=o,t.heap[1]=o++,lt(t,i,1)}while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],((t,e)=>{const i=e.dyn_tree,a=e.max_code,s=e.stat_desc.static_tree,r=e.stat_desc.has_stree,n=e.stat_desc.extra_bits,h=e.stat_desc.extra_base,o=e.stat_desc.max_length;let l,u,d,c,_,f,g=0;for(c=0;c<=$;c++)t.bl_count[c]=0;for(i[2*t.heap[t.heap_max]+1]=0,l=t.heap_max+1;l<573;l++)u=t.heap[l],c=i[2*i[2*u+1]+1]+1,c>o&&(c=o,g++),i[2*u+1]=c,u>a||(t.bl_count[c]++,_=0,u>=h&&(_=n[u-h]),f=i[2*u],t.opt_len+=f*(c+_),r&&(t.static_len+=f*(s[2*u+1]+_)));if(0!==g){do{for(c=o-1;0===t.bl_count[c];)c--;t.bl_count[c]--,t.bl_count[c+1]+=2,t.bl_count[o]--,g-=2}while(g>0);for(c=o;0!==c;c--)for(u=t.bl_count[c];0!==u;)d=t.heap[--l],d>a||(i[2*d+1]!==c&&(t.opt_len+=(c-i[2*d+1])*i[2*d],i[2*d+1]=c),u--)}})(t,e),rt(i,l,t.bl_count)},ct=(t,e,i)=>{let a,s,r=-1,n=e[1],h=0,o=7,l=4;for(0===n&&(o=138,l=3),e[2*(i+1)+1]=65535,a=0;a<=i;a++)s=n,n=e[2*(a+1)+1],++h<o&&s===n||(h<l?t.bl_tree[2*s]+=h:0!==s?(s!==r&&t.bl_tree[2*s]++,t.bl_tree[32]++):h<=10?t.bl_tree[34]++:t.bl_tree[36]++,h=0,r=s,0===n?(o=138,l=3):s===n?(o=6,l=3):(o=7,l=4))},_t=(t,e,i)=>{let a,s,r=-1,n=e[1],h=0,o=7,l=4;for(0===n&&(o=138,l=3),a=0;a<=i;a++)if(s=n,n=e[2*(a+1)+1],!(++h<o&&s===n)){if(h<l)do{at(t,s,t.bl_tree)}while(0!==--h);else 0!==s?(s!==r&&(at(t,s,t.bl_tree),h--),at(t,16,t.bl_tree),it(t,h-3,2)):h<=10?(at(t,17,t.bl_tree),it(t,h-3,3)):(at(t,18,t.bl_tree),it(t,h-11,7));h=0,r=s,0===n?(o=138,l=3):s===n?(o=6,l=3):(o=7,l=4)}};let ft=!1;const gt=(t,e,i,a)=>{it(t,0+(a?1:0),3),ht(t),et(t,i),et(t,~i),i&&t.pending_buf.set(t.window.subarray(e,e+i),t.pending),t.pending+=i};var pt=(t,e,i,a)=>{let s,r,n=0;t.level>0?(2===t.strm.data_type&&(t.strm.data_type=(t=>{let e,i=4093624447;for(e=0;e<=31;e++,i>>>=1)if(1&i&&0!==t.dyn_ltree[2*e])return 0;if(0!==t.dyn_ltree[18]||0!==t.dyn_ltree[20]||0!==t.dyn_ltree[26])return 1;for(e=32;e<W;e++)if(0!==t.dyn_ltree[2*e])return 1;return 0})(t)),dt(t,t.l_desc),dt(t,t.d_desc),n=(t=>{let e;for(ct(t,t.dyn_ltree,t.l_desc.max_code),ct(t,t.dyn_dtree,t.d_desc.max_code),dt(t,t.bl_desc),e=18;e>=3&&0===t.bl_tree[2*N[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e})(t),s=t.opt_len+3+7>>>3,r=t.static_len+3+7>>>3,r<=s&&(s=r)):s=r=i+5,i+4<=s&&-1!==e?gt(t,e,i,a):4===t.strategy||r===s?(it(t,2+(a?1:0),3),ut(t,Z,V)):(it(t,4+(a?1:0),3),((t,e,i,a)=>{let s;for(it(t,e-257,5),it(t,i-1,5),it(t,a-4,4),s=0;s<a;s++)it(t,t.bl_tree[2*N[s]+1],3);_t(t,t.dyn_ltree,e-1),_t(t,t.dyn_dtree,i-1)})(t,t.l_desc.max_code+1,t.d_desc.max_code+1,n+1),ut(t,t.dyn_ltree,t.dyn_dtree)),nt(t),a&&ht(t)},wt={_tr_init:t=>{ft||((()=>{let t,e,i,a,s;const r=new Array(16);for(i=0,a=0;a<28;a++)for(G[a]=i,t=0;t<1<<M[a];t++)j[i++]=a;for(j[i-1]=a,s=0,a=0;a<16;a++)for(J[a]=s,t=0;t<1<<P[a];t++)H[s++]=a;for(s>>=7;a<E;a++)for(J[a]=s<<7,t=0;t<1<<P[a]-7;t++)H[256+s++]=a;for(e=0;e<=$;e++)r[e]=0;for(t=0;t<=143;)Z[2*t+1]=8,t++,r[8]++;for(;t<=255;)Z[2*t+1]=9,t++,r[9]++;for(;t<=279;)Z[2*t+1]=7,t++,r[7]++;for(;t<=287;)Z[2*t+1]=8,t++,r[8]++;for(rt(Z,287,r),t=0;t<E;t++)V[2*t+1]=5,V[2*t]=st(t,5);K=new q(Z,M,257,A,$),Y=new q(V,P,0,E,$),X=new q(new Array(0),L,0,19,7)})(),ft=!0),t.l_desc=new Q(t.dyn_ltree,K),t.d_desc=new Q(t.dyn_dtree,Y),t.bl_desc=new Q(t.bl_tree,X),t.bi_buf=0,t.bi_valid=0,nt(t)},_tr_stored_block:gt,_tr_flush_block:pt,_tr_tally:(t,e,i)=>(t.pending_buf[t.sym_buf+t.sym_next++]=e,t.pending_buf[t.sym_buf+t.sym_next++]=e>>8,t.pending_buf[t.sym_buf+t.sym_next++]=i,0===e?t.dyn_ltree[2*i]++:(t.matches++,e--,t.dyn_ltree[2*(j[i]+W+1)]++,t.dyn_dtree[2*tt(e)]++),t.sym_next===t.sym_end),_tr_align:t=>{it(t,2,3),at(t,256,Z),(t=>{16===t.bi_valid?(et(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)})(t)}};var mt=(t,e,i,a)=>{let s=65535&t,r=t>>>16&65535,n=0;for(;0!==i;){n=i>2e3?2e3:i,i-=n;do{s=s+e[a++]|0,r=r+s|0}while(--n);s%=65521,r%=65521}return s|r<<16};const bt=new Uint32Array((()=>{let t,e=[];for(var i=0;i<256;i++){t=i;for(var a=0;a<8;a++)t=1&t?3988292384^t>>>1:t>>>1;e[i]=t}return e})());var yt=(t,e,i,a)=>{const s=bt,r=a+i;t^=-1;for(let i=a;i<r;i++)t=t>>>8^s[255&(t^e[i])];return-1^t},St={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"},Bt={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:vt,_tr_stored_block:Rt,_tr_flush_block:Ut,_tr_tally:It,_tr_align:Tt}=wt,{Z_NO_FLUSH:xt,Z_PARTIAL_FLUSH:Dt,Z_FULL_FLUSH:kt,Z_FINISH:Ct,Z_BLOCK:Ft,Z_OK:zt,Z_STREAM_END:Ot,Z_STREAM_ERROR:Wt,Z_DATA_ERROR:At,Z_BUF_ERROR:Et,Z_DEFAULT_COMPRESSION:$t,Z_FILTERED:Mt,Z_HUFFMAN_ONLY:Pt,Z_RLE:Lt,Z_FIXED:Nt,Z_DEFAULT_STRATEGY:Zt,Z_UNKNOWN:Vt,Z_DEFLATED:Ht}=Bt,jt=258,Gt=262,Jt=42,qt=113,Kt=666,Yt=(t,e)=>(t.msg=St[e],e),Xt=t=>2*t-(t>4?9:0),Qt=t=>{let e=t.length;for(;--e>=0;)t[e]=0},te=t=>{let e,i,a,s=t.w_size;e=t.hash_size,a=e;do{i=t.head[--a],t.head[a]=i>=s?i-s:0}while(--e);e=s,a=e;do{i=t.prev[--a],t.prev[a]=i>=s?i-s:0}while(--e)};let ee=(t,e,i)=>(e<<t.hash_shift^i)&t.hash_mask;const ie=t=>{const e=t.state;let i=e.pending;i>t.avail_out&&(i=t.avail_out),0!==i&&(t.output.set(e.pending_buf.subarray(e.pending_out,e.pending_out+i),t.next_out),t.next_out+=i,e.pending_out+=i,t.total_out+=i,t.avail_out-=i,e.pending-=i,0===e.pending&&(e.pending_out=0))},ae=(t,e)=>{Ut(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,ie(t.strm)},se=(t,e)=>{t.pending_buf[t.pending++]=e},re=(t,e)=>{t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e},ne=(t,e,i,a)=>{let s=t.avail_in;return s>a&&(s=a),0===s?0:(t.avail_in-=s,e.set(t.input.subarray(t.next_in,t.next_in+s),i),1===t.state.wrap?t.adler=mt(t.adler,e,s,i):2===t.state.wrap&&(t.adler=yt(t.adler,e,s,i)),t.next_in+=s,t.total_in+=s,s)},he=(t,e)=>{let i,a,s=t.max_chain_length,r=t.strstart,n=t.prev_length,h=t.nice_match;const o=t.strstart>t.w_size-Gt?t.strstart-(t.w_size-Gt):0,l=t.window,u=t.w_mask,d=t.prev,c=t.strstart+jt;let _=l[r+n-1],f=l[r+n];t.prev_length>=t.good_match&&(s>>=2),h>t.lookahead&&(h=t.lookahead);do{if(i=e,l[i+n]===f&&l[i+n-1]===_&&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<c);if(a=jt-(c-r),r=c-jt,a>n){if(t.match_start=e,n=a,a>=h)break;_=l[r+n-1],f=l[r+n]}}}while((e=d[e&u])>o&&0!==--s);return n<=t.lookahead?n:t.lookahead},oe=t=>{const e=t.w_size;let i,a,s;do{if(a=t.window_size-t.lookahead-t.strstart,t.strstart>=e+(e-Gt)&&(t.window.set(t.window.subarray(e,e+e-a),0),t.match_start-=e,t.strstart-=e,t.block_start-=e,t.insert>t.strstart&&(t.insert=t.strstart),te(t),a+=e),0===t.strm.avail_in)break;if(i=ne(t.strm,t.window,t.strstart+t.lookahead,a),t.lookahead+=i,t.lookahead+t.insert>=3)for(s=t.strstart-t.insert,t.ins_h=t.window[s],t.ins_h=ee(t,t.ins_h,t.window[s+1]);t.insert&&(t.ins_h=ee(t,t.ins_h,t.window[s+3-1]),t.prev[s&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=s,s++,t.insert--,!(t.lookahead+t.insert<3)););}while(t.lookahead<Gt&&0!==t.strm.avail_in)},le=(t,e)=>{let i,a,s,r=t.pending_buf_size-5>t.w_size?t.w_size:t.pending_buf_size-5,n=0,h=t.strm.avail_in;do{if(i=65535,s=t.bi_valid+42>>3,t.strm.avail_out<s)break;if(s=t.strm.avail_out-s,a=t.strstart-t.block_start,i>a+t.strm.avail_in&&(i=a+t.strm.avail_in),i>s&&(i=s),i<r&&(0===i&&e!==Ct||e===xt||i!==a+t.strm.avail_in))break;n=e===Ct&&i===a+t.strm.avail_in?1:0,Rt(t,0,0,n),t.pending_buf[t.pending-4]=i,t.pending_buf[t.pending-3]=i>>8,t.pending_buf[t.pending-2]=~i,t.pending_buf[t.pending-1]=~i>>8,ie(t.strm),a&&(a>i&&(a=i),t.strm.output.set(t.window.subarray(t.block_start,t.block_start+a),t.strm.next_out),t.strm.next_out+=a,t.strm.avail_out-=a,t.strm.total_out+=a,t.block_start+=a,i-=a),i&&(ne(t.strm,t.strm.output,t.strm.next_out,i),t.strm.next_out+=i,t.strm.avail_out-=i,t.strm.total_out+=i)}while(0===n);return h-=t.strm.avail_in,h&&(h>=t.w_size?(t.matches=2,t.window.set(t.strm.input.subarray(t.strm.next_in-t.w_size,t.strm.next_in),0),t.strstart=t.w_size,t.insert=t.strstart):(t.window_size-t.strstart<=h&&(t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,t.insert>t.strstart&&(t.insert=t.strstart)),t.window.set(t.strm.input.subarray(t.strm.next_in-h,t.strm.next_in),t.strstart),t.strstart+=h,t.insert+=h>t.w_size-t.insert?t.w_size-t.insert:h),t.block_start=t.strstart),t.high_water<t.strstart&&(t.high_water=t.strstart),n?4:e!==xt&&e!==Ct&&0===t.strm.avail_in&&t.strstart===t.block_start?2:(s=t.window_size-t.strstart,t.strm.avail_in>s&&t.block_start>=t.w_size&&(t.block_start-=t.w_size,t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,s+=t.w_size,t.insert>t.strstart&&(t.insert=t.strstart)),s>t.strm.avail_in&&(s=t.strm.avail_in),s&&(ne(t.strm,t.window,t.strstart,s),t.strstart+=s,t.insert+=s>t.w_size-t.insert?t.w_size-t.insert:s),t.high_water<t.strstart&&(t.high_water=t.strstart),s=t.bi_valid+42>>3,s=t.pending_buf_size-s>65535?65535:t.pending_buf_size-s,r=s>t.w_size?t.w_size:s,a=t.strstart-t.block_start,(a>=r||(a||e===Ct)&&e!==xt&&0===t.strm.avail_in&&a<=s)&&(i=a>s?s:a,n=e===Ct&&0===t.strm.avail_in&&i===a?1:0,Rt(t,t.block_start,i,n),t.block_start+=i,ie(t.strm)),n?3:1)},ue=(t,e)=>{let i,a;for(;;){if(t.lookahead<Gt){if(oe(t),t.lookahead<Gt&&e===xt)return 1;if(0===t.lookahead)break}if(i=0,t.lookahead>=3&&(t.ins_h=ee(t,t.ins_h,t.window[t.strstart+3-1]),i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),0!==i&&t.strstart-i<=t.w_size-Gt&&(t.match_length=he(t,i)),t.match_length>=3)if(a=It(t,t.strstart-t.match_start,t.match_length-3),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=3){t.match_length--;do{t.strstart++,t.ins_h=ee(t,t.ins_h,t.window[t.strstart+3-1]),i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart}while(0!==--t.match_length);t.strstart++}else t.strstart+=t.match_length,t.match_length=0,t.ins_h=t.window[t.strstart],t.ins_h=ee(t,t.ins_h,t.window[t.strstart+1]);else a=It(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(a&&(ae(t,!1),0===t.strm.avail_out))return 1}return t.insert=t.strstart<2?t.strstart:2,e===Ct?(ae(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ae(t,!1),0===t.strm.avail_out)?1:2},de=(t,e)=>{let i,a,s;for(;;){if(t.lookahead<Gt){if(oe(t),t.lookahead<Gt&&e===xt)return 1;if(0===t.lookahead)break}if(i=0,t.lookahead>=3&&(t.ins_h=ee(t,t.ins_h,t.window[t.strstart+3-1]),i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),t.prev_length=t.match_length,t.prev_match=t.match_start,t.match_length=2,0!==i&&t.prev_length<t.max_lazy_match&&t.strstart-i<=t.w_size-Gt&&(t.match_length=he(t,i),t.match_length<=5&&(t.strategy===Mt||3===t.match_length&&t.strstart-t.match_start>4096)&&(t.match_length=2)),t.prev_length>=3&&t.match_length<=t.prev_length){s=t.strstart+t.lookahead-3,a=It(t,t.strstart-1-t.prev_match,t.prev_length-3),t.lookahead-=t.prev_length-1,t.prev_length-=2;do{++t.strstart<=s&&(t.ins_h=ee(t,t.ins_h,t.window[t.strstart+3-1]),i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart)}while(0!==--t.prev_length);if(t.match_available=0,t.match_length=2,t.strstart++,a&&(ae(t,!1),0===t.strm.avail_out))return 1}else if(t.match_available){if(a=It(t,0,t.window[t.strstart-1]),a&&ae(t,!1),t.strstart++,t.lookahead--,0===t.strm.avail_out)return 1}else t.match_available=1,t.strstart++,t.lookahead--}return t.match_available&&(a=It(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<2?t.strstart:2,e===Ct?(ae(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ae(t,!1),0===t.strm.avail_out)?1:2};function ce(t,e,i,a,s){this.good_length=t,this.max_lazy=e,this.nice_length=i,this.max_chain=a,this.func=s}const _e=[new ce(0,0,0,0,le),new ce(4,4,8,4,ue),new ce(4,5,16,8,ue),new ce(4,6,32,32,ue),new ce(4,4,16,16,de),new ce(8,16,32,32,de),new ce(8,16,128,128,de),new ce(8,32,128,256,de),new ce(32,128,258,1024,de),new ce(32,258,258,4096,de)];function fe(){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=Ht,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),Qt(this.dyn_ltree),Qt(this.dyn_dtree),Qt(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),Qt(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),Qt(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 ge=t=>{if(!t)return 1;const e=t.state;return!e||e.strm!==t||e.status!==Jt&&57!==e.status&&69!==e.status&&73!==e.status&&91!==e.status&&103!==e.status&&e.status!==qt&&e.status!==Kt?1:0},pe=t=>{if(ge(t))return Yt(t,Wt);t.total_in=t.total_out=0,t.data_type=Vt;const e=t.state;return e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=2===e.wrap?57:e.wrap?Jt:qt,t.adler=2===e.wrap?0:1,e.last_flush=-2,vt(e),zt},we=t=>{const e=pe(t);var i;return e===zt&&((i=t.state).window_size=2*i.w_size,Qt(i.head),i.max_lazy_match=_e[i.level].max_lazy,i.good_match=_e[i.level].good_length,i.nice_match=_e[i.level].nice_length,i.max_chain_length=_e[i.level].max_chain,i.strstart=0,i.block_start=0,i.lookahead=0,i.insert=0,i.match_length=i.prev_length=2,i.match_available=0,i.ins_h=0),e},me=(t,e,i,a,s,r)=>{if(!t)return Wt;let n=1;if(e===$t&&(e=6),a<0?(n=0,a=-a):a>15&&(n=2,a-=16),s<1||s>9||i!==Ht||a<8||a>15||e<0||e>9||r<0||r>Nt||8===a&&1!==n)return Yt(t,Wt);8===a&&(a=9);const h=new fe;return t.state=h,h.strm=t,h.status=Jt,h.wrap=n,h.gzhead=null,h.w_bits=a,h.w_size=1<<h.w_bits,h.w_mask=h.w_size-1,h.hash_bits=s+7,h.hash_size=1<<h.hash_bits,h.hash_mask=h.hash_size-1,h.hash_shift=~~((h.hash_bits+3-1)/3),h.window=new Uint8Array(2*h.w_size),h.head=new Uint16Array(h.hash_size),h.prev=new Uint16Array(h.w_size),h.lit_bufsize=1<<s+6,h.pending_buf_size=4*h.lit_bufsize,h.pending_buf=new Uint8Array(h.pending_buf_size),h.sym_buf=h.lit_bufsize,h.sym_end=3*(h.lit_bufsize-1),h.level=e,h.strategy=r,h.method=i,we(t)};var be={deflateInit:(t,e)=>me(t,e,Ht,15,8,Zt),deflateInit2:me,deflateReset:we,deflateResetKeep:pe,deflateSetHeader:(t,e)=>ge(t)||2!==t.state.wrap?Wt:(t.state.gzhead=e,zt),deflate:(t,e)=>{if(ge(t)||e>Ft||e<0)return t?Yt(t,Wt):Wt;const i=t.state;if(!t.output||0!==t.avail_in&&!t.input||i.status===Kt&&e!==Ct)return Yt(t,0===t.avail_out?Et:Wt);const a=i.last_flush;if(i.last_flush=e,0!==i.pending){if(ie(t),0===t.avail_out)return i.last_flush=-1,zt}else if(0===t.avail_in&&Xt(e)<=Xt(a)&&e!==Ct)return Yt(t,Et);if(i.status===Kt&&0!==t.avail_in)return Yt(t,Et);if(i.status===Jt&&0===i.wrap&&(i.status=qt),i.status===Jt){let e=Ht+(i.w_bits-8<<4)<<8,a=-1;if(a=i.strategy>=Pt||i.level<2?0:i.level<6?1:6===i.level?2:3,e|=a<<6,0!==i.strstart&&(e|=32),e+=31-e%31,re(i,e),0!==i.strstart&&(re(i,t.adler>>>16),re(i,65535&t.adler)),t.adler=1,i.status=qt,ie(t),0!==i.pending)return i.last_flush=-1,zt}if(57===i.status)if(t.adler=0,se(i,31),se(i,139),se(i,8),i.gzhead)se(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)),se(i,255&i.gzhead.time),se(i,i.gzhead.time>>8&255),se(i,i.gzhead.time>>16&255),se(i,i.gzhead.time>>24&255),se(i,9===i.level?2:i.strategy>=Pt||i.level<2?4:0),se(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(se(i,255&i.gzhead.extra.length),se(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(t.adler=yt(t.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=69;else if(se(i,0),se(i,0),se(i,0),se(i,0),se(i,0),se(i,9===i.level?2:i.strategy>=Pt||i.level<2?4:0),se(i,3),i.status=qt,ie(t),0!==i.pending)return i.last_flush=-1,zt;if(69===i.status){if(i.gzhead.extra){let e=i.pending,a=(65535&i.gzhead.extra.length)-i.gzindex;for(;i.pending+a>i.pending_buf_size;){let s=i.pending_buf_size-i.pending;if(i.pending_buf.set(i.gzhead.extra.subarray(i.gzindex,i.gzindex+s),i.pending),i.pending=i.pending_buf_size,i.gzhead.hcrc&&i.pending>e&&(t.adler=yt(t.adler,i.pending_buf,i.pending-e,e)),i.gzindex+=s,ie(t),0!==i.pending)return i.last_flush=-1,zt;e=0,a-=s}let s=new Uint8Array(i.gzhead.extra);i.pending_buf.set(s.subarray(i.gzindex,i.gzindex+a),i.pending),i.pending+=a,i.gzhead.hcrc&&i.pending>e&&(t.adler=yt(t.adler,i.pending_buf,i.pending-e,e)),i.gzindex=0}i.status=73}if(73===i.status){if(i.gzhead.name){let e,a=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>a&&(t.adler=yt(t.adler,i.pending_buf,i.pending-a,a)),ie(t),0!==i.pending)return i.last_flush=-1,zt;a=0}e=i.gzindex<i.gzhead.name.length?255&i.gzhead.name.charCodeAt(i.gzindex++):0,se(i,e)}while(0!==e);i.gzhead.hcrc&&i.pending>a&&(t.adler=yt(t.adler,i.pending_buf,i.pending-a,a)),i.gzindex=0}i.status=91}if(91===i.status){if(i.gzhead.comment){let e,a=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>a&&(t.adler=yt(t.adler,i.pending_buf,i.pending-a,a)),ie(t),0!==i.pending)return i.last_flush=-1,zt;a=0}e=i.gzindex<i.gzhead.comment.length?255&i.gzhead.comment.charCodeAt(i.gzindex++):0,se(i,e)}while(0!==e);i.gzhead.hcrc&&i.pending>a&&(t.adler=yt(t.adler,i.pending_buf,i.pending-a,a))}i.status=103}if(103===i.status){if(i.gzhead.hcrc){if(i.pending+2>i.pending_buf_size&&(ie(t),0!==i.pending))return i.last_flush=-1,zt;se(i,255&t.adler),se(i,t.adler>>8&255),t.adler=0}if(i.status=qt,ie(t),0!==i.pending)return i.last_flush=-1,zt}if(0!==t.avail_in||0!==i.lookahead||e!==xt&&i.status!==Kt){let a=0===i.level?le(i,e):i.strategy===Pt?((t,e)=>{let i;for(;;){if(0===t.lookahead&&(oe(t),0===t.lookahead)){if(e===xt)return 1;break}if(t.match_length=0,i=It(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,i&&(ae(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===Ct?(ae(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ae(t,!1),0===t.strm.avail_out)?1:2})(i,e):i.strategy===Lt?((t,e)=>{let i,a,s,r;const n=t.window;for(;;){if(t.lookahead<=jt){if(oe(t),t.lookahead<=jt&&e===xt)return 1;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=3&&t.strstart>0&&(s=t.strstart-1,a=n[s],a===n[++s]&&a===n[++s]&&a===n[++s])){r=t.strstart+jt;do{}while(a===n[++s]&&a===n[++s]&&a===n[++s]&&a===n[++s]&&a===n[++s]&&a===n[++s]&&a===n[++s]&&a===n[++s]&&s<r);t.match_length=jt-(r-s),t.match_length>t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=3?(i=It(t,1,t.match_length-3),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(i=It(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),i&&(ae(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===Ct?(ae(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ae(t,!1),0===t.strm.avail_out)?1:2})(i,e):_e[i.level].func(i,e);if(3!==a&&4!==a||(i.status=Kt),1===a||3===a)return 0===t.avail_out&&(i.last_flush=-1),zt;if(2===a&&(e===Dt?Tt(i):e!==Ft&&(Rt(i,0,0,!1),e===kt&&(Qt(i.head),0===i.lookahead&&(i.strstart=0,i.block_start=0,i.insert=0))),ie(t),0===t.avail_out))return i.last_flush=-1,zt}return e!==Ct?zt:i.wrap<=0?Ot:(2===i.wrap?(se(i,255&t.adler),se(i,t.adler>>8&255),se(i,t.adler>>16&255),se(i,t.adler>>24&255),se(i,255&t.total_in),se(i,t.total_in>>8&255),se(i,t.total_in>>16&255),se(i,t.total_in>>24&255)):(re(i,t.adler>>>16),re(i,65535&t.adler)),ie(t),i.wrap>0&&(i.wrap=-i.wrap),0!==i.pending?zt:Ot)},deflateEnd:t=>{if(ge(t))return Wt;const e=t.state.status;return t.state=null,e===qt?Yt(t,At):zt},deflateSetDictionary:(t,e)=>{let i=e.length;if(ge(t))return Wt;const a=t.state,s=a.wrap;if(2===s||1===s&&a.status!==Jt||a.lookahead)return Wt;if(1===s&&(t.adler=mt(t.adler,e,i,0)),a.wrap=0,i>=a.w_size){0===s&&(Qt(a.head),a.strstart=0,a.block_start=0,a.insert=0);let t=new Uint8Array(a.w_size);t.set(e.subarray(i-a.w_size,i),0),e=t,i=a.w_size}const r=t.avail_in,n=t.next_in,h=t.input;for(t.avail_in=i,t.next_in=0,t.input=e,oe(a);a.lookahead>=3;){let t=a.strstart,e=a.lookahead-2;do{a.ins_h=ee(a,a.ins_h,a.window[t+3-1]),a.prev[t&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=t,t++}while(--e);a.strstart=t,a.lookahead=2,oe(a)}return a.strstart+=a.lookahead,a.block_start=a.strstart,a.insert=a.lookahead,a.lookahead=0,a.match_length=a.prev_length=2,a.match_available=0,t.next_in=n,t.input=h,t.avail_in=r,a.wrap=s,zt},deflateInfo:"pako deflate (from Nodeca project)"};const ye=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var Se=function(t){const e=Array.prototype.slice.call(arguments,1);for(;e.length;){const i=e.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(const e in i)ye(i,e)&&(t[e]=i[e])}}return t},Be=t=>{let e=0;for(let i=0,a=t.length;i<a;i++)e+=t[i].length;const i=new Uint8Array(e);for(let e=0,a=0,s=t.length;e<s;e++){let s=t[e];i.set(s,a),a+=s.length}return i};let ve=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(t){ve=!1}const Re=new Uint8Array(256);for(let t=0;t<256;t++)Re[t]=t>=252?6:t>=248?5:t>=240?4:t>=224?3:t>=192?2:1;Re[254]=Re[254]=1;var Ue=t=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(t);let e,i,a,s,r,n=t.length,h=0;for(s=0;s<n;s++)i=t.charCodeAt(s),55296==(64512&i)&&s+1<n&&(a=t.charCodeAt(s+1),56320==(64512&a)&&(i=65536+(i-55296<<10)+(a-56320),s++)),h+=i<128?1:i<2048?2:i<65536?3:4;for(e=new Uint8Array(h),r=0,s=0;r<h;s++)i=t.charCodeAt(s),55296==(64512&i)&&s+1<n&&(a=t.charCodeAt(s+1),56320==(64512&a)&&(i=65536+(i-55296<<10)+(a-56320),s++)),i<128?e[r++]=i:i<2048?(e[r++]=192|i>>>6,e[r++]=128|63&i):i<65536?(e[r++]=224|i>>>12,e[r++]=128|i>>>6&63,e[r++]=128|63&i):(e[r++]=240|i>>>18,e[r++]=128|i>>>12&63,e[r++]=128|i>>>6&63,e[r++]=128|63&i);return e};var Ie=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 Te=Object.prototype.toString,{Z_NO_FLUSH:xe,Z_SYNC_FLUSH:De,Z_FULL_FLUSH:ke,Z_FINISH:Ce,Z_OK:Fe,Z_STREAM_END:ze,Z_DEFAULT_COMPRESSION:Oe,Z_DEFAULT_STRATEGY:We,Z_DEFLATED:Ae}=Bt;function Ee(t){this.options=Se({level:Oe,method:Ae,chunkSize:16384,windowBits:15,memLevel:8,strategy:We},t||{});let e=this.options;e.raw&&e.windowBits>0?e.windowBits=-e.windowBits:e.gzip&&e.windowBits>0&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new Ie,this.strm.avail_out=0;let i=be.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(i!==Fe)throw new Error(St[i]);if(e.header&&be.deflateSetHeader(this.strm,e.header),e.dictionary){let t;if(t="string"==typeof e.dictionary?Ue(e.dictionary):"[object ArrayBuffer]"===Te.call(e.dictionary)?new Uint8Array(e.dictionary):e.dictionary,i=be.deflateSetDictionary(this.strm,t),i!==Fe)throw new Error(St[i]);this._dict_set=!0}}Ee.prototype.push=function(t,e){const i=this.strm,a=this.options.chunkSize;let s,r;if(this.ended)return!1;for(r=e===~~e?e:!0===e?Ce:xe,"string"==typeof t?i.input=Ue(t):"[object ArrayBuffer]"===Te.call(t)?i.input=new Uint8Array(t):i.input=t,i.next_in=0,i.avail_in=i.input.length;;)if(0===i.avail_out&&(i.output=new Uint8Array(a),i.next_out=0,i.avail_out=a),(r===De||r===ke)&&i.avail_out<=6)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else{if(s=be.deflate(i,r),s===ze)return i.next_out>0&&this.onData(i.output.subarray(0,i.next_out)),s=be.deflateEnd(this.strm),this.onEnd(s),this.ended=!0,s===Fe;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},Ee.prototype.onData=function(t){this.chunks.push(t)},Ee.prototype.onEnd=function(t){t===Fe&&(this.result=Be(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};var $e={deflate:function(t,e){const i=new Ee(e);if(i.push(t,!0),i.err)throw i.msg||St[i.err];return i.result}};const{deflate:Me}=$e;var Pe=Me;const Le={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}},Ne=(t,...e)=>{let i=0;if(t.replace(/[<>]/,"").length!=e.length)throw"Pack format to Argument count mismatch";const a=[];let s=!0;for(let a=0;a<t.length;a++)"<"==t[a]?s=!0:">"==t[a]?s=!1:(r(t[a],e[i]),i++);function r(t,e){if(!(t in Le))throw"Unhandled character '"+t+"' in pack format";const i=Le[t].bytes,r=new DataView(new ArrayBuffer(i));Le[t].p.bind(r)(0,e,s);for(let t=0;t<i;t++)a.push(r.getUint8(t))}return a},Ze=(t,e)=>{let i=0;const a=[];let s=!0;for(const e of t)"<"==e?s=!0:">"==e?s=!1:r(e);function r(t){if(!(t in Le))throw"Unhandled character '"+t+"' in unpack format";const r=Le[t].bytes,n=new DataView(new ArrayBuffer(r));for(let t=0;t<r;t++)n.setUint8(t,255&e[i+t]);const h=Le[t].u.bind(n);a.push(h(0,s)),i+=r}return a};class Ve extends EventTarget{constructor(t,e,i){super(),this.port=t,this.logger=e,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=h,this._isESP32S2NativeUSB=!1,this._initializationSucceeded=!1,this.__commandLock=Promise.resolve([0,[]]),this.__isReconfiguring=!1,this.__abandonCurrentOperation=!1,this.__adaptiveBlockMultiplier=1,this.__adaptiveMaxInFlightMultiplier=1,this.__consecutiveSuccessfulChunks=0,this.__lastAdaptiveAdjustment=0,this.__isCDCDevice=!1,this.state_DTR=!1,this.__writeChain=Promise.resolve()}get chipFamily(){return this._parent?this._parent.chipFamily:this.__chipFamily}set chipFamily(t){this._parent?this._parent.chipFamily=t:this.__chipFamily=t}get chipName(){return this._parent?this._parent.chipName:this.__chipName}set chipName(t){this._parent?this._parent.chipName=t:this.__chipName=t}get chipRevision(){return this._parent?this._parent.chipRevision:this.__chipRevision}set chipRevision(t){this._parent?this._parent.chipRevision=t:this.__chipRevision=t}get chipVariant(){return this._parent?this._parent.chipVariant:this.__chipVariant}set chipVariant(t){this._parent?this._parent.chipVariant=t:this.__chipVariant=t}get _inputBuffer(){return this._parent?this._parent._inputBuffer:this.__inputBuffer}get _inputBufferReadIndex(){return this._parent?this._parent._inputBufferReadIndex:this.__inputBufferReadIndex||0}set _inputBufferReadIndex(t){this._parent?this._parent._inputBufferReadIndex=t:this.__inputBufferReadIndex=t}get _inputBufferAvailable(){return this._inputBuffer.length-this._inputBufferReadIndex}_readByte(){if(!(this._inputBufferReadIndex>=this._inputBuffer.length))return this._inputBuffer[this._inputBufferReadIndex++]}_clearInputBuffer(){this._inputBuffer.length=0,this._inputBufferReadIndex=0}_compactInputBuffer(){this._inputBufferReadIndex>1e3&&this._inputBufferReadIndex>this._inputBuffer.length/2&&(this._inputBuffer.splice(0,this._inputBufferReadIndex),this._inputBufferReadIndex=0)}get _totalBytesRead(){return this._parent?this._parent._totalBytesRead:this.__totalBytesRead||0}set _totalBytesRead(t){this._parent?this._parent._totalBytesRead=t:this.__totalBytesRead=t}get _commandLock(){return this._parent?this._parent._commandLock:this.__commandLock}set _commandLock(t){this._parent?this._parent._commandLock=t:this.__commandLock=t}get _isReconfiguring(){return this._parent?this._parent._isReconfiguring:this.__isReconfiguring}set _isReconfiguring(t){this._parent?this._parent._isReconfiguring=t:this.__isReconfiguring=t}get _abandonCurrentOperation(){return this._parent?this._parent._abandonCurrentOperation:this.__abandonCurrentOperation}set _abandonCurrentOperation(t){this._parent?this._parent._abandonCurrentOperation=t:this.__abandonCurrentOperation=t}get _adaptiveBlockMultiplier(){return this._parent?this._parent._adaptiveBlockMultiplier:this.__adaptiveBlockMultiplier}set _adaptiveBlockMultiplier(t){this._parent?this._parent._adaptiveBlockMultiplier=t:this.__adaptiveBlockMultiplier=t}get _adaptiveMaxInFlightMultiplier(){return this._parent?this._parent._adaptiveMaxInFlightMultiplier:this.__adaptiveMaxInFlightMultiplier}set _adaptiveMaxInFlightMultiplier(t){this._parent?this._parent._adaptiveMaxInFlightMultiplier=t:this.__adaptiveMaxInFlightMultiplier=t}get _consecutiveSuccessfulChunks(){return this._parent?this._parent._consecutiveSuccessfulChunks:this.__consecutiveSuccessfulChunks}set _consecutiveSuccessfulChunks(t){this._parent?this._parent._consecutiveSuccessfulChunks=t:this.__consecutiveSuccessfulChunks=t}get _lastAdaptiveAdjustment(){return this._parent?this._parent._lastAdaptiveAdjustment:this.__lastAdaptiveAdjustment}set _lastAdaptiveAdjustment(t){this._parent?this._parent._lastAdaptiveAdjustment=t:this.__lastAdaptiveAdjustment=t}get _isCDCDevice(){return this._parent?this._parent._isCDCDevice:this.__isCDCDevice}set _isCDCDevice(t){this._parent?this._parent._isCDCDevice=t:this.__isCDCDevice=t}detectUSBSerialChip(t,e){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}}}[t];return i&&i[e]?i[e]:{name:`Unknown (VID: 0x${t.toString(16)}, PID: 0x${e.toString(16)})`}}async initialize(){if(!this._parent){this.__inputBuffer=[],this.__inputBufferReadIndex=0,this.__totalBytesRead=0;const t=this.port.getInfo();if(t.usbVendorId&&t.usbProductId){const e=this.detectUSBSerialChip(t.usbVendorId,t.usbProductId);this.logger.log(`USB-Serial: ${e.name} (VID: 0x${t.usbVendorId.toString(16)}, PID: 0x${t.usbProductId.toString(16)})`),e.maxBaudrate&&(this._maxUSBSerialBaudrate=e.maxBaudrate,this.logger.log(`Max baudrate: ${e.maxBaudrate}`)),12346===t.usbVendorId&&2===t.usbProductId&&(this._isESP32S2NativeUSB=!0),(12346===t.usbVendorId||6790===t.usbVendorId&&21971===t.usbProductId)&&(this._isCDCDevice=!0)}this.readLoop()}await this.connectWithResetStrategies(),await this.detectChip();const t=C(this.getChipFamily()),e=t.macFuse;for(let t=0;t<4;t++)this._efuses[t]=await this.readRegister(e+4*t);this.logger.log(`Chip type ${this.chipName}`),this.logger.debug(`Bootloader flash offset: 0x${t.flashOffs.toString(16)}`),this._initializationSucceeded=!0}async detectChip(){try{const t=(await this.getSecurityInfo()).chipId,e=R[t];if(e)return this.chipName=e.name,this.chipFamily=e.family,this.chipFamily===B&&(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: ${t} (${this.chipName})`);this.logger.debug(`Unknown IMAGE_CHIP_ID: ${t}, falling back to magic value detection`)}catch(t){this.logger.debug(`GET_SECURITY_INFO failed, using magic value detection: ${t}`),await this.drainInputBuffer(200),this._clearInputBuffer(),await s(x);try{await this.sync()}catch(t){this.logger.debug(`Re-sync after GET_SECURITY_INFO failure: ${t}`)}}const t=await this.readRegister(1073745920),e=U[t>>>0];if(void 0===e)throw new Error(`Unknown Chip: Hex: ${a(t>>>0,8).toLowerCase()} Number: ${t}`);this.chipName=e.name,this.chipFamily=e.family,this.chipFamily===B&&(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: ${a(t>>>0,8)} (${this.chipName})`)}async getChipRevision(){if(this.chipFamily!==B)return 0;const t=await this.readRegister(1343410252);return 100*((t>>23&1)<<2|t>>4&3)+(15&t)}async getSecurityInfo(){const[,t]=await this.checkCommand(20,[],0);if(0===t.length)throw new Error("GET_SECURITY_INFO not supported or returned empty response");if(t.length<12)throw new Error(`Invalid security info response length: ${t.length} (expected at least 12 bytes)`);return{flags:Ze("<I",t.slice(0,4))[0],flashCryptCnt:t[4],keyPurposes:Array.from(t.slice(5,12)),chipId:t.length>=16?Ze("<I",t.slice(12,16))[0]:0,apiVersion:t.length>=20?Ze("<I",t.slice(16,20))[0]:0}}async getMacAddress(){if(!this._initializationSucceeded)throw new Error("getMacAddress() requires initialize() to have completed successfully");return this.macAddr().map(t=>t.toString(16).padStart(2,"0").toUpperCase()).join(":")}async readLoop(){this.debug&&this.logger.debug("Starting read loop"),this._reader=this.port.readable.getReader();try{let t=!0;for(;t;){const{value:e,done:i}=await this._reader.read();if(i){this._reader.releaseLock(),t=!1;break}if(!e||0===e.length)continue;const a=Array.from(e);Array.prototype.push.apply(this._inputBuffer,a),this._totalBytesRead+=e.length}}catch{this.logger.error("Read loop got disconnected")}finally{this._isReconfiguring=!1}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(t=100){return new Promise(e=>setTimeout(e,t))}async setRTS(t){await this.port.setSignals({requestToSend:t}),await this.setDTR(this.state_DTR)}async setDTR(t){this.state_DTR=t,await this.port.setSignals({dataTerminalReady:t})}async hardResetUSBJTAGSerial(){await this.setRTS(!1),await this.setDTR(!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),await this.sleep(200)}async hardResetClassic(){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),await this.sleep(200)}async setRTSWebUSB(t){await this.port.setSignals({requestToSend:t,dataTerminalReady:this.state_DTR})}async setDTRWebUSB(t){this.state_DTR=t,await this.port.setSignals({dataTerminalReady:t,requestToSend:void 0})}async setDTRandRTSWebUSB(t,e){this.state_DTR=t,await this.port.setSignals({dataTerminalReady:t,requestToSend:e})}async hardResetUSBJTAGSerialWebUSB(){await this.setRTSWebUSB(!1),await this.setDTRWebUSB(!1),await this.sleep(100),await this.setDTRWebUSB(!0),await this.setRTSWebUSB(!1),await this.sleep(100),await this.setRTSWebUSB(!0),await this.setDTRWebUSB(!1),await this.setRTSWebUSB(!0),await this.sleep(100),await this.setDTRWebUSB(!1),await this.setRTSWebUSB(!1),await this.sleep(200)}async hardResetUSBJTAGSerialInvertedDTRWebUSB(){await this.setRTSWebUSB(!1),await this.setDTRWebUSB(!0),await this.sleep(100),await this.setDTRWebUSB(!1),await this.setRTSWebUSB(!1),await this.sleep(100),await this.setRTSWebUSB(!0),await this.setDTRWebUSB(!0),await this.setRTSWebUSB(!0),await this.sleep(100),await this.setDTRWebUSB(!0),await this.setRTSWebUSB(!1),await this.sleep(200)}async hardResetClassicWebUSB(){await this.setDTRWebUSB(!1),await this.setRTSWebUSB(!0),await this.sleep(100),await this.setDTRWebUSB(!0),await this.setRTSWebUSB(!1),await this.sleep(50),await this.setDTRWebUSB(!1),await this.sleep(200)}async hardResetUnixTightWebUSB(){await this.setDTRandRTSWebUSB(!1,!1),await this.setDTRandRTSWebUSB(!0,!0),await this.setDTRandRTSWebUSB(!1,!0),await this.sleep(100),await this.setDTRandRTSWebUSB(!0,!1),await this.sleep(50),await this.setDTRandRTSWebUSB(!1,!1),await this.setDTRWebUSB(!1),await this.sleep(200)}async hardResetClassicLongDelayWebUSB(){await this.setDTRWebUSB(!1),await this.setRTSWebUSB(!0),await this.sleep(500),await this.setDTRWebUSB(!0),await this.setRTSWebUSB(!1),await this.sleep(200),await this.setDTRWebUSB(!1),await this.sleep(500)}async hardResetClassicShortDelayWebUSB(){await this.setDTRWebUSB(!1),await this.setRTSWebUSB(!0),await this.sleep(50),await this.setDTRWebUSB(!0),await this.setRTSWebUSB(!1),await this.sleep(25),await this.setDTRWebUSB(!1),await this.sleep(100)}async hardResetInvertedWebUSB(){await this.setDTRWebUSB(!0),await this.setRTSWebUSB(!1),await this.sleep(100),await this.setDTRWebUSB(!1),await this.setRTSWebUSB(!0),await this.sleep(50),await this.setDTRWebUSB(!0),await this.sleep(200)}async hardResetInvertedDTRWebUSB(){await this.setDTRWebUSB(!0),await this.setRTSWebUSB(!0),await this.sleep(100),await this.setDTRWebUSB(!1),await this.setRTSWebUSB(!1),await this.sleep(50),await this.setDTRWebUSB(!0),await this.sleep(200)}async hardResetInvertedRTSWebUSB(){await this.setDTRWebUSB(!1),await this.setRTSWebUSB(!1),await this.sleep(100),await this.setDTRWebUSB(!0),await this.setRTSWebUSB(!0),await this.sleep(50),await this.setDTRWebUSB(!1),await this.sleep(200)}isWebUSB(){return!0===this.port.isWebUSB}async connectWithResetStrategies(){const t=this.port.getInfo(),e=4097===t.usbProductId,i=12346===t.usbVendorId,a=[],r=this;if(this.isWebUSB()){const s=!e&&!i,n=4292===t.usbVendorId,h=6790===t.usbVendorId,o=12346===t.usbVendorId&&2===t.usbProductId;(e||i)&&(o?(a.push({name:"USB-JTAG/Serial (WebUSB) - ESP32-S2",fn:async function(){return await r.hardResetUSBJTAGSerialWebUSB()}}),a.push({name:"USB-JTAG/Serial Inverted DTR (WebUSB) - ESP32-S2",fn:async function(){return await r.hardResetUSBJTAGSerialInvertedDTRWebUSB()}}),a.push({name:"UnixTight (WebUSB) - ESP32-S2 CDC",fn:async function(){return await r.hardResetUnixTightWebUSB()}}),a.push({name:"Classic (WebUSB) - ESP32-S2 CDC",fn:async function(){return await r.hardResetClassicWebUSB()}})):(a.push({name:"USB-JTAG/Serial Inverted DTR (WebUSB)",fn:async function(){return await r.hardResetUSBJTAGSerialInvertedDTRWebUSB()}}),a.push({name:"USB-JTAG/Serial (WebUSB)",fn:async function(){return await r.hardResetUSBJTAGSerialWebUSB()}}),a.push({name:"Inverted DTR Classic (WebUSB)",fn:async function(){return await r.hardResetInvertedDTRWebUSB()}}))),s&&(h?(a.push({name:"UnixTight (WebUSB) - CH34x",fn:async function(){return await r.hardResetUnixTightWebUSB()}}),a.push({name:"Classic (WebUSB) - CH34x",fn:async function(){return await r.hardResetClassicWebUSB()}}),a.push({name:"Inverted Both (WebUSB) - CH34x",fn:async function(){return await r.hardResetInvertedWebUSB()}}),a.push({name:"Inverted RTS (WebUSB) - CH34x",fn:async function(){return await r.hardResetInvertedRTSWebUSB()}}),a.push({name:"Inverted DTR (WebUSB) - CH34x",fn:async function(){return await r.hardResetInvertedDTRWebUSB()}})):n?(a.push({name:"UnixTight (WebUSB) - CP2102",fn:async function(){return await r.hardResetUnixTightWebUSB()}}),a.push({name:"Classic (WebUSB) - CP2102",fn:async function(){return await r.hardResetClassicWebUSB()}}),a.push({name:"Inverted Both (WebUSB) - CP2102",fn:async function(){return await r.hardResetInvertedWebUSB()}}),a.push({name:"Inverted RTS (WebUSB) - CP2102",fn:async function(){return await r.hardResetInvertedRTSWebUSB()}}),a.push({name:"Inverted DTR (WebUSB) - CP2102",fn:async function(){return await r.hardResetInvertedDTRWebUSB()}})):(a.push({name:"UnixTight (WebUSB)",fn:async function(){return await r.hardResetUnixTightWebUSB()}}),a.push({name:"Classic (WebUSB)",fn:async function(){return await r.hardResetClassicWebUSB()}}),a.push({name:"Inverted Both (WebUSB)",fn:async function(){return await r.hardResetInvertedWebUSB()}}),a.push({name:"Inverted RTS (WebUSB)",fn:async function(){return await r.hardResetInvertedRTSWebUSB()}}),a.push({name:"Inverted DTR (WebUSB)",fn:async function(){return await r.hardResetInvertedDTRWebUSB()}}))),n||o||(6790!==t.usbVendorId&&a.push({name:"Classic (WebUSB)",fn:async function(){return await r.hardResetClassicWebUSB()}}),a.push({name:"UnixTight (WebUSB)",fn:async function(){return await r.hardResetUnixTightWebUSB()}}),a.push({name:"Classic Long Delay (WebUSB)",fn:async function(){return await r.hardResetClassicLongDelayWebUSB()}}),a.push({name:"Classic Short Delay (WebUSB)",fn:async function(){return await r.hardResetClassicShortDelayWebUSB()}}),e||i||a.push({name:"USB-JTAG/Serial fallback (WebUSB)",fn:async function(){return await r.hardResetUSBJTAGSerialWebUSB()}}))}else(e||i)&&a.push({name:"USB-JTAG/Serial",fn:async function(){return await r.hardResetUSBJTAGSerial()}}),a.push({name:"Classic",fn:async function(){return await r.hardResetClassic()}}),e||i||a.push({name:"USB-JTAG/Serial (fallback)",fn:async function(){return await r.hardResetUSBJTAGSerial()}});let n=null;for(const t of a)try{if(!this.connected||!this.port.writable){this.logger.log(`Port disconnected, skipping ${t.name} reset`);continue}this._abandonCurrentOperation=!1,await t.fn();if(await this.syncWithTimeout(3e3))return void this.logger.log(`Connected successfully with ${t.name} reset.`);throw new Error("Sync timeout or abandoned")}catch(e){if(n=e,this.logger.log(`${t.name} reset failed: ${e.message}`),this._abandonCurrentOperation=!0,await s(100),!this.connected||!this.port.writable){this.logger.log("Port disconnected during reset attempt");break}this._clearInputBuffer(),await this.drainInputBuffer(200),await this.flushSerialBuffers()}throw new Error(`Couldn't sync to ESP. Try resetting manually. Last error: ${null==n?void 0:n.message}`)}async hardReset(t=!1){t?4097===this.port.getInfo().usbProductId?(await this.hardResetUSBJTAGSerial(),this.logger.log("USB-JTAG/Serial reset.")):this.isWebUSB()?(await this.hardResetClassicWebUSB(),this.logger.log("Classic reset (WebUSB/Android).")):(await this.hardResetClassic(),this.logger.log("Classic reset.")):this.isWebUSB()?(await this.setRTS(!0),await this.sleep(200),await this.setRTS(!1),await this.sleep(200),this.logger.log("Hard reset (WebUSB).")):(await this.setRTS(!0),await this.sleep(100),await this.setRTS(!1),this.logger.log("Hard reset.")),await new Promise(t=>setTimeout(t,1e3))}macAddr(){const t=new Array(6).fill(0),e=this._efuses[0],i=this._efuses[1],a=this._efuses[2],s=this._efuses[3];let r;if(this.chipFamily==u){if(0!=s)r=[s>>16&255,s>>8&255,255&s];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];t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=i>>8&255,t[4]=255&i,t[5]=e>>24&255}else if(this.chipFamily==d)t[0]=a>>8&255,t[1]=255&a,t[2]=i>>24&255,t[3]=i>>16&255,t[4]=i>>8&255,t[5]=255&i;else{if(this.chipFamily!=c&&this.chipFamily!=_&&this.chipFamily!=f&&this.chipFamily!=g&&this.chipFamily!=p&&this.chipFamily!=w&&this.chipFamily!=m&&this.chipFamily!=b&&this.chipFamily!=y&&this.chipFamily!=S&&this.chipFamily!=B&&this.chipFamily!=v)throw new Error("Unknown chip family");t[0]=i>>8&255,t[1]=255&i,t[2]=e>>24&255,t[3]=e>>16&255,t[4]=e>>8&255,t[5]=255&e}return t}async readRegister(t){this.debug&&this.logger.debug("Reading from Register "+a(t,8));const e=Ne("<I",t);await this.sendCommand(10,e);const[i]=await this.getResponse(10);return i}async checkCommand(t,e,i=0,s=3e3){const r=async()=>{s=Math.min(s,3e5),await this.sendCommand(t,e,i);const[r,n]=await this.getResponse(t,s);if(null===n)throw new Error("Didn't get enough status bytes");let h=n,o=0;if(this.IS_STUB||this.chipFamily==u?o=2:[d,c,_,f,g,p,w,m,b,y,S,B,v].includes(this.chipFamily)||20===t?o=4:[2,4].includes(h.length)?o=h.length:(o=2,this.logger.debug(`Unknown chip family, defaulting to 2-byte status (opcode: ${a(t)}, data.length: ${h.length})`)),h.length<o)throw new Error("Didn't get enough status bytes");const l=h.slice(-o,h.length);if(h=h.slice(0,-o),this.debug&&(this.logger.debug("status",l),this.logger.debug("value",r),this.logger.debug("data",h)),1==l[0])throw 5==l[1]?(await this.drainInputBuffer(200),new Error("Invalid (unsupported) command "+a(t))):new Error("Command failure error code "+a(l[1]));return[r,h]};return this._commandLock=this._commandLock.then(r,r),this._commandLock}async sendCommand(e,i,a=0){const s=t([...Ne("<BBHI",0,e,i.length,a),...i]);this.debug&&this.logger.debug(`Writing ${s.length} byte${1==s.length?"":"s"}:`,s),await this.writeToStream(s)}async readPacket(t){let e=null,r=!1;if(this._isCDCDevice){const n=Date.now();for(;;){if(this._abandonCurrentOperation)throw new F("Operation abandoned (reset strategy timeout)");if(Date.now()-n>t){throw new F("Timed out waiting for packet "+(null===e?"header":"content"))}if(0!==this._inputBufferAvailable)for(;this._inputBufferAvailable>0;){const t=this._readByte();if(null===e){if(192!=t)throw this.debug&&(this.logger.debug("Read invalid data: "+a(t)),this.logger.debug("Remaining data in serial buffer: "+i(this._inputBuffer))),new F("Invalid head of packet ("+a(t)+")");e=[]}else if(r)if(r=!1,220==t)e.push(192);else{if(221!=t)throw this.debug&&(this.logger.debug("Read invalid data: "+a(t)),this.logger.debug("Remaining data in serial buffer: "+i(this._inputBuffer))),new F("Invalid SLIP escape (0xdb, "+a(t)+")");e.push(219)}else if(219==t)r=!0;else{if(192==t)return this.debug&&this.logger.debug("Received full packet: "+i(e)),this._compactInputBuffer(),e;e.push(t)}}else await s(1)}}else{let n=[];for(;;){if(this._abandonCurrentOperation)throw new F("Operation abandoned (reset strategy timeout)");const h=Date.now();for(n=[];Date.now()-h<t;){if(this._inputBufferAvailable>0){n.push(this._readByte());break}await s(1)}if(0==n.length){throw new F("Timed out waiting for packet "+(null===e?"header":"content"))}this.debug&&this.logger.debug("Read "+n.length+" bytes: "+i(n));for(const t of n)if(null===e){if(192!=t)throw this.debug&&(this.logger.debug("Read invalid data: "+a(t)),this.logger.debug("Remaining data in serial buffer: "+i(this._inputBuffer))),new F("Invalid head of packet ("+a(t)+")");e=[]}else if(r)if(r=!1,220==t)e.push(192);else{if(221!=t)throw this.debug&&(this.logger.debug("Read invalid data: "+a(t)),this.logger.debug("Remaining data in serial buffer: "+i(this._inputBuffer))),new F("Invalid SLIP escape (0xdb, "+a(t)+")");e.push(219)}else if(219==t)r=!0;else{if(192==t)return this.debug&&this.logger.debug("Received full packet: "+i(e)),this._compactInputBuffer(),e;e.push(t)}}}}async getResponse(t,e=3e3){for(let i=0;i<100;i++){const i=await this.readPacket(e);if(i.length<8)continue;const[s,r,,n]=Ze("<BBHI",i.slice(0,8));if(1!=s)continue;const h=i.slice(8);if(null==t||r==t)return[n,h];if(0!=h[0]&&5==h[1])throw await this.drainInputBuffer(200),new Error(`Invalid (unsupported) command ${a(t)}`)}throw new Error("Response doesn't match request")}checksum(t,e=239){for(const i of t)e^=i;return e}async setBaudrate(t){if(this.chipFamily==u)throw new Error("Changing baud rate is not supported on the ESP8266");try{const e=Ne("<II",t,this.IS_STUB?h:0);await this.checkCommand(15,e)}catch(e){throw this.logger.error(`Baudrate change error: ${e}`),new Error(`Unable to change the baud rate to ${t}: No response from set baud rate command.`)}this._parent?await this._parent.reconfigurePort(t):await this.reconfigurePort(t),await s(x),this._parent?this._parent._currentBaudRate=t:this._currentBaudRate=t;const e=this._parent?this._parent._maxUSBSerialBaudrate:this._maxUSBSerialBaudrate;e&&t>e&&(this.logger.log(`⚠️ WARNING: Baudrate ${t} exceeds USB-Serial chip limit (${e})!`),this.logger.log("⚠️ This may cause data corruption or connection failures!")),this.logger.log(`Changed baud rate to ${t}`)}async reconfigurePort(t){var e;this._isReconfiguring=!0;try{try{await this._writeChain}catch(t){this.logger.debug(`Pending write error during reconfigure: ${t}`)}if(this.isWebUSB()){const e=this.port.getInfo(),i=6790===e.usbVendorId&&21971===e.usbProductId;if(!i&&"function"==typeof this.port.setBaudRate)return await this.port.setBaudRate(t),void await s(100)}if(this._writer){try{this._writer.releaseLock()}catch(t){this.logger.debug(`Writer release error during reconfigure: ${t}`)}this._writer=void 0}await(null===(e=this._reader)||void 0===e?void 0:e.cancel()),await this.port.close(),await this.port.open({baudRate:t}),await this.flushSerialBuffers(),this.readLoop()}catch(e){throw this.logger.error(`Reconfigure port error: ${e}`),new Error(`Unable to change the baud rate to ${t}: ${e}`)}finally{this._isReconfiguring=!1}}async syncWithTimeout(t){const e=Date.now();for(let i=0;i<5;i++){if(Date.now()-e>t)return!1;if(this._abandonCurrentOperation)return!1;this._clearInputBuffer();try{if(await this._sync())return await s(x),!0}catch(t){if(this._abandonCurrentOperation)return!1}await s(x)}return!1}async sync(){for(let t=0;t<5;t++){this._clearInputBuffer();if(await this._sync())return await s(x),!0;await s(x)}throw new Error("Couldn't sync to ESP. Try resetting.")}async _sync(){await this.sendCommand(8,l);for(let t=0;t<8;t++)try{const[,t]=await this.getResponse(8,x);if(t.length>1&&0==t[0]&&0==t[1])return!0}catch(e){this.debug&&this.logger.debug(`Sync attempt ${t+1} failed: ${e}`)}return!1}getFlashWriteSize(){return this.IS_STUB?16384:1024}async flashData(t,e,i=0,s=!1){if(t.byteLength>=8){const e=Array.from(new Uint8Array(t,0,4)),i=e[0],s=e[2],r=e[3];this.logger.log(`Image header, Magic=${a(i)}, FlashMode=${a(s)}, FlashSizeFreq=${a(r)}`)}const r=t.byteLength;let n,h=0,o=I;s?(n=Pe(new Uint8Array(t),{level:9}).buffer,h=n.byteLength,this.logger.log(`Writing data with filesize: ${r}. Compressed Size: ${h}`),o=await this.flashDeflBegin(r,h,i)):(this.logger.log(`Writing data with filesize: ${r}`),n=t,await this.flashBegin(r,i));let l=[],u=0,d=0,c=0;const _=Date.now(),f=this.getFlashWriteSize(),g=s?h:r;for(;g-c>0;)this.debug&&this.logger.log(`Writing at ${a(i+u*f,8)} `),g-c>=f?l=Array.from(new Uint8Array(n,c,f)):(l=Array.from(new Uint8Array(n,c,g-c)),s||(l=l.concat(new Array(f-l.length).fill(255)))),s?await this.flashDeflBlock(l,u,o):await this.flashBlock(l,u),u+=1,d+=s?Math.round(l.length*r/h):l.length,c+=f,e(Math.min(d,r),r);this.logger.log("Took "+(Date.now()-_)+"ms to write "+g+" bytes"),this.IS_STUB&&(await this.flashBegin(0,0),s?await this.flashDeflFinish():await this.flashFinish())}async flashBlock(t,e,i=3e3){await this.checkCommand(3,Ne("<IIII",t.length,e,0,0).concat(t),this.checksum(t),i)}async flashDeflBlock(t,e,i=3e3){await this.checkCommand(17,Ne("<IIII",t.length,e,0,0).concat(t),this.checksum(t),i)}async flashBegin(t=0,e=0,i=!1){let s;await this.flushSerialBuffers();const r=this.getFlashWriteSize();!this.IS_STUB&&[d,c,_,f,g,p,w,m,b,y,S,B,v].includes(this.chipFamily)&&await this.checkCommand(13,new Array(8).fill(0));const n=Math.floor((t+r-1)/r);s=this.chipFamily==u?this.getEraseSize(e,t):t;const h=this.IS_STUB?I:k(D,t),o=Date.now();let l=Ne("<IIII",s,n,r,e);return this.chipFamily!=d&&this.chipFamily!=c&&this.chipFamily!=_&&this.chipFamily!=f&&this.chipFamily!=g&&this.chipFamily!=p&&this.chipFamily!=w&&this.chipFamily!=m&&this.chipFamily!=b&&this.chipFamily!=y&&this.chipFamily!=S&&this.chipFamily!=B&&this.chipFamily!=v||(l=l.concat(Ne("<I",i?1:0))),this.logger.log("Erase size "+s+", blocks "+n+", block size "+a(r,4)+", offset "+a(e,4)+", encrypted "+(i?"yes":"no")),await this.checkCommand(2,l,0,h),0==t||this.IS_STUB||this.logger.log("Took "+(Date.now()-o)+"ms to erase "+n+" bytes"),n}async flashDeflBegin(t=0,e=0,i=0){const a=this.getFlashWriteSize(),s=Math.floor((e+a-1)/a),r=Math.floor((t+a-1)/a);let n=0,h=0;this.IS_STUB?(n=t,h=k(D,n)):(n=r*a,h=I);const o=Ne("<IIII",n,s,a,i);return await this.checkCommand(16,o,0,h),h}async flashFinish(){const t=Ne("<I",1);await this.checkCommand(4,t)}async flashDeflFinish(){const t=Ne("<I",1);await this.checkCommand(18,t)}getBootloaderOffset(){return C(this.getChipFamily()).flashOffs}async flashId(){return await this.runSpiFlashCommand(159,[],24)}getChipFamily(){return this._parent?this._parent.chipFamily:this.chipFamily}async writeRegister(t,e,i=4294967295,a=0,s=0){let r=Ne("<IIII",t,e,i,a);s>0&&(r=r.concat(Ne("<IIII",C(this.getChipFamily()).uartDateReg,0,0,s))),await this.checkCommand(9,r)}async setDataLengths(t,e,i){if(-1!=t.mosiDlenOffs){const a=t.regBase+t.mosiDlenOffs,s=t.regBase+t.misoDlenOffs;e>0&&await this.writeRegister(a,e-1),i>0&&await this.writeRegister(s,i-1)}else{const a=t.regBase+t.usr1Offs,s=(0==i?0:i-1)<<8|(0==e?0:e-1)<<17;await this.writeRegister(a,s)}}async waitDone(t,e){for(let i=0;i<10;i++){if(0==(await this.readRegister(t)&e))return}throw Error("SPI command did not complete in time")}async runSpiFlashCommand(t,e,i=0){const s=C(this.getChipFamily()),r=s.regBase,n=r,h=r+s.usrOffs,o=r+s.usr2Offs,l=r+s.w0Offs,u=1<<18;if(i>32)throw new Error("Reading more than 32 bits back from a SPI flash operation is unsupported");if(e.length>64)throw new Error("Writing more than 64 bytes of data with one SPI command is unsupported");const d=8*e.length,c=await this.readRegister(h),_=await this.readRegister(o);let f=1<<31;if(i>0&&(f|=268435456),d>0&&(f|=134217728),await this.setDataLengths(s,d,i),await this.writeRegister(h,f),await this.writeRegister(o,7<<28|t),0==d)await this.writeRegister(l,0);else{const t=(4-e.length%4)%4;e=e.concat(new Array(t).fill(0));const i=Ze("I".repeat(Math.floor(e.length/4)),e);let s=l;this.logger.debug(`Words Length: ${i.length}`);for(const t of i)this.logger.debug(`Writing word ${a(t)} to register offset ${a(s)}`),await this.writeRegister(s,t),s+=4}await this.writeRegister(n,u),await this.waitDone(n,u);const g=await this.readRegister(l);return await this.writeRegister(h,c),await this.writeRegister(o,_),g}async detectFlashSize(){this.logger.log("Detecting Flash Size");const t=await this.flashId(),e=255&t,i=t>>16&255;this.logger.log(`FlashId: ${a(t)}`),this.logger.log(`Flash Manufacturer: ${e.toString(16)}`),this.logger.log(`Flash Device: ${(t>>8&255).toString(16)}${i.toString(16)}`),this.flashSize=r[i],this.logger.log(`Auto-detected Flash size: ${this.flashSize}`)}getEraseSize(t,e){const i=n,a=Math.floor((e+i-1)/i);let s=16-Math.floor(t/i)%16;return a<s&&(s=a),a<2*s?Math.floor((a+1)/2*i):(a-s)*i}async memBegin(t,e,i,a){return await this.checkCommand(5,Ne("<IIII",t,e,i,a))}async memBlock(t,e){return await this.checkCommand(7,Ne("<IIII",t.length,e,0,0).concat(t),this.checksum(t))}async memFinish(t=0){const e=this.IS_STUB?I:500,i=Ne("<II",0==t?1:0,t);return await this.checkCommand(6,i,0,e)}async runStub(t=!1){const e=await z(this.chipFamily,this.chipRevision);if(null===e)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 t of["text","data"]){const a=e[t],s=e[`${t}_start`],r=a.length,n=Math.floor((r+i-1)/i);await this.memBegin(r,n,i,s);for(const t of Array(n).keys()){const e=t*i;let s=e+i;s>r&&(s=r),await this.memBlock(a.slice(e,s),t)}}await this.memFinish(e.entry);const a=await this.readPacket(500),s=String.fromCharCode(...a);if("OHAI"!=s)throw new Error("Failed to start stub. Unexpected response: "+s);this.logger.log("Stub is now running...");const r=new He(this.port,this.logger,this);return t||await r.detectFlashSize(),r}get _writer(){return this._parent?this._parent._writer:this.__writer}set _writer(t){this._parent?this._parent._writer=t:this.__writer=t}get _writeChain(){return this._parent?this._parent._writeChain:this.__writeChain}set _writeChain(t){this._parent?this._parent._writeChain=t:this.__writeChain=t}async writeToStream(t){if(this.port.writable){if(this._isReconfiguring)throw new Error("Cannot write during port reconfiguration");this._writeChain=this._writeChain.then(async()=>{if(!this.port.writable)throw new Error("Port became unavailable during write");if(!this._writer)try{this._writer=this.port.writable.getWriter()}catch(t){throw this.logger.error(`Failed to get writer: ${t}`),t}await this._writer.write(new Uint8Array(t))},async()=>{if(this.logger.debug("Previous write failed, attempting recovery for current write"),!this.port.writable)throw new Error("Port became unavailable during write");if(!this._writer)try{this._writer=this.port.writable.getWriter()}catch(t){throw this.logger.debug(`Failed to get writer in recovery: ${t}`),new Error("Cannot acquire writer lock")}await this._writer.write(new Uint8Array(t))}).catch(t=>{if(this.logger.error(`Write error: ${t}`),this._writer){try{this._writer.releaseLock()}catch{}this._writer=void 0}throw t}),await this._writeChain}else this.logger.debug("Port writable stream not available, skipping write")}async disconnect(){if(this._parent)await this._parent.disconnect();else if(this.port.writable){try{await this._writeChain}catch(t){this.logger.debug(`Pending write error during disconnect: ${t}`)}if(this._writer){try{await this._writer.close(),this._writer.releaseLock()}catch(t){this.logger.debug(`Writer close/release error: ${t}`)}this._writer=void 0}else try{const t=this.port.writable.getWriter();await t.close(),t.releaseLock()}catch(t){this.logger.debug(`Direct writer close error: ${t}`)}await new Promise(t=>{this._reader?(this.addEventListener("disconnect",t,{once:!0}),this._reader.cancel()):t(void 0)}),this.connected=!1}else this.logger.debug("Port already closed, skipping disconnect")}async reconnect(){if(this._parent)await this._parent.reconnect();else try{this.logger.log("Reconnecting serial port..."),this.connected=!1,this.__inputBuffer=[],this.__inputBufferReadIndex=0;try{await this._writeChain}catch(t){this.logger.debug(`Pending write error during reconnect: ${t}`)}if(this._isReconfiguring=!0,this._writer){try{this._writer.releaseLock()}catch(t){this.logger.debug(`Writer release error during reconnect: ${t}`)}this._writer=void 0}if(this._reader){try{await this._reader.cancel()}catch(t){this.logger.debug(`Reader cancel error: ${t}`)}this._reader=void 0}try{await this.port.close(),this.logger.log("Port closed")}catch(t){this.logger.debug(`Port close error: ${t}`)}this.logger.debug("Opening port...");try{await this.port.open({baudRate:h}),this.connected=!0}catch(t){throw new Error(`Failed to open port: ${t}`)}if(!this.port.readable||!this.port.writable)throw new Error(`Port streams not available after open (readable: ${!!this.port.readable}, writable: ${!!this.port.writable})`);this._isReconfiguring=!1;const t=this.chipFamily,e=this.chipName,i=this.chipRevision,a=this.chipVariant,s=this.flashSize;if(await this.hardReset(!0),this._parent||(this.__inputBuffer=[],this.__inputBufferReadIndex=0,this.__totalBytesRead=0,this.readLoop()),await this.flushSerialBuffers(),await this.sync(),this.chipFamily=t,this.chipName=e,this.chipRevision=i,this.chipVariant=a,this.flashSize=s,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!==h&&(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=!0,this.logger.debug("Reconnection successful")}catch(t){throw this._isReconfiguring=!1,t}}async drainInputBuffer(t=200){await s(t);let e=0;const i=Date.now();for(;e<112&&Date.now()-i<100;)if(this._inputBufferAvailable>0){void 0!==this._readByte()&&e++}else await s(1);e>0&&this.logger.debug(`Drained ${e} bytes from input buffer`),this._parent||(this.__inputBuffer=[],this.__inputBufferReadIndex=0)}async flushSerialBuffers(){this._parent||(this.__inputBuffer=[],this.__inputBufferReadIndex=0),await s(x),this._parent||(this.__inputBuffer=[],this.__inputBufferReadIndex=0),this.logger.debug("Serial buffers flushed")}async readFlash(e,i,a){if(!this.IS_STUB)throw new Error("Reading flash is only supported in stub mode. Please run runStub() first.");let r;await this.flushSerialBuffers(),this.logger.log(`Reading ${i} bytes from flash at address 0x${e.toString(16)}...`),this.isWebUSB()&&(this._isCDCDevice?(this._adaptiveBlockMultiplier=8,this._adaptiveMaxInFlightMultiplier=8,this._consecutiveSuccessfulChunks=0,this.logger.debug(`CDC device - Initialized: blockMultiplier=${this._adaptiveBlockMultiplier}, maxInFlightMultiplier=${this._adaptiveMaxInFlightMultiplier}`)):(this._adaptiveBlockMultiplier=1,this._adaptiveMaxInFlightMultiplier=1,this._consecutiveSuccessfulChunks=0,this.logger.debug("Non-CDC device - Fixed values: blockSize=31, maxInFlight=31"))),r=this.isWebUSB()?16384:262144;let n=new Uint8Array(0),h=e,o=i;for(;o>0;){const e=Math.min(r,o);let l=!1,u=0;const d=5;let c=!1;for(;!l&&u<=d;){let i=new Uint8Array(0),a=0;try{let r,o;if(0===u&&this.logger.debug(`Reading chunk at 0x${h.toString(16)}, size: 0x${e.toString(16)}`),this.isWebUSB()){const t=this.port.maxTransferSize||64,e=Math.floor((t-2)/2);r=e*this._adaptiveBlockMultiplier,o=e*this._adaptiveMaxInFlightMultiplier}else{const t=63;r=65*t,o=130*t}const d=Ne("<IIII",h,e,r,o),[c]=await this.checkCommand(210,d);if(0!=c)throw new Error("Failed to read memory: "+c);for(;i.length<e;){let r;try{r=await this.readPacket(100)}catch(t){if(t instanceof F){this.logger.debug(`SLIP read error at ${i.length} bytes: ${t.message}`);try{const t=[192,192];await this.writeToStream(t),this.logger.debug("Sent abort frame to stub"),await s(50)}catch(t){this.logger.debug(`Abort frame error: ${t}`)}if(await this.drainInputBuffer(200),i.length>=e)break}throw t}if(r&&r.length>0){const s=new Uint8Array(r),n=new Uint8Array(i.length+s.length);n.set(i),n.set(s,i.length),i=n;if(i.length>=e||i.length>=a+o){const e=Ne("<I",i.length),s=t(e);await this.writeToStream(s),a=i.length}}}const _=new Uint8Array(n.length+i.length);if(_.set(n),_.set(i,n.length),n=_,l=!0,this.isWebUSB()&&this._isCDCDevice&&0===u&&(this._consecutiveSuccessfulChunks++,this._consecutiveSuccessfulChunks>=2)){const t=this.port.maxTransferSize||64,e=Math.floor((t-2)/2),i=8,a=8;let s=!1;if(this._adaptiveBlockMultiplier<i?(this._adaptiveBlockMultiplier=Math.min(2*this._adaptiveBlockMultiplier,i),s=!0):this._adaptiveMaxInFlightMultiplier<a&&(this._adaptiveMaxInFlightMultiplier=Math.min(2*this._adaptiveMaxInFlightMultiplier,a),s=!0),s){const t=e*this._adaptiveBlockMultiplier,i=e*this._adaptiveMaxInFlightMultiplier;this.logger.debug(`Speed increased: blockSize=${t}, maxInFlight=${i}`),this._lastAdaptiveAdjustment=Date.now()}this._consecutiveSuccessfulChunks=0}}catch(t){if(u++,this.isWebUSB()&&this._isCDCDevice&&1===u)if(this._adaptiveBlockMultiplier>1||this._adaptiveMaxInFlightMultiplier>1){this._adaptiveBlockMultiplier=1,this._adaptiveMaxInFlightMultiplier=1,this._consecutiveSuccessfulChunks=0;const t=this.port.maxTransferSize||64,e=Math.floor((t-2)/2),i=e*this._adaptiveBlockMultiplier,a=e*this._adaptiveMaxInFlightMultiplier;this.logger.debug(`Error at higher speed - reduced to minimum: blockSize=${i}, maxInFlight=${a}`)}else this.logger.debug("Error at minimum speed (blockSize=31, maxInFlight=31) - not a speed issue");if(!(t instanceof F))throw t;if(u<=d){this.logger.log(`${t.message} at 0x${h.toString(16)}. Draining buffer and retrying (attempt ${u}/${d})...`);try{await this.drainInputBuffer(200),await this.flushSerialBuffers(),await s(x)}catch(t){this.logger.debug(`Buffer drain error: ${t}`)}}else{if(c)throw new Error(`Failed to read chunk at 0x${h.toString(16)} after ${d} retries and recovery attempt`);c=!0,this.logger.log(`All retries exhausted at 0x${h.toString(16)}. Attempting recovery (close and reopen port)...`);try{await this.reconnect(),this.logger.log("Deep recovery successful. Resuming read from current position..."),u=0;continue}catch(t){throw new Error(`Failed to read chunk at 0x${h.toString(16)} after ${d} retries and recovery failed: ${t}`)}}}}a&&a(new Uint8Array(e),n.length,i),h+=e,o-=e,this.logger.debug(`Total progress: 0x${n.length.toString(16)} from 0x${i.toString(16)} bytes`)}return n}}class He extends Ve{constructor(){super(...arguments),this.IS_STUB=!0}async memBegin(t,e,i,s){const r=await z(this.chipFamily,this.chipRevision);if(null===r)return[0,[]];const n=s,h=s+t;this.logger.debug(`Load range: ${a(n,8)}-${a(h,8)}`),this.logger.debug(`Stub data: ${a(r.data_start,8)}, len: ${r.data.length}, text: ${a(r.text_start,8)}, len: ${r.text.length}`);for(const[t,e]of[[r.data_start,r.data_start+r.data.length],[r.text_start,r.text_start+r.text.length]])if(n<e&&h>t)throw new Error("Software loader is resident at "+a(t,8)+"-"+a(e,8)+". Can't load binary at overlapping address range "+a(n,8)+"-"+a(h,8)+". Try changing the binary loading address.");return[0,[]]}async eraseFlash(){await this.checkCommand(208,[],0,T)}async eraseRegion(t,e){if(t<0)throw new Error(`Invalid offset: ${t} (must be non-negative)`);if(e<0)throw new Error(`Invalid size: ${e} (must be non-negative)`);if(0===e)return void this.logger.log("eraseRegion: size is 0, skipping erase");if(t%n!==0)throw new Error(`Offset ${t} (0x${t.toString(16)}) is not aligned to flash sector size 4096 (0x${n.toString(16)})`);if(e%n!==0)throw new Error(`Size ${e} (0x${e.toString(16)}) is not aligned to flash sector size 4096 (0x${n.toString(16)})`);const i=4294967295;if(t>i)throw new Error(`Offset ${t} exceeds maximum value 4294967295`);if(e>i)throw new Error(`Size ${e} exceeds maximum value 4294967295`);const a=k(D,e),s=Ne("<II",t,e);await this.checkCommand(209,s,0,a)}}const je=async t=>{let e;const i=globalThis.requestSerialPort;if("function"==typeof i)t.log("Using custom port request function"),e=await i();else{if(!navigator.serial)throw new Error("Web Serial API is not supported in this browser. Please use Chrome 89+, Edge 89+, or Opera on desktop, or Chrome 61+ on Android with USB OTG. Note: The page must be served over HTTPS or localhost.");e=await navigator.serial.requestPort()}return e.readable&&e.writable||await e.open({baudRate:h}),t.log("Connected successfully."),new Ve(e,t)},Ge=async(t,e)=>{if(!t)throw new Error("Port is required");return t.readable&&t.writable||await t.open({baudRate:h}),e.log("Connected successfully."),new Ve(t,e)};export{d as CHIP_FAMILY_ESP32,f as CHIP_FAMILY_ESP32C2,g as CHIP_FAMILY_ESP32C3,p as CHIP_FAMILY_ESP32C5,w as CHIP_FAMILY_ESP32C6,m as CHIP_FAMILY_ESP32C61,b as CHIP_FAMILY_ESP32H2,S as CHIP_FAMILY_ESP32H21,y as CHIP_FAMILY_ESP32H4,B as CHIP_FAMILY_ESP32P4,c as CHIP_FAMILY_ESP32S2,_ as CHIP_FAMILY_ESP32S3,v as CHIP_FAMILY_ESP32S31,u as CHIP_FAMILY_ESP8266,Ve as ESPLoader,je as connect,Ge as connectWithPort};
@@ -2,10 +2,10 @@
2
2
  * WebUSBSerial - Web Serial API-like wrapper for WebUSB
3
3
  * Provides a familiar interface for serial communication over USB on Android
4
4
  *
5
- * This enables ESP32Tool to work on Android devices where Web Serial API
5
+ * This enables to work on Android devices where Web Serial API
6
6
  * is not available but WebUSB is supported.
7
7
  *
8
- * IMPORTANT: For Android/Xiaomi compatibility, this class uses smaller transfer sizes
8
+ * IMPORTANT: For Android compatibility, this class uses smaller transfer sizes
9
9
  * to prevent SLIP synchronization errors. The maxTransferSize is set to 64 bytes
10
10
  * (or endpoint packetSize if smaller) to ensure SLIP frames don't get split.
11
11
  */
@@ -24,7 +24,7 @@ class WebUSBSerial {
24
24
  'close': [],
25
25
  'disconnect': []
26
26
  };
27
- // Transfer size optimized for WebUSB on Android/Xiaomi
27
+ // Transfer size optimized for WebUSB on Android
28
28
  // CRITICAL: blockSize = (maxTransferSize - 2) / 2
29
29
  // Set to 64 bytes for maximum compatibility with all USB-Serial adapters
30
30
  // With 64 bytes: blockSize = (64-2)/2 = 31 bytes per SLIP packet
@@ -109,8 +109,7 @@ class WebUSBSerial {
109
109
  const baudRate = options.baudRate || 115200;
110
110
 
111
111
  // If device is already opened, we need to close and reopen it
112
- // This is critical for ESP32-S2 which changes interfaces when switching modes
113
- if (this.device.opened) {
112
+ // This is critical for ESP32-S2
114
113
 
115
114
  try {
116
115
  // Release all interfaces
@@ -148,7 +147,7 @@ class WebUSBSerial {
148
147
  await this.device.reset();
149
148
  }
150
149
  } catch (e) {
151
- // this._log('[WebUSB] Device reset failed:', e.message);
150
+ this._log('[WebUSB] Device reset failed:', e.message);
152
151
  }
153
152
 
154
153
  const attemptOpenAndClaim = async () => {
@@ -595,7 +594,7 @@ class WebUSBSerial {
595
594
  */
596
595
  async setSignals(signals) {
597
596
  // Serialize all control transfers through a queue
598
- // This is CRITICAL for CP2102 on Android - parallel commands cause hangs
597
+ // This is CRITICAL for CP2102 - parallel commands cause hangs
599
598
  this._commandQueue = this._commandQueue.then(async () => {
600
599
  if (!this.device) {
601
600
  throw new Error('Device not open');
@@ -811,8 +810,6 @@ class WebUSBSerial {
811
810
  // CH340 (WCH VID: 0x1a86, but not CH343 PID: 0x55d3)
812
811
  else if (vid === 0x1a86 && pid !== 0x55d3) {
813
812
  // CH340 baudrate calculation (from Linux kernel driver)
814
- // CH341_BAUDBASE_FACTOR = 1532620800
815
- // CH341_BAUDBASE_DIVMAX = 3
816
813
  const CH341_BAUDBASE_FACTOR = 1532620800;
817
814
  const CH341_BAUDBASE_DIVMAX = 3;
818
815
 
@@ -979,7 +976,7 @@ class WebUSBSerial {
979
976
  /**
980
977
  * Selects and returns a serial port using the most appropriate browser API for the current platform.
981
978
  *
982
- * Attempts WebUSB on Android (where Web Serial is unreliable) and prefers the Web Serial API on desktop,
979
+ * Attempts WebUSB on Android and prefers the Web Serial API on desktop,
983
980
  * falling back between APIs as needed.
984
981
  * @param {boolean} forceNew - When true, prefer requesting a new device (ignore previously authorized devices) for WebUSB.
985
982
  * @returns {SerialPort|WebUSBSerial} A serial port obtained from the Web Serial API or a WebUSBSerial instance wrapping a USB device.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tasmota-webserial-esptool",
3
- "version": "9.1.5",
3
+ "version": "9.1.6",
4
4
  "description": "World's first tool for flashing and reading ESP devices on Android mobile devices using WebUSB. Flash & Read ESP devices using WebSerial/WebUSB - up to 10x faster flash read than esptool.py",
5
5
  "main": "dist/index.js",
6
6
  "repository": {
package/src/esp_loader.ts CHANGED
@@ -42,6 +42,7 @@ import {
42
42
  USB_RAM_BLOCK,
43
43
  ChipFamily,
44
44
  ESP_ERASE_FLASH,
45
+ ESP_ERASE_REGION,
45
46
  ESP_READ_FLASH,
46
47
  CHIP_ERASE_TIMEOUT,
47
48
  FLASH_READ_TIMEOUT,
@@ -613,6 +614,21 @@ export class ESPLoader extends EventTarget {
613
614
  };
614
615
  }
615
616
 
617
+ /**
618
+ * Get MAC address from efuses
619
+ */
620
+ async getMacAddress(): Promise<string> {
621
+ if (!this._initializationSucceeded) {
622
+ throw new Error(
623
+ "getMacAddress() requires initialize() to have completed successfully",
624
+ );
625
+ }
626
+ const macBytes = this.macAddr(); // chip-family-aware
627
+ return macBytes
628
+ .map((b) => b.toString(16).padStart(2, "0").toUpperCase())
629
+ .join(":");
630
+ }
631
+
616
632
  /**
617
633
  * @name readLoop
618
634
  * Reads data from the input stream and places it in the inputBuffer
@@ -647,7 +663,13 @@ export class ESPLoader extends EventTarget {
647
663
  }
648
664
  } catch {
649
665
  this.logger.error("Read loop got disconnected");
666
+ } finally {
667
+ // Always reset reconfiguring flag when read loop ends
668
+ // This prevents "Cannot write during port reconfiguration" errors
669
+ // when the read loop dies unexpectedly
670
+ this._isReconfiguring = false;
650
671
  }
672
+
651
673
  // Disconnected!
652
674
  this.connected = false;
653
675
 
@@ -2608,50 +2630,43 @@ export class ESPLoader extends EventTarget {
2608
2630
  return;
2609
2631
  }
2610
2632
 
2633
+ // Wait for pending writes to complete
2611
2634
  try {
2612
- // Wait for pending writes to complete
2635
+ await this._writeChain;
2636
+ } catch (err) {
2637
+ this.logger.debug(`Pending write error during disconnect: ${err}`);
2638
+ }
2639
+
2640
+ // Release persistent writer before closing
2641
+ if (this._writer) {
2613
2642
  try {
2614
- await this._writeChain;
2643
+ await this._writer.close();
2644
+ this._writer.releaseLock();
2615
2645
  } catch (err) {
2616
- this.logger.debug(`Pending write error during disconnect: ${err}`);
2646
+ this.logger.debug(`Writer close/release error: ${err}`);
2617
2647
  }
2618
-
2619
- // Block new writes during disconnect
2620
- this._isReconfiguring = true;
2621
-
2622
- // Release persistent writer before closing
2623
- if (this._writer) {
2624
- try {
2625
- await this._writer.close();
2626
- this._writer.releaseLock();
2627
- } catch (err) {
2628
- this.logger.debug(`Writer close/release error: ${err}`);
2629
- }
2630
- this._writer = undefined;
2631
- } else {
2632
- // No persistent writer exists, close stream directly
2633
- // This path is taken when no writes have been queued
2634
- try {
2635
- const writer = this.port.writable.getWriter();
2636
- await writer.close();
2637
- writer.releaseLock();
2638
- } catch (err) {
2639
- this.logger.debug(`Direct writer close error: ${err}`);
2640
- }
2648
+ this._writer = undefined;
2649
+ } else {
2650
+ // No persistent writer exists, close stream directly
2651
+ // This path is taken when no writes have been queued
2652
+ try {
2653
+ const writer = this.port.writable.getWriter();
2654
+ await writer.close();
2655
+ writer.releaseLock();
2656
+ } catch (err) {
2657
+ this.logger.debug(`Direct writer close error: ${err}`);
2641
2658
  }
2642
-
2643
- await new Promise((resolve) => {
2644
- if (!this._reader) {
2645
- resolve(undefined);
2646
- return;
2647
- }
2648
- this.addEventListener("disconnect", resolve, { once: true });
2649
- this._reader!.cancel();
2650
- });
2651
- this.connected = false;
2652
- } finally {
2653
- this._isReconfiguring = false;
2654
2659
  }
2660
+
2661
+ await new Promise((resolve) => {
2662
+ if (!this._reader) {
2663
+ resolve(undefined);
2664
+ return;
2665
+ }
2666
+ this.addEventListener("disconnect", resolve, { once: true });
2667
+ this._reader!.cancel();
2668
+ });
2669
+ this.connected = false;
2655
2670
  }
2656
2671
 
2657
2672
  /**
@@ -3029,8 +3044,9 @@ export class ESPLoader extends EventTarget {
3029
3044
  newResp.set(packetData, resp.length);
3030
3045
  resp = newResp;
3031
3046
 
3032
- // Send acknowledgment after receiving maxInFlight bytes
3033
- // This unblocks the stub to send the next batch of packets
3047
+ // Send acknowledgment when we've received maxInFlight bytes
3048
+ // The stub sends packets until (num_sent - num_acked) >= max_in_flight
3049
+ // We MUST wait for all packets before sending ACK
3034
3050
  const shouldAck =
3035
3051
  resp.length >= chunkSize || // End of chunk
3036
3052
  resp.length >= lastAckedLength + maxInFlight; // Received all packets
@@ -3274,10 +3290,55 @@ class EspStubLoader extends ESPLoader {
3274
3290
  }
3275
3291
 
3276
3292
  /**
3277
- * @name getEraseSize
3278
- * depending on flash chip model the erase may take this long (maybe longer!)
3293
+ * @name eraseFlash
3294
+ * Erase entire flash chip
3279
3295
  */
3280
3296
  async eraseFlash() {
3281
3297
  await this.checkCommand(ESP_ERASE_FLASH, [], 0, CHIP_ERASE_TIMEOUT);
3282
3298
  }
3299
+
3300
+ /**
3301
+ * @name eraseRegion
3302
+ * Erase a specific region of flash
3303
+ */
3304
+ async eraseRegion(offset: number, size: number) {
3305
+ // Validate inputs
3306
+ if (offset < 0) {
3307
+ throw new Error(`Invalid offset: ${offset} (must be non-negative)`);
3308
+ }
3309
+ if (size < 0) {
3310
+ throw new Error(`Invalid size: ${size} (must be non-negative)`);
3311
+ }
3312
+
3313
+ // No-op for zero size
3314
+ if (size === 0) {
3315
+ this.logger.log("eraseRegion: size is 0, skipping erase");
3316
+ return;
3317
+ }
3318
+
3319
+ // Check for sector alignment
3320
+ if (offset % FLASH_SECTOR_SIZE !== 0) {
3321
+ throw new Error(
3322
+ `Offset ${offset} (0x${offset.toString(16)}) is not aligned to flash sector size ${FLASH_SECTOR_SIZE} (0x${FLASH_SECTOR_SIZE.toString(16)})`,
3323
+ );
3324
+ }
3325
+ if (size % FLASH_SECTOR_SIZE !== 0) {
3326
+ throw new Error(
3327
+ `Size ${size} (0x${size.toString(16)}) is not aligned to flash sector size ${FLASH_SECTOR_SIZE} (0x${FLASH_SECTOR_SIZE.toString(16)})`,
3328
+ );
3329
+ }
3330
+
3331
+ // Check for reasonable bounds (prevent wrapping in pack)
3332
+ const maxValue = 0xffffffff; // 32-bit unsigned max
3333
+ if (offset > maxValue) {
3334
+ throw new Error(`Offset ${offset} exceeds maximum value ${maxValue}`);
3335
+ }
3336
+ if (size > maxValue) {
3337
+ throw new Error(`Size ${size} exceeds maximum value ${maxValue}`);
3338
+ }
3339
+
3340
+ const timeout = timeoutPerMb(ERASE_REGION_TIMEOUT_PER_MB, size);
3341
+ const buffer = pack("<II", offset, size);
3342
+ await this.checkCommand(ESP_ERASE_REGION, buffer, 0, timeout);
3343
+ }
3283
3344
  }