tasmota-webserial-esptool 7.3.8 → 7.3.10

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.
@@ -98,19 +98,6 @@ export declare class ESPLoader extends EventTarget {
98
98
  * Get MAC address from efuses
99
99
  */
100
100
  getMacAddress(): Promise<string>;
101
- /**
102
- * Detect if device is using USB-JTAG/Serial or USB-OTG (not external serial chip)
103
- * Stub implementation - returns undefined (not yet implemented in WebSerial_ESPTool)
104
- */
105
- detectUsbConnectionType(): Promise<boolean>;
106
- /**
107
- * Get USB mode (UART, USB-JTAG/Serial, or USB-OTG)
108
- * Reads the UARTDEV_BUF_NO register to determine the USB mode
109
- */
110
- getUsbMode(): Promise<{
111
- mode: "uart" | "usb-jtag-serial" | "usb-otg";
112
- uartNo: number;
113
- }>;
114
101
  /**
115
102
  * Get ESP32-C5 crystal frequency from ROM expectation
116
103
  */
@@ -1,7 +1,7 @@
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, ESP32_BASEFUSEADDR, ESP32_APB_CTL_DATE_ADDR, ESP32S2_EFUSE_BLOCK1_ADDR, ESP32S3_EFUSE_BLOCK1_ADDR, ESP32C2_EFUSE_BLOCK2_ADDR, ESP32C5_EFUSE_BLOCK1_ADDR, ESP32C6_EFUSE_BLOCK1_ADDR, ESP32C61_EFUSE_BLOCK1_ADDR, ESP32H2_EFUSE_BLOCK1_ADDR, ESP32P4_EFUSE_BLOCK1_ADDR, ESP32S31_EFUSE_BLOCK1_ADDR, ESP32C3_EFUSE_RD_MAC_SPI_SYS_3_REG, ESP32C3_EFUSE_RD_MAC_SPI_SYS_5_REG, ESP32C5_UART_CLKDIV_REG, ESP32C5_PCR_SYSCLK_CONF_REG, ESP32C5_PCR_SYSCLK_XTAL_FREQ_V, ESP32C5_PCR_SYSCLK_XTAL_FREQ_S, ESP32S2_UARTDEV_BUF_NO, ESP32S2_UARTDEV_BUF_NO_USB_OTG, ESP32S3_UARTDEV_BUF_NO, ESP32S3_UARTDEV_BUF_NO_USB_OTG, ESP32S3_UARTDEV_BUF_NO_USB_JTAG_SERIAL, ESP32C3_UARTDEV_BUF_NO_USB_JTAG_SERIAL, ESP32C3_BUF_UART_NO_OFFSET, ESP32C5_UARTDEV_BUF_NO, ESP32C5_UARTDEV_BUF_NO_USB_JTAG_SERIAL, ESP32C6_UARTDEV_BUF_NO, ESP32C6_UARTDEV_BUF_NO_USB_JTAG_SERIAL, ESP32C61_UARTDEV_BUF_NO_REV_LE2, ESP32C61_UARTDEV_BUF_NO_REV_GT2, ESP32C61_UARTDEV_BUF_NO_USB_JTAG_SERIAL_REV_LE2, ESP32C61_UARTDEV_BUF_NO_USB_JTAG_SERIAL_REV_GT2, ESP32H2_UARTDEV_BUF_NO, ESP32H2_UARTDEV_BUF_NO_USB_JTAG_SERIAL, ESP32H4_UARTDEV_BUF_NO, ESP32H4_UARTDEV_BUF_NO_USB_JTAG_SERIAL, ESP32P4_UARTDEV_BUF_NO_REV0, ESP32P4_UARTDEV_BUF_NO_REV300, ESP32P4_UARTDEV_BUF_NO_USB_OTG, ESP32P4_UARTDEV_BUF_NO_USB_JTAG_SERIAL, SlipReadError, ESP32P4_LP_SYSTEM_REG_ANA_XPD_PAD_GROUP_REG, ESP32P4_PMU_EXT_LDO_P0_0P1A_ANA_REG, ESP32P4_PMU_ANA_0P1A_EN_CUR_LIM_0, ESP32P4_PMU_EXT_LDO_P0_0P1A_REG, ESP32P4_PMU_0P1A_TARGET0_0, ESP32P4_PMU_0P1A_FORCE_TIEH_SEL_0, ESP32P4_PMU_DATE_REG, } 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_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, ESP32_BASEFUSEADDR, ESP32_APB_CTL_DATE_ADDR, ESP32S2_EFUSE_BLOCK1_ADDR, ESP32S3_EFUSE_BLOCK1_ADDR, ESP32C2_EFUSE_BLOCK2_ADDR, ESP32C5_EFUSE_BLOCK1_ADDR, ESP32C6_EFUSE_BLOCK1_ADDR, ESP32C61_EFUSE_BLOCK1_ADDR, ESP32H2_EFUSE_BLOCK1_ADDR, ESP32P4_EFUSE_BLOCK1_ADDR, ESP32S31_EFUSE_BLOCK1_ADDR, ESP32C3_EFUSE_RD_MAC_SPI_SYS_3_REG, ESP32C3_EFUSE_RD_MAC_SPI_SYS_5_REG, ESP32C5_UART_CLKDIV_REG, ESP32C5_PCR_SYSCLK_CONF_REG, ESP32C5_PCR_SYSCLK_XTAL_FREQ_V, ESP32C5_PCR_SYSCLK_XTAL_FREQ_S, SlipReadError, ESP32P4_LP_SYSTEM_REG_ANA_XPD_PAD_GROUP_REG, ESP32P4_PMU_EXT_LDO_P0_0P1A_ANA_REG, ESP32P4_PMU_ANA_0P1A_EN_CUR_LIM_0, ESP32P4_PMU_EXT_LDO_P0_0P1A_REG, ESP32P4_PMU_0P1A_TARGET0_0, ESP32P4_PMU_0P1A_FORCE_TIEH_SEL_0, ESP32P4_PMU_DATE_REG, } from "./const";
3
3
  import { getStubCode } from "./stubs";
4
- import { hexFormatter, sleep, slipEncode, toHex } from "./util";
4
+ import { hexFormatter, padTo, sleep, slipEncode, toHex } from "./util";
5
5
  // @ts-expect-error pako ESM module doesn't have proper type definitions
6
6
  import { deflate } from "pako/dist/pako.esm.mjs";
7
7
  import { pack, unpack } from "./struct";
@@ -325,22 +325,6 @@ export class ESPLoader extends EventTarget {
325
325
  if (this.chipFamily === CHIP_FAMILY_ESP32P4 && this.chipRevision === 301) {
326
326
  await this.powerOnFlash();
327
327
  }
328
- // Detect if device is using USB-JTAG/Serial or USB-OTG (not external serial chip)
329
- // This is needed to determine the correct reset strategy for console mode
330
- try {
331
- this._isUsbJtagOrOtg = await this.detectUsbConnectionType();
332
- this.logger.debug(`USB connection type: ${this._isUsbJtagOrOtg ? "USB-JTAG/OTG" : "External Serial Chip"}`);
333
- }
334
- catch (err) {
335
- this.logger.debug(`Could not detect USB connection type: ${err}`);
336
- }
337
- try {
338
- const usbMode = await this.getUsbMode();
339
- this.logger.debug(`USB mode (register): ${usbMode.mode} (uartNo=${usbMode.uartNo})`);
340
- }
341
- catch (err) {
342
- this.logger.debug(`Could not detect USB mode: ${err}`);
343
- }
344
328
  // Read the OTP data for this chip and store into this.efuses array
345
329
  const FlAddr = getSpiFlashAddresses(this.getChipFamily());
346
330
  const AddrMAC = FlAddr.macFuse;
@@ -587,93 +571,6 @@ export class ESPLoader extends EventTarget {
587
571
  .map((b) => b.toString(16).padStart(2, "0").toUpperCase())
588
572
  .join(":");
589
573
  }
590
- /**
591
- * Detect if device is using USB-JTAG/Serial or USB-OTG (not external serial chip)
592
- * Stub implementation - returns undefined (not yet implemented in WebSerial_ESPTool)
593
- */
594
- async detectUsbConnectionType() {
595
- // Stub implementation - would need USB PID detection
596
- return false;
597
- }
598
- /**
599
- * Get USB mode (UART, USB-JTAG/Serial, or USB-OTG)
600
- * Reads the UARTDEV_BUF_NO register to determine the USB mode
601
- */
602
- async getUsbMode() {
603
- var _a, _b;
604
- const family = this._parent ? this._parent.chipFamily : this.chipFamily;
605
- const revision = this._parent
606
- ? ((_a = this._parent.chipRevision) !== null && _a !== void 0 ? _a : 0)
607
- : ((_b = this.chipRevision) !== null && _b !== void 0 ? _b : 0);
608
- let bufNoAddr = null;
609
- let jtagSerialVal = null;
610
- let otgVal = null;
611
- switch (family) {
612
- case CHIP_FAMILY_ESP32S2:
613
- bufNoAddr = ESP32S2_UARTDEV_BUF_NO;
614
- otgVal = ESP32S2_UARTDEV_BUF_NO_USB_OTG;
615
- break;
616
- case CHIP_FAMILY_ESP32S3:
617
- bufNoAddr = ESP32S3_UARTDEV_BUF_NO;
618
- jtagSerialVal = ESP32S3_UARTDEV_BUF_NO_USB_JTAG_SERIAL;
619
- otgVal = ESP32S3_UARTDEV_BUF_NO_USB_OTG;
620
- break;
621
- case CHIP_FAMILY_ESP32C3: {
622
- const bssAddr = revision < 101 ? 0x3fcdf064 : 0x3fcdf060;
623
- bufNoAddr = bssAddr + ESP32C3_BUF_UART_NO_OFFSET;
624
- jtagSerialVal = ESP32C3_UARTDEV_BUF_NO_USB_JTAG_SERIAL;
625
- break;
626
- }
627
- case CHIP_FAMILY_ESP32C5:
628
- bufNoAddr = ESP32C5_UARTDEV_BUF_NO;
629
- jtagSerialVal = ESP32C5_UARTDEV_BUF_NO_USB_JTAG_SERIAL;
630
- break;
631
- case CHIP_FAMILY_ESP32C6:
632
- bufNoAddr = ESP32C6_UARTDEV_BUF_NO;
633
- jtagSerialVal = ESP32C6_UARTDEV_BUF_NO_USB_JTAG_SERIAL;
634
- break;
635
- case CHIP_FAMILY_ESP32C61:
636
- bufNoAddr =
637
- revision <= 200
638
- ? ESP32C61_UARTDEV_BUF_NO_REV_LE2
639
- : ESP32C61_UARTDEV_BUF_NO_REV_GT2;
640
- jtagSerialVal =
641
- revision <= 200
642
- ? ESP32C61_UARTDEV_BUF_NO_USB_JTAG_SERIAL_REV_LE2
643
- : ESP32C61_UARTDEV_BUF_NO_USB_JTAG_SERIAL_REV_GT2;
644
- break;
645
- case CHIP_FAMILY_ESP32H2:
646
- bufNoAddr = ESP32H2_UARTDEV_BUF_NO;
647
- jtagSerialVal = ESP32H2_UARTDEV_BUF_NO_USB_JTAG_SERIAL;
648
- break;
649
- case CHIP_FAMILY_ESP32H4:
650
- bufNoAddr = ESP32H4_UARTDEV_BUF_NO;
651
- jtagSerialVal = ESP32H4_UARTDEV_BUF_NO_USB_JTAG_SERIAL;
652
- break;
653
- case CHIP_FAMILY_ESP32P4:
654
- bufNoAddr =
655
- revision < 300
656
- ? ESP32P4_UARTDEV_BUF_NO_REV0
657
- : ESP32P4_UARTDEV_BUF_NO_REV300;
658
- jtagSerialVal = ESP32P4_UARTDEV_BUF_NO_USB_JTAG_SERIAL;
659
- otgVal = ESP32P4_UARTDEV_BUF_NO_USB_OTG;
660
- break;
661
- }
662
- if (bufNoAddr === null) {
663
- return { mode: "uart", uartNo: 0 };
664
- }
665
- const uartNo = (await this.readRegister(bufNoAddr)) & 0xff;
666
- if (otgVal !== null && uartNo === otgVal) {
667
- this.logger.debug(`USB mode: USB-OTG (uartNo=${uartNo})`);
668
- return { mode: "usb-otg", uartNo };
669
- }
670
- if (jtagSerialVal !== null && uartNo === jtagSerialVal) {
671
- this.logger.debug(`USB mode: USB-JTAG/Serial (uartNo=${uartNo})`);
672
- return { mode: "usb-jtag-serial", uartNo };
673
- }
674
- this.logger.debug(`USB mode: UART (uartNo=${uartNo})`);
675
- return { mode: "uart", uartNo };
676
- }
677
574
  /**
678
575
  * Get ESP32-C5 crystal frequency from ROM expectation
679
576
  */
@@ -1362,6 +1259,8 @@ export class ESPLoader extends EventTarget {
1362
1259
  const headerFlashSizeFreq = header[3];
1363
1260
  this.logger.log(`Image header, Magic=${toHex(headerMagic)}, FlashMode=${toHex(headerFlashMode)}, FlashSizeFreq=${toHex(headerFlashSizeFreq)}`);
1364
1261
  }
1262
+ const paddedData = padTo(new Uint8Array(binaryData), 4);
1263
+ binaryData = paddedData.buffer;
1365
1264
  const uncompressedFilesize = binaryData.byteLength;
1366
1265
  let compressedFilesize = 0;
1367
1266
  let dataToFlash;
@@ -2116,7 +2015,7 @@ export class ESPLoader extends EventTarget {
2116
2015
  }
2117
2016
  catch (err) {
2118
2017
  if (err instanceof SlipReadError) {
2119
- this.logger.debug(`SLIP read error at ${resp.length} bytes: ${err.message}`);
2018
+ this.logger.debug(`${err.message} at byte 0x${resp.length.toString(16)}`);
2120
2019
  // Send empty SLIP frame to abort the stub's read operation
2121
2020
  // The stub expects 4 bytes (ACK), if we send less it will break out
2122
2021
  try {
@@ -2164,18 +2063,8 @@ export class ESPLoader extends EventTarget {
2164
2063
  // Check if it's a timeout error or SLIP error
2165
2064
  if (err instanceof SlipReadError) {
2166
2065
  if (retryCount <= MAX_RETRIES) {
2167
- this.logger.log(`${err.message} at 0x${currentAddr.toString(16)}. Draining buffer and retrying (attempt ${retryCount}/${MAX_RETRIES})...`);
2168
- try {
2169
- await this.drainInputBuffer(200);
2170
- // Clear application buffer
2171
- await this.flushSerialBuffers();
2172
- // Wait before retry to let hardware settle
2173
- await sleep(SYNC_TIMEOUT);
2174
- // Continue to retry the same chunk (will send NEW read command)
2175
- }
2176
- catch (drainErr) {
2177
- this.logger.debug(`Buffer drain error: ${drainErr}`);
2178
- }
2066
+ this.logger.log(`Cleared buffer and retrying (attempt ${retryCount}/${MAX_RETRIES})...`);
2067
+ // Continue to retry the same chunk (will send NEW read command)
2179
2068
  }
2180
2069
  else {
2181
2070
  // All retries exhausted - attempt deep recovery by reconnecting and reloading stub
package/dist/util.d.ts CHANGED
@@ -11,4 +11,13 @@ export declare const slipEncode: (buffer: number[]) => number[];
11
11
  export declare const toByteArray: (str: string) => number[];
12
12
  export declare const hexFormatter: (bytes: number[]) => string;
13
13
  export declare const toHex: (value: number, size?: number) => string;
14
+ /**
15
+ * Format MAC address array to string (e.g., [0xAA, 0xBB, 0xCC] -> "AA:BB:CC:DD:EE:FF")
16
+ */
17
+ export declare const formatMacAddr: (macAddr: number[]) => string;
18
+ /**
19
+ * @name padTo
20
+ * Pad data to the next alignment boundary with the given fill byte (default 0xFF)
21
+ */
22
+ export declare function padTo(data: Uint8Array, alignment: number, padCharacter?: number): Uint8Array;
14
23
  export declare const sleep: (ms: number) => Promise<unknown>;
package/dist/util.js CHANGED
@@ -43,4 +43,27 @@ export const toHex = (value, size = 2) => {
43
43
  return "0x" + hex.padStart(size, "0");
44
44
  }
45
45
  };
46
+ /**
47
+ * Format MAC address array to string (e.g., [0xAA, 0xBB, 0xCC] -> "AA:BB:CC:DD:EE:FF")
48
+ */
49
+ export const formatMacAddr = (macAddr) => {
50
+ return macAddr
51
+ .map((value) => value.toString(16).toUpperCase().padStart(2, "0"))
52
+ .join(":");
53
+ };
54
+ /**
55
+ * @name padTo
56
+ * Pad data to the next alignment boundary with the given fill byte (default 0xFF)
57
+ */
58
+ export function padTo(data, alignment, padCharacter = 0xff) {
59
+ const padMod = data.length % alignment;
60
+ if (padMod !== 0) {
61
+ const padding = new Uint8Array(alignment - padMod).fill(padCharacter);
62
+ const paddedData = new Uint8Array(data.length + padding.length);
63
+ paddedData.set(data);
64
+ paddedData.set(padding, data.length);
65
+ return paddedData;
66
+ }
67
+ return data;
68
+ }
46
69
  export const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
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 s=t.charCodeAt(i);s<=255&&e.push(s)}return e},i=t=>"["+t.map(t=>s(t)).join(", ")+"]",s=(t,e=2)=>{const i=t.toString(16).toUpperCase();return i.startsWith("-")?"-0x"+i.substring(1).padStart(e,"0"):"0x"+i.padStart(e,"0")},a=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=1073061888,o=1061265408,l=1610612856,c=1610641408,d=1610612864,_=1610647552,u=1610647552,g=1611352064,f=1611335680,p=1611352064,w=1611335680,m=1343410176,b=1343312316,y=1<<27,v=1343312312,S=1343312892,R=544296960,B=e(" UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU"),k=33382,F=50,U=12882,x=12883,I=12994,O=12995,D=12997,C=12998,z=207969,A=12914,E=12916,$=12917,T=12928,P=12849,M={5:{name:"ESP32-C3",family:O},9:{name:"ESP32-S3",family:x},12:{name:"ESP32-C2",family:I},13:{name:"ESP32-C6",family:C},16:{name:"ESP32-H2",family:A},18:{name:"ESP32-P4",family:T},20:{name:"ESP32-C61",family:z},23:{name:"ESP32-C5",family:D},25:{name:"ESP32-H21",family:$},28:{name:"ESP32-H4",family:E},32:{name:"ESP32-S31",family:P}},L={4293968129:{name:"ESP8266",family:k},15736195:{name:"ESP32",family:F},1990:{name:"ESP32-S2",family:U}},N=3e3,Z=15e4,V=100,H=(t,e)=>{const i=Math.floor(t*(e/486));return i<N?N:i},j=t=>{switch(t){case F:return{regBase:1072963584,baseFuse:h,macFuse:1073061888,usrOffs:28,usr1Offs:32,usr2Offs:36,mosiDlenOffs:40,misoDlenOffs:44,w0Offs:128,uartDateReg:1610612856,flashOffs:4096};case U:return{regBase:1061167104,baseFuse:o,macFuse:1061265476,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:l,flashOffs:4096};case x:return{regBase:1610620928,usrOffs:24,baseFuse:c,macFuse:1610641476,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:d,flashOffs:0};case k:return{regBase:1610613248,usrOffs:28,baseFuse:1072693328,macFuse:1072693328,usr1Offs:32,usr2Offs:36,mosiDlenOffs:-1,misoDlenOffs:-1,w0Offs:64,uartDateReg:1610612856,flashOffs:0};case I:return{regBase:1610620928,baseFuse:_,macFuse:1610647616,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case O:return{regBase:1610620928,baseFuse:u,macFuse:1610647620,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case D:return{regBase:1610625024,baseFuse:g,macFuse:1611352132,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:8192};case C:return{regBase:1610625024,baseFuse:f,macFuse:1611335748,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case z:return{regBase:1610625024,baseFuse:p,macFuse:1611352132,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case A:return{regBase:1610625024,baseFuse:w,macFuse:1611335748,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case E:return{regBase:1611239424,baseFuse:1611339776,macFuse:1611339844,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610686588,flashOffs:8192};case $:return{regBase:1610625024,baseFuse:1611350016,macFuse:1611350084,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case T:return{regBase:1342754816,baseFuse:m,macFuse:1343410244,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1343004812,flashOffs:8192};case P:return{regBase:542113792,baseFuse:R,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 W extends Error{constructor(t){super(t),this.name="SlipReadError"}}const G=async(t,i)=>{let s;return t==E||t==$||t==P?null:(t==F?s=await import("./esp32-BRKoi17y.js"):t==U?s=await import("./esp32s2-iX3WoDbg.js"):t==x?s=await import("./esp32s3-DGwDVIgz.js"):t==k?s=await import("./esp8266-CUwxJpGa.js"):t==I?s=await import("./esp32c2-Btgr_lwh.js"):t==O?s=await import("./esp32c3-CHKfoI8W.js"):t==D?s=await import("./esp32c5-BDW4KtLo.js"):t==C?s=await import("./esp32c6-il8tTxAG.js"):t==z?s=await import("./esp32c61-thKzxBGf.js"):t==A?s=await import("./esp32h2-CxoUHv_P.js"):t==T&&(s=null!=i&&i>=300?await import("./esp32p4r3-CqI71ojR.js"):await import("./esp32p4-D3jLP-jY.js")),{...s,text:e(atob(s.text)),data:e(atob(s.data))})};function J(t){let e=t.length;for(;--e>=0;)t[e]=0}const q=256,K=286,Y=30,X=15,Q=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]),tt=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]),et=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),it=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),st=new Array(576);J(st);const at=new Array(60);J(at);const rt=new Array(512);J(rt);const nt=new Array(256);J(nt);const ht=new Array(29);J(ht);const ot=new Array(Y);function lt(t,e,i,s,a){this.static_tree=t,this.extra_bits=e,this.extra_base=i,this.elems=s,this.max_length=a,this.has_stree=t&&t.length}let ct,dt,_t;function ut(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}J(ot);const gt=t=>t<256?rt[t]:rt[256+(t>>>7)],ft=(t,e)=>{t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255},pt=(t,e,i)=>{t.bi_valid>16-i?(t.bi_buf|=e<<t.bi_valid&65535,ft(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)},wt=(t,e,i)=>{pt(t,i[2*e],i[2*e+1])},mt=(t,e)=>{let i=0;do{i|=1&t,t>>>=1,i<<=1}while(--e>0);return i>>>1},bt=(t,e,i)=>{const s=new Array(16);let a,r,n=0;for(a=1;a<=X;a++)n=n+i[a-1]<<1,s[a]=n;for(r=0;r<=e;r++){let e=t[2*r+1];0!==e&&(t[2*r]=mt(s[e]++,e))}},yt=t=>{let e;for(e=0;e<K;e++)t.dyn_ltree[2*e]=0;for(e=0;e<Y;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},vt=t=>{t.bi_valid>8?ft(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0},St=(t,e,i,s)=>{const a=2*e,r=2*i;return t[a]<t[r]||t[a]===t[r]&&s[e]<=s[i]},Rt=(t,e,i)=>{const s=t.heap[i];let a=i<<1;for(;a<=t.heap_len&&(a<t.heap_len&&St(e,t.heap[a+1],t.heap[a],t.depth)&&a++,!St(e,s,t.heap[a],t.depth));)t.heap[i]=t.heap[a],i=a,a<<=1;t.heap[i]=s},Bt=(t,e,i)=>{let s,a,r,n,h=0;if(0!==t.sym_next)do{s=255&t.pending_buf[t.sym_buf+h++],s+=(255&t.pending_buf[t.sym_buf+h++])<<8,a=t.pending_buf[t.sym_buf+h++],0===s?wt(t,a,e):(r=nt[a],wt(t,r+q+1,e),n=Q[r],0!==n&&(a-=ht[r],pt(t,a,n)),s--,r=gt(s),wt(t,r,i),n=tt[r],0!==n&&(s-=ot[r],pt(t,s,n)))}while(h<t.sym_next);wt(t,256,e)},kt=(t,e)=>{const i=e.dyn_tree,s=e.stat_desc.static_tree,a=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--,a&&(t.static_len-=s[2*o+1]);for(e.max_code=l,n=t.heap_len>>1;n>=1;n--)Rt(t,i,n);o=r;do{n=t.heap[1],t.heap[1]=t.heap[t.heap_len--],Rt(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++,Rt(t,i,1)}while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],((t,e)=>{const i=e.dyn_tree,s=e.max_code,a=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,c,d,_,u,g,f=0;for(_=0;_<=X;_++)t.bl_count[_]=0;for(i[2*t.heap[t.heap_max]+1]=0,l=t.heap_max+1;l<573;l++)c=t.heap[l],_=i[2*i[2*c+1]+1]+1,_>o&&(_=o,f++),i[2*c+1]=_,c>s||(t.bl_count[_]++,u=0,c>=h&&(u=n[c-h]),g=i[2*c],t.opt_len+=g*(_+u),r&&(t.static_len+=g*(a[2*c+1]+u)));if(0!==f){do{for(_=o-1;0===t.bl_count[_];)_--;t.bl_count[_]--,t.bl_count[_+1]+=2,t.bl_count[o]--,f-=2}while(f>0);for(_=o;0!==_;_--)for(c=t.bl_count[_];0!==c;)d=t.heap[--l],d>s||(i[2*d+1]!==_&&(t.opt_len+=(_-i[2*d+1])*i[2*d],i[2*d+1]=_),c--)}})(t,e),bt(i,l,t.bl_count)},Ft=(t,e,i)=>{let s,a,r=-1,n=e[1],h=0,o=7,l=4;for(0===n&&(o=138,l=3),e[2*(i+1)+1]=65535,s=0;s<=i;s++)a=n,n=e[2*(s+1)+1],++h<o&&a===n||(h<l?t.bl_tree[2*a]+=h:0!==a?(a!==r&&t.bl_tree[2*a]++,t.bl_tree[32]++):h<=10?t.bl_tree[34]++:t.bl_tree[36]++,h=0,r=a,0===n?(o=138,l=3):a===n?(o=6,l=3):(o=7,l=4))},Ut=(t,e,i)=>{let s,a,r=-1,n=e[1],h=0,o=7,l=4;for(0===n&&(o=138,l=3),s=0;s<=i;s++)if(a=n,n=e[2*(s+1)+1],!(++h<o&&a===n)){if(h<l)do{wt(t,a,t.bl_tree)}while(0!==--h);else 0!==a?(a!==r&&(wt(t,a,t.bl_tree),h--),wt(t,16,t.bl_tree),pt(t,h-3,2)):h<=10?(wt(t,17,t.bl_tree),pt(t,h-3,3)):(wt(t,18,t.bl_tree),pt(t,h-11,7));h=0,r=a,0===n?(o=138,l=3):a===n?(o=6,l=3):(o=7,l=4)}};let xt=!1;const It=(t,e,i,s)=>{pt(t,0+(s?1:0),3),vt(t),ft(t,i),ft(t,~i),i&&t.pending_buf.set(t.window.subarray(e,e+i),t.pending),t.pending+=i};var Ot=(t,e,i,s)=>{let a,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<q;e++)if(0!==t.dyn_ltree[2*e])return 1;return 0})(t)),kt(t,t.l_desc),kt(t,t.d_desc),n=(t=>{let e;for(Ft(t,t.dyn_ltree,t.l_desc.max_code),Ft(t,t.dyn_dtree,t.d_desc.max_code),kt(t,t.bl_desc),e=18;e>=3&&0===t.bl_tree[2*it[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e})(t),a=t.opt_len+3+7>>>3,r=t.static_len+3+7>>>3,r<=a&&(a=r)):a=r=i+5,i+4<=a&&-1!==e?It(t,e,i,s):4===t.strategy||r===a?(pt(t,2+(s?1:0),3),Bt(t,st,at)):(pt(t,4+(s?1:0),3),((t,e,i,s)=>{let a;for(pt(t,e-257,5),pt(t,i-1,5),pt(t,s-4,4),a=0;a<s;a++)pt(t,t.bl_tree[2*it[a]+1],3);Ut(t,t.dyn_ltree,e-1),Ut(t,t.dyn_dtree,i-1)})(t,t.l_desc.max_code+1,t.d_desc.max_code+1,n+1),Bt(t,t.dyn_ltree,t.dyn_dtree)),yt(t),s&&vt(t)},Dt={_tr_init:t=>{xt||((()=>{let t,e,i,s,a;const r=new Array(16);for(i=0,s=0;s<28;s++)for(ht[s]=i,t=0;t<1<<Q[s];t++)nt[i++]=s;for(nt[i-1]=s,a=0,s=0;s<16;s++)for(ot[s]=a,t=0;t<1<<tt[s];t++)rt[a++]=s;for(a>>=7;s<Y;s++)for(ot[s]=a<<7,t=0;t<1<<tt[s]-7;t++)rt[256+a++]=s;for(e=0;e<=X;e++)r[e]=0;for(t=0;t<=143;)st[2*t+1]=8,t++,r[8]++;for(;t<=255;)st[2*t+1]=9,t++,r[9]++;for(;t<=279;)st[2*t+1]=7,t++,r[7]++;for(;t<=287;)st[2*t+1]=8,t++,r[8]++;for(bt(st,287,r),t=0;t<Y;t++)at[2*t+1]=5,at[2*t]=mt(t,5);ct=new lt(st,Q,257,K,X),dt=new lt(at,tt,0,Y,X),_t=new lt(new Array(0),et,0,19,7)})(),xt=!0),t.l_desc=new ut(t.dyn_ltree,ct),t.d_desc=new ut(t.dyn_dtree,dt),t.bl_desc=new ut(t.bl_tree,_t),t.bi_buf=0,t.bi_valid=0,yt(t)},_tr_stored_block:It,_tr_flush_block:Ot,_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*(nt[i]+q+1)]++,t.dyn_dtree[2*gt(e)]++),t.sym_next===t.sym_end),_tr_align:t=>{pt(t,2,3),wt(t,256,st),(t=>{16===t.bi_valid?(ft(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 Ct=(t,e,i,s)=>{let a=65535&t,r=t>>>16&65535,n=0;for(;0!==i;){n=i>2e3?2e3:i,i-=n;do{a=a+e[s++]|0,r=r+a|0}while(--n);a%=65521,r%=65521}return a|r<<16};const zt=new Uint32Array((()=>{let t,e=[];for(var i=0;i<256;i++){t=i;for(var s=0;s<8;s++)t=1&t?3988292384^t>>>1:t>>>1;e[i]=t}return e})());var At=(t,e,i,s)=>{const a=zt,r=s+i;t^=-1;for(let i=s;i<r;i++)t=t>>>8^a[255&(t^e[i])];return-1^t},Et={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"},$t={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:Tt,_tr_stored_block:Pt,_tr_flush_block:Mt,_tr_tally:Lt,_tr_align:Nt}=Dt,{Z_NO_FLUSH:Zt,Z_PARTIAL_FLUSH:Vt,Z_FULL_FLUSH:Ht,Z_FINISH:jt,Z_BLOCK:Wt,Z_OK:Gt,Z_STREAM_END:Jt,Z_STREAM_ERROR:qt,Z_DATA_ERROR:Kt,Z_BUF_ERROR:Yt,Z_DEFAULT_COMPRESSION:Xt,Z_FILTERED:Qt,Z_HUFFMAN_ONLY:te,Z_RLE:ee,Z_FIXED:ie,Z_DEFAULT_STRATEGY:se,Z_UNKNOWN:ae,Z_DEFLATED:re}=$t,ne=258,he=262,oe=42,le=113,ce=666,de=(t,e)=>(t.msg=Et[e],e),_e=t=>2*t-(t>4?9:0),ue=t=>{let e=t.length;for(;--e>=0;)t[e]=0},ge=t=>{let e,i,s,a=t.w_size;e=t.hash_size,s=e;do{i=t.head[--s],t.head[s]=i>=a?i-a:0}while(--e);e=a,s=e;do{i=t.prev[--s],t.prev[s]=i>=a?i-a:0}while(--e)};let fe=(t,e,i)=>(e<<t.hash_shift^i)&t.hash_mask;const pe=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))},we=(t,e)=>{Mt(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,pe(t.strm)},me=(t,e)=>{t.pending_buf[t.pending++]=e},be=(t,e)=>{t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e},ye=(t,e,i,s)=>{let a=t.avail_in;return a>s&&(a=s),0===a?0:(t.avail_in-=a,e.set(t.input.subarray(t.next_in,t.next_in+a),i),1===t.state.wrap?t.adler=Ct(t.adler,e,a,i):2===t.state.wrap&&(t.adler=At(t.adler,e,a,i)),t.next_in+=a,t.total_in+=a,a)},ve=(t,e)=>{let i,s,a=t.max_chain_length,r=t.strstart,n=t.prev_length,h=t.nice_match;const o=t.strstart>t.w_size-he?t.strstart-(t.w_size-he):0,l=t.window,c=t.w_mask,d=t.prev,_=t.strstart+ne;let u=l[r+n-1],g=l[r+n];t.prev_length>=t.good_match&&(a>>=2),h>t.lookahead&&(h=t.lookahead);do{if(i=e,l[i+n]===g&&l[i+n-1]===u&&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<_);if(s=ne-(_-r),r=_-ne,s>n){if(t.match_start=e,n=s,s>=h)break;u=l[r+n-1],g=l[r+n]}}}while((e=d[e&c])>o&&0!==--a);return n<=t.lookahead?n:t.lookahead},Se=t=>{const e=t.w_size;let i,s,a;do{if(s=t.window_size-t.lookahead-t.strstart,t.strstart>=e+(e-he)&&(t.window.set(t.window.subarray(e,e+e-s),0),t.match_start-=e,t.strstart-=e,t.block_start-=e,t.insert>t.strstart&&(t.insert=t.strstart),ge(t),s+=e),0===t.strm.avail_in)break;if(i=ye(t.strm,t.window,t.strstart+t.lookahead,s),t.lookahead+=i,t.lookahead+t.insert>=3)for(a=t.strstart-t.insert,t.ins_h=t.window[a],t.ins_h=fe(t,t.ins_h,t.window[a+1]);t.insert&&(t.ins_h=fe(t,t.ins_h,t.window[a+3-1]),t.prev[a&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=a,a++,t.insert--,!(t.lookahead+t.insert<3)););}while(t.lookahead<he&&0!==t.strm.avail_in)},Re=(t,e)=>{let i,s,a,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,a=t.bi_valid+42>>3,t.strm.avail_out<a)break;if(a=t.strm.avail_out-a,s=t.strstart-t.block_start,i>s+t.strm.avail_in&&(i=s+t.strm.avail_in),i>a&&(i=a),i<r&&(0===i&&e!==jt||e===Zt||i!==s+t.strm.avail_in))break;n=e===jt&&i===s+t.strm.avail_in?1:0,Pt(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,pe(t.strm),s&&(s>i&&(s=i),t.strm.output.set(t.window.subarray(t.block_start,t.block_start+s),t.strm.next_out),t.strm.next_out+=s,t.strm.avail_out-=s,t.strm.total_out+=s,t.block_start+=s,i-=s),i&&(ye(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!==Zt&&e!==jt&&0===t.strm.avail_in&&t.strstart===t.block_start?2:(a=t.window_size-t.strstart,t.strm.avail_in>a&&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++,a+=t.w_size,t.insert>t.strstart&&(t.insert=t.strstart)),a>t.strm.avail_in&&(a=t.strm.avail_in),a&&(ye(t.strm,t.window,t.strstart,a),t.strstart+=a,t.insert+=a>t.w_size-t.insert?t.w_size-t.insert:a),t.high_water<t.strstart&&(t.high_water=t.strstart),a=t.bi_valid+42>>3,a=t.pending_buf_size-a>65535?65535:t.pending_buf_size-a,r=a>t.w_size?t.w_size:a,s=t.strstart-t.block_start,(s>=r||(s||e===jt)&&e!==Zt&&0===t.strm.avail_in&&s<=a)&&(i=s>a?a:s,n=e===jt&&0===t.strm.avail_in&&i===s?1:0,Pt(t,t.block_start,i,n),t.block_start+=i,pe(t.strm)),n?3:1)},Be=(t,e)=>{let i,s;for(;;){if(t.lookahead<he){if(Se(t),t.lookahead<he&&e===Zt)return 1;if(0===t.lookahead)break}if(i=0,t.lookahead>=3&&(t.ins_h=fe(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-he&&(t.match_length=ve(t,i)),t.match_length>=3)if(s=Lt(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=fe(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=fe(t,t.ins_h,t.window[t.strstart+1]);else s=Lt(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(s&&(we(t,!1),0===t.strm.avail_out))return 1}return t.insert=t.strstart<2?t.strstart:2,e===jt?(we(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(we(t,!1),0===t.strm.avail_out)?1:2},ke=(t,e)=>{let i,s,a;for(;;){if(t.lookahead<he){if(Se(t),t.lookahead<he&&e===Zt)return 1;if(0===t.lookahead)break}if(i=0,t.lookahead>=3&&(t.ins_h=fe(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-he&&(t.match_length=ve(t,i),t.match_length<=5&&(t.strategy===Qt||3===t.match_length&&t.strstart-t.match_start>4096)&&(t.match_length=2)),t.prev_length>=3&&t.match_length<=t.prev_length){a=t.strstart+t.lookahead-3,s=Lt(t,t.strstart-1-t.prev_match,t.prev_length-3),t.lookahead-=t.prev_length-1,t.prev_length-=2;do{++t.strstart<=a&&(t.ins_h=fe(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++,s&&(we(t,!1),0===t.strm.avail_out))return 1}else if(t.match_available){if(s=Lt(t,0,t.window[t.strstart-1]),s&&we(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&&(s=Lt(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<2?t.strstart:2,e===jt?(we(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(we(t,!1),0===t.strm.avail_out)?1:2};function Fe(t,e,i,s,a){this.good_length=t,this.max_lazy=e,this.nice_length=i,this.max_chain=s,this.func=a}const Ue=[new Fe(0,0,0,0,Re),new Fe(4,4,8,4,Be),new Fe(4,5,16,8,Be),new Fe(4,6,32,32,Be),new Fe(4,4,16,16,ke),new Fe(8,16,32,32,ke),new Fe(8,16,128,128,ke),new Fe(8,32,128,256,ke),new Fe(32,128,258,1024,ke),new Fe(32,258,258,4096,ke)];function xe(){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=re,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),ue(this.dyn_ltree),ue(this.dyn_dtree),ue(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),ue(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),ue(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 Ie=t=>{if(!t)return 1;const e=t.state;return!e||e.strm!==t||e.status!==oe&&57!==e.status&&69!==e.status&&73!==e.status&&91!==e.status&&103!==e.status&&e.status!==le&&e.status!==ce?1:0},Oe=t=>{if(Ie(t))return de(t,qt);t.total_in=t.total_out=0,t.data_type=ae;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?oe:le,t.adler=2===e.wrap?0:1,e.last_flush=-2,Tt(e),Gt},De=t=>{const e=Oe(t);var i;return e===Gt&&((i=t.state).window_size=2*i.w_size,ue(i.head),i.max_lazy_match=Ue[i.level].max_lazy,i.good_match=Ue[i.level].good_length,i.nice_match=Ue[i.level].nice_length,i.max_chain_length=Ue[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},Ce=(t,e,i,s,a,r)=>{if(!t)return qt;let n=1;if(e===Xt&&(e=6),s<0?(n=0,s=-s):s>15&&(n=2,s-=16),a<1||a>9||i!==re||s<8||s>15||e<0||e>9||r<0||r>ie||8===s&&1!==n)return de(t,qt);8===s&&(s=9);const h=new xe;return t.state=h,h.strm=t,h.status=oe,h.wrap=n,h.gzhead=null,h.w_bits=s,h.w_size=1<<h.w_bits,h.w_mask=h.w_size-1,h.hash_bits=a+7,h.hash_size=1<<h.hash_bits,h.hash_mask=h.hash_size-1,h.hash_shift=~~((h.hash_bits+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<<a+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,De(t)};var ze={deflateInit:(t,e)=>Ce(t,e,re,15,8,se),deflateInit2:Ce,deflateReset:De,deflateResetKeep:Oe,deflateSetHeader:(t,e)=>Ie(t)||2!==t.state.wrap?qt:(t.state.gzhead=e,Gt),deflate:(t,e)=>{if(Ie(t)||e>Wt||e<0)return t?de(t,qt):qt;const i=t.state;if(!t.output||0!==t.avail_in&&!t.input||i.status===ce&&e!==jt)return de(t,0===t.avail_out?Yt:qt);const s=i.last_flush;if(i.last_flush=e,0!==i.pending){if(pe(t),0===t.avail_out)return i.last_flush=-1,Gt}else if(0===t.avail_in&&_e(e)<=_e(s)&&e!==jt)return de(t,Yt);if(i.status===ce&&0!==t.avail_in)return de(t,Yt);if(i.status===oe&&0===i.wrap&&(i.status=le),i.status===oe){let e=re+(i.w_bits-8<<4)<<8,s=-1;if(s=i.strategy>=te||i.level<2?0:i.level<6?1:6===i.level?2:3,e|=s<<6,0!==i.strstart&&(e|=32),e+=31-e%31,be(i,e),0!==i.strstart&&(be(i,t.adler>>>16),be(i,65535&t.adler)),t.adler=1,i.status=le,pe(t),0!==i.pending)return i.last_flush=-1,Gt}if(57===i.status)if(t.adler=0,me(i,31),me(i,139),me(i,8),i.gzhead)me(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)),me(i,255&i.gzhead.time),me(i,i.gzhead.time>>8&255),me(i,i.gzhead.time>>16&255),me(i,i.gzhead.time>>24&255),me(i,9===i.level?2:i.strategy>=te||i.level<2?4:0),me(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(me(i,255&i.gzhead.extra.length),me(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(t.adler=At(t.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=69;else if(me(i,0),me(i,0),me(i,0),me(i,0),me(i,0),me(i,9===i.level?2:i.strategy>=te||i.level<2?4:0),me(i,3),i.status=le,pe(t),0!==i.pending)return i.last_flush=-1,Gt;if(69===i.status){if(i.gzhead.extra){let e=i.pending,s=(65535&i.gzhead.extra.length)-i.gzindex;for(;i.pending+s>i.pending_buf_size;){let a=i.pending_buf_size-i.pending;if(i.pending_buf.set(i.gzhead.extra.subarray(i.gzindex,i.gzindex+a),i.pending),i.pending=i.pending_buf_size,i.gzhead.hcrc&&i.pending>e&&(t.adler=At(t.adler,i.pending_buf,i.pending-e,e)),i.gzindex+=a,pe(t),0!==i.pending)return i.last_flush=-1,Gt;e=0,s-=a}let a=new Uint8Array(i.gzhead.extra);i.pending_buf.set(a.subarray(i.gzindex,i.gzindex+s),i.pending),i.pending+=s,i.gzhead.hcrc&&i.pending>e&&(t.adler=At(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,s=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>s&&(t.adler=At(t.adler,i.pending_buf,i.pending-s,s)),pe(t),0!==i.pending)return i.last_flush=-1,Gt;s=0}e=i.gzindex<i.gzhead.name.length?255&i.gzhead.name.charCodeAt(i.gzindex++):0,me(i,e)}while(0!==e);i.gzhead.hcrc&&i.pending>s&&(t.adler=At(t.adler,i.pending_buf,i.pending-s,s)),i.gzindex=0}i.status=91}if(91===i.status){if(i.gzhead.comment){let e,s=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>s&&(t.adler=At(t.adler,i.pending_buf,i.pending-s,s)),pe(t),0!==i.pending)return i.last_flush=-1,Gt;s=0}e=i.gzindex<i.gzhead.comment.length?255&i.gzhead.comment.charCodeAt(i.gzindex++):0,me(i,e)}while(0!==e);i.gzhead.hcrc&&i.pending>s&&(t.adler=At(t.adler,i.pending_buf,i.pending-s,s))}i.status=103}if(103===i.status){if(i.gzhead.hcrc){if(i.pending+2>i.pending_buf_size&&(pe(t),0!==i.pending))return i.last_flush=-1,Gt;me(i,255&t.adler),me(i,t.adler>>8&255),t.adler=0}if(i.status=le,pe(t),0!==i.pending)return i.last_flush=-1,Gt}if(0!==t.avail_in||0!==i.lookahead||e!==Zt&&i.status!==ce){let s=0===i.level?Re(i,e):i.strategy===te?((t,e)=>{let i;for(;;){if(0===t.lookahead&&(Se(t),0===t.lookahead)){if(e===Zt)return 1;break}if(t.match_length=0,i=Lt(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,i&&(we(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===jt?(we(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(we(t,!1),0===t.strm.avail_out)?1:2})(i,e):i.strategy===ee?((t,e)=>{let i,s,a,r;const n=t.window;for(;;){if(t.lookahead<=ne){if(Se(t),t.lookahead<=ne&&e===Zt)return 1;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=3&&t.strstart>0&&(a=t.strstart-1,s=n[a],s===n[++a]&&s===n[++a]&&s===n[++a])){r=t.strstart+ne;do{}while(s===n[++a]&&s===n[++a]&&s===n[++a]&&s===n[++a]&&s===n[++a]&&s===n[++a]&&s===n[++a]&&s===n[++a]&&a<r);t.match_length=ne-(r-a),t.match_length>t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=3?(i=Lt(t,1,t.match_length-3),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(i=Lt(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),i&&(we(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===jt?(we(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(we(t,!1),0===t.strm.avail_out)?1:2})(i,e):Ue[i.level].func(i,e);if(3!==s&&4!==s||(i.status=ce),1===s||3===s)return 0===t.avail_out&&(i.last_flush=-1),Gt;if(2===s&&(e===Vt?Nt(i):e!==Wt&&(Pt(i,0,0,!1),e===Ht&&(ue(i.head),0===i.lookahead&&(i.strstart=0,i.block_start=0,i.insert=0))),pe(t),0===t.avail_out))return i.last_flush=-1,Gt}return e!==jt?Gt:i.wrap<=0?Jt:(2===i.wrap?(me(i,255&t.adler),me(i,t.adler>>8&255),me(i,t.adler>>16&255),me(i,t.adler>>24&255),me(i,255&t.total_in),me(i,t.total_in>>8&255),me(i,t.total_in>>16&255),me(i,t.total_in>>24&255)):(be(i,t.adler>>>16),be(i,65535&t.adler)),pe(t),i.wrap>0&&(i.wrap=-i.wrap),0!==i.pending?Gt:Jt)},deflateEnd:t=>{if(Ie(t))return qt;const e=t.state.status;return t.state=null,e===le?de(t,Kt):Gt},deflateSetDictionary:(t,e)=>{let i=e.length;if(Ie(t))return qt;const s=t.state,a=s.wrap;if(2===a||1===a&&s.status!==oe||s.lookahead)return qt;if(1===a&&(t.adler=Ct(t.adler,e,i,0)),s.wrap=0,i>=s.w_size){0===a&&(ue(s.head),s.strstart=0,s.block_start=0,s.insert=0);let t=new Uint8Array(s.w_size);t.set(e.subarray(i-s.w_size,i),0),e=t,i=s.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,Se(s);s.lookahead>=3;){let t=s.strstart,e=s.lookahead-2;do{s.ins_h=fe(s,s.ins_h,s.window[t+3-1]),s.prev[t&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=t,t++}while(--e);s.strstart=t,s.lookahead=2,Se(s)}return s.strstart+=s.lookahead,s.block_start=s.strstart,s.insert=s.lookahead,s.lookahead=0,s.match_length=s.prev_length=2,s.match_available=0,t.next_in=n,t.input=h,t.avail_in=r,s.wrap=a,Gt},deflateInfo:"pako deflate (from Nodeca project)"};const Ae=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var Ee=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)Ae(i,e)&&(t[e]=i[e])}}return t},$e=t=>{let e=0;for(let i=0,s=t.length;i<s;i++)e+=t[i].length;const i=new Uint8Array(e);for(let e=0,s=0,a=t.length;e<a;e++){let a=t[e];i.set(a,s),s+=a.length}return i};let Te=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(t){Te=!1}const Pe=new Uint8Array(256);for(let t=0;t<256;t++)Pe[t]=t>=252?6:t>=248?5:t>=240?4:t>=224?3:t>=192?2:1;Pe[254]=Pe[254]=1;var Me=t=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(t);let e,i,s,a,r,n=t.length,h=0;for(a=0;a<n;a++)i=t.charCodeAt(a),55296==(64512&i)&&a+1<n&&(s=t.charCodeAt(a+1),56320==(64512&s)&&(i=65536+(i-55296<<10)+(s-56320),a++)),h+=i<128?1:i<2048?2:i<65536?3:4;for(e=new Uint8Array(h),r=0,a=0;r<h;a++)i=t.charCodeAt(a),55296==(64512&i)&&a+1<n&&(s=t.charCodeAt(a+1),56320==(64512&s)&&(i=65536+(i-55296<<10)+(s-56320),a++)),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 Le=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 Ne=Object.prototype.toString,{Z_NO_FLUSH:Ze,Z_SYNC_FLUSH:Ve,Z_FULL_FLUSH:He,Z_FINISH:je,Z_OK:We,Z_STREAM_END:Ge,Z_DEFAULT_COMPRESSION:Je,Z_DEFAULT_STRATEGY:qe,Z_DEFLATED:Ke}=$t;function Ye(t){this.options=Ee({level:Je,method:Ke,chunkSize:16384,windowBits:15,memLevel:8,strategy:qe},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 Le,this.strm.avail_out=0;let i=ze.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(i!==We)throw new Error(Et[i]);if(e.header&&ze.deflateSetHeader(this.strm,e.header),e.dictionary){let t;if(t="string"==typeof e.dictionary?Me(e.dictionary):"[object ArrayBuffer]"===Ne.call(e.dictionary)?new Uint8Array(e.dictionary):e.dictionary,i=ze.deflateSetDictionary(this.strm,t),i!==We)throw new Error(Et[i]);this._dict_set=!0}}Ye.prototype.push=function(t,e){const i=this.strm,s=this.options.chunkSize;let a,r;if(this.ended)return!1;for(r=e===~~e?e:!0===e?je:Ze,"string"==typeof t?i.input=Me(t):"[object ArrayBuffer]"===Ne.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(s),i.next_out=0,i.avail_out=s),(r===Ve||r===He)&&i.avail_out<=6)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else{if(a=ze.deflate(i,r),a===Ge)return i.next_out>0&&this.onData(i.output.subarray(0,i.next_out)),a=ze.deflateEnd(this.strm),this.onEnd(a),this.ended=!0,a===We;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},Ye.prototype.onData=function(t){this.chunks.push(t)},Ye.prototype.onEnd=function(t){t===We&&(this.result=$e(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};var Xe={deflate:function(t,e){const i=new Ye(e);if(i.push(t,!0),i.err)throw i.msg||Et[i.err];return i.result}};const{deflate:Qe}=Xe;var ti=Qe;const ei={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}},ii=(t,...e)=>{let i=0;if(t.replace(/[<>]/,"").length!=e.length)throw"Pack format to Argument count mismatch";const s=[];let a=!0;for(let s=0;s<t.length;s++)"<"==t[s]?a=!0:">"==t[s]?a=!1:(r(t[s],e[i]),i++);function r(t,e){if(!(t in ei))throw"Unhandled character '"+t+"' in pack format";const i=ei[t].bytes,r=new DataView(new ArrayBuffer(i));ei[t].p.bind(r)(0,e,a);for(let t=0;t<i;t++)s.push(r.getUint8(t))}return s},si=(t,e)=>{let i=0;const s=[];let a=!0;for(const e of t)"<"==e?a=!0:">"==e?a=!1:r(e);function r(t){if(!(t in ei))throw"Unhandled character '"+t+"' in unpack format";const r=ei[t].bytes,n=new DataView(new ArrayBuffer(r));for(let t=0;t<r;t++)n.setUint8(t,255&e[i+t]);const h=ei[t].u.bind(n);s.push(h(0,a)),i+=r}return s};class ai 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._suppressDisconnect=!1,this.__consoleMode=!1,this._isUsbJtagOrOtg=void 0,this.__adaptiveBlockMultiplier=1,this.__adaptiveMaxInFlightMultiplier=1,this.__consecutiveSuccessfulChunks=0,this.__lastAdaptiveAdjustment=0,this.__isCDCDevice=!1,this.state_DTR=!1,this.state_RTS=!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 _consoleMode(){return this._parent?this._parent._consoleMode:this.__consoleMode}set _consoleMode(t){this._parent?this._parent._consoleMode=t:this.__consoleMode=t}setConsoleMode(t){this._consoleMode=t}get _inputBuffer(){if(this._parent)return this._parent._inputBuffer;if(void 0===this.__inputBuffer)throw new Error("_inputBuffer accessed before initialization");return 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}_clearInputBuffer(){this._inputBuffer.length=0,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}get isUsbJtagOrOtg(){return this._parent?this._parent._isUsbJtagOrOtg:this._isUsbJtagOrOtg}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},18:{name:"ESP32-P4 Native USB",maxBaudrate:2e6},4097:{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(),this.chipFamily===T&&301===this.chipRevision&&await this.powerOnFlash();try{this._isUsbJtagOrOtg=await this.detectUsbConnectionType(),this.logger.debug("USB connection type: "+(this._isUsbJtagOrOtg?"USB-JTAG/OTG":"External Serial Chip"))}catch(t){this.logger.debug(`Could not detect USB connection type: ${t}`)}try{const t=await this.getUsbMode();this.logger.debug(`USB mode (register): ${t.mode} (uartNo=${t.uartNo})`)}catch(t){this.logger.debug(`Could not detect USB mode: ${t}`)}const t=j(this.getChipFamily()),e=t.macFuse;for(let t=0;t<4;t++)this._efuses[t]=await this.readRegister(e+4*t);const i=null!==this.chipRevision&&void 0!==this.chipRevision?` (revision ${this.chipRevision})`:"";this.logger.log(`Connected to ${this.chipName}${i}`),this.logger.debug(`Bootloader flash offset: 0x${t.flashOffs.toString(16)}`),this._initializationSucceeded=!0}async detectChip(){try{const t=(await this.getSecurityInfo()).chipId,e=M[t];if(e)return this.chipName=e.name,this.chipFamily=e.family,this.chipRevision=await this.getChipRevision(),this.logger.debug(`${this.chipName} revision: ${this.chipRevision}`),this.chipFamily===T&&this.chipRevision>=300?this.chipVariant="rev300":this.chipFamily===T&&(this.chipVariant="rev0"),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 a(V);try{await this.sync()}catch(t){this.logger.debug(`Re-sync after GET_SECURITY_INFO failure: ${t}`)}}const t=await this.readRegister(1073745920),e=L[t>>>0];if(void 0===e)throw new Error(`Unknown Chip: Hex: ${s(t>>>0,8).toLowerCase()} Number: ${t}`);this.chipName=e.name,this.chipFamily=e.family,this.chipRevision=await this.getChipRevision(),this.logger.debug(`${this.chipName} revision: ${this.chipRevision}`),this.chipFamily===T&&(this.chipVariant=this.chipRevision>=300?"rev300":"rev0",this.logger.debug(`ESP32-P4 variant: ${this.chipVariant}`)),this.logger.debug(`Detected chip via magic value: ${s(t>>>0,8)} (${this.chipName})`)}async getChipRevision(){var t;let e=0,i=0;switch(this.chipFamily){case F:{const s=await this.readRegister(1073061900),a=await this.readRegister(1073061908);e=a>>24&3;const r=s>>15&1,n=a>>20&1;i=null!==(t={0:0,1:1,3:2,7:3}[(await this.readRegister(1610612856)>>31&1)<<2|n<<1|r])&&void 0!==t?t:0;break}case U:{const t=await this.readRegister(1061265488);e=((t>>20&1)<<3)+(await this.readRegister(1061265492)>>4&7),i=t>>18&3;break}case x:{const t=await this.readRegister(1610641488),s=await this.readRegister(1610641496);e=((s>>23&1)<<3)+(t>>18&7),i=s>>24&3;break}case I:{const t=await this.readRegister(1610647620);e=t>>16&15,i=t>>20&3;break}case O:{const t=await this.readRegister(1610647628),s=await this.readRegister(1610647636);e=((s>>23&1)<<3)+(t>>18&7),i=s>>24&3;break}case D:{const t=await this.readRegister(1611352140);e=15&t,i=t>>4&3;break}case C:{const t=await this.readRegister(1611335760);e=t>>18&15,i=t>>22&3;break}case z:{const t=await this.readRegister(1611352140);e=15&t,i=t>>4&3;break}case A:{const t=await this.readRegister(1611335760);e=t>>18&7,i=t>>21&3;break}case E:case $:break;case T:{const t=await this.readRegister(1343410252);e=15&t,i=(t>>23&1)<<2|t>>4&3;break}case P:{const t=await this.readRegister(544297036);e=15&t,i=t>>4&3;break}}return 100*i+e}async powerOnFlash(){if(this.chipFamily!==T)return;if(301!==this.chipRevision)return;this.logger.debug("Powering on flash for ESP32-P4 Rev 301 (ECO6)"),await this.writeRegister(1343291660,1),await a(10);const t=await this.readRegister(b);await this.writeRegister(b,t|y);const e=await this.readRegister(v);await this.writeRegister(v,128|e);const i=await this.readRegister(S);await this.writeRegister(S,3|i),await a(.05);const s=await this.readRegister(b);await this.writeRegister(b,-134217729&s);const r=await this.readRegister(v);await this.writeRegister(v,-2139095041&r);const n=await this.readRegister(v);await this.writeRegister(v,128|n);const h=await this.readRegister(v);await this.writeRegister(v,-129&h),await a(2),this.logger.debug("Flash powered on successfully")}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:si("<I",t.slice(0,4))[0],flashCryptCnt:t[4],keyPurposes:Array.from(t.slice(5,12)),chipId:t.length>=16?si("<I",t.slice(12,16))[0]:0,apiVersion:t.length>=20?si("<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 detectUsbConnectionType(){return!1}async getUsbMode(){var t,e;const i=this._parent?this._parent.chipFamily:this.chipFamily,s=this._parent?null!==(t=this._parent.chipRevision)&&void 0!==t?t:0:null!==(e=this.chipRevision)&&void 0!==e?e:0;let a=null,r=null,n=null;switch(i){case U:a=1610612736,n=3;break;case x:a=1610612736,r=4,n=3;break;case O:a=(s<101?1070461028:1070461024)+0,r=3;break;case D:case C:a=1343004672,r=3;break;case z:a=s<=200?1611440128:1343004672,r=3;break;case A:a=1611440128,r=3;break;case E:a=1610686464,r=3;break;case T:a=1343004672,r=3,n=2}if(null===a)return{mode:"uart",uartNo:0};const h=255&await this.readRegister(a);return null!==n&&h===n?(this.logger.debug(`USB mode: USB-OTG (uartNo=${h})`),{mode:"usb-otg",uartNo:h}):null!==r&&h===r?(this.logger.debug(`USB mode: USB-JTAG/Serial (uartNo=${h})`),{mode:"usb-jtag-serial",uartNo:h}):(this.logger.debug(`USB mode: UART (uartNo=${h})`),{mode:"uart",uartNo:h})}async getC5CrystalFreqRomExpect(){return(127&await this.readRegister(1611227408))>>>24}async getC5CrystalFreqDetected(){const t=1048575&await this.readRegister(1610612756),e=n*t/1e6;return e>45?48:e>33?40:26}async setBaudrate(t){const e=this._parent?this._parent.chipFamily:this.chipFamily;if(this.IS_STUB||e!==D)try{const e=ii("<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.`)}else await this.setBaudrateC5Rom(t);this._parent?await this._parent.reconfigurePort(t):await this.reconfigurePort(t),await a(V),this._parent?this._parent.currentBaudRate=t:this.currentBaudRate=t;const i=this._parent?this._parent._maxUSBSerialBaudrate:this._maxUSBSerialBaudrate;i&&t>i&&(this.logger.log(`⚠️ WARNING: Baudrate ${t} exceeds USB-Serial chip limit (${i})!`),this.logger.log("⚠️ This may cause data corruption or connection failures!")),this.logger.debug(`Changed baud rate to ${t}`)}async setBaudrateC5Rom(t){const e=await this.getC5CrystalFreqRomExpect(),i=await this.getC5CrystalFreqDetected();this.logger.log(`ROM expects crystal freq: ${e} MHz, detected ${i} MHz.`);let s=t;48===i&&40===e?s=Math.trunc(40*t/48):40===i&&48===e&&(s=Math.trunc(48*t/40)),this.logger.log(`Changing baud rate to ${s}...`);try{const t=ii("<II",s,0);await this.checkCommand(15,t)}catch(t){throw this.logger.error(`Baudrate change error: ${t}`),new Error(`Unable to change the baud rate to ${s}: No response from set baud rate command.`)}this.logger.log("Changed.")}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 s=Array.from(e);Array.prototype.push.apply(this._inputBuffer,s),this._totalBytesRead+=e.length}}catch{}finally{if(this._isReconfiguring=!1,this._reader){try{this._reader.releaseLock(),this.logger.debug("Reader released in readLoop cleanup")}catch(t){this.logger.debug(`Reader release error in readLoop: ${t}`)}this._reader=void 0}}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._suppressDisconnect||this.dispatchEvent(new Event("disconnect")),this._suppressDisconnect=!1,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 setDTRandRTS(t,e){this.state_DTR=t,this.state_RTS=e,await this.port.setSignals({dataTerminalReady:t,requestToSend:e})}async hardReset(t=!1){t?4097===this.port.getInfo().usbProductId?(await this.hardResetUSBJTAGSerial(),this.logger.log("USB-JTAG/Serial reset.")):(await this.hardResetClassic(),this.logger.log("Classic reset.")):(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],s=this._efuses[2],a=this._efuses[3];let r;if(this.chipFamily==k){if(0!=a)r=[a>>16&255,a>>8&255,255&a];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==F)t[0]=s>>8&255,t[1]=255&s,t[2]=i>>24&255,t[3]=i>>16&255,t[4]=i>>8&255,t[5]=255&i;else{if(this.chipFamily!=U&&this.chipFamily!=x&&this.chipFamily!=I&&this.chipFamily!=O&&this.chipFamily!=D&&this.chipFamily!=C&&this.chipFamily!=z&&this.chipFamily!=A&&this.chipFamily!=E&&this.chipFamily!=$&&this.chipFamily!=T&&this.chipFamily!=P)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 "+s(t,8));const e=ii("<I",t);await this.sendCommand(10,e);const[i]=await this.getResponse(10);return i}async checkCommand(t,e,i=0,a=3e3){const r=async()=>{a=Math.min(a,3e5),await this.sendCommand(t,e,i);const[r,n]=await this.getResponse(t,a);if(null===n)throw new Error("Didn't get enough status bytes");let h=n,o=0;if(this.IS_STUB||this.chipFamily==k?o=2:[F,U,x,I,O,D,C,z,A,E,$,T,P].includes(this.chipFamily)||20===t?o=4:[2,4].includes(h.length)&&(o=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 "+s(t))):new Error("Command failure error code "+s(l[1]));return[r,h]};return this._commandLock=this._commandLock.then(r,r),this._commandLock}async sendCommand(e,i,s=0){const a=t([...ii("<BBHI",0,e,i.length,s),...i]);this.debug&&this.logger.debug(`Writing ${a.length} byte${1==a.length?"":"s"}:`,a),await this.writeToStream(a)}async readPacket(t){let e=null,r=!1,n=[];for(;;){const h=Date.now();for(n=[];Date.now()-h<t;){if(this._inputBuffer.length>0){n.push(this._inputBuffer.shift());break}await a(1)}if(0==n.length){throw new W("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: "+s(t)),this.logger.debug("Remaining data in serial buffer: "+i(this._inputBuffer))),new W("Invalid head of packet ("+s(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: "+s(t)),this.logger.debug("Remaining data in serial buffer: "+i(this._inputBuffer))),new W("Invalid SLIP escape (0xdb, "+s(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)),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[a,r,,n]=si("<BBHI",i.slice(0,8));if(1!=a)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 ${s(t)}`)}throw"Response doesn't match request"}checksum(t,e=239){for(const i of t)e^=i;return e}async reconfigurePort(t){var e;try{try{await this._writeChain}catch(t){this.logger.debug(`Pending write error during reconfigure: ${t}`)}if(this._isReconfiguring=!0,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}),this._isReconfiguring=!1,await this.flushSerialBuffers(),this.readLoop()}catch(e){throw this._isReconfiguring=!1,this.logger.error(`Reconfigure port error: ${e}`),new Error(`Unable to change the baud rate to ${t}: ${e}`)}}async connectWithResetStrategies(){var t,e;const i=this.port.getInfo(),s=4097===i.usbProductId,a=12346===i.usbVendorId;this.logger.log(`Detected USB: VID=0x${(null===(t=i.usbVendorId)||void 0===t?void 0:t.toString(16))||"unknown"}, PID=0x${(null===(e=i.usbProductId)||void 0===e?void 0:e.toString(16))||"unknown"}`);const r=[];(s||a)&&r.push({name:"USB-JTAG/Serial",fn:async()=>await this.hardResetUSBJTAGSerial()}),r.push({name:"Classic",fn:async()=>await this.hardResetClassic()}),s||a||r.push({name:"USB-JTAG/Serial (fallback)",fn:async()=>await this.hardResetUSBJTAGSerial()});let n=null;for(const t of r)try{if(this.logger.log(`Trying ${t.name} reset...`),!this.connected||!this.port.writable){this.logger.log(`Port disconnected, skipping ${t.name} reset`);continue}return await t.fn(),await this.sync(),void this.logger.log(`Connected successfully with ${t.name} reset.`)}catch(e){if(n=e,this.logger.log(`${t.name} reset failed: ${e.message}`),!this.connected||!this.port.writable){this.logger.log("Port disconnected during reset attempt");break}this._inputBuffer.length=0,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 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 sync(){for(let t=0;t<5;t++){this._inputBuffer.length=0;if(await this._sync())return await a(V),!0;await a(V)}throw new Error("Couldn't sync to ESP. Try resetting.")}async _sync(){await this.sendCommand(8,B);for(let t=0;t<8;t++)try{const[,t]=await this.getResponse(8,V);if(t.length>1&&0==t[0]&&0==t[1])return!0}catch{}return!1}getFlashWriteSize(){return this.IS_STUB?16384:1024}async flashData(t,e,i=0,a=!1){if(t.byteLength>=8){const e=Array.from(new Uint8Array(t,0,4)),i=e[0],a=e[2],r=e[3];this.logger.log(`Image header, Magic=${s(i)}, FlashMode=${s(a)}, FlashSizeFreq=${s(r)}`)}const r=t.byteLength;let n,h=0,o=N;a?(n=ti(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=[],c=0,d=0,_=0;const u=Date.now(),g=this.getFlashWriteSize(),f=a?h:r;for(;f-_>0;)this.debug&&this.logger.log(`Writing at ${s(i+c*g,8)} `),f-_>=g?l=Array.from(new Uint8Array(n,_,g)):(l=Array.from(new Uint8Array(n,_,f-_)),a||(l=l.concat(new Array(g-l.length).fill(255)))),a?await this.flashDeflBlock(l,c,o):await this.flashBlock(l,c),c+=1,d+=a?Math.round(l.length*r/h):l.length,_+=g,e(Math.min(d,r),r);this.logger.log("Took "+(Date.now()-u)+"ms to write "+f+" bytes"),this.IS_STUB&&(await this.flashBegin(0,0),a?await this.flashDeflFinish():await this.flashFinish())}async flashBlock(t,e,i=3e3){await this.checkCommand(3,ii("<IIII",t.length,e,0,0).concat(t),this.checksum(t),i)}async flashDeflBlock(t,e,i=3e3){await this.checkCommand(17,ii("<IIII",t.length,e,0,0).concat(t),this.checksum(t),i)}async flashBegin(t=0,e=0,i=!1){let a;await this.flushSerialBuffers();const r=this.getFlashWriteSize();!this.IS_STUB&&[F,U,x,I,O,D,C,z,A,E,$,T,P].includes(this.chipFamily)&&await this.checkCommand(13,new Array(8).fill(0));const n=Math.floor((t+r-1)/r);a=this.chipFamily!=k||this.IS_STUB?t:this.getEraseSize(e,t);const h=this.IS_STUB?N:H(3e4,t),o=Date.now();let l=ii("<IIII",a,n,r,e);return this.chipFamily!=F&&this.chipFamily!=U&&this.chipFamily!=x&&this.chipFamily!=I&&this.chipFamily!=O&&this.chipFamily!=D&&this.chipFamily!=C&&this.chipFamily!=z&&this.chipFamily!=A&&this.chipFamily!=E&&this.chipFamily!=$&&this.chipFamily!=T&&this.chipFamily!=P||(l=l.concat(ii("<I",i?1:0))),this.logger.log("Erase size "+a+", blocks "+n+", block size "+s(r,4)+", offset "+s(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 s=this.getFlashWriteSize(),a=Math.floor((e+s-1)/s),r=Math.floor((t+s-1)/s);let n=0,h=0;this.IS_STUB?(n=t,h=H(3e4,n)):(n=r*s,h=N);const o=ii("<IIII",n,a,s,i);return await this.checkCommand(16,o,0,h),h}async flashFinish(){const t=ii("<I",1);await this.checkCommand(4,t)}async flashDeflFinish(){const t=ii("<I",1);await this.checkCommand(18,t)}getBootloaderOffset(){return j(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,s=0,a=0){let r=ii("<IIII",t,e,i,s);a>0&&(r=r.concat(ii("<IIII",j(this.getChipFamily()).uartDateReg,0,0,a))),await this.checkCommand(9,r)}async setDataLengths(t,e,i){if(-1!=t.mosiDlenOffs){const s=t.regBase+t.mosiDlenOffs,a=t.regBase+t.misoDlenOffs;e>0&&await this.writeRegister(s,e-1),i>0&&await this.writeRegister(a,i-1)}else{const s=t.regBase+t.usr1Offs,a=(0==i?0:i-1)<<8|(0==e?0:e-1)<<17;await this.writeRegister(s,a)}}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 a=j(this.getChipFamily()),r=a.regBase,n=r,h=r+a.usrOffs,o=r+a.usr2Offs,l=r+a.w0Offs,c=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,_=await this.readRegister(h),u=await this.readRegister(o);let g=1<<31;if(i>0&&(g|=268435456),d>0&&(g|=134217728),await this.setDataLengths(a,d,i),await this.writeRegister(h,g),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=si("I".repeat(Math.floor(e.length/4)),e);let a=l;this.logger.debug(`Words Length: ${i.length}`);for(const t of i)this.logger.debug(`Writing word ${s(t)} to register offset ${s(a)}`),await this.writeRegister(a,t),a+=4}await this.writeRegister(n,c),await this.waitDone(n,c);const f=await this.readRegister(l);return await this.writeRegister(h,_),await this.writeRegister(o,u),f}async detectFlashSize(){this.logger.log("Detecting Flash Size");const t=await this.flashId(),e=255&t,i=t>>16&255;this.logger.log(`FlashId: ${s(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,s=Math.floor((e+i-1)/i);let a=16-Math.floor(t/i)%16;return s<a&&(a=s),s<2*a?Math.floor((s+1)/2*i):(s-a)*i}async memBegin(t,e,i,s){return await this.checkCommand(5,ii("<IIII",t,e,i,s))}async memBlock(t,e){return await this.checkCommand(7,ii("<IIII",t.length,e,0,0).concat(t),this.checksum(t))}async memFinish(t=0){const e=this.IS_STUB?N:500,i=ii("<II",0==t?1:0,t);return await this.checkCommand(6,i,0,e)}async runStub(t=!1){this.logger.debug(`Loading stub for ${this.chipName}, revision: ${this.chipRevision}`);const e=await G(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 s=e[t],a=e[`${t}_start`],r=s.length,n=Math.floor((r+i-1)/i);await this.memBegin(r,n,i,a);for(const t of Array(n).keys()){const e=t*i;let a=e+i;a>r&&(a=r),await this.memBlock(s.slice(e,a),t)}}await this.memFinish(e.entry);const s=await this.readPacket(500),a=String.fromCharCode(...s);if("OHAI"!=a)throw new Error("Failed to start stub. Unexpected response: "+a);this.logger.log("Stub is now running...");const r=new ri(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.port.writable)throw new Error("Port became unavailable during write");this._writer||(this._writer=this.port.writable.getWriter()),await this._writer.write(new Uint8Array(t))}).catch(t=>{if(this.logger.error(`Write error: ${t}`),this._writer){try{this._writer.releaseLock()}catch(t){}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||t(void 0),this.addEventListener("disconnect",t,{once:!0}),this._reader.cancel()}),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=[];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,s=this.chipVariant,a=this.flashSize;if(await this.hardReset(!0),this._parent||(this.__inputBuffer=[],this.__totalBytesRead=0,this.readLoop()),await this.flushSerialBuffers(),await this.sync(),this.chipFamily=t,this.chipName=e,this.chipRevision=i,this.chipVariant=s,this.flashSize=a,this.logger.debug(`Reconnect complete (chip: ${this.chipName})`),!this.port.writable||!this.port.readable)throw new Error("Port not ready after reconnect");this.chipFamily===T&&301===this.chipRevision&&await this.powerOnFlash();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&&Object.assign(this,r),this.logger.debug("Reconnection successful")}catch(t){throw this._isReconfiguring=!1,t}}async drainInputBuffer(t=200){await a(t);let e=0;const i=Date.now();for(;e<112&&Date.now()-i<100;)if(this._inputBuffer.length>0){void 0!==this._inputBuffer.shift()&&e++}else await a(1);e>0&&this.logger.debug(`Drained ${e} bytes from input buffer`),this._parent||(this.__inputBuffer=[])}async flushSerialBuffers(){this._parent||(this.__inputBuffer=[]),await a(V),this._parent||(this.__inputBuffer=[]),this.logger.debug("Serial buffers flushed")}async readFlash(e,i,s){if(!this.IS_STUB)throw new Error("Reading flash is only supported in stub mode. Please run runStub() first.");await this.flushSerialBuffers(),this.logger.log(`Reading ${i} bytes from flash at address 0x${e.toString(16)}...`);let r=new Uint8Array(0),n=e,h=i;for(;h>0;){const e=Math.min(65536,h);let o=!1,l=0;const c=5;let d=!1;for(;!o&&l<=c;){let i=new Uint8Array(0);try{0===l&&this.logger.debug(`Reading chunk at 0x${n.toString(16)}, size: 0x${e.toString(16)}`);const s=ii("<IIII",n,e,4096,1024),[h]=await this.checkCommand(210,s);if(0!=h)throw new Error("Failed to read memory: "+h);for(;i.length<e;){let s;try{s=await this.readPacket(100)}catch(t){if(t instanceof W){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 a(50)}catch(t){this.logger.debug(`Abort frame error: ${t}`)}if(await this.drainInputBuffer(200),i.length>=e)break}throw t}if(s&&s.length>0){const e=new Uint8Array(s),a=new Uint8Array(i.length+e.length);a.set(i),a.set(e,i.length),i=a;const r=ii("<I",i.length),n=t(r);await this.writeToStream(n)}}const c=new Uint8Array(r.length+i.length);c.set(r),c.set(i,r.length),r=c,o=!0}catch(t){if(l++,!(t instanceof W))throw t;if(l<=c){this.logger.log(`${t.message} at 0x${n.toString(16)}. Draining buffer and retrying (attempt ${l}/${c})...`);try{await this.drainInputBuffer(200),await this.flushSerialBuffers(),await a(V)}catch(t){this.logger.debug(`Buffer drain error: ${t}`)}}else{if(d)throw new Error(`Failed to read chunk at 0x${n.toString(16)} after ${c} retries and deep recovery attempt`);d=!0,this.logger.log(`All retries exhausted at 0x${n.toString(16)}. Attempting deep recovery (reconnect + reload stub)...`);try{await this.reconnect(),this.logger.log("Deep recovery successful. Resuming read from current position..."),l=0;continue}catch(t){throw new Error(`Failed to read chunk at 0x${n.toString(16)} after ${c} retries and deep recovery failed: ${t}`)}}}}s&&s(new Uint8Array(e),r.length,i),n+=e,h-=e,this.logger.debug(`Total progress: 0x${r.length.toString(16)} from 0x${i.toString(16)} bytes`)}return this.logger.debug(`Successfully read ${r.length} bytes from flash`),r}}class ri extends ai{constructor(){super(...arguments),this.IS_STUB=!0}async memBegin(t,e,i,a){const r=await G(this.chipFamily,this.chipRevision);if(null===r)return[0,[]];const n=a,h=a+t;this.logger.debug(`Load range: ${s(n,8)}-${s(h,8)}`),this.logger.debug(`Stub data: ${s(r.data_start,8)}, len: ${r.data.length}, text: ${s(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 "+s(t,8)+"-"+s(e,8)+". Can't load binary at overlapping address range "+s(n,8)+"-"+s(h,8)+". Try changing the binary loading address.");return[0,[]]}async eraseFlash(){await this.checkCommand(208,[],0,Z)}}const ni=async t=>{const e=await navigator.serial.requestPort();return await e.open({baudRate:n}),t.log("Connected successfully."),new ai(e,t)};export{F as CHIP_FAMILY_ESP32,I as CHIP_FAMILY_ESP32C2,O as CHIP_FAMILY_ESP32C3,D as CHIP_FAMILY_ESP32C5,C as CHIP_FAMILY_ESP32C6,z as CHIP_FAMILY_ESP32C61,A as CHIP_FAMILY_ESP32H2,$ as CHIP_FAMILY_ESP32H21,E as CHIP_FAMILY_ESP32H4,T as CHIP_FAMILY_ESP32P4,U as CHIP_FAMILY_ESP32S2,x as CHIP_FAMILY_ESP32S3,P as CHIP_FAMILY_ESP32S31,k as CHIP_FAMILY_ESP8266,ai as ESPLoader,ni as connect};
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 s=t.charCodeAt(i);s<=255&&e.push(s)}return e},i=t=>"["+t.map(t=>s(t)).join(", ")+"]",s=(t,e=2)=>{const i=t.toString(16).toUpperCase();return i.startsWith("-")?"-0x"+i.substring(1).padStart(e,"0"):"0x"+i.padStart(e,"0")};const a=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=1073061888,o=1061265408,l=1610641408,c=1610647552,d=1610647552,_=1611352064,u=1611335680,g=1611352064,f=1611335680,p=1343410176,w=1343312316,m=1<<27,b=1343312312,y=1343312892,v=544296960,R=e(" UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU"),S=33382,B=50,k=12882,F=12883,x=12994,I=12995,O=12997,D=12998,U=207969,z=12914,C=12916,A=12917,E=12928,T=12849,$={5:{name:"ESP32-C3",family:I},9:{name:"ESP32-S3",family:F},12:{name:"ESP32-C2",family:x},13:{name:"ESP32-C6",family:D},16:{name:"ESP32-H2",family:z},18:{name:"ESP32-P4",family:E},20:{name:"ESP32-C61",family:U},23:{name:"ESP32-C5",family:O},25:{name:"ESP32-H21",family:A},28:{name:"ESP32-H4",family:C},32:{name:"ESP32-S31",family:T}},P={4293968129:{name:"ESP8266",family:S},15736195:{name:"ESP32",family:B},1990:{name:"ESP32-S2",family:k}},M=3e3,L=15e4,N=100,Z=(t,e)=>{const i=Math.floor(t*(e/486));return i<M?M:i},V=t=>{switch(t){case B:return{regBase:1072963584,baseFuse:h,macFuse:1073061888,usrOffs:28,usr1Offs:32,usr2Offs:36,mosiDlenOffs:40,misoDlenOffs:44,w0Offs:128,uartDateReg:1610612856,flashOffs:4096};case k:return{regBase:1061167104,baseFuse:o,macFuse:1061265476,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612856,flashOffs:4096};case F:return{regBase:1610620928,usrOffs:24,baseFuse:l,macFuse:1610641476,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612864,flashOffs:0};case S:return{regBase:1610613248,usrOffs:28,baseFuse:1072693328,macFuse:1072693328,usr1Offs:32,usr2Offs:36,mosiDlenOffs:-1,misoDlenOffs:-1,w0Offs:64,uartDateReg:1610612856,flashOffs:0};case x:return{regBase:1610620928,baseFuse:c,macFuse:1610647616,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case I:return{regBase:1610620928,baseFuse:d,macFuse:1610647620,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case O:return{regBase:1610625024,baseFuse:_,macFuse:1611352132,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:8192};case D:return{regBase:1610625024,baseFuse:u,macFuse:1611335748,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case U:return{regBase:1610625024,baseFuse:g,macFuse:1611352132,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case z:return{regBase:1610625024,baseFuse:f,macFuse:1611335748,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case C:return{regBase:1611239424,baseFuse:1611339776,macFuse:1611339844,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610686588,flashOffs:8192};case A:return{regBase:1610625024,baseFuse:1611350016,macFuse:1611350084,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case E:return{regBase:1342754816,baseFuse:p,macFuse:1343410244,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1343004812,flashOffs:8192};case T:return{regBase:542113792,baseFuse:v,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 H extends Error{constructor(t){super(t),this.name="SlipReadError"}}const j=async(t,i)=>{let s;return t==C||t==A||t==T?null:(t==B?s=await import("./esp32-BRKoi17y.js"):t==k?s=await import("./esp32s2-iX3WoDbg.js"):t==F?s=await import("./esp32s3-DGwDVIgz.js"):t==S?s=await import("./esp8266-CUwxJpGa.js"):t==x?s=await import("./esp32c2-Btgr_lwh.js"):t==I?s=await import("./esp32c3-CHKfoI8W.js"):t==O?s=await import("./esp32c5-BDW4KtLo.js"):t==D?s=await import("./esp32c6-il8tTxAG.js"):t==U?s=await import("./esp32c61-thKzxBGf.js"):t==z?s=await import("./esp32h2-CxoUHv_P.js"):t==E&&(s=null!=i&&i>=300?await import("./esp32p4r3-CqI71ojR.js"):await import("./esp32p4-D3jLP-jY.js")),{...s,text:e(atob(s.text)),data:e(atob(s.data))})};function W(t){let e=t.length;for(;--e>=0;)t[e]=0}const G=256,q=286,K=30,J=15,Y=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]),X=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]),Q=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),tt=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),et=new Array(576);W(et);const it=new Array(60);W(it);const st=new Array(512);W(st);const at=new Array(256);W(at);const rt=new Array(29);W(rt);const nt=new Array(K);function ht(t,e,i,s,a){this.static_tree=t,this.extra_bits=e,this.extra_base=i,this.elems=s,this.max_length=a,this.has_stree=t&&t.length}let ot,lt,ct;function dt(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}W(nt);const _t=t=>t<256?st[t]:st[256+(t>>>7)],ut=(t,e)=>{t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255},gt=(t,e,i)=>{t.bi_valid>16-i?(t.bi_buf|=e<<t.bi_valid&65535,ut(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)},ft=(t,e,i)=>{gt(t,i[2*e],i[2*e+1])},pt=(t,e)=>{let i=0;do{i|=1&t,t>>>=1,i<<=1}while(--e>0);return i>>>1},wt=(t,e,i)=>{const s=new Array(16);let a,r,n=0;for(a=1;a<=J;a++)n=n+i[a-1]<<1,s[a]=n;for(r=0;r<=e;r++){let e=t[2*r+1];0!==e&&(t[2*r]=pt(s[e]++,e))}},mt=t=>{let e;for(e=0;e<q;e++)t.dyn_ltree[2*e]=0;for(e=0;e<K;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},bt=t=>{t.bi_valid>8?ut(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0},yt=(t,e,i,s)=>{const a=2*e,r=2*i;return t[a]<t[r]||t[a]===t[r]&&s[e]<=s[i]},vt=(t,e,i)=>{const s=t.heap[i];let a=i<<1;for(;a<=t.heap_len&&(a<t.heap_len&&yt(e,t.heap[a+1],t.heap[a],t.depth)&&a++,!yt(e,s,t.heap[a],t.depth));)t.heap[i]=t.heap[a],i=a,a<<=1;t.heap[i]=s},Rt=(t,e,i)=>{let s,a,r,n,h=0;if(0!==t.sym_next)do{s=255&t.pending_buf[t.sym_buf+h++],s+=(255&t.pending_buf[t.sym_buf+h++])<<8,a=t.pending_buf[t.sym_buf+h++],0===s?ft(t,a,e):(r=at[a],ft(t,r+G+1,e),n=Y[r],0!==n&&(a-=rt[r],gt(t,a,n)),s--,r=_t(s),ft(t,r,i),n=X[r],0!==n&&(s-=nt[r],gt(t,s,n)))}while(h<t.sym_next);ft(t,256,e)},St=(t,e)=>{const i=e.dyn_tree,s=e.stat_desc.static_tree,a=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--,a&&(t.static_len-=s[2*o+1]);for(e.max_code=l,n=t.heap_len>>1;n>=1;n--)vt(t,i,n);o=r;do{n=t.heap[1],t.heap[1]=t.heap[t.heap_len--],vt(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++,vt(t,i,1)}while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],((t,e)=>{const i=e.dyn_tree,s=e.max_code,a=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,c,d,_,u,g,f=0;for(_=0;_<=J;_++)t.bl_count[_]=0;for(i[2*t.heap[t.heap_max]+1]=0,l=t.heap_max+1;l<573;l++)c=t.heap[l],_=i[2*i[2*c+1]+1]+1,_>o&&(_=o,f++),i[2*c+1]=_,c>s||(t.bl_count[_]++,u=0,c>=h&&(u=n[c-h]),g=i[2*c],t.opt_len+=g*(_+u),r&&(t.static_len+=g*(a[2*c+1]+u)));if(0!==f){do{for(_=o-1;0===t.bl_count[_];)_--;t.bl_count[_]--,t.bl_count[_+1]+=2,t.bl_count[o]--,f-=2}while(f>0);for(_=o;0!==_;_--)for(c=t.bl_count[_];0!==c;)d=t.heap[--l],d>s||(i[2*d+1]!==_&&(t.opt_len+=(_-i[2*d+1])*i[2*d],i[2*d+1]=_),c--)}})(t,e),wt(i,l,t.bl_count)},Bt=(t,e,i)=>{let s,a,r=-1,n=e[1],h=0,o=7,l=4;for(0===n&&(o=138,l=3),e[2*(i+1)+1]=65535,s=0;s<=i;s++)a=n,n=e[2*(s+1)+1],++h<o&&a===n||(h<l?t.bl_tree[2*a]+=h:0!==a?(a!==r&&t.bl_tree[2*a]++,t.bl_tree[32]++):h<=10?t.bl_tree[34]++:t.bl_tree[36]++,h=0,r=a,0===n?(o=138,l=3):a===n?(o=6,l=3):(o=7,l=4))},kt=(t,e,i)=>{let s,a,r=-1,n=e[1],h=0,o=7,l=4;for(0===n&&(o=138,l=3),s=0;s<=i;s++)if(a=n,n=e[2*(s+1)+1],!(++h<o&&a===n)){if(h<l)do{ft(t,a,t.bl_tree)}while(0!==--h);else 0!==a?(a!==r&&(ft(t,a,t.bl_tree),h--),ft(t,16,t.bl_tree),gt(t,h-3,2)):h<=10?(ft(t,17,t.bl_tree),gt(t,h-3,3)):(ft(t,18,t.bl_tree),gt(t,h-11,7));h=0,r=a,0===n?(o=138,l=3):a===n?(o=6,l=3):(o=7,l=4)}};let Ft=!1;const xt=(t,e,i,s)=>{gt(t,0+(s?1:0),3),bt(t),ut(t,i),ut(t,~i),i&&t.pending_buf.set(t.window.subarray(e,e+i),t.pending),t.pending+=i};var It=(t,e,i,s)=>{let a,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<G;e++)if(0!==t.dyn_ltree[2*e])return 1;return 0})(t)),St(t,t.l_desc),St(t,t.d_desc),n=(t=>{let e;for(Bt(t,t.dyn_ltree,t.l_desc.max_code),Bt(t,t.dyn_dtree,t.d_desc.max_code),St(t,t.bl_desc),e=18;e>=3&&0===t.bl_tree[2*tt[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e})(t),a=t.opt_len+3+7>>>3,r=t.static_len+3+7>>>3,r<=a&&(a=r)):a=r=i+5,i+4<=a&&-1!==e?xt(t,e,i,s):4===t.strategy||r===a?(gt(t,2+(s?1:0),3),Rt(t,et,it)):(gt(t,4+(s?1:0),3),((t,e,i,s)=>{let a;for(gt(t,e-257,5),gt(t,i-1,5),gt(t,s-4,4),a=0;a<s;a++)gt(t,t.bl_tree[2*tt[a]+1],3);kt(t,t.dyn_ltree,e-1),kt(t,t.dyn_dtree,i-1)})(t,t.l_desc.max_code+1,t.d_desc.max_code+1,n+1),Rt(t,t.dyn_ltree,t.dyn_dtree)),mt(t),s&&bt(t)},Ot={_tr_init:t=>{Ft||((()=>{let t,e,i,s,a;const r=new Array(16);for(i=0,s=0;s<28;s++)for(rt[s]=i,t=0;t<1<<Y[s];t++)at[i++]=s;for(at[i-1]=s,a=0,s=0;s<16;s++)for(nt[s]=a,t=0;t<1<<X[s];t++)st[a++]=s;for(a>>=7;s<K;s++)for(nt[s]=a<<7,t=0;t<1<<X[s]-7;t++)st[256+a++]=s;for(e=0;e<=J;e++)r[e]=0;for(t=0;t<=143;)et[2*t+1]=8,t++,r[8]++;for(;t<=255;)et[2*t+1]=9,t++,r[9]++;for(;t<=279;)et[2*t+1]=7,t++,r[7]++;for(;t<=287;)et[2*t+1]=8,t++,r[8]++;for(wt(et,287,r),t=0;t<K;t++)it[2*t+1]=5,it[2*t]=pt(t,5);ot=new ht(et,Y,257,q,J),lt=new ht(it,X,0,K,J),ct=new ht(new Array(0),Q,0,19,7)})(),Ft=!0),t.l_desc=new dt(t.dyn_ltree,ot),t.d_desc=new dt(t.dyn_dtree,lt),t.bl_desc=new dt(t.bl_tree,ct),t.bi_buf=0,t.bi_valid=0,mt(t)},_tr_stored_block:xt,_tr_flush_block:It,_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*(at[i]+G+1)]++,t.dyn_dtree[2*_t(e)]++),t.sym_next===t.sym_end),_tr_align:t=>{gt(t,2,3),ft(t,256,et),(t=>{16===t.bi_valid?(ut(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 Dt=(t,e,i,s)=>{let a=65535&t,r=t>>>16&65535,n=0;for(;0!==i;){n=i>2e3?2e3:i,i-=n;do{a=a+e[s++]|0,r=r+a|0}while(--n);a%=65521,r%=65521}return a|r<<16};const Ut=new Uint32Array((()=>{let t,e=[];for(var i=0;i<256;i++){t=i;for(var s=0;s<8;s++)t=1&t?3988292384^t>>>1:t>>>1;e[i]=t}return e})());var zt=(t,e,i,s)=>{const a=Ut,r=s+i;t^=-1;for(let i=s;i<r;i++)t=t>>>8^a[255&(t^e[i])];return-1^t},Ct={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"},At={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:Et,_tr_stored_block:Tt,_tr_flush_block:$t,_tr_tally:Pt,_tr_align:Mt}=Ot,{Z_NO_FLUSH:Lt,Z_PARTIAL_FLUSH:Nt,Z_FULL_FLUSH:Zt,Z_FINISH:Vt,Z_BLOCK:Ht,Z_OK:jt,Z_STREAM_END:Wt,Z_STREAM_ERROR:Gt,Z_DATA_ERROR:qt,Z_BUF_ERROR:Kt,Z_DEFAULT_COMPRESSION:Jt,Z_FILTERED:Yt,Z_HUFFMAN_ONLY:Xt,Z_RLE:Qt,Z_FIXED:te,Z_DEFAULT_STRATEGY:ee,Z_UNKNOWN:ie,Z_DEFLATED:se}=At,ae=258,re=262,ne=42,he=113,oe=666,le=(t,e)=>(t.msg=Ct[e],e),ce=t=>2*t-(t>4?9:0),de=t=>{let e=t.length;for(;--e>=0;)t[e]=0},_e=t=>{let e,i,s,a=t.w_size;e=t.hash_size,s=e;do{i=t.head[--s],t.head[s]=i>=a?i-a:0}while(--e);e=a,s=e;do{i=t.prev[--s],t.prev[s]=i>=a?i-a:0}while(--e)};let ue=(t,e,i)=>(e<<t.hash_shift^i)&t.hash_mask;const ge=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))},fe=(t,e)=>{$t(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,ge(t.strm)},pe=(t,e)=>{t.pending_buf[t.pending++]=e},we=(t,e)=>{t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e},me=(t,e,i,s)=>{let a=t.avail_in;return a>s&&(a=s),0===a?0:(t.avail_in-=a,e.set(t.input.subarray(t.next_in,t.next_in+a),i),1===t.state.wrap?t.adler=Dt(t.adler,e,a,i):2===t.state.wrap&&(t.adler=zt(t.adler,e,a,i)),t.next_in+=a,t.total_in+=a,a)},be=(t,e)=>{let i,s,a=t.max_chain_length,r=t.strstart,n=t.prev_length,h=t.nice_match;const o=t.strstart>t.w_size-re?t.strstart-(t.w_size-re):0,l=t.window,c=t.w_mask,d=t.prev,_=t.strstart+ae;let u=l[r+n-1],g=l[r+n];t.prev_length>=t.good_match&&(a>>=2),h>t.lookahead&&(h=t.lookahead);do{if(i=e,l[i+n]===g&&l[i+n-1]===u&&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<_);if(s=ae-(_-r),r=_-ae,s>n){if(t.match_start=e,n=s,s>=h)break;u=l[r+n-1],g=l[r+n]}}}while((e=d[e&c])>o&&0!==--a);return n<=t.lookahead?n:t.lookahead},ye=t=>{const e=t.w_size;let i,s,a;do{if(s=t.window_size-t.lookahead-t.strstart,t.strstart>=e+(e-re)&&(t.window.set(t.window.subarray(e,e+e-s),0),t.match_start-=e,t.strstart-=e,t.block_start-=e,t.insert>t.strstart&&(t.insert=t.strstart),_e(t),s+=e),0===t.strm.avail_in)break;if(i=me(t.strm,t.window,t.strstart+t.lookahead,s),t.lookahead+=i,t.lookahead+t.insert>=3)for(a=t.strstart-t.insert,t.ins_h=t.window[a],t.ins_h=ue(t,t.ins_h,t.window[a+1]);t.insert&&(t.ins_h=ue(t,t.ins_h,t.window[a+3-1]),t.prev[a&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=a,a++,t.insert--,!(t.lookahead+t.insert<3)););}while(t.lookahead<re&&0!==t.strm.avail_in)},ve=(t,e)=>{let i,s,a,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,a=t.bi_valid+42>>3,t.strm.avail_out<a)break;if(a=t.strm.avail_out-a,s=t.strstart-t.block_start,i>s+t.strm.avail_in&&(i=s+t.strm.avail_in),i>a&&(i=a),i<r&&(0===i&&e!==Vt||e===Lt||i!==s+t.strm.avail_in))break;n=e===Vt&&i===s+t.strm.avail_in?1:0,Tt(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,ge(t.strm),s&&(s>i&&(s=i),t.strm.output.set(t.window.subarray(t.block_start,t.block_start+s),t.strm.next_out),t.strm.next_out+=s,t.strm.avail_out-=s,t.strm.total_out+=s,t.block_start+=s,i-=s),i&&(me(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!==Lt&&e!==Vt&&0===t.strm.avail_in&&t.strstart===t.block_start?2:(a=t.window_size-t.strstart,t.strm.avail_in>a&&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++,a+=t.w_size,t.insert>t.strstart&&(t.insert=t.strstart)),a>t.strm.avail_in&&(a=t.strm.avail_in),a&&(me(t.strm,t.window,t.strstart,a),t.strstart+=a,t.insert+=a>t.w_size-t.insert?t.w_size-t.insert:a),t.high_water<t.strstart&&(t.high_water=t.strstart),a=t.bi_valid+42>>3,a=t.pending_buf_size-a>65535?65535:t.pending_buf_size-a,r=a>t.w_size?t.w_size:a,s=t.strstart-t.block_start,(s>=r||(s||e===Vt)&&e!==Lt&&0===t.strm.avail_in&&s<=a)&&(i=s>a?a:s,n=e===Vt&&0===t.strm.avail_in&&i===s?1:0,Tt(t,t.block_start,i,n),t.block_start+=i,ge(t.strm)),n?3:1)},Re=(t,e)=>{let i,s;for(;;){if(t.lookahead<re){if(ye(t),t.lookahead<re&&e===Lt)return 1;if(0===t.lookahead)break}if(i=0,t.lookahead>=3&&(t.ins_h=ue(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-re&&(t.match_length=be(t,i)),t.match_length>=3)if(s=Pt(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=ue(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=ue(t,t.ins_h,t.window[t.strstart+1]);else s=Pt(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(s&&(fe(t,!1),0===t.strm.avail_out))return 1}return t.insert=t.strstart<2?t.strstart:2,e===Vt?(fe(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(fe(t,!1),0===t.strm.avail_out)?1:2},Se=(t,e)=>{let i,s,a;for(;;){if(t.lookahead<re){if(ye(t),t.lookahead<re&&e===Lt)return 1;if(0===t.lookahead)break}if(i=0,t.lookahead>=3&&(t.ins_h=ue(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-re&&(t.match_length=be(t,i),t.match_length<=5&&(t.strategy===Yt||3===t.match_length&&t.strstart-t.match_start>4096)&&(t.match_length=2)),t.prev_length>=3&&t.match_length<=t.prev_length){a=t.strstart+t.lookahead-3,s=Pt(t,t.strstart-1-t.prev_match,t.prev_length-3),t.lookahead-=t.prev_length-1,t.prev_length-=2;do{++t.strstart<=a&&(t.ins_h=ue(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++,s&&(fe(t,!1),0===t.strm.avail_out))return 1}else if(t.match_available){if(s=Pt(t,0,t.window[t.strstart-1]),s&&fe(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&&(s=Pt(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<2?t.strstart:2,e===Vt?(fe(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(fe(t,!1),0===t.strm.avail_out)?1:2};function Be(t,e,i,s,a){this.good_length=t,this.max_lazy=e,this.nice_length=i,this.max_chain=s,this.func=a}const ke=[new Be(0,0,0,0,ve),new Be(4,4,8,4,Re),new Be(4,5,16,8,Re),new Be(4,6,32,32,Re),new Be(4,4,16,16,Se),new Be(8,16,32,32,Se),new Be(8,16,128,128,Se),new Be(8,32,128,256,Se),new Be(32,128,258,1024,Se),new Be(32,258,258,4096,Se)];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=se,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),de(this.dyn_ltree),de(this.dyn_dtree),de(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),de(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),de(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 xe=t=>{if(!t)return 1;const e=t.state;return!e||e.strm!==t||e.status!==ne&&57!==e.status&&69!==e.status&&73!==e.status&&91!==e.status&&103!==e.status&&e.status!==he&&e.status!==oe?1:0},Ie=t=>{if(xe(t))return le(t,Gt);t.total_in=t.total_out=0,t.data_type=ie;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?ne:he,t.adler=2===e.wrap?0:1,e.last_flush=-2,Et(e),jt},Oe=t=>{const e=Ie(t);var i;return e===jt&&((i=t.state).window_size=2*i.w_size,de(i.head),i.max_lazy_match=ke[i.level].max_lazy,i.good_match=ke[i.level].good_length,i.nice_match=ke[i.level].nice_length,i.max_chain_length=ke[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},De=(t,e,i,s,a,r)=>{if(!t)return Gt;let n=1;if(e===Jt&&(e=6),s<0?(n=0,s=-s):s>15&&(n=2,s-=16),a<1||a>9||i!==se||s<8||s>15||e<0||e>9||r<0||r>te||8===s&&1!==n)return le(t,Gt);8===s&&(s=9);const h=new Fe;return t.state=h,h.strm=t,h.status=ne,h.wrap=n,h.gzhead=null,h.w_bits=s,h.w_size=1<<h.w_bits,h.w_mask=h.w_size-1,h.hash_bits=a+7,h.hash_size=1<<h.hash_bits,h.hash_mask=h.hash_size-1,h.hash_shift=~~((h.hash_bits+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<<a+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,Oe(t)};var Ue={deflateInit:(t,e)=>De(t,e,se,15,8,ee),deflateInit2:De,deflateReset:Oe,deflateResetKeep:Ie,deflateSetHeader:(t,e)=>xe(t)||2!==t.state.wrap?Gt:(t.state.gzhead=e,jt),deflate:(t,e)=>{if(xe(t)||e>Ht||e<0)return t?le(t,Gt):Gt;const i=t.state;if(!t.output||0!==t.avail_in&&!t.input||i.status===oe&&e!==Vt)return le(t,0===t.avail_out?Kt:Gt);const s=i.last_flush;if(i.last_flush=e,0!==i.pending){if(ge(t),0===t.avail_out)return i.last_flush=-1,jt}else if(0===t.avail_in&&ce(e)<=ce(s)&&e!==Vt)return le(t,Kt);if(i.status===oe&&0!==t.avail_in)return le(t,Kt);if(i.status===ne&&0===i.wrap&&(i.status=he),i.status===ne){let e=se+(i.w_bits-8<<4)<<8,s=-1;if(s=i.strategy>=Xt||i.level<2?0:i.level<6?1:6===i.level?2:3,e|=s<<6,0!==i.strstart&&(e|=32),e+=31-e%31,we(i,e),0!==i.strstart&&(we(i,t.adler>>>16),we(i,65535&t.adler)),t.adler=1,i.status=he,ge(t),0!==i.pending)return i.last_flush=-1,jt}if(57===i.status)if(t.adler=0,pe(i,31),pe(i,139),pe(i,8),i.gzhead)pe(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)),pe(i,255&i.gzhead.time),pe(i,i.gzhead.time>>8&255),pe(i,i.gzhead.time>>16&255),pe(i,i.gzhead.time>>24&255),pe(i,9===i.level?2:i.strategy>=Xt||i.level<2?4:0),pe(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(pe(i,255&i.gzhead.extra.length),pe(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(t.adler=zt(t.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=69;else if(pe(i,0),pe(i,0),pe(i,0),pe(i,0),pe(i,0),pe(i,9===i.level?2:i.strategy>=Xt||i.level<2?4:0),pe(i,3),i.status=he,ge(t),0!==i.pending)return i.last_flush=-1,jt;if(69===i.status){if(i.gzhead.extra){let e=i.pending,s=(65535&i.gzhead.extra.length)-i.gzindex;for(;i.pending+s>i.pending_buf_size;){let a=i.pending_buf_size-i.pending;if(i.pending_buf.set(i.gzhead.extra.subarray(i.gzindex,i.gzindex+a),i.pending),i.pending=i.pending_buf_size,i.gzhead.hcrc&&i.pending>e&&(t.adler=zt(t.adler,i.pending_buf,i.pending-e,e)),i.gzindex+=a,ge(t),0!==i.pending)return i.last_flush=-1,jt;e=0,s-=a}let a=new Uint8Array(i.gzhead.extra);i.pending_buf.set(a.subarray(i.gzindex,i.gzindex+s),i.pending),i.pending+=s,i.gzhead.hcrc&&i.pending>e&&(t.adler=zt(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,s=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>s&&(t.adler=zt(t.adler,i.pending_buf,i.pending-s,s)),ge(t),0!==i.pending)return i.last_flush=-1,jt;s=0}e=i.gzindex<i.gzhead.name.length?255&i.gzhead.name.charCodeAt(i.gzindex++):0,pe(i,e)}while(0!==e);i.gzhead.hcrc&&i.pending>s&&(t.adler=zt(t.adler,i.pending_buf,i.pending-s,s)),i.gzindex=0}i.status=91}if(91===i.status){if(i.gzhead.comment){let e,s=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>s&&(t.adler=zt(t.adler,i.pending_buf,i.pending-s,s)),ge(t),0!==i.pending)return i.last_flush=-1,jt;s=0}e=i.gzindex<i.gzhead.comment.length?255&i.gzhead.comment.charCodeAt(i.gzindex++):0,pe(i,e)}while(0!==e);i.gzhead.hcrc&&i.pending>s&&(t.adler=zt(t.adler,i.pending_buf,i.pending-s,s))}i.status=103}if(103===i.status){if(i.gzhead.hcrc){if(i.pending+2>i.pending_buf_size&&(ge(t),0!==i.pending))return i.last_flush=-1,jt;pe(i,255&t.adler),pe(i,t.adler>>8&255),t.adler=0}if(i.status=he,ge(t),0!==i.pending)return i.last_flush=-1,jt}if(0!==t.avail_in||0!==i.lookahead||e!==Lt&&i.status!==oe){let s=0===i.level?ve(i,e):i.strategy===Xt?((t,e)=>{let i;for(;;){if(0===t.lookahead&&(ye(t),0===t.lookahead)){if(e===Lt)return 1;break}if(t.match_length=0,i=Pt(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,i&&(fe(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===Vt?(fe(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(fe(t,!1),0===t.strm.avail_out)?1:2})(i,e):i.strategy===Qt?((t,e)=>{let i,s,a,r;const n=t.window;for(;;){if(t.lookahead<=ae){if(ye(t),t.lookahead<=ae&&e===Lt)return 1;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=3&&t.strstart>0&&(a=t.strstart-1,s=n[a],s===n[++a]&&s===n[++a]&&s===n[++a])){r=t.strstart+ae;do{}while(s===n[++a]&&s===n[++a]&&s===n[++a]&&s===n[++a]&&s===n[++a]&&s===n[++a]&&s===n[++a]&&s===n[++a]&&a<r);t.match_length=ae-(r-a),t.match_length>t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=3?(i=Pt(t,1,t.match_length-3),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(i=Pt(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),i&&(fe(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===Vt?(fe(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(fe(t,!1),0===t.strm.avail_out)?1:2})(i,e):ke[i.level].func(i,e);if(3!==s&&4!==s||(i.status=oe),1===s||3===s)return 0===t.avail_out&&(i.last_flush=-1),jt;if(2===s&&(e===Nt?Mt(i):e!==Ht&&(Tt(i,0,0,!1),e===Zt&&(de(i.head),0===i.lookahead&&(i.strstart=0,i.block_start=0,i.insert=0))),ge(t),0===t.avail_out))return i.last_flush=-1,jt}return e!==Vt?jt:i.wrap<=0?Wt:(2===i.wrap?(pe(i,255&t.adler),pe(i,t.adler>>8&255),pe(i,t.adler>>16&255),pe(i,t.adler>>24&255),pe(i,255&t.total_in),pe(i,t.total_in>>8&255),pe(i,t.total_in>>16&255),pe(i,t.total_in>>24&255)):(we(i,t.adler>>>16),we(i,65535&t.adler)),ge(t),i.wrap>0&&(i.wrap=-i.wrap),0!==i.pending?jt:Wt)},deflateEnd:t=>{if(xe(t))return Gt;const e=t.state.status;return t.state=null,e===he?le(t,qt):jt},deflateSetDictionary:(t,e)=>{let i=e.length;if(xe(t))return Gt;const s=t.state,a=s.wrap;if(2===a||1===a&&s.status!==ne||s.lookahead)return Gt;if(1===a&&(t.adler=Dt(t.adler,e,i,0)),s.wrap=0,i>=s.w_size){0===a&&(de(s.head),s.strstart=0,s.block_start=0,s.insert=0);let t=new Uint8Array(s.w_size);t.set(e.subarray(i-s.w_size,i),0),e=t,i=s.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,ye(s);s.lookahead>=3;){let t=s.strstart,e=s.lookahead-2;do{s.ins_h=ue(s,s.ins_h,s.window[t+3-1]),s.prev[t&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=t,t++}while(--e);s.strstart=t,s.lookahead=2,ye(s)}return s.strstart+=s.lookahead,s.block_start=s.strstart,s.insert=s.lookahead,s.lookahead=0,s.match_length=s.prev_length=2,s.match_available=0,t.next_in=n,t.input=h,t.avail_in=r,s.wrap=a,jt},deflateInfo:"pako deflate (from Nodeca project)"};const ze=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var Ce=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)ze(i,e)&&(t[e]=i[e])}}return t},Ae=t=>{let e=0;for(let i=0,s=t.length;i<s;i++)e+=t[i].length;const i=new Uint8Array(e);for(let e=0,s=0,a=t.length;e<a;e++){let a=t[e];i.set(a,s),s+=a.length}return i};let Ee=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(t){Ee=!1}const Te=new Uint8Array(256);for(let t=0;t<256;t++)Te[t]=t>=252?6:t>=248?5:t>=240?4:t>=224?3:t>=192?2:1;Te[254]=Te[254]=1;var $e=t=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(t);let e,i,s,a,r,n=t.length,h=0;for(a=0;a<n;a++)i=t.charCodeAt(a),55296==(64512&i)&&a+1<n&&(s=t.charCodeAt(a+1),56320==(64512&s)&&(i=65536+(i-55296<<10)+(s-56320),a++)),h+=i<128?1:i<2048?2:i<65536?3:4;for(e=new Uint8Array(h),r=0,a=0;r<h;a++)i=t.charCodeAt(a),55296==(64512&i)&&a+1<n&&(s=t.charCodeAt(a+1),56320==(64512&s)&&(i=65536+(i-55296<<10)+(s-56320),a++)),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 Pe=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 Me=Object.prototype.toString,{Z_NO_FLUSH:Le,Z_SYNC_FLUSH:Ne,Z_FULL_FLUSH:Ze,Z_FINISH:Ve,Z_OK:He,Z_STREAM_END:je,Z_DEFAULT_COMPRESSION:We,Z_DEFAULT_STRATEGY:Ge,Z_DEFLATED:qe}=At;function Ke(t){this.options=Ce({level:We,method:qe,chunkSize:16384,windowBits:15,memLevel:8,strategy:Ge},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 Pe,this.strm.avail_out=0;let i=Ue.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(i!==He)throw new Error(Ct[i]);if(e.header&&Ue.deflateSetHeader(this.strm,e.header),e.dictionary){let t;if(t="string"==typeof e.dictionary?$e(e.dictionary):"[object ArrayBuffer]"===Me.call(e.dictionary)?new Uint8Array(e.dictionary):e.dictionary,i=Ue.deflateSetDictionary(this.strm,t),i!==He)throw new Error(Ct[i]);this._dict_set=!0}}Ke.prototype.push=function(t,e){const i=this.strm,s=this.options.chunkSize;let a,r;if(this.ended)return!1;for(r=e===~~e?e:!0===e?Ve:Le,"string"==typeof t?i.input=$e(t):"[object ArrayBuffer]"===Me.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(s),i.next_out=0,i.avail_out=s),(r===Ne||r===Ze)&&i.avail_out<=6)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else{if(a=Ue.deflate(i,r),a===je)return i.next_out>0&&this.onData(i.output.subarray(0,i.next_out)),a=Ue.deflateEnd(this.strm),this.onEnd(a),this.ended=!0,a===He;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},Ke.prototype.onData=function(t){this.chunks.push(t)},Ke.prototype.onEnd=function(t){t===He&&(this.result=Ae(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};var Je={deflate:function(t,e){const i=new Ke(e);if(i.push(t,!0),i.err)throw i.msg||Ct[i.err];return i.result}};const{deflate:Ye}=Je;var Xe=Ye;const Qe={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}},ti=(t,...e)=>{let i=0;if(t.replace(/[<>]/,"").length!=e.length)throw"Pack format to Argument count mismatch";const s=[];let a=!0;for(let s=0;s<t.length;s++)"<"==t[s]?a=!0:">"==t[s]?a=!1:(r(t[s],e[i]),i++);function r(t,e){if(!(t in Qe))throw"Unhandled character '"+t+"' in pack format";const i=Qe[t].bytes,r=new DataView(new ArrayBuffer(i));Qe[t].p.bind(r)(0,e,a);for(let t=0;t<i;t++)s.push(r.getUint8(t))}return s},ei=(t,e)=>{let i=0;const s=[];let a=!0;for(const e of t)"<"==e?a=!0:">"==e?a=!1:r(e);function r(t){if(!(t in Qe))throw"Unhandled character '"+t+"' in unpack format";const r=Qe[t].bytes,n=new DataView(new ArrayBuffer(r));for(let t=0;t<r;t++)n.setUint8(t,255&e[i+t]);const h=Qe[t].u.bind(n);s.push(h(0,a)),i+=r}return s};class ii 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._suppressDisconnect=!1,this.__consoleMode=!1,this._isUsbJtagOrOtg=void 0,this.__adaptiveBlockMultiplier=1,this.__adaptiveMaxInFlightMultiplier=1,this.__consecutiveSuccessfulChunks=0,this.__lastAdaptiveAdjustment=0,this.__isCDCDevice=!1,this.state_DTR=!1,this.state_RTS=!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 _consoleMode(){return this._parent?this._parent._consoleMode:this.__consoleMode}set _consoleMode(t){this._parent?this._parent._consoleMode=t:this.__consoleMode=t}setConsoleMode(t){this._consoleMode=t}get _inputBuffer(){if(this._parent)return this._parent._inputBuffer;if(void 0===this.__inputBuffer)throw new Error("_inputBuffer accessed before initialization");return 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}_clearInputBuffer(){this._inputBuffer.length=0,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}get isUsbJtagOrOtg(){return this._parent?this._parent._isUsbJtagOrOtg:this._isUsbJtagOrOtg}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},18:{name:"ESP32-P4 Native USB",maxBaudrate:2e6},4097:{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(),this.chipFamily===E&&301===this.chipRevision&&await this.powerOnFlash();const t=V(this.getChipFamily()),e=t.macFuse;for(let t=0;t<4;t++)this._efuses[t]=await this.readRegister(e+4*t);const i=null!==this.chipRevision&&void 0!==this.chipRevision?` (revision ${this.chipRevision})`:"";this.logger.log(`Connected to ${this.chipName}${i}`),this.logger.debug(`Bootloader flash offset: 0x${t.flashOffs.toString(16)}`),this._initializationSucceeded=!0}async detectChip(){try{const t=(await this.getSecurityInfo()).chipId,e=$[t];if(e)return this.chipName=e.name,this.chipFamily=e.family,this.chipRevision=await this.getChipRevision(),this.logger.debug(`${this.chipName} revision: ${this.chipRevision}`),this.chipFamily===E&&this.chipRevision>=300?this.chipVariant="rev300":this.chipFamily===E&&(this.chipVariant="rev0"),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 a(N);try{await this.sync()}catch(t){this.logger.debug(`Re-sync after GET_SECURITY_INFO failure: ${t}`)}}const t=await this.readRegister(1073745920),e=P[t>>>0];if(void 0===e)throw new Error(`Unknown Chip: Hex: ${s(t>>>0,8).toLowerCase()} Number: ${t}`);this.chipName=e.name,this.chipFamily=e.family,this.chipRevision=await this.getChipRevision(),this.logger.debug(`${this.chipName} revision: ${this.chipRevision}`),this.chipFamily===E&&(this.chipVariant=this.chipRevision>=300?"rev300":"rev0",this.logger.debug(`ESP32-P4 variant: ${this.chipVariant}`)),this.logger.debug(`Detected chip via magic value: ${s(t>>>0,8)} (${this.chipName})`)}async getChipRevision(){var t;let e=0,i=0;switch(this.chipFamily){case B:{const s=await this.readRegister(1073061900),a=await this.readRegister(1073061908);e=a>>24&3;const r=s>>15&1,n=a>>20&1;i=null!==(t={0:0,1:1,3:2,7:3}[(await this.readRegister(1610612856)>>31&1)<<2|n<<1|r])&&void 0!==t?t:0;break}case k:{const t=await this.readRegister(1061265488);e=((t>>20&1)<<3)+(await this.readRegister(1061265492)>>4&7),i=t>>18&3;break}case F:{const t=await this.readRegister(1610641488),s=await this.readRegister(1610641496);e=((s>>23&1)<<3)+(t>>18&7),i=s>>24&3;break}case x:{const t=await this.readRegister(1610647620);e=t>>16&15,i=t>>20&3;break}case I:{const t=await this.readRegister(1610647628),s=await this.readRegister(1610647636);e=((s>>23&1)<<3)+(t>>18&7),i=s>>24&3;break}case O:{const t=await this.readRegister(1611352140);e=15&t,i=t>>4&3;break}case D:{const t=await this.readRegister(1611335760);e=t>>18&15,i=t>>22&3;break}case U:{const t=await this.readRegister(1611352140);e=15&t,i=t>>4&3;break}case z:{const t=await this.readRegister(1611335760);e=t>>18&7,i=t>>21&3;break}case C:case A:break;case E:{const t=await this.readRegister(1343410252);e=15&t,i=(t>>23&1)<<2|t>>4&3;break}case T:{const t=await this.readRegister(544297036);e=15&t,i=t>>4&3;break}}return 100*i+e}async powerOnFlash(){if(this.chipFamily!==E)return;if(301!==this.chipRevision)return;this.logger.debug("Powering on flash for ESP32-P4 Rev 301 (ECO6)"),await this.writeRegister(1343291660,1),await a(10);const t=await this.readRegister(w);await this.writeRegister(w,t|m);const e=await this.readRegister(b);await this.writeRegister(b,128|e);const i=await this.readRegister(y);await this.writeRegister(y,3|i),await a(.05);const s=await this.readRegister(w);await this.writeRegister(w,-134217729&s);const r=await this.readRegister(b);await this.writeRegister(b,-2139095041&r);const n=await this.readRegister(b);await this.writeRegister(b,128|n);const h=await this.readRegister(b);await this.writeRegister(b,-129&h),await a(2),this.logger.debug("Flash powered on successfully")}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:ei("<I",t.slice(0,4))[0],flashCryptCnt:t[4],keyPurposes:Array.from(t.slice(5,12)),chipId:t.length>=16?ei("<I",t.slice(12,16))[0]:0,apiVersion:t.length>=20?ei("<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 getC5CrystalFreqRomExpect(){return(127&await this.readRegister(1611227408))>>>24}async getC5CrystalFreqDetected(){const t=1048575&await this.readRegister(1610612756),e=n*t/1e6;return e>45?48:e>33?40:26}async setBaudrate(t){const e=this._parent?this._parent.chipFamily:this.chipFamily;if(this.IS_STUB||e!==O)try{const e=ti("<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.`)}else await this.setBaudrateC5Rom(t);this._parent?await this._parent.reconfigurePort(t):await this.reconfigurePort(t),await a(N),this._parent?this._parent.currentBaudRate=t:this.currentBaudRate=t;const i=this._parent?this._parent._maxUSBSerialBaudrate:this._maxUSBSerialBaudrate;i&&t>i&&(this.logger.log(`⚠️ WARNING: Baudrate ${t} exceeds USB-Serial chip limit (${i})!`),this.logger.log("⚠️ This may cause data corruption or connection failures!")),this.logger.debug(`Changed baud rate to ${t}`)}async setBaudrateC5Rom(t){const e=await this.getC5CrystalFreqRomExpect(),i=await this.getC5CrystalFreqDetected();this.logger.log(`ROM expects crystal freq: ${e} MHz, detected ${i} MHz.`);let s=t;48===i&&40===e?s=Math.trunc(40*t/48):40===i&&48===e&&(s=Math.trunc(48*t/40)),this.logger.log(`Changing baud rate to ${s}...`);try{const t=ti("<II",s,0);await this.checkCommand(15,t)}catch(t){throw this.logger.error(`Baudrate change error: ${t}`),new Error(`Unable to change the baud rate to ${s}: No response from set baud rate command.`)}this.logger.log("Changed.")}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 s=Array.from(e);Array.prototype.push.apply(this._inputBuffer,s),this._totalBytesRead+=e.length}}catch{}finally{if(this._isReconfiguring=!1,this._reader){try{this._reader.releaseLock(),this.logger.debug("Reader released in readLoop cleanup")}catch(t){this.logger.debug(`Reader release error in readLoop: ${t}`)}this._reader=void 0}}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._suppressDisconnect||this.dispatchEvent(new Event("disconnect")),this._suppressDisconnect=!1,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 setDTRandRTS(t,e){this.state_DTR=t,this.state_RTS=e,await this.port.setSignals({dataTerminalReady:t,requestToSend:e})}async hardReset(t=!1){t?4097===this.port.getInfo().usbProductId?(await this.hardResetUSBJTAGSerial(),this.logger.log("USB-JTAG/Serial reset.")):(await this.hardResetClassic(),this.logger.log("Classic reset.")):(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],s=this._efuses[2],a=this._efuses[3];let r;if(this.chipFamily==S){if(0!=a)r=[a>>16&255,a>>8&255,255&a];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==B)t[0]=s>>8&255,t[1]=255&s,t[2]=i>>24&255,t[3]=i>>16&255,t[4]=i>>8&255,t[5]=255&i;else{if(this.chipFamily!=k&&this.chipFamily!=F&&this.chipFamily!=x&&this.chipFamily!=I&&this.chipFamily!=O&&this.chipFamily!=D&&this.chipFamily!=U&&this.chipFamily!=z&&this.chipFamily!=C&&this.chipFamily!=A&&this.chipFamily!=E&&this.chipFamily!=T)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 "+s(t,8));const e=ti("<I",t);await this.sendCommand(10,e);const[i]=await this.getResponse(10);return i}async checkCommand(t,e,i=0,a=3e3){const r=async()=>{a=Math.min(a,3e5),await this.sendCommand(t,e,i);const[r,n]=await this.getResponse(t,a);if(null===n)throw new Error("Didn't get enough status bytes");let h=n,o=0;if(this.IS_STUB||this.chipFamily==S?o=2:[B,k,F,x,I,O,D,U,z,C,A,E,T].includes(this.chipFamily)||20===t?o=4:[2,4].includes(h.length)&&(o=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 "+s(t))):new Error("Command failure error code "+s(l[1]));return[r,h]};return this._commandLock=this._commandLock.then(r,r),this._commandLock}async sendCommand(e,i,s=0){const a=t([...ti("<BBHI",0,e,i.length,s),...i]);this.debug&&this.logger.debug(`Writing ${a.length} byte${1==a.length?"":"s"}:`,a),await this.writeToStream(a)}async readPacket(t){let e=null,r=!1,n=[];for(;;){const h=Date.now();for(n=[];Date.now()-h<t;){if(this._inputBuffer.length>0){n.push(this._inputBuffer.shift());break}await a(1)}if(0==n.length){throw new H("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: "+s(t)),this.logger.debug("Remaining data in serial buffer: "+i(this._inputBuffer))),new H("Invalid head of packet ("+s(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: "+s(t)),this.logger.debug("Remaining data in serial buffer: "+i(this._inputBuffer))),new H("Invalid SLIP escape (0xdb, "+s(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)),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[a,r,,n]=ei("<BBHI",i.slice(0,8));if(1!=a)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 ${s(t)}`)}throw"Response doesn't match request"}checksum(t,e=239){for(const i of t)e^=i;return e}async reconfigurePort(t){var e;try{try{await this._writeChain}catch(t){this.logger.debug(`Pending write error during reconfigure: ${t}`)}if(this._isReconfiguring=!0,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}),this._isReconfiguring=!1,await this.flushSerialBuffers(),this.readLoop()}catch(e){throw this._isReconfiguring=!1,this.logger.error(`Reconfigure port error: ${e}`),new Error(`Unable to change the baud rate to ${t}: ${e}`)}}async connectWithResetStrategies(){var t,e;const i=this.port.getInfo(),s=4097===i.usbProductId,a=12346===i.usbVendorId;this.logger.log(`Detected USB: VID=0x${(null===(t=i.usbVendorId)||void 0===t?void 0:t.toString(16))||"unknown"}, PID=0x${(null===(e=i.usbProductId)||void 0===e?void 0:e.toString(16))||"unknown"}`);const r=[];(s||a)&&r.push({name:"USB-JTAG/Serial",fn:async()=>await this.hardResetUSBJTAGSerial()}),r.push({name:"Classic",fn:async()=>await this.hardResetClassic()}),s||a||r.push({name:"USB-JTAG/Serial (fallback)",fn:async()=>await this.hardResetUSBJTAGSerial()});let n=null;for(const t of r)try{if(this.logger.log(`Trying ${t.name} reset...`),!this.connected||!this.port.writable){this.logger.log(`Port disconnected, skipping ${t.name} reset`);continue}return await t.fn(),await this.sync(),void this.logger.log(`Connected successfully with ${t.name} reset.`)}catch(e){if(n=e,this.logger.log(`${t.name} reset failed: ${e.message}`),!this.connected||!this.port.writable){this.logger.log("Port disconnected during reset attempt");break}this._inputBuffer.length=0,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 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 sync(){for(let t=0;t<5;t++){this._inputBuffer.length=0;if(await this._sync())return await a(N),!0;await a(N)}throw new Error("Couldn't sync to ESP. Try resetting.")}async _sync(){await this.sendCommand(8,R);for(let t=0;t<8;t++)try{const[,t]=await this.getResponse(8,N);if(t.length>1&&0==t[0]&&0==t[1])return!0}catch{}return!1}getFlashWriteSize(){return this.IS_STUB?16384:1024}async flashData(t,e,i=0,a=!1){if(t.byteLength>=8){const e=Array.from(new Uint8Array(t,0,4)),i=e[0],a=e[2],r=e[3];this.logger.log(`Image header, Magic=${s(i)}, FlashMode=${s(a)}, FlashSizeFreq=${s(r)}`)}const r=(t=function(t,e,i=255){const s=t.length%e;if(0!==s){const a=new Uint8Array(e-s).fill(i),r=new Uint8Array(t.length+a.length);return r.set(t),r.set(a,t.length),r}return t}(new Uint8Array(t),4).buffer).byteLength;let n,h=0,o=M;a?(n=Xe(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=[],c=0,d=0,_=0;const u=Date.now(),g=this.getFlashWriteSize(),f=a?h:r;for(;f-_>0;)this.debug&&this.logger.log(`Writing at ${s(i+c*g,8)} `),f-_>=g?l=Array.from(new Uint8Array(n,_,g)):(l=Array.from(new Uint8Array(n,_,f-_)),a||(l=l.concat(new Array(g-l.length).fill(255)))),a?await this.flashDeflBlock(l,c,o):await this.flashBlock(l,c),c+=1,d+=a?Math.round(l.length*r/h):l.length,_+=g,e(Math.min(d,r),r);this.logger.log("Took "+(Date.now()-u)+"ms to write "+f+" bytes"),this.IS_STUB&&(await this.flashBegin(0,0),a?await this.flashDeflFinish():await this.flashFinish())}async flashBlock(t,e,i=3e3){await this.checkCommand(3,ti("<IIII",t.length,e,0,0).concat(t),this.checksum(t),i)}async flashDeflBlock(t,e,i=3e3){await this.checkCommand(17,ti("<IIII",t.length,e,0,0).concat(t),this.checksum(t),i)}async flashBegin(t=0,e=0,i=!1){let a;await this.flushSerialBuffers();const r=this.getFlashWriteSize();!this.IS_STUB&&[B,k,F,x,I,O,D,U,z,C,A,E,T].includes(this.chipFamily)&&await this.checkCommand(13,new Array(8).fill(0));const n=Math.floor((t+r-1)/r);a=this.chipFamily!=S||this.IS_STUB?t:this.getEraseSize(e,t);const h=this.IS_STUB?M:Z(3e4,t),o=Date.now();let l=ti("<IIII",a,n,r,e);return this.chipFamily!=B&&this.chipFamily!=k&&this.chipFamily!=F&&this.chipFamily!=x&&this.chipFamily!=I&&this.chipFamily!=O&&this.chipFamily!=D&&this.chipFamily!=U&&this.chipFamily!=z&&this.chipFamily!=C&&this.chipFamily!=A&&this.chipFamily!=E&&this.chipFamily!=T||(l=l.concat(ti("<I",i?1:0))),this.logger.log("Erase size "+a+", blocks "+n+", block size "+s(r,4)+", offset "+s(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 s=this.getFlashWriteSize(),a=Math.floor((e+s-1)/s),r=Math.floor((t+s-1)/s);let n=0,h=0;this.IS_STUB?(n=t,h=Z(3e4,n)):(n=r*s,h=M);const o=ti("<IIII",n,a,s,i);return await this.checkCommand(16,o,0,h),h}async flashFinish(){const t=ti("<I",1);await this.checkCommand(4,t)}async flashDeflFinish(){const t=ti("<I",1);await this.checkCommand(18,t)}getBootloaderOffset(){return V(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,s=0,a=0){let r=ti("<IIII",t,e,i,s);a>0&&(r=r.concat(ti("<IIII",V(this.getChipFamily()).uartDateReg,0,0,a))),await this.checkCommand(9,r)}async setDataLengths(t,e,i){if(-1!=t.mosiDlenOffs){const s=t.regBase+t.mosiDlenOffs,a=t.regBase+t.misoDlenOffs;e>0&&await this.writeRegister(s,e-1),i>0&&await this.writeRegister(a,i-1)}else{const s=t.regBase+t.usr1Offs,a=(0==i?0:i-1)<<8|(0==e?0:e-1)<<17;await this.writeRegister(s,a)}}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 a=V(this.getChipFamily()),r=a.regBase,n=r,h=r+a.usrOffs,o=r+a.usr2Offs,l=r+a.w0Offs,c=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,_=await this.readRegister(h),u=await this.readRegister(o);let g=1<<31;if(i>0&&(g|=268435456),d>0&&(g|=134217728),await this.setDataLengths(a,d,i),await this.writeRegister(h,g),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=ei("I".repeat(Math.floor(e.length/4)),e);let a=l;this.logger.debug(`Words Length: ${i.length}`);for(const t of i)this.logger.debug(`Writing word ${s(t)} to register offset ${s(a)}`),await this.writeRegister(a,t),a+=4}await this.writeRegister(n,c),await this.waitDone(n,c);const f=await this.readRegister(l);return await this.writeRegister(h,_),await this.writeRegister(o,u),f}async detectFlashSize(){this.logger.log("Detecting Flash Size");const t=await this.flashId(),e=255&t,i=t>>16&255;this.logger.log(`FlashId: ${s(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,s=Math.floor((e+i-1)/i);let a=16-Math.floor(t/i)%16;return s<a&&(a=s),s<2*a?Math.floor((s+1)/2*i):(s-a)*i}async memBegin(t,e,i,s){return await this.checkCommand(5,ti("<IIII",t,e,i,s))}async memBlock(t,e){return await this.checkCommand(7,ti("<IIII",t.length,e,0,0).concat(t),this.checksum(t))}async memFinish(t=0){const e=this.IS_STUB?M:500,i=ti("<II",0==t?1:0,t);return await this.checkCommand(6,i,0,e)}async runStub(t=!1){this.logger.debug(`Loading stub for ${this.chipName}, revision: ${this.chipRevision}`);const e=await j(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 s=e[t],a=e[`${t}_start`],r=s.length,n=Math.floor((r+i-1)/i);await this.memBegin(r,n,i,a);for(const t of Array(n).keys()){const e=t*i;let a=e+i;a>r&&(a=r),await this.memBlock(s.slice(e,a),t)}}await this.memFinish(e.entry);const s=await this.readPacket(500),a=String.fromCharCode(...s);if("OHAI"!=a)throw new Error("Failed to start stub. Unexpected response: "+a);this.logger.log("Stub is now running...");const r=new si(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.port.writable)throw new Error("Port became unavailable during write");this._writer||(this._writer=this.port.writable.getWriter()),await this._writer.write(new Uint8Array(t))}).catch(t=>{if(this.logger.error(`Write error: ${t}`),this._writer){try{this._writer.releaseLock()}catch(t){}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||t(void 0),this.addEventListener("disconnect",t,{once:!0}),this._reader.cancel()}),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=[];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,s=this.chipVariant,a=this.flashSize;if(await this.hardReset(!0),this._parent||(this.__inputBuffer=[],this.__totalBytesRead=0,this.readLoop()),await this.flushSerialBuffers(),await this.sync(),this.chipFamily=t,this.chipName=e,this.chipRevision=i,this.chipVariant=s,this.flashSize=a,this.logger.debug(`Reconnect complete (chip: ${this.chipName})`),!this.port.writable||!this.port.readable)throw new Error("Port not ready after reconnect");this.chipFamily===E&&301===this.chipRevision&&await this.powerOnFlash();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&&Object.assign(this,r),this.logger.debug("Reconnection successful")}catch(t){throw this._isReconfiguring=!1,t}}async drainInputBuffer(t=200){await a(t);let e=0;const i=Date.now();for(;e<112&&Date.now()-i<100;)if(this._inputBuffer.length>0){void 0!==this._inputBuffer.shift()&&e++}else await a(1);e>0&&this.logger.debug(`Drained ${e} bytes from input buffer`),this._parent||(this.__inputBuffer=[])}async flushSerialBuffers(){this._parent||(this.__inputBuffer=[]),await a(N),this._parent||(this.__inputBuffer=[]),this.logger.debug("Serial buffers flushed")}async readFlash(e,i,s){if(!this.IS_STUB)throw new Error("Reading flash is only supported in stub mode. Please run runStub() first.");await this.flushSerialBuffers(),this.logger.log(`Reading ${i} bytes from flash at address 0x${e.toString(16)}...`);let r=new Uint8Array(0),n=e,h=i;for(;h>0;){const e=Math.min(65536,h);let o=!1,l=0;const c=5;let d=!1;for(;!o&&l<=c;){let i=new Uint8Array(0);try{0===l&&this.logger.debug(`Reading chunk at 0x${n.toString(16)}, size: 0x${e.toString(16)}`);const s=ti("<IIII",n,e,4096,1024),[h]=await this.checkCommand(210,s);if(0!=h)throw new Error("Failed to read memory: "+h);for(;i.length<e;){let s;try{s=await this.readPacket(100)}catch(t){if(t instanceof H){this.logger.debug(`${t.message} at byte 0x${i.length.toString(16)}`);try{const t=[192,192];await this.writeToStream(t),this.logger.debug("Sent abort frame to stub"),await a(50)}catch(t){this.logger.debug(`Abort frame error: ${t}`)}if(await this.drainInputBuffer(200),i.length>=e)break}throw t}if(s&&s.length>0){const e=new Uint8Array(s),a=new Uint8Array(i.length+e.length);a.set(i),a.set(e,i.length),i=a;const r=ti("<I",i.length),n=t(r);await this.writeToStream(n)}}const c=new Uint8Array(r.length+i.length);c.set(r),c.set(i,r.length),r=c,o=!0}catch(t){if(l++,!(t instanceof H))throw t;if(l<=c)this.logger.log(`Cleared buffer and retrying (attempt ${l}/${c})...`);else{if(d)throw new Error(`Failed to read chunk at 0x${n.toString(16)} after ${c} retries and deep recovery attempt`);d=!0,this.logger.log(`All retries exhausted at 0x${n.toString(16)}. Attempting deep recovery (reconnect + reload stub)...`);try{await this.reconnect(),this.logger.log("Deep recovery successful. Resuming read from current position..."),l=0;continue}catch(t){throw new Error(`Failed to read chunk at 0x${n.toString(16)} after ${c} retries and deep recovery failed: ${t}`)}}}}s&&s(new Uint8Array(e),r.length,i),n+=e,h-=e,this.logger.debug(`Total progress: 0x${r.length.toString(16)} from 0x${i.toString(16)} bytes`)}return this.logger.debug(`Successfully read ${r.length} bytes from flash`),r}}class si extends ii{constructor(){super(...arguments),this.IS_STUB=!0}async memBegin(t,e,i,a){const r=await j(this.chipFamily,this.chipRevision);if(null===r)return[0,[]];const n=a,h=a+t;this.logger.debug(`Load range: ${s(n,8)}-${s(h,8)}`),this.logger.debug(`Stub data: ${s(r.data_start,8)}, len: ${r.data.length}, text: ${s(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 "+s(t,8)+"-"+s(e,8)+". Can't load binary at overlapping address range "+s(n,8)+"-"+s(h,8)+". Try changing the binary loading address.");return[0,[]]}async eraseFlash(){await this.checkCommand(208,[],0,L)}}const ai=async t=>{const e=await navigator.serial.requestPort();return await e.open({baudRate:n}),t.log("Connected successfully."),new ii(e,t)};export{B as CHIP_FAMILY_ESP32,x as CHIP_FAMILY_ESP32C2,I as CHIP_FAMILY_ESP32C3,O as CHIP_FAMILY_ESP32C5,D as CHIP_FAMILY_ESP32C6,U as CHIP_FAMILY_ESP32C61,z as CHIP_FAMILY_ESP32H2,A as CHIP_FAMILY_ESP32H21,C as CHIP_FAMILY_ESP32H4,E as CHIP_FAMILY_ESP32P4,k as CHIP_FAMILY_ESP32S2,F as CHIP_FAMILY_ESP32S3,T as CHIP_FAMILY_ESP32S31,S as CHIP_FAMILY_ESP8266,ii as ESPLoader,ai as connect};
@@ -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 s=t.charCodeAt(i);s<=255&&e.push(s)}return e},i=t=>"["+t.map(t=>s(t)).join(", ")+"]",s=(t,e=2)=>{const i=t.toString(16).toUpperCase();return i.startsWith("-")?"-0x"+i.substring(1).padStart(e,"0"):"0x"+i.padStart(e,"0")},a=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=1073061888,o=1061265408,l=1610612856,c=1610641408,d=1610612864,_=1610647552,u=1610647552,g=1611352064,f=1611335680,p=1611352064,w=1611335680,m=1343410176,b=1343312316,y=1<<27,v=1343312312,S=1343312892,R=544296960,B=e(" UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU"),k=33382,F=50,U=12882,x=12883,I=12994,O=12995,D=12997,C=12998,z=207969,A=12914,E=12916,$=12917,T=12928,P=12849,M={5:{name:"ESP32-C3",family:O},9:{name:"ESP32-S3",family:x},12:{name:"ESP32-C2",family:I},13:{name:"ESP32-C6",family:C},16:{name:"ESP32-H2",family:A},18:{name:"ESP32-P4",family:T},20:{name:"ESP32-C61",family:z},23:{name:"ESP32-C5",family:D},25:{name:"ESP32-H21",family:$},28:{name:"ESP32-H4",family:E},32:{name:"ESP32-S31",family:P}},L={4293968129:{name:"ESP8266",family:k},15736195:{name:"ESP32",family:F},1990:{name:"ESP32-S2",family:U}},N=3e3,Z=15e4,V=100,H=(t,e)=>{const i=Math.floor(t*(e/486));return i<N?N:i},j=t=>{switch(t){case F:return{regBase:1072963584,baseFuse:h,macFuse:1073061888,usrOffs:28,usr1Offs:32,usr2Offs:36,mosiDlenOffs:40,misoDlenOffs:44,w0Offs:128,uartDateReg:1610612856,flashOffs:4096};case U:return{regBase:1061167104,baseFuse:o,macFuse:1061265476,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:l,flashOffs:4096};case x:return{regBase:1610620928,usrOffs:24,baseFuse:c,macFuse:1610641476,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:d,flashOffs:0};case k:return{regBase:1610613248,usrOffs:28,baseFuse:1072693328,macFuse:1072693328,usr1Offs:32,usr2Offs:36,mosiDlenOffs:-1,misoDlenOffs:-1,w0Offs:64,uartDateReg:1610612856,flashOffs:0};case I:return{regBase:1610620928,baseFuse:_,macFuse:1610647616,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case O:return{regBase:1610620928,baseFuse:u,macFuse:1610647620,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case D:return{regBase:1610625024,baseFuse:g,macFuse:1611352132,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:8192};case C:return{regBase:1610625024,baseFuse:f,macFuse:1611335748,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case z:return{regBase:1610625024,baseFuse:p,macFuse:1611352132,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case A:return{regBase:1610625024,baseFuse:w,macFuse:1611335748,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case E:return{regBase:1611239424,baseFuse:1611339776,macFuse:1611339844,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610686588,flashOffs:8192};case $:return{regBase:1610625024,baseFuse:1611350016,macFuse:1611350084,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case T:return{regBase:1342754816,baseFuse:m,macFuse:1343410244,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1343004812,flashOffs:8192};case P:return{regBase:542113792,baseFuse:R,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 W extends Error{constructor(t){super(t),this.name="SlipReadError"}}const G=async(t,i)=>{let s;return t==E||t==$||t==P?null:(t==F?s=await import("./esp32-BRKoi17y.js"):t==U?s=await import("./esp32s2-iX3WoDbg.js"):t==x?s=await import("./esp32s3-DGwDVIgz.js"):t==k?s=await import("./esp8266-CUwxJpGa.js"):t==I?s=await import("./esp32c2-Btgr_lwh.js"):t==O?s=await import("./esp32c3-CHKfoI8W.js"):t==D?s=await import("./esp32c5-BDW4KtLo.js"):t==C?s=await import("./esp32c6-il8tTxAG.js"):t==z?s=await import("./esp32c61-thKzxBGf.js"):t==A?s=await import("./esp32h2-CxoUHv_P.js"):t==T&&(s=null!=i&&i>=300?await import("./esp32p4r3-CqI71ojR.js"):await import("./esp32p4-D3jLP-jY.js")),{...s,text:e(atob(s.text)),data:e(atob(s.data))})};function J(t){let e=t.length;for(;--e>=0;)t[e]=0}const q=256,K=286,Y=30,X=15,Q=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]),tt=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]),et=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),it=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),st=new Array(576);J(st);const at=new Array(60);J(at);const rt=new Array(512);J(rt);const nt=new Array(256);J(nt);const ht=new Array(29);J(ht);const ot=new Array(Y);function lt(t,e,i,s,a){this.static_tree=t,this.extra_bits=e,this.extra_base=i,this.elems=s,this.max_length=a,this.has_stree=t&&t.length}let ct,dt,_t;function ut(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}J(ot);const gt=t=>t<256?rt[t]:rt[256+(t>>>7)],ft=(t,e)=>{t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255},pt=(t,e,i)=>{t.bi_valid>16-i?(t.bi_buf|=e<<t.bi_valid&65535,ft(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)},wt=(t,e,i)=>{pt(t,i[2*e],i[2*e+1])},mt=(t,e)=>{let i=0;do{i|=1&t,t>>>=1,i<<=1}while(--e>0);return i>>>1},bt=(t,e,i)=>{const s=new Array(16);let a,r,n=0;for(a=1;a<=X;a++)n=n+i[a-1]<<1,s[a]=n;for(r=0;r<=e;r++){let e=t[2*r+1];0!==e&&(t[2*r]=mt(s[e]++,e))}},yt=t=>{let e;for(e=0;e<K;e++)t.dyn_ltree[2*e]=0;for(e=0;e<Y;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},vt=t=>{t.bi_valid>8?ft(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0},St=(t,e,i,s)=>{const a=2*e,r=2*i;return t[a]<t[r]||t[a]===t[r]&&s[e]<=s[i]},Rt=(t,e,i)=>{const s=t.heap[i];let a=i<<1;for(;a<=t.heap_len&&(a<t.heap_len&&St(e,t.heap[a+1],t.heap[a],t.depth)&&a++,!St(e,s,t.heap[a],t.depth));)t.heap[i]=t.heap[a],i=a,a<<=1;t.heap[i]=s},Bt=(t,e,i)=>{let s,a,r,n,h=0;if(0!==t.sym_next)do{s=255&t.pending_buf[t.sym_buf+h++],s+=(255&t.pending_buf[t.sym_buf+h++])<<8,a=t.pending_buf[t.sym_buf+h++],0===s?wt(t,a,e):(r=nt[a],wt(t,r+q+1,e),n=Q[r],0!==n&&(a-=ht[r],pt(t,a,n)),s--,r=gt(s),wt(t,r,i),n=tt[r],0!==n&&(s-=ot[r],pt(t,s,n)))}while(h<t.sym_next);wt(t,256,e)},kt=(t,e)=>{const i=e.dyn_tree,s=e.stat_desc.static_tree,a=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--,a&&(t.static_len-=s[2*o+1]);for(e.max_code=l,n=t.heap_len>>1;n>=1;n--)Rt(t,i,n);o=r;do{n=t.heap[1],t.heap[1]=t.heap[t.heap_len--],Rt(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++,Rt(t,i,1)}while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],((t,e)=>{const i=e.dyn_tree,s=e.max_code,a=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,c,d,_,u,g,f=0;for(_=0;_<=X;_++)t.bl_count[_]=0;for(i[2*t.heap[t.heap_max]+1]=0,l=t.heap_max+1;l<573;l++)c=t.heap[l],_=i[2*i[2*c+1]+1]+1,_>o&&(_=o,f++),i[2*c+1]=_,c>s||(t.bl_count[_]++,u=0,c>=h&&(u=n[c-h]),g=i[2*c],t.opt_len+=g*(_+u),r&&(t.static_len+=g*(a[2*c+1]+u)));if(0!==f){do{for(_=o-1;0===t.bl_count[_];)_--;t.bl_count[_]--,t.bl_count[_+1]+=2,t.bl_count[o]--,f-=2}while(f>0);for(_=o;0!==_;_--)for(c=t.bl_count[_];0!==c;)d=t.heap[--l],d>s||(i[2*d+1]!==_&&(t.opt_len+=(_-i[2*d+1])*i[2*d],i[2*d+1]=_),c--)}})(t,e),bt(i,l,t.bl_count)},Ft=(t,e,i)=>{let s,a,r=-1,n=e[1],h=0,o=7,l=4;for(0===n&&(o=138,l=3),e[2*(i+1)+1]=65535,s=0;s<=i;s++)a=n,n=e[2*(s+1)+1],++h<o&&a===n||(h<l?t.bl_tree[2*a]+=h:0!==a?(a!==r&&t.bl_tree[2*a]++,t.bl_tree[32]++):h<=10?t.bl_tree[34]++:t.bl_tree[36]++,h=0,r=a,0===n?(o=138,l=3):a===n?(o=6,l=3):(o=7,l=4))},Ut=(t,e,i)=>{let s,a,r=-1,n=e[1],h=0,o=7,l=4;for(0===n&&(o=138,l=3),s=0;s<=i;s++)if(a=n,n=e[2*(s+1)+1],!(++h<o&&a===n)){if(h<l)do{wt(t,a,t.bl_tree)}while(0!==--h);else 0!==a?(a!==r&&(wt(t,a,t.bl_tree),h--),wt(t,16,t.bl_tree),pt(t,h-3,2)):h<=10?(wt(t,17,t.bl_tree),pt(t,h-3,3)):(wt(t,18,t.bl_tree),pt(t,h-11,7));h=0,r=a,0===n?(o=138,l=3):a===n?(o=6,l=3):(o=7,l=4)}};let xt=!1;const It=(t,e,i,s)=>{pt(t,0+(s?1:0),3),vt(t),ft(t,i),ft(t,~i),i&&t.pending_buf.set(t.window.subarray(e,e+i),t.pending),t.pending+=i};var Ot=(t,e,i,s)=>{let a,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<q;e++)if(0!==t.dyn_ltree[2*e])return 1;return 0})(t)),kt(t,t.l_desc),kt(t,t.d_desc),n=(t=>{let e;for(Ft(t,t.dyn_ltree,t.l_desc.max_code),Ft(t,t.dyn_dtree,t.d_desc.max_code),kt(t,t.bl_desc),e=18;e>=3&&0===t.bl_tree[2*it[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e})(t),a=t.opt_len+3+7>>>3,r=t.static_len+3+7>>>3,r<=a&&(a=r)):a=r=i+5,i+4<=a&&-1!==e?It(t,e,i,s):4===t.strategy||r===a?(pt(t,2+(s?1:0),3),Bt(t,st,at)):(pt(t,4+(s?1:0),3),((t,e,i,s)=>{let a;for(pt(t,e-257,5),pt(t,i-1,5),pt(t,s-4,4),a=0;a<s;a++)pt(t,t.bl_tree[2*it[a]+1],3);Ut(t,t.dyn_ltree,e-1),Ut(t,t.dyn_dtree,i-1)})(t,t.l_desc.max_code+1,t.d_desc.max_code+1,n+1),Bt(t,t.dyn_ltree,t.dyn_dtree)),yt(t),s&&vt(t)},Dt={_tr_init:t=>{xt||((()=>{let t,e,i,s,a;const r=new Array(16);for(i=0,s=0;s<28;s++)for(ht[s]=i,t=0;t<1<<Q[s];t++)nt[i++]=s;for(nt[i-1]=s,a=0,s=0;s<16;s++)for(ot[s]=a,t=0;t<1<<tt[s];t++)rt[a++]=s;for(a>>=7;s<Y;s++)for(ot[s]=a<<7,t=0;t<1<<tt[s]-7;t++)rt[256+a++]=s;for(e=0;e<=X;e++)r[e]=0;for(t=0;t<=143;)st[2*t+1]=8,t++,r[8]++;for(;t<=255;)st[2*t+1]=9,t++,r[9]++;for(;t<=279;)st[2*t+1]=7,t++,r[7]++;for(;t<=287;)st[2*t+1]=8,t++,r[8]++;for(bt(st,287,r),t=0;t<Y;t++)at[2*t+1]=5,at[2*t]=mt(t,5);ct=new lt(st,Q,257,K,X),dt=new lt(at,tt,0,Y,X),_t=new lt(new Array(0),et,0,19,7)})(),xt=!0),t.l_desc=new ut(t.dyn_ltree,ct),t.d_desc=new ut(t.dyn_dtree,dt),t.bl_desc=new ut(t.bl_tree,_t),t.bi_buf=0,t.bi_valid=0,yt(t)},_tr_stored_block:It,_tr_flush_block:Ot,_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*(nt[i]+q+1)]++,t.dyn_dtree[2*gt(e)]++),t.sym_next===t.sym_end),_tr_align:t=>{pt(t,2,3),wt(t,256,st),(t=>{16===t.bi_valid?(ft(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 Ct=(t,e,i,s)=>{let a=65535&t,r=t>>>16&65535,n=0;for(;0!==i;){n=i>2e3?2e3:i,i-=n;do{a=a+e[s++]|0,r=r+a|0}while(--n);a%=65521,r%=65521}return a|r<<16};const zt=new Uint32Array((()=>{let t,e=[];for(var i=0;i<256;i++){t=i;for(var s=0;s<8;s++)t=1&t?3988292384^t>>>1:t>>>1;e[i]=t}return e})());var At=(t,e,i,s)=>{const a=zt,r=s+i;t^=-1;for(let i=s;i<r;i++)t=t>>>8^a[255&(t^e[i])];return-1^t},Et={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"},$t={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:Tt,_tr_stored_block:Pt,_tr_flush_block:Mt,_tr_tally:Lt,_tr_align:Nt}=Dt,{Z_NO_FLUSH:Zt,Z_PARTIAL_FLUSH:Vt,Z_FULL_FLUSH:Ht,Z_FINISH:jt,Z_BLOCK:Wt,Z_OK:Gt,Z_STREAM_END:Jt,Z_STREAM_ERROR:qt,Z_DATA_ERROR:Kt,Z_BUF_ERROR:Yt,Z_DEFAULT_COMPRESSION:Xt,Z_FILTERED:Qt,Z_HUFFMAN_ONLY:te,Z_RLE:ee,Z_FIXED:ie,Z_DEFAULT_STRATEGY:se,Z_UNKNOWN:ae,Z_DEFLATED:re}=$t,ne=258,he=262,oe=42,le=113,ce=666,de=(t,e)=>(t.msg=Et[e],e),_e=t=>2*t-(t>4?9:0),ue=t=>{let e=t.length;for(;--e>=0;)t[e]=0},ge=t=>{let e,i,s,a=t.w_size;e=t.hash_size,s=e;do{i=t.head[--s],t.head[s]=i>=a?i-a:0}while(--e);e=a,s=e;do{i=t.prev[--s],t.prev[s]=i>=a?i-a:0}while(--e)};let fe=(t,e,i)=>(e<<t.hash_shift^i)&t.hash_mask;const pe=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))},we=(t,e)=>{Mt(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,pe(t.strm)},me=(t,e)=>{t.pending_buf[t.pending++]=e},be=(t,e)=>{t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e},ye=(t,e,i,s)=>{let a=t.avail_in;return a>s&&(a=s),0===a?0:(t.avail_in-=a,e.set(t.input.subarray(t.next_in,t.next_in+a),i),1===t.state.wrap?t.adler=Ct(t.adler,e,a,i):2===t.state.wrap&&(t.adler=At(t.adler,e,a,i)),t.next_in+=a,t.total_in+=a,a)},ve=(t,e)=>{let i,s,a=t.max_chain_length,r=t.strstart,n=t.prev_length,h=t.nice_match;const o=t.strstart>t.w_size-he?t.strstart-(t.w_size-he):0,l=t.window,c=t.w_mask,d=t.prev,_=t.strstart+ne;let u=l[r+n-1],g=l[r+n];t.prev_length>=t.good_match&&(a>>=2),h>t.lookahead&&(h=t.lookahead);do{if(i=e,l[i+n]===g&&l[i+n-1]===u&&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<_);if(s=ne-(_-r),r=_-ne,s>n){if(t.match_start=e,n=s,s>=h)break;u=l[r+n-1],g=l[r+n]}}}while((e=d[e&c])>o&&0!==--a);return n<=t.lookahead?n:t.lookahead},Se=t=>{const e=t.w_size;let i,s,a;do{if(s=t.window_size-t.lookahead-t.strstart,t.strstart>=e+(e-he)&&(t.window.set(t.window.subarray(e,e+e-s),0),t.match_start-=e,t.strstart-=e,t.block_start-=e,t.insert>t.strstart&&(t.insert=t.strstart),ge(t),s+=e),0===t.strm.avail_in)break;if(i=ye(t.strm,t.window,t.strstart+t.lookahead,s),t.lookahead+=i,t.lookahead+t.insert>=3)for(a=t.strstart-t.insert,t.ins_h=t.window[a],t.ins_h=fe(t,t.ins_h,t.window[a+1]);t.insert&&(t.ins_h=fe(t,t.ins_h,t.window[a+3-1]),t.prev[a&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=a,a++,t.insert--,!(t.lookahead+t.insert<3)););}while(t.lookahead<he&&0!==t.strm.avail_in)},Re=(t,e)=>{let i,s,a,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,a=t.bi_valid+42>>3,t.strm.avail_out<a)break;if(a=t.strm.avail_out-a,s=t.strstart-t.block_start,i>s+t.strm.avail_in&&(i=s+t.strm.avail_in),i>a&&(i=a),i<r&&(0===i&&e!==jt||e===Zt||i!==s+t.strm.avail_in))break;n=e===jt&&i===s+t.strm.avail_in?1:0,Pt(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,pe(t.strm),s&&(s>i&&(s=i),t.strm.output.set(t.window.subarray(t.block_start,t.block_start+s),t.strm.next_out),t.strm.next_out+=s,t.strm.avail_out-=s,t.strm.total_out+=s,t.block_start+=s,i-=s),i&&(ye(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!==Zt&&e!==jt&&0===t.strm.avail_in&&t.strstart===t.block_start?2:(a=t.window_size-t.strstart,t.strm.avail_in>a&&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++,a+=t.w_size,t.insert>t.strstart&&(t.insert=t.strstart)),a>t.strm.avail_in&&(a=t.strm.avail_in),a&&(ye(t.strm,t.window,t.strstart,a),t.strstart+=a,t.insert+=a>t.w_size-t.insert?t.w_size-t.insert:a),t.high_water<t.strstart&&(t.high_water=t.strstart),a=t.bi_valid+42>>3,a=t.pending_buf_size-a>65535?65535:t.pending_buf_size-a,r=a>t.w_size?t.w_size:a,s=t.strstart-t.block_start,(s>=r||(s||e===jt)&&e!==Zt&&0===t.strm.avail_in&&s<=a)&&(i=s>a?a:s,n=e===jt&&0===t.strm.avail_in&&i===s?1:0,Pt(t,t.block_start,i,n),t.block_start+=i,pe(t.strm)),n?3:1)},Be=(t,e)=>{let i,s;for(;;){if(t.lookahead<he){if(Se(t),t.lookahead<he&&e===Zt)return 1;if(0===t.lookahead)break}if(i=0,t.lookahead>=3&&(t.ins_h=fe(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-he&&(t.match_length=ve(t,i)),t.match_length>=3)if(s=Lt(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=fe(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=fe(t,t.ins_h,t.window[t.strstart+1]);else s=Lt(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(s&&(we(t,!1),0===t.strm.avail_out))return 1}return t.insert=t.strstart<2?t.strstart:2,e===jt?(we(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(we(t,!1),0===t.strm.avail_out)?1:2},ke=(t,e)=>{let i,s,a;for(;;){if(t.lookahead<he){if(Se(t),t.lookahead<he&&e===Zt)return 1;if(0===t.lookahead)break}if(i=0,t.lookahead>=3&&(t.ins_h=fe(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-he&&(t.match_length=ve(t,i),t.match_length<=5&&(t.strategy===Qt||3===t.match_length&&t.strstart-t.match_start>4096)&&(t.match_length=2)),t.prev_length>=3&&t.match_length<=t.prev_length){a=t.strstart+t.lookahead-3,s=Lt(t,t.strstart-1-t.prev_match,t.prev_length-3),t.lookahead-=t.prev_length-1,t.prev_length-=2;do{++t.strstart<=a&&(t.ins_h=fe(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++,s&&(we(t,!1),0===t.strm.avail_out))return 1}else if(t.match_available){if(s=Lt(t,0,t.window[t.strstart-1]),s&&we(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&&(s=Lt(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<2?t.strstart:2,e===jt?(we(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(we(t,!1),0===t.strm.avail_out)?1:2};function Fe(t,e,i,s,a){this.good_length=t,this.max_lazy=e,this.nice_length=i,this.max_chain=s,this.func=a}const Ue=[new Fe(0,0,0,0,Re),new Fe(4,4,8,4,Be),new Fe(4,5,16,8,Be),new Fe(4,6,32,32,Be),new Fe(4,4,16,16,ke),new Fe(8,16,32,32,ke),new Fe(8,16,128,128,ke),new Fe(8,32,128,256,ke),new Fe(32,128,258,1024,ke),new Fe(32,258,258,4096,ke)];function xe(){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=re,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),ue(this.dyn_ltree),ue(this.dyn_dtree),ue(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),ue(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),ue(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 Ie=t=>{if(!t)return 1;const e=t.state;return!e||e.strm!==t||e.status!==oe&&57!==e.status&&69!==e.status&&73!==e.status&&91!==e.status&&103!==e.status&&e.status!==le&&e.status!==ce?1:0},Oe=t=>{if(Ie(t))return de(t,qt);t.total_in=t.total_out=0,t.data_type=ae;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?oe:le,t.adler=2===e.wrap?0:1,e.last_flush=-2,Tt(e),Gt},De=t=>{const e=Oe(t);var i;return e===Gt&&((i=t.state).window_size=2*i.w_size,ue(i.head),i.max_lazy_match=Ue[i.level].max_lazy,i.good_match=Ue[i.level].good_length,i.nice_match=Ue[i.level].nice_length,i.max_chain_length=Ue[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},Ce=(t,e,i,s,a,r)=>{if(!t)return qt;let n=1;if(e===Xt&&(e=6),s<0?(n=0,s=-s):s>15&&(n=2,s-=16),a<1||a>9||i!==re||s<8||s>15||e<0||e>9||r<0||r>ie||8===s&&1!==n)return de(t,qt);8===s&&(s=9);const h=new xe;return t.state=h,h.strm=t,h.status=oe,h.wrap=n,h.gzhead=null,h.w_bits=s,h.w_size=1<<h.w_bits,h.w_mask=h.w_size-1,h.hash_bits=a+7,h.hash_size=1<<h.hash_bits,h.hash_mask=h.hash_size-1,h.hash_shift=~~((h.hash_bits+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<<a+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,De(t)};var ze={deflateInit:(t,e)=>Ce(t,e,re,15,8,se),deflateInit2:Ce,deflateReset:De,deflateResetKeep:Oe,deflateSetHeader:(t,e)=>Ie(t)||2!==t.state.wrap?qt:(t.state.gzhead=e,Gt),deflate:(t,e)=>{if(Ie(t)||e>Wt||e<0)return t?de(t,qt):qt;const i=t.state;if(!t.output||0!==t.avail_in&&!t.input||i.status===ce&&e!==jt)return de(t,0===t.avail_out?Yt:qt);const s=i.last_flush;if(i.last_flush=e,0!==i.pending){if(pe(t),0===t.avail_out)return i.last_flush=-1,Gt}else if(0===t.avail_in&&_e(e)<=_e(s)&&e!==jt)return de(t,Yt);if(i.status===ce&&0!==t.avail_in)return de(t,Yt);if(i.status===oe&&0===i.wrap&&(i.status=le),i.status===oe){let e=re+(i.w_bits-8<<4)<<8,s=-1;if(s=i.strategy>=te||i.level<2?0:i.level<6?1:6===i.level?2:3,e|=s<<6,0!==i.strstart&&(e|=32),e+=31-e%31,be(i,e),0!==i.strstart&&(be(i,t.adler>>>16),be(i,65535&t.adler)),t.adler=1,i.status=le,pe(t),0!==i.pending)return i.last_flush=-1,Gt}if(57===i.status)if(t.adler=0,me(i,31),me(i,139),me(i,8),i.gzhead)me(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)),me(i,255&i.gzhead.time),me(i,i.gzhead.time>>8&255),me(i,i.gzhead.time>>16&255),me(i,i.gzhead.time>>24&255),me(i,9===i.level?2:i.strategy>=te||i.level<2?4:0),me(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(me(i,255&i.gzhead.extra.length),me(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(t.adler=At(t.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=69;else if(me(i,0),me(i,0),me(i,0),me(i,0),me(i,0),me(i,9===i.level?2:i.strategy>=te||i.level<2?4:0),me(i,3),i.status=le,pe(t),0!==i.pending)return i.last_flush=-1,Gt;if(69===i.status){if(i.gzhead.extra){let e=i.pending,s=(65535&i.gzhead.extra.length)-i.gzindex;for(;i.pending+s>i.pending_buf_size;){let a=i.pending_buf_size-i.pending;if(i.pending_buf.set(i.gzhead.extra.subarray(i.gzindex,i.gzindex+a),i.pending),i.pending=i.pending_buf_size,i.gzhead.hcrc&&i.pending>e&&(t.adler=At(t.adler,i.pending_buf,i.pending-e,e)),i.gzindex+=a,pe(t),0!==i.pending)return i.last_flush=-1,Gt;e=0,s-=a}let a=new Uint8Array(i.gzhead.extra);i.pending_buf.set(a.subarray(i.gzindex,i.gzindex+s),i.pending),i.pending+=s,i.gzhead.hcrc&&i.pending>e&&(t.adler=At(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,s=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>s&&(t.adler=At(t.adler,i.pending_buf,i.pending-s,s)),pe(t),0!==i.pending)return i.last_flush=-1,Gt;s=0}e=i.gzindex<i.gzhead.name.length?255&i.gzhead.name.charCodeAt(i.gzindex++):0,me(i,e)}while(0!==e);i.gzhead.hcrc&&i.pending>s&&(t.adler=At(t.adler,i.pending_buf,i.pending-s,s)),i.gzindex=0}i.status=91}if(91===i.status){if(i.gzhead.comment){let e,s=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>s&&(t.adler=At(t.adler,i.pending_buf,i.pending-s,s)),pe(t),0!==i.pending)return i.last_flush=-1,Gt;s=0}e=i.gzindex<i.gzhead.comment.length?255&i.gzhead.comment.charCodeAt(i.gzindex++):0,me(i,e)}while(0!==e);i.gzhead.hcrc&&i.pending>s&&(t.adler=At(t.adler,i.pending_buf,i.pending-s,s))}i.status=103}if(103===i.status){if(i.gzhead.hcrc){if(i.pending+2>i.pending_buf_size&&(pe(t),0!==i.pending))return i.last_flush=-1,Gt;me(i,255&t.adler),me(i,t.adler>>8&255),t.adler=0}if(i.status=le,pe(t),0!==i.pending)return i.last_flush=-1,Gt}if(0!==t.avail_in||0!==i.lookahead||e!==Zt&&i.status!==ce){let s=0===i.level?Re(i,e):i.strategy===te?((t,e)=>{let i;for(;;){if(0===t.lookahead&&(Se(t),0===t.lookahead)){if(e===Zt)return 1;break}if(t.match_length=0,i=Lt(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,i&&(we(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===jt?(we(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(we(t,!1),0===t.strm.avail_out)?1:2})(i,e):i.strategy===ee?((t,e)=>{let i,s,a,r;const n=t.window;for(;;){if(t.lookahead<=ne){if(Se(t),t.lookahead<=ne&&e===Zt)return 1;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=3&&t.strstart>0&&(a=t.strstart-1,s=n[a],s===n[++a]&&s===n[++a]&&s===n[++a])){r=t.strstart+ne;do{}while(s===n[++a]&&s===n[++a]&&s===n[++a]&&s===n[++a]&&s===n[++a]&&s===n[++a]&&s===n[++a]&&s===n[++a]&&a<r);t.match_length=ne-(r-a),t.match_length>t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=3?(i=Lt(t,1,t.match_length-3),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(i=Lt(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),i&&(we(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===jt?(we(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(we(t,!1),0===t.strm.avail_out)?1:2})(i,e):Ue[i.level].func(i,e);if(3!==s&&4!==s||(i.status=ce),1===s||3===s)return 0===t.avail_out&&(i.last_flush=-1),Gt;if(2===s&&(e===Vt?Nt(i):e!==Wt&&(Pt(i,0,0,!1),e===Ht&&(ue(i.head),0===i.lookahead&&(i.strstart=0,i.block_start=0,i.insert=0))),pe(t),0===t.avail_out))return i.last_flush=-1,Gt}return e!==jt?Gt:i.wrap<=0?Jt:(2===i.wrap?(me(i,255&t.adler),me(i,t.adler>>8&255),me(i,t.adler>>16&255),me(i,t.adler>>24&255),me(i,255&t.total_in),me(i,t.total_in>>8&255),me(i,t.total_in>>16&255),me(i,t.total_in>>24&255)):(be(i,t.adler>>>16),be(i,65535&t.adler)),pe(t),i.wrap>0&&(i.wrap=-i.wrap),0!==i.pending?Gt:Jt)},deflateEnd:t=>{if(Ie(t))return qt;const e=t.state.status;return t.state=null,e===le?de(t,Kt):Gt},deflateSetDictionary:(t,e)=>{let i=e.length;if(Ie(t))return qt;const s=t.state,a=s.wrap;if(2===a||1===a&&s.status!==oe||s.lookahead)return qt;if(1===a&&(t.adler=Ct(t.adler,e,i,0)),s.wrap=0,i>=s.w_size){0===a&&(ue(s.head),s.strstart=0,s.block_start=0,s.insert=0);let t=new Uint8Array(s.w_size);t.set(e.subarray(i-s.w_size,i),0),e=t,i=s.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,Se(s);s.lookahead>=3;){let t=s.strstart,e=s.lookahead-2;do{s.ins_h=fe(s,s.ins_h,s.window[t+3-1]),s.prev[t&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=t,t++}while(--e);s.strstart=t,s.lookahead=2,Se(s)}return s.strstart+=s.lookahead,s.block_start=s.strstart,s.insert=s.lookahead,s.lookahead=0,s.match_length=s.prev_length=2,s.match_available=0,t.next_in=n,t.input=h,t.avail_in=r,s.wrap=a,Gt},deflateInfo:"pako deflate (from Nodeca project)"};const Ae=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var Ee=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)Ae(i,e)&&(t[e]=i[e])}}return t},$e=t=>{let e=0;for(let i=0,s=t.length;i<s;i++)e+=t[i].length;const i=new Uint8Array(e);for(let e=0,s=0,a=t.length;e<a;e++){let a=t[e];i.set(a,s),s+=a.length}return i};let Te=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(t){Te=!1}const Pe=new Uint8Array(256);for(let t=0;t<256;t++)Pe[t]=t>=252?6:t>=248?5:t>=240?4:t>=224?3:t>=192?2:1;Pe[254]=Pe[254]=1;var Me=t=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(t);let e,i,s,a,r,n=t.length,h=0;for(a=0;a<n;a++)i=t.charCodeAt(a),55296==(64512&i)&&a+1<n&&(s=t.charCodeAt(a+1),56320==(64512&s)&&(i=65536+(i-55296<<10)+(s-56320),a++)),h+=i<128?1:i<2048?2:i<65536?3:4;for(e=new Uint8Array(h),r=0,a=0;r<h;a++)i=t.charCodeAt(a),55296==(64512&i)&&a+1<n&&(s=t.charCodeAt(a+1),56320==(64512&s)&&(i=65536+(i-55296<<10)+(s-56320),a++)),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 Le=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 Ne=Object.prototype.toString,{Z_NO_FLUSH:Ze,Z_SYNC_FLUSH:Ve,Z_FULL_FLUSH:He,Z_FINISH:je,Z_OK:We,Z_STREAM_END:Ge,Z_DEFAULT_COMPRESSION:Je,Z_DEFAULT_STRATEGY:qe,Z_DEFLATED:Ke}=$t;function Ye(t){this.options=Ee({level:Je,method:Ke,chunkSize:16384,windowBits:15,memLevel:8,strategy:qe},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 Le,this.strm.avail_out=0;let i=ze.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(i!==We)throw new Error(Et[i]);if(e.header&&ze.deflateSetHeader(this.strm,e.header),e.dictionary){let t;if(t="string"==typeof e.dictionary?Me(e.dictionary):"[object ArrayBuffer]"===Ne.call(e.dictionary)?new Uint8Array(e.dictionary):e.dictionary,i=ze.deflateSetDictionary(this.strm,t),i!==We)throw new Error(Et[i]);this._dict_set=!0}}Ye.prototype.push=function(t,e){const i=this.strm,s=this.options.chunkSize;let a,r;if(this.ended)return!1;for(r=e===~~e?e:!0===e?je:Ze,"string"==typeof t?i.input=Me(t):"[object ArrayBuffer]"===Ne.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(s),i.next_out=0,i.avail_out=s),(r===Ve||r===He)&&i.avail_out<=6)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else{if(a=ze.deflate(i,r),a===Ge)return i.next_out>0&&this.onData(i.output.subarray(0,i.next_out)),a=ze.deflateEnd(this.strm),this.onEnd(a),this.ended=!0,a===We;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},Ye.prototype.onData=function(t){this.chunks.push(t)},Ye.prototype.onEnd=function(t){t===We&&(this.result=$e(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};var Xe={deflate:function(t,e){const i=new Ye(e);if(i.push(t,!0),i.err)throw i.msg||Et[i.err];return i.result}};const{deflate:Qe}=Xe;var ti=Qe;const ei={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}},ii=(t,...e)=>{let i=0;if(t.replace(/[<>]/,"").length!=e.length)throw"Pack format to Argument count mismatch";const s=[];let a=!0;for(let s=0;s<t.length;s++)"<"==t[s]?a=!0:">"==t[s]?a=!1:(r(t[s],e[i]),i++);function r(t,e){if(!(t in ei))throw"Unhandled character '"+t+"' in pack format";const i=ei[t].bytes,r=new DataView(new ArrayBuffer(i));ei[t].p.bind(r)(0,e,a);for(let t=0;t<i;t++)s.push(r.getUint8(t))}return s},si=(t,e)=>{let i=0;const s=[];let a=!0;for(const e of t)"<"==e?a=!0:">"==e?a=!1:r(e);function r(t){if(!(t in ei))throw"Unhandled character '"+t+"' in unpack format";const r=ei[t].bytes,n=new DataView(new ArrayBuffer(r));for(let t=0;t<r;t++)n.setUint8(t,255&e[i+t]);const h=ei[t].u.bind(n);s.push(h(0,a)),i+=r}return s};class ai 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._suppressDisconnect=!1,this.__consoleMode=!1,this._isUsbJtagOrOtg=void 0,this.__adaptiveBlockMultiplier=1,this.__adaptiveMaxInFlightMultiplier=1,this.__consecutiveSuccessfulChunks=0,this.__lastAdaptiveAdjustment=0,this.__isCDCDevice=!1,this.state_DTR=!1,this.state_RTS=!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 _consoleMode(){return this._parent?this._parent._consoleMode:this.__consoleMode}set _consoleMode(t){this._parent?this._parent._consoleMode=t:this.__consoleMode=t}setConsoleMode(t){this._consoleMode=t}get _inputBuffer(){if(this._parent)return this._parent._inputBuffer;if(void 0===this.__inputBuffer)throw new Error("_inputBuffer accessed before initialization");return 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}_clearInputBuffer(){this._inputBuffer.length=0,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}get isUsbJtagOrOtg(){return this._parent?this._parent._isUsbJtagOrOtg:this._isUsbJtagOrOtg}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},18:{name:"ESP32-P4 Native USB",maxBaudrate:2e6},4097:{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(),this.chipFamily===T&&301===this.chipRevision&&await this.powerOnFlash();try{this._isUsbJtagOrOtg=await this.detectUsbConnectionType(),this.logger.debug("USB connection type: "+(this._isUsbJtagOrOtg?"USB-JTAG/OTG":"External Serial Chip"))}catch(t){this.logger.debug(`Could not detect USB connection type: ${t}`)}try{const t=await this.getUsbMode();this.logger.debug(`USB mode (register): ${t.mode} (uartNo=${t.uartNo})`)}catch(t){this.logger.debug(`Could not detect USB mode: ${t}`)}const t=j(this.getChipFamily()),e=t.macFuse;for(let t=0;t<4;t++)this._efuses[t]=await this.readRegister(e+4*t);const i=null!==this.chipRevision&&void 0!==this.chipRevision?` (revision ${this.chipRevision})`:"";this.logger.log(`Connected to ${this.chipName}${i}`),this.logger.debug(`Bootloader flash offset: 0x${t.flashOffs.toString(16)}`),this._initializationSucceeded=!0}async detectChip(){try{const t=(await this.getSecurityInfo()).chipId,e=M[t];if(e)return this.chipName=e.name,this.chipFamily=e.family,this.chipRevision=await this.getChipRevision(),this.logger.debug(`${this.chipName} revision: ${this.chipRevision}`),this.chipFamily===T&&this.chipRevision>=300?this.chipVariant="rev300":this.chipFamily===T&&(this.chipVariant="rev0"),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 a(V);try{await this.sync()}catch(t){this.logger.debug(`Re-sync after GET_SECURITY_INFO failure: ${t}`)}}const t=await this.readRegister(1073745920),e=L[t>>>0];if(void 0===e)throw new Error(`Unknown Chip: Hex: ${s(t>>>0,8).toLowerCase()} Number: ${t}`);this.chipName=e.name,this.chipFamily=e.family,this.chipRevision=await this.getChipRevision(),this.logger.debug(`${this.chipName} revision: ${this.chipRevision}`),this.chipFamily===T&&(this.chipVariant=this.chipRevision>=300?"rev300":"rev0",this.logger.debug(`ESP32-P4 variant: ${this.chipVariant}`)),this.logger.debug(`Detected chip via magic value: ${s(t>>>0,8)} (${this.chipName})`)}async getChipRevision(){var t;let e=0,i=0;switch(this.chipFamily){case F:{const s=await this.readRegister(1073061900),a=await this.readRegister(1073061908);e=a>>24&3;const r=s>>15&1,n=a>>20&1;i=null!==(t={0:0,1:1,3:2,7:3}[(await this.readRegister(1610612856)>>31&1)<<2|n<<1|r])&&void 0!==t?t:0;break}case U:{const t=await this.readRegister(1061265488);e=((t>>20&1)<<3)+(await this.readRegister(1061265492)>>4&7),i=t>>18&3;break}case x:{const t=await this.readRegister(1610641488),s=await this.readRegister(1610641496);e=((s>>23&1)<<3)+(t>>18&7),i=s>>24&3;break}case I:{const t=await this.readRegister(1610647620);e=t>>16&15,i=t>>20&3;break}case O:{const t=await this.readRegister(1610647628),s=await this.readRegister(1610647636);e=((s>>23&1)<<3)+(t>>18&7),i=s>>24&3;break}case D:{const t=await this.readRegister(1611352140);e=15&t,i=t>>4&3;break}case C:{const t=await this.readRegister(1611335760);e=t>>18&15,i=t>>22&3;break}case z:{const t=await this.readRegister(1611352140);e=15&t,i=t>>4&3;break}case A:{const t=await this.readRegister(1611335760);e=t>>18&7,i=t>>21&3;break}case E:case $:break;case T:{const t=await this.readRegister(1343410252);e=15&t,i=(t>>23&1)<<2|t>>4&3;break}case P:{const t=await this.readRegister(544297036);e=15&t,i=t>>4&3;break}}return 100*i+e}async powerOnFlash(){if(this.chipFamily!==T)return;if(301!==this.chipRevision)return;this.logger.debug("Powering on flash for ESP32-P4 Rev 301 (ECO6)"),await this.writeRegister(1343291660,1),await a(10);const t=await this.readRegister(b);await this.writeRegister(b,t|y);const e=await this.readRegister(v);await this.writeRegister(v,128|e);const i=await this.readRegister(S);await this.writeRegister(S,3|i),await a(.05);const s=await this.readRegister(b);await this.writeRegister(b,-134217729&s);const r=await this.readRegister(v);await this.writeRegister(v,-2139095041&r);const n=await this.readRegister(v);await this.writeRegister(v,128|n);const h=await this.readRegister(v);await this.writeRegister(v,-129&h),await a(2),this.logger.debug("Flash powered on successfully")}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:si("<I",t.slice(0,4))[0],flashCryptCnt:t[4],keyPurposes:Array.from(t.slice(5,12)),chipId:t.length>=16?si("<I",t.slice(12,16))[0]:0,apiVersion:t.length>=20?si("<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 detectUsbConnectionType(){return!1}async getUsbMode(){var t,e;const i=this._parent?this._parent.chipFamily:this.chipFamily,s=this._parent?null!==(t=this._parent.chipRevision)&&void 0!==t?t:0:null!==(e=this.chipRevision)&&void 0!==e?e:0;let a=null,r=null,n=null;switch(i){case U:a=1610612736,n=3;break;case x:a=1610612736,r=4,n=3;break;case O:a=(s<101?1070461028:1070461024)+0,r=3;break;case D:case C:a=1343004672,r=3;break;case z:a=s<=200?1611440128:1343004672,r=3;break;case A:a=1611440128,r=3;break;case E:a=1610686464,r=3;break;case T:a=1343004672,r=3,n=2}if(null===a)return{mode:"uart",uartNo:0};const h=255&await this.readRegister(a);return null!==n&&h===n?(this.logger.debug(`USB mode: USB-OTG (uartNo=${h})`),{mode:"usb-otg",uartNo:h}):null!==r&&h===r?(this.logger.debug(`USB mode: USB-JTAG/Serial (uartNo=${h})`),{mode:"usb-jtag-serial",uartNo:h}):(this.logger.debug(`USB mode: UART (uartNo=${h})`),{mode:"uart",uartNo:h})}async getC5CrystalFreqRomExpect(){return(127&await this.readRegister(1611227408))>>>24}async getC5CrystalFreqDetected(){const t=1048575&await this.readRegister(1610612756),e=n*t/1e6;return e>45?48:e>33?40:26}async setBaudrate(t){const e=this._parent?this._parent.chipFamily:this.chipFamily;if(this.IS_STUB||e!==D)try{const e=ii("<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.`)}else await this.setBaudrateC5Rom(t);this._parent?await this._parent.reconfigurePort(t):await this.reconfigurePort(t),await a(V),this._parent?this._parent.currentBaudRate=t:this.currentBaudRate=t;const i=this._parent?this._parent._maxUSBSerialBaudrate:this._maxUSBSerialBaudrate;i&&t>i&&(this.logger.log(`⚠️ WARNING: Baudrate ${t} exceeds USB-Serial chip limit (${i})!`),this.logger.log("⚠️ This may cause data corruption or connection failures!")),this.logger.debug(`Changed baud rate to ${t}`)}async setBaudrateC5Rom(t){const e=await this.getC5CrystalFreqRomExpect(),i=await this.getC5CrystalFreqDetected();this.logger.log(`ROM expects crystal freq: ${e} MHz, detected ${i} MHz.`);let s=t;48===i&&40===e?s=Math.trunc(40*t/48):40===i&&48===e&&(s=Math.trunc(48*t/40)),this.logger.log(`Changing baud rate to ${s}...`);try{const t=ii("<II",s,0);await this.checkCommand(15,t)}catch(t){throw this.logger.error(`Baudrate change error: ${t}`),new Error(`Unable to change the baud rate to ${s}: No response from set baud rate command.`)}this.logger.log("Changed.")}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 s=Array.from(e);Array.prototype.push.apply(this._inputBuffer,s),this._totalBytesRead+=e.length}}catch{}finally{if(this._isReconfiguring=!1,this._reader){try{this._reader.releaseLock(),this.logger.debug("Reader released in readLoop cleanup")}catch(t){this.logger.debug(`Reader release error in readLoop: ${t}`)}this._reader=void 0}}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._suppressDisconnect||this.dispatchEvent(new Event("disconnect")),this._suppressDisconnect=!1,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 setDTRandRTS(t,e){this.state_DTR=t,this.state_RTS=e,await this.port.setSignals({dataTerminalReady:t,requestToSend:e})}async hardReset(t=!1){t?4097===this.port.getInfo().usbProductId?(await this.hardResetUSBJTAGSerial(),this.logger.log("USB-JTAG/Serial reset.")):(await this.hardResetClassic(),this.logger.log("Classic reset.")):(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],s=this._efuses[2],a=this._efuses[3];let r;if(this.chipFamily==k){if(0!=a)r=[a>>16&255,a>>8&255,255&a];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==F)t[0]=s>>8&255,t[1]=255&s,t[2]=i>>24&255,t[3]=i>>16&255,t[4]=i>>8&255,t[5]=255&i;else{if(this.chipFamily!=U&&this.chipFamily!=x&&this.chipFamily!=I&&this.chipFamily!=O&&this.chipFamily!=D&&this.chipFamily!=C&&this.chipFamily!=z&&this.chipFamily!=A&&this.chipFamily!=E&&this.chipFamily!=$&&this.chipFamily!=T&&this.chipFamily!=P)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 "+s(t,8));const e=ii("<I",t);await this.sendCommand(10,e);const[i]=await this.getResponse(10);return i}async checkCommand(t,e,i=0,a=3e3){const r=async()=>{a=Math.min(a,3e5),await this.sendCommand(t,e,i);const[r,n]=await this.getResponse(t,a);if(null===n)throw new Error("Didn't get enough status bytes");let h=n,o=0;if(this.IS_STUB||this.chipFamily==k?o=2:[F,U,x,I,O,D,C,z,A,E,$,T,P].includes(this.chipFamily)||20===t?o=4:[2,4].includes(h.length)&&(o=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 "+s(t))):new Error("Command failure error code "+s(l[1]));return[r,h]};return this._commandLock=this._commandLock.then(r,r),this._commandLock}async sendCommand(e,i,s=0){const a=t([...ii("<BBHI",0,e,i.length,s),...i]);this.debug&&this.logger.debug(`Writing ${a.length} byte${1==a.length?"":"s"}:`,a),await this.writeToStream(a)}async readPacket(t){let e=null,r=!1,n=[];for(;;){const h=Date.now();for(n=[];Date.now()-h<t;){if(this._inputBuffer.length>0){n.push(this._inputBuffer.shift());break}await a(1)}if(0==n.length){throw new W("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: "+s(t)),this.logger.debug("Remaining data in serial buffer: "+i(this._inputBuffer))),new W("Invalid head of packet ("+s(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: "+s(t)),this.logger.debug("Remaining data in serial buffer: "+i(this._inputBuffer))),new W("Invalid SLIP escape (0xdb, "+s(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)),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[a,r,,n]=si("<BBHI",i.slice(0,8));if(1!=a)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 ${s(t)}`)}throw"Response doesn't match request"}checksum(t,e=239){for(const i of t)e^=i;return e}async reconfigurePort(t){var e;try{try{await this._writeChain}catch(t){this.logger.debug(`Pending write error during reconfigure: ${t}`)}if(this._isReconfiguring=!0,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}),this._isReconfiguring=!1,await this.flushSerialBuffers(),this.readLoop()}catch(e){throw this._isReconfiguring=!1,this.logger.error(`Reconfigure port error: ${e}`),new Error(`Unable to change the baud rate to ${t}: ${e}`)}}async connectWithResetStrategies(){var t,e;const i=this.port.getInfo(),s=4097===i.usbProductId,a=12346===i.usbVendorId;this.logger.log(`Detected USB: VID=0x${(null===(t=i.usbVendorId)||void 0===t?void 0:t.toString(16))||"unknown"}, PID=0x${(null===(e=i.usbProductId)||void 0===e?void 0:e.toString(16))||"unknown"}`);const r=[];(s||a)&&r.push({name:"USB-JTAG/Serial",fn:async()=>await this.hardResetUSBJTAGSerial()}),r.push({name:"Classic",fn:async()=>await this.hardResetClassic()}),s||a||r.push({name:"USB-JTAG/Serial (fallback)",fn:async()=>await this.hardResetUSBJTAGSerial()});let n=null;for(const t of r)try{if(this.logger.log(`Trying ${t.name} reset...`),!this.connected||!this.port.writable){this.logger.log(`Port disconnected, skipping ${t.name} reset`);continue}return await t.fn(),await this.sync(),void this.logger.log(`Connected successfully with ${t.name} reset.`)}catch(e){if(n=e,this.logger.log(`${t.name} reset failed: ${e.message}`),!this.connected||!this.port.writable){this.logger.log("Port disconnected during reset attempt");break}this._inputBuffer.length=0,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 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 sync(){for(let t=0;t<5;t++){this._inputBuffer.length=0;if(await this._sync())return await a(V),!0;await a(V)}throw new Error("Couldn't sync to ESP. Try resetting.")}async _sync(){await this.sendCommand(8,B);for(let t=0;t<8;t++)try{const[,t]=await this.getResponse(8,V);if(t.length>1&&0==t[0]&&0==t[1])return!0}catch{}return!1}getFlashWriteSize(){return this.IS_STUB?16384:1024}async flashData(t,e,i=0,a=!1){if(t.byteLength>=8){const e=Array.from(new Uint8Array(t,0,4)),i=e[0],a=e[2],r=e[3];this.logger.log(`Image header, Magic=${s(i)}, FlashMode=${s(a)}, FlashSizeFreq=${s(r)}`)}const r=t.byteLength;let n,h=0,o=N;a?(n=ti(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=[],c=0,d=0,_=0;const u=Date.now(),g=this.getFlashWriteSize(),f=a?h:r;for(;f-_>0;)this.debug&&this.logger.log(`Writing at ${s(i+c*g,8)} `),f-_>=g?l=Array.from(new Uint8Array(n,_,g)):(l=Array.from(new Uint8Array(n,_,f-_)),a||(l=l.concat(new Array(g-l.length).fill(255)))),a?await this.flashDeflBlock(l,c,o):await this.flashBlock(l,c),c+=1,d+=a?Math.round(l.length*r/h):l.length,_+=g,e(Math.min(d,r),r);this.logger.log("Took "+(Date.now()-u)+"ms to write "+f+" bytes"),this.IS_STUB&&(await this.flashBegin(0,0),a?await this.flashDeflFinish():await this.flashFinish())}async flashBlock(t,e,i=3e3){await this.checkCommand(3,ii("<IIII",t.length,e,0,0).concat(t),this.checksum(t),i)}async flashDeflBlock(t,e,i=3e3){await this.checkCommand(17,ii("<IIII",t.length,e,0,0).concat(t),this.checksum(t),i)}async flashBegin(t=0,e=0,i=!1){let a;await this.flushSerialBuffers();const r=this.getFlashWriteSize();!this.IS_STUB&&[F,U,x,I,O,D,C,z,A,E,$,T,P].includes(this.chipFamily)&&await this.checkCommand(13,new Array(8).fill(0));const n=Math.floor((t+r-1)/r);a=this.chipFamily!=k||this.IS_STUB?t:this.getEraseSize(e,t);const h=this.IS_STUB?N:H(3e4,t),o=Date.now();let l=ii("<IIII",a,n,r,e);return this.chipFamily!=F&&this.chipFamily!=U&&this.chipFamily!=x&&this.chipFamily!=I&&this.chipFamily!=O&&this.chipFamily!=D&&this.chipFamily!=C&&this.chipFamily!=z&&this.chipFamily!=A&&this.chipFamily!=E&&this.chipFamily!=$&&this.chipFamily!=T&&this.chipFamily!=P||(l=l.concat(ii("<I",i?1:0))),this.logger.log("Erase size "+a+", blocks "+n+", block size "+s(r,4)+", offset "+s(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 s=this.getFlashWriteSize(),a=Math.floor((e+s-1)/s),r=Math.floor((t+s-1)/s);let n=0,h=0;this.IS_STUB?(n=t,h=H(3e4,n)):(n=r*s,h=N);const o=ii("<IIII",n,a,s,i);return await this.checkCommand(16,o,0,h),h}async flashFinish(){const t=ii("<I",1);await this.checkCommand(4,t)}async flashDeflFinish(){const t=ii("<I",1);await this.checkCommand(18,t)}getBootloaderOffset(){return j(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,s=0,a=0){let r=ii("<IIII",t,e,i,s);a>0&&(r=r.concat(ii("<IIII",j(this.getChipFamily()).uartDateReg,0,0,a))),await this.checkCommand(9,r)}async setDataLengths(t,e,i){if(-1!=t.mosiDlenOffs){const s=t.regBase+t.mosiDlenOffs,a=t.regBase+t.misoDlenOffs;e>0&&await this.writeRegister(s,e-1),i>0&&await this.writeRegister(a,i-1)}else{const s=t.regBase+t.usr1Offs,a=(0==i?0:i-1)<<8|(0==e?0:e-1)<<17;await this.writeRegister(s,a)}}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 a=j(this.getChipFamily()),r=a.regBase,n=r,h=r+a.usrOffs,o=r+a.usr2Offs,l=r+a.w0Offs,c=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,_=await this.readRegister(h),u=await this.readRegister(o);let g=1<<31;if(i>0&&(g|=268435456),d>0&&(g|=134217728),await this.setDataLengths(a,d,i),await this.writeRegister(h,g),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=si("I".repeat(Math.floor(e.length/4)),e);let a=l;this.logger.debug(`Words Length: ${i.length}`);for(const t of i)this.logger.debug(`Writing word ${s(t)} to register offset ${s(a)}`),await this.writeRegister(a,t),a+=4}await this.writeRegister(n,c),await this.waitDone(n,c);const f=await this.readRegister(l);return await this.writeRegister(h,_),await this.writeRegister(o,u),f}async detectFlashSize(){this.logger.log("Detecting Flash Size");const t=await this.flashId(),e=255&t,i=t>>16&255;this.logger.log(`FlashId: ${s(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,s=Math.floor((e+i-1)/i);let a=16-Math.floor(t/i)%16;return s<a&&(a=s),s<2*a?Math.floor((s+1)/2*i):(s-a)*i}async memBegin(t,e,i,s){return await this.checkCommand(5,ii("<IIII",t,e,i,s))}async memBlock(t,e){return await this.checkCommand(7,ii("<IIII",t.length,e,0,0).concat(t),this.checksum(t))}async memFinish(t=0){const e=this.IS_STUB?N:500,i=ii("<II",0==t?1:0,t);return await this.checkCommand(6,i,0,e)}async runStub(t=!1){this.logger.debug(`Loading stub for ${this.chipName}, revision: ${this.chipRevision}`);const e=await G(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 s=e[t],a=e[`${t}_start`],r=s.length,n=Math.floor((r+i-1)/i);await this.memBegin(r,n,i,a);for(const t of Array(n).keys()){const e=t*i;let a=e+i;a>r&&(a=r),await this.memBlock(s.slice(e,a),t)}}await this.memFinish(e.entry);const s=await this.readPacket(500),a=String.fromCharCode(...s);if("OHAI"!=a)throw new Error("Failed to start stub. Unexpected response: "+a);this.logger.log("Stub is now running...");const r=new ri(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.port.writable)throw new Error("Port became unavailable during write");this._writer||(this._writer=this.port.writable.getWriter()),await this._writer.write(new Uint8Array(t))}).catch(t=>{if(this.logger.error(`Write error: ${t}`),this._writer){try{this._writer.releaseLock()}catch(t){}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||t(void 0),this.addEventListener("disconnect",t,{once:!0}),this._reader.cancel()}),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=[];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,s=this.chipVariant,a=this.flashSize;if(await this.hardReset(!0),this._parent||(this.__inputBuffer=[],this.__totalBytesRead=0,this.readLoop()),await this.flushSerialBuffers(),await this.sync(),this.chipFamily=t,this.chipName=e,this.chipRevision=i,this.chipVariant=s,this.flashSize=a,this.logger.debug(`Reconnect complete (chip: ${this.chipName})`),!this.port.writable||!this.port.readable)throw new Error("Port not ready after reconnect");this.chipFamily===T&&301===this.chipRevision&&await this.powerOnFlash();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&&Object.assign(this,r),this.logger.debug("Reconnection successful")}catch(t){throw this._isReconfiguring=!1,t}}async drainInputBuffer(t=200){await a(t);let e=0;const i=Date.now();for(;e<112&&Date.now()-i<100;)if(this._inputBuffer.length>0){void 0!==this._inputBuffer.shift()&&e++}else await a(1);e>0&&this.logger.debug(`Drained ${e} bytes from input buffer`),this._parent||(this.__inputBuffer=[])}async flushSerialBuffers(){this._parent||(this.__inputBuffer=[]),await a(V),this._parent||(this.__inputBuffer=[]),this.logger.debug("Serial buffers flushed")}async readFlash(e,i,s){if(!this.IS_STUB)throw new Error("Reading flash is only supported in stub mode. Please run runStub() first.");await this.flushSerialBuffers(),this.logger.log(`Reading ${i} bytes from flash at address 0x${e.toString(16)}...`);let r=new Uint8Array(0),n=e,h=i;for(;h>0;){const e=Math.min(65536,h);let o=!1,l=0;const c=5;let d=!1;for(;!o&&l<=c;){let i=new Uint8Array(0);try{0===l&&this.logger.debug(`Reading chunk at 0x${n.toString(16)}, size: 0x${e.toString(16)}`);const s=ii("<IIII",n,e,4096,1024),[h]=await this.checkCommand(210,s);if(0!=h)throw new Error("Failed to read memory: "+h);for(;i.length<e;){let s;try{s=await this.readPacket(100)}catch(t){if(t instanceof W){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 a(50)}catch(t){this.logger.debug(`Abort frame error: ${t}`)}if(await this.drainInputBuffer(200),i.length>=e)break}throw t}if(s&&s.length>0){const e=new Uint8Array(s),a=new Uint8Array(i.length+e.length);a.set(i),a.set(e,i.length),i=a;const r=ii("<I",i.length),n=t(r);await this.writeToStream(n)}}const c=new Uint8Array(r.length+i.length);c.set(r),c.set(i,r.length),r=c,o=!0}catch(t){if(l++,!(t instanceof W))throw t;if(l<=c){this.logger.log(`${t.message} at 0x${n.toString(16)}. Draining buffer and retrying (attempt ${l}/${c})...`);try{await this.drainInputBuffer(200),await this.flushSerialBuffers(),await a(V)}catch(t){this.logger.debug(`Buffer drain error: ${t}`)}}else{if(d)throw new Error(`Failed to read chunk at 0x${n.toString(16)} after ${c} retries and deep recovery attempt`);d=!0,this.logger.log(`All retries exhausted at 0x${n.toString(16)}. Attempting deep recovery (reconnect + reload stub)...`);try{await this.reconnect(),this.logger.log("Deep recovery successful. Resuming read from current position..."),l=0;continue}catch(t){throw new Error(`Failed to read chunk at 0x${n.toString(16)} after ${c} retries and deep recovery failed: ${t}`)}}}}s&&s(new Uint8Array(e),r.length,i),n+=e,h-=e,this.logger.debug(`Total progress: 0x${r.length.toString(16)} from 0x${i.toString(16)} bytes`)}return this.logger.debug(`Successfully read ${r.length} bytes from flash`),r}}class ri extends ai{constructor(){super(...arguments),this.IS_STUB=!0}async memBegin(t,e,i,a){const r=await G(this.chipFamily,this.chipRevision);if(null===r)return[0,[]];const n=a,h=a+t;this.logger.debug(`Load range: ${s(n,8)}-${s(h,8)}`),this.logger.debug(`Stub data: ${s(r.data_start,8)}, len: ${r.data.length}, text: ${s(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 "+s(t,8)+"-"+s(e,8)+". Can't load binary at overlapping address range "+s(n,8)+"-"+s(h,8)+". Try changing the binary loading address.");return[0,[]]}async eraseFlash(){await this.checkCommand(208,[],0,Z)}}const ni=async t=>{const e=await navigator.serial.requestPort();return await e.open({baudRate:n}),t.log("Connected successfully."),new ai(e,t)};export{F as CHIP_FAMILY_ESP32,I as CHIP_FAMILY_ESP32C2,O as CHIP_FAMILY_ESP32C3,D as CHIP_FAMILY_ESP32C5,C as CHIP_FAMILY_ESP32C6,z as CHIP_FAMILY_ESP32C61,A as CHIP_FAMILY_ESP32H2,$ as CHIP_FAMILY_ESP32H21,E as CHIP_FAMILY_ESP32H4,T as CHIP_FAMILY_ESP32P4,U as CHIP_FAMILY_ESP32S2,x as CHIP_FAMILY_ESP32S3,P as CHIP_FAMILY_ESP32S31,k as CHIP_FAMILY_ESP8266,ai as ESPLoader,ni as connect};
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 s=t.charCodeAt(i);s<=255&&e.push(s)}return e},i=t=>"["+t.map(t=>s(t)).join(", ")+"]",s=(t,e=2)=>{const i=t.toString(16).toUpperCase();return i.startsWith("-")?"-0x"+i.substring(1).padStart(e,"0"):"0x"+i.padStart(e,"0")};const a=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=1073061888,o=1061265408,l=1610641408,c=1610647552,d=1610647552,_=1611352064,u=1611335680,g=1611352064,f=1611335680,p=1343410176,w=1343312316,m=1<<27,b=1343312312,y=1343312892,v=544296960,R=e(" UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU"),S=33382,B=50,k=12882,F=12883,x=12994,I=12995,O=12997,D=12998,U=207969,z=12914,C=12916,A=12917,E=12928,T=12849,$={5:{name:"ESP32-C3",family:I},9:{name:"ESP32-S3",family:F},12:{name:"ESP32-C2",family:x},13:{name:"ESP32-C6",family:D},16:{name:"ESP32-H2",family:z},18:{name:"ESP32-P4",family:E},20:{name:"ESP32-C61",family:U},23:{name:"ESP32-C5",family:O},25:{name:"ESP32-H21",family:A},28:{name:"ESP32-H4",family:C},32:{name:"ESP32-S31",family:T}},P={4293968129:{name:"ESP8266",family:S},15736195:{name:"ESP32",family:B},1990:{name:"ESP32-S2",family:k}},M=3e3,L=15e4,N=100,Z=(t,e)=>{const i=Math.floor(t*(e/486));return i<M?M:i},V=t=>{switch(t){case B:return{regBase:1072963584,baseFuse:h,macFuse:1073061888,usrOffs:28,usr1Offs:32,usr2Offs:36,mosiDlenOffs:40,misoDlenOffs:44,w0Offs:128,uartDateReg:1610612856,flashOffs:4096};case k:return{regBase:1061167104,baseFuse:o,macFuse:1061265476,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612856,flashOffs:4096};case F:return{regBase:1610620928,usrOffs:24,baseFuse:l,macFuse:1610641476,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612864,flashOffs:0};case S:return{regBase:1610613248,usrOffs:28,baseFuse:1072693328,macFuse:1072693328,usr1Offs:32,usr2Offs:36,mosiDlenOffs:-1,misoDlenOffs:-1,w0Offs:64,uartDateReg:1610612856,flashOffs:0};case x:return{regBase:1610620928,baseFuse:c,macFuse:1610647616,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case I:return{regBase:1610620928,baseFuse:d,macFuse:1610647620,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case O:return{regBase:1610625024,baseFuse:_,macFuse:1611352132,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:8192};case D:return{regBase:1610625024,baseFuse:u,macFuse:1611335748,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case U:return{regBase:1610625024,baseFuse:g,macFuse:1611352132,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case z:return{regBase:1610625024,baseFuse:f,macFuse:1611335748,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case C:return{regBase:1611239424,baseFuse:1611339776,macFuse:1611339844,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610686588,flashOffs:8192};case A:return{regBase:1610625024,baseFuse:1611350016,macFuse:1611350084,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case E:return{regBase:1342754816,baseFuse:p,macFuse:1343410244,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1343004812,flashOffs:8192};case T:return{regBase:542113792,baseFuse:v,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 H extends Error{constructor(t){super(t),this.name="SlipReadError"}}const j=async(t,i)=>{let s;return t==C||t==A||t==T?null:(t==B?s=await import("./esp32-BRKoi17y.js"):t==k?s=await import("./esp32s2-iX3WoDbg.js"):t==F?s=await import("./esp32s3-DGwDVIgz.js"):t==S?s=await import("./esp8266-CUwxJpGa.js"):t==x?s=await import("./esp32c2-Btgr_lwh.js"):t==I?s=await import("./esp32c3-CHKfoI8W.js"):t==O?s=await import("./esp32c5-BDW4KtLo.js"):t==D?s=await import("./esp32c6-il8tTxAG.js"):t==U?s=await import("./esp32c61-thKzxBGf.js"):t==z?s=await import("./esp32h2-CxoUHv_P.js"):t==E&&(s=null!=i&&i>=300?await import("./esp32p4r3-CqI71ojR.js"):await import("./esp32p4-D3jLP-jY.js")),{...s,text:e(atob(s.text)),data:e(atob(s.data))})};function W(t){let e=t.length;for(;--e>=0;)t[e]=0}const G=256,q=286,K=30,J=15,Y=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]),X=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]),Q=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),tt=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),et=new Array(576);W(et);const it=new Array(60);W(it);const st=new Array(512);W(st);const at=new Array(256);W(at);const rt=new Array(29);W(rt);const nt=new Array(K);function ht(t,e,i,s,a){this.static_tree=t,this.extra_bits=e,this.extra_base=i,this.elems=s,this.max_length=a,this.has_stree=t&&t.length}let ot,lt,ct;function dt(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}W(nt);const _t=t=>t<256?st[t]:st[256+(t>>>7)],ut=(t,e)=>{t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255},gt=(t,e,i)=>{t.bi_valid>16-i?(t.bi_buf|=e<<t.bi_valid&65535,ut(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)},ft=(t,e,i)=>{gt(t,i[2*e],i[2*e+1])},pt=(t,e)=>{let i=0;do{i|=1&t,t>>>=1,i<<=1}while(--e>0);return i>>>1},wt=(t,e,i)=>{const s=new Array(16);let a,r,n=0;for(a=1;a<=J;a++)n=n+i[a-1]<<1,s[a]=n;for(r=0;r<=e;r++){let e=t[2*r+1];0!==e&&(t[2*r]=pt(s[e]++,e))}},mt=t=>{let e;for(e=0;e<q;e++)t.dyn_ltree[2*e]=0;for(e=0;e<K;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},bt=t=>{t.bi_valid>8?ut(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0},yt=(t,e,i,s)=>{const a=2*e,r=2*i;return t[a]<t[r]||t[a]===t[r]&&s[e]<=s[i]},vt=(t,e,i)=>{const s=t.heap[i];let a=i<<1;for(;a<=t.heap_len&&(a<t.heap_len&&yt(e,t.heap[a+1],t.heap[a],t.depth)&&a++,!yt(e,s,t.heap[a],t.depth));)t.heap[i]=t.heap[a],i=a,a<<=1;t.heap[i]=s},Rt=(t,e,i)=>{let s,a,r,n,h=0;if(0!==t.sym_next)do{s=255&t.pending_buf[t.sym_buf+h++],s+=(255&t.pending_buf[t.sym_buf+h++])<<8,a=t.pending_buf[t.sym_buf+h++],0===s?ft(t,a,e):(r=at[a],ft(t,r+G+1,e),n=Y[r],0!==n&&(a-=rt[r],gt(t,a,n)),s--,r=_t(s),ft(t,r,i),n=X[r],0!==n&&(s-=nt[r],gt(t,s,n)))}while(h<t.sym_next);ft(t,256,e)},St=(t,e)=>{const i=e.dyn_tree,s=e.stat_desc.static_tree,a=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--,a&&(t.static_len-=s[2*o+1]);for(e.max_code=l,n=t.heap_len>>1;n>=1;n--)vt(t,i,n);o=r;do{n=t.heap[1],t.heap[1]=t.heap[t.heap_len--],vt(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++,vt(t,i,1)}while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],((t,e)=>{const i=e.dyn_tree,s=e.max_code,a=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,c,d,_,u,g,f=0;for(_=0;_<=J;_++)t.bl_count[_]=0;for(i[2*t.heap[t.heap_max]+1]=0,l=t.heap_max+1;l<573;l++)c=t.heap[l],_=i[2*i[2*c+1]+1]+1,_>o&&(_=o,f++),i[2*c+1]=_,c>s||(t.bl_count[_]++,u=0,c>=h&&(u=n[c-h]),g=i[2*c],t.opt_len+=g*(_+u),r&&(t.static_len+=g*(a[2*c+1]+u)));if(0!==f){do{for(_=o-1;0===t.bl_count[_];)_--;t.bl_count[_]--,t.bl_count[_+1]+=2,t.bl_count[o]--,f-=2}while(f>0);for(_=o;0!==_;_--)for(c=t.bl_count[_];0!==c;)d=t.heap[--l],d>s||(i[2*d+1]!==_&&(t.opt_len+=(_-i[2*d+1])*i[2*d],i[2*d+1]=_),c--)}})(t,e),wt(i,l,t.bl_count)},Bt=(t,e,i)=>{let s,a,r=-1,n=e[1],h=0,o=7,l=4;for(0===n&&(o=138,l=3),e[2*(i+1)+1]=65535,s=0;s<=i;s++)a=n,n=e[2*(s+1)+1],++h<o&&a===n||(h<l?t.bl_tree[2*a]+=h:0!==a?(a!==r&&t.bl_tree[2*a]++,t.bl_tree[32]++):h<=10?t.bl_tree[34]++:t.bl_tree[36]++,h=0,r=a,0===n?(o=138,l=3):a===n?(o=6,l=3):(o=7,l=4))},kt=(t,e,i)=>{let s,a,r=-1,n=e[1],h=0,o=7,l=4;for(0===n&&(o=138,l=3),s=0;s<=i;s++)if(a=n,n=e[2*(s+1)+1],!(++h<o&&a===n)){if(h<l)do{ft(t,a,t.bl_tree)}while(0!==--h);else 0!==a?(a!==r&&(ft(t,a,t.bl_tree),h--),ft(t,16,t.bl_tree),gt(t,h-3,2)):h<=10?(ft(t,17,t.bl_tree),gt(t,h-3,3)):(ft(t,18,t.bl_tree),gt(t,h-11,7));h=0,r=a,0===n?(o=138,l=3):a===n?(o=6,l=3):(o=7,l=4)}};let Ft=!1;const xt=(t,e,i,s)=>{gt(t,0+(s?1:0),3),bt(t),ut(t,i),ut(t,~i),i&&t.pending_buf.set(t.window.subarray(e,e+i),t.pending),t.pending+=i};var It=(t,e,i,s)=>{let a,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<G;e++)if(0!==t.dyn_ltree[2*e])return 1;return 0})(t)),St(t,t.l_desc),St(t,t.d_desc),n=(t=>{let e;for(Bt(t,t.dyn_ltree,t.l_desc.max_code),Bt(t,t.dyn_dtree,t.d_desc.max_code),St(t,t.bl_desc),e=18;e>=3&&0===t.bl_tree[2*tt[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e})(t),a=t.opt_len+3+7>>>3,r=t.static_len+3+7>>>3,r<=a&&(a=r)):a=r=i+5,i+4<=a&&-1!==e?xt(t,e,i,s):4===t.strategy||r===a?(gt(t,2+(s?1:0),3),Rt(t,et,it)):(gt(t,4+(s?1:0),3),((t,e,i,s)=>{let a;for(gt(t,e-257,5),gt(t,i-1,5),gt(t,s-4,4),a=0;a<s;a++)gt(t,t.bl_tree[2*tt[a]+1],3);kt(t,t.dyn_ltree,e-1),kt(t,t.dyn_dtree,i-1)})(t,t.l_desc.max_code+1,t.d_desc.max_code+1,n+1),Rt(t,t.dyn_ltree,t.dyn_dtree)),mt(t),s&&bt(t)},Ot={_tr_init:t=>{Ft||((()=>{let t,e,i,s,a;const r=new Array(16);for(i=0,s=0;s<28;s++)for(rt[s]=i,t=0;t<1<<Y[s];t++)at[i++]=s;for(at[i-1]=s,a=0,s=0;s<16;s++)for(nt[s]=a,t=0;t<1<<X[s];t++)st[a++]=s;for(a>>=7;s<K;s++)for(nt[s]=a<<7,t=0;t<1<<X[s]-7;t++)st[256+a++]=s;for(e=0;e<=J;e++)r[e]=0;for(t=0;t<=143;)et[2*t+1]=8,t++,r[8]++;for(;t<=255;)et[2*t+1]=9,t++,r[9]++;for(;t<=279;)et[2*t+1]=7,t++,r[7]++;for(;t<=287;)et[2*t+1]=8,t++,r[8]++;for(wt(et,287,r),t=0;t<K;t++)it[2*t+1]=5,it[2*t]=pt(t,5);ot=new ht(et,Y,257,q,J),lt=new ht(it,X,0,K,J),ct=new ht(new Array(0),Q,0,19,7)})(),Ft=!0),t.l_desc=new dt(t.dyn_ltree,ot),t.d_desc=new dt(t.dyn_dtree,lt),t.bl_desc=new dt(t.bl_tree,ct),t.bi_buf=0,t.bi_valid=0,mt(t)},_tr_stored_block:xt,_tr_flush_block:It,_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*(at[i]+G+1)]++,t.dyn_dtree[2*_t(e)]++),t.sym_next===t.sym_end),_tr_align:t=>{gt(t,2,3),ft(t,256,et),(t=>{16===t.bi_valid?(ut(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 Dt=(t,e,i,s)=>{let a=65535&t,r=t>>>16&65535,n=0;for(;0!==i;){n=i>2e3?2e3:i,i-=n;do{a=a+e[s++]|0,r=r+a|0}while(--n);a%=65521,r%=65521}return a|r<<16};const Ut=new Uint32Array((()=>{let t,e=[];for(var i=0;i<256;i++){t=i;for(var s=0;s<8;s++)t=1&t?3988292384^t>>>1:t>>>1;e[i]=t}return e})());var zt=(t,e,i,s)=>{const a=Ut,r=s+i;t^=-1;for(let i=s;i<r;i++)t=t>>>8^a[255&(t^e[i])];return-1^t},Ct={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"},At={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:Et,_tr_stored_block:Tt,_tr_flush_block:$t,_tr_tally:Pt,_tr_align:Mt}=Ot,{Z_NO_FLUSH:Lt,Z_PARTIAL_FLUSH:Nt,Z_FULL_FLUSH:Zt,Z_FINISH:Vt,Z_BLOCK:Ht,Z_OK:jt,Z_STREAM_END:Wt,Z_STREAM_ERROR:Gt,Z_DATA_ERROR:qt,Z_BUF_ERROR:Kt,Z_DEFAULT_COMPRESSION:Jt,Z_FILTERED:Yt,Z_HUFFMAN_ONLY:Xt,Z_RLE:Qt,Z_FIXED:te,Z_DEFAULT_STRATEGY:ee,Z_UNKNOWN:ie,Z_DEFLATED:se}=At,ae=258,re=262,ne=42,he=113,oe=666,le=(t,e)=>(t.msg=Ct[e],e),ce=t=>2*t-(t>4?9:0),de=t=>{let e=t.length;for(;--e>=0;)t[e]=0},_e=t=>{let e,i,s,a=t.w_size;e=t.hash_size,s=e;do{i=t.head[--s],t.head[s]=i>=a?i-a:0}while(--e);e=a,s=e;do{i=t.prev[--s],t.prev[s]=i>=a?i-a:0}while(--e)};let ue=(t,e,i)=>(e<<t.hash_shift^i)&t.hash_mask;const ge=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))},fe=(t,e)=>{$t(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,ge(t.strm)},pe=(t,e)=>{t.pending_buf[t.pending++]=e},we=(t,e)=>{t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e},me=(t,e,i,s)=>{let a=t.avail_in;return a>s&&(a=s),0===a?0:(t.avail_in-=a,e.set(t.input.subarray(t.next_in,t.next_in+a),i),1===t.state.wrap?t.adler=Dt(t.adler,e,a,i):2===t.state.wrap&&(t.adler=zt(t.adler,e,a,i)),t.next_in+=a,t.total_in+=a,a)},be=(t,e)=>{let i,s,a=t.max_chain_length,r=t.strstart,n=t.prev_length,h=t.nice_match;const o=t.strstart>t.w_size-re?t.strstart-(t.w_size-re):0,l=t.window,c=t.w_mask,d=t.prev,_=t.strstart+ae;let u=l[r+n-1],g=l[r+n];t.prev_length>=t.good_match&&(a>>=2),h>t.lookahead&&(h=t.lookahead);do{if(i=e,l[i+n]===g&&l[i+n-1]===u&&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<_);if(s=ae-(_-r),r=_-ae,s>n){if(t.match_start=e,n=s,s>=h)break;u=l[r+n-1],g=l[r+n]}}}while((e=d[e&c])>o&&0!==--a);return n<=t.lookahead?n:t.lookahead},ye=t=>{const e=t.w_size;let i,s,a;do{if(s=t.window_size-t.lookahead-t.strstart,t.strstart>=e+(e-re)&&(t.window.set(t.window.subarray(e,e+e-s),0),t.match_start-=e,t.strstart-=e,t.block_start-=e,t.insert>t.strstart&&(t.insert=t.strstart),_e(t),s+=e),0===t.strm.avail_in)break;if(i=me(t.strm,t.window,t.strstart+t.lookahead,s),t.lookahead+=i,t.lookahead+t.insert>=3)for(a=t.strstart-t.insert,t.ins_h=t.window[a],t.ins_h=ue(t,t.ins_h,t.window[a+1]);t.insert&&(t.ins_h=ue(t,t.ins_h,t.window[a+3-1]),t.prev[a&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=a,a++,t.insert--,!(t.lookahead+t.insert<3)););}while(t.lookahead<re&&0!==t.strm.avail_in)},ve=(t,e)=>{let i,s,a,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,a=t.bi_valid+42>>3,t.strm.avail_out<a)break;if(a=t.strm.avail_out-a,s=t.strstart-t.block_start,i>s+t.strm.avail_in&&(i=s+t.strm.avail_in),i>a&&(i=a),i<r&&(0===i&&e!==Vt||e===Lt||i!==s+t.strm.avail_in))break;n=e===Vt&&i===s+t.strm.avail_in?1:0,Tt(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,ge(t.strm),s&&(s>i&&(s=i),t.strm.output.set(t.window.subarray(t.block_start,t.block_start+s),t.strm.next_out),t.strm.next_out+=s,t.strm.avail_out-=s,t.strm.total_out+=s,t.block_start+=s,i-=s),i&&(me(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!==Lt&&e!==Vt&&0===t.strm.avail_in&&t.strstart===t.block_start?2:(a=t.window_size-t.strstart,t.strm.avail_in>a&&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++,a+=t.w_size,t.insert>t.strstart&&(t.insert=t.strstart)),a>t.strm.avail_in&&(a=t.strm.avail_in),a&&(me(t.strm,t.window,t.strstart,a),t.strstart+=a,t.insert+=a>t.w_size-t.insert?t.w_size-t.insert:a),t.high_water<t.strstart&&(t.high_water=t.strstart),a=t.bi_valid+42>>3,a=t.pending_buf_size-a>65535?65535:t.pending_buf_size-a,r=a>t.w_size?t.w_size:a,s=t.strstart-t.block_start,(s>=r||(s||e===Vt)&&e!==Lt&&0===t.strm.avail_in&&s<=a)&&(i=s>a?a:s,n=e===Vt&&0===t.strm.avail_in&&i===s?1:0,Tt(t,t.block_start,i,n),t.block_start+=i,ge(t.strm)),n?3:1)},Re=(t,e)=>{let i,s;for(;;){if(t.lookahead<re){if(ye(t),t.lookahead<re&&e===Lt)return 1;if(0===t.lookahead)break}if(i=0,t.lookahead>=3&&(t.ins_h=ue(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-re&&(t.match_length=be(t,i)),t.match_length>=3)if(s=Pt(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=ue(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=ue(t,t.ins_h,t.window[t.strstart+1]);else s=Pt(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(s&&(fe(t,!1),0===t.strm.avail_out))return 1}return t.insert=t.strstart<2?t.strstart:2,e===Vt?(fe(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(fe(t,!1),0===t.strm.avail_out)?1:2},Se=(t,e)=>{let i,s,a;for(;;){if(t.lookahead<re){if(ye(t),t.lookahead<re&&e===Lt)return 1;if(0===t.lookahead)break}if(i=0,t.lookahead>=3&&(t.ins_h=ue(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-re&&(t.match_length=be(t,i),t.match_length<=5&&(t.strategy===Yt||3===t.match_length&&t.strstart-t.match_start>4096)&&(t.match_length=2)),t.prev_length>=3&&t.match_length<=t.prev_length){a=t.strstart+t.lookahead-3,s=Pt(t,t.strstart-1-t.prev_match,t.prev_length-3),t.lookahead-=t.prev_length-1,t.prev_length-=2;do{++t.strstart<=a&&(t.ins_h=ue(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++,s&&(fe(t,!1),0===t.strm.avail_out))return 1}else if(t.match_available){if(s=Pt(t,0,t.window[t.strstart-1]),s&&fe(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&&(s=Pt(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<2?t.strstart:2,e===Vt?(fe(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(fe(t,!1),0===t.strm.avail_out)?1:2};function Be(t,e,i,s,a){this.good_length=t,this.max_lazy=e,this.nice_length=i,this.max_chain=s,this.func=a}const ke=[new Be(0,0,0,0,ve),new Be(4,4,8,4,Re),new Be(4,5,16,8,Re),new Be(4,6,32,32,Re),new Be(4,4,16,16,Se),new Be(8,16,32,32,Se),new Be(8,16,128,128,Se),new Be(8,32,128,256,Se),new Be(32,128,258,1024,Se),new Be(32,258,258,4096,Se)];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=se,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),de(this.dyn_ltree),de(this.dyn_dtree),de(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),de(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),de(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 xe=t=>{if(!t)return 1;const e=t.state;return!e||e.strm!==t||e.status!==ne&&57!==e.status&&69!==e.status&&73!==e.status&&91!==e.status&&103!==e.status&&e.status!==he&&e.status!==oe?1:0},Ie=t=>{if(xe(t))return le(t,Gt);t.total_in=t.total_out=0,t.data_type=ie;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?ne:he,t.adler=2===e.wrap?0:1,e.last_flush=-2,Et(e),jt},Oe=t=>{const e=Ie(t);var i;return e===jt&&((i=t.state).window_size=2*i.w_size,de(i.head),i.max_lazy_match=ke[i.level].max_lazy,i.good_match=ke[i.level].good_length,i.nice_match=ke[i.level].nice_length,i.max_chain_length=ke[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},De=(t,e,i,s,a,r)=>{if(!t)return Gt;let n=1;if(e===Jt&&(e=6),s<0?(n=0,s=-s):s>15&&(n=2,s-=16),a<1||a>9||i!==se||s<8||s>15||e<0||e>9||r<0||r>te||8===s&&1!==n)return le(t,Gt);8===s&&(s=9);const h=new Fe;return t.state=h,h.strm=t,h.status=ne,h.wrap=n,h.gzhead=null,h.w_bits=s,h.w_size=1<<h.w_bits,h.w_mask=h.w_size-1,h.hash_bits=a+7,h.hash_size=1<<h.hash_bits,h.hash_mask=h.hash_size-1,h.hash_shift=~~((h.hash_bits+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<<a+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,Oe(t)};var Ue={deflateInit:(t,e)=>De(t,e,se,15,8,ee),deflateInit2:De,deflateReset:Oe,deflateResetKeep:Ie,deflateSetHeader:(t,e)=>xe(t)||2!==t.state.wrap?Gt:(t.state.gzhead=e,jt),deflate:(t,e)=>{if(xe(t)||e>Ht||e<0)return t?le(t,Gt):Gt;const i=t.state;if(!t.output||0!==t.avail_in&&!t.input||i.status===oe&&e!==Vt)return le(t,0===t.avail_out?Kt:Gt);const s=i.last_flush;if(i.last_flush=e,0!==i.pending){if(ge(t),0===t.avail_out)return i.last_flush=-1,jt}else if(0===t.avail_in&&ce(e)<=ce(s)&&e!==Vt)return le(t,Kt);if(i.status===oe&&0!==t.avail_in)return le(t,Kt);if(i.status===ne&&0===i.wrap&&(i.status=he),i.status===ne){let e=se+(i.w_bits-8<<4)<<8,s=-1;if(s=i.strategy>=Xt||i.level<2?0:i.level<6?1:6===i.level?2:3,e|=s<<6,0!==i.strstart&&(e|=32),e+=31-e%31,we(i,e),0!==i.strstart&&(we(i,t.adler>>>16),we(i,65535&t.adler)),t.adler=1,i.status=he,ge(t),0!==i.pending)return i.last_flush=-1,jt}if(57===i.status)if(t.adler=0,pe(i,31),pe(i,139),pe(i,8),i.gzhead)pe(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)),pe(i,255&i.gzhead.time),pe(i,i.gzhead.time>>8&255),pe(i,i.gzhead.time>>16&255),pe(i,i.gzhead.time>>24&255),pe(i,9===i.level?2:i.strategy>=Xt||i.level<2?4:0),pe(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(pe(i,255&i.gzhead.extra.length),pe(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(t.adler=zt(t.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=69;else if(pe(i,0),pe(i,0),pe(i,0),pe(i,0),pe(i,0),pe(i,9===i.level?2:i.strategy>=Xt||i.level<2?4:0),pe(i,3),i.status=he,ge(t),0!==i.pending)return i.last_flush=-1,jt;if(69===i.status){if(i.gzhead.extra){let e=i.pending,s=(65535&i.gzhead.extra.length)-i.gzindex;for(;i.pending+s>i.pending_buf_size;){let a=i.pending_buf_size-i.pending;if(i.pending_buf.set(i.gzhead.extra.subarray(i.gzindex,i.gzindex+a),i.pending),i.pending=i.pending_buf_size,i.gzhead.hcrc&&i.pending>e&&(t.adler=zt(t.adler,i.pending_buf,i.pending-e,e)),i.gzindex+=a,ge(t),0!==i.pending)return i.last_flush=-1,jt;e=0,s-=a}let a=new Uint8Array(i.gzhead.extra);i.pending_buf.set(a.subarray(i.gzindex,i.gzindex+s),i.pending),i.pending+=s,i.gzhead.hcrc&&i.pending>e&&(t.adler=zt(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,s=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>s&&(t.adler=zt(t.adler,i.pending_buf,i.pending-s,s)),ge(t),0!==i.pending)return i.last_flush=-1,jt;s=0}e=i.gzindex<i.gzhead.name.length?255&i.gzhead.name.charCodeAt(i.gzindex++):0,pe(i,e)}while(0!==e);i.gzhead.hcrc&&i.pending>s&&(t.adler=zt(t.adler,i.pending_buf,i.pending-s,s)),i.gzindex=0}i.status=91}if(91===i.status){if(i.gzhead.comment){let e,s=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>s&&(t.adler=zt(t.adler,i.pending_buf,i.pending-s,s)),ge(t),0!==i.pending)return i.last_flush=-1,jt;s=0}e=i.gzindex<i.gzhead.comment.length?255&i.gzhead.comment.charCodeAt(i.gzindex++):0,pe(i,e)}while(0!==e);i.gzhead.hcrc&&i.pending>s&&(t.adler=zt(t.adler,i.pending_buf,i.pending-s,s))}i.status=103}if(103===i.status){if(i.gzhead.hcrc){if(i.pending+2>i.pending_buf_size&&(ge(t),0!==i.pending))return i.last_flush=-1,jt;pe(i,255&t.adler),pe(i,t.adler>>8&255),t.adler=0}if(i.status=he,ge(t),0!==i.pending)return i.last_flush=-1,jt}if(0!==t.avail_in||0!==i.lookahead||e!==Lt&&i.status!==oe){let s=0===i.level?ve(i,e):i.strategy===Xt?((t,e)=>{let i;for(;;){if(0===t.lookahead&&(ye(t),0===t.lookahead)){if(e===Lt)return 1;break}if(t.match_length=0,i=Pt(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,i&&(fe(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===Vt?(fe(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(fe(t,!1),0===t.strm.avail_out)?1:2})(i,e):i.strategy===Qt?((t,e)=>{let i,s,a,r;const n=t.window;for(;;){if(t.lookahead<=ae){if(ye(t),t.lookahead<=ae&&e===Lt)return 1;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=3&&t.strstart>0&&(a=t.strstart-1,s=n[a],s===n[++a]&&s===n[++a]&&s===n[++a])){r=t.strstart+ae;do{}while(s===n[++a]&&s===n[++a]&&s===n[++a]&&s===n[++a]&&s===n[++a]&&s===n[++a]&&s===n[++a]&&s===n[++a]&&a<r);t.match_length=ae-(r-a),t.match_length>t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=3?(i=Pt(t,1,t.match_length-3),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(i=Pt(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),i&&(fe(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===Vt?(fe(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(fe(t,!1),0===t.strm.avail_out)?1:2})(i,e):ke[i.level].func(i,e);if(3!==s&&4!==s||(i.status=oe),1===s||3===s)return 0===t.avail_out&&(i.last_flush=-1),jt;if(2===s&&(e===Nt?Mt(i):e!==Ht&&(Tt(i,0,0,!1),e===Zt&&(de(i.head),0===i.lookahead&&(i.strstart=0,i.block_start=0,i.insert=0))),ge(t),0===t.avail_out))return i.last_flush=-1,jt}return e!==Vt?jt:i.wrap<=0?Wt:(2===i.wrap?(pe(i,255&t.adler),pe(i,t.adler>>8&255),pe(i,t.adler>>16&255),pe(i,t.adler>>24&255),pe(i,255&t.total_in),pe(i,t.total_in>>8&255),pe(i,t.total_in>>16&255),pe(i,t.total_in>>24&255)):(we(i,t.adler>>>16),we(i,65535&t.adler)),ge(t),i.wrap>0&&(i.wrap=-i.wrap),0!==i.pending?jt:Wt)},deflateEnd:t=>{if(xe(t))return Gt;const e=t.state.status;return t.state=null,e===he?le(t,qt):jt},deflateSetDictionary:(t,e)=>{let i=e.length;if(xe(t))return Gt;const s=t.state,a=s.wrap;if(2===a||1===a&&s.status!==ne||s.lookahead)return Gt;if(1===a&&(t.adler=Dt(t.adler,e,i,0)),s.wrap=0,i>=s.w_size){0===a&&(de(s.head),s.strstart=0,s.block_start=0,s.insert=0);let t=new Uint8Array(s.w_size);t.set(e.subarray(i-s.w_size,i),0),e=t,i=s.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,ye(s);s.lookahead>=3;){let t=s.strstart,e=s.lookahead-2;do{s.ins_h=ue(s,s.ins_h,s.window[t+3-1]),s.prev[t&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=t,t++}while(--e);s.strstart=t,s.lookahead=2,ye(s)}return s.strstart+=s.lookahead,s.block_start=s.strstart,s.insert=s.lookahead,s.lookahead=0,s.match_length=s.prev_length=2,s.match_available=0,t.next_in=n,t.input=h,t.avail_in=r,s.wrap=a,jt},deflateInfo:"pako deflate (from Nodeca project)"};const ze=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var Ce=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)ze(i,e)&&(t[e]=i[e])}}return t},Ae=t=>{let e=0;for(let i=0,s=t.length;i<s;i++)e+=t[i].length;const i=new Uint8Array(e);for(let e=0,s=0,a=t.length;e<a;e++){let a=t[e];i.set(a,s),s+=a.length}return i};let Ee=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(t){Ee=!1}const Te=new Uint8Array(256);for(let t=0;t<256;t++)Te[t]=t>=252?6:t>=248?5:t>=240?4:t>=224?3:t>=192?2:1;Te[254]=Te[254]=1;var $e=t=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(t);let e,i,s,a,r,n=t.length,h=0;for(a=0;a<n;a++)i=t.charCodeAt(a),55296==(64512&i)&&a+1<n&&(s=t.charCodeAt(a+1),56320==(64512&s)&&(i=65536+(i-55296<<10)+(s-56320),a++)),h+=i<128?1:i<2048?2:i<65536?3:4;for(e=new Uint8Array(h),r=0,a=0;r<h;a++)i=t.charCodeAt(a),55296==(64512&i)&&a+1<n&&(s=t.charCodeAt(a+1),56320==(64512&s)&&(i=65536+(i-55296<<10)+(s-56320),a++)),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 Pe=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 Me=Object.prototype.toString,{Z_NO_FLUSH:Le,Z_SYNC_FLUSH:Ne,Z_FULL_FLUSH:Ze,Z_FINISH:Ve,Z_OK:He,Z_STREAM_END:je,Z_DEFAULT_COMPRESSION:We,Z_DEFAULT_STRATEGY:Ge,Z_DEFLATED:qe}=At;function Ke(t){this.options=Ce({level:We,method:qe,chunkSize:16384,windowBits:15,memLevel:8,strategy:Ge},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 Pe,this.strm.avail_out=0;let i=Ue.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(i!==He)throw new Error(Ct[i]);if(e.header&&Ue.deflateSetHeader(this.strm,e.header),e.dictionary){let t;if(t="string"==typeof e.dictionary?$e(e.dictionary):"[object ArrayBuffer]"===Me.call(e.dictionary)?new Uint8Array(e.dictionary):e.dictionary,i=Ue.deflateSetDictionary(this.strm,t),i!==He)throw new Error(Ct[i]);this._dict_set=!0}}Ke.prototype.push=function(t,e){const i=this.strm,s=this.options.chunkSize;let a,r;if(this.ended)return!1;for(r=e===~~e?e:!0===e?Ve:Le,"string"==typeof t?i.input=$e(t):"[object ArrayBuffer]"===Me.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(s),i.next_out=0,i.avail_out=s),(r===Ne||r===Ze)&&i.avail_out<=6)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else{if(a=Ue.deflate(i,r),a===je)return i.next_out>0&&this.onData(i.output.subarray(0,i.next_out)),a=Ue.deflateEnd(this.strm),this.onEnd(a),this.ended=!0,a===He;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},Ke.prototype.onData=function(t){this.chunks.push(t)},Ke.prototype.onEnd=function(t){t===He&&(this.result=Ae(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};var Je={deflate:function(t,e){const i=new Ke(e);if(i.push(t,!0),i.err)throw i.msg||Ct[i.err];return i.result}};const{deflate:Ye}=Je;var Xe=Ye;const Qe={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}},ti=(t,...e)=>{let i=0;if(t.replace(/[<>]/,"").length!=e.length)throw"Pack format to Argument count mismatch";const s=[];let a=!0;for(let s=0;s<t.length;s++)"<"==t[s]?a=!0:">"==t[s]?a=!1:(r(t[s],e[i]),i++);function r(t,e){if(!(t in Qe))throw"Unhandled character '"+t+"' in pack format";const i=Qe[t].bytes,r=new DataView(new ArrayBuffer(i));Qe[t].p.bind(r)(0,e,a);for(let t=0;t<i;t++)s.push(r.getUint8(t))}return s},ei=(t,e)=>{let i=0;const s=[];let a=!0;for(const e of t)"<"==e?a=!0:">"==e?a=!1:r(e);function r(t){if(!(t in Qe))throw"Unhandled character '"+t+"' in unpack format";const r=Qe[t].bytes,n=new DataView(new ArrayBuffer(r));for(let t=0;t<r;t++)n.setUint8(t,255&e[i+t]);const h=Qe[t].u.bind(n);s.push(h(0,a)),i+=r}return s};class ii 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._suppressDisconnect=!1,this.__consoleMode=!1,this._isUsbJtagOrOtg=void 0,this.__adaptiveBlockMultiplier=1,this.__adaptiveMaxInFlightMultiplier=1,this.__consecutiveSuccessfulChunks=0,this.__lastAdaptiveAdjustment=0,this.__isCDCDevice=!1,this.state_DTR=!1,this.state_RTS=!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 _consoleMode(){return this._parent?this._parent._consoleMode:this.__consoleMode}set _consoleMode(t){this._parent?this._parent._consoleMode=t:this.__consoleMode=t}setConsoleMode(t){this._consoleMode=t}get _inputBuffer(){if(this._parent)return this._parent._inputBuffer;if(void 0===this.__inputBuffer)throw new Error("_inputBuffer accessed before initialization");return 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}_clearInputBuffer(){this._inputBuffer.length=0,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}get isUsbJtagOrOtg(){return this._parent?this._parent._isUsbJtagOrOtg:this._isUsbJtagOrOtg}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},18:{name:"ESP32-P4 Native USB",maxBaudrate:2e6},4097:{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(),this.chipFamily===E&&301===this.chipRevision&&await this.powerOnFlash();const t=V(this.getChipFamily()),e=t.macFuse;for(let t=0;t<4;t++)this._efuses[t]=await this.readRegister(e+4*t);const i=null!==this.chipRevision&&void 0!==this.chipRevision?` (revision ${this.chipRevision})`:"";this.logger.log(`Connected to ${this.chipName}${i}`),this.logger.debug(`Bootloader flash offset: 0x${t.flashOffs.toString(16)}`),this._initializationSucceeded=!0}async detectChip(){try{const t=(await this.getSecurityInfo()).chipId,e=$[t];if(e)return this.chipName=e.name,this.chipFamily=e.family,this.chipRevision=await this.getChipRevision(),this.logger.debug(`${this.chipName} revision: ${this.chipRevision}`),this.chipFamily===E&&this.chipRevision>=300?this.chipVariant="rev300":this.chipFamily===E&&(this.chipVariant="rev0"),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 a(N);try{await this.sync()}catch(t){this.logger.debug(`Re-sync after GET_SECURITY_INFO failure: ${t}`)}}const t=await this.readRegister(1073745920),e=P[t>>>0];if(void 0===e)throw new Error(`Unknown Chip: Hex: ${s(t>>>0,8).toLowerCase()} Number: ${t}`);this.chipName=e.name,this.chipFamily=e.family,this.chipRevision=await this.getChipRevision(),this.logger.debug(`${this.chipName} revision: ${this.chipRevision}`),this.chipFamily===E&&(this.chipVariant=this.chipRevision>=300?"rev300":"rev0",this.logger.debug(`ESP32-P4 variant: ${this.chipVariant}`)),this.logger.debug(`Detected chip via magic value: ${s(t>>>0,8)} (${this.chipName})`)}async getChipRevision(){var t;let e=0,i=0;switch(this.chipFamily){case B:{const s=await this.readRegister(1073061900),a=await this.readRegister(1073061908);e=a>>24&3;const r=s>>15&1,n=a>>20&1;i=null!==(t={0:0,1:1,3:2,7:3}[(await this.readRegister(1610612856)>>31&1)<<2|n<<1|r])&&void 0!==t?t:0;break}case k:{const t=await this.readRegister(1061265488);e=((t>>20&1)<<3)+(await this.readRegister(1061265492)>>4&7),i=t>>18&3;break}case F:{const t=await this.readRegister(1610641488),s=await this.readRegister(1610641496);e=((s>>23&1)<<3)+(t>>18&7),i=s>>24&3;break}case x:{const t=await this.readRegister(1610647620);e=t>>16&15,i=t>>20&3;break}case I:{const t=await this.readRegister(1610647628),s=await this.readRegister(1610647636);e=((s>>23&1)<<3)+(t>>18&7),i=s>>24&3;break}case O:{const t=await this.readRegister(1611352140);e=15&t,i=t>>4&3;break}case D:{const t=await this.readRegister(1611335760);e=t>>18&15,i=t>>22&3;break}case U:{const t=await this.readRegister(1611352140);e=15&t,i=t>>4&3;break}case z:{const t=await this.readRegister(1611335760);e=t>>18&7,i=t>>21&3;break}case C:case A:break;case E:{const t=await this.readRegister(1343410252);e=15&t,i=(t>>23&1)<<2|t>>4&3;break}case T:{const t=await this.readRegister(544297036);e=15&t,i=t>>4&3;break}}return 100*i+e}async powerOnFlash(){if(this.chipFamily!==E)return;if(301!==this.chipRevision)return;this.logger.debug("Powering on flash for ESP32-P4 Rev 301 (ECO6)"),await this.writeRegister(1343291660,1),await a(10);const t=await this.readRegister(w);await this.writeRegister(w,t|m);const e=await this.readRegister(b);await this.writeRegister(b,128|e);const i=await this.readRegister(y);await this.writeRegister(y,3|i),await a(.05);const s=await this.readRegister(w);await this.writeRegister(w,-134217729&s);const r=await this.readRegister(b);await this.writeRegister(b,-2139095041&r);const n=await this.readRegister(b);await this.writeRegister(b,128|n);const h=await this.readRegister(b);await this.writeRegister(b,-129&h),await a(2),this.logger.debug("Flash powered on successfully")}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:ei("<I",t.slice(0,4))[0],flashCryptCnt:t[4],keyPurposes:Array.from(t.slice(5,12)),chipId:t.length>=16?ei("<I",t.slice(12,16))[0]:0,apiVersion:t.length>=20?ei("<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 getC5CrystalFreqRomExpect(){return(127&await this.readRegister(1611227408))>>>24}async getC5CrystalFreqDetected(){const t=1048575&await this.readRegister(1610612756),e=n*t/1e6;return e>45?48:e>33?40:26}async setBaudrate(t){const e=this._parent?this._parent.chipFamily:this.chipFamily;if(this.IS_STUB||e!==O)try{const e=ti("<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.`)}else await this.setBaudrateC5Rom(t);this._parent?await this._parent.reconfigurePort(t):await this.reconfigurePort(t),await a(N),this._parent?this._parent.currentBaudRate=t:this.currentBaudRate=t;const i=this._parent?this._parent._maxUSBSerialBaudrate:this._maxUSBSerialBaudrate;i&&t>i&&(this.logger.log(`⚠️ WARNING: Baudrate ${t} exceeds USB-Serial chip limit (${i})!`),this.logger.log("⚠️ This may cause data corruption or connection failures!")),this.logger.debug(`Changed baud rate to ${t}`)}async setBaudrateC5Rom(t){const e=await this.getC5CrystalFreqRomExpect(),i=await this.getC5CrystalFreqDetected();this.logger.log(`ROM expects crystal freq: ${e} MHz, detected ${i} MHz.`);let s=t;48===i&&40===e?s=Math.trunc(40*t/48):40===i&&48===e&&(s=Math.trunc(48*t/40)),this.logger.log(`Changing baud rate to ${s}...`);try{const t=ti("<II",s,0);await this.checkCommand(15,t)}catch(t){throw this.logger.error(`Baudrate change error: ${t}`),new Error(`Unable to change the baud rate to ${s}: No response from set baud rate command.`)}this.logger.log("Changed.")}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 s=Array.from(e);Array.prototype.push.apply(this._inputBuffer,s),this._totalBytesRead+=e.length}}catch{}finally{if(this._isReconfiguring=!1,this._reader){try{this._reader.releaseLock(),this.logger.debug("Reader released in readLoop cleanup")}catch(t){this.logger.debug(`Reader release error in readLoop: ${t}`)}this._reader=void 0}}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._suppressDisconnect||this.dispatchEvent(new Event("disconnect")),this._suppressDisconnect=!1,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 setDTRandRTS(t,e){this.state_DTR=t,this.state_RTS=e,await this.port.setSignals({dataTerminalReady:t,requestToSend:e})}async hardReset(t=!1){t?4097===this.port.getInfo().usbProductId?(await this.hardResetUSBJTAGSerial(),this.logger.log("USB-JTAG/Serial reset.")):(await this.hardResetClassic(),this.logger.log("Classic reset.")):(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],s=this._efuses[2],a=this._efuses[3];let r;if(this.chipFamily==S){if(0!=a)r=[a>>16&255,a>>8&255,255&a];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==B)t[0]=s>>8&255,t[1]=255&s,t[2]=i>>24&255,t[3]=i>>16&255,t[4]=i>>8&255,t[5]=255&i;else{if(this.chipFamily!=k&&this.chipFamily!=F&&this.chipFamily!=x&&this.chipFamily!=I&&this.chipFamily!=O&&this.chipFamily!=D&&this.chipFamily!=U&&this.chipFamily!=z&&this.chipFamily!=C&&this.chipFamily!=A&&this.chipFamily!=E&&this.chipFamily!=T)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 "+s(t,8));const e=ti("<I",t);await this.sendCommand(10,e);const[i]=await this.getResponse(10);return i}async checkCommand(t,e,i=0,a=3e3){const r=async()=>{a=Math.min(a,3e5),await this.sendCommand(t,e,i);const[r,n]=await this.getResponse(t,a);if(null===n)throw new Error("Didn't get enough status bytes");let h=n,o=0;if(this.IS_STUB||this.chipFamily==S?o=2:[B,k,F,x,I,O,D,U,z,C,A,E,T].includes(this.chipFamily)||20===t?o=4:[2,4].includes(h.length)&&(o=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 "+s(t))):new Error("Command failure error code "+s(l[1]));return[r,h]};return this._commandLock=this._commandLock.then(r,r),this._commandLock}async sendCommand(e,i,s=0){const a=t([...ti("<BBHI",0,e,i.length,s),...i]);this.debug&&this.logger.debug(`Writing ${a.length} byte${1==a.length?"":"s"}:`,a),await this.writeToStream(a)}async readPacket(t){let e=null,r=!1,n=[];for(;;){const h=Date.now();for(n=[];Date.now()-h<t;){if(this._inputBuffer.length>0){n.push(this._inputBuffer.shift());break}await a(1)}if(0==n.length){throw new H("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: "+s(t)),this.logger.debug("Remaining data in serial buffer: "+i(this._inputBuffer))),new H("Invalid head of packet ("+s(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: "+s(t)),this.logger.debug("Remaining data in serial buffer: "+i(this._inputBuffer))),new H("Invalid SLIP escape (0xdb, "+s(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)),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[a,r,,n]=ei("<BBHI",i.slice(0,8));if(1!=a)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 ${s(t)}`)}throw"Response doesn't match request"}checksum(t,e=239){for(const i of t)e^=i;return e}async reconfigurePort(t){var e;try{try{await this._writeChain}catch(t){this.logger.debug(`Pending write error during reconfigure: ${t}`)}if(this._isReconfiguring=!0,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}),this._isReconfiguring=!1,await this.flushSerialBuffers(),this.readLoop()}catch(e){throw this._isReconfiguring=!1,this.logger.error(`Reconfigure port error: ${e}`),new Error(`Unable to change the baud rate to ${t}: ${e}`)}}async connectWithResetStrategies(){var t,e;const i=this.port.getInfo(),s=4097===i.usbProductId,a=12346===i.usbVendorId;this.logger.log(`Detected USB: VID=0x${(null===(t=i.usbVendorId)||void 0===t?void 0:t.toString(16))||"unknown"}, PID=0x${(null===(e=i.usbProductId)||void 0===e?void 0:e.toString(16))||"unknown"}`);const r=[];(s||a)&&r.push({name:"USB-JTAG/Serial",fn:async()=>await this.hardResetUSBJTAGSerial()}),r.push({name:"Classic",fn:async()=>await this.hardResetClassic()}),s||a||r.push({name:"USB-JTAG/Serial (fallback)",fn:async()=>await this.hardResetUSBJTAGSerial()});let n=null;for(const t of r)try{if(this.logger.log(`Trying ${t.name} reset...`),!this.connected||!this.port.writable){this.logger.log(`Port disconnected, skipping ${t.name} reset`);continue}return await t.fn(),await this.sync(),void this.logger.log(`Connected successfully with ${t.name} reset.`)}catch(e){if(n=e,this.logger.log(`${t.name} reset failed: ${e.message}`),!this.connected||!this.port.writable){this.logger.log("Port disconnected during reset attempt");break}this._inputBuffer.length=0,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 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 sync(){for(let t=0;t<5;t++){this._inputBuffer.length=0;if(await this._sync())return await a(N),!0;await a(N)}throw new Error("Couldn't sync to ESP. Try resetting.")}async _sync(){await this.sendCommand(8,R);for(let t=0;t<8;t++)try{const[,t]=await this.getResponse(8,N);if(t.length>1&&0==t[0]&&0==t[1])return!0}catch{}return!1}getFlashWriteSize(){return this.IS_STUB?16384:1024}async flashData(t,e,i=0,a=!1){if(t.byteLength>=8){const e=Array.from(new Uint8Array(t,0,4)),i=e[0],a=e[2],r=e[3];this.logger.log(`Image header, Magic=${s(i)}, FlashMode=${s(a)}, FlashSizeFreq=${s(r)}`)}const r=(t=function(t,e,i=255){const s=t.length%e;if(0!==s){const a=new Uint8Array(e-s).fill(i),r=new Uint8Array(t.length+a.length);return r.set(t),r.set(a,t.length),r}return t}(new Uint8Array(t),4).buffer).byteLength;let n,h=0,o=M;a?(n=Xe(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=[],c=0,d=0,_=0;const u=Date.now(),g=this.getFlashWriteSize(),f=a?h:r;for(;f-_>0;)this.debug&&this.logger.log(`Writing at ${s(i+c*g,8)} `),f-_>=g?l=Array.from(new Uint8Array(n,_,g)):(l=Array.from(new Uint8Array(n,_,f-_)),a||(l=l.concat(new Array(g-l.length).fill(255)))),a?await this.flashDeflBlock(l,c,o):await this.flashBlock(l,c),c+=1,d+=a?Math.round(l.length*r/h):l.length,_+=g,e(Math.min(d,r),r);this.logger.log("Took "+(Date.now()-u)+"ms to write "+f+" bytes"),this.IS_STUB&&(await this.flashBegin(0,0),a?await this.flashDeflFinish():await this.flashFinish())}async flashBlock(t,e,i=3e3){await this.checkCommand(3,ti("<IIII",t.length,e,0,0).concat(t),this.checksum(t),i)}async flashDeflBlock(t,e,i=3e3){await this.checkCommand(17,ti("<IIII",t.length,e,0,0).concat(t),this.checksum(t),i)}async flashBegin(t=0,e=0,i=!1){let a;await this.flushSerialBuffers();const r=this.getFlashWriteSize();!this.IS_STUB&&[B,k,F,x,I,O,D,U,z,C,A,E,T].includes(this.chipFamily)&&await this.checkCommand(13,new Array(8).fill(0));const n=Math.floor((t+r-1)/r);a=this.chipFamily!=S||this.IS_STUB?t:this.getEraseSize(e,t);const h=this.IS_STUB?M:Z(3e4,t),o=Date.now();let l=ti("<IIII",a,n,r,e);return this.chipFamily!=B&&this.chipFamily!=k&&this.chipFamily!=F&&this.chipFamily!=x&&this.chipFamily!=I&&this.chipFamily!=O&&this.chipFamily!=D&&this.chipFamily!=U&&this.chipFamily!=z&&this.chipFamily!=C&&this.chipFamily!=A&&this.chipFamily!=E&&this.chipFamily!=T||(l=l.concat(ti("<I",i?1:0))),this.logger.log("Erase size "+a+", blocks "+n+", block size "+s(r,4)+", offset "+s(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 s=this.getFlashWriteSize(),a=Math.floor((e+s-1)/s),r=Math.floor((t+s-1)/s);let n=0,h=0;this.IS_STUB?(n=t,h=Z(3e4,n)):(n=r*s,h=M);const o=ti("<IIII",n,a,s,i);return await this.checkCommand(16,o,0,h),h}async flashFinish(){const t=ti("<I",1);await this.checkCommand(4,t)}async flashDeflFinish(){const t=ti("<I",1);await this.checkCommand(18,t)}getBootloaderOffset(){return V(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,s=0,a=0){let r=ti("<IIII",t,e,i,s);a>0&&(r=r.concat(ti("<IIII",V(this.getChipFamily()).uartDateReg,0,0,a))),await this.checkCommand(9,r)}async setDataLengths(t,e,i){if(-1!=t.mosiDlenOffs){const s=t.regBase+t.mosiDlenOffs,a=t.regBase+t.misoDlenOffs;e>0&&await this.writeRegister(s,e-1),i>0&&await this.writeRegister(a,i-1)}else{const s=t.regBase+t.usr1Offs,a=(0==i?0:i-1)<<8|(0==e?0:e-1)<<17;await this.writeRegister(s,a)}}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 a=V(this.getChipFamily()),r=a.regBase,n=r,h=r+a.usrOffs,o=r+a.usr2Offs,l=r+a.w0Offs,c=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,_=await this.readRegister(h),u=await this.readRegister(o);let g=1<<31;if(i>0&&(g|=268435456),d>0&&(g|=134217728),await this.setDataLengths(a,d,i),await this.writeRegister(h,g),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=ei("I".repeat(Math.floor(e.length/4)),e);let a=l;this.logger.debug(`Words Length: ${i.length}`);for(const t of i)this.logger.debug(`Writing word ${s(t)} to register offset ${s(a)}`),await this.writeRegister(a,t),a+=4}await this.writeRegister(n,c),await this.waitDone(n,c);const f=await this.readRegister(l);return await this.writeRegister(h,_),await this.writeRegister(o,u),f}async detectFlashSize(){this.logger.log("Detecting Flash Size");const t=await this.flashId(),e=255&t,i=t>>16&255;this.logger.log(`FlashId: ${s(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,s=Math.floor((e+i-1)/i);let a=16-Math.floor(t/i)%16;return s<a&&(a=s),s<2*a?Math.floor((s+1)/2*i):(s-a)*i}async memBegin(t,e,i,s){return await this.checkCommand(5,ti("<IIII",t,e,i,s))}async memBlock(t,e){return await this.checkCommand(7,ti("<IIII",t.length,e,0,0).concat(t),this.checksum(t))}async memFinish(t=0){const e=this.IS_STUB?M:500,i=ti("<II",0==t?1:0,t);return await this.checkCommand(6,i,0,e)}async runStub(t=!1){this.logger.debug(`Loading stub for ${this.chipName}, revision: ${this.chipRevision}`);const e=await j(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 s=e[t],a=e[`${t}_start`],r=s.length,n=Math.floor((r+i-1)/i);await this.memBegin(r,n,i,a);for(const t of Array(n).keys()){const e=t*i;let a=e+i;a>r&&(a=r),await this.memBlock(s.slice(e,a),t)}}await this.memFinish(e.entry);const s=await this.readPacket(500),a=String.fromCharCode(...s);if("OHAI"!=a)throw new Error("Failed to start stub. Unexpected response: "+a);this.logger.log("Stub is now running...");const r=new si(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.port.writable)throw new Error("Port became unavailable during write");this._writer||(this._writer=this.port.writable.getWriter()),await this._writer.write(new Uint8Array(t))}).catch(t=>{if(this.logger.error(`Write error: ${t}`),this._writer){try{this._writer.releaseLock()}catch(t){}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||t(void 0),this.addEventListener("disconnect",t,{once:!0}),this._reader.cancel()}),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=[];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,s=this.chipVariant,a=this.flashSize;if(await this.hardReset(!0),this._parent||(this.__inputBuffer=[],this.__totalBytesRead=0,this.readLoop()),await this.flushSerialBuffers(),await this.sync(),this.chipFamily=t,this.chipName=e,this.chipRevision=i,this.chipVariant=s,this.flashSize=a,this.logger.debug(`Reconnect complete (chip: ${this.chipName})`),!this.port.writable||!this.port.readable)throw new Error("Port not ready after reconnect");this.chipFamily===E&&301===this.chipRevision&&await this.powerOnFlash();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&&Object.assign(this,r),this.logger.debug("Reconnection successful")}catch(t){throw this._isReconfiguring=!1,t}}async drainInputBuffer(t=200){await a(t);let e=0;const i=Date.now();for(;e<112&&Date.now()-i<100;)if(this._inputBuffer.length>0){void 0!==this._inputBuffer.shift()&&e++}else await a(1);e>0&&this.logger.debug(`Drained ${e} bytes from input buffer`),this._parent||(this.__inputBuffer=[])}async flushSerialBuffers(){this._parent||(this.__inputBuffer=[]),await a(N),this._parent||(this.__inputBuffer=[]),this.logger.debug("Serial buffers flushed")}async readFlash(e,i,s){if(!this.IS_STUB)throw new Error("Reading flash is only supported in stub mode. Please run runStub() first.");await this.flushSerialBuffers(),this.logger.log(`Reading ${i} bytes from flash at address 0x${e.toString(16)}...`);let r=new Uint8Array(0),n=e,h=i;for(;h>0;){const e=Math.min(65536,h);let o=!1,l=0;const c=5;let d=!1;for(;!o&&l<=c;){let i=new Uint8Array(0);try{0===l&&this.logger.debug(`Reading chunk at 0x${n.toString(16)}, size: 0x${e.toString(16)}`);const s=ti("<IIII",n,e,4096,1024),[h]=await this.checkCommand(210,s);if(0!=h)throw new Error("Failed to read memory: "+h);for(;i.length<e;){let s;try{s=await this.readPacket(100)}catch(t){if(t instanceof H){this.logger.debug(`${t.message} at byte 0x${i.length.toString(16)}`);try{const t=[192,192];await this.writeToStream(t),this.logger.debug("Sent abort frame to stub"),await a(50)}catch(t){this.logger.debug(`Abort frame error: ${t}`)}if(await this.drainInputBuffer(200),i.length>=e)break}throw t}if(s&&s.length>0){const e=new Uint8Array(s),a=new Uint8Array(i.length+e.length);a.set(i),a.set(e,i.length),i=a;const r=ti("<I",i.length),n=t(r);await this.writeToStream(n)}}const c=new Uint8Array(r.length+i.length);c.set(r),c.set(i,r.length),r=c,o=!0}catch(t){if(l++,!(t instanceof H))throw t;if(l<=c)this.logger.log(`Cleared buffer and retrying (attempt ${l}/${c})...`);else{if(d)throw new Error(`Failed to read chunk at 0x${n.toString(16)} after ${c} retries and deep recovery attempt`);d=!0,this.logger.log(`All retries exhausted at 0x${n.toString(16)}. Attempting deep recovery (reconnect + reload stub)...`);try{await this.reconnect(),this.logger.log("Deep recovery successful. Resuming read from current position..."),l=0;continue}catch(t){throw new Error(`Failed to read chunk at 0x${n.toString(16)} after ${c} retries and deep recovery failed: ${t}`)}}}}s&&s(new Uint8Array(e),r.length,i),n+=e,h-=e,this.logger.debug(`Total progress: 0x${r.length.toString(16)} from 0x${i.toString(16)} bytes`)}return this.logger.debug(`Successfully read ${r.length} bytes from flash`),r}}class si extends ii{constructor(){super(...arguments),this.IS_STUB=!0}async memBegin(t,e,i,a){const r=await j(this.chipFamily,this.chipRevision);if(null===r)return[0,[]];const n=a,h=a+t;this.logger.debug(`Load range: ${s(n,8)}-${s(h,8)}`),this.logger.debug(`Stub data: ${s(r.data_start,8)}, len: ${r.data.length}, text: ${s(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 "+s(t,8)+"-"+s(e,8)+". Can't load binary at overlapping address range "+s(n,8)+"-"+s(h,8)+". Try changing the binary loading address.");return[0,[]]}async eraseFlash(){await this.checkCommand(208,[],0,L)}}const ai=async t=>{const e=await navigator.serial.requestPort();return await e.open({baudRate:n}),t.log("Connected successfully."),new ii(e,t)};export{B as CHIP_FAMILY_ESP32,x as CHIP_FAMILY_ESP32C2,I as CHIP_FAMILY_ESP32C3,O as CHIP_FAMILY_ESP32C5,D as CHIP_FAMILY_ESP32C6,U as CHIP_FAMILY_ESP32C61,z as CHIP_FAMILY_ESP32H2,A as CHIP_FAMILY_ESP32H21,C as CHIP_FAMILY_ESP32H4,E as CHIP_FAMILY_ESP32P4,k as CHIP_FAMILY_ESP32S2,F as CHIP_FAMILY_ESP32S3,T as CHIP_FAMILY_ESP32S31,S as CHIP_FAMILY_ESP8266,ii as ESPLoader,ai as connect};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tasmota-webserial-esptool",
3
- "version": "7.3.8",
3
+ "version": "7.3.10",
4
4
  "description": "Flash & Read ESP devices using WebSerial",
5
5
  "main": "dist/index.js",
6
6
  "repository": {
@@ -21,7 +21,7 @@
21
21
  "lintAndFix": "eslint src/ --fix"
22
22
  },
23
23
  "devDependencies": {
24
- "@types/node": "^25.0.2",
24
+ "@types/node": "^25.2.3",
25
25
  "@eslint/js": "^9.39.2",
26
26
  "@rollup/plugin-json": "^6.1.0",
27
27
  "@rollup/plugin-node-resolve": "^16.0.0",
@@ -33,13 +33,19 @@
33
33
  "eslint-config-prettier": "^10.1.8",
34
34
  "eslint-plugin-prettier": "^5.5.4",
35
35
  "prettier": "^3.7.3",
36
- "rollup": "^4.53.5",
36
+ "rollup": "^4.57.0",
37
37
  "serve": "^14.2.4",
38
38
  "typescript": "^5.7.3",
39
- "typescript-eslint": "^8.51.0"
39
+ "typescript-eslint": "^8.56.0"
40
40
  },
41
41
  "dependencies": {
42
42
  "pako": "^2.1.0",
43
43
  "tslib": "^2.8.1"
44
+ },
45
+ "overrides": {
46
+ "tmp": "^0.2.4",
47
+ "tar": "^7.5.6",
48
+ "ajv": "^8.18.0",
49
+ "minimatch": "^10.2.1"
44
50
  }
45
51
  }
package/src/esp_loader.ts CHANGED
@@ -74,29 +74,6 @@ import {
74
74
  ESP32C5_PCR_SYSCLK_CONF_REG,
75
75
  ESP32C5_PCR_SYSCLK_XTAL_FREQ_V,
76
76
  ESP32C5_PCR_SYSCLK_XTAL_FREQ_S,
77
- ESP32S2_UARTDEV_BUF_NO,
78
- ESP32S2_UARTDEV_BUF_NO_USB_OTG,
79
- ESP32S3_UARTDEV_BUF_NO,
80
- ESP32S3_UARTDEV_BUF_NO_USB_OTG,
81
- ESP32S3_UARTDEV_BUF_NO_USB_JTAG_SERIAL,
82
- ESP32C3_UARTDEV_BUF_NO_USB_JTAG_SERIAL,
83
- ESP32C3_BUF_UART_NO_OFFSET,
84
- ESP32C5_UARTDEV_BUF_NO,
85
- ESP32C5_UARTDEV_BUF_NO_USB_JTAG_SERIAL,
86
- ESP32C6_UARTDEV_BUF_NO,
87
- ESP32C6_UARTDEV_BUF_NO_USB_JTAG_SERIAL,
88
- ESP32C61_UARTDEV_BUF_NO_REV_LE2,
89
- ESP32C61_UARTDEV_BUF_NO_REV_GT2,
90
- ESP32C61_UARTDEV_BUF_NO_USB_JTAG_SERIAL_REV_LE2,
91
- ESP32C61_UARTDEV_BUF_NO_USB_JTAG_SERIAL_REV_GT2,
92
- ESP32H2_UARTDEV_BUF_NO,
93
- ESP32H2_UARTDEV_BUF_NO_USB_JTAG_SERIAL,
94
- ESP32H4_UARTDEV_BUF_NO,
95
- ESP32H4_UARTDEV_BUF_NO_USB_JTAG_SERIAL,
96
- ESP32P4_UARTDEV_BUF_NO_REV0,
97
- ESP32P4_UARTDEV_BUF_NO_REV300,
98
- ESP32P4_UARTDEV_BUF_NO_USB_OTG,
99
- ESP32P4_UARTDEV_BUF_NO_USB_JTAG_SERIAL,
100
77
  SlipReadError,
101
78
  ESP32P4_LP_SYSTEM_REG_ANA_XPD_PAD_GROUP_REG,
102
79
  ESP32P4_PMU_EXT_LDO_P0_0P1A_ANA_REG,
@@ -107,7 +84,7 @@ import {
107
84
  ESP32P4_PMU_DATE_REG,
108
85
  } from "./const";
109
86
  import { getStubCode } from "./stubs";
110
- import { hexFormatter, sleep, slipEncode, toHex } from "./util";
87
+ import { hexFormatter, padTo, sleep, slipEncode, toHex } from "./util";
111
88
  // @ts-expect-error pako ESM module doesn't have proper type definitions
112
89
  import { deflate } from "pako/dist/pako.esm.mjs";
113
90
  import { pack, unpack } from "./struct";
@@ -482,26 +459,6 @@ export class ESPLoader extends EventTarget {
482
459
  await this.powerOnFlash();
483
460
  }
484
461
 
485
- // Detect if device is using USB-JTAG/Serial or USB-OTG (not external serial chip)
486
- // This is needed to determine the correct reset strategy for console mode
487
- try {
488
- this._isUsbJtagOrOtg = await this.detectUsbConnectionType();
489
- this.logger.debug(
490
- `USB connection type: ${this._isUsbJtagOrOtg ? "USB-JTAG/OTG" : "External Serial Chip"}`,
491
- );
492
- } catch (err) {
493
- this.logger.debug(`Could not detect USB connection type: ${err}`);
494
- }
495
-
496
- try {
497
- const usbMode = await this.getUsbMode();
498
- this.logger.debug(
499
- `USB mode (register): ${usbMode.mode} (uartNo=${usbMode.uartNo})`,
500
- );
501
- } catch (err) {
502
- this.logger.debug(`Could not detect USB mode: ${err}`);
503
- }
504
-
505
462
  // Read the OTP data for this chip and store into this.efuses array
506
463
  const FlAddr = getSpiFlashAddresses(this.getChipFamily());
507
464
  const AddrMAC = FlAddr.macFuse;
@@ -839,103 +796,6 @@ export class ESPLoader extends EventTarget {
839
796
  .join(":");
840
797
  }
841
798
 
842
- /**
843
- * Detect if device is using USB-JTAG/Serial or USB-OTG (not external serial chip)
844
- * Stub implementation - returns undefined (not yet implemented in WebSerial_ESPTool)
845
- */
846
- async detectUsbConnectionType(): Promise<boolean> {
847
- // Stub implementation - would need USB PID detection
848
- return false;
849
- }
850
-
851
- /**
852
- * Get USB mode (UART, USB-JTAG/Serial, or USB-OTG)
853
- * Reads the UARTDEV_BUF_NO register to determine the USB mode
854
- */
855
- async getUsbMode(): Promise<{
856
- mode: "uart" | "usb-jtag-serial" | "usb-otg";
857
- uartNo: number;
858
- }> {
859
- const family = this._parent ? this._parent.chipFamily : this.chipFamily;
860
- const revision = this._parent
861
- ? (this._parent.chipRevision ?? 0)
862
- : (this.chipRevision ?? 0);
863
-
864
- let bufNoAddr: number | null = null;
865
- let jtagSerialVal: number | null = null;
866
- let otgVal: number | null = null;
867
-
868
- switch (family) {
869
- case CHIP_FAMILY_ESP32S2:
870
- bufNoAddr = ESP32S2_UARTDEV_BUF_NO;
871
- otgVal = ESP32S2_UARTDEV_BUF_NO_USB_OTG;
872
- break;
873
- case CHIP_FAMILY_ESP32S3:
874
- bufNoAddr = ESP32S3_UARTDEV_BUF_NO;
875
- jtagSerialVal = ESP32S3_UARTDEV_BUF_NO_USB_JTAG_SERIAL;
876
- otgVal = ESP32S3_UARTDEV_BUF_NO_USB_OTG;
877
- break;
878
- case CHIP_FAMILY_ESP32C3: {
879
- const bssAddr = revision < 101 ? 0x3fcdf064 : 0x3fcdf060;
880
- bufNoAddr = bssAddr + ESP32C3_BUF_UART_NO_OFFSET;
881
- jtagSerialVal = ESP32C3_UARTDEV_BUF_NO_USB_JTAG_SERIAL;
882
- break;
883
- }
884
- case CHIP_FAMILY_ESP32C5:
885
- bufNoAddr = ESP32C5_UARTDEV_BUF_NO;
886
- jtagSerialVal = ESP32C5_UARTDEV_BUF_NO_USB_JTAG_SERIAL;
887
- break;
888
- case CHIP_FAMILY_ESP32C6:
889
- bufNoAddr = ESP32C6_UARTDEV_BUF_NO;
890
- jtagSerialVal = ESP32C6_UARTDEV_BUF_NO_USB_JTAG_SERIAL;
891
- break;
892
- case CHIP_FAMILY_ESP32C61:
893
- bufNoAddr =
894
- revision <= 200
895
- ? ESP32C61_UARTDEV_BUF_NO_REV_LE2
896
- : ESP32C61_UARTDEV_BUF_NO_REV_GT2;
897
- jtagSerialVal =
898
- revision <= 200
899
- ? ESP32C61_UARTDEV_BUF_NO_USB_JTAG_SERIAL_REV_LE2
900
- : ESP32C61_UARTDEV_BUF_NO_USB_JTAG_SERIAL_REV_GT2;
901
- break;
902
- case CHIP_FAMILY_ESP32H2:
903
- bufNoAddr = ESP32H2_UARTDEV_BUF_NO;
904
- jtagSerialVal = ESP32H2_UARTDEV_BUF_NO_USB_JTAG_SERIAL;
905
- break;
906
- case CHIP_FAMILY_ESP32H4:
907
- bufNoAddr = ESP32H4_UARTDEV_BUF_NO;
908
- jtagSerialVal = ESP32H4_UARTDEV_BUF_NO_USB_JTAG_SERIAL;
909
- break;
910
- case CHIP_FAMILY_ESP32P4:
911
- bufNoAddr =
912
- revision < 300
913
- ? ESP32P4_UARTDEV_BUF_NO_REV0
914
- : ESP32P4_UARTDEV_BUF_NO_REV300;
915
- jtagSerialVal = ESP32P4_UARTDEV_BUF_NO_USB_JTAG_SERIAL;
916
- otgVal = ESP32P4_UARTDEV_BUF_NO_USB_OTG;
917
- break;
918
- }
919
-
920
- if (bufNoAddr === null) {
921
- return { mode: "uart", uartNo: 0 };
922
- }
923
-
924
- const uartNo = (await this.readRegister(bufNoAddr)) & 0xff;
925
-
926
- if (otgVal !== null && uartNo === otgVal) {
927
- this.logger.debug(`USB mode: USB-OTG (uartNo=${uartNo})`);
928
- return { mode: "usb-otg", uartNo };
929
- }
930
- if (jtagSerialVal !== null && uartNo === jtagSerialVal) {
931
- this.logger.debug(`USB mode: USB-JTAG/Serial (uartNo=${uartNo})`);
932
- return { mode: "usb-jtag-serial", uartNo };
933
- }
934
-
935
- this.logger.debug(`USB mode: UART (uartNo=${uartNo})`);
936
- return { mode: "uart", uartNo };
937
- }
938
-
939
799
  /**
940
800
  * Get ESP32-C5 crystal frequency from ROM expectation
941
801
  */
@@ -1728,6 +1588,9 @@ export class ESPLoader extends EventTarget {
1728
1588
  );
1729
1589
  }
1730
1590
 
1591
+ const paddedData = padTo(new Uint8Array(binaryData), 4);
1592
+ binaryData = paddedData.buffer as ArrayBuffer;
1593
+
1731
1594
  const uncompressedFilesize = binaryData.byteLength;
1732
1595
  let compressedFilesize = 0;
1733
1596
 
@@ -2700,7 +2563,7 @@ export class ESPLoader extends EventTarget {
2700
2563
  } catch (err) {
2701
2564
  if (err instanceof SlipReadError) {
2702
2565
  this.logger.debug(
2703
- `SLIP read error at ${resp.length} bytes: ${err.message}`,
2566
+ `${err.message} at byte 0x${resp.length.toString(16)}`,
2704
2567
  );
2705
2568
 
2706
2569
  // Send empty SLIP frame to abort the stub's read operation
@@ -2758,22 +2621,9 @@ export class ESPLoader extends EventTarget {
2758
2621
  if (err instanceof SlipReadError) {
2759
2622
  if (retryCount <= MAX_RETRIES) {
2760
2623
  this.logger.log(
2761
- `${err.message} at 0x${currentAddr.toString(16)}. Draining buffer and retrying (attempt ${retryCount}/${MAX_RETRIES})...`,
2624
+ `Cleared buffer and retrying (attempt ${retryCount}/${MAX_RETRIES})...`,
2762
2625
  );
2763
-
2764
- try {
2765
- await this.drainInputBuffer(200);
2766
-
2767
- // Clear application buffer
2768
- await this.flushSerialBuffers();
2769
-
2770
- // Wait before retry to let hardware settle
2771
- await sleep(SYNC_TIMEOUT);
2772
-
2773
- // Continue to retry the same chunk (will send NEW read command)
2774
- } catch (drainErr) {
2775
- this.logger.debug(`Buffer drain error: ${drainErr}`);
2776
- }
2626
+ // Continue to retry the same chunk (will send NEW read command)
2777
2627
  } else {
2778
2628
  // All retries exhausted - attempt deep recovery by reconnecting and reloading stub
2779
2629
  if (!deepRecoveryAttempted) {
package/src/util.ts CHANGED
@@ -45,5 +45,34 @@ export const toHex = (value: number, size = 2) => {
45
45
  }
46
46
  };
47
47
 
48
+ /**
49
+ * Format MAC address array to string (e.g., [0xAA, 0xBB, 0xCC] -> "AA:BB:CC:DD:EE:FF")
50
+ */
51
+ export const formatMacAddr = (macAddr: number[]): string => {
52
+ return macAddr
53
+ .map((value) => value.toString(16).toUpperCase().padStart(2, "0"))
54
+ .join(":");
55
+ };
56
+
57
+ /**
58
+ * @name padTo
59
+ * Pad data to the next alignment boundary with the given fill byte (default 0xFF)
60
+ */
61
+ export function padTo(
62
+ data: Uint8Array,
63
+ alignment: number,
64
+ padCharacter = 0xff,
65
+ ): Uint8Array {
66
+ const padMod = data.length % alignment;
67
+ if (padMod !== 0) {
68
+ const padding = new Uint8Array(alignment - padMod).fill(padCharacter);
69
+ const paddedData = new Uint8Array(data.length + padding.length);
70
+ paddedData.set(data);
71
+ paddedData.set(padding, data.length);
72
+ return paddedData;
73
+ }
74
+ return data;
75
+ }
76
+
48
77
  export const sleep = (ms: number) =>
49
78
  new Promise((resolve) => setTimeout(resolve, ms));